UNPKG

33.8 kBJavaScriptView Raw
1/**
2 * react-router v8.3.0
3 *
4 * Copyright (c) Remix Software Inc.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE.md file in the root directory of this source tree.
8 *
9 * @license MIT
10 */
11import { ABSOLUTE_URL_REGEX, PROTOCOL_RELATIVE_URL_REGEX, normalizeProtocolRelativeUrl } from "./url.js";
12import { invariant, parsePath, warning } from "./history.js";
13import * as React$1 from "react";
14//#region lib/router/utils.ts
15/**
16* Creates a type-safe {@link RouterContext} object that can be used to
17* store and retrieve arbitrary values in [`action`](../../start/framework/route-module#action)s,
18* [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
19* Similar to React's [`createContext`](https://react.dev/reference/react/createContext),
20* but specifically designed for React Router's request/response lifecycle.
21*
22* If a `defaultValue` is provided, it will be returned from `context.get()`
23* when no value has been set for the context. Otherwise, reading this context
24* when no value has been set will throw an error.
25*
26* ```tsx filename=app/context.ts
27* import { createContext } from "react-router";
28*
29* // Create a context for user data
30* export const userContext =
31* createContext<User | null>(null);
32* ```
33*
34* ```tsx filename=app/middleware/auth.ts
35* import { getUserFromSession } from "~/auth.server";
36* import { userContext } from "~/context";
37*
38* export const authMiddleware = async ({
39* context,
40* request,
41* }) => {
42* const user = await getUserFromSession(request);
43* context.set(userContext, user);
44* };
45* ```
46*
47* ```tsx filename=app/routes/profile.tsx
48* import { userContext } from "~/context";
49*
50* export async function loader({
51* context,
52* }: Route.LoaderArgs) {
53* const user = context.get(userContext);
54*
55* if (!user) {
56* throw new Response("Unauthorized", { status: 401 });
57* }
58*
59* return { user };
60* }
61* ```
62*
63* @public
64* @category Utils
65* @mode framework
66* @mode data
67* @param defaultValue An optional default value for the context. This value
68* will be returned if no value has been set for this context.
69* @returns A {@link RouterContext} object that can be used with
70* `context.get()` and `context.set()` in [`action`](../../start/framework/route-module#action)s,
71* [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
72*/
73function createContext(defaultValue) {
74 return { defaultValue };
75}
76/**
77* Provides methods for writing/reading values in application context in a
78* type-safe way. Primarily for usage with [middleware](../../how-to/middleware).
79*
80* @example
81* import {
82* createContext,
83* RouterContextProvider
84* } from "react-router";
85*
86* const userContext = createContext<User | null>(null);
87* const contextProvider = new RouterContextProvider();
88* contextProvider.set(userContext, getUser());
89* // ^ Type-safe
90* const user = contextProvider.get(userContext);
91* // ^ User
92*
93* @public
94* @category Utils
95* @mode framework
96* @mode data
97*/
98var RouterContextProvider = class {
99 #map = /* @__PURE__ */ new Map();
100 /**
101 * Create a new `RouterContextProvider` instance
102 * @param init An optional initial context map to populate the provider with
103 */
104 constructor(init) {
105 if (init) for (let [context, value] of init) this.set(context, value);
106 }
107 /**
108 * Access a value from the context. If no value has been set for the context,
109 * it will return the context's `defaultValue` if provided, or throw an error
110 * if no `defaultValue` was set.
111 * @param context The context to get the value for
112 * @returns The value for the context, or the context's `defaultValue` if no
113 * value was set
114 */
115 get(context) {
116 if (this.#map.has(context)) return this.#map.get(context);
117 if (context.defaultValue !== void 0) return context.defaultValue;
118 throw new Error("No value found for context");
119 }
120 /**
121 * Set a value for the context. If the context already has a value set, this
122 * will overwrite it.
123 *
124 * @param context The context to set the value for
125 * @param value The value to set for the context
126 * @returns {void}
127 */
128 set(context, value) {
129 this.#map.set(context, value);
130 }
131};
132const unsupportedLazyRouteObjectKeys = new Set([
133 "lazy",
134 "caseSensitive",
135 "path",
136 "id",
137 "index",
138 "children"
139]);
140function isUnsupportedLazyRouteObjectKey(key) {
141 return unsupportedLazyRouteObjectKeys.has(key);
142}
143const unsupportedLazyRouteFunctionKeys = new Set([
144 "lazy",
145 "caseSensitive",
146 "path",
147 "id",
148 "index",
149 "middleware",
150 "children"
151]);
152function isUnsupportedLazyRouteFunctionKey(key) {
153 return unsupportedLazyRouteFunctionKeys.has(key);
154}
155function isIndexRoute(route) {
156 return route.index === true;
157}
158function defaultMapRouteProperties(route) {
159 let updates = {};
160 if (route.Component) Object.assign(updates, {
161 element: React$1.createElement(route.Component),
162 Component: void 0
163 });
164 if (route.HydrateFallback) Object.assign(updates, {
165 hydrateFallbackElement: React$1.createElement(route.HydrateFallback),
166 HydrateFallback: void 0
167 });
168 if (route.ErrorBoundary) Object.assign(updates, {
169 errorElement: React$1.createElement(route.ErrorBoundary),
170 ErrorBoundary: void 0
171 });
172 return updates;
173}
174function convertRoutesToDataRoutes(routes, mapRouteProperties = defaultMapRouteProperties, parentPath = [], manifest = {}, allowInPlaceMutations = false) {
175 return routes.map((route, index) => {
176 let treePath = [...parentPath, String(index)];
177 let id = typeof route.id === "string" ? route.id : treePath.join("-");
178 invariant(route.index !== true || !route.children, `Cannot specify children on an index route`);
179 invariant(allowInPlaceMutations || !manifest[id], `Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages`);
180 if (isIndexRoute(route)) {
181 let indexRoute = {
182 ...route,
183 id
184 };
185 manifest[id] = mergeRouteUpdates(indexRoute, mapRouteProperties(indexRoute));
186 return indexRoute;
187 } else {
188 let pathOrLayoutRoute = {
189 ...route,
190 id,
191 children: void 0
192 };
193 manifest[id] = mergeRouteUpdates(pathOrLayoutRoute, mapRouteProperties(pathOrLayoutRoute));
194 if (route.children) pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest, allowInPlaceMutations);
195 return pathOrLayoutRoute;
196 }
197 });
198}
199function mergeRouteUpdates(route, updates) {
200 return Object.assign(route, {
201 ...updates,
202 ...typeof updates.lazy === "object" && updates.lazy != null ? { lazy: {
203 ...route.lazy,
204 ...updates.lazy
205 } } : {}
206 });
207}
208/**
209* Matches the given routes to a location and returns the match data.
210*
211* @example
212* import { matchRoutes } from "react-router";
213*
214* let routes = [{
215* path: "/",
216* Component: Root,
217* children: [{
218* path: "dashboard",
219* Component: Dashboard,
220* }]
221* }];
222*
223* matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
224*
225* @public
226* @category Utils
227* @param routes The array of route objects to match against.
228* @param locationArg The location to match against, either a string path or a
229* partial {@link Location} object
230* @param basename Optional base path to strip from the location before matching.
231* Defaults to `/`.
232* @returns An array of matched routes, or `null` if no matches were found.
233*/
234function matchRoutes(routes, locationArg, basename = "/") {
235 return matchRoutesImpl(routes, locationArg, basename, false);
236}
237function matchRoutesImpl(routes, locationArg, basename, allowPartial, precomputedBranches) {
238 let pathname = stripBasename((typeof locationArg === "string" ? parsePath(locationArg) : locationArg).pathname || "/", basename);
239 if (pathname == null) return null;
240 let branches = precomputedBranches ?? flattenAndRankRoutes(routes);
241 let matches = null;
242 let decoded = decodePath(pathname);
243 for (let i = 0; matches == null && i < branches.length; ++i) matches = matchRouteBranch(branches[i], decoded, allowPartial);
244 return matches;
245}
246function convertRouteMatchToUiMatch(match, loaderData) {
247 let { route, pathname, params } = match;
248 return {
249 id: route.id,
250 pathname,
251 params,
252 loaderData: loaderData[route.id],
253 handle: route.handle
254 };
255}
256function flattenAndRankRoutes(routes) {
257 let branches = flattenRoutes(routes);
258 rankRouteBranches(branches);
259 return branches;
260}
261function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "", _hasParentOptionalSegments = false) {
262 let flattenRoute = (route, index, hasParentOptionalSegments = _hasParentOptionalSegments, relativePath) => {
263 let meta = {
264 relativePath: relativePath === void 0 ? route.path || "" : relativePath,
265 caseSensitive: route.caseSensitive === true,
266 childrenIndex: index,
267 route
268 };
269 if (meta.relativePath.startsWith("/")) {
270 if (!meta.relativePath.startsWith(parentPath) && hasParentOptionalSegments) return;
271 invariant(meta.relativePath.startsWith(parentPath), `Absolute route path "${meta.relativePath}" nested under path "${parentPath}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`);
272 meta.relativePath = meta.relativePath.slice(parentPath.length);
273 }
274 let path = joinPaths([parentPath, meta.relativePath]);
275 let routesMeta = parentsMeta.concat(meta);
276 if (route.children && route.children.length > 0) {
277 invariant(route.index !== true, `Index routes must not have child routes. Please remove all child routes from route path "${path}".`);
278 flattenRoutes(route.children, branches, routesMeta, path, hasParentOptionalSegments);
279 }
280 if (route.path == null && !route.index) return;
281 branches.push({
282 path,
283 score: computeScore(path, route.index),
284 routesMeta: routesMeta.map((meta, i) => {
285 let [matcher, params] = compilePath(meta.relativePath, meta.caseSensitive, i === routesMeta.length - 1);
286 return {
287 ...meta,
288 matcher,
289 compiledParams: params
290 };
291 })
292 });
293 };
294 routes.forEach((route, index) => {
295 if (route.path === "" || !route.path?.includes("?")) flattenRoute(route, index);
296 else for (let exploded of explodeOptionalSegments(route.path)) flattenRoute(route, index, true, exploded);
297 });
298 return branches;
299}
300function explodeOptionalSegments(path) {
301 let segments = path.split("/");
302 if (segments.length === 0) return [];
303 let [first, ...rest] = segments;
304 let isOptional = first.endsWith("?");
305 let required = first.replace(/\?$/, "");
306 if (rest.length === 0) return isOptional ? [required, ""] : [required];
307 let restExploded = explodeOptionalSegments(rest.join("/"));
308 let result = [];
309 result.push(...restExploded.map((subpath) => subpath === "" ? required : [required, subpath].join("/")));
310 if (isOptional) result.push(...restExploded);
311 return result.map((exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded);
312}
313function rankRouteBranches(branches) {
314 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)));
315}
316const paramRe = /^:[\w-]+$/;
317const partialParamRe = /^:[\w-]+/;
318const partialDynamicSegmentValue = 3.5;
319const dynamicSegmentValue = 3;
320const indexRouteValue = 2;
321const emptySegmentValue = 1;
322const staticSegmentValue = 10;
323const splatPenalty = -2;
324const isSplat = (s) => s === "*";
325function computeScore(path, index) {
326 let segments = path.split("/");
327 let initialScore = segments.length;
328 if (segments.some(isSplat)) initialScore += splatPenalty;
329 if (index) initialScore += indexRouteValue;
330 return segments.filter((s) => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : partialParamRe.test(segment) ? partialDynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
331}
332function compareIndexes(a, b) {
333 return a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]) ? a[a.length - 1] - b[b.length - 1] : 0;
334}
335function matchRouteBranch(branch, pathname, allowPartial = false) {
336 let { routesMeta } = branch;
337 let matchedParams = {};
338 let matchedPathname = "/";
339 let matches = [];
340 for (let i = 0; i < routesMeta.length; ++i) {
341 let meta = routesMeta[i];
342 let end = i === routesMeta.length - 1;
343 let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
344 let pattern = {
345 path: meta.relativePath,
346 caseSensitive: meta.caseSensitive,
347 end
348 };
349 let match = meta.matcher && meta.compiledParams ? matchPathImpl(pattern, remainingPathname, meta.matcher, meta.compiledParams) : matchPath(pattern, remainingPathname);
350 let route = meta.route;
351 if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) match = matchPath({
352 path: meta.relativePath,
353 caseSensitive: meta.caseSensitive,
354 end: false
355 }, remainingPathname);
356 if (!match) return null;
357 Object.assign(matchedParams, match.params);
358 matches.push({
359 params: matchedParams,
360 pathname: joinPaths([matchedPathname, match.pathname]),
361 pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
362 route
363 });
364 if (match.pathnameBase !== "/") matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
365 }
366 return matches;
367}
368/**
369* Characters that `encodeURIComponent` escapes but that are valid literally in
370* a URL path segment. Per RFC 3986 §3.3, a path segment is made of `pchar`:
371*
372* ```
373* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
374* sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
375* ```
376*
377* `encodeURIComponent` targets query-string values, where `$ & + , ; = : @`
378* are delimiters and must be escaped — but in a path segment they carry no
379* special meaning, and browsers keep them literal in `location.pathname`.
380* (`! ' ( ) *` and the unreserved set are already left alone by
381* `encodeURIComponent`, so they need no restoring.)
382*/
383const PATH_PARAM_OVERESCAPED = {
384 "%24": "$",
385 "%26": "&",
386 "%2B": "+",
387 "%2C": ",",
388 "%3A": ":",
389 "%3B": ";",
390 "%3D": "=",
391 "%40": "@"
392};
393/**
394* Encodes a param value for interpolation into a single URL path segment.
395*
396* Escapes characters that would break the path (`/ ? # %`, whitespace,
397* non-ASCII, …) while leaving characters that RFC 3986 permits literally in a
398* path segment untouched. Escaping those would needlessly rewrite URLs — e.g.
399* a semver build param `1.0.0+1` would become `1.0.0%2B1` even though browsers
400* display and match the `+` literally in `location.pathname`.
401*
402* See [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3))
403*
404* @param value The param value to encode.
405* @returns The encoded value, safe for use as a single path segment.
406*/
407function encodePathParam(value) {
408 return encodeURIComponent(value).replace(/%(?:24|26|2B|2C|3A|3B|3D|40)/g, (match) => PATH_PARAM_OVERESCAPED[match]);
409}
410/**
411* Returns a path with params interpolated.
412*
413* Param values are percent-encoded for use in a path segment: characters that
414* would change the URL structure (`/`, `?`, `#`, `%`, whitespace, non-ASCII)
415* are escaped, while characters that RFC 3986 allows literally in a path
416* segment (`$ & + , ; = : @`) are kept as-is. Note this differs from query-string
417* encoding (`encodeURIComponent`/`URLSearchParams`), where those characters are
418* delimiters and must be escaped. Splat (`*`) values are encoded per segment,
419* preserving `/` separators.
420*
421* See [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3)
422*
423* @example
424* import { generatePath } from "react-router";
425*
426* generatePath("/users/:id", { id: "123" }); // "/users/123"
427* generatePath("/files/:name", { name: "a b" }); // "/files/a%20b"
428* generatePath("/releases/:v", { v: "1.0.0+1" }); // "/releases/1.0.0+1"
429*
430* @public
431* @category Utils
432* @param originalPath The original path to generate.
433* @param params The parameters to interpolate into the path.
434* @returns The generated path with parameters interpolated.
435*/
436function generatePath(originalPath, params = {}) {
437 let path = originalPath;
438 if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) {
439 warning(false, `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".`);
440 path = path.replace(/\*$/, "/*");
441 }
442 const prefix = path.startsWith("/") ? "/" : "";
443 const stringify = (p) => p == null ? "" : typeof p === "string" ? p : String(p);
444 return prefix + path.split(/\/+/).map((segment, index, array) => {
445 if (index === array.length - 1 && segment === "*") return stringify(params["*"]);
446 const keyMatch = segment.match(/^:([\w-]+)(\??)(.*)/);
447 if (keyMatch) {
448 const [, key, optional, suffix] = keyMatch;
449 let param = params[key];
450 invariant(optional === "?" || param != null, `Missing ":${key}" param`);
451 return encodePathParam(stringify(param)) + suffix;
452 }
453 return segment.replace(/\?$/g, "");
454 }).filter((segment) => !!segment).join("/");
455}
456/**
457* Performs pattern matching on a URL pathname and returns information about
458* the match.
459*
460* @public
461* @category Utils
462* @param pattern The pattern to match against the URL pathname. This can be a
463* string or a {@link PathPattern} object. If a string is provided, it will be
464* treated as a pattern with `caseSensitive` set to `false` and `end` set to
465* `true`.
466* @param pathname The URL pathname to match against the pattern.
467* @returns A path match object if the pattern matches the pathname,
468* or `null` if it does not match.
469*/
470function matchPath(pattern, pathname) {
471 if (typeof pattern === "string") pattern = {
472 path: pattern,
473 caseSensitive: false,
474 end: true
475 };
476 let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
477 return matchPathImpl(pattern, pathname, matcher, compiledParams);
478}
479function matchPathImpl(pattern, pathname, matcher, compiledParams) {
480 let match = pathname.match(matcher);
481 if (!match) return null;
482 let matchedPathname = match[0];
483 let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
484 let captureGroups = match.slice(1);
485 return {
486 params: compiledParams.reduce((memo, { paramName, isOptional }, index) => {
487 if (paramName === "*") {
488 let splatValue = captureGroups[index] || "";
489 pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
490 }
491 const value = captureGroups[index];
492 if (isOptional && !value) memo[paramName] = void 0;
493 else memo[paramName] = (value || "").replace(/%2F/g, "/");
494 return memo;
495 }, {}),
496 pathname: matchedPathname,
497 pathnameBase,
498 pattern
499 };
500}
501function compilePath(path, caseSensitive = false, end = true) {
502 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(/\*$/, "/*")}".`);
503 let params = [];
504 let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(/\/:([\w-]+)(\?)?/g, (match, paramName, isOptional, index, str) => {
505 params.push({
506 paramName,
507 isOptional: isOptional != null
508 });
509 if (isOptional) {
510 let nextChar = str.charAt(index + match.length);
511 if (nextChar && nextChar !== "/") return "/([^\\/]*)";
512 return "(?:/([^\\/]*))?";
513 }
514 return "/([^\\/]+)";
515 }).replace(/\/([\w-]+)\?(?=\/|$|\()/g, "(?:/$1)?");
516 if (path.endsWith("*")) {
517 params.push({ paramName: "*" });
518 regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
519 } else if (end) regexpSource += "\\/*$";
520 else if (path !== "" && path !== "/") regexpSource += "(?:(?=\\/|$))";
521 return [new RegExp(regexpSource, caseSensitive ? void 0 : "i"), params];
522}
523function decodePath(value) {
524 try {
525 return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
526 } catch (error) {
527 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}).`);
528 return value;
529 }
530}
531function stripBasename(pathname, basename) {
532 if (basename === "/") return pathname;
533 if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) return null;
534 let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
535 let nextChar = pathname.charAt(startIndex);
536 if (nextChar && nextChar !== "/") return null;
537 return pathname.slice(startIndex) || "/";
538}
539function prependBasename({ basename, pathname }) {
540 return pathname === "/" ? basename : joinPaths([basename, pathname]);
541}
542const isAbsoluteUrl = (url) => ABSOLUTE_URL_REGEX.test(url);
543/**
544* Returns a resolved {@link Path} object relative to the given pathname.
545*
546* @public
547* @category Utils
548* @param to The path to resolve, either a string or a partial {@link Path}
549* object.
550* @param fromPathname The pathname to resolve the path from. Defaults to `/`.
551* @returns A {@link Path} object with the resolved pathname, search, and hash.
552*/
553function resolvePath(to, fromPathname = "/") {
554 let { pathname: toPathname, search = "", hash = "" } = typeof to === "string" ? parsePath(to) : to;
555 let pathname;
556 if (toPathname) {
557 toPathname = removeDoubleSlashes(toPathname);
558 if (toPathname.startsWith("/")) pathname = resolvePathname(toPathname.substring(1), "/");
559 else pathname = resolvePathname(toPathname, fromPathname);
560 } else pathname = fromPathname;
561 return {
562 pathname,
563 search: normalizeSearch(search),
564 hash: normalizeHash(hash)
565 };
566}
567function resolvePathname(relativePath, fromPathname) {
568 let segments = removeTrailingSlash(fromPathname).split("/");
569 relativePath.split("/").forEach((segment) => {
570 if (segment === "..") {
571 if (segments.length > 1) segments.pop();
572 } else if (segment !== ".") segments.push(segment);
573 });
574 return segments.length > 1 ? segments.join("/") : "/";
575}
576function getInvalidPathError(char, field, dest, path) {
577 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.`;
578}
579function getPathContributingMatches(matches) {
580 return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
581}
582function getResolveToMatches(matches) {
583 let pathMatches = getPathContributingMatches(matches);
584 return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase);
585}
586function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
587 let to;
588 if (typeof toArg === "string") to = parsePath(toArg);
589 else {
590 to = { ...toArg };
591 invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to));
592 invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to));
593 invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to));
594 }
595 let isEmptyPath = toArg === "" || to.pathname === "";
596 let toPathname = isEmptyPath ? "/" : to.pathname;
597 let from;
598 if (toPathname == null) from = locationPathname;
599 else {
600 let routePathnameIndex = routePathnames.length - 1;
601 if (!isPathRelative && toPathname.startsWith("..")) {
602 let toSegments = toPathname.split("/");
603 while (toSegments[0] === "..") {
604 toSegments.shift();
605 routePathnameIndex -= 1;
606 }
607 to.pathname = toSegments.join("/");
608 }
609 from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
610 }
611 let path = resolvePath(to, from);
612 let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
613 let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
614 if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) path.pathname += "/";
615 return path;
616}
617const removeDoubleSlashes = (path) => path.replace(/[\\/]{2,}/g, "/");
618const joinPaths = (paths) => removeDoubleSlashes(paths.join("/"));
619const removeTrailingSlash = (path) => path.replace(/\/+$/, "");
620const normalizePathname = (pathname) => removeTrailingSlash(pathname).replace(/^\/*/, "/");
621const normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
622const normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
623var DataWithResponseInit = class {
624 type = "DataWithResponseInit";
625 data;
626 init;
627 constructor(data, init) {
628 this.data = data;
629 this.init = init || null;
630 }
631};
632/**
633* Create "responses" that contain `headers`/`status` without forcing
634* serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
635*
636* @example
637* import { data } from "react-router";
638*
639* export async function action({ request }: Route.ActionArgs) {
640* let formData = await request.formData();
641* let item = await createItem(formData);
642* return data(item, {
643* headers: { "X-Custom-Header": "value" }
644* status: 201,
645* });
646* }
647*
648* @public
649* @category Utils
650* @mode framework
651* @mode data
652* @param data The data to be included in the response.
653* @param init The status code or a `ResponseInit` object to be included in the
654* response.
655* @returns A {@link DataWithResponseInit} instance containing the data and
656* response init.
657*/
658function data(data, init) {
659 return new DataWithResponseInit(data, typeof init === "number" ? { status: init } : init);
660}
661/**
662* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
663* Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
664* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
665*
666* This utility accepts absolute URLs and can navigate to external domains, so
667* the application should validate any user-supplied inputs to redirects.
668*
669* @example
670* import { redirect } from "react-router";
671*
672* export async function loader({ request }: Route.LoaderArgs) {
673* if (!isLoggedIn(request))
674* throw redirect("/login");
675* }
676*
677* // ...
678* }
679*
680* @public
681* @category Utils
682* @mode framework
683* @mode data
684* @param url The URL to redirect to.
685* @param init The status code or a `ResponseInit` object to be included in the
686* response.
687* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
688* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
689* header.
690*/
691const redirect = (url, init = 302) => {
692 let responseInit = init;
693 if (typeof responseInit === "number") responseInit = { status: responseInit };
694 else if (typeof responseInit.status === "undefined") responseInit.status = 302;
695 let headers = new Headers(responseInit.headers);
696 headers.set("Location", url);
697 return new Response(null, {
698 ...responseInit,
699 headers
700 });
701};
702/**
703* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
704* that will force a document reload to the new location. Sets the status code
705* and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
706* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
707*
708* This utility accepts absolute URLs and can navigate to external domains, so
709* the application should validate any user-supplied inputs to redirects.
710*
711* ```tsx filename=routes/logout.tsx
712* import { redirectDocument } from "react-router";
713*
714* import { destroySession } from "../sessions.server";
715*
716* export async function action({ request }: Route.ActionArgs) {
717* let session = await getSession(request.headers.get("Cookie"));
718* return redirectDocument("/", {
719* headers: { "Set-Cookie": await destroySession(session) }
720* });
721* }
722* ```
723*
724* @public
725* @category Utils
726* @mode framework
727* @mode data
728* @param url The URL to redirect to.
729* @param init The status code or a `ResponseInit` object to be included in the
730* response.
731* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
732* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
733* header.
734*/
735const redirectDocument = (url, init) => {
736 let response = redirect(url, init);
737 response.headers.set("X-Remix-Reload-Document", "true");
738 return response;
739};
740/**
741* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
742* that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
743* instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
744* for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
745* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
746*
747* @example
748* import { replace } from "react-router";
749*
750* export async function loader() {
751* return replace("/new-location");
752* }
753*
754* @public
755* @category Utils
756* @mode framework
757* @mode data
758* @param url The URL to redirect to.
759* @param init The status code or a `ResponseInit` object to be included in the
760* response.
761* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
762* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
763* header.
764*/
765const replace = (url, init) => {
766 let response = redirect(url, init);
767 response.headers.set("X-Remix-Replace", "true");
768 return response;
769};
770const SUPPORTED_ERROR_TYPES = [
771 "EvalError",
772 "RangeError",
773 "ReferenceError",
774 "SyntaxError",
775 "TypeError",
776 "URIError"
777];
778var ErrorResponseImpl = class {
779 status;
780 statusText;
781 data;
782 error;
783 internal;
784 constructor(status, statusText, data, internal = false) {
785 this.status = status;
786 this.statusText = statusText || "";
787 this.internal = internal;
788 if (data instanceof Error) {
789 this.data = data.toString();
790 this.error = data;
791 } else this.data = data;
792 }
793};
794/**
795* Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
796* [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
797* thrown from an [`action`](../../start/framework/route-module#action) or
798* [`loader`](../../start/framework/route-module#loader) function.
799*
800* @example
801* import { isRouteErrorResponse } from "react-router";
802*
803* export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
804* if (isRouteErrorResponse(error)) {
805* return (
806* <>
807* <p>Error: `${error.status}: ${error.statusText}`</p>
808* <p>{error.data}</p>
809* </>
810* );
811* }
812*
813* return (
814* <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
815* );
816* }
817*
818* @public
819* @category Utils
820* @mode framework
821* @mode data
822* @param error The error to check.
823* @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
824*/
825function isRouteErrorResponse(error) {
826 return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
827}
828function getRoutePattern(matches) {
829 return joinPaths(matches.map((m) => m.route.path).filter(Boolean)) || "/";
830}
831function createDataFunctionUrl(request, path) {
832 let url = new URL(typeof request === "string" || request instanceof URL ? request : request.url);
833 let parsed = typeof path === "string" ? parsePath(path) : path;
834 url.pathname = parsed.pathname || "/";
835 if (parsed.search) {
836 let searchParams = new URLSearchParams(parsed.search);
837 let indexValues = searchParams.getAll("index");
838 searchParams.delete("index");
839 for (let value of indexValues.filter(Boolean)) searchParams.append("index", value);
840 let search = searchParams.toString();
841 url.search = search ? `?${search}` : "";
842 } else url.search = "";
843 url.hash = parsed.hash || "";
844 return url;
845}
846const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
847function parseToInfo(_to, basename) {
848 let to = _to;
849 if (typeof to !== "string" || !ABSOLUTE_URL_REGEX.test(to)) return {
850 absoluteURL: void 0,
851 isExternal: false,
852 to
853 };
854 let absoluteURL = to;
855 let isExternal = false;
856 if (isBrowser) try {
857 let currentUrl = new URL(window.location.href);
858 let targetUrl = PROTOCOL_RELATIVE_URL_REGEX.test(to) ? new URL(normalizeProtocolRelativeUrl(to, currentUrl.protocol)) : new URL(to);
859 let path = stripBasename(targetUrl.pathname, basename);
860 if (targetUrl.origin === currentUrl.origin && path != null) to = path + targetUrl.search + targetUrl.hash;
861 else isExternal = true;
862 } catch (e) {
863 warning(false, `<Link to="${to}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`);
864 }
865 return {
866 absoluteURL,
867 isExternal,
868 to
869 };
870}
871//#endregion
872export { ErrorResponseImpl, RouterContextProvider, SUPPORTED_ERROR_TYPES, compilePath, convertRouteMatchToUiMatch, convertRoutesToDataRoutes, createContext, createDataFunctionUrl, data, decodePath, defaultMapRouteProperties, encodePathParam, flattenAndRankRoutes, generatePath, getPathContributingMatches, getResolveToMatches, getRoutePattern, isAbsoluteUrl, isBrowser, isRouteErrorResponse, isUnsupportedLazyRouteFunctionKey, isUnsupportedLazyRouteObjectKey, joinPaths, matchPath, matchRoutes, matchRoutesImpl, parseToInfo, prependBasename, redirect, redirectDocument, removeDoubleSlashes, removeTrailingSlash, replace, resolvePath, resolveTo, stripBasename };