UNPKG

68.3 kB TypeScript View Raw
1import * as React from 'react';
2import { ComponentType, ReactElement } from 'react';
3
4/**
5 * An augmentable interface users can modify in their app-code to opt into
6 * future-flag-specific types
7 */
8interface Future {
9}
10type MiddlewareEnabled = Future extends {
11 v8_middleware: infer T extends boolean;
12} ? T : false;
13
14/**
15 * Actions represent the type of change to a location value.
16 */
17declare enum Action {
18 /**
19 * A POP indicates a change to an arbitrary index in the history stack, such
20 * as a back or forward navigation. It does not describe the direction of the
21 * navigation, only that the current index changed.
22 *
23 * Note: This is the default action for newly created history objects.
24 */
25 Pop = "POP",
26 /**
27 * A PUSH indicates a new entry being added to the history stack, such as when
28 * a link is clicked and a new page loads. When this happens, all subsequent
29 * entries in the stack are lost.
30 */
31 Push = "PUSH",
32 /**
33 * A REPLACE indicates the entry at the current index in the history stack
34 * being replaced by a new one.
35 */
36 Replace = "REPLACE"
37}
38/**
39 * The pathname, search, and hash values of a URL.
40 */
41interface Path {
42 /**
43 * A URL pathname, beginning with a /.
44 */
45 pathname: string;
46 /**
47 * A URL search string, beginning with a ?.
48 */
49 search: string;
50 /**
51 * A URL fragment identifier, beginning with a #.
52 */
53 hash: string;
54}
55/**
56 * An entry in a history stack. A location contains information about the
57 * URL path, as well as possibly some arbitrary state and a key.
58 */
59interface Location<State = any> extends Path {
60 /**
61 * A value of arbitrary data associated with this location.
62 */
63 state: State;
64 /**
65 * A unique string associated with this location. May be used to safely store
66 * and retrieve data in some other storage API, like `localStorage`.
67 *
68 * Note: This value is always "default" on the initial location.
69 */
70 key: string;
71 /**
72 * The masked location displayed in the URL bar, which differs from the URL the
73 * router is operating on
74 */
75 unstable_mask: Path | undefined;
76}
77/**
78 * A change to the current location.
79 */
80interface Update {
81 /**
82 * The action that triggered the change.
83 */
84 action: Action;
85 /**
86 * The new location.
87 */
88 location: Location;
89 /**
90 * The delta between this location and the former location in the history stack
91 */
92 delta: number | null;
93}
94/**
95 * A function that receives notifications about location changes.
96 */
97interface Listener {
98 (update: Update): void;
99}
100/**
101 * Describes a location that is the destination of some navigation used in
102 * {@link Link}, {@link useNavigate}, etc.
103 */
104type To = string | Partial<Path>;
105/**
106 * A history is an interface to the navigation stack. The history serves as the
107 * source of truth for the current location, as well as provides a set of
108 * methods that may be used to change it.
109 *
110 * It is similar to the DOM's `window.history` object, but with a smaller, more
111 * focused API.
112 */
113interface History {
114 /**
115 * The last action that modified the current location. This will always be
116 * Action.Pop when a history instance is first created. This value is mutable.
117 */
118 readonly action: Action;
119 /**
120 * The current location. This value is mutable.
121 */
122 readonly location: Location;
123 /**
124 * Returns a valid href for the given `to` value that may be used as
125 * the value of an <a href> attribute.
126 *
127 * @param to - The destination URL
128 */
129 createHref(to: To): string;
130 /**
131 * Returns a URL for the given `to` value
132 *
133 * @param to - The destination URL
134 */
135 createURL(to: To): URL;
136 /**
137 * Encode a location the same way window.history would do (no-op for memory
138 * history) so we ensure our PUSH/REPLACE navigations for data routers
139 * behave the same as POP
140 *
141 * @param to Unencoded path
142 */
143 encodeLocation(to: To): Path;
144 /**
145 * Pushes a new location onto the history stack, increasing its length by one.
146 * If there were any entries in the stack after the current one, they are
147 * lost.
148 *
149 * @param to - The new URL
150 * @param state - Data to associate with the new location
151 */
152 push(to: To, state?: any): void;
153 /**
154 * Replaces the current location in the history stack with a new one. The
155 * location that was replaced will no longer be available.
156 *
157 * @param to - The new URL
158 * @param state - Data to associate with the new location
159 */
160 replace(to: To, state?: any): void;
161 /**
162 * Navigates `n` entries backward/forward in the history stack relative to the
163 * current index. For example, a "back" navigation would use go(-1).
164 *
165 * @param delta - The delta in the stack index
166 */
167 go(delta: number): void;
168 /**
169 * Sets up a listener that will be called whenever the current location
170 * changes.
171 *
172 * @param listener - A function that will be called when the location changes
173 * @returns unlisten - A function that may be used to stop listening
174 */
175 listen(listener: Listener): () => void;
176}
177/**
178 * A user-supplied object that describes a location. Used when providing
179 * entries to `createMemoryHistory` via its `initialEntries` option.
180 */
181type InitialEntry = string | Partial<Location>;
182type MemoryHistoryOptions = {
183 initialEntries?: InitialEntry[];
184 initialIndex?: number;
185 v5Compat?: boolean;
186};
187/**
188 * A memory history stores locations in memory. This is useful in stateful
189 * environments where there is no web browser, such as node tests or React
190 * Native.
191 */
192interface MemoryHistory extends History {
193 /**
194 * The current index in the history stack.
195 */
196 readonly index: number;
197}
198/**
199 * Memory history stores the current location in memory. It is designed for use
200 * in stateful non-browser environments like tests and React Native.
201 */
202declare function createMemoryHistory(options?: MemoryHistoryOptions): MemoryHistory;
203/**
204 * A browser history stores the current location in regular URLs in a web
205 * browser environment. This is the standard for most web apps and provides the
206 * cleanest URLs the browser's address bar.
207 *
208 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory
209 */
210interface BrowserHistory extends UrlHistory {
211}
212type BrowserHistoryOptions = UrlHistoryOptions;
213/**
214 * Browser history stores the location in regular URLs. This is the standard for
215 * most web apps, but it requires some configuration on the server to ensure you
216 * serve the same app at multiple URLs.
217 *
218 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
219 */
220declare function createBrowserHistory(options?: BrowserHistoryOptions): BrowserHistory;
221/**
222 * A hash history stores the current location in the fragment identifier portion
223 * of the URL in a web browser environment.
224 *
225 * This is ideal for apps that do not control the server for some reason
226 * (because the fragment identifier is never sent to the server), including some
227 * shared hosting environments that do not provide fine-grained controls over
228 * which pages are served at which URLs.
229 *
230 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory
231 */
232interface HashHistory extends UrlHistory {
233}
234type HashHistoryOptions = UrlHistoryOptions;
235/**
236 * Hash history stores the location in window.location.hash. This makes it ideal
237 * for situations where you don't want to send the location to the server for
238 * some reason, either because you do cannot configure it or the URL space is
239 * reserved for something else.
240 *
241 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
242 */
243declare function createHashHistory(options?: HashHistoryOptions): HashHistory;
244/**
245 * @private
246 */
247declare function invariant(value: boolean, message?: string): asserts value;
248declare function invariant<T>(value: T | null | undefined, message?: string): asserts value is T;
249/**
250 * Creates a string URL path from the given pathname, search, and hash components.
251 *
252 * @category Utils
253 */
254declare function createPath({ pathname, search, hash, }: Partial<Path>): string;
255/**
256 * Parses a string URL path into its separate pathname, search, and hash components.
257 *
258 * @category Utils
259 */
260declare function parsePath(path: string): Partial<Path>;
261interface UrlHistory extends History {
262}
263type UrlHistoryOptions = {
264 window?: Window;
265 v5Compat?: boolean;
266};
267
268type MaybePromise<T> = T | Promise<T>;
269/**
270 * Map of routeId -> data returned from a loader/action/error
271 */
272interface RouteData {
273 [routeId: string]: any;
274}
275type LowerCaseFormMethod = "get" | "post" | "put" | "patch" | "delete";
276type UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;
277/**
278 * Users can specify either lowercase or uppercase form methods on `<Form>`,
279 * useSubmit(), `<fetcher.Form>`, etc.
280 */
281type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;
282/**
283 * Active navigation/fetcher form methods are exposed in uppercase on the
284 * RouterState. This is to align with the normalization done via fetch().
285 */
286type FormMethod = UpperCaseFormMethod;
287type FormEncType = "application/x-www-form-urlencoded" | "multipart/form-data" | "application/json" | "text/plain";
288type JsonObject = {
289 [Key in string]: JsonValue;
290} & {
291 [Key in string]?: JsonValue | undefined;
292};
293type JsonArray = JsonValue[] | readonly JsonValue[];
294type JsonPrimitive = string | number | boolean | null;
295type JsonValue = JsonPrimitive | JsonObject | JsonArray;
296/**
297 * @private
298 * Internal interface to pass around for action submissions, not intended for
299 * external consumption
300 */
301type Submission = {
302 formMethod: FormMethod;
303 formAction: string;
304 formEncType: FormEncType;
305 formData: FormData;
306 json: undefined;
307 text: undefined;
308} | {
309 formMethod: FormMethod;
310 formAction: string;
311 formEncType: FormEncType;
312 formData: undefined;
313 json: JsonValue;
314 text: undefined;
315} | {
316 formMethod: FormMethod;
317 formAction: string;
318 formEncType: FormEncType;
319 formData: undefined;
320 json: undefined;
321 text: string;
322};
323/**
324 * A context instance used as the key for the `get`/`set` methods of a
325 * {@link RouterContextProvider}. Accepts an optional default
326 * value to be returned if no value has been set.
327 */
328interface RouterContext<T = unknown> {
329 defaultValue?: T;
330}
331/**
332 * Creates a type-safe {@link RouterContext} object that can be used to
333 * store and retrieve arbitrary values in [`action`](../../start/framework/route-module#action)s,
334 * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
335 * Similar to React's [`createContext`](https://react.dev/reference/react/createContext),
336 * but specifically designed for React Router's request/response lifecycle.
337 *
338 * If a `defaultValue` is provided, it will be returned from `context.get()`
339 * when no value has been set for the context. Otherwise, reading this context
340 * when no value has been set will throw an error.
341 *
342 * ```tsx filename=app/context.ts
343 * import { createContext } from "react-router";
344 *
345 * // Create a context for user data
346 * export const userContext =
347 * createContext<User | null>(null);
348 * ```
349 *
350 * ```tsx filename=app/middleware/auth.ts
351 * import { getUserFromSession } from "~/auth.server";
352 * import { userContext } from "~/context";
353 *
354 * export const authMiddleware = async ({
355 * context,
356 * request,
357 * }) => {
358 * const user = await getUserFromSession(request);
359 * context.set(userContext, user);
360 * };
361 * ```
362 *
363 * ```tsx filename=app/routes/profile.tsx
364 * import { userContext } from "~/context";
365 *
366 * export async function loader({
367 * context,
368 * }: Route.LoaderArgs) {
369 * const user = context.get(userContext);
370 *
371 * if (!user) {
372 * throw new Response("Unauthorized", { status: 401 });
373 * }
374 *
375 * return { user };
376 * }
377 * ```
378 *
379 * @public
380 * @category Utils
381 * @mode framework
382 * @mode data
383 * @param defaultValue An optional default value for the context. This value
384 * will be returned if no value has been set for this context.
385 * @returns A {@link RouterContext} object that can be used with
386 * `context.get()` and `context.set()` in [`action`](../../start/framework/route-module#action)s,
387 * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
388 */
389declare function createContext<T>(defaultValue?: T): RouterContext<T>;
390/**
391 * Provides methods for writing/reading values in application context in a
392 * type-safe way. Primarily for usage with [middleware](../../how-to/middleware).
393 *
394 * @example
395 * import {
396 * createContext,
397 * RouterContextProvider
398 * } from "react-router";
399 *
400 * const userContext = createContext<User | null>(null);
401 * const contextProvider = new RouterContextProvider();
402 * contextProvider.set(userContext, getUser());
403 * // ^ Type-safe
404 * const user = contextProvider.get(userContext);
405 * // ^ User
406 *
407 * @public
408 * @category Utils
409 * @mode framework
410 * @mode data
411 */
412declare class RouterContextProvider {
413 #private;
414 /**
415 * Create a new `RouterContextProvider` instance
416 * @param init An optional initial context map to populate the provider with
417 */
418 constructor(init?: Map<RouterContext, unknown>);
419 /**
420 * Access a value from the context. If no value has been set for the context,
421 * it will return the context's `defaultValue` if provided, or throw an error
422 * if no `defaultValue` was set.
423 * @param context The context to get the value for
424 * @returns The value for the context, or the context's `defaultValue` if no
425 * value was set
426 */
427 get<T>(context: RouterContext<T>): T;
428 /**
429 * Set a value for the context. If the context already has a value set, this
430 * will overwrite it.
431 *
432 * @param context The context to set the value for
433 * @param value The value to set for the context
434 * @returns {void}
435 */
436 set<C extends RouterContext>(context: C, value: C extends RouterContext<infer T> ? T : never): void;
437}
438type DefaultContext = MiddlewareEnabled extends true ? Readonly<RouterContextProvider> : any;
439/**
440 * @private
441 * Arguments passed to route loader/action functions. Same for now but we keep
442 * this as a private implementation detail in case they diverge in the future.
443 */
444interface DataFunctionArgs<Context> {
445 /** A {@link https://developer.mozilla.org/en-US/docs/Web/API/Request Fetch Request instance} which you can use to read headers (like cookies, and {@link https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams URLSearchParams} from the request. */
446 request: Request;
447 /**
448 * A URL instance representing the application location being navigated to or fetched.
449 * Without `future.unstable_passThroughRequests` enabled, this matches `request.url`.
450 * With `future.unstable_passThroughRequests` enabled, this is a normalized
451 * URL with React-Router-specific implementation details removed (`.data`
452 * suffixes, `index`/`_routes` search params).
453 * The URL includes the origin from the request for convenience.
454 */
455 unstable_url: URL;
456 /**
457 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
458 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
459 */
460 unstable_pattern: string;
461 /**
462 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
463 * @example
464 * // app/routes.ts
465 * route("teams/:teamId", "./team.tsx"),
466 *
467 * // app/team.tsx
468 * export function loader({
469 * params,
470 * }: Route.LoaderArgs) {
471 * params.teamId;
472 * // ^ string
473 * }
474 */
475 params: Params;
476 /**
477 * This is the context passed in to your server adapter's getLoadContext() function.
478 * It's a way to bridge the gap between the adapter's request/response API with your React Router app.
479 * It is only applicable if you are using a custom server adapter.
480 */
481 context: Context;
482}
483/**
484 * Route middleware `next` function to call downstream handlers and then complete
485 * middlewares from the bottom-up
486 */
487interface MiddlewareNextFunction<Result = unknown> {
488 (): Promise<Result>;
489}
490/**
491 * Route middleware function signature. Receives the same "data" arguments as a
492 * `loader`/`action` (`request`, `params`, `context`) as the first parameter and
493 * a `next` function as the second parameter which will call downstream handlers
494 * and then complete middlewares from the bottom-up
495 */
496type MiddlewareFunction<Result = unknown> = (args: DataFunctionArgs<Readonly<RouterContextProvider>>, next: MiddlewareNextFunction<Result>) => MaybePromise<Result | void>;
497/**
498 * Arguments passed to loader functions
499 */
500interface LoaderFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
501}
502/**
503 * Arguments passed to action functions
504 */
505interface ActionFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
506}
507/**
508 * Loaders and actions can return anything
509 */
510type DataFunctionValue = unknown;
511type DataFunctionReturnValue = MaybePromise<DataFunctionValue>;
512/**
513 * Route loader function signature
514 */
515type LoaderFunction<Context = DefaultContext> = {
516 (args: LoaderFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
517} & {
518 hydrate?: boolean;
519};
520/**
521 * Route action function signature
522 */
523interface ActionFunction<Context = DefaultContext> {
524 (args: ActionFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
525}
526/**
527 * Arguments passed to shouldRevalidate function
528 */
529interface ShouldRevalidateFunctionArgs {
530 /** This is the url the navigation started from. You can compare it with `nextUrl` to decide if you need to revalidate this route's data. */
531 currentUrl: URL;
532 /** These are the {@link https://reactrouter.com/start/framework/routing#dynamic-segments dynamic route params} from the URL that can be compared to the `nextParams` to decide if you need to reload or not. Perhaps you're using only a partial piece of the param for data loading, you don't need to revalidate if a superfluous part of the param changed. */
533 currentParams: DataRouteMatch["params"];
534 /** In the case of navigation, this the URL the user is requesting. Some revalidations are not navigation, so it will simply be the same as currentUrl. */
535 nextUrl: URL;
536 /** In the case of navigation, these are the {@link https://reactrouter.com/start/framework/routing#dynamic-segments dynamic route params} from the next location the user is requesting. Some revalidations are not navigation, so it will simply be the same as currentParams. */
537 nextParams: DataRouteMatch["params"];
538 /** The method (probably `"GET"` or `"POST"`) used in the form submission that triggered the revalidation. */
539 formMethod?: Submission["formMethod"];
540 /** The form action (`<Form action="/somewhere">`) that triggered the revalidation. */
541 formAction?: Submission["formAction"];
542 /** The form encType (`<Form encType="application/x-www-form-urlencoded">) used in the form submission that triggered the revalidation*/
543 formEncType?: Submission["formEncType"];
544 /** The form submission data when the form's encType is `text/plain` */
545 text?: Submission["text"];
546 /** The form submission data when the form's encType is `application/x-www-form-urlencoded` or `multipart/form-data` */
547 formData?: Submission["formData"];
548 /** The form submission data when the form's encType is `application/json` */
549 json?: Submission["json"];
550 /** The status code of the action response */
551 actionStatus?: number;
552 /**
553 * When a submission causes the revalidation this will be the result of the action—either action data or an error if the action failed. It's common to include some information in the action result to instruct shouldRevalidate to revalidate or not.
554 *
555 * @example
556 * export async function action() {
557 * await saveSomeStuff();
558 * return { ok: true };
559 * }
560 *
561 * export function shouldRevalidate({
562 * actionResult,
563 * }) {
564 * if (actionResult?.ok) {
565 * return false;
566 * }
567 * return true;
568 * }
569 */
570 actionResult?: any;
571 /**
572 * By default, React Router doesn't call every loader all the time. There are reliable optimizations it can make by default. For example, only loaders with changing params are called. Consider navigating from the following URL to the one below it:
573 *
574 * /projects/123/tasks/abc
575 * /projects/123/tasks/def
576 * React Router will only call the loader for tasks/def because the param for projects/123 didn't change.
577 *
578 * It's safest to always return defaultShouldRevalidate after you've done your specific optimizations that return false, otherwise your UI might get out of sync with your data on the server.
579 */
580 defaultShouldRevalidate: boolean;
581}
582/**
583 * Route shouldRevalidate function signature. This runs after any submission
584 * (navigation or fetcher), so we flatten the navigation/fetcher submission
585 * onto the arguments. It shouldn't matter whether it came from a navigation
586 * or a fetcher, what really matters is the URLs and the formData since loaders
587 * have to re-run based on the data models that were potentially mutated.
588 */
589interface ShouldRevalidateFunction {
590 (args: ShouldRevalidateFunctionArgs): boolean;
591}
592interface DataStrategyMatch extends RouteMatch<string, DataRouteObject> {
593 /**
594 * @private
595 */
596 _lazyPromises?: {
597 middleware: Promise<void> | undefined;
598 handler: Promise<void> | undefined;
599 route: Promise<void> | undefined;
600 };
601 /**
602 * @deprecated Deprecated in favor of `shouldCallHandler`
603 *
604 * A boolean value indicating whether this route handler should be called in
605 * this pass.
606 *
607 * The `matches` array always includes _all_ matched routes even when only
608 * _some_ route handlers need to be called so that things like middleware can
609 * be implemented.
610 *
611 * `shouldLoad` is usually only interesting if you are skipping the route
612 * handler entirely and implementing custom handler logic - since it lets you
613 * determine if that custom logic should run for this route or not.
614 *
615 * For example:
616 * - If you are on `/parent/child/a` and you navigate to `/parent/child/b` -
617 * you'll get an array of three matches (`[parent, child, b]`), but only `b`
618 * will have `shouldLoad=true` because the data for `parent` and `child` is
619 * already loaded
620 * - If you are on `/parent/child/a` and you submit to `a`'s [`action`](https://reactrouter.com/docs/start/data/route-object#action),
621 * then only `a` will have `shouldLoad=true` for the action execution of
622 * `dataStrategy`
623 * - After the [`action`](https://reactrouter.com/docs/start/data/route-object#action),
624 * `dataStrategy` will be called again for the [`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
625 * revalidation, and all matches will have `shouldLoad=true` (assuming no
626 * custom `shouldRevalidate` implementations)
627 */
628 shouldLoad: boolean;
629 /**
630 * Arguments passed to the `shouldRevalidate` function for this `loader` execution.
631 * Will be `null` if this is not a revalidating loader {@link DataStrategyMatch}.
632 */
633 shouldRevalidateArgs: ShouldRevalidateFunctionArgs | null;
634 /**
635 * Determine if this route's handler should be called during this `dataStrategy`
636 * execution. Calling it with no arguments will leverage the default revalidation
637 * behavior. You can pass your own `defaultShouldRevalidate` value if you wish
638 * to change the default revalidation behavior with your `dataStrategy`.
639 *
640 * @param defaultShouldRevalidate `defaultShouldRevalidate` override value (optional)
641 */
642 shouldCallHandler(defaultShouldRevalidate?: boolean): boolean;
643 /**
644 * An async function that will resolve any `route.lazy` implementations and
645 * execute the route's handler (if necessary), returning a {@link DataStrategyResult}
646 *
647 * - Calling `match.resolve` does not mean you're calling the
648 * [`action`](https://reactrouter.com/docs/start/data/route-object#action)/[`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
649 * (the "handler") - `resolve` will only call the `handler` internally if
650 * needed _and_ if you don't pass your own `handlerOverride` function parameter
651 * - It is safe to call `match.resolve` for all matches, even if they have
652 * `shouldLoad=false`, and it will no-op if no loading is required
653 * - You should generally always call `match.resolve()` for `shouldLoad:true`
654 * routes to ensure that any `route.lazy` implementations are processed
655 * - See the examples below for how to implement custom handler execution via
656 * `match.resolve`
657 */
658 resolve: (handlerOverride?: (handler: (ctx?: unknown) => DataFunctionReturnValue) => DataFunctionReturnValue) => Promise<DataStrategyResult>;
659}
660interface DataStrategyFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
661 /**
662 * Matches for this route extended with Data strategy APIs
663 */
664 matches: DataStrategyMatch[];
665 runClientMiddleware: (cb: DataStrategyFunction<Context>) => Promise<Record<string, DataStrategyResult>>;
666 /**
667 * The key of the fetcher we are calling `dataStrategy` for, otherwise `null`
668 * for navigational executions
669 */
670 fetcherKey: string | null;
671}
672/**
673 * Result from a loader or action called via dataStrategy
674 */
675interface DataStrategyResult {
676 type: "data" | "error";
677 result: unknown;
678}
679interface DataStrategyFunction<Context = DefaultContext> {
680 (args: DataStrategyFunctionArgs<Context>): Promise<Record<string, DataStrategyResult>>;
681}
682type PatchRoutesOnNavigationFunctionArgs = {
683 signal: AbortSignal;
684 path: string;
685 matches: RouteMatch[];
686 fetcherKey: string | undefined;
687 patch: (routeId: string | null, children: RouteObject[]) => void;
688};
689type PatchRoutesOnNavigationFunction = (opts: PatchRoutesOnNavigationFunctionArgs) => MaybePromise<void>;
690/**
691 * Function provided to set route-specific properties from route objects
692 */
693interface MapRoutePropertiesFunction {
694 (route: DataRouteObject): {
695 hasErrorBoundary: boolean;
696 } & Record<string, any>;
697}
698/**
699 * Keys we cannot change from within a lazy object. We spread all other keys
700 * onto the route. Either they're meaningful to the router, or they'll get
701 * ignored.
702 */
703type UnsupportedLazyRouteObjectKey = "lazy" | "caseSensitive" | "path" | "id" | "index" | "children";
704/**
705 * Keys we cannot change from within a lazy() function. We spread all other keys
706 * onto the route. Either they're meaningful to the router, or they'll get
707 * ignored.
708 */
709type UnsupportedLazyRouteFunctionKey = UnsupportedLazyRouteObjectKey | "middleware";
710/**
711 * lazy object to load route properties, which can add non-matching
712 * related properties to a route
713 */
714type LazyRouteObject<R extends RouteObject> = {
715 [K in keyof R as K extends UnsupportedLazyRouteObjectKey ? never : K]?: () => Promise<R[K] | null | undefined>;
716};
717/**
718 * lazy() function to load a route definition, which can add non-matching
719 * related properties to a route
720 */
721interface LazyRouteFunction<R extends RouteObject> {
722 (): Promise<Omit<R, UnsupportedLazyRouteFunctionKey> & Partial<Record<UnsupportedLazyRouteFunctionKey, never>>>;
723}
724type LazyRouteDefinition<R extends RouteObject> = LazyRouteObject<R> | LazyRouteFunction<R>;
725/**
726 * Base RouteObject with common props shared by all types of routes
727 * @internal
728 */
729type BaseRouteObject = {
730 /**
731 * Whether the path should be case-sensitive. Defaults to `false`.
732 */
733 caseSensitive?: boolean;
734 /**
735 * The path pattern to match. If unspecified or empty, then this becomes a
736 * layout route.
737 */
738 path?: string;
739 /**
740 * The unique identifier for this route (for use with {@link DataRouter}s)
741 */
742 id?: string;
743 /**
744 * The route middleware.
745 * See [`middleware`](../../start/data/route-object#middleware).
746 */
747 middleware?: MiddlewareFunction[];
748 /**
749 * The route loader.
750 * See [`loader`](../../start/data/route-object#loader).
751 */
752 loader?: LoaderFunction | boolean;
753 /**
754 * The route action.
755 * See [`action`](../../start/data/route-object#action).
756 */
757 action?: ActionFunction | boolean;
758 hasErrorBoundary?: boolean;
759 /**
760 * The route shouldRevalidate function.
761 * See [`shouldRevalidate`](../../start/data/route-object#shouldRevalidate).
762 */
763 shouldRevalidate?: ShouldRevalidateFunction;
764 /**
765 * The route handle.
766 */
767 handle?: any;
768 /**
769 * A function that returns a promise that resolves to the route object.
770 * Used for code-splitting routes.
771 * See [`lazy`](../../start/data/route-object#lazy).
772 */
773 lazy?: LazyRouteDefinition<BaseRouteObject>;
774 /**
775 * The React Component to render when this route matches.
776 * Mutually exclusive with `element`.
777 */
778 Component?: React.ComponentType | null;
779 /**
780 * The React element to render when this Route matches.
781 * Mutually exclusive with `Component`.
782 */
783 element?: React.ReactNode | null;
784 /**
785 * The React Component to render at this route if an error occurs.
786 * Mutually exclusive with `errorElement`.
787 */
788 ErrorBoundary?: React.ComponentType | null;
789 /**
790 * The React element to render at this route if an error occurs.
791 * Mutually exclusive with `ErrorBoundary`.
792 */
793 errorElement?: React.ReactNode | null;
794 /**
795 * The React Component to render while this router is loading data.
796 * Mutually exclusive with `hydrateFallbackElement`.
797 */
798 HydrateFallback?: React.ComponentType | null;
799 /**
800 * The React element to render while this router is loading data.
801 * Mutually exclusive with `HydrateFallback`.
802 */
803 hydrateFallbackElement?: React.ReactNode | null;
804};
805/**
806 * Index routes must not have children
807 */
808type IndexRouteObject = BaseRouteObject & {
809 /**
810 * Child Route objects - not valid on index routes.
811 */
812 children?: undefined;
813 /**
814 * Whether this is an index route.
815 */
816 index: true;
817};
818/**
819 * Non-index routes may have children, but cannot have `index` set to `true`.
820 */
821type NonIndexRouteObject = BaseRouteObject & {
822 /**
823 * Child Route objects.
824 */
825 children?: RouteObject[];
826 /**
827 * Whether this is an index route - must be `false` or undefined on non-index routes.
828 */
829 index?: false;
830};
831/**
832 * A route object represents a logical route, with (optionally) its child
833 * routes organized in a tree-like structure.
834 */
835type RouteObject = IndexRouteObject | NonIndexRouteObject;
836type DataIndexRouteObject = IndexRouteObject & {
837 id: string;
838};
839type DataNonIndexRouteObject = NonIndexRouteObject & {
840 children?: DataRouteObject[];
841 id: string;
842};
843/**
844 * A data route object, which is just a RouteObject with a required unique ID
845 */
846type DataRouteObject = DataIndexRouteObject | DataNonIndexRouteObject;
847type RouteManifest<R = DataRouteObject> = Record<string, R | undefined>;
848type Regex_az = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z";
849type Regex_AZ = Uppercase<Regex_az>;
850type Regex_09 = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
851type Regex_w = Regex_az | Regex_AZ | Regex_09 | "_";
852/** Emulates Regex `+` operator */
853type RegexMatchPlus<char extends string, T extends string> = _RegexMatchPlus<char, T> extends infer result extends string ? result extends '' ? never : result : never;
854type _RegexMatchPlus<char extends string, T extends string> = T extends `${infer head extends char}${infer rest}` ? `${head}${_RegexMatchPlus<char, rest>}` : '';
855type ParamNameChar = Regex_w | "-";
856type Simplify<T> = {
857 [K in keyof T]: T[K];
858} & {};
859type GeneratePathParams<path extends string> = Simplify<ParseParams<path> & {
860 [key in string]: string | null | undefined;
861}>;
862type ParseParams<path extends string> = path extends '*' ? {
863 '*': string;
864} : path extends `${infer rest}/*` ? {
865 '*': string;
866} & ParseParams<rest> : _ParseParams<path>;
867type _ParseParams<path extends string> = path extends `${infer left}/${infer right}` ? _ParseParams<left> & _ParseParams<right> : path extends `:${infer param}?${string}` ? {
868 [key in RegexMatchPlus<ParamNameChar, param>]?: string | null | undefined;
869} : path extends `:${infer param}` ? {
870 [key in RegexMatchPlus<ParamNameChar, param>]: string;
871} : {};
872type PathParam<path extends string> = (keyof ParseParams<path>) & string;
873type ParamParseKey<Segment extends string> = [
874 PathParam<Segment>
875] extends [never] ? string : PathParam<Segment>;
876/**
877 * The parameters that were parsed from the URL path.
878 */
879type Params<Key extends string = string> = {
880 readonly [key in Key]: string | undefined;
881};
882/**
883 * A RouteMatch contains info about how a route matched a URL.
884 */
885interface RouteMatch<ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> {
886 /**
887 * The names and values of dynamic parameters in the URL.
888 */
889 params: Params<ParamKey>;
890 /**
891 * The portion of the URL pathname that was matched.
892 */
893 pathname: string;
894 /**
895 * The portion of the URL pathname that was matched before child routes.
896 */
897 pathnameBase: string;
898 /**
899 * The route object that was used to match.
900 */
901 route: RouteObjectType;
902}
903interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {
904}
905/**
906 * Matches the given routes to a location and returns the match data.
907 *
908 * @example
909 * import { matchRoutes } from "react-router";
910 *
911 * let routes = [{
912 * path: "/",
913 * Component: Root,
914 * children: [{
915 * path: "dashboard",
916 * Component: Dashboard,
917 * }]
918 * }];
919 *
920 * matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
921 *
922 * @public
923 * @category Utils
924 * @param routes The array of route objects to match against.
925 * @param locationArg The location to match against, either a string path or a
926 * partial {@link Location} object
927 * @param basename Optional base path to strip from the location before matching.
928 * Defaults to `/`.
929 * @returns An array of matched routes, or `null` if no matches were found.
930 */
931declare function matchRoutes<RouteObjectType extends RouteObject = RouteObject>(routes: RouteObjectType[], locationArg: Partial<Location> | string, basename?: string): RouteMatch<string, RouteObjectType>[] | null;
932interface UIMatch<Data = unknown, Handle = unknown> {
933 id: string;
934 pathname: string;
935 /**
936 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the matched route.
937 */
938 params: RouteMatch["params"];
939 /**
940 * The return value from the matched route's loader or clientLoader. This might
941 * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
942 * an error and we're currently displaying an `ErrorBoundary`.
943 *
944 * @deprecated Use `UIMatch.loaderData` instead
945 */
946 data: Data | undefined;
947 /**
948 * The return value from the matched route's loader or clientLoader. This might
949 * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
950 * an error and we're currently displaying an `ErrorBoundary`.
951 */
952 loaderData: Data | undefined;
953 /**
954 * The {@link https://reactrouter.com/start/framework/route-module#handle handle object}
955 * exported from the matched route module
956 */
957 handle: Handle;
958}
959/**
960 * Returns a path with params interpolated.
961 *
962 * @example
963 * import { generatePath } from "react-router";
964 *
965 * generatePath("/users/:id", { id: "123" }); // "/users/123"
966 *
967 * @public
968 * @category Utils
969 * @param originalPath The original path to generate.
970 * @param params The parameters to interpolate into the path.
971 * @returns The generated path with parameters interpolated.
972 */
973declare function generatePath<Path extends string>(originalPath: Path, params?: GeneratePathParams<Path>): string;
974/**
975 * Used to match on some portion of a URL pathname.
976 */
977interface PathPattern<Path extends string = string> {
978 /**
979 * A string to match against a URL pathname. May contain `:id`-style segments
980 * to indicate placeholders for dynamic parameters. It May also end with `/*`
981 * to indicate matching the rest of the URL pathname.
982 */
983 path: Path;
984 /**
985 * Should be `true` if the static portions of the `path` should be matched in
986 * the same case.
987 */
988 caseSensitive?: boolean;
989 /**
990 * Should be `true` if this pattern should match the entire URL pathname.
991 */
992 end?: boolean;
993}
994/**
995 * Contains info about how a {@link PathPattern} matched on a URL pathname.
996 */
997interface PathMatch<ParamKey extends string = string> {
998 /**
999 * The names and values of dynamic parameters in the URL.
1000 */
1001 params: Params<ParamKey>;
1002 /**
1003 * The portion of the URL pathname that was matched.
1004 */
1005 pathname: string;
1006 /**
1007 * The portion of the URL pathname that was matched before child routes.
1008 */
1009 pathnameBase: string;
1010 /**
1011 * The pattern that was used to match.
1012 */
1013 pattern: PathPattern;
1014}
1015/**
1016 * Performs pattern matching on a URL pathname and returns information about
1017 * the match.
1018 *
1019 * @public
1020 * @category Utils
1021 * @param pattern The pattern to match against the URL pathname. This can be a
1022 * string or a {@link PathPattern} object. If a string is provided, it will be
1023 * treated as a pattern with `caseSensitive` set to `false` and `end` set to
1024 * `true`.
1025 * @param pathname The URL pathname to match against the pattern.
1026 * @returns A path match object if the pattern matches the pathname,
1027 * or `null` if it does not match.
1028 */
1029declare function matchPath<Path extends string>(pattern: PathPattern<Path> | Path, pathname: string): PathMatch<ParamParseKey<Path>> | null;
1030/**
1031 * Returns a resolved {@link Path} object relative to the given pathname.
1032 *
1033 * @public
1034 * @category Utils
1035 * @param to The path to resolve, either a string or a partial {@link Path}
1036 * object.
1037 * @param fromPathname The pathname to resolve the path from. Defaults to `/`.
1038 * @returns A {@link Path} object with the resolved pathname, search, and hash.
1039 */
1040declare function resolvePath(to: To, fromPathname?: string): Path;
1041declare class DataWithResponseInit<D> {
1042 type: string;
1043 data: D;
1044 init: ResponseInit | null;
1045 constructor(data: D, init?: ResponseInit);
1046}
1047/**
1048 * Create "responses" that contain `headers`/`status` without forcing
1049 * serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1050 *
1051 * @example
1052 * import { data } from "react-router";
1053 *
1054 * export async function action({ request }: Route.ActionArgs) {
1055 * let formData = await request.formData();
1056 * let item = await createItem(formData);
1057 * return data(item, {
1058 * headers: { "X-Custom-Header": "value" }
1059 * status: 201,
1060 * });
1061 * }
1062 *
1063 * @public
1064 * @category Utils
1065 * @mode framework
1066 * @mode data
1067 * @param data The data to be included in the response.
1068 * @param init The status code or a `ResponseInit` object to be included in the
1069 * response.
1070 * @returns A {@link DataWithResponseInit} instance containing the data and
1071 * response init.
1072 */
1073declare function data<D>(data: D, init?: number | ResponseInit): DataWithResponseInit<D>;
1074interface TrackedPromise extends Promise<any> {
1075 _tracked?: boolean;
1076 _data?: any;
1077 _error?: any;
1078}
1079type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
1080/**
1081 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
1082 * Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1083 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
1084 *
1085 * This utility accepts absolute URLs and can navigate to external domains, so
1086 * the application should validate any user-supplied inputs to redirects.
1087 *
1088 * @example
1089 * import { redirect } from "react-router";
1090 *
1091 * export async function loader({ request }: Route.LoaderArgs) {
1092 * if (!isLoggedIn(request))
1093 * throw redirect("/login");
1094 * }
1095 *
1096 * // ...
1097 * }
1098 *
1099 * @public
1100 * @category Utils
1101 * @mode framework
1102 * @mode data
1103 * @param url The URL to redirect to.
1104 * @param init The status code or a `ResponseInit` object to be included in the
1105 * response.
1106 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1107 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1108 * header.
1109 */
1110declare const redirect: RedirectFunction;
1111/**
1112 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1113 * that will force a document reload to the new location. Sets the status code
1114 * and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1115 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
1116 *
1117 * This utility accepts absolute URLs and can navigate to external domains, so
1118 * the application should validate any user-supplied inputs to redirects.
1119 *
1120 * ```tsx filename=routes/logout.tsx
1121 * import { redirectDocument } from "react-router";
1122 *
1123 * import { destroySession } from "../sessions.server";
1124 *
1125 * export async function action({ request }: Route.ActionArgs) {
1126 * let session = await getSession(request.headers.get("Cookie"));
1127 * return redirectDocument("/", {
1128 * headers: { "Set-Cookie": await destroySession(session) }
1129 * });
1130 * }
1131 * ```
1132 *
1133 * @public
1134 * @category Utils
1135 * @mode framework
1136 * @mode data
1137 * @param url The URL to redirect to.
1138 * @param init The status code or a `ResponseInit` object to be included in the
1139 * response.
1140 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1141 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1142 * header.
1143 */
1144declare const redirectDocument: RedirectFunction;
1145/**
1146 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1147 * that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
1148 * instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
1149 * for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1150 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
1151 *
1152 * @example
1153 * import { replace } from "react-router";
1154 *
1155 * export async function loader() {
1156 * return replace("/new-location");
1157 * }
1158 *
1159 * @public
1160 * @category Utils
1161 * @mode framework
1162 * @mode data
1163 * @param url The URL to redirect to.
1164 * @param init The status code or a `ResponseInit` object to be included in the
1165 * response.
1166 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1167 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1168 * header.
1169 */
1170declare const replace: RedirectFunction;
1171type ErrorResponse = {
1172 status: number;
1173 statusText: string;
1174 data: any;
1175};
1176declare class ErrorResponseImpl implements ErrorResponse {
1177 status: number;
1178 statusText: string;
1179 data: any;
1180 private error?;
1181 private internal;
1182 constructor(status: number, statusText: string | undefined, data: any, internal?: boolean);
1183}
1184/**
1185 * Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
1186 * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1187 * thrown from an [`action`](../../start/framework/route-module#action) or
1188 * [`loader`](../../start/framework/route-module#loader) function.
1189 *
1190 * @example
1191 * import { isRouteErrorResponse } from "react-router";
1192 *
1193 * export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
1194 * if (isRouteErrorResponse(error)) {
1195 * return (
1196 * <>
1197 * <p>Error: `${error.status}: ${error.statusText}`</p>
1198 * <p>{error.data}</p>
1199 * </>
1200 * );
1201 * }
1202 *
1203 * return (
1204 * <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
1205 * );
1206 * }
1207 *
1208 * @public
1209 * @category Utils
1210 * @mode framework
1211 * @mode data
1212 * @param error The error to check.
1213 * @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
1214 */
1215declare function isRouteErrorResponse(error: any): error is ErrorResponse;
1216
1217/**
1218 * An object of unknown type for route loaders and actions provided by the
1219 * server's `getLoadContext()` function. This is defined as an empty interface
1220 * specifically so apps can leverage declaration merging to augment this type
1221 * globally: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
1222 */
1223interface AppLoadContext {
1224 [key: string]: unknown;
1225}
1226
1227type Primitive = null | undefined | string | number | boolean | symbol | bigint;
1228type LiteralUnion<LiteralType, BaseType extends Primitive> = LiteralType | (BaseType & Record<never, never>);
1229interface HtmlLinkProps {
1230 /**
1231 * Address of the hyperlink
1232 */
1233 href?: string;
1234 /**
1235 * How the element handles crossorigin requests
1236 */
1237 crossOrigin?: "anonymous" | "use-credentials";
1238 /**
1239 * Relationship between the document containing the hyperlink and the destination resource
1240 */
1241 rel: LiteralUnion<"alternate" | "dns-prefetch" | "icon" | "manifest" | "modulepreload" | "next" | "pingback" | "preconnect" | "prefetch" | "preload" | "prerender" | "search" | "stylesheet", string>;
1242 /**
1243 * Applicable media: "screen", "print", "(max-width: 764px)"
1244 */
1245 media?: string;
1246 /**
1247 * Integrity metadata used in Subresource Integrity checks
1248 */
1249 integrity?: string;
1250 /**
1251 * Language of the linked resource
1252 */
1253 hrefLang?: string;
1254 /**
1255 * Hint for the type of the referenced resource
1256 */
1257 type?: string;
1258 /**
1259 * Referrer policy for fetches initiated by the element
1260 */
1261 referrerPolicy?: "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
1262 /**
1263 * Sizes of the icons (for rel="icon")
1264 */
1265 sizes?: string;
1266 /**
1267 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
1268 */
1269 as?: LiteralUnion<"audio" | "audioworklet" | "document" | "embed" | "fetch" | "font" | "frame" | "iframe" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt", string>;
1270 /**
1271 * Color to use when customizing a site's icon (for rel="mask-icon")
1272 */
1273 color?: string;
1274 /**
1275 * Whether the link is disabled
1276 */
1277 disabled?: boolean;
1278 /**
1279 * The title attribute has special semantics on this element: Title of the link; CSS style sheet set name.
1280 */
1281 title?: string;
1282 /**
1283 * Images to use in different situations, e.g., high-resolution displays,
1284 * small monitors, etc. (for rel="preload")
1285 */
1286 imageSrcSet?: string;
1287 /**
1288 * Image sizes for different page layouts (for rel="preload")
1289 */
1290 imageSizes?: string;
1291}
1292interface HtmlLinkPreloadImage extends HtmlLinkProps {
1293 /**
1294 * Relationship between the document containing the hyperlink and the destination resource
1295 */
1296 rel: "preload";
1297 /**
1298 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
1299 */
1300 as: "image";
1301 /**
1302 * Address of the hyperlink
1303 */
1304 href?: string;
1305 /**
1306 * Images to use in different situations, e.g., high-resolution displays,
1307 * small monitors, etc. (for rel="preload")
1308 */
1309 imageSrcSet: string;
1310 /**
1311 * Image sizes for different page layouts (for rel="preload")
1312 */
1313 imageSizes?: string;
1314}
1315/**
1316 * Represents a `<link>` element.
1317 *
1318 * WHATWG Specification: https://html.spec.whatwg.org/multipage/semantics.html#the-link-element
1319 */
1320type HtmlLinkDescriptor = (HtmlLinkProps & Pick<Required<HtmlLinkProps>, "href">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "imageSizes">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "href"> & {
1321 imageSizes?: never;
1322});
1323interface PageLinkDescriptor extends Omit<HtmlLinkDescriptor, "href" | "rel" | "type" | "sizes" | "imageSrcSet" | "imageSizes" | "as" | "color" | "title"> {
1324 /**
1325 * A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
1326 * attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
1327 * element
1328 */
1329 nonce?: string | undefined;
1330 /**
1331 * The absolute path of the page to prefetch, e.g. `/absolute/path`.
1332 */
1333 page: string;
1334}
1335type LinkDescriptor = HtmlLinkDescriptor | PageLinkDescriptor;
1336
1337type Serializable = undefined | null | boolean | string | symbol | number | Array<Serializable> | {
1338 [key: PropertyKey]: Serializable;
1339} | bigint | Date | URL | RegExp | Error | Map<Serializable, Serializable> | Set<Serializable> | Promise<Serializable>;
1340
1341type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
1342type IsAny<T> = 0 extends 1 & T ? true : false;
1343type Func = (...args: any[]) => unknown;
1344type Pretty<T> = {
1345 [K in keyof T]: T[K];
1346} & {};
1347type Normalize<T> = _Normalize<UnionKeys<T>, T>;
1348type _Normalize<Key extends keyof any, T> = T extends infer U ? Pretty<{
1349 [K in Key as K extends keyof U ? undefined extends U[K] ? never : K : never]: K extends keyof U ? U[K] : never;
1350} & {
1351 [K in Key as K extends keyof U ? undefined extends U[K] ? K : never : never]?: K extends keyof U ? U[K] : never;
1352} & {
1353 [K in Key as K extends keyof U ? never : K]?: undefined;
1354}> : never;
1355type UnionKeys<T> = T extends any ? keyof T : never;
1356
1357type RouteModule$1 = {
1358 meta?: Func;
1359 links?: Func;
1360 headers?: Func;
1361 loader?: Func;
1362 clientLoader?: Func;
1363 action?: Func;
1364 clientAction?: Func;
1365 HydrateFallback?: Func;
1366 default?: Func;
1367 ErrorBoundary?: Func;
1368 [key: string]: unknown;
1369};
1370
1371/**
1372 * A brand that can be applied to a type to indicate that it will serialize
1373 * to a specific type when transported to the client from a loader.
1374 * Only use this if you have additional serialization/deserialization logic
1375 * in your application.
1376 */
1377type unstable_SerializesTo<T> = {
1378 unstable__ReactRouter_SerializesTo: [T];
1379};
1380
1381type Serialize<T> = T extends unstable_SerializesTo<infer To> ? To : T extends Serializable ? T : T extends (...args: any[]) => unknown ? undefined : T extends Promise<infer U> ? Promise<Serialize<U>> : T extends Map<infer K, infer V> ? Map<Serialize<K>, Serialize<V>> : T extends ReadonlyMap<infer K, infer V> ? ReadonlyMap<Serialize<K>, Serialize<V>> : T extends Set<infer U> ? Set<Serialize<U>> : T extends ReadonlySet<infer U> ? ReadonlySet<Serialize<U>> : T extends [] ? [] : T extends readonly [infer F, ...infer R] ? [Serialize<F>, ...Serialize<R>] : T extends Array<infer U> ? Array<Serialize<U>> : T extends readonly unknown[] ? readonly Serialize<T[number]>[] : T extends Record<any, any> ? {
1382 [K in keyof T]: Serialize<T[K]>;
1383} : undefined;
1384type VoidToUndefined<T> = Equal<T, void> extends true ? undefined : T;
1385type DataFrom<T> = IsAny<T> extends true ? undefined : T extends Func ? VoidToUndefined<Awaited<ReturnType<T>>> : undefined;
1386type ClientData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? U : T;
1387type ServerData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? Serialize<U> : Serialize<T>;
1388type ServerDataFrom<T> = ServerData<DataFrom<T>>;
1389type ClientDataFrom<T> = ClientData<DataFrom<T>>;
1390type ClientDataFunctionArgs<Params> = {
1391 /**
1392 * A {@link https://developer.mozilla.org/en-US/docs/Web/API/Request Fetch Request instance} which you can use to read the URL, the method, the "content-type" header, and the request body from the request.
1393 *
1394 * @note Because client data functions are called before a network request is made, the Request object does not include the headers which the browser automatically adds. React Router infers the "content-type" header from the enc-type of the form that performed the submission.
1395 **/
1396 request: Request;
1397 /**
1398 * A URL instance representing the application location being navigated to or fetched.
1399 * Without `future.unstable_passThroughRequests` enabled, this matches `request.url`.
1400 * With `future.unstable_passThroughRequests` enabled, this is a normalized
1401 * URL with React-Router-specific implementation details removed (`.data`
1402 * pathnames, `index`/`_routes` search params).
1403 * The URL includes the origin from the request for convenience.
1404 */
1405 unstable_url: URL;
1406 /**
1407 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
1408 * @example
1409 * // app/routes.ts
1410 * route("teams/:teamId", "./team.tsx"),
1411 *
1412 * // app/team.tsx
1413 * export function clientLoader({
1414 * params,
1415 * }: Route.ClientLoaderArgs) {
1416 * params.teamId;
1417 * // ^ string
1418 * }
1419 **/
1420 params: Params;
1421 /**
1422 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
1423 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
1424 */
1425 unstable_pattern: string;
1426 /**
1427 * When `future.v8_middleware` is not enabled, this is undefined.
1428 *
1429 * When `future.v8_middleware` is enabled, this is an instance of
1430 * `RouterContextProvider` and can be used to access context values
1431 * from your route middlewares. You may pass in initial context values in your
1432 * `<HydratedRouter getContext>` prop
1433 */
1434 context: Readonly<RouterContextProvider>;
1435};
1436type ServerDataFunctionArgs<Params> = {
1437 /** A {@link https://developer.mozilla.org/en-US/docs/Web/API/Request Fetch Request instance} which you can use to read the url, method, headers (such as cookies), and request body from the request. */
1438 request: Request;
1439 /**
1440 * A URL instance representing the application location being navigated to or fetched.
1441 * Without `future.unstable_passThroughRequests` enabled, this matches `request.url`.
1442 * With `future.unstable_passThroughRequests` enabled, this is a normalized
1443 * URL with React-Router-specific implementation details removed (`.data`
1444 * pathnames, `index`/`_routes` search params).
1445 * The URL includes the origin from the request for convenience.
1446 */
1447 unstable_url: URL;
1448 /**
1449 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
1450 * @example
1451 * // app/routes.ts
1452 * route("teams/:teamId", "./team.tsx"),
1453 *
1454 * // app/team.tsx
1455 * export function loader({
1456 * params,
1457 * }: Route.LoaderArgs) {
1458 * params.teamId;
1459 * // ^ string
1460 * }
1461 **/
1462 params: Params;
1463 /**
1464 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
1465 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
1466 */
1467 unstable_pattern: string;
1468 /**
1469 * Without `future.v8_middleware` enabled, this is the context passed in
1470 * to your server adapter's `getLoadContext` function. It's a way to bridge the
1471 * gap between the adapter's request/response API with your React Router app.
1472 * It is only applicable if you are using a custom server adapter.
1473 *
1474 * With `future.v8_middleware` enabled, this is an instance of
1475 * `RouterContextProvider` and can be used for type-safe access to
1476 * context value set in your route middlewares. If you are using a custom
1477 * server adapter, you may provide an initial set of context values from your
1478 * `getLoadContext` function.
1479 */
1480 context: MiddlewareEnabled extends true ? Readonly<RouterContextProvider> : AppLoadContext;
1481};
1482type SerializeFrom<T> = T extends (...args: infer Args) => unknown ? Args extends [
1483 ClientLoaderFunctionArgs | ClientActionFunctionArgs | ClientDataFunctionArgs<unknown>
1484] ? ClientDataFrom<T> : ServerDataFrom<T> : T;
1485type IsDefined<T> = Equal<T, undefined> extends true ? false : true;
1486type IsHydrate<ClientLoader> = ClientLoader extends {
1487 hydrate: true;
1488} ? true : ClientLoader extends {
1489 hydrate: false;
1490} ? false : false;
1491type GetLoaderData<T extends RouteModule$1> = _DataLoaderData<ServerDataFrom<T["loader"]>, ClientDataFrom<T["clientLoader"]>, IsHydrate<T["clientLoader"]>, T extends {
1492 HydrateFallback: Func;
1493} ? true : false>;
1494type _DataLoaderData<ServerLoaderData, ClientLoaderData, ClientLoaderHydrate extends boolean, HasHydrateFallback> = [
1495 HasHydrateFallback,
1496 ClientLoaderHydrate
1497] extends [true, true] ? IsDefined<ClientLoaderData> extends true ? ClientLoaderData : undefined : [
1498 IsDefined<ClientLoaderData>,
1499 IsDefined<ServerLoaderData>
1500] extends [true, true] ? ServerLoaderData | ClientLoaderData : IsDefined<ClientLoaderData> extends true ? ClientLoaderData : IsDefined<ServerLoaderData> extends true ? ServerLoaderData : undefined;
1501type GetActionData<T extends RouteModule$1> = _DataActionData<ServerDataFrom<T["action"]>, ClientDataFrom<T["clientAction"]>>;
1502type _DataActionData<ServerActionData, ClientActionData> = Awaited<[
1503 IsDefined<ServerActionData>,
1504 IsDefined<ClientActionData>
1505] extends [true, true] ? ServerActionData | ClientActionData : IsDefined<ClientActionData> extends true ? ClientActionData : IsDefined<ServerActionData> extends true ? ServerActionData : undefined>;
1506
1507interface RouteModules {
1508 [routeId: string]: RouteModule | undefined;
1509}
1510/**
1511 * The shape of a route module shipped to the client
1512 */
1513interface RouteModule {
1514 clientAction?: ClientActionFunction;
1515 clientLoader?: ClientLoaderFunction;
1516 clientMiddleware?: MiddlewareFunction<Record<string, DataStrategyResult>>[];
1517 ErrorBoundary?: ErrorBoundaryComponent;
1518 HydrateFallback?: HydrateFallbackComponent;
1519 Layout?: LayoutComponent;
1520 default: RouteComponent;
1521 handle?: RouteHandle;
1522 links?: LinksFunction;
1523 meta?: MetaFunction;
1524 shouldRevalidate?: ShouldRevalidateFunction;
1525}
1526/**
1527 * The shape of a route module on the server
1528 */
1529interface ServerRouteModule extends RouteModule {
1530 action?: ActionFunction;
1531 headers?: HeadersFunction | {
1532 [name: string]: string;
1533 };
1534 loader?: LoaderFunction;
1535 middleware?: MiddlewareFunction<Response>[];
1536}
1537/**
1538 * A function that handles data mutations for a route on the client
1539 */
1540type ClientActionFunction = (args: ClientActionFunctionArgs) => ReturnType<ActionFunction>;
1541/**
1542 * Arguments passed to a route `clientAction` function
1543 */
1544type ClientActionFunctionArgs = ActionFunctionArgs & {
1545 serverAction: <T = unknown>() => Promise<SerializeFrom<T>>;
1546};
1547/**
1548 * A function that loads data for a route on the client
1549 */
1550type ClientLoaderFunction = ((args: ClientLoaderFunctionArgs) => ReturnType<LoaderFunction>) & {
1551 hydrate?: boolean;
1552};
1553/**
1554 * Arguments passed to a route `clientLoader` function
1555 */
1556type ClientLoaderFunctionArgs = LoaderFunctionArgs & {
1557 serverLoader: <T = unknown>() => Promise<SerializeFrom<T>>;
1558};
1559/**
1560 * ErrorBoundary to display for this route
1561 */
1562type ErrorBoundaryComponent = ComponentType;
1563type HeadersArgs = {
1564 loaderHeaders: Headers;
1565 parentHeaders: Headers;
1566 actionHeaders: Headers;
1567 errorHeaders: Headers | undefined;
1568};
1569/**
1570 * A function that returns HTTP headers to be used for a route. These headers
1571 * will be merged with (and take precedence over) headers from parent routes.
1572 */
1573interface HeadersFunction {
1574 (args: HeadersArgs): Headers | HeadersInit;
1575}
1576/**
1577 * `<Route HydrateFallback>` component to render on initial loads
1578 * when client loaders are present
1579 */
1580type HydrateFallbackComponent = ComponentType;
1581/**
1582 * Optional, root-only `<Route Layout>` component to wrap the root content in.
1583 * Useful for defining the <html>/<head>/<body> document shell shared by the
1584 * Component, HydrateFallback, and ErrorBoundary
1585 */
1586type LayoutComponent = ComponentType<{
1587 children: ReactElement<unknown, ErrorBoundaryComponent | HydrateFallbackComponent | RouteComponent>;
1588}>;
1589/**
1590 * A function that defines `<link>` tags to be inserted into the `<head>` of
1591 * the document on route transitions.
1592 *
1593 * @see https://reactrouter.com/start/framework/route-module#meta
1594 */
1595interface LinksFunction {
1596 (): LinkDescriptor[];
1597}
1598interface MetaMatch<RouteId extends string = string, Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown> {
1599 id: RouteId;
1600 pathname: DataRouteMatch["pathname"];
1601 /** @deprecated Use `MetaMatch.loaderData` instead */
1602 data: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
1603 loaderData: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
1604 handle?: RouteHandle;
1605 params: DataRouteMatch["params"];
1606 meta: MetaDescriptor[];
1607 error?: unknown;
1608}
1609type MetaMatches<MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> = Array<{
1610 [K in keyof MatchLoaders]: MetaMatch<Exclude<K, number | symbol>, MatchLoaders[K]>;
1611}[keyof MatchLoaders]>;
1612interface MetaArgs<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
1613 /** @deprecated Use `MetaArgs.loaderData` instead */
1614 data: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
1615 loaderData: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
1616 params: Params;
1617 location: Location;
1618 matches: MetaMatches<MatchLoaders>;
1619 error?: unknown;
1620}
1621/**
1622 * A function that returns an array of data objects to use for rendering
1623 * metadata HTML tags in a route. These tags are not rendered on descendant
1624 * routes in the route hierarchy. In other words, they will only be rendered on
1625 * the route in which they are exported.
1626 *
1627 * @param Loader - The type of the current route's loader function
1628 * @param MatchLoaders - Mapping from a parent route's filepath to its loader
1629 * function type
1630 *
1631 * Note that parent route filepaths are relative to the `app/` directory.
1632 *
1633 * For example, if this meta function is for `/sales/customers/$customerId`:
1634 *
1635 * ```ts
1636 * // app/root.tsx
1637 * const loader = () => ({ hello: "world" })
1638 * export type Loader = typeof loader
1639 *
1640 * // app/routes/sales.tsx
1641 * const loader = () => ({ salesCount: 1074 })
1642 * export type Loader = typeof loader
1643 *
1644 * // app/routes/sales/customers.tsx
1645 * const loader = () => ({ customerCount: 74 })
1646 * export type Loader = typeof loader
1647 *
1648 * // app/routes/sales/customers/$customersId.tsx
1649 * import type { Loader as RootLoader } from "../../../root"
1650 * import type { Loader as SalesLoader } from "../../sales"
1651 * import type { Loader as CustomersLoader } from "../../sales/customers"
1652 *
1653 * const loader = () => ({ name: "Customer name" })
1654 *
1655 * const meta: MetaFunction<typeof loader, {
1656 * "root": RootLoader,
1657 * "routes/sales": SalesLoader,
1658 * "routes/sales/customers": CustomersLoader,
1659 * }> = ({ data, matches }) => {
1660 * const { name } = data
1661 * // ^? string
1662 * const { customerCount } = matches.find((match) => match.id === "routes/sales/customers").data
1663 * // ^? number
1664 * const { salesCount } = matches.find((match) => match.id === "routes/sales").data
1665 * // ^? number
1666 * const { hello } = matches.find((match) => match.id === "root").data
1667 * // ^? "world"
1668 * }
1669 * ```
1670 */
1671interface MetaFunction<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
1672 (args: MetaArgs<Loader, MatchLoaders>): MetaDescriptor[] | undefined;
1673}
1674type MetaDescriptor = {
1675 charSet: "utf-8";
1676} | {
1677 title: string;
1678} | {
1679 name: string;
1680 content: string;
1681} | {
1682 property: string;
1683 content: string;
1684} | {
1685 httpEquiv: string;
1686 content: string;
1687} | {
1688 "script:ld+json": LdJsonObject;
1689} | {
1690 tagName: "meta" | "link";
1691 [name: string]: string;
1692} | {
1693 [name: string]: unknown;
1694};
1695type LdJsonObject = {
1696 [Key in string]: LdJsonValue;
1697} & {
1698 [Key in string]?: LdJsonValue | undefined;
1699};
1700type LdJsonArray = LdJsonValue[] | readonly LdJsonValue[];
1701type LdJsonPrimitive = string | number | boolean | null;
1702type LdJsonValue = LdJsonPrimitive | LdJsonObject | LdJsonArray;
1703/**
1704 * A React component that is rendered for a route.
1705 */
1706type RouteComponent = ComponentType<{}>;
1707/**
1708 * An arbitrary object that is associated with a route.
1709 *
1710 * @see https://reactrouter.com/how-to/using-handle
1711 */
1712type RouteHandle = unknown;
1713
1714export { type BaseRouteObject as $, type ActionFunction as A, type DataStrategyResult as B, type ClientActionFunction as C, type DataRouteMatch as D, type ServerDataFrom as E, type FormEncType as F, type GetLoaderData as G, type HeadersFunction as H, type GetActionData as I, type RouteModules as J, type SerializeFrom as K, type Location as L, type MetaFunction as M, type Normalize as N, type PathPattern as O, type Params as P, type PathMatch as Q, type RouteModule$1 as R, type ShouldRevalidateFunction as S, type To as T, type UIMatch as U, type ParamParseKey as V, type InitialEntry as W, type IndexRouteObject as X, type NonIndexRouteObject as Y, type Equal as Z, type ActionFunctionArgs as _, type ClientLoaderFunction as a, type DataStrategyFunctionArgs as a0, type DataStrategyMatch as a1, DataWithResponseInit as a2, type ErrorResponse as a3, type FormMethod as a4, type LazyRouteFunction as a5, type MiddlewareFunction as a6, type PatchRoutesOnNavigationFunctionArgs as a7, type PathParam as a8, type RedirectFunction as a9, invariant as aA, ErrorResponseImpl as aB, type RouteManifest as aC, type ServerRouteModule as aD, type TrackedPromise as aE, type RouteMatch as aa, type RouterContext as ab, type ShouldRevalidateFunctionArgs as ac, createContext as ad, createPath as ae, parsePath as af, data as ag, generatePath as ah, isRouteErrorResponse as ai, matchPath as aj, matchRoutes as ak, redirect as al, redirectDocument as am, replace as an, resolvePath as ao, type ClientActionFunctionArgs as ap, type ClientLoaderFunctionArgs as aq, type HeadersArgs as ar, type MetaArgs as as, type PageLinkDescriptor as at, type HtmlLinkDescriptor as au, type Future as av, type unstable_SerializesTo as aw, createMemoryHistory as ax, createBrowserHistory as ay, createHashHistory as az, type LinksFunction as b, RouterContextProvider as c, type LoaderFunction as d, type RouteObject as e, type History as f, type MaybePromise as g, type MapRoutePropertiesFunction as h, Action as i, type Submission as j, type RouteData as k, type DataStrategyFunction as l, type PatchRoutesOnNavigationFunction as m, type DataRouteObject as n, type HTMLFormMethod as o, type Path as p, type LoaderFunctionArgs as q, type MiddlewareEnabled as r, type AppLoadContext as s, type LinkDescriptor as t, type Func as u, type Pretty as v, type MetaDescriptor as w, type ServerDataFunctionArgs as x, type MiddlewareNextFunction as y, type ClientDataFunctionArgs as z };