UNPKG

64.4 kBTypeScriptView Raw
1import { d as Router, e as RouteModules, D as DataStrategyFunction, T as To, f as NavigateOptions, B as BlockerFunction, g as Blocker, h as SerializeFrom, i as RelativeRoutingType, a as Location, j as ParamParseKey, k as Path, l as PathPattern, m as PathMatch, U as UIMatch, n as Navigation, A as Action, o as Params, p as RouteObject, I as InitialEntry, H as HydrationState, q as IndexRouteObject, r as LoaderFunction, s as ActionFunction, t as MetaFunction, v as LinksFunction, w as NonIndexRouteObject, x as AppLoadContext, y as unstable_RouterContextProvider, z as MiddlewareEnabled, E as unstable_InitialContext, F as Equal, J as ClientActionFunction, K as ClientLoaderFunction, O as HeadersFunction, Q as ShouldRevalidateFunction, V as RouterInit, W as RouterState, X as PatchRoutesOnNavigationFunction, Y as DataRouteObject } from './routeModules-BR2FO0ix.js';
2export { a7 as ActionFunctionArgs, aG as ClientActionFunctionArgs, aH as ClientLoaderFunctionArgs, aC as DataRouteMatch, a8 as DataStrategyFunctionArgs, a9 as DataStrategyMatch, aa as DataStrategyResult, ac as ErrorResponse, a1 as Fetcher, ad as FormEncType, ae as FormMethod, aM as Future, _ as GetScrollPositionFunction, $ as GetScrollRestorationKeyFunction, af as HTMLFormMethod, aI as HeadersArgs, aL as HtmlLinkDescriptor, as as IDLE_BLOCKER, ar as IDLE_FETCHER, aq as IDLE_NAVIGATION, ag as LazyRouteFunction, L as LinkDescriptor, ah as LoaderFunctionArgs, aJ as MetaArgs, M as MetaDescriptor, a2 as NavigationStates, aD as Navigator, aK as PageLinkDescriptor, aE as PatchRoutesOnNavigationFunctionArgs, aj as PathParam, ak as RedirectFunction, a6 as RevalidationState, aF as RouteMatch, a5 as RouterFetchOptions, a4 as RouterNavigateOptions, a3 as RouterSubscriber, am as ShouldRevalidateFunctionArgs, Z as StaticHandler, a0 as StaticHandlerContext, aS as UNSAFE_DataRouterContext, aT as UNSAFE_DataRouterStateContext, ab as UNSAFE_DataWithResponseInit, aR as UNSAFE_ErrorResponseImpl, aU as UNSAFE_FetchersContext, aV as UNSAFE_LocationContext, aW as UNSAFE_NavigationContext, aX as UNSAFE_RouteContext, aY as UNSAFE_ViewTransitionContext, aO as UNSAFE_createBrowserHistory, aQ as UNSAFE_createRouter, aP as UNSAFE_invariant, ao as createPath, at as data, au as generatePath, av as isRouteErrorResponse, aw as matchPath, ax as matchRoutes, ap as parsePath, ay as redirect, az as redirectDocument, aA as replace, aB as resolvePath, ai as unstable_MiddlewareFunction, al as unstable_RouterContext, aN as unstable_SerializesTo, an as unstable_createContext } from './routeModules-BR2FO0ix.js';
3import { A as AssetsManifest, E as EntryContext, F as FutureConfig, R as RouteComponentType, H as HydrateFallbackType, a as ErrorBoundaryType, S as ServerBuild } from './index-react-server-client-Bi_fx8qz.js';
4export { h as Await, b as AwaitProps, V as BrowserRouter, B as BrowserRouterProps, D as DOMRouterOpts, ar as DiscoverBehavior, y as FetcherFormProps, K as FetcherSubmitFunction, a9 as FetcherSubmitOptions, Q as FetcherWithComponents, _ as Form, z as FormProps, as as HandleDataRequestFunction, at as HandleDocumentRequestFunction, au as HandleErrorFunction, W as HashRouter, t as HashRouterProps, u as HistoryRouterProps, I as IndexRouteProps, L as LayoutRouteProps, X as Link, v as LinkProps, am as Links, i as MemoryRouter, M as MemoryRouterOpts, c as MemoryRouterProps, al as Meta, Z as NavLink, w as NavLinkProps, x as NavLinkRenderProps, j as Navigate, N as NavigateProps, k as Outlet, O as OutletProps, aa as ParamKeyValuePair, P as PathRouteProps, aq as PrefetchBehavior, ao as PrefetchPageLinks, l as Route, d as RouteProps, m as Router, e as RouterProps, n as RouterProvider, f as RouterProviderProps, o as Routes, g as RoutesProps, an as Scripts, ap as ScriptsProps, $ as ScrollRestoration, C as ScrollRestorationProps, av as ServerEntryModule, G as SetURLSearchParams, aj as StaticRouter, af as StaticRouterProps, ak as StaticRouterProvider, ag as StaticRouterProviderProps, J as SubmitFunction, ab as SubmitOptions, ad as SubmitTarget, aE as UNSAFE_FrameworkContext, ay as UNSAFE_WithComponentProps, aC as UNSAFE_WithErrorBoundaryProps, aA as UNSAFE_WithHydrateFallbackProps, aF as UNSAFE_createClientRoutes, aG as UNSAFE_createClientRoutesWithHMRRevalidationOptOut, aw as UNSAFE_hydrationRouteProperties, ax as UNSAFE_mapRouteProperties, aH as UNSAFE_shouldHydrateRouteLoader, aI as UNSAFE_useScrollRestoration, az as UNSAFE_withComponentProps, aD as UNSAFE_withErrorBoundaryProps, aB as UNSAFE_withHydrateFallbackProps, ac as URLSearchParamsInit, T as createBrowserRouter, U as createHashRouter, p as createMemoryRouter, q as createRoutesFromChildren, r as createRoutesFromElements, ae as createSearchParams, ah as createStaticHandler, ai as createStaticRouter, s as renderMatches, Y as unstable_HistoryRouter, a7 as unstable_usePrompt, a6 as useBeforeUnload, a4 as useFetcher, a5 as useFetchers, a3 as useFormAction, a0 as useLinkClickHandler, a1 as useSearchParams, a2 as useSubmit, a8 as useViewTransitionState } from './index-react-server-client-Bi_fx8qz.js';
5import * as React from 'react';
6import React__default, { ReactElement } from 'react';
7import { ParseOptions, SerializeOptions } from 'cookie';
8export { ParseOptions as CookieParseOptions, SerializeOptions as CookieSerializeOptions } from 'cookie';
9import { P as Pages } from './register-DiOIlEq5.js';
10export { a as Register } from './register-DiOIlEq5.js';
11import { AsyncLocalStorage } from 'node:async_hooks';
12
13declare const SingleFetchRedirectSymbol: unique symbol;
14declare function getTurboStreamSingleFetchDataStrategy(getRouter: () => Router, manifest: AssetsManifest, routeModules: RouteModules, ssr: boolean, basename: string | undefined): DataStrategyFunction;
15declare function decodeViaTurboStream(body: ReadableStream<Uint8Array>, global: Window | typeof globalThis): Promise<{
16 done: Promise<undefined>;
17 value: unknown;
18}>;
19
20/**
21 * The mode to use when running the server.
22 */
23declare enum ServerMode {
24 Development = "development",
25 Production = "production",
26 Test = "test"
27}
28
29/**
30 * Resolves a URL against the current {@link Location}.
31 *
32 * @example
33 * import { useHref } from "react-router";
34 *
35 * function SomeComponent() {
36 * let href = useHref("some/where");
37 * // "/resolved/some/where"
38 * }
39 *
40 * @public
41 * @category Hooks
42 * @param to The path to resolve
43 * @param options Options
44 * @param options.relative Defaults to `"route"` so routing is relative to the
45 * route tree.
46 * Set to `"path"` to make relative routing operate against path segments.
47 * @returns The resolved href string
48 */
49declare function useHref(to: To, { relative }?: {
50 relative?: RelativeRoutingType;
51}): string;
52/**
53 * Returns `true` if this component is a descendant of a {@link Router}, useful
54 * to ensure a component is used within a {@link Router}.
55 *
56 * @public
57 * @category Hooks
58 * @mode framework
59 * @mode data
60 * @returns Whether the component is within a {@link Router} context
61 */
62declare function useInRouterContext(): boolean;
63/**
64 * Returns the current {@link Location}. This can be useful if you'd like to
65 * perform some side effect whenever it changes.
66 *
67 * @example
68 * import * as React from 'react'
69 * import { useLocation } from 'react-router'
70 *
71 * function SomeComponent() {
72 * let location = useLocation()
73 *
74 * React.useEffect(() => {
75 * // Google Analytics
76 * ga('send', 'pageview')
77 * }, [location]);
78 *
79 * return (
80 * // ...
81 * );
82 * }
83 *
84 * @public
85 * @category Hooks
86 * @returns The current {@link Location} object
87 */
88declare function useLocation(): Location;
89/**
90 * Returns the current {@link Navigation} action which describes how the router
91 * came to the current {@link Location}, either by a pop, push, or replace on
92 * the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History) stack.
93 *
94 * @public
95 * @category Hooks
96 * @returns The current {@link NavigationType} type (`"PUSH"`, `"REPLACE"`, or `"POP"`)
97 */
98declare function useNavigationType(): Action;
99/**
100 * Returns a {@link PathMatch} object if the given pattern matches the current URL.
101 * This is useful for components that need to know "active" state, e.g.
102 * {@link NavLink | `<NavLink>`}.
103 *
104 * @public
105 * @category Hooks
106 * @param pattern The pattern to match against the current {@link Location}
107 * @returns The path match object if the pattern matches, `null` otherwise
108 */
109declare function useMatch<ParamKey extends ParamParseKey<Path>, Path extends string>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null;
110/**
111 * The interface for the `navigate` function returned from {@link useNavigate}.
112 */
113interface NavigateFunction {
114 (to: To, options?: NavigateOptions): void | Promise<void>;
115 (delta: number): void | Promise<void>;
116}
117/**
118 * Returns a function that lets you navigate programmatically in the browser in
119 * response to user interactions or effects.
120 *
121 * It's often better to use {@link redirect} in [`action`](../../start/framework/route-module#action)/[`loader`](../../start/framework/route-module#loader)
122 * functions than this hook.
123 *
124 * The returned function signature is `navigate(to, options?)`/`navigate(delta)` where:
125 *
126 * * `to` can be a string path, a {@link To} object, or a number (delta)
127 * * `options` contains options for modifying the navigation
128 * * `flushSync`: Wrap the DOM updates in [`ReactDom.flushSync`](https://react.dev/reference/react-dom/flushSync)
129 * * `preventScrollReset`: Do not scroll back to the top of the page after navigation
130 * * `relative`: `"route"` or `"path"` to control relative routing logic
131 * * `replace`: Replace the current entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History) stack
132 * * `state`: Optional [`history.state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state) to include with the new {@link Location}
133 * * `viewTransition`: Enable [`document.startViewTransition`](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition) for this navigation
134 *
135 * @example
136 * import { useNavigate } from "react-router";
137 *
138 * function SomeComponent() {
139 * let navigate = useNavigate();
140 * return (
141 * <button onClick={() => navigate(-1)}>
142 * Go Back
143 * </button>
144 * );
145 * }
146 *
147 * @additionalExamples
148 * ### Navigate to another path
149 *
150 * ```tsx
151 * navigate("/some/route");
152 * navigate("/some/route?search=param");
153 * ```
154 *
155 * ### Navigate with a {@link To} object
156 *
157 * All properties are optional.
158 *
159 * ```tsx
160 * navigate({
161 * pathname: "/some/route",
162 * search: "?search=param",
163 * hash: "#hash",
164 * state: { some: "state" },
165 * });
166 * ```
167 *
168 * If you use `state`, that will be available on the {@link Location} object on
169 * the next page. Access it with `useLocation().state` (see {@link useLocation}).
170 *
171 * ### Navigate back or forward in the history stack
172 *
173 * ```tsx
174 * // back
175 * // often used to close modals
176 * navigate(-1);
177 *
178 * // forward
179 * // often used in a multistep wizard workflows
180 * navigate(1);
181 * ```
182 *
183 * Be cautious with `navigate(number)`. If your application can load up to a
184 * route that has a button that tries to navigate forward/back, there may not be
185 * a `[`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
186 * entry to go back or forward to, or it can go somewhere you don't expect
187 * (like a different domain).
188 *
189 * Only use this if you're sure they will have an entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
190 * stack to navigate to.
191 *
192 * ### Replace the current entry in the history stack
193 *
194 * This will remove the current entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
195 * stack, replacing it with a new one, similar to a server side redirect.
196 *
197 * ```tsx
198 * navigate("/some/route", { replace: true });
199 * ```
200 *
201 * ### Prevent Scroll Reset
202 *
203 * [MODES: framework, data]
204 *
205 * <br/>
206 * <br/>
207 *
208 * To prevent {@link ScrollRestoration | `<ScrollRestoration>`} from resetting
209 * the scroll position, use the `preventScrollReset` option.
210 *
211 * ```tsx
212 * navigate("?some-tab=1", { preventScrollReset: true });
213 * ```
214 *
215 * For example, if you have a tab interface connected to search params in the
216 * middle of a page, and you don't want it to scroll to the top when a tab is
217 * clicked.
218 *
219 * @public
220 * @category Hooks
221 * @returns A navigate function for programmatic navigation
222 */
223declare function useNavigate(): NavigateFunction;
224/**
225 * Returns the parent route {@link Outlet | `<Outlet context>`}.
226 *
227 * Often parent routes manage state or other values you want shared with child
228 * routes. You can create your own [context provider](https://react.dev/learn/passing-data-deeply-with-context)
229 * if you like, but this is such a common situation that it's built-into
230 * `<Outlet />`.
231 *
232 * ```tsx
233 * // Parent route
234 * function Parent() {
235 * const [count, setCount] = React.useState(0);
236 * return <Outlet context={[count, setCount]} />;
237 * }
238 * ```
239 *
240 * ```tsx
241 * // Child route
242 * import { useOutletContext } from "react-router-dom";
243 *
244 * function Child() {
245 * const [count, setCount] = useOutletContext();
246 * const increment = () => setCount((c) => c + 1);
247 * return <button onClick={increment}>{count}</button>;
248 * }
249 * ```
250 *
251 * If you're using TypeScript, we recommend the parent component provide a custom
252 * hook for accessing the context value. This makes it easier for consumers to
253 * get nice typings, control consumers, and know who's consuming the context value.
254 *
255 * Here's a more realistic example:
256 *
257 * ```tsx filename=src/routes/dashboard.tsx lines=[13,19]
258 * import * as React from "react";
259 * import type { User } from "./types";
260 * import { Outlet, useOutletContext } from "react-router-dom";
261 *
262 * type ContextType = { user: User | null };
263 *
264 * export default function Dashboard() {
265 * const [user, setUser] = React.useState<User | null>(null);
266 *
267 * return (
268 * <div>
269 * <h1>Dashboard</h1>
270 * <Outlet context={{ user } satisfies ContextType} />
271 * </div>
272 * );
273 * }
274 *
275 * export function useUser() {
276 * return useOutletContext<ContextType>();
277 * }
278 * ```
279 *
280 * ```tsx filename=src/routes/dashboard/messages.tsx lines=[1,4]
281 * import { useUser } from "../dashboard";
282 *
283 * export default function DashboardMessages() {
284 * const { user } = useUser();
285 * return (
286 * <div>
287 * <h2>Messages</h2>
288 * <p>Hello, {user.name}!</p>
289 * </div>
290 * );
291 * }
292 * ```
293 *
294 * @public
295 * @category Hooks
296 * @returns The context value passed to the parent {@link Outlet} component
297 */
298declare function useOutletContext<Context = unknown>(): Context;
299/**
300 * Returns the element for the child route at this level of the route
301 * hierarchy. Used internally by {@link Outlet | `<Outlet>`} to render child
302 * routes.
303 *
304 * @public
305 * @category Hooks
306 * @param context The context to pass to the outlet
307 * @returns The child route element or `null` if no child routes match
308 */
309declare function useOutlet(context?: unknown): React.ReactElement | null;
310/**
311 * Returns an object of key/value-pairs of the dynamic params from the current
312 * URL that were matched by the routes. Child routes inherit all params from
313 * their parent routes.
314 *
315 * Assuming a route pattern like `/posts/:postId` is matched by `/posts/123`
316 * then `params.postId` will be `"123"`.
317 *
318 * @example
319 * import { useParams } from "react-router";
320 *
321 * function SomeComponent() {
322 * let params = useParams();
323 * params.postId;
324 * }
325 *
326 * @additionalExamples
327 * ### Basic Usage
328 *
329 * ```tsx
330 * import { useParams } from "react-router";
331 *
332 * // given a route like:
333 * <Route path="/posts/:postId" element={<Post />} />;
334 *
335 * // or a data route like:
336 * createBrowserRouter([
337 * {
338 * path: "/posts/:postId",
339 * component: Post,
340 * },
341 * ]);
342 *
343 * // or in routes.ts
344 * route("/posts/:postId", "routes/post.tsx");
345 * ```
346 *
347 * Access the params in a component:
348 *
349 * ```tsx
350 * import { useParams } from "react-router";
351 *
352 * export default function Post() {
353 * let params = useParams();
354 * return <h1>Post: {params.postId}</h1>;
355 * }
356 * ```
357 *
358 * ### Multiple Params
359 *
360 * Patterns can have multiple params:
361 *
362 * ```tsx
363 * "/posts/:postId/comments/:commentId";
364 * ```
365 *
366 * All will be available in the params object:
367 *
368 * ```tsx
369 * import { useParams } from "react-router";
370 *
371 * export default function Post() {
372 * let params = useParams();
373 * return (
374 * <h1>
375 * Post: {params.postId}, Comment: {params.commentId}
376 * </h1>
377 * );
378 * }
379 * ```
380 *
381 * ### Catchall Params
382 *
383 * Catchall params are defined with `*`:
384 *
385 * ```tsx
386 * "/files/*";
387 * ```
388 *
389 * The matched value will be available in the params object as follows:
390 *
391 * ```tsx
392 * import { useParams } from "react-router";
393 *
394 * export default function File() {
395 * let params = useParams();
396 * let catchall = params["*"];
397 * // ...
398 * }
399 * ```
400 *
401 * You can destructure the catchall param:
402 *
403 * ```tsx
404 * export default function File() {
405 * let { "*": catchall } = useParams();
406 * console.log(catchall);
407 * }
408 * ```
409 *
410 * @public
411 * @category Hooks
412 * @returns An object containing the dynamic route parameters
413 */
414declare function useParams<ParamsOrKey extends string | Record<string, string | undefined> = string>(): Readonly<[
415 ParamsOrKey
416] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>>;
417/**
418 * Resolves the pathname of the given `to` value against the current
419 * {@link Location}. Similar to {@link useHref}, but returns a
420 * {@link Path} instead of a string.
421 *
422 * @example
423 * import { useResolvedPath } from "react-router";
424 *
425 * function SomeComponent() {
426 * // if the user is at /dashboard/profile
427 * let path = useResolvedPath("../accounts");
428 * path.pathname; // "/dashboard/accounts"
429 * path.search; // ""
430 * path.hash; // ""
431 * }
432 *
433 * @public
434 * @category Hooks
435 * @param to The path to resolve
436 * @param options Options
437 * @param options.relative Defaults to `"route"` so routing is relative to the route tree.
438 * Set to `"path"` to make relative routing operate against path segments.
439 * @returns The resolved {@link Path} object with `pathname`, `search`, and `hash`
440 */
441declare function useResolvedPath(to: To, { relative }?: {
442 relative?: RelativeRoutingType;
443}): Path;
444/**
445 * Hook version of {@link Routes | `<Routes>`} that uses objects instead of
446 * components. These objects have the same properties as the component props.
447 * The return value of `useRoutes` is either a valid React element you can use
448 * to render the route tree, or `null` if nothing matched.
449 *
450 * @example
451 * import { useRoutes } from "react-router";
452 *
453 * function App() {
454 * let element = useRoutes([
455 * {
456 * path: "/",
457 * element: <Dashboard />,
458 * children: [
459 * {
460 * path: "messages",
461 * element: <DashboardMessages />,
462 * },
463 * { path: "tasks", element: <DashboardTasks /> },
464 * ],
465 * },
466 * { path: "team", element: <AboutPage /> },
467 * ]);
468 *
469 * return element;
470 * }
471 *
472 * @public
473 * @category Hooks
474 * @param routes An array of {@link RouteObject}s that define the route hierarchy
475 * @param locationArg An optional {@link Location} object or pathname string to
476 * use instead of the current {@link Location}
477 * @returns A React element to render the matched route, or `null` if no routes matched
478 */
479declare function useRoutes(routes: RouteObject[], locationArg?: Partial<Location> | string): React.ReactElement | null;
480/**
481 * Returns the current {@link Navigation}, defaulting to an "idle" navigation
482 * when no navigation is in progress. You can use this to render pending UI
483 * (like a global spinner) or read [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
484 * from a form navigation.
485 *
486 * @example
487 * import { useNavigation } from "react-router";
488 *
489 * function SomeComponent() {
490 * let navigation = useNavigation();
491 * navigation.state;
492 * navigation.formData;
493 * // etc.
494 * }
495 *
496 * @public
497 * @category Hooks
498 * @mode framework
499 * @mode data
500 * @returns The current {@link Navigation} object
501 */
502declare function useNavigation(): Navigation;
503/**
504 * Revalidate the data on the page for reasons outside of normal data mutations
505 * like [`Window` focus](https://developer.mozilla.org/en-US/docs/Web/API/Window/focus_event)
506 * or polling on an interval.
507 *
508 * Note that page data is already revalidated automatically after actions.
509 * If you find yourself using this for normal CRUD operations on your data in
510 * response to user interactions, you're probably not taking advantage of the
511 * other APIs like {@link useFetcher}, {@link Form}, {@link useSubmit} that do
512 * this automatically.
513 *
514 * @example
515 * import { useRevalidator } from "react-router";
516 *
517 * function WindowFocusRevalidator() {
518 * const revalidator = useRevalidator();
519 *
520 * useFakeWindowFocus(() => {
521 * revalidator.revalidate();
522 * });
523 *
524 * return (
525 * <div hidden={revalidator.state === "idle"}>
526 * Revalidating...
527 * </div>
528 * );
529 * }
530 *
531 * @public
532 * @category Hooks
533 * @mode framework
534 * @mode data
535 * @returns An object with a `revalidate` function and the current revalidation
536 * `state`
537 */
538declare function useRevalidator(): {
539 revalidate: () => Promise<void>;
540 state: Router["state"]["revalidation"];
541};
542/**
543 * Returns the active route matches, useful for accessing `loaderData` for
544 * parent/child routes or the route [`handle`](../../start/framework/route-module#handle)
545 * property
546 *
547 * @public
548 * @category Hooks
549 * @mode framework
550 * @mode data
551 * @returns An array of {@link UIMatch | UI matches} for the current route hierarchy
552 */
553declare function useMatches(): UIMatch[];
554/**
555 * Returns the data from the closest route
556 * [`loader`](../../start/framework/route-module#loader) or
557 * [`clientLoader`](../../start/framework/route-module#clientloader).
558 *
559 * @example
560 * import { useLoaderData } from "react-router";
561 *
562 * export async function loader() {
563 * return await fakeDb.invoices.findAll();
564 * }
565 *
566 * export default function Invoices() {
567 * let invoices = useLoaderData<typeof loader>();
568 * // ...
569 * }
570 *
571 * @public
572 * @category Hooks
573 * @mode framework
574 * @mode data
575 * @returns The data returned from the route's [`loader`](../../start/framework/route-module#loader) or [`clientLoader`](../../start/framework/route-module#clientloader) function
576 */
577declare function useLoaderData<T = any>(): SerializeFrom<T>;
578/**
579 * Returns the [`loader`](../../start/framework/route-module#loader) data for a
580 * given route by route ID.
581 *
582 * Route IDs are created automatically. They are simply the path of the route file
583 * relative to the app folder without the extension.
584 *
585 * | Route Filename | Route ID |
586 * | ---------------------------- | ---------------------- |
587 * | `app/root.tsx` | `"root"` |
588 * | `app/routes/teams.tsx` | `"routes/teams"` |
589 * | `app/whatever/teams.$id.tsx` | `"whatever/teams.$id"` |
590 *
591 * @example
592 * import { useRouteLoaderData } from "react-router";
593 *
594 * function SomeComponent() {
595 * const { user } = useRouteLoaderData("root");
596 * }
597 *
598 * // You can also specify your own route ID's manually in your routes.ts file:
599 * route("/", "containers/app.tsx", { id: "app" })
600 * useRouteLoaderData("app");
601 *
602 * @public
603 * @category Hooks
604 * @mode framework
605 * @mode data
606 * @param routeId The ID of the route to return loader data from
607 * @returns The data returned from the specified route's [`loader`](../../start/framework/route-module#loader)
608 * function, or `undefined` if not found
609 */
610declare function useRouteLoaderData<T = any>(routeId: string): SerializeFrom<T> | undefined;
611/**
612 * Returns the [`action`](../../start/framework/route-module#action) data from
613 * the most recent `POST` navigation form submission or `undefined` if there
614 * hasn't been one.
615 *
616 * @example
617 * import { Form, useActionData } from "react-router";
618 *
619 * export async function action({ request }) {
620 * const body = await request.formData();
621 * const name = body.get("visitorsName");
622 * return { message: `Hello, ${name}` };
623 * }
624 *
625 * export default function Invoices() {
626 * const data = useActionData();
627 * return (
628 * <Form method="post">
629 * <input type="text" name="visitorsName" />
630 * {data ? data.message : "Waiting..."}
631 * </Form>
632 * );
633 * }
634 *
635 * @public
636 * @category Hooks
637 * @mode framework
638 * @mode data
639 * @returns The data returned from the route's [`action`](../../start/framework/route-module#action)
640 * function, or `undefined` if no [`action`](../../start/framework/route-module#action)
641 * has been called
642 */
643declare function useActionData<T = any>(): SerializeFrom<T> | undefined;
644/**
645 * Accesses the error thrown during an
646 * [`action`](../../start/framework/route-module#action),
647 * [`loader`](../../start/framework/route-module#loader),
648 * or component render to be used in a route module
649 * [`ErrorBoundary`](../../start/framework/route-module#errorboundary).
650 *
651 * @example
652 * export function ErrorBoundary() {
653 * const error = useRouteError();
654 * return <div>{error.message}</div>;
655 * }
656 *
657 * @public
658 * @category Hooks
659 * @mode framework
660 * @mode data
661 * @returns The error that was thrown during route [loading](../../start/framework/route-module#loader),
662 * [`action`](../../start/framework/route-module#action) execution, or rendering
663 */
664declare function useRouteError(): unknown;
665/**
666 * Returns the resolved promise value from the closest {@link Await | `<Await>`}.
667 *
668 * @example
669 * function SomeDescendant() {
670 * const value = useAsyncValue();
671 * // ...
672 * }
673 *
674 * // somewhere in your app
675 * <Await resolve={somePromise}>
676 * <SomeDescendant />
677 * </Await>;
678 *
679 * @public
680 * @category Hooks
681 * @mode framework
682 * @mode data
683 * @returns The resolved value from the nearest {@link Await} component
684 */
685declare function useAsyncValue(): unknown;
686/**
687 * Returns the rejection value from the closest {@link Await | `<Await>`}.
688 *
689 * @example
690 * import { Await, useAsyncError } from "react-router";
691 *
692 * function ErrorElement() {
693 * const error = useAsyncError();
694 * return (
695 * <p>Uh Oh, something went wrong! {error.message}</p>
696 * );
697 * }
698 *
699 * // somewhere in your app
700 * <Await
701 * resolve={promiseThatRejects}
702 * errorElement={<ErrorElement />}
703 * />;
704 *
705 * @public
706 * @category Hooks
707 * @mode framework
708 * @mode data
709 * @returns The error that was thrown in the nearest {@link Await} component
710 */
711declare function useAsyncError(): unknown;
712/**
713 * Allow the application to block navigations within the SPA and present the
714 * user a confirmation dialog to confirm the navigation. Mostly used to avoid
715 * using half-filled form data. This does not handle hard-reloads or
716 * cross-origin navigations.
717 *
718 * The {@link Blocker} object returned by the hook has the following properties:
719 *
720 * - **`state`**
721 * - `unblocked` - the blocker is idle and has not prevented any navigation
722 * - `blocked` - the blocker has prevented a navigation
723 * - `proceeding` - the blocker is proceeding through from a blocked navigation
724 * - **`location`**
725 * - When in a `blocked` state, this represents the {@link Location} to which we
726 * blocked a navigation. When in a `proceeding` state, this is the location
727 * being navigated to after a `blocker.proceed()` call.
728 * - **`proceed()`**
729 * - When in a `blocked` state, you may call `blocker.proceed()` to proceed to the
730 * blocked location.
731 * - **`reset()`**
732 * - When in a `blocked` state, you may call `blocker.reset()` to return the blocker
733 * back to an `unblocked` state and leave the user at the current location.
734 *
735 * @example
736 * // Boolean version
737 * const blocker = useBlocker(value !== "");
738 *
739 * // Function version
740 * const blocker = useBlocker(
741 * ({ currentLocation, nextLocation, historyAction }) =>
742 * value !== "" &&
743 * currentLocation.pathname !== nextLocation.pathname
744 * );
745 *
746 * @additionalExamples
747 * ```tsx
748 * import { useCallback, useState } from "react";
749 * import { BlockerFunction, useBlocker } from "react-router";
750 *
751 * export function ImportantForm() {
752 * const [value, setValue] = useState("");
753 *
754 * const shouldBlock = useCallback<BlockerFunction>(
755 * () => value !== "",
756 * [value]
757 * );
758 * const blocker = useBlocker(shouldBlock);
759 *
760 * return (
761 * <form
762 * onSubmit={(e) => {
763 * e.preventDefault();
764 * setValue("");
765 * if (blocker.state === "blocked") {
766 * blocker.proceed();
767 * }
768 * }}
769 * >
770 * <input
771 * name="data"
772 * value={value}
773 * onChange={(e) => setValue(e.target.value)}
774 * />
775 *
776 * <button type="submit">Save</button>
777 *
778 * {blocker.state === "blocked" ? (
779 * <>
780 * <p style={{ color: "red" }}>
781 * Blocked the last navigation to
782 * </p>
783 * <button
784 * type="button"
785 * onClick={() => blocker.proceed()}
786 * >
787 * Let me through
788 * </button>
789 * <button
790 * type="button"
791 * onClick={() => blocker.reset()}
792 * >
793 * Keep me here
794 * </button>
795 * </>
796 * ) : blocker.state === "proceeding" ? (
797 * <p style={{ color: "orange" }}>
798 * Proceeding through blocked navigation
799 * </p>
800 * ) : (
801 * <p style={{ color: "green" }}>
802 * Blocker is currently unblocked
803 * </p>
804 * )}
805 * </form>
806 * );
807 * }
808 * ```
809 *
810 * @public
811 * @category Hooks
812 * @mode framework
813 * @mode data
814 * @param shouldBlock Either a boolean or a function returning a boolean which
815 * indicates whether the navigation should be blocked. The function format
816 * receives a single object parameter containing the `currentLocation`,
817 * `nextLocation`, and `historyAction` of the potential navigation.
818 * @returns A {@link Blocker} object with state and reset functionality
819 */
820declare function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker;
821
822interface ServerRouterProps {
823 context: EntryContext;
824 url: string | URL;
825 nonce?: string;
826}
827/**
828 * The server entry point for a React Router app in Framework Mode. This component
829 * is used to generate the HTML in the response from the server.
830 * See [`entry.server.tsx`](../api/framework-conventions/entry.server.tsx).
831 *
832 * @public
833 * @category Framework Routers
834 * @mode framework
835 * @param props Props
836 * @param props.context The entry context containing the manifest, route modules,
837 * and other data needed for rendering.
838 * @param props.url The URL of the request being handled.
839 * @param props.nonce An optional nonce for Content Security Policy (CSP) compliance,
840 * used to allow inline scripts to run safely.
841 * @returns A React element that represents the server-rendered application.
842 */
843declare function ServerRouter({ context, url, nonce, }: ServerRouterProps): ReactElement;
844
845interface StubRouteExtensions {
846 Component?: RouteComponentType;
847 HydrateFallback?: HydrateFallbackType;
848 ErrorBoundary?: ErrorBoundaryType;
849 loader?: LoaderFunction;
850 action?: ActionFunction;
851 children?: StubRouteObject[];
852 meta?: MetaFunction;
853 links?: LinksFunction;
854}
855interface StubIndexRouteObject extends Omit<IndexRouteObject, "Component" | "HydrateFallback" | "ErrorBoundary" | "loader" | "action" | "element" | "errorElement" | "children">, StubRouteExtensions {
856}
857interface StubNonIndexRouteObject extends Omit<NonIndexRouteObject, "Component" | "HydrateFallback" | "ErrorBoundary" | "loader" | "action" | "element" | "errorElement" | "children">, StubRouteExtensions {
858}
859type StubRouteObject = StubIndexRouteObject | StubNonIndexRouteObject;
860interface RoutesTestStubProps {
861 /**
862 * The initial entries in the history stack. This allows you to start a test with
863 * multiple locations already in the history stack (for testing a back navigation, etc.)
864 * The test will default to the last entry in initialEntries if no initialIndex is provided.
865 * e.g. initialEntries={["/home", "/about", "/contact"]}
866 */
867 initialEntries?: InitialEntry[];
868 /**
869 * The initial index in the history stack to render. This allows you to start a test at a specific entry.
870 * It defaults to the last entry in initialEntries.
871 * e.g.
872 * initialEntries: ["/", "/events/123"]
873 * initialIndex: 1 // start at "/events/123"
874 */
875 initialIndex?: number;
876 /**
877 * Used to set the route's initial loader and action data.
878 * e.g. hydrationData={{
879 * loaderData: { "/contact": { locale: "en-US" } },
880 * actionData: { "/login": { errors: { email: "invalid email" } }}
881 * }}
882 */
883 hydrationData?: HydrationState;
884 /**
885 * Future flags mimicking the settings in react-router.config.ts
886 */
887 future?: Partial<FutureConfig>;
888}
889/**
890 * @category Utils
891 */
892declare function createRoutesStub(routes: StubRouteObject[], _context?: AppLoadContext | unstable_RouterContextProvider): ({ initialEntries, initialIndex, hydrationData, future, }: RoutesTestStubProps) => React.JSX.Element;
893
894interface CookieSignatureOptions {
895 /**
896 * An array of secrets that may be used to sign/unsign the value of a cookie.
897 *
898 * The array makes it easy to rotate secrets. New secrets should be added to
899 * the beginning of the array. `cookie.serialize()` will always use the first
900 * value in the array, but `cookie.parse()` may use any of them so that
901 * cookies that were signed with older secrets still work.
902 */
903 secrets?: string[];
904}
905type CookieOptions = ParseOptions & SerializeOptions & CookieSignatureOptions;
906/**
907 * A HTTP cookie.
908 *
909 * A Cookie is a logical container for metadata about a HTTP cookie; its name
910 * and options. But it doesn't contain a value. Instead, it has `parse()` and
911 * `serialize()` methods that allow a single instance to be reused for
912 * parsing/encoding multiple different values.
913 *
914 * @see https://remix.run/utils/cookies#cookie-api
915 */
916interface Cookie {
917 /**
918 * The name of the cookie, used in the `Cookie` and `Set-Cookie` headers.
919 */
920 readonly name: string;
921 /**
922 * True if this cookie uses one or more secrets for verification.
923 */
924 readonly isSigned: boolean;
925 /**
926 * The Date this cookie expires.
927 *
928 * Note: This is calculated at access time using `maxAge` when no `expires`
929 * option is provided to `createCookie()`.
930 */
931 readonly expires?: Date;
932 /**
933 * Parses a raw `Cookie` header and returns the value of this cookie or
934 * `null` if it's not present.
935 */
936 parse(cookieHeader: string | null, options?: ParseOptions): Promise<any>;
937 /**
938 * Serializes the given value to a string and returns the `Set-Cookie`
939 * header.
940 */
941 serialize(value: any, options?: SerializeOptions): Promise<string>;
942}
943/**
944 * Creates a logical container for managing a browser cookie from the server.
945 */
946declare const createCookie: (name: string, cookieOptions?: CookieOptions) => Cookie;
947type IsCookieFunction = (object: any) => object is Cookie;
948/**
949 * Returns true if an object is a Remix cookie container.
950 *
951 * @see https://remix.run/utils/cookies#iscookie
952 */
953declare const isCookie: IsCookieFunction;
954
955type RequestHandler = (request: Request, loadContext?: MiddlewareEnabled extends true ? unstable_InitialContext : AppLoadContext) => Promise<Response>;
956type CreateRequestHandlerFunction = (build: ServerBuild | (() => ServerBuild | Promise<ServerBuild>), mode?: string) => RequestHandler;
957declare const createRequestHandler: CreateRequestHandlerFunction;
958
959/**
960 * An object of name/value pairs to be used in the session.
961 */
962interface SessionData {
963 [name: string]: any;
964}
965/**
966 * Session persists data across HTTP requests.
967 *
968 * @see https://reactrouter.com/explanation/sessions-and-cookies#sessions
969 */
970interface Session<Data = SessionData, FlashData = Data> {
971 /**
972 * A unique identifier for this session.
973 *
974 * Note: This will be the empty string for newly created sessions and
975 * sessions that are not backed by a database (i.e. cookie-based sessions).
976 */
977 readonly id: string;
978 /**
979 * The raw data contained in this session.
980 *
981 * This is useful mostly for SessionStorage internally to access the raw
982 * session data to persist.
983 */
984 readonly data: FlashSessionData<Data, FlashData>;
985 /**
986 * Returns `true` if the session has a value for the given `name`, `false`
987 * otherwise.
988 */
989 has(name: (keyof Data | keyof FlashData) & string): boolean;
990 /**
991 * Returns the value for the given `name` in this session.
992 */
993 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;
994 /**
995 * Sets a value in the session for the given `name`.
996 */
997 set<Key extends keyof Data & string>(name: Key, value: Data[Key]): void;
998 /**
999 * Sets a value in the session that is only valid until the next `get()`.
1000 * This can be useful for temporary values, like error messages.
1001 */
1002 flash<Key extends keyof FlashData & string>(name: Key, value: FlashData[Key]): void;
1003 /**
1004 * Removes a value from the session.
1005 */
1006 unset(name: keyof Data & string): void;
1007}
1008type FlashSessionData<Data, FlashData> = Partial<Data & {
1009 [Key in keyof FlashData as FlashDataKey<Key & string>]: FlashData[Key];
1010}>;
1011type FlashDataKey<Key extends string> = `__flash_${Key}__`;
1012type CreateSessionFunction = <Data = SessionData, FlashData = Data>(initialData?: Data, id?: string) => Session<Data, FlashData>;
1013/**
1014 * Creates a new Session object.
1015 *
1016 * Note: This function is typically not invoked directly by application code.
1017 * Instead, use a `SessionStorage` object's `getSession` method.
1018 */
1019declare const createSession: CreateSessionFunction;
1020type IsSessionFunction = (object: any) => object is Session;
1021/**
1022 * Returns true if an object is a React Router session.
1023 *
1024 * @see https://reactrouter.com/api/utils/isSession
1025 */
1026declare const isSession: IsSessionFunction;
1027/**
1028 * SessionStorage stores session data between HTTP requests and knows how to
1029 * parse and create cookies.
1030 *
1031 * A SessionStorage creates Session objects using a `Cookie` header as input.
1032 * Then, later it generates the `Set-Cookie` header to be used in the response.
1033 */
1034interface SessionStorage<Data = SessionData, FlashData = Data> {
1035 /**
1036 * Parses a Cookie header from a HTTP request and returns the associated
1037 * Session. If there is no session associated with the cookie, this will
1038 * return a new Session with no data.
1039 */
1040 getSession: (cookieHeader?: string | null, options?: ParseOptions) => Promise<Session<Data, FlashData>>;
1041 /**
1042 * Stores all data in the Session and returns the Set-Cookie header to be
1043 * used in the HTTP response.
1044 */
1045 commitSession: (session: Session<Data, FlashData>, options?: SerializeOptions) => Promise<string>;
1046 /**
1047 * Deletes all data associated with the Session and returns the Set-Cookie
1048 * header to be used in the HTTP response.
1049 */
1050 destroySession: (session: Session<Data, FlashData>, options?: SerializeOptions) => Promise<string>;
1051}
1052/**
1053 * SessionIdStorageStrategy is designed to allow anyone to easily build their
1054 * own SessionStorage using `createSessionStorage(strategy)`.
1055 *
1056 * This strategy describes a common scenario where the session id is stored in
1057 * a cookie but the actual session data is stored elsewhere, usually in a
1058 * database or on disk. A set of create, read, update, and delete operations
1059 * are provided for managing the session data.
1060 */
1061interface SessionIdStorageStrategy<Data = SessionData, FlashData = Data> {
1062 /**
1063 * The Cookie used to store the session id, or options used to automatically
1064 * create one.
1065 */
1066 cookie?: Cookie | (CookieOptions & {
1067 name?: string;
1068 });
1069 /**
1070 * Creates a new record with the given data and returns the session id.
1071 */
1072 createData: (data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<string>;
1073 /**
1074 * Returns data for a given session id, or `null` if there isn't any.
1075 */
1076 readData: (id: string) => Promise<FlashSessionData<Data, FlashData> | null>;
1077 /**
1078 * Updates data for the given session id.
1079 */
1080 updateData: (id: string, data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<void>;
1081 /**
1082 * Deletes data for a given session id from the data store.
1083 */
1084 deleteData: (id: string) => Promise<void>;
1085}
1086/**
1087 * Creates a SessionStorage object using a SessionIdStorageStrategy.
1088 *
1089 * Note: This is a low-level API that should only be used if none of the
1090 * existing session storage options meet your requirements.
1091 */
1092declare function createSessionStorage<Data = SessionData, FlashData = Data>({ cookie: cookieArg, createData, readData, updateData, deleteData, }: SessionIdStorageStrategy<Data, FlashData>): SessionStorage<Data, FlashData>;
1093
1094interface CookieSessionStorageOptions {
1095 /**
1096 * The Cookie used to store the session data on the client, or options used
1097 * to automatically create one.
1098 */
1099 cookie?: SessionIdStorageStrategy["cookie"];
1100}
1101/**
1102 * Creates and returns a SessionStorage object that stores all session data
1103 * directly in the session cookie itself.
1104 *
1105 * This has the advantage that no database or other backend services are
1106 * needed, and can help to simplify some load-balanced scenarios. However, it
1107 * also has the limitation that serialized session data may not exceed the
1108 * browser's maximum cookie size. Trade-offs!
1109 */
1110declare function createCookieSessionStorage<Data = SessionData, FlashData = Data>({ cookie: cookieArg }?: CookieSessionStorageOptions): SessionStorage<Data, FlashData>;
1111
1112interface MemorySessionStorageOptions {
1113 /**
1114 * The Cookie used to store the session id on the client, or options used
1115 * to automatically create one.
1116 */
1117 cookie?: SessionIdStorageStrategy["cookie"];
1118}
1119/**
1120 * Creates and returns a simple in-memory SessionStorage object, mostly useful
1121 * for testing and as a reference implementation.
1122 *
1123 * Note: This storage does not scale beyond a single process, so it is not
1124 * suitable for most production scenarios.
1125 */
1126declare function createMemorySessionStorage<Data = SessionData, FlashData = Data>({ cookie }?: MemorySessionStorageOptions): SessionStorage<Data, FlashData>;
1127
1128type DevServerHooks = {
1129 getCriticalCss?: (pathname: string) => Promise<string | undefined>;
1130 processRequestError?: (error: unknown) => void;
1131};
1132declare function setDevServerHooks(devServerHooks: DevServerHooks): void;
1133
1134type Args = {
1135 [K in keyof Pages]: ToArgs<Pages[K]["params"]>;
1136};
1137type ToArgs<Params extends Record<string, string | undefined>> = Equal<Params, {}> extends true ? [] : Partial<Params> extends Params ? [Params] | [] : [
1138 Params
1139];
1140/**
1141 Returns a resolved URL path for the specified route.
1142
1143 ```tsx
1144 const h = href("/:lang?/about", { lang: "en" })
1145 // -> `/en/about`
1146
1147 <Link to={href("/products/:id", { id: "abc123" })} />
1148 ```
1149 */
1150declare function href<Path extends keyof Args>(path: Path, ...args: Args[Path]): string;
1151
1152type ServerContext = {
1153 redirect?: Response;
1154};
1155declare global {
1156 var ___reactRouterServerStorage___: AsyncLocalStorage<ServerContext> | undefined;
1157}
1158type RSCRouteConfigEntryBase = {
1159 action?: ActionFunction;
1160 clientAction?: ClientActionFunction;
1161 clientLoader?: ClientLoaderFunction;
1162 ErrorBoundary?: React.ComponentType<any>;
1163 handle?: any;
1164 headers?: HeadersFunction;
1165 HydrateFallback?: React.ComponentType<any>;
1166 Layout?: React.ComponentType<any>;
1167 links?: LinksFunction;
1168 loader?: LoaderFunction;
1169 meta?: MetaFunction;
1170 shouldRevalidate?: ShouldRevalidateFunction;
1171};
1172type RSCRouteConfigEntry = RSCRouteConfigEntryBase & {
1173 id: string;
1174 path?: string;
1175 Component?: React.ComponentType<any>;
1176 lazy?: () => Promise<RSCRouteConfigEntryBase & ({
1177 default?: React.ComponentType<any>;
1178 Component?: never;
1179 } | {
1180 default?: never;
1181 Component?: React.ComponentType<any>;
1182 })>;
1183} & ({
1184 index: true;
1185} | {
1186 children?: RSCRouteConfigEntry[];
1187});
1188type RSCRouteConfig = Array<RSCRouteConfigEntry>;
1189type RSCRouteManifest = {
1190 clientAction?: ClientActionFunction;
1191 clientLoader?: ClientLoaderFunction;
1192 element?: React.ReactElement | false;
1193 errorElement?: React.ReactElement;
1194 handle?: any;
1195 hasAction: boolean;
1196 hasComponent: boolean;
1197 hasErrorBoundary: boolean;
1198 hasLoader: boolean;
1199 hydrateFallbackElement?: React.ReactElement;
1200 id: string;
1201 index?: boolean;
1202 links?: LinksFunction;
1203 meta?: MetaFunction;
1204 parentId?: string;
1205 path?: string;
1206 shouldRevalidate?: ShouldRevalidateFunction;
1207};
1208type RSCRouteMatch = RSCRouteManifest & {
1209 params: Params;
1210 pathname: string;
1211 pathnameBase: string;
1212};
1213type RSCRenderPayload = {
1214 type: "render";
1215 actionData: Record<string, any> | null;
1216 basename: string | undefined;
1217 errors: Record<string, any> | null;
1218 loaderData: Record<string, any>;
1219 location: Location;
1220 matches: RSCRouteMatch[];
1221 patches?: RSCRouteManifest[];
1222 nonce?: string;
1223 formState?: unknown;
1224};
1225type RSCManifestPayload = {
1226 type: "manifest";
1227 patches: RSCRouteManifest[];
1228};
1229type RSCActionPayload = {
1230 type: "action";
1231 actionResult: Promise<unknown>;
1232 rerender?: Promise<RSCRenderPayload | RSCRedirectPayload>;
1233};
1234type RSCRedirectPayload = {
1235 type: "redirect";
1236 status: number;
1237 location: string;
1238 replace: boolean;
1239 reload: boolean;
1240 actionResult?: Promise<unknown>;
1241};
1242type RSCPayload = RSCRenderPayload | RSCManifestPayload | RSCActionPayload | RSCRedirectPayload;
1243type RSCMatch = {
1244 statusCode: number;
1245 headers: Headers;
1246 payload: RSCPayload;
1247};
1248type DecodeActionFunction = (formData: FormData) => Promise<() => Promise<unknown>>;
1249type DecodeFormStateFunction = (result: unknown, formData: FormData) => unknown;
1250type DecodeReplyFunction = (reply: FormData | string, { temporaryReferences }: {
1251 temporaryReferences: unknown;
1252}) => Promise<unknown[]>;
1253type LoadServerActionFunction = (id: string) => Promise<Function>;
1254/**
1255 * Matches the given routes to a Request and returns a RSC Response encoding an
1256 * `RSCPayload` for consumption by a RSC enabled client router.
1257 *
1258 * @example
1259 * import {
1260 * createTemporaryReferenceSet,
1261 * decodeAction,
1262 * decodeReply,
1263 * loadServerAction,
1264 * renderToReadableStream,
1265 * } from "@vitejs/plugin-rsc/rsc";
1266 * import { unstable_matchRSCServerRequest as matchRSCServerRequest } from "react-router";
1267 *
1268 * matchRSCServerRequest({
1269 * createTemporaryReferenceSet,
1270 * decodeAction,
1271 * decodeFormState,
1272 * decodeReply,
1273 * loadServerAction,
1274 * request,
1275 * routes: routes(),
1276 * generateResponse(match) {
1277 * return new Response(
1278 * renderToReadableStream(match.payload),
1279 * {
1280 * status: match.statusCode,
1281 * headers: match.headers,
1282 * }
1283 * );
1284 * },
1285 * });
1286 *
1287 * @name unstable_matchRSCServerRequest
1288 * @public
1289 * @category RSC
1290 * @mode data
1291 * @param opts Options
1292 * @param opts.basename The basename to use when matching the request.
1293 * @param opts.decodeAction Your `react-server-dom-xyz/server`'s `decodeAction`
1294 * function, responsible for loading a server action.
1295 * @param opts.decodeReply Your `react-server-dom-xyz/server`'s `decodeReply`
1296 * function, used to decode the server function's arguments and bind them to the
1297 * implementation for invocation by the router.
1298 * @param opts.decodeFormState A function responsible for decoding form state for
1299 * progressively enhanceable forms with `useActionState` using your
1300 * `react-server-dom-xyz/server`'s `decodeFormState`.
1301 * @param opts.generateResponse A function responsible for using your
1302 * `renderToReadableStream` to generate a Response encoding the `RSCPayload`.
1303 * @param opts.loadServerAction Your `react-server-dom-xyz/server`'s
1304 * `loadServerAction` function, used to load a server action by ID.
1305 * @param opts.request The request to match against.
1306 * @param opts.requestContext An instance of `unstable_RouterContextProvider`
1307 * that should be created per request, to be passed to loaders, actions and middleware.
1308 * @param opts.routes Your route definitions.
1309 * @param opts.createTemporaryReferenceSet A function that returns a temporary
1310 * reference set for the request, used to track temporary references in the RSC stream.
1311 * @param opts.onError An optional error handler that will be called with any
1312 * errors that occur during the request processing.
1313 * @returns A Response that contains the RSC data for hydration.
1314 */
1315declare function matchRSCServerRequest({ createTemporaryReferenceSet, basename, decodeReply, requestContext, loadServerAction, decodeAction, decodeFormState, onError, request, routes, generateResponse, }: {
1316 createTemporaryReferenceSet: () => unknown;
1317 basename?: string;
1318 decodeReply?: DecodeReplyFunction;
1319 decodeAction?: DecodeActionFunction;
1320 decodeFormState?: DecodeFormStateFunction;
1321 requestContext?: unstable_RouterContextProvider;
1322 loadServerAction?: LoadServerActionFunction;
1323 onError?: (error: unknown) => void;
1324 request: Request;
1325 routes: RSCRouteConfigEntry[];
1326 generateResponse: (match: RSCMatch, { temporaryReferences, }: {
1327 temporaryReferences: unknown;
1328 }) => Response;
1329}): Promise<Response>;
1330
1331type BrowserCreateFromReadableStreamFunction = (body: ReadableStream<Uint8Array>, { temporaryReferences, }: {
1332 temporaryReferences: unknown;
1333}) => Promise<unknown>;
1334type EncodeReplyFunction = (args: unknown[], options: {
1335 temporaryReferences: unknown;
1336}) => Promise<BodyInit>;
1337/**
1338 * Create a React `callServer` implementation for React Router.
1339 *
1340 * @example
1341 * import {
1342 * createFromReadableStream,
1343 * createTemporaryReferenceSet,
1344 * encodeReply,
1345 * setServerCallback,
1346 * } from "@vitejs/plugin-rsc/browser";
1347 * import { unstable_createCallServer as createCallServer } from "react-router";
1348 *
1349 * setServerCallback(
1350 * createCallServer({
1351 * createFromReadableStream,
1352 * createTemporaryReferenceSet,
1353 * encodeReply,
1354 * })
1355 * );
1356 *
1357 * @name unstable_createCallServer
1358 * @public
1359 * @category RSC
1360 * @mode data
1361 * @param opts Options
1362 * @param opts.createFromReadableStream Your `react-server-dom-xyz/client`'s
1363 * `createFromReadableStream`. Used to decode payloads from the server.
1364 * @param opts.createTemporaryReferenceSet A function that creates a temporary
1365 * reference set for the RSC payload.
1366 * @param opts.encodeReply Your `react-server-dom-xyz/client`'s `encodeReply`.
1367 * Used when sending payloads to the server.
1368 * @param opts.fetch Optional fetch implementation. Defaults to global `fetch`.
1369 * @returns A function that can be used to call server actions.
1370 */
1371declare function createCallServer({ createFromReadableStream, createTemporaryReferenceSet, encodeReply, fetch: fetchImplementation, }: {
1372 createFromReadableStream: BrowserCreateFromReadableStreamFunction;
1373 createTemporaryReferenceSet: () => unknown;
1374 encodeReply: EncodeReplyFunction;
1375 fetch?: (request: Request) => Promise<Response>;
1376}): (id: string, args: unknown[]) => Promise<unknown>;
1377/**
1378 * Props for the `unstable_RSCHydratedRouter` component.
1379 * @name unstable_RSCHydratedRouterProps
1380 */
1381interface RSCHydratedRouterProps {
1382 /**
1383 * Your `react-server-dom-xyz/client`'s `createFromReadableStream` function,
1384 * used to decode payloads from the server.
1385 */
1386 createFromReadableStream: BrowserCreateFromReadableStreamFunction;
1387 /**
1388 * Optional fetch implementation. Defaults to global `fetch`.
1389 */
1390 fetch?: (request: Request) => Promise<Response>;
1391 /**
1392 * The decoded `RSCPayload` to hydrate.
1393 */
1394 payload: RSCPayload;
1395 /**
1396 * `eager` or `lazy` - Determines if links are eagerly discovered, or delayed
1397 * until clicked.
1398 */
1399 routeDiscovery?: "eager" | "lazy";
1400 /**
1401 * A function that returns an `unstable_InitialContext` object
1402 * (`Map<RouterContext, unknown>`), for use in client loaders, actions and
1403 * middleware.
1404 */
1405 unstable_getContext?: RouterInit["unstable_getContext"];
1406}
1407/**
1408 * Hydrates a server rendered `RSCPayload` in the browser.
1409 *
1410 * @example
1411 * import { startTransition, StrictMode } from "react";
1412 * import { hydrateRoot } from "react-dom/client";
1413 * import {
1414 * unstable_getRSCStream as getRSCStream,
1415 * unstable_RSCHydratedRouter as RSCHydratedRouter,
1416 * } from "react-router";
1417 * import type { unstable_RSCPayload as RSCPayload } from "react-router";
1418 *
1419 * createFromReadableStream(getRSCStream()).then(
1420 * (payload: RSCServerPayload) => {
1421 * startTransition(async () => {
1422 * hydrateRoot(
1423 * document,
1424 * <StrictMode>
1425 * <RSCHydratedRouter
1426 * createFromReadableStream={
1427 * createFromReadableStream
1428 * }
1429 * payload={payload}
1430 * />
1431 * </StrictMode>,
1432 * {
1433 * formState: await getFormState(payload),
1434 * }
1435 * );
1436 * });
1437 * }
1438 * );
1439 *
1440 * @name unstable_RSCHydratedRouter
1441 * @public
1442 * @category RSC
1443 * @mode data
1444 * @param props Props
1445 * @param {unstable_RSCHydratedRouterProps.createFromReadableStream} props.createFromReadableStream n/a
1446 * @param {unstable_RSCHydratedRouterProps.fetch} props.fetch n/a
1447 * @param {unstable_RSCHydratedRouterProps.payload} props.payload n/a
1448 * @param {unstable_RSCHydratedRouterProps.routeDiscovery} props.routeDiscovery n/a
1449 * @param {unstable_RSCHydratedRouterProps.unstable_getContext} props.unstable_getContext n/a
1450 * @returns A hydrated router that can be used to navigate and render routes.
1451 */
1452declare function RSCHydratedRouter({ createFromReadableStream, fetch: fetchImplementation, payload, routeDiscovery, unstable_getContext, }: RSCHydratedRouterProps): React.JSX.Element;
1453
1454type SSRCreateFromReadableStreamFunction = (body: ReadableStream<Uint8Array>) => Promise<unknown>;
1455/**
1456 * Routes the incoming request to the RSC server and appropriately proxies the
1457 * server response for data / resource requests, or renders to HTML for a document
1458 * request.
1459 *
1460 * @example
1461 * import { createFromReadableStream } from "@vitejs/plugin-rsc/ssr";
1462 * import * as ReactDomServer from "react-dom/server.edge";
1463 * import {
1464 * unstable_RSCStaticRouter as RSCStaticRouter,
1465 * unstable_routeRSCServerRequest as routeRSCServerRequest,
1466 * } from "react-router";
1467 *
1468 * routeRSCServerRequest({
1469 * request,
1470 * fetchServer,
1471 * createFromReadableStream,
1472 * async renderHTML(getPayload) {
1473 * const payload = await getPayload();
1474 *
1475 * return await renderHTMLToReadableStream(
1476 * <RSCStaticRouter getPayload={getPayload} />,
1477 * {
1478 * bootstrapScriptContent,
1479 * formState: await getFormState(payload),
1480 * }
1481 * );
1482 * },
1483 * });
1484 *
1485 * @name unstable_routeRSCServerRequest
1486 * @public
1487 * @category RSC
1488 * @mode data
1489 * @param opts Options
1490 * @param opts.createFromReadableStream Your `react-server-dom-xyz/client`'s
1491 * `createFromReadableStream` function, used to decode payloads from the server.
1492 * @param opts.fetchServer A function that forwards a `Request` to the RSC handler
1493 * and returns a `Promise<Response>` containing a serialized `RSCPayload`.
1494 * @param opts.renderHTML A function that renders the `RSCPayload` to HTML, usually
1495 * using a `<RSCStaticRouter>`.
1496 * @param opts.request The request to route.
1497 * @param opts.hydrate Whether to hydrate the server response with the RSC payload.
1498 * Defaults to `true`.
1499 * @returns A `Response` that either contains the RSC payload for data requests, or
1500 * renders the HTML for document requests.
1501 */
1502declare function routeRSCServerRequest({ request, fetchServer, createFromReadableStream, renderHTML, hydrate, }: {
1503 request: Request;
1504 fetchServer: (request: Request) => Promise<Response>;
1505 createFromReadableStream: SSRCreateFromReadableStreamFunction;
1506 renderHTML: (getPayload: () => Promise<RSCPayload>) => ReadableStream<Uint8Array> | Promise<ReadableStream<Uint8Array>>;
1507 hydrate?: boolean;
1508}): Promise<Response>;
1509/**
1510 * Props for the `RSCStaticRouter` component.
1511 * @name unstable_RSCStaticRouterProps
1512 */
1513interface RSCStaticRouterProps {
1514 /**
1515 * A function that starts decoding of the `RSCPayload`. Usually passed through
1516 * from `routeRSCServerRequest`'s `renderHTML`.
1517 */
1518 getPayload: () => Promise<RSCPayload>;
1519}
1520/**
1521 * Pre-renders an `RSCPayload` to HTML. Usually used in `routeRSCServerRequest`'s
1522 * `renderHTML` callback.
1523 *
1524 * @example
1525 * import { createFromReadableStream } from "@vitejs/plugin-rsc/ssr";
1526 * import * as ReactDomServer from "react-dom/server.edge";
1527 * import {
1528 * unstable_RSCStaticRouter as RSCStaticRouter,
1529 * unstable_routeRSCServerRequest as routeRSCServerRequest,
1530 * } from "react-router";
1531 *
1532 * routeRSCServerRequest({
1533 * request,
1534 * fetchServer,
1535 * createFromReadableStream,
1536 * async renderHTML(getPayload) {
1537 * const payload = await getPayload();
1538 *
1539 * return await renderHTMLToReadableStream(
1540 * <RSCStaticRouter getPayload={getPayload} />,
1541 * {
1542 * bootstrapScriptContent,
1543 * formState: await getFormState(payload),
1544 * }
1545 * );
1546 * },
1547 * });
1548 *
1549 * @name unstable_RSCStaticRouter
1550 * @public
1551 * @category RSC
1552 * @mode data
1553 * @param props Props
1554 * @param {unstable_RSCStaticRouterProps.getPayload} props.getPayload n/a
1555 * @returns A React component that renders the `RSCPayload` as HTML.
1556 */
1557declare function RSCStaticRouter({ getPayload }: RSCStaticRouterProps): React.JSX.Element | null;
1558
1559declare global {
1560 interface Window {
1561 __FLIGHT_DATA: any[];
1562 }
1563}
1564/**
1565 * Get the prerendered RSC stream for hydration. Usually passed directly to your
1566 * `react-server-dom-xyz/client`'s `createFromReadableStream`.
1567 *
1568 * @example
1569 * import { startTransition, StrictMode } from "react";
1570 * import { hydrateRoot } from "react-dom/client";
1571 * import {
1572 * unstable_getRSCStream as getRSCStream,
1573 * unstable_RSCHydratedRouter as RSCHydratedRouter,
1574 * } from "react-router";
1575 * import type { unstable_RSCPayload as RSCPayload } from "react-router";
1576 *
1577 * createFromReadableStream(getRSCStream()).then(
1578 * (payload: RSCServerPayload) => {
1579 * startTransition(async () => {
1580 * hydrateRoot(
1581 * document,
1582 * <StrictMode>
1583 * <RSCHydratedRouter ...props />
1584 * </StrictMode>,
1585 * {
1586 * // Options
1587 * }
1588 * );
1589 * });
1590 * }
1591 * );
1592 *
1593 * @name unstable_getRSCStream
1594 * @public
1595 * @category RSC
1596 * @mode data
1597 * @returns A `ReadableStream` that contains the RSC data for hydration.
1598 */
1599declare function getRSCStream(): ReadableStream<any>;
1600
1601declare function RSCDefaultRootErrorBoundary({ hasRootLayout, }: {
1602 hasRootLayout: boolean;
1603}): React__default.JSX.Element;
1604
1605declare function deserializeErrors(errors: RouterState["errors"]): RouterState["errors"];
1606
1607type RemixErrorBoundaryProps = React.PropsWithChildren<{
1608 location: Location;
1609 isOutsideRemixApp?: boolean;
1610 error?: Error;
1611}>;
1612type RemixErrorBoundaryState = {
1613 error: null | Error;
1614 location: Location;
1615};
1616declare class RemixErrorBoundary extends React.Component<RemixErrorBoundaryProps, RemixErrorBoundaryState> {
1617 constructor(props: RemixErrorBoundaryProps);
1618 static getDerivedStateFromError(error: Error): {
1619 error: Error;
1620 };
1621 static getDerivedStateFromProps(props: RemixErrorBoundaryProps, state: RemixErrorBoundaryState): {
1622 error: Error | null;
1623 location: Location<any>;
1624 };
1625 render(): string | number | boolean | Iterable<React.ReactNode> | React.JSX.Element | null | undefined;
1626}
1627
1628declare function getPatchRoutesOnNavigationFunction(manifest: AssetsManifest, routeModules: RouteModules, ssr: boolean, routeDiscovery: ServerBuild["routeDiscovery"], isSpaMode: boolean, basename: string | undefined): PatchRoutesOnNavigationFunction | undefined;
1629declare function useFogOFWarDiscovery(router: Router, manifest: AssetsManifest, routeModules: RouteModules, ssr: boolean, routeDiscovery: ServerBuild["routeDiscovery"], isSpaMode: boolean): void;
1630
1631declare function getHydrationData(state: {
1632 loaderData?: Router["state"]["loaderData"];
1633 actionData?: Router["state"]["actionData"];
1634 errors?: Router["state"]["errors"];
1635}, routes: DataRouteObject[], getRouteInfo: (routeId: string) => {
1636 clientLoader: ClientLoaderFunction | undefined;
1637 hasLoader: boolean;
1638 hasHydrateFallback: boolean;
1639}, location: Path, basename: string | undefined, isSpaMode: boolean): HydrationState;
1640
1641declare const unstable_matchRSCServerRequest: typeof matchRSCServerRequest;
1642
1643export { ActionFunction, AppLoadContext, Blocker, BlockerFunction, ClientActionFunction, ClientLoaderFunction, type Cookie, type CookieOptions, type CookieSignatureOptions, type CreateRequestHandlerFunction, DataRouteObject, Router as DataRouter, DataStrategyFunction, EntryContext, type FlashSessionData, HeadersFunction, HydrationState, IndexRouteObject, InitialEntry, type IsCookieFunction, type IsSessionFunction, LinksFunction, LoaderFunction, Location, MetaFunction, type NavigateFunction, NavigateOptions, Navigation, Action as NavigationType, NonIndexRouteObject, ParamParseKey, Params, PatchRoutesOnNavigationFunction, Path, PathMatch, PathPattern, RelativeRoutingType, type RequestHandler, RouteObject, RouterInit, RouterState, type RoutesTestStubProps, ServerBuild, ServerRouter, type ServerRouterProps, type Session, type SessionData, type SessionIdStorageStrategy, type SessionStorage, ShouldRevalidateFunction, To, UIMatch, AssetsManifest as UNSAFE_AssetsManifest, MiddlewareEnabled as UNSAFE_MiddlewareEnabled, RSCDefaultRootErrorBoundary as UNSAFE_RSCDefaultRootErrorBoundary, RemixErrorBoundary as UNSAFE_RemixErrorBoundary, RouteModules as UNSAFE_RouteModules, ServerMode as UNSAFE_ServerMode, SingleFetchRedirectSymbol as UNSAFE_SingleFetchRedirectSymbol, decodeViaTurboStream as UNSAFE_decodeViaTurboStream, deserializeErrors as UNSAFE_deserializeErrors, getHydrationData as UNSAFE_getHydrationData, getPatchRoutesOnNavigationFunction as UNSAFE_getPatchRoutesOnNavigationFunction, getTurboStreamSingleFetchDataStrategy as UNSAFE_getTurboStreamSingleFetchDataStrategy, useFogOFWarDiscovery as UNSAFE_useFogOFWarDiscovery, createCookie, createCookieSessionStorage, createMemorySessionStorage, createRequestHandler, createRoutesStub, createSession, createSessionStorage, href, isCookie, isSession, type BrowserCreateFromReadableStreamFunction as unstable_BrowserCreateFromReadableStreamFunction, type DecodeActionFunction as unstable_DecodeActionFunction, type DecodeFormStateFunction as unstable_DecodeFormStateFunction, type DecodeReplyFunction as unstable_DecodeReplyFunction, type EncodeReplyFunction as unstable_EncodeReplyFunction, unstable_InitialContext, type LoadServerActionFunction as unstable_LoadServerActionFunction, RSCHydratedRouter as unstable_RSCHydratedRouter, type RSCHydratedRouterProps as unstable_RSCHydratedRouterProps, 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, RSCStaticRouter as unstable_RSCStaticRouter, type RSCStaticRouterProps as unstable_RSCStaticRouterProps, unstable_RouterContextProvider, type SSRCreateFromReadableStreamFunction as unstable_SSRCreateFromReadableStreamFunction, createCallServer as unstable_createCallServer, getRSCStream as unstable_getRSCStream, unstable_matchRSCServerRequest, routeRSCServerRequest as unstable_routeRSCServerRequest, setDevServerHooks as unstable_setDevServerHooks, useActionData, useAsyncError, useAsyncValue, useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes };