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

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

Fix frontend appearance

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