react-router 7.7.1 → 7.8.0-pre.0

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 (66) hide show
  1. package/CHANGELOG.md +81 -5
  2. package/dist/development/browser-z32v5KVN.d.mts +46 -0
  3. package/dist/{production/chunk-K3SBCRK4.mjs → development/chunk-HSC5IU24.mjs} +177 -134
  4. package/dist/development/{chunk-K7YFBME3.js → chunk-IW6UADHO.js} +250 -187
  5. package/dist/development/{chunk-C37GKA54.mjs → chunk-SC4OUYO4.mjs} +232 -169
  6. package/dist/development/{chunk-R73PQUJU.js → chunk-Z4NNCWGU.js} +130 -130
  7. package/dist/development/{components-CjQijYga.d.mts → components-uUh0svuC.d.mts} +33 -21
  8. package/dist/{production/route-data-CqEmXQub.d.mts → development/context-DZWGFcKX.d.mts} +312 -524
  9. package/dist/development/dom-export.d.mts +16 -12
  10. package/dist/development/dom-export.d.ts +13 -8
  11. package/dist/development/dom-export.js +3 -3
  12. package/dist/development/dom-export.mjs +3 -3
  13. package/dist/{production/index-react-server-client-KLg-U4nr.d.mts → development/index-react-server-client-BUK-oRcG.d.mts} +327 -200
  14. package/dist/development/{index-react-server-client-Bi_fx8qz.d.ts → index-react-server-client-DSU6bZil.d.ts} +357 -219
  15. package/dist/development/index-react-server-client.d.mts +4 -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 +291 -70
  20. package/dist/development/index-react-server.d.ts +291 -70
  21. package/dist/development/index-react-server.js +174 -180
  22. package/dist/development/index-react-server.mjs +174 -180
  23. package/dist/development/index.d.mts +294 -86
  24. package/dist/development/index.d.ts +136 -105
  25. package/dist/development/index.js +258 -215
  26. package/dist/development/index.mjs +3 -3
  27. package/dist/development/lib/types/internal.d.mts +13 -2
  28. package/dist/development/lib/types/internal.d.ts +12 -2
  29. package/dist/development/lib/types/internal.js +1 -1
  30. package/dist/development/lib/types/internal.mjs +1 -1
  31. package/dist/development/route-data-UTmTa8an.d.mts +473 -0
  32. package/dist/{production/routeModules-BR2FO0ix.d.ts → development/routeModules-D5bppTB2.d.ts} +325 -67
  33. package/dist/production/browser-z32v5KVN.d.mts +46 -0
  34. package/dist/production/{chunk-4DGLNKXF.js → chunk-BCLZG6QW.js} +130 -130
  35. package/dist/{development/chunk-KIUJAIYX.mjs → production/chunk-KQ5567DT.mjs} +177 -134
  36. package/dist/production/{chunk-IZ57JD2V.mjs → chunk-X2NPJMV2.mjs} +232 -169
  37. package/dist/production/{chunk-7OQROU2D.js → chunk-YC2ENCM3.js} +250 -187
  38. package/dist/production/{components-CjQijYga.d.mts → components-uUh0svuC.d.mts} +33 -21
  39. package/dist/{development/route-data-CqEmXQub.d.mts → production/context-DZWGFcKX.d.mts} +312 -524
  40. package/dist/production/dom-export.d.mts +16 -12
  41. package/dist/production/dom-export.d.ts +13 -8
  42. package/dist/production/dom-export.js +3 -3
  43. package/dist/production/dom-export.mjs +3 -3
  44. package/dist/{development/index-react-server-client-KLg-U4nr.d.mts → production/index-react-server-client-BUK-oRcG.d.mts} +327 -200
  45. package/dist/production/{index-react-server-client-Bi_fx8qz.d.ts → index-react-server-client-DSU6bZil.d.ts} +357 -219
  46. package/dist/production/index-react-server-client.d.mts +4 -3
  47. package/dist/production/index-react-server-client.d.ts +2 -2
  48. package/dist/production/index-react-server-client.js +4 -4
  49. package/dist/production/index-react-server-client.mjs +2 -2
  50. package/dist/production/index-react-server.d.mts +291 -70
  51. package/dist/production/index-react-server.d.ts +291 -70
  52. package/dist/production/index-react-server.js +174 -180
  53. package/dist/production/index-react-server.mjs +174 -180
  54. package/dist/production/index.d.mts +294 -86
  55. package/dist/production/index.d.ts +136 -105
  56. package/dist/production/index.js +258 -215
  57. package/dist/production/index.mjs +3 -3
  58. package/dist/production/lib/types/internal.d.mts +13 -2
  59. package/dist/production/lib/types/internal.d.ts +12 -2
  60. package/dist/production/lib/types/internal.js +1 -1
  61. package/dist/production/lib/types/internal.mjs +1 -1
  62. package/dist/production/route-data-UTmTa8an.d.mts +473 -0
  63. package/dist/{development/routeModules-BR2FO0ix.d.ts → production/routeModules-D5bppTB2.d.ts} +325 -67
  64. package/package.json +1 -1
  65. package/dist/development/browser-7LYX59NK.d.mts +0 -226
  66. package/dist/production/browser-7LYX59NK.d.mts +0 -226
