UNPKG

94 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 unstable_defaultShouldRevalidate?: boolean;
1373};
1374type BaseNavigateOptions = BaseNavigateOrFetchOptions & {
1375 replace?: boolean;
1376 state?: any;
1377 fromRouteId?: string;
1378 viewTransition?: boolean;
1379};
1380type BaseSubmissionOptions = {
1381 formMethod?: HTMLFormMethod;
1382 formEncType?: FormEncType;
1383} & ({
1384 formData: FormData;
1385 body?: undefined;
1386} | {
1387 formData?: undefined;
1388 body: any;
1389});
1390/**
1391 * Options for a navigate() call for a normal (non-submission) navigation
1392 */
1393type LinkNavigateOptions = BaseNavigateOptions;
1394/**
1395 * Options for a navigate() call for a submission navigation
1396 */
1397type SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;
1398/**
1399 * Options to pass to navigate() for a navigation
1400 */
1401type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions;
1402/**
1403 * Options for a fetch() load
1404 */
1405type LoadFetchOptions = BaseNavigateOrFetchOptions;
1406/**
1407 * Options for a fetch() submission
1408 */
1409type SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;
1410/**
1411 * Options to pass to fetch()
1412 */
1413type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;
1414/**
1415 * Potential states for state.navigation
1416 */
1417type NavigationStates = {
1418 Idle: {
1419 state: "idle";
1420 location: undefined;
1421 formMethod: undefined;
1422 formAction: undefined;
1423 formEncType: undefined;
1424 formData: undefined;
1425 json: undefined;
1426 text: undefined;
1427 };
1428 Loading: {
1429 state: "loading";
1430 location: Location;
1431 formMethod: Submission["formMethod"] | undefined;
1432 formAction: Submission["formAction"] | undefined;
1433 formEncType: Submission["formEncType"] | undefined;
1434 formData: Submission["formData"] | undefined;
1435 json: Submission["json"] | undefined;
1436 text: Submission["text"] | undefined;
1437 };
1438 Submitting: {
1439 state: "submitting";
1440 location: Location;
1441 formMethod: Submission["formMethod"];
1442 formAction: Submission["formAction"];
1443 formEncType: Submission["formEncType"];
1444 formData: Submission["formData"];
1445 json: Submission["json"];
1446 text: Submission["text"];
1447 };
1448};
1449type Navigation = NavigationStates[keyof NavigationStates];
1450type RevalidationState = "idle" | "loading";
1451/**
1452 * Potential states for fetchers
1453 */
1454type FetcherStates<TData = any> = {
1455 /**
1456 * The fetcher is not calling a loader or action
1457 *
1458 * ```tsx
1459 * fetcher.state === "idle"
1460 * ```
1461 */
1462 Idle: {
1463 state: "idle";
1464 formMethod: undefined;
1465 formAction: undefined;
1466 formEncType: undefined;
1467 text: undefined;
1468 formData: undefined;
1469 json: undefined;
1470 /**
1471 * If the fetcher has never been called, this will be undefined.
1472 */
1473 data: TData | undefined;
1474 };
1475 /**
1476 * The fetcher is loading data from a {@link LoaderFunction | loader} from a
1477 * call to {@link FetcherWithComponents.load | `fetcher.load`}.
1478 *
1479 * ```tsx
1480 * // somewhere
1481 * <button onClick={() => fetcher.load("/some/route") }>Load</button>
1482 *
1483 * // the state will update
1484 * fetcher.state === "loading"
1485 * ```
1486 */
1487 Loading: {
1488 state: "loading";
1489 formMethod: Submission["formMethod"] | undefined;
1490 formAction: Submission["formAction"] | undefined;
1491 formEncType: Submission["formEncType"] | undefined;
1492 text: Submission["text"] | undefined;
1493 formData: Submission["formData"] | undefined;
1494 json: Submission["json"] | undefined;
1495 data: TData | undefined;
1496 };
1497 /**
1498 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`}.
1499
1500 ```tsx
1501 // somewhere
1502 <input
1503 onChange={e => {
1504 fetcher.submit(event.currentTarget.form, { method: "post" });
1505 }}
1506 />
1507
1508 // the state will update
1509 fetcher.state === "submitting"
1510
1511 // and formData will be available
1512 fetcher.formData
1513 ```
1514 */
1515 Submitting: {
1516 state: "submitting";
1517 formMethod: Submission["formMethod"];
1518 formAction: Submission["formAction"];
1519 formEncType: Submission["formEncType"];
1520 text: Submission["text"];
1521 formData: Submission["formData"];
1522 json: Submission["json"];
1523 data: TData | undefined;
1524 };
1525};
1526type Fetcher<TData = any> = FetcherStates<TData>[keyof FetcherStates<TData>];
1527interface BlockerBlocked {
1528 state: "blocked";
1529 reset: () => void;
1530 proceed: () => void;
1531 location: Location;
1532}
1533interface BlockerUnblocked {
1534 state: "unblocked";
1535 reset: undefined;
1536 proceed: undefined;
1537 location: undefined;
1538}
1539interface BlockerProceeding {
1540 state: "proceeding";
1541 reset: undefined;
1542 proceed: undefined;
1543 location: Location;
1544}
1545type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;
1546type BlockerFunction = (args: {
1547 currentLocation: Location;
1548 nextLocation: Location;
1549 historyAction: Action;
1550}) => boolean;
1551interface CreateStaticHandlerOptions {
1552 basename?: string;
1553 mapRouteProperties?: MapRoutePropertiesFunction;
1554 unstable_instrumentations?: Pick<unstable_ServerInstrumentation, "route">[];
1555 future?: {};
1556}
1557declare function createStaticHandler(routes: AgnosticRouteObject[], opts?: CreateStaticHandlerOptions): StaticHandler;
1558
1559interface AwaitResolveRenderFunction<Resolve = any> {
1560 (data: Awaited<Resolve>): React.ReactNode;
1561}
1562/**
1563 * @category Types
1564 */
1565interface AwaitProps<Resolve> {
1566 /**
1567 * When using a function, the resolved value is provided as the parameter.
1568 *
1569 * ```tsx [2]
1570 * <Await resolve={reviewsPromise}>
1571 * {(resolvedReviews) => <Reviews items={resolvedReviews} />}
1572 * </Await>
1573 * ```
1574 *
1575 * When using React elements, {@link useAsyncValue} will provide the
1576 * resolved value:
1577 *
1578 * ```tsx [2]
1579 * <Await resolve={reviewsPromise}>
1580 * <Reviews />
1581 * </Await>
1582 *
1583 * function Reviews() {
1584 * const resolvedReviews = useAsyncValue();
1585 * return <div>...</div>;
1586 * }
1587 * ```
1588 */
1589 children: React.ReactNode | AwaitResolveRenderFunction<Resolve>;
1590 /**
1591 * The error element renders instead of the `children` when the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
1592 * rejects.
1593 *
1594 * ```tsx
1595 * <Await
1596 * errorElement={<div>Oops</div>}
1597 * resolve={reviewsPromise}
1598 * >
1599 * <Reviews />
1600 * </Await>
1601 * ```
1602 *
1603 * To provide a more contextual error, you can use the {@link useAsyncError} in a
1604 * child component
1605 *
1606 * ```tsx
1607 * <Await
1608 * errorElement={<ReviewsError />}
1609 * resolve={reviewsPromise}
1610 * >
1611 * <Reviews />
1612 * </Await>
1613 *
1614 * function ReviewsError() {
1615 * const error = useAsyncError();
1616 * return <div>Error loading reviews: {error.message}</div>;
1617 * }
1618 * ```
1619 *
1620 * If you do not provide an `errorElement`, the rejected value will bubble up
1621 * to the nearest route-level [`ErrorBoundary`](../../start/framework/route-module#errorboundary)
1622 * and be accessible via the {@link useRouteError} hook.
1623 */
1624 errorElement?: React.ReactNode;
1625 /**
1626 * Takes a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
1627 * returned from a [`loader`](../../start/framework/route-module#loader) to be
1628 * resolved and rendered.
1629 *
1630 * ```tsx
1631 * import { Await, useLoaderData } from "react-router";
1632 *
1633 * export async function loader() {
1634 * let reviews = getReviews(); // not awaited
1635 * let book = await getBook();
1636 * return {
1637 * book,
1638 * reviews, // this is a promise
1639 * };
1640 * }
1641 *
1642 * export default function Book() {
1643 * const {
1644 * book,
1645 * reviews, // this is the same promise
1646 * } = useLoaderData();
1647 *
1648 * return (
1649 * <div>
1650 * <h1>{book.title}</h1>
1651 * <p>{book.description}</p>
1652 * <React.Suspense fallback={<ReviewsSkeleton />}>
1653 * <Await
1654 * // and is the promise we pass to Await
1655 * resolve={reviews}
1656 * >
1657 * <Reviews />
1658 * </Await>
1659 * </React.Suspense>
1660 * </div>
1661 * );
1662 * }
1663 * ```
1664 */
1665 resolve: Resolve;
1666}
1667/**
1668 * Used to render promise values with automatic error handling.
1669 *
1670 * **Note:** `<Await>` expects to be rendered inside a [`<React.Suspense>`](https://react.dev/reference/react/Suspense)
1671 *
1672 * @example
1673 * import { Await, useLoaderData } from "react-router";
1674 *
1675 * export async function loader() {
1676 * // not awaited
1677 * const reviews = getReviews();
1678 * // awaited (blocks the transition)
1679 * const book = await fetch("/api/book").then((res) => res.json());
1680 * return { book, reviews };
1681 * }
1682 *
1683 * function Book() {
1684 * const { book, reviews } = useLoaderData();
1685 * return (
1686 * <div>
1687 * <h1>{book.title}</h1>
1688 * <p>{book.description}</p>
1689 * <React.Suspense fallback={<ReviewsSkeleton />}>
1690 * <Await
1691 * resolve={reviews}
1692 * errorElement={
1693 * <div>Could not load reviews 😬</div>
1694 * }
1695 * children={(resolvedReviews) => (
1696 * <Reviews items={resolvedReviews} />
1697 * )}
1698 * />
1699 * </React.Suspense>
1700 * </div>
1701 * );
1702 * }
1703 *
1704 * @public
1705 * @category Components
1706 * @mode framework
1707 * @mode data
1708 * @param props Props
1709 * @param {AwaitProps.children} props.children n/a
1710 * @param {AwaitProps.errorElement} props.errorElement n/a
1711 * @param {AwaitProps.resolve} props.resolve n/a
1712 * @returns React element for the rendered awaited value
1713 */
1714declare function Await$1<Resolve>({ children, errorElement, resolve, }: AwaitProps<Resolve>): React.JSX.Element;
1715
1716interface IndexRouteObject {
1717 caseSensitive?: AgnosticIndexRouteObject["caseSensitive"];
1718 path?: AgnosticIndexRouteObject["path"];
1719 id?: AgnosticIndexRouteObject["id"];
1720 middleware?: AgnosticIndexRouteObject["middleware"];
1721 loader?: AgnosticIndexRouteObject["loader"];
1722 action?: AgnosticIndexRouteObject["action"];
1723 hasErrorBoundary?: AgnosticIndexRouteObject["hasErrorBoundary"];
1724 shouldRevalidate?: AgnosticIndexRouteObject["shouldRevalidate"];
1725 handle?: AgnosticIndexRouteObject["handle"];
1726 index: true;
1727 children?: undefined;
1728 element?: React.ReactNode | null;
1729 hydrateFallbackElement?: React.ReactNode | null;
1730 errorElement?: React.ReactNode | null;
1731 Component?: React.ComponentType | null;
1732 HydrateFallback?: React.ComponentType | null;
1733 ErrorBoundary?: React.ComponentType | null;
1734 lazy?: LazyRouteDefinition<RouteObject>;
1735}
1736interface NonIndexRouteObject {
1737 caseSensitive?: AgnosticNonIndexRouteObject["caseSensitive"];
1738 path?: AgnosticNonIndexRouteObject["path"];
1739 id?: AgnosticNonIndexRouteObject["id"];
1740 middleware?: AgnosticNonIndexRouteObject["middleware"];
1741 loader?: AgnosticNonIndexRouteObject["loader"];
1742 action?: AgnosticNonIndexRouteObject["action"];
1743 hasErrorBoundary?: AgnosticNonIndexRouteObject["hasErrorBoundary"];
1744 shouldRevalidate?: AgnosticNonIndexRouteObject["shouldRevalidate"];
1745 handle?: AgnosticNonIndexRouteObject["handle"];
1746 index?: false;
1747 children?: RouteObject[];
1748 element?: React.ReactNode | null;
1749 hydrateFallbackElement?: React.ReactNode | null;
1750 errorElement?: React.ReactNode | null;
1751 Component?: React.ComponentType | null;
1752 HydrateFallback?: React.ComponentType | null;
1753 ErrorBoundary?: React.ComponentType | null;
1754 lazy?: LazyRouteDefinition<RouteObject>;
1755}
1756type RouteObject = IndexRouteObject | NonIndexRouteObject;
1757type DataRouteObject = RouteObject & {
1758 children?: DataRouteObject[];
1759 id: string;
1760};
1761interface RouteMatch<ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {
1762}
1763interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {
1764}
1765
1766type Primitive = null | undefined | string | number | boolean | symbol | bigint;
1767type LiteralUnion<LiteralType, BaseType extends Primitive> = LiteralType | (BaseType & Record<never, never>);
1768interface HtmlLinkProps {
1769 /**
1770 * Address of the hyperlink
1771 */
1772 href?: string;
1773 /**
1774 * How the element handles crossorigin requests
1775 */
1776 crossOrigin?: "anonymous" | "use-credentials";
1777 /**
1778 * Relationship between the document containing the hyperlink and the destination resource
1779 */
1780 rel: LiteralUnion<"alternate" | "dns-prefetch" | "icon" | "manifest" | "modulepreload" | "next" | "pingback" | "preconnect" | "prefetch" | "preload" | "prerender" | "search" | "stylesheet", string>;
1781 /**
1782 * Applicable media: "screen", "print", "(max-width: 764px)"
1783 */
1784 media?: string;
1785 /**
1786 * Integrity metadata used in Subresource Integrity checks
1787 */
1788 integrity?: string;
1789 /**
1790 * Language of the linked resource
1791 */
1792 hrefLang?: string;
1793 /**
1794 * Hint for the type of the referenced resource
1795 */
1796 type?: string;
1797 /**
1798 * Referrer policy for fetches initiated by the element
1799 */
1800 referrerPolicy?: "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
1801 /**
1802 * Sizes of the icons (for rel="icon")
1803 */
1804 sizes?: string;
1805 /**
1806 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
1807 */
1808 as?: LiteralUnion<"audio" | "audioworklet" | "document" | "embed" | "fetch" | "font" | "frame" | "iframe" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt", string>;
1809 /**
1810 * Color to use when customizing a site's icon (for rel="mask-icon")
1811 */
1812 color?: string;
1813 /**
1814 * Whether the link is disabled
1815 */
1816 disabled?: boolean;
1817 /**
1818 * The title attribute has special semantics on this element: Title of the link; CSS style sheet set name.
1819 */
1820 title?: string;
1821 /**
1822 * Images to use in different situations, e.g., high-resolution displays,
1823 * small monitors, etc. (for rel="preload")
1824 */
1825 imageSrcSet?: string;
1826 /**
1827 * Image sizes for different page layouts (for rel="preload")
1828 */
1829 imageSizes?: string;
1830}
1831interface HtmlLinkPreloadImage extends HtmlLinkProps {
1832 /**
1833 * Relationship between the document containing the hyperlink and the destination resource
1834 */
1835 rel: "preload";
1836 /**
1837 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
1838 */
1839 as: "image";
1840 /**
1841 * Address of the hyperlink
1842 */
1843 href?: string;
1844 /**
1845 * Images to use in different situations, e.g., high-resolution displays,
1846 * small monitors, etc. (for rel="preload")
1847 */
1848 imageSrcSet: string;
1849 /**
1850 * Image sizes for different page layouts (for rel="preload")
1851 */
1852 imageSizes?: string;
1853}
1854/**
1855 * Represents a `<link>` element.
1856 *
1857 * WHATWG Specification: https://html.spec.whatwg.org/multipage/semantics.html#the-link-element
1858 */
1859type HtmlLinkDescriptor = (HtmlLinkProps & Pick<Required<HtmlLinkProps>, "href">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "imageSizes">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "href"> & {
1860 imageSizes?: never;
1861});
1862interface PageLinkDescriptor extends Omit<HtmlLinkDescriptor, "href" | "rel" | "type" | "sizes" | "imageSrcSet" | "imageSizes" | "as" | "color" | "title"> {
1863 /**
1864 * A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
1865 * attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
1866 * element
1867 */
1868 nonce?: string | undefined;
1869 /**
1870 * The absolute path of the page to prefetch, e.g. `/absolute/path`.
1871 */
1872 page: string;
1873}
1874type LinkDescriptor = HtmlLinkDescriptor | PageLinkDescriptor;
1875
1876type Serializable = undefined | null | boolean | string | symbol | number | Array<Serializable> | {
1877 [key: PropertyKey]: Serializable;
1878} | bigint | Date | URL | RegExp | Error | Map<Serializable, Serializable> | Set<Serializable> | Promise<Serializable>;
1879
1880type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
1881type IsAny<T> = 0 extends 1 & T ? true : false;
1882type Func = (...args: any[]) => unknown;
1883
1884/**
1885 * A brand that can be applied to a type to indicate that it will serialize
1886 * to a specific type when transported to the client from a loader.
1887 * Only use this if you have additional serialization/deserialization logic
1888 * in your application.
1889 */
1890type unstable_SerializesTo<T> = {
1891 unstable__ReactRouter_SerializesTo: [T];
1892};
1893
1894type 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> ? {
1895 [K in keyof T]: Serialize<T[K]>;
1896} : undefined;
1897type VoidToUndefined<T> = Equal<T, void> extends true ? undefined : T;
1898type DataFrom<T> = IsAny<T> extends true ? undefined : T extends Func ? VoidToUndefined<Awaited<ReturnType<T>>> : undefined;
1899type ClientData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? U : T;
1900type ServerData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? Serialize<U> : Serialize<T>;
1901type ServerDataFrom<T> = ServerData<DataFrom<T>>;
1902type ClientDataFrom<T> = ClientData<DataFrom<T>>;
1903type ClientDataFunctionArgs<Params> = {
1904 /**
1905 * 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.
1906 *
1907 * @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.
1908 **/
1909 request: Request;
1910 /**
1911 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
1912 * @example
1913 * // app/routes.ts
1914 * route("teams/:teamId", "./team.tsx"),
1915 *
1916 * // app/team.tsx
1917 * export function clientLoader({
1918 * params,
1919 * }: Route.ClientLoaderArgs) {
1920 * params.teamId;
1921 * // ^ string
1922 * }
1923 **/
1924 params: Params;
1925 /**
1926 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
1927 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
1928 */
1929 unstable_pattern: string;
1930 /**
1931 * When `future.v8_middleware` is not enabled, this is undefined.
1932 *
1933 * When `future.v8_middleware` is enabled, this is an instance of
1934 * `RouterContextProvider` and can be used to access context values
1935 * from your route middlewares. You may pass in initial context values in your
1936 * `<HydratedRouter getContext>` prop
1937 */
1938 context: Readonly<RouterContextProvider>;
1939};
1940type SerializeFrom<T> = T extends (...args: infer Args) => unknown ? Args extends [
1941 ClientLoaderFunctionArgs | ClientActionFunctionArgs | ClientDataFunctionArgs<unknown>
1942] ? ClientDataFrom<T> : ServerDataFrom<T> : T;
1943
1944/**
1945 * A function that handles data mutations for a route on the client
1946 */
1947type ClientActionFunction = (args: ClientActionFunctionArgs) => ReturnType<ActionFunction>;
1948/**
1949 * Arguments passed to a route `clientAction` function
1950 */
1951type ClientActionFunctionArgs = ActionFunctionArgs & {
1952 serverAction: <T = unknown>() => Promise<SerializeFrom<T>>;
1953};
1954/**
1955 * A function that loads data for a route on the client
1956 */
1957type ClientLoaderFunction = ((args: ClientLoaderFunctionArgs) => ReturnType<LoaderFunction>) & {
1958 hydrate?: boolean;
1959};
1960/**
1961 * Arguments passed to a route `clientLoader` function
1962 */
1963type ClientLoaderFunctionArgs = LoaderFunctionArgs & {
1964 serverLoader: <T = unknown>() => Promise<SerializeFrom<T>>;
1965};
1966type HeadersArgs = {
1967 loaderHeaders: Headers;
1968 parentHeaders: Headers;
1969 actionHeaders: Headers;
1970 errorHeaders: Headers | undefined;
1971};
1972/**
1973 * A function that returns HTTP headers to be used for a route. These headers
1974 * will be merged with (and take precedence over) headers from parent routes.
1975 */
1976interface HeadersFunction {
1977 (args: HeadersArgs): Headers | HeadersInit;
1978}
1979/**
1980 * A function that defines `<link>` tags to be inserted into the `<head>` of
1981 * the document on route transitions.
1982 *
1983 * @see https://reactrouter.com/start/framework/route-module#meta
1984 */
1985interface LinksFunction {
1986 (): LinkDescriptor[];
1987}
1988interface MetaMatch<RouteId extends string = string, Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown> {
1989 id: RouteId;
1990 pathname: DataRouteMatch["pathname"];
1991 /** @deprecated Use `MetaMatch.loaderData` instead */
1992 data: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
1993 loaderData: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
1994 handle?: RouteHandle;
1995 params: DataRouteMatch["params"];
1996 meta: MetaDescriptor[];
1997 error?: unknown;
1998}
1999type MetaMatches<MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> = Array<{
2000 [K in keyof MatchLoaders]: MetaMatch<Exclude<K, number | symbol>, MatchLoaders[K]>;
2001}[keyof MatchLoaders]>;
2002interface MetaArgs<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
2003 /** @deprecated Use `MetaArgs.loaderData` instead */
2004 data: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
2005 loaderData: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
2006 params: Params;
2007 location: Location;
2008 matches: MetaMatches<MatchLoaders>;
2009 error?: unknown;
2010}
2011/**
2012 * A function that returns an array of data objects to use for rendering
2013 * metadata HTML tags in a route. These tags are not rendered on descendant
2014 * routes in the route hierarchy. In other words, they will only be rendered on
2015 * the route in which they are exported.
2016 *
2017 * @param Loader - The type of the current route's loader function
2018 * @param MatchLoaders - Mapping from a parent route's filepath to its loader
2019 * function type
2020 *
2021 * Note that parent route filepaths are relative to the `app/` directory.
2022 *
2023 * For example, if this meta function is for `/sales/customers/$customerId`:
2024 *
2025 * ```ts
2026 * // app/root.tsx
2027 * const loader = () => ({ hello: "world" })
2028 * export type Loader = typeof loader
2029 *
2030 * // app/routes/sales.tsx
2031 * const loader = () => ({ salesCount: 1074 })
2032 * export type Loader = typeof loader
2033 *
2034 * // app/routes/sales/customers.tsx
2035 * const loader = () => ({ customerCount: 74 })
2036 * export type Loader = typeof loader
2037 *
2038 * // app/routes/sales/customers/$customersId.tsx
2039 * import type { Loader as RootLoader } from "../../../root"
2040 * import type { Loader as SalesLoader } from "../../sales"
2041 * import type { Loader as CustomersLoader } from "../../sales/customers"
2042 *
2043 * const loader = () => ({ name: "Customer name" })
2044 *
2045 * const meta: MetaFunction<typeof loader, {
2046 * "root": RootLoader,
2047 * "routes/sales": SalesLoader,
2048 * "routes/sales/customers": CustomersLoader,
2049 * }> = ({ data, matches }) => {
2050 * const { name } = data
2051 * // ^? string
2052 * const { customerCount } = matches.find((match) => match.id === "routes/sales/customers").data
2053 * // ^? number
2054 * const { salesCount } = matches.find((match) => match.id === "routes/sales").data
2055 * // ^? number
2056 * const { hello } = matches.find((match) => match.id === "root").data
2057 * // ^? "world"
2058 * }
2059 * ```
2060 */
2061interface MetaFunction<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
2062 (args: MetaArgs<Loader, MatchLoaders>): MetaDescriptor[] | undefined;
2063}
2064type MetaDescriptor = {
2065 charSet: "utf-8";
2066} | {
2067 title: string;
2068} | {
2069 name: string;
2070 content: string;
2071} | {
2072 property: string;
2073 content: string;
2074} | {
2075 httpEquiv: string;
2076 content: string;
2077} | {
2078 "script:ld+json": LdJsonObject;
2079} | {
2080 tagName: "meta" | "link";
2081 [name: string]: string;
2082} | {
2083 [name: string]: unknown;
2084};
2085type LdJsonObject = {
2086 [Key in string]: LdJsonValue;
2087} & {
2088 [Key in string]?: LdJsonValue | undefined;
2089};
2090type LdJsonArray = LdJsonValue[] | readonly LdJsonValue[];
2091type LdJsonPrimitive = string | number | boolean | null;
2092type LdJsonValue = LdJsonPrimitive | LdJsonObject | LdJsonArray;
2093/**
2094 * An arbitrary object that is associated with a route.
2095 *
2096 * @see https://reactrouter.com/how-to/using-handle
2097 */
2098type RouteHandle = unknown;
2099
2100declare const redirect: typeof redirect$1;
2101declare const redirectDocument: typeof redirectDocument$1;
2102declare const replace: typeof replace$1;
2103declare const Await: typeof Await$1;
2104type RSCRouteConfigEntryBase = {
2105 action?: ActionFunction;
2106 clientAction?: ClientActionFunction;
2107 clientLoader?: ClientLoaderFunction;
2108 ErrorBoundary?: React.ComponentType<any>;
2109 handle?: any;
2110 headers?: HeadersFunction;
2111 HydrateFallback?: React.ComponentType<any>;
2112 Layout?: React.ComponentType<any>;
2113 links?: LinksFunction;
2114 loader?: LoaderFunction;
2115 meta?: MetaFunction;
2116 shouldRevalidate?: ShouldRevalidateFunction;
2117};
2118type RSCRouteConfigEntry = RSCRouteConfigEntryBase & {
2119 id: string;
2120 path?: string;
2121 Component?: React.ComponentType<any>;
2122 lazy?: () => Promise<RSCRouteConfigEntryBase & ({
2123 default?: React.ComponentType<any>;
2124 Component?: never;
2125 } | {
2126 default?: never;
2127 Component?: React.ComponentType<any>;
2128 })>;
2129} & ({
2130 index: true;
2131} | {
2132 children?: RSCRouteConfigEntry[];
2133});
2134type RSCRouteConfig = Array<RSCRouteConfigEntry>;
2135type RSCRouteManifest = {
2136 clientAction?: ClientActionFunction;
2137 clientLoader?: ClientLoaderFunction;
2138 element?: React.ReactElement | false;
2139 errorElement?: React.ReactElement;
2140 handle?: any;
2141 hasAction: boolean;
2142 hasComponent: boolean;
2143 hasErrorBoundary: boolean;
2144 hasLoader: boolean;
2145 hydrateFallbackElement?: React.ReactElement;
2146 id: string;
2147 index?: boolean;
2148 links?: LinksFunction;
2149 meta?: MetaFunction;
2150 parentId?: string;
2151 path?: string;
2152 shouldRevalidate?: ShouldRevalidateFunction;
2153};
2154type RSCRouteMatch = RSCRouteManifest & {
2155 params: Params;
2156 pathname: string;
2157 pathnameBase: string;
2158};
2159type RSCRenderPayload = {
2160 type: "render";
2161 actionData: Record<string, any> | null;
2162 basename: string | undefined;
2163 errors: Record<string, any> | null;
2164 loaderData: Record<string, any>;
2165 location: Location;
2166 matches: RSCRouteMatch[];
2167 patches?: RSCRouteManifest[];
2168 nonce?: string;
2169 formState?: unknown;
2170};
2171type RSCManifestPayload = {
2172 type: "manifest";
2173 patches: RSCRouteManifest[];
2174};
2175type RSCActionPayload = {
2176 type: "action";
2177 actionResult: Promise<unknown>;
2178 rerender?: Promise<RSCRenderPayload | RSCRedirectPayload>;
2179};
2180type RSCRedirectPayload = {
2181 type: "redirect";
2182 status: number;
2183 location: string;
2184 replace: boolean;
2185 reload: boolean;
2186 actionResult?: Promise<unknown>;
2187};
2188type RSCPayload = RSCRenderPayload | RSCManifestPayload | RSCActionPayload | RSCRedirectPayload;
2189type RSCMatch = {
2190 statusCode: number;
2191 headers: Headers;
2192 payload: RSCPayload;
2193};
2194type DecodeActionFunction = (formData: FormData) => Promise<() => Promise<unknown>>;
2195type DecodeFormStateFunction = (result: unknown, formData: FormData) => unknown;
2196type DecodeReplyFunction = (reply: FormData | string, options: {
2197 temporaryReferences: unknown;
2198}) => Promise<unknown[]>;
2199type LoadServerActionFunction = (id: string) => Promise<Function>;
2200/**
2201 * Matches the given routes to a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
2202 * and returns an [RSC](https://react.dev/reference/rsc/server-components)
2203 * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2204 * encoding an {@link unstable_RSCPayload} for consumption by an [RSC](https://react.dev/reference/rsc/server-components)
2205 * enabled client router.
2206 *
2207 * @example
2208 * import {
2209 * createTemporaryReferenceSet,
2210 * decodeAction,
2211 * decodeReply,
2212 * loadServerAction,
2213 * renderToReadableStream,
2214 * } from "@vitejs/plugin-rsc/rsc";
2215 * import { unstable_matchRSCServerRequest as matchRSCServerRequest } from "react-router";
2216 *
2217 * matchRSCServerRequest({
2218 * createTemporaryReferenceSet,
2219 * decodeAction,
2220 * decodeFormState,
2221 * decodeReply,
2222 * loadServerAction,
2223 * request,
2224 * routes: routes(),
2225 * generateResponse(match) {
2226 * return new Response(
2227 * renderToReadableStream(match.payload),
2228 * {
2229 * status: match.statusCode,
2230 * headers: match.headers,
2231 * }
2232 * );
2233 * },
2234 * });
2235 *
2236 * @name unstable_matchRSCServerRequest
2237 * @public
2238 * @category RSC
2239 * @mode data
2240 * @param opts Options
2241 * @param opts.allowedActionOrigins Origin patterns that are allowed to execute actions.
2242 * @param opts.basename The basename to use when matching the request.
2243 * @param opts.createTemporaryReferenceSet A function that returns a temporary
2244 * reference set for the request, used to track temporary references in the [RSC](https://react.dev/reference/rsc/server-components)
2245 * stream.
2246 * @param opts.decodeAction Your `react-server-dom-xyz/server`'s `decodeAction`
2247 * function, responsible for loading a server action.
2248 * @param opts.decodeFormState A function responsible for decoding form state for
2249 * progressively enhanceable forms with React's [`useActionState`](https://react.dev/reference/react/useActionState)
2250 * using your `react-server-dom-xyz/server`'s `decodeFormState`.
2251 * @param opts.decodeReply Your `react-server-dom-xyz/server`'s `decodeReply`
2252 * function, used to decode the server function's arguments and bind them to the
2253 * implementation for invocation by the router.
2254 * @param opts.generateResponse A function responsible for using your
2255 * `renderToReadableStream` to generate a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2256 * encoding the {@link unstable_RSCPayload}.
2257 * @param opts.loadServerAction Your `react-server-dom-xyz/server`'s
2258 * `loadServerAction` function, used to load a server action by ID.
2259 * @param opts.onError An optional error handler that will be called with any
2260 * errors that occur during the request processing.
2261 * @param opts.request The [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
2262 * to match against.
2263 * @param opts.requestContext An instance of {@link RouterContextProvider}
2264 * that should be created per request, to be passed to [`action`](../../start/data/route-object#action)s,
2265 * [`loader`](../../start/data/route-object#loader)s and [middleware](../../how-to/middleware).
2266 * @param opts.routes Your {@link unstable_RSCRouteConfigEntry | route definitions}.
2267 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2268 * that contains the [RSC](https://react.dev/reference/rsc/server-components)
2269 * data for hydration.
2270 */
2271declare function matchRSCServerRequest({ allowedActionOrigins, createTemporaryReferenceSet, basename, decodeReply, requestContext, loadServerAction, decodeAction, decodeFormState, onError, request, routes, generateResponse, }: {
2272 allowedActionOrigins?: string[];
2273 createTemporaryReferenceSet: () => unknown;
2274 basename?: string;
2275 decodeReply?: DecodeReplyFunction;
2276 decodeAction?: DecodeActionFunction;
2277 decodeFormState?: DecodeFormStateFunction;
2278 requestContext?: RouterContextProvider;
2279 loadServerAction?: LoadServerActionFunction;
2280 onError?: (error: unknown) => void;
2281 request: Request;
2282 routes: RSCRouteConfigEntry[];
2283 generateResponse: (match: RSCMatch, { onError, temporaryReferences, }: {
2284 onError(error: unknown): string | undefined;
2285 temporaryReferences: unknown;
2286 }) => Response;
2287}): Promise<Response>;
2288
2289/**
2290 * Apps can use this interface to "register" app-wide types for React Router via interface declaration merging and module augmentation.
2291 * React Router should handle this for you via type generation.
2292 *
2293 * For more on declaration merging and module augmentation, see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation .
2294 */
2295interface Register {
2296}
2297type AnyParams = Record<string, string | undefined>;
2298type AnyPages = Record<string, {
2299 params: AnyParams;
2300}>;
2301type Pages = Register extends {
2302 pages: infer Registered extends AnyPages;
2303} ? Registered : AnyPages;
2304
2305type Args = {
2306 [K in keyof Pages]: ToArgs<Pages[K]["params"]>;
2307};
2308type ToArgs<Params extends Record<string, string | undefined>> = Equal<Params, {}> extends true ? [] : Partial<Params> extends Params ? [Params] | [] : [
2309 Params
2310];
2311/**
2312 Returns a resolved URL path for the specified route.
2313
2314 ```tsx
2315 const h = href("/:lang?/about", { lang: "en" })
2316 // -> `/en/about`
2317
2318 <Link to={href("/products/:id", { id: "abc123" })} />
2319 ```
2320 */
2321declare function href<Path extends keyof Args>(path: Path, ...args: Args[Path]): string;
2322
2323interface CookieSignatureOptions {
2324 /**
2325 * An array of secrets that may be used to sign/unsign the value of a cookie.
2326 *
2327 * The array makes it easy to rotate secrets. New secrets should be added to
2328 * the beginning of the array. `cookie.serialize()` will always use the first
2329 * value in the array, but `cookie.parse()` may use any of them so that
2330 * cookies that were signed with older secrets still work.
2331 */
2332 secrets?: string[];
2333}
2334type CookieOptions = ParseOptions & SerializeOptions & CookieSignatureOptions;
2335/**
2336 * A HTTP cookie.
2337 *
2338 * A Cookie is a logical container for metadata about a HTTP cookie; its name
2339 * and options. But it doesn't contain a value. Instead, it has `parse()` and
2340 * `serialize()` methods that allow a single instance to be reused for
2341 * parsing/encoding multiple different values.
2342 *
2343 * @see https://remix.run/utils/cookies#cookie-api
2344 */
2345interface Cookie {
2346 /**
2347 * The name of the cookie, used in the `Cookie` and `Set-Cookie` headers.
2348 */
2349 readonly name: string;
2350 /**
2351 * True if this cookie uses one or more secrets for verification.
2352 */
2353 readonly isSigned: boolean;
2354 /**
2355 * The Date this cookie expires.
2356 *
2357 * Note: This is calculated at access time using `maxAge` when no `expires`
2358 * option is provided to `createCookie()`.
2359 */
2360 readonly expires?: Date;
2361 /**
2362 * Parses a raw `Cookie` header and returns the value of this cookie or
2363 * `null` if it's not present.
2364 */
2365 parse(cookieHeader: string | null, options?: ParseOptions): Promise<any>;
2366 /**
2367 * Serializes the given value to a string and returns the `Set-Cookie`
2368 * header.
2369 */
2370 serialize(value: any, options?: SerializeOptions): Promise<string>;
2371}
2372/**
2373 * Creates a logical container for managing a browser cookie from the server.
2374 */
2375declare const createCookie: (name: string, cookieOptions?: CookieOptions) => Cookie;
2376type IsCookieFunction = (object: any) => object is Cookie;
2377/**
2378 * Returns true if an object is a Remix cookie container.
2379 *
2380 * @see https://remix.run/utils/cookies#iscookie
2381 */
2382declare const isCookie: IsCookieFunction;
2383
2384/**
2385 * An object of name/value pairs to be used in the session.
2386 */
2387interface SessionData {
2388 [name: string]: any;
2389}
2390/**
2391 * Session persists data across HTTP requests.
2392 *
2393 * @see https://reactrouter.com/explanation/sessions-and-cookies#sessions
2394 */
2395interface Session<Data = SessionData, FlashData = Data> {
2396 /**
2397 * A unique identifier for this session.
2398 *
2399 * Note: This will be the empty string for newly created sessions and
2400 * sessions that are not backed by a database (i.e. cookie-based sessions).
2401 */
2402 readonly id: string;
2403 /**
2404 * The raw data contained in this session.
2405 *
2406 * This is useful mostly for SessionStorage internally to access the raw
2407 * session data to persist.
2408 */
2409 readonly data: FlashSessionData<Data, FlashData>;
2410 /**
2411 * Returns `true` if the session has a value for the given `name`, `false`
2412 * otherwise.
2413 */
2414 has(name: (keyof Data | keyof FlashData) & string): boolean;
2415 /**
2416 * Returns the value for the given `name` in this session.
2417 */
2418 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;
2419 /**
2420 * Sets a value in the session for the given `name`.
2421 */
2422 set<Key extends keyof Data & string>(name: Key, value: Data[Key]): void;
2423 /**
2424 * Sets a value in the session that is only valid until the next `get()`.
2425 * This can be useful for temporary values, like error messages.
2426 */
2427 flash<Key extends keyof FlashData & string>(name: Key, value: FlashData[Key]): void;
2428 /**
2429 * Removes a value from the session.
2430 */
2431 unset(name: keyof Data & string): void;
2432}
2433type FlashSessionData<Data, FlashData> = Partial<Data & {
2434 [Key in keyof FlashData as FlashDataKey<Key & string>]: FlashData[Key];
2435}>;
2436type FlashDataKey<Key extends string> = `__flash_${Key}__`;
2437type CreateSessionFunction = <Data = SessionData, FlashData = Data>(initialData?: Data, id?: string) => Session<Data, FlashData>;
2438/**
2439 * Creates a new Session object.
2440 *
2441 * Note: This function is typically not invoked directly by application code.
2442 * Instead, use a `SessionStorage` object's `getSession` method.
2443 */
2444declare const createSession: CreateSessionFunction;
2445type IsSessionFunction = (object: any) => object is Session;
2446/**
2447 * Returns true if an object is a React Router session.
2448 *
2449 * @see https://reactrouter.com/api/utils/isSession
2450 */
2451declare const isSession: IsSessionFunction;
2452/**
2453 * SessionStorage stores session data between HTTP requests and knows how to
2454 * parse and create cookies.
2455 *
2456 * A SessionStorage creates Session objects using a `Cookie` header as input.
2457 * Then, later it generates the `Set-Cookie` header to be used in the response.
2458 */
2459interface SessionStorage<Data = SessionData, FlashData = Data> {
2460 /**
2461 * Parses a Cookie header from a HTTP request and returns the associated
2462 * Session. If there is no session associated with the cookie, this will
2463 * return a new Session with no data.
2464 */
2465 getSession: (cookieHeader?: string | null, options?: ParseOptions) => Promise<Session<Data, FlashData>>;
2466 /**
2467 * Stores all data in the Session and returns the Set-Cookie header to be
2468 * used in the HTTP response.
2469 */
2470 commitSession: (session: Session<Data, FlashData>, options?: SerializeOptions) => Promise<string>;
2471 /**
2472 * Deletes all data associated with the Session and returns the Set-Cookie
2473 * header to be used in the HTTP response.
2474 */
2475 destroySession: (session: Session<Data, FlashData>, options?: SerializeOptions) => Promise<string>;
2476}
2477/**
2478 * SessionIdStorageStrategy is designed to allow anyone to easily build their
2479 * own SessionStorage using `createSessionStorage(strategy)`.
2480 *
2481 * This strategy describes a common scenario where the session id is stored in
2482 * a cookie but the actual session data is stored elsewhere, usually in a
2483 * database or on disk. A set of create, read, update, and delete operations
2484 * are provided for managing the session data.
2485 */
2486interface SessionIdStorageStrategy<Data = SessionData, FlashData = Data> {
2487 /**
2488 * The Cookie used to store the session id, or options used to automatically
2489 * create one.
2490 */
2491 cookie?: Cookie | (CookieOptions & {
2492 name?: string;
2493 });
2494 /**
2495 * Creates a new record with the given data and returns the session id.
2496 */
2497 createData: (data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<string>;
2498 /**
2499 * Returns data for a given session id, or `null` if there isn't any.
2500 */
2501 readData: (id: string) => Promise<FlashSessionData<Data, FlashData> | null>;
2502 /**
2503 * Updates data for the given session id.
2504 */
2505 updateData: (id: string, data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<void>;
2506 /**
2507 * Deletes data for a given session id from the data store.
2508 */
2509 deleteData: (id: string) => Promise<void>;
2510}
2511/**
2512 * Creates a SessionStorage object using a SessionIdStorageStrategy.
2513 *
2514 * Note: This is a low-level API that should only be used if none of the
2515 * existing session storage options meet your requirements.
2516 */
2517declare function createSessionStorage<Data = SessionData, FlashData = Data>({ cookie: cookieArg, createData, readData, updateData, deleteData, }: SessionIdStorageStrategy<Data, FlashData>): SessionStorage<Data, FlashData>;
2518
2519interface CookieSessionStorageOptions {
2520 /**
2521 * The Cookie used to store the session data on the client, or options used
2522 * to automatically create one.
2523 */
2524 cookie?: SessionIdStorageStrategy["cookie"];
2525}
2526/**
2527 * Creates and returns a SessionStorage object that stores all session data
2528 * directly in the session cookie itself.
2529 *
2530 * This has the advantage that no database or other backend services are
2531 * needed, and can help to simplify some load-balanced scenarios. However, it
2532 * also has the limitation that serialized session data may not exceed the
2533 * browser's maximum cookie size. Trade-offs!
2534 */
2535declare function createCookieSessionStorage<Data = SessionData, FlashData = Data>({ cookie: cookieArg }?: CookieSessionStorageOptions): SessionStorage<Data, FlashData>;
2536
2537interface MemorySessionStorageOptions {
2538 /**
2539 * The Cookie used to store the session id on the client, or options used
2540 * to automatically create one.
2541 */
2542 cookie?: SessionIdStorageStrategy["cookie"];
2543}
2544/**
2545 * Creates and returns a simple in-memory SessionStorage object, mostly useful
2546 * for testing and as a reference implementation.
2547 *
2548 * Note: This storage does not scale beyond a single process, so it is not
2549 * suitable for most production scenarios.
2550 */
2551declare function createMemorySessionStorage<Data = SessionData, FlashData = Data>({ cookie }?: MemorySessionStorageOptions): SessionStorage<Data, FlashData>;
2552
2553export { 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 };