react-router 7.7.1 → 7.8.0-pre.1

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 +87 -5
  2. package/dist/development/browser-z32v5KVN.d.mts +46 -0
  3. package/dist/development/{chunk-R73PQUJU.js → chunk-4EVDZJGM.js} +130 -130
  4. package/dist/{production/chunk-K3SBCRK4.mjs → development/chunk-I22FVTOY.mjs} +177 -134
  5. package/dist/development/{chunk-K7YFBME3.js → chunk-NGF2R4G7.js} +285 -189
  6. package/dist/development/{chunk-C37GKA54.mjs → chunk-XFFANEXU.mjs} +266 -170
  7. package/dist/development/{components-CjQijYga.d.mts → components-CuPfnyiZ.d.mts} +33 -21
  8. package/dist/{production/route-data-CqEmXQub.d.mts → development/context-DohQKLID.d.mts} +312 -525
  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/development/{index-react-server-client-Bi_fx8qz.d.ts → index-react-server-client-BzBbJLAD.d.ts} +357 -219
  14. package/dist/{production/index-react-server-client-KLg-U4nr.d.mts → development/index-react-server-client-CuajY2vy.d.mts} +327 -200
  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 -71
  20. package/dist/development/index-react-server.d.ts +291 -71
  21. package/dist/development/index-react-server.js +209 -182
  22. package/dist/development/index-react-server.mjs +209 -182
  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-CpB5xtMm.d.mts +473 -0
  32. package/dist/{production/routeModules-BR2FO0ix.d.ts → development/routeModules-qBivMBjd.d.ts} +325 -68
  33. package/dist/production/browser-z32v5KVN.d.mts +46 -0
  34. package/dist/production/{chunk-4DGLNKXF.js → chunk-4PESVXQ2.js} +130 -130
  35. package/dist/{development/chunk-KIUJAIYX.mjs → production/chunk-JJOMWYJ4.mjs} +177 -134
  36. package/dist/production/{chunk-IZ57JD2V.mjs → chunk-P2ZJHOXZ.mjs} +266 -170
  37. package/dist/production/{chunk-7OQROU2D.js → chunk-RLJ23MYZ.js} +285 -189
  38. package/dist/production/{components-CjQijYga.d.mts → components-CuPfnyiZ.d.mts} +33 -21
  39. package/dist/{development/route-data-CqEmXQub.d.mts → production/context-DohQKLID.d.mts} +312 -525
  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/production/{index-react-server-client-Bi_fx8qz.d.ts → index-react-server-client-BzBbJLAD.d.ts} +357 -219
  45. package/dist/{development/index-react-server-client-KLg-U4nr.d.mts → production/index-react-server-client-CuajY2vy.d.mts} +327 -200
  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 -71
  51. package/dist/production/index-react-server.d.ts +291 -71
  52. package/dist/production/index-react-server.js +209 -182
  53. package/dist/production/index-react-server.mjs +209 -182
  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-CpB5xtMm.d.mts +473 -0
  63. package/dist/{development/routeModules-BR2FO0ix.d.ts → production/routeModules-qBivMBjd.d.ts} +325 -68
  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,122 @@ 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
