UNPKG

100 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$1<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$1;
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$1;
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" | "unstable_validateParams";
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 * A map of route param names to regular expressions used to validate params
660 * after a route-pattern match.
661 */
662 unstable_validateParams?: Record<string, RegExp>;
663 /**
664 * The route handle.
665 */
666 handle?: any;
667 /**
668 * A function that returns a promise that resolves to the route object.
669 * Used for code-splitting routes.
670 * See [`lazy`](../../start/data/route-object#lazy).
671 */
672 lazy?: LazyRouteDefinition<BaseRouteObject>;
673 /**
674 * The React Component to render when this route matches.
675 * Mutually exclusive with `element`.
676 */
677 Component?: React.ComponentType | null;
678 /**
679 * The React element to render when this Route matches.
680 * Mutually exclusive with `Component`.
681 */
682 element?: React.ReactNode | null;
683 /**
684 * The React Component to render at this route if an error occurs.
685 * Mutually exclusive with `errorElement`.
686 */
687 ErrorBoundary?: React.ComponentType | null;
688 /**
689 * The React element to render at this route if an error occurs.
690 * Mutually exclusive with `ErrorBoundary`.
691 */
692 errorElement?: React.ReactNode | null;
693 /**
694 * The React Component to render while this router is loading data.
695 * Mutually exclusive with `hydrateFallbackElement`.
696 */
697 HydrateFallback?: React.ComponentType | null;
698 /**
699 * The React element to render while this router is loading data.
700 * Mutually exclusive with `HydrateFallback`.
701 */
702 hydrateFallbackElement?: React.ReactNode | null;
703};
704/**
705 * Index routes must not have children
706 */
707type IndexRouteObject = BaseRouteObject & {
708 /**
709 * Child Route objects - not valid on index routes.
710 */
711 children?: undefined;
712 /**
713 * Whether this is an index route.
714 */
715 index: true;
716};
717/**
718 * Non-index routes may have children, but cannot have `index` set to `true`.
719 */
720type NonIndexRouteObject = BaseRouteObject & {
721 /**
722 * Child Route objects.
723 */
724 children?: RouteObject[];
725 /**
726 * Whether this is an index route - must be `false` or undefined on non-index routes.
727 */
728 index?: false;
729};
730/**
731 * A route object represents a logical route, with (optionally) its child
732 * routes organized in a tree-like structure.
733 */
734type RouteObject = IndexRouteObject | NonIndexRouteObject;
735type DataIndexRouteObject = IndexRouteObject & {
736 id: string;
737};
738type DataNonIndexRouteObject = NonIndexRouteObject & {
739 children?: DataRouteObject[];
740 id: string;
741};
742/**
743 * A data route object, which is just a RouteObject with a required unique ID
744 */
745type DataRouteObject = DataIndexRouteObject | DataNonIndexRouteObject;
746type RouteManifest<R = DataRouteObject> = Record<string, R | undefined>;
747/**
748 * The parameters that were parsed from the URL path.
749 */
750type Params<Key extends string = string> = { readonly [key in Key]: string | undefined };
751/**
752 * A RouteMatch contains info about how a route matched a URL.
753 */
754interface RouteMatch<ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> {
755 /**
756 * The names and values of dynamic parameters in the URL.
757 */
758 params: Params<ParamKey>;
759 /**
760 * The portion of the URL pathname that was matched.
761 */
762 pathname: string;
763 /**
764 * The portion of the URL pathname that was matched before child routes.
765 */
766 pathnameBase: string;
767 /**
768 * The route object that was used to match.
769 */
770 route: RouteObjectType;
771}
772interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}
773/**
774 * Matches the given routes to a location and returns the match data.
775 *
776 * @example
777 * import { matchRoutes } from "react-router";
778 *
779 * let routes = [{
780 * path: "/",
781 * Component: Root,
782 * children: [{
783 * path: "dashboard",
784 * Component: Dashboard,
785 * }]
786 * }];
787 *
788 * matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
789 *
790 * @public
791 * @category Utils
792 * @param routes The array of route objects to match against.
793 * @param locationArg The location to match against, either a string path or a
794 * partial {@link Location} object
795 * @param basename Optional base path to strip from the location before matching.
796 * Defaults to `/`.
797 * @returns An array of matched routes, or `null` if no matches were found.
798 */
799declare function matchRoutes<RouteObjectType extends RouteObject = RouteObject>(routes: RouteObjectType[], locationArg: Partial<Location$1> | string, basename?: string): RouteMatch<string, RouteObjectType>[] | null;
800interface UIMatch<Data = unknown, Handle = unknown> {
801 id: string;
802 pathname: string;
803 /**
804 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the matched route.
805 */
806 params: RouteMatch["params"];
807 /**
808 * The return value from the matched route's loader or clientLoader. This might
809 * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
810 * an error and we're currently displaying an `ErrorBoundary`.
811 */
812 loaderData: Data | undefined;
813 /**
814 * The {@link https://reactrouter.com/start/framework/route-module#handle handle object}
815 * exported from the matched route module
816 */
817 handle: Handle;
818}
819declare class DataWithResponseInit<D> {
820 type: string;
821 data: D;
822 init: ResponseInit | null;
823 constructor(data: D, init?: ResponseInit);
824}
825/**
826 * Create "responses" that contain `headers`/`status` without forcing
827 * serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
828 *
829 * @example
830 * import { data } from "react-router";
831 *
832 * export async function action({ request }: Route.ActionArgs) {
833 * let formData = await request.formData();
834 * let item = await createItem(formData);
835 * return data(item, {
836 * headers: { "X-Custom-Header": "value" }
837 * status: 201,
838 * });
839 * }
840 *
841 * @public
842 * @category Utils
843 * @mode framework
844 * @mode data
845 * @param data The data to be included in the response.
846 * @param init The status code or a `ResponseInit` object to be included in the
847 * response.
848 * @returns A {@link DataWithResponseInit} instance containing the data and
849 * response init.
850 */
851declare function data<D>(data: D, init?: number | ResponseInit): DataWithResponseInit<D>;
852type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
853/**
854 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
855 * Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
856 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
857 *
858 * This utility accepts absolute URLs and can navigate to external domains, so
859 * the application should validate any user-supplied inputs to redirects.
860 *
861 * @example
862 * import { redirect } from "react-router";
863 *
864 * export async function loader({ request }: Route.LoaderArgs) {
865 * if (!isLoggedIn(request))
866 * throw redirect("/login");
867 * }
868 *
869 * // ...
870 * }
871 *
872 * @public
873 * @category Utils
874 * @mode framework
875 * @mode data
876 * @param url The URL to redirect to.
877 * @param init The status code or a `ResponseInit` object to be included in the
878 * response.
879 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
880 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
881 * header.
882 */
883declare const redirect$1: RedirectFunction;
884/**
885 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
886 * that will force a document reload to the new location. Sets the status code
887 * and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
888 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
889 *
890 * This utility accepts absolute URLs and can navigate to external domains, so
891 * the application should validate any user-supplied inputs to redirects.
892 *
893 * ```tsx filename=routes/logout.tsx
894 * import { redirectDocument } from "react-router";
895 *
896 * import { destroySession } from "../sessions.server";
897 *
898 * export async function action({ request }: Route.ActionArgs) {
899 * let session = await getSession(request.headers.get("Cookie"));
900 * return redirectDocument("/", {
901 * headers: { "Set-Cookie": await destroySession(session) }
902 * });
903 * }
904 * ```
905 *
906 * @public
907 * @category Utils
908 * @mode framework
909 * @mode data
910 * @param url The URL to redirect to.
911 * @param init The status code or a `ResponseInit` object to be included in the
912 * response.
913 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
914 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
915 * header.
916 */
917declare const redirectDocument$1: RedirectFunction;
918/**
919 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
920 * that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
921 * instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
922 * for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
923 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
924 *
925 * @example
926 * import { replace } from "react-router";
927 *
928 * export async function loader() {
929 * return replace("/new-location");
930 * }
931 *
932 * @public
933 * @category Utils
934 * @mode framework
935 * @mode data
936 * @param url The URL to redirect to.
937 * @param init The status code or a `ResponseInit` object to be included in the
938 * response.
939 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
940 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
941 * header.
942 */
943declare const replace$2: RedirectFunction;
944type ErrorResponse = {
945 status: number;
946 statusText: string;
947 data: any;
948};
949/**
950 * Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
951 * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
952 * thrown from an [`action`](../../start/framework/route-module#action) or
953 * [`loader`](../../start/framework/route-module#loader) function.
954 *
955 * @example
956 * import { isRouteErrorResponse } from "react-router";
957 *
958 * export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
959 * if (isRouteErrorResponse(error)) {
960 * return (
961 * <>
962 * <p>Error: `${error.status}: ${error.statusText}`</p>
963 * <p>{error.data}</p>
964 * </>
965 * );
966 * }
967 *
968 * return (
969 * <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
970 * );
971 * }
972 *
973 * @public
974 * @category Utils
975 * @mode framework
976 * @mode data
977 * @param error The error to check.
978 * @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
979 */
980declare function isRouteErrorResponse(error: any): error is ErrorResponse;
981//#endregion
982//#region lib/router/instrumentation.d.ts
983type ServerInstrumentation = {
984 handler?: InstrumentRequestHandlerFunction;
985 route?: InstrumentRouteFunction;
986};
987type ClientInstrumentation = {
988 router?: InstrumentRouterFunction;
989 route?: InstrumentRouteFunction;
990};
991type InstrumentRequestHandlerFunction = (handler: InstrumentableRequestHandler) => void;
992type InstrumentRouterFunction = (router: InstrumentableRouter) => void;
993type InstrumentRouteFunction = (route: InstrumentableRoute) => void;
994/**
995 * Route metadata available after React Router has matched an instrumented
996 * request, navigation, or fetcher call.
997 */
998type InstrumentationResultMeta = {
999 url: LoaderFunctionArgs["url"];
1000 pattern: string;
1001 params: LoaderFunctionArgs["params"];
1002};
1003/**
1004 * Result returned by route-level instrumented handler calls, such as
1005 * instrumented loaders, actions, middleware, and lazy route functions.
1006 */
1007type InstrumentationHandlerResult = {
1008 status: "success";
1009 error: undefined;
1010} | {
1011 status: "error";
1012 error: Error;
1013};
1014/**
1015 * Result returned by client-side router instrumented navigation and fetcher
1016 * calls.
1017 */
1018type InstrumentationClientRouterResult = InstrumentationHandlerResult & {
1019 meta: InstrumentationResultMeta | undefined;
1020};
1021/**
1022 * Result returned by server request handler instrumentation.
1023 */
1024type InstrumentationServerHandlerResult = InstrumentationHandlerResult & {
1025 statusCode: number;
1026 meta: InstrumentationResultMeta | undefined;
1027};
1028type InstrumentFunction<T, TInnerResult = InstrumentationHandlerResult> = (handler: () => Promise<TInnerResult>, info: T) => Promise<void>;
1029type ReadonlyRequest = {
1030 method: string;
1031 url: string;
1032 headers: Pick<Headers, "get">;
1033};
1034type ReadonlyContext = Pick<RouterContextProvider, "get">;
1035type InstrumentableRoute = {
1036 id: string;
1037 index: boolean | undefined;
1038 path: string | undefined;
1039 instrument(instrumentations: RouteInstrumentations): void;
1040};
1041type RouteInstrumentations = {
1042 lazy?: InstrumentFunction<RouteLazyInstrumentationInfo>;
1043 "lazy.loader"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
1044 "lazy.action"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
1045 "lazy.middleware"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
1046 middleware?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
1047 loader?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
1048 action?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
1049};
1050type RouteLazyInstrumentationInfo = undefined;
1051type RouteHandlerInstrumentationInfo = Readonly<Omit<LoaderFunctionArgs, "request" | "context"> & {
1052 request: ReadonlyRequest;
1053 context: ReadonlyContext;
1054}>;
1055type InstrumentableRouter = {
1056 instrument(instrumentations: RouterInstrumentations): void;
1057};
1058type RouterInstrumentations = {
1059 navigate?: InstrumentFunction<RouterNavigationInstrumentationInfo, InstrumentationClientRouterResult>;
1060 fetch?: InstrumentFunction<RouterFetchInstrumentationInfo, InstrumentationClientRouterResult>;
1061};
1062type RouterNavigationInstrumentationInfo = Readonly<{
1063 to: string | number;
1064 currentUrl: string;
1065 formMethod?: HTMLFormMethod;
1066 formEncType?: FormEncType;
1067 formData?: FormData;
1068 body?: any;
1069}>;
1070type RouterFetchInstrumentationInfo = Readonly<{
1071 href: string;
1072 currentUrl: string;
1073 fetcherKey: string;
1074 formMethod?: HTMLFormMethod;
1075 formEncType?: FormEncType;
1076 formData?: FormData;
1077 body?: any;
1078}>;
1079type InstrumentableRequestHandler = {
1080 instrument(instrumentations: RequestHandlerInstrumentations): void;
1081};
1082type RequestHandlerInstrumentations = {
1083 request?: InstrumentFunction<RequestHandlerInstrumentationInfo, InstrumentationServerHandlerResult>;
1084};
1085type RequestHandlerInstrumentationInfo = Readonly<{
1086 request: ReadonlyRequest;
1087 context: ReadonlyContext | undefined;
1088}>;
1089//#endregion
1090//#region lib/router/router.d.ts
1091/**
1092 * A Router instance manages all navigation and data loading/mutations
1093 */
1094interface Router$1 {
1095 /**
1096 * @private
1097 * PRIVATE - DO NOT USE
1098 *
1099 * Return the basename for the router
1100 */
1101 get basename(): RouterInit["basename"];
1102 /**
1103 * @private
1104 * PRIVATE - DO NOT USE
1105 *
1106 * Return the future config for the router
1107 */
1108 get future(): FutureConfig;
1109 /**
1110 * @private
1111 * PRIVATE - DO NOT USE
1112 *
1113 * Return the current state of the router
1114 */
1115 get state(): RouterState;
1116 /**
1117 * @private
1118 * PRIVATE - DO NOT USE
1119 *
1120 * Return the routes for this router instance
1121 */
1122 get routes(): DataRouteObject[];
1123 /**
1124 * @private
1125 * PRIVATE - DO NOT USE
1126 *
1127 * Match routes against a location using the router's configured route
1128 * matching implementation.
1129 */
1130 match(locationArg: Partial<Location$1> | string): DataRouteMatch[] | null;
1131 /**
1132 * @private
1133 * PRIVATE - DO NOT USE
1134 *
1135 * Return the manifest for this router instance
1136 */
1137 get manifest(): RouteManifest;
1138 /**
1139 * @private
1140 * PRIVATE - DO NOT USE
1141 *
1142 * Return the window associated with the router
1143 */
1144 get window(): RouterInit["window"];
1145 /**
1146 * @private
1147 * PRIVATE - DO NOT USE
1148 *
1149 * Initialize the router, including adding history listeners and kicking off
1150 * initial data fetches. Returns a function to cleanup listeners and abort
1151 * any in-progress loads
1152 */
1153 initialize(): Router$1;
1154 /**
1155 * @private
1156 * PRIVATE - DO NOT USE
1157 *
1158 * Subscribe to router.state updates
1159 *
1160 * @param fn function to call with the new state
1161 */
1162 subscribe(fn: RouterSubscriber): () => void;
1163 /**
1164 * @private
1165 * PRIVATE - DO NOT USE
1166 *
1167 * Enable scroll restoration behavior in the router
1168 *
1169 * @param savedScrollPositions Object that will manage positions, in case
1170 * it's being restored from sessionStorage
1171 * @param getScrollPosition Function to get the active Y scroll position
1172 * @param getKey Function to get the key to use for restoration
1173 */
1174 enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;
1175 /**
1176 * @private
1177 * PRIVATE - DO NOT USE
1178 *
1179 * Navigate forward/backward in the history stack
1180 * @param to Delta to move in the history stack
1181 */
1182 navigate(to: number): Promise<void>;
1183 /**
1184 * Navigate to the given path
1185 * @param to Path to navigate to
1186 * @param opts Navigation options (method, submission, etc.)
1187 */
1188 navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;
1189 /**
1190 * @private
1191 * PRIVATE - DO NOT USE
1192 *
1193 * Trigger a fetcher load/submission
1194 *
1195 * @param key Fetcher key
1196 * @param routeId Route that owns the fetcher
1197 * @param href href to fetch
1198 * @param opts Fetcher options, (method, submission, etc.)
1199 */
1200 fetch(key: string, routeId: string, href: string | null, opts?: RouterFetchOptions): Promise<void>;
1201 /**
1202 * @private
1203 * PRIVATE - DO NOT USE
1204 *
1205 * Trigger a revalidation of all current route loaders and fetcher loads
1206 */
1207 revalidate(): Promise<void>;
1208 /**
1209 * @private
1210 * PRIVATE - DO NOT USE
1211 *
1212 * Utility function to create an href for the given location
1213 * @param location
1214 */
1215 createHref(location: Location$1 | URL): string;
1216 /**
1217 * @private
1218 * PRIVATE - DO NOT USE
1219 *
1220 * Utility function to create a URL for the given location
1221 * @param location
1222 */
1223 createURL?(to: To): URL;
1224 /**
1225 * @private
1226 * PRIVATE - DO NOT USE
1227 *
1228 * Utility function to URL encode a destination path according to the internal
1229 * history implementation
1230 * @param to
1231 */
1232 encodeLocation(to: To): Path;
1233 /**
1234 * @private
1235 * PRIVATE - DO NOT USE
1236 *
1237 * Get/create a fetcher for the given key
1238 * @param key
1239 */
1240 getFetcher<TData = any>(key: string): Fetcher<TData>;
1241 /**
1242 * @internal
1243 * PRIVATE - DO NOT USE
1244 *
1245 * Reset the fetcher for a given key
1246 * @param key
1247 */
1248 resetFetcher(key: string, opts?: {
1249 reason?: unknown;
1250 }): void;
1251 /**
1252 * @private
1253 * PRIVATE - DO NOT USE
1254 *
1255 * Delete the fetcher for a given key
1256 * @param key
1257 */
1258 deleteFetcher(key: string): void;
1259 /**
1260 * @private
1261 * PRIVATE - DO NOT USE
1262 *
1263 * Cleanup listeners and abort any in-progress loads
1264 */
1265 dispose(): void;
1266 /**
1267 * @private
1268 * PRIVATE - DO NOT USE
1269 *
1270 * Get a navigation blocker
1271 * @param key The identifier for the blocker
1272 * @param fn The blocker function implementation
1273 */
1274 getBlocker(key: string, fn: BlockerFunction): Blocker;
1275 /**
1276 * @private
1277 * PRIVATE - DO NOT USE
1278 *
1279 * Delete a navigation blocker
1280 * @param key The identifier for the blocker
1281 */
1282 deleteBlocker(key: string): void;
1283 /**
1284 * @private
1285 * PRIVATE DO NOT USE
1286 *
1287 * Patch additional children routes into an existing parent route
1288 * @param routeId The parent route id or a callback function accepting `patch`
1289 * to perform batch patching
1290 * @param children The additional children routes
1291 * @param unstable_allowElementMutations Allow mutation or route elements on
1292 * existing routes. Intended for RSC-usage
1293 * only.
1294 */
1295 patchRoutes(routeId: string | null, children: RouteObject[], unstable_allowElementMutations?: boolean): void;
1296 /**
1297 * @private
1298 * PRIVATE - DO NOT USE
1299 *
1300 * HMR needs to pass in-flight route updates to React Router
1301 * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)
1302 */
1303 _internalSetRoutes(routes: RouteObject[]): void;
1304 /**
1305 * @private
1306 * PRIVATE - DO NOT USE
1307 *
1308 * Cause subscribers to re-render. This is used to force a re-render.
1309 */
1310 _internalSetStateDoNotUseOrYouWillBreakYourApp(state: Partial<RouterState>): void;
1311 /**
1312 * @private
1313 * PRIVATE - DO NOT USE
1314 *
1315 * Internal fetch AbortControllers accessed by unit tests
1316 */
1317 _internalFetchControllers: Map<string, AbortController>;
1318}
1319/**
1320 * State maintained internally by the router. During a navigation, all states
1321 * reflect the "old" location unless otherwise noted.
1322 */
1323interface RouterState {
1324 /**
1325 * The action of the most recent navigation
1326 */
1327 historyAction: Action;
1328 /**
1329 * The current location reflected by the router
1330 */
1331 location: Location$1;
1332 /**
1333 * The current set of route matches
1334 */
1335 matches: DataRouteMatch[];
1336 /**
1337 * Tracks whether we've completed our initial data load
1338 */
1339 initialized: boolean;
1340 /**
1341 * Tracks whether we should be rendering a HydrateFallback during hydration
1342 */
1343 renderFallback: boolean;
1344 /**
1345 * Current scroll position we should start at for a new view
1346 * - number -> scroll position to restore to
1347 * - false -> do not restore scroll at all (used during submissions/revalidations)
1348 * - null -> don't have a saved position, scroll to hash or top of page
1349 */
1350 restoreScrollPosition: number | false | null;
1351 /**
1352 * Indicate whether this navigation should skip resetting the scroll position
1353 * if we are unable to restore the scroll position
1354 */
1355 preventScrollReset: boolean;
1356 /**
1357 * Tracks the state of the current navigation
1358 */
1359 navigation: Navigation;
1360 /**
1361 * Tracks any in-progress revalidations
1362 */
1363 revalidation: RevalidationState;
1364 /**
1365 * Data from the loaders for the current matches
1366 */
1367 loaderData: RouteData;
1368 /**
1369 * Data from the action for the current matches
1370 */
1371 actionData: RouteData | null;
1372 /**
1373 * Errors caught from loaders for the current matches
1374 */
1375 errors: RouteData | null;
1376 /**
1377 * Map of current fetchers
1378 */
1379 fetchers: Map<string, Fetcher>;
1380 /**
1381 * Map of current blockers
1382 */
1383 blockers: Map<string, Blocker>;
1384}
1385/**
1386 * Data that can be passed into hydrate a Router from SSR
1387 */
1388type HydrationState = Partial<Pick<RouterState, "loaderData" | "actionData" | "errors">>;
1389/**
1390 * Future flags to toggle new feature behavior
1391 */
1392interface FutureConfig {
1393 /** Enables route-pattern matching after calling `unstable_preloadRoutePattern()`. */
1394 unstable_routePatternMatching?: boolean;
1395}
1396/**
1397 * Initialization options for createRouter
1398 */
1399interface RouterInit {
1400 routes: RouteObject[];
1401 history: History;
1402 basename?: string;
1403 getContext?: () => MaybePromise<RouterContextProvider>;
1404 instrumentations?: ClientInstrumentation[];
1405 mapRouteProperties?: MapRoutePropertiesFunction;
1406 future?: Partial<FutureConfig>;
1407 hydrationRouteProperties?: string[];
1408 hydrationData?: HydrationState;
1409 window?: Window;
1410 dataStrategy?: DataStrategyFunction;
1411 patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;
1412}
1413/**
1414 * State returned from a server-side query() call
1415 */
1416interface StaticHandlerContext {
1417 basename: Router$1["basename"];
1418 location: RouterState["location"];
1419 matches: RouterState["matches"];
1420 loaderData: RouterState["loaderData"];
1421 actionData: RouterState["actionData"];
1422 errors: RouterState["errors"];
1423 statusCode: number;
1424 loaderHeaders: Record<string, Headers>;
1425 actionHeaders: Record<string, Headers>;
1426 _deepestRenderedBoundaryId?: string | null;
1427 /** @private */
1428 _match: StaticHandler["match"];
1429}
1430/**
1431 * A StaticHandler instance manages a singular SSR navigation/fetch event
1432 */
1433interface StaticHandler {
1434 /**
1435 * The set of data routes managed by this handler
1436 */
1437 dataRoutes: DataRouteObject[];
1438 /**
1439 * @private
1440 * PRIVATE - DO NOT USE
1441 *
1442 * Match routes against a location using the handler's configured route
1443 * matching implementation.
1444 */
1445 match(locationArg: Partial<Location$1> | string): DataRouteMatch[] | null;
1446 /**
1447 * Perform a query for a given request - executing all matched route
1448 * loaders/actions. Used for document requests.
1449 *
1450 * @param request The request to query
1451 * @param opts Optional query options
1452 * @param opts.dataStrategy Alternate dataStrategy implementation
1453 * @param opts.filterMatchesToLoad Predicate function to filter which matches should be loaded
1454 * @param opts.generateMiddlewareResponse To enable middleware, provide a function
1455 * to generate a response to bubble back up the middleware chain
1456 * @param opts.requestContext Context object to pass to loaders/actions
1457 * @param opts.skipLoaderErrorBubbling Skip loader error bubbling
1458 * @param opts.skipRevalidation Skip revalidation after action submission
1459 * @param opts.normalizePath Normalize the request path
1460 */
1461 query(request: Request, opts?: {
1462 requestContext?: unknown;
1463 filterMatchesToLoad?: (match: DataRouteMatch) => boolean;
1464 skipLoaderErrorBubbling?: boolean;
1465 skipRevalidation?: boolean;
1466 dataStrategy?: DataStrategyFunction<unknown>;
1467 generateMiddlewareResponse?: (query: (r: Request, args?: {
1468 filterMatchesToLoad?: (match: DataRouteMatch) => boolean;
1469 }) => Promise<StaticHandlerContext | Response>) => MaybePromise<Response>;
1470 normalizePath?: (request: Request) => Path;
1471 }): Promise<StaticHandlerContext | Response>;
1472 /**
1473 * Perform a query for a specific route. Used for resource requests.
1474 *
1475 * @param request The request to query
1476 * @param opts Optional queryRoute options
1477 * @param opts.dataStrategy Alternate dataStrategy implementation
1478 * @param opts.generateMiddlewareResponse To enable middleware, provide a function
1479 * to generate a response to bubble back up the middleware chain
1480 * @param opts.requestContext Context object to pass to loaders/actions
1481 * @param opts.routeId The ID of the route to query
1482 * @param opts.normalizePath Normalize the request path
1483 */
1484 queryRoute(request: Request, opts?: {
1485 routeId?: string;
1486 requestContext?: unknown;
1487 dataStrategy?: DataStrategyFunction<unknown>;
1488 generateMiddlewareResponse?: (queryRoute: (r: Request) => Promise<Response>) => MaybePromise<Response>;
1489 normalizePath?: (request: Request) => Path;
1490 }): Promise<any>;
1491}
1492type ViewTransitionOpts = {
1493 currentLocation: Location$1;
1494 nextLocation: Location$1;
1495};
1496/**
1497 * Subscriber function signature for changes to router state
1498 */
1499interface RouterSubscriber {
1500 (state: RouterState, opts: {
1501 deletedFetchers: string[];
1502 newErrors: RouteData | null;
1503 viewTransitionOpts?: ViewTransitionOpts;
1504 flushSync: boolean;
1505 }): void;
1506}
1507/**
1508 * Function signature for determining the key to be used in scroll restoration
1509 * for a given location
1510 */
1511interface GetScrollRestorationKeyFunction {
1512 (location: Location$1, matches: UIMatch[]): string | null;
1513}
1514/**
1515 * Function signature for determining the current scroll position
1516 */
1517interface GetScrollPositionFunction {
1518 (): number;
1519}
1520/**
1521 * - "route": relative to the route hierarchy so `..` means remove all segments
1522 * of the current route even if it has many. For example, a `route("posts/:id")`
1523 * would have both `:id` and `posts` removed from the url.
1524 * - "path": relative to the pathname so `..` means remove one segment of the
1525 * pathname. For example, a `route("posts/:id")` would have only `:id` removed
1526 * from the url.
1527 */
1528type RelativeRoutingType = "route" | "path";
1529type BaseNavigateOrFetchOptions = {
1530 preventScrollReset?: boolean;
1531 relative?: RelativeRoutingType;
1532 flushSync?: boolean;
1533 defaultShouldRevalidate?: boolean;
1534};
1535type BaseNavigateOptions = BaseNavigateOrFetchOptions & {
1536 replace?: boolean;
1537 state?: any;
1538 fromRouteId?: string;
1539 viewTransition?: boolean;
1540 mask?: To;
1541};
1542type BaseSubmissionOptions = {
1543 formMethod?: HTMLFormMethod;
1544 formEncType?: FormEncType;
1545} & ({
1546 formData: FormData;
1547 body?: undefined;
1548} | {
1549 formData?: undefined;
1550 body: any;
1551});
1552/**
1553 * Options for a navigate() call for a normal (non-submission) navigation
1554 */
1555type LinkNavigateOptions = BaseNavigateOptions;
1556/**
1557 * Options for a navigate() call for a submission navigation
1558 */
1559type SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;
1560/**
1561 * Options to pass to navigate() for a navigation
1562 */
1563type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions;
1564/**
1565 * Options for a fetch() load
1566 */
1567type LoadFetchOptions = BaseNavigateOrFetchOptions;
1568/**
1569 * Options for a fetch() submission
1570 */
1571type SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;
1572/**
1573 * Options to pass to fetch()
1574 */
1575type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;
1576/**
1577 * Potential states for state.navigation
1578 */
1579type NavigationStates = {
1580 Idle: {
1581 state: "idle";
1582 location: undefined;
1583 matches: undefined;
1584 historyAction: undefined;
1585 formMethod: undefined;
1586 formAction: undefined;
1587 formEncType: undefined;
1588 formData: undefined;
1589 json: undefined;
1590 text: undefined;
1591 };
1592 Loading: {
1593 state: "loading";
1594 location: Location$1;
1595 matches: DataRouteMatch[];
1596 historyAction: Action;
1597 formMethod: Submission["formMethod"] | undefined;
1598 formAction: Submission["formAction"] | undefined;
1599 formEncType: Submission["formEncType"] | undefined;
1600 formData: Submission["formData"] | undefined;
1601 json: Submission["json"] | undefined;
1602 text: Submission["text"] | undefined;
1603 };
1604 Submitting: {
1605 state: "submitting";
1606 location: Location$1;
1607 matches: DataRouteMatch[];
1608 historyAction: Action;
1609 formMethod: Submission["formMethod"];
1610 formAction: Submission["formAction"];
1611 formEncType: Submission["formEncType"];
1612 formData: Submission["formData"];
1613 json: Submission["json"];
1614 text: Submission["text"];
1615 };
1616};
1617type Navigation = NavigationStates[keyof NavigationStates];
1618type RevalidationState = "idle" | "loading";
1619/**
1620 * Potential states for fetchers
1621 */
1622type FetcherStates<TData = any> = {
1623 /**
1624 * The fetcher is not calling a loader or action
1625 *
1626 * ```tsx
1627 * fetcher.state === "idle"
1628 * ```
1629 */
1630 Idle: {
1631 state: "idle";
1632 formMethod: undefined;
1633 formAction: undefined;
1634 formEncType: undefined;
1635 text: undefined;
1636 formData: undefined;
1637 json: undefined;
1638 /**
1639 * If the fetcher has never been called, this will be undefined.
1640 */
1641 data: TData | undefined;
1642 };
1643 /**
1644 * The fetcher is loading data from a {@link LoaderFunction | loader} from a
1645 * call to {@link FetcherWithComponents.load | `fetcher.load`}.
1646 *
1647 * ```tsx
1648 * // somewhere
1649 * <button onClick={() => fetcher.load("/some/route") }>Load</button>
1650 *
1651 * // the state will update
1652 * fetcher.state === "loading"
1653 * ```
1654 */
1655 Loading: {
1656 state: "loading";
1657 formMethod: Submission["formMethod"] | undefined;
1658 formAction: Submission["formAction"] | undefined;
1659 formEncType: Submission["formEncType"] | undefined;
1660 text: Submission["text"] | undefined;
1661 formData: Submission["formData"] | undefined;
1662 json: Submission["json"] | undefined;
1663 data: TData | undefined;
1664 };
1665 /**
1666 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`}.
1667 ```tsx
1668 // somewhere
1669 <input
1670 onChange={e => {
1671 fetcher.submit(event.currentTarget.form, { method: "post" });
1672 }}
1673 />
1674 // the state will update
1675 fetcher.state === "submitting"
1676 // and formData will be available
1677 fetcher.formData
1678 ```
1679 */
1680 Submitting: {
1681 state: "submitting";
1682 formMethod: Submission["formMethod"];
1683 formAction: Submission["formAction"];
1684 formEncType: Submission["formEncType"];
1685 text: Submission["text"];
1686 formData: Submission["formData"];
1687 json: Submission["json"];
1688 data: TData | undefined;
1689 };
1690};
1691type Fetcher<TData = any> = FetcherStates<TData>[keyof FetcherStates<TData>];
1692interface BlockerBlocked {
1693 state: "blocked";
1694 reset: () => void;
1695 proceed: () => void;
1696 location: Location$1;
1697}
1698interface BlockerUnblocked {
1699 state: "unblocked";
1700 reset: undefined;
1701 proceed: undefined;
1702 location: undefined;
1703}
1704interface BlockerProceeding {
1705 state: "proceeding";
1706 reset: undefined;
1707 proceed: undefined;
1708 location: Location$1;
1709}
1710type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;
1711type BlockerFunction = (args: {
1712 currentLocation: Location$1;
1713 nextLocation: Location$1;
1714 historyAction: Action;
1715}) => boolean;
1716interface CreateStaticHandlerOptions {
1717 basename?: string;
1718 mapRouteProperties?: MapRoutePropertiesFunction;
1719 instrumentations?: Pick<ServerInstrumentation, "route">[];
1720 future?: Partial<FutureConfig>;
1721}
1722/**
1723 * Create a static handler to perform server-side data loading
1724 *
1725 * @example
1726 * export async function handleRequest(request: Request) {
1727 * let { query, dataRoutes } = createStaticHandler(routes);
1728 * let context = await query(request);
1729 *
1730 * if (context instanceof Response) {
1731 * return context;
1732 * }
1733 *
1734 * let router = createStaticRouter(dataRoutes, context);
1735 * return new Response(
1736 * ReactDOMServer.renderToString(<StaticRouterProvider ... />),
1737 * { headers: { "Content-Type": "text/html" } }
1738 * );
1739 * }
1740 *
1741 * @public
1742 * @category Data Routers
1743 * @mode data
1744 * @param routes The {@link RouteObject | route objects} to create a static
1745 * handler for
1746 * @param opts Options
1747 * @param opts.basename The base URL for the static handler (default: `/`)
1748 * @param opts.future Future flags for the static handler
1749 * @returns A static handler that can be used to query data for the provided
1750 * routes
1751 */
1752declare function createStaticHandler(routes: RouteObject[], opts?: CreateStaticHandlerOptions): StaticHandler;
1753//#endregion
1754//#region lib/router/links.d.ts
1755type Primitive = null | undefined | string | number | boolean | symbol | bigint;
1756type LiteralUnion<LiteralType, BaseType extends Primitive> = LiteralType | (BaseType & Record<never, never>);
1757interface HtmlLinkProps {
1758 /**
1759 * Address of the hyperlink
1760 */
1761 href?: string;
1762 /**
1763 * How the element handles crossorigin requests
1764 */
1765 crossOrigin?: "anonymous" | "use-credentials";
1766 /**
1767 * Relationship between the document containing the hyperlink and the destination resource
1768 */
1769 rel: LiteralUnion<"alternate" | "dns-prefetch" | "icon" | "manifest" | "modulepreload" | "next" | "pingback" | "preconnect" | "prefetch" | "preload" | "prerender" | "search" | "stylesheet", string>;
1770 /**
1771 * Applicable media: "screen", "print", "(max-width: 764px)"
1772 */
1773 media?: string;
1774 /**
1775 * Integrity metadata used in Subresource Integrity checks
1776 */
1777 integrity?: string;
1778 /**
1779 * Language of the linked resource
1780 */
1781 hrefLang?: string;
1782 /**
1783 * Hint for the type of the referenced resource
1784 */
1785 type?: string;
1786 /**
1787 * Referrer policy for fetches initiated by the element
1788 */
1789 referrerPolicy?: "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
1790 /**
1791 * Sizes of the icons (for rel="icon")
1792 */
1793 sizes?: string;
1794 /**
1795 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
1796 */
1797 as?: LiteralUnion<"audio" | "audioworklet" | "document" | "embed" | "fetch" | "font" | "frame" | "iframe" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt", string>;
1798 /**
1799 * Color to use when customizing a site's icon (for rel="mask-icon")
1800 */
1801 color?: string;
1802 /**
1803 * Whether the link is disabled
1804 */
1805 disabled?: boolean;
1806 /**
1807 * The title attribute has special semantics on this element: Title of the link; CSS style sheet set name.
1808 */
1809 title?: string;
1810 /**
1811 * Images to use in different situations, e.g., high-resolution displays,
1812 * small monitors, etc. (for rel="preload")
1813 */
1814 imageSrcSet?: string;
1815 /**
1816 * Image sizes for different page layouts (for rel="preload")
1817 */
1818 imageSizes?: string;
1819}
1820interface HtmlLinkPreloadImage extends HtmlLinkProps {
1821 /**
1822 * Relationship between the document containing the hyperlink and the destination resource
1823 */
1824 rel: "preload";
1825 /**
1826 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
1827 */
1828 as: "image";
1829 /**
1830 * Address of the hyperlink
1831 */
1832 href?: string;
1833 /**
1834 * Images to use in different situations, e.g., high-resolution displays,
1835 * small monitors, etc. (for rel="preload")
1836 */
1837 imageSrcSet: string;
1838 /**
1839 * Image sizes for different page layouts (for rel="preload")
1840 */
1841 imageSizes?: string;
1842}
1843/**
1844 * Represents a `<link>` element.
1845 *
1846 * WHATWG Specification: https://html.spec.whatwg.org/multipage/semantics.html#the-link-element
1847 */
1848type HtmlLinkDescriptor = (HtmlLinkProps & Pick<Required<HtmlLinkProps>, "href">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "imageSizes">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "href"> & {
1849 imageSizes?: never;
1850});
1851interface PageLinkDescriptor extends Omit<HtmlLinkDescriptor, "href" | "rel" | "type" | "sizes" | "imageSrcSet" | "imageSizes" | "as" | "color" | "title"> {
1852 /**
1853 * A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
1854 * attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
1855 * element. If not provided in Framework Mode, it will default to any
1856 * {@link ServerRouter | `<ServerRouter nonce>`} prop.
1857 */
1858 nonce?: string | undefined;
1859 /**
1860 * The absolute path of the page to prefetch, e.g. `/absolute/path`.
1861 */
1862 page: string;
1863}
1864type LinkDescriptor = HtmlLinkDescriptor | PageLinkDescriptor;
1865//#endregion
1866//#region lib/server-runtime/single-fetch.d.ts
1867type Serializable = undefined | null | boolean | string | symbol | number | Array<Serializable> | {
1868 [key: PropertyKey]: Serializable;
1869} | bigint | Date | URL | RegExp | Error | Map<Serializable, Serializable> | Set<Serializable> | Promise<Serializable>;
1870//#endregion
1871//#region lib/types/utils.d.ts
1872type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
1873type IsAny<T> = 0 extends 1 & T ? true : false;
1874type Func = (...args: any[]) => unknown;
1875//#endregion
1876//#region lib/types/serializes-to.d.ts
1877/**
1878 * A brand that can be applied to a type to indicate that it will serialize
1879 * to a specific type when transported to the client from a loader.
1880 * Only use this if you have additional serialization/deserialization logic
1881 * in your application.
1882 */
1883type unstable_SerializesTo<T> = {
1884 unstable__ReactRouter_SerializesTo: [T];
1885};
1886//#endregion
1887//#region lib/types/route-data.d.ts
1888type 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;
1889type VoidToUndefined<T> = Equal<T, void> extends true ? undefined : T;
1890type DataFrom<T> = IsAny<T> extends true ? undefined : T extends Func ? VoidToUndefined<Awaited<ReturnType<T>>> : undefined;
1891type ClientData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? U : T;
1892type ServerData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? Serialize<U> : Serialize<T>;
1893type ServerDataFrom<T> = ServerData<DataFrom<T>>;
1894type ClientDataFrom<T> = ClientData<DataFrom<T>>;
1895type ClientDataFunctionArgs<Params> = {
1896 /**
1897 * 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.
1898 *
1899 * @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.
1900 **/
1901 request: Request;
1902 /**
1903 * A URL instance representing the application location being navigated to or
1904 * fetched.
1905 *
1906 * In Framework mode, this is a normalized URL with React-Router-specific
1907 * implementation details removed (`.data` suffixes, `index`/`_routes` search
1908 * params). For the raw incoming URL, use `request.url`.
1909 */
1910 url: URL;
1911 /**
1912 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
1913 * @example
1914 * // app/routes.ts
1915 * route("teams/:teamId", "./team.tsx"),
1916 *
1917 * // app/team.tsx
1918 * export function clientLoader({
1919 * params,
1920 * }: Route.ClientLoaderArgs) {
1921 * params.teamId;
1922 * // ^ string
1923 * }
1924 **/
1925 params: Params;
1926 /**
1927 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
1928 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
1929 */
1930 pattern: string;
1931 /**
1932 * An instance of `RouterContextProvider` that can be used to access context
1933 * values from your route middlewares. You may pass in initial context values
1934 * in your `<HydratedRouter getContext>` prop.
1935 */
1936 context: Readonly<RouterContextProvider>;
1937};
1938type SerializeFrom<T> = T extends ((...args: infer Args) => unknown) ? Args extends [ClientLoaderFunctionArgs | ClientActionFunctionArgs | ClientDataFunctionArgs<unknown>] ? ClientDataFrom<T> : ServerDataFrom<T> : T;
1939//#endregion
1940//#region lib/dom/ssr/routeModules.d.ts
1941/**
1942 * A function that handles data mutations for a route on the client
1943 */
1944type ClientActionFunction = (args: ClientActionFunctionArgs) => ReturnType<ActionFunction>;
1945/**
1946 * Arguments passed to a route `clientAction` function
1947 */
1948type ClientActionFunctionArgs = ActionFunctionArgs & {
1949 serverAction: <T = unknown>() => Promise<SerializeFrom<T>>;
1950};
1951/**
1952 * A function that loads data for a route on the client
1953 */
1954type ClientLoaderFunction = ((args: ClientLoaderFunctionArgs) => ReturnType<LoaderFunction>) & {
1955 hydrate?: boolean;
1956};
1957/**
1958 * Arguments passed to a route `clientLoader` function
1959 */
1960type ClientLoaderFunctionArgs = LoaderFunctionArgs & {
1961 serverLoader: <T = unknown>() => Promise<SerializeFrom<T>>;
1962};
1963type HeadersArgs = {
1964 loaderHeaders: Headers;
1965 parentHeaders: Headers;
1966 actionHeaders: Headers;
1967 errorHeaders: Headers | undefined;
1968};
1969/**
1970 * A function that returns HTTP headers to be used for a route. These headers
1971 * will be merged with (and take precedence over) headers from parent routes.
1972 */
1973interface HeadersFunction {
1974 (args: HeadersArgs): Headers | HeadersInit;
1975}
1976/**
1977 * A function that defines `<link>` tags to be inserted into the `<head>` of
1978 * the document on route transitions.
1979 *
1980 * @see https://reactrouter.com/start/framework/route-module#meta
1981 */
1982interface LinksFunction {
1983 (): LinkDescriptor[];
1984}
1985interface MetaMatch<RouteId extends string = string, Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown> {
1986 id: RouteId;
1987 pathname: DataRouteMatch["pathname"];
1988 loaderData: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
1989 handle?: RouteHandle;
1990 params: DataRouteMatch["params"];
1991 meta: MetaDescriptor[];
1992 error?: unknown;
1993}
1994type 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]>;
1995interface MetaArgs<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
1996 loaderData: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
1997 params: Params;
1998 location: Location$1;
1999 matches: MetaMatches<MatchLoaders>;
2000 error?: unknown;
2001}
2002/**
2003 * A function that returns an array of data objects to use for rendering
2004 * metadata HTML tags in a route. These tags are not rendered on descendant
2005 * routes in the route hierarchy. In other words, they will only be rendered on
2006 * the route in which they are exported.
2007 *
2008 * @param Loader - The type of the current route's loader function
2009 * @param MatchLoaders - Mapping from a parent route's filepath to its loader
2010 * function type
2011 *
2012 * Note that parent route filepaths are relative to the `app/` directory.
2013 *
2014 * For example, if this meta function is for `/sales/customers/$customerId`:
2015 *
2016 * ```ts
2017 * // app/root.tsx
2018 * const loader = () => ({ hello: "world" })
2019 * export type Loader = typeof loader
2020 *
2021 * // app/routes/sales.tsx
2022 * const loader = () => ({ salesCount: 1074 })
2023 * export type Loader = typeof loader
2024 *
2025 * // app/routes/sales/customers.tsx
2026 * const loader = () => ({ customerCount: 74 })
2027 * export type Loader = typeof loader
2028 *
2029 * // app/routes/sales/customers/$customersId.tsx
2030 * import type { Loader as RootLoader } from "../../../root"
2031 * import type { Loader as SalesLoader } from "../../sales"
2032 * import type { Loader as CustomersLoader } from "../../sales/customers"
2033 *
2034 * const loader = () => ({ name: "Customer name" })
2035 *
2036 * const meta: MetaFunction<typeof loader, {
2037 * "root": RootLoader,
2038 * "routes/sales": SalesLoader,
2039 * "routes/sales/customers": CustomersLoader,
2040 * }> = ({ loaderData, matches }) => {
2041 * const { name } = loaderData
2042 * // ^? string
2043 * const { customerCount } = matches.find((match) => match.id === "routes/sales/customers").loaderData
2044 * // ^? number
2045 * const { salesCount } = matches.find((match) => match.id === "routes/sales").loaderData
2046 * // ^? number
2047 * const { hello } = matches.find((match) => match.id === "root").loaderData
2048 * // ^? "world"
2049 * }
2050 * ```
2051 */
2052interface MetaFunction<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
2053 (args: MetaArgs<Loader, MatchLoaders>): MetaDescriptor[] | undefined;
2054}
2055type MetaDescriptor = {
2056 charSet: "utf-8";
2057} | {
2058 title: string;
2059} | {
2060 name: string;
2061 content: string;
2062} | {
2063 property: string;
2064 content: string;
2065} | {
2066 httpEquiv: string;
2067 content: string;
2068} | {
2069 "script:ld+json": LdJsonObject | LdJsonObject[];
2070} | {
2071 tagName: "meta" | "link";
2072 [name: string]: string;
2073} | {
2074 [name: string]: unknown;
2075};
2076type LdJsonObject = { [Key in string]: LdJsonValue } & { [Key in string]?: LdJsonValue | undefined };
2077type LdJsonArray = LdJsonValue[] | readonly LdJsonValue[];
2078type LdJsonPrimitive = string | number | boolean | null;
2079type LdJsonValue = LdJsonPrimitive | LdJsonObject | LdJsonArray;
2080/**
2081 * A React component that is rendered for a route.
2082 */
2083/**
2084 * An arbitrary object that is associated with a route.
2085 *
2086 * @see https://reactrouter.com/how-to/using-handle
2087 */
2088type RouteHandle = unknown;
2089//#endregion
2090//#region lib/components.d.ts
2091interface AwaitResolveRenderFunction<Resolve = any> {
2092 (data: Awaited<Resolve>): React.ReactNode;
2093}
2094/**
2095 * @category Types
2096 */
2097interface AwaitProps<Resolve> {
2098 /**
2099 * When using a function, the resolved value is provided as the parameter.
2100 *
2101 * ```tsx [2]
2102 * <Await resolve={reviewsPromise}>
2103 * {(resolvedReviews) => <Reviews items={resolvedReviews} />}
2104 * </Await>
2105 * ```
2106 *
2107 * When using React elements, {@link useAsyncValue} will provide the
2108 * resolved value:
2109 *
2110 * ```tsx [2]
2111 * <Await resolve={reviewsPromise}>
2112 * <Reviews />
2113 * </Await>
2114 *
2115 * function Reviews() {
2116 * const resolvedReviews = useAsyncValue();
2117 * return <div>...</div>;
2118 * }
2119 * ```
2120 */
2121 children: React.ReactNode | AwaitResolveRenderFunction<Resolve>;
2122 /**
2123 * The error element renders instead of the `children` when the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
2124 * rejects.
2125 *
2126 * ```tsx
2127 * <Await
2128 * errorElement={<div>Oops</div>}
2129 * resolve={reviewsPromise}
2130 * >
2131 * <Reviews />
2132 * </Await>
2133 * ```
2134 *
2135 * To provide a more contextual error, you can use the {@link useAsyncError} in a
2136 * child component
2137 *
2138 * ```tsx
2139 * <Await
2140 * errorElement={<ReviewsError />}
2141 * resolve={reviewsPromise}
2142 * >
2143 * <Reviews />
2144 * </Await>
2145 *
2146 * function ReviewsError() {
2147 * const error = useAsyncError();
2148 * return <div>Error loading reviews: {error.message}</div>;
2149 * }
2150 * ```
2151 *
2152 * If you do not provide an `errorElement`, the rejected value will bubble up
2153 * to the nearest route-level [`ErrorBoundary`](../../start/framework/route-module#errorboundary)
2154 * and be accessible via the {@link useRouteError} hook.
2155 */
2156 errorElement?: React.ReactNode;
2157 /**
2158 * Takes a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
2159 * returned from a [`loader`](../../start/framework/route-module#loader) to be
2160 * resolved and rendered.
2161 *
2162 * ```tsx
2163 * import { Await, useLoaderData } from "react-router";
2164 *
2165 * export async function loader() {
2166 * let reviews = getReviews(); // not awaited
2167 * let book = await getBook();
2168 * return {
2169 * book,
2170 * reviews, // this is a promise
2171 * };
2172 * }
2173 *
2174 * export default function Book() {
2175 * const {
2176 * book,
2177 * reviews, // this is the same promise
2178 * } = useLoaderData();
2179 *
2180 * return (
2181 * <div>
2182 * <h1>{book.title}</h1>
2183 * <p>{book.description}</p>
2184 * <React.Suspense fallback={<ReviewsSkeleton />}>
2185 * <Await
2186 * // and is the promise we pass to Await
2187 * resolve={reviews}
2188 * >
2189 * <Reviews />
2190 * </Await>
2191 * </React.Suspense>
2192 * </div>
2193 * );
2194 * }
2195 * ```
2196 */
2197 resolve: Resolve;
2198}
2199/**
2200 * Used to render promise values with automatic error handling.
2201 *
2202 * **Note:** `<Await>` expects to be rendered inside a [`<React.Suspense>`](https://react.dev/reference/react/Suspense)
2203 *
2204 * @example
2205 * import { Await, useLoaderData } from "react-router";
2206 *
2207 * export async function loader() {
2208 * // not awaited
2209 * const reviews = getReviews();
2210 * // awaited (blocks the transition)
2211 * const book = await fetch("/api/book").then((res) => res.json());
2212 * return { book, reviews };
2213 * }
2214 *
2215 * function Book() {
2216 * const { book, reviews } = useLoaderData();
2217 * return (
2218 * <div>
2219 * <h1>{book.title}</h1>
2220 * <p>{book.description}</p>
2221 * <React.Suspense fallback={<ReviewsSkeleton />}>
2222 * <Await
2223 * resolve={reviews}
2224 * errorElement={
2225 * <div>Could not load reviews 😬</div>
2226 * }
2227 * children={(resolvedReviews) => (
2228 * <Reviews items={resolvedReviews} />
2229 * )}
2230 * />
2231 * </React.Suspense>
2232 * </div>
2233 * );
2234 * }
2235 *
2236 * @public
2237 * @category Components
2238 * @mode framework
2239 * @mode data
2240 * @param props Props
2241 * @param {AwaitProps.children} props.children n/a
2242 * @param {AwaitProps.errorElement} props.errorElement n/a
2243 * @param {AwaitProps.resolve} props.resolve n/a
2244 * @returns React element for the rendered awaited value
2245 */
2246declare function Await$1<Resolve>({
2247 children,
2248 errorElement,
2249 resolve
2250}: AwaitProps<Resolve>): React.JSX.Element;
2251//#endregion
2252//#region lib/rsc/server.rsc.d.ts
2253declare function getRequest(): Request;
2254declare const redirect: typeof redirect$1;
2255declare const redirectDocument: typeof redirectDocument$1;
2256declare const replace$1: typeof replace$2;
2257declare const Await: typeof Await$1;
2258type RSCRouteConfigEntryBase = {
2259 action?: ActionFunction;
2260 clientAction?: ClientActionFunction;
2261 clientLoader?: ClientLoaderFunction;
2262 ErrorBoundary?: React.ComponentType<any>;
2263 handle?: any;
2264 headers?: HeadersFunction;
2265 HydrateFallback?: React.ComponentType<any>;
2266 Layout?: React.ComponentType<any>;
2267 links?: LinksFunction;
2268 loader?: LoaderFunction;
2269 meta?: MetaFunction;
2270 shouldRevalidate?: ShouldRevalidateFunction;
2271};
2272type RSCRouteConfigEntry = RSCRouteConfigEntryBase & {
2273 id: string;
2274 path?: string;
2275 Component?: React.ComponentType<any>;
2276 lazy?: () => Promise<RSCRouteConfigEntryBase & ({
2277 default?: React.ComponentType<any>;
2278 Component?: never;
2279 } | {
2280 default?: never;
2281 Component?: React.ComponentType<any>;
2282 })>;
2283} & ({
2284 index: true;
2285} | {
2286 children?: RSCRouteConfigEntry[];
2287});
2288type RSCRouteConfig = Array<RSCRouteConfigEntry>;
2289type RSCRouteManifest = {
2290 clientAction?: ClientActionFunction;
2291 clientLoader?: ClientLoaderFunction;
2292 element?: React.ReactElement | false;
2293 errorElement?: React.ReactElement;
2294 handle?: any;
2295 hasAction: boolean;
2296 hasComponent: boolean;
2297 hasLoader: boolean;
2298 hydrateFallbackElement?: React.ReactElement;
2299 id: string;
2300 index?: boolean;
2301 links?: LinksFunction;
2302 meta?: MetaFunction;
2303 parentId?: string;
2304 path?: string;
2305 shouldRevalidate?: ShouldRevalidateFunction;
2306};
2307type RSCRouteMatch = RSCRouteManifest & {
2308 params: Params;
2309 pathname: string;
2310 pathnameBase: string;
2311};
2312type RSCRenderPayload = {
2313 type: "render";
2314 actionData: Record<string, any> | null;
2315 basename: string | undefined;
2316 clientVersion?: string;
2317 errors: Record<string, any> | null;
2318 loaderData: Record<string, any>;
2319 location: Location$1;
2320 routeDiscovery: RouteDiscovery;
2321 matches: RSCRouteMatch[];
2322 patches?: Promise<RSCRouteManifest[]>;
2323 formState?: ReactFormState;
2324};
2325type RSCManifestPayload = {
2326 type: "manifest";
2327 patches: Promise<RSCRouteManifest[]>;
2328};
2329type RSCActionPayload = {
2330 type: "action";
2331 actionResult: Promise<unknown>;
2332 rerender?: Promise<RSCRenderPayload | RSCRedirectPayload>;
2333};
2334type RSCRedirectPayload = {
2335 type: "redirect";
2336 status: number;
2337 location: string;
2338 replace: boolean;
2339 reload: boolean;
2340 actionResult?: Promise<unknown>;
2341};
2342type RSCPayload = RSCRenderPayload | RSCManifestPayload | RSCActionPayload | RSCRedirectPayload;
2343type RSCMatch = {
2344 statusCode: number;
2345 headers: Headers;
2346 payload: RSCPayload;
2347};
2348type DecodeActionFunction = (formData: FormData) => Promise<() => Promise<unknown>>;
2349type DecodeFormStateFunction = (result: unknown, formData: FormData) => Promise<ReactFormState | undefined>;
2350type DecodeReplyFunction = (reply: FormData | string, options: {
2351 temporaryReferences: unknown;
2352}) => Promise<unknown[]>;
2353type LoadServerActionFunction = (id: string) => Promise<Function>;
2354type RouteDiscovery = {
2355 mode: "lazy";
2356 manifestPath?: string | undefined;
2357} | {
2358 mode: "initial";
2359};
2360/**
2361 * Matches the given routes to a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
2362 * and returns an [RSC](https://react.dev/reference/rsc/server-components)
2363 * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2364 * encoding an {@link unstable_RSCPayload} for consumption by an [RSC](https://react.dev/reference/rsc/server-components)
2365 * enabled client router.
2366 *
2367 * Treat every React Server Function as a public endpoint. Server Functions are
2368 * not inherently associated with a route. Any route middleware that runs is
2369 * selected from the URL used to call a Server Function, but the client controls
2370 * both the Server Function identifier and the URL. Perform all access control
2371 * checks within each Server Function, or use a route action for
2372 * middleware-driven access control.
2373 *
2374 * @example
2375 * import {
2376 * createTemporaryReferenceSet,
2377 * decodeAction,
2378 * decodeReply,
2379 * loadServerAction,
2380 * renderToReadableStream,
2381 * } from "@vitejs/plugin-rsc/rsc";
2382 * import { unstable_matchRSCServerRequest as matchRSCServerRequest } from "react-router";
2383 *
2384 * matchRSCServerRequest({
2385 * createTemporaryReferenceSet,
2386 * decodeAction,
2387 * decodeFormState,
2388 * decodeReply,
2389 * loadServerAction,
2390 * request,
2391 * routes: routes(),
2392 * generateResponse(match) {
2393 * return new Response(
2394 * renderToReadableStream(match.payload),
2395 * {
2396 * status: match.statusCode,
2397 * headers: match.headers,
2398 * }
2399 * );
2400 * },
2401 * });
2402 *
2403 * @name unstable_matchRSCServerRequest
2404 * @public
2405 * @category RSC
2406 * @mode data
2407 * @param opts Options
2408 * @param opts.allowedActionOrigins Origin patterns that are allowed to execute actions.
2409 * @param opts.basename The basename to use when matching the request.
2410 * @param opts.createTemporaryReferenceSet A function that returns a temporary
2411 * reference set for the request, used to track temporary references in the [RSC](https://react.dev/reference/rsc/server-components)
2412 * stream.
2413 * @param opts.decodeAction Your `react-server-dom-xyz/server`'s `decodeAction`
2414 * function, responsible for loading a server action.
2415 * @param opts.decodeFormState A function responsible for decoding form state for
2416 * progressively enhanceable forms with React's [`useActionState`](https://react.dev/reference/react/useActionState)
2417 * using your `react-server-dom-xyz/server`'s `decodeFormState`.
2418 * @param opts.decodeReply Your `react-server-dom-xyz/server`'s `decodeReply`
2419 * function, used to decode the server function's arguments and bind them to the
2420 * implementation for invocation by the router.
2421 * @param opts.generateResponse A function responsible for using your
2422 * `renderToReadableStream` to generate a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2423 * encoding the {@link unstable_RSCPayload}.
2424 * @param opts.loadServerAction Your `react-server-dom-xyz/server`'s
2425 * `loadServerAction` function, used to load a server action by ID.
2426 * @param opts.clientVersion A version derived from the client build output used
2427 * to detect stale clients during lazy route discovery.
2428 * @param opts.onError An optional error handler that will be called with any
2429 * errors that occur during the request processing.
2430 * @param opts.request The [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
2431 * to match against.
2432 * @param opts.requestContext An instance of {@link RouterContextProvider}
2433 * that should be created per request, to be passed to [`action`](../../start/data/route-object#action)s,
2434 * [`loader`](../../start/data/route-object#loader)s and [middleware](../../how-to/middleware).
2435 * @param opts.routeDiscovery The route discovery configuration, used to determine how the router should discover new routes during navigations.
2436 * @param opts.routes Your {@link unstable_RSCRouteConfigEntry | route definitions}.
2437 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2438 * that contains the [RSC](https://react.dev/reference/rsc/server-components)
2439 * data for hydration.
2440 */
2441declare function matchRSCServerRequest({
2442 allowedActionOrigins,
2443 createTemporaryReferenceSet,
2444 basename,
2445 decodeReply,
2446 requestContext,
2447 routeDiscovery,
2448 loadServerAction,
2449 decodeAction,
2450 decodeFormState,
2451 clientVersion,
2452 onError,
2453 request,
2454 routes,
2455 generateResponse
2456}: {
2457 allowedActionOrigins?: string[];
2458 createTemporaryReferenceSet: () => unknown;
2459 basename?: string;
2460 decodeReply?: DecodeReplyFunction;
2461 decodeAction?: DecodeActionFunction;
2462 decodeFormState?: DecodeFormStateFunction;
2463 requestContext?: RouterContextProvider;
2464 loadServerAction?: LoadServerActionFunction;
2465 clientVersion?: string;
2466 onError?: (error: unknown) => void;
2467 request: Request;
2468 routes: RSCRouteConfigEntry[];
2469 routeDiscovery?: RouteDiscovery;
2470 generateResponse: (match: RSCMatch, {
2471 onError,
2472 temporaryReferences
2473 }: {
2474 onError(error: unknown): string | undefined;
2475 temporaryReferences: unknown;
2476 }) => Response;
2477}): Promise<Response>;
2478//#endregion
2479//#region lib/types/register.d.ts
2480/**
2481 * Apps can use this interface to "register" app-wide types for React Router via interface declaration merging and module augmentation.
2482 * React Router should handle this for you via type generation.
2483 *
2484 * For more on declaration merging and module augmentation, see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation .
2485 */
2486interface Register {}
2487type AnyParams = Record<string, string | undefined>;
2488type AnyPages = Record<string, {
2489 params: AnyParams;
2490}>;
2491type Pages = Register extends {
2492 pages: infer Registered extends AnyPages;
2493} ? Registered : AnyPages;
2494//#endregion
2495//#region lib/href.d.ts
2496type Args = { [K in keyof Pages]: ToArgs<Pages[K]["params"]> };
2497type ToArgs<Params extends Record<string, string | undefined>> = Equal<Params, {}> extends true ? [] : Partial<Params> extends Params ? [Params] | [] : [Params];
2498/**
2499 * Returns a resolved URL path for the specified route.
2500 *
2501 * Param values are percent-encoded for use in a path segment: characters that
2502 * would change the URL structure (`/`, `?`, `#`, `%`, whitespace, non-ASCII)
2503 * are escaped, while characters that RFC 3986 allows literally in a path
2504 * segment (`$ & + , ; = : @`) are kept as-is. Note this differs from query-string
2505 * encoding (`encodeURIComponent`/`URLSearchParams`), where those characters are
2506 * delimiters and must be escaped. Splat (`*`) values are encoded per segment,
2507 * preserving `/` separators.
2508 *
2509 * See [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3)
2510 *
2511 * @example
2512 * const h = href("/:lang?/about", { lang: "en" })
2513 * // -> `/en/about`
2514 *
2515 * <Link to={href("/products/:id", { id: "abc123" })} />
2516 *
2517 * @public
2518 * @category Utils
2519 * @mode framework
2520 * @param path The route path to resolve
2521 * @param args The route params to use when resolving the path
2522 * @returns The resolved URL path
2523 */
2524declare function href<Path extends keyof Args>(path: Path, ...args: Args[Path]): string;
2525//#endregion
2526//#region lib/server-runtime/cookies.d.ts
2527interface CookieSignatureOptions {
2528 /**
2529 * An array of secrets that may be used to sign/unsign the value of a cookie.
2530 *
2531 * The array makes it easy to rotate secrets. New secrets should be added to
2532 * the beginning of the array. `cookie.serialize()` will always use the first
2533 * value in the array, but `cookie.parse()` may use any of them so that
2534 * cookies that were signed with older secrets still work.
2535 */
2536 secrets?: string[];
2537}
2538type CookieOptions = CookieParseOptions & CookieSerializeOptions & CookieSignatureOptions;
2539/**
2540 * A HTTP cookie.
2541 *
2542 * A Cookie is a logical container for metadata about a HTTP cookie; its name
2543 * and options. But it doesn't contain a value. Instead, it has `parse()` and
2544 * `serialize()` methods that allow a single instance to be reused for
2545 * parsing/encoding multiple different values.
2546 *
2547 * @see https://remix.run/utils/cookies#cookie-api
2548 */
2549interface Cookie {
2550 /**
2551 * The name of the cookie, used in the `Cookie` and `Set-Cookie` headers.
2552 */
2553 readonly name: string;
2554 /**
2555 * True if this cookie uses one or more secrets for verification.
2556 */
2557 readonly isSigned: boolean;
2558 /**
2559 * The Date this cookie expires.
2560 *
2561 * Note: This is calculated at access time using `maxAge` when no `expires`
2562 * option is provided to `createCookie()`.
2563 */
2564 readonly expires?: Date;
2565 /**
2566 * Parses a raw `Cookie` header and returns the value of this cookie or
2567 * `null` if it's not present.
2568 */
2569 parse(cookieHeader: string | null, options?: CookieParseOptions): Promise<any>;
2570 /**
2571 * Serializes the given value to a string and returns the `Set-Cookie`
2572 * header.
2573 */
2574 serialize(value: any, options?: CookieSerializeOptions): Promise<string>;
2575}
2576/**
2577 * Creates a logical container for managing a browser cookie from the server.
2578 *
2579 * @public
2580 * @category Utils
2581 * @mode framework
2582 * @mode data
2583 * @param name The name of the cookie.
2584 * @param cookieOptions Options for parsing and serializing the cookie.
2585 * @returns A {@link Cookie} object for parsing and serializing the cookie.
2586 */
2587declare const createCookie: (name: string, cookieOptions?: CookieOptions) => Cookie;
2588/**
2589 * A function that determines whether a value is a React Router {@link Cookie}
2590 * object.
2591 *
2592 * @public
2593 * @category Utils
2594 * @mode framework
2595 * @mode data
2596 * @param object The value to check.
2597 * @returns `true` if the value is a React Router {@link Cookie} object;
2598 * otherwise, `false`.
2599 */
2600type IsCookieFunction = (object: any) => object is Cookie;
2601/**
2602 * Returns `true` if a value is a React Router {@link Cookie} object.
2603 *
2604 * @public
2605 * @category Utils
2606 * @mode framework
2607 * @mode data
2608 * @param object The value to check.
2609 * @returns `true` if the value is a React Router {@link Cookie} object;
2610 * otherwise, `false`.
2611 */
2612declare const isCookie: IsCookieFunction;
2613//#endregion
2614//#region lib/server-runtime/sessions.d.ts
2615/**
2616 * An object of name/value pairs to be used in the session.
2617 */
2618interface SessionData {
2619 [name: string]: any;
2620}
2621/**
2622 * Session persists data across HTTP requests.
2623 *
2624 * @see https://reactrouter.com/explanation/sessions-and-cookies#sessions
2625 */
2626interface Session<Data = SessionData, FlashData = Data> {
2627 /**
2628 * A unique identifier for this session.
2629 *
2630 * Note: This will be the empty string for newly created sessions and
2631 * sessions that are not backed by a database (i.e. cookie-based sessions).
2632 */
2633 readonly id: string;
2634 /**
2635 * The raw data contained in this session.
2636 *
2637 * This is useful mostly for SessionStorage internally to access the raw
2638 * session data to persist.
2639 */
2640 readonly data: FlashSessionData<Data, FlashData>;
2641 /**
2642 * Returns `true` if the session has a value for the given `name`, `false`
2643 * otherwise.
2644 */
2645 has(name: (keyof Data | keyof FlashData) & string): boolean;
2646 /**
2647 * Returns the value for the given `name` in this session.
2648 */
2649 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;
2650 /**
2651 * Sets a value in the session for the given `name`.
2652 */
2653 set<Key extends keyof Data & string>(name: Key, value: Data[Key]): void;
2654 /**
2655 * Sets a value in the session that is only valid until the next `get()`.
2656 * This can be useful for temporary values, like error messages.
2657 */
2658 flash<Key extends keyof FlashData & string>(name: Key, value: FlashData[Key]): void;
2659 /**
2660 * Removes a value from the session.
2661 */
2662 unset(name: keyof Data & string): void;
2663}
2664type FlashSessionData<Data, FlashData> = Partial<Data & { [Key in keyof FlashData as FlashDataKey<Key & string>]: FlashData[Key] }>;
2665type FlashDataKey<Key extends string> = `__flash_${Key}__`;
2666type CreateSessionFunction = <Data = SessionData, FlashData = Data>(initialData?: Data, id?: string) => Session<Data, FlashData>;
2667/**
2668 * Creates a new Session object.
2669 *
2670 * Note: This function is typically not invoked directly by application code.
2671 * Instead, use a `SessionStorage` object's `getSession` method.
2672 *
2673 * @category Utils
2674 * @param initialData The initial data for the session.
2675 * @param id The identifier for the session. Defaults to an empty string for a
2676 * new session.
2677 * @returns A new {@link Session} object.
2678 */
2679declare const createSession: CreateSessionFunction;
2680/**
2681 * A function that determines whether a value is a React Router {@link Session}
2682 * object.
2683 *
2684 * @public
2685 * @category Utils
2686 * @mode framework
2687 * @mode data
2688 * @param object The value to check.
2689 * @returns `true` if the value is a React Router {@link Session} object;
2690 * otherwise, `false`.
2691 */
2692type IsSessionFunction = (object: any) => object is Session;
2693/**
2694 * Returns `true` if a value is a React Router {@link Session} object.
2695 *
2696 * @public
2697 * @category Utils
2698 * @mode framework
2699 * @mode data
2700 * @param object The value to check.
2701 * @returns `true` if the value is a React Router {@link Session} object;
2702 * otherwise, `false`.
2703 */
2704declare const isSession: IsSessionFunction;
2705/**
2706 * SessionStorage stores session data between HTTP requests and knows how to
2707 * parse and create cookies.
2708 *
2709 * A SessionStorage creates Session objects using a `Cookie` header as input.
2710 * Then, later it generates the `Set-Cookie` header to be used in the response.
2711 */
2712interface SessionStorage<Data = SessionData, FlashData = Data> {
2713 /**
2714 * Parses a Cookie header from a HTTP request and returns the associated
2715 * Session. If there is no session associated with the cookie, this will
2716 * return a new Session with no data.
2717 */
2718 getSession: (cookieHeader?: string | null, options?: CookieParseOptions$1) => Promise<Session<Data, FlashData>>;
2719 /**
2720 * Stores all data in the Session and returns the Set-Cookie header to be
2721 * used in the HTTP response.
2722 */
2723 commitSession: (session: Session<Data, FlashData>, options?: CookieSerializeOptions$1) => Promise<string>;
2724 /**
2725 * Deletes all data associated with the Session and returns the Set-Cookie
2726 * header to be used in the HTTP response.
2727 */
2728 destroySession: (session: Session<Data, FlashData>, options?: CookieSerializeOptions$1) => Promise<string>;
2729}
2730/**
2731 * SessionIdStorageStrategy is designed to allow anyone to easily build their
2732 * own SessionStorage using `createSessionStorage(strategy)`.
2733 *
2734 * This strategy describes a common scenario where the session id is stored in
2735 * a cookie but the actual session data is stored elsewhere, usually in a
2736 * database or on disk. A set of create, read, update, and delete operations
2737 * are provided for managing the session data.
2738 */
2739interface SessionIdStorageStrategy<Data = SessionData, FlashData = Data> {
2740 /**
2741 * The Cookie used to store the session id, or options used to automatically
2742 * create one.
2743 */
2744 cookie?: Cookie | (CookieOptions & {
2745 name?: string;
2746 });
2747 /**
2748 * Creates a new record with the given data and returns the session id.
2749 */
2750 createData: (data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<string>;
2751 /**
2752 * Returns data for a given session id, or `null` if there isn't any.
2753 */
2754 readData: (id: string) => Promise<FlashSessionData<Data, FlashData> | null>;
2755 /**
2756 * Updates data for the given session id.
2757 */
2758 updateData: (id: string, data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<void>;
2759 /**
2760 * Deletes data for a given session id from the data store.
2761 */
2762 deleteData: (id: string) => Promise<void>;
2763}
2764/**
2765 * Creates a SessionStorage object using a SessionIdStorageStrategy.
2766 *
2767 * Note: This is a low-level API that should only be used if none of the
2768 * existing session storage options meet your requirements.
2769 *
2770 * @category Utils
2771 * @param strategy The strategy used to store session identifiers and data.
2772 * @returns A {@link SessionStorage} object that persists session data using the
2773 * provided strategy.
2774 */
2775declare function createSessionStorage<Data = SessionData, FlashData = Data>({
2776 cookie: cookieArg,
2777 createData,
2778 readData,
2779 updateData,
2780 deleteData
2781}: SessionIdStorageStrategy<Data, FlashData>): SessionStorage<Data, FlashData>;
2782//#endregion
2783//#region lib/server-runtime/sessions/cookieStorage.d.ts
2784interface CookieSessionStorageOptions {
2785 /**
2786 * The Cookie used to store the session data on the client, or options used
2787 * to automatically create one.
2788 */
2789 cookie?: SessionIdStorageStrategy["cookie"];
2790}
2791/**
2792 * Creates and returns a SessionStorage object that stores all session data
2793 * directly in the session cookie itself.
2794 *
2795 * This has the advantage that no database or other backend services are
2796 * needed, and can help to simplify some load-balanced scenarios. However, it
2797 * also has the limitation that serialized session data may not exceed the
2798 * browser's maximum cookie size. Trade-offs!
2799 *
2800 * @public
2801 * @category Utils
2802 * @mode framework
2803 * @mode data
2804 * @param options Options for creating the cookie-backed session storage.
2805 * @returns A {@link SessionStorage} object that stores all session data in its
2806 * cookie.
2807 */
2808declare function createCookieSessionStorage<Data = SessionData, FlashData = Data>({
2809 cookie: cookieArg
2810}?: CookieSessionStorageOptions): SessionStorage<Data, FlashData>;
2811//#endregion
2812//#region lib/server-runtime/sessions/memoryStorage.d.ts
2813interface MemorySessionStorageOptions {
2814 /**
2815 * The Cookie used to store the session id on the client, or options used
2816 * to automatically create one.
2817 */
2818 cookie?: SessionIdStorageStrategy["cookie"];
2819}
2820/**
2821 * Creates and returns a simple in-memory SessionStorage object.
2822 *
2823 * Intended for local development and testing. It does not scale beyond a single
2824 * process, and all session data is lost when the server process stops/restarts.
2825 *
2826 * @public
2827 * @category Utils
2828 * @mode framework
2829 * @mode data
2830 * @param options Options for creating the in-memory session storage.
2831 * @returns A {@link SessionStorage} object that stores session data in memory.
2832 */
2833declare function createMemorySessionStorage<Data = SessionData, FlashData = Data>({
2834 cookie
2835}?: MemorySessionStorageOptions): SessionStorage<Data, FlashData>;
2836//#endregion
2837export { 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