UNPKG

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