+ * If a `defaultValue` is provided, it will be returned from `context.get()`
290
+ * when no value has been set for the context. Otherwise, reading this context
291
+ * when no value has been set will throw an error.
292
+ *
293
+ * ```tsx filename=app/context.ts
294
+ * import { unstable_createContext } from "react-router";
295
+ *
296
+ * // Create a context for user data
297
+ * export const userContext =
298
+ * unstable_createContext<User | null>(null);
299
+ * ```
300
+ *
301
+ * ```tsx filename=app/middleware/auth.ts
302
+ * import { getUserFromSession } from "~/auth.server";
303
+ * import { userContext } from "~/context";
304
+ *
305
+ * export const authMiddleware = async ({
306
+ * context,
307
+ * request,
308
+ * }) => {
309
+ * const user = await getUserFromSession(request);
310
+ * context.set(userContext, user);
311
+ * };
312
+ * ```
279
313
  *
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.
314
+ * ```tsx filename=app/routes/profile.tsx
315
+ * import { userContext } from "~/context";
283
316
  *
284
- * @param defaultValue The default value for the context
285
- * @returns A context object
317
+ * export async function loader({
318
+ * context,
319
+ * }: Route.LoaderArgs) {
320
+ * const user = context.get(userContext);
321
+ *
322
+ * if (!user) {
323
+ * throw new Response("Unauthorized", { status: 401 });
324
+ * }
325
+ *
326
+ * return { user };
327
+ * }
328
+ * ```
329
+ *
330
+ * @public
331
+ * @category Utils
332
+ * @mode framework
333
+ * @mode data
334
+ * @param defaultValue An optional default value for the context. This value
335
+ * will be returned if no value has been set for this context.
336
+ * @returns A {@link unstable_RouterContext} object that can be used with
337
+ * `context.get()` and `context.set()` in [`action`](../../start/framework/route-module#action)s,
338
+ * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
286
339
  */
287
340
  declare function unstable_createContext<T>(defaultValue?: T): unstable_RouterContext<T>;
288
341
  /**
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.
342
+ * Provides methods for writing/reading values in application context in a
343
+ * type-safe way. Primarily for usage with [middleware](../../how-to/middleware).
344
+ *
345
+ * @example
346
+ * import {
347
+ * unstable_createContext,
348
+ * unstable_RouterContextProvider
349
+ * } from "react-router";
350
+ *
351
+ * const userContext = unstable_createContext<User | null>(null);
352
+ * const contextProvider = new unstable_RouterContextProvider();
353
+ * contextProvider.set(userContext, getUser());
354
+ * // ^ Type-safe
355
+ * const user = contextProvider.get(userContext);
356
+ * // ^ User
357
+ *
358
+ * @public
359
+ * @category Utils
360
+ * @mode framework
361
+ * @mode data
295
362
  */
296
363
  declare class unstable_RouterContextProvider {
297
364
  #private;
298
- constructor(init?: unstable_InitialContext);
365
+ /**
366
+ * Create a new `unstable_RouterContextProvider` instance
367
+ * @param init An optional initial context map to populate the provider with
368
+ */
369
+ constructor(init?: Map<unstable_RouterContext, unknown>);
370
+ /**
371
+ * Access a value from the context. If no value has been set for the context,
372
+ * it will return the context's `defaultValue` if provided, or throw an error
373
+ * if no `defaultValue` was set.
374
+ * @param context The context to get the value for
375
+ * @returns The value for the context, or the context's `defaultValue` if no
376
+ * value was set
377
+ */
299
378
  get<T>(context: unstable_RouterContext<T>): T;
379
+ /**
380
+ * Set a value for the context. If the context already has a value set, this
381
+ * will overwrite it.
382
+ *
383
+ * @param context The context to set the value for
384
+ * @param value The value to set for the context
385
+ * @returns {void}
386
+ */
300
387
  set<C extends unstable_RouterContext>(context: C, value: C extends unstable_RouterContext<infer T> ? T : never): void;
301
388
  }
302
- type DefaultContext = MiddlewareEnabled extends true ? unstable_RouterContextProvider : any;
389
+ type DefaultContext = MiddlewareEnabled extends true ? Readonly<unstable_RouterContextProvider> : any;
303
390
  /**
304
391
  * @private
305
392
  * Arguments passed to route loader/action functions. Same for now but we keep
@@ -321,7 +408,7 @@ interface DataFunctionArgs<Context> {
321
408
  * params.teamId;
322
409
  * // ^ string
323
410
  * }
324
- **/
411
+ */
325
412
  params: Params;
326
413
  /**
327
414
  * This is the context passed in to your server adapter's getLoadContext() function.
@@ -335,7 +422,7 @@ interface DataFunctionArgs<Context> {
335
422
  * middlewares from the bottom-up
336
423
  */
337
424
  interface unstable_MiddlewareNextFunction<Result = unknown> {
338
- (): MaybePromise<Result>;
425
+ (): Promise<Result>;
339
426
  }
340
427
  /**
341
428
  * Route middleware function signature. Receives the same "data" arguments as a
@@ -343,7 +430,7 @@ interface unstable_MiddlewareNextFunction<Result = unknown> {
343
430
  * a `next` function as the second parameter which will call downstream handlers
344
431
  * and then complete middlewares from the bottom-up
345
432
  */
346
- type unstable_MiddlewareFunction<Result = unknown> = (args: DataFunctionArgs<unstable_RouterContextProvider>, next: unstable_MiddlewareNextFunction<Result>) => MaybePromise<Result | void>;
433
+ type unstable_MiddlewareFunction<Result = unknown> = (args: DataFunctionArgs<Readonly<unstable_RouterContextProvider>>, next: unstable_MiddlewareNextFunction<Result>) => MaybePromise<Result | void>;
347
434
  /**
348
435
  * Arguments passed to loader functions
349
436
  */
@@ -449,34 +536,39 @@ interface DataStrategyMatch extends AgnosticRouteMatch<string, AgnosticDataRoute
449
536
  route: Promise<void> | undefined;
450
537
  };
