react-router 7.9.4 → 7.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/development/browser-DM83uryY.d.ts +310 -0
  3. package/dist/development/browser-DfMfSvsC.d.mts +310 -0
  4. package/dist/development/chunk-FQEOJFGW.js +188 -0
  5. package/dist/development/chunk-IXESJAGJ.js +1310 -0
  6. package/dist/development/{chunk-WY5IRSCW.mjs → chunk-JG3XND5A.mjs} +197 -857
  7. package/dist/development/{chunk-OIYGIGL5.mjs → chunk-UIGDSWPH.mjs} +365 -22
  8. package/dist/development/{chunk-DI2QHYMJ.js → chunk-VNR6V74N.js} +1226 -122
  9. package/dist/development/dom-export.d.mts +103 -6
  10. package/dist/development/dom-export.d.ts +103 -4
  11. package/dist/development/dom-export.js +708 -20
  12. package/dist/development/dom-export.mjs +692 -11
  13. package/dist/{production/index-react-server-client-BIz4AUNd.d.mts → development/index-react-server-client-B0vnxMMk.d.mts} +137 -78
  14. package/dist/{production/index-react-server-client-BbRcBjrA.d.ts → development/index-react-server-client-BSxMvS7Z.d.ts} +195 -135
  15. package/dist/development/index-react-server-client.d.mts +2 -3
  16. package/dist/development/index-react-server-client.d.ts +2 -2
  17. package/dist/development/index-react-server-client.js +4 -4
  18. package/dist/development/index-react-server-client.mjs +2 -2
  19. package/dist/development/index-react-server.d.mts +107 -3
  20. package/dist/development/index-react-server.d.ts +107 -3
  21. package/dist/development/index-react-server.js +235 -10
  22. package/dist/development/index-react-server.mjs +235 -10
  23. package/dist/development/index.d.mts +14 -320
  24. package/dist/development/index.d.ts +14 -362
  25. package/dist/development/index.js +146 -962
  26. package/dist/development/index.mjs +3 -9
  27. package/dist/development/{routeModules-D5iJ6JYT.d.ts → instrumentation-iAqbU5Q4.d.ts} +173 -24
  28. package/dist/development/lib/types/internal.d.mts +2 -3
  29. package/dist/development/lib/types/internal.d.ts +2 -2
  30. package/dist/development/lib/types/internal.js +1 -1
  31. package/dist/development/lib/types/internal.mjs +1 -1
  32. package/dist/development/{register-CI4bTprK.d.mts → register-_G476ptB.d.mts} +1 -1
  33. package/dist/{production/register-C34pU-in.d.ts → development/register-c-dooqKE.d.ts} +1 -1
  34. package/dist/{production/context-DSyS5mLj.d.mts → development/router-DIAPGK5f.d.mts} +1873 -1254
  35. package/dist/production/browser-DM83uryY.d.ts +310 -0
  36. package/dist/production/browser-DfMfSvsC.d.mts +310 -0
  37. package/dist/production/chunk-CWEARR4H.js +188 -0
  38. package/dist/production/{chunk-4E5LHRQP.js → chunk-EAE7427A.js} +1226 -122
  39. package/dist/production/chunk-ERPFE3MR.js +1310 -0
  40. package/dist/production/{chunk-3TADTUL4.mjs → chunk-RZ6LZWMW.mjs} +365 -22
  41. package/dist/production/{chunk-FR6HSPLK.mjs → chunk-TPBVZP6U.mjs} +197 -857
  42. package/dist/production/dom-export.d.mts +103 -6
  43. package/dist/production/dom-export.d.ts +103 -4
  44. package/dist/production/dom-export.js +708 -20
  45. package/dist/production/dom-export.mjs +692 -11
  46. package/dist/{development/index-react-server-client-BbRcBjrA.d.ts → production/index-react-server-client-B0vnxMMk.d.mts} +195 -135
  47. package/dist/{development/index-react-server-client-BIz4AUNd.d.mts → production/index-react-server-client-BSxMvS7Z.d.ts} +137 -78
  48. package/dist/production/index-react-server-client.d.mts +2 -3
  49. package/dist/production/index-react-server-client.d.ts +2 -2
  50. package/dist/production/index-react-server-client.js +4 -4
  51. package/dist/production/index-react-server-client.mjs +2 -2
  52. package/dist/production/index-react-server.d.mts +107 -3
  53. package/dist/production/index-react-server.d.ts +107 -3
  54. package/dist/production/index-react-server.js +235 -10
  55. package/dist/production/index-react-server.mjs +235 -10
  56. package/dist/production/index.d.mts +14 -320
  57. package/dist/production/index.d.ts +14 -362
  58. package/dist/production/index.js +146 -962
  59. package/dist/production/index.mjs +3 -9
  60. package/dist/production/{routeModules-D5iJ6JYT.d.ts → instrumentation-iAqbU5Q4.d.ts} +173 -24
  61. package/dist/production/lib/types/internal.d.mts +2 -3
  62. package/dist/production/lib/types/internal.d.ts +2 -2
  63. package/dist/production/lib/types/internal.js +1 -1
  64. package/dist/production/lib/types/internal.mjs +1 -1
  65. package/dist/production/{register-CI4bTprK.d.mts → register-_G476ptB.d.mts} +1 -1
  66. package/dist/{development/register-C34pU-in.d.ts → production/register-c-dooqKE.d.ts} +1 -1
  67. package/dist/{development/context-DSyS5mLj.d.mts → production/router-DIAPGK5f.d.mts} +1873 -1254
  68. package/package.json +1 -1
  69. package/dist/development/browser-z32v5KVN.d.mts +0 -46
  70. package/dist/development/chunk-72XNTZCV.js +0 -2089
  71. package/dist/development/route-data-DZQOUSqV.d.mts +0 -473
  72. package/dist/production/browser-z32v5KVN.d.mts +0 -46
  73. package/dist/production/chunk-WNLQ53P5.js +0 -2089
  74. package/dist/production/route-data-DZQOUSqV.d.mts +0 -473
@@ -1,4 +1,5 @@
1
1
  import * as React from 'react';
2
+ import { ComponentType, ReactElement } from 'react';
2
3
 
3
4
  /**
4
5
  * Actions represent the type of change to a location value.
@@ -394,6 +395,11 @@ type DefaultContext = MiddlewareEnabled extends true ? Readonly<RouterContextPro
394
395
  interface DataFunctionArgs<Context> {
395
396
  /** 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. */
396
397
  request: Request;
398
+ /**
399
+ * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
400
+ * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
401
+ */
402
+ unstable_pattern: string;
397
403
  /**
398
404
  * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
399
405
  * @example
@@ -614,7 +620,7 @@ type AgnosticPatchRoutesOnNavigationFunction<O extends AgnosticRouteObject = Agn
614
620
  * properties from framework-agnostic properties
615
621
  */