@@ -271,35 +271,123 @@ type Submission = {
271
271
  json: undefined;
272
272
  text: string;
273
273
  };
274
+ /**
275
+ * A context instance used as the key for the `get`/`set` methods of a
276
+ * {@link unstable_RouterContextProvider}. Accepts an optional default
277
+ * value to be returned if no value has been set.
278
+ */
274
279
  interface unstable_RouterContext<T = unknown> {
275
280
  defaultValue?: T;
276
281
  }
277
282
  /**
278
- * Creates a context object that may be used to store and retrieve arbitrary values.
283
+ * Creates a type-safe {@link unstable_RouterContext} object that can be used to
284
+ * * store and retrieve arbitrary values in [`action`](../../start/framework/route-module#action)s,
285
+ * * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
286
+ * * Similar to React's [`createContext`](https://react.dev/reference/react/createContext),
287
+ * * but specifically designed for React Router's request/response lifecycle.
288
+ *
289
+ * <docs-warning>Enable this API with the `future.unstable_middleware` flag.</docs-warning>
290
+ *
291
+ * If a `defaultValue` is provided, it will be returned from `context.get()`
292
+ * when no value has been set for the context. Otherwise, reading this context
293
+ * when no value has been set will throw an error.
294
+ *
295
+ * ```tsx filename=app/context.ts
296
+ * import { unstable_createContext } from "react-router";
297
+ *
298
+ * // Create a context for user data
299
+ * export const userContext =
300
+ * unstable_createContext<User | null>(null);
301
+ * ```
302
+ *
303
+ * ```tsx filename=app/middleware/auth.ts
304
+ * import { getUserFromSession } from "~/auth.server";
305
+ * import { userContext } from "~/context";
306
+ *
307
+ * export const authMiddleware = async ({
308
+ * context,
309
+ * request,
310
+ * }) => {
311
+ * const user = await getUserFromSession(request);
312
+ * context.set(userContext, user);
313
+ * };
314
+ * ```
315
+ *
316
+ * ```tsx filename=app/routes/profile.tsx
317
+ * import { userContext } from "~/context";
318
+ *
319
+ * export async function loader({
320
+ * context,
321
+ * }: Route.LoaderArgs) {
322
+ * const user = context.get(userContext);
279
323
  *
280
- * If a `defaultValue` is provided, it will be returned from `context.get()` when no value has been
281
- * set for the context. Otherwise reading this context when no value has been set will throw an
282
- * error.
324
+ * if (!user) {
325
+ * throw new Response("Unauthorized", { status: 401 });
326
+ * }
283
327
  *
284
- * @param defaultValue The default value for the context
285
- * @returns A context object
328
+ * return { user };
329
+ * }
330
+ * ```
331
+ *
332
+ * @public
333
+ * @category Utils
334
+ * @mode framework
335
+ * @mode data
336
+ * @param defaultValue An optional default value for the context. This value
337
+ * will be returned if no value has been set for this context.
338
+ * @returns A {@link unstable_RouterContext} object that can be used with
339
+ * `context.get()` and `context.set()` in [`action`](../../start/framework/route-module#action)s,
340
+ * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
286
341
  */
287
342
  declare function unstable_createContext<T>(defaultValue?: T): unstable_RouterContext<T>;
288
343
  /**
289
- * A Map of RouterContext objects to their initial values - used to populate a
290
- * fresh `context` value per request/navigation/fetch
291
- */
292
- type unstable_InitialContext = Map<unstable_RouterContext, unknown>;
293
- /**
294
- * Provides methods for writing/reading values in application context in a typesafe way.
344
+ * Provides methods for writing/reading values in application context in a
345
+ * type-safe way. Primarily for usage with [middleware](../../how-to/middleware).
346
+ *
347
+ * @example
348
+ * import {
349
+ * unstable_createContext,
350
+ * unstable_RouterContextProvider
351
+ * } from "react-router";
352
+ *
353
+ * const userContext = unstable_createContext<User | null>(null);
354
+ * const contextProvider = new unstable_RouterContextProvider();
355
+ * contextProvider.set(userContext, getUser());
356
+ * const user = contextProvider.get(userContext);
357
+ * // ^ User
358
+ *
359
+ * @public
360
+ * @category Utils
361
+ * @mode framework
362
+ * @mode data
295
363
  */
296
364
  declare class unstable_RouterContextProvider {
297
365
  #private;
298
- constructor(init?: unstable_InitialContext);
366
+ /**
367
+ * Create a new `unstable_RouterContextProvider` instance
368
+ * @param init An optional initial context map to populate the provider with
369
+ */
370
+ constructor(init?: Map<unstable_RouterContext, unknown>);
371
+ /**
372
+ * Access a value from the context. If no value has been set for the context,
373
+ * it will return the context's `defaultValue` if provided, or throw an error
374
+ * if no `defaultValue` was set.
375
+ * @param context The context to get the value for
376
+ * @returns The value for the context, or the context's `defaultValue` if no
377
+ * value was set
378
+ */
299
379
  get<T>(context: unstable_RouterContext<T>): T;
380
+ /**
381
+ * Set a value for the context. If the context already has a value set, this
382
+ * will overwrite it.
383
+ *
384
+ * @param context The context to set the value for
385
+ * @param value The value to set for the context
386
+ * @returns {void}
387
+ */
300
388
  set<C extends unstable_RouterContext>(context: C, value: C extends unstable_RouterContext<infer T> ? T : never): void;
301
389
  }
