UNPKG

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