UNPKG

93.7 kBTypeScriptView Raw
1import * as React from 'react';
2export { BrowserRouter, Form, HashRouter, Link, Links, MemoryRouter, Meta, NavLink, Navigate, Outlet, Route, Router, RouterProvider, Routes, ScrollRestoration, StaticRouter, StaticRouterProvider, unstable_HistoryRouter } from 'react-router/internal/react-server-client';
3import { ParseOptions, SerializeOptions } from 'cookie';
4export { ParseOptions as CookieParseOptions, SerializeOptions as CookieSerializeOptions } from 'cookie';
5
6/**
7 * Actions represent the type of change to a location value.
8 */
9declare enum Action {
10 /**
11 * A POP indicates a change to an arbitrary index in the history stack, such
12 * as a back or forward navigation. It does not describe the direction of the
13 * navigation, only that the current index changed.
14 *
15 * Note: This is the default action for newly created history objects.
16 */
17 Pop = "POP",
18 /**
19 * A PUSH indicates a new entry being added to the history stack, such as when
20 * a link is clicked and a new page loads. When this happens, all subsequent
21 * entries in the stack are lost.
22 */
23 Push = "PUSH",
24 /**
25 * A REPLACE indicates the entry at the current index in the history stack
26 * being replaced by a new one.
27 */
28 Replace = "REPLACE"
29}
30/**
31 * The pathname, search, and hash values of a URL.
32 */
33interface Path {
34 /**
35 * A URL pathname, beginning with a /.
36 */
37 pathname: string;
38 /**
39 * A URL search string, beginning with a ?.
40 */
41 search: string;
42 /**
43 * A URL fragment identifier, beginning with a #.
44 */
45 hash: string;
46}
47/**
48 * An entry in a history stack. A location contains information about the
49 * URL path, as well as possibly some arbitrary state and a key.
50 */
51interface Location<State = any> extends Path {
52 /**
53 * A value of arbitrary data associated with this location.
54 */
55 state: State;
56 /**
57 * A unique string associated with this location. May be used to safely store
58 * and retrieve data in some other storage API, like `localStorage`.
59 *
60 * Note: This value is always "default" on the initial location.
61 */
62 key: string;
63}
64/**
65 * A change to the current location.
66 */
67interface Update {
68 /**
69 * The action that triggered the change.
70 */
71 action: Action;
72 /**
73 * The new location.
74 */
75 location: Location;
76 /**
77 * The delta between this location and the former location in the history stack
78 */
79 delta: number | null;
80}
81/**
82 * A function that receives notifications about location changes.
83 */
84interface Listener {
85 (update: Update): void;
86}
87/**
88 * Describes a location that is the destination of some navigation used in
89 * {@link Link}, {@link useNavigate}, etc.
90 */
91type To = string | Partial<Path>;
92/**
93 * A history is an interface to the navigation stack. The history serves as the
94 * source of truth for the current location, as well as provides a set of
95 * methods that may be used to change it.
96 *
97 * It is similar to the DOM's `window.history` object, but with a smaller, more
98 * focused API.
99 */
100interface History {
101 /**
102 * The last action that modified the current location. This will always be
103 * Action.Pop when a history instance is first created. This value is mutable.
104 */
105 readonly action: Action;
106 /**
107 * The current location. This value is mutable.
108 */
109 readonly location: Location;
110 /**
111 * Returns a valid href for the given `to` value that may be used as
112 * the value of an <a href> attribute.
113 *
114 * @param to - The destination URL
115 */
116 createHref(to: To): string;
117 /**
118 * Returns a URL for the given `to` value
119 *
120 * @param to - The destination URL
121 */
122 createURL(to: To): URL;
123 /**
124 * Encode a location the same way window.history would do (no-op for memory
125 * history) so we ensure our PUSH/REPLACE navigations for data routers
126 * behave the same as POP
127 *
128 * @param to Unencoded path
129 */
130 encodeLocation(to: To): Path;
131 /**
132 * Pushes a new location onto the history stack, increasing its length by one.
133 * If there were any entries in the stack after the current one, they are
134 * lost.
135 *
136 * @param to - The new URL
137 * @param state - Data to associate with the new location
138 */
139 push(to: To, state?: any): void;
140 /**
141 * Replaces the current location in the history stack with a new one. The
142 * location that was replaced will no longer be available.
143 *
144 * @param to - The new URL
145 * @param state - Data to associate with the new location
146 */
147 replace(to: To, state?: any): void;
148 /**
149 * Navigates `n` entries backward/forward in the history stack relative to the
150 * current index. For example, a "back" navigation would use go(-1).
151 *
152 * @param delta - The delta in the stack index
153 */
154 go(delta: number): void;
155 /**
156 * Sets up a listener that will be called whenever the current location
157 * changes.
158 *
159 * @param listener - A function that will be called when the location changes
160 * @returns unlisten - A function that may be used to stop listening
161 */
162 listen(listener: Listener): () => void;
163}
164
165/**
166 * An augmentable interface users can modify in their app-code to opt into
167 * future-flag-specific types
168 */
169interface Future {
170}
171type MiddlewareEnabled = Future extends {
172 v8_middleware: infer T extends boolean;
173} ? T : false;
174
175type MaybePromise<T> = T | Promise<T>;
176/**
177 * Map of routeId -> data returned from a loader/action/error
178 */
179interface RouteData {
180 [routeId: string]: any;
181}
182type LowerCaseFormMethod = "get" | "post" | "put" | "patch" | "delete";
183type UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;
184/**
185 * Users can specify either lowercase or uppercase form methods on `<Form>`,
186 * useSubmit(), `<fetcher.Form>`, etc.
187 */
188type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;
189/**
190 * Active navigation/fetcher form methods are exposed in uppercase on the
191 * RouterState. This is to align with the normalization done via fetch().
192 */
193type FormMethod = UpperCaseFormMethod;
194type FormEncType = "application/x-www-form-urlencoded" | "multipart/form-data" | "application/json" | "text/plain";
195type JsonObject = {
196 [Key in string]: JsonValue;
197} & {
198 [Key in string]?: JsonValue | undefined;
199};
200type JsonArray = JsonValue[] | readonly JsonValue[];
201type JsonPrimitive = string | number | boolean | null;
202type JsonValue = JsonPrimitive | JsonObject | JsonArray;
203/**
204 * @private
205 * Internal interface to pass around for action submissions, not intended for
206 * external consumption
207 */
208type Submission = {
209 formMethod: FormMethod;
210 formAction: string;
211 formEncType: FormEncType;
212 formData: FormData;
213 json: undefined;
214 text: undefined;
215} | {
216 formMethod: FormMethod;
217 formAction: string;
218 formEncType: FormEncType;
219 formData: undefined;
220 json: JsonValue;
221 text: undefined;
222} | {
223 formMethod: FormMethod;
224 formAction: string;
225 formEncType: FormEncType;
226 formData: undefined;
227 json: undefined;
228 text: string;
229};
230/**
231 * A context instance used as the key for the `get`/`set` methods of a
232 * {@link RouterContextProvider}. Accepts an optional default
233 * value to be returned if no value has been set.
234 */
235interface RouterContext<T = unknown> {
236 defaultValue?: T;
237}
238/**
239 * Creates a type-safe {@link RouterContext} object that can be used to
240 * store and retrieve arbitrary values in [`action`](../../start/framework/route-module#action)s,
241 * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
242 * Similar to React's [`createContext`](https://react.dev/reference/react/createContext),
243 * but specifically designed for React Router's request/response lifecycle.
244 *
245 * If a `defaultValue` is provided, it will be returned from `context.get()`
246 * when no value has been set for the context. Otherwise, reading this context
247 * when no value has been set will throw an error.
248 *
249 * ```tsx filename=app/context.ts
250 * import { createContext } from "react-router";
251 *
252 * // Create a context for user data
253 * export const userContext =
254 * createContext<User | null>(null);
255 * ```
256 *
257 * ```tsx filename=app/middleware/auth.ts
258 * import { getUserFromSession } from "~/auth.server";
259 * import { userContext } from "~/context";
260 *
261 * export const authMiddleware = async ({
262 * context,
263 * request,
264 * }) => {
265 * const user = await getUserFromSession(request);
266 * context.set(userContext, user);
267 * };
268 * ```
269 *
270 * ```tsx filename=app/routes/profile.tsx
271 * import { userContext } from "~/context";
272 *
273 * export async function loader({
274 * context,
275 * }: Route.LoaderArgs) {
276 * const user = context.get(userContext);
277 *
278 * if (!user) {
279 * throw new Response("Unauthorized", { status: 401 });
280 * }
281 *
282 * return { user };
283 * }
284 * ```
285 *
286 * @public
287 * @category Utils
288 * @mode framework
289 * @mode data
290 * @param defaultValue An optional default value for the context. This value
291 * will be returned if no value has been set for this context.
292 * @returns A {@link RouterContext} object that can be used with
293 * `context.get()` and `context.set()` in [`action`](../../start/framework/route-module#action)s,
294 * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
295 */
296declare function createContext<T>(defaultValue?: T): RouterContext<T>;
297/**
298 * Provides methods for writing/reading values in application context in a
299 * type-safe way. Primarily for usage with [middleware](../../how-to/middleware).
300 *
301 * @example
302 * import {
303 * createContext,
304 * RouterContextProvider
305 * } from "react-router";
306 *
307 * const userContext = createContext<User | null>(null);
308 * const contextProvider = new RouterContextProvider();
309 * contextProvider.set(userContext, getUser());
310 * // ^ Type-safe
311 * const user = contextProvider.get(userContext);
312 * // ^ User
313 *
314 * @public
315 * @category Utils
316 * @mode framework
317 * @mode data
318 */
319declare class RouterContextProvider {
320 #private;
321 /**
322 * Create a new `RouterContextProvider` instance
323 * @param init An optional initial context map to populate the provider with
324 */
325 constructor(init?: Map<RouterContext, unknown>);
326 /**
327 * Access a value from the context. If no value has been set for the context,
328 * it will return the context's `defaultValue` if provided, or throw an error
329 * if no `defaultValue` was set.
330 * @param context The context to get the value for
331 * @returns The value for the context, or the context's `defaultValue` if no
332 * value was set
333 */
334 get<T>(context: RouterContext<T>): T;
335 /**
336 * Set a value for the context. If the context already has a value set, this
337 * will overwrite it.
338 *
339 * @param context The context to set the value for
340 * @param value The value to set for the context
341 * @returns {void}
342 */
343 set<C extends RouterContext>(context: C, value: C extends RouterContext<infer T> ? T : never): void;
344}
345type DefaultContext = MiddlewareEnabled extends true ? Readonly<RouterContextProvider> : any;
346/**
347 * @private
348 * Arguments passed to route loader/action functions. Same for now but we keep
349 * this as a private implementation detail in case they diverge in the future.
350 */
351interface DataFunctionArgs<Context> {
352 /** 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. */
353 request: Request;
354 /**
355 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
356 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
357 */
358 unstable_pattern: string;
359 /**
360 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
361 * @example
362 * // app/routes.ts
363 * route("teams/:teamId", "./team.tsx"),
364 *
365 * // app/team.tsx
366 * export function loader({
367 * params,
368 * }: Route.LoaderArgs) {
369 * params.teamId;
370 * // ^ string
371 * }
372 */
373 params: Params;
374 /**
375 * This is the context passed in to your server adapter's getLoadContext() function.
376 * It's a way to bridge the gap between the adapter's request/response API with your React Router app.
377 * It is only applicable if you are using a custom server adapter.
378 */
379 context: Context;
380}
381/**
382 * Route middleware `next` function to call downstream handlers and then complete
383 * middlewares from the bottom-up
384 */
385interface MiddlewareNextFunction<Result = unknown> {
386 (): Promise<Result>;
387}
388/**
389 * Route middleware function signature. Receives the same "data" arguments as a
390 * `loader`/`action` (`request`, `params`, `context`) as the first parameter and
391 * a `next` function as the second parameter which will call downstream handlers
392 * and then complete middlewares from the bottom-up
393 */
394type MiddlewareFunction<Result = unknown> = (args: DataFunctionArgs<Readonly<RouterContextProvider>>, next: MiddlewareNextFunction<Result>) => MaybePromise<Result | void>;
395/**
396 * Arguments passed to loader functions
397 */
398interface LoaderFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
399}
400/**
401 * Arguments passed to action functions
402 */
403interface ActionFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
404}
405/**
406 * Loaders and actions can return anything
407 */
408type DataFunctionValue = unknown;
409type DataFunctionReturnValue = MaybePromise<DataFunctionValue>;
410/**
411 * Route loader function signature
412 */
413type LoaderFunction<Context = DefaultContext> = {
414 (args: LoaderFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
415} & {
416 hydrate?: boolean;
417};
418/**
419 * Route action function signature
420 */
421interface ActionFunction<Context = DefaultContext> {
422 (args: ActionFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
423}
424/**
425 * Arguments passed to shouldRevalidate function
426 */
427interface ShouldRevalidateFunctionArgs {
428 /** 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. */
429 currentUrl: URL;
430 /** 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. */
431 currentParams: AgnosticDataRouteMatch["params"];
432 /** 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. */
433 nextUrl: URL;
434 /** 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. */
435 nextParams: AgnosticDataRouteMatch["params"];
436 /** The method (probably `"GET"` or `"POST"`) used in the form submission that triggered the revalidation. */
437 formMethod?: Submission["formMethod"];
438 /** The form action (`<Form action="/somewhere">`) that triggered the revalidation. */
439 formAction?: Submission["formAction"];
440 /** The form encType (`<Form encType="application/x-www-form-urlencoded">) used in the form submission that triggered the revalidation*/
441 formEncType?: Submission["formEncType"];
442 /** The form submission data when the form's encType is `text/plain` */
443 text?: Submission["text"];
444 /** The form submission data when the form's encType is `application/x-www-form-urlencoded` or `multipart/form-data` */
445 formData?: Submission["formData"];
446 /** The form submission data when the form's encType is `application/json` */
447 json?: Submission["json"];
448 /** The status code of the action response */
449 actionStatus?: number;
450 /**
451 * 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.
452 *
453 * @example
454 * export async function action() {
455 * await saveSomeStuff();
456 * return { ok: true };
457 * }
458 *
459 * export function shouldRevalidate({
460 * actionResult,
461 * }) {
462 * if (actionResult?.ok) {
463 * return false;
464 * }
465 * return true;
466 * }
467 */
468 actionResult?: any;
469 /**
470 * 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:
471 *
472 * /projects/123/tasks/abc
473 * /projects/123/tasks/def
474 * React Router will only call the loader for tasks/def because the param for projects/123 didn't change.
475 *
476 * 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.
477 */
478 defaultShouldRevalidate: boolean;
479}
480/**
481 * Route shouldRevalidate function signature. This runs after any submission
482 * (navigation or fetcher), so we flatten the navigation/fetcher submission
483 * onto the arguments. It shouldn't matter whether it came from a navigation
484 * or a fetcher, what really matters is the URLs and the formData since loaders
485 * have to re-run based on the data models that were potentially mutated.
486 */
487interface ShouldRevalidateFunction {
488 (args: ShouldRevalidateFunctionArgs): boolean;
489}
490interface DataStrategyMatch extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {
491 /**
492 * @private
493 */
494 _lazyPromises?: {
495 middleware: Promise<void> | undefined;
496 handler: Promise<void> | undefined;
497 route: Promise<void> | undefined;
498 };
499 /**
500 * @deprecated Deprecated in favor of `shouldCallHandler`
501 *
502 * A boolean value indicating whether this route handler should be called in
503 * this pass.
504 *
505 * The `matches` array always includes _all_ matched routes even when only
506 * _some_ route handlers need to be called so that things like middleware can
507 * be implemented.
508 *
509 * `shouldLoad` is usually only interesting if you are skipping the route
510 * handler entirely and implementing custom handler logic - since it lets you
511 * determine if that custom logic should run for this route or not.
512 *
513 * For example:
514 * - If you are on `/parent/child/a` and you navigate to `/parent/child/b` -
515 * you'll get an array of three matches (`[parent, child, b]`), but only `b`
516 * will have `shouldLoad=true` because the data for `parent` and `child` is
517 * already loaded
518 * - If you are on `/parent/child/a` and you submit to `a`'s [`action`](https://reactrouter.com/docs/start/data/route-object#action),
519 * then only `a` will have `shouldLoad=true` for the action execution of
520 * `dataStrategy`
521 * - After the [`action`](https://reactrouter.com/docs/start/data/route-object#action),
522 * `dataStrategy` will be called again for the [`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
523 * revalidation, and all matches will have `shouldLoad=true` (assuming no
524 * custom `shouldRevalidate` implementations)
525 */
526 shouldLoad: boolean;
527 /**
528 * Arguments passed to the `shouldRevalidate` function for this `loader` execution.
529 * Will be `null` if this is not a revalidating loader {@link DataStrategyMatch}.
530 */
531 shouldRevalidateArgs: ShouldRevalidateFunctionArgs | null;
532 /**
533 * Determine if this route's handler should be called during this `dataStrategy`
534 * execution. Calling it with no arguments will leverage the default revalidation
535 * behavior. You can pass your own `defaultShouldRevalidate` value if you wish
536 * to change the default revalidation behavior with your `dataStrategy`.
537 *
538 * @param defaultShouldRevalidate `defaultShouldRevalidate` override value (optional)
539 */
540 shouldCallHandler(defaultShouldRevalidate?: boolean): boolean;
541 /**
542 * An async function that will resolve any `route.lazy` implementations and
543 * execute the route's handler (if necessary), returning a {@link DataStrategyResult}
544 *
545 * - Calling `match.resolve` does not mean you're calling the
546 * [`action`](https://reactrouter.com/docs/start/data/route-object#action)/[`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
547 * (the "handler") - `resolve` will only call the `handler` internally if
548 * needed _and_ if you don't pass your own `handlerOverride` function parameter
549 * - It is safe to call `match.resolve` for all matches, even if they have
550 * `shouldLoad=false`, and it will no-op if no loading is required
551 * - You should generally always call `match.resolve()` for `shouldLoad:true`
552 * routes to ensure that any `route.lazy` implementations are processed
553 * - See the examples below for how to implement custom handler execution via
554 * `match.resolve`
555 */
556 resolve: (handlerOverride?: (handler: (ctx?: unknown) => DataFunctionReturnValue) => DataFunctionReturnValue) => Promise<DataStrategyResult>;
557}
558interface DataStrategyFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
559 /**
560 * Matches for this route extended with Data strategy APIs
561 */
562 matches: DataStrategyMatch[];
563 runClientMiddleware: (cb: DataStrategyFunction<Context>) => Promise<Record<string, DataStrategyResult>>;
564 /**
565 * The key of the fetcher we are calling `dataStrategy` for, otherwise `null`
566 * for navigational executions
567 */
568 fetcherKey: string | null;
569}
570/**
571 * Result from a loader or action called via dataStrategy
572 */
573interface DataStrategyResult {
574 type: "data" | "error";
575 result: unknown;
576}
577interface DataStrategyFunction<Context = DefaultContext> {
578 (args: DataStrategyFunctionArgs<Context>): Promise<Record<string, DataStrategyResult>>;
579}
580type AgnosticPatchRoutesOnNavigationFunctionArgs<O extends AgnosticRouteObject = AgnosticRouteObject, M extends AgnosticRouteMatch = AgnosticRouteMatch> = {
581 signal: AbortSignal;
582 path: string;
583 matches: M[];
584 fetcherKey: string | undefined;
585 patch: (routeId: string | null, children: O[]) => void;
586};
587type AgnosticPatchRoutesOnNavigationFunction<O extends AgnosticRouteObject = AgnosticRouteObject, M extends AgnosticRouteMatch = AgnosticRouteMatch> = (opts: AgnosticPatchRoutesOnNavigationFunctionArgs<O, M>) => MaybePromise<void>;
588/**
589 * Function provided by the framework-aware layers to set any framework-specific
590 * properties from framework-agnostic properties
591 */
592interface MapRoutePropertiesFunction {
593 (route: AgnosticDataRouteObject): {
594 hasErrorBoundary: boolean;
595 } & Record<string, any>;
596}
597/**
598 * Keys we cannot change from within a lazy object. We spread all other keys
599 * onto the route. Either they're meaningful to the router, or they'll get
600 * ignored.
601 */
602type UnsupportedLazyRouteObjectKey = "lazy" | "caseSensitive" | "path" | "id" | "index" | "children";
603/**
604 * Keys we cannot change from within a lazy() function. We spread all other keys
605 * onto the route. Either they're meaningful to the router, or they'll get
606 * ignored.
607 */
608type UnsupportedLazyRouteFunctionKey = UnsupportedLazyRouteObjectKey | "middleware";
609/**
610 * lazy object to load route properties, which can add non-matching
611 * related properties to a route
612 */
613type LazyRouteObject<R extends AgnosticRouteObject> = {
614 [K in keyof R as K extends UnsupportedLazyRouteObjectKey ? never : K]?: () => Promise<R[K] | null | undefined>;
615};
616/**
617 * lazy() function to load a route definition, which can add non-matching
618 * related properties to a route
619 */
620interface LazyRouteFunction<R extends AgnosticRouteObject> {
621 (): Promise<Omit<R, UnsupportedLazyRouteFunctionKey> & Partial<Record<UnsupportedLazyRouteFunctionKey, never>>>;
622}
623type LazyRouteDefinition<R extends AgnosticRouteObject> = LazyRouteObject<R> | LazyRouteFunction<R>;
624/**
625 * Base RouteObject with common props shared by all types of routes
626 */
627type AgnosticBaseRouteObject = {
628 caseSensitive?: boolean;
629 path?: string;
630 id?: string;
631 middleware?: MiddlewareFunction[];
632 loader?: LoaderFunction | boolean;
633 action?: ActionFunction | boolean;
634 hasErrorBoundary?: boolean;
635 shouldRevalidate?: ShouldRevalidateFunction;
636 handle?: any;
637 lazy?: LazyRouteDefinition<AgnosticBaseRouteObject>;
638};
639/**
640 * Index routes must not have children
641 */
642type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {
643 children?: undefined;
644 index: true;
645};
646/**
647 * Non-index routes may have children, but cannot have index
648 */
649type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {
650 children?: AgnosticRouteObject[];
651 index?: false;
652};
653/**
654 * A route object represents a logical route, with (optionally) its child
655 * routes organized in a tree-like structure.
656 */
657type AgnosticRouteObject = AgnosticIndexRouteObject | AgnosticNonIndexRouteObject;
658type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {
659 id: string;
660};
661type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {
662 children?: AgnosticDataRouteObject[];
663 id: string;
664};
665/**
666 * A data route object, which is just a RouteObject with a required unique ID
667 */
668type AgnosticDataRouteObject = AgnosticDataIndexRouteObject | AgnosticDataNonIndexRouteObject;
669/**
670 * The parameters that were parsed from the URL path.
671 */
672type Params<Key extends string = string> = {
673 readonly [key in Key]: string | undefined;
674};
675/**
676 * A RouteMatch contains info about how a route matched a URL.
677 */
678interface AgnosticRouteMatch<ParamKey extends string = string, RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject> {
679 /**
680 * The names and values of dynamic parameters in the URL.
681 */
682 params: Params<ParamKey>;
683 /**
684 * The portion of the URL pathname that was matched.
685 */
686 pathname: string;
687 /**
688 * The portion of the URL pathname that was matched before child routes.
689 */
690 pathnameBase: string;
691 /**
692 * The route object that was used to match.
693 */
694 route: RouteObjectType;
695}
696interface AgnosticDataRouteMatch extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {
697}
698/**
699 * Matches the given routes to a location and returns the match data.
700 *
701 * @example
702 * import { matchRoutes } from "react-router";
703 *
704 * let routes = [{
705 * path: "/",
706 * Component: Root,
707 * children: [{
708 * path: "dashboard",
709 * Component: Dashboard,
710 * }]
711 * }];
712 *
713 * matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
714 *
715 * @public
716 * @category Utils
717 * @param routes The array of route objects to match against.
718 * @param locationArg The location to match against, either a string path or a
719 * partial {@link Location} object
720 * @param basename Optional base path to strip from the location before matching.
721 * Defaults to `/`.
722 * @returns An array of matched routes, or `null` if no matches were found.
723 */
724declare function matchRoutes<RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject>(routes: RouteObjectType[], locationArg: Partial<Location> | string, basename?: string): AgnosticRouteMatch<string, RouteObjectType>[] | null;
725interface UIMatch<Data = unknown, Handle = unknown> {
726 id: string;
727 pathname: string;
728 /**
729 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the matched route.
730 */
731 params: AgnosticRouteMatch["params"];
732 /**
733 * The return value from the matched route's loader or clientLoader. This might
734 * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
735 * an error and we're currently displaying an `ErrorBoundary`.
736 *
737 * @deprecated Use `UIMatch.loaderData` instead
738 */
739 data: Data | undefined;
740 /**
741 * The return value from the matched route's loader or clientLoader. This might
742 * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
743 * an error and we're currently displaying an `ErrorBoundary`.
744 */
745 loaderData: Data | undefined;
746 /**
747 * The {@link https://reactrouter.com/start/framework/route-module#handle handle object}
748 * exported from the matched route module
749 */
750 handle: Handle;
751}
752declare class DataWithResponseInit<D> {
753 type: string;
754 data: D;
755 init: ResponseInit | null;
756 constructor(data: D, init?: ResponseInit);
757}
758/**
759 * Create "responses" that contain `headers`/`status` without forcing
760 * serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
761 *
762 * @example
763 * import { data } from "react-router";
764 *
765 * export async function action({ request }: Route.ActionArgs) {
766 * let formData = await request.formData();
767 * let item = await createItem(formData);
768 * return data(item, {
769 * headers: { "X-Custom-Header": "value" }
770 * status: 201,
771 * });
772 * }
773 *
774 * @public
775 * @category Utils
776 * @mode framework
777 * @mode data
778 * @param data The data to be included in the response.
779 * @param init The status code or a `ResponseInit` object to be included in the
780 * response.
781 * @returns A {@link DataWithResponseInit} instance containing the data and
782 * response init.
783 */
784declare function data<D>(data: D, init?: number | ResponseInit): DataWithResponseInit<D>;
785type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
786/**
787 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
788 * Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
789 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
790 *
791 * @example
792 * import { redirect } from "react-router";
793 *
794 * export async function loader({ request }: Route.LoaderArgs) {
795 * if (!isLoggedIn(request))
796 * throw redirect("/login");
797 * }
798 *
799 * // ...
800 * }
801 *
802 * @public
803 * @category Utils
804 * @mode framework
805 * @mode data
806 * @param url The URL to redirect to.
807 * @param init The status code or a `ResponseInit` object to be included in the
808 * response.
809 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
810 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
811 * header.
812 */
813declare const redirect$1: RedirectFunction;
814/**
815 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
816 * that will force a document reload to the new location. Sets the status code
817 * and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
818 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
819 *
820 * ```tsx filename=routes/logout.tsx
821 * import { redirectDocument } from "react-router";
822 *
823 * import { destroySession } from "../sessions.server";
824 *
825 * export async function action({ request }: Route.ActionArgs) {
826 * let session = await getSession(request.headers.get("Cookie"));
827 * return redirectDocument("/", {
828 * headers: { "Set-Cookie": await destroySession(session) }
829 * });
830 * }
831 * ```
832 *
833 * @public
834 * @category Utils
835 * @mode framework
836 * @mode data
837 * @param url The URL to redirect to.
838 * @param init The status code or a `ResponseInit` object to be included in the
839 * response.
840 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
841 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
842 * header.
843 */
844declare const redirectDocument$1: RedirectFunction;
845/**
846 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
847 * that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
848 * instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
849 * for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
850 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
851 *
852 * @example
853 * import { replace } from "react-router";
854 *
855 * export async function loader() {
856 * return replace("/new-location");
857 * }
858 *
859 * @public
860 * @category Utils
861 * @mode framework
862 * @mode data
863 * @param url The URL to redirect to.
864 * @param init The status code or a `ResponseInit` object to be included in the
865 * response.
866 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
867 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
868 * header.
869 */
870declare const replace$1: RedirectFunction;
871type ErrorResponse = {
872 status: number;
873 statusText: string;
874 data: any;
875};
876/**
877 * Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
878 * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
879 * thrown from an [`action`](../../start/framework/route-module#action) or
880 * [`loader`](../../start/framework/route-module#loader) function.
881 *
882 * @example
883 * import { isRouteErrorResponse } from "react-router";
884 *
885 * export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
886 * if (isRouteErrorResponse(error)) {
887 * return (
888 * <>
889 * <p>Error: `${error.status}: ${error.statusText}`</p>
890 * <p>{error.data}</p>
891 * </>
892 * );
893 * }
894 *
895 * return (
896 * <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
897 * );
898 * }
899 *
900 * @public
901 * @category Utils
902 * @mode framework
903 * @mode data
904 * @param error The error to check.
905 * @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
906 */
907declare function isRouteErrorResponse(error: any): error is ErrorResponse;
908
909/**
910 * An object of unknown type for route loaders and actions provided by the
911 * server's `getLoadContext()` function. This is defined as an empty interface
912 * specifically so apps can leverage declaration merging to augment this type
913 * globally: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
914 */
915interface AppLoadContext {
916 [key: string]: unknown;
917}
918
919type unstable_ServerInstrumentation = {
920 handler?: unstable_InstrumentRequestHandlerFunction;
921 route?: unstable_InstrumentRouteFunction;
922};
923type unstable_ClientInstrumentation = {
924 router?: unstable_InstrumentRouterFunction;
925 route?: unstable_InstrumentRouteFunction;
926};
927type unstable_InstrumentRequestHandlerFunction = (handler: InstrumentableRequestHandler) => void;
928type unstable_InstrumentRouterFunction = (router: InstrumentableRouter) => void;
929type unstable_InstrumentRouteFunction = (route: InstrumentableRoute) => void;
930type unstable_InstrumentationHandlerResult = {
931 status: "success";
932 error: undefined;
933} | {
934 status: "error";
935 error: Error;
936};
937type InstrumentFunction<T> = (handler: () => Promise<unstable_InstrumentationHandlerResult>, info: T) => Promise<void>;
938type ReadonlyRequest = {
939 method: string;
940 url: string;
941 headers: Pick<Headers, "get">;
942};
943type ReadonlyContext = MiddlewareEnabled extends true ? Pick<RouterContextProvider, "get"> : Readonly<AppLoadContext>;
944type InstrumentableRoute = {
945 id: string;
946 index: boolean | undefined;
947 path: string | undefined;
948 instrument(instrumentations: RouteInstrumentations): void;
949};
950type RouteInstrumentations = {
951 lazy?: InstrumentFunction<RouteLazyInstrumentationInfo>;
952 "lazy.loader"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
953 "lazy.action"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
954 "lazy.middleware"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
955 middleware?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
956 loader?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
957 action?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
958};
959type RouteLazyInstrumentationInfo = undefined;
960type RouteHandlerInstrumentationInfo = Readonly<{
961 request: ReadonlyRequest;
962 params: LoaderFunctionArgs["params"];
963 unstable_pattern: string;
964 context: ReadonlyContext;
965}>;
966type InstrumentableRouter = {
967 instrument(instrumentations: RouterInstrumentations): void;
968};
969type RouterInstrumentations = {
970 navigate?: InstrumentFunction<RouterNavigationInstrumentationInfo>;
971 fetch?: InstrumentFunction<RouterFetchInstrumentationInfo>;
972};
973type RouterNavigationInstrumentationInfo = Readonly<{
974 to: string | number;
975 currentUrl: string;
976 formMethod?: HTMLFormMethod;
977 formEncType?: FormEncType;
978 formData?: FormData;
979 body?: any;
980}>;
981type RouterFetchInstrumentationInfo = Readonly<{
982 href: string;
983 currentUrl: string;
984 fetcherKey: string;
985 formMethod?: HTMLFormMethod;
986 formEncType?: FormEncType;
987 formData?: FormData;
988 body?: any;
989}>;
990type InstrumentableRequestHandler = {
991 instrument(instrumentations: RequestHandlerInstrumentations): void;
992};
993type RequestHandlerInstrumentations = {
994 request?: InstrumentFunction<RequestHandlerInstrumentationInfo>;
995};
996type RequestHandlerInstrumentationInfo = Readonly<{
997 request: ReadonlyRequest;
998 context: ReadonlyContext | undefined;
999}>;
1000
1001/**
1002 * A Router instance manages all navigation and data loading/mutations
1003 */
1004interface Router {
1005 /**
1006 * @private
1007 * PRIVATE - DO NOT USE
1008 *
1009 * Return the basename for the router
1010 */
1011 get basename(): RouterInit["basename"];
1012 /**
1013 * @private
1014 * PRIVATE - DO NOT USE
1015 *
1016 * Return the future config for the router
1017 */
1018 get future(): FutureConfig;
1019 /**
1020 * @private
1021 * PRIVATE - DO NOT USE
1022 *
1023 * Return the current state of the router
1024 */
1025 get state(): RouterState;
1026 /**
1027 * @private
1028 * PRIVATE - DO NOT USE
1029 *
1030 * Return the routes for this router instance
1031 */
1032 get routes(): AgnosticDataRouteObject[];
1033 /**
1034 * @private
1035 * PRIVATE - DO NOT USE
1036 *
1037 * Return the window associated with the router
1038 */
1039 get window(): RouterInit["window"];
1040 /**
1041 * @private
1042 * PRIVATE - DO NOT USE
1043 *
1044 * Initialize the router, including adding history listeners and kicking off
1045 * initial data fetches. Returns a function to cleanup listeners and abort
1046 * any in-progress loads
1047 */
1048 initialize(): Router;
1049 /**
1050 * @private
1051 * PRIVATE - DO NOT USE
1052 *
1053 * Subscribe to router.state updates
1054 *
1055 * @param fn function to call with the new state
1056 */
1057 subscribe(fn: RouterSubscriber): () => void;
1058 /**
1059 * @private
1060 * PRIVATE - DO NOT USE
1061 *
1062 * Enable scroll restoration behavior in the router
1063 *
1064 * @param savedScrollPositions Object that will manage positions, in case
1065 * it's being restored from sessionStorage
1066 * @param getScrollPosition Function to get the active Y scroll position
1067 * @param getKey Function to get the key to use for restoration
1068 */
1069 enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;
1070 /**
1071 * @private
1072 * PRIVATE - DO NOT USE
1073 *
1074 * Navigate forward/backward in the history stack
1075 * @param to Delta to move in the history stack
1076 */
1077 navigate(to: number): Promise<void>;
1078 /**
1079 * Navigate to the given path
1080 * @param to Path to navigate to
1081 * @param opts Navigation options (method, submission, etc.)
1082 */
1083 navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;
1084 /**
1085 * @private
1086 * PRIVATE - DO NOT USE
1087 *
1088 * Trigger a fetcher load/submission
1089 *
1090 * @param key Fetcher key
1091 * @param routeId Route that owns the fetcher
1092 * @param href href to fetch
1093 * @param opts Fetcher options, (method, submission, etc.)
1094 */
1095 fetch(key: string, routeId: string, href: string | null, opts?: RouterFetchOptions): Promise<void>;
1096 /**
1097 * @private
1098 * PRIVATE - DO NOT USE
1099 *
1100 * Trigger a revalidation of all current route loaders and fetcher loads
1101 */
1102 revalidate(): Promise<void>;
1103 /**
1104 * @private
1105 * PRIVATE - DO NOT USE
1106 *
1107 * Utility function to create an href for the given location
1108 * @param location
1109 */
1110 createHref(location: Location | URL): string;
1111 /**
1112 * @private
1113 * PRIVATE - DO NOT USE
1114 *
1115 * Utility function to URL encode a destination path according to the internal
1116 * history implementation
1117 * @param to
1118 */
1119 encodeLocation(to: To): Path;
1120 /**
1121 * @private
1122 * PRIVATE - DO NOT USE
1123 *
1124 * Get/create a fetcher for the given key
1125 * @param key
1126 */
1127 getFetcher<TData = any>(key: string): Fetcher<TData>;
1128 /**
1129 * @internal
1130 * PRIVATE - DO NOT USE
1131 *
1132 * Reset the fetcher for a given key
1133 * @param key
1134 */
1135 resetFetcher(key: string, opts?: {
1136 reason?: unknown;
1137 }): void;
1138 /**
1139 * @private
1140 * PRIVATE - DO NOT USE
1141 *
1142 * Delete the fetcher for a given key
1143 * @param key
1144 */
1145 deleteFetcher(key: string): void;
1146 /**
1147 * @private
1148 * PRIVATE - DO NOT USE
1149 *
1150 * Cleanup listeners and abort any in-progress loads
1151 */
1152 dispose(): void;
1153 /**
1154 * @private
1155 * PRIVATE - DO NOT USE
1156 *
1157 * Get a navigation blocker
1158 * @param key The identifier for the blocker
1159 * @param fn The blocker function implementation
1160 */
1161 getBlocker(key: string, fn: BlockerFunction): Blocker;
1162 /**
1163 * @private
1164 * PRIVATE - DO NOT USE
1165 *
1166 * Delete a navigation blocker
1167 * @param key The identifier for the blocker
1168 */
1169 deleteBlocker(key: string): void;
1170 /**
1171 * @private
1172 * PRIVATE DO NOT USE
1173 *
1174 * Patch additional children routes into an existing parent route
1175 * @param routeId The parent route id or a callback function accepting `patch`
1176 * to perform batch patching
1177 * @param children The additional children routes
1178 * @param unstable_allowElementMutations Allow mutation or route elements on
1179 * existing routes. Intended for RSC-usage
1180 * only.
1181 */
1182 patchRoutes(routeId: string | null, children: AgnosticRouteObject[], unstable_allowElementMutations?: boolean): void;
1183 /**
1184 * @private
1185 * PRIVATE - DO NOT USE
1186 *
1187 * HMR needs to pass in-flight route updates to React Router
1188 * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)
1189 */
1190 _internalSetRoutes(routes: AgnosticRouteObject[]): void;
1191 /**
1192 * @private
1193 * PRIVATE - DO NOT USE
1194 *
1195 * Cause subscribers to re-render. This is used to force a re-render.
1196 */
1197 _internalSetStateDoNotUseOrYouWillBreakYourApp(state: Partial<RouterState>): void;
1198 /**
1199 * @private
1200 * PRIVATE - DO NOT USE
1201 *
1202 * Internal fetch AbortControllers accessed by unit tests
1203 */
1204 _internalFetchControllers: Map<string, AbortController>;
1205}
1206/**
1207 * State maintained internally by the router. During a navigation, all states
1208 * reflect the "old" location unless otherwise noted.
1209 */
1210interface RouterState {
1211 /**
1212 * The action of the most recent navigation
1213 */
1214 historyAction: Action;
1215 /**
1216 * The current location reflected by the router
1217 */
1218 location: Location;
1219 /**
1220 * The current set of route matches
1221 */
1222 matches: AgnosticDataRouteMatch[];
1223 /**
1224 * Tracks whether we've completed our initial data load
1225 */
1226 initialized: boolean;
1227 /**
1228 * Current scroll position we should start at for a new view
1229 * - number -> scroll position to restore to
1230 * - false -> do not restore scroll at all (used during submissions/revalidations)
1231 * - null -> don't have a saved position, scroll to hash or top of page
1232 */
1233 restoreScrollPosition: number | false | null;
1234 /**
1235 * Indicate whether this navigation should skip resetting the scroll position
1236 * if we are unable to restore the scroll position
1237 */
1238 preventScrollReset: boolean;
1239 /**
1240 * Tracks the state of the current navigation
1241 */
1242 navigation: Navigation;
1243 /**
1244 * Tracks any in-progress revalidations
1245 */
1246 revalidation: RevalidationState;
1247 /**
1248 * Data from the loaders for the current matches
1249 */
1250 loaderData: RouteData;
1251 /**
1252 * Data from the action for the current matches
1253 */
1254 actionData: RouteData | null;
1255 /**
1256 * Errors caught from loaders for the current matches
1257 */
1258 errors: RouteData | null;
1259 /**
1260 * Map of current fetchers
1261 */
1262 fetchers: Map<string, Fetcher>;
1263 /**
1264 * Map of current blockers
1265 */
1266 blockers: Map<string, Blocker>;
1267}
1268/**
1269 * Data that can be passed into hydrate a Router from SSR
1270 */
1271type HydrationState = Partial<Pick<RouterState, "loaderData" | "actionData" | "errors">>;
1272/**
1273 * Future flags to toggle new feature behavior
1274 */
1275interface FutureConfig {
1276}
1277/**
1278 * Initialization options for createRouter
1279 */
1280interface RouterInit {
1281 routes: AgnosticRouteObject[];
1282 history: History;
1283 basename?: string;
1284 getContext?: () => MaybePromise<RouterContextProvider>;
1285 unstable_instrumentations?: unstable_ClientInstrumentation[];
1286 mapRouteProperties?: MapRoutePropertiesFunction;
1287 future?: Partial<FutureConfig>;
1288 hydrationRouteProperties?: string[];
1289 hydrationData?: HydrationState;
1290 window?: Window;
1291 dataStrategy?: DataStrategyFunction;
1292 patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;
1293}
1294/**
1295 * State returned from a server-side query() call
1296 */
1297interface StaticHandlerContext {
1298 basename: Router["basename"];
1299 location: RouterState["location"];
1300 matches: RouterState["matches"];
1301 loaderData: RouterState["loaderData"];
1302 actionData: RouterState["actionData"];
1303 errors: RouterState["errors"];
1304 statusCode: number;
1305 loaderHeaders: Record<string, Headers>;
1306 actionHeaders: Record<string, Headers>;
1307 _deepestRenderedBoundaryId?: string | null;
1308}
1309/**
1310 * A StaticHandler instance manages a singular SSR navigation/fetch event
1311 */
1312interface StaticHandler {
1313 dataRoutes: AgnosticDataRouteObject[];
1314 query(request: Request, opts?: {
1315 requestContext?: unknown;
1316 filterMatchesToLoad?: (match: AgnosticDataRouteMatch) => boolean;
1317 skipLoaderErrorBubbling?: boolean;
1318 skipRevalidation?: boolean;
1319 dataStrategy?: DataStrategyFunction<unknown>;
1320 generateMiddlewareResponse?: (query: (r: Request, args?: {
1321 filterMatchesToLoad?: (match: AgnosticDataRouteMatch) => boolean;
1322 }) => Promise<StaticHandlerContext | Response>) => MaybePromise<Response>;
1323 }): Promise<StaticHandlerContext | Response>;
1324 queryRoute(request: Request, opts?: {
1325 routeId?: string;
1326 requestContext?: unknown;
1327 dataStrategy?: DataStrategyFunction<unknown>;
1328 generateMiddlewareResponse?: (queryRoute: (r: Request) => Promise<Response>) => MaybePromise<Response>;
1329 }): Promise<any>;
1330}
1331type ViewTransitionOpts = {
1332 currentLocation: Location;
1333 nextLocation: Location;
1334};
1335/**
1336 * Subscriber function signature for changes to router state
1337 */
1338interface RouterSubscriber {
1339 (state: RouterState, opts: {
1340 deletedFetchers: string[];
1341 newErrors: RouteData | null;
1342 viewTransitionOpts?: ViewTransitionOpts;
1343 flushSync: boolean;
1344 }): void;
1345}
1346/**
1347 * Function signature for determining the key to be used in scroll restoration
1348 * for a given location
1349 */
1350interface GetScrollRestorationKeyFunction {
1351 (location: Location, matches: UIMatch[]): string | null;
1352}
1353/**
1354 * Function signature for determining the current scroll position
1355 */
1356interface GetScrollPositionFunction {
1357 (): number;
1358}
1359/**
1360 * - "route": relative to the route hierarchy so `..` means remove all segments
1361 * of the current route even if it has many. For example, a `route("posts/:id")`
1362 * would have both `:id` and `posts` removed from the url.
1363 * - "path": relative to the pathname so `..` means remove one segment of the
1364 * pathname. For example, a `route("posts/:id")` would have only `:id` removed
1365 * from the url.
1366 */
1367type RelativeRoutingType = "route" | "path";
1368type BaseNavigateOrFetchOptions = {
1369 preventScrollReset?: boolean;
1370 relative?: RelativeRoutingType;
1371 flushSync?: boolean;
1372};
1373type BaseNavigateOptions = BaseNavigateOrFetchOptions & {
1374 replace?: boolean;
1375 state?: any;
1376 fromRouteId?: string;
1377 viewTransition?: boolean;
1378};
1379type BaseSubmissionOptions = {
1380 formMethod?: HTMLFormMethod;
1381 formEncType?: FormEncType;
1382} & ({
1383 formData: FormData;
1384 body?: undefined;
1385} | {
1386 formData?: undefined;
1387 body: any;
1388});
1389/**
1390 * Options for a navigate() call for a normal (non-submission) navigation
1391 */
1392type LinkNavigateOptions = BaseNavigateOptions;
1393/**
1394 * Options for a navigate() call for a submission navigation
1395 */
1396type SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;
1397/**
1398 * Options to pass to navigate() for a navigation
1399 */
1400type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions;
1401/**
1402 * Options for a fetch() load
1403 */
1404type LoadFetchOptions = BaseNavigateOrFetchOptions;
1405/**
1406 * Options for a fetch() submission
1407 */
1408type SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;
1409/**
1410 * Options to pass to fetch()
1411 */
1412type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;
1413/**
1414 * Potential states for state.navigation
1415 */
1416type NavigationStates = {
1417 Idle: {
1418 state: "idle";
1419 location: undefined;
1420 formMethod: undefined;
1421 formAction: undefined;
1422 formEncType: undefined;
1423 formData: undefined;
1424 json: undefined;
1425 text: undefined;
1426 };
1427 Loading: {
1428 state: "loading";
1429 location: Location;
1430 formMethod: Submission["formMethod"] | undefined;
1431 formAction: Submission["formAction"] | undefined;
1432 formEncType: Submission["formEncType"] | undefined;
1433 formData: Submission["formData"] | undefined;
1434 json: Submission["json"] | undefined;
1435 text: Submission["text"] | undefined;
1436 };
1437 Submitting: {
1438 state: "submitting";
1439 location: Location;
1440 formMethod: Submission["formMethod"];
1441 formAction: Submission["formAction"];
1442 formEncType: Submission["formEncType"];
1443 formData: Submission["formData"];
1444 json: Submission["json"];
1445 text: Submission["text"];
1446 };
1447};
1448type Navigation = NavigationStates[keyof NavigationStates];
1449type RevalidationState = "idle" | "loading";
1450/**
1451 * Potential states for fetchers
1452 */
1453type FetcherStates<TData = any> = {
1454 /**
1455 * The fetcher is not calling a loader or action
1456 *
1457 * ```tsx
1458 * fetcher.state === "idle"
1459 * ```
1460 */
1461 Idle: {
1462 state: "idle";
1463 formMethod: undefined;
1464 formAction: undefined;
1465 formEncType: undefined;
1466 text: undefined;
1467 formData: undefined;
1468 json: undefined;
1469 /**
1470 * If the fetcher has never been called, this will be undefined.
1471 */
1472 data: TData | undefined;
1473 };
1474 /**
1475 * The fetcher is loading data from a {@link LoaderFunction | loader} from a
1476 * call to {@link FetcherWithComponents.load | `fetcher.load`}.
1477 *
1478 * ```tsx
1479 * // somewhere
1480 * <button onClick={() => fetcher.load("/some/route") }>Load</button>
1481 *
1482 * // the state will update
1483 * fetcher.state === "loading"
1484 * ```
1485 */
1486 Loading: {
1487 state: "loading";
1488 formMethod: Submission["formMethod"] | undefined;
1489 formAction: Submission["formAction"] | undefined;
1490 formEncType: Submission["formEncType"] | undefined;
1491 text: Submission["text"] | undefined;
1492 formData: Submission["formData"] | undefined;
1493 json: Submission["json"] | undefined;
1494 data: TData | undefined;
1495 };
1496 /**
1497 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`}.
1498
1499 ```tsx
1500 // somewhere
1501 <input
1502 onChange={e => {
1503 fetcher.submit(event.currentTarget.form, { method: "post" });
1504 }}
1505 />
1506
1507 // the state will update
1508 fetcher.state === "submitting"
1509
1510 // and formData will be available
1511 fetcher.formData
1512 ```
1513 */
1514 Submitting: {
1515 state: "submitting";
1516 formMethod: Submission["formMethod"];
1517 formAction: Submission["formAction"];
1518 formEncType: Submission["formEncType"];
1519 text: Submission["text"];
1520 formData: Submission["formData"];
1521 json: Submission["json"];
1522 data: TData | undefined;
1523 };
1524};
1525type Fetcher<TData = any> = FetcherStates<TData>[keyof FetcherStates<TData>];
1526interface BlockerBlocked {
1527 state: "blocked";
1528 reset: () => void;
1529 proceed: () => void;
1530 location: Location;
1531}
1532interface BlockerUnblocked {
1533 state: "unblocked";
1534 reset: undefined;
1535 proceed: undefined;
1536 location: undefined;
1537}
1538interface BlockerProceeding {
1539 state: "proceeding";
1540 reset: undefined;
1541 proceed: undefined;
1542 location: Location;
1543}
1544type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;
1545type BlockerFunction = (args: {
1546 currentLocation: Location;
1547 nextLocation: Location;
1548 historyAction: Action;
1549}) => boolean;
1550interface CreateStaticHandlerOptions {
1551 basename?: string;
1552 mapRouteProperties?: MapRoutePropertiesFunction;
1553 unstable_instrumentations?: Pick<unstable_ServerInstrumentation, "route">[];
1554 future?: {};
1555}
1556declare function createStaticHandler(routes: AgnosticRouteObject[], opts?: CreateStaticHandlerOptions): StaticHandler;
1557
1558interface AwaitResolveRenderFunction<Resolve = any> {
1559 (data: Awaited<Resolve>): React.ReactNode;
1560}
1561/**
1562 * @category Types
1563 */
1564interface AwaitProps<Resolve> {
1565 /**
1566 * When using a function, the resolved value is provided as the parameter.
1567 *
1568 * ```tsx [2]
1569 * <Await resolve={reviewsPromise}>
1570 * {(resolvedReviews) => <Reviews items={resolvedReviews} />}
1571 * </Await>
1572 * ```
1573 *
1574 * When using React elements, {@link useAsyncValue} will provide the
1575 * resolved value:
1576 *
1577 * ```tsx [2]
1578 * <Await resolve={reviewsPromise}>
1579 * <Reviews />
1580 * </Await>
1581 *
1582 * function Reviews() {
1583 * const resolvedReviews = useAsyncValue();
1584 * return <div>...</div>;
1585 * }
1586 * ```
1587 */
1588 children: React.ReactNode | AwaitResolveRenderFunction<Resolve>;
1589 /**
1590 * The error element renders instead of the `children` when the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
1591 * rejects.
1592 *
1593 * ```tsx
1594 * <Await
1595 * errorElement={<div>Oops</div>}
1596 * resolve={reviewsPromise}
1597 * >
1598 * <Reviews />
1599 * </Await>
1600 * ```
1601 *
1602 * To provide a more contextual error, you can use the {@link useAsyncError} in a
1603 * child component
1604 *
1605 * ```tsx
1606 * <Await
1607 * errorElement={<ReviewsError />}
1608 * resolve={reviewsPromise}
1609 * >
1610 * <Reviews />
1611 * </Await>
1612 *
1613 * function ReviewsError() {
1614 * const error = useAsyncError();
1615 * return <div>Error loading reviews: {error.message}</div>;
1616 * }
1617 * ```
1618 *
1619 * If you do not provide an `errorElement`, the rejected value will bubble up
1620 * to the nearest route-level [`ErrorBoundary`](../../start/framework/route-module#errorboundary)
1621 * and be accessible via the {@link useRouteError} hook.
1622 */
1623 errorElement?: React.ReactNode;
1624 /**
1625 * Takes a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
1626 * returned from a [`loader`](../../start/framework/route-module#loader) to be
1627 * resolved and rendered.
1628 *
1629 * ```tsx
1630 * import { Await, useLoaderData } from "react-router";
1631 *
1632 * export async function loader() {
1633 * let reviews = getReviews(); // not awaited
1634 * let book = await getBook();
1635 * return {
1636 * book,
1637 * reviews, // this is a promise
1638 * };
1639 * }
1640 *
1641 * export default function Book() {
1642 * const {
1643 * book,
1644 * reviews, // this is the same promise
1645 * } = useLoaderData();
1646 *
1647 * return (
1648 * <div>
1649 * <h1>{book.title}</h1>
1650 * <p>{book.description}</p>
1651 * <React.Suspense fallback={<ReviewsSkeleton />}>
1652 * <Await
1653 * // and is the promise we pass to Await
1654 * resolve={reviews}
1655 * >
1656 * <Reviews />
1657 * </Await>
1658 * </React.Suspense>
1659 * </div>
1660 * );
1661 * }
1662 * ```
1663 */
1664 resolve: Resolve;
1665}
1666/**
1667 * Used to render promise values with automatic error handling.
1668 *
1669 * **Note:** `<Await>` expects to be rendered inside a [`<React.Suspense>`](https://react.dev/reference/react/Suspense)
1670 *
1671 * @example
1672 * import { Await, useLoaderData } from "react-router";
1673 *
1674 * export async function loader() {
1675 * // not awaited
1676 * const reviews = getReviews();
1677 * // awaited (blocks the transition)
1678 * const book = await fetch("/api/book").then((res) => res.json());
1679 * return { book, reviews };
1680 * }
1681 *
1682 * function Book() {
1683 * const { book, reviews } = useLoaderData();
1684 * return (
1685 * <div>
1686 * <h1>{book.title}</h1>
1687 * <p>{book.description}</p>
1688 * <React.Suspense fallback={<ReviewsSkeleton />}>
1689 * <Await
1690 * resolve={reviews}
1691 * errorElement={
1692 * <div>Could not load reviews 😬</div>
1693 * }
1694 * children={(resolvedReviews) => (
1695 * <Reviews items={resolvedReviews} />
1696 * )}
1697 * />
1698 * </React.Suspense>
1699 * </div>
1700 * );
1701 * }
1702 *
1703 * @public
1704 * @category Components
1705 * @mode framework
1706 * @mode data
1707 * @param props Props
1708 * @param {AwaitProps.children} props.children n/a
1709 * @param {AwaitProps.errorElement} props.errorElement n/a
1710 * @param {AwaitProps.resolve} props.resolve n/a
1711 * @returns React element for the rendered awaited value
1712 */
1713declare function Await$1<Resolve>({ children, errorElement, resolve, }: AwaitProps<Resolve>): React.JSX.Element;
1714
1715interface IndexRouteObject {
1716 caseSensitive?: AgnosticIndexRouteObject["caseSensitive"];
1717 path?: AgnosticIndexRouteObject["path"];
1718 id?: AgnosticIndexRouteObject["id"];
1719 middleware?: AgnosticIndexRouteObject["middleware"];
1720 loader?: AgnosticIndexRouteObject["loader"];
1721 action?: AgnosticIndexRouteObject["action"];
1722 hasErrorBoundary?: AgnosticIndexRouteObject["hasErrorBoundary"];
1723 shouldRevalidate?: AgnosticIndexRouteObject["shouldRevalidate"];
1724 handle?: AgnosticIndexRouteObject["handle"];
1725 index: true;
1726 children?: undefined;
1727 element?: React.ReactNode | null;
1728 hydrateFallbackElement?: React.ReactNode | null;
1729 errorElement?: React.ReactNode | null;
1730 Component?: React.ComponentType | null;
1731 HydrateFallback?: React.ComponentType | null;
1732 ErrorBoundary?: React.ComponentType | null;
1733 lazy?: LazyRouteDefinition<RouteObject>;
1734}
1735interface NonIndexRouteObject {
1736 caseSensitive?: AgnosticNonIndexRouteObject["caseSensitive"];
1737 path?: AgnosticNonIndexRouteObject["path"];
1738 id?: AgnosticNonIndexRouteObject["id"];
1739 middleware?: AgnosticNonIndexRouteObject["middleware"];
1740 loader?: AgnosticNonIndexRouteObject["loader"];
1741 action?: AgnosticNonIndexRouteObject["action"];
1742 hasErrorBoundary?: AgnosticNonIndexRouteObject["hasErrorBoundary"];
1743 shouldRevalidate?: AgnosticNonIndexRouteObject["shouldRevalidate"];
1744 handle?: AgnosticNonIndexRouteObject["handle"];
1745 index?: false;
1746 children?: RouteObject[];
1747 element?: React.ReactNode | null;
1748 hydrateFallbackElement?: React.ReactNode | null;
1749 errorElement?: React.ReactNode | null;
1750 Component?: React.ComponentType | null;
1751 HydrateFallback?: React.ComponentType | null;
1752 ErrorBoundary?: React.ComponentType | null;
1753 lazy?: LazyRouteDefinition<RouteObject>;
1754}
1755type RouteObject = IndexRouteObject | NonIndexRouteObject;
1756type DataRouteObject = RouteObject & {
1757 children?: DataRouteObject[];
1758 id: string;
1759};
1760interface RouteMatch<ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {
1761}
1762interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {
1763}
1764
1765type Primitive = null | undefined | string | number | boolean | symbol | bigint;
1766type LiteralUnion<LiteralType, BaseType extends Primitive> = LiteralType | (BaseType & Record<never, never>);
1767interface HtmlLinkProps {
1768 /**
1769 * Address of the hyperlink
1770 */
1771 href?: string;
1772 /**
1773 * How the element handles crossorigin requests
1774 */
1775 crossOrigin?: "anonymous" | "use-credentials";
1776 /**
1777 * Relationship between the document containing the hyperlink and the destination resource
1778 */
1779 rel: LiteralUnion<"alternate" | "dns-prefetch" | "icon" | "manifest" | "modulepreload" | "next" | "pingback" | "preconnect" | "prefetch" | "preload" | "prerender" | "search" | "stylesheet", string>;
1780 /**
1781 * Applicable media: "screen", "print", "(max-width: 764px)"
1782 */
1783 media?: string;
1784 /**
1785 * Integrity metadata used in Subresource Integrity checks
1786 */
1787 integrity?: string;
1788 /**
1789 * Language of the linked resource
1790 */
1791 hrefLang?: string;
1792 /**
1793 * Hint for the type of the referenced resource
1794 */
1795 type?: string;
1796 /**
1797 * Referrer policy for fetches initiated by the element
1798 */
1799 referrerPolicy?: "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
1800 /**
1801 * Sizes of the icons (for rel="icon")
1802 */
1803 sizes?: string;
1804 /**
1805 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
1806 */
1807 as?: LiteralUnion<"audio" | "audioworklet" | "document" | "embed" | "fetch" | "font" | "frame" | "iframe" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt", string>;
1808 /**
1809 * Color to use when customizing a site's icon (for rel="mask-icon")
1810 */
1811 color?: string;
1812 /**
1813 * Whether the link is disabled
1814 */
1815 disabled?: boolean;
1816 /**
1817 * The title attribute has special semantics on this element: Title of the link; CSS style sheet set name.
1818 */
1819 title?: string;
1820 /**
1821 * Images to use in different situations, e.g., high-resolution displays,
1822 * small monitors, etc. (for rel="preload")
1823 */
1824 imageSrcSet?: string;
1825 /**
1826 * Image sizes for different page layouts (for rel="preload")
1827 */
1828 imageSizes?: string;
1829}
1830interface HtmlLinkPreloadImage extends HtmlLinkProps {
1831 /**
1832 * Relationship between the document containing the hyperlink and the destination resource
1833 */
1834 rel: "preload";
1835 /**
1836 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
1837 */
1838 as: "image";
1839 /**
1840 * Address of the hyperlink
1841 */
1842 href?: string;
1843 /**
1844 * Images to use in different situations, e.g., high-resolution displays,
1845 * small monitors, etc. (for rel="preload")
1846 */
1847 imageSrcSet: string;
1848 /**
1849 * Image sizes for different page layouts (for rel="preload")
1850 */
1851 imageSizes?: string;
1852}
1853/**
1854 * Represents a `<link>` element.
1855 *
1856 * WHATWG Specification: https://html.spec.whatwg.org/multipage/semantics.html#the-link-element
1857 */
1858type HtmlLinkDescriptor = (HtmlLinkProps & Pick<Required<HtmlLinkProps>, "href">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "imageSizes">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "href"> & {
1859 imageSizes?: never;
1860});
1861interface PageLinkDescriptor extends Omit<HtmlLinkDescriptor, "href" | "rel" | "type" | "sizes" | "imageSrcSet" | "imageSizes" | "as" | "color" | "title"> {
1862 /**
1863 * A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
1864 * attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
1865 * element
1866 */
1867 nonce?: string | undefined;
1868 /**
1869 * The absolute path of the page to prefetch, e.g. `/absolute/path`.
1870 */
1871 page: string;
1872}
1873type LinkDescriptor = HtmlLinkDescriptor | PageLinkDescriptor;
1874
1875type Serializable = undefined | null | boolean | string | symbol | number | Array<Serializable> | {
1876 [key: PropertyKey]: Serializable;
1877} | bigint | Date | URL | RegExp | Error | Map<Serializable, Serializable> | Set<Serializable> | Promise<Serializable>;
1878
1879type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
1880type IsAny<T> = 0 extends 1 & T ? true : false;
1881type Func = (...args: any[]) => unknown;
1882
1883/**
1884 * A brand that can be applied to a type to indicate that it will serialize
1885 * to a specific type when transported to the client from a loader.
1886 * Only use this if you have additional serialization/deserialization logic
1887 * in your application.
1888 */
1889type unstable_SerializesTo<T> = {
1890 unstable__ReactRouter_SerializesTo: [T];
1891};
1892
1893type 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> ? {
1894 [K in keyof T]: Serialize<T[K]>;
1895} : undefined;
1896type VoidToUndefined<T> = Equal<T, void> extends true ? undefined : T;
1897type DataFrom<T> = IsAny<T> extends true ? undefined : T extends Func ? VoidToUndefined<Awaited<ReturnType<T>>> : undefined;
1898type ClientData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? U : T;
1899type ServerData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? Serialize<U> : Serialize<T>;
1900type ServerDataFrom<T> = ServerData<DataFrom<T>>;
1901type ClientDataFrom<T> = ClientData<DataFrom<T>>;
1902type ClientDataFunctionArgs<Params> = {
1903 /**
1904 * 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.
1905 *
1906 * @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.
1907 **/
1908 request: Request;
1909 /**
1910 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
1911 * @example
1912 * // app/routes.ts
1913 * route("teams/:teamId", "./team.tsx"),
1914 *
1915 * // app/team.tsx
1916 * export function clientLoader({
1917 * params,
1918 * }: Route.ClientLoaderArgs) {
1919 * params.teamId;
1920 * // ^ string
1921 * }
1922 **/
1923 params: Params;
1924 /**
1925 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
1926 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
1927 */
1928 unstable_pattern: string;
1929 /**
1930 * When `future.v8_middleware` is not enabled, this is undefined.
1931 *
1932 * When `future.v8_middleware` is enabled, this is an instance of
1933 * `RouterContextProvider` and can be used to access context values
1934 * from your route middlewares. You may pass in initial context values in your
1935 * `<HydratedRouter getContext>` prop
1936 */
1937 context: Readonly<RouterContextProvider>;
1938};
1939type SerializeFrom<T> = T extends (...args: infer Args) => unknown ? Args extends [
1940 ClientLoaderFunctionArgs | ClientActionFunctionArgs | ClientDataFunctionArgs<unknown>
1941] ? ClientDataFrom<T> : ServerDataFrom<T> : T;
1942
1943/**
1944 * A function that handles data mutations for a route on the client
1945 */
1946type ClientActionFunction = (args: ClientActionFunctionArgs) => ReturnType<ActionFunction>;
1947/**
1948 * Arguments passed to a route `clientAction` function
1949 */
1950type ClientActionFunctionArgs = ActionFunctionArgs & {
1951 serverAction: <T = unknown>() => Promise<SerializeFrom<T>>;
1952};
1953/**
1954 * A function that loads data for a route on the client
1955 */
1956type ClientLoaderFunction = ((args: ClientLoaderFunctionArgs) => ReturnType<LoaderFunction>) & {
1957 hydrate?: boolean;
1958};
1959/**
1960 * Arguments passed to a route `clientLoader` function
1961 */
1962type ClientLoaderFunctionArgs = LoaderFunctionArgs & {
1963 serverLoader: <T = unknown>() => Promise<SerializeFrom<T>>;
1964};
1965type HeadersArgs = {
1966 loaderHeaders: Headers;
1967 parentHeaders: Headers;
1968 actionHeaders: Headers;
1969 errorHeaders: Headers | undefined;
1970};
1971/**
1972 * A function that returns HTTP headers to be used for a route. These headers
1973 * will be merged with (and take precedence over) headers from parent routes.
1974 */
1975interface HeadersFunction {
1976 (args: HeadersArgs): Headers | HeadersInit;
1977}
1978/**
1979 * A function that defines `<link>` tags to be inserted into the `<head>` of
1980 * the document on route transitions.
1981 *
1982 * @see https://reactrouter.com/start/framework/route-module#meta
1983 */
1984interface LinksFunction {
1985 (): LinkDescriptor[];
1986}
1987interface MetaMatch<RouteId extends string = string, Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown> {
1988 id: RouteId;
1989 pathname: DataRouteMatch["pathname"];
1990 /** @deprecated Use `MetaMatch.loaderData` instead */
1991 data: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
1992 loaderData: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
1993 handle?: RouteHandle;
1994 params: DataRouteMatch["params"];
1995 meta: MetaDescriptor[];
1996 error?: unknown;
1997}
1998type MetaMatches<MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> = Array<{
1999 [K in keyof MatchLoaders]: MetaMatch<Exclude<K, number | symbol>, MatchLoaders[K]>;
2000}[keyof MatchLoaders]>;
2001interface MetaArgs<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
2002 /** @deprecated Use `MetaArgs.loaderData` instead */
2003 data: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
2004 loaderData: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
2005 params: Params;
2006 location: Location;
2007 matches: MetaMatches<MatchLoaders>;
2008 error?: unknown;
2009}
2010/**
2011 * A function that returns an array of data objects to use for rendering
2012 * metadata HTML tags in a route. These tags are not rendered on descendant
2013 * routes in the route hierarchy. In other words, they will only be rendered on
2014 * the route in which they are exported.
2015 *
2016 * @param Loader - The type of the current route's loader function
2017 * @param MatchLoaders - Mapping from a parent route's filepath to its loader
2018 * function type
2019 *
2020 * Note that parent route filepaths are relative to the `app/` directory.
2021 *
2022 * For example, if this meta function is for `/sales/customers/$customerId`:
2023 *
2024 * ```ts
2025 * // app/root.tsx
2026 * const loader = () => ({ hello: "world" })
2027 * export type Loader = typeof loader
2028 *
2029 * // app/routes/sales.tsx
2030 * const loader = () => ({ salesCount: 1074 })
2031 * export type Loader = typeof loader
2032 *
2033 * // app/routes/sales/customers.tsx
2034 * const loader = () => ({ customerCount: 74 })
2035 * export type Loader = typeof loader
2036 *
2037 * // app/routes/sales/customers/$customersId.tsx
2038 * import type { Loader as RootLoader } from "../../../root"
2039 * import type { Loader as SalesLoader } from "../../sales"
2040 * import type { Loader as CustomersLoader } from "../../sales/customers"
2041 *
2042 * const loader = () => ({ name: "Customer name" })
2043 *
2044 * const meta: MetaFunction<typeof loader, {
2045 * "root": RootLoader,
2046 * "routes/sales": SalesLoader,
2047 * "routes/sales/customers": CustomersLoader,
2048 * }> = ({ data, matches }) => {
2049 * const { name } = data
2050 * // ^? string
2051 * const { customerCount } = matches.find((match) => match.id === "routes/sales/customers").data
2052 * // ^? number
2053 * const { salesCount } = matches.find((match) => match.id === "routes/sales").data
2054 * // ^? number
2055 * const { hello } = matches.find((match) => match.id === "root").data
2056 * // ^? "world"
2057 * }
2058 * ```
2059 */
2060interface MetaFunction<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
2061 (args: MetaArgs<Loader, MatchLoaders>): MetaDescriptor[] | undefined;
2062}
2063type MetaDescriptor = {
2064 charSet: "utf-8";
2065} | {
2066 title: string;
2067} | {
2068 name: string;
2069 content: string;
2070} | {
2071 property: string;
2072 content: string;
2073} | {
2074 httpEquiv: string;
2075 content: string;
2076} | {
2077 "script:ld+json": LdJsonObject;
2078} | {
2079 tagName: "meta" | "link";
2080 [name: string]: string;
2081} | {
2082 [name: string]: unknown;
2083};
2084type LdJsonObject = {
2085 [Key in string]: LdJsonValue;
2086} & {
2087 [Key in string]?: LdJsonValue | undefined;
2088};
2089type LdJsonArray = LdJsonValue[] | readonly LdJsonValue[];
2090type LdJsonPrimitive = string | number | boolean | null;
2091type LdJsonValue = LdJsonPrimitive | LdJsonObject | LdJsonArray;
2092/**
2093 * An arbitrary object that is associated with a route.
2094 *
2095 * @see https://reactrouter.com/how-to/using-handle
2096 */
2097type RouteHandle = unknown;
2098
2099declare const redirect: typeof redirect$1;
2100declare const redirectDocument: typeof redirectDocument$1;
2101declare const replace: typeof replace$1;
2102declare const Await: typeof Await$1;
2103type RSCRouteConfigEntryBase = {
2104 action?: ActionFunction;
2105 clientAction?: ClientActionFunction;
2106 clientLoader?: ClientLoaderFunction;
2107 ErrorBoundary?: React.ComponentType<any>;
2108 handle?: any;
2109 headers?: HeadersFunction;
2110 HydrateFallback?: React.ComponentType<any>;
2111 Layout?: React.ComponentType<any>;
2112 links?: LinksFunction;
2113 loader?: LoaderFunction;
2114 meta?: MetaFunction;
2115 shouldRevalidate?: ShouldRevalidateFunction;
2116};
2117type RSCRouteConfigEntry = RSCRouteConfigEntryBase & {
2118 id: string;
2119 path?: string;
2120 Component?: React.ComponentType<any>;
2121 lazy?: () => Promise<RSCRouteConfigEntryBase & ({
2122 default?: React.ComponentType<any>;
2123 Component?: never;
2124 } | {
2125 default?: never;
2126 Component?: React.ComponentType<any>;
2127 })>;
2128} & ({
2129 index: true;
2130} | {
2131 children?: RSCRouteConfigEntry[];
2132});
2133type RSCRouteConfig = Array<RSCRouteConfigEntry>;
2134type RSCRouteManifest = {
2135 clientAction?: ClientActionFunction;
2136 clientLoader?: ClientLoaderFunction;
2137 element?: React.ReactElement | false;
2138 errorElement?: React.ReactElement;
2139 handle?: any;
2140 hasAction: boolean;
2141 hasComponent: boolean;
2142 hasErrorBoundary: boolean;
2143 hasLoader: boolean;
2144 hydrateFallbackElement?: React.ReactElement;
2145 id: string;
2146 index?: boolean;
2147 links?: LinksFunction;
2148 meta?: MetaFunction;
2149 parentId?: string;
2150 path?: string;
2151 shouldRevalidate?: ShouldRevalidateFunction;
2152};
2153type RSCRouteMatch = RSCRouteManifest & {
2154 params: Params;
2155 pathname: string;
2156 pathnameBase: string;
2157};
2158type RSCRenderPayload = {
2159 type: "render";
2160 actionData: Record<string, any> | null;
2161 basename: string | undefined;
2162 errors: Record<string, any> | null;
2163 loaderData: Record<string, any>;
2164 location: Location;
2165 matches: RSCRouteMatch[];
2166 patches?: RSCRouteManifest[];
2167 nonce?: string;
2168 formState?: unknown;
2169};
2170type RSCManifestPayload = {
2171 type: "manifest";
2172 patches: RSCRouteManifest[];
2173};
2174type RSCActionPayload = {
2175 type: "action";
2176 actionResult: Promise<unknown>;
2177 rerender?: Promise<RSCRenderPayload | RSCRedirectPayload>;
2178};
2179type RSCRedirectPayload = {
2180 type: "redirect";
2181 status: number;
2182 location: string;
2183 replace: boolean;
2184 reload: boolean;
2185 actionResult?: Promise<unknown>;
2186};
2187type RSCPayload = RSCRenderPayload | RSCManifestPayload | RSCActionPayload | RSCRedirectPayload;
2188type RSCMatch = {
2189 statusCode: number;
2190 headers: Headers;
2191 payload: RSCPayload;
2192};
2193type DecodeActionFunction = (formData: FormData) => Promise<() => Promise<unknown>>;
2194type DecodeFormStateFunction = (result: unknown, formData: FormData) => unknown;
2195type DecodeReplyFunction = (reply: FormData | string, { temporaryReferences }: {
2196 temporaryReferences: unknown;
2197}) => Promise<unknown[]>;
2198type LoadServerActionFunction = (id: string) => Promise<Function>;
2199/**
2200 * Matches the given routes to a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
2201 * and returns an [RSC](https://react.dev/reference/rsc/server-components)
2202 * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2203 * encoding an {@link unstable_RSCPayload} for consumption by an [RSC](https://react.dev/reference/rsc/server-components)
2204 * enabled client router.
2205 *
2206 * @example
2207 * import {
2208 * createTemporaryReferenceSet,
2209 * decodeAction,
2210 * decodeReply,
2211 * loadServerAction,
2212 * renderToReadableStream,
2213 * } from "@vitejs/plugin-rsc/rsc";
2214 * import { unstable_matchRSCServerRequest as matchRSCServerRequest } from "react-router";
2215 *
2216 * matchRSCServerRequest({
2217 * createTemporaryReferenceSet,
2218 * decodeAction,
2219 * decodeFormState,
2220 * decodeReply,
2221 * loadServerAction,
2222 * request,
2223 * routes: routes(),
2224 * generateResponse(match) {
2225 * return new Response(
2226 * renderToReadableStream(match.payload),
2227 * {
2228 * status: match.statusCode,
2229 * headers: match.headers,
2230 * }
2231 * );
2232 * },
2233 * });
2234 *
2235 * @name unstable_matchRSCServerRequest
2236 * @public
2237 * @category RSC
2238 * @mode data
2239 * @param opts Options
2240 * @param opts.basename The basename to use when matching the request.
2241 * @param opts.createTemporaryReferenceSet A function that returns a temporary
2242 * reference set for the request, used to track temporary references in the [RSC](https://react.dev/reference/rsc/server-components)
2243 * stream.
2244 * @param opts.decodeAction Your `react-server-dom-xyz/server`'s `decodeAction`
2245 * function, responsible for loading a server action.
2246 * @param opts.decodeFormState A function responsible for decoding form state for
2247 * progressively enhanceable forms with React's [`useActionState`](https://react.dev/reference/react/useActionState)
2248 * using your `react-server-dom-xyz/server`'s `decodeFormState`.
2249 * @param opts.decodeReply Your `react-server-dom-xyz/server`'s `decodeReply`
2250 * function, used to decode the server function's arguments and bind them to the
2251 * implementation for invocation by the router.
2252 * @param opts.generateResponse A function responsible for using your
2253 * `renderToReadableStream` to generate a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2254 * encoding the {@link unstable_RSCPayload}.
2255 * @param opts.loadServerAction Your `react-server-dom-xyz/server`'s
2256 * `loadServerAction` function, used to load a server action by ID.
2257 * @param opts.onError An optional error handler that will be called with any
2258 * errors that occur during the request processing.
2259 * @param opts.request The [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
2260 * to match against.
2261 * @param opts.requestContext An instance of {@link RouterContextProvider}
2262 * that should be created per request, to be passed to [`action`](../../start/data/route-object#action)s,
2263 * [`loader`](../../start/data/route-object#loader)s and [middleware](../../how-to/middleware).
2264 * @param opts.routes Your {@link unstable_RSCRouteConfigEntry | route definitions}.
2265 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2266 * that contains the [RSC](https://react.dev/reference/rsc/server-components)
2267 * data for hydration.
2268 */
2269declare function matchRSCServerRequest({ createTemporaryReferenceSet, basename, decodeReply, requestContext, loadServerAction, decodeAction, decodeFormState, onError, request, routes, generateResponse, }: {
2270 createTemporaryReferenceSet: () => unknown;
2271 basename?: string;
2272 decodeReply?: DecodeReplyFunction;
2273 decodeAction?: DecodeActionFunction;
2274 decodeFormState?: DecodeFormStateFunction;
2275 requestContext?: RouterContextProvider;
2276 loadServerAction?: LoadServerActionFunction;
2277 onError?: (error: unknown) => void;
2278 request: Request;
2279 routes: RSCRouteConfigEntry[];
2280 generateResponse: (match: RSCMatch, { temporaryReferences, }: {
2281 temporaryReferences: unknown;
2282 }) => Response;
2283}): Promise<Response>;
2284
2285/**
2286 * Apps can use this interface to "register" app-wide types for React Router via interface declaration merging and module augmentation.
2287 * React Router should handle this for you via type generation.
2288 *
2289 * For more on declaration merging and module augmentation, see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation .
2290 */
2291interface Register {
2292}
2293type AnyParams = Record<string, string | undefined>;
2294type AnyPages = Record<string, {
2295 params: AnyParams;
2296}>;
2297type Pages = Register extends {
2298 pages: infer Registered extends AnyPages;
2299} ? Registered : AnyPages;
2300
2301type Args = {
2302 [K in keyof Pages]: ToArgs<Pages[K]["params"]>;
2303};
2304type ToArgs<Params extends Record<string, string | undefined>> = Equal<Params, {}> extends true ? [] : Partial<Params> extends Params ? [Params] | [] : [
2305 Params
2306];
2307/**
2308 Returns a resolved URL path for the specified route.
2309
2310 ```tsx
2311 const h = href("/:lang?/about", { lang: "en" })
2312 // -> `/en/about`
2313
2314 <Link to={href("/products/:id", { id: "abc123" })} />
2315 ```
2316 */
2317declare function href<Path extends keyof Args>(path: Path, ...args: Args[Path]): string;
2318
2319interface CookieSignatureOptions {
2320 /**
2321 * An array of secrets that may be used to sign/unsign the value of a cookie.
2322 *
2323 * The array makes it easy to rotate secrets. New secrets should be added to
2324 * the beginning of the array. `cookie.serialize()` will always use the first
2325 * value in the array, but `cookie.parse()` may use any of them so that
2326 * cookies that were signed with older secrets still work.
2327 */
2328 secrets?: string[];
2329}
2330type CookieOptions = ParseOptions & SerializeOptions & CookieSignatureOptions;
2331/**
2332 * A HTTP cookie.
2333 *
2334 * A Cookie is a logical container for metadata about a HTTP cookie; its name
2335 * and options. But it doesn't contain a value. Instead, it has `parse()` and
2336 * `serialize()` methods that allow a single instance to be reused for
2337 * parsing/encoding multiple different values.
2338 *
2339 * @see https://remix.run/utils/cookies#cookie-api
2340 */
2341interface Cookie {
2342 /**
2343 * The name of the cookie, used in the `Cookie` and `Set-Cookie` headers.
2344 */
2345 readonly name: string;
2346 /**
2347 * True if this cookie uses one or more secrets for verification.
2348 */
2349 readonly isSigned: boolean;
2350 /**
2351 * The Date this cookie expires.
2352 *
2353 * Note: This is calculated at access time using `maxAge` when no `expires`
2354 * option is provided to `createCookie()`.
2355 */
2356 readonly expires?: Date;
2357 /**
2358 * Parses a raw `Cookie` header and returns the value of this cookie or
2359 * `null` if it's not present.
2360 */
2361 parse(cookieHeader: string | null, options?: ParseOptions): Promise<any>;
2362 /**
2363 * Serializes the given value to a string and returns the `Set-Cookie`
2364 * header.
2365 */
2366 serialize(value: any, options?: SerializeOptions): Promise<string>;
2367}
2368/**
2369 * Creates a logical container for managing a browser cookie from the server.
2370 */
2371declare const createCookie: (name: string, cookieOptions?: CookieOptions) => Cookie;
2372type IsCookieFunction = (object: any) => object is Cookie;
2373/**
2374 * Returns true if an object is a Remix cookie container.
2375 *
2376 * @see https://remix.run/utils/cookies#iscookie
2377 */
2378declare const isCookie: IsCookieFunction;
2379
2380/**
2381 * An object of name/value pairs to be used in the session.
2382 */
2383interface SessionData {
2384 [name: string]: any;
2385}
2386/**
2387 * Session persists data across HTTP requests.
2388 *
2389 * @see https://reactrouter.com/explanation/sessions-and-cookies#sessions
2390 */
2391interface Session<Data = SessionData, FlashData = Data> {
2392 /**
2393 * A unique identifier for this session.
2394 *
2395 * Note: This will be the empty string for newly created sessions and
2396 * sessions that are not backed by a database (i.e. cookie-based sessions).
2397 */
2398 readonly id: string;
2399 /**
2400 * The raw data contained in this session.
2401 *
2402 * This is useful mostly for SessionStorage internally to access the raw
2403 * session data to persist.
2404 */
2405 readonly data: FlashSessionData<Data, FlashData>;
2406 /**
2407 * Returns `true` if the session has a value for the given `name`, `false`
2408 * otherwise.
2409 */
2410 has(name: (keyof Data | keyof FlashData) & string): boolean;
2411 /**
2412 * Returns the value for the given `name` in this session.
2413 */
2414 get<Key extends (keyof Data | keyof FlashData) & string>(name: Key): (Key extends keyof Data ? Data[Key] : undefined) | (Key extends keyof FlashData ? FlashData[Key] : undefined) | undefined;
2415 /**
2416 * Sets a value in the session for the given `name`.
2417 */
2418 set<Key extends keyof Data & string>(name: Key, value: Data[Key]): void;
2419 /**
2420 * Sets a value in the session that is only valid until the next `get()`.
2421 * This can be useful for temporary values, like error messages.
2422 */
2423 flash<Key extends keyof FlashData & string>(name: Key, value: FlashData[Key]): void;
2424 /**
2425 * Removes a value from the session.
2426 */
2427 unset(name: keyof Data & string): void;
2428}
2429type FlashSessionData<Data, FlashData> = Partial<Data & {
2430 [Key in keyof FlashData as FlashDataKey<Key & string>]: FlashData[Key];
2431}>;
2432type FlashDataKey<Key extends string> = `__flash_${Key}__`;
2433type CreateSessionFunction = <Data = SessionData, FlashData = Data>(initialData?: Data, id?: string) => Session<Data, FlashData>;
2434/**
2435 * Creates a new Session object.
2436 *
2437 * Note: This function is typically not invoked directly by application code.
2438 * Instead, use a `SessionStorage` object's `getSession` method.
2439 */
2440declare const createSession: CreateSessionFunction;
2441type IsSessionFunction = (object: any) => object is Session;
2442/**
2443 * Returns true if an object is a React Router session.
2444 *
2445 * @see https://reactrouter.com/api/utils/isSession
2446 */
2447declare const isSession: IsSessionFunction;
2448/**
2449 * SessionStorage stores session data between HTTP requests and knows how to
2450 * parse and create cookies.
2451 *
2452 * A SessionStorage creates Session objects using a `Cookie` header as input.
2453 * Then, later it generates the `Set-Cookie` header to be used in the response.
2454 */
2455interface SessionStorage<Data = SessionData, FlashData = Data> {
2456 /**
2457 * Parses a Cookie header from a HTTP request and returns the associated
2458 * Session. If there is no session associated with the cookie, this will
2459 * return a new Session with no data.
2460 */
2461 getSession: (cookieHeader?: string | null, options?: ParseOptions) => Promise<Session<Data, FlashData>>;
2462 /**
2463 * Stores all data in the Session and returns the Set-Cookie header to be
2464 * used in the HTTP response.
2465 */
2466 commitSession: (session: Session<Data, FlashData>, options?: SerializeOptions) => Promise<string>;
2467 /**
2468 * Deletes all data associated with the Session and returns the Set-Cookie
2469 * header to be used in the HTTP response.
2470 */
2471 destroySession: (session: Session<Data, FlashData>, options?: SerializeOptions) => Promise<string>;
2472}
2473/**
2474 * SessionIdStorageStrategy is designed to allow anyone to easily build their
2475 * own SessionStorage using `createSessionStorage(strategy)`.
2476 *
2477 * This strategy describes a common scenario where the session id is stored in
2478 * a cookie but the actual session data is stored elsewhere, usually in a
2479 * database or on disk. A set of create, read, update, and delete operations
2480 * are provided for managing the session data.
2481 */
2482interface SessionIdStorageStrategy<Data = SessionData, FlashData = Data> {
2483 /**
2484 * The Cookie used to store the session id, or options used to automatically
2485 * create one.
2486 */
2487 cookie?: Cookie | (CookieOptions & {
2488 name?: string;
2489 });
2490 /**
2491 * Creates a new record with the given data and returns the session id.
2492 */
2493 createData: (data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<string>;
2494 /**
2495 * Returns data for a given session id, or `null` if there isn't any.
2496 */
2497 readData: (id: string) => Promise<FlashSessionData<Data, FlashData> | null>;
2498 /**
2499 * Updates data for the given session id.
2500 */
2501 updateData: (id: string, data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<void>;
2502 /**
2503 * Deletes data for a given session id from the data store.
2504 */
2505 deleteData: (id: string) => Promise<void>;
2506}
2507/**
2508 * Creates a SessionStorage object using a SessionIdStorageStrategy.
2509 *
2510 * Note: This is a low-level API that should only be used if none of the
2511 * existing session storage options meet your requirements.
2512 */
2513declare function createSessionStorage<Data = SessionData, FlashData = Data>({ cookie: cookieArg, createData, readData, updateData, deleteData, }: SessionIdStorageStrategy<Data, FlashData>): SessionStorage<Data, FlashData>;
2514
2515interface CookieSessionStorageOptions {
2516 /**
2517 * The Cookie used to store the session data on the client, or options used
2518 * to automatically create one.
2519 */
2520 cookie?: SessionIdStorageStrategy["cookie"];
2521}
2522/**
2523 * Creates and returns a SessionStorage object that stores all session data
2524 * directly in the session cookie itself.
2525 *
2526 * This has the advantage that no database or other backend services are
2527 * needed, and can help to simplify some load-balanced scenarios. However, it
2528 * also has the limitation that serialized session data may not exceed the
2529 * browser's maximum cookie size. Trade-offs!
2530 */
2531declare function createCookieSessionStorage<Data = SessionData, FlashData = Data>({ cookie: cookieArg }?: CookieSessionStorageOptions): SessionStorage<Data, FlashData>;
2532
2533interface MemorySessionStorageOptions {
2534 /**
2535 * The Cookie used to store the session id on the client, or options used
2536 * to automatically create one.
2537 */
2538 cookie?: SessionIdStorageStrategy["cookie"];
2539}
2540/**
2541 * Creates and returns a simple in-memory SessionStorage object, mostly useful
2542 * for testing and as a reference implementation.
2543 *
2544 * Note: This storage does not scale beyond a single process, so it is not
2545 * suitable for most production scenarios.
2546 */
2547declare function createMemorySessionStorage<Data = SessionData, FlashData = Data>({ cookie }?: MemorySessionStorageOptions): SessionStorage<Data, FlashData>;
2548
2549export { Await, type Cookie, type CookieOptions, type CookieSignatureOptions, type FlashSessionData, type IsCookieFunction, type IsSessionFunction, type MiddlewareFunction, type MiddlewareNextFunction, type RouterContext, RouterContextProvider, type Session, type SessionData, type SessionIdStorageStrategy, type SessionStorage, createContext, createCookie, createCookieSessionStorage, createMemorySessionStorage, createSession, createSessionStorage, createStaticHandler, data, href, isCookie, isRouteErrorResponse, isSession, matchRoutes, redirect, redirectDocument, replace, type DecodeActionFunction as unstable_DecodeActionFunction, type DecodeFormStateFunction as unstable_DecodeFormStateFunction, type DecodeReplyFunction as unstable_DecodeReplyFunction, type LoadServerActionFunction as unstable_LoadServerActionFunction, type RSCManifestPayload as unstable_RSCManifestPayload, type RSCMatch as unstable_RSCMatch, type RSCPayload as unstable_RSCPayload, type RSCRenderPayload as unstable_RSCRenderPayload, type RSCRouteConfig as unstable_RSCRouteConfig, type RSCRouteConfigEntry as unstable_RSCRouteConfigEntry, type RSCRouteManifest as unstable_RSCRouteManifest, type RSCRouteMatch as unstable_RSCRouteMatch, matchRSCServerRequest as unstable_matchRSCServerRequest };