302
- type DefaultContext = MiddlewareEnabled extends true ? unstable_RouterContextProvider : any;
390
+ type DefaultContext = MiddlewareEnabled extends true ? Readonly<unstable_RouterContextProvider> : any;
303
391
  /**
304
392
  * @private
305
393
  * Arguments passed to route loader/action functions. Same for now but we keep
@@ -321,7 +409,7 @@ interface DataFunctionArgs<Context> {
321
409
  * params.teamId;
322
410
  * // ^ string
323
411
  * }
324
- **/
412
+ */
325
413
  params: Params;
326
414
  /**
327
415
  * This is the context passed in to your server adapter's getLoadContext() function.
@@ -343,7 +431,7 @@ interface unstable_MiddlewareNextFunction<Result = unknown> {
343
431
  * a `next` function as the second parameter which will call downstream handlers
344
432
  * and then complete middlewares from the bottom-up
345
433
  */
346
- type unstable_MiddlewareFunction<Result = unknown> = (args: DataFunctionArgs<unstable_RouterContextProvider>, next: unstable_MiddlewareNextFunction<Result>) => MaybePromise<Result | void>;
434
+ type unstable_MiddlewareFunction<Result = unknown> = (args: DataFunctionArgs<Readonly<unstable_RouterContextProvider>>, next: unstable_MiddlewareNextFunction<Result>) => MaybePromise<Result | void>;
347
435
  /**
348
436
  * Arguments passed to loader functions
349
437
  */
@@ -449,34 +537,39 @@ interface DataStrategyMatch extends AgnosticRouteMatch<string, AgnosticDataRoute
449
537
  route: Promise<void> | undefined;
450
538
  };
451
539
  /**
452
- * A boolean value indicating whether this route handler should be called in this pass.
540
+ * A boolean value indicating whether this route handler should be called in
541
+ * this pass.
453
542
  *
454
- * The `matches` array always includes _all_ matched routes even when only _some_
455
- * route handlers need to be called so that things like middleware can be implemented.
543
+ * The `matches` array always includes _all_ matched routes even when only
544
+ * _some_ route handlers need to be called so that things like middleware can
545
+ * be implemented.
456
546
  *
457
- * `shouldLoad` is usually only interesting if you are skipping the route handler
458
- * entirely and implementing custom handler logic - since it lets you determine
459
- * if that custom logic should run for this route or not.
547
+ * `shouldLoad` is usually only interesting if you are skipping the route
548
+ * handler entirely and implementing custom handler logic - since it lets you
549
+ * determine if that custom logic should run for this route or not.
460
550
  *
461
551
  * For example:
462
552
  * - If you are on `/parent/child/a` and you navigate to `/parent/child/b` -
463
553
  * you'll get an array of three matches (`[parent, child, b]`), but only `b`
464
554
  * will have `shouldLoad=true` because the data for `parent` and `child` is
465
555
  * already loaded
466
- * - If you are on `/parent/child/a` and you submit to `a`'s `action`, then only
467
- * `a` will have `shouldLoad=true` for the action execution of `dataStrategy`
468
- * - After the `action`, `dataStrategy` will be called again for the `loader`
469
- * revalidation, and all matches will have `shouldLoad=true` (assuming no custom
470
- * `shouldRevalidate` implementations)
556
+ * - If you are on `/parent/child/a` and you submit to `a`'s [`action`](https://reactrouter.com/docs/start/data/route-object#action),
557
+ * then only `a` will have `shouldLoad=true` for the action execution of
558
+ * `dataStrategy`
559
+ * - After the [`action`](https://reactrouter.com/docs/start/data/route-object#action),
560
+ * `dataStrategy` will be called again for the [`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
561
+ * revalidation, and all matches will have `shouldLoad=true` (assuming no
562
+ * custom `shouldRevalidate` implementations)
471
563
  */
472
564
  shouldLoad: boolean;
473
565
  unstable_shouldRevalidateArgs: ShouldRevalidateFunctionArgs | null;
474
566
  unstable_shouldCallHandler(defaultShouldRevalidate?: boolean): boolean;
