react-router 6.27.0 → 7.0.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.
- package/CHANGELOG.md +309 -11
- package/README.md +1 -14
- package/dist/dom-export.d.ts +3 -0
- package/dist/dom-export.mjs +205 -0
- package/dist/dom-export.mjs.map +1 -0
- package/dist/index.d.ts +74 -29
- package/dist/index.mjs +11543 -0
- package/dist/index.mjs.map +1 -0
- package/dist/lib/components.d.ts +250 -35
- package/dist/lib/context.d.ts +18 -5
- package/dist/lib/dom/dom.d.ts +123 -0
- package/dist/lib/dom/global.d.ts +40 -0
- package/dist/lib/dom/lib.d.ts +940 -0
- package/dist/lib/dom/server.d.ts +41 -0
- package/dist/lib/dom/ssr/components.d.ts +123 -0
- package/dist/lib/dom/ssr/data.d.ts +7 -0
- package/dist/lib/dom/ssr/entry.d.ts +47 -0
- package/dist/lib/dom/ssr/errorBoundaries.d.ts +36 -0
- package/dist/lib/dom/ssr/errors.d.ts +2 -0
- package/dist/lib/dom/ssr/fallback.d.ts +2 -0
- package/dist/lib/dom/ssr/fog-of-war.d.ts +28 -0
- package/dist/lib/dom/ssr/invariant.d.ts +2 -0
- package/dist/lib/dom/ssr/links.d.ts +25 -0
- package/dist/lib/dom/ssr/markup.d.ts +5 -0
- package/dist/lib/dom/ssr/routeModules.d.ts +141 -0
- package/dist/lib/dom/ssr/routes-test-stub.d.ts +59 -0
- package/dist/lib/dom/ssr/routes.d.ts +32 -0
- package/dist/lib/dom/ssr/server.d.ts +16 -0
- package/dist/lib/dom/ssr/single-fetch.d.ts +37 -0
- package/dist/lib/dom-export/dom-router-provider.d.ts +5 -0
- package/dist/lib/dom-export/hydrated-router.d.ts +5 -0
- package/dist/lib/dom-export.d.ts +3 -0
- package/dist/lib/hooks.d.ts +286 -57
- package/dist/lib/router/history.d.ts +253 -0
- package/dist/lib/router/links.d.ts +104 -0
- package/dist/lib/router/router.d.ts +540 -0
- package/dist/lib/router/utils.d.ts +505 -0
- package/dist/lib/server-runtime/build.d.ts +38 -0
- package/dist/lib/server-runtime/cookies.d.ts +62 -0
- package/dist/lib/server-runtime/crypto.d.ts +2 -0
- package/dist/lib/server-runtime/data.d.ts +15 -0
- package/dist/lib/server-runtime/dev.d.ts +8 -0
- package/dist/lib/server-runtime/entry.d.ts +3 -0
- package/dist/lib/server-runtime/errors.d.ts +51 -0
- package/dist/lib/server-runtime/headers.d.ts +3 -0
- package/dist/lib/server-runtime/invariant.d.ts +2 -0
- package/dist/lib/server-runtime/jsonify.d.ts +33 -0
- package/dist/lib/server-runtime/markup.d.ts +1 -0
- package/dist/lib/server-runtime/mode.d.ts +9 -0
- package/dist/lib/server-runtime/responses.d.ts +37 -0
- package/dist/lib/server-runtime/routeMatching.d.ts +8 -0
- package/dist/lib/server-runtime/routeModules.d.ts +212 -0
- package/dist/lib/server-runtime/routes.d.ts +31 -0
- package/dist/lib/server-runtime/server.d.ts +5 -0
- package/dist/lib/server-runtime/serverHandoff.d.ts +11 -0
- package/dist/lib/server-runtime/sessions/cookieStorage.d.ts +19 -0
- package/dist/lib/server-runtime/sessions/memoryStorage.d.ts +17 -0
- package/dist/lib/server-runtime/sessions.d.ts +140 -0
- package/dist/lib/server-runtime/single-fetch.d.ts +30 -0
- package/dist/lib/server-runtime/typecheck.d.ts +4 -0
- package/dist/lib/server-runtime/warnings.d.ts +1 -0
- package/dist/lib/types.d.ts +76 -0
- package/dist/lib/types.mjs +10 -0
- package/dist/main-dom-export.js +19 -0
- package/dist/main.js +1 -1
- package/dist/react-router-dom.development.js +199 -0
- package/dist/react-router-dom.development.js.map +1 -0
- package/dist/react-router-dom.production.min.js +12 -0
- package/dist/react-router-dom.production.min.js.map +1 -0
- package/dist/react-router.development.js +12281 -1141
- package/dist/react-router.development.js.map +1 -1
- package/dist/react-router.production.min.js +2 -2
- package/dist/react-router.production.min.js.map +1 -1
- package/dist/umd/react-router-dom.development.js +241 -0
- package/dist/umd/react-router-dom.development.js.map +1 -0
- package/dist/umd/react-router-dom.production.min.js +12 -0
- package/dist/umd/react-router-dom.production.min.js.map +1 -0
- package/dist/umd/react-router.development.js +12467 -1238
- package/dist/umd/react-router.development.js.map +1 -1
- package/dist/umd/react-router.production.min.js +2 -2
- package/dist/umd/react-router.production.min.js.map +1 -1
- package/package.json +35 -6
- package/dist/index.js +0 -1467
- package/dist/index.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react-router.production.min.js","sources":["../../lib/context.ts","../../lib/hooks.tsx","../../lib/components.tsx","../../index.ts"],"sourcesContent":["import * as React from \"react\";\nimport type {\n AgnosticIndexRouteObject,\n AgnosticNonIndexRouteObject,\n AgnosticRouteMatch,\n History,\n LazyRouteFunction,\n Location,\n Action as NavigationType,\n RelativeRoutingType,\n Router,\n StaticHandlerContext,\n To,\n TrackedPromise,\n} from \"@remix-run/router\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticIndexRouteObject[\"path\"];\n id?: AgnosticIndexRouteObject[\"id\"];\n loader?: AgnosticIndexRouteObject[\"loader\"];\n action?: AgnosticIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticIndexRouteObject[\"handle\"];\n index: true;\n children?: undefined;\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport interface NonIndexRouteObject {\n caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticNonIndexRouteObject[\"path\"];\n id?: AgnosticNonIndexRouteObject[\"id\"];\n loader?: AgnosticNonIndexRouteObject[\"loader\"];\n action?: AgnosticNonIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticNonIndexRouteObject[\"handle\"];\n index?: false;\n children?: RouteObject[];\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n children?: DataRouteObject[];\n id: string;\n};\n\nexport interface RouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {}\n\nexport interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}\n\nexport interface DataRouterContextObject\n // Omit `future` since those can be pulled from the `router`\n // `NavigationContext` needs future since it doesn't have a `router` in all cases\n extends Omit<NavigationContextObject, \"future\"> {\n router: Router;\n staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n React.createContext<DataRouterContextObject | null>(null);\nif (__DEV__) {\n DataRouterContext.displayName = \"DataRouter\";\n}\n\nexport const DataRouterStateContext = React.createContext<\n Router[\"state\"] | null\n>(null);\nif (__DEV__) {\n DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nexport const AwaitContext = React.createContext<TrackedPromise | null>(null);\nif (__DEV__) {\n AwaitContext.displayName = \"Await\";\n}\n\nexport interface NavigateOptions {\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n flushSync?: boolean;\n viewTransition?: boolean;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `<Router>` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n createHref: History[\"createHref\"];\n // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n encodeLocation?: History[\"encodeLocation\"];\n go: History[\"go\"];\n push(to: To, state?: any, opts?: NavigateOptions): void;\n replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n basename: string;\n navigator: Navigator;\n static: boolean;\n future: {\n v7_relativeSplatPath: boolean;\n };\n}\n\nexport const NavigationContext = React.createContext<NavigationContextObject>(\n null!\n);\n\nif (__DEV__) {\n NavigationContext.displayName = \"Navigation\";\n}\n\ninterface LocationContextObject {\n location: Location;\n navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext<LocationContextObject>(\n null!\n);\n\nif (__DEV__) {\n LocationContext.displayName = \"Location\";\n}\n\nexport interface RouteContextObject {\n outlet: React.ReactElement | null;\n matches: RouteMatch[];\n isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext<RouteContextObject>({\n outlet: null,\n matches: [],\n isDataRoute: false,\n});\n\nif (__DEV__) {\n RouteContext.displayName = \"Route\";\n}\n\nexport const RouteErrorContext = React.createContext<any>(null);\n\nif (__DEV__) {\n RouteErrorContext.displayName = \"RouteError\";\n}\n","import * as React from \"react\";\nimport type {\n Blocker,\n BlockerFunction,\n Location,\n ParamParseKey,\n Params,\n Path,\n PathMatch,\n PathPattern,\n RelativeRoutingType,\n Router as RemixRouter,\n RevalidationState,\n To,\n UIMatch,\n} from \"@remix-run/router\";\nimport {\n IDLE_BLOCKER,\n Action as NavigationType,\n UNSAFE_convertRouteMatchToUiMatch as convertRouteMatchToUiMatch,\n UNSAFE_decodePath as decodePath,\n UNSAFE_getResolveToMatches as getResolveToMatches,\n UNSAFE_invariant as invariant,\n isRouteErrorResponse,\n joinPaths,\n matchPath,\n matchRoutes,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n DataRouteMatch,\n NavigateOptions,\n RouteContextObject,\n RouteMatch,\n RouteObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n RouteErrorContext,\n} from \"./context\";\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/hooks/use-href\n */\nexport function useHref(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useHref() may be used only in the context of a <Router> component.`\n );\n\n let { basename, navigator } = React.useContext(NavigationContext);\n let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n let joinedPathname = pathname;\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the href. If this is a root navigation, then just use the raw\n // basename which allows the basename to have full control over the presence\n // of a trailing slash on root links\n if (basename !== \"/\") {\n joinedPathname =\n pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n }\n\n return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a `<Router>`.\n *\n * @see https://reactrouter.com/hooks/use-in-router-context\n */\nexport function useInRouterContext(): boolean {\n return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/hooks/use-location\n */\nexport function useLocation(): Location {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useLocation() may be used only in the context of a <Router> component.`\n );\n\n return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/hooks/use-navigation-type\n */\nexport function useNavigationType(): NavigationType {\n return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * `<NavLink>`.\n *\n * @see https://reactrouter.com/hooks/use-match\n */\nexport function useMatch<\n ParamKey extends ParamParseKey<Path>,\n Path extends string\n>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useMatch() may be used only in the context of a <Router> component.`\n );\n\n let { pathname } = useLocation();\n return React.useMemo(\n () => matchPath<ParamKey, Path>(pattern, decodePath(pathname)),\n [pathname, pattern]\n );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n (to: To, options?: NavigateOptions): void;\n (delta: number): void;\n}\n\nconst navigateEffectWarning =\n `You should call navigate() in a React.useEffect(), not when ` +\n `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n cb: Parameters<typeof React.useLayoutEffect>[0]\n) {\n let isStatic = React.useContext(NavigationContext).static;\n if (!isStatic) {\n // We should be able to get rid of this once react 18.3 is released\n // See: https://github.com/facebook/react/pull/26395\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(cb);\n }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by `<Link>`s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/hooks/use-navigate\n */\nexport function useNavigate(): NavigateFunction {\n let { isDataRoute } = React.useContext(RouteContext);\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useNavigate() may be used only in the context of a <Router> component.`\n );\n\n let dataRouterContext = React.useContext(DataRouterContext);\n let { basename, future, navigator } = React.useContext(NavigationContext);\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n\n let routePathnamesJson = JSON.stringify(\n getResolveToMatches(matches, future.v7_relativeSplatPath)\n );\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our history listener yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n navigator.go(to);\n return;\n }\n\n let path = resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n options.relative === \"path\"\n );\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to handing off to history (but only if we're not in a data router,\n // otherwise it'll prepend the basename inside of the router).\n // If this is a root navigation, then we navigate to the raw basename\n // which allows the basename to have full control over the presence of a\n // trailing slash on root links\n if (dataRouterContext == null && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\"\n ? basename\n : joinPaths([basename, path.pathname]);\n }\n\n (!!options.replace ? navigator.replace : navigator.push)(\n path,\n options.state,\n options\n );\n },\n [\n basename,\n navigator,\n routePathnamesJson,\n locationPathname,\n dataRouterContext,\n ]\n );\n\n return navigate;\n}\n\nconst OutletContext = React.createContext<unknown>(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/hooks/use-outlet-context\n */\nexport function useOutletContext<Context = unknown>(): Context {\n return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `<Outlet>` to render child routes.\n *\n * @see https://reactrouter.com/hooks/use-outlet\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n let outlet = React.useContext(RouteContext).outlet;\n if (outlet) {\n return (\n <OutletContext.Provider value={context}>{outlet}</OutletContext.Provider>\n );\n }\n return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/hooks/use-params\n */\nexport function useParams<\n ParamsOrKey extends string | Record<string, string | undefined> = string\n>(): Readonly<\n [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>\n> {\n let { matches } = React.useContext(RouteContext);\n let routeMatch = matches[matches.length - 1];\n return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/hooks/use-resolved-path\n */\nexport function useResolvedPath(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n let { future } = React.useContext(NavigationContext);\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n let routePathnamesJson = JSON.stringify(\n getResolveToMatches(matches, future.v7_relativeSplatPath)\n );\n\n return React.useMemo(\n () =>\n resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n relative === \"path\"\n ),\n [to, routePathnamesJson, locationPathname, relative]\n );\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `<Outlet>` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/hooks/use-routes\n */\nexport function useRoutes(\n routes: RouteObject[],\n locationArg?: Partial<Location> | string\n): React.ReactElement | null {\n return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nexport function useRoutesImpl(\n routes: RouteObject[],\n locationArg?: Partial<Location> | string,\n dataRouterState?: RemixRouter[\"state\"],\n future?: RemixRouter[\"future\"]\n): React.ReactElement | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useRoutes() may be used only in the context of a <Router> component.`\n );\n\n let { navigator } = React.useContext(NavigationContext);\n let { matches: parentMatches } = React.useContext(RouteContext);\n let routeMatch = parentMatches[parentMatches.length - 1];\n let parentParams = routeMatch ? routeMatch.params : {};\n let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n let parentRoute = routeMatch && routeMatch.route;\n\n if (__DEV__) {\n // You won't get a warning about 2 different <Routes> under a <Route>\n // without a trailing *, but this is a best-effort warning anyway since we\n // cannot even give the warning unless they land at the parent route.\n //\n // Example:\n //\n // <Routes>\n // {/* This route path MUST end with /* because otherwise\n // it will never match /blog/post/123 */}\n // <Route path=\"blog\" element={<Blog />} />\n // <Route path=\"blog/feed\" element={<BlogFeed />} />\n // </Routes>\n //\n // function Blog() {\n // return (\n // <Routes>\n // <Route path=\"post/:id\" element={<Post />} />\n // </Routes>\n // );\n // }\n let parentPath = (parentRoute && parentRoute.path) || \"\";\n warningOnce(\n parentPathname,\n !parentRoute || parentPath.endsWith(\"*\"),\n `You rendered descendant <Routes> (or called \\`useRoutes()\\`) at ` +\n `\"${parentPathname}\" (under <Route path=\"${parentPath}\">) but the ` +\n `parent route path has no trailing \"*\". This means if you navigate ` +\n `deeper, the parent won't match anymore and therefore the child ` +\n `routes will never render.\\n\\n` +\n `Please change the parent <Route path=\"${parentPath}\"> to <Route ` +\n `path=\"${parentPath === \"/\" ? \"*\" : `${parentPath}/*`}\">.`\n );\n }\n\n let locationFromContext = useLocation();\n\n let location;\n if (locationArg) {\n let parsedLocationArg =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n invariant(\n parentPathnameBase === \"/\" ||\n parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n `When overriding the location using \\`<Routes location>\\` or \\`useRoutes(routes, location)\\`, ` +\n `the location pathname must begin with the portion of the URL pathname that was ` +\n `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n );\n\n location = parsedLocationArg;\n } else {\n location = locationFromContext;\n }\n\n let pathname = location.pathname || \"/\";\n\n let remainingPathname = pathname;\n if (parentPathnameBase !== \"/\") {\n // Determine the remaining pathname by removing the # of URL segments the\n // parentPathnameBase has, instead of removing based on character count.\n // This is because we can't guarantee that incoming/outgoing encodings/\n // decodings will match exactly.\n // We decode paths before matching on a per-segment basis with\n // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they\n // match what `window.location.pathname` would reflect. Those don't 100%\n // align when it comes to encoded URI characters such as % and &.\n //\n // So we may end up with:\n // pathname: \"/descendant/a%25b/match\"\n // parentPathnameBase: \"/descendant/a%b\"\n //\n // And the direct substring removal approach won't work :/\n let parentSegments = parentPathnameBase.replace(/^\\//, \"\").split(\"/\");\n let segments = pathname.replace(/^\\//, \"\").split(\"/\");\n remainingPathname = \"/\" + segments.slice(parentSegments.length).join(\"/\");\n }\n\n let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n if (__DEV__) {\n warning(\n parentRoute || matches != null,\n `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n );\n\n warning(\n matches == null ||\n matches[matches.length - 1].route.element !== undefined ||\n matches[matches.length - 1].route.Component !== undefined ||\n matches[matches.length - 1].route.lazy !== undefined,\n `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n `does not have an element or Component. This means it will render an <Outlet /> with a ` +\n `null value by default resulting in an \"empty\" page.`\n );\n }\n\n let renderedMatches = _renderMatches(\n matches &&\n matches.map((match) =>\n Object.assign({}, match, {\n params: Object.assign({}, parentParams, match.params),\n pathname: joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathname).pathname\n : match.pathname,\n ]),\n pathnameBase:\n match.pathnameBase === \"/\"\n ? parentPathnameBase\n : joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathnameBase).pathname\n : match.pathnameBase,\n ]),\n })\n ),\n parentMatches,\n dataRouterState,\n future\n );\n\n // When a user passes in a `locationArg`, the associated routes need to\n // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n // to use the scoped location instead of the global location.\n if (locationArg && renderedMatches) {\n return (\n <LocationContext.Provider\n value={{\n location: {\n pathname: \"/\",\n search: \"\",\n hash: \"\",\n state: null,\n key: \"default\",\n ...location,\n },\n navigationType: NavigationType.Pop,\n }}\n >\n {renderedMatches}\n </LocationContext.Provider>\n );\n }\n\n return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n let error = useRouteError();\n let message = isRouteErrorResponse(error)\n ? `${error.status} ${error.statusText}`\n : error instanceof Error\n ? error.message\n : JSON.stringify(error);\n let stack = error instanceof Error ? error.stack : null;\n let lightgrey = \"rgba(200,200,200, 0.5)\";\n let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n let devInfo = null;\n if (__DEV__) {\n console.error(\n \"Error handled by React Router default ErrorBoundary:\",\n error\n );\n\n devInfo = (\n <>\n <p>💿 Hey developer 👋</p>\n <p>\n You can provide a way better UX than this when your app throws errors\n by providing your own <code style={codeStyles}>ErrorBoundary</code> or{\" \"}\n <code style={codeStyles}>errorElement</code> prop on your route.\n </p>\n </>\n );\n }\n\n return (\n <>\n <h2>Unexpected Application Error!</h2>\n <h3 style={{ fontStyle: \"italic\" }}>{message}</h3>\n {stack ? <pre style={preStyles}>{stack}</pre> : null}\n {devInfo}\n </>\n );\n}\n\nconst defaultErrorElement = <DefaultErrorComponent />;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n location: Location;\n revalidation: RevalidationState;\n error: any;\n component: React.ReactNode;\n routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n location: Location;\n revalidation: RevalidationState;\n error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n RenderErrorBoundaryProps,\n RenderErrorBoundaryState\n> {\n constructor(props: RenderErrorBoundaryProps) {\n super(props);\n this.state = {\n location: props.location,\n revalidation: props.revalidation,\n error: props.error,\n };\n }\n\n static getDerivedStateFromError(error: any) {\n return { error: error };\n }\n\n static getDerivedStateFromProps(\n props: RenderErrorBoundaryProps,\n state: RenderErrorBoundaryState\n ) {\n // When we get into an error state, the user will likely click \"back\" to the\n // previous page that didn't have an error. Because this wraps the entire\n // application, that will have no effect--the error page continues to display.\n // This gives us a mechanism to recover from the error when the location changes.\n //\n // Whether we're in an error state or not, we update the location in state\n // so that when we are in an error state, it gets reset when a new location\n // comes in and the user recovers from the error.\n if (\n state.location !== props.location ||\n (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n ) {\n return {\n error: props.error,\n location: props.location,\n revalidation: props.revalidation,\n };\n }\n\n // If we're not changing locations, preserve the location but still surface\n // any new errors that may come through. We retain the existing error, we do\n // this because the error provided from the app state may be cleared without\n // the location changing.\n return {\n error: props.error !== undefined ? props.error : state.error,\n location: state.location,\n revalidation: props.revalidation || state.revalidation,\n };\n }\n\n componentDidCatch(error: any, errorInfo: any) {\n console.error(\n \"React Router caught the following error during render\",\n error,\n errorInfo\n );\n }\n\n render() {\n return this.state.error !== undefined ? (\n <RouteContext.Provider value={this.props.routeContext}>\n <RouteErrorContext.Provider\n value={this.state.error}\n children={this.props.component}\n />\n </RouteContext.Provider>\n ) : (\n this.props.children\n );\n }\n}\n\ninterface RenderedRouteProps {\n routeContext: RouteContextObject;\n match: RouteMatch<string, RouteObject>;\n children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n let dataRouterContext = React.useContext(DataRouterContext);\n\n // Track how deep we got in our render pass to emulate SSR componentDidCatch\n // in a DataStaticRouter\n if (\n dataRouterContext &&\n dataRouterContext.static &&\n dataRouterContext.staticContext &&\n (match.route.errorElement || match.route.ErrorBoundary)\n ) {\n dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n }\n\n return (\n <RouteContext.Provider value={routeContext}>\n {children}\n </RouteContext.Provider>\n );\n}\n\nexport function _renderMatches(\n matches: RouteMatch[] | null,\n parentMatches: RouteMatch[] = [],\n dataRouterState: RemixRouter[\"state\"] | null = null,\n future: RemixRouter[\"future\"] | null = null\n): React.ReactElement | null {\n if (matches == null) {\n if (!dataRouterState) {\n return null;\n }\n\n if (dataRouterState.errors) {\n // Don't bail if we have data router errors so we can render them in the\n // boundary. Use the pre-matched (or shimmed) matches\n matches = dataRouterState.matches as DataRouteMatch[];\n } else if (\n future?.v7_partialHydration &&\n parentMatches.length === 0 &&\n !dataRouterState.initialized &&\n dataRouterState.matches.length > 0\n ) {\n // Don't bail if we're initializing with partial hydration and we have\n // router matches. That means we're actively running `patchRoutesOnNavigation`\n // so we should render down the partial matches to the appropriate\n // `HydrateFallback`. We only do this if `parentMatches` is empty so it\n // only impacts the root matches for `RouterProvider` and no descendant\n // `<Routes>`\n matches = dataRouterState.matches as DataRouteMatch[];\n } else {\n return null;\n }\n }\n\n let renderedMatches = matches;\n\n // If we have data errors, trim matches to the highest error boundary\n let errors = dataRouterState?.errors;\n if (errors != null) {\n let errorIndex = renderedMatches.findIndex(\n (m) => m.route.id && errors?.[m.route.id] !== undefined\n );\n invariant(\n errorIndex >= 0,\n `Could not find a matching route for errors on route IDs: ${Object.keys(\n errors\n ).join(\",\")}`\n );\n renderedMatches = renderedMatches.slice(\n 0,\n Math.min(renderedMatches.length, errorIndex + 1)\n );\n }\n\n // If we're in a partial hydration mode, detect if we need to render down to\n // a given HydrateFallback while we load the rest of the hydration data\n let renderFallback = false;\n let fallbackIndex = -1;\n if (dataRouterState && future && future.v7_partialHydration) {\n for (let i = 0; i < renderedMatches.length; i++) {\n let match = renderedMatches[i];\n // Track the deepest fallback up until the first route without data\n if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {\n fallbackIndex = i;\n }\n\n if (match.route.id) {\n let { loaderData, errors } = dataRouterState;\n let needsToRunLoader =\n match.route.loader &&\n loaderData[match.route.id] === undefined &&\n (!errors || errors[match.route.id] === undefined);\n if (match.route.lazy || needsToRunLoader) {\n // We found the first route that's not ready to render (waiting on\n // lazy, or has a loader that hasn't run yet). Flag that we need to\n // render a fallback and render up until the appropriate fallback\n renderFallback = true;\n if (fallbackIndex >= 0) {\n renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);\n } else {\n renderedMatches = [renderedMatches[0]];\n }\n break;\n }\n }\n }\n }\n\n return renderedMatches.reduceRight((outlet, match, index) => {\n // Only data routers handle errors/fallbacks\n let error: any;\n let shouldRenderHydrateFallback = false;\n let errorElement: React.ReactNode | null = null;\n let hydrateFallbackElement: React.ReactNode | null = null;\n if (dataRouterState) {\n error = errors && match.route.id ? errors[match.route.id] : undefined;\n errorElement = match.route.errorElement || defaultErrorElement;\n\n if (renderFallback) {\n if (fallbackIndex < 0 && index === 0) {\n warningOnce(\n \"route-fallback\",\n false,\n \"No `HydrateFallback` element provided to render during initial hydration\"\n );\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = null;\n } else if (fallbackIndex === index) {\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = match.route.hydrateFallbackElement || null;\n }\n }\n }\n\n let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n let getChildren = () => {\n let children: React.ReactNode;\n if (error) {\n children = errorElement;\n } else if (shouldRenderHydrateFallback) {\n children = hydrateFallbackElement;\n } else if (match.route.Component) {\n // Note: This is a de-optimized path since React won't re-use the\n // ReactElement since it's identity changes with each new\n // React.createElement call. We keep this so folks can use\n // `<Route Component={...}>` in `<Routes>` but generally `Component`\n // usage is only advised in `RouterProvider` when we can convert it to\n // `element` ahead of time.\n children = <match.route.Component />;\n } else if (match.route.element) {\n children = match.route.element;\n } else {\n children = outlet;\n }\n return (\n <RenderedRoute\n match={match}\n routeContext={{\n outlet,\n matches,\n isDataRoute: dataRouterState != null,\n }}\n children={children}\n />\n );\n };\n // Only wrap in an error boundary within data router usages when we have an\n // ErrorBoundary/errorElement on this route. Otherwise let it bubble up to\n // an ancestor ErrorBoundary/errorElement\n return dataRouterState &&\n (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n <RenderErrorBoundary\n location={dataRouterState.location}\n revalidation={dataRouterState.revalidation}\n component={errorElement}\n error={error}\n children={getChildren()}\n routeContext={{ outlet: null, matches, isDataRoute: true }}\n />\n ) : (\n getChildren()\n );\n }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n UseBlocker = \"useBlocker\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n UseBlocker = \"useBlocker\",\n UseLoaderData = \"useLoaderData\",\n UseActionData = \"useActionData\",\n UseRouteError = \"useRouteError\",\n UseNavigation = \"useNavigation\",\n UseRouteLoaderData = \"useRouteLoaderData\",\n UseMatches = \"useMatches\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n hookName: DataRouterHook | DataRouterStateHook\n) {\n return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n let ctx = React.useContext(DataRouterContext);\n invariant(ctx, getDataRouterConsoleError(hookName));\n return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n let state = React.useContext(DataRouterStateContext);\n invariant(state, getDataRouterConsoleError(hookName));\n return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n let route = React.useContext(RouteContext);\n invariant(route, getDataRouterConsoleError(hookName));\n return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n let route = useRouteContext(hookName);\n let thisRoute = route.matches[route.matches.length - 1];\n invariant(\n thisRoute.route.id,\n `${hookName} can only be used on routes that contain a unique \"id\"`\n );\n return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nexport function useNavigation() {\n let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nexport function useRevalidator() {\n let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n return React.useMemo(\n () => ({\n revalidate: dataRouterContext.router.revalidate,\n state: state.revalidation,\n }),\n [dataRouterContext.router.revalidate, state.revalidation]\n );\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nexport function useMatches(): UIMatch[] {\n let { matches, loaderData } = useDataRouterState(\n DataRouterStateHook.UseMatches\n );\n return React.useMemo(\n () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),\n [matches, loaderData]\n );\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nexport function useLoaderData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n if (state.errors && state.errors[routeId] != null) {\n console.error(\n `You cannot \\`useLoaderData\\` in an errorElement (routeId: ${routeId})`\n );\n return undefined;\n }\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nexport function useActionData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseActionData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error. This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nexport function useRouteError(): unknown {\n let error = React.useContext(RouteErrorContext);\n let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n // If this was a render error, we put it in a RouteError context inside\n // of RenderErrorBoundary\n if (error !== undefined) {\n return error;\n }\n\n // Otherwise look for errors from our data router state\n return state.errors?.[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `<Await />` value\n */\nexport function useAsyncValue(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `<Await />` value\n */\nexport function useAsyncError(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation. Mostly used to avoid\n * using half-filled form data. This does not handle hard-reloads or\n * cross-origin navigations.\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);\n let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n\n let [blockerKey, setBlockerKey] = React.useState(\"\");\n let blockerFunction = React.useCallback<BlockerFunction>(\n (arg) => {\n if (typeof shouldBlock !== \"function\") {\n return !!shouldBlock;\n }\n if (basename === \"/\") {\n return shouldBlock(arg);\n }\n\n // If they provided us a function and we've got an active basename, strip\n // it from the locations we expose to the user to match the behavior of\n // useLocation\n let { currentLocation, nextLocation, historyAction } = arg;\n return shouldBlock({\n currentLocation: {\n ...currentLocation,\n pathname:\n stripBasename(currentLocation.pathname, basename) ||\n currentLocation.pathname,\n },\n nextLocation: {\n ...nextLocation,\n pathname:\n stripBasename(nextLocation.pathname, basename) ||\n nextLocation.pathname,\n },\n historyAction,\n });\n },\n [basename, shouldBlock]\n );\n\n // This effect is in charge of blocker key assignment and deletion (which is\n // tightly coupled to the key)\n React.useEffect(() => {\n let key = String(++blockerId);\n setBlockerKey(key);\n return () => router.deleteBlocker(key);\n }, [router]);\n\n // This effect handles assigning the blockerFunction. This is to handle\n // unstable blocker function identities, and happens only after the prior\n // effect so we don't get an orphaned blockerFunction in the router with a\n // key of \"\". Until then we just have the IDLE_BLOCKER.\n React.useEffect(() => {\n if (blockerKey !== \"\") {\n router.getBlocker(blockerKey, blockerFunction);\n }\n }, [router, blockerKey, blockerFunction]);\n\n // Prefer the blocker from `state` not `router.state` since DataRouterContext\n // is memoized so this ensures we update on blocker state updates\n return blockerKey && state.blockers.has(blockerKey)\n ? state.blockers.get(blockerKey)!\n : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable(): NavigateFunction {\n let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our router subscriber yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n router.navigate(to);\n } else {\n router.navigate(to, { fromRouteId: id, ...options });\n }\n },\n [router, id]\n );\n\n return navigate;\n}\n\nconst alreadyWarned: Record<string, boolean> = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n if (!cond && !alreadyWarned[key]) {\n alreadyWarned[key] = true;\n warning(false, message);\n }\n}\n","import type {\n InitialEntry,\n LazyRouteFunction,\n Location,\n MemoryHistory,\n RelativeRoutingType,\n Router as RemixRouter,\n RouterState,\n RouterSubscriber,\n To,\n TrackedPromise,\n} from \"@remix-run/router\";\nimport {\n AbortedDeferredError,\n Action as NavigationType,\n createMemoryHistory,\n UNSAFE_getResolveToMatches as getResolveToMatches,\n UNSAFE_invariant as invariant,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\nimport * as React from \"react\";\n\nimport type {\n DataRouteObject,\n IndexRouteObject,\n Navigator,\n NonIndexRouteObject,\n RouteMatch,\n RouteObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n} from \"./context\";\nimport {\n _renderMatches,\n useAsyncValue,\n useInRouterContext,\n useLocation,\n useNavigate,\n useOutlet,\n useRoutes,\n useRoutesImpl,\n} from \"./hooks\";\n\nexport interface FutureConfig {\n v7_relativeSplatPath: boolean;\n v7_startTransition: boolean;\n}\n\nexport interface RouterProviderProps {\n fallbackElement?: React.ReactNode;\n router: RemixRouter;\n // Only accept future flags relevant to rendering behavior\n // routing flags should be accessed via router.future\n future?: Partial<Pick<FutureConfig, \"v7_startTransition\">>;\n}\n\n/**\n Webpack + React 17 fails to compile on any of the following because webpack\n complains that `startTransition` doesn't exist in `React`:\n * import { startTransition } from \"react\"\n * import * as React from from \"react\";\n \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n * import * as React from from \"react\";\n \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n Moving it to a constant such as the following solves the Webpack/React 17 issue:\n * import * as React from from \"react\";\n const START_TRANSITION = \"startTransition\";\n START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n However, that introduces webpack/terser minification issues in production builds\n in React 18 where minification/obfuscation ends up removing the call of\n React.startTransition entirely from the first half of the ternary. Grabbing\n this exported reference once up front resolves that issue.\n\n See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n fallbackElement,\n router,\n future,\n}: RouterProviderProps): React.ReactElement {\n let [state, setStateImpl] = React.useState(router.state);\n let { v7_startTransition } = future || {};\n\n let setState = React.useCallback<RouterSubscriber>(\n (newState: RouterState) => {\n if (v7_startTransition && startTransitionImpl) {\n startTransitionImpl(() => setStateImpl(newState));\n } else {\n setStateImpl(newState);\n }\n },\n [setStateImpl, v7_startTransition]\n );\n\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n React.useEffect(() => {\n warning(\n fallbackElement == null || !router.future.v7_partialHydration,\n \"`<RouterProvider fallbackElement>` is deprecated when using \" +\n \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n );\n // Only log this once on initial mount\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n let navigator = React.useMemo((): Navigator => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: (n) => router.navigate(n),\n push: (to, state, opts) =>\n router.navigate(to, {\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n replace: (to, state, opts) =>\n router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n };\n }, [router]);\n\n let basename = router.basename || \"/\";\n\n let dataRouterContext = React.useMemo(\n () => ({\n router,\n navigator,\n static: false,\n basename,\n }),\n [router, navigator, basename]\n );\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a <script> here\n // containing the hydrated server-side staticContext (from StaticRouterProvider).\n // useId relies on the component tree structure to generate deterministic id's\n // so we need to ensure it remains the same on the client even though\n // we don't need the <script> tag\n return (\n <>\n <DataRouterContext.Provider value={dataRouterContext}>\n <DataRouterStateContext.Provider value={state}>\n <Router\n basename={basename}\n location={state.location}\n navigationType={state.historyAction}\n navigator={navigator}\n future={{\n v7_relativeSplatPath: router.future.v7_relativeSplatPath,\n }}\n >\n {state.initialized || router.future.v7_partialHydration ? (\n <DataRoutes\n routes={router.routes}\n future={router.future}\n state={state}\n />\n ) : (\n fallbackElement\n )}\n </Router>\n </DataRouterStateContext.Provider>\n </DataRouterContext.Provider>\n {null}\n </>\n );\n}\n\nfunction DataRoutes({\n routes,\n future,\n state,\n}: {\n routes: DataRouteObject[];\n future: RemixRouter[\"future\"];\n state: RouterState;\n}): React.ReactElement | null {\n return useRoutesImpl(routes, undefined, state, future);\n}\n\nexport interface MemoryRouterProps {\n basename?: string;\n children?: React.ReactNode;\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n future?: Partial<FutureConfig>;\n}\n\n/**\n * A `<Router>` that stores all entries in memory.\n *\n * @see https://reactrouter.com/router-components/memory-router\n */\nexport function MemoryRouter({\n basename,\n children,\n initialEntries,\n initialIndex,\n future,\n}: MemoryRouterProps): React.ReactElement {\n let historyRef = React.useRef<MemoryHistory>();\n if (historyRef.current == null) {\n historyRef.current = createMemoryHistory({\n initialEntries,\n initialIndex,\n v5Compat: true,\n });\n }\n\n let history = historyRef.current;\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n future={future}\n />\n );\n}\n\nexport interface NavigateProps {\n to: To;\n replace?: boolean;\n state?: any;\n relative?: RelativeRoutingType;\n}\n\n/**\n * Changes the current location.\n *\n * Note: This API is mostly useful in React.Component subclasses that are not\n * able to use hooks. In functional components, we recommend you use the\n * `useNavigate` hook instead.\n *\n * @see https://reactrouter.com/components/navigate\n */\nexport function Navigate({\n to,\n replace,\n state,\n relative,\n}: NavigateProps): null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of\n // the router loaded. We can help them understand how to avoid that.\n `<Navigate> may be used only in the context of a <Router> component.`\n );\n\n let { future, static: isStatic } = React.useContext(NavigationContext);\n\n warning(\n !isStatic,\n `<Navigate> must not be used on the initial render in a <StaticRouter>. ` +\n `This is a no-op, but you should modify your code so the <Navigate> is ` +\n `only ever rendered in response to some user interaction or state change.`\n );\n\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n let navigate = useNavigate();\n\n // Resolve the path outside of the effect so that when effects run twice in\n // StrictMode they navigate to the same place\n let path = resolveTo(\n to,\n getResolveToMatches(matches, future.v7_relativeSplatPath),\n locationPathname,\n relative === \"path\"\n );\n let jsonPath = JSON.stringify(path);\n\n React.useEffect(\n () => navigate(JSON.parse(jsonPath), { replace, state, relative }),\n [navigate, jsonPath, relative, replace, state]\n );\n\n return null;\n}\n\nexport interface OutletProps {\n context?: unknown;\n}\n\n/**\n * Renders the child route's element, if there is one.\n *\n * @see https://reactrouter.com/components/outlet\n */\nexport function Outlet(props: OutletProps): React.ReactElement | null {\n return useOutlet(props.context);\n}\n\nexport interface PathRouteProps {\n caseSensitive?: NonIndexRouteObject[\"caseSensitive\"];\n path?: NonIndexRouteObject[\"path\"];\n id?: NonIndexRouteObject[\"id\"];\n lazy?: LazyRouteFunction<NonIndexRouteObject>;\n loader?: NonIndexRouteObject[\"loader\"];\n action?: NonIndexRouteObject[\"action\"];\n hasErrorBoundary?: NonIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: NonIndexRouteObject[\"shouldRevalidate\"];\n handle?: NonIndexRouteObject[\"handle\"];\n index?: false;\n children?: React.ReactNode;\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n}\n\nexport interface LayoutRouteProps extends PathRouteProps {}\n\nexport interface IndexRouteProps {\n caseSensitive?: IndexRouteObject[\"caseSensitive\"];\n path?: IndexRouteObject[\"path\"];\n id?: IndexRouteObject[\"id\"];\n lazy?: LazyRouteFunction<IndexRouteObject>;\n loader?: IndexRouteObject[\"loader\"];\n action?: IndexRouteObject[\"action\"];\n hasErrorBoundary?: IndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: IndexRouteObject[\"shouldRevalidate\"];\n handle?: IndexRouteObject[\"handle\"];\n index: true;\n children?: undefined;\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n}\n\nexport type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;\n\n/**\n * Declares an element that should be rendered at a certain URL path.\n *\n * @see https://reactrouter.com/components/route\n */\nexport function Route(_props: RouteProps): React.ReactElement | null {\n invariant(\n false,\n `A <Route> is only ever to be used as the child of <Routes> element, ` +\n `never rendered directly. Please wrap your <Route> in a <Routes>.`\n );\n}\n\nexport interface RouterProps {\n basename?: string;\n children?: React.ReactNode;\n location: Partial<Location> | string;\n navigationType?: NavigationType;\n navigator: Navigator;\n static?: boolean;\n future?: Partial<Pick<FutureConfig, \"v7_relativeSplatPath\">>;\n}\n\n/**\n * Provides location context for the rest of the app.\n *\n * Note: You usually won't render a `<Router>` directly. Instead, you'll render a\n * router that is more specific to your environment such as a `<BrowserRouter>`\n * in web browsers or a `<StaticRouter>` for server rendering.\n *\n * @see https://reactrouter.com/router-components/router\n */\nexport function Router({\n basename: basenameProp = \"/\",\n children = null,\n location: locationProp,\n navigationType = NavigationType.Pop,\n navigator,\n static: staticProp = false,\n future,\n}: RouterProps): React.ReactElement | null {\n invariant(\n !useInRouterContext(),\n `You cannot render a <Router> inside another <Router>.` +\n ` You should never have more than one in your app.`\n );\n\n // Preserve trailing slashes on basename, so we can let the user control\n // the enforcement of trailing slashes throughout the app\n let basename = basenameProp.replace(/^\\/*/, \"/\");\n let navigationContext = React.useMemo(\n () => ({\n basename,\n navigator,\n static: staticProp,\n future: {\n v7_relativeSplatPath: false,\n ...future,\n },\n }),\n [basename, future, navigator, staticProp]\n );\n\n if (typeof locationProp === \"string\") {\n locationProp = parsePath(locationProp);\n }\n\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n state = null,\n key = \"default\",\n } = locationProp;\n\n let locationContext = React.useMemo(() => {\n let trailingPathname = stripBasename(pathname, basename);\n\n if (trailingPathname == null) {\n return null;\n }\n\n return {\n location: {\n pathname: trailingPathname,\n search,\n hash,\n state,\n key,\n },\n navigationType,\n };\n }, [basename, pathname, search, hash, state, key, navigationType]);\n\n warning(\n locationContext != null,\n `<Router basename=\"${basename}\"> is not able to match the URL ` +\n `\"${pathname}${search}${hash}\" because it does not start with the ` +\n `basename, so the <Router> won't render anything.`\n );\n\n if (locationContext == null) {\n return null;\n }\n\n return (\n <NavigationContext.Provider value={navigationContext}>\n <LocationContext.Provider children={children} value={locationContext} />\n </NavigationContext.Provider>\n );\n}\n\nexport interface RoutesProps {\n children?: React.ReactNode;\n location?: Partial<Location> | string;\n}\n\n/**\n * A container for a nested tree of `<Route>` elements that renders the branch\n * that best matches the current location.\n *\n * @see https://reactrouter.com/components/routes\n */\nexport function Routes({\n children,\n location,\n}: RoutesProps): React.ReactElement | null {\n return useRoutes(createRoutesFromChildren(children), location);\n}\n\nexport interface AwaitResolveRenderFunction {\n (data: Awaited<any>): React.ReactNode;\n}\n\nexport interface AwaitProps {\n children: React.ReactNode | AwaitResolveRenderFunction;\n errorElement?: React.ReactNode;\n resolve: TrackedPromise | any;\n}\n\n/**\n * Component to use for rendering lazily loaded data from returning defer()\n * in a loader function\n */\nexport function Await({ children, errorElement, resolve }: AwaitProps) {\n return (\n <AwaitErrorBoundary resolve={resolve} errorElement={errorElement}>\n <ResolveAwait>{children}</ResolveAwait>\n </AwaitErrorBoundary>\n );\n}\n\ntype AwaitErrorBoundaryProps = React.PropsWithChildren<{\n errorElement?: React.ReactNode;\n resolve: TrackedPromise | any;\n}>;\n\ntype AwaitErrorBoundaryState = {\n error: any;\n};\n\nenum AwaitRenderStatus {\n pending,\n success,\n error,\n}\n\nconst neverSettledPromise = new Promise(() => {});\n\nclass AwaitErrorBoundary extends React.Component<\n AwaitErrorBoundaryProps,\n AwaitErrorBoundaryState\n> {\n constructor(props: AwaitErrorBoundaryProps) {\n super(props);\n this.state = { error: null };\n }\n\n static getDerivedStateFromError(error: any) {\n return { error };\n }\n\n componentDidCatch(error: any, errorInfo: any) {\n console.error(\n \"<Await> caught the following error during render\",\n error,\n errorInfo\n );\n }\n\n render() {\n let { children, errorElement, resolve } = this.props;\n\n let promise: TrackedPromise | null = null;\n let status: AwaitRenderStatus = AwaitRenderStatus.pending;\n\n if (!(resolve instanceof Promise)) {\n // Didn't get a promise - provide as a resolved promise\n status = AwaitRenderStatus.success;\n promise = Promise.resolve();\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n Object.defineProperty(promise, \"_data\", { get: () => resolve });\n } else if (this.state.error) {\n // Caught a render error, provide it as a rejected promise\n status = AwaitRenderStatus.error;\n let renderError = this.state.error;\n promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n Object.defineProperty(promise, \"_error\", { get: () => renderError });\n } else if ((resolve as TrackedPromise)._tracked) {\n // Already tracked promise - check contents\n promise = resolve;\n status =\n \"_error\" in promise\n ? AwaitRenderStatus.error\n : \"_data\" in promise\n ? AwaitRenderStatus.success\n : AwaitRenderStatus.pending;\n } else {\n // Raw (untracked) promise - track it\n status = AwaitRenderStatus.pending;\n Object.defineProperty(resolve, \"_tracked\", { get: () => true });\n promise = resolve.then(\n (data: any) =>\n Object.defineProperty(resolve, \"_data\", { get: () => data }),\n (error: any) =>\n Object.defineProperty(resolve, \"_error\", { get: () => error })\n );\n }\n\n if (\n status === AwaitRenderStatus.error &&\n promise._error instanceof AbortedDeferredError\n ) {\n // Freeze the UI by throwing a never resolved promise\n throw neverSettledPromise;\n }\n\n if (status === AwaitRenderStatus.error && !errorElement) {\n // No errorElement, throw to the nearest route-level error boundary\n throw promise._error;\n }\n\n if (status === AwaitRenderStatus.error) {\n // Render via our errorElement\n return <AwaitContext.Provider value={promise} children={errorElement} />;\n }\n\n if (status === AwaitRenderStatus.success) {\n // Render children with resolved value\n return <AwaitContext.Provider value={promise} children={children} />;\n }\n\n // Throw to the suspense boundary\n throw promise;\n }\n}\n\n/**\n * @private\n * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`\n */\nfunction ResolveAwait({\n children,\n}: {\n children: React.ReactNode | AwaitResolveRenderFunction;\n}) {\n let data = useAsyncValue();\n let toRender = typeof children === \"function\" ? children(data) : children;\n return <>{toRender}</>;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// UTILS\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Creates a route config from a React \"children\" object, which is usually\n * either a `<Route>` element or an array of them. Used internally by\n * `<Routes>` to create a route config from its children.\n *\n * @see https://reactrouter.com/utils/create-routes-from-children\n */\nexport function createRoutesFromChildren(\n children: React.ReactNode,\n parentPath: number[] = []\n): RouteObject[] {\n let routes: RouteObject[] = [];\n\n React.Children.forEach(children, (element, index) => {\n if (!React.isValidElement(element)) {\n // Ignore non-elements. This allows people to more easily inline\n // conditionals in their route config.\n return;\n }\n\n let treePath = [...parentPath, index];\n\n if (element.type === React.Fragment) {\n // Transparently support React.Fragment and its children.\n routes.push.apply(\n routes,\n createRoutesFromChildren(element.props.children, treePath)\n );\n return;\n }\n\n invariant(\n element.type === Route,\n `[${\n typeof element.type === \"string\" ? element.type : element.type.name\n }] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`\n );\n\n invariant(\n !element.props.index || !element.props.children,\n \"An index route cannot have child routes.\"\n );\n\n let route: RouteObject = {\n id: element.props.id || treePath.join(\"-\"),\n caseSensitive: element.props.caseSensitive,\n element: element.props.element,\n Component: element.props.Component,\n index: element.props.index,\n path: element.props.path,\n loader: element.props.loader,\n action: element.props.action,\n errorElement: element.props.errorElement,\n ErrorBoundary: element.props.ErrorBoundary,\n hasErrorBoundary:\n element.props.ErrorBoundary != null ||\n element.props.errorElement != null,\n shouldRevalidate: element.props.shouldRevalidate,\n handle: element.props.handle,\n lazy: element.props.lazy,\n };\n\n if (element.props.children) {\n route.children = createRoutesFromChildren(\n element.props.children,\n treePath\n );\n }\n\n routes.push(route);\n });\n\n return routes;\n}\n\n/**\n * Renders the result of `matchRoutes()` into a React element.\n */\nexport function renderMatches(\n matches: RouteMatch[] | null\n): React.ReactElement | null {\n return _renderMatches(matches);\n}\n","import * as React from \"react\";\nimport type {\n ActionFunction,\n ActionFunctionArgs,\n AgnosticPatchRoutesOnNavigationFunction,\n AgnosticPatchRoutesOnNavigationFunctionArgs,\n Blocker,\n BlockerFunction,\n DataStrategyFunction,\n DataStrategyFunctionArgs,\n DataStrategyMatch,\n DataStrategyResult,\n ErrorResponse,\n Fetcher,\n HydrationState,\n InitialEntry,\n JsonFunction,\n LazyRouteFunction,\n LoaderFunction,\n LoaderFunctionArgs,\n Location,\n Navigation,\n ParamParseKey,\n Params,\n Path,\n PathMatch,\n PathParam,\n PathPattern,\n RedirectFunction,\n RelativeRoutingType,\n Router as RemixRouter,\n FutureConfig as RouterFutureConfig,\n ShouldRevalidateFunction,\n ShouldRevalidateFunctionArgs,\n To,\n UIMatch,\n} from \"@remix-run/router\";\nimport {\n AbortedDeferredError,\n Action as NavigationType,\n createMemoryHistory,\n createPath,\n createRouter,\n defer,\n generatePath,\n isRouteErrorResponse,\n json,\n matchPath,\n matchRoutes,\n parsePath,\n redirect,\n redirectDocument,\n replace,\n resolvePath,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n AwaitProps,\n FutureConfig,\n IndexRouteProps,\n LayoutRouteProps,\n MemoryRouterProps,\n NavigateProps,\n OutletProps,\n PathRouteProps,\n RouteProps,\n RouterProps,\n RouterProviderProps,\n RoutesProps,\n} from \"./lib/components\";\nimport {\n Await,\n MemoryRouter,\n Navigate,\n Outlet,\n Route,\n Router,\n RouterProvider,\n Routes,\n createRoutesFromChildren,\n renderMatches,\n} from \"./lib/components\";\nimport type {\n DataRouteMatch,\n DataRouteObject,\n IndexRouteObject,\n NavigateOptions,\n Navigator,\n NonIndexRouteObject,\n RouteMatch,\n RouteObject,\n} from \"./lib/context\";\nimport {\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n} from \"./lib/context\";\nimport type { NavigateFunction } from \"./lib/hooks\";\nimport {\n useActionData,\n useAsyncError,\n useAsyncValue,\n useBlocker,\n useHref,\n useInRouterContext,\n useLoaderData,\n useLocation,\n useMatch,\n useMatches,\n useNavigate,\n useNavigation,\n useNavigationType,\n useOutlet,\n useOutletContext,\n useParams,\n useResolvedPath,\n useRevalidator,\n useRouteError,\n useRouteId,\n useRouteLoaderData,\n useRoutes,\n useRoutesImpl,\n} from \"./lib/hooks\";\n\n// Exported for backwards compatibility, but not being used internally anymore\ntype Hash = string;\ntype Pathname = string;\ntype Search = string;\n\n// Expose react-router public API\nexport type {\n ActionFunction,\n ActionFunctionArgs,\n AwaitProps,\n DataRouteMatch,\n DataRouteObject,\n DataStrategyFunction,\n DataStrategyFunctionArgs,\n DataStrategyMatch,\n DataStrategyResult,\n ErrorResponse,\n Fetcher,\n FutureConfig,\n Hash,\n IndexRouteObject,\n IndexRouteProps,\n JsonFunction,\n LayoutRouteProps,\n LazyRouteFunction,\n LoaderFunction,\n LoaderFunctionArgs,\n Location,\n MemoryRouterProps,\n NavigateFunction,\n NavigateOptions,\n NavigateProps,\n Navigation,\n Navigator,\n NonIndexRouteObject,\n OutletProps,\n ParamParseKey,\n Params,\n Path,\n PathMatch,\n PathParam,\n PathPattern,\n PathRouteProps,\n Pathname,\n RedirectFunction,\n RelativeRoutingType,\n RouteMatch,\n RouteObject,\n RouteProps,\n RouterProps,\n RouterProviderProps,\n RoutesProps,\n Search,\n ShouldRevalidateFunction,\n ShouldRevalidateFunctionArgs,\n To,\n UIMatch,\n Blocker,\n BlockerFunction,\n};\nexport {\n AbortedDeferredError,\n Await,\n MemoryRouter,\n Navigate,\n NavigationType,\n Outlet,\n Route,\n Router,\n RouterProvider,\n Routes,\n createPath,\n createRoutesFromChildren,\n createRoutesFromChildren as createRoutesFromElements,\n defer,\n generatePath,\n isRouteErrorResponse,\n json,\n matchPath,\n matchRoutes,\n parsePath,\n redirect,\n redirectDocument,\n replace,\n renderMatches,\n resolvePath,\n useBlocker,\n useActionData,\n useAsyncError,\n useAsyncValue,\n useHref,\n useInRouterContext,\n useLoaderData,\n useLocation,\n useMatch,\n useMatches,\n useNavigate,\n useNavigation,\n useNavigationType,\n useOutlet,\n useOutletContext,\n useParams,\n useResolvedPath,\n useRevalidator,\n useRouteError,\n useRouteLoaderData,\n useRoutes,\n};\n\nexport type PatchRoutesOnNavigationFunctionArgs =\n AgnosticPatchRoutesOnNavigationFunctionArgs<RouteObject, RouteMatch>;\n\nexport type PatchRoutesOnNavigationFunction =\n AgnosticPatchRoutesOnNavigationFunction<RouteObject, RouteMatch>;\n\nfunction mapRouteProperties(route: RouteObject) {\n let updates: Partial<RouteObject> & { hasErrorBoundary: boolean } = {\n // Note: this check also occurs in createRoutesFromChildren so update\n // there if you change this -- please and thank you!\n hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null,\n };\n\n if (route.Component) {\n if (__DEV__) {\n if (route.element) {\n warning(\n false,\n \"You should not include both `Component` and `element` on your route - \" +\n \"`Component` will be used.\"\n );\n }\n }\n Object.assign(updates, {\n element: React.createElement(route.Component),\n Component: undefined,\n });\n }\n\n if (route.HydrateFallback) {\n if (__DEV__) {\n if (route.hydrateFallbackElement) {\n warning(\n false,\n \"You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - \" +\n \"`HydrateFallback` will be used.\"\n );\n }\n }\n Object.assign(updates, {\n hydrateFallbackElement: React.createElement(route.HydrateFallback),\n HydrateFallback: undefined,\n });\n }\n\n if (route.ErrorBoundary) {\n if (__DEV__) {\n if (route.errorElement) {\n warning(\n false,\n \"You should not include both `ErrorBoundary` and `errorElement` on your route - \" +\n \"`ErrorBoundary` will be used.\"\n );\n }\n }\n Object.assign(updates, {\n errorElement: React.createElement(route.ErrorBoundary),\n ErrorBoundary: undefined,\n });\n }\n\n return updates;\n}\n\nexport function createMemoryRouter(\n routes: RouteObject[],\n opts?: {\n basename?: string;\n future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n hydrationData?: HydrationState;\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n dataStrategy?: DataStrategyFunction;\n patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;\n }\n): RemixRouter {\n return createRouter({\n basename: opts?.basename,\n future: {\n ...opts?.future,\n v7_prependBasename: true,\n },\n history: createMemoryHistory({\n initialEntries: opts?.initialEntries,\n initialIndex: opts?.initialIndex,\n }),\n hydrationData: opts?.hydrationData,\n routes,\n mapRouteProperties,\n dataStrategy: opts?.dataStrategy,\n patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n }).initialize();\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n DataRouterContext as UNSAFE_DataRouterContext,\n DataRouterStateContext as UNSAFE_DataRouterStateContext,\n LocationContext as UNSAFE_LocationContext,\n NavigationContext as UNSAFE_NavigationContext,\n RouteContext as UNSAFE_RouteContext,\n mapRouteProperties as UNSAFE_mapRouteProperties,\n useRouteId as UNSAFE_useRouteId,\n useRoutesImpl as UNSAFE_useRoutesImpl,\n};\n"],"names":["DataRouterContext","React","createContext","DataRouterStateContext","AwaitContext","NavigationContext","LocationContext","RouteContext","outlet","matches","isDataRoute","RouteErrorContext","useInRouterContext","useContext","useLocation","invariant","location","useIsomorphicLayoutEffect","cb","static","useLayoutEffect","useNavigate","router","useDataRouterContext","DataRouterHook","UseNavigateStable","id","useCurrentRouteId","DataRouterStateHook","activeRef","useRef","current","useCallback","to","options","navigate","_extends","fromRouteId","useNavigateStable","dataRouterContext","basename","future","navigator","pathname","locationPathname","routePathnamesJson","JSON","stringify","getResolveToMatches","v7_relativeSplatPath","go","path","resolveTo","parse","relative","joinPaths","replace","push","state","useNavigateUnstable","OutletContext","useOutlet","context","createElement","Provider","value","useResolvedPath","_temp2","useMemo","useRoutes","routes","locationArg","useRoutesImpl","dataRouterState","parentMatches","routeMatch","length","parentParams","params","parentPathnameBase","pathnameBase","route","locationFromContext","_parsedLocationArg$pa","parsedLocationArg","parsePath","startsWith","remainingPathname","parentSegments","split","slice","join","matchRoutes","renderedMatches","_renderMatches","map","match","Object","assign","encodeLocation","search","hash","key","navigationType","NavigationType","Action","Pop","DefaultErrorComponent","error","useRouteError","message","isRouteErrorResponse","status","statusText","Error","stack","preStyles","padding","backgroundColor","Fragment","style","fontStyle","defaultErrorElement","RenderErrorBoundary","Component","constructor","props","super","this","revalidation","undefined","componentDidCatch","errorInfo","console","render","routeContext","children","component","RenderedRoute","_ref","staticContext","errorElement","ErrorBoundary","_deepestRenderedBoundaryId","_dataRouterState","_future","errors","v7_partialHydration","initialized","errorIndex","findIndex","m","UNSAFE_invariant","Math","min","renderFallback","fallbackIndex","i","HydrateFallback","hydrateFallbackElement","loaderData","needsToRunLoader","loader","lazy","reduceRight","index","shouldRenderHydrateFallback","alreadyWarned","concat","getChildren","element","hookName","ctx","useDataRouterState","useRouteContext","thisRoute","_state$errors","UseRouteError","routeId","useAsyncValue","_data","blockerId","startTransitionImpl","DataRoutes","_ref2","Route","_props","Router","_ref5","basenameProp","locationProp","staticProp","navigationContext","locationContext","trailingPathname","stripBasename","AwaitRenderStatus","neverSettledPromise","Promise","AwaitErrorBoundary","resolve","promise","pending","renderError","reject","catch","defineProperty","get","_tracked","success","then","data","_error","AbortedDeferredError","ResolveAwait","_ref8","toRender","createRoutesFromChildren","parentPath","Children","forEach","isValidElement","treePath","type","apply","caseSensitive","action","hasErrorBoundary","shouldRevalidate","handle","mapRouteProperties","updates","_ref7","_ref3","initialEntries","initialIndex","historyRef","createMemoryHistory","v5Compat","history","setStateImpl","useState","v7_startTransition","setState","newState","listen","_ref4","isStatic","UNSAFE_getResolveToMatches","jsonPath","useEffect","fallbackElement","subscribe","createHref","n","opts","preventScrollReset","historyAction","_ref6","UseRouteId","createRouter","v7_prependBasename","hydrationData","dataStrategy","patchRoutesOnNavigation","initialize","UseActionData","UseLoaderData","actionData","shouldBlock","UseBlocker","blockerKey","setBlockerKey","blockerFunction","arg","currentLocation","nextLocation","String","deleteBlocker","getBlocker","blockers","has","IDLE_BLOCKER","_temp","joinedPathname","pattern","matchPath","decodePath","UseMatches","convertRouteMatchToUiMatch","UseNavigation","navigation","UseRevalidator","revalidate","UseRouteLoaderData"],"mappings":";;;;;;;;;;q2BAgFO,MAAMA,EACXC,EAAMC,cAA8C,MAKzCC,EAAyBF,EAAMC,cAE1C,MAKWE,EAAeH,EAAMC,cAAqC,MAyC1DG,EAAoBJ,EAAMC,cACrC,MAYWI,EAAkBL,EAAMC,cACnC,MAaWK,EAAeN,EAAMC,cAAkC,CAClEM,OAAQ,KACRC,QAAS,GACTC,aAAa,IAOFC,EAAoBV,EAAMC,cAAmB,MClFnD,SAASU,IACd,OAA4C,MAArCX,EAAMY,WAAWP,EAC1B,CAYO,SAASQ,IAQd,OANEF,KADFG,EAAAA,kBAAS,GAOFd,EAAMY,WAAWP,GAAiBU,QAC3C,CAkDA,SAASC,EACPC,GAEejB,EAAMY,WAAWR,GAAmBc,QAKjDlB,EAAMmB,gBAAgBF,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AIvC,EAAoBhB,EAAqBC,EAAe4Q,gBACxD1O,EAAQmH,EAAmBjJ,EAAoBwQ,gBACnD,OAAOnS,EAAMmE,SACX,KAAO,CACLiO,WAAY9P,EAAkBjB,OAAO+Q,WACrC3O,MAAOA,EAAMuE,gBAEf,CAAC1F,EAAkBjB,OAAO+Q,WAAY3O,EAAMuE,cAEhD,yCAmCO,SAA4BiD,GAEjC,OADYL,EAAmBjJ,EAAoB0Q,oBACtCtI,WAAWkB,EAC1B"}
|
|
1
|
+
{"version":3,"file":"react-router.production.min.js","sources":["../../lib/router/history.ts","../../lib/router/utils.ts","../../lib/router/router.ts","../../lib/context.ts","../../lib/hooks.tsx","../../lib/server-runtime/warnings.ts","../../lib/components.tsx","../../lib/dom/dom.ts","../../lib/dom/ssr/invariant.ts","../../lib/dom/ssr/routeModules.ts","../../lib/dom/ssr/links.ts","../../lib/dom/ssr/markup.ts","../../lib/dom/ssr/data.ts","../../lib/dom/ssr/single-fetch.tsx","../../lib/dom/ssr/errorBoundaries.tsx","../../lib/dom/ssr/fallback.tsx","../../lib/dom/ssr/routes.tsx","../../lib/dom/ssr/fog-of-war.ts","../../lib/dom/ssr/components.tsx","../../lib/dom/lib.tsx","../../lib/dom/server.tsx","../../lib/dom/ssr/routes-test-stub.tsx","../../lib/server-runtime/crypto.ts","../../lib/server-runtime/cookies.ts","../../lib/server-runtime/entry.ts","../../lib/server-runtime/mode.ts","../../lib/server-runtime/errors.ts","../../lib/server-runtime/routeMatching.ts","../../lib/server-runtime/responses.ts","../../lib/server-runtime/data.ts","../../lib/server-runtime/invariant.ts","../../lib/server-runtime/routes.ts","../../lib/server-runtime/markup.ts","../../lib/server-runtime/serverHandoff.ts","../../lib/server-runtime/dev.ts","../../lib/server-runtime/headers.ts","../../lib/server-runtime/single-fetch.ts","../../lib/server-runtime/server.ts","../../lib/server-runtime/sessions.ts","../../lib/dom/ssr/server.tsx","../../lib/dom/ssr/errors.ts","../../lib/server-runtime/sessions/cookieStorage.ts","../../lib/server-runtime/sessions/memoryStorage.ts"],"sourcesContent":["////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location<State = any> extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: State;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n\n /**\n * The delta between this location and the former location in the history stack\n */\n delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation used in\n * {@link Link}, {@link useNavigate}, etc.\n */\nexport type To = string | Partial<Path>;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n /**\n * The last action that modified the current location. This will always be\n * Action.Pop when a history instance is first created. This value is mutable.\n */\n readonly action: Action;\n\n /**\n * The current location. This value is mutable.\n */\n readonly location: Location;\n\n /**\n * Returns a valid href for the given `to` value that may be used as\n * the value of an <a href> attribute.\n *\n * @param to - The destination URL\n */\n createHref(to: To): string;\n\n /**\n * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial<Location>;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 1 });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route (<Route path=\"*\">) since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant<T>(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\nexport function warning(cond: any, message: string) {\n if (!cond) {\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly<Location> {\n let location: Readonly<Location> = {\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\",\n ...(typeof to === \"string\" ? parsePath(to) : to),\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: (to && (to as Location).key) || key || createKey(),\n };\n return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n *\n * @category Utils\n */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial<Path>) {\n if (search && search !== \"?\")\n pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\")\n pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n *\n * @category Utils\n */\nexport function parsePath(path: string): Partial<Path> {\n let parsedPath: Partial<Path> = {};\n\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n window?: Window;\n v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n createHref: (window: Window, to: To) => string,\n validateLocation: ((location: Location, to: To) => void) | null,\n options: UrlHistoryOptions = {}\n): UrlHistory {\n let { window = document.defaultView!, v5Compat = false } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 1 });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n // Treating this as a full URL will strip any trailing spaces so we need to\n // pre-encode them since they might be part of a matching splat param from\n // an ancestor route\n href = href.replace(/ $/, \"%20\");\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n","import type { JsonFunction } from \"../server-runtime/responses\";\nimport type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: unknown;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n // We keep the raw Response for redirects so we can return it verbatim\n response: Response;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n type: ResultType.error;\n error: unknown;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult = SuccessResult | RedirectResult | ErrorResult;\n\nexport type LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\nexport type UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;\n\n/**\n * Users can specify either lowercase or uppercase form methods on `<Form>`,\n * useSubmit(), `<fetcher.Form>`, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type FormMethod = UpperCaseFormMethod;\nexport type MutationFormMethod = Exclude<FormMethod, \"GET\">;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"application/json\"\n | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n | {\n formMethod: FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: undefined;\n text: string;\n };\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs<Context> {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs<Context = any>\n extends DataFunctionArgs<Context> {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs<Context = any>\n extends DataFunctionArgs<Context> {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable<unknown> | null;\n\ntype DataFunctionReturnValue = Promise<DataFunctionValue> | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction<Context = any> = {\n (\n args: LoaderFunctionArgs<Context>,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction<Context = any> {\n (\n args: ActionFunctionArgs<Context>,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n text?: Submission[\"text\"];\n formData?: Submission[\"formData\"];\n json?: Submission[\"json\"];\n actionStatus?: number;\n actionResult?: any;\n defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\nexport interface DataStrategyMatch\n extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {\n shouldLoad: boolean;\n resolve: (\n handlerOverride?: (\n handler: (ctx?: unknown) => DataFunctionReturnValue\n ) => DataFunctionReturnValue\n ) => Promise<DataStrategyResult>;\n}\n\nexport interface DataStrategyFunctionArgs<Context = any>\n extends DataFunctionArgs<Context> {\n matches: DataStrategyMatch[];\n fetcherKey: string | null;\n}\n\n/**\n * Result from a loader or action called via dataStrategy\n */\nexport interface DataStrategyResult {\n type: \"data\" | \"error\";\n result: unknown; // data, Error, Response, DeferredData, DataWithResponseInit\n}\n\nexport interface DataStrategyFunction {\n (args: DataStrategyFunctionArgs): Promise<Record<string, DataStrategyResult>>;\n}\n\nexport type AgnosticPatchRoutesOnNavigationFunctionArgs<\n O extends AgnosticRouteObject = AgnosticRouteObject,\n M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = {\n path: string;\n matches: M[];\n patch: (routeId: string | null, children: O[]) => void;\n};\n\nexport type AgnosticPatchRoutesOnNavigationFunction<\n O extends AgnosticRouteObject = AgnosticRouteObject,\n M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = (\n opts: AgnosticPatchRoutesOnNavigationFunctionArgs<O, M>\n) => void | Promise<void>;\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record<string, any>;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set<ImmutableRouteKey>([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne<T, Key = keyof T> = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit<T, K> & Required<Pick<T, K>> : never;\n }[keyof T],\n undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction<R extends AgnosticRouteObject> {\n (): Promise<RequireOne<Omit<R, ImmutableRouteKey>>>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n caseSensitive?: boolean;\n path?: string;\n id?: string;\n loader?: LoaderFunction | boolean;\n action?: ActionFunction | boolean;\n hasErrorBoundary?: boolean;\n shouldRevalidate?: ShouldRevalidateFunction;\n handle?: any;\n lazy?: LazyRouteFunction<AgnosticBaseRouteObject>;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record<string, AgnosticDataRouteObject | undefined>;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam<Path extends string> =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam<L> | _PathParam<R>\n : // find params after `:`\n Path extends `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\n : Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam<Path extends string> =\n // check if path is just a wildcard\n Path extends \"*\" | \"/*\"\n ? \"*\"\n : // look for wildcard at the end of the path\n Path extends `${infer Rest}/*`\n ? \"*\" | _PathParam<Rest>\n : // look for params in the absence of wildcards\n _PathParam<Path>;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise, return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey<Segment extends string> =\n // if you could not find path params, fallback to `string`\n [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params<Key extends string = string> = {\n readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params<ParamKey>;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The route object that was used to match.\n */\n route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {}\n\nfunction isIndexRoute(\n route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n routes: AgnosticRouteObject[],\n mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: string[] = [],\n manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, String(index)];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(\n route.index !== true || !route.children,\n `Cannot specify children on an index route`\n );\n invariant(\n !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\n\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @category Utils\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial<Location> | string,\n basename = \"/\"\n): AgnosticRouteMatch<string, RouteObjectType>[] | null {\n return matchRoutesImpl(routes, locationArg, basename, false);\n}\n\nexport function matchRoutesImpl<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial<Location> | string,\n basename: string,\n allowPartial: boolean\n): AgnosticRouteMatch<string, RouteObjectType>[] | null {\n let location =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n let pathname = stripBasename(location.pathname || \"/\", basename);\n\n if (pathname == null) {\n return null;\n }\n\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n\n let matches = null;\n for (let i = 0; matches == null && i < branches.length; ++i) {\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n let decoded = decodePath(pathname);\n matches = matchRouteBranch<string, RouteObjectType>(\n branches[i],\n decoded,\n allowPartial\n );\n }\n\n return matches;\n}\n\nexport interface UIMatch<Data = unknown, Handle = unknown> {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: Data;\n handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UIMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle,\n };\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta<RouteObjectType>[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch<RouteObjectType>[] = [],\n parentsMeta: RouteMeta<RouteObjectType>[] = [],\n parentPath = \"\"\n): RouteBranch<RouteObjectType>[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta<RouteObjectType> = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch<RouteObjectType>,\n pathname: string,\n allowPartial = false\n): AgnosticRouteMatch<ParamKey, RouteObjectType>[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch<ParamKey, RouteObjectType>[] = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname =\n matchedPathname === \"/\"\n ? pathname\n : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath(\n { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n remainingPathname\n );\n\n let route = meta.route;\n\n if (\n !match &&\n end &&\n allowPartial &&\n !routesMeta[routesMeta.length - 1].route.index\n ) {\n match = matchPath(\n {\n path: meta.relativePath,\n caseSensitive: meta.caseSensitive,\n end: false,\n },\n remainingPathname\n );\n }\n\n if (!match) {\n return null;\n }\n\n Object.assign(matchedParams, match.params);\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params<ParamKey>,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(\n joinPaths([matchedPathname, match.pathnameBase])\n ),\n route,\n });\n\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n\n return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @category Utils\n */\nexport function generatePath<Path extends string>(\n originalPath: Path,\n params: {\n [key in PathParam<Path>]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const stringify = (p: any) =>\n p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam<Path>;\n // Apply the splat\n return stringify(params[star]);\n }\n\n const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam<Path>];\n invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n return stringify(param);\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern<Path extends string = string> {\n /**\n * A string to match against a URL pathname. May contain `:id`-style segments\n * to indicate placeholders for dynamic parameters. May also end with `/*` to\n * indicate matching the rest of the URL pathname.\n */\n path: Path;\n /**\n * Should be `true` if the static portions of the `path` should be matched in\n * the same case.\n */\n caseSensitive?: boolean;\n /**\n * Should be `true` if this pattern should match the entire URL pathname.\n */\n end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch<ParamKey extends string = string> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params<ParamKey>;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The pattern that was used to match.\n */\n pattern: PathPattern;\n}\n\ntype Mutable<T> = {\n -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @category Utils\n */\nexport function matchPath<\n ParamKey extends ParamParseKey<Path>,\n Path extends string\n>(\n pattern: PathPattern<Path> | Path,\n pathname: string\n): PathMatch<ParamKey> | null {\n if (typeof pattern === \"string\") {\n pattern = { path: pattern, caseSensitive: false, end: true };\n }\n\n let [matcher, compiledParams] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = compiledParams.reduce<Mutable<Params>>(\n (memo, { paramName, isOptional }, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n }\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, CompiledPathParam[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let params: CompiledPathParam[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(\n /\\/:([\\w-]+)(\\?)?/g,\n (_: string, paramName: string, isOptional) => {\n params.push({ paramName, isOptional: isOptional != null });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n }\n );\n\n if (path.endsWith(\"*\")) {\n params.push({ paramName: \"*\" });\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, params];\n}\n\nexport function decodePath(value: string) {\n try {\n return value\n .split(\"/\")\n .map((v) => decodeURIComponent(v).replace(/\\//g, \"%2F\"))\n .join(\"/\");\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n pathname: string,\n basename: string\n): string | null {\n if (basename === \"/\") return pathname;\n\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\")\n ? basename.length - 1\n : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n\n return pathname.slice(startIndex) || \"/\";\n}\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @category Utils\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\",\n } = typeof to === \"string\" ? parsePath(to) : to;\n\n let pathname = toPathname\n ? toPathname.startsWith(\"/\")\n ? toPathname\n : resolvePathname(toPathname, fromPathname)\n : fromPathname;\n\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash),\n };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n\n relativeSegments.forEach((segment) => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n char: string,\n field: string,\n dest: string,\n path: Partial<Path>\n) {\n return (\n `Cannot include a '${char}' character in a manually specified ` +\n `\\`to.${field}\\` field [${JSON.stringify(\n path\n )}]. Please separate it out to the ` +\n `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n `a string in <Link to=\"...\"> and the router will parse it for you.`\n );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * <Route path=\"/\">\n * <Route path=\"accounts\" element={<Link to=\"..\"}>\n * </Route>\n *\n * <Route path=\"/\">\n * <Route path=\"accounts\">\n * <Route element={<AccountsLayout />}> // <-- Does not contribute\n * <Route index element={<Link to=\"..\"} /> // <-- Does not contribute\n * </Route\n * </Route>\n * </Route>\n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\n );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n let pathMatches = getPathContributingMatches(matches);\n\n // Use the full pathname for the leaf match so we include splat values for \".\" links\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n return pathMatches.map((match, idx) =>\n idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase\n );\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial<Path>;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = { ...toArg };\n\n invariant(\n !to.pathname || !to.pathname.includes(\"?\"),\n getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n );\n invariant(\n !to.pathname || !to.pathname.includes(\"#\"),\n getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n );\n invariant(\n !to.search || !to.search.includes(\"#\"),\n getInvalidPathError(\"#\", \"search\", \"hash\", to)\n );\n }\n\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n let from: string;\n\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `<Link to>` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how <a href> works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n if (!isPathRelative && toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n !search || search === \"?\"\n ? \"\"\n : search.startsWith(\"?\")\n ? search\n : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n *\n * @category Utils\n */\nexport const json: JsonFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n\n return new Response(JSON.stringify(data), {\n ...responseInit,\n headers,\n });\n};\n\nexport class DataWithResponseInit<D> {\n type: string = \"DataWithResponseInit\";\n data: D;\n init: ResponseInit | null;\n\n constructor(data: D, init?: ResponseInit) {\n this.data = data;\n this.init = init || null;\n }\n}\n\n/**\n * Create \"responses\" that contain `status`/`headers` without forcing\n * serialization into an actual `Response` - used by Remix single fetch\n *\n * @category Utils\n */\nexport function data<D>(data: D, init?: number | ResponseInit) {\n return new DataWithResponseInit(\n data,\n typeof init === \"number\" ? { status: init } : init\n );\n}\n\nexport interface TrackedPromise extends Promise<any> {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n *\n * @category Utils\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n *\n * @category Utils\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n\n/**\n * A redirect response that will perform a `history.replaceState` instead of a\n * `history.pushState` for client-side navigation redirects.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n *\n * @category Utils\n */\nexport const replace: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Replace\", \"true\");\n return response;\n};\n\nexport type ErrorResponse = {\n status: number;\n statusText: string;\n data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n private error?: Error;\n private internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n *\n * @category Utils\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as NavigationType,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n DataStrategyMatch,\n AgnosticRouteObject,\n DataResult,\n DataStrategyFunction,\n DataStrategyFunctionArgs,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n DataStrategyResult,\n ImmutableRouteKey,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n AgnosticPatchRoutesOnNavigationFunction,\n DataWithResponseInit,\n} from \"./utils\";\nimport {\n ErrorResponseImpl,\n ResultType,\n convertRouteMatchToUiMatch,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n getResolveToMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n matchRoutesImpl,\n resolveTo,\n stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Return the future config for the router\n */\n get future(): FutureConfig;\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record<string, number>,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): Promise<void>;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ): Promise<void>;\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): Promise<void>;\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher<TData = any>(key: string): Fetcher<TData>;\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Delete the fetcher for a given key\n * @param key\n */\n deleteFetcher(key: string): void;\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @private\n * PRIVATE DO NOT USE\n *\n * Patch additional children routes into an existing parent route\n * @param routeId The parent route id or a callback function accepting `patch`\n * to perform batch patching\n * @param children The additional children routes\n */\n patchRoutes(routeId: string | null, children: AgnosticRouteObject[]): void;\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n /**\n * @private\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map<string, AbortController>;\n}\n\n/**\n * State maintained internally by the router. During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n // TODO: (v7) should we consider renaming this `navigationType` to align with\n // `useNavigationType` at some point?\n /**\n * The action of the most recent navigation\n */\n historyAction: NavigationType;\n\n /**\n * The current location reflected by the router\n */\n location: Location;\n\n /**\n * The current set of route matches\n */\n matches: AgnosticDataRouteMatch[];\n\n /**\n * Tracks whether we've completed our initial data load\n */\n initialized: boolean;\n\n /**\n * Current scroll position we should start at for a new view\n * - number -> scroll position to restore to\n * - false -> do not restore scroll at all (used during submissions)\n * - null -> don't have a saved position, scroll to hash or top of page\n */\n restoreScrollPosition: number | false | null;\n\n /**\n * Indicate whether this navigation should skip resetting the scroll position\n * if we are unable to restore the scroll position\n */\n preventScrollReset: boolean;\n\n /**\n * Tracks the state of the current navigation\n */\n navigation: Navigation;\n\n /**\n * Tracks any in-progress revalidations\n */\n revalidation: RevalidationState;\n\n /**\n * Data from the loaders for the current matches\n */\n loaderData: RouteData;\n\n /**\n * Data from the action for the current matches\n */\n actionData: RouteData | null;\n\n /**\n * Errors caught from loaders for the current matches\n */\n errors: RouteData | null;\n\n /**\n * Map of current fetchers\n */\n fetchers: Map<string, Fetcher>;\n\n /**\n * Map of current blockers\n */\n blockers: Map<string, Blocker>;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick<RouterState, \"loaderData\" | \"actionData\" | \"errors\">\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial<FutureConfig>;\n hydrationData?: HydrationState;\n window?: Window;\n dataStrategy?: DataStrategyFunction;\n patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record<string, Headers>;\n actionHeaders: Record<string, Headers>;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(\n request: Request,\n opts?: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n dataStrategy?: DataStrategyFunction;\n }\n ): Promise<StaticHandlerContext | Response>;\n queryRoute(\n request: Request,\n opts?: {\n routeId?: string;\n requestContext?: unknown;\n dataStrategy?: DataStrategyFunction;\n }\n ): Promise<any>;\n}\n\ntype ViewTransitionOpts = {\n currentLocation: Location;\n nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (\n state: RouterState,\n opts: {\n deletedFetchers: string[];\n viewTransitionOpts?: ViewTransitionOpts;\n flushSync: boolean;\n }\n ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\n/**\n - \"route\": relative to the route hierarchy so `..` means remove all segments of the current route even if it has many. For example, a `route(\"posts/:id\")` would have both `:id` and `posts` removed from the url.\n - \"path\": relative to the pathname so `..` means remove one segment of the pathname. For example, a `route(\"posts/:id\")` would have only `:id` removed from the url.\n */\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n} & (\n | { formData: FormData; body?: undefined }\n | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n json: undefined;\n text: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n text: Submission[\"text\"] | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n text: Submission[\"text\"];\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\nexport type FetcherStates<TData = any> = {\n /**\n * The fetcher is not calling a loader or action\n *\n * ```tsx\n * fetcher.state === \"idle\"\n * ```\n */\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n /**\n * If the fetcher has never been called, this will be undefined.\n */\n data: TData | undefined;\n };\n\n /**\n * The fetcher is loading data from a {@link LoaderFunction | loader} from a\n * call to {@link FetcherWithComponents.load | `fetcher.load`}.\n *\n * ```tsx\n * // somewhere\n * <button onClick={() => fetcher.load(\"/some/route\") }>Load</button>\n *\n * // the state will update\n * fetcher.state === \"loading\"\n * ```\n */\n Loading: {\n state: \"loading\";\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n text: Submission[\"text\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n data: TData | undefined;\n };\n\n /**\n 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`}.\n\n ```tsx\n // somewhere\n <input\n onChange={e => {\n fetcher.submit(event.currentTarget.form, { method: \"post\" });\n }}\n />\n\n // the state will update\n fetcher.state === \"submitting\"\n\n // and formData will be available\n fetcher.formData\n ```\n */\n Submitting: {\n state: \"submitting\";\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n text: Submission[\"text\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n data: TData | undefined;\n };\n};\n\nexport type Fetcher<TData = any> =\n FetcherStates<TData>[keyof FetcherStates<TData>];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: NavigationType;\n}) => boolean;\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\ntype PendingActionResult = [string, SuccessResult | ErrorResult];\n\ninterface HandleActionResult extends ShortCircuitable {\n /**\n * Route matches which may have been updated from fog of war discovery\n */\n matches?: RouterState[\"matches\"];\n /**\n * Tuple for the returned or thrown value from the current action. The routeId\n * is the action route for success and the bubbled boundary route for errors.\n */\n pendingActionResult?: PendingActionResult;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n /**\n * Route matches which may have been updated from fog of war discovery\n */\n matches?: RouterState[\"matches\"];\n /**\n * loaderData returned from the current set of loaders\n */\n loaderData?: RouterState[\"loaderData\"];\n /**\n * errors thrown from the current set of loaders\n */\n errors?: RouterState[\"errors\"];\n}\n\n/**\n * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"POST\",\n \"PUT\",\n \"PATCH\",\n \"DELETE\",\n];\nconst validMutationMethods = new Set<MutationFormMethod>(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"GET\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set<FormMethod>(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n// Flag used on new `loaderData` to indicate that we do not want to preserve\n// any prior loader data from the throwing route in `mergeLoaderData`\nconst ResetLoaderDataSymbol = Symbol(\"ResetLoaderData\");\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n const routerWindow = init.window\n ? init.window\n : typeof window !== \"undefined\"\n ? window\n : undefined;\n const isBrowser =\n typeof routerWindow !== \"undefined\" &&\n typeof routerWindow.document !== \"undefined\" &&\n typeof routerWindow.document.createElement !== \"undefined\";\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties = init.mapRouteProperties || defaultMapRouteProperties;\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;\n let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;\n\n // Config driven behavior flags\n let future: FutureConfig = {\n ...init.future,\n };\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set<RouterSubscriber>();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record<string, number> | null = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition: GetScrollPositionFunction | null = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from <ScrollRestoration /> until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialErrors: RouteData | null = null;\n\n if (initialMatches == null && !patchRoutesOnNavigationImpl) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and\n // our initial match is a splat route, clear them out so we run through lazy\n // discovery on hydration in case there's a more accurate lazy route match.\n // In SSR apps (with `hydrationData`), we expect that the server will send\n // up the proper matched routes so we don't want to run lazy discovery on\n // initial hydration and want to hydrate into the splat route.\n if (initialMatches && !init.hydrationData) {\n let fogOfWar = checkFogOfWar(\n initialMatches,\n dataRoutes,\n init.history.location.pathname\n );\n if (fogOfWar.active) {\n initialMatches = null;\n }\n }\n\n let initialized: boolean;\n if (!initialMatches) {\n initialized = false;\n initialMatches = [];\n\n // If partial hydration and fog of war is enabled, we will be running\n // `patchRoutesOnNavigation` during hydration so include any partial matches as\n // the initial matches so we can properly render `HydrateFallback`'s\n let fogOfWar = checkFogOfWar(\n null,\n dataRoutes,\n init.history.location.pathname\n );\n if (fogOfWar.active && fogOfWar.matches) {\n initialMatches = fogOfWar.matches;\n }\n } else if (initialMatches.some((m) => m.route.lazy)) {\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n initialized = false;\n } else if (!initialMatches.some((m) => m.route.loader)) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else {\n // With \"partial hydration\", we're initialized so long as we were\n // provided with hydrationData for every route with a loader, and no loaders\n // were marked for explicit hydration\n let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n let errors = init.hydrationData ? init.hydrationData.errors : null;\n // If errors exist, don't consider routes below the boundary\n if (errors) {\n let idx = initialMatches.findIndex(\n (m) => errors![m.route.id] !== undefined\n );\n initialized = initialMatches\n .slice(0, idx + 1)\n .every((m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors));\n } else {\n initialized = initialMatches.every(\n (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)\n );\n }\n }\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n blockers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: NavigationType = NavigationType.Pop;\n\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions: Map<string, Set<string>> = new Map<\n string,\n Set<string>\n >();\n\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener: (() => void) | null = null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: Set<string> = new Set();\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map<string, AbortController>();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map<string, number>();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set<string>();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map<string, FetchLoadMatch>();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map<string, number>();\n\n // Fetchers queued for deletion because they've been removed from the UI.\n // These will be officially deleted after they return to idle\n let fetchersQueuedForDeletion = new Set<string>();\n\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map<string, BlockerFunction>();\n\n // Map of pending patchRoutesOnNavigation() promises (keyed by path/matches) so\n // that we only kick them off once for a given combo\n let pendingPatchRoutes = new Map<\n string,\n ReturnType<AgnosticPatchRoutesOnNavigationFunction>\n >();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let unblockBlockerHistoryUpdate: (() => void) | undefined = undefined;\n\n let pendingRevalidationDfd: ReturnType<typeof createDeferred<void>> | null =\n null;\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (unblockBlockerHistoryUpdate) {\n unblockBlockerHistoryUpdate();\n unblockBlockerHistoryUpdate = undefined;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n let nextHistoryUpdatePromise = new Promise<void>((resolve) => {\n unblockBlockerHistoryUpdate = resolve;\n });\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked, after the url\n // restoration is also complete. See:\n // https://github.com/remix-run/react-router/issues/11613\n nextHistoryUpdatePromise.then(() => init.history.go(delta));\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () =>\n persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () =>\n routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallback\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(NavigationType.Pop, state.location, {\n initialHydration: true,\n });\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(\n newState: Partial<RouterState>,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Cleanup for all fetchers that have returned to idle since we only\n // care about in-flight fetchers\n // - If it's been unmounted then we can completely delete it\n // - If it's still mounted we can remove it from `state.fetchers`, but we\n // need to keep it around in thing like `fetchLoadMatches`, etc. since\n // it may be called again\n let unmountedFetchers: string[] = [];\n let mountedFetchers: string[] = [];\n\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (fetchersQueuedForDeletion.has(key)) {\n unmountedFetchers.push(key);\n } else {\n mountedFetchers.push(key);\n }\n }\n });\n\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach((subscriber) =>\n subscriber(state, {\n deletedFetchers: unmountedFetchers,\n viewTransitionOpts: opts.viewTransitionOpts,\n flushSync: opts.flushSync === true,\n })\n );\n\n // Cleanup internally now that we've called our subscribers/updated state\n unmountedFetchers.forEach((key) => deleteFetcher(key));\n mountedFetchers.forEach((key) => state.fetchers.delete(key));\n }\n\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(\n location: Location,\n newState: Partial<Omit<RouterState, \"action\" | \"location\" | \"navigation\">>,\n { flushSync }: { flushSync?: boolean } = {}\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n // Commit any in-flight routes at the end of the HMR revalidation \"navigation\"\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === NavigationType.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === NavigationType.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === NavigationType.Replace) {\n init.history.replace(location, location.state);\n }\n\n let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === NavigationType.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location,\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set<string>([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n }\n\n updateState(\n {\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers,\n },\n {\n viewTransitionOpts,\n flushSync: flushSync === true,\n }\n );\n\n // Reset stateful navigation vars\n pendingAction = NavigationType.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n pendingRevalidationDfd?.resolve();\n pendingRevalidationDfd = null;\n }\n\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(\n to: number | To | null,\n opts?: RouterNavigateOptions\n ) {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n to,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = NavigationType.Push;\n\n if (userReplace === true) {\n historyAction = NavigationType.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = NavigationType.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.flushSync) === true;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.viewTransition,\n flushSync,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n // We can't just return the promise from `startNavigation` because that\n // navigation may be interrupted and our revalidation wouldn't be finished\n // until the _next_ navigation completes. Instead we just track via a\n // deferred and resolve it the next time we run through `completeNavigation`\n // This is different than navigations which will settle if interrupted\n // because the navigation to a specific location is no longer relevant.\n // Revalidations are location-independent and will settle whenever we land\n // on our final location\n if (!pendingRevalidationDfd) {\n pendingRevalidationDfd = createDeferred<void>();\n }\n\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // Capture this here for the edge-case that we have a fully synchronous\n // startNavigation which would resolve and null out pendingRevalidationDfd\n // before we return from this function\n let promise = pendingRevalidationDfd.promise;\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return promise;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return promise;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n {\n overrideNavigation: state.navigation,\n // Proxy through any rending view transition\n enableViewTransition: pendingViewTransitionEnabled === true,\n }\n );\n return promise;\n }\n\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(\n historyAction: NavigationType,\n location: Location,\n opts?: {\n initialHydration?: boolean;\n submission?: Submission;\n fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponseImpl;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n enableViewTransition?: boolean;\n flushSync?: boolean;\n }\n ): Promise<void> {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n\n let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let { error, notFoundMatches, route } = handleNavigational404(\n location.pathname\n );\n completeNavigation(\n location,\n {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n },\n { flushSync }\n );\n return;\n }\n\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial hydration will always\n // be \"same hash\". For example, on /page#hash and submit a <Form method=\"post\">\n // which will default to a navigation to /page\n if (\n state.initialized &&\n !isRevalidationRequired &&\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches }, { flushSync });\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let pendingActionResult: PendingActionResult | undefined;\n\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingActionResult = [\n findNearestBoundary(matches).route.id,\n { type: ResultType.error, error: opts.pendingError },\n ];\n } else if (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\n // Call action if we received an action submission\n let actionResult = await handleAction(\n request,\n location,\n opts.submission,\n matches,\n fogOfWar.active,\n { replace: opts.replace, flushSync }\n );\n\n if (actionResult.shortCircuited) {\n return;\n }\n\n // If we received a 404 from handleAction, it's because we couldn't lazily\n // discover the destination route so we don't want to call loaders\n if (actionResult.pendingActionResult) {\n let [routeId, result] = actionResult.pendingActionResult;\n if (\n isErrorResult(result) &&\n isRouteErrorResponse(result.error) &&\n result.error.status === 404\n ) {\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches: actionResult.matches,\n loaderData: {},\n errors: {\n [routeId]: result.error,\n },\n });\n return;\n }\n }\n\n matches = actionResult.matches || matches;\n pendingActionResult = actionResult.pendingActionResult;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n // No need to do fog of war matching again on loader execution\n fogOfWar.active = false;\n\n // Create a GET request for the loaders\n request = createClientSideRequest(\n init.history,\n request.url,\n request.signal\n );\n }\n\n // Call loaders\n let {\n shortCircuited,\n matches: updatedMatches,\n loaderData,\n errors,\n } = await handleLoaders(\n request,\n location,\n matches,\n fogOfWar.active,\n loadingNavigation,\n opts && opts.submission,\n opts && opts.fetcherSubmission,\n opts && opts.replace,\n opts && opts.initialHydration === true,\n flushSync,\n pendingActionResult\n );\n\n if (shortCircuited) {\n return;\n }\n\n // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches: updatedMatches || matches,\n ...getActionDataForCommit(pendingActionResult),\n loaderData,\n errors,\n });\n }\n\n // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n async function handleAction(\n request: Request,\n location: Location,\n submission: Submission,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n opts: { replace?: boolean; flushSync?: boolean } = {}\n ): Promise<HandleActionResult> {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n matches,\n location.pathname,\n request.signal\n );\n if (discoverResult.type === \"aborted\") {\n return { shortCircuited: true };\n } else if (discoverResult.type === \"error\") {\n let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n .route.id;\n return {\n matches: discoverResult.partialMatches,\n pendingActionResult: [\n boundaryId,\n {\n type: ResultType.error,\n error: discoverResult.error,\n },\n ],\n };\n } else if (!discoverResult.matches) {\n let { notFoundMatches, error, route } = handleNavigational404(\n location.pathname\n );\n return {\n matches: notFoundMatches,\n pendingActionResult: [\n route.id,\n {\n type: ResultType.error,\n error,\n },\n ],\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n let results = await callDataStrategy(\n \"action\",\n state,\n request,\n [actionMatch],\n matches,\n null\n );\n result = results[actionMatch.route.id];\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n let location = normalizeRedirectLocation(\n result.response.headers.get(\"Location\")!,\n new URL(request.url),\n basename\n );\n replace = location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(request, result, true, {\n submission,\n replace,\n });\n return { shortCircuited: true };\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n // By default, all submissions to the current location are REPLACE\n // navigations, but if the action threw an error that'll be rendered in\n // an errorElement, we fall back to PUSH so that the user can use the\n // back button to get back to the pre-submission form location to try\n // again\n if ((opts && opts.replace) !== true) {\n pendingAction = NavigationType.Push;\n }\n\n return {\n matches,\n pendingActionResult: [boundaryMatch.route.id, result],\n };\n }\n\n return {\n matches,\n pendingActionResult: [actionMatch.route.id, result],\n };\n }\n\n // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n async function handleLoaders(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n overrideNavigation?: Navigation,\n submission?: Submission,\n fetcherSubmission?: Submission,\n replace?: boolean,\n initialHydration?: boolean,\n flushSync?: boolean,\n pendingActionResult?: PendingActionResult\n ): Promise<HandleLoadersResult> {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation =\n overrideNavigation || getLoadingNavigation(location, submission);\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission ||\n fetcherSubmission ||\n getSubmissionFromNavigation(loadingNavigation);\n\n // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n // Also (with \"partial hydration\"), don't update the state for the initial\n // data load since it's not a \"navigation\"\n let shouldUpdateNavigationState =\n !isUninterruptedRevalidation && !initialHydration;\n\n // When fog of war is enabled, we enter our `loading` state earlier so we\n // can discover new routes during the `loading` state. We skip this if\n // we've already run actions since we would have done our matching already.\n // If the children() function threw then, we want to proceed with the\n // partial matches it discovered.\n if (isFogOfWar) {\n if (shouldUpdateNavigationState) {\n let actionData = getUpdatedActionData(pendingActionResult);\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData !== undefined ? { actionData } : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n let discoverResult = await discoverRoutes(\n matches,\n location.pathname,\n request.signal\n );\n\n if (discoverResult.type === \"aborted\") {\n return { shortCircuited: true };\n } else if (discoverResult.type === \"error\") {\n let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n .route.id;\n return {\n matches: discoverResult.partialMatches,\n loaderData: {},\n errors: {\n [boundaryId]: discoverResult.error,\n },\n };\n } else if (!discoverResult.matches) {\n let { error, notFoundMatches, route } = handleNavigational404(\n location.pathname\n );\n return {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n initialHydration === true,\n isRevalidationRequired,\n cancelledFetcherLoads,\n fetchersQueuedForDeletion,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionResult\n );\n\n pendingNavigationLoadId = ++incrementingLoadId;\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(\n location,\n {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors:\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? { [pendingActionResult[0]]: pendingActionResult[1].error }\n : null,\n ...getActionDataForCommit(pendingActionResult),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n },\n { flushSync }\n );\n return { shortCircuited: true };\n }\n\n if (shouldUpdateNavigationState) {\n let updates: Partial<RouterState> = {};\n if (!isFogOfWar) {\n // Only update navigation/actionNData if we didn't already do it above\n updates.navigation = loadingNavigation;\n let actionData = getUpdatedActionData(pendingActionResult);\n if (actionData !== undefined) {\n updates.actionData = actionData;\n }\n }\n if (revalidatingFetchers.length > 0) {\n updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);\n }\n updateState(updates, { flushSync });\n }\n\n revalidatingFetchers.forEach((rf) => {\n abortFetcher(rf.key);\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(loaderResults);\n if (redirect) {\n await startRedirectNavigation(request, redirect.result, true, {\n replace,\n });\n return { shortCircuited: true };\n }\n\n redirect = findRedirect(fetcherResults);\n if (redirect) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n fetchRedirectIds.add(redirect.key);\n await startRedirectNavigation(request, redirect.result, true, {\n replace,\n });\n return { shortCircuited: true };\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n loaderResults,\n pendingActionResult,\n revalidatingFetchers,\n fetcherResults\n );\n\n // Preserve SSR errors during partial hydration\n if (initialHydration && state.errors) {\n errors = { ...state.errors, ...errors };\n }\n\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n matches,\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n function getUpdatedActionData(\n pendingActionResult: PendingActionResult | undefined\n ): Record<string, RouteData> | null | undefined {\n if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {\n // This is cast to `any` currently because `RouteData`uses any and it\n // would be a breaking change to use any.\n // TODO: v7 - change `RouteData` to use `unknown` instead of `any`\n return {\n [pendingActionResult[0]]: pendingActionResult[1].data as any,\n };\n } else if (state.actionData) {\n if (Object.keys(state.actionData).length === 0) {\n return null;\n } else {\n return state.actionData;\n }\n }\n }\n\n function getUpdatedRevalidatingFetchers(\n revalidatingFetchers: RevalidatingFetcher[]\n ) {\n revalidatingFetchers.forEach((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n fetcher ? fetcher.data : undefined\n );\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n return new Map(state.fetchers);\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n async function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n abortFetcher(key);\n\n let flushSync = (opts && opts.flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n href,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath }),\n { flushSync }\n );\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(\n true,\n normalizedPath,\n opts\n );\n\n if (error) {\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n let match = getTargetMatch(matches, path);\n\n let preventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n await handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n fogOfWar.active,\n flushSync,\n preventScrollReset,\n submission\n );\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, { routeId, path });\n await handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n fogOfWar.active,\n flushSync,\n preventScrollReset,\n submission\n );\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n requestMatches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n flushSync: boolean,\n preventScrollReset: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n function detectAndHandle405Error(m: AgnosticDataRouteMatch) {\n if (!m.route.action && !m.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\n setFetcherError(key, routeId, error, { flushSync });\n return true;\n }\n return false;\n }\n\n if (!isFogOfWar && detectAndHandle405Error(match)) {\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync,\n });\n\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n requestMatches,\n path,\n fetchRequest.signal\n );\n\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n setFetcherError(key, routeId, discoverResult.error, { flushSync });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: path }),\n { flushSync }\n );\n return;\n } else {\n requestMatches = discoverResult.matches;\n match = getTargetMatch(requestMatches, path);\n\n if (detectAndHandle405Error(match)) {\n return;\n }\n }\n }\n\n // Call the action for the fetcher\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResults = await callDataStrategy(\n \"action\",\n state,\n fetchRequest,\n [match],\n requestMatches,\n key\n );\n let actionResult = actionResults[match.route.id];\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n // We don't want errors bubbling up to the UI or redirects processed for\n // unmounted fetchers so we just revert them to idle\n if (fetchersQueuedForDeletion.has(key)) {\n if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // Let SuccessResult's fall through for revalidation\n } else {\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(fetchRequest, actionResult, false, {\n fetcherSubmission: submission,\n preventScrollReset,\n });\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(\n init.history,\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n false,\n isRevalidationRequired,\n cancelledFetcherLoads,\n fetchersQueuedForDeletion,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n [match.route.id, actionResult]\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(staleKey, revalidatingFetcher);\n abortFetcher(staleKey);\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect(loaderResults);\n if (redirect) {\n return startRedirectNavigation(\n revalidationRequest,\n redirect.result,\n false,\n { preventScrollReset }\n );\n }\n\n redirect = findRedirect(fetcherResults);\n if (redirect) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n fetchRedirectIds.add(redirect.key);\n return startRedirectNavigation(\n revalidationRequest,\n redirect.result,\n false,\n { preventScrollReset }\n );\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults\n );\n\n // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n\n abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n fetchers: new Map(state.fetchers),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n flushSync: boolean,\n preventScrollReset: boolean,\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(\n key,\n getLoadingFetcher(\n submission,\n existingFetcher ? existingFetcher.data : undefined\n ),\n { flushSync }\n );\n\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n matches,\n path,\n fetchRequest.signal\n );\n\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n setFetcherError(key, routeId, discoverResult.error, { flushSync });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: path }),\n { flushSync }\n );\n return;\n } else {\n matches = discoverResult.matches;\n match = getTargetMatch(matches, path);\n }\n }\n\n // Call the loader for this fetcher route match\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let results = await callDataStrategy(\n \"loader\",\n state,\n fetchRequest,\n [match],\n matches,\n key\n );\n let result = results[match.route.id];\n\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n // We don't want errors bubbling up or redirects followed for unmounted\n // fetchers, so short circuit here if it was removed from the UI\n if (fetchersQueuedForDeletion.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(fetchRequest, result, false, {\n preventScrollReset,\n });\n return;\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n request: Request,\n redirect: RedirectResult,\n isNavigation: boolean,\n {\n submission,\n fetcherSubmission,\n preventScrollReset,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n preventScrollReset?: boolean;\n replace?: boolean;\n } = {}\n ) {\n if (redirect.response.headers.has(\"X-Remix-Revalidate\")) {\n isRevalidationRequired = true;\n }\n\n let location = redirect.response.headers.get(\"Location\");\n invariant(location, \"Expected a Location header on the redirect Response\");\n location = normalizeRedirectLocation(\n location,\n new URL(request.url),\n basename\n );\n let redirectLocation = createLocation(state.location, location, {\n _isRedirect: true,\n });\n\n if (isBrowser) {\n let isDocumentReload = false;\n\n if (redirect.response.headers.has(\"X-Remix-Reload-Document\")) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(location)) {\n const url = init.history.createURL(location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(location);\n } else {\n routerWindow.location.assign(location);\n }\n return;\n }\n }\n\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectNavigationType =\n replace === true || redirect.response.headers.has(\"X-Remix-Replace\")\n ? NavigationType.Replace\n : NavigationType.Push;\n\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let { formMethod, formAction, formEncType } = state.navigation;\n if (\n !submission &&\n !fetcherSubmission &&\n formMethod &&\n formAction &&\n formEncType\n ) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (\n redirectPreserveMethodStatusCodes.has(redirect.response.status) &&\n activeSubmission &&\n isMutationMethod(activeSubmission.formMethod)\n ) {\n await startNavigation(redirectNavigationType, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: location,\n },\n // Preserve these flags across redirects\n preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n enableViewTransition: isNavigation\n ? pendingViewTransitionEnabled\n : undefined,\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(\n redirectLocation,\n submission\n );\n await startNavigation(redirectNavigationType, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve these flags across redirects\n preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n enableViewTransition: isNavigation\n ? pendingViewTransitionEnabled\n : undefined,\n });\n }\n }\n\n // Utility wrapper for calling dataStrategy client-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(\n type: \"loader\" | \"action\",\n state: RouterState,\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n fetcherKey: string | null\n ): Promise<Record<string, DataResult>> {\n let results: Record<string, DataStrategyResult>;\n let dataResults: Record<string, DataResult> = {};\n try {\n results = await callDataStrategyImpl(\n dataStrategyImpl,\n type,\n state,\n request,\n matchesToLoad,\n matches,\n fetcherKey,\n manifest,\n mapRouteProperties\n );\n } catch (e) {\n // If the outer dataStrategy method throws, just return the error for all\n // matches - and it'll naturally bubble to the root\n matchesToLoad.forEach((m) => {\n dataResults[m.route.id] = {\n type: ResultType.error,\n error: e,\n };\n });\n return dataResults;\n }\n\n for (let [routeId, result] of Object.entries(results)) {\n if (isRedirectDataStrategyResultResult(result)) {\n let response = result.result as Response;\n dataResults[routeId] = {\n type: ResultType.redirect,\n response: normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n routeId,\n matches,\n basename\n ),\n };\n } else {\n dataResults[routeId] = await convertDataStrategyResultToDataResult(\n result\n );\n }\n }\n\n return dataResults;\n }\n\n async function callLoadersAndMaybeResolveData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n let currentMatches = state.matches;\n\n // Kick off loaders and fetchers in parallel\n let loaderResultsPromise = callDataStrategy(\n \"loader\",\n state,\n request,\n matchesToLoad,\n matches,\n null\n );\n\n let fetcherResultsPromise = Promise.all(\n fetchersToLoad.map(async (f) => {\n if (f.matches && f.match && f.controller) {\n let results = await callDataStrategy(\n \"loader\",\n state,\n createClientSideRequest(init.history, f.path, f.controller.signal),\n [f.match],\n f.matches,\n f.key\n );\n let result = results[f.match.route.id];\n // Fetcher results are keyed by fetcher key from here on out, not routeId\n return { [f.key]: result };\n } else {\n return Promise.resolve({\n [f.key]: {\n type: ResultType.error,\n error: getInternalRouterError(404, {\n pathname: f.path,\n }),\n } as ErrorResult,\n });\n }\n })\n );\n\n let loaderResults = await loaderResultsPromise;\n let fetcherResults = (await fetcherResultsPromise).reduce(\n (acc, r) => Object.assign(acc, r),\n {}\n );\n\n return {\n loaderResults,\n fetcherResults,\n };\n }\n\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true;\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.add(key);\n }\n abortFetcher(key);\n });\n }\n\n function updateFetcherState(\n key: string,\n fetcher: Fetcher,\n opts: { flushSync?: boolean } = {}\n ) {\n state.fetchers.set(key, fetcher);\n updateState(\n { fetchers: new Map(state.fetchers) },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function setFetcherError(\n key: string,\n routeId: string,\n error: any,\n opts: { flushSync?: boolean } = {}\n ) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState(\n {\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function getFetcher<TData = any>(key: string): Fetcher<TData> {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (fetchersQueuedForDeletion.has(key)) {\n fetchersQueuedForDeletion.delete(key);\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n function deleteFetcher(key: string): void {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (\n fetchControllers.has(key) &&\n !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n ) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n fetchersQueuedForDeletion.delete(key);\n cancelledFetcherLoads.delete(key);\n state.fetchers.delete(key);\n }\n\n function queueFetcherForDeletion(key: string): void {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n fetchersQueuedForDeletion.add(key);\n } else {\n activeFetchers.set(key, count);\n }\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n if (controller) {\n controller.abort();\n fetchControllers.delete(key);\n }\n }\n\n function markFetchersDone(keys: string[]) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({ blockers });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: NavigationType;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\n }\n\n function handleNavigational404(pathname: string) {\n let error = getInternalRouterError(404, { pathname });\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let { matches, route } = getShortCircuitMatches(routesToUse);\n\n return { notFoundMatches: matches, route, error };\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the <ScrollRestoration> component\n function enableScrollRestoration(\n positions: Record<string, number>,\n getPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || null;\n\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered <ScrollRestoration/>\n // and therefore have no savedScrollPositions available\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({ restoreScrollPosition: y });\n }\n }\n\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n\n function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(\n location,\n matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n );\n return key || location.key;\n }\n return location.key;\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function checkFogOfWar(\n matches: AgnosticDataRouteMatch[] | null,\n routesToUse: AgnosticDataRouteObject[],\n pathname: string\n ): { active: boolean; matches: AgnosticDataRouteMatch[] | null } {\n if (patchRoutesOnNavigationImpl) {\n if (!matches) {\n let fogMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n routesToUse,\n pathname,\n basename,\n true\n );\n\n return { active: true, matches: fogMatches || [] };\n } else {\n if (Object.keys(matches[0].params).length > 0) {\n // If we matched a dynamic param or a splat, it might only be because\n // we haven't yet discovered other routes that would match with a\n // higher score. Call patchRoutesOnNavigation just to be sure\n let partialMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n routesToUse,\n pathname,\n basename,\n true\n );\n return { active: true, matches: partialMatches };\n }\n }\n }\n\n return { active: false, matches: null };\n }\n\n type DiscoverRoutesSuccessResult = {\n type: \"success\";\n matches: AgnosticDataRouteMatch[] | null;\n };\n type DiscoverRoutesErrorResult = {\n type: \"error\";\n error: any;\n partialMatches: AgnosticDataRouteMatch[];\n };\n type DiscoverRoutesAbortedResult = { type: \"aborted\" };\n type DiscoverRoutesResult =\n | DiscoverRoutesSuccessResult\n | DiscoverRoutesErrorResult\n | DiscoverRoutesAbortedResult;\n\n async function discoverRoutes(\n matches: AgnosticDataRouteMatch[],\n pathname: string,\n signal: AbortSignal\n ): Promise<DiscoverRoutesResult> {\n if (!patchRoutesOnNavigationImpl) {\n return { type: \"success\", matches };\n }\n\n let partialMatches: AgnosticDataRouteMatch[] | null = matches;\n while (true) {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let localManifest = manifest;\n try {\n await patchRoutesOnNavigationImpl({\n path: pathname,\n matches: partialMatches,\n patch: (routeId, children) => {\n if (signal.aborted) return;\n patchRoutesImpl(\n routeId,\n children,\n routesToUse,\n localManifest,\n mapRouteProperties\n );\n },\n });\n } catch (e) {\n return { type: \"error\", error: e, partialMatches };\n } finally {\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity so when we `updateState` at the end of\n // this navigation/fetch `router.routes` will be a new identity and\n // trigger a re-run of memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR && !signal.aborted) {\n dataRoutes = [...dataRoutes];\n }\n }\n\n if (signal.aborted) {\n return { type: \"aborted\" };\n }\n\n let newMatches = matchRoutes(routesToUse, pathname, basename);\n if (newMatches) {\n return { type: \"success\", matches: newMatches };\n }\n\n let newPartialMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n routesToUse,\n pathname,\n basename,\n true\n );\n\n // Avoid loops if the second pass results in the same partial matches\n if (\n !newPartialMatches ||\n (partialMatches.length === newPartialMatches.length &&\n partialMatches.every(\n (m, i) => m.route.id === newPartialMatches![i].route.id\n ))\n ) {\n return { type: \"success\", matches: null };\n }\n\n partialMatches = newPartialMatches;\n }\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\n );\n }\n\n function patchRoutes(\n routeId: string | null,\n children: AgnosticRouteObject[]\n ): void {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n patchRoutesImpl(\n routeId,\n children,\n routesToUse,\n manifest,\n mapRouteProperties\n );\n\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity and trigger a reflow via `updateState`\n // to re-run memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR) {\n dataRoutes = [...dataRoutes];\n updateState({});\n }\n }\n\n router = {\n get basename() {\n return basename;\n },\n get future() {\n return future;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: queueFetcherForDeletion,\n dispose,\n getBlocker,\n deleteBlocker,\n patchRoutes,\n _internalFetchControllers: fetchControllers,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: {};\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties =\n opts?.mapRouteProperties || defaultMapRouteProperties;\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n *\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent\n * the bubbling of errors which allows single-fetch-type implementations\n * where the client will handle the bubbling and we may need to return data\n * for the handling route\n */\n async function query(\n request: Request,\n {\n requestContext,\n skipLoaderErrorBubbling,\n dataStrategy,\n }: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise<StaticHandlerContext | Response> {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n };\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n dataStrategy || null,\n skipLoaderErrorBubbling === true,\n null\n );\n if (isResponse(result)) {\n return result;\n }\n\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n *\n * - `opts.routeId` allows you to specify the specific route handler to call.\n * If not provided the handler will determine the proper route by matching\n * against `request.url`\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n dataStrategy,\n }: {\n requestContext?: unknown;\n routeId?: string;\n dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise<any> {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n dataStrategy || null,\n false,\n match\n );\n\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n return Object.values(result.loaderData)[0];\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null\n ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method)) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction for a\n // `queryRoute` call, we throw the `DataStrategyResult` to bail out early\n // and then return or throw the raw Response here accordingly\n if (isDataStrategyResult(e) && isResponse(e.result)) {\n if (e.type === ResultType.error) {\n throw e.result;\n }\n return e.result;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n isRouteRequest: boolean\n ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n let results = await callDataStrategy(\n \"action\",\n request,\n [actionMatch],\n matches,\n isRouteRequest,\n requestContext,\n dataStrategy\n );\n result = results[actionMatch.route.id];\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest);\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.response.status,\n headers: {\n Location: result.response.headers.get(\"Location\")!,\n },\n });\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n };\n }\n\n // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = skipLoaderErrorBubbling\n ? actionMatch\n : findNearestBoundary(matches, actionMatch.route.id);\n\n let context = await loadRouteData(\n loaderRequest,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n null,\n [boundaryMatch.route.id, result]\n );\n\n // action status codes take precedence over loader status codes\n return {\n ...context,\n statusCode: isRouteErrorResponse(result.error)\n ? result.error.status\n : result.statusCode != null\n ? result.statusCode\n : 500,\n actionData: null,\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n let context = await loadRouteData(\n loaderRequest,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n null\n );\n\n return {\n ...context,\n actionData: {\n [actionMatch.route.id]: result.data,\n },\n // action status codes take precedence over loader status codes\n ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n actionHeaders: result.headers\n ? { [actionMatch.route.id]: result.headers }\n : {},\n };\n }\n\n async function loadRouteData(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null,\n pendingActionResult?: PendingActionResult\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : pendingActionResult && isErrorResult(pendingActionResult[1])\n ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0])\n : matches;\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors:\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? {\n [pendingActionResult[0]]: pendingActionResult[1].error,\n }\n : null,\n statusCode: 200,\n loaderHeaders: {},\n };\n }\n\n let results = await callDataStrategy(\n \"loader\",\n request,\n matchesToLoad,\n matches,\n isRouteRequest,\n requestContext,\n dataStrategy\n );\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest);\n }\n\n // Process and commit output from loaders\n let context = processRouteLoaderData(\n matches,\n results,\n pendingActionResult,\n true,\n skipLoaderErrorBubbling\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set<string>(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n };\n }\n\n // Utility wrapper for calling dataStrategy server-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(\n type: \"loader\" | \"action\",\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n isRouteRequest: boolean,\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null\n ): Promise<Record<string, DataResult>> {\n let results = await callDataStrategyImpl(\n dataStrategy || defaultDataStrategy,\n type,\n null,\n request,\n matchesToLoad,\n matches,\n null,\n manifest,\n mapRouteProperties,\n requestContext\n );\n\n let dataResults: Record<string, DataResult> = {};\n await Promise.all(\n matches.map(async (match) => {\n if (!(match.route.id in results)) {\n return;\n }\n let result = results[match.route.id];\n if (isRedirectDataStrategyResultResult(result)) {\n let response = result.result as Response;\n // Throw redirects and let the server handle them with an HTTP redirect\n throw normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n match.route.id,\n matches,\n basename\n );\n }\n if (isResponse(result.result) && isRouteRequest) {\n // For SSR single-route requests, we want to hand Responses back\n // directly without unwrapping\n throw result;\n }\n\n dataResults[match.route.id] =\n await convertDataStrategyResultToDataResult(result);\n })\n );\n return dataResults;\n }\n\n return {\n dataRoutes,\n query,\n queryRoute,\n };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n *\n * @category Utils\n */\nexport function getStaticContextFromError(\n routes: AgnosticDataRouteObject[],\n context: StaticHandlerContext,\n error: any\n) {\n let newContext: StaticHandlerContext = {\n ...context,\n statusCode: isRouteErrorResponse(error) ? error.status : 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error,\n },\n };\n return newContext;\n}\n\nfunction throwStaticHandlerAbortedError(\n request: Request,\n isRouteRequest: boolean\n) {\n if (request.signal.reason !== undefined) {\n throw request.signal.reason;\n }\n\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(\n `${method}() call aborted without an \\`AbortSignal.reason\\`: ${request.method} ${request.url}`\n );\n}\n\nfunction isSubmissionNavigation(\n opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n return (\n opts != null &&\n ((\"formData\" in opts && opts.formData != null) ||\n (\"body\" in opts && opts.body !== undefined))\n );\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n to: To | null,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getResolveToMatches(contextualMatches),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Account for `?index` params when routing to the current location\n if ((to == null || to === \"\" || to === \".\") && activeRouteMatch) {\n let nakedIndex = hasNakedIndexQuery(path.search);\n if (activeRouteMatch.route.index && !nakedIndex) {\n // Add one when we're targeting an index route\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n } else if (!activeRouteMatch.route.index && nakedIndex) {\n // Remove existing ones when we're not\n let params = new URLSearchParams(path.search);\n let indexValues = params.getAll(\"index\");\n params.delete(\"index\");\n indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n let qs = params.toString();\n path.search = qs ? `?${qs}` : \"\";\n }\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n isFetcher: boolean,\n path: string,\n opts?: BaseNavigateOrFetchOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponseImpl;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, { type: \"invalid-body\" }),\n });\n\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = rawFormMethod.toUpperCase() as FormMethod;\n let formAction = stripHashFromPath(path);\n\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n let text =\n typeof opts.body === \"string\"\n ? opts.body\n : opts.body instanceof FormData ||\n opts.body instanceof URLSearchParams\n ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce(\n (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n \"\"\n )\n : String(opts.body);\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text,\n },\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n try {\n let json =\n typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined,\n },\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n\n invariant(\n typeof FormData === \"function\",\n \"FormData is not available in this environment\"\n );\n\n let searchParams: URLSearchParams;\n let formData: FormData;\n\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n\n let submission: Submission = {\n formMethod,\n formAction,\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes at/below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n matches: AgnosticDataRouteMatch[],\n boundaryId: string,\n includeBoundary = false\n) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n return matches.slice(0, includeBoundary ? index + 1 : index);\n }\n return matches;\n}\n\nfunction getMatchesToLoad(\n history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n initialHydration: boolean,\n isRevalidationRequired: boolean,\n cancelledFetcherLoads: Set<string>,\n fetchersQueuedForDeletion: Set<string>,\n fetchLoadMatches: Map<string, FetchLoadMatch>,\n fetchRedirectIds: Set<string>,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionResult?: PendingActionResult\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingActionResult\n ? isErrorResult(pendingActionResult[1])\n ? pendingActionResult[1].error\n : pendingActionResult[1].data\n : undefined;\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryMatches = matches;\n if (initialHydration && state.errors) {\n // On initial hydration, only consider matches up to _and including_ the boundary.\n // This is inclusive to handle cases where a server loader ran successfully,\n // a child server loader bubbled up to this route, but this route has\n // `clientLoader.hydrate` so we want to still run the `clientLoader` so that\n // we have a complete version of `loaderData`\n boundaryMatches = getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(state.errors)[0],\n true\n );\n } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {\n // If an action threw an error, we call loaders up to, but not including the\n // boundary\n boundaryMatches = getLoaderMatchesUntilBoundary(\n matches,\n pendingActionResult[0]\n );\n }\n\n // Don't revalidate loaders by default after action 4xx/5xx responses\n // when the flag is enabled. They can still opt-into revalidation via\n // `shouldRevalidate` via `actionResult`\n let actionStatus = pendingActionResult\n ? pendingActionResult[1].statusCode\n : undefined;\n let shouldSkipRevalidation = actionStatus && actionStatus >= 400;\n\n let navigationMatches = boundaryMatches.filter((match, index) => {\n let { route } = match;\n if (route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n\n if (route.loader == null) {\n return false;\n }\n\n if (initialHydration) {\n return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);\n }\n\n // Always call the loader on new route instances\n if (isNewLoader(state.loaderData, state.matches[index], match)) {\n return true;\n }\n\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation\n ? false\n : // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate:\n // - on initial hydration (shouldn't be any fetchers then anyway)\n // - if fetcher won't be present in the subsequent render\n // - no longer matches the URL (v7_fetcherPersist=false)\n // - was unmounted but persisted due to v7_fetcherPersist=true\n if (\n initialHydration ||\n !matches.some((m) => m.route.id === f.routeId) ||\n fetchersQueuedForDeletion.has(key)\n ) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.has(key)) {\n // Always mark for revalidation if the fetcher was cancelled\n cancelledFetcherLoads.delete(key);\n shouldRevalidate = true;\n } else if (\n fetcher &&\n fetcher.state !== \"idle\" &&\n fetcher.data === undefined\n ) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation\n ? false\n : isRevalidationRequired,\n });\n }\n\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction shouldLoadRouteOnHydration(\n route: AgnosticDataRouteObject,\n loaderData: RouteData | null | undefined,\n errors: RouteData | null | undefined\n) {\n // We dunno if we have a loader - gotta find out!\n if (route.lazy) {\n return true;\n }\n\n // No loader, nothing to initialize\n if (!route.loader) {\n return false;\n }\n\n let hasData = loaderData != null && loaderData[route.id] !== undefined;\n let hasError = errors != null && errors[route.id] !== undefined;\n\n // Don't run if we error'd during SSR\n if (!hasData && hasError) {\n return false;\n }\n\n // Explicitly opting-in to running on hydration\n if (typeof route.loader === \"function\" && route.loader.hydrate === true) {\n return true;\n }\n\n // Otherwise, run if we're not yet initialized with anything\n return !hasData && !hasError;\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error\n let isMissingData = !currentLoaderData.hasOwnProperty(match.route.id);\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: ShouldRevalidateFunctionArgs\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\nfunction patchRoutesImpl(\n routeId: string | null,\n children: AgnosticRouteObject[],\n routesToUse: AgnosticDataRouteObject[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction\n) {\n let childrenToPatch: AgnosticDataRouteObject[];\n if (routeId) {\n let route = manifest[routeId];\n invariant(\n route,\n `No route found to patch children into: routeId = ${routeId}`\n );\n if (!route.children) {\n route.children = [];\n }\n childrenToPatch = route.children;\n } else {\n childrenToPatch = routesToUse;\n }\n\n // Don't patch in routes we already know about so that `patch` is idempotent\n // to simplify user-land code. This is useful because we re-call the\n // `patchRoutesOnNavigation` function for matched routes with params.\n let uniqueChildren = children.filter(\n (newRoute) =>\n !childrenToPatch.some((existingRoute) =>\n isSameRoute(newRoute, existingRoute)\n )\n );\n\n let newRoutes = convertRoutesToDataRoutes(\n uniqueChildren,\n mapRouteProperties,\n [routeId || \"_\", \"patch\", String(childrenToPatch?.length || \"0\")],\n manifest\n );\n\n childrenToPatch.push(...newRoutes);\n}\n\nfunction isSameRoute(\n newRoute: AgnosticRouteObject,\n existingRoute: AgnosticRouteObject\n): boolean {\n // Most optimal check is by id\n if (\n \"id\" in newRoute &&\n \"id\" in existingRoute &&\n newRoute.id === existingRoute.id\n ) {\n return true;\n }\n\n // Second is by pathing differences\n if (\n !(\n newRoute.index === existingRoute.index &&\n newRoute.path === existingRoute.path &&\n newRoute.caseSensitive === existingRoute.caseSensitive\n )\n ) {\n return false;\n }\n\n // Pathless layout routes are trickier since we need to check children.\n // If they have no children then they're the same as far as we can tell\n if (\n (!newRoute.children || newRoute.children.length === 0) &&\n (!existingRoute.children || existingRoute.children.length === 0)\n ) {\n return true;\n }\n\n // Otherwise, we look to see if every child in the new route is already\n // represented in the existing route's children\n return newRoute.children!.every((aChild, i) =>\n existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild))\n );\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record<string, any> = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided `mapRouteProperties`\n // function to set the framework-aware properties (`element`/`hasErrorBoundary`)\n // since the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\n// Default implementation of `dataStrategy` which fetches all loaders in parallel\nasync function defaultDataStrategy({\n matches,\n}: DataStrategyFunctionArgs): ReturnType<DataStrategyFunction> {\n let matchesToLoad = matches.filter((m) => m.shouldLoad);\n let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));\n return results.reduce(\n (acc, result, i) =>\n Object.assign(acc, { [matchesToLoad[i].route.id]: result }),\n {}\n );\n}\n\nasync function callDataStrategyImpl(\n dataStrategyImpl: DataStrategyFunction,\n type: \"loader\" | \"action\",\n state: RouterState | null,\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n fetcherKey: string | null,\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n requestContext?: unknown\n): Promise<Record<string, DataStrategyResult>> {\n let loadRouteDefinitionsPromises = matches.map((m) =>\n m.route.lazy\n ? loadLazyRouteModule(m.route, mapRouteProperties, manifest)\n : undefined\n );\n\n let dsMatches = matches.map((match, i) => {\n let loadRoutePromise = loadRouteDefinitionsPromises[i];\n let shouldLoad = matchesToLoad.some((m) => m.route.id === match.route.id);\n // `resolve` encapsulates route.lazy(), executing the loader/action,\n // and mapping return values/thrown errors to a `DataStrategyResult`. Users\n // can pass a callback to take fine-grained control over the execution\n // of the loader/action\n let resolve: DataStrategyMatch[\"resolve\"] = async (handlerOverride) => {\n if (\n handlerOverride &&\n request.method === \"GET\" &&\n (match.route.lazy || match.route.loader)\n ) {\n shouldLoad = true;\n }\n return shouldLoad\n ? callLoaderOrAction(\n type,\n request,\n match,\n loadRoutePromise,\n handlerOverride,\n requestContext\n )\n : Promise.resolve({ type: ResultType.data, result: undefined });\n };\n\n return {\n ...match,\n shouldLoad,\n resolve,\n };\n });\n\n // Send all matches here to allow for a middleware-type implementation.\n // handler will be a no-op for unneeded routes and we filter those results\n // back out below.\n let results = await dataStrategyImpl({\n matches: dsMatches,\n request,\n params: matches[0].params,\n fetcherKey,\n context: requestContext,\n });\n\n // Wait for all routes to load here but 'swallow the error since we want\n // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -\n // called from `match.resolve()`\n try {\n await Promise.all(loadRouteDefinitionsPromises);\n } catch (e) {\n // No-op\n }\n\n return results;\n}\n\n// Default logic for calling a loader/action is the user has no specified a dataStrategy\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n loadRoutePromise: Promise<void> | undefined,\n handlerOverride: Parameters<DataStrategyMatch[\"resolve\"]>[0],\n staticContext?: unknown\n): Promise<DataStrategyResult> {\n let result: DataStrategyResult;\n let onReject: (() => void) | undefined;\n\n let runHandler = (\n handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n ): Promise<DataStrategyResult> => {\n // Setup a promise we can race against so that abort signals short circuit\n let reject: () => void;\n // This will never resolve so safe to type it as Promise<DataStrategyResult> to\n // satisfy the function return value\n let abortPromise = new Promise<DataStrategyResult>((_, r) => (reject = r));\n onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n\n let actualHandler = (ctx?: unknown) => {\n if (typeof handler !== \"function\") {\n return Promise.reject(\n new Error(\n `You cannot call the handler for a route which defines a boolean ` +\n `\"${type}\" [routeId: ${match.route.id}]`\n )\n );\n }\n return handler(\n {\n request,\n params: match.params,\n context: staticContext,\n },\n ...(ctx !== undefined ? [ctx] : [])\n );\n };\n\n let handlerPromise: Promise<DataStrategyResult> = (async () => {\n try {\n let val = await (handlerOverride\n ? handlerOverride((ctx: unknown) => actualHandler(ctx))\n : actualHandler());\n return { type: \"data\", result: val };\n } catch (e) {\n return { type: \"error\", result: e };\n }\n })();\n\n return Promise.race([handlerPromise, abortPromise]);\n };\n\n try {\n let handler = match.route[type];\n\n // If we have a route.lazy promise, await that first\n if (loadRoutePromise) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let [value] = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch((e) => {\n handlerError = e;\n }),\n loadRoutePromise,\n ]);\n if (handlerError !== undefined) {\n throw handlerError;\n }\n result = value!;\n } else {\n // Load lazy route module, then run any returned handler\n await loadRoutePromise;\n\n handler = match.route[type];\n if (handler) {\n // Handler still runs even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, result: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n } catch (e) {\n // We should already be catching and converting normal handler executions to\n // DataStrategyResults and returning them, so anything that throws here is an\n // unexpected error we still need to wrap\n return { type: ResultType.error, result: e };\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n return result;\n}\n\nasync function convertDataStrategyResultToDataResult(\n dataStrategyResult: DataStrategyResult\n): Promise<DataResult> {\n let { result, type } = dataStrategyResult;\n\n if (isResponse(result)) {\n let data: any;\n\n try {\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n if (result.body == null) {\n data = null;\n } else {\n data = await result.json();\n }\n } else {\n data = await result.text();\n }\n } catch (e) {\n return { type: ResultType.error, error: e };\n }\n\n if (type === ResultType.error) {\n return {\n type: ResultType.error,\n error: new ErrorResponseImpl(result.status, result.statusText, data),\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n if (type === ResultType.error) {\n if (isDataWithResponseInit(result)) {\n if (result.data instanceof Error) {\n return {\n type: ResultType.error,\n error: result.data,\n statusCode: result.init?.status,\n };\n }\n\n // Convert thrown data() to ErrorResponse instances\n result = new ErrorResponseImpl(\n result.init?.status || 500,\n undefined,\n result.data\n );\n }\n\n return {\n type: ResultType.error,\n error: result,\n statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n };\n }\n\n if (isDataWithResponseInit(result)) {\n return {\n type: ResultType.data,\n data: result.data,\n statusCode: result.init?.status,\n headers: result.init?.headers\n ? new Headers(result.init.headers)\n : undefined,\n };\n }\n\n return { type: ResultType.data, data: result };\n}\n\n// Support relative routing in internal redirects\nfunction normalizeRelativeRoutingRedirectResponse(\n response: Response,\n request: Request,\n routeId: string,\n matches: AgnosticDataRouteMatch[],\n basename: string\n) {\n let location = response.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n let trimmedMatches = matches.slice(\n 0,\n matches.findIndex((m) => m.route.id === routeId) + 1\n );\n location = normalizeTo(\n new URL(request.url),\n trimmedMatches,\n basename,\n location\n );\n response.headers.set(\"Location\", location);\n }\n\n return response;\n}\n\nfunction normalizeRedirectLocation(\n location: string,\n currentUrl: URL,\n basename: string\n): string {\n if (ABSOLUTE_URL_REGEX.test(location)) {\n // Strip off the protocol+origin for same-origin + same-basename absolute redirects\n let normalizedLocation = location;\n let url = normalizedLocation.startsWith(\"//\")\n ? new URL(currentUrl.protocol + normalizedLocation)\n : new URL(normalizedLocation);\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n return url.pathname + url.search + url.hash;\n }\n }\n return location;\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n\n if (formEncType === \"application/json\") {\n init.headers = new Headers({ \"Content-Type\": formEncType });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (\n formEncType === \"application/x-www-form-urlencoded\" &&\n submission.formData\n ) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n\n return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n searchParams: URLSearchParams\n): FormData {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n results: Record<string, DataResult>,\n pendingActionResult: PendingActionResult | undefined,\n isStaticHandler = false,\n skipLoaderErrorBubbling = false\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record<string, Headers>;\n} {\n // Fill in loaderData/errors from our loaders\n let loaderData: RouterState[\"loaderData\"] = {};\n let errors: RouterState[\"errors\"] | null = null;\n let statusCode: number | undefined;\n let foundError = false;\n let loaderHeaders: Record<string, Headers> = {};\n let pendingError =\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? pendingActionResult[1].error\n : undefined;\n\n // Process loader results into state.loaderData/state.errors\n matches.forEach((match) => {\n if (!(match.route.id in results)) {\n return;\n }\n let id = match.route.id;\n let result = results[id];\n invariant(\n !isRedirectResult(result),\n \"Cannot handle redirect results in processLoaderData\"\n );\n if (isErrorResult(result)) {\n let error = result.error;\n // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n if (pendingError !== undefined) {\n error = pendingError;\n pendingError = undefined;\n }\n\n errors = errors || {};\n\n if (skipLoaderErrorBubbling) {\n errors[id] = error;\n } else {\n // Look upwards from the matched route for the closest ancestor error\n // boundary, defaulting to the root match. Prefer higher error values\n // if lower errors bubble to the same boundary\n let boundaryMatch = findNearestBoundary(matches, id);\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n }\n\n // Clear our any prior loaderData for the throwing route\n if (!isStaticHandler) {\n loaderData[id] = ResetLoaderDataSymbol;\n }\n\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n loaderData[id] = result.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (result.statusCode && result.statusCode !== 200 && !foundError) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n });\n\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here. Also clear out any loaderData for the\n // throwing route\n if (pendingError !== undefined && pendingActionResult) {\n errors = { [pendingActionResult[0]]: pendingError };\n loaderData[pendingActionResult[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n results: Record<string, DataResult>,\n pendingActionResult: PendingActionResult | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: Record<string, DataResult>\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n results,\n pendingActionResult\n );\n\n // Process results from our revalidating fetchers\n revalidatingFetchers.forEach((rf) => {\n let { key, match, controller } = rf;\n let result = fetcherResults[key];\n invariant(result, \"Did not find corresponding fetcher result\");\n\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n return;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n });\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[],\n errors: RouteData | null | undefined\n): RouteData {\n // Start with all new entries that are not being reset\n let mergedLoaderData = Object.entries(newLoaderData)\n .filter(([, v]) => v !== ResetLoaderDataSymbol)\n .reduce((merged, [k, v]) => {\n merged[k] = v;\n return merged;\n }, {} as RouteData);\n\n // Preserve existing `loaderData` for routes not included in `newLoaderData` and\n // where a loader wasn't removed by HMR\n for (let match of matches) {\n let id = match.route.id;\n if (\n !newLoaderData.hasOwnProperty(id) &&\n loaderData.hasOwnProperty(id) &&\n match.route.loader\n ) {\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\n\nfunction getActionDataForCommit(\n pendingActionResult: PendingActionResult | undefined\n) {\n if (!pendingActionResult) {\n return {};\n }\n return isErrorResult(pendingActionResult[1])\n ? {\n // Clear out prior actionData on errors\n actionData: {},\n }\n : {\n actionData: {\n [pendingActionResult[0]]: pendingActionResult[1].data,\n },\n };\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n message,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"invalid-body\";\n message?: string;\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponseImpl(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n results: Record<string, DataResult>\n): { key: string; result: RedirectResult } | undefined {\n let entries = Object.entries(results);\n for (let i = entries.length - 1; i >= 0; i--) {\n let [key, result] = entries[i];\n if (isRedirectResult(result)) {\n return { key, result };\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\n\nfunction isPromise<T = unknown>(val: unknown): val is Promise<T> {\n return typeof val === \"object\" && val != null && \"then\" in val;\n}\n\nfunction isDataStrategyResult(result: unknown): result is DataStrategyResult {\n return (\n result != null &&\n typeof result === \"object\" &&\n \"type\" in result &&\n \"result\" in result &&\n (result.type === ResultType.data || result.type === ResultType.error)\n );\n}\n\nfunction isRedirectDataStrategyResultResult(result: DataStrategyResult) {\n return (\n isResponse(result.result) && redirectStatusCodes.has(result.result.status)\n );\n}\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDataWithResponseInit(\n value: any\n): value is DataWithResponseInit<unknown> {\n return (\n typeof value === \"object\" &&\n value != null &&\n \"type\" in value &&\n \"data\" in value &&\n \"init\" in value &&\n value.type === \"DataWithResponseInit\"\n );\n}\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isValidMethod(method: string): method is FormMethod {\n return validRequestMethods.has(method.toUpperCase() as FormMethod);\n}\n\nfunction isMutationMethod(method: string): method is MutationFormMethod {\n return validMutationMethods.has(method.toUpperCase() as MutationFormMethod);\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n hasNakedIndexQuery(search || \"\")\n ) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n navigation: Navigation\n): Submission | undefined {\n let { formMethod, formAction, formEncType, text, formData, json } =\n navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text,\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined,\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined,\n };\n }\n}\n\nfunction getLoadingNavigation(\n location: Location,\n submission?: Submission\n): NavigationStates[\"Loading\"] {\n if (submission) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n } else {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n };\n return navigation;\n }\n}\n\nfunction getSubmittingNavigation(\n location: Location,\n submission: Submission\n): NavigationStates[\"Submitting\"] {\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n}\n\nfunction getLoadingFetcher(\n submission?: Submission,\n data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n if (submission) {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data,\n };\n return fetcher;\n } else {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n }\n}\n\nfunction getSubmittingFetcher(\n submission: Submission,\n existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined,\n };\n return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n let fetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n _window: Window,\n transitions: Map<string, Set<string>>\n) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(\n TRANSITIONS_STORAGE_KEY\n );\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\n\nfunction persistAppliedTransitions(\n _window: Window,\n transitions: Map<string, Set<string>>\n) {\n if (transitions.size > 0) {\n let json: Record<string, string[]> = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(\n TRANSITIONS_STORAGE_KEY,\n JSON.stringify(json)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save applied view transitions in sessionStorage (${error}).`\n );\n }\n }\n}\n\nfunction createDeferred<T = unknown>() {\n let resolve: (val?: any) => Promise<void>;\n let reject: (error?: Error) => Promise<void>;\n let promise = new Promise<T>((res, rej) => {\n resolve = async (val: T) => {\n res(val);\n try {\n await promise;\n } catch (e) {}\n };\n reject = async (error?: Error) => {\n rej(error);\n try {\n await promise;\n } catch (e) {}\n };\n });\n return {\n promise,\n //@ts-ignore\n resolve,\n //@ts-ignore\n reject,\n };\n}\n//#endregion\n","import * as React from \"react\";\nimport type {\n History,\n Action as NavigationType,\n Location,\n To,\n} from \"./router/history\";\nimport type {\n RelativeRoutingType,\n Router,\n StaticHandlerContext,\n} from \"./router/router\";\nimport type {\n AgnosticIndexRouteObject,\n AgnosticNonIndexRouteObject,\n AgnosticPatchRoutesOnNavigationFunction,\n AgnosticPatchRoutesOnNavigationFunctionArgs,\n AgnosticRouteMatch,\n LazyRouteFunction,\n TrackedPromise,\n} from \"./router/utils\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticIndexRouteObject[\"path\"];\n id?: AgnosticIndexRouteObject[\"id\"];\n loader?: AgnosticIndexRouteObject[\"loader\"];\n action?: AgnosticIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticIndexRouteObject[\"handle\"];\n index: true;\n children?: undefined;\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport interface NonIndexRouteObject {\n caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticNonIndexRouteObject[\"path\"];\n id?: AgnosticNonIndexRouteObject[\"id\"];\n loader?: AgnosticNonIndexRouteObject[\"loader\"];\n action?: AgnosticNonIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticNonIndexRouteObject[\"handle\"];\n index?: false;\n children?: RouteObject[];\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n children?: DataRouteObject[];\n id: string;\n};\n\nexport interface RouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {}\n\nexport interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}\n\nexport type PatchRoutesOnNavigationFunctionArgs =\n AgnosticPatchRoutesOnNavigationFunctionArgs<RouteObject, RouteMatch>;\n\nexport type PatchRoutesOnNavigationFunction =\n AgnosticPatchRoutesOnNavigationFunction<RouteObject, RouteMatch>;\n\nexport interface DataRouterContextObject\n // Omit `future` since those can be pulled from the `router`\n // `NavigationContext` needs future since it doesn't have a `router` in all cases\n extends Omit<NavigationContextObject, \"future\"> {\n router: Router;\n staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n React.createContext<DataRouterContextObject | null>(null);\nDataRouterContext.displayName = \"DataRouter\";\n\nexport const DataRouterStateContext = React.createContext<\n Router[\"state\"] | null\n>(null);\nDataRouterStateContext.displayName = \"DataRouterState\";\n\nexport type ViewTransitionContextObject =\n | {\n isTransitioning: false;\n }\n | {\n isTransitioning: true;\n flushSync: boolean;\n currentLocation: Location;\n nextLocation: Location;\n };\n\nexport const ViewTransitionContext =\n React.createContext<ViewTransitionContextObject>({\n isTransitioning: false,\n });\nViewTransitionContext.displayName = \"ViewTransition\";\n\n// TODO: (v7) Change the useFetcher data from `any` to `unknown`\nexport type FetchersContextObject = Map<string, any>;\n\nexport const FetchersContext = React.createContext<FetchersContextObject>(\n new Map()\n);\nFetchersContext.displayName = \"Fetchers\";\n\nexport const AwaitContext = React.createContext<TrackedPromise | null>(null);\nAwaitContext.displayName = \"Await\";\n\nexport interface NavigateOptions {\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n flushSync?: boolean;\n viewTransition?: boolean;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `<Router>` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n createHref: History[\"createHref\"];\n // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n encodeLocation?: History[\"encodeLocation\"];\n go: History[\"go\"];\n push(to: To, state?: any, opts?: NavigateOptions): void;\n replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n basename: string;\n navigator: Navigator;\n static: boolean;\n // TODO: Re-introduce a singular `FutureConfig` once we land our first\n // future.unstable_ or future.v8_ flag\n future: {};\n}\n\nexport const NavigationContext = React.createContext<NavigationContextObject>(\n null!\n);\nNavigationContext.displayName = \"Navigation\";\n\ninterface LocationContextObject {\n location: Location;\n navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext<LocationContextObject>(\n null!\n);\nLocationContext.displayName = \"Location\";\n\nexport interface RouteContextObject {\n outlet: React.ReactElement | null;\n matches: RouteMatch[];\n isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext<RouteContextObject>({\n outlet: null,\n matches: [],\n isDataRoute: false,\n});\nRouteContext.displayName = \"Route\";\n\nexport const RouteErrorContext = React.createContext<any>(null);\nRouteErrorContext.displayName = \"RouteError\";\n","import * as React from \"react\";\nimport type {\n DataRouteMatch,\n NavigateOptions,\n RouteContextObject,\n RouteMatch,\n RouteObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n RouteErrorContext,\n} from \"./context\";\nimport type { Location, Path, To } from \"./router/history\";\nimport {\n Action as NavigationType,\n invariant,\n parsePath,\n warning,\n} from \"./router/history\";\nimport type {\n Blocker,\n BlockerFunction,\n RelativeRoutingType,\n Router as DataRouter,\n RevalidationState,\n} from \"./router/router\";\nimport { IDLE_BLOCKER } from \"./router/router\";\nimport type {\n ParamParseKey,\n Params,\n PathMatch,\n PathPattern,\n UIMatch,\n} from \"./router/utils\";\nimport {\n convertRouteMatchToUiMatch,\n decodePath,\n getResolveToMatches,\n isRouteErrorResponse,\n joinPaths,\n matchPath,\n matchRoutes,\n resolveTo,\n stripBasename,\n} from \"./router/utils\";\n\n// TODO: Let's get this back to using an import map and development/production\n// condition once we get the rollup build replaced\nconst ENABLE_DEV_WARNINGS = true;\n\n/**\n Resolves a URL against the current location.\n\n ```tsx\n import { useHref } from \"react-router\"\n\n function SomeComponent() {\n let href = useHref(\"some/where\");\n // \"/resolved/some/where\"\n }\n ```\n\n @category Hooks\n */\nexport function useHref(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useHref() may be used only in the context of a <Router> component.`\n );\n\n let { basename, navigator } = React.useContext(NavigationContext);\n let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n let joinedPathname = pathname;\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the href. If this is a root navigation, then just use the raw\n // basename which allows the basename to have full control over the presence\n // of a trailing slash on root links\n if (basename !== \"/\") {\n joinedPathname =\n pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n }\n\n return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a Router, useful to ensure\n * a component is used within a Router.\n *\n * @category Hooks\n */\nexport function useInRouterContext(): boolean {\n return React.useContext(LocationContext) != null;\n}\n\n/**\n Returns the current {@link Location}. This can be useful if you'd like to perform some side effect whenever it changes.\n\n ```tsx\n import * as React from 'react'\n import { useLocation } from 'react-router'\n\n function SomeComponent() {\n let location = useLocation()\n\n React.useEffect(() => {\n // Google Analytics\n ga('send', 'pageview')\n }, [location]);\n\n return (\n // ...\n );\n }\n ```\n\n @category Hooks\n */\nexport function useLocation(): Location {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useLocation() may be used only in the context of a <Router> component.`\n );\n\n return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @category Hooks\n */\nexport function useNavigationType(): NavigationType {\n return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * `<NavLink>`.\n *\n * @category Hooks\n */\nexport function useMatch<\n ParamKey extends ParamParseKey<Path>,\n Path extends string\n>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useMatch() may be used only in the context of a <Router> component.`\n );\n\n let { pathname } = useLocation();\n return React.useMemo(\n () => matchPath<ParamKey, Path>(pattern, decodePath(pathname)),\n [pathname, pattern]\n );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n (to: To, options?: NavigateOptions): void | Promise<void>;\n (delta: number): void | Promise<void>;\n}\n\nconst navigateEffectWarning =\n `You should call navigate() in a React.useEffect(), not when ` +\n `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n cb: Parameters<typeof React.useLayoutEffect>[0]\n) {\n let isStatic = React.useContext(NavigationContext).static;\n if (!isStatic) {\n // We should be able to get rid of this once react 18.3 is released\n // See: https://github.com/facebook/react/pull/26395\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(cb);\n }\n}\n\n/**\n Returns a function that lets you navigate programmatically in the browser in response to user interactions or effects.\n\n ```tsx\n import { useNavigate } from \"react-router\";\n\n function SomeComponent() {\n let navigate = useNavigate();\n return (\n <button\n onClick={() => {\n navigate(-1);\n }}\n />\n );\n }\n ```\n\n It's often better to use {@link redirect} in {@link ActionFunction | actions} and {@link LoaderFunction | loaders} than this hook.\n\n @category Hooks\n */\nexport function useNavigate(): NavigateFunction {\n let { isDataRoute } = React.useContext(RouteContext);\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useNavigate() may be used only in the context of a <Router> component.`\n );\n\n let dataRouterContext = React.useContext(DataRouterContext);\n let { basename, navigator } = React.useContext(NavigationContext);\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n\n let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our history listener yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n navigator.go(to);\n return;\n }\n\n let path = resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n options.relative === \"path\"\n );\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to handing off to history (but only if we're not in a data router,\n // otherwise it'll prepend the basename inside of the router).\n // If this is a root navigation, then we navigate to the raw basename\n // which allows the basename to have full control over the presence of a\n // trailing slash on root links\n if (dataRouterContext == null && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\"\n ? basename\n : joinPaths([basename, path.pathname]);\n }\n\n (!!options.replace ? navigator.replace : navigator.push)(\n path,\n options.state,\n options\n );\n },\n [\n basename,\n navigator,\n routePathnamesJson,\n locationPathname,\n dataRouterContext,\n ]\n );\n\n return navigate;\n}\n\nconst OutletContext = React.createContext<unknown>(null);\n\n/**\n * Returns the parent route {@link OutletProps.context | `<Outlet context>`}.\n *\n * @category Hooks\n */\nexport function useOutletContext<Context = unknown>(): Context {\n return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `<Outlet>` to render child routes.\n *\n * @category Hooks\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n let outlet = React.useContext(RouteContext).outlet;\n if (outlet) {\n return (\n <OutletContext.Provider value={context}>{outlet}</OutletContext.Provider>\n );\n }\n return outlet;\n}\n\n/**\n Returns an object of key/value pairs of the dynamic params from the current URL that were matched by the routes. Child routes inherit all params from their parent routes.\n\n ```tsx\n import { useParams } from \"react-router\"\n\n function SomeComponent() {\n let params = useParams()\n params.postId\n }\n ```\n\n Assuming a route pattern like `/posts/:postId` is matched by `/posts/123` then `params.postId` will be `\"123\"`.\n\n @category Hooks\n */\nexport function useParams<\n ParamsOrKey extends string | Record<string, string | undefined> = string\n>(): Readonly<\n [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>\n> {\n let { matches } = React.useContext(RouteContext);\n let routeMatch = matches[matches.length - 1];\n return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n Resolves the pathname of the given `to` value against the current location. Similar to {@link useHref}, but returns a {@link Path} instead of a string.\n\n ```tsx\n import { useResolvedPath } from \"react-router\"\n\n function SomeComponent() {\n // if the user is at /dashboard/profile\n let path = useResolvedPath(\"../accounts\")\n path.pathname // \"/dashboard/accounts\"\n path.search // \"\"\n path.hash // \"\"\n }\n ```\n\n @category Hooks\n */\nexport function useResolvedPath(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));\n\n return React.useMemo(\n () =>\n resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n relative === \"path\"\n ),\n [to, routePathnamesJson, locationPathname, relative]\n );\n}\n\n/**\n Hook version of {@link Routes | `<Routes>`} that uses objects instead of components. These objects have the same properties as the component props.\n\n The return value of `useRoutes` is either a valid React element you can use to render the route tree, or `null` if nothing matched.\n\n ```tsx\n import * as React from \"react\";\n import { useRoutes } from \"react-router\";\n\n function App() {\n let element = useRoutes([\n {\n path: \"/\",\n element: <Dashboard />,\n children: [\n {\n path: \"messages\",\n element: <DashboardMessages />,\n },\n { path: \"tasks\", element: <DashboardTasks /> },\n ],\n },\n { path: \"team\", element: <AboutPage /> },\n ]);\n\n return element;\n }\n ```\n\n @category Hooks\n */\nexport function useRoutes(\n routes: RouteObject[],\n locationArg?: Partial<Location> | string\n): React.ReactElement | null {\n return useRoutesImpl(routes, locationArg);\n}\n\n/**\n * Internal implementation with accept optional param for RouterProvider usage\n *\n * @private\n * @category Hooks\n */\nexport function useRoutesImpl(\n routes: RouteObject[],\n locationArg?: Partial<Location> | string,\n dataRouterState?: DataRouter[\"state\"],\n future?: DataRouter[\"future\"]\n): React.ReactElement | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useRoutes() may be used only in the context of a <Router> component.`\n );\n\n let { navigator } = React.useContext(NavigationContext);\n let { matches: parentMatches } = React.useContext(RouteContext);\n let routeMatch = parentMatches[parentMatches.length - 1];\n let parentParams = routeMatch ? routeMatch.params : {};\n let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n let parentRoute = routeMatch && routeMatch.route;\n\n if (ENABLE_DEV_WARNINGS) {\n // You won't get a warning about 2 different <Routes> under a <Route>\n // without a trailing *, but this is a best-effort warning anyway since we\n // cannot even give the warning unless they land at the parent route.\n //\n // Example:\n //\n // <Routes>\n // {/* This route path MUST end with /* because otherwise\n // it will never match /blog/post/123 */}\n // <Route path=\"blog\" element={<Blog />} />\n // <Route path=\"blog/feed\" element={<BlogFeed />} />\n // </Routes>\n //\n // function Blog() {\n // return (\n // <Routes>\n // <Route path=\"post/:id\" element={<Post />} />\n // </Routes>\n // );\n // }\n let parentPath = (parentRoute && parentRoute.path) || \"\";\n warningOnce(\n parentPathname,\n !parentRoute || parentPath.endsWith(\"*\"),\n `You rendered descendant <Routes> (or called \\`useRoutes()\\`) at ` +\n `\"${parentPathname}\" (under <Route path=\"${parentPath}\">) but the ` +\n `parent route path has no trailing \"*\". This means if you navigate ` +\n `deeper, the parent won't match anymore and therefore the child ` +\n `routes will never render.\\n\\n` +\n `Please change the parent <Route path=\"${parentPath}\"> to <Route ` +\n `path=\"${parentPath === \"/\" ? \"*\" : `${parentPath}/*`}\">.`\n );\n }\n\n let locationFromContext = useLocation();\n\n let location;\n if (locationArg) {\n let parsedLocationArg =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n invariant(\n parentPathnameBase === \"/\" ||\n parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n `When overriding the location using \\`<Routes location>\\` or \\`useRoutes(routes, location)\\`, ` +\n `the location pathname must begin with the portion of the URL pathname that was ` +\n `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n );\n\n location = parsedLocationArg;\n } else {\n location = locationFromContext;\n }\n\n let pathname = location.pathname || \"/\";\n\n let remainingPathname = pathname;\n if (parentPathnameBase !== \"/\") {\n // Determine the remaining pathname by removing the # of URL segments the\n // parentPathnameBase has, instead of removing based on character count.\n // This is because we can't guarantee that incoming/outgoing encodings/\n // decodings will match exactly.\n // We decode paths before matching on a per-segment basis with\n // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they\n // match what `window.location.pathname` would reflect. Those don't 100%\n // align when it comes to encoded URI characters such as % and &.\n //\n // So we may end up with:\n // pathname: \"/descendant/a%25b/match\"\n // parentPathnameBase: \"/descendant/a%b\"\n //\n // And the direct substring removal approach won't work :/\n let parentSegments = parentPathnameBase.replace(/^\\//, \"\").split(\"/\");\n let segments = pathname.replace(/^\\//, \"\").split(\"/\");\n remainingPathname = \"/\" + segments.slice(parentSegments.length).join(\"/\");\n }\n\n let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n if (ENABLE_DEV_WARNINGS) {\n warning(\n parentRoute || matches != null,\n `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n );\n\n warning(\n matches == null ||\n matches[matches.length - 1].route.element !== undefined ||\n matches[matches.length - 1].route.Component !== undefined ||\n matches[matches.length - 1].route.lazy !== undefined,\n `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n `does not have an element or Component. This means it will render an <Outlet /> with a ` +\n `null value by default resulting in an \"empty\" page.`\n );\n }\n\n let renderedMatches = _renderMatches(\n matches &&\n matches.map((match) =>\n Object.assign({}, match, {\n params: Object.assign({}, parentParams, match.params),\n pathname: joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathname).pathname\n : match.pathname,\n ]),\n pathnameBase:\n match.pathnameBase === \"/\"\n ? parentPathnameBase\n : joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathnameBase).pathname\n : match.pathnameBase,\n ]),\n })\n ),\n parentMatches,\n dataRouterState,\n future\n );\n\n // When a user passes in a `locationArg`, the associated routes need to\n // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n // to use the scoped location instead of the global location.\n if (locationArg && renderedMatches) {\n return (\n <LocationContext.Provider\n value={{\n location: {\n pathname: \"/\",\n search: \"\",\n hash: \"\",\n state: null,\n key: \"default\",\n ...location,\n },\n navigationType: NavigationType.Pop,\n }}\n >\n {renderedMatches}\n </LocationContext.Provider>\n );\n }\n\n return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n let error = useRouteError();\n let message = isRouteErrorResponse(error)\n ? `${error.status} ${error.statusText}`\n : error instanceof Error\n ? error.message\n : JSON.stringify(error);\n let stack = error instanceof Error ? error.stack : null;\n let lightgrey = \"rgba(200,200,200, 0.5)\";\n let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n let devInfo = null;\n if (ENABLE_DEV_WARNINGS) {\n console.error(\n \"Error handled by React Router default ErrorBoundary:\",\n error\n );\n\n devInfo = (\n <>\n <p>💿 Hey developer 👋</p>\n <p>\n You can provide a way better UX than this when your app throws errors\n by providing your own <code style={codeStyles}>ErrorBoundary</code> or{\" \"}\n <code style={codeStyles}>errorElement</code> prop on your route.\n </p>\n </>\n );\n }\n\n return (\n <>\n <h2>Unexpected Application Error!</h2>\n <h3 style={{ fontStyle: \"italic\" }}>{message}</h3>\n {stack ? <pre style={preStyles}>{stack}</pre> : null}\n {devInfo}\n </>\n );\n}\n\nconst defaultErrorElement = <DefaultErrorComponent />;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n location: Location;\n revalidation: RevalidationState;\n error: any;\n component: React.ReactNode;\n routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n location: Location;\n revalidation: RevalidationState;\n error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n RenderErrorBoundaryProps,\n RenderErrorBoundaryState\n> {\n constructor(props: RenderErrorBoundaryProps) {\n super(props);\n this.state = {\n location: props.location,\n revalidation: props.revalidation,\n error: props.error,\n };\n }\n\n static getDerivedStateFromError(error: any) {\n return { error: error };\n }\n\n static getDerivedStateFromProps(\n props: RenderErrorBoundaryProps,\n state: RenderErrorBoundaryState\n ) {\n // When we get into an error state, the user will likely click \"back\" to the\n // previous page that didn't have an error. Because this wraps the entire\n // application, that will have no effect--the error page continues to display.\n // This gives us a mechanism to recover from the error when the location changes.\n //\n // Whether we're in an error state or not, we update the location in state\n // so that when we are in an error state, it gets reset when a new location\n // comes in and the user recovers from the error.\n if (\n state.location !== props.location ||\n (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n ) {\n return {\n error: props.error,\n location: props.location,\n revalidation: props.revalidation,\n };\n }\n\n // If we're not changing locations, preserve the location but still surface\n // any new errors that may come through. We retain the existing error, we do\n // this because the error provided from the app state may be cleared without\n // the location changing.\n return {\n error: props.error !== undefined ? props.error : state.error,\n location: state.location,\n revalidation: props.revalidation || state.revalidation,\n };\n }\n\n componentDidCatch(error: any, errorInfo: any) {\n console.error(\n \"React Router caught the following error during render\",\n error,\n errorInfo\n );\n }\n\n render() {\n return this.state.error !== undefined ? (\n <RouteContext.Provider value={this.props.routeContext}>\n <RouteErrorContext.Provider\n value={this.state.error}\n children={this.props.component}\n />\n </RouteContext.Provider>\n ) : (\n this.props.children\n );\n }\n}\n\ninterface RenderedRouteProps {\n routeContext: RouteContextObject;\n match: RouteMatch<string, RouteObject>;\n children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n let dataRouterContext = React.useContext(DataRouterContext);\n\n // Track how deep we got in our render pass to emulate SSR componentDidCatch\n // in a DataStaticRouter\n if (\n dataRouterContext &&\n dataRouterContext.static &&\n dataRouterContext.staticContext &&\n (match.route.errorElement || match.route.ErrorBoundary)\n ) {\n dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n }\n\n return (\n <RouteContext.Provider value={routeContext}>\n {children}\n </RouteContext.Provider>\n );\n}\n\nexport function _renderMatches(\n matches: RouteMatch[] | null,\n parentMatches: RouteMatch[] = [],\n dataRouterState: DataRouter[\"state\"] | null = null,\n future: DataRouter[\"future\"] | null = null\n): React.ReactElement | null {\n if (matches == null) {\n if (!dataRouterState) {\n return null;\n }\n\n if (dataRouterState.errors) {\n // Don't bail if we have data router errors so we can render them in the\n // boundary. Use the pre-matched (or shimmed) matches\n matches = dataRouterState.matches as DataRouteMatch[];\n } else if (\n parentMatches.length === 0 &&\n !dataRouterState.initialized &&\n dataRouterState.matches.length > 0\n ) {\n // Don't bail if we're initializing with partial hydration and we have\n // router matches. That means we're actively running `patchRoutesOnNavigation`\n // so we should render down the partial matches to the appropriate\n // `HydrateFallback`. We only do this if `parentMatches` is empty so it\n // only impacts the root matches for `RouterProvider` and no descendant\n // `<Routes>`\n matches = dataRouterState.matches as DataRouteMatch[];\n } else {\n return null;\n }\n }\n\n let renderedMatches = matches;\n\n // If we have data errors, trim matches to the highest error boundary\n let errors = dataRouterState?.errors;\n if (errors != null) {\n let errorIndex = renderedMatches.findIndex(\n (m) => m.route.id && errors?.[m.route.id] !== undefined\n );\n invariant(\n errorIndex >= 0,\n `Could not find a matching route for errors on route IDs: ${Object.keys(\n errors\n ).join(\",\")}`\n );\n renderedMatches = renderedMatches.slice(\n 0,\n Math.min(renderedMatches.length, errorIndex + 1)\n );\n }\n\n // If we're in a partial hydration mode, detect if we need to render down to\n // a given HydrateFallback while we load the rest of the hydration data\n let renderFallback = false;\n let fallbackIndex = -1;\n if (dataRouterState) {\n for (let i = 0; i < renderedMatches.length; i++) {\n let match = renderedMatches[i];\n // Track the deepest fallback up until the first route without data\n if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {\n fallbackIndex = i;\n }\n\n if (match.route.id) {\n let { loaderData, errors } = dataRouterState;\n let needsToRunLoader =\n match.route.loader &&\n !loaderData.hasOwnProperty(match.route.id) &&\n (!errors || errors[match.route.id] === undefined);\n if (match.route.lazy || needsToRunLoader) {\n // We found the first route that's not ready to render (waiting on\n // lazy, or has a loader that hasn't run yet). Flag that we need to\n // render a fallback and render up until the appropriate fallback\n renderFallback = true;\n if (fallbackIndex >= 0) {\n renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);\n } else {\n renderedMatches = [renderedMatches[0]];\n }\n break;\n }\n }\n }\n }\n\n return renderedMatches.reduceRight((outlet, match, index) => {\n // Only data routers handle errors/fallbacks\n let error: any;\n let shouldRenderHydrateFallback = false;\n let errorElement: React.ReactNode | null = null;\n let hydrateFallbackElement: React.ReactNode | null = null;\n if (dataRouterState) {\n error = errors && match.route.id ? errors[match.route.id] : undefined;\n errorElement = match.route.errorElement || defaultErrorElement;\n\n if (renderFallback) {\n if (fallbackIndex < 0 && index === 0) {\n warningOnce(\n \"route-fallback\",\n false,\n \"No `HydrateFallback` element provided to render during initial hydration\"\n );\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = null;\n } else if (fallbackIndex === index) {\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = match.route.hydrateFallbackElement || null;\n }\n }\n }\n\n let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n let getChildren = () => {\n let children: React.ReactNode;\n if (error) {\n children = errorElement;\n } else if (shouldRenderHydrateFallback) {\n children = hydrateFallbackElement;\n } else if (match.route.Component) {\n // Note: This is a de-optimized path since React won't re-use the\n // ReactElement since it's identity changes with each new\n // React.createElement call. We keep this so folks can use\n // `<Route Component={...}>` in `<Routes>` but generally `Component`\n // usage is only advised in `RouterProvider` when we can convert it to\n // `element` ahead of time.\n children = <match.route.Component />;\n } else if (match.route.element) {\n children = match.route.element;\n } else {\n children = outlet;\n }\n return (\n <RenderedRoute\n match={match}\n routeContext={{\n outlet,\n matches,\n isDataRoute: dataRouterState != null,\n }}\n children={children}\n />\n );\n };\n // Only wrap in an error boundary within data router usages when we have an\n // ErrorBoundary/errorElement on this route. Otherwise let it bubble up to\n // an ancestor ErrorBoundary/errorElement\n return dataRouterState &&\n (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n <RenderErrorBoundary\n location={dataRouterState.location}\n revalidation={dataRouterState.revalidation}\n component={errorElement}\n error={error}\n children={getChildren()}\n routeContext={{ outlet: null, matches, isDataRoute: true }}\n />\n ) : (\n getChildren()\n );\n }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n UseBlocker = \"useBlocker\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n UseBlocker = \"useBlocker\",\n UseLoaderData = \"useLoaderData\",\n UseActionData = \"useActionData\",\n UseRouteError = \"useRouteError\",\n UseNavigation = \"useNavigation\",\n UseRouteLoaderData = \"useRouteLoaderData\",\n UseMatches = \"useMatches\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n hookName: DataRouterHook | DataRouterStateHook\n) {\n return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n let ctx = React.useContext(DataRouterContext);\n invariant(ctx, getDataRouterConsoleError(hookName));\n return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n let state = React.useContext(DataRouterStateContext);\n invariant(state, getDataRouterConsoleError(hookName));\n return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n let route = React.useContext(RouteContext);\n invariant(route, getDataRouterConsoleError(hookName));\n return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n let route = useRouteContext(hookName);\n let thisRoute = route.matches[route.matches.length - 1];\n invariant(\n thisRoute.route.id,\n `${hookName} can only be used on routes that contain a unique \"id\"`\n );\n return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n Returns the current navigation, defaulting to an \"idle\" navigation when no navigation is in progress. You can use this to render pending UI (like a global spinner) or read FormData from a form navigation.\n\n ```tsx\n import { useNavigation } from \"react-router\"\n\n function SomeComponent() {\n let navigation = useNavigation();\n navigation.state\n navigation.formData\n // etc.\n }\n ```\n\n @category Hooks\n */\nexport function useNavigation() {\n let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n return state.navigation;\n}\n\n/**\n Revalidate the data on the page for reasons outside of normal data mutations like window focus or polling on an interval.\n\n ```tsx\n import { useRevalidator } from \"react-router\";\n\n function WindowFocusRevalidator() {\n const revalidator = useRevalidator();\n\n useFakeWindowFocus(() => {\n revalidator.revalidate();\n });\n\n return (\n <div hidden={revalidator.state === \"idle\"}>\n Revalidating...\n </div>\n );\n }\n ```\n\n Note that page data is already revalidated automatically after actions. If you find yourself using this for normal CRUD operations on your data in response to user interactions, you're probably not taking advantage of the other APIs like {@link useFetcher}, {@link Form}, {@link useSubmit} that do this automatically.\n\n @category Hooks\n */\nexport function useRevalidator() {\n let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n return React.useMemo(\n () => ({\n async revalidate() {\n await dataRouterContext.router.revalidate();\n },\n state: state.revalidation,\n }),\n [dataRouterContext.router, state.revalidation]\n );\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n *\n * @category Hooks\n */\nexport function useMatches(): UIMatch[] {\n let { matches, loaderData } = useDataRouterState(\n DataRouterStateHook.UseMatches\n );\n return React.useMemo(\n () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),\n [matches, loaderData]\n );\n}\n\n/**\n Returns the data from the closest route {@link LoaderFunction | loader} or {@link ClientLoaderFunction | client loader}.\n\n ```tsx\n import { useLoaderData } from \"react-router\"\n\n export async function loader() {\n return await fakeDb.invoices.findAll();\n }\n\n export default function Invoices() {\n let invoices = useLoaderData<typeof loader>();\n // ...\n }\n ```\n\n @category Hooks\n */\nexport function useLoaderData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n return state.loaderData[routeId];\n}\n\n/**\n Returns the loader data for a given route by route ID.\n\n ```tsx\n import { useRouteLoaderData } from \"react-router\";\n\n function SomeComponent() {\n const { user } = useRouteLoaderData(\"root\");\n }\n ```\n\n Route IDs are created automatically. They are simply the path of the route file relative to the app folder without the extension.\n\n | Route Filename | Route ID |\n | -------------------------- | -------------------- |\n | `app/root.tsx` | `\"root\"` |\n | `app/routes/teams.tsx` | `\"routes/teams\"` |\n | `app/whatever/teams.$id.tsx` | `\"whatever/teams.$id\"` |\n\n If you created an ID manually, you can use that instead:\n\n ```tsx\n route(\"/\", \"containers/app.tsx\", { id: \"app\" }})\n ```\n\n @category Hooks\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n return state.loaderData[routeId];\n}\n\n/**\n Returns the action data from the most recent POST navigation form submission or `undefined` if there hasn't been one.\n\n ```tsx\n import { Form, useActionData } from \"react-router\"\n\n export async function action({ request }) {\n const body = await request.formData()\n const name = body.get(\"visitorsName\")\n return { message: `Hello, ${name}` }\n }\n\n export default function Invoices() {\n const data = useActionData()\n return (\n <Form method=\"post\">\n <input type=\"text\" name=\"visitorsName\" />\n {data ? data.message : \"Waiting...\"}\n </Form>\n )\n }\n ```\n\n @category Hooks\n */\nexport function useActionData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseActionData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n Accesses the error thrown during an {@link ActionFunction | action}, {@link LoaderFunction | loader}, or component render to be used in a route module Error Boundary.\n\n ```tsx\n export function ErrorBoundary() {\n const error = useRouteError();\n return <div>{error.message}</div>;\n }\n ```\n\n @category Hooks\n */\nexport function useRouteError(): unknown {\n let error = React.useContext(RouteErrorContext);\n let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n // If this was a render error, we put it in a RouteError context inside\n // of RenderErrorBoundary\n if (error !== undefined) {\n return error;\n }\n\n // Otherwise look for errors from our data router state\n return state.errors?.[routeId];\n}\n\n/**\n Returns the resolved promise value from the closest {@link Await | `<Await>`}.\n\n ```tsx\n function SomeDescendant() {\n const value = useAsyncValue();\n // ...\n }\n\n // somewhere in your app\n <Await resolve={somePromise}>\n <SomeDescendant />\n </Await>\n ```\n\n @category Hooks\n */\nexport function useAsyncValue(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._data;\n}\n\n/**\n Returns the rejection value from the closest {@link Await | `<Await>`}.\n\n ```tsx\n import { Await, useAsyncError } from \"react-router\"\n\n function ErrorElement() {\n const error = useAsyncError();\n return (\n <p>Uh Oh, something went wrong! {error.message}</p>\n );\n }\n\n // somewhere in your app\n <Await\n resolve={promiseThatRejects}\n errorElement={<ErrorElement />}\n />\n ```\n\n @category Hooks\n */\nexport function useAsyncError(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation. Mostly used to avoid\n * using half-filled form data. This does not handle hard-reloads or\n * cross-origin navigations.\n *\n * @category Hooks\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);\n let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n\n let [blockerKey, setBlockerKey] = React.useState(\"\");\n let blockerFunction = React.useCallback<BlockerFunction>(\n (arg) => {\n if (typeof shouldBlock !== \"function\") {\n return !!shouldBlock;\n }\n if (basename === \"/\") {\n return shouldBlock(arg);\n }\n\n // If they provided us a function and we've got an active basename, strip\n // it from the locations we expose to the user to match the behavior of\n // useLocation\n let { currentLocation, nextLocation, historyAction } = arg;\n return shouldBlock({\n currentLocation: {\n ...currentLocation,\n pathname:\n stripBasename(currentLocation.pathname, basename) ||\n currentLocation.pathname,\n },\n nextLocation: {\n ...nextLocation,\n pathname:\n stripBasename(nextLocation.pathname, basename) ||\n nextLocation.pathname,\n },\n historyAction,\n });\n },\n [basename, shouldBlock]\n );\n\n // This effect is in charge of blocker key assignment and deletion (which is\n // tightly coupled to the key)\n React.useEffect(() => {\n let key = String(++blockerId);\n setBlockerKey(key);\n return () => router.deleteBlocker(key);\n }, [router]);\n\n // This effect handles assigning the blockerFunction. This is to handle\n // unstable blocker function identities, and happens only after the prior\n // effect so we don't get an orphaned blockerFunction in the router with a\n // key of \"\". Until then we just have the IDLE_BLOCKER.\n React.useEffect(() => {\n if (blockerKey !== \"\") {\n router.getBlocker(blockerKey, blockerFunction);\n }\n }, [router, blockerKey, blockerFunction]);\n\n // Prefer the blocker from `state` not `router.state` since DataRouterContext\n // is memoized so this ensures we update on blocker state updates\n return blockerKey && state.blockers.has(blockerKey)\n ? state.blockers.get(blockerKey)!\n : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n *\n * @private\n */\nfunction useNavigateStable(): NavigateFunction {\n let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n async (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our router subscriber yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n router.navigate(to);\n } else {\n await router.navigate(to, { fromRouteId: id, ...options });\n }\n },\n [router, id]\n );\n\n return navigate;\n}\n\nconst alreadyWarned: Record<string, boolean> = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n if (!cond && !alreadyWarned[key]) {\n alreadyWarned[key] = true;\n warning(false, message);\n }\n}\n","const alreadyWarned: { [message: string]: boolean } = {};\n\nexport function warnOnce(condition: boolean, message: string): void {\n if (!condition && !alreadyWarned[message]) {\n alreadyWarned[message] = true;\n console.warn(message);\n }\n}\n","import * as React from \"react\";\n\nimport type {\n InitialEntry,\n Location,\n MemoryHistory,\n To,\n} from \"./router/history\";\nimport {\n Action as NavigationType,\n createMemoryHistory,\n invariant,\n parsePath,\n warning,\n} from \"./router/history\";\nimport type {\n FutureConfig,\n HydrationState,\n RelativeRoutingType,\n Router as DataRouter,\n RouterState,\n RouterSubscriber,\n} from \"./router/router\";\nimport { createRouter } from \"./router/router\";\nimport type {\n DataStrategyFunction,\n LazyRouteFunction,\n TrackedPromise,\n} from \"./router/utils\";\nimport { getResolveToMatches, resolveTo, stripBasename } from \"./router/utils\";\n\nimport type {\n DataRouteObject,\n IndexRouteObject,\n Navigator,\n NonIndexRouteObject,\n PatchRoutesOnNavigationFunction,\n RouteMatch,\n RouteObject,\n ViewTransitionContextObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n FetchersContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n ViewTransitionContext,\n} from \"./context\";\nimport {\n _renderMatches,\n useAsyncValue,\n useInRouterContext,\n useLocation,\n useNavigate,\n useOutlet,\n useRoutes,\n useRoutesImpl,\n} from \"./hooks\";\nimport type { ViewTransition } from \"./dom/global\";\nimport { warnOnce } from \"./server-runtime/warnings\";\n\n// TODO: Let's get this back to using an import map and development/production\n// condition once we get the rollup build replaced\nconst ENABLE_DEV_WARNINGS = true;\n\n/**\n * @private\n */\nexport function mapRouteProperties(route: RouteObject) {\n let updates: Partial<RouteObject> & { hasErrorBoundary: boolean } = {\n // Note: this check also occurs in createRoutesFromChildren so update\n // there if you change this -- please and thank you!\n hasErrorBoundary:\n route.hasErrorBoundary ||\n route.ErrorBoundary != null ||\n route.errorElement != null,\n };\n\n if (route.Component) {\n if (ENABLE_DEV_WARNINGS) {\n if (route.element) {\n warning(\n false,\n \"You should not include both `Component` and `element` on your route - \" +\n \"`Component` will be used.\"\n );\n }\n }\n Object.assign(updates, {\n element: React.createElement(route.Component),\n Component: undefined,\n });\n }\n\n if (route.HydrateFallback) {\n if (ENABLE_DEV_WARNINGS) {\n if (route.hydrateFallbackElement) {\n warning(\n false,\n \"You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - \" +\n \"`HydrateFallback` will be used.\"\n );\n }\n }\n Object.assign(updates, {\n hydrateFallbackElement: React.createElement(route.HydrateFallback),\n HydrateFallback: undefined,\n });\n }\n\n if (route.ErrorBoundary) {\n if (ENABLE_DEV_WARNINGS) {\n if (route.errorElement) {\n warning(\n false,\n \"You should not include both `ErrorBoundary` and `errorElement` on your route - \" +\n \"`ErrorBoundary` will be used.\"\n );\n }\n }\n Object.assign(updates, {\n errorElement: React.createElement(route.ErrorBoundary),\n ErrorBoundary: undefined,\n });\n }\n\n return updates;\n}\n\n/**\n * @category Routers\n */\nexport function createMemoryRouter(\n routes: RouteObject[],\n opts?: {\n basename?: string;\n future?: Partial<FutureConfig>;\n hydrationData?: HydrationState;\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n dataStrategy?: DataStrategyFunction;\n patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;\n }\n): DataRouter {\n return createRouter({\n basename: opts?.basename,\n future: opts?.future,\n history: createMemoryHistory({\n initialEntries: opts?.initialEntries,\n initialIndex: opts?.initialIndex,\n }),\n hydrationData: opts?.hydrationData,\n routes,\n mapRouteProperties,\n dataStrategy: opts?.dataStrategy,\n patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n }).initialize();\n}\n\nclass Deferred<T> {\n status: \"pending\" | \"resolved\" | \"rejected\" = \"pending\";\n promise: Promise<T>;\n // @ts-expect-error - no initializer\n resolve: (value: T) => void;\n // @ts-expect-error - no initializer\n reject: (reason?: unknown) => void;\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = (value) => {\n if (this.status === \"pending\") {\n this.status = \"resolved\";\n resolve(value);\n }\n };\n this.reject = (reason) => {\n if (this.status === \"pending\") {\n this.status = \"rejected\";\n reject(reason);\n }\n };\n });\n }\n}\n\n// Copied from react-dom types\nexport interface RouterProviderProps {\n router: DataRouter;\n flushSync?: (fn: () => unknown) => undefined;\n}\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n router,\n flushSync: reactDomFlushSyncImpl,\n}: RouterProviderProps): React.ReactElement {\n let [state, setStateImpl] = React.useState(router.state);\n let [pendingState, setPendingState] = React.useState<RouterState>();\n let [vtContext, setVtContext] = React.useState<ViewTransitionContextObject>({\n isTransitioning: false,\n });\n let [renderDfd, setRenderDfd] = React.useState<Deferred<void>>();\n let [transition, setTransition] = React.useState<ViewTransition>();\n let [interruption, setInterruption] = React.useState<{\n state: RouterState;\n currentLocation: Location;\n nextLocation: Location;\n }>();\n let fetcherData = React.useRef<Map<string, any>>(new Map());\n\n let setState = React.useCallback<RouterSubscriber>(\n (\n newState: RouterState,\n {\n deletedFetchers,\n flushSync: flushSync,\n viewTransitionOpts: viewTransitionOpts,\n }\n ) => {\n deletedFetchers.forEach((key) => fetcherData.current.delete(key));\n newState.fetchers.forEach((fetcher, key) => {\n if (fetcher.data !== undefined) {\n fetcherData.current.set(key, fetcher.data);\n }\n });\n\n warnOnce(\n flushSync === false || reactDomFlushSyncImpl != null,\n \"You provided the `flushSync` option to a router update, \" +\n \"but you are not using the `<RouterProvider>` from `react-router/dom` \" +\n \"so `ReactDOM.flushSync()` is unavailable. Please update your app \" +\n 'to `import { RouterProvider } from \"react-router/dom\"` and ensure ' +\n \"you have `react-dom` installed as a dependency to use the \" +\n \"`flushSync` option.\"\n );\n\n let isViewTransitionAvailable =\n router.window != null &&\n router.window.document != null &&\n typeof router.window.document.startViewTransition === \"function\";\n\n warnOnce(\n viewTransitionOpts == null || isViewTransitionAvailable,\n \"You provided the `viewTransition` option to a router update, \" +\n \"but you do not appear to be running in a DOM environment as \" +\n \"`window.startViewTransition` is not available.\"\n );\n\n // If this isn't a view transition or it's not available in this browser,\n // just update and be done with it\n if (!viewTransitionOpts || !isViewTransitionAvailable) {\n if (reactDomFlushSyncImpl && flushSync) {\n reactDomFlushSyncImpl(() => setStateImpl(newState));\n } else {\n React.startTransition(() => setStateImpl(newState));\n }\n return;\n }\n\n // flushSync + startViewTransition\n if (reactDomFlushSyncImpl && flushSync) {\n // Flush through the context to mark DOM elements as transition=ing\n reactDomFlushSyncImpl(() => {\n // Cancel any pending transitions\n if (transition) {\n renderDfd && renderDfd.resolve();\n transition.skipTransition();\n }\n setVtContext({\n isTransitioning: true,\n flushSync: true,\n currentLocation: viewTransitionOpts.currentLocation,\n nextLocation: viewTransitionOpts.nextLocation,\n });\n });\n\n // Update the DOM\n let t = router.window!.document.startViewTransition(() => {\n reactDomFlushSyncImpl(() => setStateImpl(newState));\n });\n\n // Clean up after the animation completes\n t.finished.finally(() => {\n reactDomFlushSyncImpl(() => {\n setRenderDfd(undefined);\n setTransition(undefined);\n setPendingState(undefined);\n setVtContext({ isTransitioning: false });\n });\n });\n\n reactDomFlushSyncImpl(() => setTransition(t));\n return;\n }\n\n // startTransition + startViewTransition\n if (transition) {\n // Interrupting an in-progress transition, cancel and let everything flush\n // out, and then kick off a new transition from the interruption state\n renderDfd && renderDfd.resolve();\n transition.skipTransition();\n setInterruption({\n state: newState,\n currentLocation: viewTransitionOpts.currentLocation,\n nextLocation: viewTransitionOpts.nextLocation,\n });\n } else {\n // Completed navigation update with opted-in view transitions, let 'er rip\n setPendingState(newState);\n setVtContext({\n isTransitioning: true,\n flushSync: false,\n currentLocation: viewTransitionOpts.currentLocation,\n nextLocation: viewTransitionOpts.nextLocation,\n });\n }\n },\n [router.window, reactDomFlushSyncImpl, transition, renderDfd]\n );\n\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n // When we start a view transition, create a Deferred we can use for the\n // eventual \"completed\" render\n React.useEffect(() => {\n if (vtContext.isTransitioning && !vtContext.flushSync) {\n setRenderDfd(new Deferred<void>());\n }\n }, [vtContext]);\n\n // Once the deferred is created, kick off startViewTransition() to update the\n // DOM and then wait on the Deferred to resolve (indicating the DOM update has\n // happened)\n React.useEffect(() => {\n if (renderDfd && pendingState && router.window) {\n let newState = pendingState;\n let renderPromise = renderDfd.promise;\n let transition = router.window.document.startViewTransition(async () => {\n React.startTransition(() => setStateImpl(newState));\n await renderPromise;\n });\n transition.finished.finally(() => {\n setRenderDfd(undefined);\n setTransition(undefined);\n setPendingState(undefined);\n setVtContext({ isTransitioning: false });\n });\n setTransition(transition);\n }\n }, [pendingState, renderDfd, router.window]);\n\n // When the new location finally renders and is committed to the DOM, this\n // effect will run to resolve the transition\n React.useEffect(() => {\n if (\n renderDfd &&\n pendingState &&\n state.location.key === pendingState.location.key\n ) {\n renderDfd.resolve();\n }\n }, [renderDfd, transition, state.location, pendingState]);\n\n // If we get interrupted with a new navigation during a transition, we skip\n // the active transition, let it cleanup, then kick it off again here\n React.useEffect(() => {\n if (!vtContext.isTransitioning && interruption) {\n setPendingState(interruption.state);\n setVtContext({\n isTransitioning: true,\n flushSync: false,\n currentLocation: interruption.currentLocation,\n nextLocation: interruption.nextLocation,\n });\n setInterruption(undefined);\n }\n }, [vtContext.isTransitioning, interruption]);\n\n let navigator = React.useMemo((): Navigator => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: (n) => router.navigate(n),\n push: (to, state, opts) =>\n router.navigate(to, {\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n replace: (to, state, opts) =>\n router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n };\n }, [router]);\n\n let basename = router.basename || \"/\";\n\n let dataRouterContext = React.useMemo(\n () => ({\n router,\n navigator,\n static: false,\n basename,\n }),\n [router, navigator, basename]\n );\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a <script> here\n // containing the hydrated server-side staticContext (from StaticRouterProvider).\n // useId relies on the component tree structure to generate deterministic id's\n // so we need to ensure it remains the same on the client even though\n // we don't need the <script> tag\n return (\n <>\n <DataRouterContext.Provider value={dataRouterContext}>\n <DataRouterStateContext.Provider value={state}>\n <FetchersContext.Provider value={fetcherData.current}>\n <ViewTransitionContext.Provider value={vtContext}>\n <Router\n basename={basename}\n location={state.location}\n navigationType={state.historyAction}\n navigator={navigator}\n >\n <MemoizedDataRoutes\n routes={router.routes}\n future={router.future}\n state={state}\n />\n </Router>\n </ViewTransitionContext.Provider>\n </FetchersContext.Provider>\n </DataRouterStateContext.Provider>\n </DataRouterContext.Provider>\n {null}\n </>\n );\n}\n\n// Memoize to avoid re-renders when updating `ViewTransitionContext`\nconst MemoizedDataRoutes = React.memo(DataRoutes);\n\nfunction DataRoutes({\n routes,\n future,\n state,\n}: {\n routes: DataRouteObject[];\n future: DataRouter[\"future\"];\n state: RouterState;\n}): React.ReactElement | null {\n return useRoutesImpl(routes, undefined, state, future);\n}\n\n/**\n * @category Types\n */\nexport interface MemoryRouterProps {\n basename?: string;\n children?: React.ReactNode;\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n}\n\n/**\n * A `<Router>` that stores all entries in memory.\n *\n * @category Router Components\n */\nexport function MemoryRouter({\n basename,\n children,\n initialEntries,\n initialIndex,\n}: MemoryRouterProps): React.ReactElement {\n let historyRef = React.useRef<MemoryHistory>();\n if (historyRef.current == null) {\n historyRef.current = createMemoryHistory({\n initialEntries,\n initialIndex,\n v5Compat: true,\n });\n }\n\n let history = historyRef.current;\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n React.startTransition(() => setStateImpl(newState));\n },\n [setStateImpl]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n />\n );\n}\n\n/**\n * @category Types\n */\nexport interface NavigateProps {\n to: To;\n replace?: boolean;\n state?: any;\n relative?: RelativeRoutingType;\n}\n\n/**\n * A component-based version of {@link useNavigate} to use in a [`React.Component\n * Class`](https://reactjs.org/docs/react-component.html) where hooks are not\n * able to be used.\n *\n * It's recommended to avoid using this component in favor of {@link useNavigate}\n *\n * @category Components\n */\nexport function Navigate({\n to,\n replace,\n state,\n relative,\n}: NavigateProps): null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of\n // the router loaded. We can help them understand how to avoid that.\n `<Navigate> may be used only in the context of a <Router> component.`\n );\n\n let { static: isStatic } = React.useContext(NavigationContext);\n\n warning(\n !isStatic,\n `<Navigate> must not be used on the initial render in a <StaticRouter>. ` +\n `This is a no-op, but you should modify your code so the <Navigate> is ` +\n `only ever rendered in response to some user interaction or state change.`\n );\n\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n let navigate = useNavigate();\n\n // Resolve the path outside of the effect so that when effects run twice in\n // StrictMode they navigate to the same place\n let path = resolveTo(\n to,\n getResolveToMatches(matches),\n locationPathname,\n relative === \"path\"\n );\n let jsonPath = JSON.stringify(path);\n\n React.useEffect(() => {\n navigate(JSON.parse(jsonPath), { replace, state, relative });\n }, [navigate, jsonPath, relative, replace, state]);\n\n return null;\n}\n\n/**\n * @category Types\n */\nexport interface OutletProps {\n /**\n Provides a context value to the element tree below the outlet. Use when the parent route needs to provide values to child routes.\n\n ```tsx\n <Outlet context={myContextValue} />\n ```\n\n Access the context with {@link useOutletContext}.\n */\n context?: unknown;\n}\n\n/**\n Renders the matching child route of a parent route or nothing if no child route matches.\n\n ```tsx\n import { Outlet } from \"react-router\"\n\n export default function SomeParent() {\n return (\n <div>\n <h1>Parent Content</h1>\n <Outlet />\n </div>\n );\n }\n ```\n\n @category Components\n */\nexport function Outlet(props: OutletProps): React.ReactElement | null {\n return useOutlet(props.context);\n}\n\n/**\n * @category Types\n */\nexport interface PathRouteProps {\n caseSensitive?: NonIndexRouteObject[\"caseSensitive\"];\n path?: NonIndexRouteObject[\"path\"];\n id?: NonIndexRouteObject[\"id\"];\n lazy?: LazyRouteFunction<NonIndexRouteObject>;\n loader?: NonIndexRouteObject[\"loader\"];\n action?: NonIndexRouteObject[\"action\"];\n hasErrorBoundary?: NonIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: NonIndexRouteObject[\"shouldRevalidate\"];\n handle?: NonIndexRouteObject[\"handle\"];\n index?: false;\n children?: React.ReactNode;\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n}\n\n/**\n * @category Types\n */\nexport interface LayoutRouteProps extends PathRouteProps {}\n\n/**\n * @category Types\n */\nexport interface IndexRouteProps {\n caseSensitive?: IndexRouteObject[\"caseSensitive\"];\n path?: IndexRouteObject[\"path\"];\n id?: IndexRouteObject[\"id\"];\n lazy?: LazyRouteFunction<IndexRouteObject>;\n loader?: IndexRouteObject[\"loader\"];\n action?: IndexRouteObject[\"action\"];\n hasErrorBoundary?: IndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: IndexRouteObject[\"shouldRevalidate\"];\n handle?: IndexRouteObject[\"handle\"];\n index: true;\n children?: undefined;\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n}\n\nexport type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;\n\n/**\n * Configures an element to render when a pattern matches the current location.\n * It must be rendered within a {@link Routes} element. Note that these routes\n * do not participate in data loading, actions, code splitting, or any other\n * route module features.\n *\n * @category Components\n */\nexport function Route(_props: RouteProps): React.ReactElement | null {\n invariant(\n false,\n `A <Route> is only ever to be used as the child of <Routes> element, ` +\n `never rendered directly. Please wrap your <Route> in a <Routes>.`\n );\n}\n\n/**\n * @category Types\n */\nexport interface RouterProps {\n basename?: string;\n children?: React.ReactNode;\n location: Partial<Location> | string;\n navigationType?: NavigationType;\n navigator: Navigator;\n static?: boolean;\n}\n\n/**\n * Provides location context for the rest of the app.\n *\n * Note: You usually won't render a `<Router>` directly. Instead, you'll render a\n * router that is more specific to your environment such as a `<BrowserRouter>`\n * in web browsers or a `<StaticRouter>` for server rendering.\n *\n * @category Components\n */\nexport function Router({\n basename: basenameProp = \"/\",\n children = null,\n location: locationProp,\n navigationType = NavigationType.Pop,\n navigator,\n static: staticProp = false,\n}: RouterProps): React.ReactElement | null {\n invariant(\n !useInRouterContext(),\n `You cannot render a <Router> inside another <Router>.` +\n ` You should never have more than one in your app.`\n );\n\n // Preserve trailing slashes on basename, so we can let the user control\n // the enforcement of trailing slashes throughout the app\n let basename = basenameProp.replace(/^\\/*/, \"/\");\n let navigationContext = React.useMemo(\n () => ({\n basename,\n navigator,\n static: staticProp,\n future: {},\n }),\n [basename, navigator, staticProp]\n );\n\n if (typeof locationProp === \"string\") {\n locationProp = parsePath(locationProp);\n }\n\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n state = null,\n key = \"default\",\n } = locationProp;\n\n let locationContext = React.useMemo(() => {\n let trailingPathname = stripBasename(pathname, basename);\n\n if (trailingPathname == null) {\n return null;\n }\n\n return {\n location: {\n pathname: trailingPathname,\n search,\n hash,\n state,\n key,\n },\n navigationType,\n };\n }, [basename, pathname, search, hash, state, key, navigationType]);\n\n warning(\n locationContext != null,\n `<Router basename=\"${basename}\"> is not able to match the URL ` +\n `\"${pathname}${search}${hash}\" because it does not start with the ` +\n `basename, so the <Router> won't render anything.`\n );\n\n if (locationContext == null) {\n return null;\n }\n\n return (\n <NavigationContext.Provider value={navigationContext}>\n <LocationContext.Provider children={children} value={locationContext} />\n </NavigationContext.Provider>\n );\n}\n\n/**\n * @category Types\n */\nexport interface RoutesProps {\n /**\n * Nested {@link Route} elements\n */\n children?: React.ReactNode;\n\n /**\n * The location to match against. Defaults to the current location.\n */\n location?: Partial<Location> | string;\n}\n\n/**\n Renders a branch of {@link Route | `<Routes>`} that best matches the current\n location. Note that these routes do not participate in data loading, actions,\n code splitting, or any other route module features.\n\n ```tsx\n import { Routes, Route } from \"react-router\"\n\n<Routes>\n <Route index element={<StepOne />} />\n <Route path=\"step-2\" element={<StepTwo />} />\n <Route path=\"step-3\" element={<StepThree />}>\n</Routes>\n ```\n\n @category Components\n */\nexport function Routes({\n children,\n location,\n}: RoutesProps): React.ReactElement | null {\n return useRoutes(createRoutesFromChildren(children), location);\n}\n\nexport interface AwaitResolveRenderFunction {\n (data: Awaited<any>): React.ReactNode;\n}\n\n/**\n * @category Types\n */\nexport interface AwaitProps {\n /**\n When using a function, the resolved value is provided as the parameter.\n\n ```tsx [2]\n <Await resolve={reviewsPromise}>\n {(resolvedReviews) => <Reviews items={resolvedReviews} />}\n </Await>\n ```\n\n When using React elements, {@link useAsyncValue} will provide the\n resolved value:\n\n ```tsx [2]\n <Await resolve={reviewsPromise}>\n <Reviews />\n </Await>\n\n function Reviews() {\n const resolvedReviews = useAsyncValue()\n return <div>...</div>\n }\n ```\n */\n children: React.ReactNode | AwaitResolveRenderFunction;\n\n /**\n The error element renders instead of the children when the promise rejects.\n\n ```tsx\n <Await\n errorElement={<div>Oops</div>}\n resolve={reviewsPromise}\n >\n <Reviews />\n </Await>\n ```\n\n To provide a more contextual error, you can use the {@link useAsyncError} in a\n child component\n\n ```tsx\n <Await\n errorElement={<ReviewsError />}\n resolve={reviewsPromise}\n >\n <Reviews />\n </Await>\n\n function ReviewsError() {\n const error = useAsyncError()\n return <div>Error loading reviews: {error.message}</div>\n }\n ```\n\n If you do not provide an errorElement, the rejected value will bubble up to\n the nearest route-level {@link NonIndexRouteObject#ErrorBoundary | ErrorBoundary} and be accessible\n via {@link useRouteError} hook.\n */\n errorElement?: React.ReactNode;\n\n /**\n Takes a promise returned from a {@link LoaderFunction | loader} value to be resolved and rendered.\n\n ```jsx\n import { useLoaderData, Await } from \"react-router\"\n\n export async function loader() {\n let reviews = getReviews() // not awaited\n let book = await getBook()\n return {\n book,\n reviews, // this is a promise\n }\n }\n\n export default function Book() {\n const {\n book,\n reviews, // this is the same promise\n } = useLoaderData()\n\n return (\n <div>\n <h1>{book.title}</h1>\n <p>{book.description}</p>\n <React.Suspense fallback={<ReviewsSkeleton />}>\n <Await\n // and is the promise we pass to Await\n resolve={reviews}\n >\n <Reviews />\n </Await>\n </React.Suspense>\n </div>\n );\n }\n ```\n */\n resolve: TrackedPromise | any;\n}\n\n/**\nUsed to render promise values with automatic error handling.\n\n```tsx\nimport { Await, useLoaderData } from \"react-router\";\n\nexport function loader() {\n // not awaited\n const reviews = getReviews()\n // awaited (blocks the transition)\n const book = await fetch(\"/api/book\").then((res) => res.json())\n return { book, reviews }\n}\n\nfunction Book() {\n const { book, reviews } = useLoaderData();\n return (\n <div>\n <h1>{book.title}</h1>\n <p>{book.description}</p>\n <React.Suspense fallback={<ReviewsSkeleton />}>\n <Await\n resolve={reviews}\n errorElement={\n <div>Could not load reviews 😬</div>\n }\n children={(resolvedReviews) => (\n <Reviews items={resolvedReviews} />\n )}\n />\n </React.Suspense>\n </div>\n );\n}\n```\n\n**Note:** `<Await>` expects to be rendered inside of a `<React.Suspense>`\n\n@category Components\n\n*/\nexport function Await({ children, errorElement, resolve }: AwaitProps) {\n return (\n <AwaitErrorBoundary resolve={resolve} errorElement={errorElement}>\n <ResolveAwait>{children}</ResolveAwait>\n </AwaitErrorBoundary>\n );\n}\n\ntype AwaitErrorBoundaryProps = React.PropsWithChildren<{\n errorElement?: React.ReactNode;\n resolve: TrackedPromise | any;\n}>;\n\ntype AwaitErrorBoundaryState = {\n error: any;\n};\n\nenum AwaitRenderStatus {\n pending,\n success,\n error,\n}\n\nclass AwaitErrorBoundary extends React.Component<\n AwaitErrorBoundaryProps,\n AwaitErrorBoundaryState\n> {\n constructor(props: AwaitErrorBoundaryProps) {\n super(props);\n this.state = { error: null };\n }\n\n static getDerivedStateFromError(error: any) {\n return { error };\n }\n\n componentDidCatch(error: any, errorInfo: any) {\n console.error(\n \"<Await> caught the following error during render\",\n error,\n errorInfo\n );\n }\n\n render() {\n let { children, errorElement, resolve } = this.props;\n\n let promise: TrackedPromise | null = null;\n let status: AwaitRenderStatus = AwaitRenderStatus.pending;\n\n if (!(resolve instanceof Promise)) {\n // Didn't get a promise - provide as a resolved promise\n status = AwaitRenderStatus.success;\n promise = Promise.resolve();\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n Object.defineProperty(promise, \"_data\", { get: () => resolve });\n } else if (this.state.error) {\n // Caught a render error, provide it as a rejected promise\n status = AwaitRenderStatus.error;\n let renderError = this.state.error;\n promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n Object.defineProperty(promise, \"_error\", { get: () => renderError });\n } else if ((resolve as TrackedPromise)._tracked) {\n // Already tracked promise - check contents\n promise = resolve;\n status =\n \"_error\" in promise\n ? AwaitRenderStatus.error\n : \"_data\" in promise\n ? AwaitRenderStatus.success\n : AwaitRenderStatus.pending;\n } else {\n // Raw (untracked) promise - track it\n status = AwaitRenderStatus.pending;\n Object.defineProperty(resolve, \"_tracked\", { get: () => true });\n promise = resolve.then(\n (data: any) =>\n Object.defineProperty(resolve, \"_data\", { get: () => data }),\n (error: any) =>\n Object.defineProperty(resolve, \"_error\", { get: () => error })\n );\n }\n\n if (status === AwaitRenderStatus.error && !errorElement) {\n // No errorElement, throw to the nearest route-level error boundary\n throw promise._error;\n }\n\n if (status === AwaitRenderStatus.error) {\n // Render via our errorElement\n return <AwaitContext.Provider value={promise} children={errorElement} />;\n }\n\n if (status === AwaitRenderStatus.success) {\n // Render children with resolved value\n return <AwaitContext.Provider value={promise} children={children} />;\n }\n\n // Throw to the suspense boundary\n throw promise;\n }\n}\n\n/**\n * @private\n * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`\n */\nfunction ResolveAwait({\n children,\n}: {\n children: React.ReactNode | AwaitResolveRenderFunction;\n}) {\n let data = useAsyncValue();\n let toRender = typeof children === \"function\" ? children(data) : children;\n return <>{toRender}</>;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// UTILS\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Creates a route config from a React \"children\" object, which is usually\n * either a `<Route>` element or an array of them. Used internally by\n * `<Routes>` to create a route config from its children.\n *\n * @category Utils\n */\nexport function createRoutesFromChildren(\n children: React.ReactNode,\n parentPath: number[] = []\n): RouteObject[] {\n let routes: RouteObject[] = [];\n\n React.Children.forEach(children, (element, index) => {\n if (!React.isValidElement(element)) {\n // Ignore non-elements. This allows people to more easily inline\n // conditionals in their route config.\n return;\n }\n\n let treePath = [...parentPath, index];\n\n if (element.type === React.Fragment) {\n // Transparently support React.Fragment and its children.\n routes.push.apply(\n routes,\n createRoutesFromChildren(element.props.children, treePath)\n );\n return;\n }\n\n invariant(\n element.type === Route,\n `[${\n typeof element.type === \"string\" ? element.type : element.type.name\n }] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`\n );\n\n invariant(\n !element.props.index || !element.props.children,\n \"An index route cannot have child routes.\"\n );\n\n let route: RouteObject = {\n id: element.props.id || treePath.join(\"-\"),\n caseSensitive: element.props.caseSensitive,\n element: element.props.element,\n Component: element.props.Component,\n index: element.props.index,\n path: element.props.path,\n loader: element.props.loader,\n action: element.props.action,\n hydrateFallbackElement: element.props.hydrateFallbackElement,\n HydrateFallback: element.props.HydrateFallback,\n errorElement: element.props.errorElement,\n ErrorBoundary: element.props.ErrorBoundary,\n hasErrorBoundary:\n element.props.hasErrorBoundary === true ||\n element.props.ErrorBoundary != null ||\n element.props.errorElement != null,\n shouldRevalidate: element.props.shouldRevalidate,\n handle: element.props.handle,\n lazy: element.props.lazy,\n };\n\n if (element.props.children) {\n route.children = createRoutesFromChildren(\n element.props.children,\n treePath\n );\n }\n\n routes.push(route);\n });\n\n return routes;\n}\n\n/**\n * Renders the result of `matchRoutes()` into a React element.\n *\n * @category Utils\n */\nexport function renderMatches(\n matches: RouteMatch[] | null\n): React.ReactElement | null {\n return _renderMatches(matches);\n}\n","import { warning } from \"../router/history\";\nimport type { RelativeRoutingType } from \"../router/router\";\nimport type { FormEncType, HTMLFormMethod } from \"../router/utils\";\nimport { stripBasename } from \"../router/utils\";\n\nexport const defaultMethod: HTMLFormMethod = \"get\";\nconst defaultEncType: FormEncType = \"application/x-www-form-urlencoded\";\n\nexport function isHtmlElement(object: any): object is HTMLElement {\n return object != null && typeof object.tagName === \"string\";\n}\n\nexport function isButtonElement(object: any): object is HTMLButtonElement {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"button\";\n}\n\nexport function isFormElement(object: any): object is HTMLFormElement {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"form\";\n}\n\nexport function isInputElement(object: any): object is HTMLInputElement {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"input\";\n}\n\ntype LimitedMouseEvent = Pick<\n MouseEvent,\n \"button\" | \"metaKey\" | \"altKey\" | \"ctrlKey\" | \"shiftKey\"\n>;\n\nfunction isModifiedEvent(event: LimitedMouseEvent) {\n return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);\n}\n\nexport function shouldProcessLinkClick(\n event: LimitedMouseEvent,\n target?: string\n) {\n return (\n event.button === 0 && // Ignore everything but left clicks\n (!target || target === \"_self\") && // Let browser handle \"target=_blank\" etc.\n !isModifiedEvent(event) // Ignore clicks with modifier keys\n );\n}\n\nexport type ParamKeyValuePair = [string, string];\n\nexport type URLSearchParamsInit =\n | string\n | ParamKeyValuePair[]\n | Record<string, string | string[]>\n | URLSearchParams;\n\n/**\n Creates a URLSearchParams object using the given initializer.\n\n This is identical to `new URLSearchParams(init)` except it also\n supports arrays as values in the object form of the initializer\n instead of just strings. This is convenient when you need multiple\n values for a given key, but don't want to use an array initializer.\n\n For example, instead of:\n\n ```tsx\n let searchParams = new URLSearchParams([\n ['sort', 'name'],\n ['sort', 'price']\n ]);\n ```\n you can do:\n\n ```\n let searchParams = createSearchParams({\n sort: ['name', 'price']\n });\n ```\n\n @category Utils\n */\nexport function createSearchParams(\n init: URLSearchParamsInit = \"\"\n): URLSearchParams {\n return new URLSearchParams(\n typeof init === \"string\" ||\n Array.isArray(init) ||\n init instanceof URLSearchParams\n ? init\n : Object.keys(init).reduce((memo, key) => {\n let value = init[key];\n return memo.concat(\n Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]\n );\n }, [] as ParamKeyValuePair[])\n );\n}\n\nexport function getSearchParamsForLocation(\n locationSearch: string,\n defaultSearchParams: URLSearchParams | null\n) {\n let searchParams = createSearchParams(locationSearch);\n\n if (defaultSearchParams) {\n // Use `defaultSearchParams.forEach(...)` here instead of iterating of\n // `defaultSearchParams.keys()` to work-around a bug in Firefox related to\n // web extensions. Relevant Bugzilla tickets:\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984\n defaultSearchParams.forEach((_, key) => {\n if (!searchParams.has(key)) {\n defaultSearchParams.getAll(key).forEach((value) => {\n searchParams.append(key, value);\n });\n }\n });\n }\n\n return searchParams;\n}\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\nexport type SubmitTarget =\n | HTMLFormElement\n | HTMLButtonElement\n | HTMLInputElement\n | FormData\n | URLSearchParams\n | JsonValue\n | null;\n\n// One-time check for submitter support\nlet _formDataSupportsSubmitter: boolean | null = null;\n\nfunction isFormDataSubmitterSupported() {\n if (_formDataSupportsSubmitter === null) {\n try {\n new FormData(\n document.createElement(\"form\"),\n // @ts-expect-error if FormData supports the submitter parameter, this will throw\n 0\n );\n _formDataSupportsSubmitter = false;\n } catch (e) {\n _formDataSupportsSubmitter = true;\n }\n }\n return _formDataSupportsSubmitter;\n}\n\n/**\n * Submit options shared by both navigations and fetchers\n */\ninterface SharedSubmitOptions {\n /**\n * The HTTP method used to submit the form. Overrides `<form method>`.\n * Defaults to \"GET\".\n */\n method?: HTMLFormMethod;\n\n /**\n * The action URL path used to submit the form. Overrides `<form action>`.\n * Defaults to the path of the current route.\n */\n action?: string;\n\n /**\n * The encoding used to submit the form. Overrides `<form encType>`.\n * Defaults to \"application/x-www-form-urlencoded\".\n */\n encType?: FormEncType;\n\n /**\n * Determines whether the form action is relative to the route hierarchy or\n * the pathname. Use this if you want to opt out of navigating the route\n * hierarchy and want to instead route based on /-delimited URL segments\n */\n relative?: RelativeRoutingType;\n\n /**\n * In browser-based environments, prevent resetting scroll after this\n * navigation when using the <ScrollRestoration> component\n */\n preventScrollReset?: boolean;\n\n /**\n * Enable flushSync for this submission's state updates\n */\n flushSync?: boolean;\n}\n\n/**\n * Submit options available to fetchers\n */\nexport interface FetcherSubmitOptions extends SharedSubmitOptions {}\n\n/**\n * Submit options available to navigations\n */\nexport interface SubmitOptions extends FetcherSubmitOptions {\n /**\n * Set `true` to replace the current entry in the browser's history stack\n * instead of creating a new one (i.e. stay on \"the same page\"). Defaults\n * to `false`.\n */\n replace?: boolean;\n\n /**\n * State object to add to the history stack entry for this navigation\n */\n state?: any;\n\n /**\n * Indicate a specific fetcherKey to use when using navigate=false\n */\n fetcherKey?: string;\n\n /**\n * navigate=false will use a fetcher instead of a navigation\n */\n navigate?: boolean;\n\n /**\n * Enable view transitions on this submission navigation\n */\n viewTransition?: boolean;\n}\n\nconst supportedFormEncTypes: Set<FormEncType> = new Set([\n \"application/x-www-form-urlencoded\",\n \"multipart/form-data\",\n \"text/plain\",\n]);\n\nfunction getFormEncType(encType: string | null) {\n if (encType != null && !supportedFormEncTypes.has(encType as FormEncType)) {\n warning(\n false,\n `\"${encType}\" is not a valid \\`encType\\` for \\`<Form>\\`/\\`<fetcher.Form>\\` ` +\n `and will default to \"${defaultEncType}\"`\n );\n\n return null;\n }\n return encType;\n}\n\nexport function getFormSubmissionInfo(\n target: SubmitTarget,\n basename: string\n): {\n action: string | null;\n method: string;\n encType: string;\n formData: FormData | undefined;\n body: any;\n} {\n let method: string;\n let action: string | null;\n let encType: string;\n let formData: FormData | undefined;\n let body: any;\n\n if (isFormElement(target)) {\n // When grabbing the action from the element, it will have had the basename\n // prefixed to ensure non-JS scenarios work, so strip it since we'll\n // re-prefix in the router\n let attr = target.getAttribute(\"action\");\n action = attr ? stripBasename(attr, basename) : null;\n method = target.getAttribute(\"method\") || defaultMethod;\n encType = getFormEncType(target.getAttribute(\"enctype\")) || defaultEncType;\n\n formData = new FormData(target);\n } else if (\n isButtonElement(target) ||\n (isInputElement(target) &&\n (target.type === \"submit\" || target.type === \"image\"))\n ) {\n let form = target.form;\n\n if (form == null) {\n throw new Error(\n `Cannot submit a <button> or <input type=\"submit\"> without a <form>`\n );\n }\n\n // <button>/<input type=\"submit\"> may override attributes of <form>\n\n // When grabbing the action from the element, it will have had the basename\n // prefixed to ensure non-JS scenarios work, so strip it since we'll\n // re-prefix in the router\n let attr = target.getAttribute(\"formaction\") || form.getAttribute(\"action\");\n action = attr ? stripBasename(attr, basename) : null;\n\n method =\n target.getAttribute(\"formmethod\") ||\n form.getAttribute(\"method\") ||\n defaultMethod;\n encType =\n getFormEncType(target.getAttribute(\"formenctype\")) ||\n getFormEncType(form.getAttribute(\"enctype\")) ||\n defaultEncType;\n\n // Build a FormData object populated from a form and submitter\n formData = new FormData(form, target);\n\n // If this browser doesn't support the `FormData(el, submitter)` format,\n // then tack on the submitter value at the end. This is a lightweight\n // solution that is not 100% spec compliant. For complete support in older\n // browsers, consider using the `formdata-submitter-polyfill` package\n if (!isFormDataSubmitterSupported()) {\n let { name, type, value } = target;\n if (type === \"image\") {\n let prefix = name ? `${name}.` : \"\";\n formData.append(`${prefix}x`, \"0\");\n formData.append(`${prefix}y`, \"0\");\n } else if (name) {\n formData.append(name, value);\n }\n }\n } else if (isHtmlElement(target)) {\n throw new Error(\n `Cannot submit element that is not <form>, <button>, or ` +\n `<input type=\"submit|image\">`\n );\n } else {\n method = defaultMethod;\n action = null;\n encType = defaultEncType;\n body = target;\n }\n\n // Send body for <Form encType=\"text/plain\" so we encode it into text\n if (formData && encType === \"text/plain\") {\n body = formData;\n formData = undefined;\n }\n\n return { action, method: method.toLowerCase(), encType, formData, body };\n}\n","export default function invariant(\n value: boolean,\n message?: string\n): asserts value;\nexport default function invariant<T>(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport default function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n","import type { ComponentType, ReactElement } from \"react\";\nimport type { Location } from \"../../router/history\";\nimport type {\n ActionFunction as RRActionFunction,\n ActionFunctionArgs as RRActionFunctionArgs,\n LoaderFunction as RRLoaderFunction,\n LoaderFunctionArgs as RRLoaderFunctionArgs,\n Params,\n ShouldRevalidateFunction,\n LoaderFunctionArgs,\n} from \"../../router/utils\";\n\nimport type { SerializeFrom } from \"./components\";\nimport type { AppData } from \"./data\";\nimport type { EntryRoute } from \"./routes\";\nimport type { DataRouteMatch } from \"../../context\";\nimport type { LinkDescriptor } from \"../../router/links\";\n\nexport interface RouteModules {\n [routeId: string]: RouteModule | undefined;\n}\n\nexport interface RouteModule {\n clientAction?: ClientActionFunction;\n clientLoader?: ClientLoaderFunction;\n ErrorBoundary?: ErrorBoundaryComponent;\n HydrateFallback?: HydrateFallbackComponent;\n Layout?: LayoutComponent;\n default: RouteComponent;\n handle?: RouteHandle;\n links?: LinksFunction;\n meta?: MetaFunction;\n shouldRevalidate?: ShouldRevalidateFunction;\n}\n\n/**\n * A function that handles data mutations for a route on the client\n */\nexport type ClientActionFunction = (\n args: ClientActionFunctionArgs\n) => ReturnType<RRActionFunction>;\n\n/**\n * Arguments passed to a route `clientAction` function\n */\nexport type ClientActionFunctionArgs = RRActionFunctionArgs<undefined> & {\n serverAction: <T = AppData>() => Promise<SerializeFrom<T>>;\n};\n\n/**\n * A function that loads data for a route on the client\n */\nexport type ClientLoaderFunction = ((\n args: ClientLoaderFunctionArgs\n) => ReturnType<RRLoaderFunction>) & {\n hydrate?: boolean;\n};\n\n/**\n * Arguments passed to a route `clientLoader` function\n */\nexport type ClientLoaderFunctionArgs = RRLoaderFunctionArgs<undefined> & {\n serverLoader: <T = AppData>() => Promise<SerializeFrom<T>>;\n};\n\n/**\n * ErrorBoundary to display for this route\n */\nexport type ErrorBoundaryComponent = ComponentType;\n\n/**\n * `<Route HydrateFallback>` component to render on initial loads\n * when client loaders are present\n */\nexport type HydrateFallbackComponent = ComponentType;\n\n/**\n * Optional, root-only `<Route Layout>` component to wrap the root content in.\n * Useful for defining the <html>/<head>/<body> document shell shared by the\n * Component, HydrateFallback, and ErrorBoundary\n */\nexport type LayoutComponent = ComponentType<{\n children: ReactElement<\n unknown,\n ErrorBoundaryComponent | HydrateFallbackComponent | RouteComponent\n >;\n}>;\n\n/**\n * A function that defines `<link>` tags to be inserted into the `<head>` of\n * the document on route transitions.\n *\n * @see https://remix.run/route/meta\n */\nexport interface LinksFunction {\n (): LinkDescriptor[];\n}\n\n// Loose copy from @react-router/server-runtime to avoid circular imports\ntype LoaderFunction = (\n args: LoaderFunctionArgs & {\n // Context is always provided in Remix, and typed for module augmentation support.\n context: unknown;\n // TODO: (v7) Make this non-optional once single-fetch is the default\n response?: {\n status: number | undefined;\n headers: Headers;\n };\n }\n) => ReturnType<RRLoaderFunction>;\n\nexport interface MetaMatch<\n RouteId extends string = string,\n Loader extends LoaderFunction | unknown = unknown\n> {\n id: RouteId;\n pathname: DataRouteMatch[\"pathname\"];\n data: Loader extends LoaderFunction ? SerializeFrom<Loader> : unknown;\n handle?: RouteHandle;\n params: DataRouteMatch[\"params\"];\n meta: MetaDescriptor[];\n error?: unknown;\n}\n\nexport type MetaMatches<\n MatchLoaders extends Record<string, LoaderFunction | unknown> = Record<\n string,\n unknown\n >\n> = Array<\n {\n [K in keyof MatchLoaders]: MetaMatch<\n Exclude<K, number | symbol>,\n MatchLoaders[K]\n >;\n }[keyof MatchLoaders]\n>;\n\nexport interface MetaArgs<\n Loader extends LoaderFunction | unknown = unknown,\n MatchLoaders extends Record<string, LoaderFunction | unknown> = Record<\n string,\n unknown\n >\n> {\n data:\n | (Loader extends LoaderFunction ? SerializeFrom<Loader> : AppData)\n | undefined;\n params: Params;\n location: Location;\n matches: MetaMatches<MatchLoaders>;\n error?: unknown;\n}\n\nexport interface MetaFunction<\n Loader extends LoaderFunction | unknown = unknown,\n MatchLoaders extends Record<string, LoaderFunction | unknown> = Record<\n string,\n unknown\n >\n> {\n (args: MetaArgs<Loader, MatchLoaders>): MetaDescriptor[] | undefined;\n}\n\nexport type MetaDescriptor =\n | { charSet: \"utf-8\" }\n | { title: string }\n | { name: string; content: string }\n | { property: string; content: string }\n | { httpEquiv: string; content: string }\n | { \"script:ld+json\": LdJsonObject }\n | { tagName: \"meta\" | \"link\"; [name: string]: string }\n | { [name: string]: unknown };\n\ntype LdJsonObject = { [Key in string]: LdJsonValue } & {\n [Key in string]?: LdJsonValue | undefined;\n};\ntype LdJsonArray = LdJsonValue[] | readonly LdJsonValue[];\ntype LdJsonPrimitive = string | number | boolean | null;\ntype LdJsonValue = LdJsonPrimitive | LdJsonObject | LdJsonArray;\n\n/**\n * A React component that is rendered for a route.\n */\nexport type RouteComponent = ComponentType<{}>;\n\n/**\n * An arbitrary object that is associated with a route.\n *\n * @see https://remix.run/route/handle\n */\nexport type RouteHandle = unknown;\n\nexport async function loadRouteModule(\n route: EntryRoute,\n routeModulesCache: RouteModules\n): Promise<RouteModule> {\n if (route.id in routeModulesCache) {\n return routeModulesCache[route.id] as RouteModule;\n }\n\n try {\n let routeModule = await import(/* webpackIgnore: true */ route.module);\n routeModulesCache[route.id] = routeModule;\n return routeModule;\n } catch (error: unknown) {\n // If we can't load the route it's likely one of 2 things:\n // - User got caught in the middle of a deploy and the CDN no longer has the\n // asset we're trying to import! Reload from the server and the user\n // (should) get the new manifest--unless the developer purged the static\n // assets, the manifest path, but not the documents 😬\n // - Or, the asset trying to be imported has an error (usually in vite dev\n // mode), so the best we can do here is log the error for visibility\n // (via `Preserve log`) and reload\n\n // Log the error so it can be accessed via the `Preserve Log` setting\n console.error(\n `Error loading route module \\`${route.module}\\`, reloading page...`\n );\n console.error(error);\n\n if (\n window.__reactRouterContext &&\n window.__reactRouterContext.isSpaMode &&\n // @ts-expect-error\n typeof import.meta.hot !== \"undefined\"\n ) {\n // In SPA Mode (which implies vite) we don't want to perform a hard reload\n // on dev-time errors since it's a vite compilation error and a reload is\n // just going to fail with the same issue. Let the UI bubble to the error\n // boundary and let them see the error in the overlay or the dev server log\n throw error;\n }\n\n window.location.reload();\n\n return new Promise(() => {\n // check out of this hook cause the DJs never gonna re[s]olve this\n });\n }\n}\n","import type { Location } from \"../../router/history\";\nimport { parsePath } from \"../../router/history\";\nimport type { AgnosticDataRouteMatch } from \"../../router/utils\";\n\nimport type { AssetsManifest } from \"./entry\";\nimport type { RouteModules, RouteModule } from \"./routeModules\";\nimport type { EntryRoute } from \"./routes\";\nimport { loadRouteModule } from \"./routeModules\";\nimport type {\n HtmlLinkDescriptor,\n LinkDescriptor,\n PageLinkDescriptor,\n} from \"../../router/links\";\n\n/**\n * Gets all the links for a set of matches. The modules are assumed to have been\n * loaded already.\n */\nexport function getKeyedLinksForMatches(\n matches: AgnosticDataRouteMatch[],\n routeModules: RouteModules,\n manifest: AssetsManifest\n): KeyedLinkDescriptor[] {\n let descriptors = matches\n .map((match): LinkDescriptor[][] => {\n let module = routeModules[match.route.id];\n let route = manifest.routes[match.route.id];\n return [\n route.css ? route.css.map((href) => ({ rel: \"stylesheet\", href })) : [],\n module?.links?.() || [],\n ];\n })\n .flat(2);\n\n let preloads = getCurrentPageModulePreloadHrefs(matches, manifest);\n return dedupeLinkDescriptors(descriptors, preloads);\n}\n\nexport async function prefetchStyleLinks(\n route: EntryRoute,\n routeModule: RouteModule\n): Promise<void> {\n if ((!route.css && !routeModule.links) || !isPreloadSupported()) return;\n\n let descriptors = [];\n if (route.css) {\n descriptors.push(...route.css.map((href) => ({ rel: \"stylesheet\", href })));\n }\n if (routeModule.links) {\n descriptors.push(...routeModule.links());\n }\n if (descriptors.length === 0) return;\n\n let styleLinks: HtmlLinkDescriptor[] = [];\n for (let descriptor of descriptors) {\n if (!isPageLinkDescriptor(descriptor) && descriptor.rel === \"stylesheet\") {\n styleLinks.push({\n ...descriptor,\n rel: \"preload\",\n as: \"style\",\n } as HtmlLinkDescriptor);\n }\n }\n\n // don't block for non-matching media queries, or for stylesheets that are\n // already in the DOM (active route revalidations)\n let matchingLinks = styleLinks.filter(\n (link) =>\n (!link.media || window.matchMedia(link.media).matches) &&\n !document.querySelector(`link[rel=\"stylesheet\"][href=\"${link.href}\"]`)\n );\n\n await Promise.all(matchingLinks.map(prefetchStyleLink));\n}\n\nasync function prefetchStyleLink(\n descriptor: HtmlLinkDescriptor\n): Promise<void> {\n return new Promise((resolve) => {\n let link = document.createElement(\"link\");\n Object.assign(link, descriptor);\n\n function removeLink() {\n // if a navigation interrupts this prefetch React will update the <head>\n // and remove the link we put in there manually, so we check if it's still\n // there before trying to remove it\n if (document.head.contains(link)) {\n document.head.removeChild(link);\n }\n }\n\n link.onload = () => {\n removeLink();\n resolve();\n };\n\n link.onerror = () => {\n removeLink();\n resolve();\n };\n\n document.head.appendChild(link);\n });\n}\n\n////////////////////////////////////////////////////////////////////////////////\nexport function isPageLinkDescriptor(\n object: any\n): object is PageLinkDescriptor {\n return object != null && typeof object.page === \"string\";\n}\n\nfunction isHtmlLinkDescriptor(object: any): object is HtmlLinkDescriptor {\n if (object == null) {\n return false;\n }\n\n // <link> may not have an href if <link rel=\"preload\"> is used with imageSrcSet + imageSizes\n // https://github.com/remix-run/remix/issues/184\n // https://html.spec.whatwg.org/commit-snapshots/cb4f5ff75de5f4cbd7013c4abad02f21c77d4d1c/#attr-link-imagesrcset\n if (object.href == null) {\n return (\n object.rel === \"preload\" &&\n typeof object.imageSrcSet === \"string\" &&\n typeof object.imageSizes === \"string\"\n );\n }\n\n return typeof object.rel === \"string\" && typeof object.href === \"string\";\n}\n\nexport type KeyedHtmlLinkDescriptor = { key: string; link: HtmlLinkDescriptor };\n\nexport async function getKeyedPrefetchLinks(\n matches: AgnosticDataRouteMatch[],\n manifest: AssetsManifest,\n routeModules: RouteModules\n): Promise<KeyedHtmlLinkDescriptor[]> {\n let links = await Promise.all(\n matches.map(async (match) => {\n let mod = await loadRouteModule(\n manifest.routes[match.route.id],\n routeModules\n );\n return mod.links ? mod.links() : [];\n })\n );\n\n return dedupeLinkDescriptors(\n links\n .flat(1)\n .filter(isHtmlLinkDescriptor)\n .filter((link) => link.rel === \"stylesheet\" || link.rel === \"preload\")\n .map((link) =>\n link.rel === \"stylesheet\"\n ? ({ ...link, rel: \"prefetch\", as: \"style\" } as HtmlLinkDescriptor)\n : ({ ...link, rel: \"prefetch\" } as HtmlLinkDescriptor)\n )\n );\n}\n\n// This is ridiculously identical to transition.ts `filterMatchesToLoad`\nexport function getNewMatchesForLinks(\n page: string,\n nextMatches: AgnosticDataRouteMatch[],\n currentMatches: AgnosticDataRouteMatch[],\n manifest: AssetsManifest,\n location: Location,\n mode: \"data\" | \"assets\"\n): AgnosticDataRouteMatch[] {\n let path = parsePathPatch(page);\n\n let isNew = (match: AgnosticDataRouteMatch, index: number) => {\n if (!currentMatches[index]) return true;\n return match.route.id !== currentMatches[index].route.id;\n };\n\n let matchPathChanged = (match: AgnosticDataRouteMatch, index: number) => {\n return (\n // param change, /users/123 -> /users/456\n currentMatches[index].pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentMatches[index].route.path?.endsWith(\"*\") &&\n currentMatches[index].params[\"*\"] !== match.params[\"*\"])\n );\n };\n\n // NOTE: keep this mostly up-to-date w/ the transition data diff, but this\n // version doesn't care about submissions\n let newMatches =\n mode === \"data\" && location.search !== path.search\n ? // this is really similar to stuff in transition.ts, maybe somebody smarter\n // than me (or in less of a hurry) can share some of it. You're the best.\n nextMatches.filter((match, index) => {\n let manifestRoute = manifest.routes[match.route.id];\n if (!manifestRoute.hasLoader) {\n return false;\n }\n\n if (isNew(match, index) || matchPathChanged(match, index)) {\n return true;\n }\n\n if (match.route.shouldRevalidate) {\n let routeChoice = match.route.shouldRevalidate({\n currentUrl: new URL(\n location.pathname + location.search + location.hash,\n window.origin\n ),\n currentParams: currentMatches[0]?.params || {},\n nextUrl: new URL(page, window.origin),\n nextParams: match.params,\n defaultShouldRevalidate: true,\n });\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n return true;\n })\n : nextMatches.filter((match, index) => {\n let manifestRoute = manifest.routes[match.route.id];\n return (\n (mode === \"assets\" || manifestRoute.hasLoader) &&\n (isNew(match, index) || matchPathChanged(match, index))\n );\n });\n\n return newMatches;\n}\n\nexport function getModuleLinkHrefs(\n matches: AgnosticDataRouteMatch[],\n manifestPatch: AssetsManifest\n): string[] {\n return dedupeHrefs(\n matches\n .map((match) => {\n let route = manifestPatch.routes[match.route.id];\n let hrefs = [route.module];\n if (route.imports) {\n hrefs = hrefs.concat(route.imports);\n }\n return hrefs;\n })\n .flat(1)\n );\n}\n\n// The `<Script>` will render rel=modulepreload for the current page, we don't\n// need to include them in a page prefetch, this gives us the list to remove\n// while deduping.\nfunction getCurrentPageModulePreloadHrefs(\n matches: AgnosticDataRouteMatch[],\n manifest: AssetsManifest\n): string[] {\n return dedupeHrefs(\n matches\n .map((match) => {\n let route = manifest.routes[match.route.id];\n let hrefs = [route.module];\n\n if (route.imports) {\n hrefs = hrefs.concat(route.imports);\n }\n\n return hrefs;\n })\n .flat(1)\n );\n}\n\nfunction dedupeHrefs(hrefs: string[]): string[] {\n return [...new Set(hrefs)];\n}\n\nfunction sortKeys<Obj extends { [Key in keyof Obj]: Obj[Key] }>(obj: Obj): Obj {\n let sorted = {} as Obj;\n let keys = Object.keys(obj).sort();\n\n for (let key of keys) {\n sorted[key as keyof Obj] = obj[key as keyof Obj];\n }\n\n return sorted;\n}\n\ntype KeyedLinkDescriptor<Descriptor extends LinkDescriptor = LinkDescriptor> = {\n key: string;\n link: Descriptor;\n};\n\nfunction dedupeLinkDescriptors<Descriptor extends LinkDescriptor>(\n descriptors: Descriptor[],\n preloads?: string[]\n): KeyedLinkDescriptor<Descriptor>[] {\n let set = new Set();\n let preloadsSet = new Set(preloads);\n\n return descriptors.reduce((deduped, descriptor) => {\n let alreadyModulePreload =\n preloads &&\n !isPageLinkDescriptor(descriptor) &&\n descriptor.as === \"script\" &&\n descriptor.href &&\n preloadsSet.has(descriptor.href);\n\n if (alreadyModulePreload) {\n return deduped;\n }\n\n let key = JSON.stringify(sortKeys(descriptor));\n if (!set.has(key)) {\n set.add(key);\n deduped.push({ key, link: descriptor });\n }\n\n return deduped;\n }, [] as KeyedLinkDescriptor<Descriptor>[]);\n}\n\n// https://github.com/remix-run/history/issues/897\nfunction parsePathPatch(href: string) {\n let path = parsePath(href);\n if (path.search === undefined) path.search = \"\";\n return path;\n}\n\n// Detect if this browser supports <link rel=\"preload\"> (or has it enabled).\n// Originally added to handle the firefox `network.preload` config:\n// https://bugzilla.mozilla.org/show_bug.cgi?id=1847811\nlet _isPreloadSupported: boolean | undefined;\nfunction isPreloadSupported(): boolean {\n if (_isPreloadSupported !== undefined) {\n return _isPreloadSupported;\n }\n let el: HTMLLinkElement | null = document.createElement(\"link\");\n _isPreloadSupported = el.relList.supports(\"preload\");\n el = null;\n return _isPreloadSupported;\n}\n","// This escapeHtml utility is based on https://github.com/zertosh/htmlescape\n// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE\n\n// We've chosen to inline the utility here to reduce the number of npm dependencies we have,\n// slightly decrease the code size compared the original package and make it esm compatible.\n\nconst ESCAPE_LOOKUP: { [match: string]: string } = {\n \"&\": \"\\\\u0026\",\n \">\": \"\\\\u003e\",\n \"<\": \"\\\\u003c\",\n \"\\u2028\": \"\\\\u2028\",\n \"\\u2029\": \"\\\\u2029\",\n};\n\nconst ESCAPE_REGEX = /[&><\\u2028\\u2029]/g;\n\nexport function escapeHtml(html: string) {\n return html.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);\n}\n\nexport interface SafeHtml {\n __html: string;\n}\n\nexport function createHtml(html: string): SafeHtml {\n return { __html: html };\n}\n","import \"../global\";\n\n/**\n * Data for a route that was returned from a `loader()`.\n */\nexport type AppData = unknown;\n\nexport function isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nexport async function createRequestInit(\n request: Request\n): Promise<RequestInit> {\n let init: RequestInit = { signal: request.signal };\n\n if (request.method !== \"GET\") {\n init.method = request.method;\n\n let contentType = request.headers.get(\"Content-Type\");\n\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n init.headers = { \"Content-Type\": contentType };\n init.body = JSON.stringify(await request.json());\n } else if (contentType && /\\btext\\/plain\\b/.test(contentType)) {\n init.headers = { \"Content-Type\": contentType };\n init.body = await request.text();\n } else if (\n contentType &&\n /\\bapplication\\/x-www-form-urlencoded\\b/.test(contentType)\n ) {\n init.body = new URLSearchParams(await request.text());\n } else {\n init.body = await request.formData();\n }\n }\n\n return init;\n}\n","import * as React from \"react\";\nimport { decode } from \"turbo-stream\";\nimport type { Router as DataRouter } from \"../../router/router\";\nimport type {\n DataStrategyFunction,\n DataStrategyFunctionArgs,\n DataStrategyResult,\n DataStrategyMatch,\n} from \"../../router/utils\";\nimport {\n ErrorResponseImpl,\n isRouteErrorResponse,\n redirect,\n data,\n} from \"../../router/utils\";\nimport { createRequestInit, isResponse } from \"./data\";\nimport type { AssetsManifest, EntryContext } from \"./entry\";\nimport { escapeHtml } from \"./markup\";\nimport type { RouteModules } from \"./routeModules\";\nimport invariant from \"./invariant\";\n\nexport const SingleFetchRedirectSymbol = Symbol(\"SingleFetchRedirect\");\n\nexport type SingleFetchRedirectResult = {\n redirect: string;\n status: number;\n revalidate: boolean;\n reload: boolean;\n replace: boolean;\n};\n\nexport type SingleFetchResult =\n | { data: unknown }\n | { error: unknown }\n | SingleFetchRedirectResult;\n\nexport type SingleFetchResults = {\n [key: string]: SingleFetchResult;\n [SingleFetchRedirectSymbol]?: SingleFetchRedirectResult;\n};\n\ninterface StreamTransferProps {\n context: EntryContext;\n identifier: number;\n reader: ReadableStreamDefaultReader<Uint8Array>;\n textDecoder: TextDecoder;\n nonce?: string;\n}\n\n// StreamTransfer recursively renders down chunks of the `serverHandoffStream`\n// into the client-side `streamController`\nexport function StreamTransfer({\n context,\n identifier,\n reader,\n textDecoder,\n nonce,\n}: StreamTransferProps) {\n // If the user didn't render the <Scripts> component then we don't have to\n // bother streaming anything in\n if (!context.renderMeta || !context.renderMeta.didRenderScripts) {\n return null;\n }\n\n if (!context.renderMeta.streamCache) {\n context.renderMeta.streamCache = {};\n }\n let { streamCache } = context.renderMeta;\n let promise = streamCache[identifier];\n if (!promise) {\n promise = streamCache[identifier] = reader\n .read()\n .then((result) => {\n streamCache[identifier].result = {\n done: result.done,\n value: textDecoder.decode(result.value, { stream: true }),\n };\n })\n .catch((e) => {\n streamCache[identifier].error = e;\n });\n }\n\n if (promise.error) {\n throw promise.error;\n }\n if (promise.result === undefined) {\n throw promise;\n }\n\n let { done, value } = promise.result;\n let scriptTag = value ? (\n <script\n nonce={nonce}\n dangerouslySetInnerHTML={{\n __html: `window.__reactRouterContext.streamController.enqueue(${escapeHtml(\n JSON.stringify(value)\n )});`,\n }}\n />\n ) : null;\n\n if (done) {\n return (\n <>\n {scriptTag}\n <script\n nonce={nonce}\n dangerouslySetInnerHTML={{\n __html: `window.__reactRouterContext.streamController.close();`,\n }}\n />\n </>\n );\n } else {\n return (\n <>\n {scriptTag}\n <React.Suspense>\n <StreamTransfer\n context={context}\n identifier={identifier + 1}\n reader={reader}\n textDecoder={textDecoder}\n nonce={nonce}\n />\n </React.Suspense>\n </>\n );\n }\n}\n\nexport function getSingleFetchDataStrategy(\n manifest: AssetsManifest,\n routeModules: RouteModules,\n getRouter: () => DataRouter\n): DataStrategyFunction {\n return async ({ request, matches, fetcherKey }) => {\n // Actions are simple and behave the same for navigations and fetchers\n if (request.method !== \"GET\") {\n return singleFetchActionStrategy(request, matches);\n }\n\n // Fetcher loads are singular calls to one loader\n if (fetcherKey) {\n return singleFetchLoaderFetcherStrategy(request, matches);\n }\n\n // Navigational loads are more complex...\n return singleFetchLoaderNavigationStrategy(\n manifest,\n routeModules,\n getRouter(),\n request,\n matches\n );\n };\n}\n\n// Actions are simple since they're singular calls to the server for both\n// navigations and fetchers)\nasync function singleFetchActionStrategy(\n request: Request,\n matches: DataStrategyFunctionArgs[\"matches\"]\n) {\n let actionMatch = matches.find((m) => m.shouldLoad);\n invariant(actionMatch, \"No action match found\");\n let actionStatus: number | undefined = undefined;\n let result = await actionMatch.resolve(async (handler) => {\n let result = await handler(async () => {\n let url = singleFetchUrl(request.url);\n let init = await createRequestInit(request);\n let { data, status } = await fetchAndDecode(url, init);\n actionStatus = status;\n return unwrapSingleFetchResult(\n data as SingleFetchResult,\n actionMatch!.route.id\n );\n });\n return result;\n });\n\n if (isResponse(result.result) || isRouteErrorResponse(result.result)) {\n return { [actionMatch.route.id]: result };\n }\n\n // For non-responses, proxy along the statusCode via data()\n // (most notably for skipping action error revalidation)\n return {\n [actionMatch.route.id]: {\n type: result.type,\n result: data(result.result, actionStatus),\n },\n };\n}\n\n// Loaders are trickier since we only want to hit the server once, so we\n// create a singular promise for all server-loader routes to latch onto.\nasync function singleFetchLoaderNavigationStrategy(\n manifest: AssetsManifest,\n routeModules: RouteModules,\n router: DataRouter,\n request: Request,\n matches: DataStrategyFunctionArgs[\"matches\"]\n) {\n // Track which routes need a server load - in case we need to tack on a\n // `_routes` param\n let routesParams = new Set<string>();\n\n // We only add `_routes` when one or more routes opts out of a load via\n // `shouldRevalidate` or `clientLoader`\n let foundOptOutRoute = false;\n\n // Deferreds for each route so we can be sure they've all loaded via\n // `match.resolve()`, and a singular promise that can tell us all routes\n // have been resolved\n let routeDfds = matches.map(() => createDeferred<void>());\n let routesLoadedPromise = Promise.all(routeDfds.map((d) => d.promise));\n\n // Deferred that we'll use for the call to the server that each match can\n // await and parse out it's specific result\n let singleFetchDfd = createDeferred<SingleFetchResults>();\n\n // Base URL and RequestInit for calls to the server\n let url = stripIndexParam(singleFetchUrl(request.url));\n let init = await createRequestInit(request);\n\n // We'll build up this results object as we loop through matches\n let results: Record<string, DataStrategyResult> = {};\n\n let resolvePromise = Promise.all(\n matches.map(async (m, i) =>\n m.resolve(async (handler) => {\n routeDfds[i].resolve();\n\n if (!m.shouldLoad) {\n // If we're not yet initialized and this is the initial load, respect\n // `shouldLoad` because we're only dealing with `clientLoader.hydrate`\n // routes which will fall into the `clientLoader` section below.\n if (!router.state.initialized) {\n return;\n }\n\n // Otherwise, we opt out if we currently have data, a `loader`, and a\n // `shouldRevalidate` function. This implies that the user opted out\n // via `shouldRevalidate`\n if (\n m.route.id in router.state.loaderData &&\n manifest.routes[m.route.id].hasLoader &&\n routeModules[m.route.id]?.shouldRevalidate\n ) {\n foundOptOutRoute = true;\n return;\n }\n }\n\n // When a route has a client loader, it opts out of the singular call and\n // calls it's server loader via `serverLoader()` using a `?_routes` param\n if (manifest.routes[m.route.id].hasClientLoader) {\n if (manifest.routes[m.route.id].hasLoader) {\n foundOptOutRoute = true;\n }\n try {\n let result = await fetchSingleLoader(\n handler,\n url,\n init,\n m.route.id\n );\n results[m.route.id] = { type: \"data\", result };\n } catch (e) {\n results[m.route.id] = { type: \"error\", result: e };\n }\n return;\n }\n\n // Load this route on the server if it has a loader\n if (manifest.routes[m.route.id].hasLoader) {\n routesParams.add(m.route.id);\n }\n\n // Lump this match in with the others on a singular promise\n try {\n let result = await handler(async () => {\n let data = await singleFetchDfd.promise;\n return unwrapSingleFetchResults(data, m.route.id);\n });\n results[m.route.id] = {\n type: \"data\",\n result,\n };\n } catch (e) {\n results[m.route.id] = {\n type: \"error\",\n result: e,\n };\n }\n })\n )\n );\n\n // Wait for all routes to resolve above before we make the HTTP call\n await routesLoadedPromise;\n\n // We can skip the server call:\n // - On initial hydration - only clientLoaders can pass through via `clientLoader.hydrate`\n // - If there are no routes to fetch from the server\n //\n // One exception - if we are performing an HDR revalidation we have to call\n // the server in case a new loader has shown up that the manifest doesn't yet\n // know about\n if (\n (!router.state.initialized || routesParams.size === 0) &&\n !window.__reactRouterHdrActive\n ) {\n singleFetchDfd.resolve({});\n } else {\n try {\n // When one or more routes have opted out, we add a _routes param to\n // limit the loaders to those that have a server loader and did not\n // opt out\n if (foundOptOutRoute && routesParams.size > 0) {\n url.searchParams.set(\n \"_routes\",\n matches\n .filter((m) => routesParams.has(m.route.id))\n .map((m) => m.route.id)\n .join(\",\")\n );\n }\n\n let data = await fetchAndDecode(url, init);\n singleFetchDfd.resolve(data.data as SingleFetchResults);\n } catch (e) {\n singleFetchDfd.reject(e as Error);\n }\n }\n\n await resolvePromise;\n\n return results;\n}\n\n// Fetcher loader calls are much simpler than navigational loader calls\nasync function singleFetchLoaderFetcherStrategy(\n request: Request,\n matches: DataStrategyFunctionArgs[\"matches\"]\n) {\n let fetcherMatch = matches.find((m) => m.shouldLoad);\n invariant(fetcherMatch, \"No fetcher match found\");\n let result = await fetcherMatch.resolve(async (handler) => {\n let url = stripIndexParam(singleFetchUrl(request.url));\n let init = await createRequestInit(request);\n return fetchSingleLoader(handler, url, init, fetcherMatch!.route.id);\n });\n return { [fetcherMatch.route.id]: result };\n}\n\nfunction fetchSingleLoader(\n handler: Parameters<\n NonNullable<Parameters<DataStrategyMatch[\"resolve\"]>[0]>\n >[0],\n url: URL,\n init: RequestInit,\n routeId: string\n) {\n return handler(async () => {\n let singleLoaderUrl = new URL(url);\n singleLoaderUrl.searchParams.set(\"_routes\", routeId);\n let { data } = await fetchAndDecode(singleLoaderUrl, init);\n return unwrapSingleFetchResults(data as SingleFetchResults, routeId);\n });\n}\n\nfunction stripIndexParam(url: URL) {\n let indexValues = url.searchParams.getAll(\"index\");\n url.searchParams.delete(\"index\");\n let indexValuesToKeep = [];\n for (let indexValue of indexValues) {\n if (indexValue) {\n indexValuesToKeep.push(indexValue);\n }\n }\n for (let toKeep of indexValuesToKeep) {\n url.searchParams.append(\"index\", toKeep);\n }\n\n return url;\n}\n\nexport function singleFetchUrl(reqUrl: URL | string) {\n let url =\n typeof reqUrl === \"string\"\n ? new URL(\n reqUrl,\n // This can be called during the SSR flow via PrefetchPageLinksImpl so\n // don't assume window is available\n typeof window === \"undefined\"\n ? \"server://singlefetch/\"\n : window.location.origin\n )\n : reqUrl;\n\n if (url.pathname === \"/\") {\n url.pathname = \"_root.data\";\n } else {\n url.pathname = `${url.pathname.replace(/\\/$/, \"\")}.data`;\n }\n\n return url;\n}\n\nasync function fetchAndDecode(url: URL, init: RequestInit) {\n let res = await fetch(url, init);\n\n // If this 404'd without hitting the running server (most likely in a\n // pre-rendered app using a CDN), then bubble a standard 404 ErrorResponse\n if (res.status === 404 && !res.headers.has(\"X-Remix-Response\")) {\n throw new ErrorResponseImpl(404, \"Not Found\", true);\n }\n\n invariant(res.body, \"No response body to decode\");\n\n try {\n let decoded = await decodeViaTurboStream(res.body, window);\n return { status: res.status, data: decoded.value };\n } catch (e) {\n // Can't clone after consuming the body via turbo-stream so we can't\n // include the body here. In an ideal world we'd look for a turbo-stream\n // content type here, or even X-Remix-Response but then folks can't\n // statically deploy their prerendered .data files to a CDN unless they can\n // tell that CDN to add special headers to those certain files - which is a\n // bit restrictive.\n throw new Error(\"Unable to decode turbo-stream response\");\n }\n}\n\n// Note: If you change this function please change the corresponding\n// encodeViaTurboStream function in server-runtime\nexport function decodeViaTurboStream(\n body: ReadableStream<Uint8Array>,\n global: Window | typeof globalThis\n) {\n return decode(body, {\n plugins: [\n (type: string, ...rest: unknown[]) => {\n // Decode Errors back into Error instances using the right type and with\n // the right (potentially undefined) stacktrace\n if (type === \"SanitizedError\") {\n let [name, message, stack] = rest as [\n string,\n string,\n string | undefined\n ];\n let Constructor = Error;\n // @ts-expect-error\n if (name && name in global && typeof global[name] === \"function\") {\n // @ts-expect-error\n Constructor = global[name];\n }\n let error = new Constructor(message);\n error.stack = stack;\n return { value: error };\n }\n\n if (type === \"ErrorResponse\") {\n let [data, status, statusText] = rest as [\n unknown,\n number,\n string | undefined\n ];\n return {\n value: new ErrorResponseImpl(status, statusText, data),\n };\n }\n\n if (type === \"SingleFetchRedirect\") {\n return { value: { [SingleFetchRedirectSymbol]: rest[0] } };\n }\n\n if (type === \"SingleFetchClassInstance\") {\n return { value: rest[0] };\n }\n\n if (type === \"SingleFetchFallback\") {\n return { value: undefined };\n }\n },\n ],\n });\n}\n\nfunction unwrapSingleFetchResults(\n results: SingleFetchResults,\n routeId: string\n) {\n let redirect = results[SingleFetchRedirectSymbol];\n if (redirect) {\n return unwrapSingleFetchResult(redirect, routeId);\n }\n\n return results[routeId] !== undefined\n ? unwrapSingleFetchResult(results[routeId], routeId)\n : null;\n}\n\nfunction unwrapSingleFetchResult(result: SingleFetchResult, routeId: string) {\n if (\"error\" in result) {\n throw result.error;\n } else if (\"redirect\" in result) {\n let headers: Record<string, string> = {};\n if (result.revalidate) {\n headers[\"X-Remix-Revalidate\"] = \"yes\";\n }\n if (result.reload) {\n headers[\"X-Remix-Reload-Document\"] = \"yes\";\n }\n if (result.replace) {\n headers[\"X-Remix-Replace\"] = \"yes\";\n }\n return redirect(result.redirect, { status: result.status, headers });\n } else if (\"data\" in result) {\n return result.data;\n } else {\n throw new Error(`No response found for routeId \"${routeId}\"`);\n }\n}\n\nfunction createDeferred<T = unknown>() {\n let resolve: (val?: any) => Promise<void>;\n let reject: (error?: Error) => Promise<void>;\n let promise = new Promise<T>((res, rej) => {\n resolve = async (val: T) => {\n res(val);\n try {\n await promise;\n } catch (e) {}\n };\n reject = async (error?: Error) => {\n rej(error);\n try {\n await promise;\n } catch (e) {}\n };\n });\n return {\n promise,\n //@ts-ignore\n resolve,\n //@ts-ignore\n reject,\n };\n}\n","import * as React from \"react\";\n\nimport { Scripts, useFrameworkContext } from \"./components\";\nimport type { Location } from \"../../router/history\";\nimport { isRouteErrorResponse } from \"../../router/utils\";\n\ntype RemixErrorBoundaryProps = React.PropsWithChildren<{\n location: Location;\n isOutsideRemixApp?: boolean;\n error?: Error;\n}>;\n\ntype RemixErrorBoundaryState = {\n error: null | Error;\n location: Location;\n};\n\nexport class RemixErrorBoundary extends React.Component<\n RemixErrorBoundaryProps,\n RemixErrorBoundaryState\n> {\n constructor(props: RemixErrorBoundaryProps) {\n super(props);\n this.state = { error: props.error || null, location: props.location };\n }\n\n static getDerivedStateFromError(error: Error) {\n return { error };\n }\n\n static getDerivedStateFromProps(\n props: RemixErrorBoundaryProps,\n state: RemixErrorBoundaryState\n ) {\n // When we get into an error state, the user will likely click \"back\" to the\n // previous page that didn't have an error. Because this wraps the entire\n // application (even the HTML!) that will have no effect--the error page\n // continues to display. This gives us a mechanism to recover from the error\n // when the location changes.\n //\n // Whether we're in an error state or not, we update the location in state\n // so that when we are in an error state, it gets reset when a new location\n // comes in and the user recovers from the error.\n if (state.location !== props.location) {\n return { error: props.error || null, location: props.location };\n }\n\n // If we're not changing locations, preserve the location but still surface\n // any new errors that may come through. We retain the existing error, we do\n // this because the error provided from the app state may be cleared without\n // the location changing.\n return { error: props.error || state.error, location: state.location };\n }\n\n render() {\n if (this.state.error) {\n return (\n <RemixRootDefaultErrorBoundary\n error={this.state.error}\n isOutsideRemixApp={true}\n />\n );\n } else {\n return this.props.children;\n }\n }\n}\n\n/**\n * When app's don't provide a root level ErrorBoundary, we default to this.\n */\nexport function RemixRootDefaultErrorBoundary({\n error,\n isOutsideRemixApp,\n}: {\n error: unknown;\n isOutsideRemixApp?: boolean;\n}) {\n console.error(error);\n\n let heyDeveloper = (\n <script\n dangerouslySetInnerHTML={{\n __html: `\n console.log(\n \"💿 Hey developer 👋. You can provide a way better UX than this when your app throws errors. Check out https://remix.run/guides/errors for more information.\"\n );\n `,\n }}\n />\n );\n\n if (isRouteErrorResponse(error)) {\n return (\n <BoundaryShell title=\"Unhandled Thrown Response!\">\n <h1 style={{ fontSize: \"24px\" }}>\n {error.status} {error.statusText}\n </h1>\n {heyDeveloper}\n </BoundaryShell>\n );\n }\n\n let errorInstance: Error;\n if (error instanceof Error) {\n errorInstance = error;\n } else {\n let errorString =\n error == null\n ? \"Unknown Error\"\n : typeof error === \"object\" && \"toString\" in error\n ? error.toString()\n : JSON.stringify(error);\n errorInstance = new Error(errorString);\n }\n\n return (\n <BoundaryShell\n title=\"Application Error!\"\n isOutsideRemixApp={isOutsideRemixApp}\n >\n <h1 style={{ fontSize: \"24px\" }}>Application Error</h1>\n <pre\n style={{\n padding: \"2rem\",\n background: \"hsla(10, 50%, 50%, 0.1)\",\n color: \"red\",\n overflow: \"auto\",\n }}\n >\n {errorInstance.stack}\n </pre>\n {heyDeveloper}\n </BoundaryShell>\n );\n}\n\nexport function BoundaryShell({\n title,\n renderScripts,\n isOutsideRemixApp,\n children,\n}: {\n title: string;\n renderScripts?: boolean;\n isOutsideRemixApp?: boolean;\n children: React.ReactNode | React.ReactNode[];\n}) {\n let { routeModules } = useFrameworkContext();\n\n // Generally speaking, when the root route has a Layout we want to use that\n // as the app shell instead of the default `BoundaryShell` wrapper markup below.\n // This is true for `loader`/`action` errors, most render errors, and\n // `HydrateFallback` scenarios.\n\n // However, render errors thrown from the `Layout` present a bit of an issue\n // because if the `Layout` itself throws during the `ErrorBoundary` pass and\n // we bubble outside the `RouterProvider` to the wrapping `RemixErrorBoundary`,\n // by returning only `children` here we'll be trying to append a `<div>` to\n // the `document` and the DOM will throw, putting React into an error/hydration\n // loop.\n\n // Instead, if we're ever rendering from the outermost `RemixErrorBoundary`\n // during hydration that wraps `RouterProvider`, then we can't trust the\n // `Layout` and should fallback to the default app shell so we're always\n // returning an `<html>` document.\n if (routeModules.root?.Layout && !isOutsideRemixApp) {\n return children;\n }\n\n return (\n <html lang=\"en\">\n <head>\n <meta charSet=\"utf-8\" />\n <meta\n name=\"viewport\"\n content=\"width=device-width,initial-scale=1,viewport-fit=cover\"\n />\n <title>{title}</title>\n </head>\n <body>\n <main style={{ fontFamily: \"system-ui, sans-serif\", padding: \"2rem\" }}>\n {children}\n {renderScripts ? <Scripts /> : null}\n </main>\n </body>\n </html>\n );\n}\n","import * as React from \"react\";\n\nimport { BoundaryShell } from \"./errorBoundaries\";\n\n// If the user sets `clientLoader.hydrate=true` somewhere but does not\n// provide a `HydrateFallback` at any level of the tree, then we need to at\n// least include `<Scripts>` in the SSR so we can hydrate the app and call the\n// `clientLoader` functions\nexport function RemixRootDefaultHydrateFallback() {\n return (\n <BoundaryShell title=\"Loading...\" renderScripts>\n <script\n dangerouslySetInnerHTML={{\n __html: `\n console.log(\n \"💿 Hey developer 👋. You can provide a way better UX than this \" +\n \"when your app is loading JS modules and/or running \\`clientLoader\\` \" +\n \"functions. Check out https://remix.run/route/hydrate-fallback \" +\n \"for more information.\"\n );\n `,\n }}\n />\n </BoundaryShell>\n );\n}\n","import * as React from \"react\";\n\nimport type { HydrationState } from \"../../router/router\";\nimport type {\n ActionFunctionArgs,\n LoaderFunctionArgs,\n ShouldRevalidateFunction,\n} from \"../../router/utils\";\nimport { ErrorResponseImpl } from \"../../router/utils\";\nimport type { RouteModule, RouteModules } from \"./routeModules\";\nimport { loadRouteModule } from \"./routeModules\";\nimport type { FutureConfig } from \"./entry\";\nimport { prefetchStyleLinks } from \"./links\";\nimport { RemixRootDefaultErrorBoundary } from \"./errorBoundaries\";\nimport { RemixRootDefaultHydrateFallback } from \"./fallback\";\nimport invariant from \"./invariant\";\nimport { useRouteError } from \"../../hooks\";\nimport type { DataRouteObject } from \"../../context\";\n\nexport interface RouteManifest<Route> {\n [routeId: string]: Route;\n}\n\n// NOTE: make sure to change the Route in server-runtime if you change this\ninterface Route {\n index?: boolean;\n caseSensitive?: boolean;\n id: string;\n parentId?: string;\n path?: string;\n}\n\n// NOTE: make sure to change the EntryRoute in server-runtime if you change this\nexport interface EntryRoute extends Route {\n hasAction: boolean;\n hasLoader: boolean;\n hasClientAction: boolean;\n hasClientLoader: boolean;\n hasErrorBoundary: boolean;\n imports?: string[];\n css?: string[];\n module: string;\n parentId?: string;\n}\n\n// Create a map of routes by parentId to use recursively instead of\n// repeatedly filtering the manifest.\nfunction groupRoutesByParentId(manifest: RouteManifest<EntryRoute>) {\n let routes: Record<string, Omit<EntryRoute, \"children\">[]> = {};\n\n Object.values(manifest).forEach((route) => {\n let parentId = route.parentId || \"\";\n if (!routes[parentId]) {\n routes[parentId] = [];\n }\n routes[parentId].push(route);\n });\n\n return routes;\n}\n\nfunction getRouteComponents(\n route: EntryRoute,\n routeModule: RouteModule,\n isSpaMode: boolean\n) {\n let Component = getRouteModuleComponent(routeModule);\n // HydrateFallback can only exist on the root route in SPA Mode\n let HydrateFallback =\n routeModule.HydrateFallback && (!isSpaMode || route.id === \"root\")\n ? routeModule.HydrateFallback\n : route.id === \"root\"\n ? RemixRootDefaultHydrateFallback\n : undefined;\n let ErrorBoundary = routeModule.ErrorBoundary\n ? routeModule.ErrorBoundary\n : route.id === \"root\"\n ? () => <RemixRootDefaultErrorBoundary error={useRouteError()} />\n : undefined;\n\n if (route.id === \"root\" && routeModule.Layout) {\n return {\n ...(Component\n ? {\n element: (\n <routeModule.Layout>\n <Component />\n </routeModule.Layout>\n ),\n }\n : { Component }),\n ...(ErrorBoundary\n ? {\n errorElement: (\n <routeModule.Layout>\n <ErrorBoundary />\n </routeModule.Layout>\n ),\n }\n : { ErrorBoundary }),\n ...(HydrateFallback\n ? {\n hydrateFallbackElement: (\n <routeModule.Layout>\n <HydrateFallback />\n </routeModule.Layout>\n ),\n }\n : { HydrateFallback }),\n };\n }\n\n return { Component, ErrorBoundary, HydrateFallback };\n}\n\nexport function createServerRoutes(\n manifest: RouteManifest<EntryRoute>,\n routeModules: RouteModules,\n future: FutureConfig,\n isSpaMode: boolean,\n parentId: string = \"\",\n routesByParentId: Record<\n string,\n Omit<EntryRoute, \"children\">[]\n > = groupRoutesByParentId(manifest),\n spaModeLazyPromise = Promise.resolve({ Component: () => null })\n): DataRouteObject[] {\n return (routesByParentId[parentId] || []).map((route) => {\n let routeModule = routeModules[route.id];\n invariant(\n routeModule,\n \"No `routeModule` available to create server routes\"\n );\n\n let dataRoute: DataRouteObject = {\n ...getRouteComponents(route, routeModule, isSpaMode),\n caseSensitive: route.caseSensitive,\n id: route.id,\n index: route.index,\n path: route.path,\n handle: routeModule.handle,\n // For SPA Mode, all routes are lazy except root. However we tell the\n // router root is also lazy here too since we don't need a full\n // implementation - we just need a `lazy` prop to tell the RR rendering\n // where to stop which is always at the root route in SPA mode\n lazy: isSpaMode ? () => spaModeLazyPromise : undefined,\n // For partial hydration rendering, we need to indicate when the route\n // has a loader/clientLoader, but it won't ever be called during the static\n // render, so just give it a no-op function so we can render down to the\n // proper fallback\n loader: route.hasLoader || route.hasClientLoader ? () => null : undefined,\n // We don't need action/shouldRevalidate on these routes since they're\n // for a static render\n };\n\n let children = createServerRoutes(\n manifest,\n routeModules,\n future,\n isSpaMode,\n route.id,\n routesByParentId,\n spaModeLazyPromise\n );\n if (children.length > 0) dataRoute.children = children;\n return dataRoute;\n });\n}\n\nexport function createClientRoutesWithHMRRevalidationOptOut(\n needsRevalidation: Set<string>,\n manifest: RouteManifest<EntryRoute>,\n routeModulesCache: RouteModules,\n initialState: HydrationState,\n future: FutureConfig,\n isSpaMode: boolean\n) {\n return createClientRoutes(\n manifest,\n routeModulesCache,\n initialState,\n isSpaMode,\n \"\",\n groupRoutesByParentId(manifest),\n needsRevalidation\n );\n}\n\nfunction preventInvalidServerHandlerCall(\n type: \"action\" | \"loader\",\n route: Omit<EntryRoute, \"children\">,\n isSpaMode: boolean\n) {\n if (isSpaMode) {\n let fn = type === \"action\" ? \"serverAction()\" : \"serverLoader()\";\n let msg = `You cannot call ${fn} in SPA Mode (routeId: \"${route.id}\")`;\n console.error(msg);\n throw new ErrorResponseImpl(400, \"Bad Request\", new Error(msg), true);\n }\n\n let fn = type === \"action\" ? \"serverAction()\" : \"serverLoader()\";\n let msg =\n `You are trying to call ${fn} on a route that does not have a server ` +\n `${type} (routeId: \"${route.id}\")`;\n if (\n (type === \"loader\" && !route.hasLoader) ||\n (type === \"action\" && !route.hasAction)\n ) {\n console.error(msg);\n throw new ErrorResponseImpl(400, \"Bad Request\", new Error(msg), true);\n }\n}\n\nfunction noActionDefinedError(\n type: \"action\" | \"clientAction\",\n routeId: string\n) {\n let article = type === \"clientAction\" ? \"a\" : \"an\";\n let msg =\n `Route \"${routeId}\" does not have ${article} ${type}, but you are trying to ` +\n `submit to it. To fix this, please add ${article} \\`${type}\\` function to the route`;\n console.error(msg);\n throw new ErrorResponseImpl(405, \"Method Not Allowed\", new Error(msg), true);\n}\n\nexport function createClientRoutes(\n manifest: RouteManifest<EntryRoute>,\n routeModulesCache: RouteModules,\n initialState: HydrationState | null,\n isSpaMode: boolean,\n parentId: string = \"\",\n routesByParentId: Record<\n string,\n Omit<EntryRoute, \"children\">[]\n > = groupRoutesByParentId(manifest),\n needsRevalidation?: Set<string>\n): DataRouteObject[] {\n return (routesByParentId[parentId] || []).map((route) => {\n let routeModule = routeModulesCache[route.id];\n\n function fetchServerHandler(singleFetch: unknown) {\n invariant(\n typeof singleFetch === \"function\",\n \"No single fetch function available for route handler\"\n );\n return singleFetch();\n }\n\n function fetchServerLoader(singleFetch: unknown) {\n if (!route.hasLoader) return Promise.resolve(null);\n return fetchServerHandler(singleFetch);\n }\n\n function fetchServerAction(singleFetch: unknown) {\n if (!route.hasAction) {\n throw noActionDefinedError(\"action\", route.id);\n }\n return fetchServerHandler(singleFetch);\n }\n\n async function prefetchStylesAndCallHandler(\n handler: () => Promise<unknown>\n ) {\n // Only prefetch links if we exist in the routeModulesCache (critical modules\n // and navigating back to pages previously loaded via route.lazy). Initial\n // execution of route.lazy (when the module is not in the cache) will handle\n // prefetching style links via loadRouteModuleWithBlockingLinks.\n let cachedModule = routeModulesCache[route.id];\n let linkPrefetchPromise = cachedModule\n ? prefetchStyleLinks(route, cachedModule)\n : Promise.resolve();\n try {\n return handler();\n } finally {\n await linkPrefetchPromise;\n }\n }\n\n let dataRoute: DataRouteObject = {\n id: route.id,\n index: route.index,\n path: route.path,\n };\n\n if (routeModule) {\n // Use critical path modules directly\n Object.assign(dataRoute, {\n ...dataRoute,\n ...getRouteComponents(route, routeModule, isSpaMode),\n handle: routeModule.handle,\n shouldRevalidate: needsRevalidation\n ? wrapShouldRevalidateForHdr(\n route.id,\n routeModule.shouldRevalidate,\n needsRevalidation\n )\n : routeModule.shouldRevalidate,\n });\n\n let hasInitialData =\n initialState &&\n initialState.loaderData &&\n route.id in initialState.loaderData;\n let initialData = hasInitialData\n ? initialState?.loaderData?.[route.id]\n : undefined;\n let hasInitialError =\n initialState && initialState.errors && route.id in initialState.errors;\n let initialError = hasInitialError\n ? initialState?.errors?.[route.id]\n : undefined;\n let isHydrationRequest =\n needsRevalidation == null &&\n (routeModule.clientLoader?.hydrate === true || !route.hasLoader);\n\n dataRoute.loader = async (\n { request, params }: LoaderFunctionArgs,\n singleFetch?: unknown\n ) => {\n try {\n let result = await prefetchStylesAndCallHandler(async () => {\n invariant(\n routeModule,\n \"No `routeModule` available for critical-route loader\"\n );\n if (!routeModule.clientLoader) {\n if (isSpaMode) return null;\n // Call the server when no client loader exists\n return fetchServerLoader(singleFetch);\n }\n\n return routeModule.clientLoader({\n request,\n params,\n async serverLoader() {\n preventInvalidServerHandlerCall(\"loader\", route, isSpaMode);\n\n // On the first call, resolve with the server result\n if (isHydrationRequest) {\n if (hasInitialData) {\n return initialData;\n }\n if (hasInitialError) {\n throw initialError;\n }\n }\n\n // Call the server loader for client-side navigations\n return fetchServerLoader(singleFetch);\n },\n });\n });\n return result;\n } finally {\n // Whether or not the user calls `serverLoader`, we only let this\n // stick around as true for one loader call\n isHydrationRequest = false;\n }\n };\n\n // Let React Router know whether to run this on hydration\n dataRoute.loader.hydrate = shouldHydrateRouteLoader(\n route,\n routeModule,\n isSpaMode\n );\n\n dataRoute.action = (\n { request, params }: ActionFunctionArgs,\n singleFetch?: unknown\n ) => {\n return prefetchStylesAndCallHandler(async () => {\n invariant(\n routeModule,\n \"No `routeModule` available for critical-route action\"\n );\n if (!routeModule.clientAction) {\n if (isSpaMode) {\n throw noActionDefinedError(\"clientAction\", route.id);\n }\n return fetchServerAction(singleFetch);\n }\n\n return routeModule.clientAction({\n request,\n params,\n async serverAction() {\n preventInvalidServerHandlerCall(\"action\", route, isSpaMode);\n return fetchServerAction(singleFetch);\n },\n });\n });\n };\n } else {\n // If the lazy route does not have a client loader/action we want to call\n // the server loader/action in parallel with the module load so we add\n // loader/action as static props on the route\n if (!route.hasClientLoader) {\n dataRoute.loader = (\n { request }: LoaderFunctionArgs,\n singleFetch?: unknown\n ) =>\n prefetchStylesAndCallHandler(() => {\n if (isSpaMode) return Promise.resolve(null);\n return fetchServerLoader(singleFetch);\n });\n }\n if (!route.hasClientAction) {\n dataRoute.action = (\n { request }: ActionFunctionArgs,\n singleFetch?: unknown\n ) =>\n prefetchStylesAndCallHandler(() => {\n if (isSpaMode) {\n throw noActionDefinedError(\"clientAction\", route.id);\n }\n return fetchServerAction(singleFetch);\n });\n }\n\n // Load all other modules via route.lazy()\n dataRoute.lazy = async () => {\n let mod = await loadRouteModuleWithBlockingLinks(\n route,\n routeModulesCache\n );\n\n let lazyRoute: Partial<DataRouteObject> = { ...mod };\n if (mod.clientLoader) {\n let clientLoader = mod.clientLoader;\n lazyRoute.loader = (\n args: LoaderFunctionArgs,\n singleFetch?: unknown\n ) =>\n clientLoader({\n ...args,\n async serverLoader() {\n preventInvalidServerHandlerCall(\"loader\", route, isSpaMode);\n return fetchServerLoader(singleFetch);\n },\n });\n }\n\n if (mod.clientAction) {\n let clientAction = mod.clientAction;\n lazyRoute.action = (\n args: ActionFunctionArgs,\n singleFetch?: unknown\n ) =>\n clientAction({\n ...args,\n async serverAction() {\n preventInvalidServerHandlerCall(\"action\", route, isSpaMode);\n return fetchServerAction(singleFetch);\n },\n });\n }\n\n if (needsRevalidation) {\n lazyRoute.shouldRevalidate = wrapShouldRevalidateForHdr(\n route.id,\n mod.shouldRevalidate,\n needsRevalidation\n );\n }\n\n return {\n ...(lazyRoute.loader ? { loader: lazyRoute.loader } : {}),\n ...(lazyRoute.action ? { action: lazyRoute.action } : {}),\n hasErrorBoundary: lazyRoute.hasErrorBoundary,\n shouldRevalidate: lazyRoute.shouldRevalidate,\n handle: lazyRoute.handle,\n // No need to wrap these in layout since the root route is never\n // loaded via route.lazy()\n Component: lazyRoute.Component,\n ErrorBoundary: lazyRoute.ErrorBoundary,\n };\n };\n }\n\n let children = createClientRoutes(\n manifest,\n routeModulesCache,\n initialState,\n isSpaMode,\n route.id,\n routesByParentId,\n needsRevalidation\n );\n if (children.length > 0) dataRoute.children = children;\n return dataRoute;\n });\n}\n\n// When an HMR / HDR update happens we opt out of all user-defined\n// revalidation logic and force a revalidation on the first call\nfunction wrapShouldRevalidateForHdr(\n routeId: string,\n routeShouldRevalidate: ShouldRevalidateFunction | undefined,\n needsRevalidation: Set<string>\n): ShouldRevalidateFunction {\n let handledRevalidation = false;\n return (arg) => {\n if (!handledRevalidation) {\n handledRevalidation = true;\n return needsRevalidation.has(routeId);\n }\n\n return routeShouldRevalidate\n ? routeShouldRevalidate(arg)\n : arg.defaultShouldRevalidate;\n };\n}\n\nasync function loadRouteModuleWithBlockingLinks(\n route: EntryRoute,\n routeModules: RouteModules\n) {\n let routeModule = await loadRouteModule(route, routeModules);\n await prefetchStyleLinks(route, routeModule);\n\n // Include all `browserSafeRouteExports` fields, except `HydrateFallback`\n // since those aren't used on lazily loaded routes\n return {\n Component: getRouteModuleComponent(routeModule),\n ErrorBoundary: routeModule.ErrorBoundary,\n clientAction: routeModule.clientAction,\n clientLoader: routeModule.clientLoader,\n handle: routeModule.handle,\n links: routeModule.links,\n meta: routeModule.meta,\n shouldRevalidate: routeModule.shouldRevalidate,\n };\n}\n\n// Our compiler generates the default export as `{}` when no default is provided,\n// which can lead us to trying to use that as a Component in RR and calling\n// createElement on it. Patching here as a quick fix and hoping it's no longer\n// an issue in Vite.\nfunction getRouteModuleComponent(routeModule: RouteModule) {\n if (routeModule.default == null) return undefined;\n let isEmptyObject =\n typeof routeModule.default === \"object\" &&\n Object.keys(routeModule.default).length === 0;\n if (!isEmptyObject) {\n return routeModule.default;\n }\n}\n\nexport function shouldHydrateRouteLoader(\n route: EntryRoute,\n routeModule: RouteModule,\n isSpaMode: boolean\n) {\n return (\n (isSpaMode && route.id !== \"root\") ||\n (routeModule.clientLoader != null &&\n (routeModule.clientLoader.hydrate === true || route.hasLoader !== true))\n );\n}\n","import * as React from \"react\";\nimport type { PatchRoutesOnNavigationFunction } from \"../../context\";\nimport type { Router as DataRouter } from \"../../router/router\";\nimport { matchRoutes } from \"../../router/utils\";\nimport type { AssetsManifest } from \"./entry\";\nimport type { RouteModules } from \"./routeModules\";\nimport { createClientRoutes } from \"./routes\";\n\ndeclare global {\n interface Navigator {\n connection?: { saveData: boolean };\n }\n}\n\n// Currently rendered links that may need prefetching\nconst nextPaths = new Set<string>();\n\n// FIFO queue of previously discovered routes to prevent re-calling on\n// subsequent navigations to the same path\nconst discoveredPathsMaxSize = 1000;\nconst discoveredPaths = new Set<string>();\n\n// 7.5k to come in under the ~8k limit for most browsers\n// https://stackoverflow.com/a/417184\nconst URL_LIMIT = 7680;\n\nexport function isFogOfWarEnabled(isSpaMode: boolean) {\n return !isSpaMode;\n}\n\nexport function getPartialManifest(\n manifest: AssetsManifest,\n router: DataRouter\n) {\n // Start with our matches for this pathname\n let routeIds = new Set(router.state.matches.map((m) => m.route.id));\n\n let segments = router.state.location.pathname.split(\"/\").filter(Boolean);\n let paths: string[] = [\"/\"];\n\n // We've already matched to the last segment\n segments.pop();\n\n // Traverse each path for our parents and match in case they have pathless/index\n // children we need to include in the initial manifest\n while (segments.length > 0) {\n paths.push(`/${segments.join(\"/\")}`);\n segments.pop();\n }\n\n paths.forEach((path) => {\n let matches = matchRoutes(router.routes, path, router.basename);\n if (matches) {\n matches.forEach((m) => routeIds.add(m.route.id));\n }\n });\n\n let initialRoutes = [...routeIds].reduce(\n (acc, id) => Object.assign(acc, { [id]: manifest.routes[id] }),\n {}\n );\n return {\n ...manifest,\n routes: initialRoutes,\n };\n}\n\nexport function getPatchRoutesOnNavigationFunction(\n manifest: AssetsManifest,\n routeModules: RouteModules,\n isSpaMode: boolean,\n basename: string | undefined\n): PatchRoutesOnNavigationFunction | undefined {\n if (!isFogOfWarEnabled(isSpaMode)) {\n return undefined;\n }\n\n return async ({ path, patch }) => {\n if (discoveredPaths.has(path)) {\n return;\n }\n await fetchAndApplyManifestPatches(\n [path],\n manifest,\n routeModules,\n isSpaMode,\n basename,\n patch\n );\n };\n}\n\nexport function useFogOFWarDiscovery(\n router: DataRouter,\n manifest: AssetsManifest,\n routeModules: RouteModules,\n isSpaMode: boolean\n) {\n React.useEffect(() => {\n // Don't prefetch if not enabled or if the user has `saveData` enabled\n if (\n !isFogOfWarEnabled(isSpaMode) ||\n navigator.connection?.saveData === true\n ) {\n return;\n }\n\n // Register a link href for patching\n function registerElement(el: Element) {\n let path =\n el.tagName === \"FORM\"\n ? el.getAttribute(\"action\")\n : el.getAttribute(\"href\");\n if (!path) {\n return;\n }\n let url = new URL(path, window.location.origin);\n if (!discoveredPaths.has(url.pathname)) {\n nextPaths.add(url.pathname);\n }\n }\n\n // Register and fetch patches for all initially-rendered links/forms\n async function fetchPatches() {\n let lazyPaths = Array.from(nextPaths.keys()).filter((path) => {\n if (discoveredPaths.has(path)) {\n nextPaths.delete(path);\n return false;\n }\n return true;\n });\n\n if (lazyPaths.length === 0) {\n return;\n }\n\n try {\n await fetchAndApplyManifestPatches(\n lazyPaths,\n manifest,\n routeModules,\n isSpaMode,\n router.basename,\n router.patchRoutes\n );\n } catch (e) {\n console.error(\"Failed to fetch manifest patches\", e);\n }\n }\n\n // Register and fetch patches for all initially-rendered links\n document.body\n .querySelectorAll(\"a[data-discover], form[data-discover]\")\n .forEach((el) => registerElement(el));\n\n fetchPatches();\n\n // Setup a MutationObserver to fetch all subsequently rendered links/form\n let debouncedFetchPatches = debounce(fetchPatches, 100);\n\n function isElement(node: Node): node is Element {\n return node.nodeType === Node.ELEMENT_NODE;\n }\n\n let observer = new MutationObserver((records) => {\n let elements = new Set<Element>();\n records.forEach((r) => {\n [r.target, ...r.addedNodes].forEach((node) => {\n if (!isElement(node)) return;\n if (node.tagName === \"A\" && node.getAttribute(\"data-discover\")) {\n elements.add(node);\n } else if (\n node.tagName === \"FORM\" &&\n node.getAttribute(\"data-discover\")\n ) {\n elements.add(node);\n }\n if (node.tagName !== \"A\") {\n node\n .querySelectorAll(\"a[data-discover], form[data-discover]\")\n .forEach((el) => elements.add(el));\n }\n });\n });\n elements.forEach((el) => registerElement(el));\n debouncedFetchPatches();\n });\n\n observer.observe(document.documentElement, {\n subtree: true,\n childList: true,\n attributes: true,\n attributeFilter: [\"data-discover\", \"href\", \"action\"],\n });\n\n return () => observer.disconnect();\n }, [isSpaMode, manifest, routeModules, router]);\n}\n\nexport async function fetchAndApplyManifestPatches(\n paths: string[],\n manifest: AssetsManifest,\n routeModules: RouteModules,\n isSpaMode: boolean,\n basename: string | undefined,\n patchRoutes: DataRouter[\"patchRoutes\"]\n): Promise<void> {\n let manifestPath = `${basename != null ? basename : \"/\"}/__manifest`.replace(\n /\\/+/g,\n \"/\"\n );\n let url = new URL(manifestPath, window.location.origin);\n paths.sort().forEach((path) => url.searchParams.append(\"p\", path));\n url.searchParams.set(\"version\", manifest.version);\n\n // If the URL is nearing the ~8k limit on GET requests, skip this optimization\n // step and just let discovery happen on link click. We also wipe out the\n // nextPaths Set here so we can start filling it with fresh links\n if (url.toString().length > URL_LIMIT) {\n nextPaths.clear();\n return;\n }\n\n let res = await fetch(url);\n\n if (!res.ok) {\n throw new Error(`${res.status} ${res.statusText}`);\n } else if (res.status >= 400) {\n throw new Error(await res.text());\n }\n\n let serverPatches = (await res.json()) as AssetsManifest[\"routes\"];\n\n // Patch routes we don't know about yet into the manifest\n let knownRoutes = new Set(Object.keys(manifest.routes));\n let patches: AssetsManifest[\"routes\"] = Object.values(serverPatches).reduce(\n (acc, route) =>\n !knownRoutes.has(route.id)\n ? Object.assign(acc, { [route.id]: route })\n : acc,\n {}\n );\n Object.assign(manifest.routes, patches);\n\n // Track discovered paths so we don't have to fetch them again\n paths.forEach((p) => addToFifoQueue(p, discoveredPaths));\n\n // Identify all parentIds for which we have new children to add and patch\n // in their new children\n let parentIds = new Set<string | undefined>();\n Object.values(patches).forEach((patch) => {\n if (!patch.parentId || !patches[patch.parentId]) {\n parentIds.add(patch.parentId);\n }\n });\n parentIds.forEach((parentId) =>\n patchRoutes(\n parentId || null,\n createClientRoutes(patches, routeModules, null, isSpaMode, parentId)\n )\n );\n}\n\nfunction addToFifoQueue(path: string, queue: Set<string>) {\n if (queue.size >= discoveredPathsMaxSize) {\n let first = queue.values().next().value;\n queue.delete(first);\n }\n queue.add(path);\n}\n\n// Thanks Josh!\n// https://www.joshwcomeau.com/snippets/javascript/debounce/\nfunction debounce(callback: (...args: unknown[]) => unknown, wait: number) {\n let timeoutId: number | undefined;\n return (...args: unknown[]) => {\n window.clearTimeout(timeoutId);\n timeoutId = window.setTimeout(() => callback(...args), wait);\n };\n}\n","import type {\n FocusEventHandler,\n MouseEventHandler,\n TouchEventHandler,\n} from \"react\";\nimport * as React from \"react\";\n\nimport type { RouterState } from \"../../router/router\";\nimport type { AgnosticDataRouteMatch } from \"../../router/utils\";\nimport { matchRoutes } from \"../../router/utils\";\n\nimport type { FrameworkContextObject } from \"./entry\";\nimport invariant from \"./invariant\";\nimport {\n getKeyedLinksForMatches,\n getKeyedPrefetchLinks,\n getModuleLinkHrefs,\n getNewMatchesForLinks,\n isPageLinkDescriptor,\n} from \"./links\";\nimport type { KeyedHtmlLinkDescriptor } from \"./links\";\nimport { createHtml } from \"./markup\";\nimport type {\n MetaFunction,\n MetaDescriptor,\n MetaMatch,\n MetaMatches,\n} from \"./routeModules\";\nimport { singleFetchUrl } from \"./single-fetch\";\nimport { DataRouterContext, DataRouterStateContext } from \"../../context\";\nimport { useLocation } from \"../../hooks\";\nimport { getPartialManifest, isFogOfWarEnabled } from \"./fog-of-war\";\nimport type { PageLinkDescriptor } from \"../../router/links\";\n\n// TODO: Temporary shim until we figure out the way to handle typings in v7\nexport type SerializeFrom<D> = D extends () => {} ? Awaited<ReturnType<D>> : D;\n\nfunction useDataRouterContext() {\n let context = React.useContext(DataRouterContext);\n invariant(\n context,\n \"You must render this element inside a <DataRouterContext.Provider> element\"\n );\n return context;\n}\n\nfunction useDataRouterStateContext() {\n let context = React.useContext(DataRouterStateContext);\n invariant(\n context,\n \"You must render this element inside a <DataRouterStateContext.Provider> element\"\n );\n return context;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// FrameworkContext\n\nexport const FrameworkContext = React.createContext<\n FrameworkContextObject | undefined\n>(undefined);\nFrameworkContext.displayName = \"FrameworkContext\";\n\nexport function useFrameworkContext(): FrameworkContextObject {\n let context = React.useContext(FrameworkContext);\n invariant(\n context,\n \"You must render this element inside a <HydratedRouter> element\"\n );\n return context;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Public API\n\n/**\n * Defines the discovery behavior of the link:\n *\n * - \"render\" - default, discover the route when the link renders\n * - \"none\" - don't eagerly discover, only discover if the link is clicked\n */\nexport type DiscoverBehavior = \"render\" | \"none\";\n\n/**\n * Defines the prefetching behavior of the link:\n *\n * - \"none\": Never fetched\n * - \"intent\": Fetched when the user focuses or hovers the link\n * - \"render\": Fetched when the link is rendered\n * - \"viewport\": Fetched when the link is in the viewport\n */\nexport type PrefetchBehavior = \"intent\" | \"render\" | \"none\" | \"viewport\";\n\ninterface PrefetchHandlers {\n onFocus?: FocusEventHandler;\n onBlur?: FocusEventHandler;\n onMouseEnter?: MouseEventHandler;\n onMouseLeave?: MouseEventHandler;\n onTouchStart?: TouchEventHandler;\n}\n\nexport function usePrefetchBehavior<T extends HTMLAnchorElement>(\n prefetch: PrefetchBehavior,\n theirElementProps: PrefetchHandlers\n): [boolean, React.RefObject<T>, PrefetchHandlers] {\n let frameworkContext = React.useContext(FrameworkContext);\n let [maybePrefetch, setMaybePrefetch] = React.useState(false);\n let [shouldPrefetch, setShouldPrefetch] = React.useState(false);\n let { onFocus, onBlur, onMouseEnter, onMouseLeave, onTouchStart } =\n theirElementProps;\n\n let ref = React.useRef<T>(null);\n\n React.useEffect(() => {\n if (prefetch === \"render\") {\n setShouldPrefetch(true);\n }\n\n if (prefetch === \"viewport\") {\n let callback: IntersectionObserverCallback = (entries) => {\n entries.forEach((entry) => {\n setShouldPrefetch(entry.isIntersecting);\n });\n };\n let observer = new IntersectionObserver(callback, { threshold: 0.5 });\n if (ref.current) observer.observe(ref.current);\n\n return () => {\n observer.disconnect();\n };\n }\n }, [prefetch]);\n\n React.useEffect(() => {\n if (maybePrefetch) {\n let id = setTimeout(() => {\n setShouldPrefetch(true);\n }, 100);\n return () => {\n clearTimeout(id);\n };\n }\n }, [maybePrefetch]);\n\n let setIntent = () => {\n setMaybePrefetch(true);\n };\n\n let cancelIntent = () => {\n setMaybePrefetch(false);\n setShouldPrefetch(false);\n };\n\n // No prefetching if not using SSR\n if (!frameworkContext) {\n return [false, ref, {}];\n }\n\n if (prefetch !== \"intent\") {\n return [shouldPrefetch, ref, {}];\n }\n\n // When using prefetch=\"intent\" we need to attach focus/hover listeners\n return [\n shouldPrefetch,\n ref,\n {\n onFocus: composeEventHandlers(onFocus, setIntent),\n onBlur: composeEventHandlers(onBlur, cancelIntent),\n onMouseEnter: composeEventHandlers(onMouseEnter, setIntent),\n onMouseLeave: composeEventHandlers(onMouseLeave, cancelIntent),\n onTouchStart: composeEventHandlers(onTouchStart, setIntent),\n },\n ];\n}\n\nexport function composeEventHandlers<\n EventType extends React.SyntheticEvent | Event\n>(\n theirHandler: ((event: EventType) => any) | undefined,\n ourHandler: (event: EventType) => any\n): (event: EventType) => any {\n return (event) => {\n theirHandler && theirHandler(event);\n if (!event.defaultPrevented) {\n ourHandler(event);\n }\n };\n}\n\n// Return the matches actively being displayed:\n// - In SPA Mode we only SSR/hydrate the root match, and include all matches\n// after hydration. This lets the router handle initial match loads via lazy().\n// - When an error boundary is rendered, we slice off matches up to the\n// boundary for <Links>/<Meta>\nfunction getActiveMatches(\n matches: RouterState[\"matches\"],\n errors: RouterState[\"errors\"],\n isSpaMode: boolean\n) {\n if (isSpaMode && !isHydrated) {\n return [matches[0]];\n }\n\n if (errors) {\n let errorIdx = matches.findIndex((m) => errors[m.route.id] !== undefined);\n return matches.slice(0, errorIdx + 1);\n }\n\n return matches;\n}\n\n/**\n Renders all of the `<link>` tags created by route module {@link LinksFunction} export. You should render it inside the `<head>` of your document.\n\n ```tsx\n import { Links } from \"react-router\";\n\n export default function Root() {\n return (\n <html>\n <head>\n <Links />\n </head>\n <body></body>\n </html>\n );\n }\n ```\n\n @category Components\n */\nexport function Links() {\n let { isSpaMode, manifest, routeModules, criticalCss } =\n useFrameworkContext();\n let { errors, matches: routerMatches } = useDataRouterStateContext();\n\n let matches = getActiveMatches(routerMatches, errors, isSpaMode);\n\n let keyedLinks = React.useMemo(\n () => getKeyedLinksForMatches(matches, routeModules, manifest),\n [matches, routeModules, manifest]\n );\n\n return (\n <>\n {criticalCss ? (\n <style dangerouslySetInnerHTML={{ __html: criticalCss }} />\n ) : null}\n {keyedLinks.map(({ key, link }) =>\n isPageLinkDescriptor(link) ? (\n <PrefetchPageLinks key={key} {...link} />\n ) : (\n <link key={key} {...link} />\n )\n )}\n </>\n );\n}\n\n/**\n Renders `<link rel=prefetch|modulepreload>` tags for modules and data of another page to enable an instant navigation to that page. {@link LinkProps.prefetch | `<Link prefetch>`} uses this internally, but you can render it to prefetch a page for any other reason.\n\n ```tsx\n import { PrefetchPageLinks } from \"react-router\"\n\n <PrefetchPageLinks page=\"/absolute/path\" />\n ```\n\n For example, you may render one of this as the user types into a search field to prefetch search results before they click through to their selection.\n\n @category Components\n */\nexport function PrefetchPageLinks({\n page,\n ...dataLinkProps\n}: PageLinkDescriptor) {\n let { router } = useDataRouterContext();\n let matches = React.useMemo(\n () => matchRoutes(router.routes, page, router.basename),\n [router.routes, page, router.basename]\n );\n\n if (!matches) {\n console.warn(`Tried to prefetch ${page} but no routes matched.`);\n return null;\n }\n\n return (\n <PrefetchPageLinksImpl page={page} matches={matches} {...dataLinkProps} />\n );\n}\n\nfunction useKeyedPrefetchLinks(matches: AgnosticDataRouteMatch[]) {\n let { manifest, routeModules } = useFrameworkContext();\n\n let [keyedPrefetchLinks, setKeyedPrefetchLinks] = React.useState<\n KeyedHtmlLinkDescriptor[]\n >([]);\n\n React.useEffect(() => {\n let interrupted: boolean = false;\n\n void getKeyedPrefetchLinks(matches, manifest, routeModules).then(\n (links) => {\n if (!interrupted) {\n setKeyedPrefetchLinks(links);\n }\n }\n );\n\n return () => {\n interrupted = true;\n };\n }, [matches, manifest, routeModules]);\n\n return keyedPrefetchLinks;\n}\n\nfunction PrefetchPageLinksImpl({\n page,\n matches: nextMatches,\n ...linkProps\n}: PageLinkDescriptor & {\n matches: AgnosticDataRouteMatch[];\n}) {\n let location = useLocation();\n let { manifest, routeModules } = useFrameworkContext();\n let { loaderData, matches } = useDataRouterStateContext();\n\n let newMatchesForData = React.useMemo(\n () =>\n getNewMatchesForLinks(\n page,\n nextMatches,\n matches,\n manifest,\n location,\n \"data\"\n ),\n [page, nextMatches, matches, manifest, location]\n );\n\n let newMatchesForAssets = React.useMemo(\n () =>\n getNewMatchesForLinks(\n page,\n nextMatches,\n matches,\n manifest,\n location,\n \"assets\"\n ),\n [page, nextMatches, matches, manifest, location]\n );\n\n let dataHrefs = React.useMemo(() => {\n if (page === location.pathname + location.search + location.hash) {\n // Because we opt-into revalidation, don't compute this for the current page\n // since it would always trigger a prefetch of the existing loaders\n return [];\n }\n\n // Single-fetch is harder :)\n // This parallels the logic in the single fetch data strategy\n let routesParams = new Set<string>();\n let foundOptOutRoute = false;\n nextMatches.forEach((m) => {\n if (!manifest.routes[m.route.id].hasLoader) {\n return;\n }\n\n if (\n !newMatchesForData.some((m2) => m2.route.id === m.route.id) &&\n m.route.id in loaderData &&\n routeModules[m.route.id]?.shouldRevalidate\n ) {\n foundOptOutRoute = true;\n } else if (manifest.routes[m.route.id].hasClientLoader) {\n foundOptOutRoute = true;\n } else {\n routesParams.add(m.route.id);\n }\n });\n\n if (routesParams.size === 0) {\n return [];\n }\n\n let url = singleFetchUrl(page);\n // When one or more routes have opted out, we add a _routes param to\n // limit the loaders to those that have a server loader and did not\n // opt out\n if (foundOptOutRoute && routesParams.size > 0) {\n url.searchParams.set(\n \"_routes\",\n nextMatches\n .filter((m) => routesParams.has(m.route.id))\n .map((m) => m.route.id)\n .join(\",\")\n );\n }\n\n return [url.pathname + url.search];\n }, [\n loaderData,\n location,\n manifest,\n newMatchesForData,\n nextMatches,\n page,\n routeModules,\n ]);\n\n let moduleHrefs = React.useMemo(\n () => getModuleLinkHrefs(newMatchesForAssets, manifest),\n [newMatchesForAssets, manifest]\n );\n\n // needs to be a hook with async behavior because we need the modules, not\n // just the manifest like the other links in here.\n let keyedPrefetchLinks = useKeyedPrefetchLinks(newMatchesForAssets);\n\n return (\n <>\n {dataHrefs.map((href) => (\n <link key={href} rel=\"prefetch\" as=\"fetch\" href={href} {...linkProps} />\n ))}\n {moduleHrefs.map((href) => (\n <link key={href} rel=\"modulepreload\" href={href} {...linkProps} />\n ))}\n {keyedPrefetchLinks.map(({ key, link }) => (\n // these don't spread `linkProps` because they are full link descriptors\n // already with their own props\n <link key={key} {...link} />\n ))}\n </>\n );\n}\n\n/**\n Renders all the `<meta>` tags created by route module {@link MetaFunction} exports. You should render it inside the `<head>` of your HTML.\n\n ```tsx\n import { Meta } from \"react-router\";\n\n export default function Root() {\n return (\n <html>\n <head>\n <Meta />\n </head>\n </html>\n );\n }\n ```\n\n @category Components\n */\nexport function Meta() {\n let { isSpaMode, routeModules } = useFrameworkContext();\n let {\n errors,\n matches: routerMatches,\n loaderData,\n } = useDataRouterStateContext();\n let location = useLocation();\n\n let _matches = getActiveMatches(routerMatches, errors, isSpaMode);\n\n let error: any = null;\n if (errors) {\n error = errors[_matches[_matches.length - 1].route.id];\n }\n\n let meta: MetaDescriptor[] = [];\n let leafMeta: MetaDescriptor[] | null = null;\n let matches: MetaMatches = [];\n for (let i = 0; i < _matches.length; i++) {\n let _match = _matches[i];\n let routeId = _match.route.id;\n let data = loaderData[routeId];\n let params = _match.params;\n let routeModule = routeModules[routeId];\n let routeMeta: MetaDescriptor[] | undefined = [];\n\n let match: MetaMatch = {\n id: routeId,\n data,\n meta: [],\n params: _match.params,\n pathname: _match.pathname,\n handle: _match.route.handle,\n error,\n };\n matches[i] = match;\n\n if (routeModule?.meta) {\n routeMeta =\n typeof routeModule.meta === \"function\"\n ? (routeModule.meta as MetaFunction)({\n data,\n params,\n location,\n matches,\n error,\n })\n : Array.isArray(routeModule.meta)\n ? [...routeModule.meta]\n : routeModule.meta;\n } else if (leafMeta) {\n // We only assign the route's meta to the nearest leaf if there is no meta\n // export in the route. The meta function may return a falsy value which\n // is effectively the same as an empty array.\n routeMeta = [...leafMeta];\n }\n\n routeMeta = routeMeta || [];\n if (!Array.isArray(routeMeta)) {\n throw new Error(\n \"The route at \" +\n _match.route.path +\n \" returns an invalid value. All route meta functions must \" +\n \"return an array of meta objects.\" +\n \"\\n\\nTo reference the meta function API, see https://remix.run/route/meta\"\n );\n }\n\n match.meta = routeMeta;\n matches[i] = match;\n meta = [...routeMeta];\n leafMeta = meta;\n }\n\n return (\n <>\n {meta.flat().map((metaProps) => {\n if (!metaProps) {\n return null;\n }\n\n if (\"tagName\" in metaProps) {\n let { tagName, ...rest } = metaProps;\n if (!isValidMetaTag(tagName)) {\n console.warn(\n `A meta object uses an invalid tagName: ${tagName}. Expected either 'link' or 'meta'`\n );\n return null;\n }\n let Comp = tagName;\n return <Comp key={JSON.stringify(rest)} {...rest} />;\n }\n\n if (\"title\" in metaProps) {\n return <title key=\"title\">{String(metaProps.title)}</title>;\n }\n\n if (\"charset\" in metaProps) {\n metaProps.charSet ??= metaProps.charset;\n delete metaProps.charset;\n }\n\n if (\"charSet\" in metaProps && metaProps.charSet != null) {\n return typeof metaProps.charSet === \"string\" ? (\n <meta key=\"charSet\" charSet={metaProps.charSet} />\n ) : null;\n }\n\n if (\"script:ld+json\" in metaProps) {\n try {\n let json = JSON.stringify(metaProps[\"script:ld+json\"]);\n return (\n <script\n key={`script:ld+json:${json}`}\n type=\"application/ld+json\"\n dangerouslySetInnerHTML={{ __html: json }}\n />\n );\n } catch (err) {\n return null;\n }\n }\n return <meta key={JSON.stringify(metaProps)} {...metaProps} />;\n })}\n </>\n );\n}\n\nfunction isValidMetaTag(tagName: unknown): tagName is \"meta\" | \"link\" {\n return typeof tagName === \"string\" && /^(meta|link)$/.test(tagName);\n}\n\n/**\n * Tracks whether hydration is finished, so scripts can be skipped\n * during client-side updates.\n */\nlet isHydrated = false;\n\n/**\n A couple common attributes:\n\n - `<Scripts crossOrigin>` for hosting your static assets on a different server than your app.\n - `<Scripts nonce>` to support a [content security policy for scripts](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src) with [nonce-sources](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources#sources) for your `<script>` tags.\n\n You cannot pass through attributes such as `async`, `defer`, `src`, `type`, `noModule` because they are managed by React Router internally.\n\n @category Types\n */\nexport type ScriptsProps = Omit<\n React.HTMLProps<HTMLScriptElement>,\n | \"children\"\n | \"async\"\n | \"defer\"\n | \"src\"\n | \"type\"\n | \"noModule\"\n | \"dangerouslySetInnerHTML\"\n | \"suppressHydrationWarning\"\n>;\n\n/**\n Renders the client runtime of your app. It should be rendered inside the `<body>` of the document.\n\n ```tsx\n import { Scripts } from \"react-router\";\n\n export default function Root() {\n return (\n <html>\n <head />\n <body>\n <Scripts />\n </body>\n </html>\n );\n }\n ```\n\n If server rendering, you can omit `<Scripts/>` and the app will work as a traditional web app without JavaScript, relying solely on HTML and browser behaviors.\n\n @category Components\n */\nexport function Scripts(props: ScriptsProps) {\n let { manifest, serverHandoffString, isSpaMode, renderMeta } =\n useFrameworkContext();\n let { router, static: isStatic, staticContext } = useDataRouterContext();\n let { matches: routerMatches } = useDataRouterStateContext();\n let enableFogOfWar = isFogOfWarEnabled(isSpaMode);\n\n // Let <ServerRouter> know that we hydrated and we should render the single\n // fetch streaming scripts\n if (renderMeta) {\n renderMeta.didRenderScripts = true;\n }\n\n let matches = getActiveMatches(routerMatches, null, isSpaMode);\n\n React.useEffect(() => {\n isHydrated = true;\n }, []);\n\n let initialScripts = React.useMemo(() => {\n let streamScript =\n \"window.__reactRouterContext.stream = new ReadableStream({\" +\n \"start(controller){\" +\n \"window.__reactRouterContext.streamController = controller;\" +\n \"}\" +\n \"}).pipeThrough(new TextEncoderStream());\";\n\n let contextScript = staticContext\n ? `window.__reactRouterContext = ${serverHandoffString};${streamScript}`\n : \" \";\n\n let routeModulesScript = !isStatic\n ? \" \"\n : `${\n manifest.hmr?.runtime\n ? `import ${JSON.stringify(manifest.hmr.runtime)};`\n : \"\"\n }${!enableFogOfWar ? `import ${JSON.stringify(manifest.url)}` : \"\"};\n${matches\n .map(\n (match, index) =>\n `import * as route${index} from ${JSON.stringify(\n manifest.routes[match.route.id].module\n )};`\n )\n .join(\"\\n\")}\n ${\n enableFogOfWar\n ? // Inline a minimal manifest with the SSR matches\n `window.__reactRouterManifest = ${JSON.stringify(\n getPartialManifest(manifest, router),\n null,\n 2\n )};`\n : \"\"\n }\n window.__reactRouterRouteModules = {${matches\n .map((match, index) => `${JSON.stringify(match.route.id)}:route${index}`)\n .join(\",\")}};\n\nimport(${JSON.stringify(manifest.entry.module)});`;\n\n return (\n <>\n <script\n {...props}\n suppressHydrationWarning\n dangerouslySetInnerHTML={createHtml(contextScript)}\n type={undefined}\n />\n <script\n {...props}\n suppressHydrationWarning\n dangerouslySetInnerHTML={createHtml(routeModulesScript)}\n type=\"module\"\n async\n />\n </>\n );\n // disabled deps array because we are purposefully only rendering this once\n // for hydration, after that we want to just continue rendering the initial\n // scripts as they were when the page first loaded\n // eslint-disable-next-line\n }, []);\n\n let routePreloads = matches\n .map((match) => {\n let route = manifest.routes[match.route.id];\n return (route.imports || []).concat([route.module]);\n })\n .flat(1);\n\n let preloads = isHydrated ? [] : manifest.entry.imports.concat(routePreloads);\n\n return isHydrated ? null : (\n <>\n {!enableFogOfWar ? (\n <link\n rel=\"modulepreload\"\n href={manifest.url}\n crossOrigin={props.crossOrigin}\n />\n ) : null}\n <link\n rel=\"modulepreload\"\n href={manifest.entry.module}\n crossOrigin={props.crossOrigin}\n />\n {dedupe(preloads).map((path) => (\n <link\n key={path}\n rel=\"modulepreload\"\n href={path}\n crossOrigin={props.crossOrigin}\n />\n ))}\n {initialScripts}\n </>\n );\n}\n\nfunction dedupe(array: any[]) {\n return [...new Set(array)];\n}\n\nexport function mergeRefs<T = any>(\n ...refs: Array<React.MutableRefObject<T> | React.LegacyRef<T>>\n): React.RefCallback<T> {\n return (value) => {\n refs.forEach((ref) => {\n if (typeof ref === \"function\") {\n ref(value);\n } else if (ref != null) {\n (ref as React.MutableRefObject<T | null>).current = value;\n }\n });\n };\n}\n","import * as React from \"react\";\n\nimport type {\n BrowserHistory,\n HashHistory,\n History,\n Action as NavigationType,\n Location,\n To,\n} from \"../router/history\";\nimport {\n createBrowserHistory,\n createHashHistory,\n createPath,\n invariant,\n warning,\n} from \"../router/history\";\nimport type {\n BlockerFunction,\n Fetcher,\n FutureConfig,\n GetScrollRestorationKeyFunction,\n HydrationState,\n RelativeRoutingType,\n Router as DataRouter,\n} from \"../router/router\";\nimport { IDLE_FETCHER, createRouter } from \"../router/router\";\nimport type {\n DataStrategyFunction,\n FormEncType,\n HTMLFormMethod,\n UIMatch,\n} from \"../router/utils\";\nimport {\n ErrorResponseImpl,\n joinPaths,\n matchPath,\n stripBasename,\n} from \"../router/utils\";\n\nimport \"./global\";\nimport type {\n SubmitOptions,\n URLSearchParamsInit,\n SubmitTarget,\n FetcherSubmitOptions,\n} from \"./dom\";\nimport {\n createSearchParams,\n defaultMethod,\n getFormSubmissionInfo,\n getSearchParamsForLocation,\n shouldProcessLinkClick,\n} from \"./dom\";\n\nimport type {\n DiscoverBehavior,\n PrefetchBehavior,\n ScriptsProps,\n} from \"./ssr/components\";\nimport {\n PrefetchPageLinks,\n FrameworkContext,\n mergeRefs,\n usePrefetchBehavior,\n} from \"./ssr/components\";\nimport { Router, mapRouteProperties } from \"../components\";\nimport type {\n RouteObject,\n NavigateOptions,\n PatchRoutesOnNavigationFunction,\n} from \"../context\";\nimport {\n DataRouterContext,\n DataRouterStateContext,\n FetchersContext,\n NavigationContext,\n RouteContext,\n ViewTransitionContext,\n} from \"../context\";\nimport {\n useBlocker,\n useHref,\n useLocation,\n useMatches,\n useNavigate,\n useNavigation,\n useResolvedPath,\n useRouteId,\n} from \"../hooks\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Global Stuff\n////////////////////////////////////////////////////////////////////////////////\n\nconst isBrowser =\n typeof window !== \"undefined\" &&\n typeof window.document !== \"undefined\" &&\n typeof window.document.createElement !== \"undefined\";\n\n// HEY YOU! DON'T TOUCH THIS VARIABLE!\n//\n// It is replaced with the proper version at build time via a babel plugin in\n// the rollup config.\n//\n// Export a global property onto the window for React Router detection by the\n// Core Web Vitals Technology Report. This way they can configure the `wappalyzer`\n// to detect and properly classify live websites as being built with React Router:\n// https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json\nconst REACT_ROUTER_VERSION = \"0\";\ntry {\n if (isBrowser) {\n window.__reactRouterVersion = REACT_ROUTER_VERSION;\n }\n} catch (e) {\n // no-op\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Routers\n////////////////////////////////////////////////////////////////////////////////\n\ninterface DOMRouterOpts {\n basename?: string;\n future?: Partial<FutureConfig>;\n hydrationData?: HydrationState;\n dataStrategy?: DataStrategyFunction;\n patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;\n window?: Window;\n}\n\n/**\n * @category Routers\n */\nexport function createBrowserRouter(\n routes: RouteObject[],\n opts?: DOMRouterOpts\n): DataRouter {\n return createRouter({\n basename: opts?.basename,\n future: opts?.future,\n history: createBrowserHistory({ window: opts?.window }),\n hydrationData: opts?.hydrationData || parseHydrationData(),\n routes,\n mapRouteProperties,\n dataStrategy: opts?.dataStrategy,\n patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n window: opts?.window,\n }).initialize();\n}\n\n/**\n * @category Routers\n */\nexport function createHashRouter(\n routes: RouteObject[],\n opts?: DOMRouterOpts\n): DataRouter {\n return createRouter({\n basename: opts?.basename,\n future: opts?.future,\n history: createHashHistory({ window: opts?.window }),\n hydrationData: opts?.hydrationData || parseHydrationData(),\n routes,\n mapRouteProperties,\n dataStrategy: opts?.dataStrategy,\n patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n window: opts?.window,\n }).initialize();\n}\n\nfunction parseHydrationData(): HydrationState | undefined {\n let state = window?.__staticRouterHydrationData;\n if (state && state.errors) {\n state = {\n ...state,\n errors: deserializeErrors(state.errors),\n };\n }\n return state;\n}\n\nfunction deserializeErrors(\n errors: DataRouter[\"state\"][\"errors\"]\n): DataRouter[\"state\"][\"errors\"] {\n if (!errors) return null;\n let entries = Object.entries(errors);\n let serialized: DataRouter[\"state\"][\"errors\"] = {};\n for (let [key, val] of entries) {\n // Hey you! If you change this, please change the corresponding logic in\n // serializeErrors in react-router-dom/server.tsx :)\n if (val && val.__type === \"RouteErrorResponse\") {\n serialized[key] = new ErrorResponseImpl(\n val.status,\n val.statusText,\n val.data,\n val.internal === true\n );\n } else if (val && val.__type === \"Error\") {\n // Attempt to reconstruct the right type of Error (i.e., ReferenceError)\n if (val.__subType) {\n let ErrorConstructor = window[val.__subType];\n if (typeof ErrorConstructor === \"function\") {\n try {\n // @ts-expect-error\n let error = new ErrorConstructor(val.message);\n // Wipe away the client-side stack trace. Nothing to fill it in with\n // because we don't serialize SSR stack traces for security reasons\n error.stack = \"\";\n serialized[key] = error;\n } catch (e) {\n // no-op - fall through and create a normal Error\n }\n }\n }\n\n if (serialized[key] == null) {\n let error = new Error(val.message);\n // Wipe away the client-side stack trace. Nothing to fill it in with\n // because we don't serialize SSR stack traces for security reasons\n error.stack = \"\";\n serialized[key] = error;\n }\n } else {\n serialized[key] = val;\n }\n }\n return serialized;\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Components\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @category Types\n */\nexport interface BrowserRouterProps {\n basename?: string;\n children?: React.ReactNode;\n window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Provides the cleanest URLs.\n *\n * @category Router Components\n */\nexport function BrowserRouter({\n basename,\n children,\n window,\n}: BrowserRouterProps) {\n let historyRef = React.useRef<BrowserHistory>();\n if (historyRef.current == null) {\n historyRef.current = createBrowserHistory({ window, v5Compat: true });\n }\n\n let history = historyRef.current;\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n React.startTransition(() => setStateImpl(newState));\n },\n [setStateImpl]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n />\n );\n}\n\n/**\n * @category Types\n */\nexport interface HashRouterProps {\n basename?: string;\n children?: React.ReactNode;\n window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Stores the location in the hash\n * portion of the URL so it is not sent to the server.\n *\n * @category Router Components\n */\nexport function HashRouter({ basename, children, window }: HashRouterProps) {\n let historyRef = React.useRef<HashHistory>();\n if (historyRef.current == null) {\n historyRef.current = createHashHistory({ window, v5Compat: true });\n }\n\n let history = historyRef.current;\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n React.startTransition(() => setStateImpl(newState));\n },\n [setStateImpl]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n />\n );\n}\n\n/**\n * @category Types\n */\nexport interface HistoryRouterProps {\n basename?: string;\n children?: React.ReactNode;\n history: History;\n}\n\n/**\n * A `<Router>` that accepts a pre-instantiated history object. It's important\n * to note that using your own history object is highly discouraged and may add\n * two versions of the history library to your bundles unless you use the same\n * version of the history library that React Router uses internally.\n *\n * @name unstable_HistoryRouter\n * @category Router Components\n */\nexport function HistoryRouter({\n basename,\n children,\n history,\n}: HistoryRouterProps) {\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n React.startTransition(() => setStateImpl(newState));\n },\n [setStateImpl]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n />\n );\n}\nHistoryRouter.displayName = \"unstable_HistoryRouter\";\n\n/**\n * @category Types\n */\nexport interface LinkProps\n extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> {\n /**\n Defines the link discovery behavior\n\n ```tsx\n <Link /> // default (\"render\")\n <Link discover=\"render\" />\n <Link discover=\"none\" />\n ```\n\n - **render** - default, discover the route when the link renders\n - **none** - don't eagerly discover, only discover if the link is clicked\n */\n discover?: DiscoverBehavior;\n\n /**\n Defines the data and module prefetching behavior for the link.\n\n ```tsx\n <Link /> // default\n <Link prefetch=\"none\" />\n <Link prefetch=\"intent\" />\n <Link prefetch=\"render\" />\n <Link prefetch=\"viewport\" />\n ```\n\n - **none** - default, no prefetching\n - **intent** - prefetches when the user hovers or focuses the link\n - **render** - prefetches when the link renders\n - **viewport** - prefetches when the link is in the viewport, very useful for mobile\n\n Prefetching is done with HTML `<link rel=\"prefetch\">` tags. They are inserted after the link.\n\n ```tsx\n <a href=\"...\" />\n <a href=\"...\" />\n <link rel=\"prefetch\" /> // might conditionally render\n ```\n\n Because of this, if you are using `nav :last-child` you will need to use `nav :last-of-type` so the styles don't conditionally fall off your last link (and any other similar selectors).\n */\n prefetch?: PrefetchBehavior;\n\n /**\n Will use document navigation instead of client side routing when the link is clicked: the browser will handle the transition normally (as if it were an `<a href>`).\n\n ```tsx\n <Link to=\"/logout\" reloadDocument />\n ```\n */\n reloadDocument?: boolean;\n\n /**\n Replaces the current entry in the history stack instead of pushing a new one onto it.\n\n ```tsx\n <Link replace />\n ```\n\n ```\n # with a history stack like this\n A -> B\n\n # normal link click pushes a new entry\n A -> B -> C\n\n # but with `replace`, B is replaced by C\n A -> C\n ```\n */\n replace?: boolean;\n\n /**\n Adds persistent client side routing state to the next location.\n\n ```tsx\n <Link to=\"/somewhere/else\" state={{ some: \"value\" }} />\n ```\n\n The location state is accessed from the `location`.\n\n ```tsx\n function SomeComp() {\n const location = useLocation()\n location.state; // { some: \"value\" }\n }\n ```\n\n This state is inaccessible on the server as it is implemented on top of [`history.state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state)\n */\n state?: any;\n\n /**\n Prevents the scroll position from being reset to the top of the window when the link is clicked and the app is using {@link ScrollRestoration}. This only prevents new locations reseting scroll to the top, scroll position will be restored for back/forward button navigation.\n\n ```tsx\n <Link to=\"?tab=one\" preventScrollReset />\n ```\n */\n preventScrollReset?: boolean;\n\n /**\n Defines the relative path behavior for the link.\n\n ```tsx\n <Link to=\"..\" /> // default: \"route\"\n <Link relative=\"route\" />\n <Link relative=\"path\" />\n ```\n\n Consider a route hierarchy where a parent route pattern is \"blog\" and a child route pattern is \"blog/:slug/edit\".\n\n - **route** - default, resolves the link relative to the route pattern. In the example above a relative link of `\"..\"` will remove both `:slug/edit` segments back to \"/blog\".\n - **path** - relative to the path so `..` will only remove one URL segment up to \"/blog/:slug\"\n */\n relative?: RelativeRoutingType;\n\n /**\n Can be a string or a partial {@link Path}:\n\n ```tsx\n <Link to=\"/some/path\" />\n\n <Link\n to={{\n pathname: \"/some/path\",\n search: \"?query=string\",\n hash: \"#hash\",\n }}\n />\n ```\n */\n to: To;\n\n /**\n Enables a [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) for this navigation.\n\n ```jsx\n <Link to={to} viewTransition>\n Click me\n </Link>\n ```\n\n To apply specific styles for the transition, see {@link useViewTransitionState}\n */\n viewTransition?: boolean;\n}\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\n/**\n A progressively enhanced `<a href>` wrapper to enable navigation with client-side routing.\n\n ```tsx\n import { Link } from \"react-router\";\n\n <Link to=\"/dashboard\">Dashboard</Link>;\n\n <Link\n to={{\n pathname: \"/some/path\",\n search: \"?query=string\",\n hash: \"#hash\",\n }}\n />\n ```\n\n @category Components\n */\nexport const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(\n function LinkWithRef(\n {\n onClick,\n discover = \"render\",\n prefetch = \"none\",\n relative,\n reloadDocument,\n replace,\n state,\n target,\n to,\n preventScrollReset,\n viewTransition,\n ...rest\n },\n forwardedRef\n ) {\n let { basename } = React.useContext(NavigationContext);\n let isAbsolute = typeof to === \"string\" && ABSOLUTE_URL_REGEX.test(to);\n\n // Rendered into <a href> for absolute URLs\n let absoluteHref;\n let isExternal = false;\n\n if (typeof to === \"string\" && isAbsolute) {\n // Render the absolute href server- and client-side\n absoluteHref = to;\n\n // Only check for external origins client-side\n if (isBrowser) {\n try {\n let currentUrl = new URL(window.location.href);\n let targetUrl = to.startsWith(\"//\")\n ? new URL(currentUrl.protocol + to)\n : new URL(to);\n let path = stripBasename(targetUrl.pathname, basename);\n\n if (targetUrl.origin === currentUrl.origin && path != null) {\n // Strip the protocol/origin/basename for same-origin absolute URLs\n to = path + targetUrl.search + targetUrl.hash;\n } else {\n isExternal = true;\n }\n } catch (e) {\n // We can't do external URL detection without a valid URL\n warning(\n false,\n `<Link to=\"${to}\"> contains an invalid URL which will probably break ` +\n `when clicked - please update to a valid URL path.`\n );\n }\n }\n }\n\n // Rendered into <a href> for relative URLs\n let href = useHref(to, { relative });\n let [shouldPrefetch, prefetchRef, prefetchHandlers] = usePrefetchBehavior(\n prefetch,\n rest\n );\n\n let internalOnClick = useLinkClickHandler(to, {\n replace,\n state,\n target,\n preventScrollReset,\n relative,\n viewTransition,\n });\n function handleClick(\n event: React.MouseEvent<HTMLAnchorElement, MouseEvent>\n ) {\n if (onClick) onClick(event);\n if (!event.defaultPrevented) {\n internalOnClick(event);\n }\n }\n\n let link = (\n // eslint-disable-next-line jsx-a11y/anchor-has-content\n <a\n {...rest}\n {...prefetchHandlers}\n href={absoluteHref || href}\n onClick={isExternal || reloadDocument ? onClick : handleClick}\n ref={mergeRefs(forwardedRef, prefetchRef)}\n target={target}\n data-discover={\n !isAbsolute && discover === \"render\" ? \"true\" : undefined\n }\n />\n );\n\n return shouldPrefetch && !isAbsolute ? (\n <>\n {link}\n <PrefetchPageLinks page={href} />\n </>\n ) : (\n link\n );\n }\n);\nLink.displayName = \"Link\";\n\n/**\n The object passed to {@link NavLink} `children`, `className`, and `style` prop callbacks to render and style the link based on its state.\n\n ```\n // className\n <NavLink\n to=\"/messages\"\n className={({ isActive, isPending }) =>\n isPending ? \"pending\" : isActive ? \"active\" : \"\"\n }\n >\n Messages\n </NavLink>\n\n // style\n <NavLink\n to=\"/messages\"\n style={({ isActive, isPending }) => {\n return {\n fontWeight: isActive ? \"bold\" : \"\",\n color: isPending ? \"red\" : \"black\",\n }\n )}\n />\n\n // children\n <NavLink to=\"/tasks\">\n {({ isActive, isPending }) => (\n <span className={isActive ? \"active\" : \"\"}>Tasks</span>\n )}\n </NavLink>\n ```\n\n */\nexport type NavLinkRenderProps = {\n /**\n * Indicates if the link's URL matches the current location.\n */\n isActive: boolean;\n\n /**\n * Indicates if the pending location matches the link's URL.\n */\n isPending: boolean;\n\n /**\n * Indicates if a view transition to the link's URL is in progress. See {@link useViewTransitionState}\n */\n isTransitioning: boolean;\n};\n\n/**\n * @category Types\n */\nexport interface NavLinkProps\n extends Omit<LinkProps, \"className\" | \"style\" | \"children\"> {\n /**\n Can be regular React children or a function that receives an object with the active and pending states of the link.\n\n ```tsx\n <NavLink to=\"/tasks\">\n {({ isActive }) => (\n <span className={isActive ? \"active\" : \"\"}>Tasks</span>\n )}\n </NavLink>\n ```\n */\n children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode);\n\n /**\n Changes the matching logic to make it case-sensitive:\n\n | Link | URL | isActive |\n | -------------------------------------------- | ------------- | -------- |\n | `<NavLink to=\"/SpOnGe-bOB\" />` | `/sponge-bob` | true |\n | `<NavLink to=\"/SpOnGe-bOB\" caseSensitive />` | `/sponge-bob` | false |\n */\n caseSensitive?: boolean;\n\n /**\n Classes are automatically applied to NavLink that correspond to {@link NavLinkRenderProps}.\n\n ```css\n a.active { color: red; }\n a.pending { color: blue; }\n a.transitioning {\n view-transition-name: my-transition;\n }\n ```\n */\n className?: string | ((props: NavLinkRenderProps) => string | undefined);\n\n /**\n Changes the matching logic for the `active` and `pending` states to only match to the \"end\" of the {@link NavLinkProps.to}. If the URL is longer, it will no longer be considered active.\n\n | Link | URL | isActive |\n | ----------------------------- | ------------ | -------- |\n | `<NavLink to=\"/tasks\" />` | `/tasks` | true |\n | `<NavLink to=\"/tasks\" />` | `/tasks/123` | true |\n | `<NavLink to=\"/tasks\" end />` | `/tasks` | true |\n | `<NavLink to=\"/tasks\" end />` | `/tasks/123` | false |\n\n `<NavLink to=\"/\">` is an exceptional case because _every_ URL matches `/`. To avoid this matching every single route by default, it effectively ignores the `end` prop and only matches when you're at the root route.\n */\n end?: boolean;\n\n style?:\n | React.CSSProperties\n | ((props: NavLinkRenderProps) => React.CSSProperties | undefined);\n}\n\n/**\n Wraps {@link Link | `<Link>`} with additional props for styling active and pending states.\n\n - Automatically applies classes to the link based on its active and pending states, see {@link NavLinkProps.className}.\n - Automatically applies `aria-current=\"page\"` to the link when the link is active. See [`aria-current`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-current) on MDN.\n\n ```tsx\n import { NavLink } from \"react-router\"\n <NavLink to=\"/message\" />\n ```\n\n States are available through the className, style, and children render props. See {@link NavLinkRenderProps}.\n\n ```tsx\n <NavLink\n to=\"/messages\"\n className={({ isActive, isPending }) =>\n isPending ? \"pending\" : isActive ? \"active\" : \"\"\n }\n >\n Messages\n </NavLink>\n ```\n\n @category Components\n */\nexport const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(\n function NavLinkWithRef(\n {\n \"aria-current\": ariaCurrentProp = \"page\",\n caseSensitive = false,\n className: classNameProp = \"\",\n end = false,\n style: styleProp,\n to,\n viewTransition,\n children,\n ...rest\n },\n ref\n ) {\n let path = useResolvedPath(to, { relative: rest.relative });\n let location = useLocation();\n let routerState = React.useContext(DataRouterStateContext);\n let { navigator, basename } = React.useContext(NavigationContext);\n let isTransitioning =\n routerState != null &&\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useViewTransitionState(path) &&\n viewTransition === true;\n\n let toPathname = navigator.encodeLocation\n ? navigator.encodeLocation(path).pathname\n : path.pathname;\n let locationPathname = location.pathname;\n let nextLocationPathname =\n routerState && routerState.navigation && routerState.navigation.location\n ? routerState.navigation.location.pathname\n : null;\n\n if (!caseSensitive) {\n locationPathname = locationPathname.toLowerCase();\n nextLocationPathname = nextLocationPathname\n ? nextLocationPathname.toLowerCase()\n : null;\n toPathname = toPathname.toLowerCase();\n }\n\n if (nextLocationPathname && basename) {\n nextLocationPathname =\n stripBasename(nextLocationPathname, basename) || nextLocationPathname;\n }\n\n // If the `to` has a trailing slash, look at that exact spot. Otherwise,\n // we're looking for a slash _after_ what's in `to`. For example:\n //\n // <NavLink to=\"/users\"> and <NavLink to=\"/users/\">\n // both want to look for a / at index 6 to match URL `/users/matt`\n const endSlashPosition =\n toPathname !== \"/\" && toPathname.endsWith(\"/\")\n ? toPathname.length - 1\n : toPathname.length;\n let isActive =\n locationPathname === toPathname ||\n (!end &&\n locationPathname.startsWith(toPathname) &&\n locationPathname.charAt(endSlashPosition) === \"/\");\n\n let isPending =\n nextLocationPathname != null &&\n (nextLocationPathname === toPathname ||\n (!end &&\n nextLocationPathname.startsWith(toPathname) &&\n nextLocationPathname.charAt(toPathname.length) === \"/\"));\n\n let renderProps = {\n isActive,\n isPending,\n isTransitioning,\n };\n\n let ariaCurrent = isActive ? ariaCurrentProp : undefined;\n\n let className: string | undefined;\n if (typeof classNameProp === \"function\") {\n className = classNameProp(renderProps);\n } else {\n // If the className prop is not a function, we use a default `active`\n // class for <NavLink />s that are active. In v5 `active` was the default\n // value for `activeClassName`, but we are removing that API and can still\n // use the old default behavior for a cleaner upgrade path and keep the\n // simple styling rules working as they currently do.\n className = [\n classNameProp,\n isActive ? \"active\" : null,\n isPending ? \"pending\" : null,\n isTransitioning ? \"transitioning\" : null,\n ]\n .filter(Boolean)\n .join(\" \");\n }\n\n let style =\n typeof styleProp === \"function\" ? styleProp(renderProps) : styleProp;\n\n return (\n <Link\n {...rest}\n aria-current={ariaCurrent}\n className={className}\n ref={ref}\n style={style}\n to={to}\n viewTransition={viewTransition}\n >\n {typeof children === \"function\" ? children(renderProps) : children}\n </Link>\n );\n }\n);\nNavLink.displayName = \"NavLink\";\n\n/**\n * Form props shared by navigations and fetchers\n */\ninterface SharedFormProps extends React.FormHTMLAttributes<HTMLFormElement> {\n /**\n * The HTTP verb to use when the form is submitted. Supports \"get\", \"post\",\n * \"put\", \"delete\", and \"patch\".\n *\n * Native `<form>` only supports `get` and `post`, avoid the other verbs if\n * you'd like to support progressive enhancement\n */\n method?: HTMLFormMethod;\n\n /**\n * The encoding type to use for the form submission.\n */\n encType?:\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"text/plain\";\n\n /**\n * The URL to submit the form data to. If `undefined`, this defaults to the closest route in context.\n */\n action?: string;\n\n /**\n * Determines whether the form action is relative to the route hierarchy or\n * the pathname. Use this if you want to opt out of navigating the route\n * hierarchy and want to instead route based on /-delimited URL segments\n */\n relative?: RelativeRoutingType;\n\n /**\n * Prevent the scroll position from resetting to the top of the viewport on\n * completion of the navigation when using the <ScrollRestoration> component\n */\n preventScrollReset?: boolean;\n\n /**\n * A function to call when the form is submitted. If you call\n * `event.preventDefault()` then this form will not do anything.\n */\n onSubmit?: React.FormEventHandler<HTMLFormElement>;\n}\n\n/**\n * Form props available to fetchers\n * @category Types\n */\nexport interface FetcherFormProps extends SharedFormProps {}\n\n/**\n * Form props available to navigations\n * @category Types\n */\nexport interface FormProps extends SharedFormProps {\n discover?: DiscoverBehavior;\n\n /**\n * Indicates a specific fetcherKey to use when using `navigate={false}` so you\n * can pick up the fetcher's state in a different component in a {@link\n * useFetcher}.\n */\n fetcherKey?: string;\n\n /**\n * Skips the navigation and uses a {@link useFetcher | fetcher} internally\n * when `false`. This is essentially a shorthand for `useFetcher()` +\n * `<fetcher.Form>` where you don't care about the resulting data in this\n * component.\n */\n navigate?: boolean;\n\n /**\n * Forces a full document navigation instead of client side routing + data\n * fetch.\n */\n reloadDocument?: boolean;\n\n /**\n * Replaces the current entry in the browser history stack when the form\n * navigates. Use this if you don't want the user to be able to click \"back\"\n * to the page with the form on it.\n */\n replace?: boolean;\n\n /**\n * State object to add to the history stack entry for this navigation\n */\n state?: any;\n\n /**\n * Enables a [View\n * Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API)\n * for this navigation. To apply specific styles during the transition see\n * {@link useViewTransitionState}.\n */\n viewTransition?: boolean;\n}\n\ntype HTMLSubmitEvent = React.BaseSyntheticEvent<\n SubmitEvent,\n Event,\n HTMLFormElement\n>;\n\ntype HTMLFormSubmitter = HTMLButtonElement | HTMLInputElement;\n\n/**\n\nA progressively enhanced HTML [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) that submits data to actions via `fetch`, activating pending states in `useNavigation` which enables advanced user interfaces beyond a basic HTML form. After a form's action completes, all data on the page is automatically revalidated to keep the UI in sync with the data.\n\nBecause it uses the HTML form API, server rendered pages are interactive at a basic level before JavaScript loads. Instead of React Router managing the submission, the browser manages the submission as well as the pending states (like the spinning favicon). After JavaScript loads, React Router takes over enabling web application user experiences.\n\nForm is most useful for submissions that should also change the URL or otherwise add an entry to the browser history stack. For forms that shouldn't manipulate the browser history stack, use [`<fetcher.Form>`][fetcher_form].\n\n```tsx\nimport { Form } from \"react-router\";\n\nfunction NewEvent() {\n return (\n <Form action=\"/events\" method=\"post\">\n <input name=\"title\" type=\"text\" />\n <input name=\"description\" type=\"text\" />\n </Form>\n )\n}\n```\n\n@category Components\n*/\nexport const Form = React.forwardRef<HTMLFormElement, FormProps>(\n (\n {\n discover = \"render\",\n fetcherKey,\n navigate,\n reloadDocument,\n replace,\n state,\n method = defaultMethod,\n action,\n onSubmit,\n relative,\n preventScrollReset,\n viewTransition,\n ...props\n },\n forwardedRef\n ) => {\n let submit = useSubmit();\n let formAction = useFormAction(action, { relative });\n let formMethod: HTMLFormMethod =\n method.toLowerCase() === \"get\" ? \"get\" : \"post\";\n let isAbsolute =\n typeof action === \"string\" && ABSOLUTE_URL_REGEX.test(action);\n\n let submitHandler: React.FormEventHandler<HTMLFormElement> = (event) => {\n onSubmit && onSubmit(event);\n if (event.defaultPrevented) return;\n event.preventDefault();\n\n let submitter = (event as unknown as HTMLSubmitEvent).nativeEvent\n .submitter as HTMLFormSubmitter | null;\n\n let submitMethod =\n (submitter?.getAttribute(\"formmethod\") as HTMLFormMethod | undefined) ||\n method;\n\n submit(submitter || event.currentTarget, {\n fetcherKey,\n method: submitMethod,\n navigate,\n replace,\n state,\n relative,\n preventScrollReset,\n viewTransition,\n });\n };\n\n return (\n <form\n ref={forwardedRef}\n method={formMethod}\n action={formAction}\n onSubmit={reloadDocument ? onSubmit : submitHandler}\n {...props}\n data-discover={\n !isAbsolute && discover === \"render\" ? \"true\" : undefined\n }\n />\n );\n }\n);\nForm.displayName = \"Form\";\n\nexport type ScrollRestorationProps = ScriptsProps & {\n /**\n Defines the key used to restore scroll positions.\n\n ```tsx\n <ScrollRestoration\n getKey={(location, matches) => {\n // default behavior\n return location.key\n }}\n />\n ```\n */\n getKey?: GetScrollRestorationKeyFunction;\n\n storageKey?: string;\n};\n\n/**\n Emulates the browser's scroll restoration on location changes. Apps should only render one of these, right before the {@link Scripts} component.\n\n ```tsx\n import { ScrollRestoration } from \"react-router\";\n\n export default function Root() {\n return (\n <html>\n <body>\n <ScrollRestoration />\n <Scripts />\n </body>\n </html>\n );\n }\n ```\n\n This component renders an inline `<script>` to prevent scroll flashing. The `nonce` prop will be passed down to the script tag to allow CSP nonce usage.\n\n ```tsx\n <ScrollRestoration nonce={cspNonce} />\n ```\n\n @category Components\n */\nexport function ScrollRestoration({\n getKey,\n storageKey,\n ...props\n}: ScrollRestorationProps) {\n let remixContext = React.useContext(FrameworkContext);\n let { basename } = React.useContext(NavigationContext);\n let location = useLocation();\n let matches = useMatches();\n useScrollRestoration({ getKey, storageKey });\n\n // In order to support `getKey`, we need to compute a \"key\" here so we can\n // hydrate that up so that SSR scroll restoration isn't waiting on React to\n // hydrate. *However*, our key on the server is not the same as our key on\n // the client! So if the user's getKey implementation returns the SSR\n // location key, then let's ignore it and let our inline <script> below pick\n // up the client side history state key\n let ssrKey = React.useMemo(\n () => {\n if (!remixContext || !getKey) return null;\n let userKey = getScrollRestorationKey(\n location,\n matches,\n basename,\n getKey\n );\n return userKey !== location.key ? userKey : null;\n },\n // Nah, we only need this the first time for the SSR render\n // eslint-disable-next-line react-hooks/exhaustive-deps\n []\n );\n\n // In SPA Mode, there's nothing to restore on initial render since we didn't\n // render anything on the server\n if (!remixContext || remixContext.isSpaMode) {\n return null;\n }\n\n let restoreScroll = ((storageKey: string, restoreKey: string) => {\n if (!window.history.state || !window.history.state.key) {\n let key = Math.random().toString(32).slice(2);\n window.history.replaceState({ key }, \"\");\n }\n try {\n let positions = JSON.parse(sessionStorage.getItem(storageKey) || \"{}\");\n let storedY = positions[restoreKey || window.history.state.key];\n if (typeof storedY === \"number\") {\n window.scrollTo(0, storedY);\n }\n } catch (error: unknown) {\n console.error(error);\n sessionStorage.removeItem(storageKey);\n }\n }).toString();\n\n return (\n <script\n {...props}\n suppressHydrationWarning\n dangerouslySetInnerHTML={{\n __html: `(${restoreScroll})(${JSON.stringify(\n storageKey || SCROLL_RESTORATION_STORAGE_KEY\n )}, ${JSON.stringify(ssrKey)})`,\n }}\n />\n );\n}\nScrollRestoration.displayName = \"ScrollRestoration\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hooks\n////////////////////////////////////////////////////////////////////////////////\n\nenum DataRouterHook {\n UseScrollRestoration = \"useScrollRestoration\",\n UseSubmit = \"useSubmit\",\n UseSubmitFetcher = \"useSubmitFetcher\",\n UseFetcher = \"useFetcher\",\n useViewTransitionState = \"useViewTransitionState\",\n}\n\nenum DataRouterStateHook {\n UseFetcher = \"useFetcher\",\n UseFetchers = \"useFetchers\",\n UseScrollRestoration = \"useScrollRestoration\",\n}\n\n// Internal hooks\n\nfunction getDataRouterConsoleError(\n hookName: DataRouterHook | DataRouterStateHook\n) {\n return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n let ctx = React.useContext(DataRouterContext);\n invariant(ctx, getDataRouterConsoleError(hookName));\n return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n let state = React.useContext(DataRouterStateContext);\n invariant(state, getDataRouterConsoleError(hookName));\n return state;\n}\n\n// External hooks\n\n/**\n * Handles the click behavior for router `<Link>` components. This is useful if\n * you need to create custom `<Link>` components with the same click behavior we\n * use in our exported `<Link>`.\n *\n * @category Hooks\n */\nexport function useLinkClickHandler<E extends Element = HTMLAnchorElement>(\n to: To,\n {\n target,\n replace: replaceProp,\n state,\n preventScrollReset,\n relative,\n viewTransition,\n }: {\n target?: React.HTMLAttributeAnchorTarget;\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n viewTransition?: boolean;\n } = {}\n): (event: React.MouseEvent<E, MouseEvent>) => void {\n let navigate = useNavigate();\n let location = useLocation();\n let path = useResolvedPath(to, { relative });\n\n return React.useCallback(\n (event: React.MouseEvent<E, MouseEvent>) => {\n if (shouldProcessLinkClick(event, target)) {\n event.preventDefault();\n\n // If the URL hasn't changed, a regular <a> will do a replace instead of\n // a push, so do the same here unless the replace prop is explicitly set\n let replace =\n replaceProp !== undefined\n ? replaceProp\n : createPath(location) === createPath(path);\n\n navigate(to, {\n replace,\n state,\n preventScrollReset,\n relative,\n viewTransition,\n });\n }\n },\n [\n location,\n navigate,\n path,\n replaceProp,\n state,\n target,\n to,\n preventScrollReset,\n relative,\n viewTransition,\n ]\n );\n}\n\n/**\n Returns a tuple of the current URL's {@link URLSearchParams} and a function to update them. Setting the search params causes a navigation.\n\n ```tsx\n import { useSearchParams } from \"react-router\";\n\n export function SomeComponent() {\n const [searchParams, setSearchParams] = useSearchParams();\n // ...\n }\n ```\n\n @category Hooks\n */\nexport function useSearchParams(\n defaultInit?: URLSearchParamsInit\n): [URLSearchParams, SetURLSearchParams] {\n warning(\n typeof URLSearchParams !== \"undefined\",\n `You cannot use the \\`useSearchParams\\` hook in a browser that does not ` +\n `support the URLSearchParams API. If you need to support Internet ` +\n `Explorer 11, we recommend you load a polyfill such as ` +\n `https://github.com/ungap/url-search-params.`\n );\n\n let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));\n let hasSetSearchParamsRef = React.useRef(false);\n\n let location = useLocation();\n let searchParams = React.useMemo(\n () =>\n // Only merge in the defaults if we haven't yet called setSearchParams.\n // Once we call that we want those to take precedence, otherwise you can't\n // remove a param with setSearchParams({}) if it has an initial value\n getSearchParamsForLocation(\n location.search,\n hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current\n ),\n [location.search]\n );\n\n let navigate = useNavigate();\n let setSearchParams = React.useCallback<SetURLSearchParams>(\n (nextInit, navigateOptions) => {\n const newSearchParams = createSearchParams(\n typeof nextInit === \"function\" ? nextInit(searchParams) : nextInit\n );\n hasSetSearchParamsRef.current = true;\n navigate(\"?\" + newSearchParams, navigateOptions);\n },\n [navigate, searchParams]\n );\n\n return [searchParams, setSearchParams];\n}\n\n/**\n Sets new search params and causes a navigation when called.\n\n ```tsx\n <button\n onClick={() => {\n const params = new URLSearchParams();\n params.set(\"someKey\", \"someValue\");\n setSearchParams(params, {\n preventScrollReset: true,\n });\n }}\n />\n ```\n\n It also supports a function for setting new search params.\n\n ```tsx\n <button\n onClick={() => {\n setSearchParams((prev) => {\n prev.set(\"someKey\", \"someValue\");\n return prev;\n });\n }}\n />\n ```\n */\nexport type SetURLSearchParams = (\n nextInit?:\n | URLSearchParamsInit\n | ((prev: URLSearchParams) => URLSearchParamsInit),\n navigateOpts?: NavigateOptions\n) => void;\n\n/**\n * Submits a HTML `<form>` to the server without reloading the page.\n */\nexport interface SubmitFunction {\n (\n /**\n Can be multiple types of elements and objects\n\n **`HTMLFormElement`**\n\n ```tsx\n <Form\n onSubmit={(event) => {\n submit(event.currentTarget);\n }}\n />\n ```\n\n **`FormData`**\n\n ```tsx\n const formData = new FormData();\n formData.append(\"myKey\", \"myValue\");\n submit(formData, { method: \"post\" });\n ```\n\n **Plain object that will be serialized as `FormData`**\n\n ```tsx\n submit({ myKey: \"myValue\" }, { method: \"post\" });\n ```\n\n **Plain object that will be serialized as JSON**\n\n ```tsx\n submit(\n { myKey: \"myValue\" },\n { method: \"post\", encType: \"application/json\" }\n );\n ```\n */\n target: SubmitTarget,\n\n /**\n * Options that override the `<form>`'s own attributes. Required when\n * submitting arbitrary data without a backing `<form>`.\n */\n options?: SubmitOptions\n ): Promise<void>;\n}\n\n/**\n * Submits a fetcher `<form>` to the server without reloading the page.\n */\nexport interface FetcherSubmitFunction {\n (\n /**\n Can be multiple types of elements and objects\n\n **`HTMLFormElement`**\n\n ```tsx\n <fetcher.Form\n onSubmit={(event) => {\n fetcher.submit(event.currentTarget);\n }}\n />\n ```\n\n **`FormData`**\n\n ```tsx\n const formData = new FormData();\n formData.append(\"myKey\", \"myValue\");\n fetcher.submit(formData, { method: \"post\" });\n ```\n\n **Plain object that will be serialized as `FormData`**\n\n ```tsx\n fetcher.submit({ myKey: \"myValue\" }, { method: \"post\" });\n ```\n\n **Plain object that will be serialized as JSON**\n\n ```tsx\n fetcher.submit(\n { myKey: \"myValue\" },\n { method: \"post\", encType: \"application/json\" }\n );\n ```\n\n */\n target: SubmitTarget,\n\n // Fetchers cannot replace or set state because they are not navigation events\n options?: FetcherSubmitOptions\n ): Promise<void>;\n}\n\nlet fetcherId = 0;\nlet getUniqueFetcherId = () => `__${String(++fetcherId)}__`;\n\n/**\n The imperative version of {@link Form | `<Form>`} that lets you submit a form from code instead of a user interaction.\n\n ```tsx\n import { useSubmit } from \"react-router\";\n\n function SomeComponent() {\n const submit = useSubmit();\n return (\n <Form\n onChange={(event) => {\n submit(event.currentTarget);\n }}\n />\n );\n }\n ```\n\n @category Hooks\n */\nexport function useSubmit(): SubmitFunction {\n let { router } = useDataRouterContext(DataRouterHook.UseSubmit);\n let { basename } = React.useContext(NavigationContext);\n let currentRouteId = useRouteId();\n\n return React.useCallback<SubmitFunction>(\n async (target, options = {}) => {\n let { action, method, encType, formData, body } = getFormSubmissionInfo(\n target,\n basename\n );\n\n if (options.navigate === false) {\n let key = options.fetcherKey || getUniqueFetcherId();\n await router.fetch(key, currentRouteId, options.action || action, {\n preventScrollReset: options.preventScrollReset,\n formData,\n body,\n formMethod: options.method || (method as HTMLFormMethod),\n formEncType: options.encType || (encType as FormEncType),\n flushSync: options.flushSync,\n });\n } else {\n await router.navigate(options.action || action, {\n preventScrollReset: options.preventScrollReset,\n formData,\n body,\n formMethod: options.method || (method as HTMLFormMethod),\n formEncType: options.encType || (encType as FormEncType),\n replace: options.replace,\n state: options.state,\n fromRouteId: currentRouteId,\n flushSync: options.flushSync,\n viewTransition: options.viewTransition,\n });\n }\n },\n [router, basename, currentRouteId]\n );\n}\n\n// v7: Eventually we should deprecate this entirely in favor of using the\n// router method directly?\n/**\n Resolves the URL to the closest route in the component hierarchy instead of the current URL of the app.\n\n This is used internally by {@link Form} resolve the action to the closest route, but can be used generically as well.\n\n ```tsx\n import { useFormAction } from \"react-router\";\n\n function SomeComponent() {\n // closest route URL\n let action = useFormAction();\n\n // closest route URL + \"destroy\"\n let destroyAction = useFormAction(\"destroy\");\n }\n ```\n\n @category Hooks\n */\nexport function useFormAction(\n /**\n * The action to append to the closest route URL.\n */\n action?: string,\n { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n let { basename } = React.useContext(NavigationContext);\n let routeContext = React.useContext(RouteContext);\n invariant(routeContext, \"useFormAction must be used inside a RouteContext\");\n\n let [match] = routeContext.matches.slice(-1);\n // Shallow clone path so we can modify it below, otherwise we modify the\n // object referenced by useMemo inside useResolvedPath\n let path = { ...useResolvedPath(action ? action : \".\", { relative }) };\n\n // If no action was specified, browsers will persist current search params\n // when determining the path, so match that behavior\n // https://github.com/remix-run/remix/issues/927\n let location = useLocation();\n if (action == null) {\n // Safe to write to this directly here since if action was undefined, we\n // would have called useResolvedPath(\".\") which will never include a search\n path.search = location.search;\n\n // When grabbing search params from the URL, remove any included ?index param\n // since it might not apply to our contextual route. We add it back based\n // on match.route.index below\n let params = new URLSearchParams(path.search);\n let indexValues = params.getAll(\"index\");\n let hasNakedIndexParam = indexValues.some((v) => v === \"\");\n if (hasNakedIndexParam) {\n params.delete(\"index\");\n indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n let qs = params.toString();\n path.search = qs ? `?${qs}` : \"\";\n }\n }\n\n if ((!action || action === \".\") && match.route.index) {\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n }\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the form action. If this is a root navigation, then just use\n // the raw basename which allows the basename to have full control over the\n // presence of a trailing slash on root actions\n if (basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n/**\nThe return value of `useFetcher` that keeps track of the state of a fetcher.\n\n```tsx\nlet fetcher = useFetcher();\n```\n */\nexport type FetcherWithComponents<TData> = Fetcher<TData> & {\n /**\n Just like {@link Form} except it doesn't cause a navigation.\n\n ```tsx\n function SomeComponent() {\n const fetcher = useFetcher()\n return (\n <fetcher.Form method=\"post\" action=\"/some/route\">\n <input type=\"text\" />\n </fetcher.Form>\n )\n }\n ```\n */\n Form: React.ForwardRefExoticComponent<\n FetcherFormProps & React.RefAttributes<HTMLFormElement>\n >;\n\n /**\n Submits form data to a route. While multiple nested routes can match a URL, only the leaf route will be called.\n\n The `formData` can be multiple types:\n\n - [`FormData`][form_data] - A `FormData` instance.\n - [`HTMLFormElement`][html_form_element] - A [`<form>`][form_element] DOM element.\n - `Object` - An object of key/value pairs that will be converted to a `FormData` instance by default. You can pass a more complex object and serialize it as JSON by specifying `encType: \"application/json\"`. See [`useSubmit`][use-submit] for more details.\n\n If the method is `GET`, then the route [`loader`][loader] is being called and with the `formData` serialized to the url as [`URLSearchParams`][url_search_params]. If `DELETE`, `PATCH`, `POST`, or `PUT`, then the route [`action`][action] is being called with `formData` as the body.\n\n ```tsx\n // Submit a FormData instance (GET request)\n const formData = new FormData();\n fetcher.submit(formData);\n\n // Submit the HTML form element\n fetcher.submit(event.currentTarget.form, {\n method: \"POST\",\n });\n\n // Submit key/value JSON as a FormData instance\n fetcher.submit(\n { serialized: \"values\" },\n { method: \"POST\" }\n );\n\n // Submit raw JSON\n fetcher.submit(\n {\n deeply: {\n nested: {\n json: \"values\",\n },\n },\n },\n {\n method: \"POST\",\n encType: \"application/json\",\n }\n );\n ```\n */\n submit: FetcherSubmitFunction;\n\n /**\n Loads data from a route. Useful for loading data imperatively inside of user events outside of a normal button or form, like a combobox or search input.\n\n ```tsx\n let fetcher = useFetcher()\n\n <input onChange={e => {\n fetcher.load(`/search?q=${e.target.value}`)\n }} />\n ```\n */\n load: (\n href: string,\n opts?: {\n /**\n * Wraps the initial state update for this `fetcher.load` in a\n * `ReactDOM.flushSync` call instead of the default `React.startTransition`.\n * This allows you to perform synchronous DOM actions immediately after the\n * update is flushed to the DOM.\n */\n flushSync?: boolean;\n }\n ) => Promise<void>;\n};\n\n// TODO: (v7) Change the useFetcher generic default from `any` to `unknown`\n\n/**\n Useful for creating complex, dynamic user interfaces that require multiple, concurrent data interactions without causing a navigation.\n\n Fetchers track their own, independent state and can be used to load data, submit forms, and generally interact with loaders and actions.\n\n ```tsx\n import { useFetcher } from \"react-router\"\n\n function SomeComponent() {\n let fetcher = useFetcher()\n\n // states are available on the fetcher\n fetcher.state // \"idle\" | \"loading\" | \"submitting\"\n fetcher.data // the data returned from the action or loader\n\n // render a form\n <fetcher.Form method=\"post\" />\n\n // load data\n fetcher.load(\"/some/route\")\n\n // submit data\n fetcher.submit(someFormRef, { method: \"post\" })\n fetcher.submit(someData, {\n method: \"post\",\n encType: \"application/json\"\n })\n }\n ```\n\n @category Hooks\n */\nexport function useFetcher<TData = any>({\n key,\n}: {\n /**\n By default, `useFetcher` generate a unique fetcher scoped to that component. If you want to identify a fetcher with your own key such that you can access it from elsewhere in your app, you can do that with the `key` option:\n\n ```tsx\n function SomeComp() {\n let fetcher = useFetcher({ key: \"my-key\" })\n // ...\n }\n\n // Somewhere else\n function AnotherComp() {\n // this will be the same fetcher, sharing the state across the app\n let fetcher = useFetcher({ key: \"my-key\" });\n // ...\n }\n ```\n */\n key?: string;\n} = {}): FetcherWithComponents<TData> {\n let { router } = useDataRouterContext(DataRouterHook.UseFetcher);\n let state = useDataRouterState(DataRouterStateHook.UseFetcher);\n let fetcherData = React.useContext(FetchersContext);\n let route = React.useContext(RouteContext);\n let routeId = route.matches[route.matches.length - 1]?.route.id;\n\n invariant(fetcherData, `useFetcher must be used inside a FetchersContext`);\n invariant(route, `useFetcher must be used inside a RouteContext`);\n invariant(\n routeId != null,\n `useFetcher can only be used on routes that contain a unique \"id\"`\n );\n\n // Fetcher key handling\n let defaultKey = React.useId();\n let [fetcherKey, setFetcherKey] = React.useState<string>(key || defaultKey);\n if (key && key !== fetcherKey) {\n setFetcherKey(key);\n }\n\n // Registration/cleanup\n React.useEffect(() => {\n router.getFetcher(fetcherKey);\n return () => router.deleteFetcher(fetcherKey);\n }, [router, fetcherKey]);\n\n // Fetcher additions\n let load = React.useCallback(\n async (href: string, opts?: { flushSync?: boolean }) => {\n invariant(routeId, \"No routeId available for fetcher.load()\");\n await router.fetch(fetcherKey, routeId, href, opts);\n },\n [fetcherKey, routeId, router]\n );\n\n let submitImpl = useSubmit();\n let submit = React.useCallback<FetcherSubmitFunction>(\n async (target, opts) => {\n await submitImpl(target, {\n ...opts,\n navigate: false,\n fetcherKey,\n });\n },\n [fetcherKey, submitImpl]\n );\n\n let FetcherForm = React.useMemo(() => {\n let FetcherForm = React.forwardRef<HTMLFormElement, FetcherFormProps>(\n (props, ref) => {\n return (\n <Form {...props} navigate={false} fetcherKey={fetcherKey} ref={ref} />\n );\n }\n );\n FetcherForm.displayName = \"fetcher.Form\";\n return FetcherForm;\n }, [fetcherKey]);\n\n // Exposed FetcherWithComponents\n let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;\n let data = fetcherData.get(fetcherKey);\n let fetcherWithComponents = React.useMemo(\n () => ({\n Form: FetcherForm,\n submit,\n load,\n ...fetcher,\n data,\n }),\n [FetcherForm, submit, load, fetcher, data]\n );\n\n return fetcherWithComponents;\n}\n\n/**\n Returns an array of all in-flight fetchers. This is useful for components throughout the app that didn't create the fetchers but want to use their submissions to participate in optimistic UI.\n\n ```tsx\n import { useFetchers } from \"react-router\";\n\n function SomeComponent() {\n const fetchers = useFetchers();\n fetchers[0].formData; // FormData\n fetchers[0].state; // etc.\n // ...\n }\n ```\n\n @category Hooks\n */\nexport function useFetchers(): (Fetcher & { key: string })[] {\n let state = useDataRouterState(DataRouterStateHook.UseFetchers);\n return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({\n ...fetcher,\n key,\n }));\n}\n\nconst SCROLL_RESTORATION_STORAGE_KEY = \"react-router-scroll-positions\";\nlet savedScrollPositions: Record<string, number> = {};\n\nfunction getScrollRestorationKey(\n location: Location,\n matches: UIMatch[],\n basename: string,\n getKey?: GetScrollRestorationKeyFunction\n) {\n let key: string | null = null;\n if (getKey) {\n if (basename !== \"/\") {\n key = getKey(\n {\n ...location,\n pathname:\n stripBasename(location.pathname, basename) || location.pathname,\n },\n matches\n );\n } else {\n key = getKey(location, matches);\n }\n }\n if (key == null) {\n key = location.key;\n }\n return key;\n}\n\n/**\n * When rendered inside a RouterProvider, will restore scroll positions on navigations\n */\nexport function useScrollRestoration({\n getKey,\n storageKey,\n}: {\n getKey?: GetScrollRestorationKeyFunction;\n storageKey?: string;\n} = {}) {\n let { router } = useDataRouterContext(DataRouterHook.UseScrollRestoration);\n let { restoreScrollPosition, preventScrollReset } = useDataRouterState(\n DataRouterStateHook.UseScrollRestoration\n );\n let { basename } = React.useContext(NavigationContext);\n let location = useLocation();\n let matches = useMatches();\n let navigation = useNavigation();\n\n // Trigger manual scroll restoration while we're active\n React.useEffect(() => {\n window.history.scrollRestoration = \"manual\";\n return () => {\n window.history.scrollRestoration = \"auto\";\n };\n }, []);\n\n // Save positions on pagehide\n usePageHide(\n React.useCallback(() => {\n if (navigation.state === \"idle\") {\n let key = getScrollRestorationKey(location, matches, basename, getKey);\n savedScrollPositions[key] = window.scrollY;\n }\n try {\n sessionStorage.setItem(\n storageKey || SCROLL_RESTORATION_STORAGE_KEY,\n JSON.stringify(savedScrollPositions)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`\n );\n }\n window.history.scrollRestoration = \"auto\";\n }, [navigation.state, getKey, basename, location, matches, storageKey])\n );\n\n // Read in any saved scroll locations\n if (typeof document !== \"undefined\") {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(() => {\n try {\n let sessionPositions = sessionStorage.getItem(\n storageKey || SCROLL_RESTORATION_STORAGE_KEY\n );\n if (sessionPositions) {\n savedScrollPositions = JSON.parse(sessionPositions);\n }\n } catch (e) {\n // no-op, use default empty object\n }\n }, [storageKey]);\n\n // Enable scroll restoration in the router\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(() => {\n let disableScrollRestoration = router?.enableScrollRestoration(\n savedScrollPositions,\n () => window.scrollY,\n getKey\n ? (location, matches) =>\n getScrollRestorationKey(location, matches, basename, getKey)\n : undefined\n );\n return () => disableScrollRestoration && disableScrollRestoration();\n }, [router, basename, getKey]);\n\n // Restore scrolling when state.restoreScrollPosition changes\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(() => {\n // Explicit false means don't do anything (used for submissions)\n if (restoreScrollPosition === false) {\n return;\n }\n\n // been here before, scroll to it\n if (typeof restoreScrollPosition === \"number\") {\n window.scrollTo(0, restoreScrollPosition);\n return;\n }\n\n // try to scroll to the hash\n if (location.hash) {\n let el = document.getElementById(\n decodeURIComponent(location.hash.slice(1))\n );\n if (el) {\n el.scrollIntoView();\n return;\n }\n }\n\n // Don't reset if this navigation opted out\n if (preventScrollReset === true) {\n return;\n }\n\n // otherwise go to the top on new locations\n window.scrollTo(0, 0);\n }, [location, restoreScrollPosition, preventScrollReset]);\n }\n}\n\n/**\n * Setup a callback to be fired on the window's `beforeunload` event.\n *\n * @category Hooks\n */\nexport function useBeforeUnload(\n callback: (event: BeforeUnloadEvent) => any,\n options?: { capture?: boolean }\n): void {\n let { capture } = options || {};\n React.useEffect(() => {\n let opts = capture != null ? { capture } : undefined;\n window.addEventListener(\"beforeunload\", callback, opts);\n return () => {\n window.removeEventListener(\"beforeunload\", callback, opts);\n };\n }, [callback, capture]);\n}\n\n/**\n * Setup a callback to be fired on the window's `pagehide` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes. This event is better supported than beforeunload across browsers.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nfunction usePageHide(\n callback: (event: PageTransitionEvent) => any,\n options?: { capture?: boolean }\n): void {\n let { capture } = options || {};\n React.useEffect(() => {\n let opts = capture != null ? { capture } : undefined;\n window.addEventListener(\"pagehide\", callback, opts);\n return () => {\n window.removeEventListener(\"pagehide\", callback, opts);\n };\n }, [callback, capture]);\n}\n\n/**\n Wrapper around useBlocker to show a window.confirm prompt to users instead of building a custom UI with {@link useBlocker}.\n\n The `unstable_` flag will not be removed because this technique has a lot of rough edges and behaves very differently (and incorrectly sometimes) across browsers if users click addition back/forward navigations while the confirmation is open. Use at your own risk.\n\n ```tsx\n function ImportantForm() {\n let [value, setValue] = React.useState(\"\");\n\n // Block navigating elsewhere when data has been entered into the input\n unstable_usePrompt({\n message: \"Are you sure?\",\n when: ({ currentLocation, nextLocation }) =>\n value !== \"\" &&\n currentLocation.pathname !== nextLocation.pathname,\n });\n\n return (\n <Form method=\"post\">\n <label>\n Enter some important data:\n <input\n name=\"data\"\n value={value}\n onChange={(e) => setValue(e.target.value)}\n />\n </label>\n <button type=\"submit\">Save</button>\n </Form>\n );\n }\n ```\n\n @category Hooks\n @name unstable_usePrompt\n */\nexport function usePrompt({\n when,\n message,\n}: {\n when: boolean | BlockerFunction;\n message: string;\n}) {\n let blocker = useBlocker(when);\n\n React.useEffect(() => {\n if (blocker.state === \"blocked\") {\n let proceed = window.confirm(message);\n if (proceed) {\n // This timeout is needed to avoid a weird \"race\" on POP navigations\n // between the `window.history` revert navigation and the result of\n // `window.confirm`\n setTimeout(blocker.proceed, 0);\n } else {\n blocker.reset();\n }\n }\n }, [blocker, message]);\n\n React.useEffect(() => {\n if (blocker.state === \"blocked\" && !when) {\n blocker.reset();\n }\n }, [blocker, when]);\n}\n\n/**\n This hook returns `true` when there is an active [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) to the specified location. This can be used to apply finer-grained styles to elements to further customize the view transition. This requires that view transitions have been enabled for the given navigation via {@link LinkProps.viewTransition} (or the `Form`, `submit`, or `navigate` call)\n\n @category Hooks\n @name useViewTransitionState\n */\nexport function useViewTransitionState(\n to: To,\n opts: { relative?: RelativeRoutingType } = {}\n) {\n let vtContext = React.useContext(ViewTransitionContext);\n\n invariant(\n vtContext != null,\n \"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. \" +\n \"Did you accidentally import `RouterProvider` from `react-router`?\"\n );\n\n let { basename } = useDataRouterContext(\n DataRouterHook.useViewTransitionState\n );\n let path = useResolvedPath(to, { relative: opts.relative });\n if (!vtContext.isTransitioning) {\n return false;\n }\n\n let currentPath =\n stripBasename(vtContext.currentLocation.pathname, basename) ||\n vtContext.currentLocation.pathname;\n let nextPath =\n stripBasename(vtContext.nextLocation.pathname, basename) ||\n vtContext.nextLocation.pathname;\n\n // Transition is active if we're going to or coming from the indicated\n // destination. This ensures that other PUSH navigations that reverse\n // an indicated transition apply. I.e., on the list view you have:\n //\n // <NavLink to=\"/details/1\" viewTransition>\n //\n // If you click the breadcrumb back to the list view:\n //\n // <NavLink to=\"/list\" viewTransition>\n //\n // We should apply the transition because it's indicated as active going\n // from /list -> /details/1 and therefore should be active on the reverse\n // (even though this isn't strictly a POP reverse)\n return (\n matchPath(path.pathname, nextPath) != null ||\n matchPath(path.pathname, currentPath) != null\n );\n}\n\n//#endregion\n","import * as React from \"react\";\n\nimport type { Location, Path, To } from \"../router/history\";\nimport {\n Action as NavigationType,\n createPath,\n invariant,\n parsePath,\n} from \"../router/history\";\nimport type {\n FutureConfig,\n Router as DataRouter,\n RevalidationState,\n CreateStaticHandlerOptions as RouterCreateStaticHandlerOptions,\n RouterState,\n StaticHandlerContext,\n} from \"../router/router\";\nimport {\n IDLE_BLOCKER,\n IDLE_FETCHER,\n IDLE_NAVIGATION,\n createStaticHandler as routerCreateStaticHandler,\n} from \"../router/router\";\nimport type { RouteManifest } from \"../router/utils\";\nimport {\n convertRoutesToDataRoutes,\n isRouteErrorResponse,\n} from \"../router/utils\";\nimport { Router, mapRouteProperties } from \"../components\";\nimport type { DataRouteObject, RouteObject } from \"../context\";\nimport {\n DataRouterContext,\n DataRouterStateContext,\n FetchersContext,\n ViewTransitionContext,\n} from \"../context\";\nimport { useRoutesImpl } from \"../hooks\";\n\nexport interface StaticRouterProps {\n basename?: string;\n children?: React.ReactNode;\n location: Partial<Location> | string;\n}\n\n/**\n * A `<Router>` that may not navigate to any other location. This is useful\n * on the server where there is no stateful UI.\n *\n * @category Router Components\n */\nexport function StaticRouter({\n basename,\n children,\n location: locationProp = \"/\",\n}: StaticRouterProps) {\n if (typeof locationProp === \"string\") {\n locationProp = parsePath(locationProp);\n }\n\n let action = NavigationType.Pop;\n let location: Location = {\n pathname: locationProp.pathname || \"/\",\n search: locationProp.search || \"\",\n hash: locationProp.hash || \"\",\n state: locationProp.state != null ? locationProp.state : null,\n key: locationProp.key || \"default\",\n };\n\n let staticNavigator = getStatelessNavigator();\n return (\n <Router\n basename={basename}\n children={children}\n location={location}\n navigationType={action}\n navigator={staticNavigator}\n static={true}\n />\n );\n}\n\nexport interface StaticRouterProviderProps {\n context: StaticHandlerContext;\n router: DataRouter;\n hydrate?: boolean;\n nonce?: string;\n}\n\n/**\n * A Data Router that may not navigate to any other location. This is useful\n * on the server where there is no stateful UI.\n *\n * @category Router Components\n */\nexport function StaticRouterProvider({\n context,\n router,\n hydrate = true,\n nonce,\n}: StaticRouterProviderProps) {\n invariant(\n router && context,\n \"You must provide `router` and `context` to <StaticRouterProvider>\"\n );\n\n let dataRouterContext = {\n router,\n navigator: getStatelessNavigator(),\n static: true,\n staticContext: context,\n basename: context.basename || \"/\",\n };\n\n let fetchersContext = new Map();\n\n let hydrateScript = \"\";\n\n if (hydrate !== false) {\n let data = {\n loaderData: context.loaderData,\n actionData: context.actionData,\n errors: serializeErrors(context.errors),\n };\n // Use JSON.parse here instead of embedding a raw JS object here to speed\n // up parsing on the client. Dual-stringify is needed to ensure all quotes\n // are properly escaped in the resulting string. See:\n // https://v8.dev/blog/cost-of-javascript-2019#json\n let json = htmlEscape(JSON.stringify(JSON.stringify(data)));\n hydrateScript = `window.__staticRouterHydrationData = JSON.parse(${json});`;\n }\n\n let { state } = dataRouterContext.router;\n\n return (\n <>\n <DataRouterContext.Provider value={dataRouterContext}>\n <DataRouterStateContext.Provider value={state}>\n <FetchersContext.Provider value={fetchersContext}>\n <ViewTransitionContext.Provider value={{ isTransitioning: false }}>\n <Router\n basename={dataRouterContext.basename}\n location={state.location}\n navigationType={state.historyAction}\n navigator={dataRouterContext.navigator}\n static={dataRouterContext.static}\n >\n <DataRoutes\n routes={router.routes}\n future={router.future}\n state={state}\n />\n </Router>\n </ViewTransitionContext.Provider>\n </FetchersContext.Provider>\n </DataRouterStateContext.Provider>\n </DataRouterContext.Provider>\n {hydrateScript ? (\n <script\n suppressHydrationWarning\n nonce={nonce}\n dangerouslySetInnerHTML={{ __html: hydrateScript }}\n />\n ) : null}\n </>\n );\n}\n\nfunction DataRoutes({\n routes,\n future,\n state,\n}: {\n routes: DataRouteObject[];\n future: DataRouter[\"future\"];\n state: RouterState;\n}): React.ReactElement | null {\n return useRoutesImpl(routes, undefined, state, future);\n}\n\nfunction serializeErrors(\n errors: StaticHandlerContext[\"errors\"]\n): StaticHandlerContext[\"errors\"] {\n if (!errors) return null;\n let entries = Object.entries(errors);\n let serialized: StaticHandlerContext[\"errors\"] = {};\n for (let [key, val] of entries) {\n // Hey you! If you change this, please change the corresponding logic in\n // deserializeErrors in react-router-dom/index.tsx :)\n if (isRouteErrorResponse(val)) {\n serialized[key] = { ...val, __type: \"RouteErrorResponse\" };\n } else if (val instanceof Error) {\n // Do not serialize stack traces from SSR for security reasons\n serialized[key] = {\n message: val.message,\n __type: \"Error\",\n // If this is a subclass (i.e., ReferenceError), send up the type so we\n // can re-create the same type during hydration.\n ...(val.name !== \"Error\"\n ? {\n __subType: val.name,\n }\n : {}),\n };\n } else {\n serialized[key] = val;\n }\n }\n return serialized;\n}\n\nfunction getStatelessNavigator() {\n return {\n createHref,\n encodeLocation,\n push(to: To) {\n throw new Error(\n `You cannot use navigator.push() on the server because it is a stateless ` +\n `environment. This error was probably triggered when you did a ` +\n `\\`navigate(${JSON.stringify(to)})\\` somewhere in your app.`\n );\n },\n replace(to: To) {\n throw new Error(\n `You cannot use navigator.replace() on the server because it is a stateless ` +\n `environment. This error was probably triggered when you did a ` +\n `\\`navigate(${JSON.stringify(to)}, { replace: true })\\` somewhere ` +\n `in your app.`\n );\n },\n go(delta: number) {\n throw new Error(\n `You cannot use navigator.go() on the server because it is a stateless ` +\n `environment. This error was probably triggered when you did a ` +\n `\\`navigate(${delta})\\` somewhere in your app.`\n );\n },\n back() {\n throw new Error(\n `You cannot use navigator.back() on the server because it is a stateless ` +\n `environment.`\n );\n },\n forward() {\n throw new Error(\n `You cannot use navigator.forward() on the server because it is a stateless ` +\n `environment.`\n );\n },\n };\n}\n\ntype CreateStaticHandlerOptions = Omit<\n RouterCreateStaticHandlerOptions,\n \"mapRouteProperties\"\n>;\n\n/**\n * @category Utils\n */\nexport function createStaticHandler(\n routes: RouteObject[],\n opts?: CreateStaticHandlerOptions\n) {\n return routerCreateStaticHandler(routes, {\n ...opts,\n mapRouteProperties,\n });\n}\n\n/**\n * @category Routers\n */\nexport function createStaticRouter(\n routes: RouteObject[],\n context: StaticHandlerContext,\n opts: {\n future?: Partial<FutureConfig>;\n } = {}\n): DataRouter {\n let manifest: RouteManifest = {};\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n // Because our context matches may be from a framework-agnostic set of\n // routes passed to createStaticHandler(), we update them here with our\n // newly created/enhanced data routes\n let matches = context.matches.map((match) => {\n let route = manifest[match.route.id] || match.route;\n return {\n ...match,\n route,\n };\n });\n\n let msg = (method: string) =>\n `You cannot use router.${method}() on the server because it is a stateless environment`;\n\n return {\n get basename() {\n return context.basename;\n },\n get future() {\n return {\n ...opts?.future,\n };\n },\n get state() {\n return {\n historyAction: NavigationType.Pop,\n location: context.location,\n matches,\n loaderData: context.loaderData,\n actionData: context.actionData,\n errors: context.errors,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n restoreScrollPosition: null,\n preventScrollReset: false,\n revalidation: \"idle\" as RevalidationState,\n fetchers: new Map(),\n blockers: new Map(),\n };\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return undefined;\n },\n initialize() {\n throw msg(\"initialize\");\n },\n subscribe() {\n throw msg(\"subscribe\");\n },\n enableScrollRestoration() {\n throw msg(\"enableScrollRestoration\");\n },\n navigate() {\n throw msg(\"navigate\");\n },\n fetch() {\n throw msg(\"fetch\");\n },\n revalidate() {\n throw msg(\"revalidate\");\n },\n createHref,\n encodeLocation,\n getFetcher() {\n return IDLE_FETCHER;\n },\n deleteFetcher() {\n throw msg(\"deleteFetcher\");\n },\n dispose() {\n throw msg(\"dispose\");\n },\n getBlocker() {\n return IDLE_BLOCKER;\n },\n deleteBlocker() {\n throw msg(\"deleteBlocker\");\n },\n patchRoutes() {\n throw msg(\"patchRoutes\");\n },\n _internalFetchControllers: new Map(),\n _internalSetRoutes() {\n throw msg(\"_internalSetRoutes\");\n },\n };\n}\n\nfunction createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n}\n\nfunction encodeLocation(to: To): Path {\n let href = typeof to === \"string\" ? to : createPath(to);\n // Treating this as a full URL will strip any trailing spaces so we need to\n // pre-encode them since they might be part of a matching splat param from\n // an ancestor route\n href = href.replace(/ $/, \"%20\");\n let encoded = ABSOLUTE_URL_REGEX.test(href)\n ? new URL(href)\n : new URL(href, \"http://localhost\");\n return {\n pathname: encoded.pathname,\n search: encoded.search,\n hash: encoded.hash,\n };\n}\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\n// This utility is based on https://github.com/zertosh/htmlescape\n// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE\nconst ESCAPE_LOOKUP: { [match: string]: string } = {\n \"&\": \"\\\\u0026\",\n \">\": \"\\\\u003e\",\n \"<\": \"\\\\u003c\",\n \"\\u2028\": \"\\\\u2028\",\n \"\\u2029\": \"\\\\u2029\",\n};\n\nconst ESCAPE_REGEX = /[&><\\u2028\\u2029]/g;\n\nfunction htmlEscape(str: string): string {\n return str.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);\n}\n","import * as React from \"react\";\nimport type {\n ActionFunction,\n ActionFunctionArgs,\n LoaderFunction,\n LoaderFunctionArgs,\n} from \"../../router/utils\";\nimport type {\n DataRouteObject,\n IndexRouteObject,\n NonIndexRouteObject,\n} from \"../../context\";\nimport type { LinksFunction, MetaFunction, RouteModules } from \"./routeModules\";\nimport type { InitialEntry } from \"../../router/history\";\nimport type { HydrationState } from \"../../router/router\";\nimport { convertRoutesToDataRoutes } from \"../../router/utils\";\nimport type {\n AssetsManifest,\n FutureConfig,\n FrameworkContextObject,\n} from \"./entry\";\nimport { Outlet, RouterProvider, createMemoryRouter } from \"../../components\";\nimport type { EntryRoute } from \"./routes\";\nimport { FrameworkContext } from \"./components\";\n\ninterface StubIndexRouteObject\n extends Omit<\n IndexRouteObject,\n \"loader\" | \"action\" | \"element\" | \"errorElement\" | \"children\"\n > {\n loader?: LoaderFunction;\n action?: ActionFunction;\n children?: StubRouteObject[];\n meta?: MetaFunction;\n links?: LinksFunction;\n}\n\ninterface StubNonIndexRouteObject\n extends Omit<\n NonIndexRouteObject,\n \"loader\" | \"action\" | \"element\" | \"errorElement\" | \"children\"\n > {\n loader?: LoaderFunction;\n action?: ActionFunction;\n children?: StubRouteObject[];\n meta?: MetaFunction;\n links?: LinksFunction;\n}\n\ntype StubRouteObject = StubIndexRouteObject | StubNonIndexRouteObject;\n\ninterface AppLoadContext {\n [key: string]: unknown;\n}\n\nexport interface RoutesTestStubProps {\n /**\n * The initial entries in the history stack. This allows you to start a test with\n * multiple locations already in the history stack (for testing a back navigation, etc.)\n * The test will default to the last entry in initialEntries if no initialIndex is provided.\n * e.g. initialEntries={[\"/home\", \"/about\", \"/contact\"]}\n */\n initialEntries?: InitialEntry[];\n\n /**\n * The initial index in the history stack to render. This allows you to start a test at a specific entry.\n * It defaults to the last entry in initialEntries.\n * e.g.\n * initialEntries: [\"/\", \"/events/123\"]\n * initialIndex: 1 // start at \"/events/123\"\n */\n initialIndex?: number;\n\n /**\n * Used to set the route's initial loader and action data.\n * e.g. hydrationData={{\n * loaderData: { \"/contact\": { locale: \"en-US\" } },\n * actionData: { \"/login\": { errors: { email: \"invalid email\" } }}\n * }}\n */\n hydrationData?: HydrationState;\n\n /**\n * Future flags mimicking the settings in remix.config.js\n */\n future?: Partial<FutureConfig>;\n}\n\n/**\n * @category Utils\n */\nexport function createRoutesStub(\n routes: StubRouteObject[],\n context: AppLoadContext = {}\n) {\n return function RoutesTestStub({\n initialEntries,\n initialIndex,\n hydrationData,\n future,\n }: RoutesTestStubProps) {\n let routerRef = React.useRef<ReturnType<typeof createMemoryRouter>>();\n let remixContextRef = React.useRef<FrameworkContextObject>();\n\n if (routerRef.current == null) {\n remixContextRef.current = {\n future: {},\n manifest: {\n routes: {},\n entry: { imports: [], module: \"\" },\n url: \"\",\n version: \"\",\n },\n routeModules: {},\n isSpaMode: false,\n };\n\n // Update the routes to include context in the loader/action and populate\n // the manifest and routeModules during the walk\n let patched = processRoutes(\n // @ts-expect-error loader/action context types don't match :/\n convertRoutesToDataRoutes(routes, (r) => r),\n context,\n remixContextRef.current.manifest,\n remixContextRef.current.routeModules\n );\n routerRef.current = createMemoryRouter(patched, {\n initialEntries,\n initialIndex,\n hydrationData,\n });\n }\n\n return (\n <FrameworkContext.Provider value={remixContextRef.current}>\n <RouterProvider router={routerRef.current} />\n </FrameworkContext.Provider>\n );\n };\n}\n\nfunction processRoutes(\n routes: StubRouteObject[],\n context: AppLoadContext,\n manifest: AssetsManifest,\n routeModules: RouteModules,\n parentId?: string\n): DataRouteObject[] {\n return routes.map((route) => {\n if (!route.id) {\n throw new Error(\n \"Expected a route.id in @remix-run/testing processRoutes() function\"\n );\n }\n\n // Patch in the Remix context to loaders/actions\n let { loader, action } = route;\n let newRoute: DataRouteObject = {\n id: route.id,\n path: route.path,\n index: route.index,\n Component: route.Component,\n HydrateFallback: route.HydrateFallback,\n ErrorBoundary: route.ErrorBoundary,\n action: action\n ? (args: ActionFunctionArgs) => action!({ ...args, context })\n : undefined,\n loader: loader\n ? (args: LoaderFunctionArgs) => loader!({ ...args, context })\n : undefined,\n handle: route.handle,\n shouldRevalidate: route.shouldRevalidate,\n };\n\n // Add the EntryRoute to the manifest\n let entryRoute: EntryRoute = {\n id: route.id,\n path: route.path,\n index: route.index,\n parentId,\n hasAction: route.action != null,\n hasLoader: route.loader != null,\n // When testing routes, you should just be stubbing loader/action, not\n // trying to re-implement the full loader/clientLoader/SSR/hydration flow.\n // That is better tested via E2E tests.\n hasClientAction: false,\n hasClientLoader: false,\n hasErrorBoundary: route.ErrorBoundary != null,\n module: \"build/stub-path-to-module.js\", // any need for this?\n };\n manifest.routes[newRoute.id] = entryRoute;\n\n // Add the route to routeModules\n routeModules[route.id] = {\n default: route.Component || Outlet,\n ErrorBoundary: route.ErrorBoundary || undefined,\n handle: route.handle,\n links: route.links,\n meta: route.meta,\n shouldRevalidate: route.shouldRevalidate,\n };\n\n if (route.children) {\n newRoute.children = processRoutes(\n route.children,\n context,\n manifest,\n routeModules,\n newRoute.id\n );\n }\n\n return newRoute;\n });\n}\n","const encoder = new TextEncoder();\n\nexport const sign = async (value: string, secret: string): Promise<string> => {\n let data = encoder.encode(value);\n let key = await createKey(secret, [\"sign\"]);\n let signature = await crypto.subtle.sign(\"HMAC\", key, data);\n let hash = btoa(String.fromCharCode(...new Uint8Array(signature))).replace(\n /=+$/,\n \"\"\n );\n\n return value + \".\" + hash;\n};\n\nexport const unsign = async (\n cookie: string,\n secret: string\n): Promise<string | false> => {\n let index = cookie.lastIndexOf(\".\");\n let value = cookie.slice(0, index);\n let hash = cookie.slice(index + 1);\n\n let data = encoder.encode(value);\n\n let key = await createKey(secret, [\"verify\"]);\n let signature = byteStringToUint8Array(atob(hash));\n let valid = await crypto.subtle.verify(\"HMAC\", key, signature, data);\n\n return valid ? value : false;\n};\n\nconst createKey = async (\n secret: string,\n usages: CryptoKey[\"usages\"]\n): Promise<CryptoKey> =>\n crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n usages\n );\n\nfunction byteStringToUint8Array(byteString: string): Uint8Array {\n let array = new Uint8Array(byteString.length);\n\n for (let i = 0; i < byteString.length; i++) {\n array[i] = byteString.charCodeAt(i);\n }\n\n return array;\n}\n","import type { CookieParseOptions, CookieSerializeOptions } from \"cookie\";\nimport { parse, serialize } from \"cookie\";\n\nimport { sign, unsign } from \"./crypto\";\nimport { warnOnce } from \"./warnings\";\n\nexport type { CookieParseOptions, CookieSerializeOptions };\n\nexport interface CookieSignatureOptions {\n /**\n * An array of secrets that may be used to sign/unsign the value of a cookie.\n *\n * The array makes it easy to rotate secrets. New secrets should be added to\n * the beginning of the array. `cookie.serialize()` will always use the first\n * value in the array, but `cookie.parse()` may use any of them so that\n * cookies that were signed with older secrets still work.\n */\n secrets?: string[];\n}\n\nexport type CookieOptions = CookieParseOptions &\n CookieSerializeOptions &\n CookieSignatureOptions;\n\n/**\n * A HTTP cookie.\n *\n * A Cookie is a logical container for metadata about a HTTP cookie; its name\n * and options. But it doesn't contain a value. Instead, it has `parse()` and\n * `serialize()` methods that allow a single instance to be reused for\n * parsing/encoding multiple different values.\n *\n * @see https://remix.run/utils/cookies#cookie-api\n */\nexport interface Cookie {\n /**\n * The name of the cookie, used in the `Cookie` and `Set-Cookie` headers.\n */\n readonly name: string;\n\n /**\n * True if this cookie uses one or more secrets for verification.\n */\n readonly isSigned: boolean;\n\n /**\n * The Date this cookie expires.\n *\n * Note: This is calculated at access time using `maxAge` when no `expires`\n * option is provided to `createCookie()`.\n */\n readonly expires?: Date;\n\n /**\n * Parses a raw `Cookie` header and returns the value of this cookie or\n * `null` if it's not present.\n */\n parse(\n cookieHeader: string | null,\n options?: CookieParseOptions\n ): Promise<any>;\n\n /**\n * Serializes the given value to a string and returns the `Set-Cookie`\n * header.\n */\n serialize(value: any, options?: CookieSerializeOptions): Promise<string>;\n}\n\n/**\n * Creates a logical container for managing a browser cookie from the server.\n */\nexport const createCookie = (\n name: string,\n cookieOptions: CookieOptions = {}\n): Cookie => {\n let { secrets = [], ...options } = {\n path: \"/\",\n sameSite: \"lax\" as const,\n ...cookieOptions,\n };\n\n warnOnceAboutExpiresCookie(name, options.expires);\n\n return {\n get name() {\n return name;\n },\n get isSigned() {\n return secrets.length > 0;\n },\n get expires() {\n // Max-Age takes precedence over Expires\n return typeof options.maxAge !== \"undefined\"\n ? new Date(Date.now() + options.maxAge * 1000)\n : options.expires;\n },\n async parse(cookieHeader, parseOptions) {\n if (!cookieHeader) return null;\n let cookies = parse(cookieHeader, { ...options, ...parseOptions });\n return name in cookies\n ? cookies[name] === \"\"\n ? \"\"\n : await decodeCookieValue(cookies[name], secrets)\n : null;\n },\n async serialize(value, serializeOptions) {\n return serialize(\n name,\n value === \"\" ? \"\" : await encodeCookieValue(value, secrets),\n {\n ...options,\n ...serializeOptions,\n }\n );\n },\n };\n};\n\nexport type IsCookieFunction = (object: any) => object is Cookie;\n\n/**\n * Returns true if an object is a Remix cookie container.\n *\n * @see https://remix.run/utils/cookies#iscookie\n */\nexport const isCookie: IsCookieFunction = (object): object is Cookie => {\n return (\n object != null &&\n typeof object.name === \"string\" &&\n typeof object.isSigned === \"boolean\" &&\n typeof object.parse === \"function\" &&\n typeof object.serialize === \"function\"\n );\n};\n\nasync function encodeCookieValue(\n value: any,\n secrets: string[]\n): Promise<string> {\n let encoded = encodeData(value);\n\n if (secrets.length > 0) {\n encoded = await sign(encoded, secrets[0]);\n }\n\n return encoded;\n}\n\nasync function decodeCookieValue(\n value: string,\n secrets: string[]\n): Promise<any> {\n if (secrets.length > 0) {\n for (let secret of secrets) {\n let unsignedValue = await unsign(value, secret);\n if (unsignedValue !== false) {\n return decodeData(unsignedValue);\n }\n }\n\n return null;\n }\n\n return decodeData(value);\n}\n\nfunction encodeData(value: any): string {\n return btoa(myUnescape(encodeURIComponent(JSON.stringify(value))));\n}\n\nfunction decodeData(value: string): any {\n try {\n return JSON.parse(decodeURIComponent(myEscape(atob(value))));\n } catch (error: unknown) {\n return {};\n }\n}\n\n// See: https://github.com/zloirock/core-js/blob/master/packages/core-js/modules/es.escape.js\nfunction myEscape(value: string): string {\n let str = value.toString();\n let result = \"\";\n let index = 0;\n let chr, code;\n while (index < str.length) {\n chr = str.charAt(index++);\n if (/[\\w*+\\-./@]/.exec(chr)) {\n result += chr;\n } else {\n code = chr.charCodeAt(0);\n if (code < 256) {\n result += \"%\" + hex(code, 2);\n } else {\n result += \"%u\" + hex(code, 4).toUpperCase();\n }\n }\n }\n return result;\n}\n\nfunction hex(code: number, length: number): string {\n let result = code.toString(16);\n while (result.length < length) result = \"0\" + result;\n return result;\n}\n\n// See: https://github.com/zloirock/core-js/blob/master/packages/core-js/modules/es.unescape.js\nfunction myUnescape(value: string): string {\n let str = value.toString();\n let result = \"\";\n let index = 0;\n let chr, part;\n while (index < str.length) {\n chr = str.charAt(index++);\n if (chr === \"%\") {\n if (str.charAt(index) === \"u\") {\n part = str.slice(index + 1, index + 5);\n if (/^[\\da-f]{4}$/i.exec(part)) {\n result += String.fromCharCode(parseInt(part, 16));\n index += 5;\n continue;\n }\n } else {\n part = str.slice(index, index + 2);\n if (/^[\\da-f]{2}$/i.exec(part)) {\n result += String.fromCharCode(parseInt(part, 16));\n index += 2;\n continue;\n }\n }\n }\n result += chr;\n }\n return result;\n}\n\nfunction warnOnceAboutExpiresCookie(name: string, expires?: Date) {\n warnOnce(\n !expires,\n `The \"${name}\" cookie has an \"expires\" property set. ` +\n `This will cause the expires value to not be updated when the session is committed. ` +\n `Instead, you should set the expires value when serializing the cookie. ` +\n `You can use \\`commitSession(session, { expires })\\` if using a session storage object, ` +\n `or \\`cookie.serialize(\"value\", { expires })\\` if you're using the cookie directly.`\n );\n}\n","import type { ServerRouteManifest } from \"./routes\";\nimport type { RouteModules, EntryRouteModule } from \"./routeModules\";\n\nexport function createEntryRouteModules(\n manifest: ServerRouteManifest\n): RouteModules<EntryRouteModule> {\n return Object.keys(manifest).reduce((memo, routeId) => {\n memo[routeId] = manifest[routeId].module;\n return memo;\n }, {} as RouteModules<EntryRouteModule>);\n}\n","/**\n * The mode to use when running the server.\n */\nexport enum ServerMode {\n Development = \"development\",\n Production = \"production\",\n Test = \"test\",\n}\n\nexport function isServerMode(value: any): value is ServerMode {\n return (\n value === ServerMode.Development ||\n value === ServerMode.Production ||\n value === ServerMode.Test\n );\n}\n","import type { StaticHandlerContext } from \"../router/router\";\nimport { isRouteErrorResponse } from \"../router/utils\";\n\nimport { ServerMode } from \"./mode\";\n\n/**\n * This thing probably warrants some explanation.\n *\n * The whole point here is to emulate componentDidCatch for server rendering and\n * data loading. It can get tricky. React can do this on component boundaries\n * but doesn't support it for server rendering or data loading. We know enough\n * with nested routes to be able to emulate the behavior (because we know them\n * statically before rendering.)\n *\n * Each route can export an `ErrorBoundary`.\n *\n * - When rendering throws an error, the nearest error boundary will render\n * (normal react componentDidCatch). This will be the route's own boundary, but\n * if none is provided, it will bubble up to the parents.\n * - When data loading throws an error, the nearest error boundary will render\n * - When performing an action, the nearest error boundary for the action's\n * route tree will render (no redirect happens)\n *\n * During normal react rendering, we do nothing special, just normal\n * componentDidCatch.\n *\n * For server rendering, we mutate `renderBoundaryRouteId` to know the last\n * layout that has an error boundary that tried to render. This emulates which\n * layout would catch a thrown error. If the rendering fails, we catch the error\n * on the server, and go again a second time with the emulator holding on to the\n * information it needs to render the same error boundary as a dynamically\n * thrown render error.\n *\n * When data loading, server or client side, we use the emulator to likewise\n * hang on to the error and re-render at the appropriate layout (where a thrown\n * error would have been caught by cDC).\n *\n * When actions throw, it all works the same. There's an edge case to be aware\n * of though. Actions normally are required to redirect, but in the case of\n * errors, we render the action's route with the emulator holding on to the\n * error. If during this render a parent route/loader throws we ignore that new\n * error and render the action's original error as deeply as possible. In other\n * words, we simply ignore the new error and use the action's error in place\n * because it came first, and that just wouldn't be fair to let errors cut in\n * line.\n */\n\nexport function sanitizeError<T = unknown>(error: T, serverMode: ServerMode) {\n if (error instanceof Error && serverMode !== ServerMode.Development) {\n let sanitized = new Error(\"Unexpected Server Error\");\n sanitized.stack = undefined;\n return sanitized;\n }\n return error;\n}\n\nexport function sanitizeErrors(\n errors: NonNullable<StaticHandlerContext[\"errors\"]>,\n serverMode: ServerMode\n) {\n return Object.entries(errors).reduce((acc, [routeId, error]) => {\n return Object.assign(acc, { [routeId]: sanitizeError(error, serverMode) });\n }, {});\n}\n\n// must be type alias due to inference issues on interfaces\n// https://github.com/microsoft/TypeScript/issues/15300\nexport type SerializedError = {\n message: string;\n stack?: string;\n};\n\nexport function serializeError(\n error: Error,\n serverMode: ServerMode\n): SerializedError {\n let sanitized = sanitizeError(error, serverMode);\n return {\n message: sanitized.message,\n stack: sanitized.stack,\n };\n}\n\nexport function serializeErrors(\n errors: StaticHandlerContext[\"errors\"],\n serverMode: ServerMode\n): StaticHandlerContext[\"errors\"] {\n if (!errors) return null;\n let entries = Object.entries(errors);\n let serialized: StaticHandlerContext[\"errors\"] = {};\n for (let [key, val] of entries) {\n // Hey you! If you change this, please change the corresponding logic in\n // deserializeErrors in remix-react/errors.ts :)\n if (isRouteErrorResponse(val)) {\n serialized[key] = { ...val, __type: \"RouteErrorResponse\" };\n } else if (val instanceof Error) {\n let sanitized = sanitizeError(val, serverMode);\n serialized[key] = {\n message: sanitized.message,\n stack: sanitized.stack,\n __type: \"Error\",\n // If this is a subclass (i.e., ReferenceError), send up the type so we\n // can re-create the same type during hydration. This will only apply\n // in dev mode since all production errors are sanitized to normal\n // Error instances\n ...(sanitized.name !== \"Error\"\n ? {\n __subType: sanitized.name,\n }\n : {}),\n };\n } else {\n serialized[key] = val;\n }\n }\n return serialized;\n}\n","import type { Params, AgnosticRouteObject } from \"../router/utils\";\nimport { matchRoutes } from \"../router/utils\";\nimport type { ServerRoute } from \"./routes\";\n\nexport interface RouteMatch<Route> {\n params: Params;\n pathname: string;\n route: Route;\n}\n\nexport function matchServerRoutes(\n routes: ServerRoute[],\n pathname: string,\n basename?: string\n): RouteMatch<ServerRoute>[] | null {\n let matches = matchRoutes(\n routes as unknown as AgnosticRouteObject[],\n pathname,\n basename\n );\n if (!matches) return null;\n\n return matches.map((match) => ({\n params: match.params,\n pathname: match.pathname,\n route: match.route as unknown as ServerRoute,\n }));\n}\n","import {\n json as routerJson,\n redirect as routerRedirect,\n redirectDocument as routerRedirectDocument,\n replace as routerReplace,\n} from \"../router/utils\";\n\nexport type JsonFunction = <Data>(\n data: Data,\n init?: number | ResponseInit\n) => TypedResponse<Data>;\n\n// must be a type since this is a subtype of response\n// interfaces must conform to the types they extend\nexport type TypedResponse<T = unknown> = Omit<Response, \"json\"> & {\n json(): Promise<T>;\n};\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n *\n * @see https://remix.run/utils/json\n */\nexport const json: JsonFunction = (data, init = {}) => {\n return routerJson(data, init);\n};\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => TypedResponse<never>;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n *\n * @see https://remix.run/utils/redirect\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n return routerRedirect(url, init) as TypedResponse<never>;\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n *\n * @see https://remix.run/utils/redirect\n */\nexport const redirectDocument: RedirectFunction = (url, init = 302) => {\n return routerRedirectDocument(url, init) as TypedResponse<never>;\n};\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n *\n * @see https://remix.run/utils/redirect\n */\nexport const replace: RedirectFunction = (url, init = 302) => {\n return routerReplace(url, init) as TypedResponse<never>;\n};\n\nexport function isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nexport function isRedirectStatusCode(statusCode: number): boolean {\n return redirectStatusCodes.has(statusCode);\n}\nexport function isRedirectResponse(response: Response): boolean {\n return isRedirectStatusCode(response.status);\n}\n","import { isDataWithResponseInit } from \"../router/router\";\nimport { isRedirectStatusCode } from \"./responses\";\nimport type {\n ActionFunction,\n ActionFunctionArgs,\n LoaderFunction,\n LoaderFunctionArgs,\n} from \"./routeModules\";\n\n/**\n * An object of unknown type for route loaders and actions provided by the\n * server's `getLoadContext()` function. This is defined as an empty interface\n * specifically so apps can leverage declaration merging to augment this type\n * globally: https://www.typescriptlang.org/docs/handbook/declaration-merging.html\n */\nexport interface AppLoadContext {\n [key: string]: unknown;\n}\n\n/**\n * Data for a route that was returned from a `loader()`.\n */\nexport type AppData = unknown;\n\n// Need to use RR's version here to permit the optional context even\n// though we know it'll always be provided in remix\nexport async function callRouteHandler(\n handler: LoaderFunction | ActionFunction,\n args: LoaderFunctionArgs | ActionFunctionArgs\n) {\n let result = await handler({\n request: stripRoutesParam(stripIndexParam(args.request)),\n params: args.params,\n context: args.context,\n });\n\n // If they returned a redirect via data(), re-throw it as a Response\n if (\n isDataWithResponseInit(result) &&\n result.init &&\n result.init.status &&\n isRedirectStatusCode(result.init.status)\n ) {\n throw new Response(null, result.init);\n }\n\n return result;\n}\n\n// TODO: Document these search params better\n// and stop stripping these in V2. These break\n// support for running in a SW and also expose\n// valuable info to data funcs that is being asked\n// for such as \"is this a data request?\".\nfunction stripIndexParam(request: Request) {\n let url = new URL(request.url);\n let indexValues = url.searchParams.getAll(\"index\");\n url.searchParams.delete(\"index\");\n let indexValuesToKeep = [];\n for (let indexValue of indexValues) {\n if (indexValue) {\n indexValuesToKeep.push(indexValue);\n }\n }\n for (let toKeep of indexValuesToKeep) {\n url.searchParams.append(\"index\", toKeep);\n }\n\n let init: RequestInit = {\n method: request.method,\n body: request.body,\n headers: request.headers,\n signal: request.signal,\n };\n\n if (init.body) {\n (init as { duplex: \"half\" }).duplex = \"half\";\n }\n\n return new Request(url.href, init);\n}\n\nfunction stripRoutesParam(request: Request) {\n let url = new URL(request.url);\n url.searchParams.delete(\"_routes\");\n let init: RequestInit = {\n method: request.method,\n body: request.body,\n headers: request.headers,\n signal: request.signal,\n };\n\n if (init.body) {\n (init as { duplex: \"half\" }).duplex = \"half\";\n }\n\n return new Request(url.href, init);\n}\n","export default function invariant(\n value: boolean,\n message?: string\n): asserts value;\nexport default function invariant<T>(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport default function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n console.error(\n \"The following error is a bug in Remix; please open an issue! https://github.com/remix-run/remix/issues/new\"\n );\n throw new Error(message);\n }\n}\n","import type {\n AgnosticDataRouteObject,\n LoaderFunctionArgs as RRLoaderFunctionArgs,\n ActionFunctionArgs as RRActionFunctionArgs,\n} from \"../router/utils\";\nimport { callRouteHandler } from \"./data\";\nimport type { FutureConfig } from \"../dom/ssr/entry\";\nimport type {\n ActionFunctionArgs,\n LoaderFunctionArgs,\n ServerRouteModule,\n} from \"./routeModules\";\nimport type {\n SingleFetchResult,\n SingleFetchResults,\n} from \"../dom/ssr/single-fetch\";\nimport { decodeViaTurboStream } from \"../dom/ssr/single-fetch\";\nimport invariant from \"./invariant\";\n\nexport interface RouteManifest<Route> {\n [routeId: string]: Route;\n}\n\nexport type ServerRouteManifest = RouteManifest<Omit<ServerRoute, \"children\">>;\n\n// NOTE: make sure to change the Route in remix-react/react-router-dev if you change this\nexport interface Route {\n index?: boolean;\n caseSensitive?: boolean;\n id: string;\n parentId?: string;\n path?: string;\n}\n\n// NOTE: make sure to change the EntryRoute in react-router/react-router-dev if you change this\nexport interface EntryRoute extends Route {\n hasAction: boolean;\n hasLoader: boolean;\n hasClientAction: boolean;\n hasClientLoader: boolean;\n hasErrorBoundary: boolean;\n imports?: string[];\n css?: string[];\n module: string;\n parentId?: string;\n}\n\nexport interface ServerRoute extends Route {\n children: ServerRoute[];\n module: ServerRouteModule;\n}\n\nfunction groupRoutesByParentId(manifest: ServerRouteManifest) {\n let routes: Record<string, Omit<ServerRoute, \"children\">[]> = {};\n\n Object.values(manifest).forEach((route) => {\n let parentId = route.parentId || \"\";\n if (!routes[parentId]) {\n routes[parentId] = [];\n }\n routes[parentId].push(route);\n });\n\n return routes;\n}\n\n// Create a map of routes by parentId to use recursively instead of\n// repeatedly filtering the manifest.\nexport function createRoutes(\n manifest: ServerRouteManifest,\n parentId: string = \"\",\n routesByParentId: Record<\n string,\n Omit<ServerRoute, \"children\">[]\n > = groupRoutesByParentId(manifest)\n): ServerRoute[] {\n return (routesByParentId[parentId] || []).map((route) => ({\n ...route,\n children: createRoutes(manifest, route.id, routesByParentId),\n }));\n}\n\n// Convert the Remix ServerManifest into DataRouteObject's for use with\n// createStaticHandler\nexport function createStaticHandlerDataRoutes(\n manifest: ServerRouteManifest,\n future: FutureConfig,\n parentId: string = \"\",\n routesByParentId: Record<\n string,\n Omit<ServerRoute, \"children\">[]\n > = groupRoutesByParentId(manifest)\n): AgnosticDataRouteObject[] {\n return (routesByParentId[parentId] || []).map((route) => {\n let commonRoute = {\n // Always include root due to default boundaries\n hasErrorBoundary:\n route.id === \"root\" || route.module.ErrorBoundary != null,\n id: route.id,\n path: route.path,\n // Need to use RR's version in the param typed here to permit the optional\n // context even though we know it'll always be provided in remix\n loader: route.module.loader\n ? async (args: RRLoaderFunctionArgs) => {\n // If we're prerendering, use the data passed in from prerendering\n // the .data route so we dom't call loaders twice\n if (args.request.headers.has(\"X-React-Router-Prerender-Data\")) {\n let encoded = args.request.headers.get(\n \"X-React-Router-Prerender-Data\"\n );\n invariant(encoded, \"Missing prerendered data for route\");\n let uint8array = new TextEncoder().encode(encoded);\n let stream = new ReadableStream({\n start(controller) {\n controller.enqueue(uint8array);\n controller.close();\n },\n });\n let decoded = await decodeViaTurboStream(stream, global);\n let data = decoded.value as SingleFetchResults;\n invariant(\n data && route.id in data,\n \"Unable to decode prerendered data\"\n );\n let result = data[route.id] as SingleFetchResult;\n invariant(\"data\" in result, \"Unable to process prerendered data\");\n return result.data;\n }\n let val = await callRouteHandler(\n route.module.loader!,\n args as LoaderFunctionArgs\n );\n return val;\n }\n : undefined,\n action: route.module.action\n ? (args: RRActionFunctionArgs) =>\n callRouteHandler(route.module.action!, args as ActionFunctionArgs)\n : undefined,\n handle: route.module.handle,\n };\n\n return route.index\n ? {\n index: true,\n ...commonRoute,\n }\n : {\n caseSensitive: route.caseSensitive,\n children: createStaticHandlerDataRoutes(\n manifest,\n future,\n route.id,\n routesByParentId\n ),\n ...commonRoute,\n };\n });\n}\n","// This escapeHtml utility is based on https://github.com/zertosh/htmlescape\n// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE\n\n// We've chosen to inline the utility here to reduce the number of npm dependencies we have,\n// slightly decrease the code size compared the original package and make it esm compatible.\n\nconst ESCAPE_LOOKUP: { [match: string]: string } = {\n \"&\": \"\\\\u0026\",\n \">\": \"\\\\u003e\",\n \"<\": \"\\\\u003c\",\n \"\\u2028\": \"\\\\u2028\",\n \"\\u2029\": \"\\\\u2029\",\n};\n\nconst ESCAPE_REGEX = /[&><\\u2028\\u2029]/g;\n\nexport function escapeHtml(html: string) {\n return html.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);\n}\n","import type { HydrationState } from \"../router/router\";\nimport type { FutureConfig } from \"../dom/ssr/entry\";\nimport { escapeHtml } from \"./markup\";\n\ntype ValidateShape<T, Shape> =\n // If it extends T\n T extends Shape\n ? // and there are no leftover props after removing the base\n Exclude<keyof T, keyof Shape> extends never\n ? // we are good\n T\n : // otherwise it's either too many or too few props\n never\n : never;\n\n// TODO: Remove Promises from serialization\nexport function createServerHandoffString<T>(serverHandoff: {\n // Don't allow StaticHandlerContext to be passed in verbatim, since then\n // we'd end up including duplicate info\n state?: ValidateShape<T, HydrationState>;\n criticalCss?: string;\n basename: string | undefined;\n future: FutureConfig;\n isSpaMode: boolean;\n}): string {\n // Uses faster alternative of jsesc to escape data returned from the loaders.\n // This string is inserted directly into the HTML in the `<Scripts>` element.\n return escapeHtml(JSON.stringify(serverHandoff));\n}\n","import type { ServerBuild } from \"./build\";\n\ntype DevServerHooks = {\n getCriticalCss?: (\n build: ServerBuild,\n pathname: string\n ) => Promise<string | undefined>;\n processRequestError?: (error: unknown) => void;\n};\n\nconst globalDevServerHooksKey = \"__reactRouterDevServerHooks\";\n\nexport function setDevServerHooks(devServerHooks: DevServerHooks) {\n // @ts-expect-error\n globalThis[globalDevServerHooksKey] = devServerHooks;\n}\n\nexport function getDevServerHooks(): DevServerHooks | undefined {\n // @ts-expect-error\n return globalThis[globalDevServerHooksKey];\n}\n","import { splitCookiesString } from \"set-cookie-parser\";\n\nimport type { ServerBuild } from \"./build\";\nimport type { StaticHandlerContext } from \"../router/router\";\n\nexport function getDocumentHeaders(\n build: ServerBuild,\n context: StaticHandlerContext\n): Headers {\n let boundaryIdx = context.errors\n ? context.matches.findIndex((m) => context.errors![m.route.id])\n : -1;\n let matches =\n boundaryIdx >= 0\n ? context.matches.slice(0, boundaryIdx + 1)\n : context.matches;\n\n let errorHeaders: Headers | undefined;\n\n if (boundaryIdx >= 0) {\n // Look for any errorHeaders from the boundary route down, which can be\n // identified by the presence of headers but no data\n let { actionHeaders, actionData, loaderHeaders, loaderData } = context;\n context.matches.slice(boundaryIdx).some((match) => {\n let id = match.route.id;\n if (\n actionHeaders[id] &&\n (!actionData || !actionData.hasOwnProperty(id))\n ) {\n errorHeaders = actionHeaders[id];\n } else if (loaderHeaders[id] && !loaderData.hasOwnProperty(id)) {\n errorHeaders = loaderHeaders[id];\n }\n return errorHeaders != null;\n });\n }\n\n return matches.reduce((parentHeaders, match, idx) => {\n let { id } = match.route;\n let routeModule = build.routes[id].module;\n let loaderHeaders = context.loaderHeaders[id] || new Headers();\n let actionHeaders = context.actionHeaders[id] || new Headers();\n\n // Only expose errorHeaders to the leaf headers() function to\n // avoid duplication via parentHeaders\n let includeErrorHeaders =\n errorHeaders != undefined && idx === matches.length - 1;\n // Only prepend cookies from errorHeaders at the leaf renderable route\n // when it's not the same as loaderHeaders/actionHeaders to avoid\n // duplicate cookies\n let includeErrorCookies =\n includeErrorHeaders &&\n errorHeaders !== loaderHeaders &&\n errorHeaders !== actionHeaders;\n\n // Use the parent headers for any route without a `headers` export\n if (routeModule.headers == null) {\n let headers = new Headers(parentHeaders);\n if (includeErrorCookies) {\n prependCookies(errorHeaders!, headers);\n }\n prependCookies(actionHeaders, headers);\n prependCookies(loaderHeaders, headers);\n return headers;\n }\n\n let headers = new Headers(\n routeModule.headers\n ? typeof routeModule.headers === \"function\"\n ? routeModule.headers({\n loaderHeaders,\n parentHeaders,\n actionHeaders,\n errorHeaders: includeErrorHeaders ? errorHeaders : undefined,\n })\n : routeModule.headers\n : undefined\n );\n\n // Automatically preserve Set-Cookie headers from bubbled responses,\n // loaders, errors, and parent routes\n if (includeErrorCookies) {\n prependCookies(errorHeaders!, headers);\n }\n prependCookies(actionHeaders, headers);\n prependCookies(loaderHeaders, headers);\n prependCookies(parentHeaders, headers);\n\n return headers;\n }, new Headers());\n}\n\nfunction prependCookies(parentHeaders: Headers, childHeaders: Headers): void {\n let parentSetCookieString = parentHeaders.get(\"Set-Cookie\");\n\n if (parentSetCookieString) {\n let cookies = splitCookiesString(parentSetCookieString);\n cookies.forEach((cookie) => {\n childHeaders.append(\"Set-Cookie\", cookie);\n });\n }\n}\n","import { encode } from \"turbo-stream\";\n\nimport type { StaticHandler } from \"../router/router\";\nimport type {\n DataStrategyFunctionArgs,\n DataStrategyFunction,\n} from \"../router/utils\";\nimport {\n isRouteErrorResponse,\n ErrorResponseImpl,\n data as routerData,\n stripBasename,\n} from \"../router/utils\";\nimport type {\n SingleFetchRedirectResult,\n SingleFetchResult,\n SingleFetchResults,\n} from \"../dom/ssr/single-fetch\";\nimport { SingleFetchRedirectSymbol } from \"../dom/ssr/single-fetch\";\nimport type { AppLoadContext } from \"./data\";\nimport { sanitizeError, sanitizeErrors } from \"./errors\";\nimport { ServerMode } from \"./mode\";\nimport { isRedirectStatusCode, isResponse } from \"./responses\";\nimport { getDocumentHeaders } from \"./headers\";\nimport type { ServerBuild } from \"./build\";\n\nexport type { SingleFetchResult, SingleFetchResults };\nexport { SingleFetchRedirectSymbol };\n\n// We can't use a 3xx status or else the `fetch()` would follow the redirect.\n// We need to communicate the redirect back as data so we can act on it in the\n// client side router. We use a 202 to avoid any automatic caching we might\n// get from a 200 since a \"temporary\" redirect should not be cached. This lets\n// the user control cache behavior via Cache-Control\nexport const SINGLE_FETCH_REDIRECT_STATUS = 202;\n\nexport function getSingleFetchDataStrategy({\n isActionDataRequest,\n loadRouteIds,\n}: {\n isActionDataRequest?: boolean;\n loadRouteIds?: string[];\n} = {}): DataStrategyFunction {\n return async ({ request, matches }: DataStrategyFunctionArgs) => {\n // Don't call loaders on action data requests\n if (isActionDataRequest && request.method === \"GET\") {\n return {};\n }\n\n // Only run opt-in loaders when fine-grained revalidation is enabled\n let matchesToLoad = loadRouteIds\n ? matches.filter((m) => loadRouteIds.includes(m.route.id))\n : matches;\n\n let results = await Promise.all(\n matchesToLoad.map((match) => match.resolve())\n );\n return results.reduce(\n (acc, result, i) =>\n Object.assign(acc, { [matchesToLoad[i].route.id]: result }),\n {}\n );\n };\n}\n\nexport async function singleFetchAction(\n build: ServerBuild,\n serverMode: ServerMode,\n staticHandler: StaticHandler,\n request: Request,\n handlerUrl: URL,\n loadContext: AppLoadContext,\n handleError: (err: unknown) => void\n): Promise<{ result: SingleFetchResult; headers: Headers; status: number }> {\n try {\n let handlerRequest = new Request(handlerUrl, {\n method: request.method,\n body: request.body,\n headers: request.headers,\n signal: request.signal,\n ...(request.body ? { duplex: \"half\" } : undefined),\n });\n\n let result = await staticHandler.query(handlerRequest, {\n requestContext: loadContext,\n skipLoaderErrorBubbling: true,\n dataStrategy: getSingleFetchDataStrategy({\n isActionDataRequest: true,\n }),\n });\n\n // Unlike `handleDataRequest`, when singleFetch is enabled, query does\n // let non-Response return values through\n if (isResponse(result)) {\n return {\n result: getSingleFetchRedirect(\n result.status,\n result.headers,\n build.basename\n ),\n headers: result.headers,\n status: SINGLE_FETCH_REDIRECT_STATUS,\n };\n }\n\n let context = result;\n let headers = getDocumentHeaders(build, context);\n\n if (isRedirectStatusCode(context.statusCode) && headers.has(\"Location\")) {\n return {\n result: getSingleFetchRedirect(\n context.statusCode,\n headers,\n build.basename\n ),\n headers,\n status: SINGLE_FETCH_REDIRECT_STATUS,\n };\n }\n\n // Sanitize errors outside of development environments\n if (context.errors) {\n Object.values(context.errors).forEach((err) => {\n // @ts-expect-error This is \"private\" from users but intended for internal use\n if (!isRouteErrorResponse(err) || err.error) {\n handleError(err);\n }\n });\n context.errors = sanitizeErrors(context.errors, serverMode);\n }\n\n let singleFetchResult: SingleFetchResult;\n if (context.errors) {\n singleFetchResult = { error: Object.values(context.errors)[0] };\n } else {\n singleFetchResult = { data: Object.values(context.actionData || {})[0] };\n }\n\n return {\n result: singleFetchResult,\n headers,\n status: context.statusCode,\n };\n } catch (error) {\n handleError(error);\n // These should only be internal remix errors, no need to deal with responseStubs\n return {\n result: { error },\n headers: new Headers(),\n status: 500,\n };\n }\n}\n\nexport async function singleFetchLoaders(\n build: ServerBuild,\n serverMode: ServerMode,\n staticHandler: StaticHandler,\n request: Request,\n handlerUrl: URL,\n loadContext: AppLoadContext,\n handleError: (err: unknown) => void\n): Promise<{ result: SingleFetchResults; headers: Headers; status: number }> {\n try {\n let handlerRequest = new Request(handlerUrl, {\n headers: request.headers,\n signal: request.signal,\n });\n let loadRouteIds =\n new URL(request.url).searchParams.get(\"_routes\")?.split(\",\") || undefined;\n\n let result = await staticHandler.query(handlerRequest, {\n requestContext: loadContext,\n skipLoaderErrorBubbling: true,\n dataStrategy: getSingleFetchDataStrategy({\n loadRouteIds,\n }),\n });\n\n if (isResponse(result)) {\n return {\n result: {\n [SingleFetchRedirectSymbol]: getSingleFetchRedirect(\n result.status,\n result.headers,\n build.basename\n ),\n },\n headers: result.headers,\n status: SINGLE_FETCH_REDIRECT_STATUS,\n };\n }\n\n let context = result;\n let headers = getDocumentHeaders(build, context);\n\n if (isRedirectStatusCode(context.statusCode) && headers.has(\"Location\")) {\n return {\n result: {\n [SingleFetchRedirectSymbol]: getSingleFetchRedirect(\n context.statusCode,\n headers,\n build.basename\n ),\n },\n headers,\n status: SINGLE_FETCH_REDIRECT_STATUS,\n };\n }\n\n // Sanitize errors outside of development environments\n if (context.errors) {\n Object.values(context.errors).forEach((err) => {\n // @ts-expect-error This is \"private\" from users but intended for internal use\n if (!isRouteErrorResponse(err) || err.error) {\n handleError(err);\n }\n });\n context.errors = sanitizeErrors(context.errors, serverMode);\n }\n\n // Aggregate results based on the matches we intended to load since we get\n // `null` values back in `context.loaderData` for routes we didn't load\n let results: SingleFetchResults = {};\n let loadedMatches = loadRouteIds\n ? context.matches.filter(\n (m) => m.route.loader && loadRouteIds!.includes(m.route.id)\n )\n : context.matches;\n\n loadedMatches.forEach((m) => {\n let { id } = m.route;\n if (context.errors && context.errors.hasOwnProperty(id)) {\n results[id] = { error: context.errors[id] };\n } else if (context.loaderData.hasOwnProperty(id)) {\n results[id] = { data: context.loaderData[id] };\n }\n });\n\n return {\n result: results,\n headers,\n status: context.statusCode,\n };\n } catch (error: unknown) {\n handleError(error);\n // These should only be internal remix errors, no need to deal with responseStubs\n return {\n result: { root: { error } },\n headers: new Headers(),\n status: 500,\n };\n }\n}\n\nexport function getSingleFetchRedirect(\n status: number,\n headers: Headers,\n basename: string | undefined\n): SingleFetchRedirectResult {\n let redirect = headers.get(\"Location\")!;\n\n if (basename) {\n redirect = stripBasename(redirect, basename) || redirect;\n }\n\n return {\n redirect,\n status,\n revalidate:\n // Technically X-Remix-Revalidate isn't needed here - that was an implementation\n // detail of ?_data requests as our way to tell the front end to revalidate when\n // we didn't have a response body to include that information in.\n // With single fetch, we tell the front end via this revalidate boolean field.\n // However, we're respecting it for now because it may be something folks have\n // used in their own responses\n // TODO(v3): Consider removing or making this official public API\n headers.has(\"X-Remix-Revalidate\") || headers.has(\"Set-Cookie\"),\n reload: headers.has(\"X-Remix-Reload-Document\"),\n replace: headers.has(\"X-Remix-Replace\"),\n };\n}\n\nexport type Serializable =\n | undefined\n | null\n | boolean\n | string\n | symbol\n | number\n | Array<Serializable>\n | { [key: PropertyKey]: Serializable }\n | bigint\n | Date\n | URL\n | RegExp\n | Error\n | Map<Serializable, Serializable>\n | Set<Serializable>\n | Promise<Serializable>;\n\nexport function data(value: Serializable, init?: number | ResponseInit) {\n return routerData(value, init);\n}\n\n// Note: If you change this function please change the corresponding\n// decodeViaTurboStream function in server-runtime\nexport function encodeViaTurboStream(\n data: any,\n requestSignal: AbortSignal,\n streamTimeout: number | undefined,\n serverMode: ServerMode\n) {\n let controller = new AbortController();\n // How long are we willing to wait for all of the promises in `data` to resolve\n // before timing out? We default this to 50ms shorter than the default value for\n // `ABORT_DELAY` in our built-in `entry.server.tsx` so that once we reject we\n // have time to flush the rejections down through React's rendering stream before `\n // we call abort() on that. If the user provides their own it's up to them to\n // decouple the aborting of the stream from the aborting of React's renderToPipeableStream\n let timeoutId = setTimeout(\n () => controller.abort(new Error(\"Server Timeout\")),\n typeof streamTimeout === \"number\" ? streamTimeout : 4950\n );\n requestSignal.addEventListener(\"abort\", () => clearTimeout(timeoutId));\n\n return encode(data, {\n signal: controller.signal,\n plugins: [\n (value) => {\n // Even though we sanitized errors on context.errors prior to responding,\n // we still need to handle this for any deferred data that rejects with an\n // Error - as those will not be sanitized yet\n if (value instanceof Error) {\n let { name, message, stack } =\n serverMode === ServerMode.Production\n ? sanitizeError(value, serverMode)\n : value;\n return [\"SanitizedError\", name, message, stack];\n }\n\n if (value instanceof ErrorResponseImpl) {\n let { data, status, statusText } = value;\n return [\"ErrorResponse\", data, status, statusText];\n }\n\n if (\n value &&\n typeof value === \"object\" &&\n SingleFetchRedirectSymbol in value\n ) {\n return [\"SingleFetchRedirect\", value[SingleFetchRedirectSymbol]];\n }\n },\n ],\n postPlugins: [\n (value) => {\n if (!value) return;\n if (typeof value !== \"object\") return;\n\n return [\n \"SingleFetchClassInstance\",\n Object.fromEntries(Object.entries(value)),\n ];\n },\n () => [\"SingleFetchFallback\"],\n ],\n });\n}\n","import type { StaticHandler } from \"../router/router\";\nimport type { ErrorResponse } from \"../router/utils\";\nimport {\n isRouteErrorResponse,\n json as routerJson,\n ErrorResponseImpl,\n} from \"../router/utils\";\nimport {\n getStaticContextFromError,\n createStaticHandler,\n} from \"../router/router\";\nimport type { AppLoadContext } from \"./data\";\nimport type { HandleErrorFunction, ServerBuild } from \"./build\";\nimport type { EntryContext } from \"../dom/ssr/entry\";\nimport { createEntryRouteModules } from \"./entry\";\nimport { sanitizeErrors, serializeError, serializeErrors } from \"./errors\";\nimport { ServerMode, isServerMode } from \"./mode\";\nimport type { RouteMatch } from \"./routeMatching\";\nimport { matchServerRoutes } from \"./routeMatching\";\nimport type { EntryRoute, ServerRoute } from \"./routes\";\nimport { createStaticHandlerDataRoutes, createRoutes } from \"./routes\";\nimport { isRedirectResponse, isResponse, json } from \"./responses\";\nimport { createServerHandoffString } from \"./serverHandoff\";\nimport { getDevServerHooks } from \"./dev\";\nimport type { SingleFetchResult, SingleFetchResults } from \"./single-fetch\";\nimport {\n encodeViaTurboStream,\n getSingleFetchRedirect,\n singleFetchAction,\n singleFetchLoaders,\n SingleFetchRedirectSymbol,\n SINGLE_FETCH_REDIRECT_STATUS,\n} from \"./single-fetch\";\nimport { getDocumentHeaders } from \"./headers\";\nimport invariant from \"./invariant\";\n\nexport type RequestHandler = (\n request: Request,\n loadContext?: AppLoadContext\n) => Promise<Response>;\n\nexport type CreateRequestHandlerFunction = (\n build: ServerBuild | (() => ServerBuild | Promise<ServerBuild>),\n mode?: string\n) => RequestHandler;\n\nfunction derive(build: ServerBuild, mode?: string) {\n let routes = createRoutes(build.routes);\n let dataRoutes = createStaticHandlerDataRoutes(build.routes, build.future);\n let serverMode = isServerMode(mode) ? mode : ServerMode.Production;\n let staticHandler = createStaticHandler(dataRoutes, {\n basename: build.basename,\n });\n\n let errorHandler =\n build.entry.module.handleError ||\n ((error, { request }) => {\n if (serverMode !== ServerMode.Test && !request.signal.aborted) {\n console.error(\n // @ts-expect-error This is \"private\" from users but intended for internal use\n isRouteErrorResponse(error) && error.error ? error.error : error\n );\n }\n });\n return {\n routes,\n dataRoutes,\n serverMode,\n staticHandler,\n errorHandler,\n };\n}\n\nexport const createRequestHandler: CreateRequestHandlerFunction = (\n build,\n mode\n) => {\n let _build: ServerBuild;\n let routes: ServerRoute[];\n let serverMode: ServerMode;\n let staticHandler: StaticHandler;\n let errorHandler: HandleErrorFunction;\n\n return async function requestHandler(request, loadContext = {}) {\n _build = typeof build === \"function\" ? await build() : build;\n if (typeof build === \"function\") {\n let derived = derive(_build, mode);\n routes = derived.routes;\n serverMode = derived.serverMode;\n staticHandler = derived.staticHandler;\n errorHandler = derived.errorHandler;\n } else if (!routes || !serverMode || !staticHandler || !errorHandler) {\n let derived = derive(_build, mode);\n routes = derived.routes;\n serverMode = derived.serverMode;\n staticHandler = derived.staticHandler;\n errorHandler = derived.errorHandler;\n }\n\n let url = new URL(request.url);\n let params: RouteMatch<ServerRoute>[\"params\"] = {};\n let handleError = (error: unknown) => {\n if (mode === ServerMode.Development) {\n getDevServerHooks()?.processRequestError?.(error);\n }\n\n errorHandler(error, {\n context: loadContext,\n params,\n request,\n });\n };\n\n // Manifest request for fog of war\n let manifestUrl = `${_build.basename ?? \"/\"}/__manifest`.replace(\n /\\/+/g,\n \"/\"\n );\n if (url.pathname === manifestUrl) {\n try {\n let res = await handleManifestRequest(_build, routes, url);\n return res;\n } catch (e) {\n handleError(e);\n return new Response(\"Unknown Server Error\", { status: 500 });\n }\n }\n\n let matches = matchServerRoutes(routes, url.pathname, _build.basename);\n if (matches && matches.length > 0) {\n Object.assign(params, matches[0].params);\n }\n\n let response: Response;\n if (url.pathname.endsWith(\".data\")) {\n let handlerUrl = new URL(request.url);\n handlerUrl.pathname = handlerUrl.pathname\n .replace(/\\.data$/, \"\")\n .replace(/^\\/_root$/, \"/\");\n\n let singleFetchMatches = matchServerRoutes(\n routes,\n handlerUrl.pathname,\n _build.basename\n );\n\n response = await handleSingleFetchRequest(\n serverMode,\n _build,\n staticHandler,\n request,\n handlerUrl,\n loadContext,\n handleError\n );\n\n if (_build.entry.module.handleDataRequest) {\n response = await _build.entry.module.handleDataRequest(response, {\n context: loadContext,\n params: singleFetchMatches ? singleFetchMatches[0].params : {},\n request,\n });\n\n if (isRedirectResponse(response)) {\n let result: SingleFetchResult | SingleFetchResults =\n getSingleFetchRedirect(\n response.status,\n response.headers,\n _build.basename\n );\n\n if (request.method === \"GET\") {\n result = {\n [SingleFetchRedirectSymbol]: result,\n };\n }\n let headers = new Headers(response.headers);\n headers.set(\"Content-Type\", \"text/x-script\");\n\n return new Response(\n encodeViaTurboStream(\n result,\n request.signal,\n _build.entry.module.streamTimeout,\n serverMode\n ),\n {\n status: SINGLE_FETCH_REDIRECT_STATUS,\n headers,\n }\n );\n }\n }\n } else if (\n matches &&\n matches[matches.length - 1].route.module.default == null &&\n matches[matches.length - 1].route.module.ErrorBoundary == null\n ) {\n response = await handleResourceRequest(\n serverMode,\n _build,\n staticHandler,\n matches.slice(-1)[0].route.id,\n request,\n loadContext,\n handleError\n );\n } else {\n let criticalCss =\n mode === ServerMode.Development\n ? await getDevServerHooks()?.getCriticalCss?.(_build, url.pathname)\n : undefined;\n\n response = await handleDocumentRequest(\n serverMode,\n _build,\n staticHandler,\n request,\n loadContext,\n handleError,\n criticalCss\n );\n }\n\n if (request.method === \"HEAD\") {\n return new Response(null, {\n headers: response.headers,\n status: response.status,\n statusText: response.statusText,\n });\n }\n\n return response;\n };\n};\n\nasync function handleManifestRequest(\n build: ServerBuild,\n routes: ServerRoute[],\n url: URL\n) {\n let patches: Record<string, EntryRoute> = {};\n\n if (url.searchParams.has(\"p\")) {\n for (let path of url.searchParams.getAll(\"p\")) {\n let matches = matchServerRoutes(routes, path, build.basename);\n if (matches) {\n for (let match of matches) {\n let routeId = match.route.id;\n patches[routeId] = build.assets.routes[routeId];\n }\n }\n }\n\n return json(patches, {\n headers: {\n \"Cache-Control\": \"public, max-age=31536000, immutable\",\n },\n }) as Response; // Override the TypedResponse stuff from json()\n }\n\n return new Response(\"Invalid Request\", { status: 400 });\n}\n\nasync function handleSingleFetchRequest(\n serverMode: ServerMode,\n build: ServerBuild,\n staticHandler: StaticHandler,\n request: Request,\n handlerUrl: URL,\n loadContext: AppLoadContext,\n handleError: (err: unknown) => void\n): Promise<Response> {\n let { result, headers, status } =\n request.method !== \"GET\"\n ? await singleFetchAction(\n build,\n serverMode,\n staticHandler,\n request,\n handlerUrl,\n loadContext,\n handleError\n )\n : await singleFetchLoaders(\n build,\n serverMode,\n staticHandler,\n request,\n handlerUrl,\n loadContext,\n handleError\n );\n\n // Mark all successful responses with a header so we can identify in-flight\n // network errors that are missing this header\n let resultHeaders = new Headers(headers);\n resultHeaders.set(\"X-Remix-Response\", \"yes\");\n\n // 304 responses should not have a body\n if (status === 304) {\n return new Response(null, { status: 304, headers: resultHeaders });\n }\n\n // We use a less-descriptive `text/x-script` here instead of something like\n // `text/x-turbo` to enable compression when deployed via Cloudflare. See:\n // - https://github.com/remix-run/remix/issues/9884\n // - https://developers.cloudflare.com/speed/optimization/content/brotli/content-compression/\n resultHeaders.set(\"Content-Type\", \"text/x-script\");\n\n return new Response(\n encodeViaTurboStream(\n result,\n request.signal,\n build.entry.module.streamTimeout,\n serverMode\n ),\n {\n status: status || 200,\n headers: resultHeaders,\n }\n );\n}\n\nasync function handleDocumentRequest(\n serverMode: ServerMode,\n build: ServerBuild,\n staticHandler: StaticHandler,\n request: Request,\n loadContext: AppLoadContext,\n handleError: (err: unknown) => void,\n criticalCss?: string\n) {\n let context;\n try {\n context = await staticHandler.query(request, {\n requestContext: loadContext,\n });\n } catch (error: unknown) {\n handleError(error);\n return new Response(null, { status: 500 });\n }\n\n if (isResponse(context)) {\n return context;\n }\n\n let headers = getDocumentHeaders(build, context);\n\n // 304 responses should not have a body or a content-type\n if (context.statusCode === 304) {\n return new Response(null, { status: 304, headers });\n }\n\n // Sanitize errors outside of development environments\n if (context.errors) {\n Object.values(context.errors).forEach((err) => {\n // @ts-expect-error This is \"private\" from users but intended for internal use\n if (!isRouteErrorResponse(err) || err.error) {\n handleError(err);\n }\n });\n context.errors = sanitizeErrors(context.errors, serverMode);\n }\n\n // Server UI state to send to the client.\n // - When single fetch is enabled, this is streamed down via `serverHandoffStream`\n // - Otherwise it's stringified into `serverHandoffString`\n let state = {\n loaderData: context.loaderData,\n actionData: context.actionData,\n errors: serializeErrors(context.errors, serverMode),\n };\n let entryContext: EntryContext = {\n manifest: build.assets,\n routeModules: createEntryRouteModules(build.routes),\n staticHandlerContext: context,\n criticalCss,\n serverHandoffString: createServerHandoffString({\n basename: build.basename,\n criticalCss,\n future: build.future,\n isSpaMode: build.isSpaMode,\n }),\n serverHandoffStream: encodeViaTurboStream(\n state,\n request.signal,\n build.entry.module.streamTimeout,\n serverMode\n ),\n renderMeta: {},\n future: build.future,\n isSpaMode: build.isSpaMode,\n serializeError: (err) => serializeError(err, serverMode),\n };\n\n let handleDocumentRequestFunction = build.entry.module.default;\n try {\n return await handleDocumentRequestFunction(\n request,\n context.statusCode,\n headers,\n entryContext,\n loadContext\n );\n } catch (error: unknown) {\n handleError(error);\n\n let errorForSecondRender = error;\n\n // If they threw a response, unwrap it into an ErrorResponse like we would\n // have for a loader/action\n if (isResponse(error)) {\n try {\n let data = await unwrapResponse(error);\n errorForSecondRender = new ErrorResponseImpl(\n error.status,\n error.statusText,\n data\n );\n } catch (e) {\n // If we can't unwrap the response - just leave it as-is\n }\n }\n\n // Get a new StaticHandlerContext that contains the error at the right boundary\n context = getStaticContextFromError(\n staticHandler.dataRoutes,\n context,\n errorForSecondRender\n );\n\n // Sanitize errors outside of development environments\n if (context.errors) {\n context.errors = sanitizeErrors(context.errors, serverMode);\n }\n\n // Get a new entryContext for the second render pass\n // Server UI state to send to the client.\n // - When single fetch is enabled, this is streamed down via `serverHandoffStream`\n // - Otherwise it's stringified into `serverHandoffString`\n let state = {\n loaderData: context.loaderData,\n actionData: context.actionData,\n errors: serializeErrors(context.errors, serverMode),\n };\n entryContext = {\n ...entryContext,\n staticHandlerContext: context,\n serverHandoffString: createServerHandoffString({\n basename: build.basename,\n future: build.future,\n isSpaMode: build.isSpaMode,\n }),\n serverHandoffStream: encodeViaTurboStream(\n state,\n request.signal,\n build.entry.module.streamTimeout,\n serverMode\n ),\n renderMeta: {},\n };\n\n try {\n return await handleDocumentRequestFunction(\n request,\n context.statusCode,\n headers,\n entryContext,\n loadContext\n );\n } catch (error: any) {\n handleError(error);\n return returnLastResortErrorResponse(error, serverMode);\n }\n }\n}\n\nasync function handleResourceRequest(\n serverMode: ServerMode,\n build: ServerBuild,\n staticHandler: StaticHandler,\n routeId: string,\n request: Request,\n loadContext: AppLoadContext,\n handleError: (err: unknown) => void\n) {\n try {\n // Note we keep the routeId here to align with the Remix handling of\n // resource routes which doesn't take ?index into account and just takes\n // the leaf match\n let response = await staticHandler.queryRoute(request, {\n routeId,\n requestContext: loadContext,\n });\n\n invariant(\n isResponse(response),\n \"Expected a Response to be returned from resource route handler\"\n );\n\n return response;\n } catch (error: unknown) {\n if (isResponse(error)) {\n // Note: Not functionally required but ensures that our response headers\n // match identically to what Remix returns\n error.headers.set(\"X-Remix-Catch\", \"yes\");\n return error;\n }\n\n if (isRouteErrorResponse(error)) {\n if (error) {\n handleError(error);\n }\n return errorResponseToJson(error, serverMode);\n }\n\n handleError(error);\n return returnLastResortErrorResponse(error, serverMode);\n }\n}\n\nfunction errorResponseToJson(\n errorResponse: ErrorResponse,\n serverMode: ServerMode\n): Response {\n return routerJson(\n serializeError(\n // @ts-expect-error This is \"private\" from users but intended for internal use\n errorResponse.error || new Error(\"Unexpected Server Error\"),\n serverMode\n ),\n {\n status: errorResponse.status,\n statusText: errorResponse.statusText,\n headers: {\n \"X-Remix-Error\": \"yes\",\n },\n }\n );\n}\n\nfunction returnLastResortErrorResponse(error: any, serverMode?: ServerMode) {\n let message = \"Unexpected Server Error\";\n\n if (serverMode !== ServerMode.Production) {\n message += `\\n\\n${String(error)}`;\n }\n\n // Good grief folks, get your act together 😂!\n return new Response(message, {\n status: 500,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n}\n\nfunction unwrapResponse(response: Response) {\n let contentType = response.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n return contentType && /\\bapplication\\/json\\b/.test(contentType)\n ? response.body == null\n ? null\n : response.json()\n : response.text();\n}\n","import type { CookieParseOptions, CookieSerializeOptions } from \"cookie\";\n\nimport type { Cookie, CookieOptions } from \"./cookies\";\nimport { createCookie, isCookie } from \"./cookies\";\nimport { warnOnce } from \"./warnings\";\n\n/**\n * An object of name/value pairs to be used in the session.\n */\nexport interface SessionData {\n [name: string]: any;\n}\n\n/**\n * Session persists data across HTTP requests.\n *\n * @see https://remix.run/utils/sessions#session-api\n */\nexport interface Session<Data = SessionData, FlashData = Data> {\n /**\n * A unique identifier for this session.\n *\n * Note: This will be the empty string for newly created sessions and\n * sessions that are not backed by a database (i.e. cookie-based sessions).\n */\n readonly id: string;\n\n /**\n * The raw data contained in this session.\n *\n * This is useful mostly for SessionStorage internally to access the raw\n * session data to persist.\n */\n readonly data: FlashSessionData<Data, FlashData>;\n\n /**\n * Returns `true` if the session has a value for the given `name`, `false`\n * otherwise.\n */\n has(name: (keyof Data | keyof FlashData) & string): boolean;\n\n /**\n * Returns the value for the given `name` in this session.\n */\n get<Key extends (keyof Data | keyof FlashData) & string>(\n name: Key\n ):\n | (Key extends keyof Data ? Data[Key] : undefined)\n | (Key extends keyof FlashData ? FlashData[Key] : undefined)\n | undefined;\n\n /**\n * Sets a value in the session for the given `name`.\n */\n set<Key extends keyof Data & string>(name: Key, value: Data[Key]): void;\n\n /**\n * Sets a value in the session that is only valid until the next `get()`.\n * This can be useful for temporary values, like error messages.\n */\n flash<Key extends keyof FlashData & string>(\n name: Key,\n value: FlashData[Key]\n ): void;\n\n /**\n * Removes a value from the session.\n */\n unset(name: keyof Data & string): void;\n}\n\nexport type FlashSessionData<Data, FlashData> = Partial<\n Data & {\n [Key in keyof FlashData as FlashDataKey<Key & string>]: FlashData[Key];\n }\n>;\ntype FlashDataKey<Key extends string> = `__flash_${Key}__`;\nfunction flash<Key extends string>(name: Key): FlashDataKey<Key> {\n return `__flash_${name}__`;\n}\n\nexport type CreateSessionFunction = <Data = SessionData, FlashData = Data>(\n initialData?: Data,\n id?: string\n) => Session<Data, FlashData>;\n\n/**\n * Creates a new Session object.\n *\n * Note: This function is typically not invoked directly by application code.\n * Instead, use a `SessionStorage` object's `getSession` method.\n *\n * @see https://remix.run/utils/sessions#createsession\n */\nexport const createSession: CreateSessionFunction = <\n Data = SessionData,\n FlashData = Data\n>(\n initialData: Partial<Data> = {},\n id = \"\"\n): Session<Data, FlashData> => {\n let map = new Map(Object.entries(initialData)) as Map<\n keyof Data | FlashDataKey<keyof FlashData & string>,\n any\n >;\n\n return {\n get id() {\n return id;\n },\n get data() {\n return Object.fromEntries(map) as FlashSessionData<Data, FlashData>;\n },\n has(name) {\n return (\n map.has(name as keyof Data) ||\n map.has(flash(name as keyof FlashData & string))\n );\n },\n get(name) {\n if (map.has(name as keyof Data)) return map.get(name as keyof Data);\n\n let flashName = flash(name as keyof FlashData & string);\n if (map.has(flashName)) {\n let value = map.get(flashName);\n map.delete(flashName);\n return value;\n }\n\n return undefined;\n },\n set(name, value) {\n map.set(name, value);\n },\n flash(name, value) {\n map.set(flash(name), value);\n },\n unset(name) {\n map.delete(name);\n },\n };\n};\n\nexport type IsSessionFunction = (object: any) => object is Session;\n\n/**\n * Returns true if an object is a Remix session.\n *\n * @see https://remix.run/utils/sessions#issession\n */\nexport const isSession: IsSessionFunction = (object): object is Session => {\n return (\n object != null &&\n typeof object.id === \"string\" &&\n typeof object.data !== \"undefined\" &&\n typeof object.has === \"function\" &&\n typeof object.get === \"function\" &&\n typeof object.set === \"function\" &&\n typeof object.flash === \"function\" &&\n typeof object.unset === \"function\"\n );\n};\n\n/**\n * SessionStorage stores session data between HTTP requests and knows how to\n * parse and create cookies.\n *\n * A SessionStorage creates Session objects using a `Cookie` header as input.\n * Then, later it generates the `Set-Cookie` header to be used in the response.\n */\nexport interface SessionStorage<Data = SessionData, FlashData = Data> {\n /**\n * Parses a Cookie header from a HTTP request and returns the associated\n * Session. If there is no session associated with the cookie, this will\n * return a new Session with no data.\n */\n getSession: (\n cookieHeader?: string | null,\n options?: CookieParseOptions\n ) => Promise<Session<Data, FlashData>>;\n\n /**\n * Stores all data in the Session and returns the Set-Cookie header to be\n * used in the HTTP response.\n */\n commitSession: (\n session: Session<Data, FlashData>,\n options?: CookieSerializeOptions\n ) => Promise<string>;\n\n /**\n * Deletes all data associated with the Session and returns the Set-Cookie\n * header to be used in the HTTP response.\n */\n destroySession: (\n session: Session<Data, FlashData>,\n options?: CookieSerializeOptions\n ) => Promise<string>;\n}\n\n/**\n * SessionIdStorageStrategy is designed to allow anyone to easily build their\n * own SessionStorage using `createSessionStorage(strategy)`.\n *\n * This strategy describes a common scenario where the session id is stored in\n * a cookie but the actual session data is stored elsewhere, usually in a\n * database or on disk. A set of create, read, update, and delete operations\n * are provided for managing the session data.\n */\nexport interface SessionIdStorageStrategy<\n Data = SessionData,\n FlashData = Data\n> {\n /**\n * The Cookie used to store the session id, or options used to automatically\n * create one.\n */\n cookie?: Cookie | (CookieOptions & { name?: string });\n\n /**\n * Creates a new record with the given data and returns the session id.\n */\n createData: (\n data: FlashSessionData<Data, FlashData>,\n expires?: Date\n ) => Promise<string>;\n\n /**\n * Returns data for a given session id, or `null` if there isn't any.\n */\n readData: (id: string) => Promise<FlashSessionData<Data, FlashData> | null>;\n\n /**\n * Updates data for the given session id.\n */\n updateData: (\n id: string,\n data: FlashSessionData<Data, FlashData>,\n expires?: Date\n ) => Promise<void>;\n\n /**\n * Deletes data for a given session id from the data store.\n */\n deleteData: (id: string) => Promise<void>;\n}\n\n/**\n * Creates a SessionStorage object using a SessionIdStorageStrategy.\n *\n * Note: This is a low-level API that should only be used if none of the\n * existing session storage options meet your requirements.\n */\nexport function createSessionStorage<Data = SessionData, FlashData = Data>({\n cookie: cookieArg,\n createData,\n readData,\n updateData,\n deleteData,\n}: SessionIdStorageStrategy<Data, FlashData>): SessionStorage<Data, FlashData> {\n let cookie = isCookie(cookieArg)\n ? cookieArg\n : createCookie(cookieArg?.name || \"__session\", cookieArg);\n\n warnOnceAboutSigningSessionCookie(cookie);\n\n return {\n async getSession(cookieHeader, options) {\n let id = cookieHeader && (await cookie.parse(cookieHeader, options));\n let data = id && (await readData(id));\n return createSession(data || {}, id || \"\");\n },\n async commitSession(session, options) {\n let { id, data } = session;\n let expires =\n options?.maxAge != null\n ? new Date(Date.now() + options.maxAge * 1000)\n : options?.expires != null\n ? options.expires\n : cookie.expires;\n\n if (id) {\n await updateData(id, data, expires);\n } else {\n id = await createData(data, expires);\n }\n\n return cookie.serialize(id, options);\n },\n async destroySession(session, options) {\n await deleteData(session.id);\n return cookie.serialize(\"\", {\n ...options,\n maxAge: undefined,\n expires: new Date(0),\n });\n },\n };\n}\n\nexport function warnOnceAboutSigningSessionCookie(cookie: Cookie) {\n warnOnce(\n cookie.isSigned,\n `The \"${cookie.name}\" cookie is not signed, but session cookies should be ` +\n `signed to prevent tampering on the client before they are sent back to the ` +\n `server. See https://remix.run/utils/cookies#signing-cookies ` +\n `for more information.`\n );\n}\n","import type { ReactElement } from \"react\";\nimport * as React from \"react\";\n\nimport { createStaticRouter, StaticRouterProvider } from \"../server\";\nimport { FrameworkContext } from \"./components\";\nimport type { EntryContext } from \"./entry\";\nimport { RemixErrorBoundary } from \"./errorBoundaries\";\nimport { createServerRoutes, shouldHydrateRouteLoader } from \"./routes\";\nimport { StreamTransfer } from \"./single-fetch\";\n\nexport interface ServerRouterProps {\n context: EntryContext;\n url: string | URL;\n abortDelay?: number;\n nonce?: string;\n}\n\n/**\n * The entry point for a Remix app when it is rendered on the server (in\n * `app/entry.server.js`). This component is used to generate the HTML in the\n * response from the server.\n *\n * @category Components\n */\nexport function ServerRouter({\n context,\n url,\n abortDelay,\n nonce,\n}: ServerRouterProps): ReactElement {\n if (typeof url === \"string\") {\n url = new URL(url);\n }\n\n let { manifest, routeModules, criticalCss, serverHandoffString } = context;\n let routes = createServerRoutes(\n manifest.routes,\n routeModules,\n context.future,\n context.isSpaMode\n );\n\n // Create a shallow clone of `loaderData` we can mutate for partial hydration.\n // When a route exports a `clientLoader` and a `HydrateFallback`, we want to\n // render the fallback on the server so we clear our the `loaderData` during SSR.\n // Is it important not to change the `context` reference here since we use it\n // for context._deepestRenderedBoundaryId tracking\n context.staticHandlerContext.loaderData = {\n ...context.staticHandlerContext.loaderData,\n };\n for (let match of context.staticHandlerContext.matches) {\n let routeId = match.route.id;\n let route = routeModules[routeId];\n let manifestRoute = context.manifest.routes[routeId];\n // Clear out the loaderData to avoid rendering the route component when the\n // route opted into clientLoader hydration and either:\n // * gave us a HydrateFallback\n // * or doesn't have a server loader and we have no data to render\n if (\n route &&\n shouldHydrateRouteLoader(manifestRoute, route, context.isSpaMode) &&\n (route.HydrateFallback || !manifestRoute.hasLoader)\n ) {\n delete context.staticHandlerContext.loaderData[routeId];\n }\n }\n\n let router = createStaticRouter(routes, context.staticHandlerContext);\n\n return (\n <>\n <FrameworkContext.Provider\n value={{\n manifest,\n routeModules,\n criticalCss,\n serverHandoffString,\n future: context.future,\n isSpaMode: context.isSpaMode,\n serializeError: context.serializeError,\n abortDelay,\n renderMeta: context.renderMeta,\n }}\n >\n <RemixErrorBoundary location={router.state.location}>\n <StaticRouterProvider\n router={router}\n context={context.staticHandlerContext}\n hydrate={false}\n />\n </RemixErrorBoundary>\n </FrameworkContext.Provider>\n {context.serverHandoffStream ? (\n <React.Suspense>\n <StreamTransfer\n context={context}\n identifier={0}\n reader={context.serverHandoffStream.getReader()}\n textDecoder={new TextDecoder()}\n nonce={nonce}\n />\n </React.Suspense>\n ) : null}\n </>\n );\n}\n","import type { RouterState } from \"../../router/router\";\nimport { ErrorResponseImpl } from \"../../router/utils\";\n\nexport function deserializeErrors(\n errors: RouterState[\"errors\"]\n): RouterState[\"errors\"] {\n if (!errors) return null;\n let entries = Object.entries(errors);\n let serialized: RouterState[\"errors\"] = {};\n for (let [key, val] of entries) {\n // Hey you! If you change this, please change the corresponding logic in\n // serializeErrors in react-router/lib/server-runtime/errors.ts :)\n if (val && val.__type === \"RouteErrorResponse\") {\n serialized[key] = new ErrorResponseImpl(\n val.status,\n val.statusText,\n val.data,\n val.internal === true\n );\n } else if (val && val.__type === \"Error\") {\n // Attempt to reconstruct the right type of Error (i.e., ReferenceError)\n if (val.__subType) {\n let ErrorConstructor = window[val.__subType];\n if (typeof ErrorConstructor === \"function\") {\n try {\n // @ts-expect-error\n let error = new ErrorConstructor(val.message);\n error.stack = val.stack;\n serialized[key] = error;\n } catch (e) {\n // no-op - fall through and create a normal Error\n }\n }\n }\n\n if (serialized[key] == null) {\n let error = new Error(val.message);\n error.stack = val.stack;\n serialized[key] = error;\n }\n } else {\n serialized[key] = val;\n }\n }\n return serialized;\n}\n","import { createCookie, isCookie } from \"../cookies\";\nimport type {\n SessionStorage,\n SessionIdStorageStrategy,\n SessionData,\n} from \"../sessions\";\nimport { warnOnceAboutSigningSessionCookie, createSession } from \"../sessions\";\n\ninterface CookieSessionStorageOptions {\n /**\n * The Cookie used to store the session data on the client, or options used\n * to automatically create one.\n */\n cookie?: SessionIdStorageStrategy[\"cookie\"];\n}\n\n/**\n * Creates and returns a SessionStorage object that stores all session data\n * directly in the session cookie itself.\n *\n * This has the advantage that no database or other backend services are\n * needed, and can help to simplify some load-balanced scenarios. However, it\n * also has the limitation that serialized session data may not exceed the\n * browser's maximum cookie size. Trade-offs!\n */\nexport function createCookieSessionStorage<\n Data = SessionData,\n FlashData = Data\n>({ cookie: cookieArg }: CookieSessionStorageOptions = {}): SessionStorage<\n Data,\n FlashData\n> {\n let cookie = isCookie(cookieArg)\n ? cookieArg\n : createCookie(cookieArg?.name || \"__session\", cookieArg);\n\n warnOnceAboutSigningSessionCookie(cookie);\n\n return {\n async getSession(cookieHeader, options) {\n return createSession(\n (cookieHeader && (await cookie.parse(cookieHeader, options))) || {}\n );\n },\n async commitSession(session, options) {\n let serializedCookie = await cookie.serialize(session.data, options);\n if (serializedCookie.length > 4096) {\n throw new Error(\n \"Cookie length will exceed browser maximum. Length: \" +\n serializedCookie.length\n );\n }\n return serializedCookie;\n },\n async destroySession(_session, options) {\n return cookie.serialize(\"\", {\n ...options,\n maxAge: undefined,\n expires: new Date(0),\n });\n },\n };\n}\n","import type {\n SessionData,\n SessionStorage,\n SessionIdStorageStrategy,\n FlashSessionData,\n} from \"../sessions\";\nimport { createSessionStorage } from \"../sessions\";\n\ninterface MemorySessionStorageOptions {\n /**\n * The Cookie used to store the session id on the client, or options used\n * to automatically create one.\n */\n cookie?: SessionIdStorageStrategy[\"cookie\"];\n}\n\n/**\n * Creates and returns a simple in-memory SessionStorage object, mostly useful\n * for testing and as a reference implementation.\n *\n * Note: This storage does not scale beyond a single process, so it is not\n * suitable for most production scenarios.\n */\nexport function createMemorySessionStorage<\n Data = SessionData,\n FlashData = Data\n>({ cookie }: MemorySessionStorageOptions = {}): SessionStorage<\n Data,\n FlashData\n> {\n let map = new Map<\n string,\n { data: FlashSessionData<Data, FlashData>; expires?: Date }\n >();\n\n return createSessionStorage({\n cookie,\n async createData(data, expires) {\n let id = Math.random().toString(36).substring(2, 10);\n map.set(id, { data, expires });\n return id;\n },\n async readData(id) {\n if (map.has(id)) {\n let { data, expires } = map.get(id)!;\n\n if (!expires || expires > new Date()) {\n return data;\n }\n\n // Remove expired session data.\n if (expires) map.delete(id);\n }\n\n return null;\n },\n async updateData(id, data, expires) {\n map.set(id, { data, expires });\n },\n async deleteData(id) {\n map.delete(id);\n },\n });\n}\n"],"names":["Action","PopStateEventType","createMemoryHistory","options","entries","initialEntries","initialIndex","v5Compat","map","entry","index","createMemoryLocation","state","undefined","clampIndex","length","action","Pop","listener","n","Math","min","max","getCurrentLocation","to","key","createLocation","pathname","createHref","createPath","location","createURL","URL","encodeLocation","path","parsePath","search","hash","push","Push","nextLocation","splice","delta","replace","Replace","go","nextIndex","listen","fn","createBrowserHistory","getUrlBasedHistory","window","globalHistory","usr","createHashHistory","substr","startsWith","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","invariant","value","message","Error","getHistoryState","idx","current","_extends","random","toString","_ref","charAt","parsedPath","searchIndex","getLocation","validateLocation","defaultView","history","getIndex","handlePop","origin","replaceState","addEventListener","removeEventListener","historyState","pushState","error","DOMException","name","assign","ResultType","immutableRouteKeys","Set","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","route","treePath","String","id","join","children","isIndexRoute","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","matchRoutesImpl","allowPartial","stripBasename","branches","flattenRoutes","sort","a","b","score","every","i","compareIndexes","routesMeta","meta","childrenIndex","rankRouteBranches","matches","decoded","decodePath","matchRouteBranch","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","caseSensitive","joinPaths","concat","computeScore","forEach","_route$path","includes","exploded","explodeOptionalSegments","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","paramRe","isSplat","s","initialScore","some","filter","reduce","segment","test","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","pattern","matcher","compiledParams","regexpSource","_","paramName","RegExp","compilePath","captureGroups","memo","splatValue","v","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","pop","resolvePathname","normalizeSearch","normalizeHash","getPathContributingMatches","getResolveToMatches","pathMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","from","isEmptyPath","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","paths","json","init","responseInit","status","headers","Headers","has","set","Response","JSON","stringify","DataWithResponseInit","constructor","this","type","redirect","ErrorResponseImpl","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","text","IDLE_FETCHER","IDLE_BLOCKER","proceed","reset","ABSOLUTE_URL_REGEX","defaultMapRouteProperties","hasErrorBoundary","Boolean","TRANSITIONS_STORAGE_KEY","ResetLoaderDataSymbol","Symbol","createRouter","routerWindow","isBrowser","createElement","inFlightDataRoutes","initialized","router","dataRoutes","dataStrategyImpl","dataStrategy","defaultDataStrategy","patchRoutesOnNavigationImpl","patchRoutesOnNavigation","future","unlistenHistory","subscribers","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialErrors","getInternalRouterError","getShortCircuitMatches","checkFogOfWar","active","m","lazy","loader","errors","findIndex","shouldLoadRouteOnHydration","fogOfWar","pendingNavigationController","unblockBlockerHistoryUpdate","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","actionData","fetchers","Map","blockers","pendingAction","NavigationType","pendingPreventScrollReset","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","isRevalidationRequired","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeFetchers","fetchersQueuedForDeletion","blockerFunctions","pendingRevalidationDfd","updateState","newState","opts","unmountedFetchers","mountedFetchers","fetcher","subscriber","deletedFetchers","viewTransitionOpts","flushSync","deleteFetcher","delete","completeNavigation","_temp","_location$state","_location$state2","_pendingRevalidationD","isActionReload","isMutationMethod","_isRedirect","keys","mergeLoaderData","size","k","priorPaths","get","currentLocation","toPaths","add","getSavedScrollPosition","resolve","async","startNavigation","abort","startUninterruptedRevalidation","getScrollKey","saveScrollPosition","enableViewTransition","routesToUse","loadingNavigation","overrideNavigation","notFoundMatches","handleNavigational404","isHashChangeOnly","submission","AbortController","pendingActionResult","request","createClientSideRequest","signal","pendingError","findNearestBoundary","actionResult","isFogOfWar","interruptActiveLoads","getSubmittingNavigation","discoverResult","discoverRoutes","shortCircuited","boundaryId","partialMatches","actionMatch","getTargetMatch","callDataStrategy","aborted","method","routeId","isRedirectResult","normalizeRedirectLocation","response","startRedirectNavigation","isErrorResult","boundaryMatch","handleAction","getLoadingNavigation","updatedMatches","fetcherSubmission","initialHydration","activeSubmission","getSubmissionFromNavigation","shouldUpdateNavigationState","getUpdatedActionData","matchesToLoad","revalidatingFetchers","getMatchesToLoad","updatedFetchers","markFetchRedirectsDone","getActionDataForCommit","updates","rf","revalidatingFetcher","getLoadingFetcher","getUpdatedRevalidatingFetchers","abortFetcher","controller","abortPendingFetchRevalidations","f","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","findRedirect","processLoaderData","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","handleLoaders","isNavigation","_temp2","redirectLocation","isDocumentReload","redirectNavigationType","fetcherKey","results","dataResults","callDataStrategyImpl","e","isRedirectDataStrategyResultResult","normalizeRelativeRoutingRedirectResponse","convertDataStrategyResultToDataResult","fetchersToLoad","loaderResultsPromise","fetcherResultsPromise","Promise","all","acc","r","updateFetcherState","setFetcherError","getFetcher","markFetchersDone","doneFetcher","getDoneFetcher","doneKeys","landedId","yeetedKeys","deleteBlocker","updateBlocker","newBlocker","blocker","shouldBlockNavigation","_ref2","Array","blockerKey","blockerFunction","y","isNonHMR","localManifest","patch","patchRoutesImpl","newMatches","newPartialMatches","initialize","nextHistoryUpdatePromise","then","_window","transitions","sessionPositions","sessionStorage","getItem","parse","isArray","restoreAppliedTransitions","_saveAppliedTransitions","setItem","persistAppliedTransitions","subscribe","enableScrollRestoration","positions","getPosition","getKey","navigate","normalizedPath","normalizeTo","fromRouteId","relative","normalizeNavigateOptions","userReplace","viewTransition","fetch","requestMatches","detectAndHandle405Error","existingFetcher","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","revalidationRequest","loadId","loadFetcher","staleKey","handleFetcherAction","handleFetcherLoader","revalidate","reject","promise","res","rej","val","createDeferred","count","dispose","clear","getBlocker","patchRoutes","_internalFetchControllers","_internalSetRoutes","newRoutes","createStaticHandler","queryImpl","requestContext","skipLoaderErrorBubbling","routeMatch","isRouteRequest","throwStaticHandlerAbortedError","Location","statusCode","loaderHeaders","actionHeaders","loaderRequest","Request","loadRouteData","submit","isResponse","isDataStrategyResult","isRedirectResponse","getLoaderMatchesUntilBoundary","context","processRouteLoaderData","executedLoaders","query","_temp3","isValidMethod","methodNotAllowedMatches","queryRoute","_temp4","find","values","reason","contextualMatches","activeRouteMatch","nakedIndex","hasNakedIndexQuery","URLSearchParams","indexValues","getAll","append","qs","isFetcher","body","isSubmissionNavigation","searchParams","getInvalidBodyError","toUpperCase","stripHashFromPath","FormData","_ref3","convertFormDataToSearchParams","convertSearchParamsToFormData","includeBoundary","currentUrl","nextUrl","boundaryMatches","actionStatus","shouldSkipRevalidation","navigationMatches","currentLoaderData","currentMatch","isNew","isMissingData","hasOwnProperty","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","defaultShouldRevalidate","isNewRouteInstance","fetcherMatches","fetcherMatch","shouldRevalidate","hasData","hasError","hydrate","currentPath","loaderMatch","arg","routeChoice","_childrenToPatch","childrenToPatch","newRoute","existingRoute","isSameRoute","aChild","_existingRoute$childr","bChild","_ref4","shouldLoad","loadRouteDefinitionsPromises","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","loadLazyRouteModule","dsMatches","loadRoutePromise","handlerOverride","staticContext","onReject","runHandler","handler","abortPromise","actualHandler","ctx","handlerPromise","race","handlerError","catch","callLoaderOrAction","dataStrategyResult","contentType","isDataWithResponseInit","_result$init2","_result$init","_result$init3","_result$init4","trimmedMatches","normalizedLocation","protocol","isSameBasename","isStaticHandler","foundError","newLoaderData","mergedLoaderData","_ref5","merged","_ref6","reverse","_temp5","errorMessage","DataRouterContext","React","createContext","displayName","DataRouterStateContext","ViewTransitionContext","isTransitioning","FetchersContext","AwaitContext","NavigationContext","LocationContext","RouteContext","outlet","isDataRoute","RouteErrorContext","useHref","useInRouterContext","navigator","useContext","useResolvedPath","joinedPathname","useLocation","useIsomorphicLayoutEffect","cb","static","useLayoutEffect","useNavigate","useDataRouterContext","DataRouterHook","UseNavigateStable","useCurrentRouteId","DataRouterStateHook","activeRef","useRef","useCallback","useNavigateStable","dataRouterContext","routePathnamesJson","useNavigateUnstable","OutletContext","useOutlet","Provider","useMemo","useRoutes","useRoutesImpl","dataRouterState","parentMatches","parentParams","parentPathname","parentPathnameBase","parentRoute","warningOnce","locationFromContext","_parsedLocationArg$pa","parsedLocationArg","parentSegments","renderedMatches","_renderMatches","navigationType","DefaultErrorComponent","useRouteError","stack","lightgrey","preStyles","padding","backgroundColor","codeStyles","devInfo","console","Fragment","style","fontStyle","defaultErrorElement","RenderErrorBoundary","Component","props","super","componentDidCatch","errorInfo","render","routeContext","component","RenderedRoute","errorElement","ErrorBoundary","_deepestRenderedBoundaryId","_dataRouterState","errorIndex","renderFallback","fallbackIndex","HydrateFallback","hydrateFallbackElement","needsToRunLoader","reduceRight","shouldRenderHydrateFallback","getChildren","element","hookName","useDataRouterState","useRouteContext","thisRoute","useNavigation","UseNavigation","useMatches","UseMatches","_state$errors","UseRouteError","useAsyncValue","_data","blockerId","useBlocker","shouldBlock","UseBlocker","setBlockerKey","useState","useEffect","alreadyWarned","cond","warnOnce","condition","warn","createMemoryRouter","Deferred","RouterProvider","reactDomFlushSyncImpl","setStateImpl","pendingState","setPendingState","vtContext","setVtContext","renderDfd","setRenderDfd","transition","setTransition","interruption","setInterruption","fetcherData","setState","isViewTransitionAvailable","startViewTransition","skipTransition","t","finished","finally","startTransition","renderPromise","Router","MemoizedDataRoutes","DataRoutes","Outlet","Route","_props","basenameProp","locationProp","staticProp","navigationContext","locationContext","trailingPathname","AwaitRenderStatus","AwaitErrorBoundary","pending","renderError","defineProperty","_tracked","success","_error","ResolveAwait","_ref9","toRender","createRoutesFromChildren","Children","isValidElement","apply","defaultMethod","defaultEncType","isHtmlElement","object","tagName","createSearchParams","_formDataSupportsSubmitter","supportedFormEncTypes","getFormEncType","encType","getFormSubmissionInfo","target","attr","isButtonElement","isInputElement","form","isFormDataSubmitterSupported","prefix","loadRouteModule","routeModulesCache","routeModule","import","module","__reactRouterContext","isSpaMode","reload","getKeyedLinksForMatches","routeModules","descriptors","css","rel","links","flat","preloads","dedupeHrefs","hrefs","imports","getCurrentPageModulePreloadHrefs","dedupeLinkDescriptors","prefetchStyleLinks","_isPreloadSupported","el","relList","supports","isPreloadSupported","styleLinks","descriptor","isPageLinkDescriptor","as","matchingLinks","link","media","matchMedia","prefetchStyleLink","removeLink","head","contains","removeChild","onload","onerror","appendChild","page","isHtmlLinkDescriptor","imageSrcSet","imageSizes","getNewMatchesForLinks","nextMatches","currentMatches","mode","parsePathPatch","matchPathChanged","_currentMatches$index","hasLoader","_currentMatches$","manifestRoute","preloadsSet","deduped","obj","sorted","sortKeys","ESCAPE_LOOKUP","ESCAPE_REGEX","createHtml","html","__html","createRequestInit","SingleFetchRedirectSymbol","StreamTransfer","identifier","reader","textDecoder","nonce","renderMeta","didRenderScripts","streamCache","read","done","decode","stream","scriptTag","dangerouslySetInnerHTML","Suspense","fetchSingleLoader","singleLoaderUrl","fetchAndDecode","unwrapSingleFetchResults","stripIndexParam","indexValuesToKeep","indexValue","toKeep","singleFetchUrl","reqUrl","decodeViaTurboStream","global","plugins","_len","arguments","_key","Constructor","unwrapSingleFetchResult","RemixErrorBoundary","RemixRootDefaultErrorBoundary","isOutsideRemixApp","errorInstance","heyDeveloper","BoundaryShell","title","fontSize","errorString","background","color","overflow","_routeModules$root","renderScripts","useFrameworkContext","root","Layout","lang","charSet","content","fontFamily","Scripts","RemixRootDefaultHydrateFallback","groupRoutesByParentId","parentId","getRouteComponents","getRouteModuleComponent","createServerRoutes","routesByParentId","spaModeLazyPromise","dataRoute","hasClientLoader","preventInvalidServerHandlerCall","msg","hasAction","noActionDefinedError","article","createClientRoutes","initialState","needsRevalidation","fetchServerHandler","singleFetch","fetchServerLoader","fetchServerAction","prefetchStylesAndCallHandler","cachedModule","linkPrefetchPromise","_initialState$loaderD","_initialState$errors","_routeModule$clientLo","wrapShouldRevalidateForHdr","hasInitialData","initialData","hasInitialError","initialError","isHydrationRequest","clientLoader","shouldHydrateRouteLoader","clientAction","serverAction","hasClientAction","mod","loadRouteModuleWithBlockingLinks","args","serverLoader","routeShouldRevalidate","handledRevalidation","default","nextPaths","discoveredPaths","isFogOfWarEnabled","fetchAndApplyManifestPatches","manifestPath","version","ok","serverPatches","knownRoutes","patches","p","queue","next","addToFifoQueue","parentIds","useDataRouterStateContext","FrameworkContext","composeEventHandlers","theirHandler","ourHandler","event","defaultPrevented","getActiveMatches","isHydrated","errorIdx","PrefetchPageLinks","dataLinkProps","_objectWithoutPropertiesLoose","_excluded","PrefetchPageLinksImpl","useKeyedPrefetchLinks","keyedPrefetchLinks","setKeyedPrefetchLinks","interrupted","getKeyedPrefetchLinks","linkProps","_excluded2","newMatchesForData","newMatchesForAssets","dataHrefs","routesParams","foundOptOutRoute","_routeModules$m$route","m2","moduleHrefs","manifestPatch","getModuleLinkHrefs","serverHandoffString","isStatic","routerMatches","enableFogOfWar","initialScripts","_manifest$hmr","contextScript","routeModulesScript","hmr","runtime","routeIds","initialRoutes","getPartialManifest","suppressHydrationWarning","routePreloads","crossOrigin","array","mergeRefs","refs","ref","__reactRouterVersion","parseHydrationData","__staticRouterHydrationData","deserializeErrors","serialized","__type","__subType","ErrorConstructor","HistoryRouter","Link","forwardRef","forwardedRef","absoluteHref","onClick","discover","prefetch","reloadDocument","isAbsolute","isExternal","targetUrl","shouldPrefetch","prefetchRef","prefetchHandlers","theirElementProps","frameworkContext","maybePrefetch","setMaybePrefetch","setShouldPrefetch","onFocus","onBlur","onMouseEnter","onMouseLeave","onTouchStart","observer","IntersectionObserver","isIntersecting","threshold","observe","disconnect","setTimeout","clearTimeout","setIntent","cancelIntent","usePrefetchBehavior","internalOnClick","useLinkClickHandler","NavLink","ariaCurrentProp","className","classNameProp","styleProp","routerState","useViewTransitionState","nextLocationPathname","endSlashPosition","isActive","isPending","renderProps","ariaCurrent","Form","onSubmit","_excluded3","useSubmit","useFormAction","preventDefault","submitter","nativeEvent","submitMethod","currentTarget","ScrollRestoration","_ref7","storageKey","_excluded4","remixContext","useScrollRestoration","ssrKey","userKey","restoreScroll","restoreKey","storedY","scrollTo","removeItem","SCROLL_RESTORATION_STORAGE_KEY","replaceProp","button","metaKey","altKey","ctrlKey","shiftKey","isModifiedEvent","shouldProcessLinkClick","fetcherId","UseSubmit","currentRouteId","UseRouteId","UseScrollRestoration","scrollRestoration","callback","capture","usePageHide","scrollY","disableScrollRestoration","getElementById","scrollIntoView","nextPath","StaticRouterProvider","getStatelessNavigator","fetchersContext","hydrateScript","serializeErrors","back","forward","createStaticRouter","_opts","encoded","processRoutes","entryRoute","encoder","TextEncoder","unsign","cookie","secret","lastIndexOf","encode","createKey","signature","byteString","Uint8Array","charCodeAt","byteStringToUint8Array","atob","crypto","subtle","verify","usages","importKey","createCookie","cookieOptions","_path$sameSite$cookie","sameSite","secrets","expires","warnOnceAboutExpiresCookie","isSigned","maxAge","Date","now","cookieHeader","parseOptions","cookies","unsignedValue","decodeData","decodeCookieValue","serialize","serializeOptions","btoa","chr","part","str","exec","fromCharCode","parseInt","myUnescape","encodeURIComponent","encodeData","sign","encodeCookieValue","isCookie","code","hex","myEscape","createEntryRouteModules","ServerMode","sanitizeError","serverMode","Development","sanitized","sanitizeErrors","serializeError","matchServerRoutes","isRedirectStatusCode","callRouteHandler","stripRoutesParam","duplex","createRoutes","createStaticHandlerDataRoutes","commonRoute","uint8array","ReadableStream","start","enqueue","close","createServerHandoffString","serverHandoff","globalDevServerHooksKey","getDevServerHooks","globalThis","getDocumentHeaders","build","errorHeaders","boundaryIdx","parentHeaders","includeErrorHeaders","includeErrorCookies","prependCookies","childHeaders","parentSetCookieString","splitCookiesString","SINGLE_FETCH_REDIRECT_STATUS","getSingleFetchDataStrategy","isActionDataRequest","loadRouteIds","getSingleFetchRedirect","encodeViaTurboStream","requestSignal","streamTimeout","timeoutId","Production","postPlugins","fromEntries","derive","Test","staticHandler","errorHandler","handleError","returnLastResortErrorResponse","flash","createSession","flashName","unset","createSessionStorage","cookieArg","createData","readData","updateData","deleteData","warnOnceAboutSigningSessionCookie","session","destroySession","_ref8","historyRef","criticalCss","keyedLinks","_matches","leafMeta","_match","routeMeta","metaProps","isValidMetaTag","Comp","_metaProps$charSet","charset","err","jsonPath","abortDelay","staticHandlerContext","serverHandoffStream","getReader","TextDecoder","staticNavigator","getRouter","singleFetchActionStrategy","singleFetchLoaderFetcherStrategy","routeDfds","routesLoadedPromise","d","singleFetchDfd","resolvePromise","__reactRouterHdrActive","singleFetchLoaderNavigationStrategy","_navigator$connection","connection","saveData","registerElement","fetchPatches","lazyPaths","querySelectorAll","debouncedFetchPatches","wait","debounce","MutationObserver","records","elements","addedNodes","node","nodeType","Node","ELEMENT_NODE","isElement","documentElement","subtree","childList","attributes","attributeFilter","getSession","serializedCookie","_session","substring","createRequestHandler","_build","loadContext","_build$basename","derived","_getDevServerHooks","processRequestError","manifestUrl","assets","routerJson","handleManifestRequest","handlerUrl","singleFetchMatches","handlerRequest","singleFetchResult","singleFetchAction","_URL$searchParams$get","singleFetchLoaders","resultHeaders","handleSingleFetchRequest","handleDataRequest","errorResponse","errorResponseToJson","handleResourceRequest","_getDevServerHooks2","getCriticalCss","entryContext","handleDocumentRequestFunction","errorForSecondRender","unwrapResponse","getStaticContextFromError","handleDocumentRequest","routerRef","remixContextRef","patched","routerCreateStaticHandler","originalPath","keyMatch","optional","param","redirectDocument","devServerHooks","when","confirm","UseActionData","UseLoaderData","_route$matches","UseFetcher","defaultKey","useId","setFetcherKey","load","submitImpl","FetcherForm","UseFetchers","UseRevalidator","UseRouteLoaderData","defaultInit","defaultSearchParamsRef","hasSetSearchParamsRef","locationSearch","defaultSearchParams","getSearchParamsForLocation","setSearchParams","nextInit","navigateOptions","newSearchParams"],"mappings":";;;;;;;;;;4kCAOYA,IAAAA,WAAAA,GAAM,OAANA,EAAM,IAAA,MAAN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