616
622
  interface MapRoutePropertiesFunction {
617
- (route: AgnosticRouteObject): {
623
+ (route: AgnosticDataRouteObject): {
618
624
  hasErrorBoundary: boolean;
619
625
  } & Record<string, any>;
620
626
  }
@@ -1040,1529 +1046,2142 @@ declare class ErrorResponseImpl implements ErrorResponse {
1040
1046
  declare function isRouteErrorResponse(error: any): error is ErrorResponse;
1041
1047
 
1042
1048
  /**
1043
- * A Router instance manages all navigation and data loading/mutations
1049
+ * An object of unknown type for route loaders and actions provided by the
1050
+ * server's `getLoadContext()` function. This is defined as an empty interface
1051
+ * specifically so apps can leverage declaration merging to augment this type
1052
+ * globally: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
1044
1053
  */
1045
- interface Router$1 {
1046
- /**
1047
- * @private
1048
- * PRIVATE - DO NOT USE
1049
- *
1050
- * Return the basename for the router
1051
- */
1052
- get basename(): RouterInit["basename"];
1053
- /**
1054
- * @private
1055
- * PRIVATE - DO NOT USE
1056
- *
1057
- * Return the future config for the router
1058
- */
1059
- get future(): FutureConfig;
1054
+ interface AppLoadContext {
1055
+ [key: string]: unknown;
1056
+ }
1057
+
1058
+ declare function mapRouteProperties(route: RouteObject): Partial<RouteObject> & {
1059
+ hasErrorBoundary: boolean;
1060
+ };
1061
+ declare const hydrationRouteProperties: (keyof RouteObject)[];
1062
+ /**
1063
+ * @category Data Routers
1064
+ */
1065
+ interface MemoryRouterOpts {
1060
1066
  /**
1061
- * @private
1062
- * PRIVATE - DO NOT USE
1063
- *
1064
- * Return the current state of the router
1067
+ * Basename path for the application.
1065
1068
  */
1066
- get state(): RouterState;
1069
+ basename?: string;
1067
1070
  /**
1068
- * @private
1069
- * PRIVATE - DO NOT USE
1070
- *
1071
- * Return the routes for this router instance
1071
+ * A function that returns an {@link RouterContextProvider} instance
1072
+ * which is provided as the `context` argument to client [`action`](../../start/data/route-object#action)s,
1073
+ * [`loader`](../../start/data/route-object#loader)s and [middleware](../../how-to/middleware).
1074
+ * This function is called to generate a fresh `context` instance on each
1075
+ * navigation or fetcher call.
1072
1076
  */
1073
- get routes(): AgnosticDataRouteObject[];
1077
+ getContext?: RouterInit["getContext"];
1074
1078
  /**
1075
- * @private
1076
- * PRIVATE - DO NOT USE
1077
- *
1078
- * Return the window associated with the router
1079
+ * Future flags to enable for the router.
1079
1080
  */
1080
- get window(): RouterInit["window"];
1081
+ future?: Partial<FutureConfig>;
1081
1082
  /**
1082
- * @private
1083
- * PRIVATE - DO NOT USE
1084
- *
1085
- * Initialize the router, including adding history listeners and kicking off
1086
- * initial data fetches. Returns a function to cleanup listeners and abort
1087
- * any in-progress loads
1083
+ * Hydration data to initialize the router with if you have already performed
1084
+ * data loading on the server.
1088
1085
  */
1089
- initialize(): Router$1;
1086
+ hydrationData?: HydrationState;
1090
1087
  /**
1091
- * @private
1092
- * PRIVATE - DO NOT USE
1093
- *
1094
- * Subscribe to router.state updates
1095
- *
1096
- * @param fn function to call with the new state
1088
+ * Initial entries in the in-memory history stack
1097
1089
  */
1098
- subscribe(fn: RouterSubscriber): () => void;
1090
+ initialEntries?: InitialEntry[];
1099
1091
  /**
1100
- * @private
1101
- * PRIVATE - DO NOT USE
1102
- *
1103
- * Enable scroll restoration behavior in the router
1104
- *
1105
- * @param savedScrollPositions Object that will manage positions, in case
1106
- * it's being restored from sessionStorage
1107
- * @param getScrollPosition Function to get the active Y scroll position
1108
- * @param getKey Function to get the key to use for restoration
1092
+ * Index of `initialEntries` the application should initialize to
1109
1093
  */
1110
- enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;
1094
+ initialIndex?: number;
1111
1095
  /**
1112
- * @private
1113
- * PRIVATE - DO NOT USE
1096
+ * Array of instrumentation objects allowing you to instrument the router and
1097
+ * individual routes prior to router initialization (and on any subsequently
1098
+ * added routes via `route.lazy` or `patchRoutesOnNavigation`). This is
1099
+ * mostly useful for observability such as wrapping navigations, fetches,
1100
+ * as well as route loaders/actions/middlewares with logging and/or performance
1101
+ * tracing.
1114
1102
  *
1115
- * Navigate forward/backward in the history stack
1116
- * @param to Delta to move in the history stack
1103
+ * ```tsx
1104
+ * let router = createBrowserRouter(routes, {
1105
+ * unstable_instrumentations: [logging]
1106
+ * });
1107
+ *
1108
+ *
1109
+ * let logging = {
1110
+ * router({ instrument }) {
1111
+ * instrument({
1112
+ * navigate: (impl, info) => logExecution(`navigate ${info.to}`, impl),
1113
+ * fetch: (impl, info) => logExecution(`fetch ${info.to}`, impl)
1114
+ * });
1115
+ * },
1116
+ * route({ instrument, id }) {
1117
+ * instrument({
1118
+ * middleware: (impl, info) => logExecution(
1119
+ * `middleware ${info.request.url} (route ${id})`,
1120
+ * impl
1121
+ * ),
1122
+ * loader: (impl, info) => logExecution(
1123
+ * `loader ${info.request.url} (route ${id})`,
1124
+ * impl
1125
+ * ),
1126
+ * action: (impl, info) => logExecution(
1127
+ * `action ${info.request.url} (route ${id})`,
1128
+ * impl
1129
+ * ),
1130
+ * })
1131
+ * }
1132
+ * };
1133
+ *
1134
+ * async function logExecution(label: string, impl: () => Promise<void>) {
1135
+ * let start = performance.now();
1136
+ * console.log(`start ${label}`);
1137
+ * await impl();
1138
+ * let duration = Math.round(performance.now() - start);
1139
+ * console.log(`end ${label} (${duration}ms)`);
1140
+ * }
1141
+ * ```
1117
1142
  */
1118
- navigate(to: number): Promise<void>;
1143
+ unstable_instrumentations?: unstable_ClientInstrumentation[];
1119
1144
  /**
1120
- * Navigate to the given path
1121
- * @param to Path to navigate to
1122
- * @param opts Navigation options (method, submission, etc.)
1145
+ * Override the default data strategy of loading in parallel.
1146
+ * Only intended for advanced usage.
1123
1147
  */
1124
- navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;
1148
+ dataStrategy?: DataStrategyFunction;
1125
1149
  /**
1126
- * @private
1127
- * PRIVATE - DO NOT USE
1128
- *
1129
- * Trigger a fetcher load/submission
1130
- *
1131
- * @param key Fetcher key
1132
- * @param routeId Route that owns the fetcher
1133
- * @param href href to fetch
1134
- * @param opts Fetcher options, (method, submission, etc.)
1150
+ * Lazily define portions of the route tree on navigations.
1135
1151
  */
1136
- fetch(key: string, routeId: string, href: string | null, opts?: RouterFetchOptions): Promise<void>;
1152
+ patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;
1153
+ }
1154
+ /**
1155
+ * Create a new {@link DataRouter} that manages the application path using an
1156
+ * in-memory [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1157
+ * stack. Useful for non-browser environments without a DOM API.
1158
+ *
1159
+ * @public
1160
+ * @category Data Routers
1161
+ * @mode data
1162
+ * @param routes Application routes
1163
+ * @param opts Options
1164
+ * @param {MemoryRouterOpts.basename} opts.basename n/a
1165
+ * @param {MemoryRouterOpts.dataStrategy} opts.dataStrategy n/a
1166
+ * @param {MemoryRouterOpts.future} opts.future n/a
1167
+ * @param {MemoryRouterOpts.getContext} opts.getContext n/a
1168
+ * @param {MemoryRouterOpts.hydrationData} opts.hydrationData n/a
1169
+ * @param {MemoryRouterOpts.initialEntries} opts.initialEntries n/a
1170
+ * @param {MemoryRouterOpts.initialIndex} opts.initialIndex n/a
1171
+ * @param {MemoryRouterOpts.unstable_instrumentations} opts.unstable_instrumentations n/a
1172
+ * @param {MemoryRouterOpts.patchRoutesOnNavigation} opts.patchRoutesOnNavigation n/a
1173
+ * @returns An initialized {@link DataRouter} to pass to {@link RouterProvider | `<RouterProvider>`}
1174
+ */
1175
+ declare function createMemoryRouter(routes: RouteObject[], opts?: MemoryRouterOpts): Router;
1176
+ /**
1177
+ * Function signature for client side error handling for loader/actions errors
1178
+ * and rendering errors via `componentDidCatch`
1179
+ */
1180
+ interface unstable_ClientOnErrorFunction {
1181
+ (error: unknown, errorInfo?: React.ErrorInfo): void;
1182
+ }
1183
+ /**
1184
+ * @category Types
1185
+ */
1186
+ interface RouterProviderProps {
1137
1187
  /**
1138
- * @private
1139
- * PRIVATE - DO NOT USE
1140
- *
1141
- * Trigger a revalidation of all current route loaders and fetcher loads
1188
+ * The {@link DataRouter} instance to use for navigation and data fetching.
1142
1189
  */
1143
- revalidate(): Promise<void>;
1190
+ router: Router;
1144
1191
  /**
1145
- * @private
1146
- * PRIVATE - DO NOT USE
1192
+ * The [`ReactDOM.flushSync`](https://react.dev/reference/react-dom/flushSync)
1193
+ * implementation to use for flushing updates.
1147
1194
  *
1148
- * Utility function to create an href for the given location
1149
- * @param location
1195
+ * You usually don't have to worry about this:
1196
+ * - The `RouterProvider` exported from `react-router/dom` handles this internally for you
1197
+ * - If you are rendering in a non-DOM environment, you can import
1198
+ * `RouterProvider` from `react-router` and ignore this prop
1150
1199
  */
1151
- createHref(location: Location | URL): string;
1200
+ flushSync?: (fn: () => unknown) => undefined;
1152
1201
  /**
1153
- * @private
1154
- * PRIVATE - DO NOT USE
1202
+ * An error handler function that will be called for any loader/action/render
1203
+ * errors that are encountered in your application. This is useful for
1204
+ * logging or reporting errors instead of the `ErrorBoundary` because it's not
1205
+ * subject to re-rendering and will only run one time per error.
1155
1206
  *
1156
- * Utility function to URL encode a destination path according to the internal
1157
- * history implementation
1158
- * @param to
1159
- */
1160
- encodeLocation(to: To): Path;
1161
- /**
1162
- * @private
1163
- * PRIVATE - DO NOT USE
1207
+ * The `errorInfo` parameter is passed along from
1208
+ * [`componentDidCatch`](https://react.dev/reference/react/Component#componentdidcatch)
1209
+ * and is only present for render errors.
1164
1210
  *
1165
- * Get/create a fetcher for the given key
1166
- * @param key
1211
+ * ```tsx
1212
+ * <RouterProvider unstable_onError=(error, errorInfo) => {
1213
+ * console.error(error, errorInfo);
1214
+ * reportToErrorService(error, errorInfo);
1215
+ * }} />
1216
+ * ```
1167
1217
  */
1168
- getFetcher<TData = any>(key: string): Fetcher<TData>;
1218
+ unstable_onError?: unstable_ClientOnErrorFunction;
1219
+ }
1220
+ /**
1221
+ * Render the UI for the given {@link DataRouter}. This component should
1222
+ * typically be at the top of an app's element tree.
1223
+ *
1224
+ * ```tsx
1225
+ * import { createBrowserRouter } from "react-router";
1226
+ * import { RouterProvider } from "react-router/dom";
1227
+ * import { createRoot } from "react-dom/client";
1228
+ *
1229
+ * const router = createBrowserRouter(routes);
1230
+ * createRoot(document.getElementById("root")).render(
1231
+ * <RouterProvider router={router} />
1232
+ * );
1233
+ * ```
1234
+ *
1235
+ * <docs-info>Please note that this component is exported both from
1236
+ * `react-router` and `react-router/dom` with the only difference being that the
1237
+ * latter automatically wires up `react-dom`'s [`flushSync`](https://react.dev/reference/react-dom/flushSync)
1238
+ * implementation. You _almost always_ want to use the version from
1239
+ * `react-router/dom` unless you're running in a non-DOM environment.</docs-info>
1240
+ *
1241
+ *
1242
+ * @public
1243
+ * @category Data Routers
1244
+ * @mode data
1245
+ * @param props Props
1246
+ * @param {RouterProviderProps.flushSync} props.flushSync n/a
1247
+ * @param {RouterProviderProps.unstable_onError} props.unstable_onError n/a
1248
+ * @param {RouterProviderProps.router} props.router n/a
1249
+ * @returns React element for the rendered router
1250
+ */
1251
+ declare function RouterProvider({ router, flushSync: reactDomFlushSyncImpl, unstable_onError, }: RouterProviderProps): React.ReactElement;
1252
+ /**
1253
+ * @category Types
1254
+ */
1255
+ interface MemoryRouterProps {
1169
1256
  /**
1170
- * @internal
1171
- * PRIVATE - DO NOT USE
1172
- *
1173
- * Reset the fetcher for a given key
1174
- * @param key
1257
+ * Application basename
1175
1258
  */
1176
- resetFetcher(key: string, opts?: {
1177
- reason?: unknown;
1178
- }): void;
1259
+ basename?: string;
1179
1260
  /**
1180
- * @private
1181
- * PRIVATE - DO NOT USE
1182
- *
1183
- * Delete the fetcher for a given key
1184
- * @param key
1261
+ * Nested {@link Route} elements describing the route tree
1185
1262
  */
1186
- deleteFetcher(key: string): void;
1263
+ children?: React.ReactNode;
1187
1264
  /**
1188
- * @private
1189
- * PRIVATE - DO NOT USE
1190
- *
1191
- * Cleanup listeners and abort any in-progress loads
1265
+ * Initial entries in the in-memory history stack
1192
1266
  */
1193
- dispose(): void;
1267
+ initialEntries?: InitialEntry[];
1194
1268
  /**
1195
- * @private
1196
- * PRIVATE - DO NOT USE
1197
- *
1198
- * Get a navigation blocker
1199
- * @param key The identifier for the blocker
1200
- * @param fn The blocker function implementation
1269
+ * Index of `initialEntries` the application should initialize to
1201
1270
  */
1202
- getBlocker(key: string, fn: BlockerFunction): Blocker;
1271
+ initialIndex?: number;
1272
+ }
1273
+ /**
1274
+ * A declarative {@link Router | `<Router>`} that stores all entries in memory.
1275
+ *
1276
+ * @public
1277
+ * @category Declarative Routers
1278
+ * @mode declarative
1279
+ * @param props Props
1280
+ * @param {MemoryRouterProps.basename} props.basename n/a
1281
+ * @param {MemoryRouterProps.children} props.children n/a
1282
+ * @param {MemoryRouterProps.initialEntries} props.initialEntries n/a
1283
+ * @param {MemoryRouterProps.initialIndex} props.initialIndex n/a
1284
+ * @returns A declarative in-memory {@link Router | `<Router>`} for client-side
1285
+ * routing.
1286
+ */
1287
+ declare function MemoryRouter({ basename, children, initialEntries, initialIndex, }: MemoryRouterProps): React.ReactElement;
1288
+ /**
1289
+ * @category Types
1290
+ */
1291
+ interface NavigateProps {
1203
1292
  /**
1204
- * @private
1205
- * PRIVATE - DO NOT USE
1206
- *
1207
- * Delete a navigation blocker
1208
- * @param key The identifier for the blocker
1293
+ * The path to navigate to. This can be a string or a {@link Path} object
1209
1294
  */
1210
- deleteBlocker(key: string): void;
1295
+ to: To;
1211
1296
  /**
1212
- * @private
1213
- * PRIVATE DO NOT USE
1214
- *
1215
- * Patch additional children routes into an existing parent route
1216
- * @param routeId The parent route id or a callback function accepting `patch`
1217
- * to perform batch patching
1218
- * @param children The additional children routes
1219
- * @param unstable_allowElementMutations Allow mutation or route elements on
1220
- * existing routes. Intended for RSC-usage
1221
- * only.
1297
+ * Whether to replace the current entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1298
+ * stack
1222
1299
  */
1223
- patchRoutes(routeId: string | null, children: AgnosticRouteObject[], unstable_allowElementMutations?: boolean): void;
1300
+ replace?: boolean;
1224
1301
  /**
1225
- * @private
1226
- * PRIVATE - DO NOT USE
1227
- *
1228
- * HMR needs to pass in-flight route updates to React Router
1229
- * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)
1302
+ * State to pass to the new {@link Location} to store in [`history.state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state).
1230
1303
  */
1231
- _internalSetRoutes(routes: AgnosticRouteObject[]): void;
1304
+ state?: any;
1232
1305
  /**
1233
- * @private
1234
- * PRIVATE - DO NOT USE
1235
- *
1236
- * Cause subscribers to re-render. This is used to force a re-render.
1306
+ * How to interpret relative routing in the `to` prop.
1307
+ * See {@link RelativeRoutingType}.
1237
1308
  */
1238
- _internalSetStateDoNotUseOrYouWillBreakYourApp(state: Partial<RouterState>): void;
1309
+ relative?: RelativeRoutingType;
1310
+ }
1311
+ /**
1312
+ * A component-based version of {@link useNavigate} to use in a
1313
+ * [`React.Component` class](https://react.dev/reference/react/Component) where
1314
+ * hooks cannot be used.
1315
+ *
1316
+ * It's recommended to avoid using this component in favor of {@link useNavigate}.
1317
+ *
1318
+ * @example
1319
+ * <Navigate to="/tasks" />
1320
+ *
1321
+ * @public
1322
+ * @category Components
1323
+ * @param props Props
1324
+ * @param {NavigateProps.relative} props.relative n/a
1325
+ * @param {NavigateProps.replace} props.replace n/a
1326
+ * @param {NavigateProps.state} props.state n/a
1327
+ * @param {NavigateProps.to} props.to n/a
1328
+ * @returns {void}
1329
+ *
1330
+ */
1331
+ declare function Navigate({ to, replace, state, relative, }: NavigateProps): null;
1332
+ /**
1333
+ * @category Types
1334
+ */
1335
+ interface OutletProps {
1239
1336
  /**
1240
- * @private
1241
- * PRIVATE - DO NOT USE
1337
+ * Provides a context value to the element tree below the outlet. Use when
1338
+ * the parent route needs to provide values to child routes.
1242
1339
  *
1243
- * Internal fetch AbortControllers accessed by unit tests
1340
+ * ```tsx
1341
+ * <Outlet context={myContextValue} />
1342
+ * ```
1343
+ *
1344
+ * Access the context with {@link useOutletContext}.
1244
1345
  */
1245
- _internalFetchControllers: Map<string, AbortController>;
1346
+ context?: unknown;
1246
1347
  }
1247
1348
  /**
1248
- * State maintained internally by the router. During a navigation, all states
1249
- * reflect the "old" location unless otherwise noted.
1349
+ * Renders the matching child route of a parent route or nothing if no child
1350
+ * route matches.
1351
+ *
1352
+ * @example
1353
+ * import { Outlet } from "react-router";
1354
+ *
1355
+ * export default function SomeParent() {
1356
+ * return (
1357
+ * <div>
1358
+ * <h1>Parent Content</h1>
1359
+ * <Outlet />
1360
+ * </div>
1361
+ * );
1362
+ * }
1363
+ *
1364
+ * @public
1365
+ * @category Components
1366
+ * @param props Props
1367
+ * @param {OutletProps.context} props.context n/a
1368
+ * @returns React element for the rendered outlet or `null` if no child route matches.
1250
1369
  */
1251
- interface RouterState {
1370
+ declare function Outlet(props: OutletProps): React.ReactElement | null;
1371
+ /**
1372
+ * @category Types
1373
+ */
1374
+ interface PathRouteProps {
1252
1375
  /**
1253
- * The action of the most recent navigation
1376
+ * Whether the path should be case-sensitive. Defaults to `false`.
1254
1377
  */
1255
- historyAction: Action;
1378
+ caseSensitive?: NonIndexRouteObject["caseSensitive"];
1256
1379
  /**
1257
- * The current location reflected by the router
1380
+ * The path pattern to match. If unspecified or empty, then this becomes a
1381
+ * layout route.
1258
1382
  */
1259
- location: Location;
1383
+ path?: NonIndexRouteObject["path"];
1260
1384
  /**
1261
- * The current set of route matches
1385
+ * The unique identifier for this route (for use with {@link DataRouter}s)
1262
1386
  */
1263
- matches: AgnosticDataRouteMatch[];
1387
+ id?: NonIndexRouteObject["id"];
1264
1388
  /**
1265
- * Tracks whether we've completed our initial data load
1389
+ * A function that returns a promise that resolves to the route object.
1390
+ * Used for code-splitting routes.
1391
+ * See [`lazy`](../../start/data/route-object#lazy).
1266
1392
  */
1267
- initialized: boolean;
1393
+ lazy?: LazyRouteFunction<NonIndexRouteObject>;
1268
1394
  /**
1269
- * Current scroll position we should start at for a new view
1270
- * - number -> scroll position to restore to
1271
- * - false -> do not restore scroll at all (used during submissions/revalidations)
1272
- * - null -> don't have a saved position, scroll to hash or top of page
1395
+ * The route middleware.
1396
+ * See [`middleware`](../../start/data/route-object#middleware).
1273
1397
  */
1274
- restoreScrollPosition: number | false | null;
1398
+ middleware?: NonIndexRouteObject["middleware"];
1275
1399
  /**
1276
- * Indicate whether this navigation should skip resetting the scroll position
1277
- * if we are unable to restore the scroll position
1400
+ * The route loader.
1401
+ * See [`loader`](../../start/data/route-object#loader).
1278
1402
  */
1279
- preventScrollReset: boolean;
1403
+ loader?: NonIndexRouteObject["loader"];
1280
1404
  /**
1281
- * Tracks the state of the current navigation
1405
+ * The route action.
1406
+ * See [`action`](../../start/data/route-object#action).
1282
1407
  */
1283
- navigation: Navigation;
1408
+ action?: NonIndexRouteObject["action"];
1409
+ hasErrorBoundary?: NonIndexRouteObject["hasErrorBoundary"];
1284
1410
  /**
1285
- * Tracks any in-progress revalidations
1411
+ * The route shouldRevalidate function.
1412
+ * See [`shouldRevalidate`](../../start/data/route-object#shouldRevalidate).
1286
1413
  */
1287
- revalidation: RevalidationState;
1414
+ shouldRevalidate?: NonIndexRouteObject["shouldRevalidate"];
1288
1415
  /**
1289
- * Data from the loaders for the current matches
1416
+ * The route handle.
1290
1417
  */
1291
- loaderData: RouteData;
1418
+ handle?: NonIndexRouteObject["handle"];
1292
1419
  /**
1293
- * Data from the action for the current matches
1420
+ * Whether this is an index route.
1294
1421
  */
1295
- actionData: RouteData | null;
1422
+ index?: false;
1296
1423
  /**
1297
- * Errors caught from loaders for the current matches
1424
+ * Child Route components
1298
1425
  */
1299
- errors: RouteData | null;
1426
+ children?: React.ReactNode;
1300
1427
  /**
1301
- * Map of current fetchers
1428
+ * The React element to render when this Route matches.
1429
+ * Mutually exclusive with `Component`.
1302
1430
  */
1303
- fetchers: Map<string, Fetcher>;
1431
+ element?: React.ReactNode | null;
1304
1432
  /**
1305
- * Map of current blockers
1433
+ * The React element to render while this router is loading data.
1434
+ * Mutually exclusive with `HydrateFallback`.
1306
1435
  */
1307
- blockers: Map<string, Blocker>;
1308
- }
1309
- /**
1310
- * Data that can be passed into hydrate a Router from SSR
1311
- */
1312
- type HydrationState = Partial<Pick<RouterState, "loaderData" | "actionData" | "errors">>;
1313
- /**
1314
- * Future flags to toggle new feature behavior
1315
- */
1316
- interface FutureConfig {
1317
- }
1318
- /**
1319
- * Initialization options for createRouter
1320
- */
1321
- interface RouterInit {
1322
- routes: AgnosticRouteObject[];
1323
- history: History;
1324
- basename?: string;
1325
- getContext?: () => MaybePromise<RouterContextProvider>;
1326
- mapRouteProperties?: MapRoutePropertiesFunction;
1327
- future?: Partial<FutureConfig>;
1328
- hydrationRouteProperties?: string[];
1329
- hydrationData?: HydrationState;
1330
- window?: Window;
1331
- dataStrategy?: DataStrategyFunction;
1332
- patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;
1436
+ hydrateFallbackElement?: React.ReactNode | null;
1437
+ /**
1438
+ * The React element to render at this route if an error occurs.
1439
+ * Mutually exclusive with `ErrorBoundary`.
1440
+ */
1441
+ errorElement?: React.ReactNode | null;
1442
+ /**
1443
+ * The React Component to render when this route matches.
1444
+ * Mutually exclusive with `element`.
1445
+ */
1446
+ Component?: React.ComponentType | null;
1447
+ /**
1448
+ * The React Component to render while this router is loading data.
1449
+ * Mutually exclusive with `hydrateFallbackElement`.
1450
+ */
1451
+ HydrateFallback?: React.ComponentType | null;
1452
+ /**
1453
+ * The React Component to render at this route if an error occurs.
1454
+ * Mutually exclusive with `errorElement`.
1455
+ */
1456
+ ErrorBoundary?: React.ComponentType | null;
1333
1457
  }
1334
1458
  /**
1335
- * State returned from a server-side query() call
1459
+ * @category Types
1336
1460
  */
1337
- interface StaticHandlerContext {
1338
- basename: Router$1["basename"];
1339
- location: RouterState["location"];
1340
- matches: RouterState["matches"];
1341
- loaderData: RouterState["loaderData"];
1342
- actionData: RouterState["actionData"];
1343
- errors: RouterState["errors"];
1344
- statusCode: number;
1345
- loaderHeaders: Record<string, Headers>;
1346
- actionHeaders: Record<string, Headers>;
1347
- _deepestRenderedBoundaryId?: string | null;
1461
+ interface LayoutRouteProps extends PathRouteProps {
1348
1462
  }
1349
1463
  /**
1350
- * A StaticHandler instance manages a singular SSR navigation/fetch event
1464
+ * @category Types
1351
1465
  */
1352
- interface StaticHandler {
1353
- dataRoutes: AgnosticDataRouteObject[];
1354
- query(request: Request, opts?: {
1355
- requestContext?: unknown;
1356
- filterMatchesToLoad?: (match: AgnosticDataRouteMatch) => boolean;
1357
- skipLoaderErrorBubbling?: boolean;
1358
- skipRevalidation?: boolean;
1359
- dataStrategy?: DataStrategyFunction<unknown>;
1360
- generateMiddlewareResponse?: (query: (r: Request, args?: {
1361
- filterMatchesToLoad?: (match: AgnosticDataRouteMatch) => boolean;
1362
- }) => Promise<StaticHandlerContext | Response>) => MaybePromise<Response>;
1363
- }): Promise<StaticHandlerContext | Response>;
1364
- queryRoute(request: Request, opts?: {
1365
- routeId?: string;
1366
- requestContext?: unknown;
1367
- dataStrategy?: DataStrategyFunction<unknown>;
1368
- generateMiddlewareResponse?: (queryRoute: (r: Request) => Promise<Response>) => MaybePromise<Response>;
1369
- }): Promise<any>;
1370
- }
1371
- type ViewTransitionOpts = {
1372
- currentLocation: Location;
1373
- nextLocation: Location;
1374
- };
1375
- /**
1376
- * Subscriber function signature for changes to router state
1377
- */
1378
- interface RouterSubscriber {
1379
- (state: RouterState, opts: {
1380
- deletedFetchers: string[];
1381
- viewTransitionOpts?: ViewTransitionOpts;
1382
- flushSync: boolean;
1383
- }): void;
1384
- }
1385
- /**
1386
- * Function signature for determining the key to be used in scroll restoration
1387
- * for a given location
1388
- */
1389
- interface GetScrollRestorationKeyFunction {
1390
- (location: Location, matches: UIMatch[]): string | null;
1391
- }
1392
- /**
1393
- * Function signature for determining the current scroll position
1394
- */
1395
- interface GetScrollPositionFunction {
1396
- (): number;
1397
- }
1398
- /**
1399
- * - "route": relative to the route hierarchy so `..` means remove all segments
1400
- * of the current route even if it has many. For example, a `route("posts/:id")`
1401
- * would have both `:id` and `posts` removed from the url.
1402
- * - "path": relative to the pathname so `..` means remove one segment of the
1403
- * pathname. For example, a `route("posts/:id")` would have only `:id` removed
1404
- * from the url.
1405
- */
1406
- type RelativeRoutingType = "route" | "path";
1407
- type BaseNavigateOrFetchOptions = {
1408
- preventScrollReset?: boolean;
1409
- relative?: RelativeRoutingType;
1410
- flushSync?: boolean;
1411
- };
1412
- type BaseNavigateOptions = BaseNavigateOrFetchOptions & {
1413
- replace?: boolean;
1414
- state?: any;
1415
- fromRouteId?: string;
1416
- viewTransition?: boolean;
1417
- };
1418
- type BaseSubmissionOptions = {
1419
- formMethod?: HTMLFormMethod;
1420
- formEncType?: FormEncType;
1421
- } & ({
1422
- formData: FormData;
1423
- body?: undefined;
1424
- } | {
1425
- formData?: undefined;
1426
- body: any;
1427
- });
1428
- /**
1429
- * Options for a navigate() call for a normal (non-submission) navigation
1430
- */
1431
- type LinkNavigateOptions = BaseNavigateOptions;
1432
- /**
1433
- * Options for a navigate() call for a submission navigation
1434
- */
1435
- type SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;
1436
- /**
1437
- * Options to pass to navigate() for a navigation
1438
- */
1439
- type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions;
1440
- /**
1441
- * Options for a fetch() load
1442
- */
1443
- type LoadFetchOptions = BaseNavigateOrFetchOptions;
1444
- /**
1445
- * Options for a fetch() submission
1446
- */
1447
- type SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;
1448
- /**
1449
- * Options to pass to fetch()
1450
- */
1451
- type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;
1452
- /**
1453
- * Potential states for state.navigation
1454
- */
1455
- type NavigationStates = {
1456
- Idle: {
1457
- state: "idle";
1458
- location: undefined;
1459
- formMethod: undefined;
1460
- formAction: undefined;
1461
- formEncType: undefined;
1462
- formData: undefined;
1463
- json: undefined;
1464
- text: undefined;
1465
- };
1466
- Loading: {
1467
- state: "loading";
1468
- location: Location;
1469
- formMethod: Submission["formMethod"] | undefined;
1470
- formAction: Submission["formAction"] | undefined;
1471
- formEncType: Submission["formEncType"] | undefined;
1472
- formData: Submission["formData"] | undefined;
1473
- json: Submission["json"] | undefined;
1474
- text: Submission["text"] | undefined;
1475
- };
1476
- Submitting: {
1477
- state: "submitting";
1478
- location: Location;
1479
- formMethod: Submission["formMethod"];
1480
- formAction: Submission["formAction"];
1481
- formEncType: Submission["formEncType"];
1482
- formData: Submission["formData"];
1483
- json: Submission["json"];
1484
- text: Submission["text"];
1485
- };
1486
- };
1487
- type Navigation = NavigationStates[keyof NavigationStates];
1488
- type RevalidationState = "idle" | "loading";
1489
- /**
1490
- * Potential states for fetchers
1491
- */
1492
- type FetcherStates<TData = any> = {
1466
+ interface IndexRouteProps {
1493
1467
  /**
1494
- * The fetcher is not calling a loader or action
1495
- *
1496
- * ```tsx
1497
- * fetcher.state === "idle"
1498
- * ```
1468
+ * Whether the path should be case-sensitive. Defaults to `false`.
1499
1469
  */
1500
- Idle: {
1501
- state: "idle";
1502
- formMethod: undefined;
1503
- formAction: undefined;
1504
- formEncType: undefined;
1505
- text: undefined;
1506
- formData: undefined;
1507
- json: undefined;
1508
- /**
1509
- * If the fetcher has never been called, this will be undefined.
1510
- */
1511
- data: TData | undefined;
1512
- };
1470
+ caseSensitive?: IndexRouteObject["caseSensitive"];
1513
1471
  /**
1514
- * The fetcher is loading data from a {@link LoaderFunction | loader} from a
1515
- * call to {@link FetcherWithComponents.load | `fetcher.load`}.
1516
- *
1517
- * ```tsx
1518
- * // somewhere
1519
- * <button onClick={() => fetcher.load("/some/route") }>Load</button>
1520
- *
1521
- * // the state will update
1522
- * fetcher.state === "loading"
1523
- * ```
1472
+ * The path pattern to match. If unspecified or empty, then this becomes a
1473
+ * layout route.
1524
1474
  */
1525
- Loading: {
1526
- state: "loading";
1527
- formMethod: Submission["formMethod"] | undefined;
1528
- formAction: Submission["formAction"] | undefined;
1529
- formEncType: Submission["formEncType"] | undefined;
1530
- text: Submission["text"] | undefined;
1531
- formData: Submission["formData"] | undefined;
1532
- json: Submission["json"] | undefined;
1533
- data: TData | undefined;
1534
- };
1475
+ path?: IndexRouteObject["path"];
1535
1476
  /**
1536
- 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`}.
1537
-
1538
- ```tsx
1539
- // somewhere
1540
- <input
1541
- onChange={e => {
1542
- fetcher.submit(event.currentTarget.form, { method: "post" });
1543
- }}
1544
- />
1545
-
1546
- // the state will update
1547
- fetcher.state === "submitting"
1548
-
1549
- // and formData will be available
1550
- fetcher.formData
1551
- ```
1477
+ * The unique identifier for this route (for use with {@link DataRouter}s)
1552
1478
  */
1553
- Submitting: {
1554
- state: "submitting";
1555
- formMethod: Submission["formMethod"];
1556
- formAction: Submission["formAction"];
1557
- formEncType: Submission["formEncType"];
1558
- text: Submission["text"];
1559
- formData: Submission["formData"];
1560
- json: Submission["json"];
1561
- data: TData | undefined;
1562
- };
1563
- };
1564
- type Fetcher<TData = any> = FetcherStates<TData>[keyof FetcherStates<TData>];
1565
- interface BlockerBlocked {
1566
- state: "blocked";
1567
- reset: () => void;
1568
- proceed: () => void;
1569
- location: Location;
1570
- }
1571
- interface BlockerUnblocked {
1572
- state: "unblocked";
1573
- reset: undefined;
1574
- proceed: undefined;
1575
- location: undefined;
1576
- }
1577
- interface BlockerProceeding {
1578
- state: "proceeding";
1579
- reset: undefined;
1580
- proceed: undefined;
1581
- location: Location;
1479
+ id?: IndexRouteObject["id"];
1480
+ /**
1481
+ * A function that returns a promise that resolves to the route object.
1482
+ * Used for code-splitting routes.
1483
+ * See [`lazy`](../../start/data/route-object#lazy).
1484
+ */
1485
+ lazy?: LazyRouteFunction<IndexRouteObject>;
1486
+ /**
1487
+ * The route middleware.
1488
+ * See [`middleware`](../../start/data/route-object#middleware).
1489
+ */
1490
+ middleware?: IndexRouteObject["middleware"];
1491
+ /**
1492
+ * The route loader.
1493
+ * See [`loader`](../../start/data/route-object#loader).
1494
+ */
1495
+ loader?: IndexRouteObject["loader"];
1496
+ /**
1497
+ * The route action.
1498
+ * See [`action`](../../start/data/route-object#action).
1499
+ */
1500
+ action?: IndexRouteObject["action"];
1501
+ hasErrorBoundary?: IndexRouteObject["hasErrorBoundary"];
1502
+ /**
1503
+ * The route shouldRevalidate function.
1504
+ * See [`shouldRevalidate`](../../start/data/route-object#shouldRevalidate).
1505
+ */
1506
+ shouldRevalidate?: IndexRouteObject["shouldRevalidate"];
1507
+ /**
1508
+ * The route handle.
1509
+ */
1510
+ handle?: IndexRouteObject["handle"];
1511
+ /**
1512
+ * Whether this is an index route.
1513
+ */
1514
+ index: true;
1515
+ /**
1516
+ * Child Route components
1517
+ */
1518
+ children?: undefined;
1519
+ /**
1520
+ * The React element to render when this Route matches.
1521
+ * Mutually exclusive with `Component`.
1522
+ */
1523
+ element?: React.ReactNode | null;
1524
+ /**
1525
+ * The React element to render while this router is loading data.
1526
+ * Mutually exclusive with `HydrateFallback`.
1527
+ */
1528
+ hydrateFallbackElement?: React.ReactNode | null;
1529
+ /**
1530
+ * The React element to render at this route if an error occurs.
1531
+ * Mutually exclusive with `ErrorBoundary`.
1532
+ */
1533
+ errorElement?: React.ReactNode | null;
1534
+ /**
1535
+ * The React Component to render when this route matches.
1536
+ * Mutually exclusive with `element`.
1537
+ */
1538
+ Component?: React.ComponentType | null;
1539
+ /**
1540
+ * The React Component to render while this router is loading data.
1541
+ * Mutually exclusive with `hydrateFallbackElement`.
1542
+ */
1543
+ HydrateFallback?: React.ComponentType | null;
1544
+ /**
1545
+ * The React Component to render at this route if an error occurs.
1546
+ * Mutually exclusive with `errorElement`.
1547
+ */
1548
+ ErrorBoundary?: React.ComponentType | null;
1582
1549
  }
1583
- type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;
1584
- type BlockerFunction = (args: {
1585
- currentLocation: Location;
1586
- nextLocation: Location;
1587
- historyAction: Action;
1588
- }) => boolean;
1589
- declare const IDLE_NAVIGATION: NavigationStates["Idle"];
1590
- declare const IDLE_FETCHER: FetcherStates["Idle"];
1591
- declare const IDLE_BLOCKER: BlockerUnblocked;
1550
+ type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;
1592
1551
  /**
1593
- * Create a router and listen to history POP navigations
1552
+ * Configures an element to render when a pattern matches the current location.
1553
+ * It must be rendered within a {@link Routes} element. Note that these routes
1554
+ * do not participate in data loading, actions, code splitting, or any other
1555
+ * route module features.
1556
+ *
1557
+ * @example
1558
+ * // Usually used in a declarative router
1559
+ * function App() {
1560
+ * return (
1561
+ * <BrowserRouter>
1562
+ * <Routes>
1563
+ * <Route index element={<StepOne />} />
1564
+ * <Route path="step-2" element={<StepTwo />} />
1565
+ * <Route path="step-3" element={<StepThree />} />
1566
+ * </Routes>
1567
+ * </BrowserRouter>
1568
+ * );
1569
+ * }
1570
+ *
1571
+ * // But can be used with a data router as well if you prefer the JSX notation
1572
+ * const routes = createRoutesFromElements(
1573
+ * <>
1574
+ * <Route index loader={step1Loader} Component={StepOne} />
1575
+ * <Route path="step-2" loader={step2Loader} Component={StepTwo} />
1576
+ * <Route path="step-3" loader={step3Loader} Component={StepThree} />
1577
+ * </>
1578
+ * );
1579
+ *
1580
+ * const router = createBrowserRouter(routes);
1581
+ *
1582
+ * function App() {
1583
+ * return <RouterProvider router={router} />;
1584
+ * }
1585
+ *
1586
+ * @public
1587
+ * @category Components
1588
+ * @param props Props
1589
+ * @param {PathRouteProps.action} props.action n/a
1590
+ * @param {PathRouteProps.caseSensitive} props.caseSensitive n/a
1591
+ * @param {PathRouteProps.Component} props.Component n/a
1592
+ * @param {PathRouteProps.children} props.children n/a
1593
+ * @param {PathRouteProps.element} props.element n/a
1594
+ * @param {PathRouteProps.ErrorBoundary} props.ErrorBoundary n/a
1595
+ * @param {PathRouteProps.errorElement} props.errorElement n/a
1596
+ * @param {PathRouteProps.handle} props.handle n/a
1597
+ * @param {PathRouteProps.HydrateFallback} props.HydrateFallback n/a
1598
+ * @param {PathRouteProps.hydrateFallbackElement} props.hydrateFallbackElement n/a
1599
+ * @param {PathRouteProps.id} props.id n/a
1600
+ * @param {PathRouteProps.index} props.index n/a
1601
+ * @param {PathRouteProps.lazy} props.lazy n/a
1602
+ * @param {PathRouteProps.loader} props.loader n/a
1603
+ * @param {PathRouteProps.path} props.path n/a
1604
+ * @param {PathRouteProps.shouldRevalidate} props.shouldRevalidate n/a
1605
+ * @returns {void}
1594
1606
  */
1595
- declare function createRouter(init: RouterInit): Router$1;
1596
- interface CreateStaticHandlerOptions {
1597
- basename?: string;
1598
- mapRouteProperties?: MapRoutePropertiesFunction;
1599
- future?: {};
1600
- }
1601
-
1602
- declare function mapRouteProperties(route: RouteObject): Partial<RouteObject> & {
1603
- hasErrorBoundary: boolean;
1604
- };
1605
- declare const hydrationRouteProperties: (keyof RouteObject)[];
1607
+ declare function Route(props: RouteProps): React.ReactElement | null;
1606
1608
  /**
1607
- * @category Data Routers
1609
+ * @category Types
1608
1610
  */
1609
- interface MemoryRouterOpts {
1611
+ interface RouterProps {
1610
1612
  /**
1611
- * Basename path for the application.
1613
+ * The base path for the application. This is prepended to all locations
1612
1614
  */
1613
1615
  basename?: string;
1614
1616
  /**
1615
- * A function that returns an {@link RouterContextProvider} instance
1616
- * which is provided as the `context` argument to client [`action`](../../start/data/route-object#action)s,
1617
- * [`loader`](../../start/data/route-object#loader)s and [middleware](../../how-to/middleware).
1618
- * This function is called to generate a fresh `context` instance on each
1619
- * navigation or fetcher call.
1617
+ * Nested {@link Route} elements describing the route tree
1620
1618
  */
1621
- getContext?: RouterInit["getContext"];
1619
+ children?: React.ReactNode;
1622
1620
  /**
1623
- * Future flags to enable for the router.
1621
+ * The location to match against. Defaults to the current location.
1622
+ * This can be a string or a {@link Location} object.
1624
1623
  */
1625
- future?: Partial<FutureConfig>;
1624
+ location: Partial<Location> | string;
1626
1625
  /**
1627
- * Hydration data to initialize the router with if you have already performed
1628
- * data loading on the server.
1626
+ * The type of navigation that triggered this `location` change.
1627
+ * Defaults to {@link NavigationType.Pop}.
1629
1628
  */
1630
- hydrationData?: HydrationState;
1629
+ navigationType?: Action;
1631
1630
  /**
1632
- * Initial entries in the in-memory history stack
1631
+ * The navigator to use for navigation. This is usually a history object
1632
+ * or a custom navigator that implements the {@link Navigator} interface.
1633
1633
  */
1634
- initialEntries?: InitialEntry[];
1634
+ navigator: Navigator;
1635
1635
  /**
1636
- * Index of `initialEntries` the application should initialize to
1636
+ * Whether this router is static or not (used for SSR). If `true`, the router
1637
+ * will not be reactive to location changes.
1637
1638
  */
1638
- initialIndex?: number;
1639
+ static?: boolean;
1640
+ }
1641
+ /**
1642
+ * Provides location context for the rest of the app.
1643
+ *
1644
+ * Note: You usually won't render a `<Router>` directly. Instead, you'll render a
1645
+ * router that is more specific to your environment such as a {@link BrowserRouter}
1646
+ * in web browsers or a {@link ServerRouter} for server rendering.
1647
+ *
1648
+ * @public
1649
+ * @category Declarative Routers
1650
+ * @mode declarative
1651
+ * @param props Props
1652
+ * @param {RouterProps.basename} props.basename n/a
1653
+ * @param {RouterProps.children} props.children n/a
1654
+ * @param {RouterProps.location} props.location n/a
1655
+ * @param {RouterProps.navigationType} props.navigationType n/a
1656
+ * @param {RouterProps.navigator} props.navigator n/a
1657
+ * @param {RouterProps.static} props.static n/a
1658
+ * @returns React element for the rendered router or `null` if the location does
1659
+ * not match the {@link props.basename}
1660
+ */
1661
+ declare function Router$1({ basename: basenameProp, children, location: locationProp, navigationType, navigator, static: staticProp, }: RouterProps): React.ReactElement | null;
1662
+ /**
1663
+ * @category Types
1664
+ */
1665
+ interface RoutesProps {
1639
1666
  /**
1640
- * Override the default data strategy of loading in parallel.
1641
- * Only intended for advanced usage.
1667
+ * Nested {@link Route} elements
1642
1668
  */
1643
- dataStrategy?: DataStrategyFunction;
1669
+ children?: React.ReactNode;
1644
1670
  /**
1645
- * Lazily define portions of the route tree on navigations.
1671
+ * The {@link Location} to match against. Defaults to the current location.
1646
1672
  */
1647
- patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;
1673
+ location?: Partial<Location> | string;
1648
1674
  }
1649
1675
  /**
1650
- * Create a new {@link DataRouter} that manages the application path using an
1651
- * in-memory [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1652
- * stack. Useful for non-browser environments without a DOM API.
1676
+ * Renders a branch of {@link Route | `<Route>`s} that best matches the current
1677
+ * location. Note that these routes do not participate in [data loading](../../start/framework/route-module#loader),
1678
+ * [`action`](../../start/framework/route-module#action), code splitting, or
1679
+ * any other [route module](../../start/framework/route-module) features.
1680
+ *
1681
+ * @example
1682
+ * import { Route, Routes } from "react-router";
1683
+ *
1684
+ * <Routes>
1685
+ * <Route index element={<StepOne />} />
1686
+ * <Route path="step-2" element={<StepTwo />} />
1687
+ * <Route path="step-3" element={<StepThree />} />
1688
+ * </Routes>
1653
1689
  *
1654
1690
  * @public
1655
- * @category Data Routers
1656
- * @mode data
1657
- * @param routes Application routes
1658
- * @param opts Options
1659
- * @param {MemoryRouterOpts.basename} opts.basename n/a
1660
- * @param {MemoryRouterOpts.dataStrategy} opts.dataStrategy n/a
1661
- * @param {MemoryRouterOpts.future} opts.future n/a
1662
- * @param {MemoryRouterOpts.getContext} opts.getContext n/a
1663
- * @param {MemoryRouterOpts.hydrationData} opts.hydrationData n/a
1664
- * @param {MemoryRouterOpts.initialEntries} opts.initialEntries n/a
1665
- * @param {MemoryRouterOpts.initialIndex} opts.initialIndex n/a
1666
- * @param {MemoryRouterOpts.patchRoutesOnNavigation} opts.patchRoutesOnNavigation n/a
1667
- * @returns An initialized {@link DataRouter} to pass to {@link RouterProvider | `<RouterProvider>`}
1691
+ * @category Components
1692
+ * @param props Props
1693
+ * @param {RoutesProps.children} props.children n/a
1694
+ * @param {RoutesProps.location} props.location n/a
1695
+ * @returns React element for the rendered routes or `null` if no route matches
1668
1696
  */
1669
- declare function createMemoryRouter(routes: RouteObject[], opts?: MemoryRouterOpts): Router$1;
1697
+ declare function Routes({ children, location, }: RoutesProps): React.ReactElement | null;
1698
+ interface AwaitResolveRenderFunction<Resolve = any> {
1699
+ (data: Awaited<Resolve>): React.ReactNode;
1700
+ }
1670
1701
  /**
1671
- * Function signature for client side error handling for loader/actions errors
1672
- * and rendering errors via `componentDidCatch`
1702
+ * @category Types
1703
+ */
1704
+ interface AwaitProps<Resolve> {
1705
+ /**
1706
+ * When using a function, the resolved value is provided as the parameter.
1707
+ *
1708
+ * ```tsx [2]
1709
+ * <Await resolve={reviewsPromise}>
1710
+ * {(resolvedReviews) => <Reviews items={resolvedReviews} />}
1711
+ * </Await>
1712
+ * ```
1713
+ *
1714
+ * When using React elements, {@link useAsyncValue} will provide the
1715
+ * resolved value:
1716
+ *
1717
+ * ```tsx [2]
1718
+ * <Await resolve={reviewsPromise}>
1719
+ * <Reviews />
1720
+ * </Await>
1721
+ *
1722
+ * function Reviews() {
1723
+ * const resolvedReviews = useAsyncValue();
1724
+ * return <div>...</div>;
1725
+ * }
1726
+ * ```
1727
+ */
1728
+ children: React.ReactNode | AwaitResolveRenderFunction<Resolve>;
1729
+ /**
1730
+ * The error element renders instead of the `children` when the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
1731
+ * rejects.
1732
+ *
1733
+ * ```tsx
1734
+ * <Await
1735
+ * errorElement={<div>Oops</div>}
1736
+ * resolve={reviewsPromise}
1737
+ * >
1738
+ * <Reviews />
1739
+ * </Await>
1740
+ * ```
1741
+ *
1742
+ * To provide a more contextual error, you can use the {@link useAsyncError} in a
1743
+ * child component
1744
+ *
1745
+ * ```tsx
1746
+ * <Await
1747
+ * errorElement={<ReviewsError />}
1748
+ * resolve={reviewsPromise}
1749
+ * >
1750
+ * <Reviews />
1751
+ * </Await>
1752
+ *
1753
+ * function ReviewsError() {
1754
+ * const error = useAsyncError();
1755
+ * return <div>Error loading reviews: {error.message}</div>;
1756
+ * }
1757
+ * ```
1758
+ *
1759
+ * If you do not provide an `errorElement`, the rejected value will bubble up
1760
+ * to the nearest route-level [`ErrorBoundary`](../../start/framework/route-module#errorboundary)
1761
+ * and be accessible via the {@link useRouteError} hook.
1762
+ */
1763
+ errorElement?: React.ReactNode;
1764
+ /**
1765
+ * Takes a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
1766
+ * returned from a [`loader`](../../start/framework/route-module#loader) to be
1767
+ * resolved and rendered.
1768
+ *
1769
+ * ```tsx
1770
+ * import { Await, useLoaderData } from "react-router";
1771
+ *
1772
+ * export async function loader() {
1773
+ * let reviews = getReviews(); // not awaited
1774
+ * let book = await getBook();
1775
+ * return {
1776
+ * book,
1777
+ * reviews, // this is a promise
1778
+ * };
1779
+ * }
1780
+ *
1781
+ * export default function Book() {
1782
+ * const {
1783
+ * book,
1784
+ * reviews, // this is the same promise
1785
+ * } = useLoaderData();
1786
+ *
1787
+ * return (
1788
+ * <div>
1789
+ * <h1>{book.title}</h1>
1790
+ * <p>{book.description}</p>
1791
+ * <React.Suspense fallback={<ReviewsSkeleton />}>
1792
+ * <Await
1793
+ * // and is the promise we pass to Await
1794
+ * resolve={reviews}
1795
+ * >
1796
+ * <Reviews />
1797
+ * </Await>
1798
+ * </React.Suspense>
1799
+ * </div>
1800
+ * );
1801
+ * }
1802
+ * ```
1803
+ */
1804
+ resolve: Resolve;
1805
+ }
1806
+ /**
1807
+ * Used to render promise values with automatic error handling.
1808
+ *
1809
+ * **Note:** `<Await>` expects to be rendered inside a [`<React.Suspense>`](https://react.dev/reference/react/Suspense)
1810
+ *
1811
+ * @example
1812
+ * import { Await, useLoaderData } from "react-router";
1813
+ *
1814
+ * export async function loader() {
1815
+ * // not awaited
1816
+ * const reviews = getReviews();
1817
+ * // awaited (blocks the transition)
1818
+ * const book = await fetch("/api/book").then((res) => res.json());
1819
+ * return { book, reviews };
1820
+ * }
1821
+ *
1822
+ * function Book() {
1823
+ * const { book, reviews } = useLoaderData();
1824
+ * return (
1825
+ * <div>
1826
+ * <h1>{book.title}</h1>
1827
+ * <p>{book.description}</p>
1828
+ * <React.Suspense fallback={<ReviewsSkeleton />}>
1829
+ * <Await
1830
+ * resolve={reviews}
1831
+ * errorElement={
1832
+ * <div>Could not load reviews 😬</div>
1833
+ * }
1834
+ * children={(resolvedReviews) => (
1835
+ * <Reviews items={resolvedReviews} />
1836
+ * )}
1837
+ * />
1838
+ * </React.Suspense>
1839
+ * </div>
1840
+ * );
1841
+ * }
1842
+ *
1843
+ * @public
1844
+ * @category Components
1845
+ * @mode framework
1846
+ * @mode data
1847
+ * @param props Props
1848
+ * @param {AwaitProps.children} props.children n/a
1849
+ * @param {AwaitProps.errorElement} props.errorElement n/a
1850
+ * @param {AwaitProps.resolve} props.resolve n/a
1851
+ * @returns React element for the rendered awaited value
1673
1852
  */
1674
- interface unstable_ClientOnErrorFunction {
1675
- (error: unknown, errorInfo?: React.ErrorInfo): void;
1676
- }
1853
+ declare function Await<Resolve>({ children, errorElement, resolve, }: AwaitProps<Resolve>): React.JSX.Element;
1677
1854
  /**
1678
- * @category Types
1855
+ * Creates a route config from a React "children" object, which is usually
1856
+ * either a `<Route>` element or an array of them. Used internally by
1857
+ * `<Routes>` to create a route config from its children.
1858
+ *
1859
+ * @category Utils
1860
+ * @mode data
1861
+ * @param children The React children to convert into a route config
1862
+ * @param parentPath The path of the parent route, used to generate unique IDs.
1863
+ * @returns An array of {@link RouteObject}s that can be used with a {@link DataRouter}
1679
1864
  */
1680
- interface RouterProviderProps {
1681
- /**
1682
- * The {@link DataRouter} instance to use for navigation and data fetching.
1683
- */
1684
- router: Router$1;
1685
- /**
1686
- * The [`ReactDOM.flushSync`](https://react.dev/reference/react-dom/flushSync)
1687
- * implementation to use for flushing updates.
1688
- *
1689
- * You usually don't have to worry about this:
1690
- * - The `RouterProvider` exported from `react-router/dom` handles this internally for you
1691
- * - If you are rendering in a non-DOM environment, you can import
1692
- * `RouterProvider` from `react-router` and ignore this prop
1693
- */
1694
- flushSync?: (fn: () => unknown) => undefined;
1695
- /**
1696
- * An error handler function that will be called for any loader/action/render
1697
- * errors that are encountered in your application. This is useful for
1698
- * logging or reporting errors instead of the `ErrorBoundary` because it's not
1699
- * subject to re-rendering and will only run one time per error.
1700
- *
1701
- * The `errorInfo` parameter is passed along from
1702
- * [`componentDidCatch`](https://react.dev/reference/react/Component#componentdidcatch)
1703
- * and is only present for render errors.
1704
- *
1705
- * ```tsx
1706
- * <RouterProvider unstable_onError=(error, errorInfo) => {
1707
- * console.error(error, errorInfo);
1708
- * reportToErrorService(error, errorInfo);
1709
- * }} />
1710
- * ```
1711
- */
1712
- unstable_onError?: unstable_ClientOnErrorFunction;
1713
- }
1865
+ declare function createRoutesFromChildren(children: React.ReactNode, parentPath?: number[]): RouteObject[];
1714
1866
  /**
1715
- * Render the UI for the given {@link DataRouter}. This component should
1716
- * typically be at the top of an app's element tree.
1717
- *
1718
- * ```tsx
1719
- * import { createBrowserRouter } from "react-router";
1720
- * import { RouterProvider } from "react-router/dom";
1721
- * import { createRoot } from "react-dom/client";
1867
+ * Create route objects from JSX elements instead of arrays of objects.
1722
1868
  *
1723
- * const router = createBrowserRouter(routes);
1724
- * createRoot(document.getElementById("root")).render(
1725
- * <RouterProvider router={router} />
1869
+ * @example
1870
+ * const routes = createRoutesFromElements(
1871
+ * <>
1872
+ * <Route index loader={step1Loader} Component={StepOne} />
1873
+ * <Route path="step-2" loader={step2Loader} Component={StepTwo} />
1874
+ * <Route path="step-3" loader={step3Loader} Component={StepThree} />
1875
+ * </>
1726
1876
  * );
1727
- * ```
1728
1877
  *
1729
- * <docs-info>Please note that this component is exported both from
1730
- * `react-router` and `react-router/dom` with the only difference being that the
1731
- * latter automatically wires up `react-dom`'s [`flushSync`](https://react.dev/reference/react-dom/flushSync)
1732
- * implementation. You _almost always_ want to use the version from
1733
- * `react-router/dom` unless you're running in a non-DOM environment.</docs-info>
1878
+ * const router = createBrowserRouter(routes);
1734
1879
  *
1880
+ * function App() {
1881
+ * return <RouterProvider router={router} />;
1882
+ * }
1735
1883
  *
1884
+ * @name createRoutesFromElements
1736
1885
  * @public
1737
- * @category Data Routers
1886
+ * @category Utils
1738
1887
  * @mode data
1739
- * @param props Props
1740
- * @param {RouterProviderProps.flushSync} props.flushSync n/a
1741
- * @param {RouterProviderProps.unstable_onError} props.unstable_onError n/a
1742
- * @param {RouterProviderProps.router} props.router n/a
1743
- * @returns React element for the rendered router
1888
+ * @param children The React children to convert into a route config
1889
+ * @param parentPath The path of the parent route, used to generate unique IDs.
1890
+ * This is used for internal recursion and is not intended to be used by the
1891
+ * application developer.
1892
+ * @returns An array of {@link RouteObject}s that can be used with a {@link DataRouter}
1744
1893
  */
1745
- declare function RouterProvider({ router, flushSync: reactDomFlushSyncImpl, unstable_onError, }: RouterProviderProps): React.ReactElement;
1894
+ declare const createRoutesFromElements: typeof createRoutesFromChildren;
1746
1895
  /**
1747
- * @category Types
1896
+ * Renders the result of {@link matchRoutes} into a React element.
1897
+ *
1898
+ * @public
1899
+ * @category Utils
1900
+ * @param matches The array of {@link RouteMatch | route matches} to render
1901
+ * @returns A React element that renders the matched routes or `null` if no matches
1748
1902
  */
1749
- interface MemoryRouterProps {
1903
+ declare function renderMatches(matches: RouteMatch[] | null): React.ReactElement | null;
1904
+ declare function useRouteComponentProps(): {
1905
+ params: Readonly<Params<string>>;
1906
+ loaderData: any;
1907
+ actionData: any;
1908
+ matches: UIMatch<unknown, unknown>[];
1909
+ };
1910
+ type RouteComponentProps = ReturnType<typeof useRouteComponentProps>;
1911
+ type RouteComponentType = React.ComponentType<RouteComponentProps>;
1912
+ declare function WithComponentProps({ children, }: {
1913
+ children: React.ReactElement;
1914
+ }): React.ReactElement<any, string | React.JSXElementConstructor<any>>;
1915
+ declare function withComponentProps(Component: RouteComponentType): () => React.ReactElement<{
1916
+ params: Readonly<Params<string>>;
1917
+ loaderData: any;
1918
+ actionData: any;
1919
+ matches: UIMatch<unknown, unknown>[];
1920
+ }, string | React.JSXElementConstructor<any>>;
1921
+ declare function useHydrateFallbackProps(): {
1922
+ params: Readonly<Params<string>>;
1923
+ loaderData: any;
1924
+ actionData: any;
1925
+ };
1926
+ type HydrateFallbackProps = ReturnType<typeof useHydrateFallbackProps>;
1927
+ type HydrateFallbackType = React.ComponentType<HydrateFallbackProps>;
1928
+ declare function WithHydrateFallbackProps({ children, }: {
1929
+ children: React.ReactElement;
1930
+ }): React.ReactElement<any, string | React.JSXElementConstructor<any>>;
1931
+ declare function withHydrateFallbackProps(HydrateFallback: HydrateFallbackType): () => React.ReactElement<{
1932
+ params: Readonly<Params<string>>;
1933
+ loaderData: any;
1934
+ actionData: any;
1935
+ }, string | React.JSXElementConstructor<any>>;
1936
+ declare function useErrorBoundaryProps(): {
1937
+ params: Readonly<Params<string>>;
1938
+ loaderData: any;
1939
+ actionData: any;
1940
+ error: unknown;
1941
+ };
1942
+ type ErrorBoundaryProps = ReturnType<typeof useErrorBoundaryProps>;
1943
+ type ErrorBoundaryType = React.ComponentType<ErrorBoundaryProps>;
1944
+ declare function WithErrorBoundaryProps({ children, }: {
1945
+ children: React.ReactElement;
1946
+ }): React.ReactElement<any, string | React.JSXElementConstructor<any>>;
1947
+ declare function withErrorBoundaryProps(ErrorBoundary: ErrorBoundaryType): () => React.ReactElement<{
1948
+ params: Readonly<Params<string>>;
1949
+ loaderData: any;
1950
+ actionData: any;
1951
+ error: unknown;
1952
+ }, string | React.JSXElementConstructor<any>>;
1953
+
1954
+ interface IndexRouteObject {
1955
+ caseSensitive?: AgnosticIndexRouteObject["caseSensitive"];
1956
+ path?: AgnosticIndexRouteObject["path"];
1957
+ id?: AgnosticIndexRouteObject["id"];
1958
+ middleware?: AgnosticIndexRouteObject["middleware"];
1959
+ loader?: AgnosticIndexRouteObject["loader"];
1960
+ action?: AgnosticIndexRouteObject["action"];
1961
+ hasErrorBoundary?: AgnosticIndexRouteObject["hasErrorBoundary"];
1962
+ shouldRevalidate?: AgnosticIndexRouteObject["shouldRevalidate"];
1963
+ handle?: AgnosticIndexRouteObject["handle"];
1964
+ index: true;
1965
+ children?: undefined;
1966
+ element?: React.ReactNode | null;
1967
+ hydrateFallbackElement?: React.ReactNode | null;
1968
+ errorElement?: React.ReactNode | null;
1969
+ Component?: React.ComponentType | null;
1970
+ HydrateFallback?: React.ComponentType | null;
1971
+ ErrorBoundary?: React.ComponentType | null;
1972
+ lazy?: LazyRouteDefinition<RouteObject>;
1973
+ }
1974
+ interface NonIndexRouteObject {
1975
+ caseSensitive?: AgnosticNonIndexRouteObject["caseSensitive"];
1976
+ path?: AgnosticNonIndexRouteObject["path"];
1977
+ id?: AgnosticNonIndexRouteObject["id"];
1978
+ middleware?: AgnosticNonIndexRouteObject["middleware"];
1979
+ loader?: AgnosticNonIndexRouteObject["loader"];
1980
+ action?: AgnosticNonIndexRouteObject["action"];
1981
+ hasErrorBoundary?: AgnosticNonIndexRouteObject["hasErrorBoundary"];
1982
+ shouldRevalidate?: AgnosticNonIndexRouteObject["shouldRevalidate"];
1983
+ handle?: AgnosticNonIndexRouteObject["handle"];
1984
+ index?: false;
1985
+ children?: RouteObject[];
1986
+ element?: React.ReactNode | null;
1987
+ hydrateFallbackElement?: React.ReactNode | null;
1988
+ errorElement?: React.ReactNode | null;
1989
+ Component?: React.ComponentType | null;
1990
+ HydrateFallback?: React.ComponentType | null;
1991
+ ErrorBoundary?: React.ComponentType | null;
1992
+ lazy?: LazyRouteDefinition<RouteObject>;
1993
+ }
1994
+ type RouteObject = IndexRouteObject | NonIndexRouteObject;
1995
+ type DataRouteObject = RouteObject & {
1996
+ children?: DataRouteObject[];
1997
+ id: string;
1998
+ };
1999
+ interface RouteMatch<ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {
2000
+ }
2001
+ interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {
2002
+ }
2003
+ type PatchRoutesOnNavigationFunctionArgs = AgnosticPatchRoutesOnNavigationFunctionArgs<RouteObject, RouteMatch>;
2004
+ type PatchRoutesOnNavigationFunction = AgnosticPatchRoutesOnNavigationFunction<RouteObject, RouteMatch>;
2005
+ interface DataRouterContextObject extends Omit<NavigationContextObject, "future"> {
2006
+ router: Router;
2007
+ staticContext?: StaticHandlerContext;
2008
+ unstable_onError?: unstable_ClientOnErrorFunction;
2009
+ }
2010
+ declare const DataRouterContext: React.Context<DataRouterContextObject | null>;
2011
+ declare const DataRouterStateContext: React.Context<RouterState | null>;
2012
+ type ViewTransitionContextObject = {
2013
+ isTransitioning: false;
2014
+ } | {
2015
+ isTransitioning: true;
2016
+ flushSync: boolean;
2017
+ currentLocation: Location;
2018
+ nextLocation: Location;
2019
+ };
2020
+ declare const ViewTransitionContext: React.Context<ViewTransitionContextObject>;
2021
+ type FetchersContextObject = Map<string, any>;
2022
+ declare const FetchersContext: React.Context<FetchersContextObject>;
2023
+ declare const AwaitContext: React.Context<TrackedPromise | null>;
2024
+ declare const AwaitContextProvider: (props: React.ComponentProps<typeof AwaitContext.Provider>) => React.FunctionComponentElement<React.ProviderProps<TrackedPromise | null>>;
2025
+ interface NavigateOptions {
2026
+ /** Replace the current entry in the history stack instead of pushing a new one */
2027
+ replace?: boolean;
2028
+ /** Adds persistent client side routing state to the next location */
2029
+ state?: any;
2030
+ /** If you are using {@link https://api.reactrouter.com/v7/functions/react_router.ScrollRestoration.html <ScrollRestoration>}, prevent the scroll position from being reset to the top of the window when navigating */
2031
+ preventScrollReset?: boolean;
2032
+ /** Defines the relative path behavior for the link. "route" will use the route hierarchy so ".." will remove all URL segments of the current route pattern while "path" will use the URL path so ".." will remove one URL segment. */
2033
+ relative?: RelativeRoutingType;
2034
+ /** Wraps the initial state update for this navigation in a {@link https://react.dev/reference/react-dom/flushSync ReactDOM.flushSync} call instead of the default {@link https://react.dev/reference/react/startTransition React.startTransition} */
2035
+ flushSync?: boolean;
2036
+ /** Enables a {@link https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API View Transition} for this navigation by wrapping the final state update in `document.startViewTransition()`. If you need to apply specific styles for this view transition, you will also need to leverage the {@link https://api.reactrouter.com/v7/functions/react_router.useViewTransitionState.html useViewTransitionState()} hook. */
2037
+ viewTransition?: boolean;
2038
+ }
2039
+ /**
2040
+ * A Navigator is a "location changer"; it's how you get to different locations.
2041
+ *
2042
+ * Every history instance conforms to the Navigator interface, but the
2043
+ * distinction is useful primarily when it comes to the low-level `<Router>` API
2044
+ * where both the location and a navigator must be provided separately in order
2045
+ * to avoid "tearing" that may occur in a suspense-enabled app if the action
2046
+ * and/or location were to be read directly from the history instance.
2047
+ */
2048
+ interface Navigator {
2049
+ createHref: History["createHref"];
2050
+ encodeLocation?: History["encodeLocation"];
2051
+ go: History["go"];
2052
+ push(to: To, state?: any, opts?: NavigateOptions): void;
2053
+ replace(to: To, state?: any, opts?: NavigateOptions): void;
2054
+ }
2055
+ interface NavigationContextObject {
2056
+ basename: string;
2057
+ navigator: Navigator;
2058
+ static: boolean;
2059
+ future: {};
2060
+ }
2061
+ declare const NavigationContext: React.Context<NavigationContextObject>;
2062
+ interface LocationContextObject {
2063
+ location: Location;
2064
+ navigationType: Action;
2065
+ }
2066
+ declare const LocationContext: React.Context<LocationContextObject>;
2067
+ interface RouteContextObject {
2068
+ outlet: React.ReactElement | null;
2069
+ matches: RouteMatch[];
2070
+ isDataRoute: boolean;
2071
+ }
2072
+ declare const RouteContext: React.Context<RouteContextObject>;
2073
+
2074
+ type Primitive = null | undefined | string | number | boolean | symbol | bigint;
2075
+ type LiteralUnion<LiteralType, BaseType extends Primitive> = LiteralType | (BaseType & Record<never, never>);
2076
+ interface HtmlLinkProps {
1750
2077
  /**
1751
- * Application basename
2078
+ * Address of the hyperlink
1752
2079
  */
1753
- basename?: string;
2080
+ href?: string;
1754
2081
  /**
1755
- * Nested {@link Route} elements describing the route tree
2082
+ * How the element handles crossorigin requests
1756
2083
  */
1757
- children?: React.ReactNode;
2084
+ crossOrigin?: "anonymous" | "use-credentials";
1758
2085
  /**
1759
- * Initial entries in the in-memory history stack
2086
+ * Relationship between the document containing the hyperlink and the destination resource
1760
2087
  */
1761
- initialEntries?: InitialEntry[];
2088
+ rel: LiteralUnion<"alternate" | "dns-prefetch" | "icon" | "manifest" | "modulepreload" | "next" | "pingback" | "preconnect" | "prefetch" | "preload" | "prerender" | "search" | "stylesheet", string>;
1762
2089
  /**
1763
- * Index of `initialEntries` the application should initialize to
2090
+ * Applicable media: "screen", "print", "(max-width: 764px)"
1764
2091
  */
1765
- initialIndex?: number;
1766
- }
1767
- /**
1768
- * A declarative {@link Router | `<Router>`} that stores all entries in memory.
1769
- *
1770
- * @public
1771
- * @category Declarative Routers
1772
- * @mode declarative
1773
- * @param props Props
1774
- * @param {MemoryRouterProps.basename} props.basename n/a
1775
- * @param {MemoryRouterProps.children} props.children n/a
1776
- * @param {MemoryRouterProps.initialEntries} props.initialEntries n/a
1777
- * @param {MemoryRouterProps.initialIndex} props.initialIndex n/a
1778
- * @returns A declarative in-memory {@link Router | `<Router>`} for client-side
1779
- * routing.
1780
- */
1781
- declare function MemoryRouter({ basename, children, initialEntries, initialIndex, }: MemoryRouterProps): React.ReactElement;
1782
- /**
1783
- * @category Types
1784
- */
1785
- interface NavigateProps {
2092
+ media?: string;
1786
2093
  /**
1787
- * The path to navigate to. This can be a string or a {@link Path} object
2094
+ * Integrity metadata used in Subresource Integrity checks
1788
2095
  */
1789
- to: To;
2096
+ integrity?: string;
1790
2097
  /**
1791
- * Whether to replace the current entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1792
- * stack
2098
+ * Language of the linked resource
1793
2099
  */
1794
- replace?: boolean;
2100
+ hrefLang?: string;
1795
2101
  /**
1796
- * State to pass to the new {@link Location} to store in [`history.state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state).
2102
+ * Hint for the type of the referenced resource
1797
2103
  */
1798
- state?: any;
2104
+ type?: string;
1799
2105
  /**
1800
- * How to interpret relative routing in the `to` prop.
1801
- * See {@link RelativeRoutingType}.
2106
+ * Referrer policy for fetches initiated by the element
1802
2107
  */
1803
- relative?: RelativeRoutingType;
1804
- }
1805
- /**
1806
- * A component-based version of {@link useNavigate} to use in a
1807
- * [`React.Component` class](https://react.dev/reference/react/Component) where
1808
- * hooks cannot be used.
1809
- *
1810
- * It's recommended to avoid using this component in favor of {@link useNavigate}.
1811
- *
1812
- * @example
1813
- * <Navigate to="/tasks" />
1814
- *
1815
- * @public
1816
- * @category Components
1817
- * @param props Props
1818
- * @param {NavigateProps.relative} props.relative n/a
1819
- * @param {NavigateProps.replace} props.replace n/a
1820
- * @param {NavigateProps.state} props.state n/a
1821
- * @param {NavigateProps.to} props.to n/a
1822
- * @returns {void}
1823
- *
1824
- */
1825
- declare function Navigate({ to, replace, state, relative, }: NavigateProps): null;
1826
- /**
1827
- * @category Types
1828
- */
1829
- interface OutletProps {
2108
+ referrerPolicy?: "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
1830
2109
  /**
1831
- * Provides a context value to the element tree below the outlet. Use when
1832
- * the parent route needs to provide values to child routes.
1833
- *
1834
- * ```tsx
1835
- * <Outlet context={myContextValue} />
1836
- * ```
1837
- *
1838
- * Access the context with {@link useOutletContext}.
2110
+ * Sizes of the icons (for rel="icon")
1839
2111
  */
1840
- context?: unknown;
1841
- }
1842
- /**
1843
- * Renders the matching child route of a parent route or nothing if no child
1844
- * route matches.
1845
- *
1846
- * @example
1847
- * import { Outlet } from "react-router";
1848
- *
1849
- * export default function SomeParent() {
1850
- * return (
1851
- * <div>
1852
- * <h1>Parent Content</h1>
1853
- * <Outlet />
1854
- * </div>
1855
- * );
1856
- * }
1857
- *
1858
- * @public
1859
- * @category Components
1860
- * @param props Props
1861
- * @param {OutletProps.context} props.context n/a
1862
- * @returns React element for the rendered outlet or `null` if no child route matches.
1863
- */
1864
- declare function Outlet(props: OutletProps): React.ReactElement | null;
1865
- /**
1866
- * @category Types
1867
- */
1868
- interface PathRouteProps {
2112
+ sizes?: string;
1869
2113
  /**
1870
- * Whether the path should be case-sensitive. Defaults to `false`.
2114
+ * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
1871
2115
  */
1872
- caseSensitive?: NonIndexRouteObject["caseSensitive"];
2116
+ as?: LiteralUnion<"audio" | "audioworklet" | "document" | "embed" | "fetch" | "font" | "frame" | "iframe" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt", string>;
1873
2117
  /**
1874
- * The path pattern to match. If unspecified or empty, then this becomes a
1875
- * layout route.
2118
+ * Color to use when customizing a site's icon (for rel="mask-icon")
1876
2119
  */
1877
- path?: NonIndexRouteObject["path"];
2120
+ color?: string;
1878
2121
  /**
1879
- * The unique identifier for this route (for use with {@link DataRouter}s)
2122
+ * Whether the link is disabled
1880
2123
  */
1881
- id?: NonIndexRouteObject["id"];
2124
+ disabled?: boolean;
1882
2125
  /**
1883
- * A function that returns a promise that resolves to the route object.
1884
- * Used for code-splitting routes.
1885
- * See [`lazy`](../../start/data/route-object#lazy).
2126
+ * The title attribute has special semantics on this element: Title of the link; CSS style sheet set name.
1886
2127
  */
1887
- lazy?: LazyRouteFunction<NonIndexRouteObject>;
2128
+ title?: string;
1888
2129
  /**
1889
- * The route middleware.
1890
- * See [`middleware`](../../start/data/route-object#middleware).
2130
+ * Images to use in different situations, e.g., high-resolution displays,
2131
+ * small monitors, etc. (for rel="preload")
1891
2132
  */
1892
- middleware?: NonIndexRouteObject["middleware"];
2133
+ imageSrcSet?: string;
1893
2134
  /**
1894
- * The route loader.
1895
- * See [`loader`](../../start/data/route-object#loader).
2135
+ * Image sizes for different page layouts (for rel="preload")
1896
2136
  */
1897
- loader?: NonIndexRouteObject["loader"];
2137
+ imageSizes?: string;
2138
+ }
2139
+ interface HtmlLinkPreloadImage extends HtmlLinkProps {
1898
2140
  /**
1899
- * The route action.
1900
- * See [`action`](../../start/data/route-object#action).
2141
+ * Relationship between the document containing the hyperlink and the destination resource
1901
2142
  */
1902
- action?: NonIndexRouteObject["action"];
1903
- hasErrorBoundary?: NonIndexRouteObject["hasErrorBoundary"];
2143
+ rel: "preload";
1904
2144
  /**
1905
- * The route shouldRevalidate function.
1906
- * See [`shouldRevalidate`](../../start/data/route-object#shouldRevalidate).
2145
+ * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
1907
2146
  */
1908
- shouldRevalidate?: NonIndexRouteObject["shouldRevalidate"];
2147
+ as: "image";
1909
2148
  /**
1910
- * The route handle.
2149
+ * Address of the hyperlink
1911
2150
  */
1912
- handle?: NonIndexRouteObject["handle"];
2151
+ href?: string;
1913
2152
  /**
1914
- * Whether this is an index route.
2153
+ * Images to use in different situations, e.g., high-resolution displays,
2154
+ * small monitors, etc. (for rel="preload")
1915
2155
  */
1916
- index?: false;
2156
+ imageSrcSet: string;
1917
2157
  /**
1918
- * Child Route components
2158
+ * Image sizes for different page layouts (for rel="preload")
1919
2159
  */
1920
- children?: React.ReactNode;
2160
+ imageSizes?: string;
2161
+ }
2162
+ /**
2163
+ * Represents a `<link>` element.
2164
+ *
2165
+ * WHATWG Specification: https://html.spec.whatwg.org/multipage/semantics.html#the-link-element
2166
+ */
2167
+ type HtmlLinkDescriptor = (HtmlLinkProps & Pick<Required<HtmlLinkProps>, "href">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "imageSizes">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "href"> & {
2168
+ imageSizes?: never;
2169
+ });
2170
+ interface PageLinkDescriptor extends Omit<HtmlLinkDescriptor, "href" | "rel" | "type" | "sizes" | "imageSrcSet" | "imageSizes" | "as" | "color" | "title"> {
1921
2171
  /**
1922
- * The React element to render when this Route matches.
1923
- * Mutually exclusive with `Component`.
2172
+ * A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
2173
+ * attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
2174
+ * element
1924
2175
  */
1925
- element?: React.ReactNode | null;
2176
+ nonce?: string | undefined;
1926
2177
  /**
1927
- * The React element to render while this router is loading data.
1928
- * Mutually exclusive with `HydrateFallback`.
2178
+ * The absolute path of the page to prefetch, e.g. `/absolute/path`.
1929
2179
  */
1930
- hydrateFallbackElement?: React.ReactNode | null;
2180
+ page: string;
2181
+ }
2182
+ type LinkDescriptor = HtmlLinkDescriptor | PageLinkDescriptor;
2183
+
2184
+ type Serializable = undefined | null | boolean | string | symbol | number | Array<Serializable> | {
2185
+ [key: PropertyKey]: Serializable;
2186
+ } | bigint | Date | URL | RegExp | Error | Map<Serializable, Serializable> | Set<Serializable> | Promise<Serializable>;
2187
+
2188
+ type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
2189
+ type IsAny<T> = 0 extends 1 & T ? true : false;
2190
+ type Func = (...args: any[]) => unknown;
2191
+ type Pretty<T> = {
2192
+ [K in keyof T]: T[K];
2193
+ } & {};
2194
+ type Normalize<T> = _Normalize<UnionKeys<T>, T>;
2195
+ type _Normalize<Key extends keyof any, T> = T extends infer U ? Pretty<{
2196
+ [K in Key as K extends keyof U ? undefined extends U[K] ? never : K : never]: K extends keyof U ? U[K] : never;
2197
+ } & {
2198
+ [K in Key as K extends keyof U ? undefined extends U[K] ? K : never : never]?: K extends keyof U ? U[K] : never;
2199
+ } & {
2200
+ [K in Key as K extends keyof U ? never : K]?: undefined;
2201
+ }> : never;
2202
+ type UnionKeys<T> = T extends any ? keyof T : never;
2203
+
2204
+ type RouteModule$1 = {
2205
+ meta?: Func;
2206
+ links?: Func;
2207
+ headers?: Func;
2208
+ loader?: Func;
2209
+ clientLoader?: Func;
2210
+ action?: Func;
2211
+ clientAction?: Func;
2212
+ HydrateFallback?: Func;
2213
+ default?: Func;
2214
+ ErrorBoundary?: Func;
2215
+ [key: string]: unknown;
2216
+ };
2217
+
2218
+ /**
2219
+ * A brand that can be applied to a type to indicate that it will serialize
2220
+ * to a specific type when transported to the client from a loader.
2221
+ * Only use this if you have additional serialization/deserialization logic
2222
+ * in your application.
2223
+ */
2224
+ type unstable_SerializesTo<T> = {
2225
+ unstable__ReactRouter_SerializesTo: [T];
2226
+ };
2227
+
2228
+ type 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> ? {
2229
+ [K in keyof T]: Serialize<T[K]>;
2230
+ } : undefined;
2231
+ type VoidToUndefined<T> = Equal<T, void> extends true ? undefined : T;
2232
+ type DataFrom<T> = IsAny<T> extends true ? undefined : T extends Func ? VoidToUndefined<Awaited<ReturnType<T>>> : undefined;
2233
+ type ClientData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? U : T;
2234
+ type ServerData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? Serialize<U> : Serialize<T>;
2235
+ type ServerDataFrom<T> = ServerData<DataFrom<T>>;
2236
+ type ClientDataFrom<T> = ClientData<DataFrom<T>>;
2237
+ type ClientDataFunctionArgs<Params> = {
2238
+ /**
2239
+ * 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.
2240
+ *
2241
+ * @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.
2242
+ **/
2243
+ request: Request;
1931
2244
  /**
1932
- * The React element to render at this route if an error occurs.
1933
- * Mutually exclusive with `ErrorBoundary`.
2245
+ * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
2246
+ * @example
2247
+ * // app/routes.ts
2248
+ * route("teams/:teamId", "./team.tsx"),
2249
+ *
2250
+ * // app/team.tsx
2251
+ * export function clientLoader({
2252
+ * params,
2253
+ * }: Route.ClientLoaderArgs) {
2254
+ * params.teamId;
2255
+ * // ^ string
2256
+ * }
2257
+ **/
2258
+ params: Params;
2259
+ /**
2260
+ * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
2261
+ * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
1934
2262
  */
1935
- errorElement?: React.ReactNode | null;
2263
+ unstable_pattern: string;
1936
2264
  /**
1937
- * The React Component to render when this route matches.
1938
- * Mutually exclusive with `element`.
2265
+ * When `future.v8_middleware` is not enabled, this is undefined.
2266
+ *
2267
+ * When `future.v8_middleware` is enabled, this is an instance of
2268
+ * `RouterContextProvider` and can be used to access context values
2269
+ * from your route middlewares. You may pass in initial context values in your
2270
+ * `<HydratedRouter getContext>` prop
1939
2271
  */
1940
- Component?: React.ComponentType | null;
2272
+ context: Readonly<RouterContextProvider>;
2273
+ };
2274
+ type ServerDataFunctionArgs<Params> = {
2275
+ /** A {@link https://developer.mozilla.org/en-US/docs/Web/API/Request Fetch Request instance} which you can use to read the url, method, headers (such as cookies), and request body from the request. */
2276
+ request: Request;
1941
2277
  /**
1942
- * The React Component to render while this router is loading data.
1943
- * Mutually exclusive with `hydrateFallbackElement`.
2278
+ * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
2279
+ * @example
2280
+ * // app/routes.ts
2281
+ * route("teams/:teamId", "./team.tsx"),
2282
+ *
2283
+ * // app/team.tsx
2284
+ * export function loader({
2285
+ * params,
2286
+ * }: Route.LoaderArgs) {
2287
+ * params.teamId;
2288
+ * // ^ string
2289
+ * }
2290
+ **/
2291
+ params: Params;
2292
+ /**
2293
+ * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
2294
+ * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
1944
2295
  */
1945
- HydrateFallback?: React.ComponentType | null;
2296
+ unstable_pattern: string;
1946
2297
  /**
1947
- * The React Component to render at this route if an error occurs.
1948
- * Mutually exclusive with `errorElement`.
2298
+ * Without `future.v8_middleware` enabled, this is the context passed in
2299
+ * to your server adapter's `getLoadContext` function. It's a way to bridge the
2300
+ * gap between the adapter's request/response API with your React Router app.
2301
+ * It is only applicable if you are using a custom server adapter.
2302
+ *
2303
+ * With `future.v8_middleware` enabled, this is an instance of
2304
+ * `RouterContextProvider` and can be used for type-safe access to
2305
+ * context value set in your route middlewares. If you are using a custom
2306
+ * server adapter, you may provide an initial set of context values from your
2307
+ * `getLoadContext` function.
1949
2308
  */
1950
- ErrorBoundary?: React.ComponentType | null;
2309
+ context: MiddlewareEnabled extends true ? Readonly<RouterContextProvider> : AppLoadContext;
2310
+ };
2311
+ type SerializeFrom<T> = T extends (...args: infer Args) => unknown ? Args extends [
2312
+ ClientLoaderFunctionArgs | ClientActionFunctionArgs | ClientDataFunctionArgs<unknown>
2313
+ ] ? ClientDataFrom<T> : ServerDataFrom<T> : T;
2314
+ type IsDefined<T> = Equal<T, undefined> extends true ? false : true;
2315
+ type IsHydrate<ClientLoader> = ClientLoader extends {
2316
+ hydrate: true;
2317
+ } ? true : ClientLoader extends {
2318
+ hydrate: false;
2319
+ } ? false : false;
2320
+ type GetLoaderData<T extends RouteModule$1> = _DataLoaderData<ServerDataFrom<T["loader"]>, ClientDataFrom<T["clientLoader"]>, IsHydrate<T["clientLoader"]>, T extends {
2321
+ HydrateFallback: Func;
2322
+ } ? true : false>;
2323
+ type _DataLoaderData<ServerLoaderData, ClientLoaderData, ClientLoaderHydrate extends boolean, HasHydrateFallback> = [
2324
+ HasHydrateFallback,
2325
+ ClientLoaderHydrate
2326
+ ] extends [true, true] ? IsDefined<ClientLoaderData> extends true ? ClientLoaderData : undefined : [
2327
+ IsDefined<ClientLoaderData>,
2328
+ IsDefined<ServerLoaderData>
2329
+ ] extends [true, true] ? ServerLoaderData | ClientLoaderData : IsDefined<ClientLoaderData> extends true ? ClientLoaderData : IsDefined<ServerLoaderData> extends true ? ServerLoaderData : undefined;
2330
+ type GetActionData<T extends RouteModule$1> = _DataActionData<ServerDataFrom<T["action"]>, ClientDataFrom<T["clientAction"]>>;
2331
+ type _DataActionData<ServerActionData, ClientActionData> = Awaited<[
2332
+ IsDefined<ServerActionData>,
2333
+ IsDefined<ClientActionData>
2334
+ ] extends [true, true] ? ServerActionData | ClientActionData : IsDefined<ClientActionData> extends true ? ClientActionData : IsDefined<ServerActionData> extends true ? ServerActionData : undefined>;
2335
+
2336
+ interface RouteModules {
2337
+ [routeId: string]: RouteModule | undefined;
2338
+ }
2339
+ /**
2340
+ * The shape of a route module shipped to the client
2341
+ */
2342
+ interface RouteModule {
2343
+ clientAction?: ClientActionFunction;
2344
+ clientLoader?: ClientLoaderFunction;
2345
+ clientMiddleware?: MiddlewareFunction<Record<string, DataStrategyResult>>[];
2346
+ ErrorBoundary?: ErrorBoundaryComponent;
2347
+ HydrateFallback?: HydrateFallbackComponent;
2348
+ Layout?: LayoutComponent;
2349
+ default: RouteComponent;
2350
+ handle?: RouteHandle;
2351
+ links?: LinksFunction;
2352
+ meta?: MetaFunction;
2353
+ shouldRevalidate?: ShouldRevalidateFunction;
2354
+ }
2355
+ /**
2356
+ * The shape of a route module on the server
2357
+ */
2358
+ interface ServerRouteModule extends RouteModule {
2359
+ action?: ActionFunction;
2360
+ headers?: HeadersFunction | {
2361
+ [name: string]: string;
2362
+ };
2363
+ loader?: LoaderFunction;
2364
+ middleware?: MiddlewareFunction<Response>[];
2365
+ }
2366
+ /**
2367
+ * A function that handles data mutations for a route on the client
2368
+ */
2369
+ type ClientActionFunction = (args: ClientActionFunctionArgs) => ReturnType<ActionFunction>;
2370
+ /**
2371
+ * Arguments passed to a route `clientAction` function
2372
+ */
2373
+ type ClientActionFunctionArgs = ActionFunctionArgs & {
2374
+ serverAction: <T = unknown>() => Promise<SerializeFrom<T>>;
2375
+ };
2376
+ /**
2377
+ * A function that loads data for a route on the client
2378
+ */
2379
+ type ClientLoaderFunction = ((args: ClientLoaderFunctionArgs) => ReturnType<LoaderFunction>) & {
2380
+ hydrate?: boolean;
2381
+ };
2382
+ /**
2383
+ * Arguments passed to a route `clientLoader` function
2384
+ */
2385
+ type ClientLoaderFunctionArgs = LoaderFunctionArgs & {
2386
+ serverLoader: <T = unknown>() => Promise<SerializeFrom<T>>;
2387
+ };
2388
+ /**
2389
+ * ErrorBoundary to display for this route
2390
+ */
2391
+ type ErrorBoundaryComponent = ComponentType;
2392
+ type HeadersArgs = {
2393
+ loaderHeaders: Headers;
2394
+ parentHeaders: Headers;
2395
+ actionHeaders: Headers;
2396
+ errorHeaders: Headers | undefined;
2397
+ };
2398
+ /**
2399
+ * A function that returns HTTP headers to be used for a route. These headers
2400
+ * will be merged with (and take precedence over) headers from parent routes.
2401
+ */
2402
+ interface HeadersFunction {
2403
+ (args: HeadersArgs): Headers | HeadersInit;
1951
2404
  }
1952
2405
  /**
1953
- * @category Types
2406
+ * `<Route HydrateFallback>` component to render on initial loads
2407
+ * when client loaders are present
2408
+ */
2409
+ type HydrateFallbackComponent = ComponentType;
2410
+ /**
2411
+ * Optional, root-only `<Route Layout>` component to wrap the root content in.
2412
+ * Useful for defining the <html>/<head>/<body> document shell shared by the
2413
+ * Component, HydrateFallback, and ErrorBoundary
2414
+ */
2415
+ type LayoutComponent = ComponentType<{
2416
+ children: ReactElement<unknown, ErrorBoundaryComponent | HydrateFallbackComponent | RouteComponent>;
2417
+ }>;
2418
+ /**
2419
+ * A function that defines `<link>` tags to be inserted into the `<head>` of
2420
+ * the document on route transitions.
2421
+ *
2422
+ * @see https://reactrouter.com/start/framework/route-module#meta
2423
+ */
2424
+ interface LinksFunction {
2425
+ (): LinkDescriptor[];
2426
+ }
2427
+ interface MetaMatch<RouteId extends string = string, Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown> {
2428
+ id: RouteId;
2429
+ pathname: DataRouteMatch["pathname"];
2430
+ /** @deprecated Use `MetaMatch.loaderData` instead */
2431
+ data: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
2432
+ loaderData: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
2433
+ handle?: RouteHandle;
2434
+ params: DataRouteMatch["params"];
2435
+ meta: MetaDescriptor[];
2436
+ error?: unknown;
2437
+ }
2438
+ type MetaMatches<MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> = Array<{
2439
+ [K in keyof MatchLoaders]: MetaMatch<Exclude<K, number | symbol>, MatchLoaders[K]>;
2440
+ }[keyof MatchLoaders]>;
2441
+ interface MetaArgs<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
2442
+ /** @deprecated Use `MetaArgs.loaderData` instead */
2443
+ data: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
2444
+ loaderData: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
2445
+ params: Params;
2446
+ location: Location;
2447
+ matches: MetaMatches<MatchLoaders>;
2448
+ error?: unknown;
2449
+ }
2450
+ /**
2451
+ * A function that returns an array of data objects to use for rendering
2452
+ * metadata HTML tags in a route. These tags are not rendered on descendant
2453
+ * routes in the route hierarchy. In other words, they will only be rendered on
2454
+ * the route in which they are exported.
2455
+ *
2456
+ * @param Loader - The type of the current route's loader function
2457
+ * @param MatchLoaders - Mapping from a parent route's filepath to its loader
2458
+ * function type
2459
+ *
2460
+ * Note that parent route filepaths are relative to the `app/` directory.
2461
+ *
2462
+ * For example, if this meta function is for `/sales/customers/$customerId`:
2463
+ *
2464
+ * ```ts
2465
+ * // app/root.tsx
2466
+ * const loader = () => ({ hello: "world" })
2467
+ * export type Loader = typeof loader
2468
+ *
2469
+ * // app/routes/sales.tsx
2470
+ * const loader = () => ({ salesCount: 1074 })
2471
+ * export type Loader = typeof loader
2472
+ *
2473
+ * // app/routes/sales/customers.tsx
2474
+ * const loader = () => ({ customerCount: 74 })
2475
+ * export type Loader = typeof loader
2476
+ *
2477
+ * // app/routes/sales/customers/$customersId.tsx
2478
+ * import type { Loader as RootLoader } from "../../../root"
2479
+ * import type { Loader as SalesLoader } from "../../sales"
2480
+ * import type { Loader as CustomersLoader } from "../../sales/customers"
2481
+ *
2482
+ * const loader = () => ({ name: "Customer name" })
2483
+ *
2484
+ * const meta: MetaFunction<typeof loader, {
2485
+ * "root": RootLoader,
2486
+ * "routes/sales": SalesLoader,
2487
+ * "routes/sales/customers": CustomersLoader,
2488
+ * }> = ({ data, matches }) => {
2489
+ * const { name } = data
2490
+ * // ^? string
2491
+ * const { customerCount } = matches.find((match) => match.id === "routes/sales/customers").data
2492
+ * // ^? number
2493
+ * const { salesCount } = matches.find((match) => match.id === "routes/sales").data
2494
+ * // ^? number
2495
+ * const { hello } = matches.find((match) => match.id === "root").data
2496
+ * // ^? "world"
2497
+ * }
2498
+ * ```
2499
+ */
2500
+ interface MetaFunction<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
2501
+ (args: MetaArgs<Loader, MatchLoaders>): MetaDescriptor[] | undefined;
2502
+ }
2503
+ type MetaDescriptor = {
2504
+ charSet: "utf-8";
2505
+ } | {
2506
+ title: string;
2507
+ } | {
2508
+ name: string;
2509
+ content: string;
2510
+ } | {
2511
+ property: string;
2512
+ content: string;
2513
+ } | {
2514
+ httpEquiv: string;
2515
+ content: string;
2516
+ } | {
2517
+ "script:ld+json": LdJsonObject;
2518
+ } | {
2519
+ tagName: "meta" | "link";
2520
+ [name: string]: string;
2521
+ } | {
2522
+ [name: string]: unknown;
2523
+ };
2524
+ type LdJsonObject = {
2525
+ [Key in string]: LdJsonValue;
2526
+ } & {
2527
+ [Key in string]?: LdJsonValue | undefined;
2528
+ };
2529
+ type LdJsonArray = LdJsonValue[] | readonly LdJsonValue[];
2530
+ type LdJsonPrimitive = string | number | boolean | null;
2531
+ type LdJsonValue = LdJsonPrimitive | LdJsonObject | LdJsonArray;
2532
+ /**
2533
+ * A React component that is rendered for a route.
1954
2534
  */
1955
- interface LayoutRouteProps extends PathRouteProps {
1956
- }
2535
+ type RouteComponent = ComponentType<{}>;
1957
2536
  /**
1958
- * @category Types
2537
+ * An arbitrary object that is associated with a route.
2538
+ *
2539
+ * @see https://reactrouter.com/how-to/using-handle
1959
2540
  */
1960
- interface IndexRouteProps {
2541
+ type RouteHandle = unknown;
2542
+
2543
+ type unstable_ServerInstrumentation = {
2544
+ handler?: unstable_InstrumentRequestHandlerFunction;
2545
+ route?: unstable_InstrumentRouteFunction;
2546
+ };
2547
+ type unstable_ClientInstrumentation = {
2548
+ router?: unstable_InstrumentRouterFunction;
2549
+ route?: unstable_InstrumentRouteFunction;
2550
+ };
2551
+ type unstable_InstrumentRequestHandlerFunction = (handler: InstrumentableRequestHandler) => void;
2552
+ type unstable_InstrumentRouterFunction = (router: InstrumentableRouter) => void;
2553
+ type unstable_InstrumentRouteFunction = (route: InstrumentableRoute) => void;
2554
+ type unstable_InstrumentationHandlerResult = {
2555
+ status: "success";
2556
+ error: undefined;
2557
+ } | {
2558
+ status: "error";
2559
+ error: Error;
2560
+ };
2561
+ type InstrumentFunction<T> = (handler: () => Promise<unstable_InstrumentationHandlerResult>, info: T) => Promise<void>;
2562
+ type ReadonlyRequest = {
2563
+ method: string;
2564
+ url: string;
2565
+ headers: Pick<Headers, "get">;
2566
+ };
2567
+ type ReadonlyContext = MiddlewareEnabled extends true ? Pick<RouterContextProvider, "get"> : Readonly<AppLoadContext>;
2568
+ type InstrumentableRoute = {
2569
+ id: string;
2570
+ index: boolean | undefined;
2571
+ path: string | undefined;
2572
+ instrument(instrumentations: RouteInstrumentations): void;
2573
+ };
2574
+ type RouteInstrumentations = {
2575
+ lazy?: InstrumentFunction<RouteLazyInstrumentationInfo>;
2576
+ "lazy.loader"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
2577
+ "lazy.action"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
2578
+ "lazy.middleware"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
2579
+ middleware?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
2580
+ loader?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
2581
+ action?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
2582
+ };
2583
+ type RouteLazyInstrumentationInfo = undefined;
2584
+ type RouteHandlerInstrumentationInfo = Readonly<{
2585
+ request: ReadonlyRequest;
2586
+ params: LoaderFunctionArgs["params"];
2587
+ unstable_pattern: string;
2588
+ context: ReadonlyContext;
2589
+ }>;
2590
+ type InstrumentableRouter = {
2591
+ instrument(instrumentations: RouterInstrumentations): void;
2592
+ };
2593
+ type RouterInstrumentations = {
2594
+ navigate?: InstrumentFunction<RouterNavigationInstrumentationInfo>;
2595
+ fetch?: InstrumentFunction<RouterFetchInstrumentationInfo>;
2596
+ };
2597
+ type RouterNavigationInstrumentationInfo = Readonly<{
2598
+ to: string | number;
2599
+ currentUrl: string;
2600
+ formMethod?: HTMLFormMethod;
2601
+ formEncType?: FormEncType;
2602
+ formData?: FormData;
2603
+ body?: any;
2604
+ }>;
2605
+ type RouterFetchInstrumentationInfo = Readonly<{
2606
+ href: string;
2607
+ currentUrl: string;
2608
+ fetcherKey: string;
2609
+ formMethod?: HTMLFormMethod;
2610
+ formEncType?: FormEncType;
2611
+ formData?: FormData;
2612
+ body?: any;
2613
+ }>;
2614
+ type InstrumentableRequestHandler = {
2615
+ instrument(instrumentations: RequestHandlerInstrumentations): void;
2616
+ };
2617
+ type RequestHandlerInstrumentations = {
2618
+ request?: InstrumentFunction<RequestHandlerInstrumentationInfo>;
2619
+ };
2620
+ type RequestHandlerInstrumentationInfo = Readonly<{
2621
+ request: ReadonlyRequest;
2622
+ context: ReadonlyContext | undefined;
2623
+ }>;
2624
+
2625
+ /**
2626
+ * A Router instance manages all navigation and data loading/mutations
2627
+ */
2628
+ interface Router {
1961
2629
  /**
1962
- * Whether the path should be case-sensitive. Defaults to `false`.
2630
+ * @private
2631
+ * PRIVATE - DO NOT USE
2632
+ *
2633
+ * Return the basename for the router
1963
2634
  */
1964
- caseSensitive?: IndexRouteObject["caseSensitive"];
2635
+ get basename(): RouterInit["basename"];
1965
2636
  /**
1966
- * The path pattern to match. If unspecified or empty, then this becomes a
1967
- * layout route.
2637
+ * @private
2638
+ * PRIVATE - DO NOT USE
2639
+ *
2640
+ * Return the future config for the router
1968
2641
  */
1969
- path?: IndexRouteObject["path"];
2642
+ get future(): FutureConfig;
1970
2643
  /**
1971
- * The unique identifier for this route (for use with {@link DataRouter}s)
2644
+ * @private
2645
+ * PRIVATE - DO NOT USE
2646
+ *
2647
+ * Return the current state of the router
1972
2648
  */
1973
- id?: IndexRouteObject["id"];
2649
+ get state(): RouterState;
1974
2650
  /**
1975
- * A function that returns a promise that resolves to the route object.
1976
- * Used for code-splitting routes.
1977
- * See [`lazy`](../../start/data/route-object#lazy).
2651
+ * @private
2652
+ * PRIVATE - DO NOT USE
2653
+ *
2654
+ * Return the routes for this router instance
1978
2655
  */
1979
- lazy?: LazyRouteFunction<IndexRouteObject>;
2656
+ get routes(): AgnosticDataRouteObject[];
1980
2657
  /**
1981
- * The route middleware.
1982
- * See [`middleware`](../../start/data/route-object#middleware).
2658
+ * @private
2659
+ * PRIVATE - DO NOT USE
2660
+ *
2661
+ * Return the window associated with the router
1983
2662
  */
1984
- middleware?: IndexRouteObject["middleware"];
2663
+ get window(): RouterInit["window"];
1985
2664
  /**
1986
- * The route loader.
1987
- * See [`loader`](../../start/data/route-object#loader).
2665
+ * @private
2666
+ * PRIVATE - DO NOT USE
2667
+ *
2668
+ * Initialize the router, including adding history listeners and kicking off
2669
+ * initial data fetches. Returns a function to cleanup listeners and abort
2670
+ * any in-progress loads
1988
2671
  */
1989
- loader?: IndexRouteObject["loader"];
2672
+ initialize(): Router;
1990
2673
  /**
1991
- * The route action.
1992
- * See [`action`](../../start/data/route-object#action).
2674
+ * @private
2675
+ * PRIVATE - DO NOT USE
2676
+ *
2677
+ * Subscribe to router.state updates
2678
+ *
2679
+ * @param fn function to call with the new state
1993
2680
  */
1994
- action?: IndexRouteObject["action"];
1995
- hasErrorBoundary?: IndexRouteObject["hasErrorBoundary"];
2681
+ subscribe(fn: RouterSubscriber): () => void;
1996
2682
  /**
1997
- * The route shouldRevalidate function.
1998
- * See [`shouldRevalidate`](../../start/data/route-object#shouldRevalidate).
2683
+ * @private
2684
+ * PRIVATE - DO NOT USE
2685
+ *
2686
+ * Enable scroll restoration behavior in the router
2687
+ *
2688
+ * @param savedScrollPositions Object that will manage positions, in case
2689
+ * it's being restored from sessionStorage
2690
+ * @param getScrollPosition Function to get the active Y scroll position
2691
+ * @param getKey Function to get the key to use for restoration
1999
2692
  */
2000
- shouldRevalidate?: IndexRouteObject["shouldRevalidate"];
2693
+ enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;
2001
2694
  /**
2002
- * The route handle.
2695
+ * @private
2696
+ * PRIVATE - DO NOT USE
2697
+ *
2698
+ * Navigate forward/backward in the history stack
2699
+ * @param to Delta to move in the history stack
2003
2700
  */
2004
- handle?: IndexRouteObject["handle"];
2701
+ navigate(to: number): Promise<void>;
2005
2702
  /**
2006
- * Whether this is an index route.
2703
+ * Navigate to the given path
2704
+ * @param to Path to navigate to
2705
+ * @param opts Navigation options (method, submission, etc.)
2007
2706
  */
2008
- index: true;
2707
+ navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;
2009
2708
  /**
2010
- * Child Route components
2709
+ * @private
2710
+ * PRIVATE - DO NOT USE
2711
+ *
2712
+ * Trigger a fetcher load/submission
2713
+ *
2714
+ * @param key Fetcher key
2715
+ * @param routeId Route that owns the fetcher
2716
+ * @param href href to fetch
2717
+ * @param opts Fetcher options, (method, submission, etc.)
2011
2718
  */
2012
- children?: undefined;
2719
+ fetch(key: string, routeId: string, href: string | null, opts?: RouterFetchOptions): Promise<void>;
2013
2720
  /**
2014
- * The React element to render when this Route matches.
2015
- * Mutually exclusive with `Component`.
2721
+ * @private
2722
+ * PRIVATE - DO NOT USE
2723
+ *
2724
+ * Trigger a revalidation of all current route loaders and fetcher loads
2016
2725
  */
2017
- element?: React.ReactNode | null;
2726
+ revalidate(): Promise<void>;
2018
2727
  /**
2019
- * The React element to render while this router is loading data.
2020
- * Mutually exclusive with `HydrateFallback`.
2728
+ * @private
2729
+ * PRIVATE - DO NOT USE
2730
+ *
2731
+ * Utility function to create an href for the given location
2732
+ * @param location
2021
2733
  */
2022
- hydrateFallbackElement?: React.ReactNode | null;
2734
+ createHref(location: Location | URL): string;
2023
2735
  /**
2024
- * The React element to render at this route if an error occurs.
2025
- * Mutually exclusive with `ErrorBoundary`.
2736
+ * @private
2737
+ * PRIVATE - DO NOT USE
2738
+ *
2739
+ * Utility function to URL encode a destination path according to the internal
2740
+ * history implementation
2741
+ * @param to
2026
2742
  */
2027
- errorElement?: React.ReactNode | null;
2743
+ encodeLocation(to: To): Path;
2028
2744
  /**
2029
- * The React Component to render when this route matches.
2030
- * Mutually exclusive with `element`.
2745
+ * @private
2746
+ * PRIVATE - DO NOT USE
2747
+ *
2748
+ * Get/create a fetcher for the given key
2749
+ * @param key
2031
2750
  */
2032
- Component?: React.ComponentType | null;
2751
+ getFetcher<TData = any>(key: string): Fetcher<TData>;
2033
2752
  /**
2034
- * The React Component to render while this router is loading data.
2035
- * Mutually exclusive with `hydrateFallbackElement`.
2753
+ * @internal
2754
+ * PRIVATE - DO NOT USE
2755
+ *
2756
+ * Reset the fetcher for a given key
2757
+ * @param key
2036
2758
  */
2037
- HydrateFallback?: React.ComponentType | null;
2759
+ resetFetcher(key: string, opts?: {
2760
+ reason?: unknown;
2761
+ }): void;
2038
2762
  /**
2039
- * The React Component to render at this route if an error occurs.
2040
- * Mutually exclusive with `errorElement`.
2763
+ * @private
2764
+ * PRIVATE - DO NOT USE
2765
+ *
2766
+ * Delete the fetcher for a given key
2767
+ * @param key
2041
2768
  */
2042
- ErrorBoundary?: React.ComponentType | null;
2043
- }
2044
- type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;
2045
- /**
2046
- * Configures an element to render when a pattern matches the current location.
2047
- * It must be rendered within a {@link Routes} element. Note that these routes
2048
- * do not participate in data loading, actions, code splitting, or any other
2049
- * route module features.
2050
- *
2051
- * @example
2052
- * // Usually used in a declarative router
2053
- * function App() {
2054
- * return (
2055
- * <BrowserRouter>
2056
- * <Routes>
2057
- * <Route index element={<StepOne />} />
2058
- * <Route path="step-2" element={<StepTwo />} />
2059
- * <Route path="step-3" element={<StepThree />} />
2060
- * </Routes>
2061
- * </BrowserRouter>
2062
- * );
2063
- * }
2064
- *
2065
- * // But can be used with a data router as well if you prefer the JSX notation
2066
- * const routes = createRoutesFromElements(
2067
- * <>
2068
- * <Route index loader={step1Loader} Component={StepOne} />
2069
- * <Route path="step-2" loader={step2Loader} Component={StepTwo} />
2070
- * <Route path="step-3" loader={step3Loader} Component={StepThree} />
2071
- * </>
2072
- * );
2073
- *
2074
- * const router = createBrowserRouter(routes);
2075
- *
2076
- * function App() {
2077
- * return <RouterProvider router={router} />;
2078
- * }
2079
- *
2080
- * @public
2081
- * @category Components
2082
- * @param props Props
2083
- * @param {PathRouteProps.action} props.action n/a
2084
- * @param {PathRouteProps.caseSensitive} props.caseSensitive n/a
2085
- * @param {PathRouteProps.Component} props.Component n/a
2086
- * @param {PathRouteProps.children} props.children n/a
2087
- * @param {PathRouteProps.element} props.element n/a
2088
- * @param {PathRouteProps.ErrorBoundary} props.ErrorBoundary n/a
2089
- * @param {PathRouteProps.errorElement} props.errorElement n/a
2090
- * @param {PathRouteProps.handle} props.handle n/a
2091
- * @param {PathRouteProps.HydrateFallback} props.HydrateFallback n/a
2092
- * @param {PathRouteProps.hydrateFallbackElement} props.hydrateFallbackElement n/a
2093
- * @param {PathRouteProps.id} props.id n/a
2094
- * @param {PathRouteProps.index} props.index n/a
2095
- * @param {PathRouteProps.lazy} props.lazy n/a
2096
- * @param {PathRouteProps.loader} props.loader n/a
2097
- * @param {PathRouteProps.path} props.path n/a
2098
- * @param {PathRouteProps.shouldRevalidate} props.shouldRevalidate n/a
2099
- * @returns {void}
2100
- */
2101
- declare function Route(props: RouteProps): React.ReactElement | null;
2102
- /**
2103
- * @category Types
2104
- */
2105
- interface RouterProps {
2769
+ deleteFetcher(key: string): void;
2770
+ /**
2771
+ * @private
2772
+ * PRIVATE - DO NOT USE
2773
+ *
2774
+ * Cleanup listeners and abort any in-progress loads
2775
+ */
2776
+ dispose(): void;
2106
2777
  /**
2107
- * The base path for the application. This is prepended to all locations
2778
+ * @private
2779
+ * PRIVATE - DO NOT USE
2780
+ *
2781
+ * Get a navigation blocker
2782
+ * @param key The identifier for the blocker
2783
+ * @param fn The blocker function implementation
2108
2784
  */
2109
- basename?: string;
2785
+ getBlocker(key: string, fn: BlockerFunction): Blocker;
2110
2786
  /**
2111
- * Nested {@link Route} elements describing the route tree
2787
+ * @private
2788
+ * PRIVATE - DO NOT USE
2789
+ *
2790
+ * Delete a navigation blocker
2791
+ * @param key The identifier for the blocker
2112
2792
  */
2113
- children?: React.ReactNode;
2793
+ deleteBlocker(key: string): void;
2114
2794
  /**
2115
- * The location to match against. Defaults to the current location.
2116
- * This can be a string or a {@link Location} object.
2795
+ * @private
2796
+ * PRIVATE DO NOT USE
2797
+ *
2798
+ * Patch additional children routes into an existing parent route
2799
+ * @param routeId The parent route id or a callback function accepting `patch`
2800
+ * to perform batch patching
2801
+ * @param children The additional children routes
2802
+ * @param unstable_allowElementMutations Allow mutation or route elements on
2803
+ * existing routes. Intended for RSC-usage
2804
+ * only.
2117
2805
  */
2118
- location: Partial<Location> | string;
2806
+ patchRoutes(routeId: string | null, children: AgnosticRouteObject[], unstable_allowElementMutations?: boolean): void;
2119
2807
  /**
2120
- * The type of navigation that triggered this `location` change.
2121
- * Defaults to {@link NavigationType.Pop}.
2808
+ * @private
2809
+ * PRIVATE - DO NOT USE
2810
+ *
2811
+ * HMR needs to pass in-flight route updates to React Router
2812
+ * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)
2122
2813
  */
2123
- navigationType?: Action;
2814
+ _internalSetRoutes(routes: AgnosticRouteObject[]): void;
2124
2815
  /**
2125
- * The navigator to use for navigation. This is usually a history object
2126
- * or a custom navigator that implements the {@link Navigator} interface.
2816
+ * @private
2817
+ * PRIVATE - DO NOT USE
2818
+ *
2819
+ * Cause subscribers to re-render. This is used to force a re-render.
2127
2820
  */
2128
- navigator: Navigator;
2821
+ _internalSetStateDoNotUseOrYouWillBreakYourApp(state: Partial<RouterState>): void;
2129
2822
  /**
2130
- * Whether this router is static or not (used for SSR). If `true`, the router
2131
- * will not be reactive to location changes.
2823
+ * @private
2824
+ * PRIVATE - DO NOT USE
2825
+ *
2826
+ * Internal fetch AbortControllers accessed by unit tests
2132
2827
  */
2133
- static?: boolean;
2828
+ _internalFetchControllers: Map<string, AbortController>;
2134
2829
  }
2135
2830
  /**
2136
- * Provides location context for the rest of the app.
2137
- *
2138
- * Note: You usually won't render a `<Router>` directly. Instead, you'll render a
2139
- * router that is more specific to your environment such as a {@link BrowserRouter}
2140
- * in web browsers or a {@link ServerRouter} for server rendering.
2141
- *
2142
- * @public
2143
- * @category Declarative Routers
2144
- * @mode declarative
2145
- * @param props Props
2146
- * @param {RouterProps.basename} props.basename n/a
2147
- * @param {RouterProps.children} props.children n/a
2148
- * @param {RouterProps.location} props.location n/a
2149
- * @param {RouterProps.navigationType} props.navigationType n/a
2150
- * @param {RouterProps.navigator} props.navigator n/a
2151
- * @param {RouterProps.static} props.static n/a
2152
- * @returns React element for the rendered router or `null` if the location does
2153
- * not match the {@link props.basename}
2154
- */
2155
- declare function Router({ basename: basenameProp, children, location: locationProp, navigationType, navigator, static: staticProp, }: RouterProps): React.ReactElement | null;
2156
- /**
2157
- * @category Types
2831
+ * State maintained internally by the router. During a navigation, all states
2832
+ * reflect the "old" location unless otherwise noted.
2158
2833
  */
2159
- interface RoutesProps {
2834
+ interface RouterState {
2160
2835
  /**
2161
- * Nested {@link Route} elements
2836
+ * The action of the most recent navigation
2162
2837
  */
2163
- children?: React.ReactNode;
2838
+ historyAction: Action;
2164
2839
  /**
2165
- * The {@link Location} to match against. Defaults to the current location.
2840
+ * The current location reflected by the router
2166
2841
  */
2167
- location?: Partial<Location> | string;
2168
- }
2169
- /**
2170
- * Renders a branch of {@link Route | `<Route>`s} that best matches the current
2171
- * location. Note that these routes do not participate in [data loading](../../start/framework/route-module#loader),
2172
- * [`action`](../../start/framework/route-module#action), code splitting, or
2173
- * any other [route module](../../start/framework/route-module) features.
2174
- *
2175
- * @example
2176
- * import { Route, Routes } from "react-router";
2177
- *
2178
- * <Routes>
2179
- * <Route index element={<StepOne />} />
2180
- * <Route path="step-2" element={<StepTwo />} />
2181
- * <Route path="step-3" element={<StepThree />} />
2182
- * </Routes>
2183
- *
2184
- * @public
2185
- * @category Components
2186
- * @param props Props
2187
- * @param {RoutesProps.children} props.children n/a
2188
- * @param {RoutesProps.location} props.location n/a
2189
- * @returns React element for the rendered routes or `null` if no route matches
2190
- */
2191
- declare function Routes({ children, location, }: RoutesProps): React.ReactElement | null;
2192
- interface AwaitResolveRenderFunction<Resolve = any> {
2193
- (data: Awaited<Resolve>): React.ReactNode;
2194
- }
2195
- /**
2196
- * @category Types
2197
- */
2198
- interface AwaitProps<Resolve> {
2842
+ location: Location;
2199
2843
  /**
2200
- * When using a function, the resolved value is provided as the parameter.
2201
- *
2202
- * ```tsx [2]
2203
- * <Await resolve={reviewsPromise}>
2204
- * {(resolvedReviews) => <Reviews items={resolvedReviews} />}
2205
- * </Await>
2206
- * ```
2207
- *
2208
- * When using React elements, {@link useAsyncValue} will provide the
2209
- * resolved value:
2210
- *
2211
- * ```tsx [2]
2212
- * <Await resolve={reviewsPromise}>
2213
- * <Reviews />
2214
- * </Await>
2215
- *
2216
- * function Reviews() {
2217
- * const resolvedReviews = useAsyncValue();
2218
- * return <div>...</div>;
2219
- * }
2220
- * ```
2844
+ * The current set of route matches
2221
2845
  */
2222
- children: React.ReactNode | AwaitResolveRenderFunction<Resolve>;
2846
+ matches: AgnosticDataRouteMatch[];
2223
2847
  /**
2224
- * The error element renders instead of the `children` when the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
2225
- * rejects.
2226
- *
2227
- * ```tsx
2228
- * <Await
2229
- * errorElement={<div>Oops</div>}
2230
- * resolve={reviewsPromise}
2231
- * >
2232
- * <Reviews />
2233
- * </Await>
2234
- * ```
2235
- *
2236
- * To provide a more contextual error, you can use the {@link useAsyncError} in a
2237
- * child component
2238
- *
2239
- * ```tsx
2240
- * <Await
2241
- * errorElement={<ReviewsError />}
2242
- * resolve={reviewsPromise}
2243
- * >
2244
- * <Reviews />
2245
- * </Await>
2246
- *
2247
- * function ReviewsError() {
2248
- * const error = useAsyncError();
2249
- * return <div>Error loading reviews: {error.message}</div>;
2250
- * }
2251
- * ```
2252
- *
2253
- * If you do not provide an `errorElement`, the rejected value will bubble up
2254
- * to the nearest route-level [`ErrorBoundary`](../../start/framework/route-module#errorboundary)
2255
- * and be accessible via the {@link useRouteError} hook.
2848
+ * Tracks whether we've completed our initial data load
2256
2849
  */
2257
- errorElement?: React.ReactNode;
2850
+ initialized: boolean;
2258
2851
  /**
2259
- * Takes a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
2260
- * returned from a [`loader`](../../start/framework/route-module#loader) to be
2261
- * resolved and rendered.
2262
- *
2263
- * ```tsx
2264
- * import { Await, useLoaderData } from "react-router";
2265
- *
2266
- * export async function loader() {
2267
- * let reviews = getReviews(); // not awaited
2268
- * let book = await getBook();
2269
- * return {
2270
- * book,
2271
- * reviews, // this is a promise
2272
- * };
2273
- * }
2274
- *
2275
- * export default function Book() {
2276
- * const {
2277
- * book,
2278
- * reviews, // this is the same promise
2279
- * } = useLoaderData();
2280
- *
2281
- * return (
2282
- * <div>
2283
- * <h1>{book.title}</h1>
2284
- * <p>{book.description}</p>
2285
- * <React.Suspense fallback={<ReviewsSkeleton />}>
2286
- * <Await
2287
- * // and is the promise we pass to Await
2288
- * resolve={reviews}
2289
- * >
2290
- * <Reviews />
2291
- * </Await>
2292
- * </React.Suspense>
2293
- * </div>
2294
- * );
2295
- * }
2296
- * ```
2852
+ * Current scroll position we should start at for a new view
2853
+ * - number -> scroll position to restore to
2854
+ * - false -> do not restore scroll at all (used during submissions/revalidations)
2855
+ * - null -> don't have a saved position, scroll to hash or top of page
2856
+ */
2857
+ restoreScrollPosition: number | false | null;
2858
+ /**
2859
+ * Indicate whether this navigation should skip resetting the scroll position
2860
+ * if we are unable to restore the scroll position
2861
+ */
2862
+ preventScrollReset: boolean;
2863
+ /**
2864
+ * Tracks the state of the current navigation
2865
+ */
2866
+ navigation: Navigation;
2867
+ /**
2868
+ * Tracks any in-progress revalidations
2869
+ */
2870
+ revalidation: RevalidationState;
2871
+ /**
2872
+ * Data from the loaders for the current matches
2873
+ */
2874
+ loaderData: RouteData;
2875
+ /**
2876
+ * Data from the action for the current matches
2877
+ */
2878
+ actionData: RouteData | null;
2879
+ /**
2880
+ * Errors caught from loaders for the current matches
2881
+ */
2882
+ errors: RouteData | null;
2883
+ /**
2884
+ * Map of current fetchers
2885
+ */
2886
+ fetchers: Map<string, Fetcher>;
2887
+ /**
2888
+ * Map of current blockers
2297
2889
  */
2298
- resolve: Resolve;
2890
+ blockers: Map<string, Blocker>;
2299
2891
  }
2300
2892
  /**
2301
- * Used to render promise values with automatic error handling.
2302
- *
2303
- * **Note:** `<Await>` expects to be rendered inside a [`<React.Suspense>`](https://react.dev/reference/react/Suspense)
2304
- *
2305
- * @example
2306
- * import { Await, useLoaderData } from "react-router";
2307
- *
2308
- * export async function loader() {
2309
- * // not awaited
2310
- * const reviews = getReviews();
2311
- * // awaited (blocks the transition)
2312
- * const book = await fetch("/api/book").then((res) => res.json());
2313
- * return { book, reviews };
2314
- * }
2315
- *
2316
- * function Book() {
2317
- * const { book, reviews } = useLoaderData();
2318
- * return (
2319
- * <div>
2320
- * <h1>{book.title}</h1>
2321
- * <p>{book.description}</p>
2322
- * <React.Suspense fallback={<ReviewsSkeleton />}>
2323
- * <Await
2324
- * resolve={reviews}
2325
- * errorElement={
2326
- * <div>Could not load reviews 😬</div>
2327
- * }
2328
- * children={(resolvedReviews) => (
2329
- * <Reviews items={resolvedReviews} />
2330
- * )}
2331
- * />
2332
- * </React.Suspense>
2333
- * </div>
2334
- * );
2335
- * }
2336
- *
2337
- * @public
2338
- * @category Components
2339
- * @mode framework
2340
- * @mode data
2341
- * @param props Props
2342
- * @param {AwaitProps.children} props.children n/a
2343
- * @param {AwaitProps.errorElement} props.errorElement n/a
2344
- * @param {AwaitProps.resolve} props.resolve n/a
2345
- * @returns React element for the rendered awaited value
2893
+ * Data that can be passed into hydrate a Router from SSR
2346
2894
  */
2347
- declare function Await<Resolve>({ children, errorElement, resolve, }: AwaitProps<Resolve>): React.JSX.Element;
2895
+ type HydrationState = Partial<Pick<RouterState, "loaderData" | "actionData" | "errors">>;
2348
2896
  /**
2349
- * Creates a route config from a React "children" object, which is usually
2350
- * either a `<Route>` element or an array of them. Used internally by
2351
- * `<Routes>` to create a route config from its children.
2352
- *
2353
- * @category Utils
2354
- * @mode data
2355
- * @param children The React children to convert into a route config
2356
- * @param parentPath The path of the parent route, used to generate unique IDs.
2357
- * @returns An array of {@link RouteObject}s that can be used with a {@link DataRouter}
2897
+ * Future flags to toggle new feature behavior
2358
2898
  */
2359
- declare function createRoutesFromChildren(children: React.ReactNode, parentPath?: number[]): RouteObject[];
2899
+ interface FutureConfig {
2900
+ }
2360
2901
  /**
2361
- * Create route objects from JSX elements instead of arrays of objects.
2362
- *
2363
- * @example
2364
- * const routes = createRoutesFromElements(
2365
- * <>
2366
- * <Route index loader={step1Loader} Component={StepOne} />
2367
- * <Route path="step-2" loader={step2Loader} Component={StepTwo} />
2368
- * <Route path="step-3" loader={step3Loader} Component={StepThree} />
2369
- * </>
2370
- * );
2371
- *
2372
- * const router = createBrowserRouter(routes);
2373
- *
2374
- * function App() {
2375
- * return <RouterProvider router={router} />;
2376
- * }
2377
- *
2378
- * @name createRoutesFromElements
2379
- * @public
2380
- * @category Utils
2381
- * @mode data
2382
- * @param children The React children to convert into a route config
2383
- * @param parentPath The path of the parent route, used to generate unique IDs.
2384
- * This is used for internal recursion and is not intended to be used by the
2385
- * application developer.
2386
- * @returns An array of {@link RouteObject}s that can be used with a {@link DataRouter}
2902
+ * Initialization options for createRouter
2387
2903
  */
2388
- declare const createRoutesFromElements: typeof createRoutesFromChildren;
2904
+ interface RouterInit {
2905
+ routes: AgnosticRouteObject[];
2906
+ history: History;
2907
+ basename?: string;
2908
+ getContext?: () => MaybePromise<RouterContextProvider>;
2909
+ unstable_instrumentations?: unstable_ClientInstrumentation[];
2910
+ mapRouteProperties?: MapRoutePropertiesFunction;
2911
+ future?: Partial<FutureConfig>;
2912
+ hydrationRouteProperties?: string[];
2913
+ hydrationData?: HydrationState;
2914
+ window?: Window;
2915
+ dataStrategy?: DataStrategyFunction;
2916
+ patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;
2917
+ }
2389
2918
  /**
2390
- * Renders the result of {@link matchRoutes} into a React element.
2391
- *
2392
- * @public
2393
- * @category Utils
2394
- * @param matches The array of {@link RouteMatch | route matches} to render
2395
- * @returns A React element that renders the matched routes or `null` if no matches
2919
+ * State returned from a server-side query() call
2396
2920
  */
2397
- declare function renderMatches(matches: RouteMatch[] | null): React.ReactElement | null;
2398
- declare function useRouteComponentProps(): {
2399
- params: Readonly<Params<string>>;
2400
- loaderData: any;
2401
- actionData: any;
2402
- matches: UIMatch<unknown, unknown>[];
2403
- };
2404
- type RouteComponentProps = ReturnType<typeof useRouteComponentProps>;
2405
- type RouteComponentType = React.ComponentType<RouteComponentProps>;
2406
- declare function WithComponentProps({ children, }: {
2407
- children: React.ReactElement;
2408
- }): React.ReactElement<any, string | React.JSXElementConstructor<any>>;
2409
- declare function withComponentProps(Component: RouteComponentType): () => React.ReactElement<{
2410
- params: Readonly<Params<string>>;
2411
- loaderData: any;
2412
- actionData: any;
2413
- matches: UIMatch<unknown, unknown>[];
2414
- }, string | React.JSXElementConstructor<any>>;
2415
- declare function useHydrateFallbackProps(): {
2416
- params: Readonly<Params<string>>;
2417
- loaderData: any;
2418
- actionData: any;
2419
- };
2420
- type HydrateFallbackProps = ReturnType<typeof useHydrateFallbackProps>;
2421
- type HydrateFallbackType = React.ComponentType<HydrateFallbackProps>;
2422
- declare function WithHydrateFallbackProps({ children, }: {
2423
- children: React.ReactElement;
2424
- }): React.ReactElement<any, string | React.JSXElementConstructor<any>>;
2425
- declare function withHydrateFallbackProps(HydrateFallback: HydrateFallbackType): () => React.ReactElement<{
2426
- params: Readonly<Params<string>>;
2427
- loaderData: any;
2428
- actionData: any;
2429
- }, string | React.JSXElementConstructor<any>>;
2430
- declare function useErrorBoundaryProps(): {
2431
- params: Readonly<Params<string>>;
2432
- loaderData: any;
2433
- actionData: any;
2434
- error: unknown;
2435
- };
2436
- type ErrorBoundaryProps = ReturnType<typeof useErrorBoundaryProps>;
2437
- type ErrorBoundaryType = React.ComponentType<ErrorBoundaryProps>;
2438
- declare function WithErrorBoundaryProps({ children, }: {
2439
- children: React.ReactElement;
2440
- }): React.ReactElement<any, string | React.JSXElementConstructor<any>>;
2441
- declare function withErrorBoundaryProps(ErrorBoundary: ErrorBoundaryType): () => React.ReactElement<{
2442
- params: Readonly<Params<string>>;
2443
- loaderData: any;
2444
- actionData: any;
2445
- error: unknown;
2446
- }, string | React.JSXElementConstructor<any>>;
2447
-
2448
- interface IndexRouteObject {
2449
- caseSensitive?: AgnosticIndexRouteObject["caseSensitive"];
2450
- path?: AgnosticIndexRouteObject["path"];
2451
- id?: AgnosticIndexRouteObject["id"];
2452
- middleware?: AgnosticIndexRouteObject["middleware"];
2453
- loader?: AgnosticIndexRouteObject["loader"];
2454
- action?: AgnosticIndexRouteObject["action"];
2455
- hasErrorBoundary?: AgnosticIndexRouteObject["hasErrorBoundary"];
2456
- shouldRevalidate?: AgnosticIndexRouteObject["shouldRevalidate"];
2457
- handle?: AgnosticIndexRouteObject["handle"];
2458
- index: true;
2459
- children?: undefined;
2460
- element?: React.ReactNode | null;
2461
- hydrateFallbackElement?: React.ReactNode | null;
2462
- errorElement?: React.ReactNode | null;
2463
- Component?: React.ComponentType | null;
2464
- HydrateFallback?: React.ComponentType | null;
2465
- ErrorBoundary?: React.ComponentType | null;
2466
- lazy?: LazyRouteDefinition<RouteObject>;
2467
- }
2468
- interface NonIndexRouteObject {
2469
- caseSensitive?: AgnosticNonIndexRouteObject["caseSensitive"];
2470
- path?: AgnosticNonIndexRouteObject["path"];
2471
- id?: AgnosticNonIndexRouteObject["id"];
2472
- middleware?: AgnosticNonIndexRouteObject["middleware"];
2473
- loader?: AgnosticNonIndexRouteObject["loader"];
2474
- action?: AgnosticNonIndexRouteObject["action"];
2475
- hasErrorBoundary?: AgnosticNonIndexRouteObject["hasErrorBoundary"];
2476
- shouldRevalidate?: AgnosticNonIndexRouteObject["shouldRevalidate"];
2477
- handle?: AgnosticNonIndexRouteObject["handle"];
2478
- index?: false;
2479
- children?: RouteObject[];
2480
- element?: React.ReactNode | null;
2481
- hydrateFallbackElement?: React.ReactNode | null;
2482
- errorElement?: React.ReactNode | null;
2483
- Component?: React.ComponentType | null;
2484
- HydrateFallback?: React.ComponentType | null;
2485
- ErrorBoundary?: React.ComponentType | null;
2486
- lazy?: LazyRouteDefinition<RouteObject>;
2487
- }
2488
- type RouteObject = IndexRouteObject | NonIndexRouteObject;
2489
- type DataRouteObject = RouteObject & {
2490
- children?: DataRouteObject[];
2491
- id: string;
2492
- };
2493
- interface RouteMatch<ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {
2494
- }
2495
- interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {
2921
+ interface StaticHandlerContext {
2922
+ basename: Router["basename"];
2923
+ location: RouterState["location"];
2924
+ matches: RouterState["matches"];
2925
+ loaderData: RouterState["loaderData"];
2926
+ actionData: RouterState["actionData"];
2927
+ errors: RouterState["errors"];
2928
+ statusCode: number;
2929
+ loaderHeaders: Record<string, Headers>;
2930
+ actionHeaders: Record<string, Headers>;
2931
+ _deepestRenderedBoundaryId?: string | null;
2496
2932
  }
2497
- type PatchRoutesOnNavigationFunctionArgs = AgnosticPatchRoutesOnNavigationFunctionArgs<RouteObject, RouteMatch>;
2498
- type PatchRoutesOnNavigationFunction = AgnosticPatchRoutesOnNavigationFunction<RouteObject, RouteMatch>;
2499
- interface DataRouterContextObject extends Omit<NavigationContextObject, "future"> {
2500
- router: Router$1;
2501
- staticContext?: StaticHandlerContext;
2502
- unstable_onError?: unstable_ClientOnErrorFunction;
2933
+ /**
2934
+ * A StaticHandler instance manages a singular SSR navigation/fetch event
2935
+ */
2936
+ interface StaticHandler {
2937
+ dataRoutes: AgnosticDataRouteObject[];
2938
+ query(request: Request, opts?: {
2939
+ requestContext?: unknown;
2940
+ filterMatchesToLoad?: (match: AgnosticDataRouteMatch) => boolean;
2941
+ skipLoaderErrorBubbling?: boolean;
2942
+ skipRevalidation?: boolean;
2943
+ dataStrategy?: DataStrategyFunction<unknown>;
2944
+ generateMiddlewareResponse?: (query: (r: Request, args?: {
2945
+ filterMatchesToLoad?: (match: AgnosticDataRouteMatch) => boolean;
2946
+ }) => Promise<StaticHandlerContext | Response>) => MaybePromise<Response>;
2947
+ }): Promise<StaticHandlerContext | Response>;
2948
+ queryRoute(request: Request, opts?: {
2949
+ routeId?: string;
2950
+ requestContext?: unknown;
2951
+ dataStrategy?: DataStrategyFunction<unknown>;
2952
+ generateMiddlewareResponse?: (queryRoute: (r: Request) => Promise<Response>) => MaybePromise<Response>;
2953
+ }): Promise<any>;
2503
2954
  }
2504
- declare const DataRouterContext: React.Context<DataRouterContextObject | null>;
2505
- declare const DataRouterStateContext: React.Context<RouterState | null>;
2506
- type ViewTransitionContextObject = {
2507
- isTransitioning: false;
2508
- } | {
2509
- isTransitioning: true;
2510
- flushSync: boolean;
2955
+ type ViewTransitionOpts = {
2511
2956
  currentLocation: Location;
2512
2957
  nextLocation: Location;
2513
2958
  };
2514
- declare const ViewTransitionContext: React.Context<ViewTransitionContextObject>;
2515
- type FetchersContextObject = Map<string, any>;
2516
- declare const FetchersContext: React.Context<FetchersContextObject>;
2517
- declare const AwaitContext: React.Context<TrackedPromise | null>;
2518
- declare const AwaitContextProvider: (props: React.ComponentProps<typeof AwaitContext.Provider>) => React.FunctionComponentElement<React.ProviderProps<TrackedPromise | null>>;
2519
- interface NavigateOptions {
2520
- /** Replace the current entry in the history stack instead of pushing a new one */
2521
- replace?: boolean;
2522
- /** Adds persistent client side routing state to the next location */
2523
- state?: any;
2524
- /** If you are using {@link https://api.reactrouter.com/v7/functions/react_router.ScrollRestoration.html <ScrollRestoration>}, prevent the scroll position from being reset to the top of the window when navigating */
2959
+ /**
2960
+ * Subscriber function signature for changes to router state
2961
+ */
2962
+ interface RouterSubscriber {
2963
+ (state: RouterState, opts: {
2964
+ deletedFetchers: string[];
2965
+ viewTransitionOpts?: ViewTransitionOpts;
2966
+ flushSync: boolean;
2967
+ }): void;
2968
+ }
2969
+ /**
2970
+ * Function signature for determining the key to be used in scroll restoration
2971
+ * for a given location
2972
+ */
2973
+ interface GetScrollRestorationKeyFunction {
2974
+ (location: Location, matches: UIMatch[]): string | null;
2975
+ }
2976
+ /**
2977
+ * Function signature for determining the current scroll position
2978
+ */
2979
+ interface GetScrollPositionFunction {
2980
+ (): number;
2981
+ }
2982
+ /**
2983
+ * - "route": relative to the route hierarchy so `..` means remove all segments
2984
+ * of the current route even if it has many. For example, a `route("posts/:id")`
2985
+ * would have both `:id` and `posts` removed from the url.
2986
+ * - "path": relative to the pathname so `..` means remove one segment of the
2987
+ * pathname. For example, a `route("posts/:id")` would have only `:id` removed
2988
+ * from the url.
2989
+ */
2990
+ type RelativeRoutingType = "route" | "path";
2991
+ type BaseNavigateOrFetchOptions = {
2525
2992
  preventScrollReset?: boolean;
2526
- /** Defines the relative path behavior for the link. "route" will use the route hierarchy so ".." will remove all URL segments of the current route pattern while "path" will use the URL path so ".." will remove one URL segment. */
2527
2993
  relative?: RelativeRoutingType;
2528
- /** Wraps the initial state update for this navigation in a {@link https://react.dev/reference/react-dom/flushSync ReactDOM.flushSync} call instead of the default {@link https://react.dev/reference/react/startTransition React.startTransition} */
2529
2994
  flushSync?: boolean;
2530
- /** Enables a {@link https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API View Transition} for this navigation by wrapping the final state update in `document.startViewTransition()`. If you need to apply specific styles for this view transition, you will also need to leverage the {@link https://api.reactrouter.com/v7/functions/react_router.useViewTransitionState.html useViewTransitionState()} hook. */
2995
+ };
2996
+ type BaseNavigateOptions = BaseNavigateOrFetchOptions & {
2997
+ replace?: boolean;
2998
+ state?: any;
2999
+ fromRouteId?: string;
2531
3000
  viewTransition?: boolean;
2532
- }
3001
+ };
3002
+ type BaseSubmissionOptions = {
3003
+ formMethod?: HTMLFormMethod;
3004
+ formEncType?: FormEncType;
3005
+ } & ({
3006
+ formData: FormData;
3007
+ body?: undefined;
3008
+ } | {
3009
+ formData?: undefined;
3010
+ body: any;
3011
+ });
2533
3012
  /**
2534
- * A Navigator is a "location changer"; it's how you get to different locations.
2535
- *
2536
- * Every history instance conforms to the Navigator interface, but the
2537
- * distinction is useful primarily when it comes to the low-level `<Router>` API
2538
- * where both the location and a navigator must be provided separately in order
2539
- * to avoid "tearing" that may occur in a suspense-enabled app if the action
2540
- * and/or location were to be read directly from the history instance.
3013
+ * Options for a navigate() call for a normal (non-submission) navigation
2541
3014
  */
2542
- interface Navigator {
2543
- createHref: History["createHref"];
2544
- encodeLocation?: History["encodeLocation"];
2545
- go: History["go"];
2546
- push(to: To, state?: any, opts?: NavigateOptions): void;
2547
- replace(to: To, state?: any, opts?: NavigateOptions): void;
3015
+ type LinkNavigateOptions = BaseNavigateOptions;
3016
+ /**
3017
+ * Options for a navigate() call for a submission navigation
3018
+ */
3019
+ type SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;
3020
+ /**
3021
+ * Options to pass to navigate() for a navigation
3022
+ */
3023
+ type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions;
3024
+ /**
3025
+ * Options for a fetch() load
3026
+ */
3027
+ type LoadFetchOptions = BaseNavigateOrFetchOptions;
3028
+ /**
3029
+ * Options for a fetch() submission
3030
+ */
3031
+ type SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;
3032
+ /**
3033
+ * Options to pass to fetch()
3034
+ */
3035
+ type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;
3036
+ /**
3037
+ * Potential states for state.navigation
3038
+ */
3039
+ type NavigationStates = {
3040
+ Idle: {
3041
+ state: "idle";
3042
+ location: undefined;
3043
+ formMethod: undefined;
3044
+ formAction: undefined;
3045
+ formEncType: undefined;
3046
+ formData: undefined;
3047
+ json: undefined;
3048
+ text: undefined;
3049
+ };
3050
+ Loading: {
3051
+ state: "loading";
3052
+ location: Location;
3053
+ formMethod: Submission["formMethod"] | undefined;
3054
+ formAction: Submission["formAction"] | undefined;
3055
+ formEncType: Submission["formEncType"] | undefined;
3056
+ formData: Submission["formData"] | undefined;
3057
+ json: Submission["json"] | undefined;
3058
+ text: Submission["text"] | undefined;
3059
+ };
3060
+ Submitting: {
3061
+ state: "submitting";
3062
+ location: Location;
3063
+ formMethod: Submission["formMethod"];
3064
+ formAction: Submission["formAction"];
3065
+ formEncType: Submission["formEncType"];
3066
+ formData: Submission["formData"];
3067
+ json: Submission["json"];
3068
+ text: Submission["text"];
3069
+ };
3070
+ };
3071
+ type Navigation = NavigationStates[keyof NavigationStates];
3072
+ type RevalidationState = "idle" | "loading";
3073
+ /**
3074
+ * Potential states for fetchers
3075
+ */
3076
+ type FetcherStates<TData = any> = {
3077
+ /**
3078
+ * The fetcher is not calling a loader or action
3079
+ *
3080
+ * ```tsx
3081
+ * fetcher.state === "idle"
3082
+ * ```
3083
+ */
3084
+ Idle: {
3085
+ state: "idle";
3086
+ formMethod: undefined;
3087
+ formAction: undefined;
3088
+ formEncType: undefined;
3089
+ text: undefined;
3090
+ formData: undefined;
3091
+ json: undefined;
3092
+ /**
3093
+ * If the fetcher has never been called, this will be undefined.
3094
+ */
3095
+ data: TData | undefined;
3096
+ };
3097
+ /**
3098
+ * The fetcher is loading data from a {@link LoaderFunction | loader} from a
3099
+ * call to {@link FetcherWithComponents.load | `fetcher.load`}.
3100
+ *
3101
+ * ```tsx
3102
+ * // somewhere
3103
+ * <button onClick={() => fetcher.load("/some/route") }>Load</button>
3104
+ *
3105
+ * // the state will update
3106
+ * fetcher.state === "loading"
3107
+ * ```
3108
+ */
3109
+ Loading: {
3110
+ state: "loading";
3111
+ formMethod: Submission["formMethod"] | undefined;
3112
+ formAction: Submission["formAction"] | undefined;
3113
+ formEncType: Submission["formEncType"] | undefined;
3114
+ text: Submission["text"] | undefined;
3115
+ formData: Submission["formData"] | undefined;
3116
+ json: Submission["json"] | undefined;
3117
+ data: TData | undefined;
3118
+ };
3119
+ /**
3120
+ 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`}.
3121
+
3122
+ ```tsx
3123
+ // somewhere
3124
+ <input
3125
+ onChange={e => {
3126
+ fetcher.submit(event.currentTarget.form, { method: "post" });
3127
+ }}
3128
+ />
3129
+
3130
+ // the state will update
3131
+ fetcher.state === "submitting"
3132
+
3133
+ // and formData will be available
3134
+ fetcher.formData
3135
+ ```
3136
+ */
3137
+ Submitting: {
3138
+ state: "submitting";
3139
+ formMethod: Submission["formMethod"];
3140
+ formAction: Submission["formAction"];
3141
+ formEncType: Submission["formEncType"];
3142
+ text: Submission["text"];
3143
+ formData: Submission["formData"];
3144
+ json: Submission["json"];
3145
+ data: TData | undefined;
3146
+ };
3147
+ };
3148
+ type Fetcher<TData = any> = FetcherStates<TData>[keyof FetcherStates<TData>];
3149
+ interface BlockerBlocked {
3150
+ state: "blocked";
3151
+ reset: () => void;
3152
+ proceed: () => void;
3153
+ location: Location;
2548
3154
  }
2549
- interface NavigationContextObject {
2550
- basename: string;
2551
- navigator: Navigator;
2552
- static: boolean;
2553
- future: {};
3155
+ interface BlockerUnblocked {
3156
+ state: "unblocked";
3157
+ reset: undefined;
3158
+ proceed: undefined;
3159
+ location: undefined;
2554
3160
  }
2555
- declare const NavigationContext: React.Context<NavigationContextObject>;
2556
- interface LocationContextObject {
3161
+ interface BlockerProceeding {
3162
+ state: "proceeding";
3163
+ reset: undefined;
3164
+ proceed: undefined;
2557
3165
  location: Location;
2558
- navigationType: Action;
2559
3166
  }
2560
- declare const LocationContext: React.Context<LocationContextObject>;
2561
- interface RouteContextObject {
2562
- outlet: React.ReactElement | null;
2563
- matches: RouteMatch[];
2564
- isDataRoute: boolean;
3167
+ type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;
3168
+ type BlockerFunction = (args: {
3169
+ currentLocation: Location;
3170
+ nextLocation: Location;
3171
+ historyAction: Action;
3172
+ }) => boolean;
3173
+ declare const IDLE_NAVIGATION: NavigationStates["Idle"];
3174
+ declare const IDLE_FETCHER: FetcherStates["Idle"];
3175
+ declare const IDLE_BLOCKER: BlockerUnblocked;
3176
+ /**
3177
+ * Create a router and listen to history POP navigations
3178
+ */
3179
+ declare function createRouter(init: RouterInit): Router;
3180
+ interface CreateStaticHandlerOptions {
3181
+ basename?: string;
3182
+ mapRouteProperties?: MapRoutePropertiesFunction;
3183
+ unstable_instrumentations?: Pick<unstable_ServerInstrumentation, "route">[];
3184
+ future?: {};
2565
3185
  }
2566
- declare const RouteContext: React.Context<RouteContextObject>;
2567
3186
 
2568
- export { type DataStrategyMatch as $, type ActionFunctionArgs as A, type BlockerFunction as B, type PatchRoutesOnNavigationFunction as C, type DataStrategyResult as D, type ErrorBoundaryType as E, type DataRouteObject as F, type StaticHandler as G, type HydrationState as H, type InitialEntry as I, type GetScrollPositionFunction as J, type GetScrollRestorationKeyFunction as K, type Location as L, type MiddlewareNextFunction as M, type NavigateOptions as N, type StaticHandlerContext as O, type Params as P, type Fetcher as Q, type RouterProviderProps as R, type ShouldRevalidateFunction as S, type To as T, type UIMatch as U, type NavigationStates as V, type RouterSubscriber as W, type RouterNavigateOptions as X, type RouterFetchOptions as Y, type RevalidationState as Z, type DataStrategyFunctionArgs as _, type RouterInit as a, hydrationRouteProperties as a$, type ErrorResponse as a0, type FormEncType as a1, type FormMethod as a2, type HTMLFormMethod as a3, type LazyRouteFunction as a4, type PathParam as a5, type RedirectFunction as a6, type RouterContext as a7, type ShouldRevalidateFunctionArgs as a8, createContext as a9, type RouteProps as aA, type RouterProps as aB, type RoutesProps as aC, Await as aD, MemoryRouter as aE, Navigate as aF, Outlet as aG, Route as aH, Router as aI, RouterProvider as aJ, Routes as aK, createMemoryRouter as aL, createRoutesFromChildren as aM, createRoutesFromElements as aN, renderMatches as aO, type Future as aP, createBrowserHistory as aQ, invariant as aR, createRouter as aS, ErrorResponseImpl as aT, DataRouterContext as aU, DataRouterStateContext as aV, FetchersContext as aW, LocationContext as aX, NavigationContext as aY, RouteContext as aZ, ViewTransitionContext as a_, createPath as aa, parsePath as ab, IDLE_NAVIGATION as ac, IDLE_FETCHER as ad, IDLE_BLOCKER as ae, data as af, generatePath as ag, isRouteErrorResponse as ah, matchPath as ai, matchRoutes as aj, redirect as ak, redirectDocument as al, replace as am, resolvePath as an, type Navigator as ao, type PatchRoutesOnNavigationFunctionArgs as ap, type RouteMatch as aq, AwaitContextProvider as ar, type AwaitProps as as, type IndexRouteProps as at, type LayoutRouteProps as au, type MemoryRouterOpts as av, type MemoryRouterProps as aw, type NavigateProps as ax, type OutletProps as ay, type PathRouteProps as az, type LoaderFunctionArgs as b, mapRouteProperties as b0, WithComponentProps as b1, withComponentProps as b2, WithHydrateFallbackProps as b3, withHydrateFallbackProps as b4, WithErrorBoundaryProps as b5, withErrorBoundaryProps as b6, type RouteManifest as b7, type History as b8, type FutureConfig as b9, type CreateStaticHandlerOptions as ba, type ActionFunction as c, type LoaderFunction as d, type DataRouteMatch as e, type MiddlewareFunction as f, RouterContextProvider as g, DataWithResponseInit as h, type MiddlewareEnabled as i, type Router$1 as j, type DataStrategyFunction as k, type Blocker as l, type RelativeRoutingType as m, type ParamParseKey as n, type Path as o, type PathPattern as p, type PathMatch as q, type Navigation as r, Action as s, type RouteObject as t, type unstable_ClientOnErrorFunction as u, type IndexRouteObject as v, type RouteComponentType as w, type HydrateFallbackType as x, type NonIndexRouteObject as y, type RouterState as z };
3187
+ export { type NonIndexRouteObject as $, type ActionFunction as A, type BlockerFunction as B, type ClientActionFunction as C, type DataStrategyResult as D, type Path as E, type Func as F, type GetLoaderData as G, type HeadersFunction as H, type PathPattern as I, type PathMatch as J, type Navigation as K, type Location as L, type MetaFunction as M, type Normalize as N, Action as O, type Params as P, type RouteObject as Q, type RouteModule$1 as R, type ShouldRevalidateFunction as S, type To as T, type UIMatch as U, type InitialEntry as V, type HydrationState as W, type IndexRouteObject as X, type RouteComponentType as Y, type HydrateFallbackType as Z, type ErrorBoundaryType as _, type ClientLoaderFunction as a, type RouterProps as a$, type Equal as a0, type RouterState as a1, type PatchRoutesOnNavigationFunction as a2, type DataRouteObject as a3, type StaticHandler as a4, type GetScrollPositionFunction as a5, type GetScrollRestorationKeyFunction as a6, type StaticHandlerContext as a7, type Fetcher as a8, type NavigationStates as a9, type unstable_InstrumentationHandlerResult as aA, IDLE_NAVIGATION as aB, IDLE_FETCHER as aC, IDLE_BLOCKER as aD, data as aE, generatePath as aF, isRouteErrorResponse as aG, matchPath as aH, matchRoutes as aI, redirect as aJ, redirectDocument as aK, replace as aL, resolvePath as aM, type DataRouteMatch as aN, type Navigator as aO, type PatchRoutesOnNavigationFunctionArgs as aP, type RouteMatch as aQ, AwaitContextProvider as aR, type AwaitProps as aS, type IndexRouteProps as aT, type LayoutRouteProps as aU, type MemoryRouterOpts as aV, type MemoryRouterProps as aW, type NavigateProps as aX, type OutletProps as aY, type PathRouteProps as aZ, type RouteProps as a_, type RouterSubscriber as aa, type RouterNavigateOptions as ab, type RouterFetchOptions as ac, type RevalidationState as ad, type ActionFunctionArgs as ae, type DataStrategyFunctionArgs as af, type DataStrategyMatch as ag, DataWithResponseInit as ah, type ErrorResponse as ai, type FormEncType as aj, type FormMethod as ak, type HTMLFormMethod as al, type LazyRouteFunction as am, type LoaderFunctionArgs as an, type MiddlewareFunction as ao, type PathParam as ap, type RedirectFunction as aq, type RouterContext as ar, type ShouldRevalidateFunctionArgs as as, createContext as at, createPath as au, parsePath as av, type unstable_ServerInstrumentation as aw, type unstable_InstrumentRequestHandlerFunction as ax, type unstable_InstrumentRouterFunction as ay, type unstable_InstrumentRouteFunction as az, type LinksFunction as b, type RoutesProps as b0, Await as b1, MemoryRouter as b2, Navigate as b3, Outlet as b4, Route as b5, Router$1 as b6, RouterProvider as b7, Routes as b8, createMemoryRouter as b9, WithHydrateFallbackProps as bA, withHydrateFallbackProps as bB, WithErrorBoundaryProps as bC, withErrorBoundaryProps as bD, type RouteManifest as bE, type ServerRouteModule as bF, type History as bG, type FutureConfig as bH, type CreateStaticHandlerOptions as bI, createRoutesFromChildren as ba, createRoutesFromElements as bb, renderMatches as bc, type ClientActionFunctionArgs as bd, type ClientLoaderFunctionArgs as be, type HeadersArgs as bf, type MetaArgs as bg, type PageLinkDescriptor as bh, type HtmlLinkDescriptor as bi, type Future as bj, type unstable_SerializesTo as bk, createBrowserHistory as bl, invariant as bm, createRouter as bn, ErrorResponseImpl as bo, DataRouterContext as bp, DataRouterStateContext as bq, FetchersContext as br, LocationContext as bs, NavigationContext as bt, RouteContext as bu, ViewTransitionContext as bv, hydrationRouteProperties as bw, mapRouteProperties as bx, WithComponentProps as by, withComponentProps as bz, RouterContextProvider as c, type LoaderFunction as d, type RouterInit as e, type RouterProviderProps as f, type unstable_ClientOnErrorFunction as g, type LinkDescriptor as h, type Pretty as i, type MetaDescriptor as j, type ServerDataFunctionArgs as k, type MiddlewareNextFunction as l, type ClientDataFunctionArgs as m, type ServerDataFrom as n, type GetActionData as o, type Router as p, type RouteModules as q, type DataStrategyFunction as r, type MiddlewareEnabled as s, type AppLoadContext as t, type unstable_ClientInstrumentation as u, type NavigateOptions as v, type Blocker as w, type SerializeFrom as x, type RelativeRoutingType as y, type ParamParseKey as z };