UNPKG

137 kBJavaScriptView Raw
1/**
2 * react-router v8.5.3
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 */
11import { AsyncLocalStorage } from "node:async_hooks";
12import * as React from "react";
13import { parse, serialize, splitSetCookieString } from "cookie-es";
14import { BrowserRouter, Form, HashRouter, Link, Links, MemoryRouter, Meta, NavLink, Navigate, Outlet, Outlet as Outlet$1, Route, Router, RouterProvider, Routes, ScrollRestoration, StaticRouter, StaticRouterProvider, UNSAFE_AwaitContextProvider, UNSAFE_WithComponentProps, UNSAFE_WithErrorBoundaryProps, UNSAFE_WithHydrateFallbackProps, unstable_HistoryRouter } from "react-router/internal/react-server-client";
15//#region lib/router/url.ts
16const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i;
17//#endregion
18//#region lib/router/history.ts
19function invariant$1(value, message) {
20 if (value === false || value === null || typeof value === "undefined") throw new Error(message);
21}
22function warning(cond, message) {
23 if (!cond) {
24 if (typeof console !== "undefined") console.warn(message);
25 try {
26 throw new Error(message);
27 } catch {}
28 }
29}
30function createKey$1() {
31 return Math.random().toString(36).substring(2, 10);
32}
33/**
34* Creates a Location object with a unique key from the given Path
35*/
36function createLocation(current, to, state = null, key, mask) {
37 return {
38 pathname: typeof current === "string" ? current : current.pathname,
39 search: "",
40 hash: "",
41 ...typeof to === "string" ? parsePath(to) : to,
42 state,
43 key: to && to.key || key || createKey$1(),
44 mask
45 };
46}
47/**
48* Creates a string URL path from the given pathname, search, and hash components.
49*
50* @public
51* @category Utils
52* @param path The pathname, search, and hash components to combine.
53* @returns The combined URL path.
54*/
55function createPath({ pathname = "/", search = "", hash = "" }) {
56 if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search;
57 if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
58 return pathname;
59}
60/**
61* Parses a string URL path into its separate pathname, search, and hash components.
62*
63* @public
64* @category Utils
65* @param path The URL path to parse.
66* @returns The parsed pathname, search, and hash components.
67*/
68function parsePath(path) {
69 let parsedPath = {};
70 if (path) {
71 let hashIndex = path.indexOf("#");
72 if (hashIndex >= 0) {
73 parsedPath.hash = path.substring(hashIndex);
74 path = path.substring(0, hashIndex);
75 }
76 let searchIndex = path.indexOf("?");
77 if (searchIndex >= 0) {
78 parsedPath.search = path.substring(searchIndex);
79 path = path.substring(0, searchIndex);
80 }
81 if (path) parsedPath.pathname = path;
82 }
83 return parsedPath;
84}
85//#endregion
86//#region lib/router/navigation.ts
87const DEFAULT_NAVIGATION_URL = new URL("http://localhost");
88function isSameOrigin(a, b) {
89 return a.origin === b.origin && (a.origin !== "null" || a.protocol === b.protocol && a.host === b.host);
90}
91function isExplicitUrl(destination, target) {
92 if (destination.startsWith("//")) return true;
93 let protocol = target.protocol.toLowerCase();
94 if (!destination.toLowerCase().startsWith(protocol)) return false;
95 return target.host === "" || destination.slice(protocol.length).startsWith("//");
96}
97function validateDocumentNavigationTarget(destination) {
98 let normalized = destination.replace(/[\t\n\r]/g, "");
99 let start = 0;
100 while (normalized.charCodeAt(start) <= 32) start++;
101 normalized = normalized.slice(start);
102 if (!ABSOLUTE_URL_REGEX.test(normalized)) return;
103 let target;
104 try {
105 target = new URL(destination, DEFAULT_NAVIGATION_URL);
106 } catch {
107 return;
108 }
109 if (!isExplicitUrl(destination, target)) throw new Error("External navigation is not allowed");
110}
111function validateNavigationTarget(original, resolved, currentUrl, externalPolicy) {
112 let originalUrl = null;
113 try {
114 originalUrl = original == null ? null : new URL(original, currentUrl);
115 } catch {}
116 let resolvedUrl = new URL(resolved, currentUrl);
117 let originalIsExternal = originalUrl != null && !isSameOrigin(originalUrl, currentUrl);
118 let resolvedIsExternal = !isSameOrigin(resolvedUrl, currentUrl);
119 if (externalPolicy === "reject") {
120 if (originalIsExternal || resolvedIsExternal) throw new Error("External navigation is not allowed");
121 } else if (resolvedIsExternal) {
122 if (originalUrl == null || !isExplicitUrl(original, originalUrl) || !isSameOrigin(originalUrl, resolvedUrl)) throw new Error("External navigation is not allowed");
123 }
124}
125//#endregion
126//#region lib/router/utils.ts
127/**
128* Creates a type-safe {@link RouterContext} object that can be used to
129* store and retrieve arbitrary values in [`action`](../../start/framework/route-module#action)s,
130* [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
131* Similar to React's [`createContext`](https://react.dev/reference/react/createContext),
132* but specifically designed for React Router's request/response lifecycle.
133*
134* If a `defaultValue` is provided, it will be returned from `context.get()`
135* when no value has been set for the context. Otherwise, reading this context
136* when no value has been set will throw an error.
137*
138* ```tsx filename=app/context.ts
139* import { createContext } from "react-router";
140*
141* // Create a context for user data
142* export const userContext =
143* createContext<User | null>(null);
144* ```
145*
146* ```tsx filename=app/middleware/auth.ts
147* import { getUserFromSession } from "~/auth.server";
148* import { userContext } from "~/context";
149*
150* export const authMiddleware = async ({
151* context,
152* request,
153* }) => {
154* const user = await getUserFromSession(request);
155* context.set(userContext, user);
156* };
157* ```
158*
159* ```tsx filename=app/routes/profile.tsx
160* import { userContext } from "~/context";
161*
162* export async function loader({
163* context,
164* }: Route.LoaderArgs) {
165* const user = context.get(userContext);
166*
167* if (!user) {
168* throw new Response("Unauthorized", { status: 401 });
169* }
170*
171* return { user };
172* }
173* ```
174*
175* @public
176* @category Utils
177* @mode framework
178* @mode data
179* @param defaultValue An optional default value for the context. This value
180* will be returned if no value has been set for this context.
181* @returns A {@link RouterContext} object that can be used with
182* `context.get()` and `context.set()` in [`action`](../../start/framework/route-module#action)s,
183* [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
184*/
185function createContext(defaultValue) {
186 return { defaultValue };
187}
188/**
189* Provides methods for writing/reading values in application context in a
190* type-safe way. Primarily for usage with [middleware](../../how-to/middleware).
191*
192* @example
193* import {
194* createContext,
195* RouterContextProvider
196* } from "react-router";
197*
198* const userContext = createContext<User | null>(null);
199* const contextProvider = new RouterContextProvider();
200* contextProvider.set(userContext, getUser());
201* // ^ Type-safe
202* const user = contextProvider.get(userContext);
203* // ^ User
204*
205* @public
206* @category Utils
207* @mode framework
208* @mode data
209*/
210var RouterContextProvider = class {
211 #map = /* @__PURE__ */ new Map();
212 /**
213 * Create a new `RouterContextProvider` instance
214 * @param init An optional initial context map to populate the provider with
215 */
216 constructor(init) {
217 if (init) for (let [context, value] of init) this.set(context, value);
218 }
219 /**
220 * Access a value from the context. If no value has been set for the context,
221 * it will return the context's `defaultValue` if provided, or throw an error
222 * if no `defaultValue` was set.
223 * @param context The context to get the value for
224 * @returns The value for the context, or the context's `defaultValue` if no
225 * value was set
226 */
227 get(context) {
228 if (this.#map.has(context)) return this.#map.get(context);
229 if (context.defaultValue !== void 0) return context.defaultValue;
230 throw new Error("No value found for context");
231 }
232 /**
233 * Set a value for the context. If the context already has a value set, this
234 * will overwrite it.
235 *
236 * @param context The context to set the value for
237 * @param value The value to set for the context
238 * @returns {void}
239 */
240 set(context, value) {
241 this.#map.set(context, value);
242 }
243};
244const unsupportedLazyRouteObjectKeys = new Set([
245 "lazy",
246 "caseSensitive",
247 "path",
248 "id",
249 "index",
250 "children",
251 "unstable_validateParams"
252]);
253function isUnsupportedLazyRouteObjectKey(key) {
254 return unsupportedLazyRouteObjectKeys.has(key);
255}
256const unsupportedLazyRouteFunctionKeys = new Set([
257 "lazy",
258 "caseSensitive",
259 "path",
260 "id",
261 "index",
262 "middleware",
263 "children",
264 "unstable_validateParams"
265]);
266function isUnsupportedLazyRouteFunctionKey(key) {
267 return unsupportedLazyRouteFunctionKeys.has(key);
268}
269function isIndexRoute(route) {
270 return route.index === true;
271}
272function defaultMapRouteProperties(route) {
273 let updates = {};
274 if (route.Component) {
275 if (route.element) warning(false, "You should not include both `Component` and `element` on your route - `Component` will be used.");
276 Object.assign(updates, {
277 element: React.createElement(route.Component),
278 Component: void 0
279 });
280 }
281 if (route.HydrateFallback) {
282 if (route.hydrateFallbackElement) warning(false, "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - `HydrateFallback` will be used.");
283 Object.assign(updates, {
284 hydrateFallbackElement: React.createElement(route.HydrateFallback),
285 HydrateFallback: void 0
286 });
287 }
288 if (route.ErrorBoundary) {
289 if (route.errorElement) warning(false, "You should not include both `ErrorBoundary` and `errorElement` on your route - `ErrorBoundary` will be used.");
290 Object.assign(updates, {
291 errorElement: React.createElement(route.ErrorBoundary),
292 ErrorBoundary: void 0
293 });
294 }
295 return updates;
296}
297function convertRoutesToDataRoutes(routes, mapRouteProperties = defaultMapRouteProperties, parentPath = [], manifest = {}, allowInPlaceMutations = false) {
298 return routes.map((route, index) => {
299 let treePath = [...parentPath, String(index)];
300 let id = typeof route.id === "string" ? route.id : treePath.join("-");
301 invariant$1(route.index !== true || !route.children, `Cannot specify children on an index route`);
302 invariant$1(allowInPlaceMutations || !manifest[id], `Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages`);
303 if (isIndexRoute(route)) {
304 let indexRoute = {
305 ...route,
306 id
307 };
308 manifest[id] = mergeRouteUpdates(indexRoute, mapRouteProperties(indexRoute));
309 return indexRoute;
310 } else {
311 let pathOrLayoutRoute = {
312 ...route,
313 id,
314 children: void 0
315 };
316 manifest[id] = mergeRouteUpdates(pathOrLayoutRoute, mapRouteProperties(pathOrLayoutRoute));
317 if (route.children) pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest, allowInPlaceMutations);
318 return pathOrLayoutRoute;
319 }
320 });
321}
322function mergeRouteUpdates(route, updates) {
323 return Object.assign(route, {
324 ...updates,
325 ...typeof updates.lazy === "object" && updates.lazy != null ? { lazy: {
326 ...route.lazy,
327 ...updates.lazy
328 } } : {}
329 });
330}
331/**
332* Matches the given routes to a location and returns the match data.
333*
334* @example
335* import { matchRoutes } from "react-router";
336*
337* let routes = [{
338* path: "/",
339* Component: Root,
340* children: [{
341* path: "dashboard",
342* Component: Dashboard,
343* }]
344* }];
345*
346* matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
347*
348* @public
349* @category Utils
350* @param routes The array of route objects to match against.
351* @param locationArg The location to match against, either a string path or a
352* partial {@link Location} object
353* @param basename Optional base path to strip from the location before matching.
354* Defaults to `/`.
355* @returns An array of matched routes, or `null` if no matches were found.
356*/
357function matchRoutes(routes, locationArg, basename = "/") {
358 return matchRoutesImpl(routes, locationArg, basename, false);
359}
360function matchRoutesImpl(routes, locationArg, basename, allowPartial, precomputedBranches) {
361 let pathname = stripBasename((typeof locationArg === "string" ? parsePath(locationArg) : locationArg).pathname || "/", basename);
362 if (pathname == null) return null;
363 let branches = precomputedBranches ?? flattenAndRankRoutes(routes);
364 let matches = null;
365 let decoded = decodePath(pathname);
366 for (let i = 0; matches == null && i < branches.length; ++i) matches = matchRouteBranch(branches[i], decoded, allowPartial);
367 return matches;
368}
369function convertRouteMatchToUiMatch(match, loaderData) {
370 let { route, pathname, params } = match;
371 return {
372 id: route.id,
373 pathname,
374 params,
375 loaderData: loaderData[route.id],
376 handle: route.handle
377 };
378}
379function flattenAndRankRoutes(routes) {
380 let branches = flattenRoutes(routes);
381 rankRouteBranches(branches);
382 return branches;
383}
384function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "", _hasParentOptionalSegments = false) {
385 let flattenRoute = (route, index, hasParentOptionalSegments = _hasParentOptionalSegments, relativePath) => {
386 let meta = {
387 relativePath: relativePath === void 0 ? route.path || "" : relativePath,
388 caseSensitive: route.caseSensitive === true,
389 childrenIndex: index,
390 route
391 };
392 if (meta.relativePath.startsWith("/")) {
393 if (!meta.relativePath.startsWith(parentPath) && hasParentOptionalSegments) return;
394 invariant$1(meta.relativePath.startsWith(parentPath), `Absolute route path "${meta.relativePath}" nested under path "${parentPath}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`);
395 meta.relativePath = meta.relativePath.slice(parentPath.length);
396 }
397 let path = joinPaths([parentPath, meta.relativePath]);
398 let routesMeta = parentsMeta.concat(meta);
399 if (route.children && route.children.length > 0) {
400 invariant$1(route.index !== true, `Index routes must not have child routes. Please remove all child routes from route path "${path}".`);
401 flattenRoutes(route.children, branches, routesMeta, path, hasParentOptionalSegments);
402 }
403 if (route.path == null && !route.index) return;
404 branches.push({
405 path,
406 score: computeScore(path, route.index),
407 routesMeta: routesMeta.map((meta, i) => {
408 let [matcher, params] = compilePath(meta.relativePath, meta.caseSensitive, i === routesMeta.length - 1);
409 return {
410 ...meta,
411 matcher,
412 compiledParams: params
413 };
414 })
415 });
416 };
417 routes.forEach((route, index) => {
418 if (route.path === "" || !route.path?.includes("?")) flattenRoute(route, index);
419 else for (let exploded of explodeOptionalSegments(route.path)) flattenRoute(route, index, true, exploded);
420 });
421 return branches;
422}
423function explodeOptionalSegments(path) {
424 let segments = path.split("/");
425 if (segments.length === 0) return [];
426 let [first, ...rest] = segments;
427 let isOptional = first.endsWith("?");
428 let required = first.replace(/\?$/, "");
429 if (rest.length === 0) return isOptional ? [required, ""] : [required];
430 let restExploded = explodeOptionalSegments(rest.join("/"));
431 let result = [];
432 result.push(...restExploded.map((subpath) => subpath === "" ? required : [required, subpath].join("/")));
433 if (isOptional) result.push(...restExploded);
434 return result.map((exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded);
435}
436function rankRouteBranches(branches) {
437 branches.sort((a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(a.routesMeta.map((meta) => meta.childrenIndex), b.routesMeta.map((meta) => meta.childrenIndex)));
438}
439const paramRe = /^:[\w-]+$/;
440const partialParamRe = /^:[\w-]+/;
441const partialDynamicSegmentValue = 3.5;
442const dynamicSegmentValue = 3;
443const indexRouteValue = 2;
444const emptySegmentValue = 1;
445const staticSegmentValue = 10;
446const splatPenalty = -2;
447const isSplat = (s) => s === "*";
448function computeScore(path, index) {
449 let segments = path.split("/");
450 let initialScore = segments.length;
451 if (segments.some(isSplat)) initialScore += splatPenalty;
452 if (index) initialScore += indexRouteValue;
453 return segments.filter((s) => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : partialParamRe.test(segment) ? partialDynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
454}
455function compareIndexes(a, b) {
456 return a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]) ? a[a.length - 1] - b[b.length - 1] : 0;
457}
458function matchRouteBranch(branch, pathname, allowPartial = false) {
459 let { routesMeta } = branch;
460 let matchedParams = {};
461 let matchedPathname = "/";
462 let matches = [];
463 for (let i = 0; i < routesMeta.length; ++i) {
464 let meta = routesMeta[i];
465 let end = i === routesMeta.length - 1;
466 let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
467 let pattern = {
468 path: meta.relativePath,
469 caseSensitive: meta.caseSensitive,
470 end
471 };
472 let match = meta.matcher && meta.compiledParams ? matchPathImpl(pattern, remainingPathname, meta.matcher, meta.compiledParams) : matchPath(pattern, remainingPathname);
473 let route = meta.route;
474 if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) match = matchPath({
475 path: meta.relativePath,
476 caseSensitive: meta.caseSensitive,
477 end: false
478 }, remainingPathname);
479 if (!match) return null;
480 Object.assign(matchedParams, match.params);
481 matches.push({
482 params: matchedParams,
483 pathname: joinPaths([matchedPathname, match.pathname]),
484 pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
485 route
486 });
487 if (match.pathnameBase !== "/") matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
488 }
489 return matches;
490}
491/**
492* Characters that `encodeURIComponent` escapes but that are valid literally in
493* a URL path segment. Per RFC 3986 §3.3, a path segment is made of `pchar`:
494*
495* ```
496* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
497* sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
498* ```
499*
500* `encodeURIComponent` targets query-string values, where `$ & + , ; = : @`
501* are delimiters and must be escaped — but in a path segment they carry no
502* special meaning, and browsers keep them literal in `location.pathname`.
503* (`! ' ( ) *` and the unreserved set are already left alone by
504* `encodeURIComponent`, so they need no restoring.)
505*/
506const PATH_PARAM_OVERESCAPED = {
507 "%24": "$",
508 "%26": "&",
509 "%2B": "+",
510 "%2C": ",",
511 "%3A": ":",
512 "%3B": ";",
513 "%3D": "=",
514 "%40": "@"
515};
516/**
517* Encodes a param value for interpolation into a single URL path segment.
518*
519* Escapes characters that would break the path (`/ ? # %`, whitespace,
520* non-ASCII, …) while leaving characters that RFC 3986 permits literally in a
521* path segment untouched. Escaping those would needlessly rewrite URLs — e.g.
522* a semver build param `1.0.0+1` would become `1.0.0%2B1` even though browsers
523* display and match the `+` literally in `location.pathname`.
524*
525* See [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3))
526*
527* @param value The param value to encode.
528* @returns The encoded value, safe for use as a single path segment.
529*/
530function encodePathParam(value) {
531 return encodeURIComponent(value).replace(/%(?:24|26|2B|2C|3A|3B|3D|40)/g, (match) => PATH_PARAM_OVERESCAPED[match]);
532}
533const MAX_OPTIONAL_PATH_SEGMENTS = 12;
534/**
535* Performs pattern matching on a URL pathname and returns information about
536* the match.
537*
538* Throws if the pattern contains more than 12 optional (`?`) markers.
539*
540* @public
541* @category Utils
542* @param pattern The pattern to match against the URL pathname. This can be a
543* string or a {@link PathPattern} object. If a string is provided, it will be
544* treated as a pattern with `caseSensitive` set to `false` and `end` set to
545* `true`.
546* @param pathname The URL pathname to match against the pattern.
547* @returns A path match object if the pattern matches the pathname,
548* or `null` if it does not match.
549*/
550function matchPath(pattern, pathname) {
551 if (typeof pattern === "string") pattern = {
552 path: pattern,
553 caseSensitive: false,
554 end: true
555 };
556 let { path } = pattern;
557 let optionalSegments = 0;
558 for (let index = path.indexOf("?"); index !== -1; index = path.indexOf("?", index + 1)) if (++optionalSegments > MAX_OPTIONAL_PATH_SEGMENTS) throw new Error(`Path pattern ${JSON.stringify(path)} exceeds the limit of ${MAX_OPTIONAL_PATH_SEGMENTS} optional segments.`);
559 let [matcher, compiledParams] = compilePath(path, pattern.caseSensitive, pattern.end);
560 return matchPathImpl(pattern, pathname, matcher, compiledParams);
561}
562function matchPathImpl(pattern, pathname, matcher, compiledParams) {
563 let match = pathname.match(matcher);
564 if (!match) return null;
565 let matchedPathname = match[0];
566 let pathnameBase = removeTrailingSlash(matchedPathname, 1);
567 let captureGroups = match.slice(1);
568 return {
569 params: compiledParams.reduce((memo, { paramName, isOptional }, index) => {
570 if (paramName === "*") {
571 let splatValue = captureGroups[index] || "";
572 pathnameBase = removeTrailingSlash(matchedPathname.slice(0, matchedPathname.length - splatValue.length), 1);
573 }
574 const value = captureGroups[index];
575 if (isOptional && !value) memo[paramName] = void 0;
576 else memo[paramName] = (value || "").replace(/%2F/g, "/");
577 return memo;
578 }, {}),
579 pathname: matchedPathname,
580 pathnameBase,
581 pattern
582 };
583}
584function compilePath(path, caseSensitive = false, end = true) {
585 warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".`);
586 let params = [];
587 let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(/\/:([\w-]+)(\?)?/g, (match, paramName, isOptional, index, str) => {
588 params.push({
589 paramName,
590 isOptional: isOptional != null
591 });
592 if (isOptional) {
593 let nextChar = str.charAt(index + match.length);
594 if (nextChar && nextChar !== "/") return "/([^\\/]*)";
595 return "(?:/([^\\/]*))?";
596 }
597 return "/([^\\/]+)";
598 }).replace(/\/((?:[^/?()[\]*^\\]|\\.)+)\?(?=\/|$|\()/g, "(?:/$1)?");
599 if (path.endsWith("*")) {
600 params.push({ paramName: "*" });
601 regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
602 } else if (end) regexpSource += "\\/*$";
603 else if (path !== "" && path !== "/") regexpSource += "(?:(?=\\/|$))";
604 return [new RegExp(regexpSource, caseSensitive ? void 0 : "i"), params];
605}
606function decodePath(value) {
607 try {
608 return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
609 } catch (error) {
610 warning(false, `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}).`);
611 return value;
612 }
613}
614function stripBasename(pathname, basename) {
615 if (basename === "/") return pathname;
616 if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) return null;
617 let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
618 let nextChar = pathname.charAt(startIndex);
619 if (nextChar && nextChar !== "/") return null;
620 return pathname.slice(startIndex) || "/";
621}
622function prependBasename({ basename, pathname }) {
623 return pathname === "/" ? basename : joinPaths([basename, pathname]);
624}
625const isAbsoluteUrl = (url) => ABSOLUTE_URL_REGEX.test(url);
626/**
627* Returns a resolved {@link Path} object relative to the given pathname.
628*
629* @public
630* @category Utils
631* @param to The path to resolve, either a string or a partial {@link Path}
632* object.
633* @param fromPathname The pathname to resolve the path from. Defaults to `/`.
634* @returns A {@link Path} object with the resolved pathname, search, and hash.
635*/
636function resolvePath(to, fromPathname = "/") {
637 let { pathname: toPathname, search = "", hash = "" } = typeof to === "string" ? parsePath(to) : to;
638 let pathname;
639 if (toPathname) {
640 toPathname = removeDoubleSlashes(toPathname);
641 if (toPathname.startsWith("/") || toPathname.startsWith("\\")) pathname = resolvePathname(toPathname.substring(1), "/");
642 else pathname = resolvePathname(toPathname, fromPathname);
643 } else pathname = fromPathname;
644 return {
645 pathname,
646 search: normalizeSearch(search),
647 hash: normalizeHash(hash)
648 };
649}
650function resolvePathname(relativePath, fromPathname) {
651 let segments = removeTrailingSlash(fromPathname).split("/");
652 relativePath.split("/").forEach((segment) => {
653 if (segment === "..") {
654 if (segments.length > 1) segments.pop();
655 } else if (segment !== ".") segments.push(segment);
656 });
657 return segments.length > 1 ? segments.join("/") : "/";
658}
659function getInvalidPathError(char, field, dest, path) {
660 return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(path)}]. Please separate it out to the \`to.${dest}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`;
661}
662function getPathContributingMatches(matches) {
663 return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
664}
665function getResolveToMatches(matches) {
666 let pathMatches = getPathContributingMatches(matches);
667 return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase);
668}
669function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
670 let to;
671 if (typeof toArg === "string") to = parsePath(toArg);
672 else {
673 to = { ...toArg };
674 invariant$1(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to));
675 invariant$1(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to));
676 invariant$1(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to));
677 }
678 let isEmptyPath = toArg === "" || to.pathname === "";
679 let toPathname = isEmptyPath ? "/" : to.pathname;
680 let from;
681 if (toPathname == null) from = locationPathname;
682 else {
683 let routePathnameIndex = routePathnames.length - 1;
684 if (!isPathRelative && toPathname.startsWith("..")) {
685 let toSegments = toPathname.split("/");
686 while (toSegments[0] === "..") {
687 toSegments.shift();
688 routePathnameIndex -= 1;
689 }
690 to.pathname = toSegments.join("/");
691 }
692 from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
693 }
694 let path = resolvePath(to, from);
695 let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
696 let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
697 if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) path.pathname += "/";
698 return path;
699}
700const removeDoubleSlashes = (path) => path.replace(/[\\/]{2,}/g, "/");
701const joinPaths = (paths) => removeDoubleSlashes(paths.join("/"));
702function removeTrailingSlash(path, minLength = 0) {
703 let end = path.length;
704 while (end > minLength && path.charCodeAt(end - 1) === 47) end--;
705 return end === path.length ? path : path.slice(0, end);
706}
707const normalizePathname = (pathname) => removeTrailingSlash(pathname).replace(/^\/*/, "/");
708const normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
709const normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
710var DataWithResponseInit = class {
711 type = "DataWithResponseInit";
712 data;
713 init;
714 constructor(data, init) {
715 this.data = data;
716 this.init = init || null;
717 }
718};
719/**
720* Create "responses" that contain `headers`/`status` without forcing
721* serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
722*
723* @example
724* import { data } from "react-router";
725*
726* export async function action({ request }: Route.ActionArgs) {
727* let formData = await request.formData();
728* let item = await createItem(formData);
729* return data(item, {
730* headers: { "X-Custom-Header": "value" }
731* status: 201,
732* });
733* }
734*
735* @public
736* @category Utils
737* @mode framework
738* @mode data
739* @param data The data to be included in the response.
740* @param init The status code or a `ResponseInit` object to be included in the
741* response.
742* @returns A {@link DataWithResponseInit} instance containing the data and
743* response init.
744*/
745function data(data, init) {
746 return new DataWithResponseInit(data, typeof init === "number" ? { status: init } : init);
747}
748/**
749* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
750* Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
751* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
752*
753* This utility accepts absolute URLs and can navigate to external domains, so
754* the application should validate any user-supplied inputs to redirects.
755*
756* @example
757* import { redirect } from "react-router";
758*
759* export async function loader({ request }: Route.LoaderArgs) {
760* if (!isLoggedIn(request))
761* throw redirect("/login");
762* }
763*
764* // ...
765* }
766*
767* @public
768* @category Utils
769* @mode framework
770* @mode data
771* @param url The URL to redirect to.
772* @param init The status code or a `ResponseInit` object to be included in the
773* response.
774* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
775* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
776* header.
777*/
778const redirect$1 = (url, init = 302) => {
779 validateDocumentNavigationTarget(url);
780 let responseInit = init;
781 if (typeof responseInit === "number") responseInit = { status: responseInit };
782 let headers = new Headers(responseInit.headers);
783 headers.set("Location", url);
784 if (typeof responseInit.status === "undefined") responseInit = {
785 ...responseInit,
786 status: 302
787 };
788 return new Response(null, {
789 ...responseInit,
790 headers
791 });
792};
793/**
794* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
795* that will force a document reload to the new location. Sets the status code
796* and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
797* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
798*
799* This utility accepts absolute URLs and can navigate to external domains, so
800* the application should validate any user-supplied inputs to redirects.
801*
802* ```tsx filename=routes/logout.tsx
803* import { redirectDocument } from "react-router";
804*
805* import { destroySession } from "../sessions.server";
806*
807* export async function action({ request }: Route.ActionArgs) {
808* let session = await getSession(request.headers.get("Cookie"));
809* return redirectDocument("/", {
810* headers: { "Set-Cookie": await destroySession(session) }
811* });
812* }
813* ```
814*
815* @public
816* @category Utils
817* @mode framework
818* @mode data
819* @param url The URL to redirect to.
820* @param init The status code or a `ResponseInit` object to be included in the
821* response.
822* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
823* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
824* header.
825*/
826const redirectDocument$1 = (url, init) => {
827 let response = redirect$1(url, init);
828 response.headers.set("X-Remix-Reload-Document", "true");
829 return response;
830};
831/**
832* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
833* that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
834* instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
835* for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
836* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
837*
838* @example
839* import { replace } from "react-router";
840*
841* export async function loader() {
842* return replace("/new-location");
843* }
844*
845* @public
846* @category Utils
847* @mode framework
848* @mode data
849* @param url The URL to redirect to.
850* @param init The status code or a `ResponseInit` object to be included in the
851* response.
852* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
853* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
854* header.
855*/
856const replace$1 = (url, init) => {
857 let response = redirect$1(url, init);
858 response.headers.set("X-Remix-Replace", "true");
859 return response;
860};
861var ErrorResponseImpl = class {
862 status;
863 statusText;
864 data;
865 error;
866 internal;
867 constructor(status, statusText, data, internal = false) {
868 this.status = status;
869 this.statusText = statusText || "";
870 this.internal = internal;
871 if (data instanceof Error) {
872 this.data = data.toString();
873 this.error = data;
874 } else this.data = data;
875 }
876};
877/**
878* Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
879* [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
880* thrown from an [`action`](../../start/framework/route-module#action) or
881* [`loader`](../../start/framework/route-module#loader) function.
882*
883* @example
884* import { isRouteErrorResponse } from "react-router";
885*
886* export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
887* if (isRouteErrorResponse(error)) {
888* return (
889* <>
890* <p>Error: `${error.status}: ${error.statusText}`</p>
891* <p>{error.data}</p>
892* </>
893* );
894* }
895*
896* return (
897* <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
898* );
899* }
900*
901* @public
902* @category Utils
903* @mode framework
904* @mode data
905* @param error The error to check.
906* @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
907*/
908function isRouteErrorResponse(error) {
909 return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
910}
911function getRoutePattern(matches) {
912 return joinPaths(matches.map((m) => m.route.path).filter(Boolean)) || "/";
913}
914function createDataFunctionUrl(request, path) {
915 let url = new URL(typeof request === "string" || request instanceof URL ? request : request.url);
916 let parsed = typeof path === "string" ? parsePath(path) : path;
917 url.pathname = parsed.pathname || "/";
918 if (parsed.search) {
919 let searchParams = new URLSearchParams(parsed.search);
920 let indexValues = searchParams.getAll("index");
921 searchParams.delete("index");
922 for (let value of indexValues.filter(Boolean)) searchParams.append("index", value);
923 let search = searchParams.toString();
924 url.search = search ? `?${search}` : "";
925 } else url.search = "";
926 url.hash = parsed.hash || "";
927 return url;
928}
929typeof window !== "undefined" && typeof window.document !== "undefined" && window.document.createElement;
930//#endregion
931//#region lib/router/instrumentation.ts
932const UninstrumentedSymbol = Symbol("Uninstrumented");
933function getRouteInstrumentationUpdates(fns, route) {
934 let aggregated = {
935 lazy: [],
936 "lazy.loader": [],
937 "lazy.action": [],
938 "lazy.middleware": [],
939 middleware: [],
940 loader: [],
941 action: []
942 };
943 fns.forEach((fn) => fn({
944 id: route.id,
945 index: route.index,
946 path: route.path,
947 instrument(i) {
948 if (i.lazy != null) aggregated.lazy.push(i.lazy);
949 if (i["lazy.loader"] != null) aggregated["lazy.loader"].push(i["lazy.loader"]);
950 if (i["lazy.action"] != null) aggregated["lazy.action"].push(i["lazy.action"]);
951 if (i["lazy.middleware"] != null) aggregated["lazy.middleware"].push(i["lazy.middleware"]);
952 if (i.middleware != null) aggregated.middleware.push(i.middleware);
953 if (i.loader != null) aggregated.loader.push(i.loader);
954 if (i.action != null) aggregated.action.push(i.action);
955 }
956 }));
957 let updates = {};
958 if (typeof route.lazy === "function" && aggregated.lazy.length > 0) {
959 let lazy = route.lazy;
960 updates.lazy = async (...args) => {
961 return throwOrReturnResult(await recurseRight(aggregated.lazy, void 0, () => lazy(...args), getInstrumentationInnerResult));
962 };
963 }
964 if (typeof route.lazy === "object") {
965 let lazyObject = route.lazy;
966 if (typeof lazyObject.middleware === "function" && aggregated["lazy.middleware"].length > 0) {
967 let middleware = lazyObject.middleware;
968 updates.lazy = Object.assign(updates.lazy || {}, { middleware: async (...args) => {
969 return throwOrReturnResult(await recurseRight(aggregated["lazy.middleware"], void 0, () => middleware(...args), getInstrumentationInnerResult));
970 } });
971 }
972 if (typeof lazyObject.loader === "function" && aggregated["lazy.loader"].length > 0) {
973 let loader = lazyObject.loader;
974 updates.lazy = Object.assign(updates.lazy || {}, { loader: async (...args) => {
975 return throwOrReturnResult(await recurseRight(aggregated["lazy.loader"], void 0, () => loader(...args), getInstrumentationInnerResult));
976 } });
977 }
978 if (typeof lazyObject.action === "function" && aggregated["lazy.action"].length > 0) {
979 let action = lazyObject.action;
980 updates.lazy = Object.assign(updates.lazy || {}, { action: async (...args) => {
981 return throwOrReturnResult(await recurseRight(aggregated["lazy.action"], void 0, () => action(...args), getInstrumentationInnerResult));
982 } });
983 }
984 }
985 if (typeof route.loader === "function" && aggregated.loader.length > 0) {
986 let original = getUninstrumentedHandler(route.loader);
987 let instrumented = async (...args) => {
988 return throwOrReturnResult(await recurseRight(aggregated.loader, getHandlerInfo(args[0]), () => original(...args), getInstrumentationInnerResult));
989 };
990 if (original.hydrate === true) instrumented.hydrate = true;
991 setUninstrumentedHandler(instrumented, original);
992 updates.loader = instrumented;
993 }
994 if (typeof route.action === "function" && aggregated.action.length > 0) {
995 let original = getUninstrumentedHandler(route.action);
996 let instrumented = async (...args) => {
997 return throwOrReturnResult(await recurseRight(aggregated.action, getHandlerInfo(args[0]), () => original(...args), getInstrumentationInnerResult));
998 };
999 setUninstrumentedHandler(instrumented, original);
1000 updates.action = instrumented;
1001 }
1002 if (route.middleware && route.middleware.length > 0 && aggregated.middleware.length > 0) updates.middleware = route.middleware.map((middleware) => {
1003 let original = getUninstrumentedHandler(middleware);
1004 let instrumented = async (...args) => {
1005 return throwOrReturnResult(await recurseRight(aggregated.middleware, getHandlerInfo(args[0]), () => original(...args), getInstrumentationInnerResult));
1006 };
1007 setUninstrumentedHandler(instrumented, original);
1008 return instrumented;
1009 });
1010 return updates;
1011}
1012function getUninstrumentedHandler(handler) {
1013 return handler[UninstrumentedSymbol] ?? handler;
1014}
1015function setUninstrumentedHandler(handler, uninstrumentedHandler) {
1016 handler[UninstrumentedSymbol] = uninstrumentedHandler;
1017}
1018function throwOrReturnResult(result) {
1019 if (result.type === "error") throw result.value;
1020 return result.value;
1021}
1022async function recurseRight(impls, info, handler, getInnerResult, state = {
1023 result: null,
1024 innerResult: null
1025}, index = impls.length - 1) {
1026 let impl = impls[index];
1027 if (!impl) {
1028 try {
1029 state.result = {
1030 type: "success",
1031 value: await handler()
1032 };
1033 } catch (e) {
1034 state.result = {
1035 type: "error",
1036 value: e
1037 };
1038 }
1039 state.innerResult = getInnerResult(state.result, info);
1040 } else {
1041 let handlerPromise = void 0;
1042 let callHandler = async () => {
1043 if (handlerPromise) console.error("You cannot call instrumented handlers more than once");
1044 else handlerPromise = recurseRight(impls, info, handler, getInnerResult, state, index - 1);
1045 await handlerPromise;
1046 invariant$1(state.innerResult, "Expected an inner result");
1047 return state.innerResult;
1048 };
1049 try {
1050 await impl(callHandler, info);
1051 } catch (e) {
1052 console.error("An instrumentation function threw an error:", e);
1053 }
1054 if (!handlerPromise) await callHandler();
1055 await handlerPromise;
1056 }
1057 if (state.result) return state.result;
1058 state.result = {
1059 type: "error",
1060 value: /* @__PURE__ */ new Error("No result assigned in instrumentation chain.")
1061 };
1062 state.innerResult = getInnerResult(state.result, info);
1063 return state.result;
1064}
1065function getInstrumentationInnerResult(result) {
1066 if (result.type === "error" && result.value instanceof Error) return {
1067 status: "error",
1068 error: result.value
1069 };
1070 return {
1071 status: "success",
1072 error: void 0
1073 };
1074}
1075function getHandlerInfo(args) {
1076 let { request, context, params } = args;
1077 return {
1078 ...args,
1079 request: getReadonlyRequest(request),
1080 params: { ...params },
1081 context: getReadonlyContext(context)
1082 };
1083}
1084function getReadonlyRequest(request) {
1085 return {
1086 method: request.method,
1087 url: request.url,
1088 headers: { get: (...args) => request.headers.get(...args) }
1089 };
1090}
1091function getReadonlyContext(context) {
1092 return { get: (ctx) => context.get(ctx) };
1093}
1094//#endregion
1095//#region lib/router/matcher.ts
1096var V6RegExMatcher = class {
1097 #routes = [];
1098 #branches = [];
1099 #basename;
1100 #matchCost = 0;
1101 constructor(basename) {
1102 this.#basename = basename;
1103 }
1104 update(routes) {
1105 this.#routes = routes;
1106 this.#branches = flattenAndRankRoutes(routes);
1107 this.#matchCost = this.#branches.reduce((total, branch) => total + branch.routesMeta.length, 0);
1108 }
1109 get matchCost() {
1110 return this.#matchCost;
1111 }
1112 match(locationArg, allowPartial = false) {
1113 return matchRoutesImpl(this.#routes, locationArg, this.#basename, allowPartial, this.#branches);
1114 }
1115};
1116//#endregion
1117//#region lib/router/router.ts
1118const validMutationMethodsArr = [
1119 "POST",
1120 "PUT",
1121 "PATCH",
1122 "DELETE"
1123];
1124const validMutationMethods = new Set(validMutationMethodsArr);
1125const validRequestMethodsArr = ["GET", ...validMutationMethodsArr];
1126const validRequestMethods = new Set(validRequestMethodsArr);
1127const redirectStatusCodes = new Set([
1128 301,
1129 302,
1130 303,
1131 307,
1132 308
1133]);
1134const ResetLoaderDataSymbol = Symbol("ResetLoaderData");
1135function createDataRouteMatcher(future, basename) {
1136 if (future.unstable_routePatternMatching) {
1137 let RoutePatternMatcher = void 0;
1138 invariant$1(RoutePatternMatcher, "You must call unstable_preloadRoutePattern() from \"react-router/route-pattern\" before enabling future.unstable_routePatternMatching.");
1139 return new RoutePatternMatcher(basename);
1140 }
1141 return new V6RegExMatcher(basename);
1142}
1143/**
1144* Create a static handler to perform server-side data loading
1145*
1146* @example
1147* export async function handleRequest(request: Request) {
1148* let { query, dataRoutes } = createStaticHandler(routes);
1149* let context = await query(request);
1150*
1151* if (context instanceof Response) {
1152* return context;
1153* }
1154*
1155* let router = createStaticRouter(dataRoutes, context);
1156* return new Response(
1157* ReactDOMServer.renderToString(<StaticRouterProvider ... />),
1158* { headers: { "Content-Type": "text/html" } }
1159* );
1160* }
1161*
1162* @public
1163* @category Data Routers
1164* @mode data
1165* @param routes The {@link RouteObject | route objects} to create a static
1166* handler for
1167* @param opts Options
1168* @param opts.basename The base URL for the static handler (default: `/`)
1169* @param opts.future Future flags for the static handler
1170* @returns A static handler that can be used to query data for the provided
1171* routes
1172*/
1173function createStaticHandler(routes, opts) {
1174 invariant$1(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler");
1175 let manifest = {};
1176 let basename = (opts ? opts.basename : null) || "/";
1177 let _mapRouteProperties = opts?.mapRouteProperties;
1178 let mapRouteProperties = _mapRouteProperties ? _mapRouteProperties : () => ({});
1179 let dataRouteMatcher = createDataRouteMatcher({ ...opts?.future }, basename);
1180 if (opts?.instrumentations) {
1181 let instrumentations = opts.instrumentations;
1182 mapRouteProperties = (route) => {
1183 return {
1184 ..._mapRouteProperties?.(route),
1185 ...getRouteInstrumentationUpdates(instrumentations.map((i) => i.route).filter(Boolean), route)
1186 };
1187 };
1188 }
1189 let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, void 0, manifest);
1190 dataRouteMatcher.update(dataRoutes);
1191 let match = (locationArg) => dataRouteMatcher.match(locationArg);
1192 /**
1193 * The query() method is intended for document requests, in which we want to
1194 * call an optional action and potentially multiple loaders for all nested
1195 * routes. It returns a StaticHandlerContext object, which is very similar
1196 * to the router state (location, loaderData, actionData, errors, etc.) and
1197 * also adds SSR-specific information such as the statusCode and headers
1198 * from action/loaders Responses.
1199 *
1200 * It _should_ never throw and should report all errors through the
1201 * returned handlerContext.errors object, properly associating errors to
1202 * their error boundary. Additionally, it tracks _deepestRenderedBoundaryId
1203 * which can be used to emulate React error boundaries during SSR by performing
1204 * a second pass only down to the boundaryId.
1205 *
1206 * The one exception where we do not return a StaticHandlerContext is when a
1207 * redirect response is returned or thrown from any action/loader. We
1208 * propagate that out and return the raw Response so the HTTP server can
1209 * return it directly.
1210 *
1211 * - `opts.requestContext` is an optional server context that will be passed
1212 * to actions/loaders in the `context` parameter
1213 * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent
1214 * the bubbling of errors which allows single-fetch-type implementations
1215 * where the client will handle the bubbling and we may need to return data
1216 * for the handling route
1217 */
1218 async function query(request, { requestContext, filterMatchesToLoad, skipLoaderErrorBubbling, skipRevalidation, dataStrategy, generateMiddlewareResponse, normalizePath } = {}) {
1219 let normalizePathImpl = normalizePath || defaultNormalizePath;
1220 let method = request.method;
1221 let location = createLocation("", normalizePathImpl(request), null, "default");
1222 let matches = dataRouteMatcher.match(location);
1223 requestContext = requestContext != null ? requestContext : new RouterContextProvider();
1224 if (!isValidMethod(method) && method !== "HEAD") {
1225 let error = getInternalRouterError(405, { method });
1226 let { matches: methodNotAllowedMatches, route } = getShortCircuitMatches(dataRoutes);
1227 let staticContext = {
1228 basename,
1229 location,
1230 matches: methodNotAllowedMatches,
1231 loaderData: {},
1232 actionData: null,
1233 errors: { [route.id]: error },
1234 statusCode: error.status,
1235 loaderHeaders: {},
1236 actionHeaders: {},
1237 _match: match
1238 };
1239 return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext;
1240 } else if (!matches) {
1241 let error = getInternalRouterError(404, { pathname: location.pathname });
1242 let { matches: notFoundMatches, route } = getShortCircuitMatches(dataRoutes);
1243 let staticContext = {
1244 basename,
1245 location,
1246 matches: notFoundMatches,
1247 loaderData: {},
1248 actionData: null,
1249 errors: { [route.id]: error },
1250 statusCode: error.status,
1251 loaderHeaders: {},
1252 actionHeaders: {},
1253 _match: match
1254 };
1255 return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext;
1256 }
1257 if (generateMiddlewareResponse) {
1258 invariant$1(requestContext instanceof RouterContextProvider, "When using middleware in `staticHandler.query()`, any provided `requestContext` must be an instance of `RouterContextProvider`");
1259 try {
1260 await loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties);
1261 let renderedStaticContext;
1262 let response = await runServerMiddlewarePipeline({
1263 request,
1264 url: createDataFunctionUrl(request, location),
1265 pattern: getRoutePattern(matches),
1266 matches,
1267 params: matches[0].params,
1268 context: requestContext
1269 }, async () => {
1270 return await generateMiddlewareResponse(async (revalidationRequest, opts = {}) => {
1271 let result = await queryImpl(revalidationRequest, location, matches, requestContext, dataStrategy || null, skipLoaderErrorBubbling === true, null, "filterMatchesToLoad" in opts ? opts.filterMatchesToLoad ?? null : filterMatchesToLoad ?? null, skipRevalidation === true);
1272 if (isResponse(result)) return result;
1273 renderedStaticContext = {
1274 location,
1275 basename,
1276 ...result,
1277 _match: match
1278 };
1279 return renderedStaticContext;
1280 });
1281 }, async (error, routeId) => {
1282 if (isRedirectResponse(error)) return error;
1283 if (isResponse(error)) try {
1284 error = new ErrorResponseImpl(error.status, error.statusText, await parseResponseBody(error));
1285 } catch (e) {
1286 error = e;
1287 }
1288 if (isDataWithResponseInit(error)) error = dataWithResponseInitToErrorResponse(error);
1289 if (renderedStaticContext) {
1290 if (routeId in renderedStaticContext.loaderData) renderedStaticContext.loaderData[routeId] = void 0;
1291 let staticContext = getStaticContextFromError(dataRoutes, renderedStaticContext, error, skipLoaderErrorBubbling ? routeId : findNearestBoundary(matches, routeId).route.id);
1292 return generateMiddlewareResponse(() => Promise.resolve(staticContext));
1293 } else {
1294 let staticContext = {
1295 matches,
1296 location,
1297 basename,
1298 loaderData: {},
1299 actionData: null,
1300 errors: { [skipLoaderErrorBubbling ? routeId : findNearestBoundary(matches, matches.find((m) => m.route.id === routeId || m.route.loader)?.route.id || routeId).route.id]: error },
1301 statusCode: isRouteErrorResponse(error) ? error.status : 500,
1302 actionHeaders: {},
1303 loaderHeaders: {},
1304 _match: match
1305 };
1306 return generateMiddlewareResponse(() => Promise.resolve(staticContext));
1307 }
1308 });
1309 invariant$1(isResponse(response), "Expected a response in query()");
1310 return response;
1311 } catch (e) {
1312 if (isResponse(e)) return e;
1313 throw e;
1314 }
1315 }
1316 let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, skipLoaderErrorBubbling === true, null, filterMatchesToLoad || null, skipRevalidation === true);
1317 if (isResponse(result)) return result;
1318 return {
1319 location,
1320 basename,
1321 ...result,
1322 _match: match
1323 };
1324 }
1325 /**
1326 * The queryRoute() method is intended for targeted route requests, either
1327 * for fetch ?_data requests or resource route requests. In this case, we
1328 * are only ever calling a single action or loader, and we are returning the
1329 * returned value directly. In most cases, this will be a Response returned
1330 * from the action/loader, but it may be a primitive or other value as well -
1331 * and in such cases the calling context should handle that accordingly.
1332 *
1333 * We do respect the throw/return differentiation, so if an action/loader
1334 * throws, then this method will throw the value. This is important so we
1335 * can do proper boundary identification in Remix where a thrown Response
1336 * must go to the Catch Boundary but a returned Response is happy-path.
1337 *
1338 * One thing to note is that any Router-initiated Errors that make sense
1339 * to associate with a status code will be thrown as an ErrorResponse
1340 * instance which include the raw Error, such that the calling context can
1341 * serialize the error as they see fit while including the proper response
1342 * code. Examples here are 404 and 405 errors that occur prior to reaching
1343 * any user-defined loaders.
1344 *
1345 * - `opts.routeId` allows you to specify the specific route handler to call.
1346 * If not provided the handler will determine the proper route by matching
1347 * against `request.url`
1348 * - `opts.requestContext` is an optional server context that will be passed
1349 * to actions/loaders in the `context` parameter
1350 */
1351 async function queryRoute(request, { routeId, requestContext, dataStrategy, generateMiddlewareResponse, normalizePath } = {}) {
1352 let normalizePathImpl = normalizePath || defaultNormalizePath;
1353 let method = request.method;
1354 let location = createLocation("", normalizePathImpl(request), null, "default");
1355 let matches = dataRouteMatcher.match(location);
1356 requestContext = requestContext != null ? requestContext : new RouterContextProvider();
1357 if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") throw getInternalRouterError(405, { method });
1358 else if (!matches) throw getInternalRouterError(404, { pathname: location.pathname });
1359 let match = routeId ? matches.find((m) => m.route.id === routeId) : getTargetMatch(matches, location);
1360 if (routeId && !match) throw getInternalRouterError(403, {
1361 pathname: location.pathname,
1362 routeId
1363 });
1364 else if (!match) throw getInternalRouterError(404, { pathname: location.pathname });
1365 if (generateMiddlewareResponse) {
1366 invariant$1(requestContext instanceof RouterContextProvider, "When using middleware in `staticHandler.queryRoute()`, any provided `requestContext` must be an instance of `RouterContextProvider`");
1367 await loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties);
1368 return await runServerMiddlewarePipeline({
1369 request,
1370 url: createDataFunctionUrl(request, location),
1371 pattern: getRoutePattern(matches),
1372 matches,
1373 params: matches[0].params,
1374 context: requestContext
1375 }, async () => {
1376 return await generateMiddlewareResponse(async (innerRequest) => {
1377 let processed = handleQueryResult(await queryImpl(innerRequest, location, matches, requestContext, dataStrategy || null, false, match, null, false));
1378 return isResponse(processed) ? processed : typeof processed === "string" ? new Response(processed) : Response.json(processed);
1379 });
1380 }, (error) => {
1381 if (isDataWithResponseInit(error)) return Promise.resolve(dataWithResponseInitToResponse(error));
1382 if (isResponse(error)) return Promise.resolve(error);
1383 throw error;
1384 });
1385 }
1386 return handleQueryResult(await queryImpl(request, location, matches, requestContext, dataStrategy || null, false, match, null, false));
1387 function handleQueryResult(result) {
1388 if (isResponse(result)) return result;
1389 let error = result.errors ? Object.values(result.errors)[0] : void 0;
1390 if (error !== void 0) throw error;
1391 if (result.actionData) return Object.values(result.actionData)[0];
1392 if (result.loaderData) return Object.values(result.loaderData)[0];
1393 }
1394 }
1395 async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, skipRevalidation) {
1396 invariant$1(request.signal, "query()/queryRoute() requests must contain an AbortController signal");
1397 try {
1398 if (isMutationMethod(request.method)) return await submit(request, location, matches, routeMatch || getTargetMatch(matches, location), requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch != null, filterMatchesToLoad, skipRevalidation);
1399 let result = await loadRouteData(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad);
1400 return isResponse(result) ? result : {
1401 ...result,
1402 actionData: null,
1403 actionHeaders: {}
1404 };
1405 } catch (e) {
1406 if (isDataStrategyResult(e) && isResponse(e.result)) {
1407 if (e.type === "error") throw e.result;
1408 return e.result;
1409 }
1410 if (isRedirectResponse(e)) return e;
1411 throw e;
1412 }
1413 }
1414 async function submit(request, location, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest, filterMatchesToLoad, skipRevalidation) {
1415 let result;
1416 if (!actionMatch.route.action && !actionMatch.route.lazy) {
1417 let error = getInternalRouterError(405, {
1418 method: request.method,
1419 pathname: new URL(request.url).pathname,
1420 routeId: actionMatch.route.id
1421 });
1422 if (isRouteRequest) throw error;
1423 result = {
1424 type: "error",
1425 error
1426 };
1427 } else {
1428 result = (await callDataStrategy(request, location, getTargetedDataStrategyMatches(mapRouteProperties, manifest, request, location, matches, actionMatch, [], requestContext), isRouteRequest, requestContext, dataStrategy))[actionMatch.route.id];
1429 if (request.signal.aborted) throwStaticHandlerAbortedError(request, isRouteRequest);
1430 }
1431 if (isRedirectResult(result)) throw new Response(null, {
1432 status: result.response.status,
1433 headers: { Location: result.response.headers.get("Location") }
1434 });
1435 if (isRouteRequest) {
1436 if (isErrorResult(result)) throw result.error;
1437 return {
1438 matches: [actionMatch],
1439 loaderData: {},
1440 actionData: { [actionMatch.route.id]: result.data },
1441 errors: null,
1442 statusCode: 200,
1443 loaderHeaders: {},
1444 actionHeaders: {}
1445 };
1446 }
1447 if (skipRevalidation) if (isErrorResult(result)) {
1448 let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
1449 return {
1450 statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
1451 actionData: null,
1452 actionHeaders: { ...result.headers ? { [actionMatch.route.id]: result.headers } : {} },
1453 matches,
1454 loaderData: {},
1455 errors: { [boundaryMatch.route.id]: result.error },
1456 loaderHeaders: {}
1457 };
1458 } else return {
1459 actionData: { [actionMatch.route.id]: result.data },
1460 actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {},
1461 matches,
1462 loaderData: {},
1463 errors: null,
1464 statusCode: result.statusCode || 200,
1465 loaderHeaders: {}
1466 };
1467 let loaderRequest = new Request(request.url, {
1468 headers: request.headers,
1469 redirect: request.redirect,
1470 signal: request.signal
1471 });
1472 if (isErrorResult(result)) return {
1473 ...await loadRouteData(loaderRequest, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null, filterMatchesToLoad, [(skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id)).route.id, result]),
1474 statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
1475 actionData: null,
1476 actionHeaders: { ...result.headers ? { [actionMatch.route.id]: result.headers } : {} }
1477 };
1478 return {
1479 ...await loadRouteData(loaderRequest, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null, filterMatchesToLoad),
1480 actionData: { [actionMatch.route.id]: result.data },
1481 ...result.statusCode ? { statusCode: result.statusCode } : {},
1482 actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {}
1483 };
1484 }
1485 async function loadRouteData(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, pendingActionResult) {
1486 let isRouteRequest = routeMatch != null;
1487 if (isRouteRequest && !routeMatch?.route.loader && !routeMatch?.route.lazy) throw getInternalRouterError(400, {
1488 method: request.method,
1489 pathname: new URL(request.url).pathname,
1490 routeId: routeMatch?.route.id
1491 });
1492 let dsMatches;
1493 if (routeMatch) dsMatches = getTargetedDataStrategyMatches(mapRouteProperties, manifest, request, location, matches, routeMatch, [], requestContext);
1494 else {
1495 let maxIdx = pendingActionResult && isErrorResult(pendingActionResult[1]) ? matches.findIndex((m) => m.route.id === pendingActionResult[0]) - 1 : void 0;
1496 let pattern = getRoutePattern(matches);
1497 dsMatches = matches.map((match, index) => {
1498 if (maxIdx != null && index > maxIdx) return getDataStrategyMatch(mapRouteProperties, manifest, request, location, pattern, match, [], requestContext, false);
1499 return getDataStrategyMatch(mapRouteProperties, manifest, request, location, pattern, match, [], requestContext, (match.route.loader || match.route.lazy) != null && (!filterMatchesToLoad || filterMatchesToLoad(match)));
1500 });
1501 }
1502 if (!dataStrategy && !dsMatches.some((m) => m.shouldLoad)) return {
1503 matches,
1504 loaderData: {},
1505 errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { [pendingActionResult[0]]: pendingActionResult[1].error } : null,
1506 statusCode: 200,
1507 loaderHeaders: {}
1508 };
1509 let results = await callDataStrategy(request, location, dsMatches, isRouteRequest, requestContext, dataStrategy);
1510 if (request.signal.aborted) throwStaticHandlerAbortedError(request, isRouteRequest);
1511 return {
1512 ...processRouteLoaderData(matches, results, pendingActionResult, true, skipLoaderErrorBubbling),
1513 matches
1514 };
1515 }
1516 async function callDataStrategy(request, location, matches, isRouteRequest, requestContext, dataStrategy) {
1517 let results = await callDataStrategyImpl(dataStrategy || defaultDataStrategy, request, location, matches, null, "static", requestContext, true);
1518 let dataResults = {};
1519 await Promise.all(matches.map(async (match) => {
1520 if (!(match.route.id in results)) return;
1521 let result = results[match.route.id];
1522 if (isRedirectDataStrategyResult(result)) {
1523 let response = result.result;
1524 throw normalizeRelativeRoutingRedirectResponse(response, request, match.route.id, matches, basename);
1525 }
1526 if (isRouteRequest) {
1527 if (isResponse(result.result)) throw result;
1528 else if (isDataWithResponseInit(result.result)) throw dataWithResponseInitToResponse(result.result);
1529 }
1530 dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
1531 }));
1532 return dataResults;
1533 }
1534 return {
1535 dataRoutes,
1536 get _matchCost() {
1537 return dataRouteMatcher instanceof V6RegExMatcher ? dataRouteMatcher.matchCost : void 0;
1538 },
1539 match,
1540 query,
1541 queryRoute
1542 };
1543}
1544/**
1545* Given an existing StaticHandlerContext and an error thrown at render time,
1546* provide an updated StaticHandlerContext suitable for a second SSR render
1547*
1548* @category Utils
1549*/
1550function getStaticContextFromError(routes, handlerContext, error, boundaryId) {
1551 let errorBoundaryId = boundaryId || handlerContext._deepestRenderedBoundaryId || routes[0].id;
1552 return {
1553 ...handlerContext,
1554 statusCode: isRouteErrorResponse(error) ? error.status : 500,
1555 errors: { [errorBoundaryId]: error }
1556 };
1557}
1558function throwStaticHandlerAbortedError(request, isRouteRequest) {
1559 if (request.signal.reason !== void 0) throw request.signal.reason;
1560 throw new Error(`${isRouteRequest ? "queryRoute" : "query"}() call aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`);
1561}
1562function defaultNormalizePath(request) {
1563 let url = new URL(request.url);
1564 return {
1565 pathname: url.pathname,
1566 search: url.search,
1567 hash: url.hash
1568 };
1569}
1570function normalizeTo(location, matches, basename, to, fromRouteId, relative) {
1571 let contextualMatches;
1572 let activeRouteMatch;
1573 if (fromRouteId) {
1574 contextualMatches = [];
1575 for (let match of matches) {
1576 contextualMatches.push(match);
1577 if (match.route.id === fromRouteId) {
1578 activeRouteMatch = match;
1579 break;
1580 }
1581 }
1582 } else {
1583 contextualMatches = matches;
1584 activeRouteMatch = matches[matches.length - 1];
1585 }
1586 let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches), stripBasename(location.pathname, basename) || location.pathname, relative === "path");
1587 if (to == null) {
1588 path.search = location.search;
1589 path.hash = location.hash;
1590 }
1591 if ((to == null || to === "" || to === ".") && activeRouteMatch) {
1592 let nakedIndex = hasNakedIndexQuery(path.search);
1593 if (activeRouteMatch.route.index && !nakedIndex) path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
1594 else if (!activeRouteMatch.route.index && nakedIndex) {
1595 let params = new URLSearchParams(path.search);
1596 let indexValues = params.getAll("index");
1597 params.delete("index");
1598 indexValues.filter((v) => v).forEach((v) => params.append("index", v));
1599 let qs = params.toString();
1600 path.search = qs ? `?${qs}` : "";
1601 }
1602 }
1603 if (basename !== "/") path.pathname = prependBasename({
1604 basename,
1605 pathname: path.pathname
1606 });
1607 return createPath(path);
1608}
1609function shouldRevalidateLoader(loaderMatch, arg) {
1610 if (loaderMatch.route.shouldRevalidate) {
1611 let routeChoice = loaderMatch.route.shouldRevalidate(arg);
1612 if (typeof routeChoice === "boolean") return routeChoice;
1613 }
1614 return arg.defaultShouldRevalidate;
1615}
1616const lazyRoutePropertyCache = /* @__PURE__ */ new WeakMap();
1617const loadLazyRouteProperty = ({ key, route, manifest, mapRouteProperties }) => {
1618 let routeToUpdate = manifest[route.id];
1619 invariant$1(routeToUpdate, "No route found in manifest");
1620 if (!routeToUpdate.lazy || typeof routeToUpdate.lazy !== "object") return;
1621 let lazyFn = routeToUpdate.lazy[key];
1622 if (!lazyFn) return;
1623 let cache = lazyRoutePropertyCache.get(routeToUpdate);
1624 if (!cache) {
1625 cache = {};
1626 lazyRoutePropertyCache.set(routeToUpdate, cache);
1627 }
1628 let cachedPromise = cache[key];
1629 if (cachedPromise) return cachedPromise;
1630 let propertyPromise = (async () => {
1631 let isUnsupported = isUnsupportedLazyRouteObjectKey(key);
1632 let isStaticallyDefined = routeToUpdate[key] !== void 0;
1633 if (isUnsupported) {
1634 warning(!isUnsupported, "Route property " + key + " is not a supported lazy route property. This property will be ignored.");
1635 cache[key] = Promise.resolve();
1636 } else if (isStaticallyDefined) warning(false, `Route "${routeToUpdate.id}" has a static property "${key}" defined. The lazy property will be ignored.`);
1637 else {
1638 let value = await lazyFn();
1639 if (value != null) {
1640 Object.assign(routeToUpdate, { [key]: value });
1641 Object.assign(routeToUpdate, mapRouteProperties(routeToUpdate));
1642 }
1643 }
1644 if (typeof routeToUpdate.lazy === "object") {
1645 routeToUpdate.lazy[key] = void 0;
1646 if (Object.values(routeToUpdate.lazy).every((value) => value === void 0)) routeToUpdate.lazy = void 0;
1647 }
1648 })();
1649 cache[key] = propertyPromise;
1650 propertyPromise.catch(() => {
1651 if (cache[key] === propertyPromise) delete cache[key];
1652 });
1653 return propertyPromise;
1654};
1655const lazyRouteFunctionCache = /* @__PURE__ */ new WeakMap();
1656/**
1657* Execute route.lazy functions to lazily load route modules (loader, action,
1658* shouldRevalidate) and update the routeManifest in place which shares objects
1659* with dataRoutes so those get updated as well.
1660*/
1661function loadLazyRoute(route, type, manifest, mapRouteProperties, lazyRoutePropertiesToSkip) {
1662 let routeToUpdate = manifest[route.id];
1663 invariant$1(routeToUpdate, "No route found in manifest");
1664 if (!route.lazy) return {
1665 lazyRoutePromise: void 0,
1666 lazyHandlerPromise: void 0
1667 };
1668 if (typeof route.lazy === "function") {
1669 let cachedPromise = lazyRouteFunctionCache.get(routeToUpdate);
1670 if (cachedPromise) return {
1671 lazyRoutePromise: cachedPromise,
1672 lazyHandlerPromise: cachedPromise
1673 };
1674 let lazyRoutePromise = (async () => {
1675 invariant$1(typeof route.lazy === "function", "No lazy route function found");
1676 let lazyRoute = await route.lazy();
1677 let routeUpdates = {};
1678 for (let lazyRouteProperty in lazyRoute) {
1679 let lazyValue = lazyRoute[lazyRouteProperty];
1680 if (lazyValue === void 0) continue;
1681 let isUnsupported = isUnsupportedLazyRouteFunctionKey(lazyRouteProperty);
1682 let isStaticallyDefined = routeToUpdate[lazyRouteProperty] !== void 0;
1683 if (isUnsupported) warning(!isUnsupported, "Route property " + lazyRouteProperty + " is not a supported property to be returned from a lazy route function. This property will be ignored.");
1684 else if (isStaticallyDefined) warning(!isStaticallyDefined, `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.`);
1685 else routeUpdates[lazyRouteProperty] = lazyValue;
1686 }
1687 Object.assign(routeToUpdate, routeUpdates);
1688 Object.assign(routeToUpdate, {
1689 ...mapRouteProperties(routeToUpdate),
1690 lazy: void 0
1691 });
1692 })();
1693 lazyRouteFunctionCache.set(routeToUpdate, lazyRoutePromise);
1694 lazyRoutePromise.catch(() => {
1695 if (lazyRouteFunctionCache.get(routeToUpdate) === lazyRoutePromise) lazyRouteFunctionCache.delete(routeToUpdate);
1696 });
1697 return {
1698 lazyRoutePromise,
1699 lazyHandlerPromise: lazyRoutePromise
1700 };
1701 }
1702 let lazyKeys = Object.keys(route.lazy);
1703 let lazyPropertyPromises = [];
1704 let lazyHandlerPromise = void 0;
1705 for (let key of lazyKeys) {
1706 if (lazyRoutePropertiesToSkip && lazyRoutePropertiesToSkip.includes(key)) continue;
1707 let promise = loadLazyRouteProperty({
1708 key,
1709 route,
1710 manifest,
1711 mapRouteProperties
1712 });
1713 if (promise) {
1714 lazyPropertyPromises.push(promise);
1715 if (key === type) lazyHandlerPromise = promise;
1716 }
1717 }
1718 let lazyRoutePromise = lazyPropertyPromises.length > 0 ? Promise.all(lazyPropertyPromises).then(() => {}) : void 0;
1719 lazyRoutePromise?.catch(() => {});
1720 lazyHandlerPromise?.catch(() => {});
1721 return {
1722 lazyRoutePromise,
1723 lazyHandlerPromise
1724 };
1725}
1726function isNonNullable(value) {
1727 return value !== void 0;
1728}
1729function loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties) {
1730 let promises = matches.map(({ route }) => {
1731 if (typeof route.lazy !== "object" || !route.lazy.middleware) return;
1732 return loadLazyRouteProperty({
1733 key: "middleware",
1734 route,
1735 manifest,
1736 mapRouteProperties
1737 });
1738 }).filter(isNonNullable);
1739 return promises.length > 0 ? Promise.all(promises) : void 0;
1740}
1741async function defaultDataStrategy(args) {
1742 let matchesToLoad = args.matches.filter((m) => m.shouldLoad);
1743 let keyedResults = {};
1744 (await Promise.all(matchesToLoad.map((m) => m.resolve()))).forEach((result, i) => {
1745 keyedResults[matchesToLoad[i].route.id] = result;
1746 });
1747 return keyedResults;
1748}
1749function runServerMiddlewarePipeline(args, handler, errorHandler) {
1750 return runMiddlewarePipeline(args, handler, processResult, isResponse, errorHandler);
1751 function processResult(result) {
1752 return isDataWithResponseInit(result) ? dataWithResponseInitToResponse(result) : result;
1753 }
1754}
1755function runClientMiddlewarePipeline(args, handler) {
1756 return runMiddlewarePipeline(args, handler, (r) => {
1757 if (isRedirectResponse(r)) throw r;
1758 return r;
1759 }, isDataStrategyResults, errorHandler);
1760 async function errorHandler(error, routeId, nextResult) {
1761 if (nextResult) return Object.assign(nextResult.value, { [routeId]: {
1762 type: "error",
1763 result: error
1764 } });
1765 else {
1766 let { matches } = args;
1767 let maxBoundaryIdx = Math.min(Math.max(matches.findIndex((m) => m.route.id === routeId), 0), Math.max(matches.findIndex((m) => m.shouldCallHandler()), 0));
1768 let deepestRouteId = matches[maxBoundaryIdx].route.id;
1769 for (let match of matches.slice(0, maxBoundaryIdx + 1)) try {
1770 await match._lazyPromises?.route;
1771 } catch {
1772 deepestRouteId = match.route.id;
1773 break;
1774 }
1775 return { [findNearestBoundary(matches, deepestRouteId).route.id]: {
1776 type: "error",
1777 result: error
1778 } };
1779 }
1780 }
1781}
1782async function runMiddlewarePipeline(args, handler, processResult, isResult, errorHandler) {
1783 let { matches, ...dataFnArgs } = args;
1784 return await callRouteMiddleware(dataFnArgs, matches.flatMap((m) => m.route.middleware ? m.route.middleware.map((fn) => [m.route.id, fn]) : []), handler, processResult, isResult, errorHandler);
1785}
1786async function callRouteMiddleware(args, middlewares, handler, processResult, isResult, errorHandler, idx = 0) {
1787 let { request } = args;
1788 if (request.signal.aborted) throw request.signal.reason ?? /* @__PURE__ */ new Error(`Request aborted: ${request.method} ${request.url}`);
1789 let tuple = middlewares[idx];
1790 if (!tuple) return await handler();
1791 let [routeId, middleware] = tuple;
1792 let nextResult;
1793 let next = async () => {
1794 if (nextResult) throw new Error("You may only call `next()` once per middleware");
1795 try {
1796 nextResult = { value: await callRouteMiddleware(args, middlewares, handler, processResult, isResult, errorHandler, idx + 1) };
1797 return nextResult.value;
1798 } catch (error) {
1799 nextResult = { value: await errorHandler(error, routeId, nextResult) };
1800 return nextResult.value;
1801 }
1802 };
1803 try {
1804 let value = await middleware(args, next);
1805 let result = value != null ? processResult(value) : void 0;
1806 if (isResult(result)) return result;
1807 else if (nextResult) return result ?? nextResult.value;
1808 else {
1809 nextResult = { value: await next() };
1810 return nextResult.value;
1811 }
1812 } catch (error) {
1813 return await errorHandler(error, routeId, nextResult);
1814 }
1815}
1816function getDataStrategyMatchLazyPromises(mapRouteProperties, manifest, request, match, lazyRoutePropertiesToSkip) {
1817 let lazyMiddlewarePromise = loadLazyRouteProperty({
1818 key: "middleware",
1819 route: match.route,
1820 manifest,
1821 mapRouteProperties
1822 });
1823 let lazyRoutePromises = loadLazyRoute(match.route, isMutationMethod(request.method) ? "action" : "loader", manifest, mapRouteProperties, lazyRoutePropertiesToSkip);
1824 return {
1825 middleware: lazyMiddlewarePromise,
1826 route: lazyRoutePromises.lazyRoutePromise,
1827 handler: lazyRoutePromises.lazyHandlerPromise
1828 };
1829}
1830function getDataStrategyMatch(mapRouteProperties, manifest, request, path, pattern, match, lazyRoutePropertiesToSkip, scopedContext, shouldLoad, shouldRevalidateArgs = null, callSiteDefaultShouldRevalidate) {
1831 let isUsingNewApi = false;
1832 let _lazyPromises = getDataStrategyMatchLazyPromises(mapRouteProperties, manifest, request, match, lazyRoutePropertiesToSkip);
1833 return {
1834 ...match,
1835 _lazyPromises,
1836 shouldLoad,
1837 shouldRevalidateArgs,
1838 shouldCallHandler(defaultShouldRevalidate) {
1839 isUsingNewApi = true;
1840 if (!shouldRevalidateArgs) return shouldLoad;
1841 if (typeof callSiteDefaultShouldRevalidate === "boolean") return shouldRevalidateLoader(match, {
1842 ...shouldRevalidateArgs,
1843 defaultShouldRevalidate: callSiteDefaultShouldRevalidate
1844 });
1845 if (typeof defaultShouldRevalidate === "boolean") return shouldRevalidateLoader(match, {
1846 ...shouldRevalidateArgs,
1847 defaultShouldRevalidate
1848 });
1849 return shouldRevalidateLoader(match, shouldRevalidateArgs);
1850 },
1851 resolve(handlerOverride) {
1852 let { lazy, loader, middleware } = match.route;
1853 let callHandler = isUsingNewApi || shouldLoad || handlerOverride && !isMutationMethod(request.method) && (lazy || loader);
1854 let isMiddlewareOnlyRoute = middleware && middleware.length > 0 && !loader && !lazy;
1855 if (callHandler && (isMutationMethod(request.method) || !isMiddlewareOnlyRoute)) return callLoaderOrAction({
1856 request,
1857 path,
1858 pattern,
1859 match,
1860 lazyHandlerPromise: _lazyPromises?.handler,
1861 lazyRoutePromise: _lazyPromises?.route,
1862 handlerOverride,
1863 scopedContext
1864 });
1865 return Promise.resolve({
1866 type: "data",
1867 result: void 0
1868 });
1869 }
1870 };
1871}
1872function getTargetedDataStrategyMatches(mapRouteProperties, manifest, request, path, matches, targetMatch, lazyRoutePropertiesToSkip, scopedContext, shouldRevalidateArgs = null) {
1873 return matches.map((match) => {
1874 if (match.route.id !== targetMatch.route.id) return {
1875 ...match,
1876 shouldLoad: false,
1877 shouldRevalidateArgs,
1878 shouldCallHandler: () => false,
1879 _lazyPromises: getDataStrategyMatchLazyPromises(mapRouteProperties, manifest, request, match, lazyRoutePropertiesToSkip),
1880 resolve: () => Promise.resolve({
1881 type: "data",
1882 result: void 0
1883 })
1884 };
1885 return getDataStrategyMatch(mapRouteProperties, manifest, request, path, getRoutePattern(matches), match, lazyRoutePropertiesToSkip, scopedContext, true, shouldRevalidateArgs);
1886 });
1887}
1888async function callDataStrategyImpl(dataStrategyImpl, request, path, matches, fetcherKey, initiator, scopedContext, isStaticHandler, navigationType = null) {
1889 if (matches.some((m) => m._lazyPromises?.middleware)) await Promise.all(matches.map((m) => m._lazyPromises?.middleware));
1890 let dataStrategyArgs = {
1891 request,
1892 url: createDataFunctionUrl(request, path),
1893 pattern: getRoutePattern(matches),
1894 params: matches[0].params,
1895 context: scopedContext,
1896 matches,
1897 unstable_initiator: initiator,
1898 unstable_navigationType: initiator === "navigation" ? navigationType : null
1899 };
1900 let runClientMiddleware = isStaticHandler ? () => {
1901 throw new Error("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`");
1902 } : (cb) => {
1903 let typedDataStrategyArgs = dataStrategyArgs;
1904 return runClientMiddlewarePipeline(typedDataStrategyArgs, () => {
1905 return cb({
1906 ...typedDataStrategyArgs,
1907 fetcherKey,
1908 runClientMiddleware: () => {
1909 throw new Error("Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler");
1910 }
1911 });
1912 });
1913 };
1914 let results = await dataStrategyImpl({
1915 ...dataStrategyArgs,
1916 fetcherKey,
1917 runClientMiddleware
1918 });
1919 try {
1920 await Promise.all(matches.flatMap((m) => [m._lazyPromises?.handler, m._lazyPromises?.route]));
1921 } catch {}
1922 return results;
1923}
1924async function callLoaderOrAction({ request, path, pattern, match, lazyHandlerPromise, lazyRoutePromise, handlerOverride, scopedContext }) {
1925 let result;
1926 let onReject;
1927 let isAction = isMutationMethod(request.method);
1928 let type = isAction ? "action" : "loader";
1929 let runHandler = (handler) => {
1930 let reject;
1931 let abortPromise = new Promise((_, r) => reject = r);
1932 onReject = () => reject();
1933 request.signal.addEventListener("abort", onReject);
1934 let actualHandler = (ctx) => {
1935 if (typeof handler !== "function") return Promise.reject(/* @__PURE__ */ new Error(`You cannot call the handler for a route which defines a boolean "${type}" [routeId: ${match.route.id}]`));
1936 return handler({
1937 request,
1938 url: createDataFunctionUrl(request, path),
1939 pattern,
1940 params: match.params,
1941 context: scopedContext
1942 }, ...ctx !== void 0 ? [ctx] : []);
1943 };
1944 let handlerPromise = (async () => {
1945 try {
1946 return {
1947 type: "data",
1948 result: await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler())
1949 };
1950 } catch (e) {
1951 return {
1952 type: "error",
1953 result: e
1954 };
1955 }
1956 })();
1957 return Promise.race([handlerPromise, abortPromise]);
1958 };
1959 try {
1960 let handler = isAction ? match.route.action : match.route.loader;
1961 if (lazyHandlerPromise || lazyRoutePromise) if (handler) {
1962 let handlerError;
1963 let [value] = await Promise.all([
1964 runHandler(handler).catch((e) => {
1965 handlerError = e;
1966 }),
1967 lazyHandlerPromise,
1968 lazyRoutePromise
1969 ]);
1970 if (handlerError !== void 0) throw handlerError;
1971 result = value;
1972 } else {
1973 await lazyHandlerPromise;
1974 let handler = isAction ? match.route.action : match.route.loader;
1975 if (handler) [result] = await Promise.all([runHandler(handler), lazyRoutePromise]);
1976 else if (type === "action") {
1977 let url = new URL(request.url);
1978 let pathname = url.pathname + url.search;
1979 throw getInternalRouterError(405, {
1980 method: request.method,
1981 pathname,
1982 routeId: match.route.id
1983 });
1984 } else {
1985 await lazyRoutePromise;
1986 return {
1987 type: "data",
1988 result: void 0
1989 };
1990 }
1991 }
1992 else if (!handler) {
1993 let url = new URL(request.url);
1994 throw getInternalRouterError(404, { pathname: url.pathname + url.search });
1995 } else result = await runHandler(handler);
1996 } catch (e) {
1997 return {
1998 type: "error",
1999 result: e
2000 };
2001 } finally {
2002 if (onReject) request.signal.removeEventListener("abort", onReject);
2003 }
2004 return result;
2005}
2006async function parseResponseBody(response) {
2007 let contentType = response.headers.get("Content-Type");
2008 if (contentType && /\bapplication\/json\b/.test(contentType)) return response.body == null ? null : response.json();
2009 return response.text();
2010}
2011async function convertDataStrategyResultToDataResult(dataStrategyResult) {
2012 let { result, type } = dataStrategyResult;
2013 if (isResponse(result)) {
2014 let data;
2015 try {
2016 data = await parseResponseBody(result);
2017 } catch (e) {
2018 return {
2019 type: "error",
2020 error: e
2021 };
2022 }
2023 if (type === "error") return {
2024 type: "error",
2025 error: new ErrorResponseImpl(result.status, result.statusText, data),
2026 statusCode: result.status,
2027 headers: result.headers
2028 };
2029 return {
2030 type: "data",
2031 data,
2032 statusCode: result.status,
2033 headers: result.headers
2034 };
2035 }
2036 if (type === "error") {
2037 if (isDataWithResponseInit(result)) {
2038 if (result.data instanceof Error) return {
2039 type: "error",
2040 error: result.data,
2041 statusCode: result.init?.status,
2042 headers: result.init?.headers ? new Headers(result.init.headers) : void 0
2043 };
2044 return {
2045 type: "error",
2046 error: dataWithResponseInitToErrorResponse(result),
2047 statusCode: isRouteErrorResponse(result) ? result.status : void 0,
2048 headers: result.init?.headers ? new Headers(result.init.headers) : void 0
2049 };
2050 }
2051 return {
2052 type: "error",
2053 error: result,
2054 statusCode: isRouteErrorResponse(result) ? result.status : void 0
2055 };
2056 }
2057 if (isDataWithResponseInit(result)) return {
2058 type: "data",
2059 data: result.data,
2060 statusCode: result.init?.status,
2061 headers: result.init?.headers ? new Headers(result.init.headers) : void 0
2062 };
2063 return {
2064 type: "data",
2065 data: result
2066 };
2067}
2068function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename) {
2069 let location = response.headers.get("Location");
2070 invariant$1(location, "Redirects returned/thrown from loaders/actions must have a Location header");
2071 validateNavigationTarget(location, location, new URL(request.url), "allow-explicit");
2072 if (!isAbsoluteUrl(location)) {
2073 let trimmedMatches = matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1);
2074 location = normalizeTo(new URL(request.url), trimmedMatches, basename, location);
2075 response.headers.set("Location", location);
2076 }
2077 return response;
2078}
2079function processRouteLoaderData(matches, results, pendingActionResult, isStaticHandler = false, skipLoaderErrorBubbling = false) {
2080 let loaderData = {};
2081 let errors = null;
2082 let statusCode;
2083 let foundError = false;
2084 let loaderHeaders = {};
2085 let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0;
2086 matches.forEach((match) => {
2087 if (!(match.route.id in results)) return;
2088 let id = match.route.id;
2089 let result = results[id];
2090 invariant$1(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData");
2091 if (isErrorResult(result)) {
2092 let error = result.error;
2093 if (pendingError !== void 0) {
2094 error = pendingError;
2095 pendingError = void 0;
2096 }
2097 errors = errors || {};
2098 if (skipLoaderErrorBubbling) errors[id] = error;
2099 else {
2100 let boundaryMatch = findNearestBoundary(matches, id);
2101 if (errors[boundaryMatch.route.id] == null) errors[boundaryMatch.route.id] = error;
2102 }
2103 if (!isStaticHandler) loaderData[id] = ResetLoaderDataSymbol;
2104 if (!foundError) {
2105 foundError = true;
2106 statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
2107 }
2108 if (result.headers) loaderHeaders[id] = result.headers;
2109 } else {
2110 loaderData[id] = result.data;
2111 if (result.statusCode && result.statusCode !== 200 && !foundError) statusCode = result.statusCode;
2112 if (result.headers) loaderHeaders[id] = result.headers;
2113 }
2114 });
2115 if (pendingError !== void 0 && pendingActionResult) {
2116 errors = { [pendingActionResult[0]]: pendingError };
2117 if (pendingActionResult[2]) loaderData[pendingActionResult[2]] = void 0;
2118 }
2119 return {
2120 loaderData,
2121 errors,
2122 statusCode: statusCode || 200,
2123 loaderHeaders
2124 };
2125}
2126function findNearestBoundary(matches, routeId) {
2127 return (routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches]).reverse().find((m) => m.route.ErrorBoundary != null || m.route.errorElement != null) || matches[0];
2128}
2129function getShortCircuitMatches(routes) {
2130 let route = routes.length === 1 ? routes[0] : routes.find((r) => r.index || !r.path || r.path === "/") || { id: `__shim-error-route__` };
2131 return {
2132 matches: [{
2133 params: {},
2134 pathname: "",
2135 pathnameBase: "",
2136 route
2137 }],
2138 route
2139 };
2140}
2141function getInternalRouterError(status, { pathname, routeId, method, type, message } = {}) {
2142 let statusText = "Unknown Server Error";
2143 let errorMessage = "Unknown @remix-run/router error";
2144 if (status === 400) {
2145 statusText = "Bad Request";
2146 if (method && pathname && routeId) 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.`;
2147 else if (type === "invalid-body") errorMessage = "Unable to encode submission body";
2148 } else if (status === 403) {
2149 statusText = "Forbidden";
2150 errorMessage = `Route "${routeId}" does not match URL "${pathname}"`;
2151 } else if (status === 404) {
2152 statusText = "Not Found";
2153 errorMessage = `No route matches URL "${pathname}"`;
2154 } else if (status === 405) {
2155 statusText = "Method Not Allowed";
2156 if (method && pathname && routeId) 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.`;
2157 else if (method) errorMessage = `Invalid request method "${method.toUpperCase()}"`;
2158 }
2159 return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true);
2160}
2161function dataWithResponseInitToResponse(data) {
2162 return Response.json(data.data, data.init ?? void 0);
2163}
2164function dataWithResponseInitToErrorResponse(data) {
2165 return new ErrorResponseImpl(data.init?.status ?? 500, data.init?.statusText ?? "Internal Server Error", data.data);
2166}
2167function isDataStrategyResults(result) {
2168 return result != null && typeof result === "object" && Object.entries(result).every(([key, value]) => typeof key === "string" && isDataStrategyResult(value));
2169}
2170function isDataStrategyResult(result) {
2171 return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === "data" || result.type === "error");
2172}
2173function isRedirectDataStrategyResult(result) {
2174 return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
2175}
2176function isErrorResult(result) {
2177 return result.type === "error";
2178}
2179function isRedirectResult(result) {
2180 return (result && result.type) === "redirect";
2181}
2182function isDataWithResponseInit(value) {
2183 return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
2184}
2185function isResponse(value) {
2186 return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
2187}
2188function isRedirectStatusCode(statusCode) {
2189 return redirectStatusCodes.has(statusCode);
2190}
2191function isRedirectResponse(result) {
2192 return isResponse(result) && isRedirectStatusCode(result.status) && result.headers.has("Location");
2193}
2194function isValidMethod(method) {
2195 return validRequestMethods.has(method.toUpperCase());
2196}
2197function isMutationMethod(method) {
2198 return validMutationMethods.has(method.toUpperCase());
2199}
2200function hasNakedIndexQuery(search) {
2201 return new URLSearchParams(search).getAll("index").some((v) => v === "");
2202}
2203function getTargetMatch(matches, location) {
2204 let search = typeof location === "string" ? parsePath(location).search : location.search;
2205 if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) return matches[matches.length - 1];
2206 let pathMatches = getPathContributingMatches(matches);
2207 return pathMatches[pathMatches.length - 1];
2208}
2209//#endregion
2210//#region lib/server-runtime/invariant.ts
2211function invariant(value, message) {
2212 if (value === false || value === null || typeof value === "undefined") {
2213 console.error("The following error is a bug in React Router; please open an issue! https://github.com/remix-run/react-router/issues/new/choose");
2214 throw new Error(message);
2215 }
2216}
2217//#endregion
2218//#region lib/server-runtime/headers.ts
2219function getDocumentHeadersImpl(context, getRouteHeadersFn, _defaultHeaders) {
2220 let boundaryIdx = context.errors ? context.matches.findIndex((m) => context.errors[m.route.id]) : -1;
2221 let matches = boundaryIdx >= 0 ? context.matches.slice(0, boundaryIdx + 1) : context.matches;
2222 let errorHeaders;
2223 if (boundaryIdx >= 0) {
2224 let { actionHeaders, actionData, loaderHeaders, loaderData } = context;
2225 context.matches.slice(boundaryIdx).some((match) => {
2226 let id = match.route.id;
2227 if (actionHeaders[id] && (!actionData || !actionData.hasOwnProperty(id))) errorHeaders = actionHeaders[id];
2228 else if (loaderHeaders[id] && !loaderData.hasOwnProperty(id)) errorHeaders = loaderHeaders[id];
2229 return errorHeaders != null;
2230 });
2231 }
2232 const defaultHeaders = new Headers(_defaultHeaders);
2233 return matches.reduce((parentHeaders, match, idx) => {
2234 let { id } = match.route;
2235 let loaderHeaders = context.loaderHeaders[id] || new Headers();
2236 let actionHeaders = context.actionHeaders[id] || new Headers();
2237 let includeErrorHeaders = errorHeaders != null && idx === matches.length - 1;
2238 let includeErrorCookies = includeErrorHeaders && errorHeaders !== loaderHeaders && errorHeaders !== actionHeaders;
2239 let headersFn = getRouteHeadersFn(match);
2240 if (headersFn == null) {
2241 let headers = new Headers(parentHeaders);
2242 if (includeErrorCookies) prependCookies(errorHeaders, headers);
2243 prependCookies(actionHeaders, headers);
2244 prependCookies(loaderHeaders, headers);
2245 return headers;
2246 }
2247 let headers = new Headers(typeof headersFn === "function" ? headersFn({
2248 loaderHeaders,
2249 parentHeaders,
2250 actionHeaders,
2251 errorHeaders: includeErrorHeaders ? errorHeaders : void 0
2252 }) : headersFn);
2253 if (includeErrorCookies) prependCookies(errorHeaders, headers);
2254 prependCookies(actionHeaders, headers);
2255 prependCookies(loaderHeaders, headers);
2256 prependCookies(parentHeaders, headers);
2257 return headers;
2258 }, new Headers(defaultHeaders));
2259}
2260function prependCookies(parentHeaders, childHeaders) {
2261 let parentSetCookieString = parentHeaders.get("Set-Cookie");
2262 if (parentSetCookieString) {
2263 let cookies = splitSetCookieString(parentSetCookieString);
2264 let childCookies = new Set(childHeaders.getSetCookie());
2265 cookies.forEach((cookie) => {
2266 if (!childCookies.has(cookie)) childHeaders.append("Set-Cookie", cookie);
2267 });
2268 }
2269}
2270//#endregion
2271//#region lib/server-runtime/warnings.ts
2272const alreadyWarned = {};
2273function warnOnce(condition, message) {
2274 if (!condition && !alreadyWarned[message]) {
2275 alreadyWarned[message] = true;
2276 console.warn(message);
2277 }
2278}
2279//#endregion
2280//#region lib/errors.ts
2281const ERROR_DIGEST_BASE = "REACT_ROUTER_ERROR";
2282const ERROR_DIGEST_REDIRECT = "REDIRECT";
2283const ERROR_DIGEST_ROUTE_ERROR_RESPONSE = "ROUTE_ERROR_RESPONSE";
2284function createRedirectErrorDigest(response) {
2285 return `${ERROR_DIGEST_BASE}:${ERROR_DIGEST_REDIRECT}:${JSON.stringify({
2286 status: response.status,
2287 statusText: response.statusText,
2288 location: response.headers.get("Location"),
2289 reloadDocument: response.headers.get("X-Remix-Reload-Document") === "true",
2290 replace: response.headers.get("X-Remix-Replace") === "true"
2291 })}`;
2292}
2293function createRouteErrorResponseDigest(response) {
2294 let status = 500;
2295 let statusText = "";
2296 let data;
2297 if (isDataWithResponseInit(response)) {
2298 status = response.init?.status ?? status;
2299 statusText = response.init?.statusText ?? statusText;
2300 data = response.data;
2301 } else {
2302 status = response.status;
2303 statusText = response.statusText;
2304 data = void 0;
2305 }
2306 return `${ERROR_DIGEST_BASE}:${ERROR_DIGEST_ROUTE_ERROR_RESPONSE}:${JSON.stringify({
2307 status,
2308 statusText,
2309 data
2310 })}`;
2311}
2312function getPathsWithAncestors(paths) {
2313 let result = /* @__PURE__ */ new Set();
2314 paths.forEach((path) => {
2315 if (!path.startsWith("/")) path = `/${path}`;
2316 for (let i = 1; i < path.length; i++) if (path[i] === "/") result.add(path.slice(0, i));
2317 result.add(path);
2318 });
2319 return Array.from(result);
2320}
2321const MANIFEST_MATCH_COST_LIMIT = 5e4;
2322const MANIFEST_MATCH_COST_SEGMENT_THRESHOLD = 10;
2323function shouldUseInitialRouteDiscovery(pathname, matchCost = 0) {
2324 let segmentCount = pathname.split("/").length - 1;
2325 return Math.max(segmentCount - 1, 0) * pathname.length + 1 > 7680 || segmentCount > MANIFEST_MATCH_COST_SEGMENT_THRESHOLD && segmentCount * matchCost > MANIFEST_MATCH_COST_LIMIT;
2326}
2327//#endregion
2328//#region lib/actions.ts
2329function throwIfPotentialCSRFAttack(request, allowedActionOrigins) {
2330 let originHeader = request.headers.get("origin");
2331 let originDomain = null;
2332 let originUrl = null;
2333 try {
2334 if (typeof originHeader === "string" && originHeader !== "null") {
2335 originUrl = new URL(originHeader);
2336 originDomain = originUrl.host;
2337 } else originDomain = originHeader;
2338 } catch {
2339 throw new Error(`\`origin\` header is not a valid URL. Aborting the action.`);
2340 }
2341 let requestUrl = new URL(request.url);
2342 let originMatchesRequest = originUrl ? originUrl.origin === requestUrl.origin : originDomain === requestUrl.host;
2343 if (originDomain && !originMatchesRequest) {
2344 if (!isAllowedOrigin(originDomain, allowedActionOrigins)) throw new Error("The `request.url` origin does not match `origin` header from a forwarded action request. Aborting the action.");
2345 }
2346}
2347function matchWildcardDomain(domain, pattern) {
2348 const domainParts = domain.split(".");
2349 const patternParts = pattern.split(".");
2350 if (patternParts.length < 1) return false;
2351 if (domainParts.length < patternParts.length) return false;
2352 while (patternParts.length) {
2353 const patternPart = patternParts.pop();
2354 const domainPart = domainParts.pop();
2355 switch (patternPart) {
2356 case "": return false;
2357 case "*": if (domainPart) continue;
2358 else return false;
2359 case "**":
2360 if (patternParts.length > 0) return false;
2361 return domainPart !== void 0;
2362 case void 0:
2363 default: if (domainPart !== patternPart) return false;
2364 }
2365 }
2366 return domainParts.length === 0;
2367}
2368function isAllowedOrigin(originDomain, allowedActionOrigins = []) {
2369 return allowedActionOrigins.some((allowedOrigin) => allowedOrigin && (allowedOrigin === originDomain || matchWildcardDomain(originDomain, allowedOrigin)));
2370}
2371//#endregion
2372//#region lib/server-runtime/urls.ts
2373function getNormalizedPath(request) {
2374 let url = new URL(request.url);
2375 let pathname = url.pathname;
2376 if (pathname.endsWith("/_.data")) pathname = pathname.replace(/_\.data$/, "");
2377 else pathname = pathname.replace(/\.data$/, "");
2378 let searchParams = new URLSearchParams(url.search);
2379 searchParams.delete("_routes");
2380 let search = searchParams.toString();
2381 if (search) search = `?${search}`;
2382 return {
2383 pathname,
2384 search,
2385 hash: ""
2386 };
2387}
2388//#endregion
2389//#region lib/rsc/server.rsc.ts
2390const Outlet$2 = Outlet$1;
2391const WithComponentProps = UNSAFE_WithComponentProps;
2392const WithErrorBoundaryProps = UNSAFE_WithErrorBoundaryProps;
2393const WithHydrateFallbackProps = UNSAFE_WithHydrateFallbackProps;
2394const globalVar = typeof globalThis !== "undefined" ? globalThis : global;
2395const ServerStorage = globalVar.___reactRouterServerStorage___ ??= new AsyncLocalStorage();
2396function getRequest() {
2397 const ctx = ServerStorage.getStore();
2398 if (!ctx) throw new Error("getRequest must be called from within a React Server render context");
2399 return ctx.request;
2400}
2401const redirect = (...args) => {
2402 const response = redirect$1(...args);
2403 const ctx = ServerStorage.getStore();
2404 if (ctx && ctx.runningAction) ctx.redirect = response;
2405 return response;
2406};
2407const redirectDocument = (...args) => {
2408 const response = redirectDocument$1(...args);
2409 const ctx = ServerStorage.getStore();
2410 if (ctx && ctx.runningAction) ctx.redirect = response;
2411 return response;
2412};
2413const replace = (...args) => {
2414 const response = replace$1(...args);
2415 const ctx = ServerStorage.getStore();
2416 if (ctx && ctx.runningAction) ctx.redirect = response;
2417 return response;
2418};
2419const cachedResolvePromise = React.cache(async (resolve) => {
2420 return Promise.allSettled([resolve]).then((r) => r[0]);
2421});
2422const Await = (async (props) => {
2423 invariant$1("resolve" in props !== "unstable_promise" in props, "<Await> requires exactly one of `resolve` or `unstable_promise`");
2424 let { children, errorElement } = props;
2425 let usePromise = "unstable_promise" in props;
2426 let resolved = await cachedResolvePromise(usePromise ? props.unstable_promise : props.resolve);
2427 if (resolved.status === "rejected" && !errorElement) throw resolved.reason;
2428 if (resolved.status === "rejected") return React.createElement(UNSAFE_AwaitContextProvider, {
2429 children: React.createElement(React.Fragment, null, errorElement),
2430 value: usePromise ? resolved : {
2431 _tracked: true,
2432 _error: resolved.reason
2433 }
2434 });
2435 const toRender = typeof children === "function" ? children(resolved.value) : children;
2436 return React.createElement(UNSAFE_AwaitContextProvider, {
2437 children: toRender,
2438 value: usePromise ? resolved : {
2439 _tracked: true,
2440 _data: resolved.value
2441 }
2442 });
2443});
2444/**
2445* Matches the given routes to a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
2446* and returns an [RSC](https://react.dev/reference/rsc/server-components)
2447* [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2448* encoding an {@link unstable_RSCPayload} for consumption by an [RSC](https://react.dev/reference/rsc/server-components)
2449* enabled client router.
2450*
2451* Treat every React Server Function as a public endpoint. Server Functions are
2452* not inherently associated with a route. Any route middleware that runs is
2453* selected from the URL used to call a Server Function, but the client controls
2454* both the Server Function identifier and the URL. Perform all access control
2455* checks within each Server Function, or use a route action for
2456* middleware-driven access control.
2457*
2458* @example
2459* import {
2460* createTemporaryReferenceSet,
2461* decodeAction,
2462* decodeReply,
2463* loadServerAction,
2464* renderToReadableStream,
2465* } from "@vitejs/plugin-rsc/rsc";
2466* import { unstable_matchRSCServerRequest as matchRSCServerRequest } from "react-router";
2467*
2468* matchRSCServerRequest({
2469* createTemporaryReferenceSet,
2470* decodeAction,
2471* decodeFormState,
2472* decodeReply,
2473* loadServerAction,
2474* request,
2475* routes: routes(),
2476* generateResponse(match) {
2477* return new Response(
2478* renderToReadableStream(match.payload),
2479* {
2480* status: match.statusCode,
2481* headers: match.headers,
2482* }
2483* );
2484* },
2485* });
2486*
2487* @name unstable_matchRSCServerRequest
2488* @public
2489* @category RSC
2490* @mode data
2491* @param opts Options
2492* @param opts.allowedActionOrigins Origin patterns that are allowed to execute actions.
2493* @param opts.basename The basename to use when matching the request.
2494* @param opts.createTemporaryReferenceSet A function that returns a temporary
2495* reference set for the request, used to track temporary references in the [RSC](https://react.dev/reference/rsc/server-components)
2496* stream.
2497* @param opts.decodeAction Your `react-server-dom-xyz/server`'s `decodeAction`
2498* function, responsible for loading a server action.
2499* @param opts.decodeFormState A function responsible for decoding form state for
2500* progressively enhanceable forms with React's [`useActionState`](https://react.dev/reference/react/useActionState)
2501* using your `react-server-dom-xyz/server`'s `decodeFormState`.
2502* @param opts.decodeReply Your `react-server-dom-xyz/server`'s `decodeReply`
2503* function, used to decode the server function's arguments and bind them to the
2504* implementation for invocation by the router.
2505* @param opts.generateResponse A function responsible for using your
2506* `renderToReadableStream` to generate a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2507* encoding the {@link unstable_RSCPayload}.
2508* @param opts.loadServerAction Your `react-server-dom-xyz/server`'s
2509* `loadServerAction` function, used to load a server action by ID.
2510* @param opts.clientVersion A version derived from the client build output used
2511* to detect stale clients during lazy route discovery.
2512* @param opts.onError An optional error handler that will be called with any
2513* errors that occur during the request processing. Defaults to logging errors
2514* with `console.error` unless the request was aborted.
2515* @param opts.request The [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
2516* to match against.
2517* @param opts.requestContext An instance of {@link RouterContextProvider}
2518* that should be created per request, to be passed to [`action`](../../start/data/route-object#action)s,
2519* [`loader`](../../start/data/route-object#loader)s and [middleware](../../how-to/middleware).
2520* @param opts.routeDiscovery The route discovery configuration, used to determine how the router should discover new routes during navigations.
2521* @param opts.routes Your {@link unstable_RSCRouteConfigEntry | route definitions}.
2522* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2523* that contains the [RSC](https://react.dev/reference/rsc/server-components)
2524* data for hydration.
2525*/
2526async function matchRSCServerRequest({ allowedActionOrigins, createTemporaryReferenceSet, basename, decodeReply, requestContext, routeDiscovery, loadServerAction, decodeAction, decodeFormState, clientVersion, onError, request, routes, generateResponse: encodeResponse }) {
2527 let generateResponse = (match, options) => {
2528 let response = encodeResponse(match, options);
2529 response.headers.set("Content-Type", "text/x-component");
2530 return response;
2531 };
2532 let url = new URL(request.url);
2533 onError ??= (error) => {
2534 if (!request.signal.aborted) console.error(isRouteErrorResponse(error) && error.error ? error.error : error);
2535 };
2536 basename = basename || "/";
2537 let normalizedPath = url.pathname;
2538 if (url.pathname.endsWith("/_.rsc")) normalizedPath = url.pathname.replace(/_\.rsc$/, "");
2539 else if (url.pathname.endsWith(".rsc")) normalizedPath = url.pathname.replace(/\.rsc$/, "");
2540 if (stripBasename(normalizedPath, basename) !== "/" && normalizedPath.endsWith("/")) normalizedPath = normalizedPath.slice(0, -1);
2541 url.pathname = normalizedPath;
2542 basename = basename.length > normalizedPath.length ? normalizedPath : basename;
2543 let routerRequest = new Request(url.toString(), {
2544 method: request.method,
2545 headers: request.headers,
2546 body: request.body,
2547 signal: request.signal,
2548 duplex: request.body ? "half" : void 0
2549 });
2550 const temporaryReferences = createTemporaryReferenceSet();
2551 const requestUrl = new URL(request.url);
2552 if (isManifestRequest(requestUrl)) return await generateManifestResponse(routes, basename, request, generateResponse, temporaryReferences, routeDiscovery, clientVersion);
2553 let isDataRequest = isReactServerRequest(requestUrl);
2554 let staticHandler = createStaticHandler(routes, { basename });
2555 let matches = staticHandler.match(url.pathname);
2556 if (matches) await Promise.all(matches.map((m) => explodeLazyRoute(m.route)));
2557 const leafMatch = matches?.[matches.length - 1];
2558 if (!isDataRequest && leafMatch && !leafMatch.route.Component && !leafMatch.route.ErrorBoundary) return normalizeResourceResponse(request, await generateResourceResponse(routerRequest, staticHandler, leafMatch.route.id, requestContext, onError));
2559 let response = await generateRenderResponse(routerRequest, staticHandler, basename, isDataRequest, decodeReply, requestContext, loadServerAction, decodeAction, decodeFormState, onError, generateResponse, temporaryReferences, allowedActionOrigins, routeDiscovery, clientVersion);
2560 response.headers.set("X-Remix-Response", "yes");
2561 return normalizeResourceResponse(request, response);
2562}
2563function normalizeResourceResponse(request, response) {
2564 if (request.method === "HEAD" && response.headers.get("React-Router-Resource") === "true") {
2565 response.body?.cancel().catch(() => {});
2566 return new Response(null, {
2567 status: response.status,
2568 statusText: response.statusText,
2569 headers: response.headers
2570 });
2571 }
2572 return response;
2573}
2574async function generateManifestResponse(routes, basename, request, generateResponse, temporaryReferences, routeDiscovery, clientVersion) {
2575 let url = new URL(request.url);
2576 if (url.toString().length > 7680) return new Response(null, {
2577 statusText: "Bad Request",
2578 status: 400
2579 });
2580 if (clientVersion !== void 0 && clientVersion !== url.searchParams.get("version")) return new Response(null, {
2581 status: 204,
2582 headers: { "X-Remix-Reload-Document": "true" }
2583 });
2584 if (routeDiscovery?.mode === "initial") {
2585 let payload = {
2586 type: "manifest",
2587 patches: getAllRoutePatches(routes, basename)
2588 };
2589 return generateResponse({
2590 statusCode: 200,
2591 headers: new Headers({
2592 "Content-Type": "text/x-component",
2593 Vary: "Content-Type"
2594 }),
2595 payload
2596 }, {
2597 temporaryReferences,
2598 onError: defaultOnError
2599 });
2600 }
2601 let pathParam = url.searchParams.get("paths");
2602 let pathnames = pathParam ? pathParam.split(",").filter(Boolean) : [url.pathname.replace(/\.manifest$/, "")];
2603 let staticHandler = routes.length > 0 ? createStaticHandler(routes, { basename }) : void 0;
2604 let routeIds = /* @__PURE__ */ new Set();
2605 let matchedRoutes = staticHandler ? pathnames.flatMap((pathname) => {
2606 let pathnameMatches = staticHandler.match(pathname);
2607 return pathnameMatches?.map((m, i) => ({
2608 ...m.route,
2609 parentId: pathnameMatches[i - 1]?.route.id
2610 })) ?? [];
2611 }).filter((route) => {
2612 if (!routeIds.has(route.id)) {
2613 routeIds.add(route.id);
2614 return true;
2615 }
2616 return false;
2617 }) : [];
2618 let payload = {
2619 type: "manifest",
2620 patches: Promise.all([...matchedRoutes.map((route) => getManifestRoute(route)), staticHandler ? getAdditionalRoutePatches(pathnames, staticHandler, Array.from(routeIds)) : Promise.resolve([])]).then((r) => r.flat(1))
2621 };
2622 return generateResponse({
2623 statusCode: 200,
2624 headers: new Headers({ "Content-Type": "text/x-component" }),
2625 payload
2626 }, {
2627 temporaryReferences,
2628 onError: defaultOnError
2629 });
2630}
2631function prependBasenameToRedirectResponse(response, basename = "/") {
2632 if (basename === "/") return response;
2633 let redirect = response.headers.get("Location");
2634 if (!redirect || isAbsoluteUrl(redirect)) return response;
2635 response.headers.set("Location", prependBasename({
2636 basename,
2637 pathname: redirect
2638 }));
2639 return response;
2640}
2641async function processServerAction(request, basename, decodeReply, loadServerAction, decodeAction, decodeFormState, onError, temporaryReferences) {
2642 const getRevalidationRequest = () => new Request(request.url, {
2643 method: "GET",
2644 headers: request.headers,
2645 signal: request.signal
2646 });
2647 const isFormRequest = canDecodeWithFormData(request.headers.get("Content-Type"));
2648 const actionId = request.headers.get("rsc-action-id");
2649 if (actionId) {
2650 if (!decodeReply || !loadServerAction) throw new Error("Cannot handle enhanced server action without decodeReply and loadServerAction functions");
2651 const actionArgs = await decodeReply(isFormRequest ? await request.formData() : await request.text(), { temporaryReferences });
2652 const serverAction = (await loadServerAction(actionId)).bind(null, ...actionArgs);
2653 let actionResult = Promise.resolve(serverAction());
2654 try {
2655 await actionResult;
2656 } catch (error) {
2657 if (isResponse(error)) return error;
2658 onError?.(error);
2659 }
2660 let maybeFormData = actionArgs.length === 1 ? actionArgs[0] : actionArgs[1];
2661 let skipRevalidation = (maybeFormData && typeof maybeFormData === "object" && maybeFormData instanceof FormData ? maybeFormData : null)?.has("$SKIP_REVALIDATION") ?? false;
2662 return {
2663 actionResult,
2664 revalidationRequest: getRevalidationRequest(),
2665 skipRevalidation
2666 };
2667 } else if (isFormRequest) {
2668 const formData = await request.clone().formData();
2669 if (Array.from(formData.keys()).some((k) => k.startsWith("$ACTION_"))) {
2670 if (!decodeAction) throw new Error("Cannot handle form actions without a decodeAction function");
2671 const action = await decodeAction(formData);
2672 let formState = void 0;
2673 try {
2674 let result = await action();
2675 if (isRedirectResponse(result)) result = prependBasenameToRedirectResponse(result, basename);
2676 formState = await decodeFormState?.(result, formData);
2677 } catch (error) {
2678 if (isRedirectResponse(error)) return prependBasenameToRedirectResponse(error, basename);
2679 if (isResponse(error)) return error;
2680 onError?.(error);
2681 }
2682 return {
2683 formState,
2684 revalidationRequest: getRevalidationRequest(),
2685 skipRevalidation: false
2686 };
2687 }
2688 }
2689}
2690async function generateResourceResponse(request, staticHandler, routeId, requestContext, onError) {
2691 try {
2692 return tagResourceResponse(await staticHandler.queryRoute(request, {
2693 routeId,
2694 requestContext,
2695 async generateMiddlewareResponse(queryRoute) {
2696 try {
2697 return tagResourceResponse(await queryRoute(request));
2698 } catch (error) {
2699 return generateErrorResponse(error);
2700 }
2701 },
2702 normalizePath: (r) => getNormalizedPath(r)
2703 }));
2704 } catch (error) {
2705 return generateErrorResponse(error);
2706 }
2707 function generateErrorResponse(error) {
2708 let response;
2709 if (isResponse(error)) response = error;
2710 else if (isRouteErrorResponse(error)) {
2711 onError?.(error);
2712 const errorMessage = typeof error.data === "string" ? error.data : error.statusText;
2713 response = new Response(errorMessage, {
2714 status: error.status,
2715 statusText: error.statusText
2716 });
2717 } else {
2718 onError?.(error);
2719 response = new Response("Internal Server Error", { status: 500 });
2720 }
2721 return tagResourceResponse(response);
2722 }
2723}
2724function tagResourceResponse(response) {
2725 const headers = new Headers(response.headers);
2726 headers.set("React-Router-Resource", "true");
2727 return new Response(response.body, {
2728 status: response.status,
2729 statusText: response.statusText,
2730 headers
2731 });
2732}
2733async function generateRenderResponse(request, staticHandler, basename, isDataRequest, decodeReply, requestContext, loadServerAction, decodeAction, decodeFormState, onError, generateResponse, temporaryReferences, allowedActionOrigins, routeDiscovery, clientVersion) {
2734 if (isMutationMethod(request.method)) try {
2735 throwIfPotentialCSRFAttack(request, allowedActionOrigins);
2736 } catch (error) {
2737 onError?.(error);
2738 return tagResourceResponse(new Response("Bad Request", { status: 400 }));
2739 }
2740 let statusCode = 200;
2741 let url = new URL(request.url);
2742 let isSubmission = isMutationMethod(request.method);
2743 let routeIdsToLoad = !isSubmission && url.searchParams.has("_routes") ? url.searchParams.get("_routes").split(",") : null;
2744 let actionResult;
2745 let handledSubmission = false;
2746 const ctx = {
2747 request,
2748 runningAction: false
2749 };
2750 const result = await ServerStorage.run(ctx, () => staticHandler.query(request, {
2751 requestContext,
2752 skipLoaderErrorBubbling: isDataRequest,
2753 skipRevalidation: isSubmission,
2754 ...routeIdsToLoad ? { filterMatchesToLoad: (m) => routeIdsToLoad.includes(m.route.id) } : {},
2755 normalizePath: (r) => getNormalizedPath(r),
2756 async generateMiddlewareResponse(query) {
2757 let formState;
2758 let skipRevalidation = false;
2759 if (isSubmission && !handledSubmission) {
2760 handledSubmission = true;
2761 ctx.runningAction = true;
2762 let result = await processServerAction(request, basename, decodeReply, loadServerAction, decodeAction, decodeFormState, onError, temporaryReferences).finally(() => {
2763 ctx.runningAction = false;
2764 });
2765 if (isResponse(result)) return generateRedirectResponse(result, actionResult, basename, isDataRequest, generateResponse, temporaryReferences, result === ctx.redirect ? void 0 : ctx.redirect?.headers);
2766 skipRevalidation = result?.skipRevalidation ?? false;
2767 actionResult = result?.actionResult;
2768 formState = result?.formState;
2769 request = result?.revalidationRequest ?? request;
2770 if (ctx.redirect) return generateRedirectResponse(ctx.redirect, actionResult, basename, isDataRequest, generateResponse, temporaryReferences, void 0);
2771 }
2772 let staticContext = await query(request, skipRevalidation ? { filterMatchesToLoad: () => false } : void 0);
2773 if (isResponse(staticContext)) return generateRedirectResponse(staticContext, actionResult, basename, isDataRequest, generateResponse, temporaryReferences, ctx.redirect?.headers);
2774 if (staticContext.errors) Object.values(staticContext.errors).forEach((error) => {
2775 if (!isRouteErrorResponse(error) || error.error) onError?.(error);
2776 });
2777 return generateStaticContextResponse(staticHandler, basename, generateResponse, statusCode, routeIdsToLoad, isDataRequest, isSubmission, actionResult, formState, staticContext, temporaryReferences, skipRevalidation, ctx.redirect?.headers, routeDiscovery, clientVersion);
2778 }
2779 }));
2780 if (isRedirectResponse(result)) return generateRedirectResponse(result, actionResult, basename, isDataRequest, generateResponse, temporaryReferences, ctx.redirect?.headers);
2781 invariant(isResponse(result), "Expected a response from query");
2782 if (result.headers.get("Content-Type")?.split(";")[0].trim().toLowerCase() !== "text/x-component") return tagResourceResponse(result);
2783 return result;
2784}
2785function generateRedirectResponse(response, actionResult, basename, isDataRequest, generateResponse, temporaryReferences, sideEffectRedirectHeaders) {
2786 let redirect = response.headers.get("Location");
2787 if (isDataRequest && basename) redirect = stripBasename(redirect, basename) || redirect;
2788 let payload = {
2789 type: "redirect",
2790 location: redirect,
2791 reload: response.headers.get("X-Remix-Reload-Document") === "true",
2792 replace: response.headers.get("X-Remix-Replace") === "true",
2793 status: response.status,
2794 actionResult
2795 };
2796 let headers = new Headers(sideEffectRedirectHeaders === response.headers ? void 0 : sideEffectRedirectHeaders);
2797 for (const [key, value] of response.headers.entries()) headers.append(key, value);
2798 headers.delete("Location");
2799 headers.delete("X-Remix-Reload-Document");
2800 headers.delete("X-Remix-Replace");
2801 headers.delete("Content-Length");
2802 headers.set("Content-Type", "text/x-component");
2803 return generateResponse({
2804 statusCode: 202,
2805 headers,
2806 payload
2807 }, {
2808 temporaryReferences,
2809 onError: defaultOnError
2810 });
2811}
2812async function generateStaticContextResponse(staticHandler, basename, generateResponse, statusCode, routeIdsToLoad, isDataRequest, isSubmission, actionResult, formState, staticContext, temporaryReferences, skipRevalidation, sideEffectRedirectHeaders, routeDiscovery, clientVersion) {
2813 statusCode = staticContext.statusCode ?? statusCode;
2814 if (staticContext.errors) staticContext.errors = Object.fromEntries(Object.entries(staticContext.errors).map(([key, error]) => [key, isRouteErrorResponse(error) ? Object.fromEntries(Object.entries(error)) : error]));
2815 staticContext.matches.forEach((m) => {
2816 const routeHasNoLoaderData = staticContext.loaderData[m.route.id] === void 0;
2817 const routeHasError = Boolean(staticContext.errors && m.route.id in staticContext.errors);
2818 if (routeHasNoLoaderData && !routeHasError) staticContext.loaderData[m.route.id] = null;
2819 });
2820 let headers = getDocumentHeadersImpl(staticContext, (match) => match.route.headers, sideEffectRedirectHeaders);
2821 headers.delete("Content-Length");
2822 const baseRenderPayload = {
2823 type: "render",
2824 basename: staticContext.basename,
2825 clientVersion,
2826 routeDiscovery: routeDiscovery ?? { mode: "lazy" },
2827 actionData: staticContext.actionData,
2828 errors: staticContext.errors,
2829 loaderData: staticContext.loaderData,
2830 location: staticContext.location,
2831 formState
2832 };
2833 const renderPayloadPromise = () => getRenderPayload(baseRenderPayload, staticHandler, basename, routeIdsToLoad, isDataRequest, staticContext, routeDiscovery);
2834 let payload;
2835 if (actionResult) payload = {
2836 type: "action",
2837 actionResult,
2838 rerender: skipRevalidation ? void 0 : renderPayloadPromise()
2839 };
2840 else if (isSubmission && isDataRequest) payload = {
2841 ...baseRenderPayload,
2842 matches: [],
2843 patches: Promise.resolve([])
2844 };
2845 else payload = await renderPayloadPromise();
2846 return generateResponse({
2847 statusCode,
2848 headers,
2849 payload
2850 }, {
2851 temporaryReferences,
2852 onError: defaultOnError
2853 });
2854}
2855async function getRenderPayload(baseRenderPayload, staticHandler, basename, routeIdsToLoad, isDataRequest, staticContext, routeDiscovery) {
2856 let routes = staticHandler.dataRoutes;
2857 let deepestRenderedRouteIdx = staticContext.matches.length - 1;
2858 let parentIds = {};
2859 staticContext.matches.forEach((m, i) => {
2860 if (i > 0) parentIds[m.route.id] = staticContext.matches[i - 1].route.id;
2861 if (staticContext.errors && m.route.id in staticContext.errors && deepestRenderedRouteIdx > i) deepestRenderedRouteIdx = i;
2862 });
2863 let matchesPromise = Promise.all(staticContext.matches.map((match, i) => {
2864 let isBelowErrorBoundary = i > deepestRenderedRouteIdx;
2865 let parentId = parentIds[match.route.id];
2866 return getRSCRouteMatch({
2867 staticContext,
2868 match,
2869 routeIdsToLoad,
2870 isBelowErrorBoundary,
2871 parentId
2872 });
2873 }));
2874 let pathname = staticContext.location.pathname;
2875 let useInitialRouteDiscovery = routeDiscovery?.mode === "initial" && !isDataRequest || shouldUseInitialRouteDiscovery(pathname, staticHandler._matchCost);
2876 let patches;
2877 if (useInitialRouteDiscovery) patches = getAllRoutePatches(routes, basename).then((patches) => patches.filter((patch) => !staticContext.matches.some((m) => m.route.id === patch.id)));
2878 else patches = getAdditionalRoutePatches(getPathsWithAncestors([pathname]).slice(0, -1), staticHandler, staticContext.matches.map((m) => m.route.id));
2879 return {
2880 ...baseRenderPayload,
2881 routeDiscovery: useInitialRouteDiscovery ? { mode: "initial" } : baseRenderPayload.routeDiscovery,
2882 matches: await matchesPromise,
2883 patches
2884 };
2885}
2886async function getRSCRouteMatch({ staticContext, match, isBelowErrorBoundary, routeIdsToLoad, parentId }) {
2887 const route = match.route;
2888 await explodeLazyRoute(route);
2889 const Layout = route.Layout || React.Fragment;
2890 const Component = route.Component;
2891 const ErrorBoundary = route.ErrorBoundary;
2892 const HydrateFallback = route.HydrateFallback;
2893 const loaderData = staticContext.loaderData[route.id];
2894 const actionData = staticContext.actionData?.[route.id];
2895 const params = match.params;
2896 let element = void 0;
2897 let shouldLoadRoute = !routeIdsToLoad || routeIdsToLoad.includes(route.id);
2898 if (Component && shouldLoadRoute) element = !isBelowErrorBoundary ? React.createElement(Layout, null, isClientReference(Component) ? React.createElement(WithComponentProps, { children: React.createElement(Component) }) : React.createElement(Component, {
2899 loaderData,
2900 actionData,
2901 params,
2902 matches: staticContext.matches.map((match) => convertRouteMatchToUiMatch(match, staticContext.loaderData))
2903 })) : React.createElement(Outlet$2);
2904 let error = void 0;
2905 if (ErrorBoundary && staticContext.errors) error = staticContext.errors[route.id];
2906 const errorElement = ErrorBoundary ? React.createElement(Layout, null, isClientReference(ErrorBoundary) ? React.createElement(WithErrorBoundaryProps, { children: React.createElement(ErrorBoundary) }) : React.createElement(ErrorBoundary, {
2907 loaderData,
2908 actionData,
2909 params,
2910 error
2911 })) : void 0;
2912 const hydrateFallbackElement = HydrateFallback ? React.createElement(Layout, null, isClientReference(HydrateFallback) ? React.createElement(WithHydrateFallbackProps, { children: React.createElement(HydrateFallback) }) : React.createElement(HydrateFallback, {
2913 loaderData,
2914 actionData,
2915 params
2916 })) : void 0;
2917 const hmrRoute = route;
2918 return {
2919 clientAction: route.clientAction,
2920 clientLoader: route.clientLoader,
2921 clientMiddleware: route.clientMiddleware,
2922 element,
2923 errorElement,
2924 handle: route.handle,
2925 hasAction: !!route.action,
2926 hasComponent: !!Component,
2927 hasLoader: !!route.loader,
2928 hydrateFallbackElement,
2929 id: route.id,
2930 index: "index" in route ? route.index : void 0,
2931 links: route.links,
2932 meta: route.meta,
2933 params,
2934 parentId,
2935 path: route.path,
2936 pathname: match.pathname,
2937 pathnameBase: match.pathnameBase,
2938 shouldRevalidate: route.shouldRevalidate,
2939 ...hmrRoute.__ensureClientRouteModuleForHMR ? { __ensureClientRouteModuleForHMR: hmrRoute.__ensureClientRouteModuleForHMR } : {}
2940 };
2941}
2942async function getManifestRoute(route) {
2943 await explodeLazyRoute(route);
2944 const Layout = route.Layout || React.Fragment;
2945 const errorElement = route.ErrorBoundary ? React.createElement(Layout, null, React.createElement(route.ErrorBoundary)) : void 0;
2946 return {
2947 clientAction: route.clientAction,
2948 clientLoader: route.clientLoader,
2949 clientMiddleware: route.clientMiddleware,
2950 handle: route.handle,
2951 hasAction: !!route.action,
2952 hasComponent: !!route.Component,
2953 errorElement,
2954 hasLoader: !!route.loader,
2955 id: route.id,
2956 parentId: route.parentId,
2957 path: route.path,
2958 index: "index" in route ? route.index : void 0,
2959 links: route.links,
2960 meta: route.meta
2961 };
2962}
2963async function explodeLazyRoute(route) {
2964 if ("lazy" in route && route.lazy) {
2965 let { default: lazyDefaultExport, Component: lazyComponentExport, ...lazyProperties } = await route.lazy();
2966 let Component = lazyComponentExport || lazyDefaultExport;
2967 if (Component && !route.Component) route.Component = Component;
2968 for (let [k, v] of Object.entries(lazyProperties)) if (k !== "id" && k !== "path" && k !== "index" && k !== "children" && route[k] == null) route[k] = v;
2969 route.lazy = void 0;
2970 }
2971}
2972async function getAllRoutePatches(routes, basename) {
2973 let patches = [];
2974 async function traverse(route, parentId) {
2975 let manifestRoute = await getManifestRoute({
2976 ...route,
2977 parentId
2978 });
2979 patches.push(manifestRoute);
2980 if ("children" in route && route.children?.length) for (let child of route.children) await traverse(child, route.id);
2981 }
2982 for (let route of routes) await traverse(route, void 0);
2983 return patches.filter((p) => !!p.parentId);
2984}
2985async function getAdditionalRoutePatches(pathnames, staticHandler, matchedRouteIds) {
2986 let patchRouteMatches = /* @__PURE__ */ new Map();
2987 let matchedPaths = /* @__PURE__ */ new Set();
2988 for (const pathname of pathnames) {
2989 if (matchedPaths.has(pathname)) continue;
2990 matchedPaths.add(pathname);
2991 let matches = staticHandler.match(pathname) || [];
2992 matches.forEach((m, i) => {
2993 if (patchRouteMatches.get(m.route.id)) return;
2994 patchRouteMatches.set(m.route.id, {
2995 ...m.route,
2996 parentId: matches[i - 1]?.route.id
2997 });
2998 });
2999 }
3000 return await Promise.all([...patchRouteMatches.values()].filter((route) => !matchedRouteIds.some((id) => id === route.id)).map((route) => getManifestRoute(route)));
3001}
3002function isReactServerRequest(url) {
3003 return url.pathname.endsWith(".rsc");
3004}
3005function isManifestRequest(url) {
3006 return url.pathname.endsWith(".manifest");
3007}
3008function defaultOnError(error) {
3009 if (isRedirectResponse(error)) return createRedirectErrorDigest(error);
3010 if (isResponse(error) || isDataWithResponseInit(error)) return createRouteErrorResponseDigest(error);
3011}
3012function isClientReference(x) {
3013 try {
3014 return x.$$typeof === Symbol.for("react.client.reference");
3015 } catch {
3016 return false;
3017 }
3018}
3019function canDecodeWithFormData(contentType) {
3020 if (!contentType) return false;
3021 return contentType.match(/\bapplication\/x-www-form-urlencoded\b/) || contentType.match(/\bmultipart\/form-data\b/);
3022}
3023//#endregion
3024//#region lib/href.ts
3025function stringify(p) {
3026 return p == null ? "" : typeof p === "string" ? p : String(p);
3027}
3028/**
3029* Returns a resolved URL path for the specified route.
3030*
3031* Param values are percent-encoded for use in a path segment: characters that
3032* would change the URL structure (`/`, `?`, `#`, `%`, whitespace, non-ASCII)
3033* are escaped, while characters that RFC 3986 allows literally in a path
3034* segment (`$ & + , ; = : @`) are kept as-is. Note this differs from query-string
3035* encoding (`encodeURIComponent`/`URLSearchParams`), where those characters are
3036* delimiters and must be escaped. Splat (`*`) values are encoded per segment,
3037* preserving `/` separators.
3038*
3039* See [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3)
3040*
3041* @example
3042* const h = href("/:lang?/about", { lang: "en" })
3043* // -> `/en/about`
3044*
3045* <Link to={href("/products/:id", { id: "abc123" })} />
3046*
3047* @public
3048* @category Utils
3049* @mode framework
3050* @param path The route path to resolve
3051* @param args The route params to use when resolving the path
3052* @returns The resolved URL path
3053*/
3054function href(path, ...args) {
3055 let params = args[0];
3056 let result = trimTrailingSplat(path).replace(/\/:([\w-]+)(\?)?/g, (_, param, questionMark) => {
3057 const isRequired = questionMark === void 0;
3058 const value = params?.[param];
3059 if (isRequired && value == null) throw new Error(`Path '${path}' requires param '${param}' but it was not provided`);
3060 return value == null ? "" : "/" + encodePathParam(stringify(value));
3061 });
3062 if (path.endsWith("*")) {
3063 const value = params?.["*"];
3064 if (value != null) result += "/" + stringify(value).split("/").map(encodePathParam).join("/");
3065 }
3066 return result.replace(/^\/{2,}/, "/") || "/";
3067}
3068/**
3069* Removes a trailing splat and any number of slashes from the end of the path.
3070*
3071* Benchmarked to be faster than `path.replace(/\/*\*?$/, "")`, which backtracks.
3072*/
3073function trimTrailingSplat(path) {
3074 let i = path.length - 1;
3075 let char = path[i];
3076 if (char !== "*" && char !== "/") return path;
3077 i--;
3078 for (; i >= 0; i--) if (path[i] !== "/") break;
3079 return path.slice(0, i + 1);
3080}
3081//#endregion
3082//#region lib/server-runtime/crypto.ts
3083const encoder = /* @__PURE__ */ new TextEncoder();
3084const sign = async (value, secret) => {
3085 let data = encoder.encode(value);
3086 let key = await createKey(secret, ["sign"]);
3087 let signature = await crypto.subtle.sign("HMAC", key, data);
3088 let hash = btoa(String.fromCharCode(...new Uint8Array(signature))).replace(/=+$/, "");
3089 return value + "." + hash;
3090};
3091const unsign = async (cookie, secret) => {
3092 let index = cookie.lastIndexOf(".");
3093 let value = cookie.slice(0, index);
3094 let hash = cookie.slice(index + 1);
3095 let data = encoder.encode(value);
3096 let key = await createKey(secret, ["verify"]);
3097 try {
3098 let signature = byteStringToUint8Array(atob(hash));
3099 return await crypto.subtle.verify("HMAC", key, signature, data) ? value : false;
3100 } catch {
3101 return false;
3102 }
3103};
3104const createKey = async (secret, usages) => crypto.subtle.importKey("raw", encoder.encode(secret), {
3105 name: "HMAC",
3106 hash: "SHA-256"
3107}, false, usages);
3108function byteStringToUint8Array(byteString) {
3109 let array = new Uint8Array(byteString.length);
3110 for (let i = 0; i < byteString.length; i++) array[i] = byteString.charCodeAt(i);
3111 return array;
3112}
3113//#endregion
3114//#region lib/server-runtime/cookies.ts
3115/**
3116* Creates a logical container for managing a browser cookie from the server.
3117*
3118* @public
3119* @category Utils
3120* @mode framework
3121* @mode data
3122* @param name The name of the cookie.
3123* @param cookieOptions Options for parsing and serializing the cookie.
3124* @returns A {@link Cookie} object for parsing and serializing the cookie.
3125*/
3126const createCookie = (name, cookieOptions = {}) => {
3127 let { secrets = [], ...options } = {
3128 path: "/",
3129 sameSite: "lax",
3130 ...cookieOptions
3131 };
3132 warnOnceAboutExpiresCookie(name, options.expires);
3133 return {
3134 get name() {
3135 return name;
3136 },
3137 get isSigned() {
3138 return secrets.length > 0;
3139 },
3140 get expires() {
3141 return typeof options.maxAge !== "undefined" ? new Date(Date.now() + options.maxAge * 1e3) : options.expires;
3142 },
3143 async parse(cookieHeader, parseOptions) {
3144 if (!cookieHeader) return null;
3145 let cookies = parse(cookieHeader, {
3146 ...options,
3147 ...parseOptions
3148 });
3149 if (name in cookies) {
3150 let value = cookies[name];
3151 if (typeof value === "string" && value !== "") return await decodeCookieValue(value, secrets);
3152 else return "";
3153 } else return null;
3154 },
3155 async serialize(value, serializeOptions) {
3156 return serialize(name, value === "" ? "" : await encodeCookieValue(value, secrets), {
3157 ...options,
3158 ...serializeOptions
3159 });
3160 }
3161 };
3162};
3163/**
3164* Returns `true` if a value is a React Router {@link Cookie} object.
3165*
3166* @public
3167* @category Utils
3168* @mode framework
3169* @mode data
3170* @param object The value to check.
3171* @returns `true` if the value is a React Router {@link Cookie} object;
3172* otherwise, `false`.
3173*/
3174const isCookie = (object) => {
3175 return object != null && typeof object.name === "string" && typeof object.isSigned === "boolean" && typeof object.parse === "function" && typeof object.serialize === "function";
3176};
3177async function encodeCookieValue(value, secrets) {
3178 let encoded = encodeData(value);
3179 if (secrets.length > 0) encoded = await sign(encoded, secrets[0]);
3180 return encoded;
3181}
3182async function decodeCookieValue(value, secrets) {
3183 if (secrets.length > 0) {
3184 for (let secret of secrets) {
3185 let unsignedValue = await unsign(value, secret);
3186 if (unsignedValue !== false) return decodeData(unsignedValue);
3187 }
3188 return null;
3189 }
3190 return decodeData(value);
3191}
3192function encodeData(value) {
3193 return btoa(myUnescape(encodeURIComponent(JSON.stringify(value))));
3194}
3195function decodeData(value) {
3196 try {
3197 return JSON.parse(decodeURIComponent(myEscape(atob(value))));
3198 } catch {
3199 return {};
3200 }
3201}
3202function myEscape(value) {
3203 let str = value.toString();
3204 let result = "";
3205 let index = 0;
3206 let chr, code;
3207 while (index < str.length) {
3208 chr = str.charAt(index++);
3209 if (/[\w*+\-./@]/.exec(chr)) result += chr;
3210 else {
3211 code = chr.charCodeAt(0);
3212 if (code < 256) result += "%" + hex(code, 2);
3213 else result += "%u" + hex(code, 4).toUpperCase();
3214 }
3215 }
3216 return result;
3217}
3218function hex(code, length) {
3219 let result = code.toString(16);
3220 while (result.length < length) result = "0" + result;
3221 return result;
3222}
3223function myUnescape(value) {
3224 let str = value.toString();
3225 let result = "";
3226 let index = 0;
3227 let chr, part;
3228 while (index < str.length) {
3229 chr = str.charAt(index++);
3230 if (chr === "%") if (str.charAt(index) === "u") {
3231 part = str.slice(index + 1, index + 5);
3232 if (/^[\da-f]{4}$/i.exec(part)) {
3233 result += String.fromCharCode(parseInt(part, 16));
3234 index += 5;
3235 continue;
3236 }
3237 } else {
3238 part = str.slice(index, index + 2);
3239 if (/^[\da-f]{2}$/i.exec(part)) {
3240 result += String.fromCharCode(parseInt(part, 16));
3241 index += 2;
3242 continue;
3243 }
3244 }
3245 result += chr;
3246 }
3247 return result;
3248}
3249function warnOnceAboutExpiresCookie(name, expires) {
3250 warnOnce(!expires, `The "${name}" cookie has an "expires" property set. This will cause the expires value to not be updated when the session is committed. Instead, you should set the expires value when serializing the cookie. You can use \`commitSession(session, { expires })\` if using a session storage object, or \`cookie.serialize("value", { expires })\` if you're using the cookie directly.`);
3251}
3252//#endregion
3253//#region lib/server-runtime/sessions.ts
3254function flash(name) {
3255 return `__flash_${name}__`;
3256}
3257/**
3258* Creates a new Session object.
3259*
3260* Note: This function is typically not invoked directly by application code.
3261* Instead, use a `SessionStorage` object's `getSession` method.
3262*
3263* @category Utils
3264* @param initialData The initial data for the session.
3265* @param id The identifier for the session. Defaults to an empty string for a
3266* new session.
3267* @returns A new {@link Session} object.
3268*/
3269const createSession = (initialData = {}, id = "") => {
3270 let map = new Map(Object.entries(initialData));
3271 return {
3272 get id() {
3273 return id;
3274 },
3275 get data() {
3276 return Object.fromEntries(map);
3277 },
3278 has(name) {
3279 return map.has(name) || map.has(flash(name));
3280 },
3281 get(name) {
3282 if (map.has(name)) return map.get(name);
3283 let flashName = flash(name);
3284 if (map.has(flashName)) {
3285 let value = map.get(flashName);
3286 map.delete(flashName);
3287 return value;
3288 }
3289 },
3290 set(name, value) {
3291 map.set(name, value);
3292 },
3293 flash(name, value) {
3294 map.set(flash(name), value);
3295 },
3296 unset(name) {
3297 map.delete(name);
3298 map.delete(flash(name));
3299 }
3300 };
3301};
3302/**
3303* Returns `true` if a value is a React Router {@link Session} object.
3304*
3305* @public
3306* @category Utils
3307* @mode framework
3308* @mode data
3309* @param object The value to check.
3310* @returns `true` if the value is a React Router {@link Session} object;
3311* otherwise, `false`.
3312*/
3313const isSession = (object) => {
3314 return object != null && typeof object.id === "string" && typeof object.data !== "undefined" && typeof object.has === "function" && typeof object.get === "function" && typeof object.set === "function" && typeof object.flash === "function" && typeof object.unset === "function";
3315};
3316/**
3317* Creates a SessionStorage object using a SessionIdStorageStrategy.
3318*
3319* Note: This is a low-level API that should only be used if none of the
3320* existing session storage options meet your requirements.
3321*
3322* @category Utils
3323* @param strategy The strategy used to store session identifiers and data.
3324* @returns A {@link SessionStorage} object that persists session data using the
3325* provided strategy.
3326*/
3327function createSessionStorage({ cookie: cookieArg, createData, readData, updateData, deleteData }) {
3328 let cookie = isCookie(cookieArg) ? cookieArg : createCookie(cookieArg?.name || "__session", cookieArg);
3329 warnOnceAboutSigningSessionCookie(cookie);
3330 return {
3331 async getSession(cookieHeader, options) {
3332 let parsedId = cookieHeader && await cookie.parse(cookieHeader, options);
3333 let id = typeof parsedId === "string" && parsedId ? parsedId : "";
3334 return createSession((id ? await readData(id) : null) || {}, id);
3335 },
3336 async commitSession(session, options) {
3337 let { id, data } = session;
3338 let expires = options?.maxAge != null ? new Date(Date.now() + options.maxAge * 1e3) : options?.expires != null ? options.expires : cookie.expires;
3339 if (id) await updateData(id, data, expires);
3340 else id = await createData(data, expires);
3341 return cookie.serialize(id, options);
3342 },
3343 async destroySession(session, options) {
3344 if (session.id) await deleteData(session.id);
3345 return cookie.serialize("", {
3346 ...options,
3347 maxAge: void 0,
3348 expires: /* @__PURE__ */ new Date(0)
3349 });
3350 }
3351 };
3352}
3353function warnOnceAboutSigningSessionCookie(cookie) {
3354 warnOnce(cookie.isSigned, `The "${cookie.name}" cookie is not signed, but session cookies should be signed to prevent tampering on the client before they are sent back to the server. See https://reactrouter.com/explanation/sessions-and-cookies#signing-cookies for more information.`);
3355}
3356//#endregion
3357//#region lib/server-runtime/sessions/cookieStorage.ts
3358/**
3359* Creates and returns a SessionStorage object that stores all session data
3360* directly in the session cookie itself.
3361*
3362* This has the advantage that no database or other backend services are
3363* needed, and can help to simplify some load-balanced scenarios. However, it
3364* also has the limitation that serialized session data may not exceed the
3365* browser's maximum cookie size. Trade-offs!
3366*
3367* @public
3368* @category Utils
3369* @mode framework
3370* @mode data
3371* @param options Options for creating the cookie-backed session storage.
3372* @returns A {@link SessionStorage} object that stores all session data in its
3373* cookie.
3374*/
3375function createCookieSessionStorage({ cookie: cookieArg } = {}) {
3376 let cookie = isCookie(cookieArg) ? cookieArg : createCookie(cookieArg?.name || "__session", cookieArg);
3377 warnOnceAboutSigningSessionCookie(cookie);
3378 return {
3379 async getSession(cookieHeader, options) {
3380 let data = cookieHeader && await cookie.parse(cookieHeader, options);
3381 return createSession(typeof data === "object" && data !== null && !Array.isArray(data) ? data : {});
3382 },
3383 async commitSession(session, options) {
3384 let serializedCookie = await cookie.serialize(session.data, options);
3385 if (serializedCookie.length > 4096) throw new Error("Cookie length will exceed browser maximum. Length: " + serializedCookie.length);
3386 return serializedCookie;
3387 },
3388 async destroySession(_session, options) {
3389 return cookie.serialize("", {
3390 ...options,
3391 maxAge: void 0,
3392 expires: /* @__PURE__ */ new Date(0)
3393 });
3394 }
3395 };
3396}
3397//#endregion
3398//#region lib/server-runtime/sessions/memoryStorage.ts
3399/**
3400* Creates and returns a simple in-memory SessionStorage object.
3401*
3402* Intended for local development and testing. It does not scale beyond a single
3403* process, and all session data is lost when the server process stops/restarts.
3404*
3405* @public
3406* @category Utils
3407* @mode framework
3408* @mode data
3409* @param options Options for creating the in-memory session storage.
3410* @returns A {@link SessionStorage} object that stores session data in memory.
3411*/
3412function createMemorySessionStorage({ cookie } = {}) {
3413 let map = /* @__PURE__ */ new Map();
3414 return createSessionStorage({
3415 cookie,
3416 async createData(data, expires) {
3417 let id = crypto.randomUUID();
3418 map.set(id, {
3419 data,
3420 expires
3421 });
3422 return id;
3423 },
3424 async readData(id) {
3425 if (map.has(id)) {
3426 let { data, expires } = map.get(id);
3427 if (!expires || expires > /* @__PURE__ */ new Date()) return data;
3428 if (expires) map.delete(id);
3429 }
3430 return null;
3431 },
3432 async updateData(id, data, expires) {
3433 map.set(id, {
3434 data,
3435 expires
3436 });
3437 },
3438 async deleteData(id) {
3439 map.delete(id);
3440 }
3441 });
3442}
3443//#endregion
3444export { Await, BrowserRouter, Form, HashRouter, Link, Links, MemoryRouter, Meta, NavLink, Navigate, Outlet, Route, Router, RouterContextProvider, RouterProvider, Routes, ScrollRestoration, StaticRouter, StaticRouterProvider, createContext, createCookie, createCookieSessionStorage, createMemorySessionStorage, createSession, createSessionStorage, createStaticHandler, data, href, isCookie, isRouteErrorResponse, isSession, matchRoutes, redirect, redirectDocument, replace, unstable_HistoryRouter, getRequest as unstable_getRequest, matchRSCServerRequest as unstable_matchRSCServerRequest };