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