451
538
  /**
452
- * A boolean value indicating whether this route handler should be called in this pass.
539
+ * A boolean value indicating whether this route handler should be called in
540
+ * this pass.
453
541
  *
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.
542
+ * The `matches` array always includes _all_ matched routes even when only
543
+ * _some_ route handlers need to be called so that things like middleware can
544
+ * be implemented.
456
545
  *
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.
546
+ * `shouldLoad` is usually only interesting if you are skipping the route
547
+ * handler entirely and implementing custom handler logic - since it lets you
548
+ * determine if that custom logic should run for this route or not.
460
549
  *
461
550
  * For example:
462
551
  * - If you are on `/parent/child/a` and you navigate to `/parent/child/b` -
463
552
  * you'll get an array of three matches (`[parent, child, b]`), but only `b`
464
553
  * will have `shouldLoad=true` because the data for `parent` and `child` is
465
554
  * 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)
555
+ * - If you are on `/parent/child/a` and you submit to `a`'s [`action`](https://reactrouter.com/docs/start/data/route-object#action),
556
+ * then only `a` will have `shouldLoad=true` for the action execution of
557
+ * `dataStrategy`
558
+ * - After the [`action`](https://reactrouter.com/docs/start/data/route-object#action),
559
+ * `dataStrategy` will be called again for the [`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
560
+ * revalidation, and all matches will have `shouldLoad=true` (assuming no
561
+ * custom `shouldRevalidate` implementations)
471
562
  */
472
563
  shouldLoad: boolean;
473
564
  unstable_shouldRevalidateArgs: ShouldRevalidateFunctionArgs | null;
474
565
  unstable_shouldCallHandler(defaultShouldRevalidate?: boolean): boolean;
475
566
  /**
476
567
  * An async function that will resolve any `route.lazy` implementations and
477
- * execute the route's handler (if necessary), returning a `DataStrategyResult`
568
+ * execute the route's handler (if necessary), returning a {@link DataStrategyResult}
478
569
  *
479
- * - Calling `match.resolve` does not mean you're calling the `loader`/`action`
570
+ * - Calling `match.resolve` does not mean you're calling the
571
+ * [`action`](https://reactrouter.com/docs/start/data/route-object#action)/[`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
480
572
  * (the "handler") - `resolve` will only call the `handler` internally if
481
573
  * needed _and_ if you don't pass your own `handlerOverride` function parameter
482
574
  * - It is safe to call `match.resolve` for all matches, even if they have
@@ -643,7 +735,28 @@ interface AgnosticDataRouteMatch extends AgnosticRouteMatch<string, AgnosticData
643
735
  /**
644
736
  * Matches the given routes to a location and returns the match data.
645
737
  *
738
+ * @example
739
+ * import { matchRoutes } from "react-router";
740
+ *
741
+ * let routes = [{
742
+ * path: "/",
743
+ * Component: Root,
744
+ * children: [{
745
+ * path: "dashboard",
746
+ * Component: Dashboard,
747
+ * }]
748
+ * }];
749
+ *
750
+ * matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
751
+ *
752
+ * @public
646
753
  * @category Utils
754
+ * @param routes The array of route objects to match against.
755
+ * @param locationArg The location to match against, either a string path or a
756
+ * partial {@link Location} object
757
+ * @param basename Optional base path to strip from the location before matching.
758
+ * Defaults to `/`.
759
+ * @returns An array of matched routes, or `null` if no matches were found.
647
760
  */
