INDIE UNPKG

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