475
567
  /**
476
568
  * An async function that will resolve any `route.lazy` implementations and
477
- * execute the route's handler (if necessary), returning a `DataStrategyResult`
569
+ * execute the route's handler (if necessary), returning a {@link DataStrategyResult}
478
570
  *
479
- * - Calling `match.resolve` does not mean you're calling the `loader`/`action`
571
+ * - Calling `match.resolve` does not mean you're calling the
572
+ * [`action`](https://reactrouter.com/docs/start/data/route-object#action)/[`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
480
573
  * (the "handler") - `resolve` will only call the `handler` internally if
481
574
  * needed _and_ if you don't pass your own `handlerOverride` function parameter
482
575
  * - It is safe to call `match.resolve` for all matches, even if they have
@@ -643,7 +736,28 @@ interface AgnosticDataRouteMatch extends AgnosticRouteMatch<string, AgnosticData
643
736
  /**
644
737
  * Matches the given routes to a location and returns the match data.
645
738
  *
739
+ * @example
740
+ * import { matchRoutes } from "react-router";
741
+ *
742
+ * let routes = [{
743
+ * path: "/",
744
+ * Component: Root,
745
+ * children: [{
746
+ * path: "dashboard",
747
+ * Component: Dashboard,
748
+ * }]
749
+ * }];
750
+ *
751
+ * matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
752
+ *
753
+ * @public
646
754
  * @category Utils
755
+ * @param routes The array of route objects to match against.
756
+ * @param locationArg The location to match against, either a string path or a
757
+ * partial {@link Location} object
758
+ * @param basename Optional base path to strip from the location before matching.
759
+ * Defaults to `/`.
760
+ * @returns An array of matched routes, or `null` if no matches were found.
647
761
  */
648
762
  declare function matchRoutes<RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject>(routes: RouteObjectType[], locationArg: Partial<Location> | string, basename?: string): AgnosticRouteMatch<string, RouteObjectType>[] | null;
