UNPKG

127 kBTypeScriptView 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/**
73 * A change to the current location.
74 */
75interface Update {
76 /**
77 * The action that triggered the change.
78 */
79 action: Action;
80 /**
81 * The new location.
82 */
83 location: Location;
84 /**
85 * The delta between this location and the former location in the history stack
86 */
87 delta: number | null;
88}
89/**
90 * A function that receives notifications about location changes.
91 */
92interface Listener {
93 (update: Update): void;
94}
95/**
96 * Describes a location that is the destination of some navigation used in
97 * {@link Link}, {@link useNavigate}, etc.
98 */
99type To = string | Partial<Path>;
100/**
101 * A history is an interface to the navigation stack. The history serves as the
102 * source of truth for the current location, as well as provides a set of
103 * methods that may be used to change it.
104 *
105 * It is similar to the DOM's `window.history` object, but with a smaller, more
106 * focused API.
107 */
108interface History {
109 /**
110 * The last action that modified the current location. This will always be
111 * Action.Pop when a history instance is first created. This value is mutable.
112 */
113 readonly action: Action;
114 /**
115 * The current location. This value is mutable.
116 */
117 readonly location: Location;
118 /**
119 * Returns a valid href for the given `to` value that may be used as
120 * the value of an <a href> attribute.
121 *
122 * @param to - The destination URL
123 */
124 createHref(to: To): string;
125 /**
126 * Returns a URL for the given `to` value
127 *
128 * @param to - The destination URL
129 */
130 createURL(to: To): URL;
131 /**
132 * Encode a location the same way window.history would do (no-op for memory
133 * history) so we ensure our PUSH/REPLACE navigations for data routers
134 * behave the same as POP
135 *
136 * @param to Unencoded path
137 */
138 encodeLocation(to: To): Path;
139 /**
140 * Pushes a new location onto the history stack, increasing its length by one.
141 * If there were any entries in the stack after the current one, they are
142 * lost.
143 *
144 * @param to - The new URL
145 * @param state - Data to associate with the new location
146 */
147 push(to: To, state?: any): void;
148 /**
149 * Replaces the current location in the history stack with a new one. The
150 * location that was replaced will no longer be available.
151 *
152 * @param to - The new URL
153 * @param state - Data to associate with the new location
154 */
155 replace(to: To, state?: any): void;
156 /**
157 * Navigates `n` entries backward/forward in the history stack relative to the
158 * current index. For example, a "back" navigation would use go(-1).
159 *
160 * @param delta - The delta in the stack index
161 */
162 go(delta: number): void;
163 /**
164 * Sets up a listener that will be called whenever the current location
165 * changes.
166 *
167 * @param listener - A function that will be called when the location changes
168 * @returns unlisten - A function that may be used to stop listening
169 */
170 listen(listener: Listener): () => void;
171}
172/**
173 * A user-supplied object that describes a location. Used when providing
174 * entries to `createMemoryHistory` via its `initialEntries` option.
175 */
176type InitialEntry = string | Partial<Location>;
177type MemoryHistoryOptions = {
178 initialEntries?: InitialEntry[];
179 initialIndex?: number;
180 v5Compat?: boolean;
181};
182/**
183 * A memory history stores locations in memory. This is useful in stateful
184 * environments where there is no web browser, such as node tests or React
185 * Native.
186 */
187interface MemoryHistory extends History {
188 /**
189 * The current index in the history stack.
190 */
191 readonly index: number;
192}
193/**
194 * Memory history stores the current location in memory. It is designed for use
195 * in stateful non-browser environments like tests and React Native.
196 */
197declare function createMemoryHistory(options?: MemoryHistoryOptions): MemoryHistory;
198/**
199 * A browser history stores the current location in regular URLs in a web
200 * browser environment. This is the standard for most web apps and provides the
201 * cleanest URLs the browser's address bar.
202 *
203 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory
204 */
205interface BrowserHistory extends UrlHistory {
206}
207type BrowserHistoryOptions = UrlHistoryOptions;
208/**
209 * Browser history stores the location in regular URLs. This is the standard for
210 * most web apps, but it requires some configuration on the server to ensure you
211 * serve the same app at multiple URLs.
212 *
213 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
214 */
215declare function createBrowserHistory(options?: BrowserHistoryOptions): BrowserHistory;
216/**
217 * A hash history stores the current location in the fragment identifier portion
218 * of the URL in a web browser environment.
219 *
220 * This is ideal for apps that do not control the server for some reason
221 * (because the fragment identifier is never sent to the server), including some
222 * shared hosting environments that do not provide fine-grained controls over
223 * which pages are served at which URLs.
224 *
225 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory
226 */
227interface HashHistory extends UrlHistory {
228}
229type HashHistoryOptions = UrlHistoryOptions;
230/**
231 * Hash history stores the location in window.location.hash. This makes it ideal
232 * for situations where you don't want to send the location to the server for
233 * some reason, either because you do cannot configure it or the URL space is
234 * reserved for something else.
235 *
236 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
237 */
238declare function createHashHistory(options?: HashHistoryOptions): HashHistory;
239/**
240 * @private
241 */
242declare function invariant(value: boolean, message?: string): asserts value;
243declare function invariant<T>(value: T | null | undefined, message?: string): asserts value is T;
244/**
245 * Creates a string URL path from the given pathname, search, and hash components.
246 *
247 * @category Utils
248 */
249declare function createPath({ pathname, search, hash, }: Partial<Path>): string;
250/**
251 * Parses a string URL path into its separate pathname, search, and hash components.
252 *
253 * @category Utils
254 */
255declare function parsePath(path: string): Partial<Path>;
256interface UrlHistory extends History {
257}
258type UrlHistoryOptions = {
259 window?: Window;
260 v5Compat?: boolean;
261};
262
263type MaybePromise<T> = T | Promise<T>;
264/**
265 * Map of routeId -> data returned from a loader/action/error
266 */
267interface RouteData {
268 [routeId: string]: any;
269}
270type LowerCaseFormMethod = "get" | "post" | "put" | "patch" | "delete";
271type UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;
272/**
273 * Users can specify either lowercase or uppercase form methods on `<Form>`,
274 * useSubmit(), `<fetcher.Form>`, etc.
275 */
276type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;
277/**
278 * Active navigation/fetcher form methods are exposed in uppercase on the
279 * RouterState. This is to align with the normalization done via fetch().
280 */
281type FormMethod = UpperCaseFormMethod;
282type FormEncType = "application/x-www-form-urlencoded" | "multipart/form-data" | "application/json" | "text/plain";
283type JsonObject = {
284 [Key in string]: JsonValue;
285} & {
286 [Key in string]?: JsonValue | undefined;
287};
288type JsonArray = JsonValue[] | readonly JsonValue[];
289type JsonPrimitive = string | number | boolean | null;
290type JsonValue = JsonPrimitive | JsonObject | JsonArray;
291/**
292 * @private
293 * Internal interface to pass around for action submissions, not intended for
294 * external consumption
295 */
296type Submission = {
297 formMethod: FormMethod;
298 formAction: string;
299 formEncType: FormEncType;
300 formData: FormData;
301 json: undefined;
302 text: undefined;
303} | {
304 formMethod: FormMethod;
305 formAction: string;
306 formEncType: FormEncType;
307 formData: undefined;
308 json: JsonValue;
309 text: undefined;
310} | {
311 formMethod: FormMethod;
312 formAction: string;
313 formEncType: FormEncType;
314 formData: undefined;
315 json: undefined;
316 text: string;
317};
318/**
319 * A context instance used as the key for the `get`/`set` methods of a
320 * {@link RouterContextProvider}. Accepts an optional default
321 * value to be returned if no value has been set.
322 */
323interface RouterContext<T = unknown> {
324 defaultValue?: T;
325}
326/**
327 * Creates a type-safe {@link RouterContext} object that can be used to
328 * store and retrieve arbitrary values in [`action`](../../start/framework/route-module#action)s,
329 * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
330 * Similar to React's [`createContext`](https://react.dev/reference/react/createContext),
331 * but specifically designed for React Router's request/response lifecycle.
332 *
333 * If a `defaultValue` is provided, it will be returned from `context.get()`
334 * when no value has been set for the context. Otherwise, reading this context
335 * when no value has been set will throw an error.
336 *
337 * ```tsx filename=app/context.ts
338 * import { createContext } from "react-router";
339 *
340 * // Create a context for user data
341 * export const userContext =
342 * createContext<User | null>(null);
343 * ```
344 *
345 * ```tsx filename=app/middleware/auth.ts
346 * import { getUserFromSession } from "~/auth.server";
347 * import { userContext } from "~/context";
348 *
349 * export const authMiddleware = async ({
350 * context,
351 * request,
352 * }) => {
353 * const user = await getUserFromSession(request);
354 * context.set(userContext, user);
355 * };
356 * ```
357 *
358 * ```tsx filename=app/routes/profile.tsx
359 * import { userContext } from "~/context";
360 *
361 * export async function loader({
362 * context,
363 * }: Route.LoaderArgs) {
364 * const user = context.get(userContext);
365 *
366 * if (!user) {
367 * throw new Response("Unauthorized", { status: 401 });
368 * }
369 *
370 * return { user };
371 * }
372 * ```
373 *
374 * @public
375 * @category Utils
376 * @mode framework
377 * @mode data
378 * @param defaultValue An optional default value for the context. This value
379 * will be returned if no value has been set for this context.
380 * @returns A {@link RouterContext} object that can be used with
381 * `context.get()` and `context.set()` in [`action`](../../start/framework/route-module#action)s,
382 * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
383 */
384declare function createContext<T>(defaultValue?: T): RouterContext<T>;
385/**
386 * Provides methods for writing/reading values in application context in a
387 * type-safe way. Primarily for usage with [middleware](../../how-to/middleware).
388 *
389 * @example
390 * import {
391 * createContext,
392 * RouterContextProvider
393 * } from "react-router";
394 *
395 * const userContext = createContext<User | null>(null);
396 * const contextProvider = new RouterContextProvider();
397 * contextProvider.set(userContext, getUser());
398 * // ^ Type-safe
399 * const user = contextProvider.get(userContext);
400 * // ^ User
401 *
402 * @public
403 * @category Utils
404 * @mode framework
405 * @mode data
406 */
407declare class RouterContextProvider {
408 #private;
409 /**
410 * Create a new `RouterContextProvider` instance
411 * @param init An optional initial context map to populate the provider with
412 */
413 constructor(init?: Map<RouterContext, unknown>);
414 /**
415 * Access a value from the context. If no value has been set for the context,
416 * it will return the context's `defaultValue` if provided, or throw an error
417 * if no `defaultValue` was set.
418 * @param context The context to get the value for
419 * @returns The value for the context, or the context's `defaultValue` if no
420 * value was set
421 */
422 get<T>(context: RouterContext<T>): T;
423 /**
424 * Set a value for the context. If the context already has a value set, this
425 * will overwrite it.
426 *
427 * @param context The context to set the value for
428 * @param value The value to set for the context
429 * @returns {void}
430 */
431 set<C extends RouterContext>(context: C, value: C extends RouterContext<infer T> ? T : never): void;
432}
433type DefaultContext = MiddlewareEnabled extends true ? Readonly<RouterContextProvider> : any;
434/**
435 * @private
436 * Arguments passed to route loader/action functions. Same for now but we keep
437 * this as a private implementation detail in case they diverge in the future.
438 */
439interface DataFunctionArgs<Context> {
440 /** 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. */
441 request: Request;
442 /**
443 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
444 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
445 */
446 unstable_pattern: string;
447 /**
448 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
449 * @example
450 * // app/routes.ts
451 * route("teams/:teamId", "./team.tsx"),
452 *
453 * // app/team.tsx
454 * export function loader({
455 * params,
456 * }: Route.LoaderArgs) {
457 * params.teamId;
458 * // ^ string
459 * }
460 */
461 params: Params;
462 /**
463 * This is the context passed in to your server adapter's getLoadContext() function.
464 * It's a way to bridge the gap between the adapter's request/response API with your React Router app.
465 * It is only applicable if you are using a custom server adapter.
466 */
467 context: Context;
468}
469/**
470 * Route middleware `next` function to call downstream handlers and then complete
471 * middlewares from the bottom-up
472 */
473interface MiddlewareNextFunction<Result = unknown> {
474 (): Promise<Result>;
475}
476/**
477 * Route middleware function signature. Receives the same "data" arguments as a
478 * `loader`/`action` (`request`, `params`, `context`) as the first parameter and
479 * a `next` function as the second parameter which will call downstream handlers
480 * and then complete middlewares from the bottom-up
481 */
482type MiddlewareFunction<Result = unknown> = (args: DataFunctionArgs<Readonly<RouterContextProvider>>, next: MiddlewareNextFunction<Result>) => MaybePromise<Result | void>;
483/**
484 * Arguments passed to loader functions
485 */
486interface LoaderFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
487}
488/**
489 * Arguments passed to action functions
490 */
491interface ActionFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
492}
493/**
494 * Loaders and actions can return anything
495 */
496type DataFunctionValue = unknown;
497type DataFunctionReturnValue = MaybePromise<DataFunctionValue>;
498/**
499 * Route loader function signature
500 */
501type LoaderFunction<Context = DefaultContext> = {
502 (args: LoaderFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
503} & {
504 hydrate?: boolean;
505};
506/**
507 * Route action function signature
508 */
509interface ActionFunction<Context = DefaultContext> {
510 (args: ActionFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
511}
512/**
513 * Arguments passed to shouldRevalidate function
514 */
515interface ShouldRevalidateFunctionArgs {
516 /** 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. */
517 currentUrl: URL;
518 /** 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. */
519 currentParams: AgnosticDataRouteMatch["params"];
520 /** 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. */
521 nextUrl: URL;
522 /** 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. */
523 nextParams: AgnosticDataRouteMatch["params"];
524 /** The method (probably `"GET"` or `"POST"`) used in the form submission that triggered the revalidation. */
525 formMethod?: Submission["formMethod"];
526 /** The form action (`<Form action="/somewhere">`) that triggered the revalidation. */
527 formAction?: Submission["formAction"];
528 /** The form encType (`<Form encType="application/x-www-form-urlencoded">) used in the form submission that triggered the revalidation*/
529 formEncType?: Submission["formEncType"];
530 /** The form submission data when the form's encType is `text/plain` */
531 text?: Submission["text"];
532 /** The form submission data when the form's encType is `application/x-www-form-urlencoded` or `multipart/form-data` */
533 formData?: Submission["formData"];
534 /** The form submission data when the form's encType is `application/json` */
535 json?: Submission["json"];
536 /** The status code of the action response */
537 actionStatus?: number;
538 /**
539 * 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.
540 *
541 * @example
542 * export async function action() {
543 * await saveSomeStuff();
544 * return { ok: true };
545 * }
546 *
547 * export function shouldRevalidate({
548 * actionResult,
549 * }) {
550 * if (actionResult?.ok) {
551 * return false;
552 * }
553 * return true;
554 * }
555 */
556 actionResult?: any;
557 /**
558 * 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:
559 *
560 * /projects/123/tasks/abc
561 * /projects/123/tasks/def
562 * React Router will only call the loader for tasks/def because the param for projects/123 didn't change.
563 *
564 * 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.
565 */
566 defaultShouldRevalidate: boolean;
567}
568/**
569 * Route shouldRevalidate function signature. This runs after any submission
570 * (navigation or fetcher), so we flatten the navigation/fetcher submission
571 * onto the arguments. It shouldn't matter whether it came from a navigation
572 * or a fetcher, what really matters is the URLs and the formData since loaders
573 * have to re-run based on the data models that were potentially mutated.
574 */
575interface ShouldRevalidateFunction {
576 (args: ShouldRevalidateFunctionArgs): boolean;
577}
578interface DataStrategyMatch extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {
579 /**
580 * @private
581 */
582 _lazyPromises?: {
583 middleware: Promise<void> | undefined;
584 handler: Promise<void> | undefined;
585 route: Promise<void> | undefined;
586 };
587 /**
588 * @deprecated Deprecated in favor of `shouldCallHandler`
589 *
590 * A boolean value indicating whether this route handler should be called in
591 * this pass.
592 *
593 * The `matches` array always includes _all_ matched routes even when only
594 * _some_ route handlers need to be called so that things like middleware can
595 * be implemented.
596 *
597 * `shouldLoad` is usually only interesting if you are skipping the route
598 * handler entirely and implementing custom handler logic - since it lets you
599 * determine if that custom logic should run for this route or not.
600 *
601 * For example:
602 * - If you are on `/parent/child/a` and you navigate to `/parent/child/b` -
603 * you'll get an array of three matches (`[parent, child, b]`), but only `b`
604 * will have `shouldLoad=true` because the data for `parent` and `child` is
605 * already loaded
606 * - If you are on `/parent/child/a` and you submit to `a`'s [`action`](https://reactrouter.com/docs/start/data/route-object#action),
607 * then only `a` will have `shouldLoad=true` for the action execution of
608 * `dataStrategy`
609 * - After the [`action`](https://reactrouter.com/docs/start/data/route-object#action),
610 * `dataStrategy` will be called again for the [`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
611 * revalidation, and all matches will have `shouldLoad=true` (assuming no
612 * custom `shouldRevalidate` implementations)
613 */
614 shouldLoad: boolean;
615 /**
616 * Arguments passed to the `shouldRevalidate` function for this `loader` execution.
617 * Will be `null` if this is not a revalidating loader {@link DataStrategyMatch}.
618 */
619 shouldRevalidateArgs: ShouldRevalidateFunctionArgs | null;
620 /**
621 * Determine if this route's handler should be called during this `dataStrategy`
622 * execution. Calling it with no arguments will leverage the default revalidation
623 * behavior. You can pass your own `defaultShouldRevalidate` value if you wish
624 * to change the default revalidation behavior with your `dataStrategy`.
625 *
626 * @param defaultShouldRevalidate `defaultShouldRevalidate` override value (optional)
627 */
628 shouldCallHandler(defaultShouldRevalidate?: boolean): boolean;
629 /**
630 * An async function that will resolve any `route.lazy` implementations and
631 * execute the route's handler (if necessary), returning a {@link DataStrategyResult}
632 *
633 * - Calling `match.resolve` does not mean you're calling the
634 * [`action`](https://reactrouter.com/docs/start/data/route-object#action)/[`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
635 * (the "handler") - `resolve` will only call the `handler` internally if
636 * needed _and_ if you don't pass your own `handlerOverride` function parameter
637 * - It is safe to call `match.resolve` for all matches, even if they have
638 * `shouldLoad=false`, and it will no-op if no loading is required
639 * - You should generally always call `match.resolve()` for `shouldLoad:true`
640 * routes to ensure that any `route.lazy` implementations are processed
641 * - See the examples below for how to implement custom handler execution via
642 * `match.resolve`
643 */
644 resolve: (handlerOverride?: (handler: (ctx?: unknown) => DataFunctionReturnValue) => DataFunctionReturnValue) => Promise<DataStrategyResult>;
645}
646interface DataStrategyFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
647 /**
648 * Matches for this route extended with Data strategy APIs
649 */
650 matches: DataStrategyMatch[];
651 runClientMiddleware: (cb: DataStrategyFunction<Context>) => Promise<Record<string, DataStrategyResult>>;
652 /**
653 * The key of the fetcher we are calling `dataStrategy` for, otherwise `null`
654 * for navigational executions
655 */
656 fetcherKey: string | null;
657}
658/**
659 * Result from a loader or action called via dataStrategy
660 */
661interface DataStrategyResult {
662 type: "data" | "error";
663 result: unknown;
664}
665interface DataStrategyFunction<Context = DefaultContext> {
666 (args: DataStrategyFunctionArgs<Context>): Promise<Record<string, DataStrategyResult>>;
667}
668type AgnosticPatchRoutesOnNavigationFunctionArgs<O extends AgnosticRouteObject = AgnosticRouteObject, M extends AgnosticRouteMatch = AgnosticRouteMatch> = {
669 signal: AbortSignal;
670 path: string;
671 matches: M[];
672 fetcherKey: string | undefined;
673 patch: (routeId: string | null, children: O[]) => void;
674};
675type AgnosticPatchRoutesOnNavigationFunction<O extends AgnosticRouteObject = AgnosticRouteObject, M extends AgnosticRouteMatch = AgnosticRouteMatch> = (opts: AgnosticPatchRoutesOnNavigationFunctionArgs<O, M>) => MaybePromise<void>;
676/**
677 * Function provided by the framework-aware layers to set any framework-specific
678 * properties from framework-agnostic properties
679 */
680interface MapRoutePropertiesFunction {
681 (route: AgnosticDataRouteObject): {
682 hasErrorBoundary: boolean;
683 } & Record<string, any>;
684}
685/**
686 * Keys we cannot change from within a lazy object. We spread all other keys
687 * onto the route. Either they're meaningful to the router, or they'll get
688 * ignored.
689 */
690type UnsupportedLazyRouteObjectKey = "lazy" | "caseSensitive" | "path" | "id" | "index" | "children";
691/**
692 * Keys we cannot change from within a lazy() function. We spread all other keys
693 * onto the route. Either they're meaningful to the router, or they'll get
694 * ignored.
695 */
696type UnsupportedLazyRouteFunctionKey = UnsupportedLazyRouteObjectKey | "middleware";
697/**
698 * lazy object to load route properties, which can add non-matching
699 * related properties to a route
700 */
701type LazyRouteObject<R extends AgnosticRouteObject> = {
702 [K in keyof R as K extends UnsupportedLazyRouteObjectKey ? never : K]?: () => Promise<R[K] | null | undefined>;
703};
704/**
705 * lazy() function to load a route definition, which can add non-matching
706 * related properties to a route
707 */
708interface LazyRouteFunction<R extends AgnosticRouteObject> {
709 (): Promise<Omit<R, UnsupportedLazyRouteFunctionKey> & Partial<Record<UnsupportedLazyRouteFunctionKey, never>>>;
710}
711type LazyRouteDefinition<R extends AgnosticRouteObject> = LazyRouteObject<R> | LazyRouteFunction<R>;
712/**
713 * Base RouteObject with common props shared by all types of routes
714 */
715type AgnosticBaseRouteObject = {
716 caseSensitive?: boolean;
717 path?: string;
718 id?: string;
719 middleware?: MiddlewareFunction[];
720 loader?: LoaderFunction | boolean;
721 action?: ActionFunction | boolean;
722 hasErrorBoundary?: boolean;
723 shouldRevalidate?: ShouldRevalidateFunction;
724 handle?: any;
725 lazy?: LazyRouteDefinition<AgnosticBaseRouteObject>;
726};
727/**
728 * Index routes must not have children
729 */
730type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {
731 children?: undefined;
732 index: true;
733};
734/**
735 * Non-index routes may have children, but cannot have index
736 */
737type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {
738 children?: AgnosticRouteObject[];
739 index?: false;
740};
741/**
742 * A route object represents a logical route, with (optionally) its child
743 * routes organized in a tree-like structure.
744 */
745type AgnosticRouteObject = AgnosticIndexRouteObject | AgnosticNonIndexRouteObject;
746type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {
747 id: string;
748};
749type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {
750 children?: AgnosticDataRouteObject[];
751 id: string;
752};
753/**
754 * A data route object, which is just a RouteObject with a required unique ID
755 */
756type AgnosticDataRouteObject = AgnosticDataIndexRouteObject | AgnosticDataNonIndexRouteObject;
757type RouteManifest<R = AgnosticDataRouteObject> = Record<string, R | undefined>;
758type 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";
759type Regez_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";
760type Regex_09 = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
761type Regex_w = Regex_az | Regez_AZ | Regex_09 | "_";
762type ParamChar = Regex_w | "-";
763type RegexMatchPlus<CharPattern extends string, T extends string> = T extends `${infer First}${infer Rest}` ? First extends CharPattern ? RegexMatchPlus<CharPattern, Rest> extends never ? First : `${First}${RegexMatchPlus<CharPattern, Rest>}` : never : never;
764type _PathParam<Path extends string> = Path extends `${infer L}/${infer R}` ? _PathParam<L> | _PathParam<R> : Path extends `:${infer Param}` ? Param extends `${infer Optional}?${string}` ? RegexMatchPlus<ParamChar, Optional> : RegexMatchPlus<ParamChar, Param> : never;
765type PathParam<Path extends string> = Path extends "*" | "/*" ? "*" : Path extends `${infer Rest}/*` ? "*" | _PathParam<Rest> : _PathParam<Path>;
766type ParamParseKey<Segment extends string> = [
767 PathParam<Segment>
768] extends [never] ? string : PathParam<Segment>;
769/**
770 * The parameters that were parsed from the URL path.
771 */
772type Params<Key extends string = string> = {
773 readonly [key in Key]: string | undefined;
774};
775/**
776 * A RouteMatch contains info about how a route matched a URL.
777 */
778interface AgnosticRouteMatch<ParamKey extends string = string, RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject> {
779 /**
780 * The names and values of dynamic parameters in the URL.
781 */
782 params: Params<ParamKey>;
783 /**
784 * The portion of the URL pathname that was matched.
785 */
786 pathname: string;
787 /**
788 * The portion of the URL pathname that was matched before child routes.
789 */
790 pathnameBase: string;
791 /**
792 * The route object that was used to match.
793 */
794 route: RouteObjectType;
795}
796interface AgnosticDataRouteMatch extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {
797}
798/**
799 * Matches the given routes to a location and returns the match data.
800 *
801 * @example
802 * import { matchRoutes } from "react-router";
803 *
804 * let routes = [{
805 * path: "/",
806 * Component: Root,
807 * children: [{
808 * path: "dashboard",
809 * Component: Dashboard,
810 * }]
811 * }];
812 *
813 * matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
814 *
815 * @public
816 * @category Utils
817 * @param routes The array of route objects to match against.
818 * @param locationArg The location to match against, either a string path or a
819 * partial {@link Location} object
820 * @param basename Optional base path to strip from the location before matching.
821 * Defaults to `/`.
822 * @returns An array of matched routes, or `null` if no matches were found.
823 */
824declare function matchRoutes<RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject>(routes: RouteObjectType[], locationArg: Partial<Location> | string, basename?: string): AgnosticRouteMatch<string, RouteObjectType>[] | null;
825interface UIMatch<Data = unknown, Handle = unknown> {
826 id: string;
827 pathname: string;
828 /**
829 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the matched route.
830 */
831 params: AgnosticRouteMatch["params"];
832 /**
833 * The return value from the matched route's loader or clientLoader. This might
834 * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
835 * an error and we're currently displaying an `ErrorBoundary`.
836 *
837 * @deprecated Use `UIMatch.loaderData` instead
838 */
839 data: Data | undefined;
840 /**
841 * The return value from the matched route's loader or clientLoader. This might
842 * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
843 * an error and we're currently displaying an `ErrorBoundary`.
844 */
845 loaderData: Data | undefined;
846 /**
847 * The {@link https://reactrouter.com/start/framework/route-module#handle handle object}
848 * exported from the matched route module
849 */
850 handle: Handle;
851}
852/**
853 * Returns a path with params interpolated.
854 *
855 * @example
856 * import { generatePath } from "react-router";
857 *
858 * generatePath("/users/:id", { id: "123" }); // "/users/123"
859 *
860 * @public
861 * @category Utils
862 * @param originalPath The original path to generate.
863 * @param params The parameters to interpolate into the path.
864 * @returns The generated path with parameters interpolated.
865 */
866declare function generatePath<Path extends string>(originalPath: Path, params?: {
867 [key in PathParam<Path>]: string | null;
868}): string;
869/**
870 * Used to match on some portion of a URL pathname.
871 */
872interface PathPattern<Path extends string = string> {
873 /**
874 * A string to match against a URL pathname. May contain `:id`-style segments
875 * to indicate placeholders for dynamic parameters. It May also end with `/*`
876 * to indicate matching the rest of the URL pathname.
877 */
878 path: Path;
879 /**
880 * Should be `true` if the static portions of the `path` should be matched in
881 * the same case.
882 */
883 caseSensitive?: boolean;
884 /**
885 * Should be `true` if this pattern should match the entire URL pathname.
886 */
887 end?: boolean;
888}
889/**
890 * Contains info about how a {@link PathPattern} matched on a URL pathname.
891 */
892interface PathMatch<ParamKey extends string = string> {
893 /**
894 * The names and values of dynamic parameters in the URL.
895 */
896 params: Params<ParamKey>;
897 /**
898 * The portion of the URL pathname that was matched.
899 */
900 pathname: string;
901 /**
902 * The portion of the URL pathname that was matched before child routes.
903 */
904 pathnameBase: string;
905 /**
906 * The pattern that was used to match.
907 */
908 pattern: PathPattern;
909}
910/**
911 * Performs pattern matching on a URL pathname and returns information about
912 * the match.
913 *
914 * @public
915 * @category Utils
916 * @param pattern The pattern to match against the URL pathname. This can be a
917 * string or a {@link PathPattern} object. If a string is provided, it will be
918 * treated as a pattern with `caseSensitive` set to `false` and `end` set to
919 * `true`.
920 * @param pathname The URL pathname to match against the pattern.
921 * @returns A path match object if the pattern matches the pathname,
922 * or `null` if it does not match.
923 */
924declare function matchPath<ParamKey extends ParamParseKey<Path>, Path extends string>(pattern: PathPattern<Path> | Path, pathname: string): PathMatch<ParamKey> | null;
925/**
926 * Returns a resolved {@link Path} object relative to the given pathname.
927 *
928 * @public
929 * @category Utils
930 * @param to The path to resolve, either a string or a partial {@link Path}
931 * object.
932 * @param fromPathname The pathname to resolve the path from. Defaults to `/`.
933 * @returns A {@link Path} object with the resolved pathname, search, and hash.
934 */
935declare function resolvePath(to: To, fromPathname?: string): Path;
936declare class DataWithResponseInit<D> {
937 type: string;
938 data: D;
939 init: ResponseInit | null;
940 constructor(data: D, init?: ResponseInit);
941}
942/**
943 * Create "responses" that contain `headers`/`status` without forcing
944 * serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
945 *
946 * @example
947 * import { data } from "react-router";
948 *
949 * export async function action({ request }: Route.ActionArgs) {
950 * let formData = await request.formData();
951 * let item = await createItem(formData);
952 * return data(item, {
953 * headers: { "X-Custom-Header": "value" }
954 * status: 201,
955 * });
956 * }
957 *
958 * @public
959 * @category Utils
960 * @mode framework
961 * @mode data
962 * @param data The data to be included in the response.
963 * @param init The status code or a `ResponseInit` object to be included in the
964 * response.
965 * @returns A {@link DataWithResponseInit} instance containing the data and
966 * response init.
967 */
968declare function data<D>(data: D, init?: number | ResponseInit): DataWithResponseInit<D>;
969interface TrackedPromise extends Promise<any> {
970 _tracked?: boolean;
971 _data?: any;
972 _error?: any;
973}
974type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
975/**
976 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
977 * Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
978 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
979 *
980 * @example
981 * import { redirect } from "react-router";
982 *
983 * export async function loader({ request }: Route.LoaderArgs) {
984 * if (!isLoggedIn(request))
985 * throw redirect("/login");
986 * }
987 *
988 * // ...
989 * }
990 *
991 * @public
992 * @category Utils
993 * @mode framework
994 * @mode data
995 * @param url The URL to redirect to.
996 * @param init The status code or a `ResponseInit` object to be included in the
997 * response.
998 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
999 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1000 * header.
1001 */
1002declare const redirect: RedirectFunction;
1003/**
1004 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1005 * that will force a document reload to the new location. Sets the status code
1006 * and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1007 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
1008 *
1009 * ```tsx filename=routes/logout.tsx
1010 * import { redirectDocument } from "react-router";
1011 *
1012 * import { destroySession } from "../sessions.server";
1013 *
1014 * export async function action({ request }: Route.ActionArgs) {
1015 * let session = await getSession(request.headers.get("Cookie"));
1016 * return redirectDocument("/", {
1017 * headers: { "Set-Cookie": await destroySession(session) }
1018 * });
1019 * }
1020 * ```
1021 *
1022 * @public
1023 * @category Utils
1024 * @mode framework
1025 * @mode data
1026 * @param url The URL to redirect to.
1027 * @param init The status code or a `ResponseInit` object to be included in the
1028 * response.
1029 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1030 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1031 * header.
1032 */
1033declare const redirectDocument: RedirectFunction;
1034/**
1035 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1036 * that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
1037 * instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
1038 * for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1039 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
1040 *
1041 * @example
1042 * import { replace } from "react-router";
1043 *
1044 * export async function loader() {
1045 * return replace("/new-location");
1046 * }
1047 *
1048 * @public
1049 * @category Utils
1050 * @mode framework
1051 * @mode data
1052 * @param url The URL to redirect to.
1053 * @param init The status code or a `ResponseInit` object to be included in the
1054 * response.
1055 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1056 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1057 * header.
1058 */
1059declare const replace: RedirectFunction;
1060type ErrorResponse = {
1061 status: number;
1062 statusText: string;
1063 data: any;
1064};
1065declare class ErrorResponseImpl implements ErrorResponse {
1066 status: number;
1067 statusText: string;
1068 data: any;
1069 private error?;
1070 private internal;
1071 constructor(status: number, statusText: string | undefined, data: any, internal?: boolean);
1072}
1073/**
1074 * Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
1075 * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1076 * thrown from an [`action`](../../start/framework/route-module#action) or
1077 * [`loader`](../../start/framework/route-module#loader) function.
1078 *
1079 * @example
1080 * import { isRouteErrorResponse } from "react-router";
1081 *
1082 * export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
1083 * if (isRouteErrorResponse(error)) {
1084 * return (
1085 * <>
1086 * <p>Error: `${error.status}: ${error.statusText}`</p>
1087 * <p>{error.data}</p>
1088 * </>
1089 * );
1090 * }
1091 *
1092 * return (
1093 * <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
1094 * );
1095 * }
1096 *
1097 * @public
1098 * @category Utils
1099 * @mode framework
1100 * @mode data
1101 * @param error The error to check.
1102 * @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
1103 */
1104declare function isRouteErrorResponse(error: any): error is ErrorResponse;
1105
1106/**
1107 * An object of unknown type for route loaders and actions provided by the
1108 * server's `getLoadContext()` function. This is defined as an empty interface
1109 * specifically so apps can leverage declaration merging to augment this type
1110 * globally: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
1111 */
1112interface AppLoadContext {
1113 [key: string]: unknown;
1114}
1115
1116/**
1117 * A Router instance manages all navigation and data loading/mutations
1118 */
1119interface Router$1 {
1120 /**
1121 * @private
1122 * PRIVATE - DO NOT USE
1123 *
1124 * Return the basename for the router
1125 */
1126 get basename(): RouterInit["basename"];
1127 /**
1128 * @private
1129 * PRIVATE - DO NOT USE
1130 *
1131 * Return the future config for the router
1132 */
1133 get future(): FutureConfig;
1134 /**
1135 * @private
1136 * PRIVATE - DO NOT USE
1137 *
1138 * Return the current state of the router
1139 */
1140 get state(): RouterState;
1141 /**
1142 * @private
1143 * PRIVATE - DO NOT USE
1144 *
1145 * Return the routes for this router instance
1146 */
1147 get routes(): AgnosticDataRouteObject[];
1148 /**
1149 * @private
1150 * PRIVATE - DO NOT USE
1151 *
1152 * Return the window associated with the router
1153 */
1154 get window(): RouterInit["window"];
1155 /**
1156 * @private
1157 * PRIVATE - DO NOT USE
1158 *
1159 * Initialize the router, including adding history listeners and kicking off
1160 * initial data fetches. Returns a function to cleanup listeners and abort
1161 * any in-progress loads
1162 */
1163 initialize(): Router$1;
1164 /**
1165 * @private
1166 * PRIVATE - DO NOT USE
1167 *
1168 * Subscribe to router.state updates
1169 *
1170 * @param fn function to call with the new state
1171 */
1172 subscribe(fn: RouterSubscriber): () => void;
1173 /**
1174 * @private
1175 * PRIVATE - DO NOT USE
1176 *
1177 * Enable scroll restoration behavior in the router
1178 *
1179 * @param savedScrollPositions Object that will manage positions, in case
1180 * it's being restored from sessionStorage
1181 * @param getScrollPosition Function to get the active Y scroll position
1182 * @param getKey Function to get the key to use for restoration
1183 */
1184 enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;
1185 /**
1186 * @private
1187 * PRIVATE - DO NOT USE
1188 *
1189 * Navigate forward/backward in the history stack
1190 * @param to Delta to move in the history stack
1191 */
1192 navigate(to: number): Promise<void>;
1193 /**
1194 * Navigate to the given path
1195 * @param to Path to navigate to
1196 * @param opts Navigation options (method, submission, etc.)
1197 */
1198 navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;
1199 /**
1200 * @private
1201 * PRIVATE - DO NOT USE
1202 *
1203 * Trigger a fetcher load/submission
1204 *
1205 * @param key Fetcher key
1206 * @param routeId Route that owns the fetcher
1207 * @param href href to fetch
1208 * @param opts Fetcher options, (method, submission, etc.)
1209 */
1210 fetch(key: string, routeId: string, href: string | null, opts?: RouterFetchOptions): Promise<void>;
1211 /**
1212 * @private
1213 * PRIVATE - DO NOT USE
1214 *
1215 * Trigger a revalidation of all current route loaders and fetcher loads
1216 */
1217 revalidate(): Promise<void>;
1218 /**
1219 * @private
1220 * PRIVATE - DO NOT USE
1221 *
1222 * Utility function to create an href for the given location
1223 * @param location
1224 */
1225 createHref(location: Location | URL): string;
1226 /**
1227 * @private
1228 * PRIVATE - DO NOT USE
1229 *
1230 * Utility function to URL encode a destination path according to the internal
1231 * history implementation
1232 * @param to
1233 */
1234 encodeLocation(to: To): Path;
1235 /**
1236 * @private
1237 * PRIVATE - DO NOT USE
1238 *
1239 * Get/create a fetcher for the given key
1240 * @param key
1241 */
1242 getFetcher<TData = any>(key: string): Fetcher<TData>;
1243 /**
1244 * @internal
1245 * PRIVATE - DO NOT USE
1246 *
1247 * Reset the fetcher for a given key
1248 * @param key
1249 */
1250 resetFetcher(key: string, opts?: {
1251 reason?: unknown;
1252 }): void;
1253 /**
1254 * @private
1255 * PRIVATE - DO NOT USE
1256 *
1257 * Delete the fetcher for a given key
1258 * @param key
1259 */
1260 deleteFetcher(key: string): void;
1261 /**
1262 * @private
1263 * PRIVATE - DO NOT USE
1264 *
1265 * Cleanup listeners and abort any in-progress loads
1266 */
1267 dispose(): void;
1268 /**
1269 * @private
1270 * PRIVATE - DO NOT USE
1271 *
1272 * Get a navigation blocker
1273 * @param key The identifier for the blocker
1274 * @param fn The blocker function implementation
1275 */
1276 getBlocker(key: string, fn: BlockerFunction): Blocker;
1277 /**
1278 * @private
1279 * PRIVATE - DO NOT USE
1280 *
1281 * Delete a navigation blocker
1282 * @param key The identifier for the blocker
1283 */
1284 deleteBlocker(key: string): void;
1285 /**
1286 * @private
1287 * PRIVATE DO NOT USE
1288 *
1289 * Patch additional children routes into an existing parent route
1290 * @param routeId The parent route id or a callback function accepting `patch`
1291 * to perform batch patching
1292 * @param children The additional children routes
1293 * @param unstable_allowElementMutations Allow mutation or route elements on
1294 * existing routes. Intended for RSC-usage
1295 * only.
1296 */
1297 patchRoutes(routeId: string | null, children: AgnosticRouteObject[], unstable_allowElementMutations?: boolean): void;
1298 /**
1299 * @private
1300 * PRIVATE - DO NOT USE
1301 *
1302 * HMR needs to pass in-flight route updates to React Router
1303 * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)
1304 */
1305 _internalSetRoutes(routes: AgnosticRouteObject[]): void;
1306 /**
1307 * @private
1308 * PRIVATE - DO NOT USE
1309 *
1310 * Cause subscribers to re-render. This is used to force a re-render.
1311 */
1312 _internalSetStateDoNotUseOrYouWillBreakYourApp(state: Partial<RouterState>): void;
1313 /**
1314 * @private
1315 * PRIVATE - DO NOT USE
1316 *
1317 * Internal fetch AbortControllers accessed by unit tests
1318 */
1319 _internalFetchControllers: Map<string, AbortController>;
1320}
1321/**
1322 * State maintained internally by the router. During a navigation, all states
1323 * reflect the "old" location unless otherwise noted.
1324 */
1325interface RouterState {
1326 /**
1327 * The action of the most recent navigation
1328 */
1329 historyAction: Action;
1330 /**
1331 * The current location reflected by the router
1332 */
1333 location: Location;
1334 /**
1335 * The current set of route matches
1336 */
1337 matches: AgnosticDataRouteMatch[];
1338 /**
1339 * Tracks whether we've completed our initial data load
1340 */
1341 initialized: boolean;
1342 /**
1343 * Current scroll position we should start at for a new view
1344 * - number -> scroll position to restore to
1345 * - false -> do not restore scroll at all (used during submissions/revalidations)
1346 * - null -> don't have a saved position, scroll to hash or top of page
1347 */
1348 restoreScrollPosition: number | false | null;
1349 /**
1350 * Indicate whether this navigation should skip resetting the scroll position
1351 * if we are unable to restore the scroll position
1352 */
1353 preventScrollReset: boolean;
1354 /**
1355 * Tracks the state of the current navigation
1356 */
1357 navigation: Navigation;
1358 /**
1359 * Tracks any in-progress revalidations
1360 */
1361 revalidation: RevalidationState;
1362 /**
1363 * Data from the loaders for the current matches
1364 */
1365 loaderData: RouteData;
1366 /**
1367 * Data from the action for the current matches
1368 */
1369 actionData: RouteData | null;
1370 /**
1371 * Errors caught from loaders for the current matches
1372 */
1373 errors: RouteData | null;
1374 /**
1375 * Map of current fetchers
1376 */
1377 fetchers: Map<string, Fetcher>;
1378 /**
1379 * Map of current blockers
1380 */
1381 blockers: Map<string, Blocker>;
1382}
1383/**
1384 * Data that can be passed into hydrate a Router from SSR
1385 */
1386type HydrationState = Partial<Pick<RouterState, "loaderData" | "actionData" | "errors">>;
1387/**
1388 * Future flags to toggle new feature behavior
1389 */
1390interface FutureConfig {
1391}
1392/**
1393 * Initialization options for createRouter
1394 */
1395interface RouterInit {
1396 routes: AgnosticRouteObject[];
1397 history: History;
1398 basename?: string;
1399 getContext?: () => MaybePromise<RouterContextProvider>;
1400 unstable_instrumentations?: unstable_ClientInstrumentation[];
1401 mapRouteProperties?: MapRoutePropertiesFunction;
1402 future?: Partial<FutureConfig>;
1403 hydrationRouteProperties?: string[];
1404 hydrationData?: HydrationState;
1405 window?: Window;
1406 dataStrategy?: DataStrategyFunction;
1407 patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;
1408}
1409/**
1410 * State returned from a server-side query() call
1411 */
1412interface StaticHandlerContext {
1413 basename: Router$1["basename"];
1414 location: RouterState["location"];
1415 matches: RouterState["matches"];
1416 loaderData: RouterState["loaderData"];
1417 actionData: RouterState["actionData"];
1418 errors: RouterState["errors"];
1419 statusCode: number;
1420 loaderHeaders: Record<string, Headers>;
1421 actionHeaders: Record<string, Headers>;
1422 _deepestRenderedBoundaryId?: string | null;
1423}
1424/**
1425 * A StaticHandler instance manages a singular SSR navigation/fetch event
1426 */
1427interface StaticHandler {
1428 dataRoutes: AgnosticDataRouteObject[];
1429 query(request: Request, opts?: {
1430 requestContext?: unknown;
1431 filterMatchesToLoad?: (match: AgnosticDataRouteMatch) => boolean;
1432 skipLoaderErrorBubbling?: boolean;
1433 skipRevalidation?: boolean;
1434 dataStrategy?: DataStrategyFunction<unknown>;
1435 generateMiddlewareResponse?: (query: (r: Request, args?: {
1436 filterMatchesToLoad?: (match: AgnosticDataRouteMatch) => boolean;
1437 }) => Promise<StaticHandlerContext | Response>) => MaybePromise<Response>;
1438 }): Promise<StaticHandlerContext | Response>;
1439 queryRoute(request: Request, opts?: {
1440 routeId?: string;
1441 requestContext?: unknown;
1442 dataStrategy?: DataStrategyFunction<unknown>;
1443 generateMiddlewareResponse?: (queryRoute: (r: Request) => Promise<Response>) => MaybePromise<Response>;
1444 }): Promise<any>;
1445}
1446type ViewTransitionOpts = {
1447 currentLocation: Location;
1448 nextLocation: Location;
1449};
1450/**
1451 * Subscriber function signature for changes to router state
1452 */
1453interface RouterSubscriber {
1454 (state: RouterState, opts: {
1455 deletedFetchers: string[];
1456 newErrors: RouteData | null;
1457 viewTransitionOpts?: ViewTransitionOpts;
1458 flushSync: boolean;
1459 }): void;
1460}
1461/**
1462 * Function signature for determining the key to be used in scroll restoration
1463 * for a given location
1464 */
1465interface GetScrollRestorationKeyFunction {
1466 (location: Location, matches: UIMatch[]): string | null;
1467}
1468/**
1469 * Function signature for determining the current scroll position
1470 */
1471interface GetScrollPositionFunction {
1472 (): number;
1473}
1474/**
1475 * - "route": relative to the route hierarchy so `..` means remove all segments
1476 * of the current route even if it has many. For example, a `route("posts/:id")`
1477 * would have both `:id` and `posts` removed from the url.
1478 * - "path": relative to the pathname so `..` means remove one segment of the
1479 * pathname. For example, a `route("posts/:id")` would have only `:id` removed
1480 * from the url.
1481 */
1482type RelativeRoutingType = "route" | "path";
1483type BaseNavigateOrFetchOptions = {
1484 preventScrollReset?: boolean;
1485 relative?: RelativeRoutingType;
1486 flushSync?: boolean;
1487 unstable_defaultShouldRevalidate?: boolean;
1488};
1489type BaseNavigateOptions = BaseNavigateOrFetchOptions & {
1490 replace?: boolean;
1491 state?: any;
1492 fromRouteId?: string;
1493 viewTransition?: boolean;
1494};
1495type BaseSubmissionOptions = {
1496 formMethod?: HTMLFormMethod;
1497 formEncType?: FormEncType;
1498} & ({
1499 formData: FormData;
1500 body?: undefined;
1501} | {
1502 formData?: undefined;
1503 body: any;
1504});
1505/**
1506 * Options for a navigate() call for a normal (non-submission) navigation
1507 */
1508type LinkNavigateOptions = BaseNavigateOptions;
1509/**
1510 * Options for a navigate() call for a submission navigation
1511 */
1512type SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;
1513/**
1514 * Options to pass to navigate() for a navigation
1515 */
1516type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions;
1517/**
1518 * Options for a fetch() load
1519 */
1520type LoadFetchOptions = BaseNavigateOrFetchOptions;
1521/**
1522 * Options for a fetch() submission
1523 */
1524type SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;
1525/**
1526 * Options to pass to fetch()
1527 */
1528type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;
1529/**
1530 * Potential states for state.navigation
1531 */
1532type NavigationStates = {
1533 Idle: {
1534 state: "idle";
1535 location: undefined;
1536 formMethod: undefined;
1537 formAction: undefined;
1538 formEncType: undefined;
1539 formData: undefined;
1540 json: undefined;
1541 text: undefined;
1542 };
1543 Loading: {
1544 state: "loading";
1545 location: Location;
1546 formMethod: Submission["formMethod"] | undefined;
1547 formAction: Submission["formAction"] | undefined;
1548 formEncType: Submission["formEncType"] | undefined;
1549 formData: Submission["formData"] | undefined;
1550 json: Submission["json"] | undefined;
1551 text: Submission["text"] | undefined;
1552 };
1553 Submitting: {
1554 state: "submitting";
1555 location: Location;
1556 formMethod: Submission["formMethod"];
1557 formAction: Submission["formAction"];
1558 formEncType: Submission["formEncType"];
1559 formData: Submission["formData"];
1560 json: Submission["json"];
1561 text: Submission["text"];
1562 };
1563};
1564type Navigation = NavigationStates[keyof NavigationStates];
1565type RevalidationState = "idle" | "loading";
1566/**
1567 * Potential states for fetchers
1568 */
1569type FetcherStates<TData = any> = {
1570 /**
1571 * The fetcher is not calling a loader or action
1572 *
1573 * ```tsx
1574 * fetcher.state === "idle"
1575 * ```
1576 */
1577 Idle: {
1578 state: "idle";
1579 formMethod: undefined;
1580 formAction: undefined;
1581 formEncType: undefined;
1582 text: undefined;
1583 formData: undefined;
1584 json: undefined;
1585 /**
1586 * If the fetcher has never been called, this will be undefined.
1587 */
1588 data: TData | undefined;
1589 };
1590 /**
1591 * The fetcher is loading data from a {@link LoaderFunction | loader} from a
1592 * call to {@link FetcherWithComponents.load | `fetcher.load`}.
1593 *
1594 * ```tsx
1595 * // somewhere
1596 * <button onClick={() => fetcher.load("/some/route") }>Load</button>
1597 *
1598 * // the state will update
1599 * fetcher.state === "loading"
1600 * ```
1601 */
1602 Loading: {
1603 state: "loading";
1604 formMethod: Submission["formMethod"] | undefined;
1605 formAction: Submission["formAction"] | undefined;
1606 formEncType: Submission["formEncType"] | undefined;
1607 text: Submission["text"] | undefined;
1608 formData: Submission["formData"] | undefined;
1609 json: Submission["json"] | undefined;
1610 data: TData | undefined;
1611 };
1612 /**
1613 The fetcher is submitting to a {@link LoaderFunction} (GET) or {@link ActionFunction} (POST) from a {@link FetcherWithComponents.Form | `fetcher.Form`} or {@link FetcherWithComponents.submit | `fetcher.submit`}.
1614
1615 ```tsx
1616 // somewhere
1617 <input
1618 onChange={e => {
1619 fetcher.submit(event.currentTarget.form, { method: "post" });
1620 }}
1621 />
1622
1623 // the state will update
1624 fetcher.state === "submitting"
1625
1626 // and formData will be available
1627 fetcher.formData
1628 ```
1629 */
1630 Submitting: {
1631 state: "submitting";
1632 formMethod: Submission["formMethod"];
1633 formAction: Submission["formAction"];
1634 formEncType: Submission["formEncType"];
1635 text: Submission["text"];
1636 formData: Submission["formData"];
1637 json: Submission["json"];
1638 data: TData | undefined;
1639 };
1640};
1641type Fetcher<TData = any> = FetcherStates<TData>[keyof FetcherStates<TData>];
1642interface BlockerBlocked {
1643 state: "blocked";
1644 reset: () => void;
1645 proceed: () => void;
1646 location: Location;
1647}
1648interface BlockerUnblocked {
1649 state: "unblocked";
1650 reset: undefined;
1651 proceed: undefined;
1652 location: undefined;
1653}
1654interface BlockerProceeding {
1655 state: "proceeding";
1656 reset: undefined;
1657 proceed: undefined;
1658 location: Location;
1659}
1660type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;
1661type BlockerFunction = (args: {
1662 currentLocation: Location;
1663 nextLocation: Location;
1664 historyAction: Action;
1665}) => boolean;
1666declare const IDLE_NAVIGATION: NavigationStates["Idle"];
1667declare const IDLE_FETCHER: FetcherStates["Idle"];
1668declare const IDLE_BLOCKER: BlockerUnblocked;
1669/**
1670 * Create a router and listen to history POP navigations
1671 */
1672declare function createRouter(init: RouterInit): Router$1;
1673interface CreateStaticHandlerOptions {
1674 basename?: string;
1675 mapRouteProperties?: MapRoutePropertiesFunction;
1676 unstable_instrumentations?: Pick<unstable_ServerInstrumentation, "route">[];
1677 future?: {};
1678}
1679
1680declare function mapRouteProperties(route: RouteObject): Partial<RouteObject> & {
1681 hasErrorBoundary: boolean;
1682};
1683declare const hydrationRouteProperties: (keyof RouteObject)[];
1684/**
1685 * @category Data Routers
1686 */
1687interface MemoryRouterOpts {
1688 /**
1689 * Basename path for the application.
1690 */
1691 basename?: string;
1692 /**
1693 * A function that returns an {@link RouterContextProvider} instance
1694 * which is provided as the `context` argument to client [`action`](../../start/data/route-object#action)s,
1695 * [`loader`](../../start/data/route-object#loader)s and [middleware](../../how-to/middleware).
1696 * This function is called to generate a fresh `context` instance on each
1697 * navigation or fetcher call.
1698 */
1699 getContext?: RouterInit["getContext"];
1700 /**
1701 * Future flags to enable for the router.
1702 */
1703 future?: Partial<FutureConfig>;
1704 /**
1705 * Hydration data to initialize the router with if you have already performed
1706 * data loading on the server.
1707 */
1708 hydrationData?: HydrationState;
1709 /**
1710 * Initial entries in the in-memory history stack
1711 */
1712 initialEntries?: InitialEntry[];
1713 /**
1714 * Index of `initialEntries` the application should initialize to
1715 */
1716 initialIndex?: number;
1717 /**
1718 * Array of instrumentation objects allowing you to instrument the router and
1719 * individual routes prior to router initialization (and on any subsequently
1720 * added routes via `route.lazy` or `patchRoutesOnNavigation`). This is
1721 * mostly useful for observability such as wrapping navigations, fetches,
1722 * as well as route loaders/actions/middlewares with logging and/or performance
1723 * tracing. See the [docs](../../how-to/instrumentation) for more information.
1724 *
1725 * ```tsx
1726 * let router = createBrowserRouter(routes, {
1727 * unstable_instrumentations: [logging]
1728 * });
1729 *
1730 *
1731 * let logging = {
1732 * router({ instrument }) {
1733 * instrument({
1734 * navigate: (impl, info) => logExecution(`navigate ${info.to}`, impl),
1735 * fetch: (impl, info) => logExecution(`fetch ${info.to}`, impl)
1736 * });
1737 * },
1738 * route({ instrument, id }) {
1739 * instrument({
1740 * middleware: (impl, info) => logExecution(
1741 * `middleware ${info.request.url} (route ${id})`,
1742 * impl
1743 * ),
1744 * loader: (impl, info) => logExecution(
1745 * `loader ${info.request.url} (route ${id})`,
1746 * impl
1747 * ),
1748 * action: (impl, info) => logExecution(
1749 * `action ${info.request.url} (route ${id})`,
1750 * impl
1751 * ),
1752 * })
1753 * }
1754 * };
1755 *
1756 * async function logExecution(label: string, impl: () => Promise<void>) {
1757 * let start = performance.now();
1758 * console.log(`start ${label}`);
1759 * await impl();
1760 * let duration = Math.round(performance.now() - start);
1761 * console.log(`end ${label} (${duration}ms)`);
1762 * }
1763 * ```
1764 */
1765 unstable_instrumentations?: unstable_ClientInstrumentation[];
1766 /**
1767 * Override the default data strategy of running loaders in parallel -
1768 * see the [docs](../../how-to/data-strategy) for more information.
1769 *
1770 * ```tsx
1771 * let router = createBrowserRouter(routes, {
1772 * async dataStrategy({
1773 * matches,
1774 * request,
1775 * runClientMiddleware,
1776 * }) {
1777 * const matchesToLoad = matches.filter((m) =>
1778 * m.shouldCallHandler(),
1779 * );
1780 *
1781 * const results: Record<string, DataStrategyResult> = {};
1782 * await runClientMiddleware(() =>
1783 * Promise.all(
1784 * matchesToLoad.map(async (match) => {
1785 * results[match.route.id] = await match.resolve();
1786 * }),
1787 * ),
1788 * );
1789 * return results;
1790 * },
1791 * });
1792 * ```
1793 */
1794 dataStrategy?: DataStrategyFunction;
1795 /**
1796 * Lazily define portions of the route tree on navigations.
1797 */
1798 patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;
1799}
1800/**
1801 * Create a new {@link DataRouter} that manages the application path using an
1802 * in-memory [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1803 * stack. Useful for non-browser environments without a DOM API.
1804 *
1805 * @public
1806 * @category Data Routers
1807 * @mode data
1808 * @param routes Application routes
1809 * @param opts Options
1810 * @param {MemoryRouterOpts.basename} opts.basename n/a
1811 * @param {MemoryRouterOpts.dataStrategy} opts.dataStrategy n/a
1812 * @param {MemoryRouterOpts.future} opts.future n/a
1813 * @param {MemoryRouterOpts.getContext} opts.getContext n/a
1814 * @param {MemoryRouterOpts.hydrationData} opts.hydrationData n/a
1815 * @param {MemoryRouterOpts.initialEntries} opts.initialEntries n/a
1816 * @param {MemoryRouterOpts.initialIndex} opts.initialIndex n/a
1817 * @param {MemoryRouterOpts.unstable_instrumentations} opts.unstable_instrumentations n/a
1818 * @param {MemoryRouterOpts.patchRoutesOnNavigation} opts.patchRoutesOnNavigation n/a
1819 * @returns An initialized {@link DataRouter} to pass to {@link RouterProvider | `<RouterProvider>`}
1820 */
1821declare function createMemoryRouter(routes: RouteObject[], opts?: MemoryRouterOpts): Router$1;
1822/**
1823 * Function signature for client side error handling for loader/actions errors
1824 * and rendering errors via `componentDidCatch`
1825 */
1826interface ClientOnErrorFunction {
1827 (error: unknown, info: {
1828 location: Location;
1829 params: Params;
1830 unstable_pattern: string;
1831 errorInfo?: React.ErrorInfo;
1832 }): void;
1833}
1834/**
1835 * @category Types
1836 */
1837interface RouterProviderProps {
1838 /**
1839 * The {@link DataRouter} instance to use for navigation and data fetching.
1840 */
1841 router: Router$1;
1842 /**
1843 * The [`ReactDOM.flushSync`](https://react.dev/reference/react-dom/flushSync)
1844 * implementation to use for flushing updates.
1845 *
1846 * You usually don't have to worry about this:
1847 * - The `RouterProvider` exported from `react-router/dom` handles this internally for you
1848 * - If you are rendering in a non-DOM environment, you can import
1849 * `RouterProvider` from `react-router` and ignore this prop
1850 */
1851 flushSync?: (fn: () => unknown) => undefined;
1852 /**
1853 * An error handler function that will be called for any middleware, loader, action,
1854 * or render errors that are encountered in your application. This is useful for
1855 * logging or reporting errors instead of in the {@link ErrorBoundary} because it's not
1856 * subject to re-rendering and will only run one time per error.
1857 *
1858 * The `errorInfo` parameter is passed along from
1859 * [`componentDidCatch`](https://react.dev/reference/react/Component#componentdidcatch)
1860 * and is only present for render errors.
1861 *
1862 * ```tsx
1863 * <RouterProvider onError=(error, info) => {
1864 * let { location, params, unstable_pattern, errorInfo } = info;
1865 * console.error(error, location, errorInfo);
1866 * reportToErrorService(error, location, errorInfo);
1867 * }} />
1868 * ```
1869 */
1870 onError?: ClientOnErrorFunction;
1871 /**
1872 * Control whether router state updates are internally wrapped in
1873 * [`React.startTransition`](https://react.dev/reference/react/startTransition).
1874 *
1875 * - When left `undefined`, all state updates are wrapped in
1876 * `React.startTransition`
1877 * - This can lead to buggy behaviors if you are wrapping your own
1878 * navigations/fetchers in `startTransition`.
1879 * - When set to `true`, {@link Link} and {@link Form} navigations will be wrapped
1880 * in `React.startTransition` and router state changes will be wrapped in
1881 * `React.startTransition` and also sent through
1882 * [`useOptimistic`](https://react.dev/reference/react/useOptimistic) to
1883 * surface mid-navigation router state changes to the UI.
1884 * - When set to `false`, the router will not leverage `React.startTransition` or
1885 * `React.useOptimistic` on any navigations or state changes.
1886 *
1887 * For more information, please see the [docs](https://reactrouter.com/explanation/react-transitions).
1888 */
1889 unstable_useTransitions?: boolean;
1890}
1891/**
1892 * Render the UI for the given {@link DataRouter}. This component should
1893 * typically be at the top of an app's element tree.
1894 *
1895 * ```tsx
1896 * import { createBrowserRouter } from "react-router";
1897 * import { RouterProvider } from "react-router/dom";
1898 * import { createRoot } from "react-dom/client";
1899 *
1900 * const router = createBrowserRouter(routes);
1901 * createRoot(document.getElementById("root")).render(
1902 * <RouterProvider router={router} />
1903 * );
1904 * ```
1905 *
1906 * <docs-info>Please note that this component is exported both from
1907 * `react-router` and `react-router/dom` with the only difference being that the
1908 * latter automatically wires up `react-dom`'s [`flushSync`](https://react.dev/reference/react-dom/flushSync)
1909 * implementation. You _almost always_ want to use the version from
1910 * `react-router/dom` unless you're running in a non-DOM environment.</docs-info>
1911 *
1912 *
1913 * @public
1914 * @category Data Routers
1915 * @mode data
1916 * @param props Props
1917 * @param {RouterProviderProps.flushSync} props.flushSync n/a
1918 * @param {RouterProviderProps.onError} props.onError n/a
1919 * @param {RouterProviderProps.router} props.router n/a
1920 * @param {RouterProviderProps.unstable_useTransitions} props.unstable_useTransitions n/a
1921 * @returns React element for the rendered router
1922 */
1923declare function RouterProvider({ router, flushSync: reactDomFlushSyncImpl, onError, unstable_useTransitions, }: RouterProviderProps): React.ReactElement;
1924/**
1925 * @category Types
1926 */
1927interface MemoryRouterProps {
1928 /**
1929 * Application basename
1930 */
1931 basename?: string;
1932 /**
1933 * Nested {@link Route} elements describing the route tree
1934 */
1935 children?: React.ReactNode;
1936 /**
1937 * Initial entries in the in-memory history stack
1938 */
1939 initialEntries?: InitialEntry[];
1940 /**
1941 * Index of `initialEntries` the application should initialize to
1942 */
1943 initialIndex?: number;
1944 /**
1945 * Control whether router state updates are internally wrapped in
1946 * [`React.startTransition`](https://react.dev/reference/react/startTransition).
1947 *
1948 * - When left `undefined`, all router state updates are wrapped in
1949 * `React.startTransition`
1950 * - When set to `true`, {@link Link} and {@link Form} navigations will be wrapped
1951 * in `React.startTransition` and all router state updates are wrapped in
1952 * `React.startTransition`
1953 * - When set to `false`, the router will not leverage `React.startTransition`
1954 * on any navigations or state changes.
1955 *
1956 * For more information, please see the [docs](https://reactrouter.com/explanation/react-transitions).
1957 */
1958 unstable_useTransitions?: boolean;
1959}
1960/**
1961 * A declarative {@link Router | `<Router>`} that stores all entries in memory.
1962 *
1963 * @public
1964 * @category Declarative Routers
1965 * @mode declarative
1966 * @param props Props
1967 * @param {MemoryRouterProps.basename} props.basename n/a
1968 * @param {MemoryRouterProps.children} props.children n/a
1969 * @param {MemoryRouterProps.initialEntries} props.initialEntries n/a
1970 * @param {MemoryRouterProps.initialIndex} props.initialIndex n/a
1971 * @param {MemoryRouterProps.unstable_useTransitions} props.unstable_useTransitions n/a
1972 * @returns A declarative in-memory {@link Router | `<Router>`} for client-side
1973 * routing.
1974 */
1975declare function MemoryRouter({ basename, children, initialEntries, initialIndex, unstable_useTransitions, }: MemoryRouterProps): React.ReactElement;
1976/**
1977 * @category Types
1978 */
1979interface NavigateProps {
1980 /**
1981 * The path to navigate to. This can be a string or a {@link Path} object
1982 */
1983 to: To;
1984 /**
1985 * Whether to replace the current entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1986 * stack
1987 */
1988 replace?: boolean;
1989 /**
1990 * State to pass to the new {@link Location} to store in [`history.state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state).
1991 */
1992 state?: any;
1993 /**
1994 * How to interpret relative routing in the `to` prop.
1995 * See {@link RelativeRoutingType}.
1996 */
1997 relative?: RelativeRoutingType;
1998}
1999/**
2000 * A component-based version of {@link useNavigate} to use in a
2001 * [`React.Component` class](https://react.dev/reference/react/Component) where
2002 * hooks cannot be used.
2003 *
2004 * It's recommended to avoid using this component in favor of {@link useNavigate}.
2005 *
2006 * @example
2007 * <Navigate to="/tasks" />
2008 *
2009 * @public
2010 * @category Components
2011 * @param props Props
2012 * @param {NavigateProps.relative} props.relative n/a
2013 * @param {NavigateProps.replace} props.replace n/a
2014 * @param {NavigateProps.state} props.state n/a
2015 * @param {NavigateProps.to} props.to n/a
2016 * @returns {void}
2017 *
2018 */
2019declare function Navigate({ to, replace, state, relative, }: NavigateProps): null;
2020/**
2021 * @category Types
2022 */
2023interface OutletProps {
2024 /**
2025 * Provides a context value to the element tree below the outlet. Use when
2026 * the parent route needs to provide values to child routes.
2027 *
2028 * ```tsx
2029 * <Outlet context={myContextValue} />
2030 * ```
2031 *
2032 * Access the context with {@link useOutletContext}.
2033 */
2034 context?: unknown;
2035}
2036/**
2037 * Renders the matching child route of a parent route or nothing if no child
2038 * route matches.
2039 *
2040 * @example
2041 * import { Outlet } from "react-router";
2042 *
2043 * export default function SomeParent() {
2044 * return (
2045 * <div>
2046 * <h1>Parent Content</h1>
2047 * <Outlet />
2048 * </div>
2049 * );
2050 * }
2051 *
2052 * @public
2053 * @category Components
2054 * @param props Props
2055 * @param {OutletProps.context} props.context n/a
2056 * @returns React element for the rendered outlet or `null` if no child route matches.
2057 */
2058declare function Outlet(props: OutletProps): React.ReactElement | null;
2059/**
2060 * @category Types
2061 */
2062interface PathRouteProps {
2063 /**
2064 * Whether the path should be case-sensitive. Defaults to `false`.
2065 */
2066 caseSensitive?: NonIndexRouteObject["caseSensitive"];
2067 /**
2068 * The path pattern to match. If unspecified or empty, then this becomes a
2069 * layout route.
2070 */
2071 path?: NonIndexRouteObject["path"];
2072 /**
2073 * The unique identifier for this route (for use with {@link DataRouter}s)
2074 */
2075 id?: NonIndexRouteObject["id"];
2076 /**
2077 * A function that returns a promise that resolves to the route object.
2078 * Used for code-splitting routes.
2079 * See [`lazy`](../../start/data/route-object#lazy).
2080 */
2081 lazy?: LazyRouteFunction<NonIndexRouteObject>;
2082 /**
2083 * The route middleware.
2084 * See [`middleware`](../../start/data/route-object#middleware).
2085 */
2086 middleware?: NonIndexRouteObject["middleware"];
2087 /**
2088 * The route loader.
2089 * See [`loader`](../../start/data/route-object#loader).
2090 */
2091 loader?: NonIndexRouteObject["loader"];
2092 /**
2093 * The route action.
2094 * See [`action`](../../start/data/route-object#action).
2095 */
2096 action?: NonIndexRouteObject["action"];
2097 hasErrorBoundary?: NonIndexRouteObject["hasErrorBoundary"];
2098 /**
2099 * The route shouldRevalidate function.
2100 * See [`shouldRevalidate`](../../start/data/route-object#shouldRevalidate).
2101 */
2102 shouldRevalidate?: NonIndexRouteObject["shouldRevalidate"];
2103 /**
2104 * The route handle.
2105 */
2106 handle?: NonIndexRouteObject["handle"];
2107 /**
2108 * Whether this is an index route.
2109 */
2110 index?: false;
2111 /**
2112 * Child Route components
2113 */
2114 children?: React.ReactNode;
2115 /**
2116 * The React element to render when this Route matches.
2117 * Mutually exclusive with `Component`.
2118 */
2119 element?: React.ReactNode | null;
2120 /**
2121 * The React element to render while this router is loading data.
2122 * Mutually exclusive with `HydrateFallback`.
2123 */
2124 hydrateFallbackElement?: React.ReactNode | null;
2125 /**
2126 * The React element to render at this route if an error occurs.
2127 * Mutually exclusive with `ErrorBoundary`.
2128 */
2129 errorElement?: React.ReactNode | null;
2130 /**
2131 * The React Component to render when this route matches.
2132 * Mutually exclusive with `element`.
2133 */
2134 Component?: React.ComponentType | null;
2135 /**
2136 * The React Component to render while this router is loading data.
2137 * Mutually exclusive with `hydrateFallbackElement`.
2138 */
2139 HydrateFallback?: React.ComponentType | null;
2140 /**
2141 * The React Component to render at this route if an error occurs.
2142 * Mutually exclusive with `errorElement`.
2143 */
2144 ErrorBoundary?: React.ComponentType | null;
2145}
2146/**
2147 * @category Types
2148 */
2149interface LayoutRouteProps extends PathRouteProps {
2150}
2151/**
2152 * @category Types
2153 */
2154interface IndexRouteProps {
2155 /**
2156 * Whether the path should be case-sensitive. Defaults to `false`.
2157 */
2158 caseSensitive?: IndexRouteObject["caseSensitive"];
2159 /**
2160 * The path pattern to match. If unspecified or empty, then this becomes a
2161 * layout route.
2162 */
2163 path?: IndexRouteObject["path"];
2164 /**
2165 * The unique identifier for this route (for use with {@link DataRouter}s)
2166 */
2167 id?: IndexRouteObject["id"];
2168 /**
2169 * A function that returns a promise that resolves to the route object.
2170 * Used for code-splitting routes.
2171 * See [`lazy`](../../start/data/route-object#lazy).
2172 */
2173 lazy?: LazyRouteFunction<IndexRouteObject>;
2174 /**
2175 * The route middleware.
2176 * See [`middleware`](../../start/data/route-object#middleware).
2177 */
2178 middleware?: IndexRouteObject["middleware"];
2179 /**
2180 * The route loader.
2181 * See [`loader`](../../start/data/route-object#loader).
2182 */
2183 loader?: IndexRouteObject["loader"];
2184 /**
2185 * The route action.
2186 * See [`action`](../../start/data/route-object#action).
2187 */
2188 action?: IndexRouteObject["action"];
2189 hasErrorBoundary?: IndexRouteObject["hasErrorBoundary"];
2190 /**
2191 * The route shouldRevalidate function.
2192 * See [`shouldRevalidate`](../../start/data/route-object#shouldRevalidate).
2193 */
2194 shouldRevalidate?: IndexRouteObject["shouldRevalidate"];
2195 /**
2196 * The route handle.
2197 */
2198 handle?: IndexRouteObject["handle"];
2199 /**
2200 * Whether this is an index route.
2201 */
2202 index: true;
2203 /**
2204 * Child Route components
2205 */
2206 children?: undefined;
2207 /**
2208 * The React element to render when this Route matches.
2209 * Mutually exclusive with `Component`.
2210 */
2211 element?: React.ReactNode | null;
2212 /**
2213 * The React element to render while this router is loading data.
2214 * Mutually exclusive with `HydrateFallback`.
2215 */
2216 hydrateFallbackElement?: React.ReactNode | null;
2217 /**
2218 * The React element to render at this route if an error occurs.
2219 * Mutually exclusive with `ErrorBoundary`.
2220 */
2221 errorElement?: React.ReactNode | null;
2222 /**
2223 * The React Component to render when this route matches.
2224 * Mutually exclusive with `element`.
2225 */
2226 Component?: React.ComponentType | null;
2227 /**
2228 * The React Component to render while this router is loading data.
2229 * Mutually exclusive with `hydrateFallbackElement`.
2230 */
2231 HydrateFallback?: React.ComponentType | null;
2232 /**
2233 * The React Component to render at this route if an error occurs.
2234 * Mutually exclusive with `errorElement`.
2235 */
2236 ErrorBoundary?: React.ComponentType | null;
2237}
2238type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;
2239/**
2240 * Configures an element to render when a pattern matches the current location.
2241 * It must be rendered within a {@link Routes} element. Note that these routes
2242 * do not participate in data loading, actions, code splitting, or any other
2243 * route module features.
2244 *
2245 * @example
2246 * // Usually used in a declarative router
2247 * function App() {
2248 * return (
2249 * <BrowserRouter>
2250 * <Routes>
2251 * <Route index element={<StepOne />} />
2252 * <Route path="step-2" element={<StepTwo />} />
2253 * <Route path="step-3" element={<StepThree />} />
2254 * </Routes>
2255 * </BrowserRouter>
2256 * );
2257 * }
2258 *
2259 * // But can be used with a data router as well if you prefer the JSX notation
2260 * const routes = createRoutesFromElements(
2261 * <>
2262 * <Route index loader={step1Loader} Component={StepOne} />
2263 * <Route path="step-2" loader={step2Loader} Component={StepTwo} />
2264 * <Route path="step-3" loader={step3Loader} Component={StepThree} />
2265 * </>
2266 * );
2267 *
2268 * const router = createBrowserRouter(routes);
2269 *
2270 * function App() {
2271 * return <RouterProvider router={router} />;
2272 * }
2273 *
2274 * @public
2275 * @category Components
2276 * @param props Props
2277 * @param {PathRouteProps.action} props.action n/a
2278 * @param {PathRouteProps.caseSensitive} props.caseSensitive n/a
2279 * @param {PathRouteProps.Component} props.Component n/a
2280 * @param {PathRouteProps.children} props.children n/a
2281 * @param {PathRouteProps.element} props.element n/a
2282 * @param {PathRouteProps.ErrorBoundary} props.ErrorBoundary n/a
2283 * @param {PathRouteProps.errorElement} props.errorElement n/a
2284 * @param {PathRouteProps.handle} props.handle n/a
2285 * @param {PathRouteProps.HydrateFallback} props.HydrateFallback n/a
2286 * @param {PathRouteProps.hydrateFallbackElement} props.hydrateFallbackElement n/a
2287 * @param {PathRouteProps.id} props.id n/a
2288 * @param {PathRouteProps.index} props.index n/a
2289 * @param {PathRouteProps.lazy} props.lazy n/a
2290 * @param {PathRouteProps.loader} props.loader n/a
2291 * @param {PathRouteProps.path} props.path n/a
2292 * @param {PathRouteProps.shouldRevalidate} props.shouldRevalidate n/a
2293 * @returns {void}
2294 */
2295declare function Route(props: RouteProps): React.ReactElement | null;
2296/**
2297 * @category Types
2298 */
2299interface RouterProps {
2300 /**
2301 * The base path for the application. This is prepended to all locations
2302 */
2303 basename?: string;
2304 /**
2305 * Nested {@link Route} elements describing the route tree
2306 */
2307 children?: React.ReactNode;
2308 /**
2309 * The location to match against. Defaults to the current location.
2310 * This can be a string or a {@link Location} object.
2311 */
2312 location: Partial<Location> | string;
2313 /**
2314 * The type of navigation that triggered this `location` change.
2315 * Defaults to {@link NavigationType.Pop}.
2316 */
2317 navigationType?: Action;
2318 /**
2319 * The navigator to use for navigation. This is usually a history object
2320 * or a custom navigator that implements the {@link Navigator} interface.
2321 */
2322 navigator: Navigator;
2323 /**
2324 * Whether this router is static or not (used for SSR). If `true`, the router
2325 * will not be reactive to location changes.
2326 */
2327 static?: boolean;
2328 /**
2329 * Control whether router state updates are internally wrapped in
2330 * [`React.startTransition`](https://react.dev/reference/react/startTransition).
2331 *
2332 * - When left `undefined`, all router state updates are wrapped in
2333 * `React.startTransition`
2334 * - When set to `true`, {@link Link} and {@link Form} navigations will be wrapped
2335 * in `React.startTransition` and all router state updates are wrapped in
2336 * `React.startTransition`
2337 * - When set to `false`, the router will not leverage `React.startTransition`
2338 * on any navigations or state changes.
2339 *
2340 * For more information, please see the [docs](https://reactrouter.com/explanation/react-transitions).
2341 */
2342 unstable_useTransitions?: boolean;
2343}
2344/**
2345 * Provides location context for the rest of the app.
2346 *
2347 * Note: You usually won't render a `<Router>` directly. Instead, you'll render a
2348 * router that is more specific to your environment such as a {@link BrowserRouter}
2349 * in web browsers or a {@link ServerRouter} for server rendering.
2350 *
2351 * @public
2352 * @category Declarative Routers
2353 * @mode declarative
2354 * @param props Props
2355 * @param {RouterProps.basename} props.basename n/a
2356 * @param {RouterProps.children} props.children n/a
2357 * @param {RouterProps.location} props.location n/a
2358 * @param {RouterProps.navigationType} props.navigationType n/a
2359 * @param {RouterProps.navigator} props.navigator n/a
2360 * @param {RouterProps.static} props.static n/a
2361 * @param {RouterProps.unstable_useTransitions} props.unstable_useTransitions n/a
2362 * @returns React element for the rendered router or `null` if the location does
2363 * not match the {@link props.basename}
2364 */
2365declare function Router({ basename: basenameProp, children, location: locationProp, navigationType, navigator, static: staticProp, unstable_useTransitions, }: RouterProps): React.ReactElement | null;
2366/**
2367 * @category Types
2368 */
2369interface RoutesProps {
2370 /**
2371 * Nested {@link Route} elements
2372 */
2373 children?: React.ReactNode;
2374 /**
2375 * The {@link Location} to match against. Defaults to the current location.
2376 */
2377 location?: Partial<Location> | string;
2378}
2379/**
2380 * Renders a branch of {@link Route | `<Route>`s} that best matches the current
2381 * location. Note that these routes do not participate in [data loading](../../start/framework/route-module#loader),
2382 * [`action`](../../start/framework/route-module#action), code splitting, or
2383 * any other [route module](../../start/framework/route-module) features.
2384 *
2385 * @example
2386 * import { Route, Routes } from "react-router";
2387 *
2388 * <Routes>
2389 * <Route index element={<StepOne />} />
2390 * <Route path="step-2" element={<StepTwo />} />
2391 * <Route path="step-3" element={<StepThree />} />
2392 * </Routes>
2393 *
2394 * @public
2395 * @category Components
2396 * @param props Props
2397 * @param {RoutesProps.children} props.children n/a
2398 * @param {RoutesProps.location} props.location n/a
2399 * @returns React element for the rendered routes or `null` if no route matches
2400 */
2401declare function Routes({ children, location, }: RoutesProps): React.ReactElement | null;
2402interface AwaitResolveRenderFunction<Resolve = any> {
2403 (data: Awaited<Resolve>): React.ReactNode;
2404}
2405/**
2406 * @category Types
2407 */
2408interface AwaitProps<Resolve> {
2409 /**
2410 * When using a function, the resolved value is provided as the parameter.
2411 *
2412 * ```tsx [2]
2413 * <Await resolve={reviewsPromise}>
2414 * {(resolvedReviews) => <Reviews items={resolvedReviews} />}
2415 * </Await>
2416 * ```
2417 *
2418 * When using React elements, {@link useAsyncValue} will provide the
2419 * resolved value:
2420 *
2421 * ```tsx [2]
2422 * <Await resolve={reviewsPromise}>
2423 * <Reviews />
2424 * </Await>
2425 *
2426 * function Reviews() {
2427 * const resolvedReviews = useAsyncValue();
2428 * return <div>...</div>;
2429 * }
2430 * ```
2431 */
2432 children: React.ReactNode | AwaitResolveRenderFunction<Resolve>;
2433 /**
2434 * The error element renders instead of the `children` when the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
2435 * rejects.
2436 *
2437 * ```tsx
2438 * <Await
2439 * errorElement={<div>Oops</div>}
2440 * resolve={reviewsPromise}
2441 * >
2442 * <Reviews />
2443 * </Await>
2444 * ```
2445 *
2446 * To provide a more contextual error, you can use the {@link useAsyncError} in a
2447 * child component
2448 *
2449 * ```tsx
2450 * <Await
2451 * errorElement={<ReviewsError />}
2452 * resolve={reviewsPromise}
2453 * >
2454 * <Reviews />
2455 * </Await>
2456 *
2457 * function ReviewsError() {
2458 * const error = useAsyncError();
2459 * return <div>Error loading reviews: {error.message}</div>;
2460 * }
2461 * ```
2462 *
2463 * If you do not provide an `errorElement`, the rejected value will bubble up
2464 * to the nearest route-level [`ErrorBoundary`](../../start/framework/route-module#errorboundary)
2465 * and be accessible via the {@link useRouteError} hook.
2466 */
2467 errorElement?: React.ReactNode;
2468 /**
2469 * Takes a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
2470 * returned from a [`loader`](../../start/framework/route-module#loader) to be
2471 * resolved and rendered.
2472 *
2473 * ```tsx
2474 * import { Await, useLoaderData } from "react-router";
2475 *
2476 * export async function loader() {
2477 * let reviews = getReviews(); // not awaited
2478 * let book = await getBook();
2479 * return {
2480 * book,
2481 * reviews, // this is a promise
2482 * };
2483 * }
2484 *
2485 * export default function Book() {
2486 * const {
2487 * book,
2488 * reviews, // this is the same promise
2489 * } = useLoaderData();
2490 *
2491 * return (
2492 * <div>
2493 * <h1>{book.title}</h1>
2494 * <p>{book.description}</p>
2495 * <React.Suspense fallback={<ReviewsSkeleton />}>
2496 * <Await
2497 * // and is the promise we pass to Await
2498 * resolve={reviews}
2499 * >
2500 * <Reviews />
2501 * </Await>
2502 * </React.Suspense>
2503 * </div>
2504 * );
2505 * }
2506 * ```
2507 */
2508 resolve: Resolve;
2509}
2510/**
2511 * Used to render promise values with automatic error handling.
2512 *
2513 * **Note:** `<Await>` expects to be rendered inside a [`<React.Suspense>`](https://react.dev/reference/react/Suspense)
2514 *
2515 * @example
2516 * import { Await, useLoaderData } from "react-router";
2517 *
2518 * export async function loader() {
2519 * // not awaited
2520 * const reviews = getReviews();
2521 * // awaited (blocks the transition)
2522 * const book = await fetch("/api/book").then((res) => res.json());
2523 * return { book, reviews };
2524 * }
2525 *
2526 * function Book() {
2527 * const { book, reviews } = useLoaderData();
2528 * return (
2529 * <div>
2530 * <h1>{book.title}</h1>
2531 * <p>{book.description}</p>
2532 * <React.Suspense fallback={<ReviewsSkeleton />}>
2533 * <Await
2534 * resolve={reviews}
2535 * errorElement={
2536 * <div>Could not load reviews 😬</div>
2537 * }
2538 * children={(resolvedReviews) => (
2539 * <Reviews items={resolvedReviews} />
2540 * )}
2541 * />
2542 * </React.Suspense>
2543 * </div>
2544 * );
2545 * }
2546 *
2547 * @public
2548 * @category Components
2549 * @mode framework
2550 * @mode data
2551 * @param props Props
2552 * @param {AwaitProps.children} props.children n/a
2553 * @param {AwaitProps.errorElement} props.errorElement n/a
2554 * @param {AwaitProps.resolve} props.resolve n/a
2555 * @returns React element for the rendered awaited value
2556 */
2557declare function Await<Resolve>({ children, errorElement, resolve, }: AwaitProps<Resolve>): React.JSX.Element;
2558/**
2559 * Creates a route config from a React "children" object, which is usually
2560 * either a `<Route>` element or an array of them. Used internally by
2561 * `<Routes>` to create a route config from its children.
2562 *
2563 * @category Utils
2564 * @mode data
2565 * @param children The React children to convert into a route config
2566 * @param parentPath The path of the parent route, used to generate unique IDs.
2567 * @returns An array of {@link RouteObject}s that can be used with a {@link DataRouter}
2568 */
2569declare function createRoutesFromChildren(children: React.ReactNode, parentPath?: number[]): RouteObject[];
2570/**
2571 * Create route objects from JSX elements instead of arrays of objects.
2572 *
2573 * @example
2574 * const routes = createRoutesFromElements(
2575 * <>
2576 * <Route index loader={step1Loader} Component={StepOne} />
2577 * <Route path="step-2" loader={step2Loader} Component={StepTwo} />
2578 * <Route path="step-3" loader={step3Loader} Component={StepThree} />
2579 * </>
2580 * );
2581 *
2582 * const router = createBrowserRouter(routes);
2583 *
2584 * function App() {
2585 * return <RouterProvider router={router} />;
2586 * }
2587 *
2588 * @name createRoutesFromElements
2589 * @public
2590 * @category Utils
2591 * @mode data
2592 * @param children The React children to convert into a route config
2593 * @param parentPath The path of the parent route, used to generate unique IDs.
2594 * This is used for internal recursion and is not intended to be used by the
2595 * application developer.
2596 * @returns An array of {@link RouteObject}s that can be used with a {@link DataRouter}
2597 */
2598declare const createRoutesFromElements: typeof createRoutesFromChildren;
2599/**
2600 * Renders the result of {@link matchRoutes} into a React element.
2601 *
2602 * @public
2603 * @category Utils
2604 * @param matches The array of {@link RouteMatch | route matches} to render
2605 * @returns A React element that renders the matched routes or `null` if no matches
2606 */
2607declare function renderMatches(matches: RouteMatch[] | null): React.ReactElement | null;
2608declare function useRouteComponentProps(): {
2609 params: Readonly<Params<string>>;
2610 loaderData: any;
2611 actionData: any;
2612 matches: UIMatch<unknown, unknown>[];
2613};
2614type RouteComponentProps = ReturnType<typeof useRouteComponentProps>;
2615type RouteComponentType = React.ComponentType<RouteComponentProps>;
2616declare function WithComponentProps({ children, }: {
2617 children: React.ReactElement;
2618}): React.ReactElement<any, string | React.JSXElementConstructor<any>>;
2619declare function withComponentProps(Component: RouteComponentType): () => React.ReactElement<{
2620 params: Readonly<Params<string>>;
2621 loaderData: any;
2622 actionData: any;
2623 matches: UIMatch<unknown, unknown>[];
2624}, string | React.JSXElementConstructor<any>>;
2625declare function useHydrateFallbackProps(): {
2626 params: Readonly<Params<string>>;
2627 loaderData: any;
2628 actionData: any;
2629};
2630type HydrateFallbackProps = ReturnType<typeof useHydrateFallbackProps>;
2631type HydrateFallbackType = React.ComponentType<HydrateFallbackProps>;
2632declare function WithHydrateFallbackProps({ children, }: {
2633 children: React.ReactElement;
2634}): React.ReactElement<any, string | React.JSXElementConstructor<any>>;
2635declare function withHydrateFallbackProps(HydrateFallback: HydrateFallbackType): () => React.ReactElement<{
2636 params: Readonly<Params<string>>;
2637 loaderData: any;
2638 actionData: any;
2639}, string | React.JSXElementConstructor<any>>;
2640declare function useErrorBoundaryProps(): {
2641 params: Readonly<Params<string>>;
2642 loaderData: any;
2643 actionData: any;
2644 error: unknown;
2645};
2646type ErrorBoundaryProps = ReturnType<typeof useErrorBoundaryProps>;
2647type ErrorBoundaryType = React.ComponentType<ErrorBoundaryProps>;
2648declare function WithErrorBoundaryProps({ children, }: {
2649 children: React.ReactElement;
2650}): React.ReactElement<any, string | React.JSXElementConstructor<any>>;
2651declare function withErrorBoundaryProps(ErrorBoundary: ErrorBoundaryType): () => React.ReactElement<{
2652 params: Readonly<Params<string>>;
2653 loaderData: any;
2654 actionData: any;
2655 error: unknown;
2656}, string | React.JSXElementConstructor<any>>;
2657
2658interface IndexRouteObject {
2659 caseSensitive?: AgnosticIndexRouteObject["caseSensitive"];
2660 path?: AgnosticIndexRouteObject["path"];
2661 id?: AgnosticIndexRouteObject["id"];
2662 middleware?: AgnosticIndexRouteObject["middleware"];
2663 loader?: AgnosticIndexRouteObject["loader"];
2664 action?: AgnosticIndexRouteObject["action"];
2665 hasErrorBoundary?: AgnosticIndexRouteObject["hasErrorBoundary"];
2666 shouldRevalidate?: AgnosticIndexRouteObject["shouldRevalidate"];
2667 handle?: AgnosticIndexRouteObject["handle"];
2668 index: true;
2669 children?: undefined;
2670 element?: React.ReactNode | null;
2671 hydrateFallbackElement?: React.ReactNode | null;
2672 errorElement?: React.ReactNode | null;
2673 Component?: React.ComponentType | null;
2674 HydrateFallback?: React.ComponentType | null;
2675 ErrorBoundary?: React.ComponentType | null;
2676 lazy?: LazyRouteDefinition<RouteObject>;
2677}
2678interface NonIndexRouteObject {
2679 caseSensitive?: AgnosticNonIndexRouteObject["caseSensitive"];
2680 path?: AgnosticNonIndexRouteObject["path"];
2681 id?: AgnosticNonIndexRouteObject["id"];
2682 middleware?: AgnosticNonIndexRouteObject["middleware"];
2683 loader?: AgnosticNonIndexRouteObject["loader"];
2684 action?: AgnosticNonIndexRouteObject["action"];
2685 hasErrorBoundary?: AgnosticNonIndexRouteObject["hasErrorBoundary"];
2686 shouldRevalidate?: AgnosticNonIndexRouteObject["shouldRevalidate"];
2687 handle?: AgnosticNonIndexRouteObject["handle"];
2688 index?: false;
2689 children?: RouteObject[];
2690 element?: React.ReactNode | null;
2691 hydrateFallbackElement?: React.ReactNode | null;
2692 errorElement?: React.ReactNode | null;
2693 Component?: React.ComponentType | null;
2694 HydrateFallback?: React.ComponentType | null;
2695 ErrorBoundary?: React.ComponentType | null;
2696 lazy?: LazyRouteDefinition<RouteObject>;
2697}
2698type RouteObject = IndexRouteObject | NonIndexRouteObject;
2699type DataRouteObject = RouteObject & {
2700 children?: DataRouteObject[];
2701 id: string;
2702};
2703interface RouteMatch<ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {
2704}
2705interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {
2706}
2707type PatchRoutesOnNavigationFunctionArgs = AgnosticPatchRoutesOnNavigationFunctionArgs<RouteObject, RouteMatch>;
2708type PatchRoutesOnNavigationFunction = AgnosticPatchRoutesOnNavigationFunction<RouteObject, RouteMatch>;
2709interface DataRouterContextObject extends Omit<NavigationContextObject, "future" | "unstable_useTransitions"> {
2710 router: Router$1;
2711 staticContext?: StaticHandlerContext;
2712 onError?: ClientOnErrorFunction;
2713}
2714declare const DataRouterContext: React.Context<DataRouterContextObject | null>;
2715declare const DataRouterStateContext: React.Context<RouterState | null>;
2716type ViewTransitionContextObject = {
2717 isTransitioning: false;
2718} | {
2719 isTransitioning: true;
2720 flushSync: boolean;
2721 currentLocation: Location;
2722 nextLocation: Location;
2723};
2724declare const ViewTransitionContext: React.Context<ViewTransitionContextObject>;
2725type FetchersContextObject = Map<string, any>;
2726declare const FetchersContext: React.Context<FetchersContextObject>;
2727declare const AwaitContext: React.Context<TrackedPromise | null>;
2728declare const AwaitContextProvider: (props: React.ComponentProps<typeof AwaitContext.Provider>) => React.FunctionComponentElement<React.ProviderProps<TrackedPromise | null>>;
2729interface NavigateOptions {
2730 /** Replace the current entry in the history stack instead of pushing a new one */
2731 replace?: boolean;
2732 /** Adds persistent client side routing state to the next location */
2733 state?: any;
2734 /** If you are using {@link https://api.reactrouter.com/v7/functions/react_router.ScrollRestoration.html <ScrollRestoration>}, prevent the scroll position from being reset to the top of the window when navigating */
2735 preventScrollReset?: boolean;
2736 /** Defines the relative path behavior for the link. "route" will use the route hierarchy so ".." will remove all URL segments of the current route pattern while "path" will use the URL path so ".." will remove one URL segment. */
2737 relative?: RelativeRoutingType;
2738 /** Wraps the initial state update for this navigation in a {@link https://react.dev/reference/react-dom/flushSync ReactDOM.flushSync} call instead of the default {@link https://react.dev/reference/react/startTransition React.startTransition} */
2739 flushSync?: boolean;
2740 /** Enables a {@link https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API View Transition} for this navigation by wrapping the final state update in `document.startViewTransition()`. If you need to apply specific styles for this view transition, you will also need to leverage the {@link https://api.reactrouter.com/v7/functions/react_router.useViewTransitionState.html useViewTransitionState()} hook. */
2741 viewTransition?: boolean;
2742 /** Specifies the default revalidation behavior after this submission */
2743 unstable_defaultShouldRevalidate?: boolean;
2744}
2745/**
2746 * A Navigator is a "location changer"; it's how you get to different locations.
2747 *
2748 * Every history instance conforms to the Navigator interface, but the
2749 * distinction is useful primarily when it comes to the low-level `<Router>` API
2750 * where both the location and a navigator must be provided separately in order
2751 * to avoid "tearing" that may occur in a suspense-enabled app if the action
2752 * and/or location were to be read directly from the history instance.
2753 */
2754interface Navigator {
2755 createHref: History["createHref"];
2756 encodeLocation?: History["encodeLocation"];
2757 go: History["go"];
2758 push(to: To, state?: any, opts?: NavigateOptions): void;
2759 replace(to: To, state?: any, opts?: NavigateOptions): void;
2760}
2761interface NavigationContextObject {
2762 basename: string;
2763 navigator: Navigator;
2764 static: boolean;
2765 unstable_useTransitions: boolean | undefined;
2766 future: {};
2767}
2768declare const NavigationContext: React.Context<NavigationContextObject>;
2769interface LocationContextObject {
2770 location: Location;
2771 navigationType: Action;
2772}
2773declare const LocationContext: React.Context<LocationContextObject>;
2774interface RouteContextObject {
2775 outlet: React.ReactElement | null;
2776 matches: RouteMatch[];
2777 isDataRoute: boolean;
2778}
2779declare const RouteContext: React.Context<RouteContextObject>;
2780
2781type Primitive = null | undefined | string | number | boolean | symbol | bigint;
2782type LiteralUnion<LiteralType, BaseType extends Primitive> = LiteralType | (BaseType & Record<never, never>);
2783interface HtmlLinkProps {
2784 /**
2785 * Address of the hyperlink
2786 */
2787 href?: string;
2788 /**
2789 * How the element handles crossorigin requests
2790 */
2791 crossOrigin?: "anonymous" | "use-credentials";
2792 /**
2793 * Relationship between the document containing the hyperlink and the destination resource
2794 */
2795 rel: LiteralUnion<"alternate" | "dns-prefetch" | "icon" | "manifest" | "modulepreload" | "next" | "pingback" | "preconnect" | "prefetch" | "preload" | "prerender" | "search" | "stylesheet", string>;
2796 /**
2797 * Applicable media: "screen", "print", "(max-width: 764px)"
2798 */
2799 media?: string;
2800 /**
2801 * Integrity metadata used in Subresource Integrity checks
2802 */
2803 integrity?: string;
2804 /**
2805 * Language of the linked resource
2806 */
2807 hrefLang?: string;
2808 /**
2809 * Hint for the type of the referenced resource
2810 */
2811 type?: string;
2812 /**
2813 * Referrer policy for fetches initiated by the element
2814 */
2815 referrerPolicy?: "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
2816 /**
2817 * Sizes of the icons (for rel="icon")
2818 */
2819 sizes?: string;
2820 /**
2821 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
2822 */
2823 as?: LiteralUnion<"audio" | "audioworklet" | "document" | "embed" | "fetch" | "font" | "frame" | "iframe" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt", string>;
2824 /**
2825 * Color to use when customizing a site's icon (for rel="mask-icon")
2826 */
2827 color?: string;
2828 /**
2829 * Whether the link is disabled
2830 */
2831 disabled?: boolean;
2832 /**
2833 * The title attribute has special semantics on this element: Title of the link; CSS style sheet set name.
2834 */
2835 title?: string;
2836 /**
2837 * Images to use in different situations, e.g., high-resolution displays,
2838 * small monitors, etc. (for rel="preload")
2839 */
2840 imageSrcSet?: string;
2841 /**
2842 * Image sizes for different page layouts (for rel="preload")
2843 */
2844 imageSizes?: string;
2845}
2846interface HtmlLinkPreloadImage extends HtmlLinkProps {
2847 /**
2848 * Relationship between the document containing the hyperlink and the destination resource
2849 */
2850 rel: "preload";
2851 /**
2852 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
2853 */
2854 as: "image";
2855 /**
2856 * Address of the hyperlink
2857 */
2858 href?: string;
2859 /**
2860 * Images to use in different situations, e.g., high-resolution displays,
2861 * small monitors, etc. (for rel="preload")
2862 */
2863 imageSrcSet: string;
2864 /**
2865 * Image sizes for different page layouts (for rel="preload")
2866 */
2867 imageSizes?: string;
2868}
2869/**
2870 * Represents a `<link>` element.
2871 *
2872 * WHATWG Specification: https://html.spec.whatwg.org/multipage/semantics.html#the-link-element
2873 */
2874type HtmlLinkDescriptor = (HtmlLinkProps & Pick<Required<HtmlLinkProps>, "href">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "imageSizes">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "href"> & {
2875 imageSizes?: never;
2876});
2877interface PageLinkDescriptor extends Omit<HtmlLinkDescriptor, "href" | "rel" | "type" | "sizes" | "imageSrcSet" | "imageSizes" | "as" | "color" | "title"> {
2878 /**
2879 * A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
2880 * attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
2881 * element
2882 */
2883 nonce?: string | undefined;
2884 /**
2885 * The absolute path of the page to prefetch, e.g. `/absolute/path`.
2886 */
2887 page: string;
2888}
2889type LinkDescriptor = HtmlLinkDescriptor | PageLinkDescriptor;
2890
2891type Serializable = undefined | null | boolean | string | symbol | number | Array<Serializable> | {
2892 [key: PropertyKey]: Serializable;
2893} | bigint | Date | URL | RegExp | Error | Map<Serializable, Serializable> | Set<Serializable> | Promise<Serializable>;
2894
2895type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
2896type IsAny<T> = 0 extends 1 & T ? true : false;
2897type Func = (...args: any[]) => unknown;
2898type Pretty<T> = {
2899 [K in keyof T]: T[K];
2900} & {};
2901type Normalize<T> = _Normalize<UnionKeys<T>, T>;
2902type _Normalize<Key extends keyof any, T> = T extends infer U ? Pretty<{
2903 [K in Key as K extends keyof U ? undefined extends U[K] ? never : K : never]: K extends keyof U ? U[K] : never;
2904} & {
2905 [K in Key as K extends keyof U ? undefined extends U[K] ? K : never : never]?: K extends keyof U ? U[K] : never;
2906} & {
2907 [K in Key as K extends keyof U ? never : K]?: undefined;
2908}> : never;
2909type UnionKeys<T> = T extends any ? keyof T : never;
2910
2911type RouteModule$1 = {
2912 meta?: Func;
2913 links?: Func;
2914 headers?: Func;
2915 loader?: Func;
2916 clientLoader?: Func;
2917 action?: Func;
2918 clientAction?: Func;
2919 HydrateFallback?: Func;
2920 default?: Func;
2921 ErrorBoundary?: Func;
2922 [key: string]: unknown;
2923};
2924
2925/**
2926 * A brand that can be applied to a type to indicate that it will serialize
2927 * to a specific type when transported to the client from a loader.
2928 * Only use this if you have additional serialization/deserialization logic
2929 * in your application.
2930 */
2931type unstable_SerializesTo<T> = {
2932 unstable__ReactRouter_SerializesTo: [T];
2933};
2934
2935type 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> ? {
2936 [K in keyof T]: Serialize<T[K]>;
2937} : undefined;
2938type VoidToUndefined<T> = Equal<T, void> extends true ? undefined : T;
2939type DataFrom<T> = IsAny<T> extends true ? undefined : T extends Func ? VoidToUndefined<Awaited<ReturnType<T>>> : undefined;
2940type ClientData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? U : T;
2941type ServerData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? Serialize<U> : Serialize<T>;
2942type ServerDataFrom<T> = ServerData<DataFrom<T>>;
2943type ClientDataFrom<T> = ClientData<DataFrom<T>>;
2944type ClientDataFunctionArgs<Params> = {
2945 /**
2946 * 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.
2947 *
2948 * @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.
2949 **/
2950 request: Request;
2951 /**
2952 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
2953 * @example
2954 * // app/routes.ts
2955 * route("teams/:teamId", "./team.tsx"),
2956 *
2957 * // app/team.tsx
2958 * export function clientLoader({
2959 * params,
2960 * }: Route.ClientLoaderArgs) {
2961 * params.teamId;
2962 * // ^ string
2963 * }
2964 **/
2965 params: Params;
2966 /**
2967 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
2968 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
2969 */
2970 unstable_pattern: string;
2971 /**
2972 * When `future.v8_middleware` is not enabled, this is undefined.
2973 *
2974 * When `future.v8_middleware` is enabled, this is an instance of
2975 * `RouterContextProvider` and can be used to access context values
2976 * from your route middlewares. You may pass in initial context values in your
2977 * `<HydratedRouter getContext>` prop
2978 */
2979 context: Readonly<RouterContextProvider>;
2980};
2981type ServerDataFunctionArgs<Params> = {
2982 /** 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. */
2983 request: Request;
2984 /**
2985 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
2986 * @example
2987 * // app/routes.ts
2988 * route("teams/:teamId", "./team.tsx"),
2989 *
2990 * // app/team.tsx
2991 * export function loader({
2992 * params,
2993 * }: Route.LoaderArgs) {
2994 * params.teamId;
2995 * // ^ string
2996 * }
2997 **/
2998 params: Params;
2999 /**
3000 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
3001 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
3002 */
3003 unstable_pattern: string;
3004 /**
3005 * Without `future.v8_middleware` enabled, this is the context passed in
3006 * to your server adapter's `getLoadContext` function. It's a way to bridge the
3007 * gap between the adapter's request/response API with your React Router app.
3008 * It is only applicable if you are using a custom server adapter.
3009 *
3010 * With `future.v8_middleware` enabled, this is an instance of
3011 * `RouterContextProvider` and can be used for type-safe access to
3012 * context value set in your route middlewares. If you are using a custom
3013 * server adapter, you may provide an initial set of context values from your
3014 * `getLoadContext` function.
3015 */
3016 context: MiddlewareEnabled extends true ? Readonly<RouterContextProvider> : AppLoadContext;
3017};
3018type SerializeFrom<T> = T extends (...args: infer Args) => unknown ? Args extends [
3019 ClientLoaderFunctionArgs | ClientActionFunctionArgs | ClientDataFunctionArgs<unknown>
3020] ? ClientDataFrom<T> : ServerDataFrom<T> : T;
3021type IsDefined<T> = Equal<T, undefined> extends true ? false : true;
3022type IsHydrate<ClientLoader> = ClientLoader extends {
3023 hydrate: true;
3024} ? true : ClientLoader extends {
3025 hydrate: false;
3026} ? false : false;
3027type GetLoaderData<T extends RouteModule$1> = _DataLoaderData<ServerDataFrom<T["loader"]>, ClientDataFrom<T["clientLoader"]>, IsHydrate<T["clientLoader"]>, T extends {
3028 HydrateFallback: Func;
3029} ? true : false>;
3030type _DataLoaderData<ServerLoaderData, ClientLoaderData, ClientLoaderHydrate extends boolean, HasHydrateFallback> = [
3031 HasHydrateFallback,
3032 ClientLoaderHydrate
3033] extends [true, true] ? IsDefined<ClientLoaderData> extends true ? ClientLoaderData : undefined : [
3034 IsDefined<ClientLoaderData>,
3035 IsDefined<ServerLoaderData>
3036] extends [true, true] ? ServerLoaderData | ClientLoaderData : IsDefined<ClientLoaderData> extends true ? ClientLoaderData : IsDefined<ServerLoaderData> extends true ? ServerLoaderData : undefined;
3037type GetActionData<T extends RouteModule$1> = _DataActionData<ServerDataFrom<T["action"]>, ClientDataFrom<T["clientAction"]>>;
3038type _DataActionData<ServerActionData, ClientActionData> = Awaited<[
3039 IsDefined<ServerActionData>,
3040 IsDefined<ClientActionData>
3041] extends [true, true] ? ServerActionData | ClientActionData : IsDefined<ClientActionData> extends true ? ClientActionData : IsDefined<ServerActionData> extends true ? ServerActionData : undefined>;
3042
3043interface RouteModules {
3044 [routeId: string]: RouteModule | undefined;
3045}
3046/**
3047 * The shape of a route module shipped to the client
3048 */
3049interface RouteModule {
3050 clientAction?: ClientActionFunction;
3051 clientLoader?: ClientLoaderFunction;
3052 clientMiddleware?: MiddlewareFunction<Record<string, DataStrategyResult>>[];
3053 ErrorBoundary?: ErrorBoundaryComponent;
3054 HydrateFallback?: HydrateFallbackComponent;
3055 Layout?: LayoutComponent;
3056 default: RouteComponent;
3057 handle?: RouteHandle;
3058 links?: LinksFunction;
3059 meta?: MetaFunction;
3060 shouldRevalidate?: ShouldRevalidateFunction;
3061}
3062/**
3063 * The shape of a route module on the server
3064 */
3065interface ServerRouteModule extends RouteModule {
3066 action?: ActionFunction;
3067 headers?: HeadersFunction | {
3068 [name: string]: string;
3069 };
3070 loader?: LoaderFunction;
3071 middleware?: MiddlewareFunction<Response>[];
3072}
3073/**
3074 * A function that handles data mutations for a route on the client
3075 */
3076type ClientActionFunction = (args: ClientActionFunctionArgs) => ReturnType<ActionFunction>;
3077/**
3078 * Arguments passed to a route `clientAction` function
3079 */
3080type ClientActionFunctionArgs = ActionFunctionArgs & {
3081 serverAction: <T = unknown>() => Promise<SerializeFrom<T>>;
3082};
3083/**
3084 * A function that loads data for a route on the client
3085 */
3086type ClientLoaderFunction = ((args: ClientLoaderFunctionArgs) => ReturnType<LoaderFunction>) & {
3087 hydrate?: boolean;
3088};
3089/**
3090 * Arguments passed to a route `clientLoader` function
3091 */
3092type ClientLoaderFunctionArgs = LoaderFunctionArgs & {
3093 serverLoader: <T = unknown>() => Promise<SerializeFrom<T>>;
3094};
3095/**
3096 * ErrorBoundary to display for this route
3097 */
3098type ErrorBoundaryComponent = ComponentType;
3099type HeadersArgs = {
3100 loaderHeaders: Headers;
3101 parentHeaders: Headers;
3102 actionHeaders: Headers;
3103 errorHeaders: Headers | undefined;
3104};
3105/**
3106 * A function that returns HTTP headers to be used for a route. These headers
3107 * will be merged with (and take precedence over) headers from parent routes.
3108 */
3109interface HeadersFunction {
3110 (args: HeadersArgs): Headers | HeadersInit;
3111}
3112/**
3113 * `<Route HydrateFallback>` component to render on initial loads
3114 * when client loaders are present
3115 */
3116type HydrateFallbackComponent = ComponentType;
3117/**
3118 * Optional, root-only `<Route Layout>` component to wrap the root content in.
3119 * Useful for defining the <html>/<head>/<body> document shell shared by the
3120 * Component, HydrateFallback, and ErrorBoundary
3121 */
3122type LayoutComponent = ComponentType<{
3123 children: ReactElement<unknown, ErrorBoundaryComponent | HydrateFallbackComponent | RouteComponent>;
3124}>;
3125/**
3126 * A function that defines `<link>` tags to be inserted into the `<head>` of
3127 * the document on route transitions.
3128 *
3129 * @see https://reactrouter.com/start/framework/route-module#meta
3130 */
3131interface LinksFunction {
3132 (): LinkDescriptor[];
3133}
3134interface MetaMatch<RouteId extends string = string, Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown> {
3135 id: RouteId;
3136 pathname: DataRouteMatch["pathname"];
3137 /** @deprecated Use `MetaMatch.loaderData` instead */
3138 data: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
3139 loaderData: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
3140 handle?: RouteHandle;
3141 params: DataRouteMatch["params"];
3142 meta: MetaDescriptor[];
3143 error?: unknown;
3144}
3145type MetaMatches<MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> = Array<{
3146 [K in keyof MatchLoaders]: MetaMatch<Exclude<K, number | symbol>, MatchLoaders[K]>;
3147}[keyof MatchLoaders]>;
3148interface MetaArgs<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
3149 /** @deprecated Use `MetaArgs.loaderData` instead */
3150 data: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
3151 loaderData: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
3152 params: Params;
3153 location: Location;
3154 matches: MetaMatches<MatchLoaders>;
3155 error?: unknown;
3156}
3157/**
3158 * A function that returns an array of data objects to use for rendering
3159 * metadata HTML tags in a route. These tags are not rendered on descendant
3160 * routes in the route hierarchy. In other words, they will only be rendered on
3161 * the route in which they are exported.
3162 *
3163 * @param Loader - The type of the current route's loader function
3164 * @param MatchLoaders - Mapping from a parent route's filepath to its loader
3165 * function type
3166 *
3167 * Note that parent route filepaths are relative to the `app/` directory.
3168 *
3169 * For example, if this meta function is for `/sales/customers/$customerId`:
3170 *
3171 * ```ts
3172 * // app/root.tsx
3173 * const loader = () => ({ hello: "world" })
3174 * export type Loader = typeof loader
3175 *
3176 * // app/routes/sales.tsx
3177 * const loader = () => ({ salesCount: 1074 })
3178 * export type Loader = typeof loader
3179 *
3180 * // app/routes/sales/customers.tsx
3181 * const loader = () => ({ customerCount: 74 })
3182 * export type Loader = typeof loader
3183 *
3184 * // app/routes/sales/customers/$customersId.tsx
3185 * import type { Loader as RootLoader } from "../../../root"
3186 * import type { Loader as SalesLoader } from "../../sales"
3187 * import type { Loader as CustomersLoader } from "../../sales/customers"
3188 *
3189 * const loader = () => ({ name: "Customer name" })
3190 *
3191 * const meta: MetaFunction<typeof loader, {
3192 * "root": RootLoader,
3193 * "routes/sales": SalesLoader,
3194 * "routes/sales/customers": CustomersLoader,
3195 * }> = ({ data, matches }) => {
3196 * const { name } = data
3197 * // ^? string
3198 * const { customerCount } = matches.find((match) => match.id === "routes/sales/customers").data
3199 * // ^? number
3200 * const { salesCount } = matches.find((match) => match.id === "routes/sales").data
3201 * // ^? number
3202 * const { hello } = matches.find((match) => match.id === "root").data
3203 * // ^? "world"
3204 * }
3205 * ```
3206 */
3207interface MetaFunction<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
3208 (args: MetaArgs<Loader, MatchLoaders>): MetaDescriptor[] | undefined;
3209}
3210type MetaDescriptor = {
3211 charSet: "utf-8";
3212} | {
3213 title: string;
3214} | {
3215 name: string;
3216 content: string;
3217} | {
3218 property: string;
3219 content: string;
3220} | {
3221 httpEquiv: string;
3222 content: string;
3223} | {
3224 "script:ld+json": LdJsonObject;
3225} | {
3226 tagName: "meta" | "link";
3227 [name: string]: string;
3228} | {
3229 [name: string]: unknown;
3230};
3231type LdJsonObject = {
3232 [Key in string]: LdJsonValue;
3233} & {
3234 [Key in string]?: LdJsonValue | undefined;
3235};
3236type LdJsonArray = LdJsonValue[] | readonly LdJsonValue[];
3237type LdJsonPrimitive = string | number | boolean | null;
3238type LdJsonValue = LdJsonPrimitive | LdJsonObject | LdJsonArray;
3239/**
3240 * A React component that is rendered for a route.
3241 */
3242type RouteComponent = ComponentType<{}>;
3243/**
3244 * An arbitrary object that is associated with a route.
3245 *
3246 * @see https://reactrouter.com/how-to/using-handle
3247 */
3248type RouteHandle = unknown;
3249
3250type unstable_ServerInstrumentation = {
3251 handler?: unstable_InstrumentRequestHandlerFunction;
3252 route?: unstable_InstrumentRouteFunction;
3253};
3254type unstable_ClientInstrumentation = {
3255 router?: unstable_InstrumentRouterFunction;
3256 route?: unstable_InstrumentRouteFunction;
3257};
3258type unstable_InstrumentRequestHandlerFunction = (handler: InstrumentableRequestHandler) => void;
3259type unstable_InstrumentRouterFunction = (router: InstrumentableRouter) => void;
3260type unstable_InstrumentRouteFunction = (route: InstrumentableRoute) => void;
3261type unstable_InstrumentationHandlerResult = {
3262 status: "success";
3263 error: undefined;
3264} | {
3265 status: "error";
3266 error: Error;
3267};
3268type InstrumentFunction<T> = (handler: () => Promise<unstable_InstrumentationHandlerResult>, info: T) => Promise<void>;
3269type ReadonlyRequest = {
3270 method: string;
3271 url: string;
3272 headers: Pick<Headers, "get">;
3273};
3274type ReadonlyContext = MiddlewareEnabled extends true ? Pick<RouterContextProvider, "get"> : Readonly<AppLoadContext>;
3275type InstrumentableRoute = {
3276 id: string;
3277 index: boolean | undefined;
3278 path: string | undefined;
3279 instrument(instrumentations: RouteInstrumentations): void;
3280};
3281type RouteInstrumentations = {
3282 lazy?: InstrumentFunction<RouteLazyInstrumentationInfo>;
3283 "lazy.loader"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
3284 "lazy.action"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
3285 "lazy.middleware"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
3286 middleware?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
3287 loader?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
3288 action?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
3289};
3290type RouteLazyInstrumentationInfo = undefined;
3291type RouteHandlerInstrumentationInfo = Readonly<{
3292 request: ReadonlyRequest;
3293 params: LoaderFunctionArgs["params"];
3294 unstable_pattern: string;
3295 context: ReadonlyContext;
3296}>;
3297type InstrumentableRouter = {
3298 instrument(instrumentations: RouterInstrumentations): void;
3299};
3300type RouterInstrumentations = {
3301 navigate?: InstrumentFunction<RouterNavigationInstrumentationInfo>;
3302 fetch?: InstrumentFunction<RouterFetchInstrumentationInfo>;
3303};
3304type RouterNavigationInstrumentationInfo = Readonly<{
3305 to: string | number;
3306 currentUrl: string;
3307 formMethod?: HTMLFormMethod;
3308 formEncType?: FormEncType;
3309 formData?: FormData;
3310 body?: any;
3311}>;
3312type RouterFetchInstrumentationInfo = Readonly<{
3313 href: string;
3314 currentUrl: string;
3315 fetcherKey: string;
3316 formMethod?: HTMLFormMethod;
3317 formEncType?: FormEncType;
3318 formData?: FormData;
3319 body?: any;
3320}>;
3321type InstrumentableRequestHandler = {
3322 instrument(instrumentations: RequestHandlerInstrumentations): void;
3323};
3324type RequestHandlerInstrumentations = {
3325 request?: InstrumentFunction<RequestHandlerInstrumentationInfo>;
3326};
3327type RequestHandlerInstrumentationInfo = Readonly<{
3328 request: ReadonlyRequest;
3329 context: ReadonlyContext | undefined;
3330}>;
3331
3332export { type RouterState as $, type ActionFunction as A, type BlockerFunction as B, type ClientActionFunction as C, type DataStrategyResult as D, type PathMatch as E, type Func as F, type GetLoaderData as G, type HeadersFunction as H, type Navigation as I, Action as J, type RouteObject as K, type Location as L, type MetaFunction as M, type Normalize as N, type InitialEntry as O, type Params as P, type HydrationState as Q, type RouteModule$1 as R, type ShouldRevalidateFunction as S, type To as T, type UIMatch as U, type IndexRouteObject as V, type RouteComponentType as W, type HydrateFallbackType as X, type ErrorBoundaryType as Y, type NonIndexRouteObject as Z, type Equal as _, type ClientLoaderFunction as a, type RouterProviderProps as a$, type PatchRoutesOnNavigationFunction as a0, type DataRouteObject as a1, type StaticHandler as a2, type GetScrollPositionFunction as a3, type GetScrollRestorationKeyFunction as a4, type StaticHandlerContext as a5, type Fetcher as a6, type NavigationStates as a7, type RouterSubscriber as a8, type RouterNavigateOptions as a9, IDLE_FETCHER as aA, IDLE_BLOCKER as aB, data as aC, generatePath as aD, isRouteErrorResponse as aE, matchPath as aF, matchRoutes as aG, redirect as aH, redirectDocument as aI, replace as aJ, resolvePath as aK, type DataRouteMatch as aL, type Navigator as aM, type PatchRoutesOnNavigationFunctionArgs as aN, type RouteMatch as aO, AwaitContextProvider as aP, type AwaitProps as aQ, type IndexRouteProps as aR, type ClientOnErrorFunction as aS, type LayoutRouteProps as aT, type MemoryRouterOpts as aU, type MemoryRouterProps as aV, type NavigateProps as aW, type OutletProps as aX, type PathRouteProps as aY, type RouteProps as aZ, type RouterProps as a_, type RouterFetchOptions as aa, type RevalidationState as ab, type ActionFunctionArgs as ac, type DataStrategyFunctionArgs as ad, type DataStrategyMatch as ae, DataWithResponseInit as af, type ErrorResponse as ag, type FormEncType as ah, type FormMethod as ai, type HTMLFormMethod as aj, type LazyRouteFunction as ak, type LoaderFunctionArgs as al, type MiddlewareFunction as am, type PathParam as an, type RedirectFunction as ao, type RouterContext as ap, type ShouldRevalidateFunctionArgs as aq, createContext as ar, createPath as as, parsePath as at, type unstable_ServerInstrumentation as au, type unstable_InstrumentRequestHandlerFunction as av, type unstable_InstrumentRouterFunction as aw, type unstable_InstrumentRouteFunction as ax, type unstable_InstrumentationHandlerResult as ay, IDLE_NAVIGATION as az, type LinksFunction as b, type RoutesProps as b0, Await as b1, MemoryRouter as b2, Navigate as b3, Outlet as b4, Route as b5, Router as b6, RouterProvider as b7, Routes as b8, createMemoryRouter as b9, WithComponentProps as bA, withComponentProps as bB, WithHydrateFallbackProps as bC, withHydrateFallbackProps as bD, WithErrorBoundaryProps as bE, withErrorBoundaryProps as bF, type RouteManifest as bG, type ServerRouteModule as bH, type History as bI, type FutureConfig as bJ, type CreateStaticHandlerOptions as bK, createRoutesFromChildren as ba, createRoutesFromElements as bb, renderMatches as bc, type ClientActionFunctionArgs as bd, type ClientLoaderFunctionArgs as be, type HeadersArgs as bf, type MetaArgs as bg, type PageLinkDescriptor as bh, type HtmlLinkDescriptor as bi, type Future as bj, type unstable_SerializesTo as bk, createMemoryHistory as bl, createBrowserHistory as bm, createHashHistory as bn, invariant as bo, createRouter as bp, ErrorResponseImpl as bq, DataRouterContext as br, DataRouterStateContext as bs, FetchersContext as bt, LocationContext as bu, NavigationContext as bv, RouteContext as bw, ViewTransitionContext as bx, hydrationRouteProperties as by, mapRouteProperties as bz, RouterContextProvider as c, type LoaderFunction as d, type RouterInit as e, type LinkDescriptor as f, type Pretty as g, type MetaDescriptor as h, type ServerDataFunctionArgs as i, type MiddlewareNextFunction as j, type ClientDataFunctionArgs as k, type ServerDataFrom as l, type GetActionData as m, type Router$1 as n, type RouteModules as o, type DataStrategyFunction as p, type MiddlewareEnabled as q, type AppLoadContext as r, type NavigateOptions as s, type Blocker as t, type unstable_ClientInstrumentation as u, type SerializeFrom as v, type RelativeRoutingType as w, type ParamParseKey as x, type Path as y, type PathPattern as z };