source: frontend/node_modules/@remix-run/router/dist/router.cjs.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 2 weeks ago

Fix frontend appearance

  • Property mode set to 100644
File size: 203.0 KB
Line 
1/**
2 * @remix-run/router v1.23.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'use strict';
12
13Object.defineProperty(exports, '__esModule', { value: true });
14
15function _extends() {
16 _extends = Object.assign ? Object.assign.bind() : function (target) {
17 for (var i = 1; i < arguments.length; i++) {
18 var source = arguments[i];
19 for (var key in source) {
20 if (Object.prototype.hasOwnProperty.call(source, key)) {
21 target[key] = source[key];
22 }
23 }
24 }
25 return target;
26 };
27 return _extends.apply(this, arguments);
28}
29
30////////////////////////////////////////////////////////////////////////////////
31//#region Types and Constants
32////////////////////////////////////////////////////////////////////////////////
33
34/**
35 * Actions represent the type of change to a location value.
36 */
37let Action = /*#__PURE__*/function (Action) {
38 Action["Pop"] = "POP";
39 Action["Push"] = "PUSH";
40 Action["Replace"] = "REPLACE";
41 return Action;
42}({});
43
44/**
45 * The pathname, search, and hash values of a URL.
46 */
47
48// TODO: (v7) Change the Location generic default from `any` to `unknown` and
49// remove Remix `useLocation` wrapper.
50/**
51 * An entry in a history stack. A location contains information about the
52 * URL path, as well as possibly some arbitrary state and a key.
53 */
54/**
55 * A change to the current location.
56 */
57/**
58 * A function that receives notifications about location changes.
59 */
60/**
61 * Describes a location that is the destination of some navigation, either via
62 * `history.push` or `history.replace`. This may be either a URL or the pieces
63 * of a URL path.
64 */
65/**
66 * A history is an interface to the navigation stack. The history serves as the
67 * source of truth for the current location, as well as provides a set of
68 * methods that may be used to change it.
69 *
70 * It is similar to the DOM's `window.history` object, but with a smaller, more
71 * focused API.
72 */
73const PopStateEventType = "popstate";
74//#endregion
75
76////////////////////////////////////////////////////////////////////////////////
77//#region Memory History
78////////////////////////////////////////////////////////////////////////////////
79
80/**
81 * A user-supplied object that describes a location. Used when providing
82 * entries to `createMemoryHistory` via its `initialEntries` option.
83 */
84/**
85 * A memory history stores locations in memory. This is useful in stateful
86 * environments where there is no web browser, such as node tests or React
87 * Native.
88 */
89/**
90 * Memory history stores the current location in memory. It is designed for use
91 * in stateful non-browser environments like tests and React Native.
92 */
93function createMemoryHistory(options) {
94 if (options === void 0) {
95 options = {};
96 }
97 let {
98 initialEntries = ["/"],
99 initialIndex,
100 v5Compat = false
101 } = options;
102 let entries; // Declare so we can access from createMemoryLocation
103 entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : undefined));
104 let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);
105 let action = Action.Pop;
106 let listener = null;
107 function clampIndex(n) {
108 return Math.min(Math.max(n, 0), entries.length - 1);
109 }
110 function getCurrentLocation() {
111 return entries[index];
112 }
113 function createMemoryLocation(to, state, key) {
114 if (state === void 0) {
115 state = null;
116 }
117 let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key);
118 warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to));
119 return location;
120 }
121 function createHref(to) {
122 return typeof to === "string" ? to : createPath(to);
123 }
124 let history = {
125 get index() {
126 return index;
127 },
128 get action() {
129 return action;
130 },
131 get location() {
132 return getCurrentLocation();
133 },
134 createHref,
135 createURL(to) {
136 return new URL(createHref(to), "http://localhost");
137 },
138 encodeLocation(to) {
139 let path = typeof to === "string" ? parsePath(to) : to;
140 return {
141 pathname: path.pathname || "",
142 search: path.search || "",
143 hash: path.hash || ""
144 };
145 },
146 push(to, state) {
147 action = Action.Push;
148 let nextLocation = createMemoryLocation(to, state);
149 index += 1;
150 entries.splice(index, entries.length, nextLocation);
151 if (v5Compat && listener) {
152 listener({
153 action,
154 location: nextLocation,
155 delta: 1
156 });
157 }
158 },
159 replace(to, state) {
160 action = Action.Replace;
161 let nextLocation = createMemoryLocation(to, state);
162 entries[index] = nextLocation;
163 if (v5Compat && listener) {
164 listener({
165 action,
166 location: nextLocation,
167 delta: 0
168 });
169 }
170 },
171 go(delta) {
172 action = Action.Pop;
173 let nextIndex = clampIndex(index + delta);
174 let nextLocation = entries[nextIndex];
175 index = nextIndex;
176 if (listener) {
177 listener({
178 action,
179 location: nextLocation,
180 delta
181 });
182 }
183 },
184 listen(fn) {
185 listener = fn;
186 return () => {
187 listener = null;
188 };
189 }
190 };
191 return history;
192}
193//#endregion
194
195////////////////////////////////////////////////////////////////////////////////
196//#region Browser History
197////////////////////////////////////////////////////////////////////////////////
198
199/**
200 * A browser history stores the current location in regular URLs in a web
201 * browser environment. This is the standard for most web apps and provides the
202 * cleanest URLs the browser's address bar.
203 *
204 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory
205 */
206/**
207 * Browser history stores the location in regular URLs. This is the standard for
208 * most web apps, but it requires some configuration on the server to ensure you
209 * serve the same app at multiple URLs.
210 *
211 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
212 */
213function createBrowserHistory(options) {
214 if (options === void 0) {
215 options = {};
216 }
217 function createBrowserLocation(window, globalHistory) {
218 let {
219 pathname,
220 search,
221 hash
222 } = window.location;
223 return createLocation("", {
224 pathname,
225 search,
226 hash
227 },
228 // state defaults to `null` because `window.history.state` does
229 globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
230 }
231 function createBrowserHref(window, to) {
232 return typeof to === "string" ? to : createPath(to);
233 }
234 return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);
235}
236//#endregion
237
238////////////////////////////////////////////////////////////////////////////////
239//#region Hash History
240////////////////////////////////////////////////////////////////////////////////
241
242/**
243 * A hash history stores the current location in the fragment identifier portion
244 * of the URL in a web browser environment.
245 *
246 * This is ideal for apps that do not control the server for some reason
247 * (because the fragment identifier is never sent to the server), including some
248 * shared hosting environments that do not provide fine-grained controls over
249 * which pages are served at which URLs.
250 *
251 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory
252 */
253/**
254 * Hash history stores the location in window.location.hash. This makes it ideal
255 * for situations where you don't want to send the location to the server for
256 * some reason, either because you do cannot configure it or the URL space is
257 * reserved for something else.
258 *
259 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
260 */
261function createHashHistory(options) {
262 if (options === void 0) {
263 options = {};
264 }
265 function createHashLocation(window, globalHistory) {
266 let {
267 pathname = "/",
268 search = "",
269 hash = ""
270 } = parsePath(window.location.hash.substr(1));
271
272 // Hash URL should always have a leading / just like window.location.pathname
273 // does, so if an app ends up at a route like /#something then we add a
274 // leading slash so all of our path-matching behaves the same as if it would
275 // in a browser router. This is particularly important when there exists a
276 // root splat route (<Route path="*">) since that matches internally against
277 // "/*" and we'd expect /#something to 404 in a hash router app.
278 if (!pathname.startsWith("/") && !pathname.startsWith(".")) {
279 pathname = "/" + pathname;
280 }
281 return createLocation("", {
282 pathname,
283 search,
284 hash
285 },
286 // state defaults to `null` because `window.history.state` does
287 globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
288 }
289 function createHashHref(window, to) {
290 let base = window.document.querySelector("base");
291 let href = "";
292 if (base && base.getAttribute("href")) {
293 let url = window.location.href;
294 let hashIndex = url.indexOf("#");
295 href = hashIndex === -1 ? url : url.slice(0, hashIndex);
296 }
297 return href + "#" + (typeof to === "string" ? to : createPath(to));
298 }
299 function validateHashLocation(location, to) {
300 warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")");
301 }
302 return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);
303}
304//#endregion
305
306////////////////////////////////////////////////////////////////////////////////
307//#region UTILS
308////////////////////////////////////////////////////////////////////////////////
309
310/**
311 * @private
312 */
313function invariant(value, message) {
314 if (value === false || value === null || typeof value === "undefined") {
315 throw new Error(message);
316 }
317}
318function warning(cond, message) {
319 if (!cond) {
320 // eslint-disable-next-line no-console
321 if (typeof console !== "undefined") console.warn(message);
322 try {
323 // Welcome to debugging history!
324 //
325 // This error is thrown as a convenience, so you can more easily
326 // find the source for a warning that appears in the console by
327 // enabling "pause on exceptions" in your JavaScript debugger.
328 throw new Error(message);
329 // eslint-disable-next-line no-empty
330 } catch (e) {}
331 }
332}
333function createKey() {
334 return Math.random().toString(36).substr(2, 8);
335}
336
337/**
338 * For browser-based histories, we combine the state and key into an object
339 */
340function getHistoryState(location, index) {
341 return {
342 usr: location.state,
343 key: location.key,
344 idx: index
345 };
346}
347
348/**
349 * Creates a Location object with a unique key from the given Path
350 */
351function createLocation(current, to, state, key) {
352 if (state === void 0) {
353 state = null;
354 }
355 let location = _extends({
356 pathname: typeof current === "string" ? current : current.pathname,
357 search: "",
358 hash: ""
359 }, typeof to === "string" ? parsePath(to) : to, {
360 state,
361 // TODO: This could be cleaned up. push/replace should probably just take
362 // full Locations now and avoid the need to run through this flow at all
363 // But that's a pretty big refactor to the current test suite so going to
364 // keep as is for the time being and just let any incoming keys take precedence
365 key: to && to.key || key || createKey()
366 });
367 return location;
368}
369
370/**
371 * Creates a string URL path from the given pathname, search, and hash components.
372 */
373function createPath(_ref) {
374 let {
375 pathname = "/",
376 search = "",
377 hash = ""
378 } = _ref;
379 if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search;
380 if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
381 return pathname;
382}
383
384/**
385 * Parses a string URL path into its separate pathname, search, and hash components.
386 */
387function parsePath(path) {
388 let parsedPath = {};
389 if (path) {
390 let hashIndex = path.indexOf("#");
391 if (hashIndex >= 0) {
392 parsedPath.hash = path.substr(hashIndex);
393 path = path.substr(0, hashIndex);
394 }
395 let searchIndex = path.indexOf("?");
396 if (searchIndex >= 0) {
397 parsedPath.search = path.substr(searchIndex);
398 path = path.substr(0, searchIndex);
399 }
400 if (path) {
401 parsedPath.pathname = path;
402 }
403 }
404 return parsedPath;
405}
406function getUrlBasedHistory(getLocation, createHref, validateLocation, options) {
407 if (options === void 0) {
408 options = {};
409 }
410 let {
411 window = document.defaultView,
412 v5Compat = false
413 } = options;
414 let globalHistory = window.history;
415 let action = Action.Pop;
416 let listener = null;
417 let index = getIndex();
418 // Index should only be null when we initialize. If not, it's because the
419 // user called history.pushState or history.replaceState directly, in which
420 // case we should log a warning as it will result in bugs.
421 if (index == null) {
422 index = 0;
423 globalHistory.replaceState(_extends({}, globalHistory.state, {
424 idx: index
425 }), "");
426 }
427 function getIndex() {
428 let state = globalHistory.state || {
429 idx: null
430 };
431 return state.idx;
432 }
433 function handlePop() {
434 action = Action.Pop;
435 let nextIndex = getIndex();
436 let delta = nextIndex == null ? null : nextIndex - index;
437 index = nextIndex;
438 if (listener) {
439 listener({
440 action,
441 location: history.location,
442 delta
443 });
444 }
445 }
446 function push(to, state) {
447 action = Action.Push;
448 let location = createLocation(history.location, to, state);
449 if (validateLocation) validateLocation(location, to);
450 index = getIndex() + 1;
451 let historyState = getHistoryState(location, index);
452 let url = history.createHref(location);
453
454 // try...catch because iOS limits us to 100 pushState calls :/
455 try {
456 globalHistory.pushState(historyState, "", url);
457 } catch (error) {
458 // If the exception is because `state` can't be serialized, let that throw
459 // outwards just like a replace call would so the dev knows the cause
460 // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps
461 // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal
462 if (error instanceof DOMException && error.name === "DataCloneError") {
463 throw error;
464 }
465 // They are going to lose state here, but there is no real
466 // way to warn them about it since the page will refresh...
467 window.location.assign(url);
468 }
469 if (v5Compat && listener) {
470 listener({
471 action,
472 location: history.location,
473 delta: 1
474 });
475 }
476 }
477 function replace(to, state) {
478 action = Action.Replace;
479 let location = createLocation(history.location, to, state);
480 if (validateLocation) validateLocation(location, to);
481 index = getIndex();
482 let historyState = getHistoryState(location, index);
483 let url = history.createHref(location);
484 globalHistory.replaceState(historyState, "", url);
485 if (v5Compat && listener) {
486 listener({
487 action,
488 location: history.location,
489 delta: 0
490 });
491 }
492 }
493 function createURL(to) {
494 // window.location.origin is "null" (the literal string value) in Firefox
495 // under certain conditions, notably when serving from a local HTML file
496 // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297
497 let base = window.location.origin !== "null" ? window.location.origin : window.location.href;
498 let href = typeof to === "string" ? to : createPath(to);
499 // Treating this as a full URL will strip any trailing spaces so we need to
500 // pre-encode them since they might be part of a matching splat param from
501 // an ancestor route
502 href = href.replace(/ $/, "%20");
503 invariant(base, "No window.location.(origin|href) available to create URL for href: " + href);
504 return new URL(href, base);
505 }
506 let history = {
507 get action() {
508 return action;
509 },
510 get location() {
511 return getLocation(window, globalHistory);
512 },
513 listen(fn) {
514 if (listener) {
515 throw new Error("A history only accepts one active listener");
516 }
517 window.addEventListener(PopStateEventType, handlePop);
518 listener = fn;
519 return () => {
520 window.removeEventListener(PopStateEventType, handlePop);
521 listener = null;
522 };
523 },
524 createHref(to) {
525 return createHref(window, to);
526 },
527 createURL,
528 encodeLocation(to) {
529 // Encode a Location the same way window.location would
530 let url = createURL(to);
531 return {
532 pathname: url.pathname,
533 search: url.search,
534 hash: url.hash
535 };
536 },
537 push,
538 replace,
539 go(n) {
540 return globalHistory.go(n);
541 }
542 };
543 return history;
544}
545
546//#endregion
547
548/**
549 * Map of routeId -> data returned from a loader/action/error
550 */
551
552let ResultType = /*#__PURE__*/function (ResultType) {
553 ResultType["data"] = "data";
554 ResultType["deferred"] = "deferred";
555 ResultType["redirect"] = "redirect";
556 ResultType["error"] = "error";
557 return ResultType;
558}({});
559
560/**
561 * Successful result from a loader or action
562 */
563
564/**
565 * Successful defer() result from a loader or action
566 */
567
568/**
569 * Redirect result from a loader or action
570 */
571
572/**
573 * Unsuccessful result from a loader or action
574 */
575
576/**
577 * Result from a loader or action - potentially successful or unsuccessful
578 */
579
580/**
581 * Users can specify either lowercase or uppercase form methods on `<Form>`,
582 * useSubmit(), `<fetcher.Form>`, etc.
583 */
584
585/**
586 * Active navigation/fetcher form methods are exposed in lowercase on the
587 * RouterState
588 */
589
590/**
591 * In v7, active navigation/fetcher form methods are exposed in uppercase on the
592 * RouterState. This is to align with the normalization done via fetch().
593 */
594
595// Thanks https://github.com/sindresorhus/type-fest!
596
597/**
598 * @private
599 * Internal interface to pass around for action submissions, not intended for
600 * external consumption
601 */
602
603/**
604 * @private
605 * Arguments passed to route loader/action functions. Same for now but we keep
606 * this as a private implementation detail in case they diverge in the future.
607 */
608
609// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:
610// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs
611// Also, make them a type alias instead of an interface
612/**
613 * Arguments passed to loader functions
614 */
615/**
616 * Arguments passed to action functions
617 */
618/**
619 * Loaders and actions can return anything except `undefined` (`null` is a
620 * valid return value if there is no data to return). Responses are preferred
621 * and will ease any future migration to Remix
622 */
623/**
624 * Route loader function signature
625 */
626/**
627 * Route action function signature
628 */
629/**
630 * Arguments passed to shouldRevalidate function
631 */
632/**
633 * Route shouldRevalidate function signature. This runs after any submission
634 * (navigation or fetcher), so we flatten the navigation/fetcher submission
635 * onto the arguments. It shouldn't matter whether it came from a navigation
636 * or a fetcher, what really matters is the URLs and the formData since loaders
637 * have to re-run based on the data models that were potentially mutated.
638 */
639/**
640 * Function provided by the framework-aware layers to set `hasErrorBoundary`
641 * from the framework-aware `errorElement` prop
642 *
643 * @deprecated Use `mapRouteProperties` instead
644 */
645/**
646 * Result from a loader or action called via dataStrategy
647 */
648/**
649 * Function provided by the framework-aware layers to set any framework-specific
650 * properties from framework-agnostic properties
651 */
652/**
653 * Keys we cannot change from within a lazy() function. We spread all other keys
654 * onto the route. Either they're meaningful to the router, or they'll get
655 * ignored.
656 */
657const immutableRouteKeys = new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]);
658
659/**
660 * lazy() function to load a route definition, which can add non-matching
661 * related properties to a route
662 */
663
664/**
665 * Base RouteObject with common props shared by all types of routes
666 */
667
668/**
669 * Index routes must not have children
670 */
671
672/**
673 * Non-index routes may have children, but cannot have index
674 */
675
676/**
677 * A route object represents a logical route, with (optionally) its child
678 * routes organized in a tree-like structure.
679 */
680
681/**
682 * A data route object, which is just a RouteObject with a required unique ID
683 */
684
685// Recursive helper for finding path parameters in the absence of wildcards
686
687/**
688 * Examples:
689 * "/a/b/*" -> "*"
690 * ":a" -> "a"
691 * "/a/:b" -> "b"
692 * "/a/blahblahblah:b" -> "b"
693 * "/:a/:b" -> "a" | "b"
694 * "/:a/b/:c/*" -> "a" | "c" | "*"
695 */
696
697// Attempt to parse the given string segment. If it fails, then just return the
698// plain string type as a default fallback. Otherwise, return the union of the
699// parsed string literals that were referenced as dynamic segments in the route.
700/**
701 * The parameters that were parsed from the URL path.
702 */
703/**
704 * A RouteMatch contains info about how a route matched a URL.
705 */
706function isIndexRoute(route) {
707 return route.index === true;
708}
709
710// Walk the route tree generating unique IDs where necessary, so we are working
711// solely with AgnosticDataRouteObject's within the Router
712function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) {
713 if (parentPath === void 0) {
714 parentPath = [];
715 }
716 if (manifest === void 0) {
717 manifest = {};
718 }
719 return routes.map((route, index) => {
720 let treePath = [...parentPath, String(index)];
721 let id = typeof route.id === "string" ? route.id : treePath.join("-");
722 invariant(route.index !== true || !route.children, "Cannot specify children on an index route");
723 invariant(!manifest[id], "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages");
724 if (isIndexRoute(route)) {
725 let indexRoute = _extends({}, route, mapRouteProperties(route), {
726 id
727 });
728 manifest[id] = indexRoute;
729 return indexRoute;
730 } else {
731 let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), {
732 id,
733 children: undefined
734 });
735 manifest[id] = pathOrLayoutRoute;
736 if (route.children) {
737 pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest);
738 }
739 return pathOrLayoutRoute;
740 }
741 });
742}
743
744/**
745 * Matches the given routes to a location and returns the match data.
746 *
747 * @see https://reactrouter.com/v6/utils/match-routes
748 */
749function matchRoutes(routes, locationArg, basename) {
750 if (basename === void 0) {
751 basename = "/";
752 }
753 return matchRoutesImpl(routes, locationArg, basename, false);
754}
755function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
756 let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
757 let pathname = stripBasename(location.pathname || "/", basename);
758 if (pathname == null) {
759 return null;
760 }
761 let branches = flattenRoutes(routes);
762 rankRouteBranches(branches);
763 let matches = null;
764 for (let i = 0; matches == null && i < branches.length; ++i) {
765 // Incoming pathnames are generally encoded from either window.location
766 // or from router.navigate, but we want to match against the unencoded
767 // paths in the route definitions. Memory router locations won't be
768 // encoded here but there also shouldn't be anything to decode so this
769 // should be a safe operation. This avoids needing matchRoutes to be
770 // history-aware.
771 let decoded = decodePath(pathname);
772 matches = matchRouteBranch(branches[i], decoded, allowPartial);
773 }
774 return matches;
775}
776function convertRouteMatchToUiMatch(match, loaderData) {
777 let {
778 route,
779 pathname,
780 params
781 } = match;
782 return {
783 id: route.id,
784 pathname,
785 params,
786 data: loaderData[route.id],
787 handle: route.handle
788 };
789}
790function flattenRoutes(routes, branches, parentsMeta, parentPath) {
791 if (branches === void 0) {
792 branches = [];
793 }
794 if (parentsMeta === void 0) {
795 parentsMeta = [];
796 }
797 if (parentPath === void 0) {
798 parentPath = "";
799 }
800 let flattenRoute = (route, index, relativePath) => {
801 let meta = {
802 relativePath: relativePath === undefined ? route.path || "" : relativePath,
803 caseSensitive: route.caseSensitive === true,
804 childrenIndex: index,
805 route
806 };
807 if (meta.relativePath.startsWith("/")) {
808 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.");
809 meta.relativePath = meta.relativePath.slice(parentPath.length);
810 }
811 let path = joinPaths([parentPath, meta.relativePath]);
812 let routesMeta = parentsMeta.concat(meta);
813
814 // Add the children before adding this route to the array, so we traverse the
815 // route tree depth-first and child routes appear before their parents in
816 // the "flattened" version.
817 if (route.children && route.children.length > 0) {
818 invariant(
819 // Our types know better, but runtime JS may not!
820 // @ts-expect-error
821 route.index !== true, "Index routes must not have child routes. Please remove " + ("all child routes from route path \"" + path + "\"."));
822 flattenRoutes(route.children, branches, routesMeta, path);
823 }
824
825 // Routes without a path shouldn't ever match by themselves unless they are
826 // index routes, so don't add them to the list of possible branches.
827 if (route.path == null && !route.index) {
828 return;
829 }
830 branches.push({
831 path,
832 score: computeScore(path, route.index),
833 routesMeta
834 });
835 };
836 routes.forEach((route, index) => {
837 var _route$path;
838 // coarse-grain check for optional params
839 if (route.path === "" || !((_route$path = route.path) != null && _route$path.includes("?"))) {
840 flattenRoute(route, index);
841 } else {
842 for (let exploded of explodeOptionalSegments(route.path)) {
843 flattenRoute(route, index, exploded);
844 }
845 }
846 });
847 return branches;
848}
849
850/**
851 * Computes all combinations of optional path segments for a given path,
852 * excluding combinations that are ambiguous and of lower priority.
853 *
854 * For example, `/one/:two?/three/:four?/:five?` explodes to:
855 * - `/one/three`
856 * - `/one/:two/three`
857 * - `/one/three/:four`
858 * - `/one/three/:five`
859 * - `/one/:two/three/:four`
860 * - `/one/:two/three/:five`
861 * - `/one/three/:four/:five`
862 * - `/one/:two/three/:four/:five`
863 */
864function explodeOptionalSegments(path) {
865 let segments = path.split("/");
866 if (segments.length === 0) return [];
867 let [first, ...rest] = segments;
868
869 // Optional path segments are denoted by a trailing `?`
870 let isOptional = first.endsWith("?");
871 // Compute the corresponding required segment: `foo?` -> `foo`
872 let required = first.replace(/\?$/, "");
873 if (rest.length === 0) {
874 // Intepret empty string as omitting an optional segment
875 // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`
876 return isOptional ? [required, ""] : [required];
877 }
878 let restExploded = explodeOptionalSegments(rest.join("/"));
879 let result = [];
880
881 // All child paths with the prefix. Do this for all children before the
882 // optional version for all children, so we get consistent ordering where the
883 // parent optional aspect is preferred as required. Otherwise, we can get
884 // child sections interspersed where deeper optional segments are higher than
885 // parent optional segments, where for example, /:two would explode _earlier_
886 // then /:one. By always including the parent as required _for all children_
887 // first, we avoid this issue
888 result.push(...restExploded.map(subpath => subpath === "" ? required : [required, subpath].join("/")));
889
890 // Then, if this is an optional value, add all child versions without
891 if (isOptional) {
892 result.push(...restExploded);
893 }
894
895 // for absolute paths, ensure `/` instead of empty segment
896 return result.map(exploded => path.startsWith("/") && exploded === "" ? "/" : exploded);
897}
898function rankRouteBranches(branches) {
899 branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first
900 : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));
901}
902const paramRe = /^:[\w-]+$/;
903const dynamicSegmentValue = 3;
904const indexRouteValue = 2;
905const emptySegmentValue = 1;
906const staticSegmentValue = 10;
907const splatPenalty = -2;
908const isSplat = s => s === "*";
909function computeScore(path, index) {
910 let segments = path.split("/");
911 let initialScore = segments.length;
912 if (segments.some(isSplat)) {
913 initialScore += splatPenalty;
914 }
915 if (index) {
916 initialScore += indexRouteValue;
917 }
918 return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
919}
920function compareIndexes(a, b) {
921 let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
922 return siblings ?
923 // If two routes are siblings, we should try to match the earlier sibling
924 // first. This allows people to have fine-grained control over the matching
925 // behavior by simply putting routes with identical paths in the order they
926 // want them tried.
927 a[a.length - 1] - b[b.length - 1] :
928 // Otherwise, it doesn't really make sense to rank non-siblings by index,
929 // so they sort equally.
930 0;
931}
932function matchRouteBranch(branch, pathname, allowPartial) {
933 if (allowPartial === void 0) {
934 allowPartial = false;
935 }
936 let {
937 routesMeta
938 } = branch;
939 let matchedParams = {};
940 let matchedPathname = "/";
941 let matches = [];
942 for (let i = 0; i < routesMeta.length; ++i) {
943 let meta = routesMeta[i];
944 let end = i === routesMeta.length - 1;
945 let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
946 let match = matchPath({
947 path: meta.relativePath,
948 caseSensitive: meta.caseSensitive,
949 end
950 }, remainingPathname);
951 let route = meta.route;
952 if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
953 match = matchPath({
954 path: meta.relativePath,
955 caseSensitive: meta.caseSensitive,
956 end: false
957 }, remainingPathname);
958 }
959 if (!match) {
960 return null;
961 }
962 Object.assign(matchedParams, match.params);
963 matches.push({
964 // TODO: Can this as be avoided?
965 params: matchedParams,
966 pathname: joinPaths([matchedPathname, match.pathname]),
967 pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
968 route
969 });
970 if (match.pathnameBase !== "/") {
971 matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
972 }
973 }
974 return matches;
975}
976
977/**
978 * Returns a path with params interpolated.
979 *
980 * @see https://reactrouter.com/v6/utils/generate-path
981 */
982function generatePath(originalPath, params) {
983 if (params === void 0) {
984 params = {};
985 }
986 let path = originalPath;
987 if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) {
988 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(/\*$/, "/*") + "\"."));
989 path = path.replace(/\*$/, "/*");
990 }
991
992 // ensure `/` is added at the beginning if the path is absolute
993 const prefix = path.startsWith("/") ? "/" : "";
994 const stringify = p => p == null ? "" : typeof p === "string" ? p : String(p);
995 const segments = path.split(/\/+/).map((segment, index, array) => {
996 const isLastSegment = index === array.length - 1;
997
998 // only apply the splat if it's the last segment
999 if (isLastSegment && segment === "*") {
1000 const star = "*";
1001 // Apply the splat
1002 return stringify(params[star]);
1003 }
1004 const keyMatch = segment.match(/^:([\w-]+)(\??)$/);
1005 if (keyMatch) {
1006 const [, key, optional] = keyMatch;
1007 let param = params[key];
1008 invariant(optional === "?" || param != null, "Missing \":" + key + "\" param");
1009 return stringify(param);
1010 }
1011
1012 // Remove any optional markers from optional static segments
1013 return segment.replace(/\?$/g, "");
1014 })
1015 // Remove empty segments
1016 .filter(segment => !!segment);
1017 return prefix + segments.join("/");
1018}
1019
1020/**
1021 * A PathPattern is used to match on some portion of a URL pathname.
1022 */
1023
1024/**
1025 * A PathMatch contains info about how a PathPattern matched on a URL pathname.
1026 */
1027
1028/**
1029 * Performs pattern matching on a URL pathname and returns information about
1030 * the match.
1031 *
1032 * @see https://reactrouter.com/v6/utils/match-path
1033 */
1034function matchPath(pattern, pathname) {
1035 if (typeof pattern === "string") {
1036 pattern = {
1037 path: pattern,
1038 caseSensitive: false,
1039 end: true
1040 };
1041 }
1042 let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
1043 let match = pathname.match(matcher);
1044 if (!match) return null;
1045 let matchedPathname = match[0];
1046 let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
1047 let captureGroups = match.slice(1);
1048 let params = compiledParams.reduce((memo, _ref, index) => {
1049 let {
1050 paramName,
1051 isOptional
1052 } = _ref;
1053 // We need to compute the pathnameBase here using the raw splat value
1054 // instead of using params["*"] later because it will be decoded then
1055 if (paramName === "*") {
1056 let splatValue = captureGroups[index] || "";
1057 pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
1058 }
1059 const value = captureGroups[index];
1060 if (isOptional && !value) {
1061 memo[paramName] = undefined;
1062 } else {
1063 memo[paramName] = (value || "").replace(/%2F/g, "/");
1064 }
1065 return memo;
1066 }, {});
1067 return {
1068 params,
1069 pathname: matchedPathname,
1070 pathnameBase,
1071 pattern
1072 };
1073}
1074function compilePath(path, caseSensitive, end) {
1075 if (caseSensitive === void 0) {
1076 caseSensitive = false;
1077 }
1078 if (end === void 0) {
1079 end = true;
1080 }
1081 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(/\*$/, "/*") + "\"."));
1082 let params = [];
1083 let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
1084 .replace(/^\/*/, "/") // Make sure it has a leading /
1085 .replace(/[\\.*+^${}|()[\]]/g, "\\$&") // Escape special regex chars
1086 .replace(/\/:([\w-]+)(\?)?/g, (_, paramName, isOptional) => {
1087 params.push({
1088 paramName,
1089 isOptional: isOptional != null
1090 });
1091 return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
1092 });
1093 if (path.endsWith("*")) {
1094 params.push({
1095 paramName: "*"
1096 });
1097 regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest
1098 : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"]
1099 } else if (end) {
1100 // When matching to the end, ignore trailing slashes
1101 regexpSource += "\\/*$";
1102 } else if (path !== "" && path !== "/") {
1103 // If our path is non-empty and contains anything beyond an initial slash,
1104 // then we have _some_ form of path in our regex, so we should expect to
1105 // match only if we find the end of this path segment. Look for an optional
1106 // non-captured trailing slash (to match a portion of the URL) or the end
1107 // of the path (if we've matched to the end). We used to do this with a
1108 // word boundary but that gives false positives on routes like
1109 // /user-preferences since `-` counts as a word boundary.
1110 regexpSource += "(?:(?=\\/|$))";
1111 } else ;
1112 let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i");
1113 return [matcher, params];
1114}
1115function decodePath(value) {
1116 try {
1117 return value.split("/").map(v => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
1118 } catch (error) {
1119 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 + ")."));
1120 return value;
1121 }
1122}
1123
1124/**
1125 * @private
1126 */
1127function stripBasename(pathname, basename) {
1128 if (basename === "/") return pathname;
1129 if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
1130 return null;
1131 }
1132
1133 // We want to leave trailing slash behavior in the user's control, so if they
1134 // specify a basename with a trailing slash, we should support it
1135 let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
1136 let nextChar = pathname.charAt(startIndex);
1137 if (nextChar && nextChar !== "/") {
1138 // pathname does not start with basename/
1139 return null;
1140 }
1141 return pathname.slice(startIndex) || "/";
1142}
1143const ABSOLUTE_URL_REGEX$1 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
1144const isAbsoluteUrl = url => ABSOLUTE_URL_REGEX$1.test(url);
1145
1146/**
1147 * Returns a resolved path object relative to the given pathname.
1148 *
1149 * @see https://reactrouter.com/v6/utils/resolve-path
1150 */
1151function resolvePath(to, fromPathname) {
1152 if (fromPathname === void 0) {
1153 fromPathname = "/";
1154 }
1155 let {
1156 pathname: toPathname,
1157 search = "",
1158 hash = ""
1159 } = typeof to === "string" ? parsePath(to) : to;
1160 let pathname;
1161 if (toPathname) {
1162 if (isAbsoluteUrl(toPathname)) {
1163 pathname = toPathname;
1164 } else {
1165 if (toPathname.includes("//")) {
1166 let oldPathname = toPathname;
1167 toPathname = toPathname.replace(/\/\/+/g, "/");
1168 warning(false, "Pathnames cannot have embedded double slashes - normalizing " + (oldPathname + " -> " + toPathname));
1169 }
1170 if (toPathname.startsWith("/")) {
1171 pathname = resolvePathname(toPathname.substring(1), "/");
1172 } else {
1173 pathname = resolvePathname(toPathname, fromPathname);
1174 }
1175 }
1176 } else {
1177 pathname = fromPathname;
1178 }
1179 return {
1180 pathname,
1181 search: normalizeSearch(search),
1182 hash: normalizeHash(hash)
1183 };
1184}
1185function resolvePathname(relativePath, fromPathname) {
1186 let segments = fromPathname.replace(/\/+$/, "").split("/");
1187 let relativeSegments = relativePath.split("/");
1188 relativeSegments.forEach(segment => {
1189 if (segment === "..") {
1190 // Keep the root "" segment so the pathname starts at /
1191 if (segments.length > 1) segments.pop();
1192 } else if (segment !== ".") {
1193 segments.push(segment);
1194 }
1195 });
1196 return segments.length > 1 ? segments.join("/") : "/";
1197}
1198function getInvalidPathError(char, field, dest, path) {
1199 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.";
1200}
1201
1202/**
1203 * @private
1204 *
1205 * When processing relative navigation we want to ignore ancestor routes that
1206 * do not contribute to the path, such that index/pathless layout routes don't
1207 * interfere.
1208 *
1209 * For example, when moving a route element into an index route and/or a
1210 * pathless layout route, relative link behavior contained within should stay
1211 * the same. Both of the following examples should link back to the root:
1212 *
1213 * <Route path="/">
1214 * <Route path="accounts" element={<Link to=".."}>
1215 * </Route>
1216 *
1217 * <Route path="/">
1218 * <Route path="accounts">
1219 * <Route element={<AccountsLayout />}> // <-- Does not contribute
1220 * <Route index element={<Link to=".."} /> // <-- Does not contribute
1221 * </Route
1222 * </Route>
1223 * </Route>
1224 */
1225function getPathContributingMatches(matches) {
1226 return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
1227}
1228
1229// Return the array of pathnames for the current route matches - used to
1230// generate the routePathnames input for resolveTo()
1231function getResolveToMatches(matches, v7_relativeSplatPath) {
1232 let pathMatches = getPathContributingMatches(matches);
1233
1234 // When v7_relativeSplatPath is enabled, use the full pathname for the leaf
1235 // match so we include splat values for "." links. See:
1236 // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329
1237 if (v7_relativeSplatPath) {
1238 return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase);
1239 }
1240 return pathMatches.map(match => match.pathnameBase);
1241}
1242
1243/**
1244 * @private
1245 */
1246function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {
1247 if (isPathRelative === void 0) {
1248 isPathRelative = false;
1249 }
1250 let to;
1251 if (typeof toArg === "string") {
1252 to = parsePath(toArg);
1253 } else {
1254 to = _extends({}, toArg);
1255 invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to));
1256 invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to));
1257 invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to));
1258 }
1259 let isEmptyPath = toArg === "" || to.pathname === "";
1260 let toPathname = isEmptyPath ? "/" : to.pathname;
1261 let from;
1262
1263 // Routing is relative to the current pathname if explicitly requested.
1264 //
1265 // If a pathname is explicitly provided in `to`, it should be relative to the
1266 // route context. This is explained in `Note on `<Link to>` values` in our
1267 // migration guide from v5 as a means of disambiguation between `to` values
1268 // that begin with `/` and those that do not. However, this is problematic for
1269 // `to` values that do not provide a pathname. `to` can simply be a search or
1270 // hash string, in which case we should assume that the navigation is relative
1271 // to the current location's pathname and *not* the route pathname.
1272 if (toPathname == null) {
1273 from = locationPathname;
1274 } else {
1275 let routePathnameIndex = routePathnames.length - 1;
1276
1277 // With relative="route" (the default), each leading .. segment means
1278 // "go up one route" instead of "go up one URL segment". This is a key
1279 // difference from how <a href> works and a major reason we call this a
1280 // "to" value instead of a "href".
1281 if (!isPathRelative && toPathname.startsWith("..")) {
1282 let toSegments = toPathname.split("/");
1283 while (toSegments[0] === "..") {
1284 toSegments.shift();
1285 routePathnameIndex -= 1;
1286 }
1287 to.pathname = toSegments.join("/");
1288 }
1289 from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
1290 }
1291 let path = resolvePath(to, from);
1292
1293 // Ensure the pathname has a trailing slash if the original "to" had one
1294 let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
1295 // Or if this was a link to the current path which has a trailing slash
1296 let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
1297 if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
1298 path.pathname += "/";
1299 }
1300 return path;
1301}
1302
1303/**
1304 * @private
1305 */
1306function getToPathname(to) {
1307 // Empty strings should be treated the same as / paths
1308 return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname;
1309}
1310
1311/**
1312 * @private
1313 */
1314const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/");
1315
1316/**
1317 * @private
1318 */
1319const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
1320
1321/**
1322 * @private
1323 */
1324const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
1325
1326/**
1327 * @private
1328 */
1329const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
1330/**
1331 * This is a shortcut for creating `application/json` responses. Converts `data`
1332 * to JSON and sets the `Content-Type` header.
1333 *
1334 * @deprecated The `json` method is deprecated in favor of returning raw objects.
1335 * This method will be removed in v7.
1336 */
1337const json = function json(data, init) {
1338 if (init === void 0) {
1339 init = {};
1340 }
1341 let responseInit = typeof init === "number" ? {
1342 status: init
1343 } : init;
1344 let headers = new Headers(responseInit.headers);
1345 if (!headers.has("Content-Type")) {
1346 headers.set("Content-Type", "application/json; charset=utf-8");
1347 }
1348 return new Response(JSON.stringify(data), _extends({}, responseInit, {
1349 headers
1350 }));
1351};
1352class DataWithResponseInit {
1353 constructor(data, init) {
1354 this.type = "DataWithResponseInit";
1355 this.data = data;
1356 this.init = init || null;
1357 }
1358}
1359
1360/**
1361 * Create "responses" that contain `status`/`headers` without forcing
1362 * serialization into an actual `Response` - used by Remix single fetch
1363 */
1364function data(data, init) {
1365 return new DataWithResponseInit(data, typeof init === "number" ? {
1366 status: init
1367 } : init);
1368}
1369class AbortedDeferredError extends Error {}
1370class DeferredData {
1371 constructor(data, responseInit) {
1372 this.pendingKeysSet = new Set();
1373 this.subscribers = new Set();
1374 this.deferredKeys = [];
1375 invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects");
1376
1377 // Set up an AbortController + Promise we can race against to exit early
1378 // cancellation
1379 let reject;
1380 this.abortPromise = new Promise((_, r) => reject = r);
1381 this.controller = new AbortController();
1382 let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted"));
1383 this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort);
1384 this.controller.signal.addEventListener("abort", onAbort);
1385 this.data = Object.entries(data).reduce((acc, _ref2) => {
1386 let [key, value] = _ref2;
1387 return Object.assign(acc, {
1388 [key]: this.trackPromise(key, value)
1389 });
1390 }, {});
1391 if (this.done) {
1392 // All incoming values were resolved
1393 this.unlistenAbortSignal();
1394 }
1395 this.init = responseInit;
1396 }
1397 trackPromise(key, value) {
1398 if (!(value instanceof Promise)) {
1399 return value;
1400 }
1401 this.deferredKeys.push(key);
1402 this.pendingKeysSet.add(key);
1403
1404 // We store a little wrapper promise that will be extended with
1405 // _data/_error props upon resolve/reject
1406 let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error));
1407
1408 // Register rejection listeners to avoid uncaught promise rejections on
1409 // errors or aborted deferred values
1410 promise.catch(() => {});
1411 Object.defineProperty(promise, "_tracked", {
1412 get: () => true
1413 });
1414 return promise;
1415 }
1416 onSettle(promise, key, error, data) {
1417 if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {
1418 this.unlistenAbortSignal();
1419 Object.defineProperty(promise, "_error", {
1420 get: () => error
1421 });
1422 return Promise.reject(error);
1423 }
1424 this.pendingKeysSet.delete(key);
1425 if (this.done) {
1426 // Nothing left to abort!
1427 this.unlistenAbortSignal();
1428 }
1429
1430 // If the promise was resolved/rejected with undefined, we'll throw an error as you
1431 // should always resolve with a value or null
1432 if (error === undefined && data === undefined) {
1433 let undefinedError = new Error("Deferred data for key \"" + key + "\" resolved/rejected with `undefined`, " + "you must resolve/reject with a value or `null`.");
1434 Object.defineProperty(promise, "_error", {
1435 get: () => undefinedError
1436 });
1437 this.emit(false, key);
1438 return Promise.reject(undefinedError);
1439 }
1440 if (data === undefined) {
1441 Object.defineProperty(promise, "_error", {
1442 get: () => error
1443 });
1444 this.emit(false, key);
1445 return Promise.reject(error);
1446 }
1447 Object.defineProperty(promise, "_data", {
1448 get: () => data
1449 });
1450 this.emit(false, key);
1451 return data;
1452 }
1453 emit(aborted, settledKey) {
1454 this.subscribers.forEach(subscriber => subscriber(aborted, settledKey));
1455 }
1456 subscribe(fn) {
1457 this.subscribers.add(fn);
1458 return () => this.subscribers.delete(fn);
1459 }
1460 cancel() {
1461 this.controller.abort();
1462 this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));
1463 this.emit(true);
1464 }
1465 async resolveData(signal) {
1466 let aborted = false;
1467 if (!this.done) {
1468 let onAbort = () => this.cancel();
1469 signal.addEventListener("abort", onAbort);
1470 aborted = await new Promise(resolve => {
1471 this.subscribe(aborted => {
1472 signal.removeEventListener("abort", onAbort);
1473 if (aborted || this.done) {
1474 resolve(aborted);
1475 }
1476 });
1477 });
1478 }
1479 return aborted;
1480 }
1481 get done() {
1482 return this.pendingKeysSet.size === 0;
1483 }
1484 get unwrappedData() {
1485 invariant(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds");
1486 return Object.entries(this.data).reduce((acc, _ref3) => {
1487 let [key, value] = _ref3;
1488 return Object.assign(acc, {
1489 [key]: unwrapTrackedPromise(value)
1490 });
1491 }, {});
1492 }
1493 get pendingKeys() {
1494 return Array.from(this.pendingKeysSet);
1495 }
1496}
1497function isTrackedPromise(value) {
1498 return value instanceof Promise && value._tracked === true;
1499}
1500function unwrapTrackedPromise(value) {
1501 if (!isTrackedPromise(value)) {
1502 return value;
1503 }
1504 if (value._error) {
1505 throw value._error;
1506 }
1507 return value._data;
1508}
1509/**
1510 * @deprecated The `defer` method is deprecated in favor of returning raw
1511 * objects. This method will be removed in v7.
1512 */
1513const defer = function defer(data, init) {
1514 if (init === void 0) {
1515 init = {};
1516 }
1517 let responseInit = typeof init === "number" ? {
1518 status: init
1519 } : init;
1520 return new DeferredData(data, responseInit);
1521};
1522/**
1523 * A redirect response. Sets the status code and the `Location` header.
1524 * Defaults to "302 Found".
1525 */
1526const redirect = function redirect(url, init) {
1527 if (init === void 0) {
1528 init = 302;
1529 }
1530 let responseInit = init;
1531 if (typeof responseInit === "number") {
1532 responseInit = {
1533 status: responseInit
1534 };
1535 } else if (typeof responseInit.status === "undefined") {
1536 responseInit.status = 302;
1537 }
1538 let headers = new Headers(responseInit.headers);
1539 headers.set("Location", url);
1540 return new Response(null, _extends({}, responseInit, {
1541 headers
1542 }));
1543};
1544
1545/**
1546 * A redirect response that will force a document reload to the new location.
1547 * Sets the status code and the `Location` header.
1548 * Defaults to "302 Found".
1549 */
1550const redirectDocument = (url, init) => {
1551 let response = redirect(url, init);
1552 response.headers.set("X-Remix-Reload-Document", "true");
1553 return response;
1554};
1555
1556/**
1557 * A redirect response that will perform a `history.replaceState` instead of a
1558 * `history.pushState` for client-side navigation redirects.
1559 * Sets the status code and the `Location` header.
1560 * Defaults to "302 Found".
1561 */
1562const replace = (url, init) => {
1563 let response = redirect(url, init);
1564 response.headers.set("X-Remix-Replace", "true");
1565 return response;
1566};
1567/**
1568 * @private
1569 * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
1570 *
1571 * We don't export the class for public use since it's an implementation
1572 * detail, but we export the interface above so folks can build their own
1573 * abstractions around instances via isRouteErrorResponse()
1574 */
1575class ErrorResponseImpl {
1576 constructor(status, statusText, data, internal) {
1577 if (internal === void 0) {
1578 internal = false;
1579 }
1580 this.status = status;
1581 this.statusText = statusText || "";
1582 this.internal = internal;
1583 if (data instanceof Error) {
1584 this.data = data.toString();
1585 this.error = data;
1586 } else {
1587 this.data = data;
1588 }
1589 }
1590}
1591
1592/**
1593 * Check if the given error is an ErrorResponse generated from a 4xx/5xx
1594 * Response thrown from an action/loader
1595 */
1596function isRouteErrorResponse(error) {
1597 return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
1598}
1599
1600////////////////////////////////////////////////////////////////////////////////
1601//#region Types and Constants
1602////////////////////////////////////////////////////////////////////////////////
1603
1604/**
1605 * A Router instance manages all navigation and data loading/mutations
1606 */
1607/**
1608 * State maintained internally by the router. During a navigation, all states
1609 * reflect the the "old" location unless otherwise noted.
1610 */
1611/**
1612 * Data that can be passed into hydrate a Router from SSR
1613 */
1614/**
1615 * Future flags to toggle new feature behavior
1616 */
1617/**
1618 * Initialization options for createRouter
1619 */
1620/**
1621 * State returned from a server-side query() call
1622 */
1623/**
1624 * A StaticHandler instance manages a singular SSR navigation/fetch event
1625 */
1626/**
1627 * Subscriber function signature for changes to router state
1628 */
1629/**
1630 * Function signature for determining the key to be used in scroll restoration
1631 * for a given location
1632 */
1633/**
1634 * Function signature for determining the current scroll position
1635 */
1636// Allowed for any navigation or fetch
1637// Only allowed for navigations
1638// Only allowed for submission navigations
1639/**
1640 * Options for a navigate() call for a normal (non-submission) navigation
1641 */
1642/**
1643 * Options for a navigate() call for a submission navigation
1644 */
1645/**
1646 * Options to pass to navigate() for a navigation
1647 */
1648/**
1649 * Options for a fetch() load
1650 */
1651/**
1652 * Options for a fetch() submission
1653 */
1654/**
1655 * Options to pass to fetch()
1656 */
1657/**
1658 * Potential states for state.navigation
1659 */
1660/**
1661 * Potential states for fetchers
1662 */
1663/**
1664 * Cached info for active fetcher.load() instances so they can participate
1665 * in revalidation
1666 */
1667/**
1668 * Identified fetcher.load() calls that need to be revalidated
1669 */
1670const validMutationMethodsArr = ["post", "put", "patch", "delete"];
1671const validMutationMethods = new Set(validMutationMethodsArr);
1672const validRequestMethodsArr = ["get", ...validMutationMethodsArr];
1673const validRequestMethods = new Set(validRequestMethodsArr);
1674const redirectStatusCodes = new Set([301, 302, 303, 307, 308]);
1675const redirectPreserveMethodStatusCodes = new Set([307, 308]);
1676const IDLE_NAVIGATION = {
1677 state: "idle",
1678 location: undefined,
1679 formMethod: undefined,
1680 formAction: undefined,
1681 formEncType: undefined,
1682 formData: undefined,
1683 json: undefined,
1684 text: undefined
1685};
1686const IDLE_FETCHER = {
1687 state: "idle",
1688 data: undefined,
1689 formMethod: undefined,
1690 formAction: undefined,
1691 formEncType: undefined,
1692 formData: undefined,
1693 json: undefined,
1694 text: undefined
1695};
1696const IDLE_BLOCKER = {
1697 state: "unblocked",
1698 proceed: undefined,
1699 reset: undefined,
1700 location: undefined
1701};
1702const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
1703const defaultMapRouteProperties = route => ({
1704 hasErrorBoundary: Boolean(route.hasErrorBoundary)
1705});
1706const TRANSITIONS_STORAGE_KEY = "remix-router-transitions";
1707
1708//#endregion
1709
1710////////////////////////////////////////////////////////////////////////////////
1711//#region createRouter
1712////////////////////////////////////////////////////////////////////////////////
1713
1714/**
1715 * Create a router and listen to history POP navigations
1716 */
1717function createRouter(init) {
1718 const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : undefined;
1719 const isBrowser = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined";
1720 const isServer = !isBrowser;
1721 invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter");
1722 let mapRouteProperties;
1723 if (init.mapRouteProperties) {
1724 mapRouteProperties = init.mapRouteProperties;
1725 } else if (init.detectErrorBoundary) {
1726 // If they are still using the deprecated version, wrap it with the new API
1727 let detectErrorBoundary = init.detectErrorBoundary;
1728 mapRouteProperties = route => ({
1729 hasErrorBoundary: detectErrorBoundary(route)
1730 });
1731 } else {
1732 mapRouteProperties = defaultMapRouteProperties;
1733 }
1734
1735 // Routes keyed by ID
1736 let manifest = {};
1737 // Routes in tree format for matching
1738 let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest);
1739 let inFlightDataRoutes;
1740 let basename = init.basename || "/";
1741 let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;
1742 let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;
1743
1744 // Config driven behavior flags
1745 let future = _extends({
1746 v7_fetcherPersist: false,
1747 v7_normalizeFormMethod: false,
1748 v7_partialHydration: false,
1749 v7_prependBasename: false,
1750 v7_relativeSplatPath: false,
1751 v7_skipActionErrorRevalidation: false
1752 }, init.future);
1753 // Cleanup function for history
1754 let unlistenHistory = null;
1755 // Externally-provided functions to call on all state changes
1756 let subscribers = new Set();
1757 // Externally-provided object to hold scroll restoration locations during routing
1758 let savedScrollPositions = null;
1759 // Externally-provided function to get scroll restoration keys
1760 let getScrollRestorationKey = null;
1761 // Externally-provided function to get current scroll position
1762 let getScrollPosition = null;
1763 // One-time flag to control the initial hydration scroll restoration. Because
1764 // we don't get the saved positions from <ScrollRestoration /> until _after_
1765 // the initial render, we need to manually trigger a separate updateState to
1766 // send along the restoreScrollPosition
1767 // Set to true if we have `hydrationData` since we assume we were SSR'd and that
1768 // SSR did the initial scroll restoration.
1769 let initialScrollRestored = init.hydrationData != null;
1770 let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
1771 let initialMatchesIsFOW = false;
1772 let initialErrors = null;
1773 if (initialMatches == null && !patchRoutesOnNavigationImpl) {
1774 // If we do not match a user-provided-route, fall back to the root
1775 // to allow the error boundary to take over
1776 let error = getInternalRouterError(404, {
1777 pathname: init.history.location.pathname
1778 });
1779 let {
1780 matches,
1781 route
1782 } = getShortCircuitMatches(dataRoutes);
1783 initialMatches = matches;
1784 initialErrors = {
1785 [route.id]: error
1786 };
1787 }
1788
1789 // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and
1790 // our initial match is a splat route, clear them out so we run through lazy
1791 // discovery on hydration in case there's a more accurate lazy route match.
1792 // In SSR apps (with `hydrationData`), we expect that the server will send
1793 // up the proper matched routes so we don't want to run lazy discovery on
1794 // initial hydration and want to hydrate into the splat route.
1795 if (initialMatches && !init.hydrationData) {
1796 let fogOfWar = checkFogOfWar(initialMatches, dataRoutes, init.history.location.pathname);
1797 if (fogOfWar.active) {
1798 initialMatches = null;
1799 }
1800 }
1801 let initialized;
1802 if (!initialMatches) {
1803 initialized = false;
1804 initialMatches = [];
1805
1806 // If partial hydration and fog of war is enabled, we will be running
1807 // `patchRoutesOnNavigation` during hydration so include any partial matches as
1808 // the initial matches so we can properly render `HydrateFallback`'s
1809 if (future.v7_partialHydration) {
1810 let fogOfWar = checkFogOfWar(null, dataRoutes, init.history.location.pathname);
1811 if (fogOfWar.active && fogOfWar.matches) {
1812 initialMatchesIsFOW = true;
1813 initialMatches = fogOfWar.matches;
1814 }
1815 }
1816 } else if (initialMatches.some(m => m.route.lazy)) {
1817 // All initialMatches need to be loaded before we're ready. If we have lazy
1818 // functions around still then we'll need to run them in initialize()
1819 initialized = false;
1820 } else if (!initialMatches.some(m => m.route.loader)) {
1821 // If we've got no loaders to run, then we're good to go
1822 initialized = true;
1823 } else if (future.v7_partialHydration) {
1824 // If partial hydration is enabled, we're initialized so long as we were
1825 // provided with hydrationData for every route with a loader, and no loaders
1826 // were marked for explicit hydration
1827 let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
1828 let errors = init.hydrationData ? init.hydrationData.errors : null;
1829 // If errors exist, don't consider routes below the boundary
1830 if (errors) {
1831 let idx = initialMatches.findIndex(m => errors[m.route.id] !== undefined);
1832 initialized = initialMatches.slice(0, idx + 1).every(m => !shouldLoadRouteOnHydration(m.route, loaderData, errors));
1833 } else {
1834 initialized = initialMatches.every(m => !shouldLoadRouteOnHydration(m.route, loaderData, errors));
1835 }
1836 } else {
1837 // Without partial hydration - we're initialized if we were provided any
1838 // hydrationData - which is expected to be complete
1839 initialized = init.hydrationData != null;
1840 }
1841 let router;
1842 let state = {
1843 historyAction: init.history.action,
1844 location: init.history.location,
1845 matches: initialMatches,
1846 initialized,
1847 navigation: IDLE_NAVIGATION,
1848 // Don't restore on initial updateState() if we were SSR'd
1849 restoreScrollPosition: init.hydrationData != null ? false : null,
1850 preventScrollReset: false,
1851 revalidation: "idle",
1852 loaderData: init.hydrationData && init.hydrationData.loaderData || {},
1853 actionData: init.hydrationData && init.hydrationData.actionData || null,
1854 errors: init.hydrationData && init.hydrationData.errors || initialErrors,
1855 fetchers: new Map(),
1856 blockers: new Map()
1857 };
1858
1859 // -- Stateful internal variables to manage navigations --
1860 // Current navigation in progress (to be committed in completeNavigation)
1861 let pendingAction = Action.Pop;
1862
1863 // Should the current navigation prevent the scroll reset if scroll cannot
1864 // be restored?
1865 let pendingPreventScrollReset = false;
1866
1867 // AbortController for the active navigation
1868 let pendingNavigationController;
1869
1870 // Should the current navigation enable document.startViewTransition?
1871 let pendingViewTransitionEnabled = false;
1872
1873 // Store applied view transitions so we can apply them on POP
1874 let appliedViewTransitions = new Map();
1875
1876 // Cleanup function for persisting applied transitions to sessionStorage
1877 let removePageHideEventListener = null;
1878
1879 // We use this to avoid touching history in completeNavigation if a
1880 // revalidation is entirely uninterrupted
1881 let isUninterruptedRevalidation = false;
1882
1883 // Use this internal flag to force revalidation of all loaders:
1884 // - submissions (completed or interrupted)
1885 // - useRevalidator()
1886 // - X-Remix-Revalidate (from redirect)
1887 let isRevalidationRequired = false;
1888
1889 // Use this internal array to capture routes that require revalidation due
1890 // to a cancelled deferred on action submission
1891 let cancelledDeferredRoutes = [];
1892
1893 // Use this internal array to capture fetcher loads that were cancelled by an
1894 // action navigation and require revalidation
1895 let cancelledFetcherLoads = new Set();
1896
1897 // AbortControllers for any in-flight fetchers
1898 let fetchControllers = new Map();
1899
1900 // Track loads based on the order in which they started
1901 let incrementingLoadId = 0;
1902
1903 // Track the outstanding pending navigation data load to be compared against
1904 // the globally incrementing load when a fetcher load lands after a completed
1905 // navigation
1906 let pendingNavigationLoadId = -1;
1907
1908 // Fetchers that triggered data reloads as a result of their actions
1909 let fetchReloadIds = new Map();
1910
1911 // Fetchers that triggered redirect navigations
1912 let fetchRedirectIds = new Set();
1913
1914 // Most recent href/match for fetcher.load calls for fetchers
1915 let fetchLoadMatches = new Map();
1916
1917 // Ref-count mounted fetchers so we know when it's ok to clean them up
1918 let activeFetchers = new Map();
1919
1920 // Fetchers that have requested a delete when using v7_fetcherPersist,
1921 // they'll be officially removed after they return to idle
1922 let deletedFetchers = new Set();
1923
1924 // Store DeferredData instances for active route matches. When a
1925 // route loader returns defer() we stick one in here. Then, when a nested
1926 // promise resolves we update loaderData. If a new navigation starts we
1927 // cancel active deferreds for eliminated routes.
1928 let activeDeferreds = new Map();
1929
1930 // Store blocker functions in a separate Map outside of router state since
1931 // we don't need to update UI state if they change
1932 let blockerFunctions = new Map();
1933
1934 // Flag to ignore the next history update, so we can revert the URL change on
1935 // a POP navigation that was blocked by the user without touching router state
1936 let unblockBlockerHistoryUpdate = undefined;
1937
1938 // Initialize the router, all side effects should be kicked off from here.
1939 // Implemented as a Fluent API for ease of:
1940 // let router = createRouter(init).initialize();
1941 function initialize() {
1942 // If history informs us of a POP navigation, start the navigation but do not update
1943 // state. We'll update our own state once the navigation completes
1944 unlistenHistory = init.history.listen(_ref => {
1945 let {
1946 action: historyAction,
1947 location,
1948 delta
1949 } = _ref;
1950 // Ignore this event if it was just us resetting the URL from a
1951 // blocked POP navigation
1952 if (unblockBlockerHistoryUpdate) {
1953 unblockBlockerHistoryUpdate();
1954 unblockBlockerHistoryUpdate = undefined;
1955 return;
1956 }
1957 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.");
1958 let blockerKey = shouldBlockNavigation({
1959 currentLocation: state.location,
1960 nextLocation: location,
1961 historyAction
1962 });
1963 if (blockerKey && delta != null) {
1964 // Restore the URL to match the current UI, but don't update router state
1965 let nextHistoryUpdatePromise = new Promise(resolve => {
1966 unblockBlockerHistoryUpdate = resolve;
1967 });
1968 init.history.go(delta * -1);
1969
1970 // Put the blocker into a blocked state
1971 updateBlocker(blockerKey, {
1972 state: "blocked",
1973 location,
1974 proceed() {
1975 updateBlocker(blockerKey, {
1976 state: "proceeding",
1977 proceed: undefined,
1978 reset: undefined,
1979 location
1980 });
1981 // Re-do the same POP navigation we just blocked, after the url
1982 // restoration is also complete. See:
1983 // https://github.com/remix-run/react-router/issues/11613
1984 nextHistoryUpdatePromise.then(() => init.history.go(delta));
1985 },
1986 reset() {
1987 let blockers = new Map(state.blockers);
1988 blockers.set(blockerKey, IDLE_BLOCKER);
1989 updateState({
1990 blockers
1991 });
1992 }
1993 });
1994 return;
1995 }
1996 return startNavigation(historyAction, location);
1997 });
1998 if (isBrowser) {
1999 // FIXME: This feels gross. How can we cleanup the lines between
2000 // scrollRestoration/appliedTransitions persistance?
2001 restoreAppliedTransitions(routerWindow, appliedViewTransitions);
2002 let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);
2003 routerWindow.addEventListener("pagehide", _saveAppliedTransitions);
2004 removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions);
2005 }
2006
2007 // Kick off initial data load if needed. Use Pop to avoid modifying history
2008 // Note we don't do any handling of lazy here. For SPA's it'll get handled
2009 // in the normal navigation flow. For SSR it's expected that lazy modules are
2010 // resolved prior to router creation since we can't go into a fallbackElement
2011 // UI for SSR'd apps
2012 if (!state.initialized) {
2013 startNavigation(Action.Pop, state.location, {
2014 initialHydration: true
2015 });
2016 }
2017 return router;
2018 }
2019
2020 // Clean up a router and it's side effects
2021 function dispose() {
2022 if (unlistenHistory) {
2023 unlistenHistory();
2024 }
2025 if (removePageHideEventListener) {
2026 removePageHideEventListener();
2027 }
2028 subscribers.clear();
2029 pendingNavigationController && pendingNavigationController.abort();
2030 state.fetchers.forEach((_, key) => deleteFetcher(key));
2031 state.blockers.forEach((_, key) => deleteBlocker(key));
2032 }
2033
2034 // Subscribe to state updates for the router
2035 function subscribe(fn) {
2036 subscribers.add(fn);
2037 return () => subscribers.delete(fn);
2038 }
2039
2040 // Update our state and notify the calling context of the change
2041 function updateState(newState, opts) {
2042 if (opts === void 0) {
2043 opts = {};
2044 }
2045 state = _extends({}, state, newState);
2046
2047 // Prep fetcher cleanup so we can tell the UI which fetcher data entries
2048 // can be removed
2049 let completedFetchers = [];
2050 let deletedFetchersKeys = [];
2051 if (future.v7_fetcherPersist) {
2052 state.fetchers.forEach((fetcher, key) => {
2053 if (fetcher.state === "idle") {
2054 if (deletedFetchers.has(key)) {
2055 // Unmounted from the UI and can be totally removed
2056 deletedFetchersKeys.push(key);
2057 } else {
2058 // Returned to idle but still mounted in the UI, so semi-remains for
2059 // revalidations and such
2060 completedFetchers.push(key);
2061 }
2062 }
2063 });
2064 }
2065
2066 // Remove any lingering deleted fetchers that have already been removed
2067 // from state.fetchers
2068 deletedFetchers.forEach(key => {
2069 if (!state.fetchers.has(key) && !fetchControllers.has(key)) {
2070 deletedFetchersKeys.push(key);
2071 }
2072 });
2073
2074 // Iterate over a local copy so that if flushSync is used and we end up
2075 // removing and adding a new subscriber due to the useCallback dependencies,
2076 // we don't get ourselves into a loop calling the new subscriber immediately
2077 [...subscribers].forEach(subscriber => subscriber(state, {
2078 deletedFetchers: deletedFetchersKeys,
2079 viewTransitionOpts: opts.viewTransitionOpts,
2080 flushSync: opts.flushSync === true
2081 }));
2082
2083 // Remove idle fetchers from state since we only care about in-flight fetchers.
2084 if (future.v7_fetcherPersist) {
2085 completedFetchers.forEach(key => state.fetchers.delete(key));
2086 deletedFetchersKeys.forEach(key => deleteFetcher(key));
2087 } else {
2088 // We already called deleteFetcher() on these, can remove them from this
2089 // Set now that we've handed the keys off to the data layer
2090 deletedFetchersKeys.forEach(key => deletedFetchers.delete(key));
2091 }
2092 }
2093
2094 // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION
2095 // and setting state.[historyAction/location/matches] to the new route.
2096 // - Location is a required param
2097 // - Navigation will always be set to IDLE_NAVIGATION
2098 // - Can pass any other state in newState
2099 function completeNavigation(location, newState, _temp) {
2100 var _location$state, _location$state2;
2101 let {
2102 flushSync
2103 } = _temp === void 0 ? {} : _temp;
2104 // Deduce if we're in a loading/actionReload state:
2105 // - We have committed actionData in the store
2106 // - The current navigation was a mutation submission
2107 // - We're past the submitting state and into the loading state
2108 // - The location being loaded is not the result of a redirect
2109 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;
2110 let actionData;
2111 if (newState.actionData) {
2112 if (Object.keys(newState.actionData).length > 0) {
2113 actionData = newState.actionData;
2114 } else {
2115 // Empty actionData -> clear prior actionData due to an action error
2116 actionData = null;
2117 }
2118 } else if (isActionReload) {
2119 // Keep the current data if we're wrapping up the action reload
2120 actionData = state.actionData;
2121 } else {
2122 // Clear actionData on any other completed navigations
2123 actionData = null;
2124 }
2125
2126 // Always preserve any existing loaderData from re-used routes
2127 let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;
2128
2129 // On a successful navigation we can assume we got through all blockers
2130 // so we can start fresh
2131 let blockers = state.blockers;
2132 if (blockers.size > 0) {
2133 blockers = new Map(blockers);
2134 blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));
2135 }
2136
2137 // Always respect the user flag. Otherwise don't reset on mutation
2138 // submission navigations unless they redirect
2139 let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true;
2140
2141 // Commit any in-flight routes at the end of the HMR revalidation "navigation"
2142 if (inFlightDataRoutes) {
2143 dataRoutes = inFlightDataRoutes;
2144 inFlightDataRoutes = undefined;
2145 }
2146 if (isUninterruptedRevalidation) ; else if (pendingAction === Action.Pop) ; else if (pendingAction === Action.Push) {
2147 init.history.push(location, location.state);
2148 } else if (pendingAction === Action.Replace) {
2149 init.history.replace(location, location.state);
2150 }
2151 let viewTransitionOpts;
2152
2153 // On POP, enable transitions if they were enabled on the original navigation
2154 if (pendingAction === Action.Pop) {
2155 // Forward takes precedence so they behave like the original navigation
2156 let priorPaths = appliedViewTransitions.get(state.location.pathname);
2157 if (priorPaths && priorPaths.has(location.pathname)) {
2158 viewTransitionOpts = {
2159 currentLocation: state.location,
2160 nextLocation: location
2161 };
2162 } else if (appliedViewTransitions.has(location.pathname)) {
2163 // If we don't have a previous forward nav, assume we're popping back to
2164 // the new location and enable if that location previously enabled
2165 viewTransitionOpts = {
2166 currentLocation: location,
2167 nextLocation: state.location
2168 };
2169 }
2170 } else if (pendingViewTransitionEnabled) {
2171 // Store the applied transition on PUSH/REPLACE
2172 let toPaths = appliedViewTransitions.get(state.location.pathname);
2173 if (toPaths) {
2174 toPaths.add(location.pathname);
2175 } else {
2176 toPaths = new Set([location.pathname]);
2177 appliedViewTransitions.set(state.location.pathname, toPaths);
2178 }
2179 viewTransitionOpts = {
2180 currentLocation: state.location,
2181 nextLocation: location
2182 };
2183 }
2184 updateState(_extends({}, newState, {
2185 // matches, errors, fetchers go through as-is
2186 actionData,
2187 loaderData,
2188 historyAction: pendingAction,
2189 location,
2190 initialized: true,
2191 navigation: IDLE_NAVIGATION,
2192 revalidation: "idle",
2193 restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches),
2194 preventScrollReset,
2195 blockers
2196 }), {
2197 viewTransitionOpts,
2198 flushSync: flushSync === true
2199 });
2200
2201 // Reset stateful navigation vars
2202 pendingAction = Action.Pop;
2203 pendingPreventScrollReset = false;
2204 pendingViewTransitionEnabled = false;
2205 isUninterruptedRevalidation = false;
2206 isRevalidationRequired = false;
2207 cancelledDeferredRoutes = [];
2208 }
2209
2210 // Trigger a navigation event, which can either be a numerical POP or a PUSH
2211 // replace with an optional submission
2212 async function navigate(to, opts) {
2213 if (typeof to === "number") {
2214 init.history.go(to);
2215 return;
2216 }
2217 let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, future.v7_relativeSplatPath, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative);
2218 let {
2219 path,
2220 submission,
2221 error
2222 } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts);
2223 let currentLocation = state.location;
2224 let nextLocation = createLocation(state.location, path, opts && opts.state);
2225
2226 // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded
2227 // URL from window.location, so we need to encode it here so the behavior
2228 // remains the same as POP and non-data-router usages. new URL() does all
2229 // the same encoding we'd get from a history.pushState/window.location read
2230 // without having to touch history
2231 nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));
2232 let userReplace = opts && opts.replace != null ? opts.replace : undefined;
2233 let historyAction = Action.Push;
2234 if (userReplace === true) {
2235 historyAction = Action.Replace;
2236 } else if (userReplace === false) ; else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {
2237 // By default on submissions to the current location we REPLACE so that
2238 // users don't have to double-click the back button to get to the prior
2239 // location. If the user redirects to a different location from the
2240 // action/loader this will be ignored and the redirect will be a PUSH
2241 historyAction = Action.Replace;
2242 }
2243 let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined;
2244 let flushSync = (opts && opts.flushSync) === true;
2245 let blockerKey = shouldBlockNavigation({
2246 currentLocation,
2247 nextLocation,
2248 historyAction
2249 });
2250 if (blockerKey) {
2251 // Put the blocker into a blocked state
2252 updateBlocker(blockerKey, {
2253 state: "blocked",
2254 location: nextLocation,
2255 proceed() {
2256 updateBlocker(blockerKey, {
2257 state: "proceeding",
2258 proceed: undefined,
2259 reset: undefined,
2260 location: nextLocation
2261 });
2262 // Send the same navigation through
2263 navigate(to, opts);
2264 },
2265 reset() {
2266 let blockers = new Map(state.blockers);
2267 blockers.set(blockerKey, IDLE_BLOCKER);
2268 updateState({
2269 blockers
2270 });
2271 }
2272 });
2273 return;
2274 }
2275 return await startNavigation(historyAction, nextLocation, {
2276 submission,
2277 // Send through the formData serialization error if we have one so we can
2278 // render at the right error boundary after we match routes
2279 pendingError: error,
2280 preventScrollReset,
2281 replace: opts && opts.replace,
2282 enableViewTransition: opts && opts.viewTransition,
2283 flushSync
2284 });
2285 }
2286
2287 // Revalidate all current loaders. If a navigation is in progress or if this
2288 // is interrupted by a navigation, allow this to "succeed" by calling all
2289 // loaders during the next loader round
2290 function revalidate() {
2291 interruptActiveLoads();
2292 updateState({
2293 revalidation: "loading"
2294 });
2295
2296 // If we're currently submitting an action, we don't need to start a new
2297 // navigation, we'll just let the follow up loader execution call all loaders
2298 if (state.navigation.state === "submitting") {
2299 return;
2300 }
2301
2302 // If we're currently in an idle state, start a new navigation for the current
2303 // action/location and mark it as uninterrupted, which will skip the history
2304 // update in completeNavigation
2305 if (state.navigation.state === "idle") {
2306 startNavigation(state.historyAction, state.location, {
2307 startUninterruptedRevalidation: true
2308 });
2309 return;
2310 }
2311
2312 // Otherwise, if we're currently in a loading state, just start a new
2313 // navigation to the navigation.location but do not trigger an uninterrupted
2314 // revalidation so that history correctly updates once the navigation completes
2315 startNavigation(pendingAction || state.historyAction, state.navigation.location, {
2316 overrideNavigation: state.navigation,
2317 // Proxy through any rending view transition
2318 enableViewTransition: pendingViewTransitionEnabled === true
2319 });
2320 }
2321
2322 // Start a navigation to the given action/location. Can optionally provide a
2323 // overrideNavigation which will override the normalLoad in the case of a redirect
2324 // navigation
2325 async function startNavigation(historyAction, location, opts) {
2326 // Abort any in-progress navigations and start a new one. Unset any ongoing
2327 // uninterrupted revalidations unless told otherwise, since we want this
2328 // new navigation to update history normally
2329 pendingNavigationController && pendingNavigationController.abort();
2330 pendingNavigationController = null;
2331 pendingAction = historyAction;
2332 isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;
2333
2334 // Save the current scroll position every time we start a new navigation,
2335 // and track whether we should reset scroll on completion
2336 saveScrollPosition(state.location, state.matches);
2337 pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
2338 pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;
2339 let routesToUse = inFlightDataRoutes || dataRoutes;
2340 let loadingNavigation = opts && opts.overrideNavigation;
2341 let matches = opts != null && opts.initialHydration && state.matches && state.matches.length > 0 && !initialMatchesIsFOW ?
2342 // `matchRoutes()` has already been called if we're in here via `router.initialize()`
2343 state.matches : matchRoutes(routesToUse, location, basename);
2344 let flushSync = (opts && opts.flushSync) === true;
2345
2346 // Short circuit if it's only a hash change and not a revalidation or
2347 // mutation submission.
2348 //
2349 // Ignore on initial page loads because since the initial hydration will always
2350 // be "same hash". For example, on /page#hash and submit a <Form method="post">
2351 // which will default to a navigation to /page
2352 if (matches && state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
2353 completeNavigation(location, {
2354 matches
2355 }, {
2356 flushSync
2357 });
2358 return;
2359 }
2360 let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);
2361 if (fogOfWar.active && fogOfWar.matches) {
2362 matches = fogOfWar.matches;
2363 }
2364
2365 // Short circuit with a 404 on the root error boundary if we match nothing
2366 if (!matches) {
2367 let {
2368 error,
2369 notFoundMatches,
2370 route
2371 } = handleNavigational404(location.pathname);
2372 completeNavigation(location, {
2373 matches: notFoundMatches,
2374 loaderData: {},
2375 errors: {
2376 [route.id]: error
2377 }
2378 }, {
2379 flushSync
2380 });
2381 return;
2382 }
2383
2384 // Create a controller/Request for this navigation
2385 pendingNavigationController = new AbortController();
2386 let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission);
2387 let pendingActionResult;
2388 if (opts && opts.pendingError) {
2389 // If we have a pendingError, it means the user attempted a GET submission
2390 // with binary FormData so assign here and skip to handleLoaders. That
2391 // way we handle calling loaders above the boundary etc. It's not really
2392 // different from an actionError in that sense.
2393 pendingActionResult = [findNearestBoundary(matches).route.id, {
2394 type: ResultType.error,
2395 error: opts.pendingError
2396 }];
2397 } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
2398 // Call action if we received an action submission
2399 let actionResult = await handleAction(request, location, opts.submission, matches, fogOfWar.active, {
2400 replace: opts.replace,
2401 flushSync
2402 });
2403 if (actionResult.shortCircuited) {
2404 return;
2405 }
2406
2407 // If we received a 404 from handleAction, it's because we couldn't lazily
2408 // discover the destination route so we don't want to call loaders
2409 if (actionResult.pendingActionResult) {
2410 let [routeId, result] = actionResult.pendingActionResult;
2411 if (isErrorResult(result) && isRouteErrorResponse(result.error) && result.error.status === 404) {
2412 pendingNavigationController = null;
2413 completeNavigation(location, {
2414 matches: actionResult.matches,
2415 loaderData: {},
2416 errors: {
2417 [routeId]: result.error
2418 }
2419 });
2420 return;
2421 }
2422 }
2423 matches = actionResult.matches || matches;
2424 pendingActionResult = actionResult.pendingActionResult;
2425 loadingNavigation = getLoadingNavigation(location, opts.submission);
2426 flushSync = false;
2427 // No need to do fog of war matching again on loader execution
2428 fogOfWar.active = false;
2429
2430 // Create a GET request for the loaders
2431 request = createClientSideRequest(init.history, request.url, request.signal);
2432 }
2433
2434 // Call loaders
2435 let {
2436 shortCircuited,
2437 matches: updatedMatches,
2438 loaderData,
2439 errors
2440 } = await handleLoaders(request, location, matches, fogOfWar.active, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionResult);
2441 if (shortCircuited) {
2442 return;
2443 }
2444
2445 // Clean up now that the action/loaders have completed. Don't clean up if
2446 // we short circuited because pendingNavigationController will have already
2447 // been assigned to a new controller for the next navigation
2448 pendingNavigationController = null;
2449 completeNavigation(location, _extends({
2450 matches: updatedMatches || matches
2451 }, getActionDataForCommit(pendingActionResult), {
2452 loaderData,
2453 errors
2454 }));
2455 }
2456
2457 // Call the action matched by the leaf route for this navigation and handle
2458 // redirects/errors
2459 async function handleAction(request, location, submission, matches, isFogOfWar, opts) {
2460 if (opts === void 0) {
2461 opts = {};
2462 }
2463 interruptActiveLoads();
2464
2465 // Put us in a submitting state
2466 let navigation = getSubmittingNavigation(location, submission);
2467 updateState({
2468 navigation
2469 }, {
2470 flushSync: opts.flushSync === true
2471 });
2472 if (isFogOfWar) {
2473 let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);
2474 if (discoverResult.type === "aborted") {
2475 return {
2476 shortCircuited: true
2477 };
2478 } else if (discoverResult.type === "error") {
2479 let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
2480 return {
2481 matches: discoverResult.partialMatches,
2482 pendingActionResult: [boundaryId, {
2483 type: ResultType.error,
2484 error: discoverResult.error
2485 }]
2486 };
2487 } else if (!discoverResult.matches) {
2488 let {
2489 notFoundMatches,
2490 error,
2491 route
2492 } = handleNavigational404(location.pathname);
2493 return {
2494 matches: notFoundMatches,
2495 pendingActionResult: [route.id, {
2496 type: ResultType.error,
2497 error
2498 }]
2499 };
2500 } else {
2501 matches = discoverResult.matches;
2502 }
2503 }
2504
2505 // Call our action and get the result
2506 let result;
2507 let actionMatch = getTargetMatch(matches, location);
2508 if (!actionMatch.route.action && !actionMatch.route.lazy) {
2509 result = {
2510 type: ResultType.error,
2511 error: getInternalRouterError(405, {
2512 method: request.method,
2513 pathname: location.pathname,
2514 routeId: actionMatch.route.id
2515 })
2516 };
2517 } else {
2518 let results = await callDataStrategy("action", state, request, [actionMatch], matches, null);
2519 result = results[actionMatch.route.id];
2520 if (request.signal.aborted) {
2521 return {
2522 shortCircuited: true
2523 };
2524 }
2525 }
2526 if (isRedirectResult(result)) {
2527 let replace;
2528 if (opts && opts.replace != null) {
2529 replace = opts.replace;
2530 } else {
2531 // If the user didn't explicity indicate replace behavior, replace if
2532 // we redirected to the exact same location we're currently at to avoid
2533 // double back-buttons
2534 let location = normalizeRedirectLocation(result.response.headers.get("Location"), new URL(request.url), basename, init.history);
2535 replace = location === state.location.pathname + state.location.search;
2536 }
2537 await startRedirectNavigation(request, result, true, {
2538 submission,
2539 replace
2540 });
2541 return {
2542 shortCircuited: true
2543 };
2544 }
2545 if (isDeferredResult(result)) {
2546 throw getInternalRouterError(400, {
2547 type: "defer-action"
2548 });
2549 }
2550 if (isErrorResult(result)) {
2551 // Store off the pending error - we use it to determine which loaders
2552 // to call and will commit it when we complete the navigation
2553 let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
2554
2555 // By default, all submissions to the current location are REPLACE
2556 // navigations, but if the action threw an error that'll be rendered in
2557 // an errorElement, we fall back to PUSH so that the user can use the
2558 // back button to get back to the pre-submission form location to try
2559 // again
2560 if ((opts && opts.replace) !== true) {
2561 pendingAction = Action.Push;
2562 }
2563 return {
2564 matches,
2565 pendingActionResult: [boundaryMatch.route.id, result]
2566 };
2567 }
2568 return {
2569 matches,
2570 pendingActionResult: [actionMatch.route.id, result]
2571 };
2572 }
2573
2574 // Call all applicable loaders for the given matches, handling redirects,
2575 // errors, etc.
2576 async function handleLoaders(request, location, matches, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionResult) {
2577 // Figure out the right navigation we want to use for data loading
2578 let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);
2579
2580 // If this was a redirect from an action we don't have a "submission" but
2581 // we have it on the loading navigation so use that if available
2582 let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);
2583
2584 // If this is an uninterrupted revalidation, we remain in our current idle
2585 // state. If not, we need to switch to our loading state and load data,
2586 // preserving any new action data or existing action data (in the case of
2587 // a revalidation interrupting an actionReload)
2588 // If we have partialHydration enabled, then don't update the state for the
2589 // initial data load since it's not a "navigation"
2590 let shouldUpdateNavigationState = !isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration);
2591
2592 // When fog of war is enabled, we enter our `loading` state earlier so we
2593 // can discover new routes during the `loading` state. We skip this if
2594 // we've already run actions since we would have done our matching already.
2595 // If the children() function threw then, we want to proceed with the
2596 // partial matches it discovered.
2597 if (isFogOfWar) {
2598 if (shouldUpdateNavigationState) {
2599 let actionData = getUpdatedActionData(pendingActionResult);
2600 updateState(_extends({
2601 navigation: loadingNavigation
2602 }, actionData !== undefined ? {
2603 actionData
2604 } : {}), {
2605 flushSync
2606 });
2607 }
2608 let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);
2609 if (discoverResult.type === "aborted") {
2610 return {
2611 shortCircuited: true
2612 };
2613 } else if (discoverResult.type === "error") {
2614 let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
2615 return {
2616 matches: discoverResult.partialMatches,
2617 loaderData: {},
2618 errors: {
2619 [boundaryId]: discoverResult.error
2620 }
2621 };
2622 } else if (!discoverResult.matches) {
2623 let {
2624 error,
2625 notFoundMatches,
2626 route
2627 } = handleNavigational404(location.pathname);
2628 return {
2629 matches: notFoundMatches,
2630 loaderData: {},
2631 errors: {
2632 [route.id]: error
2633 }
2634 };
2635 } else {
2636 matches = discoverResult.matches;
2637 }
2638 }
2639 let routesToUse = inFlightDataRoutes || dataRoutes;
2640 let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult);
2641
2642 // Cancel pending deferreds for no-longer-matched routes or routes we're
2643 // about to reload. Note that if this is an action reload we would have
2644 // already cancelled all pending deferreds so this would be a no-op
2645 cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId));
2646 pendingNavigationLoadId = ++incrementingLoadId;
2647
2648 // Short circuit if we have no loaders to run
2649 if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {
2650 let updatedFetchers = markFetchRedirectsDone();
2651 completeNavigation(location, _extends({
2652 matches,
2653 loaderData: {},
2654 // Commit pending error if we're short circuiting
2655 errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
2656 [pendingActionResult[0]]: pendingActionResult[1].error
2657 } : null
2658 }, getActionDataForCommit(pendingActionResult), updatedFetchers ? {
2659 fetchers: new Map(state.fetchers)
2660 } : {}), {
2661 flushSync
2662 });
2663 return {
2664 shortCircuited: true
2665 };
2666 }
2667 if (shouldUpdateNavigationState) {
2668 let updates = {};
2669 if (!isFogOfWar) {
2670 // Only update navigation/actionNData if we didn't already do it above
2671 updates.navigation = loadingNavigation;
2672 let actionData = getUpdatedActionData(pendingActionResult);
2673 if (actionData !== undefined) {
2674 updates.actionData = actionData;
2675 }
2676 }
2677 if (revalidatingFetchers.length > 0) {
2678 updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);
2679 }
2680 updateState(updates, {
2681 flushSync
2682 });
2683 }
2684 revalidatingFetchers.forEach(rf => {
2685 abortFetcher(rf.key);
2686 if (rf.controller) {
2687 // Fetchers use an independent AbortController so that aborting a fetcher
2688 // (via deleteFetcher) does not abort the triggering navigation that
2689 // triggered the revalidation
2690 fetchControllers.set(rf.key, rf.controller);
2691 }
2692 });
2693
2694 // Proxy navigation abort through to revalidation fetchers
2695 let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key));
2696 if (pendingNavigationController) {
2697 pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations);
2698 }
2699 let {
2700 loaderResults,
2701 fetcherResults
2702 } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, request);
2703 if (request.signal.aborted) {
2704 return {
2705 shortCircuited: true
2706 };
2707 }
2708
2709 // Clean up _after_ loaders have completed. Don't clean up if we short
2710 // circuited because fetchControllers would have been aborted and
2711 // reassigned to new controllers for the next navigation
2712 if (pendingNavigationController) {
2713 pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
2714 }
2715 revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key));
2716
2717 // If any loaders returned a redirect Response, start a new REPLACE navigation
2718 let redirect = findRedirect(loaderResults);
2719 if (redirect) {
2720 await startRedirectNavigation(request, redirect.result, true, {
2721 replace
2722 });
2723 return {
2724 shortCircuited: true
2725 };
2726 }
2727 redirect = findRedirect(fetcherResults);
2728 if (redirect) {
2729 // If this redirect came from a fetcher make sure we mark it in
2730 // fetchRedirectIds so it doesn't get revalidated on the next set of
2731 // loader executions
2732 fetchRedirectIds.add(redirect.key);
2733 await startRedirectNavigation(request, redirect.result, true, {
2734 replace
2735 });
2736 return {
2737 shortCircuited: true
2738 };
2739 }
2740
2741 // Process and commit output from loaders
2742 let {
2743 loaderData,
2744 errors
2745 } = processLoaderData(state, matches, loaderResults, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds);
2746
2747 // Wire up subscribers to update loaderData as promises settle
2748 activeDeferreds.forEach((deferredData, routeId) => {
2749 deferredData.subscribe(aborted => {
2750 // Note: No need to updateState here since the TrackedPromise on
2751 // loaderData is stable across resolve/reject
2752 // Remove this instance if we were aborted or if promises have settled
2753 if (aborted || deferredData.done) {
2754 activeDeferreds.delete(routeId);
2755 }
2756 });
2757 });
2758
2759 // Preserve SSR errors during partial hydration
2760 if (future.v7_partialHydration && initialHydration && state.errors) {
2761 errors = _extends({}, state.errors, errors);
2762 }
2763 let updatedFetchers = markFetchRedirectsDone();
2764 let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
2765 let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;
2766 return _extends({
2767 matches,
2768 loaderData,
2769 errors
2770 }, shouldUpdateFetchers ? {
2771 fetchers: new Map(state.fetchers)
2772 } : {});
2773 }
2774 function getUpdatedActionData(pendingActionResult) {
2775 if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {
2776 // This is cast to `any` currently because `RouteData`uses any and it
2777 // would be a breaking change to use any.
2778 // TODO: v7 - change `RouteData` to use `unknown` instead of `any`
2779 return {
2780 [pendingActionResult[0]]: pendingActionResult[1].data
2781 };
2782 } else if (state.actionData) {
2783 if (Object.keys(state.actionData).length === 0) {
2784 return null;
2785 } else {
2786 return state.actionData;
2787 }
2788 }
2789 }
2790 function getUpdatedRevalidatingFetchers(revalidatingFetchers) {
2791 revalidatingFetchers.forEach(rf => {
2792 let fetcher = state.fetchers.get(rf.key);
2793 let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined);
2794 state.fetchers.set(rf.key, revalidatingFetcher);
2795 });
2796 return new Map(state.fetchers);
2797 }
2798
2799 // Trigger a fetcher load/submit for the given fetcher key
2800 function fetch(key, routeId, href, opts) {
2801 if (isServer) {
2802 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.");
2803 }
2804 abortFetcher(key);
2805 let flushSync = (opts && opts.flushSync) === true;
2806 let routesToUse = inFlightDataRoutes || dataRoutes;
2807 let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, future.v7_relativeSplatPath, routeId, opts == null ? void 0 : opts.relative);
2808 let matches = matchRoutes(routesToUse, normalizedPath, basename);
2809 let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);
2810 if (fogOfWar.active && fogOfWar.matches) {
2811 matches = fogOfWar.matches;
2812 }
2813 if (!matches) {
2814 setFetcherError(key, routeId, getInternalRouterError(404, {
2815 pathname: normalizedPath
2816 }), {
2817 flushSync
2818 });
2819 return;
2820 }
2821 let {
2822 path,
2823 submission,
2824 error
2825 } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts);
2826 if (error) {
2827 setFetcherError(key, routeId, error, {
2828 flushSync
2829 });
2830 return;
2831 }
2832 let match = getTargetMatch(matches, path);
2833 let preventScrollReset = (opts && opts.preventScrollReset) === true;
2834 if (submission && isMutationMethod(submission.formMethod)) {
2835 handleFetcherAction(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);
2836 return;
2837 }
2838
2839 // Store off the match so we can call it's shouldRevalidate on subsequent
2840 // revalidations
2841 fetchLoadMatches.set(key, {
2842 routeId,
2843 path
2844 });
2845 handleFetcherLoader(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);
2846 }
2847
2848 // Call the action for the matched fetcher.submit(), and then handle redirects,
2849 // errors, and revalidation
2850 async function handleFetcherAction(key, routeId, path, match, requestMatches, isFogOfWar, flushSync, preventScrollReset, submission) {
2851 interruptActiveLoads();
2852 fetchLoadMatches.delete(key);
2853 function detectAndHandle405Error(m) {
2854 if (!m.route.action && !m.route.lazy) {
2855 let error = getInternalRouterError(405, {
2856 method: submission.formMethod,
2857 pathname: path,
2858 routeId: routeId
2859 });
2860 setFetcherError(key, routeId, error, {
2861 flushSync
2862 });
2863 return true;
2864 }
2865 return false;
2866 }
2867 if (!isFogOfWar && detectAndHandle405Error(match)) {
2868 return;
2869 }
2870
2871 // Put this fetcher into it's submitting state
2872 let existingFetcher = state.fetchers.get(key);
2873 updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {
2874 flushSync
2875 });
2876 let abortController = new AbortController();
2877 let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);
2878 if (isFogOfWar) {
2879 let discoverResult = await discoverRoutes(requestMatches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);
2880 if (discoverResult.type === "aborted") {
2881 return;
2882 } else if (discoverResult.type === "error") {
2883 setFetcherError(key, routeId, discoverResult.error, {
2884 flushSync
2885 });
2886 return;
2887 } else if (!discoverResult.matches) {
2888 setFetcherError(key, routeId, getInternalRouterError(404, {
2889 pathname: path
2890 }), {
2891 flushSync
2892 });
2893 return;
2894 } else {
2895 requestMatches = discoverResult.matches;
2896 match = getTargetMatch(requestMatches, path);
2897 if (detectAndHandle405Error(match)) {
2898 return;
2899 }
2900 }
2901 }
2902
2903 // Call the action for the fetcher
2904 fetchControllers.set(key, abortController);
2905 let originatingLoadId = incrementingLoadId;
2906 let actionResults = await callDataStrategy("action", state, fetchRequest, [match], requestMatches, key);
2907 let actionResult = actionResults[match.route.id];
2908 if (fetchRequest.signal.aborted) {
2909 // We can delete this so long as we weren't aborted by our own fetcher
2910 // re-submit which would have put _new_ controller is in fetchControllers
2911 if (fetchControllers.get(key) === abortController) {
2912 fetchControllers.delete(key);
2913 }
2914 return;
2915 }
2916
2917 // When using v7_fetcherPersist, we don't want errors bubbling up to the UI
2918 // or redirects processed for unmounted fetchers so we just revert them to
2919 // idle
2920 if (future.v7_fetcherPersist && deletedFetchers.has(key)) {
2921 if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {
2922 updateFetcherState(key, getDoneFetcher(undefined));
2923 return;
2924 }
2925 // Let SuccessResult's fall through for revalidation
2926 } else {
2927 if (isRedirectResult(actionResult)) {
2928 fetchControllers.delete(key);
2929 if (pendingNavigationLoadId > originatingLoadId) {
2930 // A new navigation was kicked off after our action started, so that
2931 // should take precedence over this redirect navigation. We already
2932 // set isRevalidationRequired so all loaders for the new route should
2933 // fire unless opted out via shouldRevalidate
2934 updateFetcherState(key, getDoneFetcher(undefined));
2935 return;
2936 } else {
2937 fetchRedirectIds.add(key);
2938 updateFetcherState(key, getLoadingFetcher(submission));
2939 return startRedirectNavigation(fetchRequest, actionResult, false, {
2940 fetcherSubmission: submission,
2941 preventScrollReset
2942 });
2943 }
2944 }
2945
2946 // Process any non-redirect errors thrown
2947 if (isErrorResult(actionResult)) {
2948 setFetcherError(key, routeId, actionResult.error);
2949 return;
2950 }
2951 }
2952 if (isDeferredResult(actionResult)) {
2953 throw getInternalRouterError(400, {
2954 type: "defer-action"
2955 });
2956 }
2957
2958 // Start the data load for current matches, or the next location if we're
2959 // in the middle of a navigation
2960 let nextLocation = state.navigation.location || state.location;
2961 let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal);
2962 let routesToUse = inFlightDataRoutes || dataRoutes;
2963 let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches;
2964 invariant(matches, "Didn't find any matches after fetcher action");
2965 let loadId = ++incrementingLoadId;
2966 fetchReloadIds.set(key, loadId);
2967 let loadFetcher = getLoadingFetcher(submission, actionResult.data);
2968 state.fetchers.set(key, loadFetcher);
2969 let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, false, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, [match.route.id, actionResult]);
2970
2971 // Put all revalidating fetchers into the loading state, except for the
2972 // current fetcher which we want to keep in it's current loading state which
2973 // contains it's action submission info + action data
2974 revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => {
2975 let staleKey = rf.key;
2976 let existingFetcher = state.fetchers.get(staleKey);
2977 let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined);
2978 state.fetchers.set(staleKey, revalidatingFetcher);
2979 abortFetcher(staleKey);
2980 if (rf.controller) {
2981 fetchControllers.set(staleKey, rf.controller);
2982 }
2983 });
2984 updateState({
2985 fetchers: new Map(state.fetchers)
2986 });
2987 let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key));
2988 abortController.signal.addEventListener("abort", abortPendingFetchRevalidations);
2989 let {
2990 loaderResults,
2991 fetcherResults
2992 } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);
2993 if (abortController.signal.aborted) {
2994 return;
2995 }
2996 abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
2997 fetchReloadIds.delete(key);
2998 fetchControllers.delete(key);
2999 revalidatingFetchers.forEach(r => fetchControllers.delete(r.key));
3000 let redirect = findRedirect(loaderResults);
3001 if (redirect) {
3002 return startRedirectNavigation(revalidationRequest, redirect.result, false, {
3003 preventScrollReset
3004 });
3005 }
3006 redirect = findRedirect(fetcherResults);
3007 if (redirect) {
3008 // If this redirect came from a fetcher make sure we mark it in
3009 // fetchRedirectIds so it doesn't get revalidated on the next set of
3010 // loader executions
3011 fetchRedirectIds.add(redirect.key);
3012 return startRedirectNavigation(revalidationRequest, redirect.result, false, {
3013 preventScrollReset
3014 });
3015 }
3016
3017 // Process and commit output from loaders
3018 let {
3019 loaderData,
3020 errors
3021 } = processLoaderData(state, matches, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);
3022
3023 // Since we let revalidations complete even if the submitting fetcher was
3024 // deleted, only put it back to idle if it hasn't been deleted
3025 if (state.fetchers.has(key)) {
3026 let doneFetcher = getDoneFetcher(actionResult.data);
3027 state.fetchers.set(key, doneFetcher);
3028 }
3029 abortStaleFetchLoads(loadId);
3030
3031 // If we are currently in a navigation loading state and this fetcher is
3032 // more recent than the navigation, we want the newer data so abort the
3033 // navigation and complete it with the fetcher data
3034 if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) {
3035 invariant(pendingAction, "Expected pending action");
3036 pendingNavigationController && pendingNavigationController.abort();
3037 completeNavigation(state.navigation.location, {
3038 matches,
3039 loaderData,
3040 errors,
3041 fetchers: new Map(state.fetchers)
3042 });
3043 } else {
3044 // otherwise just update with the fetcher data, preserving any existing
3045 // loaderData for loaders that did not need to reload. We have to
3046 // manually merge here since we aren't going through completeNavigation
3047 updateState({
3048 errors,
3049 loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors),
3050 fetchers: new Map(state.fetchers)
3051 });
3052 isRevalidationRequired = false;
3053 }
3054 }
3055
3056 // Call the matched loader for fetcher.load(), handling redirects, errors, etc.
3057 async function handleFetcherLoader(key, routeId, path, match, matches, isFogOfWar, flushSync, preventScrollReset, submission) {
3058 let existingFetcher = state.fetchers.get(key);
3059 updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined), {
3060 flushSync
3061 });
3062 let abortController = new AbortController();
3063 let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);
3064 if (isFogOfWar) {
3065 let discoverResult = await discoverRoutes(matches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);
3066 if (discoverResult.type === "aborted") {
3067 return;
3068 } else if (discoverResult.type === "error") {
3069 setFetcherError(key, routeId, discoverResult.error, {
3070 flushSync
3071 });
3072 return;
3073 } else if (!discoverResult.matches) {
3074 setFetcherError(key, routeId, getInternalRouterError(404, {
3075 pathname: path
3076 }), {
3077 flushSync
3078 });
3079 return;
3080 } else {
3081 matches = discoverResult.matches;
3082 match = getTargetMatch(matches, path);
3083 }
3084 }
3085
3086 // Call the loader for this fetcher route match
3087 fetchControllers.set(key, abortController);
3088 let originatingLoadId = incrementingLoadId;
3089 let results = await callDataStrategy("loader", state, fetchRequest, [match], matches, key);
3090 let result = results[match.route.id];
3091
3092 // Deferred isn't supported for fetcher loads, await everything and treat it
3093 // as a normal load. resolveDeferredData will return undefined if this
3094 // fetcher gets aborted, so we just leave result untouched and short circuit
3095 // below if that happens
3096 if (isDeferredResult(result)) {
3097 result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;
3098 }
3099
3100 // We can delete this so long as we weren't aborted by our our own fetcher
3101 // re-load which would have put _new_ controller is in fetchControllers
3102 if (fetchControllers.get(key) === abortController) {
3103 fetchControllers.delete(key);
3104 }
3105 if (fetchRequest.signal.aborted) {
3106 return;
3107 }
3108
3109 // We don't want errors bubbling up or redirects followed for unmounted
3110 // fetchers, so short circuit here if it was removed from the UI
3111 if (deletedFetchers.has(key)) {
3112 updateFetcherState(key, getDoneFetcher(undefined));
3113 return;
3114 }
3115
3116 // If the loader threw a redirect Response, start a new REPLACE navigation
3117 if (isRedirectResult(result)) {
3118 if (pendingNavigationLoadId > originatingLoadId) {
3119 // A new navigation was kicked off after our loader started, so that
3120 // should take precedence over this redirect navigation
3121 updateFetcherState(key, getDoneFetcher(undefined));
3122 return;
3123 } else {
3124 fetchRedirectIds.add(key);
3125 await startRedirectNavigation(fetchRequest, result, false, {
3126 preventScrollReset
3127 });
3128 return;
3129 }
3130 }
3131
3132 // Process any non-redirect errors thrown
3133 if (isErrorResult(result)) {
3134 setFetcherError(key, routeId, result.error);
3135 return;
3136 }
3137 invariant(!isDeferredResult(result), "Unhandled fetcher deferred data");
3138
3139 // Put the fetcher back into an idle state
3140 updateFetcherState(key, getDoneFetcher(result.data));
3141 }
3142
3143 /**
3144 * Utility function to handle redirects returned from an action or loader.
3145 * Normally, a redirect "replaces" the navigation that triggered it. So, for
3146 * example:
3147 *
3148 * - user is on /a
3149 * - user clicks a link to /b
3150 * - loader for /b redirects to /c
3151 *
3152 * In a non-JS app the browser would track the in-flight navigation to /b and
3153 * then replace it with /c when it encountered the redirect response. In
3154 * the end it would only ever update the URL bar with /c.
3155 *
3156 * In client-side routing using pushState/replaceState, we aim to emulate
3157 * this behavior and we also do not update history until the end of the
3158 * navigation (including processed redirects). This means that we never
3159 * actually touch history until we've processed redirects, so we just use
3160 * the history action from the original navigation (PUSH or REPLACE).
3161 */
3162 async function startRedirectNavigation(request, redirect, isNavigation, _temp2) {
3163 let {
3164 submission,
3165 fetcherSubmission,
3166 preventScrollReset,
3167 replace
3168 } = _temp2 === void 0 ? {} : _temp2;
3169 if (redirect.response.headers.has("X-Remix-Revalidate")) {
3170 isRevalidationRequired = true;
3171 }
3172 let location = redirect.response.headers.get("Location");
3173 invariant(location, "Expected a Location header on the redirect Response");
3174 location = normalizeRedirectLocation(location, new URL(request.url), basename, init.history);
3175 let redirectLocation = createLocation(state.location, location, {
3176 _isRedirect: true
3177 });
3178 if (isBrowser) {
3179 let isDocumentReload = false;
3180 if (redirect.response.headers.has("X-Remix-Reload-Document")) {
3181 // Hard reload if the response contained X-Remix-Reload-Document
3182 isDocumentReload = true;
3183 } else if (ABSOLUTE_URL_REGEX.test(location)) {
3184 const url = init.history.createURL(location);
3185 isDocumentReload =
3186 // Hard reload if it's an absolute URL to a new origin
3187 url.origin !== routerWindow.location.origin ||
3188 // Hard reload if it's an absolute URL that does not match our basename
3189 stripBasename(url.pathname, basename) == null;
3190 }
3191 if (isDocumentReload) {
3192 if (replace) {
3193 routerWindow.location.replace(location);
3194 } else {
3195 routerWindow.location.assign(location);
3196 }
3197 return;
3198 }
3199 }
3200
3201 // There's no need to abort on redirects, since we don't detect the
3202 // redirect until the action/loaders have settled
3203 pendingNavigationController = null;
3204 let redirectHistoryAction = replace === true || redirect.response.headers.has("X-Remix-Replace") ? Action.Replace : Action.Push;
3205
3206 // Use the incoming submission if provided, fallback on the active one in
3207 // state.navigation
3208 let {
3209 formMethod,
3210 formAction,
3211 formEncType
3212 } = state.navigation;
3213 if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {
3214 submission = getSubmissionFromNavigation(state.navigation);
3215 }
3216
3217 // If this was a 307/308 submission we want to preserve the HTTP method and
3218 // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the
3219 // redirected location
3220 let activeSubmission = submission || fetcherSubmission;
3221 if (redirectPreserveMethodStatusCodes.has(redirect.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {
3222 await startNavigation(redirectHistoryAction, redirectLocation, {
3223 submission: _extends({}, activeSubmission, {
3224 formAction: location
3225 }),
3226 // Preserve these flags across redirects
3227 preventScrollReset: preventScrollReset || pendingPreventScrollReset,
3228 enableViewTransition: isNavigation ? pendingViewTransitionEnabled : undefined
3229 });
3230 } else {
3231 // If we have a navigation submission, we will preserve it through the
3232 // redirect navigation
3233 let overrideNavigation = getLoadingNavigation(redirectLocation, submission);
3234 await startNavigation(redirectHistoryAction, redirectLocation, {
3235 overrideNavigation,
3236 // Send fetcher submissions through for shouldRevalidate
3237 fetcherSubmission,
3238 // Preserve these flags across redirects
3239 preventScrollReset: preventScrollReset || pendingPreventScrollReset,
3240 enableViewTransition: isNavigation ? pendingViewTransitionEnabled : undefined
3241 });
3242 }
3243 }
3244
3245 // Utility wrapper for calling dataStrategy client-side without having to
3246 // pass around the manifest, mapRouteProperties, etc.
3247 async function callDataStrategy(type, state, request, matchesToLoad, matches, fetcherKey) {
3248 let results;
3249 let dataResults = {};
3250 try {
3251 results = await callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties);
3252 } catch (e) {
3253 // If the outer dataStrategy method throws, just return the error for all
3254 // matches - and it'll naturally bubble to the root
3255 matchesToLoad.forEach(m => {
3256 dataResults[m.route.id] = {
3257 type: ResultType.error,
3258 error: e
3259 };
3260 });
3261 return dataResults;
3262 }
3263 for (let [routeId, result] of Object.entries(results)) {
3264 if (isRedirectDataStrategyResultResult(result)) {
3265 let response = result.result;
3266 dataResults[routeId] = {
3267 type: ResultType.redirect,
3268 response: normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, future.v7_relativeSplatPath)
3269 };
3270 } else {
3271 dataResults[routeId] = await convertDataStrategyResultToDataResult(result);
3272 }
3273 }
3274 return dataResults;
3275 }
3276 async function callLoadersAndMaybeResolveData(state, matches, matchesToLoad, fetchersToLoad, request) {
3277 let currentMatches = state.matches;
3278
3279 // Kick off loaders and fetchers in parallel
3280 let loaderResultsPromise = callDataStrategy("loader", state, request, matchesToLoad, matches, null);
3281 let fetcherResultsPromise = Promise.all(fetchersToLoad.map(async f => {
3282 if (f.matches && f.match && f.controller) {
3283 let results = await callDataStrategy("loader", state, createClientSideRequest(init.history, f.path, f.controller.signal), [f.match], f.matches, f.key);
3284 let result = results[f.match.route.id];
3285 // Fetcher results are keyed by fetcher key from here on out, not routeId
3286 return {
3287 [f.key]: result
3288 };
3289 } else {
3290 return Promise.resolve({
3291 [f.key]: {
3292 type: ResultType.error,
3293 error: getInternalRouterError(404, {
3294 pathname: f.path
3295 })
3296 }
3297 });
3298 }
3299 }));
3300 let loaderResults = await loaderResultsPromise;
3301 let fetcherResults = (await fetcherResultsPromise).reduce((acc, r) => Object.assign(acc, r), {});
3302 await Promise.all([resolveNavigationDeferredResults(matches, loaderResults, request.signal, currentMatches, state.loaderData), resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad)]);
3303 return {
3304 loaderResults,
3305 fetcherResults
3306 };
3307 }
3308 function interruptActiveLoads() {
3309 // Every interruption triggers a revalidation
3310 isRevalidationRequired = true;
3311
3312 // Cancel pending route-level deferreds and mark cancelled routes for
3313 // revalidation
3314 cancelledDeferredRoutes.push(...cancelActiveDeferreds());
3315
3316 // Abort in-flight fetcher loads
3317 fetchLoadMatches.forEach((_, key) => {
3318 if (fetchControllers.has(key)) {
3319 cancelledFetcherLoads.add(key);
3320 }
3321 abortFetcher(key);
3322 });
3323 }
3324 function updateFetcherState(key, fetcher, opts) {
3325 if (opts === void 0) {
3326 opts = {};
3327 }
3328 state.fetchers.set(key, fetcher);
3329 updateState({
3330 fetchers: new Map(state.fetchers)
3331 }, {
3332 flushSync: (opts && opts.flushSync) === true
3333 });
3334 }
3335 function setFetcherError(key, routeId, error, opts) {
3336 if (opts === void 0) {
3337 opts = {};
3338 }
3339 let boundaryMatch = findNearestBoundary(state.matches, routeId);
3340 deleteFetcher(key);
3341 updateState({
3342 errors: {
3343 [boundaryMatch.route.id]: error
3344 },
3345 fetchers: new Map(state.fetchers)
3346 }, {
3347 flushSync: (opts && opts.flushSync) === true
3348 });
3349 }
3350 function getFetcher(key) {
3351 activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);
3352 // If this fetcher was previously marked for deletion, unmark it since we
3353 // have a new instance
3354 if (deletedFetchers.has(key)) {
3355 deletedFetchers.delete(key);
3356 }
3357 return state.fetchers.get(key) || IDLE_FETCHER;
3358 }
3359 function deleteFetcher(key) {
3360 let fetcher = state.fetchers.get(key);
3361 // Don't abort the controller if this is a deletion of a fetcher.submit()
3362 // in it's loading phase since - we don't want to abort the corresponding
3363 // revalidation and want them to complete and land
3364 if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) {
3365 abortFetcher(key);
3366 }
3367 fetchLoadMatches.delete(key);
3368 fetchReloadIds.delete(key);
3369 fetchRedirectIds.delete(key);
3370
3371 // If we opted into the flag we can clear this now since we're calling
3372 // deleteFetcher() at the end of updateState() and we've already handed the
3373 // deleted fetcher keys off to the data layer.
3374 // If not, we're eagerly calling deleteFetcher() and we need to keep this
3375 // Set populated until the next updateState call, and we'll clear
3376 // `deletedFetchers` then
3377 if (future.v7_fetcherPersist) {
3378 deletedFetchers.delete(key);
3379 }
3380 cancelledFetcherLoads.delete(key);
3381 state.fetchers.delete(key);
3382 }
3383 function deleteFetcherAndUpdateState(key) {
3384 let count = (activeFetchers.get(key) || 0) - 1;
3385 if (count <= 0) {
3386 activeFetchers.delete(key);
3387 deletedFetchers.add(key);
3388 if (!future.v7_fetcherPersist) {
3389 deleteFetcher(key);
3390 }
3391 } else {
3392 activeFetchers.set(key, count);
3393 }
3394 updateState({
3395 fetchers: new Map(state.fetchers)
3396 });
3397 }
3398 function abortFetcher(key) {
3399 let controller = fetchControllers.get(key);
3400 if (controller) {
3401 controller.abort();
3402 fetchControllers.delete(key);
3403 }
3404 }
3405 function markFetchersDone(keys) {
3406 for (let key of keys) {
3407 let fetcher = getFetcher(key);
3408 let doneFetcher = getDoneFetcher(fetcher.data);
3409 state.fetchers.set(key, doneFetcher);
3410 }
3411 }
3412 function markFetchRedirectsDone() {
3413 let doneKeys = [];
3414 let updatedFetchers = false;
3415 for (let key of fetchRedirectIds) {
3416 let fetcher = state.fetchers.get(key);
3417 invariant(fetcher, "Expected fetcher: " + key);
3418 if (fetcher.state === "loading") {
3419 fetchRedirectIds.delete(key);
3420 doneKeys.push(key);
3421 updatedFetchers = true;
3422 }
3423 }
3424 markFetchersDone(doneKeys);
3425 return updatedFetchers;
3426 }
3427 function abortStaleFetchLoads(landedId) {
3428 let yeetedKeys = [];
3429 for (let [key, id] of fetchReloadIds) {
3430 if (id < landedId) {
3431 let fetcher = state.fetchers.get(key);
3432 invariant(fetcher, "Expected fetcher: " + key);
3433 if (fetcher.state === "loading") {
3434 abortFetcher(key);
3435 fetchReloadIds.delete(key);
3436 yeetedKeys.push(key);
3437 }
3438 }
3439 }
3440 markFetchersDone(yeetedKeys);
3441 return yeetedKeys.length > 0;
3442 }
3443 function getBlocker(key, fn) {
3444 let blocker = state.blockers.get(key) || IDLE_BLOCKER;
3445 if (blockerFunctions.get(key) !== fn) {
3446 blockerFunctions.set(key, fn);
3447 }
3448 return blocker;
3449 }
3450 function deleteBlocker(key) {
3451 state.blockers.delete(key);
3452 blockerFunctions.delete(key);
3453 }
3454
3455 // Utility function to update blockers, ensuring valid state transitions
3456 function updateBlocker(key, newBlocker) {
3457 let blocker = state.blockers.get(key) || IDLE_BLOCKER;
3458
3459 // Poor mans state machine :)
3460 // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM
3461 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);
3462 let blockers = new Map(state.blockers);
3463 blockers.set(key, newBlocker);
3464 updateState({
3465 blockers
3466 });
3467 }
3468 function shouldBlockNavigation(_ref2) {
3469 let {
3470 currentLocation,
3471 nextLocation,
3472 historyAction
3473 } = _ref2;
3474 if (blockerFunctions.size === 0) {
3475 return;
3476 }
3477
3478 // We ony support a single active blocker at the moment since we don't have
3479 // any compelling use cases for multi-blocker yet
3480 if (blockerFunctions.size > 1) {
3481 warning(false, "A router only supports one blocker at a time");
3482 }
3483 let entries = Array.from(blockerFunctions.entries());
3484 let [blockerKey, blockerFunction] = entries[entries.length - 1];
3485 let blocker = state.blockers.get(blockerKey);
3486 if (blocker && blocker.state === "proceeding") {
3487 // If the blocker is currently proceeding, we don't need to re-check
3488 // it and can let this navigation continue
3489 return;
3490 }
3491
3492 // At this point, we know we're unblocked/blocked so we need to check the
3493 // user-provided blocker function
3494 if (blockerFunction({
3495 currentLocation,
3496 nextLocation,
3497 historyAction
3498 })) {
3499 return blockerKey;
3500 }
3501 }
3502 function handleNavigational404(pathname) {
3503 let error = getInternalRouterError(404, {
3504 pathname
3505 });
3506 let routesToUse = inFlightDataRoutes || dataRoutes;
3507 let {
3508 matches,
3509 route
3510 } = getShortCircuitMatches(routesToUse);
3511
3512 // Cancel all pending deferred on 404s since we don't keep any routes
3513 cancelActiveDeferreds();
3514 return {
3515 notFoundMatches: matches,
3516 route,
3517 error
3518 };
3519 }
3520 function cancelActiveDeferreds(predicate) {
3521 let cancelledRouteIds = [];
3522 activeDeferreds.forEach((dfd, routeId) => {
3523 if (!predicate || predicate(routeId)) {
3524 // Cancel the deferred - but do not remove from activeDeferreds here -
3525 // we rely on the subscribers to do that so our tests can assert proper
3526 // cleanup via _internalActiveDeferreds
3527 dfd.cancel();
3528 cancelledRouteIds.push(routeId);
3529 activeDeferreds.delete(routeId);
3530 }
3531 });
3532 return cancelledRouteIds;
3533 }
3534
3535 // Opt in to capturing and reporting scroll positions during navigations,
3536 // used by the <ScrollRestoration> component
3537 function enableScrollRestoration(positions, getPosition, getKey) {
3538 savedScrollPositions = positions;
3539 getScrollPosition = getPosition;
3540 getScrollRestorationKey = getKey || null;
3541
3542 // Perform initial hydration scroll restoration, since we miss the boat on
3543 // the initial updateState() because we've not yet rendered <ScrollRestoration/>
3544 // and therefore have no savedScrollPositions available
3545 if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
3546 initialScrollRestored = true;
3547 let y = getSavedScrollPosition(state.location, state.matches);
3548 if (y != null) {
3549 updateState({
3550 restoreScrollPosition: y
3551 });
3552 }
3553 }
3554 return () => {
3555 savedScrollPositions = null;
3556 getScrollPosition = null;
3557 getScrollRestorationKey = null;
3558 };
3559 }
3560 function getScrollKey(location, matches) {
3561 if (getScrollRestorationKey) {
3562 let key = getScrollRestorationKey(location, matches.map(m => convertRouteMatchToUiMatch(m, state.loaderData)));
3563 return key || location.key;
3564 }
3565 return location.key;
3566 }
3567 function saveScrollPosition(location, matches) {
3568 if (savedScrollPositions && getScrollPosition) {
3569 let key = getScrollKey(location, matches);
3570 savedScrollPositions[key] = getScrollPosition();
3571 }
3572 }
3573 function getSavedScrollPosition(location, matches) {
3574 if (savedScrollPositions) {
3575 let key = getScrollKey(location, matches);
3576 let y = savedScrollPositions[key];
3577 if (typeof y === "number") {
3578 return y;
3579 }
3580 }
3581 return null;
3582 }
3583 function checkFogOfWar(matches, routesToUse, pathname) {
3584 if (patchRoutesOnNavigationImpl) {
3585 if (!matches) {
3586 let fogMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
3587 return {
3588 active: true,
3589 matches: fogMatches || []
3590 };
3591 } else {
3592 if (Object.keys(matches[0].params).length > 0) {
3593 // If we matched a dynamic param or a splat, it might only be because
3594 // we haven't yet discovered other routes that would match with a
3595 // higher score. Call patchRoutesOnNavigation just to be sure
3596 let partialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
3597 return {
3598 active: true,
3599 matches: partialMatches
3600 };
3601 }
3602 }
3603 }
3604 return {
3605 active: false,
3606 matches: null
3607 };
3608 }
3609 async function discoverRoutes(matches, pathname, signal, fetcherKey) {
3610 if (!patchRoutesOnNavigationImpl) {
3611 return {
3612 type: "success",
3613 matches
3614 };
3615 }
3616 let partialMatches = matches;
3617 while (true) {
3618 let isNonHMR = inFlightDataRoutes == null;
3619 let routesToUse = inFlightDataRoutes || dataRoutes;
3620 let localManifest = manifest;
3621 try {
3622 await patchRoutesOnNavigationImpl({
3623 signal,
3624 path: pathname,
3625 matches: partialMatches,
3626 fetcherKey,
3627 patch: (routeId, children) => {
3628 if (signal.aborted) return;
3629 patchRoutesImpl(routeId, children, routesToUse, localManifest, mapRouteProperties);
3630 }
3631 });
3632 } catch (e) {
3633 return {
3634 type: "error",
3635 error: e,
3636 partialMatches
3637 };
3638 } finally {
3639 // If we are not in the middle of an HMR revalidation and we changed the
3640 // routes, provide a new identity so when we `updateState` at the end of
3641 // this navigation/fetch `router.routes` will be a new identity and
3642 // trigger a re-run of memoized `router.routes` dependencies.
3643 // HMR will already update the identity and reflow when it lands
3644 // `inFlightDataRoutes` in `completeNavigation`
3645 if (isNonHMR && !signal.aborted) {
3646 dataRoutes = [...dataRoutes];
3647 }
3648 }
3649 if (signal.aborted) {
3650 return {
3651 type: "aborted"
3652 };
3653 }
3654 let newMatches = matchRoutes(routesToUse, pathname, basename);
3655 if (newMatches) {
3656 return {
3657 type: "success",
3658 matches: newMatches
3659 };
3660 }
3661 let newPartialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
3662
3663 // Avoid loops if the second pass results in the same partial matches
3664 if (!newPartialMatches || partialMatches.length === newPartialMatches.length && partialMatches.every((m, i) => m.route.id === newPartialMatches[i].route.id)) {
3665 return {
3666 type: "success",
3667 matches: null
3668 };
3669 }
3670 partialMatches = newPartialMatches;
3671 }
3672 }
3673 function _internalSetRoutes(newRoutes) {
3674 manifest = {};
3675 inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest);
3676 }
3677 function patchRoutes(routeId, children) {
3678 let isNonHMR = inFlightDataRoutes == null;
3679 let routesToUse = inFlightDataRoutes || dataRoutes;
3680 patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties);
3681
3682 // If we are not in the middle of an HMR revalidation and we changed the
3683 // routes, provide a new identity and trigger a reflow via `updateState`
3684 // to re-run memoized `router.routes` dependencies.
3685 // HMR will already update the identity and reflow when it lands
3686 // `inFlightDataRoutes` in `completeNavigation`
3687 if (isNonHMR) {
3688 dataRoutes = [...dataRoutes];
3689 updateState({});
3690 }
3691 }
3692 router = {
3693 get basename() {
3694 return basename;
3695 },
3696 get future() {
3697 return future;
3698 },
3699 get state() {
3700 return state;
3701 },
3702 get routes() {
3703 return dataRoutes;
3704 },
3705 get window() {
3706 return routerWindow;
3707 },
3708 initialize,
3709 subscribe,
3710 enableScrollRestoration,
3711 navigate,
3712 fetch,
3713 revalidate,
3714 // Passthrough to history-aware createHref used by useHref so we get proper
3715 // hash-aware URLs in DOM paths
3716 createHref: to => init.history.createHref(to),
3717 encodeLocation: to => init.history.encodeLocation(to),
3718 getFetcher,
3719 deleteFetcher: deleteFetcherAndUpdateState,
3720 dispose,
3721 getBlocker,
3722 deleteBlocker,
3723 patchRoutes,
3724 _internalFetchControllers: fetchControllers,
3725 _internalActiveDeferreds: activeDeferreds,
3726 // TODO: Remove setRoutes, it's temporary to avoid dealing with
3727 // updating the tree while validating the update algorithm.
3728 _internalSetRoutes
3729 };
3730 return router;
3731}
3732//#endregion
3733
3734////////////////////////////////////////////////////////////////////////////////
3735//#region createStaticHandler
3736////////////////////////////////////////////////////////////////////////////////
3737
3738const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred");
3739
3740/**
3741 * Future flags to toggle new feature behavior
3742 */
3743
3744function createStaticHandler(routes, opts) {
3745 invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler");
3746 let manifest = {};
3747 let basename = (opts ? opts.basename : null) || "/";
3748 let mapRouteProperties;
3749 if (opts != null && opts.mapRouteProperties) {
3750 mapRouteProperties = opts.mapRouteProperties;
3751 } else if (opts != null && opts.detectErrorBoundary) {
3752 // If they are still using the deprecated version, wrap it with the new API
3753 let detectErrorBoundary = opts.detectErrorBoundary;
3754 mapRouteProperties = route => ({
3755 hasErrorBoundary: detectErrorBoundary(route)
3756 });
3757 } else {
3758 mapRouteProperties = defaultMapRouteProperties;
3759 }
3760 // Config driven behavior flags
3761 let future = _extends({
3762 v7_relativeSplatPath: false,
3763 v7_throwAbortReason: false
3764 }, opts ? opts.future : null);
3765 let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest);
3766
3767 /**
3768 * The query() method is intended for document requests, in which we want to
3769 * call an optional action and potentially multiple loaders for all nested
3770 * routes. It returns a StaticHandlerContext object, which is very similar
3771 * to the router state (location, loaderData, actionData, errors, etc.) and
3772 * also adds SSR-specific information such as the statusCode and headers
3773 * from action/loaders Responses.
3774 *
3775 * It _should_ never throw and should report all errors through the
3776 * returned context.errors object, properly associating errors to their error
3777 * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be
3778 * used to emulate React error boundaries during SSr by performing a second
3779 * pass only down to the boundaryId.
3780 *
3781 * The one exception where we do not return a StaticHandlerContext is when a
3782 * redirect response is returned or thrown from any action/loader. We
3783 * propagate that out and return the raw Response so the HTTP server can
3784 * return it directly.
3785 *
3786 * - `opts.requestContext` is an optional server context that will be passed
3787 * to actions/loaders in the `context` parameter
3788 * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent
3789 * the bubbling of errors which allows single-fetch-type implementations
3790 * where the client will handle the bubbling and we may need to return data
3791 * for the handling route
3792 */
3793 async function query(request, _temp3) {
3794 let {
3795 requestContext,
3796 skipLoaderErrorBubbling,
3797 dataStrategy
3798 } = _temp3 === void 0 ? {} : _temp3;
3799 let url = new URL(request.url);
3800 let method = request.method;
3801 let location = createLocation("", createPath(url), null, "default");
3802 let matches = matchRoutes(dataRoutes, location, basename);
3803
3804 // SSR supports HEAD requests while SPA doesn't
3805 if (!isValidMethod(method) && method !== "HEAD") {
3806 let error = getInternalRouterError(405, {
3807 method
3808 });
3809 let {
3810 matches: methodNotAllowedMatches,
3811 route
3812 } = getShortCircuitMatches(dataRoutes);
3813 return {
3814 basename,
3815 location,
3816 matches: methodNotAllowedMatches,
3817 loaderData: {},
3818 actionData: null,
3819 errors: {
3820 [route.id]: error
3821 },
3822 statusCode: error.status,
3823 loaderHeaders: {},
3824 actionHeaders: {},
3825 activeDeferreds: null
3826 };
3827 } else if (!matches) {
3828 let error = getInternalRouterError(404, {
3829 pathname: location.pathname
3830 });
3831 let {
3832 matches: notFoundMatches,
3833 route
3834 } = getShortCircuitMatches(dataRoutes);
3835 return {
3836 basename,
3837 location,
3838 matches: notFoundMatches,
3839 loaderData: {},
3840 actionData: null,
3841 errors: {
3842 [route.id]: error
3843 },
3844 statusCode: error.status,
3845 loaderHeaders: {},
3846 actionHeaders: {},
3847 activeDeferreds: null
3848 };
3849 }
3850 let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, skipLoaderErrorBubbling === true, null);
3851 if (isResponse(result)) {
3852 return result;
3853 }
3854
3855 // When returning StaticHandlerContext, we patch back in the location here
3856 // since we need it for React Context. But this helps keep our submit and
3857 // loadRouteData operating on a Request instead of a Location
3858 return _extends({
3859 location,
3860 basename
3861 }, result);
3862 }
3863
3864 /**
3865 * The queryRoute() method is intended for targeted route requests, either
3866 * for fetch ?_data requests or resource route requests. In this case, we
3867 * are only ever calling a single action or loader, and we are returning the
3868 * returned value directly. In most cases, this will be a Response returned
3869 * from the action/loader, but it may be a primitive or other value as well -
3870 * and in such cases the calling context should handle that accordingly.
3871 *
3872 * We do respect the throw/return differentiation, so if an action/loader
3873 * throws, then this method will throw the value. This is important so we
3874 * can do proper boundary identification in Remix where a thrown Response
3875 * must go to the Catch Boundary but a returned Response is happy-path.
3876 *
3877 * One thing to note is that any Router-initiated Errors that make sense
3878 * to associate with a status code will be thrown as an ErrorResponse
3879 * instance which include the raw Error, such that the calling context can
3880 * serialize the error as they see fit while including the proper response
3881 * code. Examples here are 404 and 405 errors that occur prior to reaching
3882 * any user-defined loaders.
3883 *
3884 * - `opts.routeId` allows you to specify the specific route handler to call.
3885 * If not provided the handler will determine the proper route by matching
3886 * against `request.url`
3887 * - `opts.requestContext` is an optional server context that will be passed
3888 * to actions/loaders in the `context` parameter
3889 */
3890 async function queryRoute(request, _temp4) {
3891 let {
3892 routeId,
3893 requestContext,
3894 dataStrategy
3895 } = _temp4 === void 0 ? {} : _temp4;
3896 let url = new URL(request.url);
3897 let method = request.method;
3898 let location = createLocation("", createPath(url), null, "default");
3899 let matches = matchRoutes(dataRoutes, location, basename);
3900
3901 // SSR supports HEAD requests while SPA doesn't
3902 if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
3903 throw getInternalRouterError(405, {
3904 method
3905 });
3906 } else if (!matches) {
3907 throw getInternalRouterError(404, {
3908 pathname: location.pathname
3909 });
3910 }
3911 let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location);
3912 if (routeId && !match) {
3913 throw getInternalRouterError(403, {
3914 pathname: location.pathname,
3915 routeId
3916 });
3917 } else if (!match) {
3918 // This should never hit I don't think?
3919 throw getInternalRouterError(404, {
3920 pathname: location.pathname
3921 });
3922 }
3923 let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, false, match);
3924 if (isResponse(result)) {
3925 return result;
3926 }
3927 let error = result.errors ? Object.values(result.errors)[0] : undefined;
3928 if (error !== undefined) {
3929 // If we got back result.errors, that means the loader/action threw
3930 // _something_ that wasn't a Response, but it's not guaranteed/required
3931 // to be an `instanceof Error` either, so we have to use throw here to
3932 // preserve the "error" state outside of queryImpl.
3933 throw error;
3934 }
3935
3936 // Pick off the right state value to return
3937 if (result.actionData) {
3938 return Object.values(result.actionData)[0];
3939 }
3940 if (result.loaderData) {
3941 var _result$activeDeferre;
3942 let data = Object.values(result.loaderData)[0];
3943 if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) {
3944 data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];
3945 }
3946 return data;
3947 }
3948 return undefined;
3949 }
3950 async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch) {
3951 invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal");
3952 try {
3953 if (isMutationMethod(request.method.toLowerCase())) {
3954 let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch != null);
3955 return result;
3956 }
3957 let result = await loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch);
3958 return isResponse(result) ? result : _extends({}, result, {
3959 actionData: null,
3960 actionHeaders: {}
3961 });
3962 } catch (e) {
3963 // If the user threw/returned a Response in callLoaderOrAction for a
3964 // `queryRoute` call, we throw the `DataStrategyResult` to bail out early
3965 // and then return or throw the raw Response here accordingly
3966 if (isDataStrategyResult(e) && isResponse(e.result)) {
3967 if (e.type === ResultType.error) {
3968 throw e.result;
3969 }
3970 return e.result;
3971 }
3972 // Redirects are always returned since they don't propagate to catch
3973 // boundaries
3974 if (isRedirectResponse(e)) {
3975 return e;
3976 }
3977 throw e;
3978 }
3979 }
3980 async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest) {
3981 let result;
3982 if (!actionMatch.route.action && !actionMatch.route.lazy) {
3983 let error = getInternalRouterError(405, {
3984 method: request.method,
3985 pathname: new URL(request.url).pathname,
3986 routeId: actionMatch.route.id
3987 });
3988 if (isRouteRequest) {
3989 throw error;
3990 }
3991 result = {
3992 type: ResultType.error,
3993 error
3994 };
3995 } else {
3996 let results = await callDataStrategy("action", request, [actionMatch], matches, isRouteRequest, requestContext, dataStrategy);
3997 result = results[actionMatch.route.id];
3998 if (request.signal.aborted) {
3999 throwStaticHandlerAbortedError(request, isRouteRequest, future);
4000 }
4001 }
4002 if (isRedirectResult(result)) {
4003 // Uhhhh - this should never happen, we should always throw these from
4004 // callLoaderOrAction, but the type narrowing here keeps TS happy and we
4005 // can get back on the "throw all redirect responses" train here should
4006 // this ever happen :/
4007 throw new Response(null, {
4008 status: result.response.status,
4009 headers: {
4010 Location: result.response.headers.get("Location")
4011 }
4012 });
4013 }
4014 if (isDeferredResult(result)) {
4015 let error = getInternalRouterError(400, {
4016 type: "defer-action"
4017 });
4018 if (isRouteRequest) {
4019 throw error;
4020 }
4021 result = {
4022 type: ResultType.error,
4023 error
4024 };
4025 }
4026 if (isRouteRequest) {
4027 // Note: This should only be non-Response values if we get here, since
4028 // isRouteRequest should throw any Response received in callLoaderOrAction
4029 if (isErrorResult(result)) {
4030 throw result.error;
4031 }
4032 return {
4033 matches: [actionMatch],
4034 loaderData: {},
4035 actionData: {
4036 [actionMatch.route.id]: result.data
4037 },
4038 errors: null,
4039 // Note: statusCode + headers are unused here since queryRoute will
4040 // return the raw Response or value
4041 statusCode: 200,
4042 loaderHeaders: {},
4043 actionHeaders: {},
4044 activeDeferreds: null
4045 };
4046 }
4047
4048 // Create a GET request for the loaders
4049 let loaderRequest = new Request(request.url, {
4050 headers: request.headers,
4051 redirect: request.redirect,
4052 signal: request.signal
4053 });
4054 if (isErrorResult(result)) {
4055 // Store off the pending error - we use it to determine which loaders
4056 // to call and will commit it when we complete the navigation
4057 let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
4058 let context = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null, [boundaryMatch.route.id, result]);
4059
4060 // action status codes take precedence over loader status codes
4061 return _extends({}, context, {
4062 statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
4063 actionData: null,
4064 actionHeaders: _extends({}, result.headers ? {
4065 [actionMatch.route.id]: result.headers
4066 } : {})
4067 });
4068 }
4069 let context = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null);
4070 return _extends({}, context, {
4071 actionData: {
4072 [actionMatch.route.id]: result.data
4073 }
4074 }, result.statusCode ? {
4075 statusCode: result.statusCode
4076 } : {}, {
4077 actionHeaders: result.headers ? {
4078 [actionMatch.route.id]: result.headers
4079 } : {}
4080 });
4081 }
4082 async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, pendingActionResult) {
4083 let isRouteRequest = routeMatch != null;
4084
4085 // Short circuit if we have no loaders to run (queryRoute())
4086 if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) {
4087 throw getInternalRouterError(400, {
4088 method: request.method,
4089 pathname: new URL(request.url).pathname,
4090 routeId: routeMatch == null ? void 0 : routeMatch.route.id
4091 });
4092 }
4093 let requestMatches = routeMatch ? [routeMatch] : pendingActionResult && isErrorResult(pendingActionResult[1]) ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) : matches;
4094 let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy);
4095
4096 // Short circuit if we have no loaders to run (query())
4097 if (matchesToLoad.length === 0) {
4098 return {
4099 matches,
4100 // Add a null for all matched routes for proper revalidation on the client
4101 loaderData: matches.reduce((acc, m) => Object.assign(acc, {
4102 [m.route.id]: null
4103 }), {}),
4104 errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
4105 [pendingActionResult[0]]: pendingActionResult[1].error
4106 } : null,
4107 statusCode: 200,
4108 loaderHeaders: {},
4109 activeDeferreds: null
4110 };
4111 }
4112 let results = await callDataStrategy("loader", request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy);
4113 if (request.signal.aborted) {
4114 throwStaticHandlerAbortedError(request, isRouteRequest, future);
4115 }
4116
4117 // Process and commit output from loaders
4118 let activeDeferreds = new Map();
4119 let context = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling);
4120
4121 // Add a null for any non-loader matches for proper revalidation on the client
4122 let executedLoaders = new Set(matchesToLoad.map(match => match.route.id));
4123 matches.forEach(match => {
4124 if (!executedLoaders.has(match.route.id)) {
4125 context.loaderData[match.route.id] = null;
4126 }
4127 });
4128 return _extends({}, context, {
4129 matches,
4130 activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null
4131 });
4132 }
4133
4134 // Utility wrapper for calling dataStrategy server-side without having to
4135 // pass around the manifest, mapRouteProperties, etc.
4136 async function callDataStrategy(type, request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy) {
4137 let results = await callDataStrategyImpl(dataStrategy || defaultDataStrategy, type, null, request, matchesToLoad, matches, null, manifest, mapRouteProperties, requestContext);
4138 let dataResults = {};
4139 await Promise.all(matches.map(async match => {
4140 if (!(match.route.id in results)) {
4141 return;
4142 }
4143 let result = results[match.route.id];
4144 if (isRedirectDataStrategyResultResult(result)) {
4145 let response = result.result;
4146 // Throw redirects and let the server handle them with an HTTP redirect
4147 throw normalizeRelativeRoutingRedirectResponse(response, request, match.route.id, matches, basename, future.v7_relativeSplatPath);
4148 }
4149 if (isResponse(result.result) && isRouteRequest) {
4150 // For SSR single-route requests, we want to hand Responses back
4151 // directly without unwrapping
4152 throw result;
4153 }
4154 dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
4155 }));
4156 return dataResults;
4157 }
4158 return {
4159 dataRoutes,
4160 query,
4161 queryRoute
4162 };
4163}
4164
4165//#endregion
4166
4167////////////////////////////////////////////////////////////////////////////////
4168//#region Helpers
4169////////////////////////////////////////////////////////////////////////////////
4170
4171/**
4172 * Given an existing StaticHandlerContext and an error thrown at render time,
4173 * provide an updated StaticHandlerContext suitable for a second SSR render
4174 */
4175function getStaticContextFromError(routes, context, error) {
4176 let newContext = _extends({}, context, {
4177 statusCode: isRouteErrorResponse(error) ? error.status : 500,
4178 errors: {
4179 [context._deepestRenderedBoundaryId || routes[0].id]: error
4180 }
4181 });
4182 return newContext;
4183}
4184function throwStaticHandlerAbortedError(request, isRouteRequest, future) {
4185 if (future.v7_throwAbortReason && request.signal.reason !== undefined) {
4186 throw request.signal.reason;
4187 }
4188 let method = isRouteRequest ? "queryRoute" : "query";
4189 throw new Error(method + "() call aborted: " + request.method + " " + request.url);
4190}
4191function isSubmissionNavigation(opts) {
4192 return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== undefined);
4193}
4194function normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) {
4195 let contextualMatches;
4196 let activeRouteMatch;
4197 if (fromRouteId) {
4198 // Grab matches up to the calling route so our route-relative logic is
4199 // relative to the correct source route
4200 contextualMatches = [];
4201 for (let match of matches) {
4202 contextualMatches.push(match);
4203 if (match.route.id === fromRouteId) {
4204 activeRouteMatch = match;
4205 break;
4206 }
4207 }
4208 } else {
4209 contextualMatches = matches;
4210 activeRouteMatch = matches[matches.length - 1];
4211 }
4212
4213 // Resolve the relative path
4214 let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === "path");
4215
4216 // When `to` is not specified we inherit search/hash from the current
4217 // location, unlike when to="." and we just inherit the path.
4218 // See https://github.com/remix-run/remix/issues/927
4219 if (to == null) {
4220 path.search = location.search;
4221 path.hash = location.hash;
4222 }
4223
4224 // Account for `?index` params when routing to the current location
4225 if ((to == null || to === "" || to === ".") && activeRouteMatch) {
4226 let nakedIndex = hasNakedIndexQuery(path.search);
4227 if (activeRouteMatch.route.index && !nakedIndex) {
4228 // Add one when we're targeting an index route
4229 path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
4230 } else if (!activeRouteMatch.route.index && nakedIndex) {
4231 // Remove existing ones when we're not
4232 let params = new URLSearchParams(path.search);
4233 let indexValues = params.getAll("index");
4234 params.delete("index");
4235 indexValues.filter(v => v).forEach(v => params.append("index", v));
4236 let qs = params.toString();
4237 path.search = qs ? "?" + qs : "";
4238 }
4239 }
4240
4241 // If we're operating within a basename, prepend it to the pathname. If
4242 // this is a root navigation, then just use the raw basename which allows
4243 // the basename to have full control over the presence of a trailing slash
4244 // on root actions
4245 if (prependBasename && basename !== "/") {
4246 path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
4247 }
4248 return createPath(path);
4249}
4250
4251// Normalize navigation options by converting formMethod=GET formData objects to
4252// URLSearchParams so they behave identically to links with query params
4253function normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) {
4254 // Return location verbatim on non-submission navigations
4255 if (!opts || !isSubmissionNavigation(opts)) {
4256 return {
4257 path
4258 };
4259 }
4260 if (opts.formMethod && !isValidMethod(opts.formMethod)) {
4261 return {
4262 path,
4263 error: getInternalRouterError(405, {
4264 method: opts.formMethod
4265 })
4266 };
4267 }
4268 let getInvalidBodyError = () => ({
4269 path,
4270 error: getInternalRouterError(400, {
4271 type: "invalid-body"
4272 })
4273 });
4274
4275 // Create a Submission on non-GET navigations
4276 let rawFormMethod = opts.formMethod || "get";
4277 let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase();
4278 let formAction = stripHashFromPath(path);
4279 if (opts.body !== undefined) {
4280 if (opts.formEncType === "text/plain") {
4281 // text only support POST/PUT/PATCH/DELETE submissions
4282 if (!isMutationMethod(formMethod)) {
4283 return getInvalidBodyError();
4284 }
4285 let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ?
4286 // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data
4287 Array.from(opts.body.entries()).reduce((acc, _ref3) => {
4288 let [name, value] = _ref3;
4289 return "" + acc + name + "=" + value + "\n";
4290 }, "") : String(opts.body);
4291 return {
4292 path,
4293 submission: {
4294 formMethod,
4295 formAction,
4296 formEncType: opts.formEncType,
4297 formData: undefined,
4298 json: undefined,
4299 text
4300 }
4301 };
4302 } else if (opts.formEncType === "application/json") {
4303 // json only supports POST/PUT/PATCH/DELETE submissions
4304 if (!isMutationMethod(formMethod)) {
4305 return getInvalidBodyError();
4306 }
4307 try {
4308 let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body;
4309 return {
4310 path,
4311 submission: {
4312 formMethod,
4313 formAction,
4314 formEncType: opts.formEncType,
4315 formData: undefined,
4316 json,
4317 text: undefined
4318 }
4319 };
4320 } catch (e) {
4321 return getInvalidBodyError();
4322 }
4323 }
4324 }
4325 invariant(typeof FormData === "function", "FormData is not available in this environment");
4326 let searchParams;
4327 let formData;
4328 if (opts.formData) {
4329 searchParams = convertFormDataToSearchParams(opts.formData);
4330 formData = opts.formData;
4331 } else if (opts.body instanceof FormData) {
4332 searchParams = convertFormDataToSearchParams(opts.body);
4333 formData = opts.body;
4334 } else if (opts.body instanceof URLSearchParams) {
4335 searchParams = opts.body;
4336 formData = convertSearchParamsToFormData(searchParams);
4337 } else if (opts.body == null) {
4338 searchParams = new URLSearchParams();
4339 formData = new FormData();
4340 } else {
4341 try {
4342 searchParams = new URLSearchParams(opts.body);
4343 formData = convertSearchParamsToFormData(searchParams);
4344 } catch (e) {
4345 return getInvalidBodyError();
4346 }
4347 }
4348 let submission = {
4349 formMethod,
4350 formAction,
4351 formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded",
4352 formData,
4353 json: undefined,
4354 text: undefined
4355 };
4356 if (isMutationMethod(submission.formMethod)) {
4357 return {
4358 path,
4359 submission
4360 };
4361 }
4362
4363 // Flatten submission onto URLSearchParams for GET submissions
4364 let parsedPath = parsePath(path);
4365 // On GET navigation submissions we can drop the ?index param from the
4366 // resulting location since all loaders will run. But fetcher GET submissions
4367 // only run a single loader so we need to preserve any incoming ?index params
4368 if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
4369 searchParams.append("index", "");
4370 }
4371 parsedPath.search = "?" + searchParams;
4372 return {
4373 path: createPath(parsedPath),
4374 submission
4375 };
4376}
4377
4378// Filter out all routes at/below any caught error as they aren't going to
4379// render so we don't need to load them
4380function getLoaderMatchesUntilBoundary(matches, boundaryId, includeBoundary) {
4381 if (includeBoundary === void 0) {
4382 includeBoundary = false;
4383 }
4384 let index = matches.findIndex(m => m.route.id === boundaryId);
4385 if (index >= 0) {
4386 return matches.slice(0, includeBoundary ? index + 1 : index);
4387 }
4388 return matches;
4389}
4390function getMatchesToLoad(history, state, matches, submission, location, initialHydration, skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult) {
4391 let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : undefined;
4392 let currentUrl = history.createURL(state.location);
4393 let nextUrl = history.createURL(location);
4394
4395 // Pick navigation matches that are net-new or qualify for revalidation
4396 let boundaryMatches = matches;
4397 if (initialHydration && state.errors) {
4398 // On initial hydration, only consider matches up to _and including_ the boundary.
4399 // This is inclusive to handle cases where a server loader ran successfully,
4400 // a child server loader bubbled up to this route, but this route has
4401 // `clientLoader.hydrate` so we want to still run the `clientLoader` so that
4402 // we have a complete version of `loaderData`
4403 boundaryMatches = getLoaderMatchesUntilBoundary(matches, Object.keys(state.errors)[0], true);
4404 } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {
4405 // If an action threw an error, we call loaders up to, but not including the
4406 // boundary
4407 boundaryMatches = getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]);
4408 }
4409
4410 // Don't revalidate loaders by default after action 4xx/5xx responses
4411 // when the flag is enabled. They can still opt-into revalidation via
4412 // `shouldRevalidate` via `actionResult`
4413 let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : undefined;
4414 let shouldSkipRevalidation = skipActionErrorRevalidation && actionStatus && actionStatus >= 400;
4415 let navigationMatches = boundaryMatches.filter((match, index) => {
4416 let {
4417 route
4418 } = match;
4419 if (route.lazy) {
4420 // We haven't loaded this route yet so we don't know if it's got a loader!
4421 return true;
4422 }
4423 if (route.loader == null) {
4424 return false;
4425 }
4426 if (initialHydration) {
4427 return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);
4428 }
4429
4430 // Always call the loader on new route instances and pending defer cancellations
4431 if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) {
4432 return true;
4433 }
4434
4435 // This is the default implementation for when we revalidate. If the route
4436 // provides it's own implementation, then we give them full control but
4437 // provide this value so they can leverage it if needed after they check
4438 // their own specific use cases
4439 let currentRouteMatch = state.matches[index];
4440 let nextRouteMatch = match;
4441 return shouldRevalidateLoader(match, _extends({
4442 currentUrl,
4443 currentParams: currentRouteMatch.params,
4444 nextUrl,
4445 nextParams: nextRouteMatch.params
4446 }, submission, {
4447 actionResult,
4448 actionStatus,
4449 defaultShouldRevalidate: shouldSkipRevalidation ? false :
4450 // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate
4451 isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search ||
4452 // Search params affect all loaders
4453 currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch)
4454 }));
4455 });
4456
4457 // Pick fetcher.loads that need to be revalidated
4458 let revalidatingFetchers = [];
4459 fetchLoadMatches.forEach((f, key) => {
4460 // Don't revalidate:
4461 // - on initial hydration (shouldn't be any fetchers then anyway)
4462 // - if fetcher won't be present in the subsequent render
4463 // - no longer matches the URL (v7_fetcherPersist=false)
4464 // - was unmounted but persisted due to v7_fetcherPersist=true
4465 if (initialHydration || !matches.some(m => m.route.id === f.routeId) || deletedFetchers.has(key)) {
4466 return;
4467 }
4468 let fetcherMatches = matchRoutes(routesToUse, f.path, basename);
4469
4470 // If the fetcher path no longer matches, push it in with null matches so
4471 // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is
4472 // currently only a use-case for Remix HMR where the route tree can change
4473 // at runtime and remove a route previously loaded via a fetcher
4474 if (!fetcherMatches) {
4475 revalidatingFetchers.push({
4476 key,
4477 routeId: f.routeId,
4478 path: f.path,
4479 matches: null,
4480 match: null,
4481 controller: null
4482 });
4483 return;
4484 }
4485
4486 // Revalidating fetchers are decoupled from the route matches since they
4487 // load from a static href. They revalidate based on explicit revalidation
4488 // (submission, useRevalidator, or X-Remix-Revalidate)
4489 let fetcher = state.fetchers.get(key);
4490 let fetcherMatch = getTargetMatch(fetcherMatches, f.path);
4491 let shouldRevalidate = false;
4492 if (fetchRedirectIds.has(key)) {
4493 // Never trigger a revalidation of an actively redirecting fetcher
4494 shouldRevalidate = false;
4495 } else if (cancelledFetcherLoads.has(key)) {
4496 // Always mark for revalidation if the fetcher was cancelled
4497 cancelledFetcherLoads.delete(key);
4498 shouldRevalidate = true;
4499 } else if (fetcher && fetcher.state !== "idle" && fetcher.data === undefined) {
4500 // If the fetcher hasn't ever completed loading yet, then this isn't a
4501 // revalidation, it would just be a brand new load if an explicit
4502 // revalidation is required
4503 shouldRevalidate = isRevalidationRequired;
4504 } else {
4505 // Otherwise fall back on any user-defined shouldRevalidate, defaulting
4506 // to explicit revalidations only
4507 shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({
4508 currentUrl,
4509 currentParams: state.matches[state.matches.length - 1].params,
4510 nextUrl,
4511 nextParams: matches[matches.length - 1].params
4512 }, submission, {
4513 actionResult,
4514 actionStatus,
4515 defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired
4516 }));
4517 }
4518 if (shouldRevalidate) {
4519 revalidatingFetchers.push({
4520 key,
4521 routeId: f.routeId,
4522 path: f.path,
4523 matches: fetcherMatches,
4524 match: fetcherMatch,
4525 controller: new AbortController()
4526 });
4527 }
4528 });
4529 return [navigationMatches, revalidatingFetchers];
4530}
4531function shouldLoadRouteOnHydration(route, loaderData, errors) {
4532 // We dunno if we have a loader - gotta find out!
4533 if (route.lazy) {
4534 return true;
4535 }
4536
4537 // No loader, nothing to initialize
4538 if (!route.loader) {
4539 return false;
4540 }
4541 let hasData = loaderData != null && loaderData[route.id] !== undefined;
4542 let hasError = errors != null && errors[route.id] !== undefined;
4543
4544 // Don't run if we error'd during SSR
4545 if (!hasData && hasError) {
4546 return false;
4547 }
4548
4549 // Explicitly opting-in to running on hydration
4550 if (typeof route.loader === "function" && route.loader.hydrate === true) {
4551 return true;
4552 }
4553
4554 // Otherwise, run if we're not yet initialized with anything
4555 return !hasData && !hasError;
4556}
4557function isNewLoader(currentLoaderData, currentMatch, match) {
4558 let isNew =
4559 // [a] -> [a, b]
4560 !currentMatch ||
4561 // [a, b] -> [a, c]
4562 match.route.id !== currentMatch.route.id;
4563
4564 // Handle the case that we don't have data for a re-used route, potentially
4565 // from a prior error or from a cancelled pending deferred
4566 let isMissingData = currentLoaderData[match.route.id] === undefined;
4567
4568 // Always load if this is a net-new route or we don't yet have data
4569 return isNew || isMissingData;
4570}
4571function isNewRouteInstance(currentMatch, match) {
4572 let currentPath = currentMatch.route.path;
4573 return (
4574 // param change for this match, /users/123 -> /users/456
4575 currentMatch.pathname !== match.pathname ||
4576 // splat param changed, which is not present in match.path
4577 // e.g. /files/images/avatar.jpg -> files/finances.xls
4578 currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"]
4579 );
4580}
4581function shouldRevalidateLoader(loaderMatch, arg) {
4582 if (loaderMatch.route.shouldRevalidate) {
4583 let routeChoice = loaderMatch.route.shouldRevalidate(arg);
4584 if (typeof routeChoice === "boolean") {
4585 return routeChoice;
4586 }
4587 }
4588 return arg.defaultShouldRevalidate;
4589}
4590function patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties) {
4591 var _childrenToPatch;
4592 let childrenToPatch;
4593 if (routeId) {
4594 let route = manifest[routeId];
4595 invariant(route, "No route found to patch children into: routeId = " + routeId);
4596 if (!route.children) {
4597 route.children = [];
4598 }
4599 childrenToPatch = route.children;
4600 } else {
4601 childrenToPatch = routesToUse;
4602 }
4603
4604 // Don't patch in routes we already know about so that `patch` is idempotent
4605 // to simplify user-land code. This is useful because we re-call the
4606 // `patchRoutesOnNavigation` function for matched routes with params.
4607 let uniqueChildren = children.filter(newRoute => !childrenToPatch.some(existingRoute => isSameRoute(newRoute, existingRoute)));
4608 let newRoutes = convertRoutesToDataRoutes(uniqueChildren, mapRouteProperties, [routeId || "_", "patch", String(((_childrenToPatch = childrenToPatch) == null ? void 0 : _childrenToPatch.length) || "0")], manifest);
4609 childrenToPatch.push(...newRoutes);
4610}
4611function isSameRoute(newRoute, existingRoute) {
4612 // Most optimal check is by id
4613 if ("id" in newRoute && "id" in existingRoute && newRoute.id === existingRoute.id) {
4614 return true;
4615 }
4616
4617 // Second is by pathing differences
4618 if (!(newRoute.index === existingRoute.index && newRoute.path === existingRoute.path && newRoute.caseSensitive === existingRoute.caseSensitive)) {
4619 return false;
4620 }
4621
4622 // Pathless layout routes are trickier since we need to check children.
4623 // If they have no children then they're the same as far as we can tell
4624 if ((!newRoute.children || newRoute.children.length === 0) && (!existingRoute.children || existingRoute.children.length === 0)) {
4625 return true;
4626 }
4627
4628 // Otherwise, we look to see if every child in the new route is already
4629 // represented in the existing route's children
4630 return newRoute.children.every((aChild, i) => {
4631 var _existingRoute$childr;
4632 return (_existingRoute$childr = existingRoute.children) == null ? void 0 : _existingRoute$childr.some(bChild => isSameRoute(aChild, bChild));
4633 });
4634}
4635
4636/**
4637 * Execute route.lazy() methods to lazily load route modules (loader, action,
4638 * shouldRevalidate) and update the routeManifest in place which shares objects
4639 * with dataRoutes so those get updated as well.
4640 */
4641async function loadLazyRouteModule(route, mapRouteProperties, manifest) {
4642 if (!route.lazy) {
4643 return;
4644 }
4645 let lazyRoute = await route.lazy();
4646
4647 // If the lazy route function was executed and removed by another parallel
4648 // call then we can return - first lazy() to finish wins because the return
4649 // value of lazy is expected to be static
4650 if (!route.lazy) {
4651 return;
4652 }
4653 let routeToUpdate = manifest[route.id];
4654 invariant(routeToUpdate, "No route found in manifest");
4655
4656 // Update the route in place. This should be safe because there's no way
4657 // we could yet be sitting on this route as we can't get there without
4658 // resolving lazy() first.
4659 //
4660 // This is different than the HMR "update" use-case where we may actively be
4661 // on the route being updated. The main concern boils down to "does this
4662 // mutation affect any ongoing navigations or any current state.matches
4663 // values?". If not, it should be safe to update in place.
4664 let routeUpdates = {};
4665 for (let lazyRouteProperty in lazyRoute) {
4666 let staticRouteValue = routeToUpdate[lazyRouteProperty];
4667 let isPropertyStaticallyDefined = staticRouteValue !== undefined &&
4668 // This property isn't static since it should always be updated based
4669 // on the route updates
4670 lazyRouteProperty !== "hasErrorBoundary";
4671 warning(!isPropertyStaticallyDefined, "Route \"" + routeToUpdate.id + "\" has a static property \"" + lazyRouteProperty + "\" " + "defined but its lazy function is also returning a value for this property. " + ("The lazy route property \"" + lazyRouteProperty + "\" will be ignored."));
4672 if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) {
4673 routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty];
4674 }
4675 }
4676
4677 // Mutate the route with the provided updates. Do this first so we pass
4678 // the updated version to mapRouteProperties
4679 Object.assign(routeToUpdate, routeUpdates);
4680
4681 // Mutate the `hasErrorBoundary` property on the route based on the route
4682 // updates and remove the `lazy` function so we don't resolve the lazy
4683 // route again.
4684 Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), {
4685 lazy: undefined
4686 }));
4687}
4688
4689// Default implementation of `dataStrategy` which fetches all loaders in parallel
4690async function defaultDataStrategy(_ref4) {
4691 let {
4692 matches
4693 } = _ref4;
4694 let matchesToLoad = matches.filter(m => m.shouldLoad);
4695 let results = await Promise.all(matchesToLoad.map(m => m.resolve()));
4696 return results.reduce((acc, result, i) => Object.assign(acc, {
4697 [matchesToLoad[i].route.id]: result
4698 }), {});
4699}
4700async function callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties, requestContext) {
4701 let loadRouteDefinitionsPromises = matches.map(m => m.route.lazy ? loadLazyRouteModule(m.route, mapRouteProperties, manifest) : undefined);
4702 let dsMatches = matches.map((match, i) => {
4703 let loadRoutePromise = loadRouteDefinitionsPromises[i];
4704 let shouldLoad = matchesToLoad.some(m => m.route.id === match.route.id);
4705 // `resolve` encapsulates route.lazy(), executing the loader/action,
4706 // and mapping return values/thrown errors to a `DataStrategyResult`. Users
4707 // can pass a callback to take fine-grained control over the execution
4708 // of the loader/action
4709 let resolve = async handlerOverride => {
4710 if (handlerOverride && request.method === "GET" && (match.route.lazy || match.route.loader)) {
4711 shouldLoad = true;
4712 }
4713 return shouldLoad ? callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, requestContext) : Promise.resolve({
4714 type: ResultType.data,
4715 result: undefined
4716 });
4717 };
4718 return _extends({}, match, {
4719 shouldLoad,
4720 resolve
4721 });
4722 });
4723
4724 // Send all matches here to allow for a middleware-type implementation.
4725 // handler will be a no-op for unneeded routes and we filter those results
4726 // back out below.
4727 let results = await dataStrategyImpl({
4728 matches: dsMatches,
4729 request,
4730 params: matches[0].params,
4731 fetcherKey,
4732 context: requestContext
4733 });
4734
4735 // Wait for all routes to load here but 'swallow the error since we want
4736 // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -
4737 // called from `match.resolve()`
4738 try {
4739 await Promise.all(loadRouteDefinitionsPromises);
4740 } catch (e) {
4741 // No-op
4742 }
4743 return results;
4744}
4745
4746// Default logic for calling a loader/action is the user has no specified a dataStrategy
4747async function callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, staticContext) {
4748 let result;
4749 let onReject;
4750 let runHandler = handler => {
4751 // Setup a promise we can race against so that abort signals short circuit
4752 let reject;
4753 // This will never resolve so safe to type it as Promise<DataStrategyResult> to
4754 // satisfy the function return value
4755 let abortPromise = new Promise((_, r) => reject = r);
4756 onReject = () => reject();
4757 request.signal.addEventListener("abort", onReject);
4758 let actualHandler = ctx => {
4759 if (typeof handler !== "function") {
4760 return Promise.reject(new Error("You cannot call the handler for a route which defines a boolean " + ("\"" + type + "\" [routeId: " + match.route.id + "]")));
4761 }
4762 return handler({
4763 request,
4764 params: match.params,
4765 context: staticContext
4766 }, ...(ctx !== undefined ? [ctx] : []));
4767 };
4768 let handlerPromise = (async () => {
4769 try {
4770 let val = await (handlerOverride ? handlerOverride(ctx => actualHandler(ctx)) : actualHandler());
4771 return {
4772 type: "data",
4773 result: val
4774 };
4775 } catch (e) {
4776 return {
4777 type: "error",
4778 result: e
4779 };
4780 }
4781 })();
4782 return Promise.race([handlerPromise, abortPromise]);
4783 };
4784 try {
4785 let handler = match.route[type];
4786
4787 // If we have a route.lazy promise, await that first
4788 if (loadRoutePromise) {
4789 if (handler) {
4790 // Run statically defined handler in parallel with lazy()
4791 let handlerError;
4792 let [value] = await Promise.all([
4793 // If the handler throws, don't let it immediately bubble out,
4794 // since we need to let the lazy() execution finish so we know if this
4795 // route has a boundary that can handle the error
4796 runHandler(handler).catch(e => {
4797 handlerError = e;
4798 }), loadRoutePromise]);
4799 if (handlerError !== undefined) {
4800 throw handlerError;
4801 }
4802 result = value;
4803 } else {
4804 // Load lazy route module, then run any returned handler
4805 await loadRoutePromise;
4806 handler = match.route[type];
4807 if (handler) {
4808 // Handler still runs even if we got interrupted to maintain consistency
4809 // with un-abortable behavior of handler execution on non-lazy or
4810 // previously-lazy-loaded routes
4811 result = await runHandler(handler);
4812 } else if (type === "action") {
4813 let url = new URL(request.url);
4814 let pathname = url.pathname + url.search;
4815 throw getInternalRouterError(405, {
4816 method: request.method,
4817 pathname,
4818 routeId: match.route.id
4819 });
4820 } else {
4821 // lazy() route has no loader to run. Short circuit here so we don't
4822 // hit the invariant below that errors on returning undefined.
4823 return {
4824 type: ResultType.data,
4825 result: undefined
4826 };
4827 }
4828 }
4829 } else if (!handler) {
4830 let url = new URL(request.url);
4831 let pathname = url.pathname + url.search;
4832 throw getInternalRouterError(404, {
4833 pathname
4834 });
4835 } else {
4836 result = await runHandler(handler);
4837 }
4838 invariant(result.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`.");
4839 } catch (e) {
4840 // We should already be catching and converting normal handler executions to
4841 // DataStrategyResults and returning them, so anything that throws here is an
4842 // unexpected error we still need to wrap
4843 return {
4844 type: ResultType.error,
4845 result: e
4846 };
4847 } finally {
4848 if (onReject) {
4849 request.signal.removeEventListener("abort", onReject);
4850 }
4851 }
4852 return result;
4853}
4854async function convertDataStrategyResultToDataResult(dataStrategyResult) {
4855 let {
4856 result,
4857 type
4858 } = dataStrategyResult;
4859 if (isResponse(result)) {
4860 let data;
4861 try {
4862 let contentType = result.headers.get("Content-Type");
4863 // Check between word boundaries instead of startsWith() due to the last
4864 // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type
4865 if (contentType && /\bapplication\/json\b/.test(contentType)) {
4866 if (result.body == null) {
4867 data = null;
4868 } else {
4869 data = await result.json();
4870 }
4871 } else {
4872 data = await result.text();
4873 }
4874 } catch (e) {
4875 return {
4876 type: ResultType.error,
4877 error: e
4878 };
4879 }
4880 if (type === ResultType.error) {
4881 return {
4882 type: ResultType.error,
4883 error: new ErrorResponseImpl(result.status, result.statusText, data),
4884 statusCode: result.status,
4885 headers: result.headers
4886 };
4887 }
4888 return {
4889 type: ResultType.data,
4890 data,
4891 statusCode: result.status,
4892 headers: result.headers
4893 };
4894 }
4895 if (type === ResultType.error) {
4896 if (isDataWithResponseInit(result)) {
4897 var _result$init3, _result$init4;
4898 if (result.data instanceof Error) {
4899 var _result$init, _result$init2;
4900 return {
4901 type: ResultType.error,
4902 error: result.data,
4903 statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status,
4904 headers: (_result$init2 = result.init) != null && _result$init2.headers ? new Headers(result.init.headers) : undefined
4905 };
4906 }
4907
4908 // Convert thrown data() to ErrorResponse instances
4909 return {
4910 type: ResultType.error,
4911 error: new ErrorResponseImpl(((_result$init3 = result.init) == null ? void 0 : _result$init3.status) || 500, undefined, result.data),
4912 statusCode: isRouteErrorResponse(result) ? result.status : undefined,
4913 headers: (_result$init4 = result.init) != null && _result$init4.headers ? new Headers(result.init.headers) : undefined
4914 };
4915 }
4916 return {
4917 type: ResultType.error,
4918 error: result,
4919 statusCode: isRouteErrorResponse(result) ? result.status : undefined
4920 };
4921 }
4922 if (isDeferredData(result)) {
4923 var _result$init5, _result$init6;
4924 return {
4925 type: ResultType.deferred,
4926 deferredData: result,
4927 statusCode: (_result$init5 = result.init) == null ? void 0 : _result$init5.status,
4928 headers: ((_result$init6 = result.init) == null ? void 0 : _result$init6.headers) && new Headers(result.init.headers)
4929 };
4930 }
4931 if (isDataWithResponseInit(result)) {
4932 var _result$init7, _result$init8;
4933 return {
4934 type: ResultType.data,
4935 data: result.data,
4936 statusCode: (_result$init7 = result.init) == null ? void 0 : _result$init7.status,
4937 headers: (_result$init8 = result.init) != null && _result$init8.headers ? new Headers(result.init.headers) : undefined
4938 };
4939 }
4940 return {
4941 type: ResultType.data,
4942 data: result
4943 };
4944}
4945
4946// Support relative routing in internal redirects
4947function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, v7_relativeSplatPath) {
4948 let location = response.headers.get("Location");
4949 invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header");
4950 if (!ABSOLUTE_URL_REGEX.test(location)) {
4951 let trimmedMatches = matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1);
4952 location = normalizeTo(new URL(request.url), trimmedMatches, basename, true, location, v7_relativeSplatPath);
4953 response.headers.set("Location", location);
4954 }
4955 return response;
4956}
4957function normalizeRedirectLocation(location, currentUrl, basename, historyInstance) {
4958 // Match Chrome's behavior:
4959 // https://github.com/chromium/chromium/blob/216dbeb61db0c667e62082e5f5400a32d6983df3/content/public/common/url_utils.cc#L82
4960 let invalidProtocols = ["about:", "blob:", "chrome:", "chrome-untrusted:", "content:", "data:", "devtools:", "file:", "filesystem:",
4961 // eslint-disable-next-line no-script-url
4962 "javascript:"];
4963 if (ABSOLUTE_URL_REGEX.test(location)) {
4964 // Strip off the protocol+origin for same-origin + same-basename absolute redirects
4965 let normalizedLocation = location;
4966 let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);
4967 if (invalidProtocols.includes(url.protocol)) {
4968 throw new Error("Invalid redirect location");
4969 }
4970 let isSameBasename = stripBasename(url.pathname, basename) != null;
4971 if (url.origin === currentUrl.origin && isSameBasename) {
4972 return url.pathname + url.search + url.hash;
4973 }
4974 }
4975 try {
4976 let url = historyInstance.createURL(location);
4977 if (invalidProtocols.includes(url.protocol)) {
4978 throw new Error("Invalid redirect location");
4979 }
4980 } catch (e) {}
4981 return location;
4982}
4983
4984// Utility method for creating the Request instances for loaders/actions during
4985// client-side navigations and fetches. During SSR we will always have a
4986// Request instance from the static handler (query/queryRoute)
4987function createClientSideRequest(history, location, signal, submission) {
4988 let url = history.createURL(stripHashFromPath(location)).toString();
4989 let init = {
4990 signal
4991 };
4992 if (submission && isMutationMethod(submission.formMethod)) {
4993 let {
4994 formMethod,
4995 formEncType
4996 } = submission;
4997 // Didn't think we needed this but it turns out unlike other methods, patch
4998 // won't be properly normalized to uppercase and results in a 405 error.
4999 // See: https://fetch.spec.whatwg.org/#concept-method
5000 init.method = formMethod.toUpperCase();
5001 if (formEncType === "application/json") {
5002 init.headers = new Headers({
5003 "Content-Type": formEncType
5004 });
5005 init.body = JSON.stringify(submission.json);
5006 } else if (formEncType === "text/plain") {
5007 // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
5008 init.body = submission.text;
5009 } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) {
5010 // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
5011 init.body = convertFormDataToSearchParams(submission.formData);
5012 } else {
5013 // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
5014 init.body = submission.formData;
5015 }
5016 }
5017 return new Request(url, init);
5018}
5019function convertFormDataToSearchParams(formData) {
5020 let searchParams = new URLSearchParams();
5021 for (let [key, value] of formData.entries()) {
5022 // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs
5023 searchParams.append(key, typeof value === "string" ? value : value.name);
5024 }
5025 return searchParams;
5026}
5027function convertSearchParamsToFormData(searchParams) {
5028 let formData = new FormData();
5029 for (let [key, value] of searchParams.entries()) {
5030 formData.append(key, value);
5031 }
5032 return formData;
5033}
5034function processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling) {
5035 // Fill in loaderData/errors from our loaders
5036 let loaderData = {};
5037 let errors = null;
5038 let statusCode;
5039 let foundError = false;
5040 let loaderHeaders = {};
5041 let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : undefined;
5042
5043 // Process loader results into state.loaderData/state.errors
5044 matches.forEach(match => {
5045 if (!(match.route.id in results)) {
5046 return;
5047 }
5048 let id = match.route.id;
5049 let result = results[id];
5050 invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData");
5051 if (isErrorResult(result)) {
5052 let error = result.error;
5053 // If we have a pending action error, we report it at the highest-route
5054 // that throws a loader error, and then clear it out to indicate that
5055 // it was consumed
5056 if (pendingError !== undefined) {
5057 error = pendingError;
5058 pendingError = undefined;
5059 }
5060 errors = errors || {};
5061 if (skipLoaderErrorBubbling) {
5062 errors[id] = error;
5063 } else {
5064 // Look upwards from the matched route for the closest ancestor error
5065 // boundary, defaulting to the root match. Prefer higher error values
5066 // if lower errors bubble to the same boundary
5067 let boundaryMatch = findNearestBoundary(matches, id);
5068 if (errors[boundaryMatch.route.id] == null) {
5069 errors[boundaryMatch.route.id] = error;
5070 }
5071 }
5072
5073 // Clear our any prior loaderData for the throwing route
5074 loaderData[id] = undefined;
5075
5076 // Once we find our first (highest) error, we set the status code and
5077 // prevent deeper status codes from overriding
5078 if (!foundError) {
5079 foundError = true;
5080 statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
5081 }
5082 if (result.headers) {
5083 loaderHeaders[id] = result.headers;
5084 }
5085 } else {
5086 if (isDeferredResult(result)) {
5087 activeDeferreds.set(id, result.deferredData);
5088 loaderData[id] = result.deferredData.data;
5089 // Error status codes always override success status codes, but if all
5090 // loaders are successful we take the deepest status code.
5091 if (result.statusCode != null && result.statusCode !== 200 && !foundError) {
5092 statusCode = result.statusCode;
5093 }
5094 if (result.headers) {
5095 loaderHeaders[id] = result.headers;
5096 }
5097 } else {
5098 loaderData[id] = result.data;
5099 // Error status codes always override success status codes, but if all
5100 // loaders are successful we take the deepest status code.
5101 if (result.statusCode && result.statusCode !== 200 && !foundError) {
5102 statusCode = result.statusCode;
5103 }
5104 if (result.headers) {
5105 loaderHeaders[id] = result.headers;
5106 }
5107 }
5108 }
5109 });
5110
5111 // If we didn't consume the pending action error (i.e., all loaders
5112 // resolved), then consume it here. Also clear out any loaderData for the
5113 // throwing route
5114 if (pendingError !== undefined && pendingActionResult) {
5115 errors = {
5116 [pendingActionResult[0]]: pendingError
5117 };
5118 loaderData[pendingActionResult[0]] = undefined;
5119 }
5120 return {
5121 loaderData,
5122 errors,
5123 statusCode: statusCode || 200,
5124 loaderHeaders
5125 };
5126}
5127function processLoaderData(state, matches, results, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds) {
5128 let {
5129 loaderData,
5130 errors
5131 } = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, false // This method is only called client side so we always want to bubble
5132 );
5133
5134 // Process results from our revalidating fetchers
5135 revalidatingFetchers.forEach(rf => {
5136 let {
5137 key,
5138 match,
5139 controller
5140 } = rf;
5141 let result = fetcherResults[key];
5142 invariant(result, "Did not find corresponding fetcher result");
5143
5144 // Process fetcher non-redirect errors
5145 if (controller && controller.signal.aborted) {
5146 // Nothing to do for aborted fetchers
5147 return;
5148 } else if (isErrorResult(result)) {
5149 let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id);
5150 if (!(errors && errors[boundaryMatch.route.id])) {
5151 errors = _extends({}, errors, {
5152 [boundaryMatch.route.id]: result.error
5153 });
5154 }
5155 state.fetchers.delete(key);
5156 } else if (isRedirectResult(result)) {
5157 // Should never get here, redirects should get processed above, but we
5158 // keep this to type narrow to a success result in the else
5159 invariant(false, "Unhandled fetcher revalidation redirect");
5160 } else if (isDeferredResult(result)) {
5161 // Should never get here, deferred data should be awaited for fetchers
5162 // in resolveDeferredResults
5163 invariant(false, "Unhandled fetcher deferred data");
5164 } else {
5165 let doneFetcher = getDoneFetcher(result.data);
5166 state.fetchers.set(key, doneFetcher);
5167 }
5168 });
5169 return {
5170 loaderData,
5171 errors
5172 };
5173}
5174function mergeLoaderData(loaderData, newLoaderData, matches, errors) {
5175 let mergedLoaderData = _extends({}, newLoaderData);
5176 for (let match of matches) {
5177 let id = match.route.id;
5178 if (newLoaderData.hasOwnProperty(id)) {
5179 if (newLoaderData[id] !== undefined) {
5180 mergedLoaderData[id] = newLoaderData[id];
5181 }
5182 } else if (loaderData[id] !== undefined && match.route.loader) {
5183 // Preserve existing keys not included in newLoaderData and where a loader
5184 // wasn't removed by HMR
5185 mergedLoaderData[id] = loaderData[id];
5186 }
5187 if (errors && errors.hasOwnProperty(id)) {
5188 // Don't keep any loader data below the boundary
5189 break;
5190 }
5191 }
5192 return mergedLoaderData;
5193}
5194function getActionDataForCommit(pendingActionResult) {
5195 if (!pendingActionResult) {
5196 return {};
5197 }
5198 return isErrorResult(pendingActionResult[1]) ? {
5199 // Clear out prior actionData on errors
5200 actionData: {}
5201 } : {
5202 actionData: {
5203 [pendingActionResult[0]]: pendingActionResult[1].data
5204 }
5205 };
5206}
5207
5208// Find the nearest error boundary, looking upwards from the leaf route (or the
5209// route specified by routeId) for the closest ancestor error boundary,
5210// defaulting to the root match
5211function findNearestBoundary(matches, routeId) {
5212 let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches];
5213 return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0];
5214}
5215function getShortCircuitMatches(routes) {
5216 // Prefer a root layout route if present, otherwise shim in a route object
5217 let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === "/") || {
5218 id: "__shim-error-route__"
5219 };
5220 return {
5221 matches: [{
5222 params: {},
5223 pathname: "",
5224 pathnameBase: "",
5225 route
5226 }],
5227 route
5228 };
5229}
5230function getInternalRouterError(status, _temp5) {
5231 let {
5232 pathname,
5233 routeId,
5234 method,
5235 type,
5236 message
5237 } = _temp5 === void 0 ? {} : _temp5;
5238 let statusText = "Unknown Server Error";
5239 let errorMessage = "Unknown @remix-run/router error";
5240 if (status === 400) {
5241 statusText = "Bad Request";
5242 if (method && pathname && routeId) {
5243 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.";
5244 } else if (type === "defer-action") {
5245 errorMessage = "defer() is not supported in actions";
5246 } else if (type === "invalid-body") {
5247 errorMessage = "Unable to encode submission body";
5248 }
5249 } else if (status === 403) {
5250 statusText = "Forbidden";
5251 errorMessage = "Route \"" + routeId + "\" does not match URL \"" + pathname + "\"";
5252 } else if (status === 404) {
5253 statusText = "Not Found";
5254 errorMessage = "No route matches URL \"" + pathname + "\"";
5255 } else if (status === 405) {
5256 statusText = "Method Not Allowed";
5257 if (method && pathname && routeId) {
5258 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.";
5259 } else if (method) {
5260 errorMessage = "Invalid request method \"" + method.toUpperCase() + "\"";
5261 }
5262 }
5263 return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true);
5264}
5265
5266// Find any returned redirect errors, starting from the lowest match
5267function findRedirect(results) {
5268 let entries = Object.entries(results);
5269 for (let i = entries.length - 1; i >= 0; i--) {
5270 let [key, result] = entries[i];
5271 if (isRedirectResult(result)) {
5272 return {
5273 key,
5274 result
5275 };
5276 }
5277 }
5278}
5279function stripHashFromPath(path) {
5280 let parsedPath = typeof path === "string" ? parsePath(path) : path;
5281 return createPath(_extends({}, parsedPath, {
5282 hash: ""
5283 }));
5284}
5285function isHashChangeOnly(a, b) {
5286 if (a.pathname !== b.pathname || a.search !== b.search) {
5287 return false;
5288 }
5289 if (a.hash === "") {
5290 // /page -> /page#hash
5291 return b.hash !== "";
5292 } else if (a.hash === b.hash) {
5293 // /page#hash -> /page#hash
5294 return true;
5295 } else if (b.hash !== "") {
5296 // /page#hash -> /page#other
5297 return true;
5298 }
5299
5300 // If the hash is removed the browser will re-perform a request to the server
5301 // /page#hash -> /page
5302 return false;
5303}
5304function isDataStrategyResult(result) {
5305 return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === ResultType.data || result.type === ResultType.error);
5306}
5307function isRedirectDataStrategyResultResult(result) {
5308 return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
5309}
5310function isDeferredResult(result) {
5311 return result.type === ResultType.deferred;
5312}
5313function isErrorResult(result) {
5314 return result.type === ResultType.error;
5315}
5316function isRedirectResult(result) {
5317 return (result && result.type) === ResultType.redirect;
5318}
5319function isDataWithResponseInit(value) {
5320 return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
5321}
5322function isDeferredData(value) {
5323 let deferred = value;
5324 return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function";
5325}
5326function isResponse(value) {
5327 return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
5328}
5329function isRedirectResponse(result) {
5330 if (!isResponse(result)) {
5331 return false;
5332 }
5333 let status = result.status;
5334 let location = result.headers.get("Location");
5335 return status >= 300 && status <= 399 && location != null;
5336}
5337function isValidMethod(method) {
5338 return validRequestMethods.has(method.toLowerCase());
5339}
5340function isMutationMethod(method) {
5341 return validMutationMethods.has(method.toLowerCase());
5342}
5343async function resolveNavigationDeferredResults(matches, results, signal, currentMatches, currentLoaderData) {
5344 let entries = Object.entries(results);
5345 for (let index = 0; index < entries.length; index++) {
5346 let [routeId, result] = entries[index];
5347 let match = matches.find(m => (m == null ? void 0 : m.route.id) === routeId);
5348 // If we don't have a match, then we can have a deferred result to do
5349 // anything with. This is for revalidating fetchers where the route was
5350 // removed during HMR
5351 if (!match) {
5352 continue;
5353 }
5354 let currentMatch = currentMatches.find(m => m.route.id === match.route.id);
5355 let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;
5356 if (isDeferredResult(result) && isRevalidatingLoader) {
5357 // Note: we do not have to touch activeDeferreds here since we race them
5358 // against the signal in resolveDeferredData and they'll get aborted
5359 // there if needed
5360 await resolveDeferredData(result, signal, false).then(result => {
5361 if (result) {
5362 results[routeId] = result;
5363 }
5364 });
5365 }
5366 }
5367}
5368async function resolveFetcherDeferredResults(matches, results, revalidatingFetchers) {
5369 for (let index = 0; index < revalidatingFetchers.length; index++) {
5370 let {
5371 key,
5372 routeId,
5373 controller
5374 } = revalidatingFetchers[index];
5375 let result = results[key];
5376 let match = matches.find(m => (m == null ? void 0 : m.route.id) === routeId);
5377 // If we don't have a match, then we can have a deferred result to do
5378 // anything with. This is for revalidating fetchers where the route was
5379 // removed during HMR
5380 if (!match) {
5381 continue;
5382 }
5383 if (isDeferredResult(result)) {
5384 // Note: we do not have to touch activeDeferreds here since we race them
5385 // against the signal in resolveDeferredData and they'll get aborted
5386 // there if needed
5387 invariant(controller, "Expected an AbortController for revalidating fetcher deferred result");
5388 await resolveDeferredData(result, controller.signal, true).then(result => {
5389 if (result) {
5390 results[key] = result;
5391 }
5392 });
5393 }
5394 }
5395}
5396async function resolveDeferredData(result, signal, unwrap) {
5397 if (unwrap === void 0) {
5398 unwrap = false;
5399 }
5400 let aborted = await result.deferredData.resolveData(signal);
5401 if (aborted) {
5402 return;
5403 }
5404 if (unwrap) {
5405 try {
5406 return {
5407 type: ResultType.data,
5408 data: result.deferredData.unwrappedData
5409 };
5410 } catch (e) {
5411 // Handle any TrackedPromise._error values encountered while unwrapping
5412 return {
5413 type: ResultType.error,
5414 error: e
5415 };
5416 }
5417 }
5418 return {
5419 type: ResultType.data,
5420 data: result.deferredData.data
5421 };
5422}
5423function hasNakedIndexQuery(search) {
5424 return new URLSearchParams(search).getAll("index").some(v => v === "");
5425}
5426function getTargetMatch(matches, location) {
5427 let search = typeof location === "string" ? parsePath(location).search : location.search;
5428 if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
5429 // Return the leaf index route when index is present
5430 return matches[matches.length - 1];
5431 }
5432 // Otherwise grab the deepest "path contributing" match (ignoring index and
5433 // pathless layout routes)
5434 let pathMatches = getPathContributingMatches(matches);
5435 return pathMatches[pathMatches.length - 1];
5436}
5437function getSubmissionFromNavigation(navigation) {
5438 let {
5439 formMethod,
5440 formAction,
5441 formEncType,
5442 text,
5443 formData,
5444 json
5445 } = navigation;
5446 if (!formMethod || !formAction || !formEncType) {
5447 return;
5448 }
5449 if (text != null) {
5450 return {
5451 formMethod,
5452 formAction,
5453 formEncType,
5454 formData: undefined,
5455 json: undefined,
5456 text
5457 };
5458 } else if (formData != null) {
5459 return {
5460 formMethod,
5461 formAction,
5462 formEncType,
5463 formData,
5464 json: undefined,
5465 text: undefined
5466 };
5467 } else if (json !== undefined) {
5468 return {
5469 formMethod,
5470 formAction,
5471 formEncType,
5472 formData: undefined,
5473 json,
5474 text: undefined
5475 };
5476 }
5477}
5478function getLoadingNavigation(location, submission) {
5479 if (submission) {
5480 let navigation = {
5481 state: "loading",
5482 location,
5483 formMethod: submission.formMethod,
5484 formAction: submission.formAction,
5485 formEncType: submission.formEncType,
5486 formData: submission.formData,
5487 json: submission.json,
5488 text: submission.text
5489 };
5490 return navigation;
5491 } else {
5492 let navigation = {
5493 state: "loading",
5494 location,
5495 formMethod: undefined,
5496 formAction: undefined,
5497 formEncType: undefined,
5498 formData: undefined,
5499 json: undefined,
5500 text: undefined
5501 };
5502 return navigation;
5503 }
5504}
5505function getSubmittingNavigation(location, submission) {
5506 let navigation = {
5507 state: "submitting",
5508 location,
5509 formMethod: submission.formMethod,
5510 formAction: submission.formAction,
5511 formEncType: submission.formEncType,
5512 formData: submission.formData,
5513 json: submission.json,
5514 text: submission.text
5515 };
5516 return navigation;
5517}
5518function getLoadingFetcher(submission, data) {
5519 if (submission) {
5520 let fetcher = {
5521 state: "loading",
5522 formMethod: submission.formMethod,
5523 formAction: submission.formAction,
5524 formEncType: submission.formEncType,
5525 formData: submission.formData,
5526 json: submission.json,
5527 text: submission.text,
5528 data
5529 };
5530 return fetcher;
5531 } else {
5532 let fetcher = {
5533 state: "loading",
5534 formMethod: undefined,
5535 formAction: undefined,
5536 formEncType: undefined,
5537 formData: undefined,
5538 json: undefined,
5539 text: undefined,
5540 data
5541 };
5542 return fetcher;
5543 }
5544}
5545function getSubmittingFetcher(submission, existingFetcher) {
5546 let fetcher = {
5547 state: "submitting",
5548 formMethod: submission.formMethod,
5549 formAction: submission.formAction,
5550 formEncType: submission.formEncType,
5551 formData: submission.formData,
5552 json: submission.json,
5553 text: submission.text,
5554 data: existingFetcher ? existingFetcher.data : undefined
5555 };
5556 return fetcher;
5557}
5558function getDoneFetcher(data) {
5559 let fetcher = {
5560 state: "idle",
5561 formMethod: undefined,
5562 formAction: undefined,
5563 formEncType: undefined,
5564 formData: undefined,
5565 json: undefined,
5566 text: undefined,
5567 data
5568 };
5569 return fetcher;
5570}
5571function restoreAppliedTransitions(_window, transitions) {
5572 try {
5573 let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY);
5574 if (sessionPositions) {
5575 let json = JSON.parse(sessionPositions);
5576 for (let [k, v] of Object.entries(json || {})) {
5577 if (v && Array.isArray(v)) {
5578 transitions.set(k, new Set(v || []));
5579 }
5580 }
5581 }
5582 } catch (e) {
5583 // no-op, use default empty object
5584 }
5585}
5586function persistAppliedTransitions(_window, transitions) {
5587 if (transitions.size > 0) {
5588 let json = {};
5589 for (let [k, v] of transitions) {
5590 json[k] = [...v];
5591 }
5592 try {
5593 _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json));
5594 } catch (error) {
5595 warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ").");
5596 }
5597 }
5598}
5599//#endregion
5600
5601exports.AbortedDeferredError = AbortedDeferredError;
5602exports.Action = Action;
5603exports.IDLE_BLOCKER = IDLE_BLOCKER;
5604exports.IDLE_FETCHER = IDLE_FETCHER;
5605exports.IDLE_NAVIGATION = IDLE_NAVIGATION;
5606exports.UNSAFE_DEFERRED_SYMBOL = UNSAFE_DEFERRED_SYMBOL;
5607exports.UNSAFE_DeferredData = DeferredData;
5608exports.UNSAFE_ErrorResponseImpl = ErrorResponseImpl;
5609exports.UNSAFE_convertRouteMatchToUiMatch = convertRouteMatchToUiMatch;
5610exports.UNSAFE_convertRoutesToDataRoutes = convertRoutesToDataRoutes;
5611exports.UNSAFE_decodePath = decodePath;
5612exports.UNSAFE_getResolveToMatches = getResolveToMatches;
5613exports.UNSAFE_invariant = invariant;
5614exports.UNSAFE_warning = warning;
5615exports.createBrowserHistory = createBrowserHistory;
5616exports.createHashHistory = createHashHistory;
5617exports.createMemoryHistory = createMemoryHistory;
5618exports.createPath = createPath;
5619exports.createRouter = createRouter;
5620exports.createStaticHandler = createStaticHandler;
5621exports.data = data;
5622exports.defer = defer;
5623exports.generatePath = generatePath;
5624exports.getStaticContextFromError = getStaticContextFromError;
5625exports.getToPathname = getToPathname;
5626exports.isDataWithResponseInit = isDataWithResponseInit;
5627exports.isDeferredData = isDeferredData;
5628exports.isRouteErrorResponse = isRouteErrorResponse;
5629exports.joinPaths = joinPaths;
5630exports.json = json;
5631exports.matchPath = matchPath;
5632exports.matchRoutes = matchRoutes;
5633exports.normalizePathname = normalizePathname;
5634exports.parsePath = parsePath;
5635exports.redirect = redirect;
5636exports.redirectDocument = redirectDocument;
5637exports.replace = replace;
5638exports.resolvePath = resolvePath;
5639exports.resolveTo = resolveTo;
5640exports.stripBasename = stripBasename;
5641//# sourceMappingURL=router.cjs.js.map
Note: See TracBrowser for help on using the repository browser.