648
761
  declare function matchRoutes<RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject>(routes: RouteObjectType[], locationArg: Partial<Location> | string, basename?: string): AgnosticRouteMatch<string, RouteObjectType>[] | null;
649
762
  interface UIMatch<Data = unknown, Handle = unknown> {
@@ -651,29 +764,53 @@ interface UIMatch<Data = unknown, Handle = unknown> {
651
764
  pathname: string;
652
765
  /**
653
766
  * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the matched route.
654
- **/
767
+ */
655
768
  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 */
769
+ /**
770
+ * The return value from the matched route's loader or clientLoader. This might
771
+ * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
772
+ * an error and we're currently displaying an `ErrorBoundary`.
773
+ *
774
+ * @deprecated Use `UIMatch.loaderData` instead
775
+ */
776
+ data: Data | undefined;
777
+ /**
778
+ * The return value from the matched route's loader or clientLoader. This might
779
+ * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
780
+ * an error and we're currently displaying an `ErrorBoundary`.
781
+ */
782
+ loaderData: Data | undefined;
783
+ /**
784
+ * The {@link https://reactrouter.com/start/framework/route-module#handle handle object}
785
+ * exported from the matched route module
786
+ */
659
787
  handle: Handle;
660
788
  }
661
789
  /**
662
790
  * Returns a path with params interpolated.
663
791
  *
792
+ * @example
793
+ * import { generatePath } from "react-router";
794
+ *
795
+ * generatePath("/users/:id", { id: "123" }); // "/users/123"
796
+ *
797
+ * @public
664
798
  * @category Utils
799
+ * @param originalPath The original path to generate.
800
+ * @param params The parameters to interpolate into the path.
801
+ * @returns The generated path with parameters interpolated.
665
802
  */
666
803
  declare function generatePath<Path extends string>(originalPath: Path, params?: {
667
804
  [key in PathParam<Path>]: string | null;
668
805
  }): string;
669
806
  /**
670
- * A PathPattern is used to match on some portion of a URL pathname.
807
+ * Used to match on some portion of a URL pathname.
671
808
  */
672
809
  interface PathPattern<Path extends string = string> {
673
810
  /**
674
811
  * 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.
812
+ * to indicate placeholders for dynamic parameters. It May also end with `/*`
813
+ * to indicate matching the rest of the URL pathname.
677
814
  */
678
815
  path: Path;
679
816
  /**
@@ -687,7 +824,7 @@ interface PathPattern<Path extends string = string> {
687
824
  end?: boolean;
688
825
  }
689
826
  /**
690
- * A PathMatch contains info about how a PathPattern matched on a URL pathname.
827
+ * Contains info about how a {@link PathPattern} matched on a URL pathname.
691
828
  */
692
829
  interface PathMatch<ParamKey extends string = string> {
693
830
  /**
@@ -711,13 +848,26 @@ interface PathMatch<ParamKey extends string = string> {
711
848
  * Performs pattern matching on a URL pathname and returns information about
712
849
  * the match.
713
850
  *
851
+ * @public
714
852
  * @category Utils
853
+ * @param pattern The pattern to match against the URL pathname. This can be a
854
+ * string or a {@link PathPattern} object. If a string is provided, it will be
855
+ * treated as a pattern with `caseSensitive` set to `false` and `end` set to
856
+ * `true`.
857
+ * @param pathname The URL pathname to match against the pattern.
858
+ * @returns A path match object if the pattern matches the pathname,
859
+ * or `null` if it does not match.
715
860
  */
716
861
  declare function matchPath<ParamKey extends ParamParseKey<Path>, Path extends string>(pattern: PathPattern<Path> | Path, pathname: string): PathMatch<ParamKey> | null;
717
862
  /**
718
- * Returns a resolved path object relative to the given pathname.
863
+ * Returns a resolved {@link Path} object relative to the given pathname.
719
864
  *
865
+ * @public
720
866
  * @category Utils
867
+ * @param to The path to resolve, either a string or a partial {@link Path}
868
+ * object.
869
+ * @param fromPathname The pathname to resolve the path from. Defaults to `/`.
870
+ * @returns A {@link Path} object with the resolved pathname, search, and hash.
721
871
  */
722
872
  declare function resolvePath(to: To, fromPathname?: string): Path;
723
873
  declare class DataWithResponseInit<D> {
@@ -727,35 +877,116 @@ declare class DataWithResponseInit<D> {
727
877
  constructor(data: D, init?: ResponseInit);
728
878
  }
729
879
  /**
730
- * Create "responses" that contain `status`/`headers` without forcing
731
- * serialization into an actual `Response` - used by Remix single fetch
880
+ * Create "responses" that contain `headers`/`status` without forcing
881
+ * serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
732
882
  *
883
+ * @example
884
+ * import { data } from "react-router";
885
+ *
886
+ * export async function action({ request }: Route.ActionArgs) {
887
+ * let formData = await request.formData();
888
+ * let item = await createItem(formData);
889
+ * return data(item, {
890
+ * headers: { "X-Custom-Header": "value" }
891
+ * status: 201,
892
+ * });
893
+ * }
894
+ *
895
+ * @public
733
896
  * @category Utils
897
+ * @mode framework
898
+ * @mode data
899
+ * @param data The data to be included in the response.
900
+ * @param init The status code or a `ResponseInit` object to be included in the
901
+ * response.
902
+ * @returns A {@link DataWithResponseInit} instance containing the data and
903
+ * response init.
734
904
  */
735
905
  declare function data<D>(data: D, init?: number | ResponseInit): DataWithResponseInit<D>;
736
906
  type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
737
907
  /**
738
- * A redirect response. Sets the status code and the `Location` header.
739
- * Defaults to "302 Found".
908
+ * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
909
+ * Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
910
+ * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
911
+ *
912
+ * @example
913
+ * import { redirect } from "react-router";
914
+ *
915
+ * export async function loader({ request }: Route.LoaderArgs) {
916
+ * if (!isLoggedIn(request))
917
+ * throw redirect("/login");
918
+ * }
740
919
  *
920
+ * // ...
921
+ * }
922
+ *
923
+ * @public
741
924
  * @category Utils
925
+ * @mode framework
926
+ * @mode data
927
+ * @param url The URL to redirect to.
928
+ * @param init The status code or a `ResponseInit` object to be included in the
929
+ * response.
930
+ * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
931
+ * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
932
+ * header.
742
933
  */
743
934
  declare const redirect: RedirectFunction;
744
935
  /**
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".
936
+ * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
937
+ * that will force a document reload to the new location. Sets the status code
938
+ * and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
939
+ * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
940
+ *
941
+ * ```tsx filename=routes/logout.tsx
942
+ * import { redirectDocument } from "react-router";
943
+ *
944
+ * import { destroySession } from "../sessions.server";
748
945
  *
946
+ * export async function action({ request }: Route.ActionArgs) {
947
+ * let session = await getSession(request.headers.get("Cookie"));
948
+ * return redirectDocument("/", {
949
+ * headers: { "Set-Cookie": await destroySession(session) }
950
+ * });
951
+ * }
952
+ * ```
953
+ *
954
+ * @public
749
955
  * @category Utils
956
+ * @mode framework
957
+ * @mode data
958
+ * @param url The URL to redirect to.
959
+ * @param init The status code or a `ResponseInit` object to be included in the
960
+ * response.
961
+ * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
962
+ * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
963
+ * header.
750
964
  */
751
965
  declare const redirectDocument: RedirectFunction;
752
966
  /**
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".
967
+ * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
968
+ * that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
969
+ * instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
970
+ * for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
971
+ * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
757
972
  *
973
+ * @example
974
+ * import { replace } from "react-router";
975
+ *
976
+ * export async function loader() {
977
+ * return replace("/new-location");
978
+ * }
979
+ *
980
+ * @public
758
981
  * @category Utils
982
+ * @mode framework
983
+ * @mode data
984
+ * @param url The URL to redirect to.
985
+ * @param init The status code or a `ResponseInit` object to be included in the
986
+ * response.
987
+ * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
988
+ * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
989
+ * header.
759
990
  */
760
991
  declare const replace: RedirectFunction;
761
992
  type ErrorResponse = {
@@ -763,14 +994,6 @@ type ErrorResponse = {
763
994
  statusText: string;
764
995
  data: any;
765
996
  };
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
997
  declare class ErrorResponseImpl implements ErrorResponse {
775
998
  status: number;
776
999
  statusText: string;
@@ -780,10 +1003,35 @@ declare class ErrorResponseImpl implements ErrorResponse {
780
1003
  constructor(status: number, statusText: string | undefined, data: any, internal?: boolean);
781
1004
  }
782
1005
  /**
783
- * Check if the given error is an ErrorResponse generated from a 4xx/5xx
784
- * Response thrown from an action/loader
1006
+ * Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
1007
+ * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1008
+ * thrown from an [`action`](../../start/framework/route-module#action)/[`loader`](../../start/framework/route-module#loader)
1009
+ *
1010
+ * @example
1011
+ * import { isRouteErrorResponse } from "react-router";
1012
+ *
1013
+ * export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
1014
+ * if (isRouteErrorResponse(error)) {
1015
+ * return (
1016
+ * <>
1017
+ * <p>Error: `${error.status}: ${error.statusText}`</p>
1018
+ * <p>{error.data}</p>
1019
+ * </>
1020
+ * );
1021
+ * }
1022
+ *
1023
+ * return (
1024
+ * <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
1025
+ * );
1026
+ * }
785
1027
  *
1028
+ * @public
786
1029
  * @category Utils
1030
+ * @mode framework
1031
+ * @mode data
1032
+ * @param error The error to check.
1033
+ * @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
1034
+ *
787
1035
  */
788
1036
  declare function isRouteErrorResponse(error: any): error is ErrorResponse;
789
1037
 
@@ -1061,7 +1309,7 @@ interface RouterInit {
1061
1309
  routes: AgnosticRouteObject[];
1062
1310
  history: History;
1063
1311
  basename?: string;
1064
- unstable_getContext?: () => MaybePromise<unstable_InitialContext>;
1312
+ unstable_getContext?: () => MaybePromise<unstable_RouterContextProvider>;
1065
1313
  mapRouteProperties?: MapRoutePropertiesFunction;
1066
1314
  future?: Partial<FutureConfig>;
1067
1315
  hydrationRouteProperties?: string[];
@@ -1096,14 +1344,13 @@ interface StaticHandler {
1096
1344
  skipLoaderErrorBubbling?: boolean;
1097
1345
  skipRevalidation?: boolean;
1098
1346
  dataStrategy?: DataStrategyFunction<unknown>;
1099
- unstable_respond?: (staticContext: StaticHandlerContext) => MaybePromise<Response>;
1100
- unstable_stream?: (context: unstable_RouterContextProvider, query: (r: Request) => Promise<StaticHandlerContext | Response>) => MaybePromise<Response>;
1347
+ unstable_generateMiddlewareResponse?: (query: (r: Request) => Promise<StaticHandlerContext | Response>) => MaybePromise<Response>;
1101
1348
  }): Promise<StaticHandlerContext | Response>;
1102
1349
  queryRoute(request: Request, opts?: {
1103
1350
  routeId?: string;
1104
1351
  requestContext?: unknown;
1105
1352
  dataStrategy?: DataStrategyFunction<unknown>;
1106
- unstable_respond?: (res: Response) => MaybePromise<Response>;
1353
+ unstable_generateMiddlewareResponse?: (queryRoute: (r: Request) => Promise<Response>) => MaybePromise<Response>;
1107
1354
  }): Promise<any>;
1108
1355
  }
1109
1356
  type ViewTransitionOpts = {
@@ -1552,7 +1799,13 @@ type HtmlLinkDescriptor = (HtmlLinkProps & Pick<Required<HtmlLinkProps>, "href">
1552
1799
  });
1553
1800
  interface PageLinkDescriptor extends Omit<HtmlLinkDescriptor, "href" | "rel" | "type" | "sizes" | "imageSrcSet" | "imageSizes" | "as" | "color" | "title"> {
1554
1801
  /**
1555
- * The absolute path of the page to prefetch.
1802
+ * A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
1803
+ * attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
1804
+ * element
1805
+ */
1806
+ nonce?: string | undefined;
1807
+ /**
1808
+ * The absolute path of the page to prefetch, e.g. `/absolute/path`.
1556
1809
  */
1557
1810
  page: string;
1558
1811
  }
@@ -1651,7 +1904,7 @@ type ClientDataFunctionArgs<Params> = {
1651
1904
  * from your route middlewares. You may pass in initial context values in your
1652
1905
  * `<HydratedRouter unstable_getContext>` prop
1653
1906
  */
1654
- context: unstable_RouterContextProvider;
1907
+ context: Readonly<unstable_RouterContextProvider>;
1655
1908
  };
1656
1909
  type ServerDataFunctionArgs<Params> = {
1657
1910
  /** 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 +1936,7 @@ type ServerDataFunctionArgs<Params> = {
1683
1936
  * server adapter, you may provide an initial set of context values from your
1684
1937
  * `getLoadContext` function.
1685
1938
  */
1686
- context: MiddlewareEnabled extends true ? unstable_RouterContextProvider : AppLoadContext;
1939
+ context: MiddlewareEnabled extends true ? Readonly<unstable_RouterContextProvider> : AppLoadContext;
1687
1940
  };
1688
1941
  type SerializeFrom<T> = T extends (...args: infer Args) => unknown ? Args extends [
1689
1942
  ClientLoaderFunctionArgs | ClientActionFunctionArgs | ClientDataFunctionArgs<unknown>
@@ -1804,7 +2057,9 @@ interface LinksFunction {
1804
2057
  interface MetaMatch<RouteId extends string = string, Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown> {
1805
2058
  id: RouteId;
1806
2059
  pathname: DataRouteMatch["pathname"];
2060
+ /** @deprecated Use `MetaMatch.loaderData` instead */
1807
2061
  data: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
2062
+ loaderData: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
1808
2063
  handle?: RouteHandle;
1809
2064
  params: DataRouteMatch["params"];
1810
2065
  meta: MetaDescriptor[];
@@ -1814,7 +2069,9 @@ type MetaMatches<MatchLoaders extends Record<string, LoaderFunction | ClientLoad
1814
2069
  [K in keyof MatchLoaders]: MetaMatch<Exclude<K, number | symbol>, MatchLoaders[K]>;
1815
2070
  }[keyof MatchLoaders]>;
1816
2071
  interface MetaArgs<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
2072
+ /** @deprecated Use `MetaArgs.loaderData` instead */
1817
2073
  data: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
2074
+ loaderData: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
1818
2075
  params: Params;
1819
2076
  location: Location;
1820
2077
  matches: MetaMatches<MatchLoaders>;
@@ -1913,4 +2170,4 @@ type RouteComponent = ComponentType<{}>;
1913
2170
  */
1914
2171
  type RouteHandle = unknown;
1915
2172
 
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 };
2173
+ 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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-router",
3
- "version": "7.7.1",
3
+ "version": "7.8.0-pre.1",
4
4
  "description": "Declarative routing for React",
5
5
  "keywords": [
6
6
  "react",