649
763
  interface UIMatch<Data = unknown, Handle = unknown> {
@@ -651,29 +765,53 @@ interface UIMatch<Data = unknown, Handle = unknown> {
651
765
  pathname: string;
652
766
  /**
653
767
  * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the matched route.
654
- **/
768
+ */
655
769
  params: AgnosticRouteMatch["params"];
656
- /** The return value from the matched route's loader or clientLoader */
657
- data: Data;
658
- /** The {@link https://reactrouter.com/start/framework/route-module#handle handle object} exported from the matched route module */
770
+ /**
771
+ * The return value from the matched route's loader or clientLoader. This might
772
+ * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
773
+ * an error and we're currently displaying an `ErrorBoundary`.
774
+ *
775
+ * @deprecated Use `UIMatch.loaderData` instead
776
+ */
777
+ data: Data | undefined;
778
+ /**
779
+ * The return value from the matched route's loader or clientLoader. This might
780
+ * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
781
+ * an error and we're currently displaying an `ErrorBoundary`.
782
+ */
783
+ loaderData: Data | undefined;
784
+ /**
785
+ * The {@link https://reactrouter.com/start/framework/route-module#handle handle object}
786
+ * exported from the matched route module
787
+ */
659
788
  handle: Handle;
660
789
  }
661
790
  /**
662
791
  * Returns a path with params interpolated.
663
792
  *
793
+ * @example
794
+ * import { generatePath } from "react-router";
795
+ *
796
+ * generatePath("/users/:id", { id: "123" }); // "/users/123"
797
+ *
798
+ * @public
664
799
  * @category Utils
800
+ * @param originalPath The original path to generate.
801
+ * @param params The parameters to interpolate into the path.
802
+ * @returns The generated path with parameters interpolated.
665
803
  */
666
804
  declare function generatePath<Path extends string>(originalPath: Path, params?: {
667
805
  [key in PathParam<Path>]: string | null;
668
806
  }): string;
669
807
  /**
670
- * A PathPattern is used to match on some portion of a URL pathname.
808
+ * Used to match on some portion of a URL pathname.
671
809
  */
672
810
  interface PathPattern<Path extends string = string> {
673
811
  /**
674
812
  * A string to match against a URL pathname. May contain `:id`-style segments
675
- * to indicate placeholders for dynamic parameters. May also end with `/*` to
676
- * indicate matching the rest of the URL pathname.
813
+ * to indicate placeholders for dynamic parameters. It May also end with `/*`
814
+ * to indicate matching the rest of the URL pathname.
677
815
  */
678
816
  path: Path;
679
817
  /**
@@ -687,7 +825,7 @@ interface PathPattern<Path extends string = string> {
687
825
  end?: boolean;
688
826
  }
689
827
  /**
690
- * A PathMatch contains info about how a PathPattern matched on a URL pathname.
828
+ * Contains info about how a {@link PathPattern} matched on a URL pathname.
691
829
  */
692
830
  interface PathMatch<ParamKey extends string = string> {
693
831
  /**
@@ -711,13 +849,26 @@ interface PathMatch<ParamKey extends string = string> {
711
849
  * Performs pattern matching on a URL pathname and returns information about
712
850
  * the match.
713
851
  *
852
+ * @public
714
853
  * @category Utils
854
+ * @param pattern The pattern to match against the URL pathname. This can be a
855
+ * string or a {@link PathPattern} object. If a string is provided, it will be
856
+ * treated as a pattern with `caseSensitive` set to `false` and `end` set to
857
+ * `true`.
858
+ * @param pathname The URL pathname to match against the pattern.
859
+ * @returns A path match object if the pattern matches the pathname,
860
+ * or `null` if it does not match.
715
861
  */
716
862
  declare function matchPath<ParamKey extends ParamParseKey<Path>, Path extends string>(pattern: PathPattern<Path> | Path, pathname: string): PathMatch<ParamKey> | null;
717
863
  /**
718
- * Returns a resolved path object relative to the given pathname.
864
+ * Returns a resolved {@link Path} object relative to the given pathname.
719
865
  *
866
+ * @public
720
867
  * @category Utils
868
+ * @param to The path to resolve, either a string or a partial {@link Path}
869
+ * object.
870
+ * @param fromPathname The pathname to resolve the path from. Defaults to `/`.
871
+ * @returns A {@link Path} object with the resolved pathname, search, and hash.
721
872
  */
722
873
  declare function resolvePath(to: To, fromPathname?: string): Path;
723
874
  declare class DataWithResponseInit<D> {
@@ -727,35 +878,116 @@ declare class DataWithResponseInit<D> {
727
878
  constructor(data: D, init?: ResponseInit);
728
879
  }
729
880
  /**
730
- * Create "responses" that contain `status`/`headers` without forcing
731
- * serialization into an actual `Response` - used by Remix single fetch
881
+ * Create "responses" that contain `headers`/`status` without forcing
882
+ * serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
732
883
  *
884
+ * @example
885
+ * import { data } from "react-router";
886
+ *
887
+ * export async function action({ request }: Route.ActionArgs) {
888
+ * let formData = await request.formData();
889
+ * let item = await createItem(formData);
890
+ * return data(item, {
891
+ * headers: { "X-Custom-Header": "value" }
892
+ * status: 201,
893
+ * });
894
+ * }
895
+ *
896
+ * @public
733
897
  * @category Utils
898
+ * @mode framework
899
+ * @mode data
900
+ * @param data The data to be included in the response.
901
+ * @param init The status code or a `ResponseInit` object to be included in the
902
+ * response.
903
+ * @returns A {@link DataWithResponseInit} instance containing the data and
904
+ * response init.
734
905
  */
735
906
  declare function data<D>(data: D, init?: number | ResponseInit): DataWithResponseInit<D>;
736
907
  type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
737
908
  /**
738
- * A redirect response. Sets the status code and the `Location` header.
739
- * Defaults to "302 Found".
909
+ * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
910
+ * Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
911
+ * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
912
+ *
913
+ * @example
914
+ * import { redirect } from "react-router";
915
+ *
916
+ * export async function loader({ request }: Route.LoaderArgs) {
917
+ * if (!isLoggedIn(request))
918
+ * throw redirect("/login");
919
+ * }
740
920
  *
921
+ * // ...
922
+ * }
923
+ *
924
+ * @public
741
925
  * @category Utils
926
+ * @mode framework
927
+ * @mode data
928
+ * @param url The URL to redirect to.
929
+ * @param init The status code or a `ResponseInit` object to be included in the
930
+ * response.
931
+ * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
932
+ * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
933
+ * header.
742
934
  */
743
935
  declare const redirect: RedirectFunction;
744
936
  /**
745
- * A redirect response that will force a document reload to the new location.
746
- * Sets the status code and the `Location` header.
747
- * Defaults to "302 Found".
937
+ * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
938
+ * that will force a document reload to the new location. Sets the status code
939
+ * and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
940
+ * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
941
+ *
942
+ * ```tsx filename=routes/logout.tsx
943
+ * import { redirectDocument } from "react-router";
944
+ *
945
+ * import { destroySession } from "../sessions.server";
748
946
  *
947
+ * export async function action({ request }: Route.ActionArgs) {
948
+ * let session = await getSession(request.headers.get("Cookie"));
949
+ * return redirectDocument("/", {
950
+ * headers: { "Set-Cookie": await destroySession(session) }
951
+ * });
952
+ * }
953
+ * ```
954
+ *
955
+ * @public
749
956
  * @category Utils
957
+ * @mode framework
958
+ * @mode data
959
+ * @param url The URL to redirect to.
960
+ * @param init The status code or a `ResponseInit` object to be included in the
961
+ * response.
962
+ * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
963
+ * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
964
+ * header.
750
965
  */
751
966
  declare const redirectDocument: RedirectFunction;
752
967
  /**
753
- * A redirect response that will perform a `history.replaceState` instead of a
754
- * `history.pushState` for client-side navigation redirects.
755
- * Sets the status code and the `Location` header.
756
- * Defaults to "302 Found".
968
+ * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
969
+ * that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
970
+ * instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
971
+ * for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
972
+ * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
757
973
  *
974
+ * @example
975
+ * import { replace } from "react-router";
976
+ *
977
+ * export async function loader() {
978
+ * return replace("/new-location");
979
+ * }
980
+ *
981
+ * @public
758
982
  * @category Utils
983
+ * @mode framework
984
+ * @mode data
985
+ * @param url The URL to redirect to.
986
+ * @param init The status code or a `ResponseInit` object to be included in the
987
+ * response.
988
+ * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
989
+ * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
990
+ * header.
759
991
  */
760
992
  declare const replace: RedirectFunction;
761
993
  type ErrorResponse = {
@@ -763,14 +995,6 @@ type ErrorResponse = {
763
995
  statusText: string;
764
996
  data: any;
765
997
  };
766
- /**
767
- * @private
768
- * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
769
- *
770
- * We don't export the class for public use since it's an implementation
771
- * detail, but we export the interface above so folks can build their own
772
- * abstractions around instances via isRouteErrorResponse()
773
- */
774
998
  declare class ErrorResponseImpl implements ErrorResponse {
775
999
  status: number;
776
1000
  statusText: string;
@@ -780,10 +1004,35 @@ declare class ErrorResponseImpl implements ErrorResponse {
780
1004
  constructor(status: number, statusText: string | undefined, data: any, internal?: boolean);
781
1005
  }
782
1006
  /**
783
- * Check if the given error is an ErrorResponse generated from a 4xx/5xx
784
- * Response thrown from an action/loader
1007
+ * Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
1008
+ * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1009
+ * thrown from an [`action`](../../start/framework/route-module#action)/[`loader`](../../start/framework/route-module#loader)
1010
+ *
1011
+ * @example
1012
+ * import { isRouteErrorResponse } from "react-router";
1013
+ *
1014
+ * export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
1015
+ * if (isRouteErrorResponse(error)) {
1016
+ * return (
1017
+ * <>
1018
+ * <p>Error: `${error.status}: ${error.statusText}`</p>
1019
+ * <p>{error.data}</p>
1020
+ * </>
1021
+ * );
1022
+ * }
1023
+ *
1024
+ * return (
1025
+ * <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
1026
+ * );
1027
+ * }
785
1028
  *
1029
+ * @public
786
1030
  * @category Utils
1031
+ * @mode framework
1032
+ * @mode data
1033
+ * @param error The error to check.
1034
+ * @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
1035
+ *
787
1036
  */
788
1037
  declare function isRouteErrorResponse(error: any): error is ErrorResponse;
789
1038
 
@@ -1061,7 +1310,7 @@ interface RouterInit {
1061
1310
  routes: AgnosticRouteObject[];
1062
1311
  history: History;
1063
1312
  basename?: string;
1064
- unstable_getContext?: () => MaybePromise<unstable_InitialContext>;
1313
+ unstable_getContext?: () => MaybePromise<unstable_RouterContextProvider>;
1065
1314
  mapRouteProperties?: MapRoutePropertiesFunction;
1066
1315
  future?: Partial<FutureConfig>;
1067
1316
  hydrationRouteProperties?: string[];
@@ -1096,14 +1345,13 @@ interface StaticHandler {
1096
1345
  skipLoaderErrorBubbling?: boolean;
1097
1346
  skipRevalidation?: boolean;
1098
1347
  dataStrategy?: DataStrategyFunction<unknown>;
1099
- unstable_respond?: (staticContext: StaticHandlerContext) => MaybePromise<Response>;
1100
- unstable_stream?: (context: unstable_RouterContextProvider, query: (r: Request) => Promise<StaticHandlerContext | Response>) => MaybePromise<Response>;
1348
+ unstable_generateMiddlewareResponse?: (query: (r: Request) => Promise<StaticHandlerContext | Response>) => MaybePromise<Response>;
1101
1349
  }): Promise<StaticHandlerContext | Response>;
1102
1350
  queryRoute(request: Request, opts?: {
1103
1351
  routeId?: string;
1104
1352
  requestContext?: unknown;
1105
1353
  dataStrategy?: DataStrategyFunction<unknown>;
1106
- unstable_respond?: (res: Response) => MaybePromise<Response>;
1354
+ unstable_generateMiddlewareResponse?: (queryRoute: (r: Request) => Promise<Response>) => MaybePromise<Response>;
1107
1355
  }): Promise<any>;
1108
1356
  }
1109
1357
  type ViewTransitionOpts = {
@@ -1552,7 +1800,13 @@ type HtmlLinkDescriptor = (HtmlLinkProps & Pick<Required<HtmlLinkProps>, "href">
1552
1800
  });
1553
1801
  interface PageLinkDescriptor extends Omit<HtmlLinkDescriptor, "href" | "rel" | "type" | "sizes" | "imageSrcSet" | "imageSizes" | "as" | "color" | "title"> {
1554
1802
  /**
1555
- * The absolute path of the page to prefetch.
1803
+ * A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
1804
+ * attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
1805
+ * element
1806
+ */
1807
+ nonce?: string | undefined;
1808
+ /**
1809
+ * The absolute path of the page to prefetch, e.g. `/absolute/path`.
1556
1810
  */
1557
1811
  page: string;
1558
1812
  }
@@ -1651,7 +1905,7 @@ type ClientDataFunctionArgs<Params> = {
1651
1905
  * from your route middlewares. You may pass in initial context values in your
1652
1906
  * `<HydratedRouter unstable_getContext>` prop
1653
1907
  */
1654
- context: unstable_RouterContextProvider;
1908
+ context: Readonly<unstable_RouterContextProvider>;
1655
1909
  };
1656
1910
  type ServerDataFunctionArgs<Params> = {
1657
1911
  /** 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. */
@@ -1683,7 +1937,7 @@ type ServerDataFunctionArgs<Params> = {
1683
1937
  * server adapter, you may provide an initial set of context values from your
1684
1938
  * `getLoadContext` function.
1685
1939
  */
1686
- context: MiddlewareEnabled extends true ? unstable_RouterContextProvider : AppLoadContext;
1940
+ context: MiddlewareEnabled extends true ? Readonly<unstable_RouterContextProvider> : AppLoadContext;
1687
1941
  };
1688
1942
  type SerializeFrom<T> = T extends (...args: infer Args) => unknown ? Args extends [
1689
1943
  ClientLoaderFunctionArgs | ClientActionFunctionArgs | ClientDataFunctionArgs<unknown>
@@ -1804,7 +2058,9 @@ interface LinksFunction {
1804
2058
  interface MetaMatch<RouteId extends string = string, Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown> {
1805
2059
  id: RouteId;
1806
2060
  pathname: DataRouteMatch["pathname"];
2061
+ /** @deprecated Use `MetaMatch.loaderData` instead */
1807
2062
  data: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
2063
+ loaderData: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
1808
2064
  handle?: RouteHandle;
1809
2065
  params: DataRouteMatch["params"];
1810
2066
  meta: MetaDescriptor[];
@@ -1814,7 +2070,9 @@ type MetaMatches<MatchLoaders extends Record<string, LoaderFunction | ClientLoad
1814
2070
  [K in keyof MatchLoaders]: MetaMatch<Exclude<K, number | symbol>, MatchLoaders[K]>;
1815
2071
  }[keyof MatchLoaders]>;
1816
2072
  interface MetaArgs<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
2073
+ /** @deprecated Use `MetaArgs.loaderData` instead */
1817
2074
  data: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
2075
+ loaderData: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
1818
2076
  params: Params;
1819
2077
  location: Location;
1820
2078
  matches: MetaMatches<MatchLoaders>;
@@ -1913,4 +2171,4 @@ type RouteComponent = ComponentType<{}>;
1913
2171
  */
1914
2172
  type RouteHandle = unknown;
1915
2173
 
1916
- export { type GetScrollRestorationKeyFunction as $, Action as A, type BlockerFunction as B, type ClientDataFunctionArgs as C, type DataStrategyFunction as D, type unstable_InitialContext as E, type Equal as F, type GetLoaderData as G, type HydrationState as H, type InitialEntry as I, type ClientActionFunction as J, type ClientLoaderFunction as K, type LinkDescriptor as L, type MetaDescriptor as M, type Normalize as N, type HeadersFunction as O, type Pretty as P, type ShouldRevalidateFunction as Q, type RouteModule$1 as R, type ServerDataFunctionArgs as S, type To as T, type UIMatch as U, type RouterInit as V, type RouterState as W, type PatchRoutesOnNavigationFunction as X, type DataRouteObject as Y, type StaticHandler as Z, type GetScrollPositionFunction as _, type Location as a, type ServerRouteModule as a$, type StaticHandlerContext as a0, type Fetcher as a1, type NavigationStates as a2, type RouterSubscriber as a3, type RouterNavigateOptions as a4, type RouterFetchOptions as a5, type RevalidationState as a6, type ActionFunctionArgs as a7, type DataStrategyFunctionArgs as a8, type DataStrategyMatch as a9, replace as aA, resolvePath as aB, type DataRouteMatch as aC, type Navigator as aD, type PatchRoutesOnNavigationFunctionArgs as aE, type RouteMatch as aF, type ClientActionFunctionArgs as aG, type ClientLoaderFunctionArgs as aH, type HeadersArgs as aI, type MetaArgs as aJ, type PageLinkDescriptor as aK, type HtmlLinkDescriptor as aL, type Future as aM, type unstable_SerializesTo as aN, createBrowserHistory as aO, invariant as aP, createRouter as aQ, ErrorResponseImpl as aR, DataRouterContext as aS, DataRouterStateContext as aT, FetchersContext as aU, LocationContext as aV, NavigationContext as aW, RouteContext as aX, ViewTransitionContext as aY, type FutureConfig as aZ, type RouteManifest as a_, type DataStrategyResult as aa, DataWithResponseInit as ab, type ErrorResponse as ac, type FormEncType as ad, type FormMethod as ae, type HTMLFormMethod as af, type LazyRouteFunction as ag, type LoaderFunctionArgs as ah, type unstable_MiddlewareFunction as ai, type PathParam as aj, type RedirectFunction as ak, type unstable_RouterContext as al, type ShouldRevalidateFunctionArgs as am, unstable_createContext as an, createPath as ao, parsePath as ap, IDLE_NAVIGATION as aq, IDLE_FETCHER as ar, IDLE_BLOCKER as as, data as at, generatePath as au, isRouteErrorResponse as av, matchPath as aw, matchRoutes as ax, redirect as ay, redirectDocument as az, type ServerDataFrom as b, type History as b0, type CreateStaticHandlerOptions as b1, type GetActionData as c, type Router as d, type RouteModules as e, type NavigateOptions as f, type Blocker as g, type SerializeFrom as h, type RelativeRoutingType as i, type ParamParseKey as j, type Path as k, type PathPattern as l, type PathMatch as m, type Navigation as n, type Params as o, type RouteObject as p, type IndexRouteObject as q, type LoaderFunction as r, type ActionFunction as s, type MetaFunction as t, type unstable_MiddlewareNextFunction as u, type LinksFunction as v, type NonIndexRouteObject as w, type AppLoadContext as x, unstable_RouterContextProvider as y, type MiddlewareEnabled as z };
2174
+ export { type StaticHandlerContext as $, Action as A, type BlockerFunction as B, type ClientDataFunctionArgs as C, type DataStrategyFunction as D, type Equal as E, type ClientActionFunction as F, type GetLoaderData as G, type HydrationState as H, type InitialEntry as I, type ClientLoaderFunction as J, type HeadersFunction as K, type LinkDescriptor as L, type MetaDescriptor as M, type Normalize as N, type ShouldRevalidateFunction as O, type Pretty as P, type RouterInit as Q, type RouteModule$1 as R, type ServerDataFunctionArgs as S, type To as T, type UIMatch as U, type RouterState as V, type PatchRoutesOnNavigationFunction as W, type DataRouteObject as X, type StaticHandler as Y, type GetScrollPositionFunction as Z, type GetScrollRestorationKeyFunction as _, type Location as a, type History as a$, type Fetcher as a0, type NavigationStates as a1, type RouterSubscriber as a2, type RouterNavigateOptions as a3, type RouterFetchOptions as a4, type RevalidationState as a5, type ActionFunctionArgs as a6, type DataStrategyFunctionArgs as a7, type DataStrategyMatch as a8, type DataStrategyResult as a9, resolvePath as aA, type DataRouteMatch as aB, type Navigator as aC, type PatchRoutesOnNavigationFunctionArgs as aD, type RouteMatch as aE, type ClientActionFunctionArgs as aF, type ClientLoaderFunctionArgs as aG, type HeadersArgs as aH, type MetaArgs as aI, type PageLinkDescriptor as aJ, type HtmlLinkDescriptor as aK, type Future as aL, type unstable_SerializesTo as aM, createBrowserHistory as aN, invariant as aO, createRouter as aP, ErrorResponseImpl as aQ, DataRouterContext as aR, DataRouterStateContext as aS, FetchersContext as aT, LocationContext as aU, NavigationContext as aV, RouteContext as aW, ViewTransitionContext as aX, type FutureConfig as aY, type RouteManifest as aZ, type ServerRouteModule as a_, DataWithResponseInit as aa, type ErrorResponse as ab, type FormEncType as ac, type FormMethod as ad, type HTMLFormMethod as ae, type LazyRouteFunction as af, type LoaderFunctionArgs as ag, type unstable_MiddlewareFunction as ah, type PathParam as ai, type RedirectFunction as aj, type unstable_RouterContext as ak, type ShouldRevalidateFunctionArgs as al, unstable_createContext as am, createPath as an, parsePath as ao, IDLE_NAVIGATION as ap, IDLE_FETCHER as aq, IDLE_BLOCKER as ar, data as as, generatePath as at, isRouteErrorResponse as au, matchPath as av, matchRoutes as aw, redirect as ax, redirectDocument as ay, replace as az, type ServerDataFrom as b, type CreateStaticHandlerOptions as b0, type GetActionData as c, type Router as d, type RouteModules as e, type NavigateOptions as f, type Blocker as g, type SerializeFrom as h, type RelativeRoutingType as i, type ParamParseKey as j, type Path as k, type PathPattern as l, type PathMatch as m, type Navigation as n, type Params as o, type RouteObject as p, type IndexRouteObject as q, type LoaderFunction as r, type ActionFunction as s, type MetaFunction as t, type unstable_MiddlewareNextFunction as u, type LinksFunction as v, type NonIndexRouteObject as w, type AppLoadContext as x, unstable_RouterContextProvider as y, type MiddlewareEnabled as z };
@@ -0,0 +1,46 @@
1
+ declare global {
2
+ interface Window {
3
+ __FLIGHT_DATA: any[];
4
+ }
5
+ }
6
+ /**
7
+ * Get the prerendered [RSC](https://react.dev/reference/rsc/server-components)
8
+ * stream for hydration. Usually passed directly to your
9
+ * `react-server-dom-xyz/client`'s `createFromReadableStream`.
10
+ *
11
+ * @example
12
+ * import { startTransition, StrictMode } from "react";
13
+ * import { hydrateRoot } from "react-dom/client";
14
+ * import {
15
+ * unstable_getRSCStream as getRSCStream,
16
+ * unstable_RSCHydratedRouter as RSCHydratedRouter,
17
+ * } from "react-router";
18
+ * import type { unstable_RSCPayload as RSCPayload } from "react-router";
19
+ *
20
+ * createFromReadableStream(getRSCStream()).then(
21
+ * (payload: RSCServerPayload) => {
22
+ * startTransition(async () => {
23
+ * hydrateRoot(
24
+ * document,
25
+ * <StrictMode>
26
+ * <RSCHydratedRouter {...props} />
27
+ * </StrictMode>,
28
+ * {
29
+ * // Options
30
+ * }
31
+ * );
32
+ * });
33
+ * }
34
+ * );
35
+ *
36
+ * @name unstable_getRSCStream
37
+ * @public
38
+ * @category RSC
39
+ * @mode data
40
+ * @returns A [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)
41
+ * that contains the [RSC](https://react.dev/reference/rsc/server-components)
42
+ * data for hydration.
43
+ */
44
+ declare function getRSCStream(): ReadableStream;
45
+
46
+ export { getRSCStream as g };