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

main
Last change on this file since d565449 was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

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