UNPKG

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