diff --git a/front-end/package-lock.json b/front-end/package-lock.json index a69b758a..ecdcaec3 100644 --- a/front-end/package-lock.json +++ b/front-end/package-lock.json @@ -9,7 +9,8 @@ "version": "0.0.0", "dependencies": { "react": "^18.2.0", - "react-dom": "^18.2.0" + "react-dom": "^18.2.0", + "react-router-dom": "^6.23.1" }, "devDependencies": { "@types/react": "^18.2.66", @@ -922,6 +923,14 @@ "node": ">= 8" } }, + "node_modules/@remix-run/router": { + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.16.1.tgz", + "integrity": "sha512-es2g3dq6Nb07iFxGk5GuHN20RwBZOsuDQN7izWIisUcv9r+d2C5jQxqmgkdebXgReWfiyUabcki6Fg77mSNrig==", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/@rollup/rollup-android-arm-eabi": { "version": "4.18.0", "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.18.0.tgz", @@ -3545,6 +3554,36 @@ "node": ">=0.10.0" } }, + "node_modules/react-router": { + "version": "6.23.1", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.23.1.tgz", + "integrity": "sha512-fzcOaRF69uvqbbM7OhvQyBTFDVrrGlsFdS3AL+1KfIBtGETibHzi3FkoTRyiDJnWNc2VxrfvR+657ROHjaNjqQ==", + "dependencies": { + "@remix-run/router": "1.16.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "react": ">=16.8" + } + }, + "node_modules/react-router-dom": { + "version": "6.23.1", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.23.1.tgz", + "integrity": "sha512-utP+K+aSTtEdbWpC+4gxhdlPFwuEfDKq8ZrPFU65bbRJY+l706qjR7yaidBpo3MSeA/fzwbXWbKBI6ftOnP3OQ==", + "dependencies": { + "@remix-run/router": "1.16.1", + "react-router": "6.23.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "react": ">=16.8", + "react-dom": ">=16.8" + } + }, "node_modules/reflect.getprototypeof": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.6.tgz", diff --git a/front-end/package.json b/front-end/package.json index 9881f779..2dc2f3a6 100644 --- a/front-end/package.json +++ b/front-end/package.json @@ -11,7 +11,8 @@ }, "dependencies": { "react": "^18.2.0", - "react-dom": "^18.2.0" + "react-dom": "^18.2.0", + "react-router-dom": "^6.23.1" }, "devDependencies": { "@types/react": "^18.2.66", diff --git a/front-end/src/Header.jsx b/front-end/src/Header.jsx index 97133a65..d3c8859c 100644 --- a/front-end/src/Header.jsx +++ b/front-end/src/Header.jsx @@ -1,4 +1,4 @@ -import {Link} from 'react-router-dom'; // //Add page routing using router dom +import {Link, Outlet} from 'react-router-dom'; // //Add page routing using router dom import cylcleLogo from './assets/CYCLE-logo.png'; import erasmusLogo from './assets/erasmus-plus-logo.jpg'; diff --git a/node_modules/.bin/loose-envify b/node_modules/.bin/loose-envify deleted file mode 100644 index 076f91b1..00000000 --- a/node_modules/.bin/loose-envify +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*|*MINGW*|*MSYS*) - if command -v cygpath > /dev/null 2>&1; then - basedir=`cygpath -w "$basedir"` - fi - ;; -esac - -if [ -x "$basedir/node" ]; then - exec "$basedir/node" "$basedir/../loose-envify/cli.js" "$@" -else - exec node "$basedir/../loose-envify/cli.js" "$@" -fi diff --git a/node_modules/.bin/loose-envify.cmd b/node_modules/.bin/loose-envify.cmd deleted file mode 100644 index 599576f9..00000000 --- a/node_modules/.bin/loose-envify.cmd +++ /dev/null @@ -1,17 +0,0 @@ -@ECHO off -GOTO start -:find_dp0 -SET dp0=%~dp0 -EXIT /b -:start -SETLOCAL -CALL :find_dp0 - -IF EXIST "%dp0%\node.exe" ( - SET "_prog=%dp0%\node.exe" -) ELSE ( - SET "_prog=node" - SET PATHEXT=%PATHEXT:;.JS;=;% -) - -endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\loose-envify\cli.js" %* diff --git a/node_modules/.bin/loose-envify.ps1 b/node_modules/.bin/loose-envify.ps1 deleted file mode 100644 index eb866fca..00000000 --- a/node_modules/.bin/loose-envify.ps1 +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env pwsh -$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent - -$exe="" -if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { - # Fix case when both the Windows and Linux builds of Node - # are installed in the same directory - $exe=".exe" -} -$ret=0 -if (Test-Path "$basedir/node$exe") { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "$basedir/node$exe" "$basedir/../loose-envify/cli.js" $args - } else { - & "$basedir/node$exe" "$basedir/../loose-envify/cli.js" $args - } - $ret=$LASTEXITCODE -} else { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "node$exe" "$basedir/../loose-envify/cli.js" $args - } else { - & "node$exe" "$basedir/../loose-envify/cli.js" $args - } - $ret=$LASTEXITCODE -} -exit $ret diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json deleted file mode 100644 index e5b349e5..00000000 --- a/node_modules/.package-lock.json +++ /dev/null @@ -1,97 +0,0 @@ -{ - "name": "e20-co200-Erasmus-plus-Project-Web-and-MIS", - "lockfileVersion": 3, - "requires": true, - "packages": { - "node_modules/@remix-run/router": { - "version": "1.16.1", - "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.16.1.tgz", - "integrity": "sha512-es2g3dq6Nb07iFxGk5GuHN20RwBZOsuDQN7izWIisUcv9r+d2C5jQxqmgkdebXgReWfiyUabcki6Fg77mSNrig==", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "peer": true - }, - "node_modules/loose-envify": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", - "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", - "peer": true, - "dependencies": { - "js-tokens": "^3.0.0 || ^4.0.0" - }, - "bin": { - "loose-envify": "cli.js" - } - }, - "node_modules/react": { - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", - "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", - "peer": true, - "dependencies": { - "loose-envify": "^1.1.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/react-dom": { - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", - "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", - "peer": true, - "dependencies": { - "loose-envify": "^1.1.0", - "scheduler": "^0.23.2" - }, - "peerDependencies": { - "react": "^18.3.1" - } - }, - "node_modules/react-router": { - "version": "6.23.1", - "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.23.1.tgz", - "integrity": "sha512-fzcOaRF69uvqbbM7OhvQyBTFDVrrGlsFdS3AL+1KfIBtGETibHzi3FkoTRyiDJnWNc2VxrfvR+657ROHjaNjqQ==", - "dependencies": { - "@remix-run/router": "1.16.1" - }, - "engines": { - "node": ">=14.0.0" - }, - "peerDependencies": { - "react": ">=16.8" - } - }, - "node_modules/react-router-dom": { - "version": "6.23.1", - "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.23.1.tgz", - "integrity": "sha512-utP+K+aSTtEdbWpC+4gxhdlPFwuEfDKq8ZrPFU65bbRJY+l706qjR7yaidBpo3MSeA/fzwbXWbKBI6ftOnP3OQ==", - "dependencies": { - "@remix-run/router": "1.16.1", - "react-router": "6.23.1" - }, - "engines": { - "node": ">=14.0.0" - }, - "peerDependencies": { - "react": ">=16.8", - "react-dom": ">=16.8" - } - }, - "node_modules/scheduler": { - "version": "0.23.2", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", - "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", - "peer": true, - "dependencies": { - "loose-envify": "^1.1.0" - } - } - } -} diff --git a/node_modules/@remix-run/router/CHANGELOG.md b/node_modules/@remix-run/router/CHANGELOG.md deleted file mode 100644 index 32ebe56d..00000000 --- a/node_modules/@remix-run/router/CHANGELOG.md +++ /dev/null @@ -1,738 +0,0 @@ -# `@remix-run/router` - -## 1.16.1 - -### Patch Changes - -- Support `unstable_dataStrategy` on `staticHandler.queryRoute` ([#11515](https://github.com/remix-run/react-router/pull/11515)) - -## 1.16.0 - -### Minor Changes - -- Add a new `unstable_dataStrategy` configuration option ([#11098](https://github.com/remix-run/react-router/pull/11098)) - - This option allows Data Router applications to take control over the approach for executing route loaders and actions - - The default implementation is today's behavior, to fetch all loaders in parallel, but this option allows users to implement more advanced data flows including Remix single-fetch, middleware/context APIs, automatic loader caching, and more -- Move `unstable_dataStrategy` from `createStaticHandler` to `staticHandler.query` so it can be request-specific for use with the `ResponseStub` approach in Remix. It's not really applicable to `queryRoute` for now since that's a singular handler call anyway so any pre-processing/post/processing could be done there manually. ([#11377](https://github.com/remix-run/react-router/pull/11377)) -- Add a new `future.unstable_skipActionRevalidation` future flag ([#11098](https://github.com/remix-run/react-router/pull/11098)) - - Currently, active loaders revalidate after any action, regardless of the result - - With this flag enabled, actions that return/throw a 4xx/5xx response status will no longer automatically revalidate - - This should reduce load on your server since it's rare that a 4xx/5xx should actually mutate any data - - If you need to revalidate after a 4xx/5xx result with this flag enabled, you can still do that via returning `true` from `shouldRevalidate` - - `shouldRevalidate` now also receives a new `unstable_actionStatus` argument alongside `actionResult` so you can make decision based on the status of the `action` response without having to encode it into the action data -- Added a `skipLoaderErrorBubbling` flag to `staticHandler.query` to disable error bubbling on loader executions for single-fetch scenarios where the client-side router will handle the bubbling ([#11098](https://github.com/remix-run/react-router/pull/11098)) - -## 1.15.3 - -### Patch Changes - -- Fix a `future.v7_partialHydration` bug that would re-run loaders below the boundary on hydration if SSR loader errors bubbled to a parent boundary ([#11324](https://github.com/remix-run/react-router/pull/11324)) -- Fix a `future.v7_partialHydration` bug that would consider the router uninitialized if a route did not have a loader ([#11325](https://github.com/remix-run/react-router/pull/11325)) - -## 1.15.2 - -### Patch Changes - -- Preserve hydrated errors during partial hydration runs ([#11305](https://github.com/remix-run/react-router/pull/11305)) - -## 1.15.1 - -### Patch Changes - -- Fix encoding/decoding issues with pre-encoded dynamic parameter values ([#11199](https://github.com/remix-run/react-router/pull/11199)) - -## 1.15.0 - -### Minor Changes - -- Add a `createStaticHandler` `future.v7_throwAbortReason` flag to throw `request.signal.reason` (defaults to a `DOMException`) when a request is aborted instead of an `Error` such as `new Error("query() call aborted: GET /path")` ([#11104](https://github.com/remix-run/react-router/pull/11104)) - - - Please note that `DOMException` was added in Node v17 so you will not get a `DOMException` on Node 16 and below. - -### Patch Changes - -- Respect the `ErrorResponse` status code if passed to `getStaticContextFormError` ([#11213](https://github.com/remix-run/react-router/pull/11213)) - -## 1.14.2 - -### Patch Changes - -- Fix bug where dashes were not picked up in dynamic parameter names ([#11160](https://github.com/remix-run/react-router/pull/11160)) -- Do not attempt to deserialize empty JSON responses ([#11164](https://github.com/remix-run/react-router/pull/11164)) - -## 1.14.1 - -### Patch Changes - -- Fix bug with `route.lazy` not working correctly on initial SPA load when `v7_partialHydration` is specified ([#11121](https://github.com/remix-run/react-router/pull/11121)) -- Fix bug preventing revalidation from occurring for persisted fetchers unmounted during the `submitting` phase ([#11102](https://github.com/remix-run/react-router/pull/11102)) -- De-dup relative path logic in `resolveTo` ([#11097](https://github.com/remix-run/react-router/pull/11097)) - -## 1.14.0 - -### Minor Changes - -- Added a new `future.v7_partialHydration` future flag that enables partial hydration of a data router when Server-Side Rendering. This allows you to provide `hydrationData.loaderData` that has values for _some_ initially matched route loaders, but not all. When this flag is enabled, the router will call `loader` functions for routes that do not have hydration loader data during `router.initialize()`, and it will render down to the deepest provided `HydrateFallback` (up to the first route without hydration data) while it executes the unhydrated routes. ([#11033](https://github.com/remix-run/react-router/pull/11033)) - - For example, the following router has a `root` and `index` route, but only provided `hydrationData.loaderData` for the `root` route. Because the `index` route has a `loader`, we need to run that during initialization. With `future.v7_partialHydration` specified, `` will render the `RootComponent` (because it has data) and then the `IndexFallback` (since it does not have data). Once `indexLoader` finishes, application will update and display `IndexComponent`. - - ```jsx - let router = createBrowserRouter( - [ - { - id: "root", - path: "/", - loader: rootLoader, - Component: RootComponent, - Fallback: RootFallback, - children: [ - { - id: "index", - index: true, - loader: indexLoader, - Component: IndexComponent, - HydrateFallback: IndexFallback, - }, - ], - }, - ], - { - future: { - v7_partialHydration: true, - }, - hydrationData: { - loaderData: { - root: { message: "Hydrated from Root!" }, - }, - }, - } - ); - ``` - - If the above example did not have an `IndexFallback`, then `RouterProvider` would instead render the `RootFallback` while it executed the `indexLoader`. - - **Note:** When `future.v7_partialHydration` is provided, the `` prop is ignored since you can move it to a `Fallback` on your top-most route. The `fallbackElement` prop will be removed in React Router v7 when `v7_partialHydration` behavior becomes the standard behavior. - -- Add a new `future.v7_relativeSplatPath` flag to implement a breaking bug fix to relative routing when inside a splat route. ([#11087](https://github.com/remix-run/react-router/pull/11087)) - - This fix was originally added in [#10983](https://github.com/remix-run/react-router/issues/10983) and was later reverted in [#11078](https://github.com/remix-run/react-router/pull/11078) because it was determined that a large number of existing applications were relying on the buggy behavior (see [#11052](https://github.com/remix-run/react-router/issues/11052)) - - **The Bug** - The buggy behavior is that without this flag, the default behavior when resolving relative paths is to _ignore_ any splat (`*`) portion of the current route path. - - **The Background** - This decision was originally made thinking that it would make the concept of nested different sections of your apps in `` easier if relative routing would _replace_ the current splat: - - ```jsx - - - } /> - } /> - - - ``` - - Any paths like `/dashboard`, `/dashboard/team`, `/dashboard/projects` will match the `Dashboard` route. The dashboard component itself can then render nested ``: - - ```jsx - function Dashboard() { - return ( -
-

Dashboard

- - - - } /> - } /> - } /> - -
- ); - } - ``` - - Now, all links and route paths are relative to the router above them. This makes code splitting and compartmentalizing your app really easy. You could render the `Dashboard` as its own independent app, or embed it into your large app without making any changes to it. - - **The Problem** - - The problem is that this concept of ignoring part of a path breaks a lot of other assumptions in React Router - namely that `"."` always means the current location pathname for that route. When we ignore the splat portion, we start getting invalid paths when using `"."`: - - ```jsx - // If we are on URL /dashboard/team, and we want to link to /dashboard/team: - function DashboardTeam() { - // ❌ This is broken and results in - return A broken link to the Current URL; - - // ✅ This is fixed but super unintuitive since we're already at /dashboard/team! - return A broken link to the Current URL; - } - ``` - - We've also introduced an issue that we can no longer move our `DashboardTeam` component around our route hierarchy easily - since it behaves differently if we're underneath a non-splat route, such as `/dashboard/:widget`. Now, our `"."` links will, properly point to ourself _inclusive of the dynamic param value_ so behavior will break from it's corresponding usage in a `/dashboard/*` route. - - Even worse, consider a nested splat route configuration: - - ```jsx - - - - } /> - - - - ``` - - Now, a `` and a `` inside the `Dashboard` component go to the same place! That is definitely not correct! - - Another common issue arose in Data Routers (and Remix) where any `
` should post to it's own route `action` if you the user doesn't specify a form action: - - ```jsx - let router = createBrowserRouter({ - path: "/dashboard", - children: [ - { - path: "*", - action: dashboardAction, - Component() { - // ❌ This form is broken! It throws a 405 error when it submits because - // it tries to submit to /dashboard (without the splat value) and the parent - // `/dashboard` route doesn't have an action - return ...
; - }, - }, - ], - }); - ``` - - This is just a compounded issue from the above because the default location for a `Form` to submit to is itself (`"."`) - and if we ignore the splat portion, that now resolves to the parent route. - - **The Solution** - If you are leveraging this behavior, it's recommended to enable the future flag, move your splat to it's own route, and leverage `../` for any links to "sibling" pages: - - ```jsx - - - - } /> - - - - - function Dashboard() { - return ( -
-

Dashboard

- - - - } /> - } /> - } /> - -
- ); - } - ``` - - This way, `.` means "the full current pathname for my route" in all cases (including static, dynamic, and splat routes) and `..` always means "my parents pathname". - -### Patch Changes - -- Catch and bubble errors thrown when trying to unwrap responses from `loader`/`action` functions ([#11061](https://github.com/remix-run/react-router/pull/11061)) -- Fix `relative="path"` issue when rendering `Link`/`NavLink` outside of matched routes ([#11062](https://github.com/remix-run/react-router/pull/11062)) - -## 1.13.1 - -### Patch Changes - -- Revert the `useResolvedPath` fix for splat routes due to a large number of applications that were relying on the buggy behavior (see ). We plan to re-introduce this fix behind a future flag in the next minor version. ([#11078](https://github.com/remix-run/react-router/pull/11078)) - -## 1.13.0 - -### Minor Changes - -- Export the `PathParam` type from the public API ([#10719](https://github.com/remix-run/react-router/pull/10719)) - -### Patch Changes - -- Fix bug with `resolveTo` in splat routes ([#11045](https://github.com/remix-run/react-router/pull/11045)) - - This is a follow up to [#10983](https://github.com/remix-run/react-router/pull/10983) to handle the few other code paths using `getPathContributingMatches` - - This removes the `UNSAFE_getPathContributingMatches` export from `@remix-run/router` since we no longer need this in the `react-router`/`react-router-dom` layers -- Do not revalidate unmounted fetchers when `v7_fetcherPersist` is enabled ([#11044](https://github.com/remix-run/react-router/pull/11044)) - -## 1.12.0 - -### Minor Changes - -- Add `unstable_flushSync` option to `router.navigate` and `router.fetch` to tell the React Router layer to opt-out of `React.startTransition` and into `ReactDOM.flushSync` for state updates ([#11005](https://github.com/remix-run/react-router/pull/11005)) - -### Patch Changes - -- Fix `relative="path"` bug where relative path calculations started from the full location pathname, instead of from the current contextual route pathname. ([#11006](https://github.com/remix-run/react-router/pull/11006)) - - ```jsx - - }> - - - ; - - function Component() { - return ( - <> - {/* This is now correctly relative to /a/b, not /a/b/c */} - - - - ); - } - ``` - -## 1.11.0 - -### Minor Changes - -- Add a new `future.v7_fetcherPersist` flag to the `@remix-run/router` to change the persistence behavior of fetchers when `router.deleteFetcher` is called. Instead of being immediately cleaned up, fetchers will persist until they return to an `idle` state ([RFC](https://github.com/remix-run/remix/discussions/7698)) ([#10962](https://github.com/remix-run/react-router/pull/10962)) - - - This is sort of a long-standing bug fix as the `useFetchers()` API was always supposed to only reflect **in-flight** fetcher information for pending/optimistic UI -- it was not intended to reflect fetcher data or hang onto fetchers after they returned to an `idle` state - - Keep an eye out for the following specific behavioral changes when opting into this flag and check your app for compatibility: - - Fetchers that complete _while still mounted_ will no longer appear in `useFetchers()`. They served effectively no purpose in there since you can access the data via `useFetcher().data`). - - Fetchers that previously unmounted _while in-flight_ will not be immediately aborted and will instead be cleaned up once they return to an `idle` state. They will remain exposed via `useFetchers` while in-flight so you can still access pending/optimistic data after unmount. - -- When `v7_fetcherPersist` is enabled, the router now performs ref-counting on fetcher keys via `getFetcher`/`deleteFetcher` so it knows when a given fetcher is totally unmounted from the UI ([#10977](https://github.com/remix-run/react-router/pull/10977)) - - - Once a fetcher has been totally unmounted, we can ignore post-processing of a persisted fetcher result such as a redirect or an error - - The router will also pass a new `deletedFetchers` array to the subscriber callbacks so that the UI layer can remove associated fetcher data - -- Add support for optional path segments in `matchPath` ([#10768](https://github.com/remix-run/react-router/pull/10768)) - -### Patch Changes - -- Fix `router.getFetcher`/`router.deleteFetcher` type definitions which incorrectly specified `key` as an optional parameter ([#10960](https://github.com/remix-run/react-router/pull/10960)) - -## 1.10.0 - -### Minor Changes - -- Add experimental support for the [View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/ViewTransition) by allowing users to opt-into view transitions on navigations via the new `unstable_viewTransition` option to `router.navigate` ([#10916](https://github.com/remix-run/react-router/pull/10916)) - -### Patch Changes - -- Allow 404 detection to leverage root route error boundary if path contains a URL segment ([#10852](https://github.com/remix-run/react-router/pull/10852)) -- Fix `ErrorResponse` type to avoid leaking internal field ([#10876](https://github.com/remix-run/react-router/pull/10876)) - -## 1.9.0 - -### Minor Changes - -- In order to move towards stricter TypeScript support in the future, we're aiming to replace current usages of `any` with `unknown` on exposed typings for user-provided data. To do this in Remix v2 without introducing breaking changes in React Router v6, we have added generics to a number of shared types. These continue to default to `any` in React Router and are overridden with `unknown` in Remix. In React Router v7 we plan to move these to `unknown` as a breaking change. ([#10843](https://github.com/remix-run/react-router/pull/10843)) - - `Location` now accepts a generic for the `location.state` value - - `ActionFunctionArgs`/`ActionFunction`/`LoaderFunctionArgs`/`LoaderFunction` now accept a generic for the `context` parameter (only used in SSR usages via `createStaticHandler`) - - The return type of `useMatches` (now exported as `UIMatch`) accepts generics for `match.data` and `match.handle` - both of which were already set to `unknown` -- Move the `@private` class export `ErrorResponse` to an `UNSAFE_ErrorResponseImpl` export since it is an implementation detail and there should be no construction of `ErrorResponse` instances in userland. This frees us up to export a `type ErrorResponse` which correlates to an instance of the class via `InstanceType`. Userland code should only ever be using `ErrorResponse` as a type and should be type-narrowing via `isRouteErrorResponse`. ([#10811](https://github.com/remix-run/react-router/pull/10811)) -- Export `ShouldRevalidateFunctionArgs` interface ([#10797](https://github.com/remix-run/react-router/pull/10797)) -- Removed private/internal APIs only required for the Remix v1 backwards compatibility layer and no longer needed in Remix v2 (`_isFetchActionRedirect`, `_hasFetcherDoneAnything`) ([#10715](https://github.com/remix-run/react-router/pull/10715)) - -### Patch Changes - -- Add method/url to error message on aborted `query`/`queryRoute` calls ([#10793](https://github.com/remix-run/react-router/pull/10793)) -- Fix a race-condition with loader/action-thrown errors on `route.lazy` routes ([#10778](https://github.com/remix-run/react-router/pull/10778)) -- Fix type for `actionResult` on the arguments object passed to `shouldRevalidate` ([#10779](https://github.com/remix-run/react-router/pull/10779)) - -## 1.8.0 - -### Minor Changes - -- Add's a new `redirectDocument()` function which allows users to specify that a redirect from a `loader`/`action` should trigger a document reload (via `window.location`) instead of attempting to navigate to the redirected location via React Router ([#10705](https://github.com/remix-run/react-router/pull/10705)) - -### Patch Changes - -- Fix an issue in `queryRoute` that was not always identifying thrown `Response` instances ([#10717](https://github.com/remix-run/react-router/pull/10717)) -- Ensure hash history always includes a leading slash on hash pathnames ([#10753](https://github.com/remix-run/react-router/pull/10753)) - -## 1.7.2 - -### Patch Changes - -- Trigger an error if a `defer` promise resolves/rejects with `undefined` in order to match the behavior of loaders and actions which must return a value or `null` ([#10690](https://github.com/remix-run/react-router/pull/10690)) -- Properly handle fetcher redirects interrupted by normal navigations ([#10674](https://github.com/remix-run/react-router/pull/10674), [#10709](https://github.com/remix-run/react-router/pull/10709)) -- Initial-load fetchers should not automatically revalidate on GET navigations ([#10688](https://github.com/remix-run/react-router/pull/10688)) -- Enhance the return type of `Route.lazy` to prohibit returning an empty object ([#10634](https://github.com/remix-run/react-router/pull/10634)) - -## 1.7.1 - -### Patch Changes - -- Fix issues with reused blockers on subsequent navigations ([#10656](https://github.com/remix-run/react-router/pull/10656)) - -## 1.7.0 - -### Minor Changes - -- Add support for `application/json` and `text/plain` encodings for `router.navigate`/`router.fetch` submissions. To leverage these encodings, pass your data in a `body` parameter and specify the desired `formEncType`: ([#10413](https://github.com/remix-run/react-router/pull/10413)) - - ```js - // By default, the encoding is "application/x-www-form-urlencoded" - router.navigate("/", { - formMethod: "post", - body: { key: "value" }, - }); - - async function action({ request }) { - // await request.formData() => FormData instance with entry [key=value] - } - ``` - - ```js - // Pass `formEncType` to opt-into a different encoding (json) - router.navigate("/", { - formMethod: "post", - formEncType: "application/json", - body: { key: "value" }, - }); - - async function action({ request }) { - // await request.json() => { key: "value" } - } - ``` - - ```js - // Pass `formEncType` to opt-into a different encoding (text) - router.navigate("/", { - formMethod: "post", - formEncType: "text/plain", - body: "Text submission", - }); - - async function action({ request }) { - // await request.text() => "Text submission" - } - ``` - -### Patch Changes - -- Call `window.history.pushState/replaceState` before updating React Router state (instead of after) so that `window.location` matches `useLocation` during synchronous React 17 rendering ([#10448](https://github.com/remix-run/react-router/pull/10448)) - - ⚠️ However, generally apps should not be relying on `window.location` and should always reference `useLocation` when possible, as `window.location` will not be in sync 100% of the time (due to `popstate` events, concurrent mode, etc.) -- Strip `basename` from the `location` provided to `` to match the `useLocation` behavior ([#10550](https://github.com/remix-run/react-router/pull/10550)) -- Avoid calling `shouldRevalidate` for fetchers that have not yet completed a data load ([#10623](https://github.com/remix-run/react-router/pull/10623)) -- Fix `unstable_useBlocker` key issues in `StrictMode` ([#10573](https://github.com/remix-run/react-router/pull/10573)) -- Upgrade `typescript` to 5.1 ([#10581](https://github.com/remix-run/react-router/pull/10581)) - -## 1.6.3 - -### Patch Changes - -- Allow fetcher revalidations to complete if submitting fetcher is deleted ([#10535](https://github.com/remix-run/react-router/pull/10535)) -- Re-throw `DOMException` (`DataCloneError`) when attempting to perform a `PUSH` navigation with non-serializable state. ([#10427](https://github.com/remix-run/react-router/pull/10427)) -- Ensure revalidations happen when hash is present ([#10516](https://github.com/remix-run/react-router/pull/10516)) -- upgrade jest and jsdom ([#10453](https://github.com/remix-run/react-router/pull/10453)) - -## 1.6.2 - -### Patch Changes - -- Fix HMR-driven error boundaries by properly reconstructing new routes and `manifest` in `\_internalSetRoutes` ([#10437](https://github.com/remix-run/react-router/pull/10437)) -- Fix bug where initial data load would not kick off when hash is present ([#10493](https://github.com/remix-run/react-router/pull/10493)) - -## 1.6.1 - -### Patch Changes - -- Fix `basename` handling when navigating without a path ([#10433](https://github.com/remix-run/react-router/pull/10433)) -- "Same hash" navigations no longer re-run loaders to match browser behavior (i.e. `/path#hash -> /path#hash`) ([#10408](https://github.com/remix-run/react-router/pull/10408)) - -## 1.6.0 - -### Minor Changes - -- Enable relative routing in the `@remix-run/router` when providing a source route ID from which the path is relative to: ([#10336](https://github.com/remix-run/react-router/pull/10336)) - - - Example: `router.navigate("../path", { fromRouteId: "some-route" })`. - - This also applies to `router.fetch` which already receives a source route ID - -- Introduce a new `@remix-run/router` `future.v7_prependBasename` flag to enable `basename` prefixing to all paths coming into `router.navigate` and `router.fetch`. - - - Previously the `basename` was prepended in the React Router layer, but now that relative routing is being handled by the router we need prepend the `basename` _after_ resolving any relative paths - - This also enables `basename` support in `useFetcher` as well - -### Patch Changes - -- Enhance `LoaderFunction`/`ActionFunction` return type to prevent `undefined` from being a valid return value ([#10267](https://github.com/remix-run/react-router/pull/10267)) -- Ensure proper 404 error on `fetcher.load` call to a route without a `loader` ([#10345](https://github.com/remix-run/react-router/pull/10345)) -- Deprecate the `createRouter` `detectErrorBoundary` option in favor of the new `mapRouteProperties` option for converting a framework-agnostic route to a framework-aware route. This allows us to set more than just the `hasErrorBoundary` property during route pre-processing, and is now used for mapping `Component -> element` and `ErrorBoundary -> errorElement` in `react-router`. ([#10287](https://github.com/remix-run/react-router/pull/10287)) -- Fixed a bug where fetchers were incorrectly attempting to revalidate on search params changes or routing to the same URL (using the same logic for route `loader` revalidations). However, since fetchers have a static href, they should only revalidate on `action` submissions or `router.revalidate` calls. ([#10344](https://github.com/remix-run/react-router/pull/10344)) -- Decouple `AbortController` usage between revalidating fetchers and the thing that triggered them such that the unmount/deletion of a revalidating fetcher doesn't impact the ongoing triggering navigation/revalidation ([#10271](https://github.com/remix-run/react-router/pull/10271)) - -## 1.5.0 - -### Minor Changes - -- Added support for [**Future Flags**](https://reactrouter.com/en/main/guides/api-development-strategy) in React Router. The first flag being introduced is `future.v7_normalizeFormMethod` which will normalize the exposed `useNavigation()/useFetcher()` `formMethod` fields as uppercase HTTP methods to align with the `fetch()` behavior. ([#10207](https://github.com/remix-run/react-router/pull/10207)) - - - When `future.v7_normalizeFormMethod === false` (default v6 behavior), - - `useNavigation().formMethod` is lowercase - - `useFetcher().formMethod` is lowercase - - When `future.v7_normalizeFormMethod === true`: - - `useNavigation().formMethod` is uppercase - - `useFetcher().formMethod` is uppercase - -### Patch Changes - -- Provide fetcher submission to `shouldRevalidate` if the fetcher action redirects ([#10208](https://github.com/remix-run/react-router/pull/10208)) -- Properly handle `lazy()` errors during router initialization ([#10201](https://github.com/remix-run/react-router/pull/10201)) -- Remove `instanceof` check for `DeferredData` to be resilient to ESM/CJS boundaries in SSR bundling scenarios ([#10247](https://github.com/remix-run/react-router/pull/10247)) -- Update to latest `@remix-run/web-fetch@4.3.3` ([#10216](https://github.com/remix-run/react-router/pull/10216)) - -## 1.4.0 - -### Minor Changes - -- **Introducing Lazy Route Modules!** ([#10045](https://github.com/remix-run/react-router/pull/10045)) - - In order to keep your application bundles small and support code-splitting of your routes, we've introduced a new `lazy()` route property. This is an async function that resolves the non-route-matching portions of your route definition (`loader`, `action`, `element`/`Component`, `errorElement`/`ErrorBoundary`, `shouldRevalidate`, `handle`). - - Lazy routes are resolved on initial load and during the `loading` or `submitting` phase of a navigation or fetcher call. You cannot lazily define route-matching properties (`path`, `index`, `children`) since we only execute your lazy route functions after we've matched known routes. - - Your `lazy` functions will typically return the result of a dynamic import. - - ```jsx - // In this example, we assume most folks land on the homepage so we include that - // in our critical-path bundle, but then we lazily load modules for /a and /b so - // they don't load until the user navigates to those routes - let routes = createRoutesFromElements( - }> - } /> - import("./a")} /> - import("./b")} /> - - ); - ``` - - Then in your lazy route modules, export the properties you want defined for the route: - - ```jsx - export async function loader({ request }) { - let data = await fetchData(request); - return json(data); - } - - // Export a `Component` directly instead of needing to create a React Element from it - export function Component() { - let data = useLoaderData(); - - return ( - <> -

You made it!

-

{data}

- - ); - } - - // Export an `ErrorBoundary` directly instead of needing to create a React Element from it - export function ErrorBoundary() { - let error = useRouteError(); - return isRouteErrorResponse(error) ? ( -

- {error.status} {error.statusText} -

- ) : ( -

{error.message || error}

- ); - } - ``` - - An example of this in action can be found in the [`examples/lazy-loading-router-provider`](https://github.com/remix-run/react-router/tree/main/examples/lazy-loading-router-provider) directory of the repository. - - 🙌 Huge thanks to @rossipedia for the [Initial Proposal](https://github.com/remix-run/react-router/discussions/9826) and [POC Implementation](https://github.com/remix-run/react-router/pull/9830). - -### Patch Changes - -- Fix `generatePath` incorrectly applying parameters in some cases ([#10078](https://github.com/remix-run/react-router/pull/10078)) - -## 1.3.3 - -### Patch Changes - -- Correctly perform a hard redirect for same-origin absolute URLs outside of the router `basename` ([#10076](https://github.com/remix-run/react-router/pull/10076)) -- Ensure status code and headers are maintained for `defer` loader responses in `createStaticHandler`'s `query()` method ([#10077](https://github.com/remix-run/react-router/pull/10077)) -- Change `invariant` to an `UNSAFE_invariant` export since it's only intended for internal use ([#10066](https://github.com/remix-run/react-router/pull/10066)) -- Add internal API for custom HMR implementations ([#9996](https://github.com/remix-run/react-router/pull/9996)) - -## 1.3.2 - -### Patch Changes - -- Remove inaccurate console warning for POP navigations and update active blocker logic ([#10030](https://github.com/remix-run/react-router/pull/10030)) -- Only check for differing origin on absolute URL redirects ([#10033](https://github.com/remix-run/react-router/pull/10033)) - -## 1.3.1 - -### Patch Changes - -- Fixes 2 separate issues for revalidating fetcher `shouldRevalidate` calls ([#9948](https://github.com/remix-run/react-router/pull/9948)) - - The `shouldRevalidate` function was only being called for _explicit_ revalidation scenarios (after a mutation, manual `useRevalidator` call, or an `X-Remix-Revalidate` header used for cookie setting in Remix). It was not properly being called on _implicit_ revalidation scenarios that also apply to navigation `loader` revalidation, such as a change in search params or clicking a link for the page we're already on. It's now correctly called in those additional scenarios. - - The parameters being passed were incorrect and inconsistent with one another since the `current*`/`next*` parameters reflected the static `fetcher.load` URL (and thus were identical). Instead, they should have reflected the the navigation that triggered the revalidation (as the `form*` parameters did). These parameters now correctly reflect the triggering navigation. -- Respect `preventScrollReset` on `` ([#9963](https://github.com/remix-run/react-router/pull/9963)) -- Do not short circuit on hash change only mutation submissions ([#9944](https://github.com/remix-run/react-router/pull/9944)) -- Remove `instanceof` check from `isRouteErrorResponse` to avoid bundling issues on the server ([#9930](https://github.com/remix-run/react-router/pull/9930)) -- Fix navigation for hash routers on manual URL changes ([#9980](https://github.com/remix-run/react-router/pull/9980)) -- Detect when a `defer` call only contains critical data and remove the `AbortController` ([#9965](https://github.com/remix-run/react-router/pull/9965)) -- Send the name as the value when url-encoding `File` `FormData` entries ([#9867](https://github.com/remix-run/react-router/pull/9867)) - -## 1.3.0 - -### Minor Changes - -- Added support for navigation blocking APIs ([#9709](https://github.com/remix-run/react-router/pull/9709)) -- Expose deferred information from `createStaticHandler` ([#9760](https://github.com/remix-run/react-router/pull/9760)) - -### Patch Changes - -- Improved absolute redirect url detection in actions/loaders ([#9829](https://github.com/remix-run/react-router/pull/9829)) -- Fix URL creation with memory histories ([#9814](https://github.com/remix-run/react-router/pull/9814)) -- Fix `generatePath` when optional params are present ([#9764](https://github.com/remix-run/react-router/pull/9764)) -- Fix scroll reset if a submission redirects ([#9886](https://github.com/remix-run/react-router/pull/9886)) -- Fix 404 bug with same-origin absolute redirects ([#9913](https://github.com/remix-run/react-router/pull/9913)) -- Support `OPTIONS` requests in `staticHandler.queryRoute` ([#9914](https://github.com/remix-run/react-router/pull/9914)) - -## 1.2.1 - -### Patch Changes - -- Include submission info in `shouldRevalidate` on action redirects ([#9777](https://github.com/remix-run/react-router/pull/9777), [#9782](https://github.com/remix-run/react-router/pull/9782)) -- Reset `actionData` on action redirect to current location ([#9772](https://github.com/remix-run/react-router/pull/9772)) - -## 1.2.0 - -### Minor Changes - -- Remove `unstable_` prefix from `createStaticHandler`/`createStaticRouter`/`StaticRouterProvider` ([#9738](https://github.com/remix-run/react-router/pull/9738)) - -### Patch Changes - -- Fix explicit `replace` on submissions and `PUSH` on submission to new paths ([#9734](https://github.com/remix-run/react-router/pull/9734)) -- Fix a few bugs where loader/action data wasn't properly cleared on errors ([#9735](https://github.com/remix-run/react-router/pull/9735)) -- Prevent `useLoaderData` usage in `errorElement` ([#9735](https://github.com/remix-run/react-router/pull/9735)) -- Skip initial scroll restoration for SSR apps with `hydrationData` ([#9664](https://github.com/remix-run/react-router/pull/9664)) - -## 1.1.0 - -This release introduces support for [Optional Route Segments](https://github.com/remix-run/react-router/issues/9546). Now, adding a `?` to the end of any path segment will make that entire segment optional. This works for both static segments and dynamic parameters. - -**Optional Params Examples** - -- Path `lang?/about` will match: - - `/:lang/about` - - `/about` -- Path `/multistep/:widget1?/widget2?/widget3?` will match: - - `/multistep` - - `/multistep/:widget1` - - `/multistep/:widget1/:widget2` - - `/multistep/:widget1/:widget2/:widget3` - -**Optional Static Segment Example** - -- Path `/home?` will match: - - `/` - - `/home` -- Path `/fr?/about` will match: - - `/about` - - `/fr/about` - -### Minor Changes - -- Allows optional routes and optional static segments ([#9650](https://github.com/remix-run/react-router/pull/9650)) - -### Patch Changes - -- Stop incorrectly matching on partial named parameters, i.e. ``, to align with how splat parameters work. If you were previously relying on this behavior then it's recommended to extract the static portion of the path at the `useParams` call site: ([#9506](https://github.com/remix-run/react-router/pull/9506)) - -```jsx -// Old behavior at URL /prefix-123 - }> - -function Comp() { - let params = useParams(); // { id: '123' } - let id = params.id; // "123" - ... -} - -// New behavior at URL /prefix-123 - }> - -function Comp() { - let params = useParams(); // { id: 'prefix-123' } - let id = params.id.replace(/^prefix-/, ''); // "123" - ... -} -``` - -- Persist `headers` on `loader` `request`'s after SSR document `action` request ([#9721](https://github.com/remix-run/react-router/pull/9721)) -- Fix requests sent to revalidating loaders so they reflect a GET request ([#9660](https://github.com/remix-run/react-router/pull/9660)) -- Fix issue with deeply nested optional segments ([#9727](https://github.com/remix-run/react-router/pull/9727)) -- GET forms now expose a submission on the loading navigation ([#9695](https://github.com/remix-run/react-router/pull/9695)) -- Fix error boundary tracking for multiple errors bubbling to the same boundary ([#9702](https://github.com/remix-run/react-router/pull/9702)) - -## 1.0.5 - -### Patch Changes - -- Fix requests sent to revalidating loaders so they reflect a `GET` request ([#9680](https://github.com/remix-run/react-router/pull/9680)) -- Remove `instanceof Response` checks in favor of `isResponse` ([#9690](https://github.com/remix-run/react-router/pull/9690)) -- Fix `URL` creation in Cloudflare Pages or other non-browser-environments ([#9682](https://github.com/remix-run/react-router/pull/9682), [#9689](https://github.com/remix-run/react-router/pull/9689)) -- Add `requestContext` support to static handler `query`/`queryRoute` ([#9696](https://github.com/remix-run/react-router/pull/9696)) - - Note that the unstable API of `queryRoute(path, routeId)` has been changed to `queryRoute(path, { routeId, requestContext })` - -## 1.0.4 - -### Patch Changes - -- Throw an error if an `action`/`loader` function returns `undefined` as revalidations need to know whether the loader has previously been executed. `undefined` also causes issues during SSR stringification for hydration. You should always ensure you `loader`/`action` returns a value, and you may return `null` if you don't wish to return anything. ([#9511](https://github.com/remix-run/react-router/pull/9511)) -- Properly handle redirects to external domains ([#9590](https://github.com/remix-run/react-router/pull/9590), [#9654](https://github.com/remix-run/react-router/pull/9654)) -- Preserve the HTTP method on 307/308 redirects ([#9597](https://github.com/remix-run/react-router/pull/9597)) -- Support `basename` in static data routers ([#9591](https://github.com/remix-run/react-router/pull/9591)) -- Enhanced `ErrorResponse` bodies to contain more descriptive text in internal 403/404/405 scenarios - -## 1.0.3 - -### Patch Changes - -- Fix hrefs generated when using `createHashRouter` ([#9409](https://github.com/remix-run/react-router/pull/9409)) -- fix encoding/matching issues with special chars ([#9477](https://github.com/remix-run/react-router/pull/9477), [#9496](https://github.com/remix-run/react-router/pull/9496)) -- Support `basename` and relative routing in `loader`/`action` redirects ([#9447](https://github.com/remix-run/react-router/pull/9447)) -- Ignore pathless layout routes when looking for proper submission `action` function ([#9455](https://github.com/remix-run/react-router/pull/9455)) -- properly support `index` routes with a `path` in `useResolvedPath` ([#9486](https://github.com/remix-run/react-router/pull/9486)) -- Add UMD build for `@remix-run/router` ([#9446](https://github.com/remix-run/react-router/pull/9446)) -- fix `createURL` in local file execution in Firefox ([#9464](https://github.com/remix-run/react-router/pull/9464)) -- Updates to `unstable_createStaticHandler` for incorporating into Remix ([#9482](https://github.com/remix-run/react-router/pull/9482), [#9465](https://github.com/remix-run/react-router/pull/9465)) - -## 1.0.2 - -### Patch Changes - -- Reset `actionData` after a successful action redirect ([#9334](https://github.com/remix-run/react-router/pull/9334)) -- Update `matchPath` to avoid false positives on dash-separated segments ([#9300](https://github.com/remix-run/react-router/pull/9300)) -- If an index route has children, it will result in a runtime error. We have strengthened our `RouteObject`/`RouteProps` types to surface the error in TypeScript. ([#9366](https://github.com/remix-run/react-router/pull/9366)) - -## 1.0.1 - -### Patch Changes - -- Preserve state from `initialEntries` ([#9288](https://github.com/remix-run/react-router/pull/9288)) -- Preserve `?index` for fetcher get submissions to index routes ([#9312](https://github.com/remix-run/react-router/pull/9312)) - -## 1.0.0 - -This is the first stable release of `@remix-run/router`, which provides all the underlying routing and data loading/mutation logic for `react-router`. You should _not_ be using this package directly unless you are authoring a routing library similar to `react-router`. - -For an overview of the features provided by `react-router`, we recommend you go check out the [docs](https://reactrouter.com), especially the [feature overview](https://reactrouter.com/start/overview) and the [tutorial](https://reactrouter.com/start/tutorial). - -For an overview of the features provided by `@remix-run/router`, please check out the [`README`](./README.md). diff --git a/node_modules/@remix-run/router/LICENSE.md b/node_modules/@remix-run/router/LICENSE.md deleted file mode 100644 index 7d0a32c3..00000000 --- a/node_modules/@remix-run/router/LICENSE.md +++ /dev/null @@ -1,23 +0,0 @@ -MIT License - -Copyright (c) React Training LLC 2015-2019 -Copyright (c) Remix Software Inc. 2020-2021 -Copyright (c) Shopify Inc. 2022-2023 - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/node_modules/@remix-run/router/README.md b/node_modules/@remix-run/router/README.md deleted file mode 100644 index 1c8536de..00000000 --- a/node_modules/@remix-run/router/README.md +++ /dev/null @@ -1,135 +0,0 @@ -# Remix Router - -The `@remix-run/router` package is a framework-agnostic routing package (sometimes referred to as a browser-emulator) that serves as the heart of [React Router][react-router] and [Remix][remix] and provides all the core functionality for routing coupled with data loading and data mutations. It comes with built-in handling of errors, race-conditions, interruptions, cancellations, lazy-loading data, and much, much more. - -If you're using React Router, you should never `import` anything directly from the `@remix-run/router` - you should have everything you need in `react-router-dom` (or `react-router`/`react-router-native` if you're not rendering in the browser). All of those packages should re-export everything you would otherwise need from `@remix-run/router`. - -> [!WARNING] -> -> This router is a low-level package intended to be consumed by UI layer routing libraries. You should very likely not be using this package directly unless you are authoring a routing library such as [`react-router-dom`][react-router-repo] or one of it's other [UI ports][remix-routers-repo]. - -## API - -A Router instance can be created using `createRouter`: - -```js -// Create and initialize a router. "initialize" contains all side effects -// including history listeners and kicking off the initial data fetch -let router = createRouter({ - // Required properties - routes: [{ - path: '/', - loader: ({ request, params }) => { /* ... */ }, - children: [{ - path: 'home', - loader: ({ request, params }) => { /* ... */ }, - }] - }, - history: createBrowserHistory(), - - // Optional properties - basename, // Base path - mapRouteProperties, // Map framework-agnostic routes to framework-aware routes - future, // Future flags - hydrationData, // Hydration data if using server-side-rendering -}).initialize(); -``` - -Internally, the Router represents the state in an object of the following format, which is available through `router.state`. You can also register a subscriber of the signature `(state: RouterState) => void` to execute when the state updates via `router.subscribe()`; - -```ts -interface RouterState { - // False during the initial data load, true once we have our initial data - initialized: boolean; - // The `history` action of the most recently completed navigation - historyAction: Action; - // The current location of the router. During a navigation this reflects - // the "old" location and is updated upon completion of the navigation - location: Location; - // The current set of route matches - matches: DataRouteMatch[]; - // The state of the current navigation - navigation: Navigation; - // The state of any in-progress router.revalidate() calls - revalidation: RevalidationState; - // Data from the loaders for the current matches - loaderData: RouteData; - // Data from the action for the current matches - actionData: RouteData | null; - // Errors thrown from loaders/actions for the current matches - errors: RouteData | null; - // Map of all active fetchers - fetchers: Map; - // Scroll position to restore to for the active Location, false if we - // should not restore, or null if we don't have a saved position - // Note: must be enabled via router.enableScrollRestoration() - restoreScrollPosition: number | false | null; - // Proxied `preventScrollReset` value passed to router.navigate() - preventScrollReset: boolean; -} -``` - -### Navigations - -All navigations are done through the `router.navigate` API which is overloaded to support different types of navigations: - -```js -// Link navigation (pushes onto the history stack by default) -router.navigate("/page"); - -// Link navigation (replacing the history stack) -router.navigate("/page", { replace: true }); - -// Pop navigation (moving backward/forward in the history stack) -router.navigate(-1); - -// Form submission navigation -let formData = new FormData(); -formData.append(key, value); -router.navigate("/page", { - formMethod: "post", - formData, -}); - -// Relative routing from a source routeId -router.navigate("../../somewhere", { - fromRouteId: "active-route-id", -}); -``` - -### Fetchers - -Fetchers are a mechanism to call loaders/actions without triggering a navigation, and are done through the `router.fetch()` API. All fetch calls require a unique key to identify the fetcher. - -```js -// Execute the loader for /page -router.fetch("key", "/page"); - -// Submit to the action for /page -let formData = new FormData(); -formData.append(key, value); -router.fetch("key", "/page", { - formMethod: "post", - formData, -}); -``` - -### Revalidation - -By default, active loaders will revalidate after any navigation or fetcher mutation. If you need to kick off a revalidation for other use-cases, you can use `router.revalidate()` to re-execute all active loaders. - -### Future Flags - -We use _Future Flags_ in the router to help us introduce breaking changes in an opt-in fashion ahead of major releases. Please check out the [blog post][future-flags-post] and [React Router Docs][api-development-strategy] for more information on this process. The currently available future flags in `@remix-run/router` are: - -| Flag | Description | -| ------------------------ | ------------------------------------------------------------------------- | -| `v7_normalizeFormMethod` | Normalize `useNavigation().formMethod` to be an uppercase HTTP Method | -| `v7_prependBasename` | Prepend the `basename` to incoming `router.navigate`/`router.fetch` paths | - -[react-router]: https://reactrouter.com -[remix]: https://remix.run -[react-router-repo]: https://github.com/remix-run/react-router -[remix-routers-repo]: https://github.com/brophdawg11/remix-routers -[api-development-strategy]: https://reactrouter.com/en/main/guides/api-development-strategy -[future-flags-post]: https://remix.run/blog/future-flags diff --git a/node_modules/@remix-run/router/dist/history.d.ts b/node_modules/@remix-run/router/dist/history.d.ts deleted file mode 100644 index bda67222..00000000 --- a/node_modules/@remix-run/router/dist/history.d.ts +++ /dev/null @@ -1,250 +0,0 @@ -/** - * Actions represent the type of change to a location value. - */ -export declare enum Action { - /** - * A POP indicates a change to an arbitrary index in the history stack, such - * as a back or forward navigation. It does not describe the direction of the - * navigation, only that the current index changed. - * - * Note: This is the default action for newly created history objects. - */ - Pop = "POP", - /** - * A PUSH indicates a new entry being added to the history stack, such as when - * a link is clicked and a new page loads. When this happens, all subsequent - * entries in the stack are lost. - */ - Push = "PUSH", - /** - * A REPLACE indicates the entry at the current index in the history stack - * being replaced by a new one. - */ - Replace = "REPLACE" -} -/** - * The pathname, search, and hash values of a URL. - */ -export interface Path { - /** - * A URL pathname, beginning with a /. - */ - pathname: string; - /** - * A URL search string, beginning with a ?. - */ - search: string; - /** - * A URL fragment identifier, beginning with a #. - */ - hash: string; -} -/** - * An entry in a history stack. A location contains information about the - * URL path, as well as possibly some arbitrary state and a key. - */ -export interface Location extends Path { - /** - * A value of arbitrary data associated with this location. - */ - state: State; - /** - * A unique string associated with this location. May be used to safely store - * and retrieve data in some other storage API, like `localStorage`. - * - * Note: This value is always "default" on the initial location. - */ - key: string; -} -/** - * A change to the current location. - */ -export interface Update { - /** - * The action that triggered the change. - */ - action: Action; - /** - * The new location. - */ - location: Location; - /** - * The delta between this location and the former location in the history stack - */ - delta: number | null; -} -/** - * A function that receives notifications about location changes. - */ -export interface Listener { - (update: Update): void; -} -/** - * Describes a location that is the destination of some navigation, either via - * `history.push` or `history.replace`. This may be either a URL or the pieces - * of a URL path. - */ -export type To = string | Partial; -/** - * A history is an interface to the navigation stack. The history serves as the - * source of truth for the current location, as well as provides a set of - * methods that may be used to change it. - * - * It is similar to the DOM's `window.history` object, but with a smaller, more - * focused API. - */ -export interface History { - /** - * The last action that modified the current location. This will always be - * Action.Pop when a history instance is first created. This value is mutable. - */ - readonly action: Action; - /** - * The current location. This value is mutable. - */ - readonly location: Location; - /** - * Returns a valid href for the given `to` value that may be used as - * the value of an
attribute. - * - * @param to - The destination URL - */ - createHref(to: To): string; - /** - * Returns a URL for the given `to` value - * - * @param to - The destination URL - */ - createURL(to: To): URL; - /** - * Encode a location the same way window.history would do (no-op for memory - * history) so we ensure our PUSH/REPLACE navigations for data routers - * behave the same as POP - * - * @param to Unencoded path - */ - encodeLocation(to: To): Path; - /** - * Pushes a new location onto the history stack, increasing its length by one. - * If there were any entries in the stack after the current one, they are - * lost. - * - * @param to - The new URL - * @param state - Data to associate with the new location - */ - push(to: To, state?: any): void; - /** - * Replaces the current location in the history stack with a new one. The - * location that was replaced will no longer be available. - * - * @param to - The new URL - * @param state - Data to associate with the new location - */ - replace(to: To, state?: any): void; - /** - * Navigates `n` entries backward/forward in the history stack relative to the - * current index. For example, a "back" navigation would use go(-1). - * - * @param delta - The delta in the stack index - */ - go(delta: number): void; - /** - * Sets up a listener that will be called whenever the current location - * changes. - * - * @param listener - A function that will be called when the location changes - * @returns unlisten - A function that may be used to stop listening - */ - listen(listener: Listener): () => void; -} -/** - * A user-supplied object that describes a location. Used when providing - * entries to `createMemoryHistory` via its `initialEntries` option. - */ -export type InitialEntry = string | Partial; -export type MemoryHistoryOptions = { - initialEntries?: InitialEntry[]; - initialIndex?: number; - v5Compat?: boolean; -}; -/** - * A memory history stores locations in memory. This is useful in stateful - * environments where there is no web browser, such as node tests or React - * Native. - */ -export interface MemoryHistory extends History { - /** - * The current index in the history stack. - */ - readonly index: number; -} -/** - * Memory history stores the current location in memory. It is designed for use - * in stateful non-browser environments like tests and React Native. - */ -export declare function createMemoryHistory(options?: MemoryHistoryOptions): MemoryHistory; -/** - * A browser history stores the current location in regular URLs in a web - * browser environment. This is the standard for most web apps and provides the - * cleanest URLs the browser's address bar. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory - */ -export interface BrowserHistory extends UrlHistory { -} -export type BrowserHistoryOptions = UrlHistoryOptions; -/** - * Browser history stores the location in regular URLs. This is the standard for - * most web apps, but it requires some configuration on the server to ensure you - * serve the same app at multiple URLs. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory - */ -export declare function createBrowserHistory(options?: BrowserHistoryOptions): BrowserHistory; -/** - * A hash history stores the current location in the fragment identifier portion - * of the URL in a web browser environment. - * - * This is ideal for apps that do not control the server for some reason - * (because the fragment identifier is never sent to the server), including some - * shared hosting environments that do not provide fine-grained controls over - * which pages are served at which URLs. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory - */ -export interface HashHistory extends UrlHistory { -} -export type HashHistoryOptions = UrlHistoryOptions; -/** - * Hash history stores the location in window.location.hash. This makes it ideal - * for situations where you don't want to send the location to the server for - * some reason, either because you do cannot configure it or the URL space is - * reserved for something else. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory - */ -export declare function createHashHistory(options?: HashHistoryOptions): HashHistory; -/** - * @private - */ -export declare function invariant(value: boolean, message?: string): asserts value; -export declare function invariant(value: T | null | undefined, message?: string): asserts value is T; -export declare function warning(cond: any, message: string): void; -/** - * Creates a Location object with a unique key from the given Path - */ -export declare function createLocation(current: string | Location, to: To, state?: any, key?: string): Readonly; -/** - * Creates a string URL path from the given pathname, search, and hash components. - */ -export declare function createPath({ pathname, search, hash, }: Partial): string; -/** - * Parses a string URL path into its separate pathname, search, and hash components. - */ -export declare function parsePath(path: string): Partial; -export interface UrlHistory extends History { -} -export type UrlHistoryOptions = { - window?: Window; - v5Compat?: boolean; -}; diff --git a/node_modules/@remix-run/router/dist/index.d.ts b/node_modules/@remix-run/router/dist/index.d.ts deleted file mode 100644 index 84b57c0b..00000000 --- a/node_modules/@remix-run/router/dist/index.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -export type { ActionFunction, ActionFunctionArgs, AgnosticDataIndexRouteObject, AgnosticDataNonIndexRouteObject, AgnosticDataRouteMatch, AgnosticDataRouteObject, AgnosticIndexRouteObject, AgnosticNonIndexRouteObject, AgnosticRouteMatch, AgnosticRouteObject, DataStrategyFunction as unstable_DataStrategyFunction, DataStrategyFunctionArgs as unstable_DataStrategyFunctionArgs, DataStrategyMatch as unstable_DataStrategyMatch, ErrorResponse, FormEncType, FormMethod, HandlerResult as unstable_HandlerResult, HTMLFormMethod, JsonFunction, LazyRouteFunction, LoaderFunction, LoaderFunctionArgs, ParamParseKey, Params, PathMatch, PathParam, PathPattern, RedirectFunction, ShouldRevalidateFunction, ShouldRevalidateFunctionArgs, TrackedPromise, UIMatch, V7_FormMethod, } from "./utils"; -export { AbortedDeferredError, defer, generatePath, getToPathname, isRouteErrorResponse, joinPaths, json, matchPath, matchRoutes, normalizePathname, redirect, redirectDocument, resolvePath, resolveTo, stripBasename, } from "./utils"; -export type { BrowserHistory, BrowserHistoryOptions, HashHistory, HashHistoryOptions, History, InitialEntry, Location, MemoryHistory, MemoryHistoryOptions, Path, To, } from "./history"; -export { Action, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, parsePath, } from "./history"; -export * from "./router"; -/** @internal */ -export type { RouteManifest as UNSAFE_RouteManifest } from "./utils"; -export { DeferredData as UNSAFE_DeferredData, ErrorResponseImpl as UNSAFE_ErrorResponseImpl, convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes, convertRouteMatchToUiMatch as UNSAFE_convertRouteMatchToUiMatch, getResolveToMatches as UNSAFE_getResolveToMatches, } from "./utils"; -export { invariant as UNSAFE_invariant, warning as UNSAFE_warning, } from "./history"; diff --git a/node_modules/@remix-run/router/dist/router.cjs.js b/node_modules/@remix-run/router/dist/router.cjs.js deleted file mode 100644 index 7c5abbb2..00000000 --- a/node_modules/@remix-run/router/dist/router.cjs.js +++ /dev/null @@ -1,5020 +0,0 @@ -/** - * @remix-run/router v1.16.1 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _extends() { - _extends = Object.assign ? Object.assign.bind() : function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - return target; - }; - return _extends.apply(this, arguments); -} - -//////////////////////////////////////////////////////////////////////////////// -//#region Types and Constants -//////////////////////////////////////////////////////////////////////////////// - -/** - * Actions represent the type of change to a location value. - */ -let Action = /*#__PURE__*/function (Action) { - Action["Pop"] = "POP"; - Action["Push"] = "PUSH"; - Action["Replace"] = "REPLACE"; - return Action; -}({}); - -/** - * The pathname, search, and hash values of a URL. - */ - -// TODO: (v7) Change the Location generic default from `any` to `unknown` and -// remove Remix `useLocation` wrapper. -/** - * An entry in a history stack. A location contains information about the - * URL path, as well as possibly some arbitrary state and a key. - */ -/** - * A change to the current location. - */ -/** - * A function that receives notifications about location changes. - */ -/** - * Describes a location that is the destination of some navigation, either via - * `history.push` or `history.replace`. This may be either a URL or the pieces - * of a URL path. - */ -/** - * A history is an interface to the navigation stack. The history serves as the - * source of truth for the current location, as well as provides a set of - * methods that may be used to change it. - * - * It is similar to the DOM's `window.history` object, but with a smaller, more - * focused API. - */ -const PopStateEventType = "popstate"; -//#endregion - -//////////////////////////////////////////////////////////////////////////////// -//#region Memory History -//////////////////////////////////////////////////////////////////////////////// - -/** - * A user-supplied object that describes a location. Used when providing - * entries to `createMemoryHistory` via its `initialEntries` option. - */ -/** - * A memory history stores locations in memory. This is useful in stateful - * environments where there is no web browser, such as node tests or React - * Native. - */ -/** - * Memory history stores the current location in memory. It is designed for use - * in stateful non-browser environments like tests and React Native. - */ -function createMemoryHistory(options) { - if (options === void 0) { - options = {}; - } - let { - initialEntries = ["/"], - initialIndex, - v5Compat = false - } = options; - let entries; // Declare so we can access from createMemoryLocation - entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : undefined)); - let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex); - let action = Action.Pop; - let listener = null; - function clampIndex(n) { - return Math.min(Math.max(n, 0), entries.length - 1); - } - function getCurrentLocation() { - return entries[index]; - } - function createMemoryLocation(to, state, key) { - if (state === void 0) { - state = null; - } - let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key); - warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to)); - return location; - } - function createHref(to) { - return typeof to === "string" ? to : createPath(to); - } - let history = { - get index() { - return index; - }, - get action() { - return action; - }, - get location() { - return getCurrentLocation(); - }, - createHref, - createURL(to) { - return new URL(createHref(to), "http://localhost"); - }, - encodeLocation(to) { - let path = typeof to === "string" ? parsePath(to) : to; - return { - pathname: path.pathname || "", - search: path.search || "", - hash: path.hash || "" - }; - }, - push(to, state) { - action = Action.Push; - let nextLocation = createMemoryLocation(to, state); - index += 1; - entries.splice(index, entries.length, nextLocation); - if (v5Compat && listener) { - listener({ - action, - location: nextLocation, - delta: 1 - }); - } - }, - replace(to, state) { - action = Action.Replace; - let nextLocation = createMemoryLocation(to, state); - entries[index] = nextLocation; - if (v5Compat && listener) { - listener({ - action, - location: nextLocation, - delta: 0 - }); - } - }, - go(delta) { - action = Action.Pop; - let nextIndex = clampIndex(index + delta); - let nextLocation = entries[nextIndex]; - index = nextIndex; - if (listener) { - listener({ - action, - location: nextLocation, - delta - }); - } - }, - listen(fn) { - listener = fn; - return () => { - listener = null; - }; - } - }; - return history; -} -//#endregion - -//////////////////////////////////////////////////////////////////////////////// -//#region Browser History -//////////////////////////////////////////////////////////////////////////////// - -/** - * A browser history stores the current location in regular URLs in a web - * browser environment. This is the standard for most web apps and provides the - * cleanest URLs the browser's address bar. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory - */ -/** - * Browser history stores the location in regular URLs. This is the standard for - * most web apps, but it requires some configuration on the server to ensure you - * serve the same app at multiple URLs. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory - */ -function createBrowserHistory(options) { - if (options === void 0) { - options = {}; - } - function createBrowserLocation(window, globalHistory) { - let { - pathname, - search, - hash - } = window.location; - return createLocation("", { - pathname, - search, - hash - }, - // state defaults to `null` because `window.history.state` does - globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default"); - } - function createBrowserHref(window, to) { - return typeof to === "string" ? to : createPath(to); - } - return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options); -} -//#endregion - -//////////////////////////////////////////////////////////////////////////////// -//#region Hash History -//////////////////////////////////////////////////////////////////////////////// - -/** - * A hash history stores the current location in the fragment identifier portion - * of the URL in a web browser environment. - * - * This is ideal for apps that do not control the server for some reason - * (because the fragment identifier is never sent to the server), including some - * shared hosting environments that do not provide fine-grained controls over - * which pages are served at which URLs. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory - */ -/** - * Hash history stores the location in window.location.hash. This makes it ideal - * for situations where you don't want to send the location to the server for - * some reason, either because you do cannot configure it or the URL space is - * reserved for something else. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory - */ -function createHashHistory(options) { - if (options === void 0) { - options = {}; - } - function createHashLocation(window, globalHistory) { - let { - pathname = "/", - search = "", - hash = "" - } = parsePath(window.location.hash.substr(1)); - - // Hash URL should always have a leading / just like window.location.pathname - // does, so if an app ends up at a route like /#something then we add a - // leading slash so all of our path-matching behaves the same as if it would - // in a browser router. This is particularly important when there exists a - // root splat route () since that matches internally against - // "/*" and we'd expect /#something to 404 in a hash router app. - if (!pathname.startsWith("/") && !pathname.startsWith(".")) { - pathname = "/" + pathname; - } - return createLocation("", { - pathname, - search, - hash - }, - // state defaults to `null` because `window.history.state` does - globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default"); - } - function createHashHref(window, to) { - let base = window.document.querySelector("base"); - let href = ""; - if (base && base.getAttribute("href")) { - let url = window.location.href; - let hashIndex = url.indexOf("#"); - href = hashIndex === -1 ? url : url.slice(0, hashIndex); - } - return href + "#" + (typeof to === "string" ? to : createPath(to)); - } - function validateHashLocation(location, to) { - warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")"); - } - return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options); -} -//#endregion - -//////////////////////////////////////////////////////////////////////////////// -//#region UTILS -//////////////////////////////////////////////////////////////////////////////// - -/** - * @private - */ -function invariant(value, message) { - if (value === false || value === null || typeof value === "undefined") { - throw new Error(message); - } -} -function warning(cond, message) { - if (!cond) { - // eslint-disable-next-line no-console - if (typeof console !== "undefined") console.warn(message); - try { - // Welcome to debugging history! - // - // This error is thrown as a convenience, so you can more easily - // find the source for a warning that appears in the console by - // enabling "pause on exceptions" in your JavaScript debugger. - throw new Error(message); - // eslint-disable-next-line no-empty - } catch (e) {} - } -} -function createKey() { - return Math.random().toString(36).substr(2, 8); -} - -/** - * For browser-based histories, we combine the state and key into an object - */ -function getHistoryState(location, index) { - return { - usr: location.state, - key: location.key, - idx: index - }; -} - -/** - * Creates a Location object with a unique key from the given Path - */ -function createLocation(current, to, state, key) { - if (state === void 0) { - state = null; - } - let location = _extends({ - pathname: typeof current === "string" ? current : current.pathname, - search: "", - hash: "" - }, typeof to === "string" ? parsePath(to) : to, { - state, - // TODO: This could be cleaned up. push/replace should probably just take - // full Locations now and avoid the need to run through this flow at all - // But that's a pretty big refactor to the current test suite so going to - // keep as is for the time being and just let any incoming keys take precedence - key: to && to.key || key || createKey() - }); - return location; -} - -/** - * Creates a string URL path from the given pathname, search, and hash components. - */ -function createPath(_ref) { - let { - pathname = "/", - search = "", - hash = "" - } = _ref; - if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search; - if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash; - return pathname; -} - -/** - * Parses a string URL path into its separate pathname, search, and hash components. - */ -function parsePath(path) { - let parsedPath = {}; - if (path) { - let hashIndex = path.indexOf("#"); - if (hashIndex >= 0) { - parsedPath.hash = path.substr(hashIndex); - path = path.substr(0, hashIndex); - } - let searchIndex = path.indexOf("?"); - if (searchIndex >= 0) { - parsedPath.search = path.substr(searchIndex); - path = path.substr(0, searchIndex); - } - if (path) { - parsedPath.pathname = path; - } - } - return parsedPath; -} -function getUrlBasedHistory(getLocation, createHref, validateLocation, options) { - if (options === void 0) { - options = {}; - } - let { - window = document.defaultView, - v5Compat = false - } = options; - let globalHistory = window.history; - let action = Action.Pop; - let listener = null; - let index = getIndex(); - // Index should only be null when we initialize. If not, it's because the - // user called history.pushState or history.replaceState directly, in which - // case we should log a warning as it will result in bugs. - if (index == null) { - index = 0; - globalHistory.replaceState(_extends({}, globalHistory.state, { - idx: index - }), ""); - } - function getIndex() { - let state = globalHistory.state || { - idx: null - }; - return state.idx; - } - function handlePop() { - action = Action.Pop; - let nextIndex = getIndex(); - let delta = nextIndex == null ? null : nextIndex - index; - index = nextIndex; - if (listener) { - listener({ - action, - location: history.location, - delta - }); - } - } - function push(to, state) { - action = Action.Push; - let location = createLocation(history.location, to, state); - if (validateLocation) validateLocation(location, to); - index = getIndex() + 1; - let historyState = getHistoryState(location, index); - let url = history.createHref(location); - - // try...catch because iOS limits us to 100 pushState calls :/ - try { - globalHistory.pushState(historyState, "", url); - } catch (error) { - // If the exception is because `state` can't be serialized, let that throw - // outwards just like a replace call would so the dev knows the cause - // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps - // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal - if (error instanceof DOMException && error.name === "DataCloneError") { - throw error; - } - // They are going to lose state here, but there is no real - // way to warn them about it since the page will refresh... - window.location.assign(url); - } - if (v5Compat && listener) { - listener({ - action, - location: history.location, - delta: 1 - }); - } - } - function replace(to, state) { - action = Action.Replace; - let location = createLocation(history.location, to, state); - if (validateLocation) validateLocation(location, to); - index = getIndex(); - let historyState = getHistoryState(location, index); - let url = history.createHref(location); - globalHistory.replaceState(historyState, "", url); - if (v5Compat && listener) { - listener({ - action, - location: history.location, - delta: 0 - }); - } - } - function createURL(to) { - // window.location.origin is "null" (the literal string value) in Firefox - // under certain conditions, notably when serving from a local HTML file - // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297 - let base = window.location.origin !== "null" ? window.location.origin : window.location.href; - let href = typeof to === "string" ? to : createPath(to); - // Treating this as a full URL will strip any trailing spaces so we need to - // pre-encode them since they might be part of a matching splat param from - // an ancestor route - href = href.replace(/ $/, "%20"); - invariant(base, "No window.location.(origin|href) available to create URL for href: " + href); - return new URL(href, base); - } - let history = { - get action() { - return action; - }, - get location() { - return getLocation(window, globalHistory); - }, - listen(fn) { - if (listener) { - throw new Error("A history only accepts one active listener"); - } - window.addEventListener(PopStateEventType, handlePop); - listener = fn; - return () => { - window.removeEventListener(PopStateEventType, handlePop); - listener = null; - }; - }, - createHref(to) { - return createHref(window, to); - }, - createURL, - encodeLocation(to) { - // Encode a Location the same way window.location would - let url = createURL(to); - return { - pathname: url.pathname, - search: url.search, - hash: url.hash - }; - }, - push, - replace, - go(n) { - return globalHistory.go(n); - } - }; - return history; -} - -//#endregion - -/** - * Map of routeId -> data returned from a loader/action/error - */ - -let ResultType = /*#__PURE__*/function (ResultType) { - ResultType["data"] = "data"; - ResultType["deferred"] = "deferred"; - ResultType["redirect"] = "redirect"; - ResultType["error"] = "error"; - return ResultType; -}({}); - -/** - * Successful result from a loader or action - */ - -/** - * Successful defer() result from a loader or action - */ - -/** - * Redirect result from a loader or action - */ - -/** - * Unsuccessful result from a loader or action - */ - -/** - * Result from a loader or action - potentially successful or unsuccessful - */ - -/** - * Result from a loader or action called via dataStrategy - */ - -/** - * Users can specify either lowercase or uppercase form methods on `
`, - * useSubmit(), ``, etc. - */ - -/** - * Active navigation/fetcher form methods are exposed in lowercase on the - * RouterState - */ - -/** - * In v7, active navigation/fetcher form methods are exposed in uppercase on the - * RouterState. This is to align with the normalization done via fetch(). - */ - -// Thanks https://github.com/sindresorhus/type-fest! - -/** - * @private - * Internal interface to pass around for action submissions, not intended for - * external consumption - */ - -/** - * @private - * Arguments passed to route loader/action functions. Same for now but we keep - * this as a private implementation detail in case they diverge in the future. - */ - -// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers: -// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs -// Also, make them a type alias instead of an interface -/** - * Arguments passed to loader functions - */ -/** - * Arguments passed to action functions - */ -/** - * Loaders and actions can return anything except `undefined` (`null` is a - * valid return value if there is no data to return). Responses are preferred - * and will ease any future migration to Remix - */ -/** - * Route loader function signature - */ -/** - * Route action function signature - */ -/** - * Arguments passed to shouldRevalidate function - */ -/** - * Route shouldRevalidate function signature. This runs after any submission - * (navigation or fetcher), so we flatten the navigation/fetcher submission - * onto the arguments. It shouldn't matter whether it came from a navigation - * or a fetcher, what really matters is the URLs and the formData since loaders - * have to re-run based on the data models that were potentially mutated. - */ -/** - * Function provided by the framework-aware layers to set `hasErrorBoundary` - * from the framework-aware `errorElement` prop - * - * @deprecated Use `mapRouteProperties` instead - */ -/** - * Function provided by the framework-aware layers to set any framework-specific - * properties from framework-agnostic properties - */ -/** - * Keys we cannot change from within a lazy() function. We spread all other keys - * onto the route. Either they're meaningful to the router, or they'll get - * ignored. - */ -const immutableRouteKeys = new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]); - -/** - * lazy() function to load a route definition, which can add non-matching - * related properties to a route - */ - -/** - * Base RouteObject with common props shared by all types of routes - */ - -/** - * Index routes must not have children - */ - -/** - * Non-index routes may have children, but cannot have index - */ - -/** - * A route object represents a logical route, with (optionally) its child - * routes organized in a tree-like structure. - */ - -/** - * A data route object, which is just a RouteObject with a required unique ID - */ - -// Recursive helper for finding path parameters in the absence of wildcards - -/** - * Examples: - * "/a/b/*" -> "*" - * ":a" -> "a" - * "/a/:b" -> "b" - * "/a/blahblahblah:b" -> "b" - * "/:a/:b" -> "a" | "b" - * "/:a/b/:c/*" -> "a" | "c" | "*" - */ - -// Attempt to parse the given string segment. If it fails, then just return the -// plain string type as a default fallback. Otherwise, return the union of the -// parsed string literals that were referenced as dynamic segments in the route. -/** - * The parameters that were parsed from the URL path. - */ -/** - * A RouteMatch contains info about how a route matched a URL. - */ -function isIndexRoute(route) { - return route.index === true; -} - -// Walk the route tree generating unique IDs where necessary, so we are working -// solely with AgnosticDataRouteObject's within the Router -function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) { - if (parentPath === void 0) { - parentPath = []; - } - if (manifest === void 0) { - manifest = {}; - } - return routes.map((route, index) => { - let treePath = [...parentPath, index]; - let id = typeof route.id === "string" ? route.id : treePath.join("-"); - invariant(route.index !== true || !route.children, "Cannot specify children on an index route"); - invariant(!manifest[id], "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages"); - if (isIndexRoute(route)) { - let indexRoute = _extends({}, route, mapRouteProperties(route), { - id - }); - manifest[id] = indexRoute; - return indexRoute; - } else { - let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), { - id, - children: undefined - }); - manifest[id] = pathOrLayoutRoute; - if (route.children) { - pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest); - } - return pathOrLayoutRoute; - } - }); -} - -/** - * Matches the given routes to a location and returns the match data. - * - * @see https://reactrouter.com/utils/match-routes - */ -function matchRoutes(routes, locationArg, basename) { - if (basename === void 0) { - basename = "/"; - } - let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg; - let pathname = stripBasename(location.pathname || "/", basename); - if (pathname == null) { - return null; - } - let branches = flattenRoutes(routes); - rankRouteBranches(branches); - let matches = null; - for (let i = 0; matches == null && i < branches.length; ++i) { - // Incoming pathnames are generally encoded from either window.location - // or from router.navigate, but we want to match against the unencoded - // paths in the route definitions. Memory router locations won't be - // encoded here but there also shouldn't be anything to decode so this - // should be a safe operation. This avoids needing matchRoutes to be - // history-aware. - let decoded = decodePath(pathname); - matches = matchRouteBranch(branches[i], decoded); - } - return matches; -} -function convertRouteMatchToUiMatch(match, loaderData) { - let { - route, - pathname, - params - } = match; - return { - id: route.id, - pathname, - params, - data: loaderData[route.id], - handle: route.handle - }; -} -function flattenRoutes(routes, branches, parentsMeta, parentPath) { - if (branches === void 0) { - branches = []; - } - if (parentsMeta === void 0) { - parentsMeta = []; - } - if (parentPath === void 0) { - parentPath = ""; - } - let flattenRoute = (route, index, relativePath) => { - let meta = { - relativePath: relativePath === undefined ? route.path || "" : relativePath, - caseSensitive: route.caseSensitive === true, - childrenIndex: index, - route - }; - if (meta.relativePath.startsWith("/")) { - invariant(meta.relativePath.startsWith(parentPath), "Absolute route path \"" + meta.relativePath + "\" nested under path " + ("\"" + parentPath + "\" is not valid. An absolute child route path ") + "must start with the combined path of all its parent routes."); - meta.relativePath = meta.relativePath.slice(parentPath.length); - } - let path = joinPaths([parentPath, meta.relativePath]); - let routesMeta = parentsMeta.concat(meta); - - // Add the children before adding this route to the array, so we traverse the - // route tree depth-first and child routes appear before their parents in - // the "flattened" version. - if (route.children && route.children.length > 0) { - invariant( - // Our types know better, but runtime JS may not! - // @ts-expect-error - route.index !== true, "Index routes must not have child routes. Please remove " + ("all child routes from route path \"" + path + "\".")); - flattenRoutes(route.children, branches, routesMeta, path); - } - - // Routes without a path shouldn't ever match by themselves unless they are - // index routes, so don't add them to the list of possible branches. - if (route.path == null && !route.index) { - return; - } - branches.push({ - path, - score: computeScore(path, route.index), - routesMeta - }); - }; - routes.forEach((route, index) => { - var _route$path; - // coarse-grain check for optional params - if (route.path === "" || !((_route$path = route.path) != null && _route$path.includes("?"))) { - flattenRoute(route, index); - } else { - for (let exploded of explodeOptionalSegments(route.path)) { - flattenRoute(route, index, exploded); - } - } - }); - return branches; -} - -/** - * Computes all combinations of optional path segments for a given path, - * excluding combinations that are ambiguous and of lower priority. - * - * For example, `/one/:two?/three/:four?/:five?` explodes to: - * - `/one/three` - * - `/one/:two/three` - * - `/one/three/:four` - * - `/one/three/:five` - * - `/one/:two/three/:four` - * - `/one/:two/three/:five` - * - `/one/three/:four/:five` - * - `/one/:two/three/:four/:five` - */ -function explodeOptionalSegments(path) { - let segments = path.split("/"); - if (segments.length === 0) return []; - let [first, ...rest] = segments; - - // Optional path segments are denoted by a trailing `?` - let isOptional = first.endsWith("?"); - // Compute the corresponding required segment: `foo?` -> `foo` - let required = first.replace(/\?$/, ""); - if (rest.length === 0) { - // Intepret empty string as omitting an optional segment - // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three` - return isOptional ? [required, ""] : [required]; - } - let restExploded = explodeOptionalSegments(rest.join("/")); - let result = []; - - // All child paths with the prefix. Do this for all children before the - // optional version for all children, so we get consistent ordering where the - // parent optional aspect is preferred as required. Otherwise, we can get - // child sections interspersed where deeper optional segments are higher than - // parent optional segments, where for example, /:two would explode _earlier_ - // then /:one. By always including the parent as required _for all children_ - // first, we avoid this issue - result.push(...restExploded.map(subpath => subpath === "" ? required : [required, subpath].join("/"))); - - // Then, if this is an optional value, add all child versions without - if (isOptional) { - result.push(...restExploded); - } - - // for absolute paths, ensure `/` instead of empty segment - return result.map(exploded => path.startsWith("/") && exploded === "" ? "/" : exploded); -} -function rankRouteBranches(branches) { - branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first - : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex))); -} -const paramRe = /^:[\w-]+$/; -const dynamicSegmentValue = 3; -const indexRouteValue = 2; -const emptySegmentValue = 1; -const staticSegmentValue = 10; -const splatPenalty = -2; -const isSplat = s => s === "*"; -function computeScore(path, index) { - let segments = path.split("/"); - let initialScore = segments.length; - if (segments.some(isSplat)) { - initialScore += splatPenalty; - } - if (index) { - initialScore += indexRouteValue; - } - return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore); -} -function compareIndexes(a, b) { - let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]); - return siblings ? - // If two routes are siblings, we should try to match the earlier sibling - // first. This allows people to have fine-grained control over the matching - // behavior by simply putting routes with identical paths in the order they - // want them tried. - a[a.length - 1] - b[b.length - 1] : - // Otherwise, it doesn't really make sense to rank non-siblings by index, - // so they sort equally. - 0; -} -function matchRouteBranch(branch, pathname) { - let { - routesMeta - } = branch; - let matchedParams = {}; - let matchedPathname = "/"; - let matches = []; - for (let i = 0; i < routesMeta.length; ++i) { - let meta = routesMeta[i]; - let end = i === routesMeta.length - 1; - let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/"; - let match = matchPath({ - path: meta.relativePath, - caseSensitive: meta.caseSensitive, - end - }, remainingPathname); - if (!match) return null; - Object.assign(matchedParams, match.params); - let route = meta.route; - matches.push({ - // TODO: Can this as be avoided? - params: matchedParams, - pathname: joinPaths([matchedPathname, match.pathname]), - pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])), - route - }); - if (match.pathnameBase !== "/") { - matchedPathname = joinPaths([matchedPathname, match.pathnameBase]); - } - } - return matches; -} - -/** - * Returns a path with params interpolated. - * - * @see https://reactrouter.com/utils/generate-path - */ -function generatePath(originalPath, params) { - if (params === void 0) { - params = {}; - } - let path = originalPath; - if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) { - warning(false, "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\".")); - path = path.replace(/\*$/, "/*"); - } - - // ensure `/` is added at the beginning if the path is absolute - const prefix = path.startsWith("/") ? "/" : ""; - const stringify = p => p == null ? "" : typeof p === "string" ? p : String(p); - const segments = path.split(/\/+/).map((segment, index, array) => { - const isLastSegment = index === array.length - 1; - - // only apply the splat if it's the last segment - if (isLastSegment && segment === "*") { - const star = "*"; - // Apply the splat - return stringify(params[star]); - } - const keyMatch = segment.match(/^:([\w-]+)(\??)$/); - if (keyMatch) { - const [, key, optional] = keyMatch; - let param = params[key]; - invariant(optional === "?" || param != null, "Missing \":" + key + "\" param"); - return stringify(param); - } - - // Remove any optional markers from optional static segments - return segment.replace(/\?$/g, ""); - }) - // Remove empty segments - .filter(segment => !!segment); - return prefix + segments.join("/"); -} - -/** - * A PathPattern is used to match on some portion of a URL pathname. - */ - -/** - * A PathMatch contains info about how a PathPattern matched on a URL pathname. - */ - -/** - * Performs pattern matching on a URL pathname and returns information about - * the match. - * - * @see https://reactrouter.com/utils/match-path - */ -function matchPath(pattern, pathname) { - if (typeof pattern === "string") { - pattern = { - path: pattern, - caseSensitive: false, - end: true - }; - } - let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end); - let match = pathname.match(matcher); - if (!match) return null; - let matchedPathname = match[0]; - let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1"); - let captureGroups = match.slice(1); - let params = compiledParams.reduce((memo, _ref, index) => { - let { - paramName, - isOptional - } = _ref; - // We need to compute the pathnameBase here using the raw splat value - // instead of using params["*"] later because it will be decoded then - if (paramName === "*") { - let splatValue = captureGroups[index] || ""; - pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1"); - } - const value = captureGroups[index]; - if (isOptional && !value) { - memo[paramName] = undefined; - } else { - memo[paramName] = (value || "").replace(/%2F/g, "/"); - } - return memo; - }, {}); - return { - params, - pathname: matchedPathname, - pathnameBase, - pattern - }; -} -function compilePath(path, caseSensitive, end) { - if (caseSensitive === void 0) { - caseSensitive = false; - } - if (end === void 0) { - end = true; - } - warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\".")); - let params = []; - let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below - .replace(/^\/*/, "/") // Make sure it has a leading / - .replace(/[\\.*+^${}|()[\]]/g, "\\$&") // Escape special regex chars - .replace(/\/:([\w-]+)(\?)?/g, (_, paramName, isOptional) => { - params.push({ - paramName, - isOptional: isOptional != null - }); - return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)"; - }); - if (path.endsWith("*")) { - params.push({ - paramName: "*" - }); - regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest - : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"] - } else if (end) { - // When matching to the end, ignore trailing slashes - regexpSource += "\\/*$"; - } else if (path !== "" && path !== "/") { - // If our path is non-empty and contains anything beyond an initial slash, - // then we have _some_ form of path in our regex, so we should expect to - // match only if we find the end of this path segment. Look for an optional - // non-captured trailing slash (to match a portion of the URL) or the end - // of the path (if we've matched to the end). We used to do this with a - // word boundary but that gives false positives on routes like - // /user-preferences since `-` counts as a word boundary. - regexpSource += "(?:(?=\\/|$))"; - } else ; - let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i"); - return [matcher, params]; -} -function decodePath(value) { - try { - return value.split("/").map(v => decodeURIComponent(v).replace(/\//g, "%2F")).join("/"); - } catch (error) { - warning(false, "The URL path \"" + value + "\" could not be decoded because it is is a " + "malformed URL segment. This is probably due to a bad percent " + ("encoding (" + error + ").")); - return value; - } -} - -/** - * @private - */ -function stripBasename(pathname, basename) { - if (basename === "/") return pathname; - if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) { - return null; - } - - // We want to leave trailing slash behavior in the user's control, so if they - // specify a basename with a trailing slash, we should support it - let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length; - let nextChar = pathname.charAt(startIndex); - if (nextChar && nextChar !== "/") { - // pathname does not start with basename/ - return null; - } - return pathname.slice(startIndex) || "/"; -} - -/** - * Returns a resolved path object relative to the given pathname. - * - * @see https://reactrouter.com/utils/resolve-path - */ -function resolvePath(to, fromPathname) { - if (fromPathname === void 0) { - fromPathname = "/"; - } - let { - pathname: toPathname, - search = "", - hash = "" - } = typeof to === "string" ? parsePath(to) : to; - let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname; - return { - pathname, - search: normalizeSearch(search), - hash: normalizeHash(hash) - }; -} -function resolvePathname(relativePath, fromPathname) { - let segments = fromPathname.replace(/\/+$/, "").split("/"); - let relativeSegments = relativePath.split("/"); - relativeSegments.forEach(segment => { - if (segment === "..") { - // Keep the root "" segment so the pathname starts at / - if (segments.length > 1) segments.pop(); - } else if (segment !== ".") { - segments.push(segment); - } - }); - return segments.length > 1 ? segments.join("/") : "/"; -} -function getInvalidPathError(char, field, dest, path) { - return "Cannot include a '" + char + "' character in a manually specified " + ("`to." + field + "` field [" + JSON.stringify(path) + "]. Please separate it out to the ") + ("`to." + dest + "` field. Alternatively you may provide the full path as ") + "a string in and the router will parse it for you."; -} - -/** - * @private - * - * When processing relative navigation we want to ignore ancestor routes that - * do not contribute to the path, such that index/pathless layout routes don't - * interfere. - * - * For example, when moving a route element into an index route and/or a - * pathless layout route, relative link behavior contained within should stay - * the same. Both of the following examples should link back to the root: - * - * - * - * - * - * - * - * }> // <-- Does not contribute - * // <-- Does not contribute - * - * - */ -function getPathContributingMatches(matches) { - return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0); -} - -// Return the array of pathnames for the current route matches - used to -// generate the routePathnames input for resolveTo() -function getResolveToMatches(matches, v7_relativeSplatPath) { - let pathMatches = getPathContributingMatches(matches); - - // When v7_relativeSplatPath is enabled, use the full pathname for the leaf - // match so we include splat values for "." links. See: - // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329 - if (v7_relativeSplatPath) { - return pathMatches.map((match, idx) => idx === matches.length - 1 ? match.pathname : match.pathnameBase); - } - return pathMatches.map(match => match.pathnameBase); -} - -/** - * @private - */ -function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) { - if (isPathRelative === void 0) { - isPathRelative = false; - } - let to; - if (typeof toArg === "string") { - to = parsePath(toArg); - } else { - to = _extends({}, toArg); - invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to)); - invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to)); - invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to)); - } - let isEmptyPath = toArg === "" || to.pathname === ""; - let toPathname = isEmptyPath ? "/" : to.pathname; - let from; - - // Routing is relative to the current pathname if explicitly requested. - // - // If a pathname is explicitly provided in `to`, it should be relative to the - // route context. This is explained in `Note on `` values` in our - // migration guide from v5 as a means of disambiguation between `to` values - // that begin with `/` and those that do not. However, this is problematic for - // `to` values that do not provide a pathname. `to` can simply be a search or - // hash string, in which case we should assume that the navigation is relative - // to the current location's pathname and *not* the route pathname. - if (toPathname == null) { - from = locationPathname; - } else { - let routePathnameIndex = routePathnames.length - 1; - - // With relative="route" (the default), each leading .. segment means - // "go up one route" instead of "go up one URL segment". This is a key - // difference from how works and a major reason we call this a - // "to" value instead of a "href". - if (!isPathRelative && toPathname.startsWith("..")) { - let toSegments = toPathname.split("/"); - while (toSegments[0] === "..") { - toSegments.shift(); - routePathnameIndex -= 1; - } - to.pathname = toSegments.join("/"); - } - from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/"; - } - let path = resolvePath(to, from); - - // Ensure the pathname has a trailing slash if the original "to" had one - let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/"); - // Or if this was a link to the current path which has a trailing slash - let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/"); - if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) { - path.pathname += "/"; - } - return path; -} - -/** - * @private - */ -function getToPathname(to) { - // Empty strings should be treated the same as / paths - return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname; -} - -/** - * @private - */ -const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/"); - -/** - * @private - */ -const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/"); - -/** - * @private - */ -const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search; - -/** - * @private - */ -const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash; -/** - * This is a shortcut for creating `application/json` responses. Converts `data` - * to JSON and sets the `Content-Type` header. - */ -const json = function json(data, init) { - if (init === void 0) { - init = {}; - } - let responseInit = typeof init === "number" ? { - status: init - } : init; - let headers = new Headers(responseInit.headers); - if (!headers.has("Content-Type")) { - headers.set("Content-Type", "application/json; charset=utf-8"); - } - return new Response(JSON.stringify(data), _extends({}, responseInit, { - headers - })); -}; -class AbortedDeferredError extends Error {} -class DeferredData { - constructor(data, responseInit) { - this.pendingKeysSet = new Set(); - this.subscribers = new Set(); - this.deferredKeys = []; - invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects"); - - // Set up an AbortController + Promise we can race against to exit early - // cancellation - let reject; - this.abortPromise = new Promise((_, r) => reject = r); - this.controller = new AbortController(); - let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted")); - this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort); - this.controller.signal.addEventListener("abort", onAbort); - this.data = Object.entries(data).reduce((acc, _ref2) => { - let [key, value] = _ref2; - return Object.assign(acc, { - [key]: this.trackPromise(key, value) - }); - }, {}); - if (this.done) { - // All incoming values were resolved - this.unlistenAbortSignal(); - } - this.init = responseInit; - } - trackPromise(key, value) { - if (!(value instanceof Promise)) { - return value; - } - this.deferredKeys.push(key); - this.pendingKeysSet.add(key); - - // We store a little wrapper promise that will be extended with - // _data/_error props upon resolve/reject - let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error)); - - // Register rejection listeners to avoid uncaught promise rejections on - // errors or aborted deferred values - promise.catch(() => {}); - Object.defineProperty(promise, "_tracked", { - get: () => true - }); - return promise; - } - onSettle(promise, key, error, data) { - if (this.controller.signal.aborted && error instanceof AbortedDeferredError) { - this.unlistenAbortSignal(); - Object.defineProperty(promise, "_error", { - get: () => error - }); - return Promise.reject(error); - } - this.pendingKeysSet.delete(key); - if (this.done) { - // Nothing left to abort! - this.unlistenAbortSignal(); - } - - // If the promise was resolved/rejected with undefined, we'll throw an error as you - // should always resolve with a value or null - if (error === undefined && data === undefined) { - let undefinedError = new Error("Deferred data for key \"" + key + "\" resolved/rejected with `undefined`, " + "you must resolve/reject with a value or `null`."); - Object.defineProperty(promise, "_error", { - get: () => undefinedError - }); - this.emit(false, key); - return Promise.reject(undefinedError); - } - if (data === undefined) { - Object.defineProperty(promise, "_error", { - get: () => error - }); - this.emit(false, key); - return Promise.reject(error); - } - Object.defineProperty(promise, "_data", { - get: () => data - }); - this.emit(false, key); - return data; - } - emit(aborted, settledKey) { - this.subscribers.forEach(subscriber => subscriber(aborted, settledKey)); - } - subscribe(fn) { - this.subscribers.add(fn); - return () => this.subscribers.delete(fn); - } - cancel() { - this.controller.abort(); - this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k)); - this.emit(true); - } - async resolveData(signal) { - let aborted = false; - if (!this.done) { - let onAbort = () => this.cancel(); - signal.addEventListener("abort", onAbort); - aborted = await new Promise(resolve => { - this.subscribe(aborted => { - signal.removeEventListener("abort", onAbort); - if (aborted || this.done) { - resolve(aborted); - } - }); - }); - } - return aborted; - } - get done() { - return this.pendingKeysSet.size === 0; - } - get unwrappedData() { - invariant(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds"); - return Object.entries(this.data).reduce((acc, _ref3) => { - let [key, value] = _ref3; - return Object.assign(acc, { - [key]: unwrapTrackedPromise(value) - }); - }, {}); - } - get pendingKeys() { - return Array.from(this.pendingKeysSet); - } -} -function isTrackedPromise(value) { - return value instanceof Promise && value._tracked === true; -} -function unwrapTrackedPromise(value) { - if (!isTrackedPromise(value)) { - return value; - } - if (value._error) { - throw value._error; - } - return value._data; -} -const defer = function defer(data, init) { - if (init === void 0) { - init = {}; - } - let responseInit = typeof init === "number" ? { - status: init - } : init; - return new DeferredData(data, responseInit); -}; -/** - * A redirect response. Sets the status code and the `Location` header. - * Defaults to "302 Found". - */ -const redirect = function redirect(url, init) { - if (init === void 0) { - init = 302; - } - let responseInit = init; - if (typeof responseInit === "number") { - responseInit = { - status: responseInit - }; - } else if (typeof responseInit.status === "undefined") { - responseInit.status = 302; - } - let headers = new Headers(responseInit.headers); - headers.set("Location", url); - return new Response(null, _extends({}, responseInit, { - headers - })); -}; - -/** - * A redirect response that will force a document reload to the new location. - * Sets the status code and the `Location` header. - * Defaults to "302 Found". - */ -const redirectDocument = (url, init) => { - let response = redirect(url, init); - response.headers.set("X-Remix-Reload-Document", "true"); - return response; -}; -/** - * @private - * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies - * - * We don't export the class for public use since it's an implementation - * detail, but we export the interface above so folks can build their own - * abstractions around instances via isRouteErrorResponse() - */ -class ErrorResponseImpl { - constructor(status, statusText, data, internal) { - if (internal === void 0) { - internal = false; - } - this.status = status; - this.statusText = statusText || ""; - this.internal = internal; - if (data instanceof Error) { - this.data = data.toString(); - this.error = data; - } else { - this.data = data; - } - } -} - -/** - * Check if the given error is an ErrorResponse generated from a 4xx/5xx - * Response thrown from an action/loader - */ -function isRouteErrorResponse(error) { - return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error; -} - -//////////////////////////////////////////////////////////////////////////////// -//#region Types and Constants -//////////////////////////////////////////////////////////////////////////////// - -/** - * A Router instance manages all navigation and data loading/mutations - */ -/** - * State maintained internally by the router. During a navigation, all states - * reflect the the "old" location unless otherwise noted. - */ -/** - * Data that can be passed into hydrate a Router from SSR - */ -/** - * Future flags to toggle new feature behavior - */ -/** - * Initialization options for createRouter - */ -/** - * State returned from a server-side query() call - */ -/** - * A StaticHandler instance manages a singular SSR navigation/fetch event - */ -/** - * Subscriber function signature for changes to router state - */ -/** - * Function signature for determining the key to be used in scroll restoration - * for a given location - */ -/** - * Function signature for determining the current scroll position - */ -// Allowed for any navigation or fetch -// Only allowed for navigations -// Only allowed for submission navigations -/** - * Options for a navigate() call for a normal (non-submission) navigation - */ -/** - * Options for a navigate() call for a submission navigation - */ -/** - * Options to pass to navigate() for a navigation - */ -/** - * Options for a fetch() load - */ -/** - * Options for a fetch() submission - */ -/** - * Options to pass to fetch() - */ -/** - * Potential states for state.navigation - */ -/** - * Potential states for fetchers - */ -/** - * Cached info for active fetcher.load() instances so they can participate - * in revalidation - */ -/** - * Identified fetcher.load() calls that need to be revalidated - */ -const validMutationMethodsArr = ["post", "put", "patch", "delete"]; -const validMutationMethods = new Set(validMutationMethodsArr); -const validRequestMethodsArr = ["get", ...validMutationMethodsArr]; -const validRequestMethods = new Set(validRequestMethodsArr); -const redirectStatusCodes = new Set([301, 302, 303, 307, 308]); -const redirectPreserveMethodStatusCodes = new Set([307, 308]); -const IDLE_NAVIGATION = { - state: "idle", - location: undefined, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined -}; -const IDLE_FETCHER = { - state: "idle", - data: undefined, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined -}; -const IDLE_BLOCKER = { - state: "unblocked", - proceed: undefined, - reset: undefined, - location: undefined -}; -const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i; -const defaultMapRouteProperties = route => ({ - hasErrorBoundary: Boolean(route.hasErrorBoundary) -}); -const TRANSITIONS_STORAGE_KEY = "remix-router-transitions"; - -//#endregion - -//////////////////////////////////////////////////////////////////////////////// -//#region createRouter -//////////////////////////////////////////////////////////////////////////////// - -/** - * Create a router and listen to history POP navigations - */ -function createRouter(init) { - const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : undefined; - const isBrowser = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined"; - const isServer = !isBrowser; - invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter"); - let mapRouteProperties; - if (init.mapRouteProperties) { - mapRouteProperties = init.mapRouteProperties; - } else if (init.detectErrorBoundary) { - // If they are still using the deprecated version, wrap it with the new API - let detectErrorBoundary = init.detectErrorBoundary; - mapRouteProperties = route => ({ - hasErrorBoundary: detectErrorBoundary(route) - }); - } else { - mapRouteProperties = defaultMapRouteProperties; - } - - // Routes keyed by ID - let manifest = {}; - // Routes in tree format for matching - let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest); - let inFlightDataRoutes; - let basename = init.basename || "/"; - let dataStrategyImpl = init.unstable_dataStrategy || defaultDataStrategy; - // Config driven behavior flags - let future = _extends({ - v7_fetcherPersist: false, - v7_normalizeFormMethod: false, - v7_partialHydration: false, - v7_prependBasename: false, - v7_relativeSplatPath: false, - unstable_skipActionErrorRevalidation: false - }, init.future); - // Cleanup function for history - let unlistenHistory = null; - // Externally-provided functions to call on all state changes - let subscribers = new Set(); - // Externally-provided object to hold scroll restoration locations during routing - let savedScrollPositions = null; - // Externally-provided function to get scroll restoration keys - let getScrollRestorationKey = null; - // Externally-provided function to get current scroll position - let getScrollPosition = null; - // One-time flag to control the initial hydration scroll restoration. Because - // we don't get the saved positions from until _after_ - // the initial render, we need to manually trigger a separate updateState to - // send along the restoreScrollPosition - // Set to true if we have `hydrationData` since we assume we were SSR'd and that - // SSR did the initial scroll restoration. - let initialScrollRestored = init.hydrationData != null; - let initialMatches = matchRoutes(dataRoutes, init.history.location, basename); - let initialErrors = null; - if (initialMatches == null) { - // If we do not match a user-provided-route, fall back to the root - // to allow the error boundary to take over - let error = getInternalRouterError(404, { - pathname: init.history.location.pathname - }); - let { - matches, - route - } = getShortCircuitMatches(dataRoutes); - initialMatches = matches; - initialErrors = { - [route.id]: error - }; - } - let initialized; - let hasLazyRoutes = initialMatches.some(m => m.route.lazy); - let hasLoaders = initialMatches.some(m => m.route.loader); - if (hasLazyRoutes) { - // All initialMatches need to be loaded before we're ready. If we have lazy - // functions around still then we'll need to run them in initialize() - initialized = false; - } else if (!hasLoaders) { - // If we've got no loaders to run, then we're good to go - initialized = true; - } else if (future.v7_partialHydration) { - // If partial hydration is enabled, we're initialized so long as we were - // provided with hydrationData for every route with a loader, and no loaders - // were marked for explicit hydration - let loaderData = init.hydrationData ? init.hydrationData.loaderData : null; - let errors = init.hydrationData ? init.hydrationData.errors : null; - let isRouteInitialized = m => { - // No loader, nothing to initialize - if (!m.route.loader) { - return true; - } - // Explicitly opting-in to running on hydration - if (typeof m.route.loader === "function" && m.route.loader.hydrate === true) { - return false; - } - // Otherwise, initialized if hydrated with data or an error - return loaderData && loaderData[m.route.id] !== undefined || errors && errors[m.route.id] !== undefined; - }; - - // If errors exist, don't consider routes below the boundary - if (errors) { - let idx = initialMatches.findIndex(m => errors[m.route.id] !== undefined); - initialized = initialMatches.slice(0, idx + 1).every(isRouteInitialized); - } else { - initialized = initialMatches.every(isRouteInitialized); - } - } else { - // Without partial hydration - we're initialized if we were provided any - // hydrationData - which is expected to be complete - initialized = init.hydrationData != null; - } - let router; - let state = { - historyAction: init.history.action, - location: init.history.location, - matches: initialMatches, - initialized, - navigation: IDLE_NAVIGATION, - // Don't restore on initial updateState() if we were SSR'd - restoreScrollPosition: init.hydrationData != null ? false : null, - preventScrollReset: false, - revalidation: "idle", - loaderData: init.hydrationData && init.hydrationData.loaderData || {}, - actionData: init.hydrationData && init.hydrationData.actionData || null, - errors: init.hydrationData && init.hydrationData.errors || initialErrors, - fetchers: new Map(), - blockers: new Map() - }; - - // -- Stateful internal variables to manage navigations -- - // Current navigation in progress (to be committed in completeNavigation) - let pendingAction = Action.Pop; - - // Should the current navigation prevent the scroll reset if scroll cannot - // be restored? - let pendingPreventScrollReset = false; - - // AbortController for the active navigation - let pendingNavigationController; - - // Should the current navigation enable document.startViewTransition? - let pendingViewTransitionEnabled = false; - - // Store applied view transitions so we can apply them on POP - let appliedViewTransitions = new Map(); - - // Cleanup function for persisting applied transitions to sessionStorage - let removePageHideEventListener = null; - - // We use this to avoid touching history in completeNavigation if a - // revalidation is entirely uninterrupted - let isUninterruptedRevalidation = false; - - // Use this internal flag to force revalidation of all loaders: - // - submissions (completed or interrupted) - // - useRevalidator() - // - X-Remix-Revalidate (from redirect) - let isRevalidationRequired = false; - - // Use this internal array to capture routes that require revalidation due - // to a cancelled deferred on action submission - let cancelledDeferredRoutes = []; - - // Use this internal array to capture fetcher loads that were cancelled by an - // action navigation and require revalidation - let cancelledFetcherLoads = []; - - // AbortControllers for any in-flight fetchers - let fetchControllers = new Map(); - - // Track loads based on the order in which they started - let incrementingLoadId = 0; - - // Track the outstanding pending navigation data load to be compared against - // the globally incrementing load when a fetcher load lands after a completed - // navigation - let pendingNavigationLoadId = -1; - - // Fetchers that triggered data reloads as a result of their actions - let fetchReloadIds = new Map(); - - // Fetchers that triggered redirect navigations - let fetchRedirectIds = new Set(); - - // Most recent href/match for fetcher.load calls for fetchers - let fetchLoadMatches = new Map(); - - // Ref-count mounted fetchers so we know when it's ok to clean them up - let activeFetchers = new Map(); - - // Fetchers that have requested a delete when using v7_fetcherPersist, - // they'll be officially removed after they return to idle - let deletedFetchers = new Set(); - - // Store DeferredData instances for active route matches. When a - // route loader returns defer() we stick one in here. Then, when a nested - // promise resolves we update loaderData. If a new navigation starts we - // cancel active deferreds for eliminated routes. - let activeDeferreds = new Map(); - - // Store blocker functions in a separate Map outside of router state since - // we don't need to update UI state if they change - let blockerFunctions = new Map(); - - // Flag to ignore the next history update, so we can revert the URL change on - // a POP navigation that was blocked by the user without touching router state - let ignoreNextHistoryUpdate = false; - - // Initialize the router, all side effects should be kicked off from here. - // Implemented as a Fluent API for ease of: - // let router = createRouter(init).initialize(); - function initialize() { - // If history informs us of a POP navigation, start the navigation but do not update - // state. We'll update our own state once the navigation completes - unlistenHistory = init.history.listen(_ref => { - let { - action: historyAction, - location, - delta - } = _ref; - // Ignore this event if it was just us resetting the URL from a - // blocked POP navigation - if (ignoreNextHistoryUpdate) { - ignoreNextHistoryUpdate = false; - return; - } - warning(blockerFunctions.size === 0 || delta != null, "You are trying to use a blocker on a POP navigation to a location " + "that was not created by @remix-run/router. This will fail silently in " + "production. This can happen if you are navigating outside the router " + "via `window.history.pushState`/`window.location.hash` instead of using " + "router navigation APIs. This can also happen if you are using " + "createHashRouter and the user manually changes the URL."); - let blockerKey = shouldBlockNavigation({ - currentLocation: state.location, - nextLocation: location, - historyAction - }); - if (blockerKey && delta != null) { - // Restore the URL to match the current UI, but don't update router state - ignoreNextHistoryUpdate = true; - init.history.go(delta * -1); - - // Put the blocker into a blocked state - updateBlocker(blockerKey, { - state: "blocked", - location, - proceed() { - updateBlocker(blockerKey, { - state: "proceeding", - proceed: undefined, - reset: undefined, - location - }); - // Re-do the same POP navigation we just blocked - init.history.go(delta); - }, - reset() { - let blockers = new Map(state.blockers); - blockers.set(blockerKey, IDLE_BLOCKER); - updateState({ - blockers - }); - } - }); - return; - } - return startNavigation(historyAction, location); - }); - if (isBrowser) { - // FIXME: This feels gross. How can we cleanup the lines between - // scrollRestoration/appliedTransitions persistance? - restoreAppliedTransitions(routerWindow, appliedViewTransitions); - let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions); - routerWindow.addEventListener("pagehide", _saveAppliedTransitions); - removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions); - } - - // Kick off initial data load if needed. Use Pop to avoid modifying history - // Note we don't do any handling of lazy here. For SPA's it'll get handled - // in the normal navigation flow. For SSR it's expected that lazy modules are - // resolved prior to router creation since we can't go into a fallbackElement - // UI for SSR'd apps - if (!state.initialized) { - startNavigation(Action.Pop, state.location, { - initialHydration: true - }); - } - return router; - } - - // Clean up a router and it's side effects - function dispose() { - if (unlistenHistory) { - unlistenHistory(); - } - if (removePageHideEventListener) { - removePageHideEventListener(); - } - subscribers.clear(); - pendingNavigationController && pendingNavigationController.abort(); - state.fetchers.forEach((_, key) => deleteFetcher(key)); - state.blockers.forEach((_, key) => deleteBlocker(key)); - } - - // Subscribe to state updates for the router - function subscribe(fn) { - subscribers.add(fn); - return () => subscribers.delete(fn); - } - - // Update our state and notify the calling context of the change - function updateState(newState, opts) { - if (opts === void 0) { - opts = {}; - } - state = _extends({}, state, newState); - - // Prep fetcher cleanup so we can tell the UI which fetcher data entries - // can be removed - let completedFetchers = []; - let deletedFetchersKeys = []; - if (future.v7_fetcherPersist) { - state.fetchers.forEach((fetcher, key) => { - if (fetcher.state === "idle") { - if (deletedFetchers.has(key)) { - // Unmounted from the UI and can be totally removed - deletedFetchersKeys.push(key); - } else { - // Returned to idle but still mounted in the UI, so semi-remains for - // revalidations and such - completedFetchers.push(key); - } - } - }); - } - - // Iterate over a local copy so that if flushSync is used and we end up - // removing and adding a new subscriber due to the useCallback dependencies, - // we don't get ourselves into a loop calling the new subscriber immediately - [...subscribers].forEach(subscriber => subscriber(state, { - deletedFetchers: deletedFetchersKeys, - unstable_viewTransitionOpts: opts.viewTransitionOpts, - unstable_flushSync: opts.flushSync === true - })); - - // Remove idle fetchers from state since we only care about in-flight fetchers. - if (future.v7_fetcherPersist) { - completedFetchers.forEach(key => state.fetchers.delete(key)); - deletedFetchersKeys.forEach(key => deleteFetcher(key)); - } - } - - // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION - // and setting state.[historyAction/location/matches] to the new route. - // - Location is a required param - // - Navigation will always be set to IDLE_NAVIGATION - // - Can pass any other state in newState - function completeNavigation(location, newState, _temp) { - var _location$state, _location$state2; - let { - flushSync - } = _temp === void 0 ? {} : _temp; - // Deduce if we're in a loading/actionReload state: - // - We have committed actionData in the store - // - The current navigation was a mutation submission - // - We're past the submitting state and into the loading state - // - The location being loaded is not the result of a redirect - let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true; - let actionData; - if (newState.actionData) { - if (Object.keys(newState.actionData).length > 0) { - actionData = newState.actionData; - } else { - // Empty actionData -> clear prior actionData due to an action error - actionData = null; - } - } else if (isActionReload) { - // Keep the current data if we're wrapping up the action reload - actionData = state.actionData; - } else { - // Clear actionData on any other completed navigations - actionData = null; - } - - // Always preserve any existing loaderData from re-used routes - let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData; - - // On a successful navigation we can assume we got through all blockers - // so we can start fresh - let blockers = state.blockers; - if (blockers.size > 0) { - blockers = new Map(blockers); - blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER)); - } - - // Always respect the user flag. Otherwise don't reset on mutation - // submission navigations unless they redirect - let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true; - if (inFlightDataRoutes) { - dataRoutes = inFlightDataRoutes; - inFlightDataRoutes = undefined; - } - if (isUninterruptedRevalidation) ; else if (pendingAction === Action.Pop) ; else if (pendingAction === Action.Push) { - init.history.push(location, location.state); - } else if (pendingAction === Action.Replace) { - init.history.replace(location, location.state); - } - let viewTransitionOpts; - - // On POP, enable transitions if they were enabled on the original navigation - if (pendingAction === Action.Pop) { - // Forward takes precedence so they behave like the original navigation - let priorPaths = appliedViewTransitions.get(state.location.pathname); - if (priorPaths && priorPaths.has(location.pathname)) { - viewTransitionOpts = { - currentLocation: state.location, - nextLocation: location - }; - } else if (appliedViewTransitions.has(location.pathname)) { - // If we don't have a previous forward nav, assume we're popping back to - // the new location and enable if that location previously enabled - viewTransitionOpts = { - currentLocation: location, - nextLocation: state.location - }; - } - } else if (pendingViewTransitionEnabled) { - // Store the applied transition on PUSH/REPLACE - let toPaths = appliedViewTransitions.get(state.location.pathname); - if (toPaths) { - toPaths.add(location.pathname); - } else { - toPaths = new Set([location.pathname]); - appliedViewTransitions.set(state.location.pathname, toPaths); - } - viewTransitionOpts = { - currentLocation: state.location, - nextLocation: location - }; - } - updateState(_extends({}, newState, { - // matches, errors, fetchers go through as-is - actionData, - loaderData, - historyAction: pendingAction, - location, - initialized: true, - navigation: IDLE_NAVIGATION, - revalidation: "idle", - restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches), - preventScrollReset, - blockers - }), { - viewTransitionOpts, - flushSync: flushSync === true - }); - - // Reset stateful navigation vars - pendingAction = Action.Pop; - pendingPreventScrollReset = false; - pendingViewTransitionEnabled = false; - isUninterruptedRevalidation = false; - isRevalidationRequired = false; - cancelledDeferredRoutes = []; - cancelledFetcherLoads = []; - } - - // Trigger a navigation event, which can either be a numerical POP or a PUSH - // replace with an optional submission - async function navigate(to, opts) { - if (typeof to === "number") { - init.history.go(to); - return; - } - let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, future.v7_relativeSplatPath, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative); - let { - path, - submission, - error - } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts); - let currentLocation = state.location; - let nextLocation = createLocation(state.location, path, opts && opts.state); - - // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded - // URL from window.location, so we need to encode it here so the behavior - // remains the same as POP and non-data-router usages. new URL() does all - // the same encoding we'd get from a history.pushState/window.location read - // without having to touch history - nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation)); - let userReplace = opts && opts.replace != null ? opts.replace : undefined; - let historyAction = Action.Push; - if (userReplace === true) { - historyAction = Action.Replace; - } else if (userReplace === false) ; else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) { - // By default on submissions to the current location we REPLACE so that - // users don't have to double-click the back button to get to the prior - // location. If the user redirects to a different location from the - // action/loader this will be ignored and the redirect will be a PUSH - historyAction = Action.Replace; - } - let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined; - let flushSync = (opts && opts.unstable_flushSync) === true; - let blockerKey = shouldBlockNavigation({ - currentLocation, - nextLocation, - historyAction - }); - if (blockerKey) { - // Put the blocker into a blocked state - updateBlocker(blockerKey, { - state: "blocked", - location: nextLocation, - proceed() { - updateBlocker(blockerKey, { - state: "proceeding", - proceed: undefined, - reset: undefined, - location: nextLocation - }); - // Send the same navigation through - navigate(to, opts); - }, - reset() { - let blockers = new Map(state.blockers); - blockers.set(blockerKey, IDLE_BLOCKER); - updateState({ - blockers - }); - } - }); - return; - } - return await startNavigation(historyAction, nextLocation, { - submission, - // Send through the formData serialization error if we have one so we can - // render at the right error boundary after we match routes - pendingError: error, - preventScrollReset, - replace: opts && opts.replace, - enableViewTransition: opts && opts.unstable_viewTransition, - flushSync - }); - } - - // Revalidate all current loaders. If a navigation is in progress or if this - // is interrupted by a navigation, allow this to "succeed" by calling all - // loaders during the next loader round - function revalidate() { - interruptActiveLoads(); - updateState({ - revalidation: "loading" - }); - - // If we're currently submitting an action, we don't need to start a new - // navigation, we'll just let the follow up loader execution call all loaders - if (state.navigation.state === "submitting") { - return; - } - - // If we're currently in an idle state, start a new navigation for the current - // action/location and mark it as uninterrupted, which will skip the history - // update in completeNavigation - if (state.navigation.state === "idle") { - startNavigation(state.historyAction, state.location, { - startUninterruptedRevalidation: true - }); - return; - } - - // Otherwise, if we're currently in a loading state, just start a new - // navigation to the navigation.location but do not trigger an uninterrupted - // revalidation so that history correctly updates once the navigation completes - startNavigation(pendingAction || state.historyAction, state.navigation.location, { - overrideNavigation: state.navigation - }); - } - - // Start a navigation to the given action/location. Can optionally provide a - // overrideNavigation which will override the normalLoad in the case of a redirect - // navigation - async function startNavigation(historyAction, location, opts) { - // Abort any in-progress navigations and start a new one. Unset any ongoing - // uninterrupted revalidations unless told otherwise, since we want this - // new navigation to update history normally - pendingNavigationController && pendingNavigationController.abort(); - pendingNavigationController = null; - pendingAction = historyAction; - isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true; - - // Save the current scroll position every time we start a new navigation, - // and track whether we should reset scroll on completion - saveScrollPosition(state.location, state.matches); - pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; - pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true; - let routesToUse = inFlightDataRoutes || dataRoutes; - let loadingNavigation = opts && opts.overrideNavigation; - let matches = matchRoutes(routesToUse, location, basename); - let flushSync = (opts && opts.flushSync) === true; - - // Short circuit with a 404 on the root error boundary if we match nothing - if (!matches) { - let error = getInternalRouterError(404, { - pathname: location.pathname - }); - let { - matches: notFoundMatches, - route - } = getShortCircuitMatches(routesToUse); - // Cancel all pending deferred on 404s since we don't keep any routes - cancelActiveDeferreds(); - completeNavigation(location, { - matches: notFoundMatches, - loaderData: {}, - errors: { - [route.id]: error - } - }, { - flushSync - }); - return; - } - - // Short circuit if it's only a hash change and not a revalidation or - // mutation submission. - // - // Ignore on initial page loads because since the initial load will always - // be "same hash". For example, on /page#hash and submit a - // which will default to a navigation to /page - if (state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) { - completeNavigation(location, { - matches - }, { - flushSync - }); - return; - } - - // Create a controller/Request for this navigation - pendingNavigationController = new AbortController(); - let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission); - let pendingActionResult; - if (opts && opts.pendingError) { - // If we have a pendingError, it means the user attempted a GET submission - // with binary FormData so assign here and skip to handleLoaders. That - // way we handle calling loaders above the boundary etc. It's not really - // different from an actionError in that sense. - pendingActionResult = [findNearestBoundary(matches).route.id, { - type: ResultType.error, - error: opts.pendingError - }]; - } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) { - // Call action if we received an action submission - let actionResult = await handleAction(request, location, opts.submission, matches, { - replace: opts.replace, - flushSync - }); - if (actionResult.shortCircuited) { - return; - } - pendingActionResult = actionResult.pendingActionResult; - loadingNavigation = getLoadingNavigation(location, opts.submission); - flushSync = false; - - // Create a GET request for the loaders - request = createClientSideRequest(init.history, request.url, request.signal); - } - - // Call loaders - let { - shortCircuited, - loaderData, - errors - } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionResult); - if (shortCircuited) { - return; - } - - // Clean up now that the action/loaders have completed. Don't clean up if - // we short circuited because pendingNavigationController will have already - // been assigned to a new controller for the next navigation - pendingNavigationController = null; - completeNavigation(location, _extends({ - matches - }, getActionDataForCommit(pendingActionResult), { - loaderData, - errors - })); - } - - // Call the action matched by the leaf route for this navigation and handle - // redirects/errors - async function handleAction(request, location, submission, matches, opts) { - if (opts === void 0) { - opts = {}; - } - interruptActiveLoads(); - - // Put us in a submitting state - let navigation = getSubmittingNavigation(location, submission); - updateState({ - navigation - }, { - flushSync: opts.flushSync === true - }); - - // Call our action and get the result - let result; - let actionMatch = getTargetMatch(matches, location); - if (!actionMatch.route.action && !actionMatch.route.lazy) { - result = { - type: ResultType.error, - error: getInternalRouterError(405, { - method: request.method, - pathname: location.pathname, - routeId: actionMatch.route.id - }) - }; - } else { - let results = await callDataStrategy("action", request, [actionMatch], matches); - result = results[0]; - if (request.signal.aborted) { - return { - shortCircuited: true - }; - } - } - if (isRedirectResult(result)) { - let replace; - if (opts && opts.replace != null) { - replace = opts.replace; - } else { - // If the user didn't explicity indicate replace behavior, replace if - // we redirected to the exact same location we're currently at to avoid - // double back-buttons - let location = normalizeRedirectLocation(result.response.headers.get("Location"), new URL(request.url), basename); - replace = location === state.location.pathname + state.location.search; - } - await startRedirectNavigation(request, result, { - submission, - replace - }); - return { - shortCircuited: true - }; - } - if (isDeferredResult(result)) { - throw getInternalRouterError(400, { - type: "defer-action" - }); - } - if (isErrorResult(result)) { - // Store off the pending error - we use it to determine which loaders - // to call and will commit it when we complete the navigation - let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); - - // By default, all submissions are REPLACE navigations, but if the - // action threw an error that'll be rendered in an errorElement, we fall - // back to PUSH so that the user can use the back button to get back to - // the pre-submission form location to try again - if ((opts && opts.replace) !== true) { - pendingAction = Action.Push; - } - return { - pendingActionResult: [boundaryMatch.route.id, result] - }; - } - return { - pendingActionResult: [actionMatch.route.id, result] - }; - } - - // Call all applicable loaders for the given matches, handling redirects, - // errors, etc. - async function handleLoaders(request, location, matches, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionResult) { - // Figure out the right navigation we want to use for data loading - let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission); - - // If this was a redirect from an action we don't have a "submission" but - // we have it on the loading navigation so use that if available - let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation); - let routesToUse = inFlightDataRoutes || dataRoutes; - let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, future.unstable_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult); - - // Cancel pending deferreds for no-longer-matched routes or routes we're - // about to reload. Note that if this is an action reload we would have - // already cancelled all pending deferreds so this would be a no-op - cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId)); - pendingNavigationLoadId = ++incrementingLoadId; - - // Short circuit if we have no loaders to run - if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) { - let updatedFetchers = markFetchRedirectsDone(); - completeNavigation(location, _extends({ - matches, - loaderData: {}, - // Commit pending error if we're short circuiting - errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { - [pendingActionResult[0]]: pendingActionResult[1].error - } : null - }, getActionDataForCommit(pendingActionResult), updatedFetchers ? { - fetchers: new Map(state.fetchers) - } : {}), { - flushSync - }); - return { - shortCircuited: true - }; - } - - // If this is an uninterrupted revalidation, we remain in our current idle - // state. If not, we need to switch to our loading state and load data, - // preserving any new action data or existing action data (in the case of - // a revalidation interrupting an actionReload) - // If we have partialHydration enabled, then don't update the state for the - // initial data load since it's not a "navigation" - if (!isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration)) { - revalidatingFetchers.forEach(rf => { - let fetcher = state.fetchers.get(rf.key); - let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined); - state.fetchers.set(rf.key, revalidatingFetcher); - }); - let actionData; - if (pendingActionResult && !isErrorResult(pendingActionResult[1])) { - // This is cast to `any` currently because `RouteData`uses any and it - // would be a breaking change to use any. - // TODO: v7 - change `RouteData` to use `unknown` instead of `any` - actionData = { - [pendingActionResult[0]]: pendingActionResult[1].data - }; - } else if (state.actionData) { - if (Object.keys(state.actionData).length === 0) { - actionData = null; - } else { - actionData = state.actionData; - } - } - updateState(_extends({ - navigation: loadingNavigation - }, actionData !== undefined ? { - actionData - } : {}, revalidatingFetchers.length > 0 ? { - fetchers: new Map(state.fetchers) - } : {}), { - flushSync - }); - } - revalidatingFetchers.forEach(rf => { - if (fetchControllers.has(rf.key)) { - abortFetcher(rf.key); - } - if (rf.controller) { - // Fetchers use an independent AbortController so that aborting a fetcher - // (via deleteFetcher) does not abort the triggering navigation that - // triggered the revalidation - fetchControllers.set(rf.key, rf.controller); - } - }); - - // Proxy navigation abort through to revalidation fetchers - let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key)); - if (pendingNavigationController) { - pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations); - } - let { - loaderResults, - fetcherResults - } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, request); - if (request.signal.aborted) { - return { - shortCircuited: true - }; - } - - // Clean up _after_ loaders have completed. Don't clean up if we short - // circuited because fetchControllers would have been aborted and - // reassigned to new controllers for the next navigation - if (pendingNavigationController) { - pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations); - } - revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key)); - - // If any loaders returned a redirect Response, start a new REPLACE navigation - let redirect = findRedirect([...loaderResults, ...fetcherResults]); - if (redirect) { - if (redirect.idx >= matchesToLoad.length) { - // If this redirect came from a fetcher make sure we mark it in - // fetchRedirectIds so it doesn't get revalidated on the next set of - // loader executions - let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key; - fetchRedirectIds.add(fetcherKey); - } - await startRedirectNavigation(request, redirect.result, { - replace - }); - return { - shortCircuited: true - }; - } - - // Process and commit output from loaders - let { - loaderData, - errors - } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds); - - // Wire up subscribers to update loaderData as promises settle - activeDeferreds.forEach((deferredData, routeId) => { - deferredData.subscribe(aborted => { - // Note: No need to updateState here since the TrackedPromise on - // loaderData is stable across resolve/reject - // Remove this instance if we were aborted or if promises have settled - if (aborted || deferredData.done) { - activeDeferreds.delete(routeId); - } - }); - }); - - // During partial hydration, preserve SSR errors for routes that don't re-run - if (future.v7_partialHydration && initialHydration && state.errors) { - Object.entries(state.errors).filter(_ref2 => { - let [id] = _ref2; - return !matchesToLoad.some(m => m.route.id === id); - }).forEach(_ref3 => { - let [routeId, error] = _ref3; - errors = Object.assign(errors || {}, { - [routeId]: error - }); - }); - } - let updatedFetchers = markFetchRedirectsDone(); - let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId); - let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0; - return _extends({ - loaderData, - errors - }, shouldUpdateFetchers ? { - fetchers: new Map(state.fetchers) - } : {}); - } - - // Trigger a fetcher load/submit for the given fetcher key - function fetch(key, routeId, href, opts) { - if (isServer) { - throw new Error("router.fetch() was called during the server render, but it shouldn't be. " + "You are likely calling a useFetcher() method in the body of your component. " + "Try moving it to a useEffect or a callback."); - } - if (fetchControllers.has(key)) abortFetcher(key); - let flushSync = (opts && opts.unstable_flushSync) === true; - let routesToUse = inFlightDataRoutes || dataRoutes; - let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, future.v7_relativeSplatPath, routeId, opts == null ? void 0 : opts.relative); - let matches = matchRoutes(routesToUse, normalizedPath, basename); - if (!matches) { - setFetcherError(key, routeId, getInternalRouterError(404, { - pathname: normalizedPath - }), { - flushSync - }); - return; - } - let { - path, - submission, - error - } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts); - if (error) { - setFetcherError(key, routeId, error, { - flushSync - }); - return; - } - let match = getTargetMatch(matches, path); - pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; - if (submission && isMutationMethod(submission.formMethod)) { - handleFetcherAction(key, routeId, path, match, matches, flushSync, submission); - return; - } - - // Store off the match so we can call it's shouldRevalidate on subsequent - // revalidations - fetchLoadMatches.set(key, { - routeId, - path - }); - handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission); - } - - // Call the action for the matched fetcher.submit(), and then handle redirects, - // errors, and revalidation - async function handleFetcherAction(key, routeId, path, match, requestMatches, flushSync, submission) { - interruptActiveLoads(); - fetchLoadMatches.delete(key); - if (!match.route.action && !match.route.lazy) { - let error = getInternalRouterError(405, { - method: submission.formMethod, - pathname: path, - routeId: routeId - }); - setFetcherError(key, routeId, error, { - flushSync - }); - return; - } - - // Put this fetcher into it's submitting state - let existingFetcher = state.fetchers.get(key); - updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), { - flushSync - }); - - // Call the action for the fetcher - let abortController = new AbortController(); - let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission); - fetchControllers.set(key, abortController); - let originatingLoadId = incrementingLoadId; - let actionResults = await callDataStrategy("action", fetchRequest, [match], requestMatches); - let actionResult = actionResults[0]; - if (fetchRequest.signal.aborted) { - // We can delete this so long as we weren't aborted by our own fetcher - // re-submit which would have put _new_ controller is in fetchControllers - if (fetchControllers.get(key) === abortController) { - fetchControllers.delete(key); - } - return; - } - - // When using v7_fetcherPersist, we don't want errors bubbling up to the UI - // or redirects processed for unmounted fetchers so we just revert them to - // idle - if (future.v7_fetcherPersist && deletedFetchers.has(key)) { - if (isRedirectResult(actionResult) || isErrorResult(actionResult)) { - updateFetcherState(key, getDoneFetcher(undefined)); - return; - } - // Let SuccessResult's fall through for revalidation - } else { - if (isRedirectResult(actionResult)) { - fetchControllers.delete(key); - if (pendingNavigationLoadId > originatingLoadId) { - // A new navigation was kicked off after our action started, so that - // should take precedence over this redirect navigation. We already - // set isRevalidationRequired so all loaders for the new route should - // fire unless opted out via shouldRevalidate - updateFetcherState(key, getDoneFetcher(undefined)); - return; - } else { - fetchRedirectIds.add(key); - updateFetcherState(key, getLoadingFetcher(submission)); - return startRedirectNavigation(fetchRequest, actionResult, { - fetcherSubmission: submission - }); - } - } - - // Process any non-redirect errors thrown - if (isErrorResult(actionResult)) { - setFetcherError(key, routeId, actionResult.error); - return; - } - } - if (isDeferredResult(actionResult)) { - throw getInternalRouterError(400, { - type: "defer-action" - }); - } - - // Start the data load for current matches, or the next location if we're - // in the middle of a navigation - let nextLocation = state.navigation.location || state.location; - let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal); - let routesToUse = inFlightDataRoutes || dataRoutes; - let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches; - invariant(matches, "Didn't find any matches after fetcher action"); - let loadId = ++incrementingLoadId; - fetchReloadIds.set(key, loadId); - let loadFetcher = getLoadingFetcher(submission, actionResult.data); - state.fetchers.set(key, loadFetcher); - let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, false, future.unstable_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, [match.route.id, actionResult]); - - // Put all revalidating fetchers into the loading state, except for the - // current fetcher which we want to keep in it's current loading state which - // contains it's action submission info + action data - revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => { - let staleKey = rf.key; - let existingFetcher = state.fetchers.get(staleKey); - let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined); - state.fetchers.set(staleKey, revalidatingFetcher); - if (fetchControllers.has(staleKey)) { - abortFetcher(staleKey); - } - if (rf.controller) { - fetchControllers.set(staleKey, rf.controller); - } - }); - updateState({ - fetchers: new Map(state.fetchers) - }); - let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key)); - abortController.signal.addEventListener("abort", abortPendingFetchRevalidations); - let { - loaderResults, - fetcherResults - } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, revalidationRequest); - if (abortController.signal.aborted) { - return; - } - abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations); - fetchReloadIds.delete(key); - fetchControllers.delete(key); - revalidatingFetchers.forEach(r => fetchControllers.delete(r.key)); - let redirect = findRedirect([...loaderResults, ...fetcherResults]); - if (redirect) { - if (redirect.idx >= matchesToLoad.length) { - // If this redirect came from a fetcher make sure we mark it in - // fetchRedirectIds so it doesn't get revalidated on the next set of - // loader executions - let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key; - fetchRedirectIds.add(fetcherKey); - } - return startRedirectNavigation(revalidationRequest, redirect.result); - } - - // Process and commit output from loaders - let { - loaderData, - errors - } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds); - - // Since we let revalidations complete even if the submitting fetcher was - // deleted, only put it back to idle if it hasn't been deleted - if (state.fetchers.has(key)) { - let doneFetcher = getDoneFetcher(actionResult.data); - state.fetchers.set(key, doneFetcher); - } - abortStaleFetchLoads(loadId); - - // If we are currently in a navigation loading state and this fetcher is - // more recent than the navigation, we want the newer data so abort the - // navigation and complete it with the fetcher data - if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) { - invariant(pendingAction, "Expected pending action"); - pendingNavigationController && pendingNavigationController.abort(); - completeNavigation(state.navigation.location, { - matches, - loaderData, - errors, - fetchers: new Map(state.fetchers) - }); - } else { - // otherwise just update with the fetcher data, preserving any existing - // loaderData for loaders that did not need to reload. We have to - // manually merge here since we aren't going through completeNavigation - updateState({ - errors, - loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors), - fetchers: new Map(state.fetchers) - }); - isRevalidationRequired = false; - } - } - - // Call the matched loader for fetcher.load(), handling redirects, errors, etc. - async function handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission) { - let existingFetcher = state.fetchers.get(key); - updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined), { - flushSync - }); - - // Call the loader for this fetcher route match - let abortController = new AbortController(); - let fetchRequest = createClientSideRequest(init.history, path, abortController.signal); - fetchControllers.set(key, abortController); - let originatingLoadId = incrementingLoadId; - let results = await callDataStrategy("loader", fetchRequest, [match], matches); - let result = results[0]; - - // Deferred isn't supported for fetcher loads, await everything and treat it - // as a normal load. resolveDeferredData will return undefined if this - // fetcher gets aborted, so we just leave result untouched and short circuit - // below if that happens - if (isDeferredResult(result)) { - result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result; - } - - // We can delete this so long as we weren't aborted by our our own fetcher - // re-load which would have put _new_ controller is in fetchControllers - if (fetchControllers.get(key) === abortController) { - fetchControllers.delete(key); - } - if (fetchRequest.signal.aborted) { - return; - } - - // We don't want errors bubbling up or redirects followed for unmounted - // fetchers, so short circuit here if it was removed from the UI - if (deletedFetchers.has(key)) { - updateFetcherState(key, getDoneFetcher(undefined)); - return; - } - - // If the loader threw a redirect Response, start a new REPLACE navigation - if (isRedirectResult(result)) { - if (pendingNavigationLoadId > originatingLoadId) { - // A new navigation was kicked off after our loader started, so that - // should take precedence over this redirect navigation - updateFetcherState(key, getDoneFetcher(undefined)); - return; - } else { - fetchRedirectIds.add(key); - await startRedirectNavigation(fetchRequest, result); - return; - } - } - - // Process any non-redirect errors thrown - if (isErrorResult(result)) { - setFetcherError(key, routeId, result.error); - return; - } - invariant(!isDeferredResult(result), "Unhandled fetcher deferred data"); - - // Put the fetcher back into an idle state - updateFetcherState(key, getDoneFetcher(result.data)); - } - - /** - * Utility function to handle redirects returned from an action or loader. - * Normally, a redirect "replaces" the navigation that triggered it. So, for - * example: - * - * - user is on /a - * - user clicks a link to /b - * - loader for /b redirects to /c - * - * In a non-JS app the browser would track the in-flight navigation to /b and - * then replace it with /c when it encountered the redirect response. In - * the end it would only ever update the URL bar with /c. - * - * In client-side routing using pushState/replaceState, we aim to emulate - * this behavior and we also do not update history until the end of the - * navigation (including processed redirects). This means that we never - * actually touch history until we've processed redirects, so we just use - * the history action from the original navigation (PUSH or REPLACE). - */ - async function startRedirectNavigation(request, redirect, _temp2) { - let { - submission, - fetcherSubmission, - replace - } = _temp2 === void 0 ? {} : _temp2; - if (redirect.response.headers.has("X-Remix-Revalidate")) { - isRevalidationRequired = true; - } - let location = redirect.response.headers.get("Location"); - invariant(location, "Expected a Location header on the redirect Response"); - location = normalizeRedirectLocation(location, new URL(request.url), basename); - let redirectLocation = createLocation(state.location, location, { - _isRedirect: true - }); - if (isBrowser) { - let isDocumentReload = false; - if (redirect.response.headers.has("X-Remix-Reload-Document")) { - // Hard reload if the response contained X-Remix-Reload-Document - isDocumentReload = true; - } else if (ABSOLUTE_URL_REGEX.test(location)) { - const url = init.history.createURL(location); - isDocumentReload = - // Hard reload if it's an absolute URL to a new origin - url.origin !== routerWindow.location.origin || - // Hard reload if it's an absolute URL that does not match our basename - stripBasename(url.pathname, basename) == null; - } - if (isDocumentReload) { - if (replace) { - routerWindow.location.replace(location); - } else { - routerWindow.location.assign(location); - } - return; - } - } - - // There's no need to abort on redirects, since we don't detect the - // redirect until the action/loaders have settled - pendingNavigationController = null; - let redirectHistoryAction = replace === true ? Action.Replace : Action.Push; - - // Use the incoming submission if provided, fallback on the active one in - // state.navigation - let { - formMethod, - formAction, - formEncType - } = state.navigation; - if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) { - submission = getSubmissionFromNavigation(state.navigation); - } - - // If this was a 307/308 submission we want to preserve the HTTP method and - // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the - // redirected location - let activeSubmission = submission || fetcherSubmission; - if (redirectPreserveMethodStatusCodes.has(redirect.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) { - await startNavigation(redirectHistoryAction, redirectLocation, { - submission: _extends({}, activeSubmission, { - formAction: location - }), - // Preserve this flag across redirects - preventScrollReset: pendingPreventScrollReset - }); - } else { - // If we have a navigation submission, we will preserve it through the - // redirect navigation - let overrideNavigation = getLoadingNavigation(redirectLocation, submission); - await startNavigation(redirectHistoryAction, redirectLocation, { - overrideNavigation, - // Send fetcher submissions through for shouldRevalidate - fetcherSubmission, - // Preserve this flag across redirects - preventScrollReset: pendingPreventScrollReset - }); - } - } - - // Utility wrapper for calling dataStrategy client-side without having to - // pass around the manifest, mapRouteProperties, etc. - async function callDataStrategy(type, request, matchesToLoad, matches) { - try { - let results = await callDataStrategyImpl(dataStrategyImpl, type, request, matchesToLoad, matches, manifest, mapRouteProperties); - return await Promise.all(results.map((result, i) => { - if (isRedirectHandlerResult(result)) { - let response = result.result; - return { - type: ResultType.redirect, - response: normalizeRelativeRoutingRedirectResponse(response, request, matchesToLoad[i].route.id, matches, basename, future.v7_relativeSplatPath) - }; - } - return convertHandlerResultToDataResult(result); - })); - } catch (e) { - // If the outer dataStrategy method throws, just return the error for all - // matches - and it'll naturally bubble to the root - return matchesToLoad.map(() => ({ - type: ResultType.error, - error: e - })); - } - } - async function callLoadersAndMaybeResolveData(currentMatches, matches, matchesToLoad, fetchersToLoad, request) { - let [loaderResults, ...fetcherResults] = await Promise.all([matchesToLoad.length ? callDataStrategy("loader", request, matchesToLoad, matches) : [], ...fetchersToLoad.map(f => { - if (f.matches && f.match && f.controller) { - let fetcherRequest = createClientSideRequest(init.history, f.path, f.controller.signal); - return callDataStrategy("loader", fetcherRequest, [f.match], f.matches).then(r => r[0]); - } else { - return Promise.resolve({ - type: ResultType.error, - error: getInternalRouterError(404, { - pathname: f.path - }) - }); - } - })]); - await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, loaderResults.map(() => request.signal), false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(f => f.match), fetcherResults, fetchersToLoad.map(f => f.controller ? f.controller.signal : null), true)]); - return { - loaderResults, - fetcherResults - }; - } - function interruptActiveLoads() { - // Every interruption triggers a revalidation - isRevalidationRequired = true; - - // Cancel pending route-level deferreds and mark cancelled routes for - // revalidation - cancelledDeferredRoutes.push(...cancelActiveDeferreds()); - - // Abort in-flight fetcher loads - fetchLoadMatches.forEach((_, key) => { - if (fetchControllers.has(key)) { - cancelledFetcherLoads.push(key); - abortFetcher(key); - } - }); - } - function updateFetcherState(key, fetcher, opts) { - if (opts === void 0) { - opts = {}; - } - state.fetchers.set(key, fetcher); - updateState({ - fetchers: new Map(state.fetchers) - }, { - flushSync: (opts && opts.flushSync) === true - }); - } - function setFetcherError(key, routeId, error, opts) { - if (opts === void 0) { - opts = {}; - } - let boundaryMatch = findNearestBoundary(state.matches, routeId); - deleteFetcher(key); - updateState({ - errors: { - [boundaryMatch.route.id]: error - }, - fetchers: new Map(state.fetchers) - }, { - flushSync: (opts && opts.flushSync) === true - }); - } - function getFetcher(key) { - if (future.v7_fetcherPersist) { - activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1); - // If this fetcher was previously marked for deletion, unmark it since we - // have a new instance - if (deletedFetchers.has(key)) { - deletedFetchers.delete(key); - } - } - return state.fetchers.get(key) || IDLE_FETCHER; - } - function deleteFetcher(key) { - let fetcher = state.fetchers.get(key); - // Don't abort the controller if this is a deletion of a fetcher.submit() - // in it's loading phase since - we don't want to abort the corresponding - // revalidation and want them to complete and land - if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) { - abortFetcher(key); - } - fetchLoadMatches.delete(key); - fetchReloadIds.delete(key); - fetchRedirectIds.delete(key); - deletedFetchers.delete(key); - state.fetchers.delete(key); - } - function deleteFetcherAndUpdateState(key) { - if (future.v7_fetcherPersist) { - let count = (activeFetchers.get(key) || 0) - 1; - if (count <= 0) { - activeFetchers.delete(key); - deletedFetchers.add(key); - } else { - activeFetchers.set(key, count); - } - } else { - deleteFetcher(key); - } - updateState({ - fetchers: new Map(state.fetchers) - }); - } - function abortFetcher(key) { - let controller = fetchControllers.get(key); - invariant(controller, "Expected fetch controller: " + key); - controller.abort(); - fetchControllers.delete(key); - } - function markFetchersDone(keys) { - for (let key of keys) { - let fetcher = getFetcher(key); - let doneFetcher = getDoneFetcher(fetcher.data); - state.fetchers.set(key, doneFetcher); - } - } - function markFetchRedirectsDone() { - let doneKeys = []; - let updatedFetchers = false; - for (let key of fetchRedirectIds) { - let fetcher = state.fetchers.get(key); - invariant(fetcher, "Expected fetcher: " + key); - if (fetcher.state === "loading") { - fetchRedirectIds.delete(key); - doneKeys.push(key); - updatedFetchers = true; - } - } - markFetchersDone(doneKeys); - return updatedFetchers; - } - function abortStaleFetchLoads(landedId) { - let yeetedKeys = []; - for (let [key, id] of fetchReloadIds) { - if (id < landedId) { - let fetcher = state.fetchers.get(key); - invariant(fetcher, "Expected fetcher: " + key); - if (fetcher.state === "loading") { - abortFetcher(key); - fetchReloadIds.delete(key); - yeetedKeys.push(key); - } - } - } - markFetchersDone(yeetedKeys); - return yeetedKeys.length > 0; - } - function getBlocker(key, fn) { - let blocker = state.blockers.get(key) || IDLE_BLOCKER; - if (blockerFunctions.get(key) !== fn) { - blockerFunctions.set(key, fn); - } - return blocker; - } - function deleteBlocker(key) { - state.blockers.delete(key); - blockerFunctions.delete(key); - } - - // Utility function to update blockers, ensuring valid state transitions - function updateBlocker(key, newBlocker) { - let blocker = state.blockers.get(key) || IDLE_BLOCKER; - - // Poor mans state machine :) - // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM - invariant(blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked", "Invalid blocker state transition: " + blocker.state + " -> " + newBlocker.state); - let blockers = new Map(state.blockers); - blockers.set(key, newBlocker); - updateState({ - blockers - }); - } - function shouldBlockNavigation(_ref4) { - let { - currentLocation, - nextLocation, - historyAction - } = _ref4; - if (blockerFunctions.size === 0) { - return; - } - - // We ony support a single active blocker at the moment since we don't have - // any compelling use cases for multi-blocker yet - if (blockerFunctions.size > 1) { - warning(false, "A router only supports one blocker at a time"); - } - let entries = Array.from(blockerFunctions.entries()); - let [blockerKey, blockerFunction] = entries[entries.length - 1]; - let blocker = state.blockers.get(blockerKey); - if (blocker && blocker.state === "proceeding") { - // If the blocker is currently proceeding, we don't need to re-check - // it and can let this navigation continue - return; - } - - // At this point, we know we're unblocked/blocked so we need to check the - // user-provided blocker function - if (blockerFunction({ - currentLocation, - nextLocation, - historyAction - })) { - return blockerKey; - } - } - function cancelActiveDeferreds(predicate) { - let cancelledRouteIds = []; - activeDeferreds.forEach((dfd, routeId) => { - if (!predicate || predicate(routeId)) { - // Cancel the deferred - but do not remove from activeDeferreds here - - // we rely on the subscribers to do that so our tests can assert proper - // cleanup via _internalActiveDeferreds - dfd.cancel(); - cancelledRouteIds.push(routeId); - activeDeferreds.delete(routeId); - } - }); - return cancelledRouteIds; - } - - // Opt in to capturing and reporting scroll positions during navigations, - // used by the component - function enableScrollRestoration(positions, getPosition, getKey) { - savedScrollPositions = positions; - getScrollPosition = getPosition; - getScrollRestorationKey = getKey || null; - - // Perform initial hydration scroll restoration, since we miss the boat on - // the initial updateState() because we've not yet rendered - // and therefore have no savedScrollPositions available - if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) { - initialScrollRestored = true; - let y = getSavedScrollPosition(state.location, state.matches); - if (y != null) { - updateState({ - restoreScrollPosition: y - }); - } - } - return () => { - savedScrollPositions = null; - getScrollPosition = null; - getScrollRestorationKey = null; - }; - } - function getScrollKey(location, matches) { - if (getScrollRestorationKey) { - let key = getScrollRestorationKey(location, matches.map(m => convertRouteMatchToUiMatch(m, state.loaderData))); - return key || location.key; - } - return location.key; - } - function saveScrollPosition(location, matches) { - if (savedScrollPositions && getScrollPosition) { - let key = getScrollKey(location, matches); - savedScrollPositions[key] = getScrollPosition(); - } - } - function getSavedScrollPosition(location, matches) { - if (savedScrollPositions) { - let key = getScrollKey(location, matches); - let y = savedScrollPositions[key]; - if (typeof y === "number") { - return y; - } - } - return null; - } - function _internalSetRoutes(newRoutes) { - manifest = {}; - inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest); - } - router = { - get basename() { - return basename; - }, - get future() { - return future; - }, - get state() { - return state; - }, - get routes() { - return dataRoutes; - }, - get window() { - return routerWindow; - }, - initialize, - subscribe, - enableScrollRestoration, - navigate, - fetch, - revalidate, - // Passthrough to history-aware createHref used by useHref so we get proper - // hash-aware URLs in DOM paths - createHref: to => init.history.createHref(to), - encodeLocation: to => init.history.encodeLocation(to), - getFetcher, - deleteFetcher: deleteFetcherAndUpdateState, - dispose, - getBlocker, - deleteBlocker, - _internalFetchControllers: fetchControllers, - _internalActiveDeferreds: activeDeferreds, - // TODO: Remove setRoutes, it's temporary to avoid dealing with - // updating the tree while validating the update algorithm. - _internalSetRoutes - }; - return router; -} -//#endregion - -//////////////////////////////////////////////////////////////////////////////// -//#region createStaticHandler -//////////////////////////////////////////////////////////////////////////////// - -const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred"); - -/** - * Future flags to toggle new feature behavior - */ - -function createStaticHandler(routes, opts) { - invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler"); - let manifest = {}; - let basename = (opts ? opts.basename : null) || "/"; - let mapRouteProperties; - if (opts != null && opts.mapRouteProperties) { - mapRouteProperties = opts.mapRouteProperties; - } else if (opts != null && opts.detectErrorBoundary) { - // If they are still using the deprecated version, wrap it with the new API - let detectErrorBoundary = opts.detectErrorBoundary; - mapRouteProperties = route => ({ - hasErrorBoundary: detectErrorBoundary(route) - }); - } else { - mapRouteProperties = defaultMapRouteProperties; - } - // Config driven behavior flags - let future = _extends({ - v7_relativeSplatPath: false, - v7_throwAbortReason: false - }, opts ? opts.future : null); - let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest); - - /** - * The query() method is intended for document requests, in which we want to - * call an optional action and potentially multiple loaders for all nested - * routes. It returns a StaticHandlerContext object, which is very similar - * to the router state (location, loaderData, actionData, errors, etc.) and - * also adds SSR-specific information such as the statusCode and headers - * from action/loaders Responses. - * - * It _should_ never throw and should report all errors through the - * returned context.errors object, properly associating errors to their error - * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be - * used to emulate React error boundaries during SSr by performing a second - * pass only down to the boundaryId. - * - * The one exception where we do not return a StaticHandlerContext is when a - * redirect response is returned or thrown from any action/loader. We - * propagate that out and return the raw Response so the HTTP server can - * return it directly. - * - * - `opts.requestContext` is an optional server context that will be passed - * to actions/loaders in the `context` parameter - * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent - * the bubbling of errors which allows single-fetch-type implementations - * where the client will handle the bubbling and we may need to return data - * for the handling route - */ - async function query(request, _temp3) { - let { - requestContext, - skipLoaderErrorBubbling, - unstable_dataStrategy - } = _temp3 === void 0 ? {} : _temp3; - let url = new URL(request.url); - let method = request.method; - let location = createLocation("", createPath(url), null, "default"); - let matches = matchRoutes(dataRoutes, location, basename); - - // SSR supports HEAD requests while SPA doesn't - if (!isValidMethod(method) && method !== "HEAD") { - let error = getInternalRouterError(405, { - method - }); - let { - matches: methodNotAllowedMatches, - route - } = getShortCircuitMatches(dataRoutes); - return { - basename, - location, - matches: methodNotAllowedMatches, - loaderData: {}, - actionData: null, - errors: { - [route.id]: error - }, - statusCode: error.status, - loaderHeaders: {}, - actionHeaders: {}, - activeDeferreds: null - }; - } else if (!matches) { - let error = getInternalRouterError(404, { - pathname: location.pathname - }); - let { - matches: notFoundMatches, - route - } = getShortCircuitMatches(dataRoutes); - return { - basename, - location, - matches: notFoundMatches, - loaderData: {}, - actionData: null, - errors: { - [route.id]: error - }, - statusCode: error.status, - loaderHeaders: {}, - actionHeaders: {}, - activeDeferreds: null - }; - } - let result = await queryImpl(request, location, matches, requestContext, unstable_dataStrategy || null, skipLoaderErrorBubbling === true, null); - if (isResponse(result)) { - return result; - } - - // When returning StaticHandlerContext, we patch back in the location here - // since we need it for React Context. But this helps keep our submit and - // loadRouteData operating on a Request instead of a Location - return _extends({ - location, - basename - }, result); - } - - /** - * The queryRoute() method is intended for targeted route requests, either - * for fetch ?_data requests or resource route requests. In this case, we - * are only ever calling a single action or loader, and we are returning the - * returned value directly. In most cases, this will be a Response returned - * from the action/loader, but it may be a primitive or other value as well - - * and in such cases the calling context should handle that accordingly. - * - * We do respect the throw/return differentiation, so if an action/loader - * throws, then this method will throw the value. This is important so we - * can do proper boundary identification in Remix where a thrown Response - * must go to the Catch Boundary but a returned Response is happy-path. - * - * One thing to note is that any Router-initiated Errors that make sense - * to associate with a status code will be thrown as an ErrorResponse - * instance which include the raw Error, such that the calling context can - * serialize the error as they see fit while including the proper response - * code. Examples here are 404 and 405 errors that occur prior to reaching - * any user-defined loaders. - * - * - `opts.routeId` allows you to specify the specific route handler to call. - * If not provided the handler will determine the proper route by matching - * against `request.url` - * - `opts.requestContext` is an optional server context that will be passed - * to actions/loaders in the `context` parameter - */ - async function queryRoute(request, _temp4) { - let { - routeId, - requestContext, - unstable_dataStrategy - } = _temp4 === void 0 ? {} : _temp4; - let url = new URL(request.url); - let method = request.method; - let location = createLocation("", createPath(url), null, "default"); - let matches = matchRoutes(dataRoutes, location, basename); - - // SSR supports HEAD requests while SPA doesn't - if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") { - throw getInternalRouterError(405, { - method - }); - } else if (!matches) { - throw getInternalRouterError(404, { - pathname: location.pathname - }); - } - let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location); - if (routeId && !match) { - throw getInternalRouterError(403, { - pathname: location.pathname, - routeId - }); - } else if (!match) { - // This should never hit I don't think? - throw getInternalRouterError(404, { - pathname: location.pathname - }); - } - let result = await queryImpl(request, location, matches, requestContext, unstable_dataStrategy || null, false, match); - if (isResponse(result)) { - return result; - } - let error = result.errors ? Object.values(result.errors)[0] : undefined; - if (error !== undefined) { - // If we got back result.errors, that means the loader/action threw - // _something_ that wasn't a Response, but it's not guaranteed/required - // to be an `instanceof Error` either, so we have to use throw here to - // preserve the "error" state outside of queryImpl. - throw error; - } - - // Pick off the right state value to return - if (result.actionData) { - return Object.values(result.actionData)[0]; - } - if (result.loaderData) { - var _result$activeDeferre; - let data = Object.values(result.loaderData)[0]; - if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) { - data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id]; - } - return data; - } - return undefined; - } - async function queryImpl(request, location, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch) { - invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal"); - try { - if (isMutationMethod(request.method.toLowerCase())) { - let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch != null); - return result; - } - let result = await loadRouteData(request, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch); - return isResponse(result) ? result : _extends({}, result, { - actionData: null, - actionHeaders: {} - }); - } catch (e) { - // If the user threw/returned a Response in callLoaderOrAction for a - // `queryRoute` call, we throw the `HandlerResult` to bail out early - // and then return or throw the raw Response here accordingly - if (isHandlerResult(e) && isResponse(e.result)) { - if (e.type === ResultType.error) { - throw e.result; - } - return e.result; - } - // Redirects are always returned since they don't propagate to catch - // boundaries - if (isRedirectResponse(e)) { - return e; - } - throw e; - } - } - async function submit(request, matches, actionMatch, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, isRouteRequest) { - let result; - if (!actionMatch.route.action && !actionMatch.route.lazy) { - let error = getInternalRouterError(405, { - method: request.method, - pathname: new URL(request.url).pathname, - routeId: actionMatch.route.id - }); - if (isRouteRequest) { - throw error; - } - result = { - type: ResultType.error, - error - }; - } else { - let results = await callDataStrategy("action", request, [actionMatch], matches, isRouteRequest, requestContext, unstable_dataStrategy); - result = results[0]; - if (request.signal.aborted) { - throwStaticHandlerAbortedError(request, isRouteRequest, future); - } - } - if (isRedirectResult(result)) { - // Uhhhh - this should never happen, we should always throw these from - // callLoaderOrAction, but the type narrowing here keeps TS happy and we - // can get back on the "throw all redirect responses" train here should - // this ever happen :/ - throw new Response(null, { - status: result.response.status, - headers: { - Location: result.response.headers.get("Location") - } - }); - } - if (isDeferredResult(result)) { - let error = getInternalRouterError(400, { - type: "defer-action" - }); - if (isRouteRequest) { - throw error; - } - result = { - type: ResultType.error, - error - }; - } - if (isRouteRequest) { - // Note: This should only be non-Response values if we get here, since - // isRouteRequest should throw any Response received in callLoaderOrAction - if (isErrorResult(result)) { - throw result.error; - } - return { - matches: [actionMatch], - loaderData: {}, - actionData: { - [actionMatch.route.id]: result.data - }, - errors: null, - // Note: statusCode + headers are unused here since queryRoute will - // return the raw Response or value - statusCode: 200, - loaderHeaders: {}, - actionHeaders: {}, - activeDeferreds: null - }; - } - - // Create a GET request for the loaders - let loaderRequest = new Request(request.url, { - headers: request.headers, - redirect: request.redirect, - signal: request.signal - }); - if (isErrorResult(result)) { - // Store off the pending error - we use it to determine which loaders - // to call and will commit it when we complete the navigation - let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id); - let context = await loadRouteData(loaderRequest, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, null, [boundaryMatch.route.id, result]); - - // action status codes take precedence over loader status codes - return _extends({}, context, { - statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500, - actionData: null, - actionHeaders: _extends({}, result.headers ? { - [actionMatch.route.id]: result.headers - } : {}) - }); - } - let context = await loadRouteData(loaderRequest, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, null); - return _extends({}, context, { - actionData: { - [actionMatch.route.id]: result.data - } - }, result.statusCode ? { - statusCode: result.statusCode - } : {}, { - actionHeaders: result.headers ? { - [actionMatch.route.id]: result.headers - } : {} - }); - } - async function loadRouteData(request, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch, pendingActionResult) { - let isRouteRequest = routeMatch != null; - - // Short circuit if we have no loaders to run (queryRoute()) - if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) { - throw getInternalRouterError(400, { - method: request.method, - pathname: new URL(request.url).pathname, - routeId: routeMatch == null ? void 0 : routeMatch.route.id - }); - } - let requestMatches = routeMatch ? [routeMatch] : pendingActionResult && isErrorResult(pendingActionResult[1]) ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) : matches; - let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy); - - // Short circuit if we have no loaders to run (query()) - if (matchesToLoad.length === 0) { - return { - matches, - // Add a null for all matched routes for proper revalidation on the client - loaderData: matches.reduce((acc, m) => Object.assign(acc, { - [m.route.id]: null - }), {}), - errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { - [pendingActionResult[0]]: pendingActionResult[1].error - } : null, - statusCode: 200, - loaderHeaders: {}, - activeDeferreds: null - }; - } - let results = await callDataStrategy("loader", request, matchesToLoad, matches, isRouteRequest, requestContext, unstable_dataStrategy); - if (request.signal.aborted) { - throwStaticHandlerAbortedError(request, isRouteRequest, future); - } - - // Process and commit output from loaders - let activeDeferreds = new Map(); - let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling); - - // Add a null for any non-loader matches for proper revalidation on the client - let executedLoaders = new Set(matchesToLoad.map(match => match.route.id)); - matches.forEach(match => { - if (!executedLoaders.has(match.route.id)) { - context.loaderData[match.route.id] = null; - } - }); - return _extends({}, context, { - matches, - activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null - }); - } - - // Utility wrapper for calling dataStrategy server-side without having to - // pass around the manifest, mapRouteProperties, etc. - async function callDataStrategy(type, request, matchesToLoad, matches, isRouteRequest, requestContext, unstable_dataStrategy) { - let results = await callDataStrategyImpl(unstable_dataStrategy || defaultDataStrategy, type, request, matchesToLoad, matches, manifest, mapRouteProperties, requestContext); - return await Promise.all(results.map((result, i) => { - if (isRedirectHandlerResult(result)) { - let response = result.result; - // Throw redirects and let the server handle them with an HTTP redirect - throw normalizeRelativeRoutingRedirectResponse(response, request, matchesToLoad[i].route.id, matches, basename, future.v7_relativeSplatPath); - } - if (isResponse(result.result) && isRouteRequest) { - // For SSR single-route requests, we want to hand Responses back - // directly without unwrapping - throw result; - } - return convertHandlerResultToDataResult(result); - })); - } - return { - dataRoutes, - query, - queryRoute - }; -} - -//#endregion - -//////////////////////////////////////////////////////////////////////////////// -//#region Helpers -//////////////////////////////////////////////////////////////////////////////// - -/** - * Given an existing StaticHandlerContext and an error thrown at render time, - * provide an updated StaticHandlerContext suitable for a second SSR render - */ -function getStaticContextFromError(routes, context, error) { - let newContext = _extends({}, context, { - statusCode: isRouteErrorResponse(error) ? error.status : 500, - errors: { - [context._deepestRenderedBoundaryId || routes[0].id]: error - } - }); - return newContext; -} -function throwStaticHandlerAbortedError(request, isRouteRequest, future) { - if (future.v7_throwAbortReason && request.signal.reason !== undefined) { - throw request.signal.reason; - } - let method = isRouteRequest ? "queryRoute" : "query"; - throw new Error(method + "() call aborted: " + request.method + " " + request.url); -} -function isSubmissionNavigation(opts) { - return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== undefined); -} -function normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) { - let contextualMatches; - let activeRouteMatch; - if (fromRouteId) { - // Grab matches up to the calling route so our route-relative logic is - // relative to the correct source route - contextualMatches = []; - for (let match of matches) { - contextualMatches.push(match); - if (match.route.id === fromRouteId) { - activeRouteMatch = match; - break; - } - } - } else { - contextualMatches = matches; - activeRouteMatch = matches[matches.length - 1]; - } - - // Resolve the relative path - let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === "path"); - - // When `to` is not specified we inherit search/hash from the current - // location, unlike when to="." and we just inherit the path. - // See https://github.com/remix-run/remix/issues/927 - if (to == null) { - path.search = location.search; - path.hash = location.hash; - } - - // Add an ?index param for matched index routes if we don't already have one - if ((to == null || to === "" || to === ".") && activeRouteMatch && activeRouteMatch.route.index && !hasNakedIndexQuery(path.search)) { - path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index"; - } - - // If we're operating within a basename, prepend it to the pathname. If - // this is a root navigation, then just use the raw basename which allows - // the basename to have full control over the presence of a trailing slash - // on root actions - if (prependBasename && basename !== "/") { - path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]); - } - return createPath(path); -} - -// Normalize navigation options by converting formMethod=GET formData objects to -// URLSearchParams so they behave identically to links with query params -function normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) { - // Return location verbatim on non-submission navigations - if (!opts || !isSubmissionNavigation(opts)) { - return { - path - }; - } - if (opts.formMethod && !isValidMethod(opts.formMethod)) { - return { - path, - error: getInternalRouterError(405, { - method: opts.formMethod - }) - }; - } - let getInvalidBodyError = () => ({ - path, - error: getInternalRouterError(400, { - type: "invalid-body" - }) - }); - - // Create a Submission on non-GET navigations - let rawFormMethod = opts.formMethod || "get"; - let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase(); - let formAction = stripHashFromPath(path); - if (opts.body !== undefined) { - if (opts.formEncType === "text/plain") { - // text only support POST/PUT/PATCH/DELETE submissions - if (!isMutationMethod(formMethod)) { - return getInvalidBodyError(); - } - let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? - // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data - Array.from(opts.body.entries()).reduce((acc, _ref5) => { - let [name, value] = _ref5; - return "" + acc + name + "=" + value + "\n"; - }, "") : String(opts.body); - return { - path, - submission: { - formMethod, - formAction, - formEncType: opts.formEncType, - formData: undefined, - json: undefined, - text - } - }; - } else if (opts.formEncType === "application/json") { - // json only supports POST/PUT/PATCH/DELETE submissions - if (!isMutationMethod(formMethod)) { - return getInvalidBodyError(); - } - try { - let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body; - return { - path, - submission: { - formMethod, - formAction, - formEncType: opts.formEncType, - formData: undefined, - json, - text: undefined - } - }; - } catch (e) { - return getInvalidBodyError(); - } - } - } - invariant(typeof FormData === "function", "FormData is not available in this environment"); - let searchParams; - let formData; - if (opts.formData) { - searchParams = convertFormDataToSearchParams(opts.formData); - formData = opts.formData; - } else if (opts.body instanceof FormData) { - searchParams = convertFormDataToSearchParams(opts.body); - formData = opts.body; - } else if (opts.body instanceof URLSearchParams) { - searchParams = opts.body; - formData = convertSearchParamsToFormData(searchParams); - } else if (opts.body == null) { - searchParams = new URLSearchParams(); - formData = new FormData(); - } else { - try { - searchParams = new URLSearchParams(opts.body); - formData = convertSearchParamsToFormData(searchParams); - } catch (e) { - return getInvalidBodyError(); - } - } - let submission = { - formMethod, - formAction, - formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded", - formData, - json: undefined, - text: undefined - }; - if (isMutationMethod(submission.formMethod)) { - return { - path, - submission - }; - } - - // Flatten submission onto URLSearchParams for GET submissions - let parsedPath = parsePath(path); - // On GET navigation submissions we can drop the ?index param from the - // resulting location since all loaders will run. But fetcher GET submissions - // only run a single loader so we need to preserve any incoming ?index params - if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) { - searchParams.append("index", ""); - } - parsedPath.search = "?" + searchParams; - return { - path: createPath(parsedPath), - submission - }; -} - -// Filter out all routes below any caught error as they aren't going to -// render so we don't need to load them -function getLoaderMatchesUntilBoundary(matches, boundaryId) { - let boundaryMatches = matches; - if (boundaryId) { - let index = matches.findIndex(m => m.route.id === boundaryId); - if (index >= 0) { - boundaryMatches = matches.slice(0, index); - } - } - return boundaryMatches; -} -function getMatchesToLoad(history, state, matches, submission, location, isInitialLoad, skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult) { - let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : undefined; - let currentUrl = history.createURL(state.location); - let nextUrl = history.createURL(location); - - // Pick navigation matches that are net-new or qualify for revalidation - let boundaryId = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[0] : undefined; - let boundaryMatches = boundaryId ? getLoaderMatchesUntilBoundary(matches, boundaryId) : matches; - - // Don't revalidate loaders by default after action 4xx/5xx responses - // when the flag is enabled. They can still opt-into revalidation via - // `shouldRevalidate` via `actionResult` - let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : undefined; - let shouldSkipRevalidation = skipActionErrorRevalidation && actionStatus && actionStatus >= 400; - let navigationMatches = boundaryMatches.filter((match, index) => { - let { - route - } = match; - if (route.lazy) { - // We haven't loaded this route yet so we don't know if it's got a loader! - return true; - } - if (route.loader == null) { - return false; - } - if (isInitialLoad) { - if (typeof route.loader !== "function" || route.loader.hydrate) { - return true; - } - return state.loaderData[route.id] === undefined && ( - // Don't re-run if the loader ran and threw an error - !state.errors || state.errors[route.id] === undefined); - } - - // Always call the loader on new route instances and pending defer cancellations - if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) { - return true; - } - - // This is the default implementation for when we revalidate. If the route - // provides it's own implementation, then we give them full control but - // provide this value so they can leverage it if needed after they check - // their own specific use cases - let currentRouteMatch = state.matches[index]; - let nextRouteMatch = match; - return shouldRevalidateLoader(match, _extends({ - currentUrl, - currentParams: currentRouteMatch.params, - nextUrl, - nextParams: nextRouteMatch.params - }, submission, { - actionResult, - unstable_actionStatus: actionStatus, - defaultShouldRevalidate: shouldSkipRevalidation ? false : - // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate - isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search || - // Search params affect all loaders - currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch) - })); - }); - - // Pick fetcher.loads that need to be revalidated - let revalidatingFetchers = []; - fetchLoadMatches.forEach((f, key) => { - // Don't revalidate: - // - on initial load (shouldn't be any fetchers then anyway) - // - if fetcher won't be present in the subsequent render - // - no longer matches the URL (v7_fetcherPersist=false) - // - was unmounted but persisted due to v7_fetcherPersist=true - if (isInitialLoad || !matches.some(m => m.route.id === f.routeId) || deletedFetchers.has(key)) { - return; - } - let fetcherMatches = matchRoutes(routesToUse, f.path, basename); - - // If the fetcher path no longer matches, push it in with null matches so - // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is - // currently only a use-case for Remix HMR where the route tree can change - // at runtime and remove a route previously loaded via a fetcher - if (!fetcherMatches) { - revalidatingFetchers.push({ - key, - routeId: f.routeId, - path: f.path, - matches: null, - match: null, - controller: null - }); - return; - } - - // Revalidating fetchers are decoupled from the route matches since they - // load from a static href. They revalidate based on explicit revalidation - // (submission, useRevalidator, or X-Remix-Revalidate) - let fetcher = state.fetchers.get(key); - let fetcherMatch = getTargetMatch(fetcherMatches, f.path); - let shouldRevalidate = false; - if (fetchRedirectIds.has(key)) { - // Never trigger a revalidation of an actively redirecting fetcher - shouldRevalidate = false; - } else if (cancelledFetcherLoads.includes(key)) { - // Always revalidate if the fetcher was cancelled - shouldRevalidate = true; - } else if (fetcher && fetcher.state !== "idle" && fetcher.data === undefined) { - // If the fetcher hasn't ever completed loading yet, then this isn't a - // revalidation, it would just be a brand new load if an explicit - // revalidation is required - shouldRevalidate = isRevalidationRequired; - } else { - // Otherwise fall back on any user-defined shouldRevalidate, defaulting - // to explicit revalidations only - shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({ - currentUrl, - currentParams: state.matches[state.matches.length - 1].params, - nextUrl, - nextParams: matches[matches.length - 1].params - }, submission, { - actionResult, - unstable_actionStatus: actionStatus, - defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired - })); - } - if (shouldRevalidate) { - revalidatingFetchers.push({ - key, - routeId: f.routeId, - path: f.path, - matches: fetcherMatches, - match: fetcherMatch, - controller: new AbortController() - }); - } - }); - return [navigationMatches, revalidatingFetchers]; -} -function isNewLoader(currentLoaderData, currentMatch, match) { - let isNew = - // [a] -> [a, b] - !currentMatch || - // [a, b] -> [a, c] - match.route.id !== currentMatch.route.id; - - // Handle the case that we don't have data for a re-used route, potentially - // from a prior error or from a cancelled pending deferred - let isMissingData = currentLoaderData[match.route.id] === undefined; - - // Always load if this is a net-new route or we don't yet have data - return isNew || isMissingData; -} -function isNewRouteInstance(currentMatch, match) { - let currentPath = currentMatch.route.path; - return ( - // param change for this match, /users/123 -> /users/456 - currentMatch.pathname !== match.pathname || - // splat param changed, which is not present in match.path - // e.g. /files/images/avatar.jpg -> files/finances.xls - currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"] - ); -} -function shouldRevalidateLoader(loaderMatch, arg) { - if (loaderMatch.route.shouldRevalidate) { - let routeChoice = loaderMatch.route.shouldRevalidate(arg); - if (typeof routeChoice === "boolean") { - return routeChoice; - } - } - return arg.defaultShouldRevalidate; -} - -/** - * Execute route.lazy() methods to lazily load route modules (loader, action, - * shouldRevalidate) and update the routeManifest in place which shares objects - * with dataRoutes so those get updated as well. - */ -async function loadLazyRouteModule(route, mapRouteProperties, manifest) { - if (!route.lazy) { - return; - } - let lazyRoute = await route.lazy(); - - // If the lazy route function was executed and removed by another parallel - // call then we can return - first lazy() to finish wins because the return - // value of lazy is expected to be static - if (!route.lazy) { - return; - } - let routeToUpdate = manifest[route.id]; - invariant(routeToUpdate, "No route found in manifest"); - - // Update the route in place. This should be safe because there's no way - // we could yet be sitting on this route as we can't get there without - // resolving lazy() first. - // - // This is different than the HMR "update" use-case where we may actively be - // on the route being updated. The main concern boils down to "does this - // mutation affect any ongoing navigations or any current state.matches - // values?". If not, it should be safe to update in place. - let routeUpdates = {}; - for (let lazyRouteProperty in lazyRoute) { - let staticRouteValue = routeToUpdate[lazyRouteProperty]; - let isPropertyStaticallyDefined = staticRouteValue !== undefined && - // This property isn't static since it should always be updated based - // on the route updates - lazyRouteProperty !== "hasErrorBoundary"; - warning(!isPropertyStaticallyDefined, "Route \"" + routeToUpdate.id + "\" has a static property \"" + lazyRouteProperty + "\" " + "defined but its lazy function is also returning a value for this property. " + ("The lazy route property \"" + lazyRouteProperty + "\" will be ignored.")); - if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) { - routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty]; - } - } - - // Mutate the route with the provided updates. Do this first so we pass - // the updated version to mapRouteProperties - Object.assign(routeToUpdate, routeUpdates); - - // Mutate the `hasErrorBoundary` property on the route based on the route - // updates and remove the `lazy` function so we don't resolve the lazy - // route again. - Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), { - lazy: undefined - })); -} - -// Default implementation of `dataStrategy` which fetches all loaders in parallel -function defaultDataStrategy(opts) { - return Promise.all(opts.matches.map(m => m.resolve())); -} -async function callDataStrategyImpl(dataStrategyImpl, type, request, matchesToLoad, matches, manifest, mapRouteProperties, requestContext) { - let routeIdsToLoad = matchesToLoad.reduce((acc, m) => acc.add(m.route.id), new Set()); - let loadedMatches = new Set(); - - // Send all matches here to allow for a middleware-type implementation. - // handler will be a no-op for unneeded routes and we filter those results - // back out below. - let results = await dataStrategyImpl({ - matches: matches.map(match => { - let shouldLoad = routeIdsToLoad.has(match.route.id); - // `resolve` encapsulates the route.lazy, executing the - // loader/action, and mapping return values/thrown errors to a - // HandlerResult. Users can pass a callback to take fine-grained control - // over the execution of the loader/action - let resolve = handlerOverride => { - loadedMatches.add(match.route.id); - return shouldLoad ? callLoaderOrAction(type, request, match, manifest, mapRouteProperties, handlerOverride, requestContext) : Promise.resolve({ - type: ResultType.data, - result: undefined - }); - }; - return _extends({}, match, { - shouldLoad, - resolve - }); - }), - request, - params: matches[0].params, - context: requestContext - }); - - // Throw if any loadRoute implementations not called since they are what - // ensures a route is fully loaded - matches.forEach(m => invariant(loadedMatches.has(m.route.id), "`match.resolve()` was not called for route id \"" + m.route.id + "\". " + "You must call `match.resolve()` on every match passed to " + "`dataStrategy` to ensure all routes are properly loaded.")); - - // Filter out any middleware-only matches for which we didn't need to run handlers - return results.filter((_, i) => routeIdsToLoad.has(matches[i].route.id)); -} - -// Default logic for calling a loader/action is the user has no specified a dataStrategy -async function callLoaderOrAction(type, request, match, manifest, mapRouteProperties, handlerOverride, staticContext) { - let result; - let onReject; - let runHandler = handler => { - // Setup a promise we can race against so that abort signals short circuit - let reject; - // This will never resolve so safe to type it as Promise to - // satisfy the function return value - let abortPromise = new Promise((_, r) => reject = r); - onReject = () => reject(); - request.signal.addEventListener("abort", onReject); - let actualHandler = ctx => { - if (typeof handler !== "function") { - return Promise.reject(new Error("You cannot call the handler for a route which defines a boolean " + ("\"" + type + "\" [routeId: " + match.route.id + "]"))); - } - return handler({ - request, - params: match.params, - context: staticContext - }, ...(ctx !== undefined ? [ctx] : [])); - }; - let handlerPromise; - if (handlerOverride) { - handlerPromise = handlerOverride(ctx => actualHandler(ctx)); - } else { - handlerPromise = (async () => { - try { - let val = await actualHandler(); - return { - type: "data", - result: val - }; - } catch (e) { - return { - type: "error", - result: e - }; - } - })(); - } - return Promise.race([handlerPromise, abortPromise]); - }; - try { - let handler = match.route[type]; - if (match.route.lazy) { - if (handler) { - // Run statically defined handler in parallel with lazy() - let handlerError; - let [value] = await Promise.all([ - // If the handler throws, don't let it immediately bubble out, - // since we need to let the lazy() execution finish so we know if this - // route has a boundary that can handle the error - runHandler(handler).catch(e => { - handlerError = e; - }), loadLazyRouteModule(match.route, mapRouteProperties, manifest)]); - if (handlerError !== undefined) { - throw handlerError; - } - result = value; - } else { - // Load lazy route module, then run any returned handler - await loadLazyRouteModule(match.route, mapRouteProperties, manifest); - handler = match.route[type]; - if (handler) { - // Handler still runs even if we got interrupted to maintain consistency - // with un-abortable behavior of handler execution on non-lazy or - // previously-lazy-loaded routes - result = await runHandler(handler); - } else if (type === "action") { - let url = new URL(request.url); - let pathname = url.pathname + url.search; - throw getInternalRouterError(405, { - method: request.method, - pathname, - routeId: match.route.id - }); - } else { - // lazy() route has no loader to run. Short circuit here so we don't - // hit the invariant below that errors on returning undefined. - return { - type: ResultType.data, - result: undefined - }; - } - } - } else if (!handler) { - let url = new URL(request.url); - let pathname = url.pathname + url.search; - throw getInternalRouterError(404, { - pathname - }); - } else { - result = await runHandler(handler); - } - invariant(result.result !== undefined, "You defined " + (type === "action" ? "an action" : "a loader") + " for route " + ("\"" + match.route.id + "\" but didn't return anything from your `" + type + "` ") + "function. Please return a value or `null`."); - } catch (e) { - // We should already be catching and converting normal handler executions to - // HandlerResults and returning them, so anything that throws here is an - // unexpected error we still need to wrap - return { - type: ResultType.error, - result: e - }; - } finally { - if (onReject) { - request.signal.removeEventListener("abort", onReject); - } - } - return result; -} -async function convertHandlerResultToDataResult(handlerResult) { - let { - result, - type, - status - } = handlerResult; - if (isResponse(result)) { - let data; - try { - let contentType = result.headers.get("Content-Type"); - // Check between word boundaries instead of startsWith() due to the last - // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type - if (contentType && /\bapplication\/json\b/.test(contentType)) { - if (result.body == null) { - data = null; - } else { - data = await result.json(); - } - } else { - data = await result.text(); - } - } catch (e) { - return { - type: ResultType.error, - error: e - }; - } - if (type === ResultType.error) { - return { - type: ResultType.error, - error: new ErrorResponseImpl(result.status, result.statusText, data), - statusCode: result.status, - headers: result.headers - }; - } - return { - type: ResultType.data, - data, - statusCode: result.status, - headers: result.headers - }; - } - if (type === ResultType.error) { - return { - type: ResultType.error, - error: result, - statusCode: isRouteErrorResponse(result) ? result.status : status - }; - } - if (isDeferredData(result)) { - var _result$init, _result$init2; - return { - type: ResultType.deferred, - deferredData: result, - statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status, - headers: ((_result$init2 = result.init) == null ? void 0 : _result$init2.headers) && new Headers(result.init.headers) - }; - } - return { - type: ResultType.data, - data: result, - statusCode: status - }; -} - -// Support relative routing in internal redirects -function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, v7_relativeSplatPath) { - let location = response.headers.get("Location"); - invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header"); - if (!ABSOLUTE_URL_REGEX.test(location)) { - let trimmedMatches = matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1); - location = normalizeTo(new URL(request.url), trimmedMatches, basename, true, location, v7_relativeSplatPath); - response.headers.set("Location", location); - } - return response; -} -function normalizeRedirectLocation(location, currentUrl, basename) { - if (ABSOLUTE_URL_REGEX.test(location)) { - // Strip off the protocol+origin for same-origin + same-basename absolute redirects - let normalizedLocation = location; - let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation); - let isSameBasename = stripBasename(url.pathname, basename) != null; - if (url.origin === currentUrl.origin && isSameBasename) { - return url.pathname + url.search + url.hash; - } - } - return location; -} - -// Utility method for creating the Request instances for loaders/actions during -// client-side navigations and fetches. During SSR we will always have a -// Request instance from the static handler (query/queryRoute) -function createClientSideRequest(history, location, signal, submission) { - let url = history.createURL(stripHashFromPath(location)).toString(); - let init = { - signal - }; - if (submission && isMutationMethod(submission.formMethod)) { - let { - formMethod, - formEncType - } = submission; - // Didn't think we needed this but it turns out unlike other methods, patch - // won't be properly normalized to uppercase and results in a 405 error. - // See: https://fetch.spec.whatwg.org/#concept-method - init.method = formMethod.toUpperCase(); - if (formEncType === "application/json") { - init.headers = new Headers({ - "Content-Type": formEncType - }); - init.body = JSON.stringify(submission.json); - } else if (formEncType === "text/plain") { - // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) - init.body = submission.text; - } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) { - // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) - init.body = convertFormDataToSearchParams(submission.formData); - } else { - // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) - init.body = submission.formData; - } - } - return new Request(url, init); -} -function convertFormDataToSearchParams(formData) { - let searchParams = new URLSearchParams(); - for (let [key, value] of formData.entries()) { - // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs - searchParams.append(key, typeof value === "string" ? value : value.name); - } - return searchParams; -} -function convertSearchParamsToFormData(searchParams) { - let formData = new FormData(); - for (let [key, value] of searchParams.entries()) { - formData.append(key, value); - } - return formData; -} -function processRouteLoaderData(matches, matchesToLoad, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling) { - // Fill in loaderData/errors from our loaders - let loaderData = {}; - let errors = null; - let statusCode; - let foundError = false; - let loaderHeaders = {}; - let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : undefined; - - // Process loader results into state.loaderData/state.errors - results.forEach((result, index) => { - let id = matchesToLoad[index].route.id; - invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData"); - if (isErrorResult(result)) { - let error = result.error; - // If we have a pending action error, we report it at the highest-route - // that throws a loader error, and then clear it out to indicate that - // it was consumed - if (pendingError !== undefined) { - error = pendingError; - pendingError = undefined; - } - errors = errors || {}; - if (skipLoaderErrorBubbling) { - errors[id] = error; - } else { - // Look upwards from the matched route for the closest ancestor error - // boundary, defaulting to the root match. Prefer higher error values - // if lower errors bubble to the same boundary - let boundaryMatch = findNearestBoundary(matches, id); - if (errors[boundaryMatch.route.id] == null) { - errors[boundaryMatch.route.id] = error; - } - } - - // Clear our any prior loaderData for the throwing route - loaderData[id] = undefined; - - // Once we find our first (highest) error, we set the status code and - // prevent deeper status codes from overriding - if (!foundError) { - foundError = true; - statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500; - } - if (result.headers) { - loaderHeaders[id] = result.headers; - } - } else { - if (isDeferredResult(result)) { - activeDeferreds.set(id, result.deferredData); - loaderData[id] = result.deferredData.data; - // Error status codes always override success status codes, but if all - // loaders are successful we take the deepest status code. - if (result.statusCode != null && result.statusCode !== 200 && !foundError) { - statusCode = result.statusCode; - } - if (result.headers) { - loaderHeaders[id] = result.headers; - } - } else { - loaderData[id] = result.data; - // Error status codes always override success status codes, but if all - // loaders are successful we take the deepest status code. - if (result.statusCode && result.statusCode !== 200 && !foundError) { - statusCode = result.statusCode; - } - if (result.headers) { - loaderHeaders[id] = result.headers; - } - } - } - }); - - // If we didn't consume the pending action error (i.e., all loaders - // resolved), then consume it here. Also clear out any loaderData for the - // throwing route - if (pendingError !== undefined && pendingActionResult) { - errors = { - [pendingActionResult[0]]: pendingError - }; - loaderData[pendingActionResult[0]] = undefined; - } - return { - loaderData, - errors, - statusCode: statusCode || 200, - loaderHeaders - }; -} -function processLoaderData(state, matches, matchesToLoad, results, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds) { - let { - loaderData, - errors - } = processRouteLoaderData(matches, matchesToLoad, results, pendingActionResult, activeDeferreds, false // This method is only called client side so we always want to bubble - ); - - // Process results from our revalidating fetchers - for (let index = 0; index < revalidatingFetchers.length; index++) { - let { - key, - match, - controller - } = revalidatingFetchers[index]; - invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, "Did not find corresponding fetcher result"); - let result = fetcherResults[index]; - - // Process fetcher non-redirect errors - if (controller && controller.signal.aborted) { - // Nothing to do for aborted fetchers - continue; - } else if (isErrorResult(result)) { - let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id); - if (!(errors && errors[boundaryMatch.route.id])) { - errors = _extends({}, errors, { - [boundaryMatch.route.id]: result.error - }); - } - state.fetchers.delete(key); - } else if (isRedirectResult(result)) { - // Should never get here, redirects should get processed above, but we - // keep this to type narrow to a success result in the else - invariant(false, "Unhandled fetcher revalidation redirect"); - } else if (isDeferredResult(result)) { - // Should never get here, deferred data should be awaited for fetchers - // in resolveDeferredResults - invariant(false, "Unhandled fetcher deferred data"); - } else { - let doneFetcher = getDoneFetcher(result.data); - state.fetchers.set(key, doneFetcher); - } - } - return { - loaderData, - errors - }; -} -function mergeLoaderData(loaderData, newLoaderData, matches, errors) { - let mergedLoaderData = _extends({}, newLoaderData); - for (let match of matches) { - let id = match.route.id; - if (newLoaderData.hasOwnProperty(id)) { - if (newLoaderData[id] !== undefined) { - mergedLoaderData[id] = newLoaderData[id]; - } - } else if (loaderData[id] !== undefined && match.route.loader) { - // Preserve existing keys not included in newLoaderData and where a loader - // wasn't removed by HMR - mergedLoaderData[id] = loaderData[id]; - } - if (errors && errors.hasOwnProperty(id)) { - // Don't keep any loader data below the boundary - break; - } - } - return mergedLoaderData; -} -function getActionDataForCommit(pendingActionResult) { - if (!pendingActionResult) { - return {}; - } - return isErrorResult(pendingActionResult[1]) ? { - // Clear out prior actionData on errors - actionData: {} - } : { - actionData: { - [pendingActionResult[0]]: pendingActionResult[1].data - } - }; -} - -// Find the nearest error boundary, looking upwards from the leaf route (or the -// route specified by routeId) for the closest ancestor error boundary, -// defaulting to the root match -function findNearestBoundary(matches, routeId) { - let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches]; - return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0]; -} -function getShortCircuitMatches(routes) { - // Prefer a root layout route if present, otherwise shim in a route object - let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === "/") || { - id: "__shim-error-route__" - }; - return { - matches: [{ - params: {}, - pathname: "", - pathnameBase: "", - route - }], - route - }; -} -function getInternalRouterError(status, _temp5) { - let { - pathname, - routeId, - method, - type - } = _temp5 === void 0 ? {} : _temp5; - let statusText = "Unknown Server Error"; - let errorMessage = "Unknown @remix-run/router error"; - if (status === 400) { - statusText = "Bad Request"; - if (method && pathname && routeId) { - errorMessage = "You made a " + method + " request to \"" + pathname + "\" but " + ("did not provide a `loader` for route \"" + routeId + "\", ") + "so there is no way to handle the request."; - } else if (type === "defer-action") { - errorMessage = "defer() is not supported in actions"; - } else if (type === "invalid-body") { - errorMessage = "Unable to encode submission body"; - } - } else if (status === 403) { - statusText = "Forbidden"; - errorMessage = "Route \"" + routeId + "\" does not match URL \"" + pathname + "\""; - } else if (status === 404) { - statusText = "Not Found"; - errorMessage = "No route matches URL \"" + pathname + "\""; - } else if (status === 405) { - statusText = "Method Not Allowed"; - if (method && pathname && routeId) { - errorMessage = "You made a " + method.toUpperCase() + " request to \"" + pathname + "\" but " + ("did not provide an `action` for route \"" + routeId + "\", ") + "so there is no way to handle the request."; - } else if (method) { - errorMessage = "Invalid request method \"" + method.toUpperCase() + "\""; - } - } - return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true); -} - -// Find any returned redirect errors, starting from the lowest match -function findRedirect(results) { - for (let i = results.length - 1; i >= 0; i--) { - let result = results[i]; - if (isRedirectResult(result)) { - return { - result, - idx: i - }; - } - } -} -function stripHashFromPath(path) { - let parsedPath = typeof path === "string" ? parsePath(path) : path; - return createPath(_extends({}, parsedPath, { - hash: "" - })); -} -function isHashChangeOnly(a, b) { - if (a.pathname !== b.pathname || a.search !== b.search) { - return false; - } - if (a.hash === "") { - // /page -> /page#hash - return b.hash !== ""; - } else if (a.hash === b.hash) { - // /page#hash -> /page#hash - return true; - } else if (b.hash !== "") { - // /page#hash -> /page#other - return true; - } - - // If the hash is removed the browser will re-perform a request to the server - // /page#hash -> /page - return false; -} -function isHandlerResult(result) { - return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === ResultType.data || result.type === ResultType.error); -} -function isRedirectHandlerResult(result) { - return isResponse(result.result) && redirectStatusCodes.has(result.result.status); -} -function isDeferredResult(result) { - return result.type === ResultType.deferred; -} -function isErrorResult(result) { - return result.type === ResultType.error; -} -function isRedirectResult(result) { - return (result && result.type) === ResultType.redirect; -} -function isDeferredData(value) { - let deferred = value; - return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function"; -} -function isResponse(value) { - return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined"; -} -function isRedirectResponse(result) { - if (!isResponse(result)) { - return false; - } - let status = result.status; - let location = result.headers.get("Location"); - return status >= 300 && status <= 399 && location != null; -} -function isValidMethod(method) { - return validRequestMethods.has(method.toLowerCase()); -} -function isMutationMethod(method) { - return validMutationMethods.has(method.toLowerCase()); -} -async function resolveDeferredResults(currentMatches, matchesToLoad, results, signals, isFetcher, currentLoaderData) { - for (let index = 0; index < results.length; index++) { - let result = results[index]; - let match = matchesToLoad[index]; - // If we don't have a match, then we can have a deferred result to do - // anything with. This is for revalidating fetchers where the route was - // removed during HMR - if (!match) { - continue; - } - let currentMatch = currentMatches.find(m => m.route.id === match.route.id); - let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined; - if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) { - // Note: we do not have to touch activeDeferreds here since we race them - // against the signal in resolveDeferredData and they'll get aborted - // there if needed - let signal = signals[index]; - invariant(signal, "Expected an AbortSignal for revalidating fetcher deferred result"); - await resolveDeferredData(result, signal, isFetcher).then(result => { - if (result) { - results[index] = result || results[index]; - } - }); - } - } -} -async function resolveDeferredData(result, signal, unwrap) { - if (unwrap === void 0) { - unwrap = false; - } - let aborted = await result.deferredData.resolveData(signal); - if (aborted) { - return; - } - if (unwrap) { - try { - return { - type: ResultType.data, - data: result.deferredData.unwrappedData - }; - } catch (e) { - // Handle any TrackedPromise._error values encountered while unwrapping - return { - type: ResultType.error, - error: e - }; - } - } - return { - type: ResultType.data, - data: result.deferredData.data - }; -} -function hasNakedIndexQuery(search) { - return new URLSearchParams(search).getAll("index").some(v => v === ""); -} -function getTargetMatch(matches, location) { - let search = typeof location === "string" ? parsePath(location).search : location.search; - if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) { - // Return the leaf index route when index is present - return matches[matches.length - 1]; - } - // Otherwise grab the deepest "path contributing" match (ignoring index and - // pathless layout routes) - let pathMatches = getPathContributingMatches(matches); - return pathMatches[pathMatches.length - 1]; -} -function getSubmissionFromNavigation(navigation) { - let { - formMethod, - formAction, - formEncType, - text, - formData, - json - } = navigation; - if (!formMethod || !formAction || !formEncType) { - return; - } - if (text != null) { - return { - formMethod, - formAction, - formEncType, - formData: undefined, - json: undefined, - text - }; - } else if (formData != null) { - return { - formMethod, - formAction, - formEncType, - formData, - json: undefined, - text: undefined - }; - } else if (json !== undefined) { - return { - formMethod, - formAction, - formEncType, - formData: undefined, - json, - text: undefined - }; - } -} -function getLoadingNavigation(location, submission) { - if (submission) { - let navigation = { - state: "loading", - location, - formMethod: submission.formMethod, - formAction: submission.formAction, - formEncType: submission.formEncType, - formData: submission.formData, - json: submission.json, - text: submission.text - }; - return navigation; - } else { - let navigation = { - state: "loading", - location, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined - }; - return navigation; - } -} -function getSubmittingNavigation(location, submission) { - let navigation = { - state: "submitting", - location, - formMethod: submission.formMethod, - formAction: submission.formAction, - formEncType: submission.formEncType, - formData: submission.formData, - json: submission.json, - text: submission.text - }; - return navigation; -} -function getLoadingFetcher(submission, data) { - if (submission) { - let fetcher = { - state: "loading", - formMethod: submission.formMethod, - formAction: submission.formAction, - formEncType: submission.formEncType, - formData: submission.formData, - json: submission.json, - text: submission.text, - data - }; - return fetcher; - } else { - let fetcher = { - state: "loading", - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined, - data - }; - return fetcher; - } -} -function getSubmittingFetcher(submission, existingFetcher) { - let fetcher = { - state: "submitting", - formMethod: submission.formMethod, - formAction: submission.formAction, - formEncType: submission.formEncType, - formData: submission.formData, - json: submission.json, - text: submission.text, - data: existingFetcher ? existingFetcher.data : undefined - }; - return fetcher; -} -function getDoneFetcher(data) { - let fetcher = { - state: "idle", - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined, - data - }; - return fetcher; -} -function restoreAppliedTransitions(_window, transitions) { - try { - let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY); - if (sessionPositions) { - let json = JSON.parse(sessionPositions); - for (let [k, v] of Object.entries(json || {})) { - if (v && Array.isArray(v)) { - transitions.set(k, new Set(v || [])); - } - } - } - } catch (e) { - // no-op, use default empty object - } -} -function persistAppliedTransitions(_window, transitions) { - if (transitions.size > 0) { - let json = {}; - for (let [k, v] of transitions) { - json[k] = [...v]; - } - try { - _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json)); - } catch (error) { - warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ")."); - } - } -} - -//#endregion - -exports.AbortedDeferredError = AbortedDeferredError; -exports.Action = Action; -exports.IDLE_BLOCKER = IDLE_BLOCKER; -exports.IDLE_FETCHER = IDLE_FETCHER; -exports.IDLE_NAVIGATION = IDLE_NAVIGATION; -exports.UNSAFE_DEFERRED_SYMBOL = UNSAFE_DEFERRED_SYMBOL; -exports.UNSAFE_DeferredData = DeferredData; -exports.UNSAFE_ErrorResponseImpl = ErrorResponseImpl; -exports.UNSAFE_convertRouteMatchToUiMatch = convertRouteMatchToUiMatch; -exports.UNSAFE_convertRoutesToDataRoutes = convertRoutesToDataRoutes; -exports.UNSAFE_getResolveToMatches = getResolveToMatches; -exports.UNSAFE_invariant = invariant; -exports.UNSAFE_warning = warning; -exports.createBrowserHistory = createBrowserHistory; -exports.createHashHistory = createHashHistory; -exports.createMemoryHistory = createMemoryHistory; -exports.createPath = createPath; -exports.createRouter = createRouter; -exports.createStaticHandler = createStaticHandler; -exports.defer = defer; -exports.generatePath = generatePath; -exports.getStaticContextFromError = getStaticContextFromError; -exports.getToPathname = getToPathname; -exports.isDeferredData = isDeferredData; -exports.isRouteErrorResponse = isRouteErrorResponse; -exports.joinPaths = joinPaths; -exports.json = json; -exports.matchPath = matchPath; -exports.matchRoutes = matchRoutes; -exports.normalizePathname = normalizePathname; -exports.parsePath = parsePath; -exports.redirect = redirect; -exports.redirectDocument = redirectDocument; -exports.resolvePath = resolvePath; -exports.resolveTo = resolveTo; -exports.stripBasename = stripBasename; -//# sourceMappingURL=router.cjs.js.map diff --git a/node_modules/@remix-run/router/dist/router.cjs.js.map b/node_modules/@remix-run/router/dist/router.cjs.js.map deleted file mode 100644 index 79899445..00000000 --- a/node_modules/@remix-run/router/dist/router.cjs.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"router.cjs.js","sources":["../history.ts","../utils.ts","../router.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 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, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial;\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 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;\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 () 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(\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 // eslint-disable-next-line no-console\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 // eslint-disable-next-line no-empty\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 {\n let location: Readonly = {\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 */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial) {\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 */\nexport function parsePath(path: string): Partial {\n let parsedPath: Partial = {};\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 { 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 deferred = \"deferred\",\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 * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n type: ResultType.deferred;\n deferredData: DeferredData;\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 =\n | SuccessResult\n | DeferredResult\n | RedirectResult\n | ErrorResult;\n\n/**\n * Result from a loader or action called via dataStrategy\n */\nexport interface HandlerResult {\n type: \"data\" | \"error\";\n result: unknown; // data, Error, Response, DeferredData\n status?: number;\n}\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase;\n\n/**\n * Users can specify either lowercase or uppercase form methods on ``,\n * useSubmit(), ``, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude;\n\n/**\n * In v7, 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 V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude;\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 | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_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 {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs\n extends DataFunctionArgs {}\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 | null;\n\ntype DataFunctionReturnValue = Promise | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction = {\n (\n args: LoaderFunctionArgs,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (\n args: ActionFunctionArgs,\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 unstable_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\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\nexport interface DataStrategyMatch\n extends AgnosticRouteMatch {\n shouldLoad: boolean;\n resolve: (\n handlerOverride?: (\n handler: (ctx?: unknown) => DataFunctionReturnValue\n ) => Promise\n ) => Promise;\n}\n\nexport interface DataStrategyFunctionArgs\n extends DataFunctionArgs {\n matches: DataStrategyMatch[];\n}\n\nexport interface DataStrategyFunction {\n (args: DataStrategyFunctionArgs): Promise;\n}\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;\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([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit & Required> : 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 {\n (): Promise>>;\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;\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;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam | _PathParam\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 =\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\n : // look for params in the absence of wildcards\n _PathParam;\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 =\n // if you could not find path params, fallback to `string`\n [PathParam] extends [never] ? string : PathParam;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params = {\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;\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 {}\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: number[] = [],\n manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, 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 * @see https://reactrouter.com/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename = \"/\"\n): AgnosticRouteMatch[] | 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(branches[i], decoded);\n }\n\n return matches;\n}\n\nexport interface UIMatch {\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[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta = {\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\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,\n pathname: string\n): AgnosticRouteMatch[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch[] = [];\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 if (!match) return null;\n\n Object.assign(matchedParams, match.params);\n\n let route = meta.route;\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params,\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 * @see https://reactrouter.com/utils/generate-path\n */\nexport function generatePath(\n originalPath: Path,\n params: {\n [key in PathParam]: 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;\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];\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 {\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 {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\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 = {\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 * @see https://reactrouter.com/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey,\n Path extends string\n>(\n pattern: PathPattern | Path,\n pathname: string\n): PathMatch | 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>(\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\nfunction 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 * @see https://reactrouter.com/utils/resolve-path\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\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 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 * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \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[], v7_relativeSplatPath: boolean) {\n let pathMatches = getPathContributingMatches(matches);\n\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) =>\n idx === matches.length - 1 ? match.pathname : match.pathnameBase\n );\n }\n\n return pathMatches.map((match) => match.pathnameBase);\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;\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 `` 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 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 function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\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\nexport type JsonFunction = (\n data: Data,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\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 interface TrackedPromise extends Promise {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeysSet: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record,\n init?: number | ResponseInit\n) => DeferredData;\n\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\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 */\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 */\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\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 */\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 HistoryAction,\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 DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n HandlerResult,\n ImmutableRouteKey,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\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 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 * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the future config for the router\n */\n get future(): FutureConfig;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\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 * @internal\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 * @internal\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,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\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;\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;\n\n /**\n * @internal\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 ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\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 * @internal\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 * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(key: string): Fetcher;\n\n /**\n * @internal\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 * @internal\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @internal\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 * @internal\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 * @internal\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 * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map;\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 /**\n * The action of the most recent navigation\n */\n historyAction: HistoryAction;\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;\n\n /**\n * Map of current blockers\n */\n blockers: Map;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_partialHydration: boolean;\n v7_prependBasename: boolean;\n v7_relativeSplatPath: boolean;\n unstable_skipActionErrorRevalidation: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n hydrationData?: HydrationState;\n window?: Window;\n unstable_dataStrategy?: DataStrategyFunction;\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;\n actionHeaders: Record;\n activeDeferreds: Record | null;\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 unstable_dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\n queryRoute(\n request: Request,\n opts?: {\n routeId?: string;\n requestContext?: unknown;\n unstable_dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\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 unstable_viewTransitionOpts?: ViewTransitionOpts;\n unstable_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\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n unstable_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 */\ntype FetcherStates = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\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 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 =\n FetcherStates[keyof FetcherStates];\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: HistoryAction;\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 * 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 * 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(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set(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//#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 const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\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.unstable_dataStrategy || defaultDataStrategy;\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n unstable_skipActionErrorRevalidation: false,\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();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record | 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 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) {\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 let initialized: boolean;\n let hasLazyRoutes = initialMatches.some((m) => m.route.lazy);\n let hasLoaders = initialMatches.some((m) => m.route.loader);\n if (hasLazyRoutes) {\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 (!hasLoaders) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, 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 let isRouteInitialized = (m: AgnosticDataRouteMatch) => {\n // No loader, nothing to initialize\n if (!m.route.loader) {\n return true;\n }\n // Explicitly opting-in to running on hydration\n if (\n typeof m.route.loader === \"function\" &&\n m.route.loader.hydrate === true\n ) {\n return false;\n }\n // Otherwise, initialized if hydrated with data or an error\n return (\n (loaderData && loaderData[m.route.id] !== undefined) ||\n (errors && errors[m.route.id] !== undefined)\n );\n };\n\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.slice(0, idx + 1).every(isRouteInitialized);\n } else {\n initialized = initialMatches.every(isRouteInitialized);\n }\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\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: HistoryAction = HistoryAction.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> = new Map<\n string,\n Set\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 routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\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();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\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();\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 ignoreNextHistoryUpdate = false;\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 (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\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 ignoreNextHistoryUpdate = true;\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\n 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 fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.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,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\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: deletedFetchersKeys,\n unstable_viewTransitionOpts: opts.viewTransitionOpts,\n unstable_flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n }\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>,\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 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 === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.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 === HistoryAction.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([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 = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\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 ): Promise {\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 future.v7_prependBasename,\n to,\n future.v7_relativeSplatPath,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\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 = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.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 = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.unstable_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 return 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.unstable_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 interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\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;\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;\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 { overrideNavigation: state.navigation }\n );\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: HistoryAction,\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 {\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 // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\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 load will always\n // be \"same hash\". For example, on /page#hash and submit a \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 { replace: opts.replace, flushSync }\n );\n\n if (actionResult.shortCircuited) {\n return;\n }\n\n pendingActionResult = actionResult.pendingActionResult;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = 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 { shortCircuited, loaderData, errors } = await handleLoaders(\n request,\n location,\n matches,\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,\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 opts: { replace?: boolean; flushSync?: boolean } = {}\n ): Promise {\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 // 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 request,\n [actionMatch],\n matches\n );\n result = results[0];\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, {\n submission,\n replace,\n });\n return { shortCircuited: true };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\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 are REPLACE navigations, but if the\n // action threw an error that'll be rendered in an errorElement, we fall\n // back to PUSH so that the user can use the back button to get back to\n // the pre-submission form location to try again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n pendingActionResult: [boundaryMatch.route.id, result],\n };\n }\n\n return {\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 overrideNavigation?: Navigation,\n submission?: Submission,\n fetcherSubmission?: Submission,\n replace?: boolean,\n initialHydration?: boolean,\n flushSync?: boolean,\n pendingActionResult?: PendingActionResult\n ): Promise {\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 let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n future.v7_partialHydration && initialHydration === true,\n future.unstable_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionResult\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\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 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 // If we have partialHydration enabled, then don't update the state for the\n // initial data load since it's not a \"navigation\"\n if (\n !isUninterruptedRevalidation &&\n (!future.v7_partialHydration || !initialHydration)\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\n let actionData: Record | 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 actionData = {\n [pendingActionResult[0]]: pendingActionResult[1].data as any,\n };\n } else if (state.actionData) {\n if (Object.keys(state.actionData).length === 0) {\n actionData = null;\n } else {\n actionData = state.actionData;\n }\n }\n\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData !== undefined ? { actionData } : {}),\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n revalidatingFetchers.forEach((rf) => {\n if (fetchControllers.has(rf.key)) {\n abortFetcher(rf.key);\n }\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.matches,\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 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, ...fetcherResults]);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\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 let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n await startRedirectNavigation(request, redirect.result, {\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 matchesToLoad,\n loaderResults,\n pendingActionResult,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe((aborted) => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n\n // During partial hydration, preserve SSR errors for routes that don't re-run\n if (future.v7_partialHydration && initialHydration && state.errors) {\n Object.entries(state.errors)\n .filter(([id]) => !matchesToLoad.some((m) => m.route.id === id))\n .forEach(([routeId, error]) => {\n errors = Object.assign(errors || {}, { [routeId]: error });\n });\n }\n\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n if (fetchControllers.has(key)) abortFetcher(key);\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n future.v7_relativeSplatPath,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\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 future.v7_normalizeFormMethod,\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 pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\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 handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\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 flushSync: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action && !match.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;\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 // Call the action for the fetcher\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResults = await callDataStrategy(\n \"action\",\n fetchRequest,\n [match],\n requestMatches\n );\n let actionResult = actionResults[0];\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 // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.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, {\n fetcherSubmission: submission,\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 if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\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 future.unstable_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\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 if (fetchControllers.has(staleKey)) {\n abortFetcher(staleKey);\n }\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.matches,\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, ...fetcherResults]);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\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 let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n return startRedirectNavigation(revalidationRequest, redirect.result);\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n state.matches,\n matchesToLoad,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\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 flushSync: 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 // Call the loader for this fetcher route match\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let results = await callDataStrategy(\n \"loader\",\n fetchRequest,\n [match],\n matches\n );\n let result = results[0];\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\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 (deletedFetchers.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);\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 invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\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 {\n submission,\n fetcherSubmission,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\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 redirectHistoryAction =\n replace === true ? HistoryAction.Replace : HistoryAction.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(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: location,\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\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(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\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 request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[]\n ): Promise {\n try {\n let results = await callDataStrategyImpl(\n dataStrategyImpl,\n type,\n request,\n matchesToLoad,\n matches,\n manifest,\n mapRouteProperties\n );\n\n return await Promise.all(\n results.map((result, i) => {\n if (isRedirectHandlerResult(result)) {\n let response = result.result as Response;\n return {\n type: ResultType.redirect,\n response: normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n matchesToLoad[i].route.id,\n matches,\n basename,\n future.v7_relativeSplatPath\n ),\n };\n }\n\n return convertHandlerResultToDataResult(result);\n })\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 return matchesToLoad.map(() => ({\n type: ResultType.error,\n error: e,\n }));\n }\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n let [loaderResults, ...fetcherResults] = await Promise.all([\n matchesToLoad.length\n ? callDataStrategy(\"loader\", request, matchesToLoad, matches)\n : [],\n ...fetchersToLoad.map((f) => {\n if (f.matches && f.match && f.controller) {\n let fetcherRequest = createClientSideRequest(\n init.history,\n f.path,\n f.controller.signal\n );\n return callDataStrategy(\n \"loader\",\n fetcherRequest,\n [f.match],\n f.matches\n ).then((r) => r[0]);\n } else {\n return Promise.resolve({\n type: ResultType.error,\n error: getInternalRouterError(404, {\n pathname: f.path,\n }),\n });\n }\n }),\n ]);\n\n await Promise.all([\n resolveDeferredResults(\n currentMatches,\n matchesToLoad,\n loaderResults,\n loaderResults.map(() => request.signal),\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map((f) => f.match),\n fetcherResults,\n fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)),\n true\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 // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.push(key);\n abortFetcher(key);\n }\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(key: string): Fetcher {\n if (future.v7_fetcherPersist) {\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 (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\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 deletedFetchers.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n if (future.v7_fetcherPersist) {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n } else {\n activeFetchers.set(key, count);\n }\n } else {\n deleteFetcher(key);\n }\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n invariant(controller, `Expected fetch controller: ${key}`);\n controller.abort();\n fetchControllers.delete(key);\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: HistoryAction;\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 cancelActiveDeferreds(\n predicate?: (routeId: string) => boolean\n ): string[] {\n let cancelledRouteIds: string[] = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the component\n function enableScrollRestoration(\n positions: Record,\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 \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 _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\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: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\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 const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n v7_relativeSplatPath: boolean;\n v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\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: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future: StaticHandlerFutureConfig = {\n v7_relativeSplatPath: false,\n v7_throwAbortReason: false,\n ...(opts ? opts.future : null),\n };\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 unstable_dataStrategy,\n }: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n unstable_dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\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 activeDeferreds: null,\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 activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n unstable_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 unstable_dataStrategy,\n }: {\n requestContext?: unknown;\n routeId?: string;\n unstable_dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\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 unstable_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 let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n unstable_dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null\n ): Promise | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n unstable_dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n unstable_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 `HandlerResult` to bail out early\n // and then return or throw the raw Response here accordingly\n if (isHandlerResult(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 unstable_dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n isRouteRequest: boolean\n ): Promise | 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 unstable_dataStrategy\n );\n result = results[0];\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\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 (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\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 activeDeferreds: null,\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 unstable_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 unstable_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 unstable_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 activeDeferreds: null,\n };\n }\n\n let results = await callDataStrategy(\n \"loader\",\n request,\n matchesToLoad,\n matches,\n isRouteRequest,\n requestContext,\n unstable_dataStrategy\n );\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionResult,\n activeDeferreds,\n skipLoaderErrorBubbling\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(\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 activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\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 unstable_dataStrategy: DataStrategyFunction | null\n ): Promise {\n let results = await callDataStrategyImpl(\n unstable_dataStrategy || defaultDataStrategy,\n type,\n request,\n matchesToLoad,\n matches,\n manifest,\n mapRouteProperties,\n requestContext\n );\n\n return await Promise.all(\n results.map((result, i) => {\n if (isRedirectHandlerResult(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 matchesToLoad[i].route.id,\n matches,\n basename,\n future.v7_relativeSplatPath\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 return convertHandlerResultToDataResult(result);\n })\n );\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 */\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 future: StaticHandlerFutureConfig\n) {\n if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n throw request.signal.reason;\n }\n\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\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 prependBasename: boolean,\n to: To | null,\n v7_relativeSplatPath: boolean,\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, v7_relativeSplatPath),\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 // Add an ?index param for matched index routes if we don't already have one\n if (\n (to == null || to === \"\" || to === \".\") &&\n activeRouteMatch &&\n activeRouteMatch.route.index &&\n !hasNakedIndexQuery(path.search)\n ) {\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. 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 (prependBasename && 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 normalizeFormMethod: boolean,\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 = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() 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 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) {\n let boundaryMatches = matches;\n if (boundaryId) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n boundaryMatches = matches.slice(0, index);\n }\n }\n return boundaryMatches;\n}\n\nfunction getMatchesToLoad(\n history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isInitialLoad: boolean,\n skipActionErrorRevalidation: boolean,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n deletedFetchers: Set,\n fetchLoadMatches: Map,\n fetchRedirectIds: Set,\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 boundaryId =\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? pendingActionResult[0]\n : undefined;\n let boundaryMatches = boundaryId\n ? getLoaderMatchesUntilBoundary(matches, boundaryId)\n : matches;\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 =\n skipActionErrorRevalidation && 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 (isInitialLoad) {\n if (typeof route.loader !== \"function\" || route.loader.hydrate) {\n return true;\n }\n return (\n state.loaderData[route.id] === undefined &&\n // Don't re-run if the loader ran and threw an error\n (!state.errors || state.errors[route.id] === undefined)\n );\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\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 unstable_actionStatus: 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 load (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 isInitialLoad ||\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.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.includes(key)) {\n // Always revalidate if the fetcher was cancelled\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 unstable_actionStatus: 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 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 or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\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\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 = {};\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\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // 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\nfunction defaultDataStrategy(\n opts: DataStrategyFunctionArgs\n): ReturnType {\n return Promise.all(opts.matches.map((m) => m.resolve()));\n}\n\nasync function callDataStrategyImpl(\n dataStrategyImpl: DataStrategyFunction,\n type: \"loader\" | \"action\",\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n requestContext?: unknown\n): Promise {\n let routeIdsToLoad = matchesToLoad.reduce(\n (acc, m) => acc.add(m.route.id),\n new Set()\n );\n let loadedMatches = new Set();\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: matches.map((match) => {\n let shouldLoad = routeIdsToLoad.has(match.route.id);\n // `resolve` encapsulates the route.lazy, executing the\n // loader/action, and mapping return values/thrown errors to a\n // HandlerResult. Users can pass a callback to take fine-grained control\n // over the execution of the loader/action\n let resolve: DataStrategyMatch[\"resolve\"] = (handlerOverride) => {\n loadedMatches.add(match.route.id);\n return shouldLoad\n ? callLoaderOrAction(\n type,\n request,\n match,\n manifest,\n mapRouteProperties,\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 request,\n params: matches[0].params,\n context: requestContext,\n });\n\n // Throw if any loadRoute implementations not called since they are what\n // ensures a route is fully loaded\n matches.forEach((m) =>\n invariant(\n loadedMatches.has(m.route.id),\n `\\`match.resolve()\\` was not called for route id \"${m.route.id}\". ` +\n \"You must call `match.resolve()` on every match passed to \" +\n \"`dataStrategy` to ensure all routes are properly loaded.\"\n )\n );\n\n // Filter out any middleware-only matches for which we didn't need to run handlers\n return results.filter((_, i) => routeIdsToLoad.has(matches[i].route.id));\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 manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n handlerOverride: Parameters[0],\n staticContext?: unknown\n): Promise {\n let result: HandlerResult;\n let onReject: (() => void) | undefined;\n\n let runHandler = (\n handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n ): Promise => {\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 to\n // satisfy the function return value\n let abortPromise = new Promise((_, 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;\n if (handlerOverride) {\n handlerPromise = handlerOverride((ctx: unknown) => actualHandler(ctx));\n } else {\n handlerPromise = (async () => {\n try {\n let val = await actualHandler();\n return { type: \"data\", result: val };\n } catch (e) {\n return { type: \"error\", result: e };\n }\n })();\n }\n\n return Promise.race([handlerPromise, abortPromise]);\n };\n\n try {\n let handler = match.route[type];\n\n if (match.route.lazy) {\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 loadLazyRouteModule(match.route, mapRouteProperties, manifest),\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 loadLazyRouteModule(match.route, mapRouteProperties, manifest);\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\n invariant(\n result.result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n // We should already be catching and converting normal handler executions to\n // HandlerResults 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 convertHandlerResultToDataResult(\n handlerResult: HandlerResult\n): Promise {\n let { result, type, status } = handlerResult;\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 return {\n type: ResultType.error,\n error: result,\n statusCode: isRouteErrorResponse(result) ? result.status : status,\n };\n }\n\n if (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n return { type: ResultType.data, data: result, statusCode: status };\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 v7_relativeSplatPath: boolean\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 true,\n location,\n v7_relativeSplatPath\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 matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingActionResult: PendingActionResult | undefined,\n activeDeferreds: Map,\n skipLoaderErrorBubbling: boolean\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record;\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 = {};\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 results.forEach((result, index) => {\n let id = matchesToLoad[index].route.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 loaderData[id] = undefined;\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 if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.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 (\n result.statusCode != null &&\n result.statusCode !== 200 &&\n !foundError\n ) {\n statusCode = result.statusCode;\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\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 matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingActionResult: PendingActionResult | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: DataResult[],\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionResult,\n activeDeferreds,\n false // This method is only called client side so we always want to bubble\n );\n\n // Process results from our revalidating fetchers\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let { key, match, controller } = revalidatingFetchers[index];\n invariant(\n fetcherResults !== undefined && fetcherResults[index] !== undefined,\n \"Did not find corresponding fetcher result\"\n );\n let result = fetcherResults[index];\n\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n continue;\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 if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\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 let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\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 }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\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 === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\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: DataResult[]\n): { result: RedirectResult; idx: number } | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return { result, idx: i };\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 isHandlerResult(result: unknown): result is HandlerResult {\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 isRedirectHandlerResult(result: HandlerResult) {\n return (\n isResponse(result.result) && redirectStatusCodes.has(result.result.status)\n );\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\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 isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\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 | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: (AgnosticDataRouteMatch | null)[],\n results: DataResult[],\n signals: (AbortSignal | null)[],\n isFetcher: boolean,\n currentLoaderData?: RouteData\n) {\n for (let index = 0; index < results.length; index++) {\n let result = results[index];\n let match = matchesToLoad[index];\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n let signal = signals[index];\n invariant(\n signal,\n \"Expected an AbortSignal for revalidating fetcher deferred result\"\n );\n await resolveDeferredData(result, signal, isFetcher).then((result) => {\n if (result) {\n results[index] = result || results[index];\n }\n });\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise {\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData,\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e,\n };\n }\n }\n\n return {\n type: ResultType.data,\n data: result.deferredData.data,\n };\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>\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>\n) {\n if (transitions.size > 0) {\n let json: Record = {};\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\n//#endregion\n"],"names":["Action","PopStateEventType","createMemoryHistory","options","initialEntries","initialIndex","v5Compat","entries","map","entry","index","createMemoryLocation","state","undefined","clampIndex","length","action","Pop","listener","n","Math","min","max","getCurrentLocation","to","key","location","createLocation","pathname","warning","charAt","JSON","stringify","createHref","createPath","history","createURL","URL","encodeLocation","path","parsePath","search","hash","push","Push","nextLocation","splice","delta","replace","Replace","go","nextIndex","listen","fn","createBrowserHistory","createBrowserLocation","window","globalHistory","usr","createBrowserHref","getUrlBasedHistory","createHashHistory","createHashLocation","substr","startsWith","createHashHref","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","validateHashLocation","invariant","value","message","Error","cond","console","warn","e","createKey","random","toString","getHistoryState","idx","current","_extends","_ref","parsedPath","searchIndex","getLocation","validateLocation","defaultView","getIndex","replaceState","handlePop","historyState","pushState","error","DOMException","name","assign","origin","addEventListener","removeEventListener","ResultType","immutableRouteKeys","Set","isIndexRoute","route","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","treePath","id","join","children","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","stripBasename","branches","flattenRoutes","rankRouteBranches","matches","i","decoded","decodePath","matchRouteBranch","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","meta","caseSensitive","childrenIndex","joinPaths","routesMeta","concat","score","computeScore","forEach","_route$path","includes","exploded","explodeOptionalSegments","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","sort","a","b","compareIndexes","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","initialScore","some","filter","reduce","segment","test","siblings","every","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","generatePath","originalPath","prefix","p","String","array","isLastSegment","star","keyMatch","optional","param","pattern","matcher","compiledParams","compilePath","captureGroups","memo","paramName","splatValue","regexpSource","_","RegExp","v","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","resolvePathname","normalizeSearch","normalizeHash","relativeSegments","pop","getInvalidPathError","char","field","dest","getPathContributingMatches","getResolveToMatches","v7_relativeSplatPath","pathMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","getToPathname","paths","json","init","responseInit","status","headers","Headers","has","set","Response","AbortedDeferredError","DeferredData","constructor","pendingKeysSet","subscribers","deferredKeys","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","_ref2","trackPromise","done","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","k","resolveData","resolve","size","unwrappedData","_ref3","unwrapTrackedPromise","pendingKeys","isTrackedPromise","_tracked","_error","_data","defer","redirect","redirectDocument","response","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","createRouter","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","dataRoutes","inFlightDataRoutes","dataStrategyImpl","unstable_dataStrategy","defaultDataStrategy","future","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_prependBasename","unstable_skipActionErrorRevalidation","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialErrors","getInternalRouterError","getShortCircuitMatches","initialized","hasLazyRoutes","m","lazy","hasLoaders","loader","errors","isRouteInitialized","hydrate","findIndex","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","actionData","fetchers","Map","blockers","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeFetchers","deletedFetchers","activeDeferreds","blockerFunctions","ignoreNextHistoryUpdate","initialize","blockerKey","shouldBlockNavigation","currentLocation","updateBlocker","updateState","startNavigation","restoreAppliedTransitions","_saveAppliedTransitions","persistAppliedTransitions","initialHydration","dispose","clear","deleteFetcher","deleteBlocker","newState","opts","completedFetchers","deletedFetchersKeys","fetcher","unstable_viewTransitionOpts","viewTransitionOpts","unstable_flushSync","flushSync","completeNavigation","_temp","_location$state","_location$state2","isActionReload","isMutationMethod","_isRedirect","keys","mergeLoaderData","priorPaths","toPaths","getSavedScrollPosition","navigate","normalizedPath","normalizeTo","fromRouteId","relative","submission","normalizeNavigateOptions","userReplace","pendingError","enableViewTransition","unstable_viewTransition","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","routesToUse","loadingNavigation","notFoundMatches","cancelActiveDeferreds","isHashChangeOnly","request","createClientSideRequest","pendingActionResult","findNearestBoundary","type","actionResult","handleAction","shortCircuited","getLoadingNavigation","handleLoaders","fetcherSubmission","getActionDataForCommit","getSubmittingNavigation","actionMatch","getTargetMatch","method","routeId","results","callDataStrategy","isRedirectResult","normalizeRedirectLocation","startRedirectNavigation","isDeferredResult","isErrorResult","boundaryMatch","activeSubmission","getSubmissionFromNavigation","matchesToLoad","revalidatingFetchers","getMatchesToLoad","updatedFetchers","markFetchRedirectsDone","rf","revalidatingFetcher","getLoadingFetcher","abortFetcher","abortPendingFetchRevalidations","f","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","findRedirect","fetcherKey","processLoaderData","deferredData","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","fetch","setFetcherError","handleFetcherAction","handleFetcherLoader","requestMatches","existingFetcher","updateFetcherState","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","actionResults","getDoneFetcher","revalidationRequest","loadId","loadFetcher","staleKey","doneFetcher","resolveDeferredData","_temp2","redirectLocation","isDocumentReload","redirectHistoryAction","callDataStrategyImpl","all","isRedirectHandlerResult","normalizeRelativeRoutingRedirectResponse","convertHandlerResultToDataResult","currentMatches","fetchersToLoad","fetcherRequest","resolveDeferredResults","getFetcher","deleteFetcherAndUpdateState","count","markFetchersDone","doneKeys","landedId","yeetedKeys","getBlocker","blocker","newBlocker","_ref4","blockerFunction","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","getScrollKey","_internalSetRoutes","newRoutes","_internalFetchControllers","_internalActiveDeferreds","UNSAFE_DEFERRED_SYMBOL","Symbol","createStaticHandler","v7_throwAbortReason","query","_temp3","requestContext","skipLoaderErrorBubbling","isValidMethod","methodNotAllowedMatches","statusCode","loaderHeaders","actionHeaders","queryImpl","isResponse","queryRoute","_temp4","find","values","_result$activeDeferre","routeMatch","submit","loadRouteData","isHandlerResult","isRedirectResponse","isRouteRequest","throwStaticHandlerAbortedError","Location","loaderRequest","Request","context","getLoaderMatchesUntilBoundary","processRouteLoaderData","executedLoaders","fromEntries","getStaticContextFromError","newContext","_deepestRenderedBoundaryId","reason","isSubmissionNavigation","body","prependBasename","contextualMatches","activeRouteMatch","hasNakedIndexQuery","normalizeFormMethod","isFetcher","getInvalidBodyError","rawFormMethod","toUpperCase","stripHashFromPath","FormData","URLSearchParams","_ref5","parse","searchParams","convertFormDataToSearchParams","convertSearchParamsToFormData","append","boundaryId","boundaryMatches","isInitialLoad","skipActionErrorRevalidation","currentUrl","nextUrl","actionStatus","shouldSkipRevalidation","navigationMatches","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","unstable_actionStatus","defaultShouldRevalidate","isNewRouteInstance","fetcherMatches","fetcherMatch","shouldRevalidate","currentLoaderData","currentMatch","isNew","isMissingData","currentPath","loaderMatch","arg","routeChoice","loadLazyRouteModule","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","staticRouteValue","isPropertyStaticallyDefined","routeIdsToLoad","loadedMatches","shouldLoad","handlerOverride","callLoaderOrAction","staticContext","onReject","runHandler","handler","actualHandler","ctx","handlerPromise","val","handlerError","handlerResult","contentType","isDeferredData","_result$init","_result$init2","deferred","trimmedMatches","normalizedLocation","protocol","isSameBasename","foundError","newLoaderData","mergedLoaderData","hasOwnProperty","eligibleMatches","reverse","_temp5","errorMessage","signals","isRevalidatingLoader","unwrap","getAll","_window","transitions","sessionPositions","sessionStorage","getItem","setItem"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;;AAEA;AACA;AACA;AACYA,IAAAA,MAAM,0BAANA,MAAM,EAAA;EAANA,MAAM,CAAA,KAAA,CAAA,GAAA,KAAA,CAAA;EAANA,MAAM,CAAA,MAAA,CAAA,GAAA,MAAA,CAAA;EAANA,MAAM,CAAA,SAAA,CAAA,GAAA,SAAA,CAAA;AAAA,EAAA,OAANA,MAAM,CAAA;AAAA,CAAA,CAAA,EAAA,EAAA;;AAwBlB;AACA;AACA;;AAkBA;AACA;AAEA;AACA;AACA;AACA;AAgBA;AACA;AACA;AAkBA;AACA;AACA;AAKA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAgFA,MAAMC,iBAAiB,GAAG,UAAU,CAAA;AACpC;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AASA;AACA;AACA;AACA;AACA;AAQA;AACA;AACA;AACA;AACO,SAASC,mBAAmBA,CACj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C,EAAE;AACzBse,UAAAA,WAAW,CAAC5b,GAAG,CAACwC,CAAC,EAAE,IAAI/L,GAAG,CAAC6G,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;AACtC,SAAA;AACF,OAAA;AACF,KAAA;GACD,CAAC,OAAOzI,CAAC,EAAE;AACV;AAAA,GAAA;AAEJ,CAAA;AAEA,SAASkV,yBAAyBA,CAChC4R,OAAe,EACfC,WAAqC,EACrC;AACA,EAAA,IAAIA,WAAW,CAACjZ,IAAI,GAAG,CAAC,EAAE;IACxB,IAAIlD,IAA8B,GAAG,EAAE,CAAA;IACvC,KAAK,IAAI,CAAC+C,CAAC,EAAElF,CAAC,CAAC,IAAIse,WAAW,EAAE;AAC9Bnc,MAAAA,IAAI,CAAC+C,CAAC,CAAC,GAAG,CAAC,GAAGlF,CAAC,CAAC,CAAA;AAClB,KAAA;IACA,IAAI;AACFqe,MAAAA,OAAO,CAACG,cAAc,CAACE,OAAO,CAC5BhX,uBAAuB,EACvBvT,IAAI,CAACC,SAAS,CAAC+N,IAAI,CACrB,CAAC,CAAA;KACF,CAAC,OAAOzJ,KAAK,EAAE;AACdzE,MAAAA,OAAO,CACL,KAAK,EACyDyE,6DAAAA,GAAAA,KAAK,OACrE,CAAC,CAAA;AACH,KAAA;AACF,GAAA;AACF,CAAA;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@remix-run/router/dist/router.d.ts b/node_modules/@remix-run/router/dist/router.d.ts deleted file mode 100644 index f9c6cadf..00000000 --- a/node_modules/@remix-run/router/dist/router.d.ts +++ /dev/null @@ -1,513 +0,0 @@ -import type { History, Location, Path, To } from "./history"; -import { Action as HistoryAction } from "./history"; -import type { AgnosticDataRouteMatch, AgnosticDataRouteObject, AgnosticRouteObject, DataStrategyFunction, DeferredData, DetectErrorBoundaryFunction, FormEncType, HTMLFormMethod, MapRoutePropertiesFunction, RouteData, Submission, UIMatch } from "./utils"; -/** - * A Router instance manages all navigation and data loading/mutations - */ -export interface Router { - /** - * @internal - * PRIVATE - DO NOT USE - * - * Return the basename for the router - */ - get basename(): RouterInit["basename"]; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Return the future config for the router - */ - get future(): FutureConfig; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Return the current state of the router - */ - get state(): RouterState; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Return the routes for this router instance - */ - get routes(): AgnosticDataRouteObject[]; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Return the window associated with the router - */ - get window(): RouterInit["window"]; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Initialize the router, including adding history listeners and kicking off - * initial data fetches. Returns a function to cleanup listeners and abort - * any in-progress loads - */ - initialize(): Router; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Subscribe to router.state updates - * - * @param fn function to call with the new state - */ - subscribe(fn: RouterSubscriber): () => void; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Enable scroll restoration behavior in the router - * - * @param savedScrollPositions Object that will manage positions, in case - * it's being restored from sessionStorage - * @param getScrollPosition Function to get the active Y scroll position - * @param getKey Function to get the key to use for restoration - */ - enableScrollRestoration(savedScrollPositions: Record, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Navigate forward/backward in the history stack - * @param to Delta to move in the history stack - */ - navigate(to: number): Promise; - /** - * Navigate to the given path - * @param to Path to navigate to - * @param opts Navigation options (method, submission, etc.) - */ - navigate(to: To | null, opts?: RouterNavigateOptions): Promise; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Trigger a fetcher load/submission - * - * @param key Fetcher key - * @param routeId Route that owns the fetcher - * @param href href to fetch - * @param opts Fetcher options, (method, submission, etc.) - */ - fetch(key: string, routeId: string, href: string | null, opts?: RouterFetchOptions): void; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Trigger a revalidation of all current route loaders and fetcher loads - */ - revalidate(): void; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Utility function to create an href for the given location - * @param location - */ - createHref(location: Location | URL): string; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Utility function to URL encode a destination path according to the internal - * history implementation - * @param to - */ - encodeLocation(to: To): Path; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Get/create a fetcher for the given key - * @param key - */ - getFetcher(key: string): Fetcher; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Delete the fetcher for a given key - * @param key - */ - deleteFetcher(key: string): void; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Cleanup listeners and abort any in-progress loads - */ - dispose(): void; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Get a navigation blocker - * @param key The identifier for the blocker - * @param fn The blocker function implementation - */ - getBlocker(key: string, fn: BlockerFunction): Blocker; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Delete a navigation blocker - * @param key The identifier for the blocker - */ - deleteBlocker(key: string): void; - /** - * @internal - * PRIVATE - DO NOT USE - * - * HMR needs to pass in-flight route updates to React Router - * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute) - */ - _internalSetRoutes(routes: AgnosticRouteObject[]): void; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Internal fetch AbortControllers accessed by unit tests - */ - _internalFetchControllers: Map; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Internal pending DeferredData instances accessed by unit tests - */ - _internalActiveDeferreds: Map; -} -/** - * State maintained internally by the router. During a navigation, all states - * reflect the the "old" location unless otherwise noted. - */ -export interface RouterState { - /** - * The action of the most recent navigation - */ - historyAction: HistoryAction; - /** - * The current location reflected by the router - */ - location: Location; - /** - * The current set of route matches - */ - matches: AgnosticDataRouteMatch[]; - /** - * Tracks whether we've completed our initial data load - */ - initialized: boolean; - /** - * Current scroll position we should start at for a new view - * - number -> scroll position to restore to - * - false -> do not restore scroll at all (used during submissions) - * - null -> don't have a saved position, scroll to hash or top of page - */ - restoreScrollPosition: number | false | null; - /** - * Indicate whether this navigation should skip resetting the scroll position - * if we are unable to restore the scroll position - */ - preventScrollReset: boolean; - /** - * Tracks the state of the current navigation - */ - navigation: Navigation; - /** - * Tracks any in-progress revalidations - */ - revalidation: RevalidationState; - /** - * Data from the loaders for the current matches - */ - loaderData: RouteData; - /** - * Data from the action for the current matches - */ - actionData: RouteData | null; - /** - * Errors caught from loaders for the current matches - */ - errors: RouteData | null; - /** - * Map of current fetchers - */ - fetchers: Map; - /** - * Map of current blockers - */ - blockers: Map; -} -/** - * Data that can be passed into hydrate a Router from SSR - */ -export type HydrationState = Partial>; -/** - * Future flags to toggle new feature behavior - */ -export interface FutureConfig { - v7_fetcherPersist: boolean; - v7_normalizeFormMethod: boolean; - v7_partialHydration: boolean; - v7_prependBasename: boolean; - v7_relativeSplatPath: boolean; - unstable_skipActionErrorRevalidation: boolean; -} -/** - * Initialization options for createRouter - */ -export interface RouterInit { - routes: AgnosticRouteObject[]; - history: History; - basename?: string; - /** - * @deprecated Use `mapRouteProperties` instead - */ - detectErrorBoundary?: DetectErrorBoundaryFunction; - mapRouteProperties?: MapRoutePropertiesFunction; - future?: Partial; - hydrationData?: HydrationState; - window?: Window; - unstable_dataStrategy?: DataStrategyFunction; -} -/** - * State returned from a server-side query() call - */ -export interface StaticHandlerContext { - basename: Router["basename"]; - location: RouterState["location"]; - matches: RouterState["matches"]; - loaderData: RouterState["loaderData"]; - actionData: RouterState["actionData"]; - errors: RouterState["errors"]; - statusCode: number; - loaderHeaders: Record; - actionHeaders: Record; - activeDeferreds: Record | null; - _deepestRenderedBoundaryId?: string | null; -} -/** - * A StaticHandler instance manages a singular SSR navigation/fetch event - */ -export interface StaticHandler { - dataRoutes: AgnosticDataRouteObject[]; - query(request: Request, opts?: { - requestContext?: unknown; - skipLoaderErrorBubbling?: boolean; - unstable_dataStrategy?: DataStrategyFunction; - }): Promise; - queryRoute(request: Request, opts?: { - routeId?: string; - requestContext?: unknown; - unstable_dataStrategy?: DataStrategyFunction; - }): Promise; -} -type ViewTransitionOpts = { - currentLocation: Location; - nextLocation: Location; -}; -/** - * Subscriber function signature for changes to router state - */ -export interface RouterSubscriber { - (state: RouterState, opts: { - deletedFetchers: string[]; - unstable_viewTransitionOpts?: ViewTransitionOpts; - unstable_flushSync: boolean; - }): void; -} -/** - * Function signature for determining the key to be used in scroll restoration - * for a given location - */ -export interface GetScrollRestorationKeyFunction { - (location: Location, matches: UIMatch[]): string | null; -} -/** - * Function signature for determining the current scroll position - */ -export interface GetScrollPositionFunction { - (): number; -} -export type RelativeRoutingType = "route" | "path"; -type BaseNavigateOrFetchOptions = { - preventScrollReset?: boolean; - relative?: RelativeRoutingType; - unstable_flushSync?: boolean; -}; -type BaseNavigateOptions = BaseNavigateOrFetchOptions & { - replace?: boolean; - state?: any; - fromRouteId?: string; - unstable_viewTransition?: boolean; -}; -type BaseSubmissionOptions = { - formMethod?: HTMLFormMethod; - formEncType?: FormEncType; -} & ({ - formData: FormData; - body?: undefined; -} | { - formData?: undefined; - body: any; -}); -/** - * Options for a navigate() call for a normal (non-submission) navigation - */ -type LinkNavigateOptions = BaseNavigateOptions; -/** - * Options for a navigate() call for a submission navigation - */ -type SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions; -/** - * Options to pass to navigate() for a navigation - */ -export type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions; -/** - * Options for a fetch() load - */ -type LoadFetchOptions = BaseNavigateOrFetchOptions; -/** - * Options for a fetch() submission - */ -type SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions; -/** - * Options to pass to fetch() - */ -export type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions; -/** - * Potential states for state.navigation - */ -export type NavigationStates = { - Idle: { - state: "idle"; - location: undefined; - formMethod: undefined; - formAction: undefined; - formEncType: undefined; - formData: undefined; - json: undefined; - text: undefined; - }; - Loading: { - state: "loading"; - location: Location; - formMethod: Submission["formMethod"] | undefined; - formAction: Submission["formAction"] | undefined; - formEncType: Submission["formEncType"] | undefined; - formData: Submission["formData"] | undefined; - json: Submission["json"] | undefined; - text: Submission["text"] | undefined; - }; - Submitting: { - state: "submitting"; - location: Location; - formMethod: Submission["formMethod"]; - formAction: Submission["formAction"]; - formEncType: Submission["formEncType"]; - formData: Submission["formData"]; - json: Submission["json"]; - text: Submission["text"]; - }; -}; -export type Navigation = NavigationStates[keyof NavigationStates]; -export type RevalidationState = "idle" | "loading"; -/** - * Potential states for fetchers - */ -type FetcherStates = { - Idle: { - state: "idle"; - formMethod: undefined; - formAction: undefined; - formEncType: undefined; - text: undefined; - formData: undefined; - json: undefined; - data: TData | undefined; - }; - Loading: { - state: "loading"; - formMethod: Submission["formMethod"] | undefined; - formAction: Submission["formAction"] | undefined; - formEncType: Submission["formEncType"] | undefined; - text: Submission["text"] | undefined; - formData: Submission["formData"] | undefined; - json: Submission["json"] | undefined; - data: TData | undefined; - }; - Submitting: { - state: "submitting"; - formMethod: Submission["formMethod"]; - formAction: Submission["formAction"]; - formEncType: Submission["formEncType"]; - text: Submission["text"]; - formData: Submission["formData"]; - json: Submission["json"]; - data: TData | undefined; - }; -}; -export type Fetcher = FetcherStates[keyof FetcherStates]; -interface BlockerBlocked { - state: "blocked"; - reset(): void; - proceed(): void; - location: Location; -} -interface BlockerUnblocked { - state: "unblocked"; - reset: undefined; - proceed: undefined; - location: undefined; -} -interface BlockerProceeding { - state: "proceeding"; - reset: undefined; - proceed: undefined; - location: Location; -} -export type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding; -export type BlockerFunction = (args: { - currentLocation: Location; - nextLocation: Location; - historyAction: HistoryAction; -}) => boolean; -export declare const IDLE_NAVIGATION: NavigationStates["Idle"]; -export declare const IDLE_FETCHER: FetcherStates["Idle"]; -export declare const IDLE_BLOCKER: BlockerUnblocked; -/** - * Create a router and listen to history POP navigations - */ -export declare function createRouter(init: RouterInit): Router; -export declare const UNSAFE_DEFERRED_SYMBOL: unique symbol; -/** - * Future flags to toggle new feature behavior - */ -export interface StaticHandlerFutureConfig { - v7_relativeSplatPath: boolean; - v7_throwAbortReason: boolean; -} -export interface CreateStaticHandlerOptions { - basename?: string; - /** - * @deprecated Use `mapRouteProperties` instead - */ - detectErrorBoundary?: DetectErrorBoundaryFunction; - mapRouteProperties?: MapRoutePropertiesFunction; - future?: Partial; -} -export declare function createStaticHandler(routes: AgnosticRouteObject[], opts?: CreateStaticHandlerOptions): StaticHandler; -/** - * Given an existing StaticHandlerContext and an error thrown at render time, - * provide an updated StaticHandlerContext suitable for a second SSR render - */ -export declare function getStaticContextFromError(routes: AgnosticDataRouteObject[], context: StaticHandlerContext, error: any): StaticHandlerContext; -export declare function isDeferredData(value: any): value is DeferredData; -export {}; diff --git a/node_modules/@remix-run/router/dist/router.js b/node_modules/@remix-run/router/dist/router.js deleted file mode 100644 index d70796d0..00000000 --- a/node_modules/@remix-run/router/dist/router.js +++ /dev/null @@ -1,4475 +0,0 @@ -/** - * @remix-run/router v1.16.1 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */ -function _extends() { - _extends = Object.assign ? Object.assign.bind() : function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - return target; - }; - return _extends.apply(this, arguments); -} - -//////////////////////////////////////////////////////////////////////////////// -//#region Types and Constants -//////////////////////////////////////////////////////////////////////////////// -/** - * Actions represent the type of change to a location value. - */ -var Action; -(function (Action) { - /** - * A POP indicates a change to an arbitrary index in the history stack, such - * as a back or forward navigation. It does not describe the direction of the - * navigation, only that the current index changed. - * - * Note: This is the default action for newly created history objects. - */ - Action["Pop"] = "POP"; - /** - * A PUSH indicates a new entry being added to the history stack, such as when - * a link is clicked and a new page loads. When this happens, all subsequent - * entries in the stack are lost. - */ - Action["Push"] = "PUSH"; - /** - * A REPLACE indicates the entry at the current index in the history stack - * being replaced by a new one. - */ - Action["Replace"] = "REPLACE"; -})(Action || (Action = {})); -const PopStateEventType = "popstate"; -/** - * Memory history stores the current location in memory. It is designed for use - * in stateful non-browser environments like tests and React Native. - */ -function createMemoryHistory(options) { - if (options === void 0) { - options = {}; - } - let { - initialEntries = ["/"], - initialIndex, - v5Compat = false - } = options; - let entries; // Declare so we can access from createMemoryLocation - entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : undefined)); - let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex); - let action = Action.Pop; - let listener = null; - function clampIndex(n) { - return Math.min(Math.max(n, 0), entries.length - 1); - } - function getCurrentLocation() { - return entries[index]; - } - function createMemoryLocation(to, state, key) { - if (state === void 0) { - state = null; - } - let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key); - warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to)); - return location; - } - function createHref(to) { - return typeof to === "string" ? to : createPath(to); - } - let history = { - get index() { - return index; - }, - get action() { - return action; - }, - get location() { - return getCurrentLocation(); - }, - createHref, - createURL(to) { - return new URL(createHref(to), "http://localhost"); - }, - encodeLocation(to) { - let path = typeof to === "string" ? parsePath(to) : to; - return { - pathname: path.pathname || "", - search: path.search || "", - hash: path.hash || "" - }; - }, - push(to, state) { - action = Action.Push; - let nextLocation = createMemoryLocation(to, state); - index += 1; - entries.splice(index, entries.length, nextLocation); - if (v5Compat && listener) { - listener({ - action, - location: nextLocation, - delta: 1 - }); - } - }, - replace(to, state) { - action = Action.Replace; - let nextLocation = createMemoryLocation(to, state); - entries[index] = nextLocation; - if (v5Compat && listener) { - listener({ - action, - location: nextLocation, - delta: 0 - }); - } - }, - go(delta) { - action = Action.Pop; - let nextIndex = clampIndex(index + delta); - let nextLocation = entries[nextIndex]; - index = nextIndex; - if (listener) { - listener({ - action, - location: nextLocation, - delta - }); - } - }, - listen(fn) { - listener = fn; - return () => { - listener = null; - }; - } - }; - return history; -} -/** - * Browser history stores the location in regular URLs. This is the standard for - * most web apps, but it requires some configuration on the server to ensure you - * serve the same app at multiple URLs. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory - */ -function createBrowserHistory(options) { - if (options === void 0) { - options = {}; - } - function createBrowserLocation(window, globalHistory) { - let { - pathname, - search, - hash - } = window.location; - return createLocation("", { - pathname, - search, - hash - }, - // state defaults to `null` because `window.history.state` does - globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default"); - } - function createBrowserHref(window, to) { - return typeof to === "string" ? to : createPath(to); - } - return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options); -} -/** - * Hash history stores the location in window.location.hash. This makes it ideal - * for situations where you don't want to send the location to the server for - * some reason, either because you do cannot configure it or the URL space is - * reserved for something else. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory - */ -function createHashHistory(options) { - if (options === void 0) { - options = {}; - } - function createHashLocation(window, globalHistory) { - let { - pathname = "/", - search = "", - hash = "" - } = parsePath(window.location.hash.substr(1)); - // Hash URL should always have a leading / just like window.location.pathname - // does, so if an app ends up at a route like /#something then we add a - // leading slash so all of our path-matching behaves the same as if it would - // in a browser router. This is particularly important when there exists a - // root splat route () since that matches internally against - // "/*" and we'd expect /#something to 404 in a hash router app. - if (!pathname.startsWith("/") && !pathname.startsWith(".")) { - pathname = "/" + pathname; - } - return createLocation("", { - pathname, - search, - hash - }, - // state defaults to `null` because `window.history.state` does - globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default"); - } - function createHashHref(window, to) { - let base = window.document.querySelector("base"); - let href = ""; - if (base && base.getAttribute("href")) { - let url = window.location.href; - let hashIndex = url.indexOf("#"); - href = hashIndex === -1 ? url : url.slice(0, hashIndex); - } - return href + "#" + (typeof to === "string" ? to : createPath(to)); - } - function validateHashLocation(location, to) { - warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")"); - } - return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options); -} -function invariant(value, message) { - if (value === false || value === null || typeof value === "undefined") { - throw new Error(message); - } -} -function warning(cond, message) { - if (!cond) { - // eslint-disable-next-line no-console - if (typeof console !== "undefined") console.warn(message); - try { - // Welcome to debugging history! - // - // This error is thrown as a convenience, so you can more easily - // find the source for a warning that appears in the console by - // enabling "pause on exceptions" in your JavaScript debugger. - throw new Error(message); - // eslint-disable-next-line no-empty - } catch (e) {} - } -} -function createKey() { - return Math.random().toString(36).substr(2, 8); -} -/** - * For browser-based histories, we combine the state and key into an object - */ -function getHistoryState(location, index) { - return { - usr: location.state, - key: location.key, - idx: index - }; -} -/** - * Creates a Location object with a unique key from the given Path - */ -function createLocation(current, to, state, key) { - if (state === void 0) { - state = null; - } - let location = _extends({ - pathname: typeof current === "string" ? current : current.pathname, - search: "", - hash: "" - }, typeof to === "string" ? parsePath(to) : to, { - state, - // TODO: This could be cleaned up. push/replace should probably just take - // full Locations now and avoid the need to run through this flow at all - // But that's a pretty big refactor to the current test suite so going to - // keep as is for the time being and just let any incoming keys take precedence - key: to && to.key || key || createKey() - }); - return location; -} -/** - * Creates a string URL path from the given pathname, search, and hash components. - */ -function createPath(_ref) { - let { - pathname = "/", - search = "", - hash = "" - } = _ref; - if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search; - if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash; - return pathname; -} -/** - * Parses a string URL path into its separate pathname, search, and hash components. - */ -function parsePath(path) { - let parsedPath = {}; - if (path) { - let hashIndex = path.indexOf("#"); - if (hashIndex >= 0) { - parsedPath.hash = path.substr(hashIndex); - path = path.substr(0, hashIndex); - } - let searchIndex = path.indexOf("?"); - if (searchIndex >= 0) { - parsedPath.search = path.substr(searchIndex); - path = path.substr(0, searchIndex); - } - if (path) { - parsedPath.pathname = path; - } - } - return parsedPath; -} -function getUrlBasedHistory(getLocation, createHref, validateLocation, options) { - if (options === void 0) { - options = {}; - } - let { - window = document.defaultView, - v5Compat = false - } = options; - let globalHistory = window.history; - let action = Action.Pop; - let listener = null; - let index = getIndex(); - // Index should only be null when we initialize. If not, it's because the - // user called history.pushState or history.replaceState directly, in which - // case we should log a warning as it will result in bugs. - if (index == null) { - index = 0; - globalHistory.replaceState(_extends({}, globalHistory.state, { - idx: index - }), ""); - } - function getIndex() { - let state = globalHistory.state || { - idx: null - }; - return state.idx; - } - function handlePop() { - action = Action.Pop; - let nextIndex = getIndex(); - let delta = nextIndex == null ? null : nextIndex - index; - index = nextIndex; - if (listener) { - listener({ - action, - location: history.location, - delta - }); - } - } - function push(to, state) { - action = Action.Push; - let location = createLocation(history.location, to, state); - if (validateLocation) validateLocation(location, to); - index = getIndex() + 1; - let historyState = getHistoryState(location, index); - let url = history.createHref(location); - // try...catch because iOS limits us to 100 pushState calls :/ - try { - globalHistory.pushState(historyState, "", url); - } catch (error) { - // If the exception is because `state` can't be serialized, let that throw - // outwards just like a replace call would so the dev knows the cause - // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps - // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal - if (error instanceof DOMException && error.name === "DataCloneError") { - throw error; - } - // They are going to lose state here, but there is no real - // way to warn them about it since the page will refresh... - window.location.assign(url); - } - if (v5Compat && listener) { - listener({ - action, - location: history.location, - delta: 1 - }); - } - } - function replace(to, state) { - action = Action.Replace; - let location = createLocation(history.location, to, state); - if (validateLocation) validateLocation(location, to); - index = getIndex(); - let historyState = getHistoryState(location, index); - let url = history.createHref(location); - globalHistory.replaceState(historyState, "", url); - if (v5Compat && listener) { - listener({ - action, - location: history.location, - delta: 0 - }); - } - } - function createURL(to) { - // window.location.origin is "null" (the literal string value) in Firefox - // under certain conditions, notably when serving from a local HTML file - // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297 - let base = window.location.origin !== "null" ? window.location.origin : window.location.href; - let href = typeof to === "string" ? to : createPath(to); - // Treating this as a full URL will strip any trailing spaces so we need to - // pre-encode them since they might be part of a matching splat param from - // an ancestor route - href = href.replace(/ $/, "%20"); - invariant(base, "No window.location.(origin|href) available to create URL for href: " + href); - return new URL(href, base); - } - let history = { - get action() { - return action; - }, - get location() { - return getLocation(window, globalHistory); - }, - listen(fn) { - if (listener) { - throw new Error("A history only accepts one active listener"); - } - window.addEventListener(PopStateEventType, handlePop); - listener = fn; - return () => { - window.removeEventListener(PopStateEventType, handlePop); - listener = null; - }; - }, - createHref(to) { - return createHref(window, to); - }, - createURL, - encodeLocation(to) { - // Encode a Location the same way window.location would - let url = createURL(to); - return { - pathname: url.pathname, - search: url.search, - hash: url.hash - }; - }, - push, - replace, - go(n) { - return globalHistory.go(n); - } - }; - return history; -} -//#endregion - -var ResultType; -(function (ResultType) { - ResultType["data"] = "data"; - ResultType["deferred"] = "deferred"; - ResultType["redirect"] = "redirect"; - ResultType["error"] = "error"; -})(ResultType || (ResultType = {})); -const immutableRouteKeys = new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]); -function isIndexRoute(route) { - return route.index === true; -} -// Walk the route tree generating unique IDs where necessary, so we are working -// solely with AgnosticDataRouteObject's within the Router -function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) { - if (parentPath === void 0) { - parentPath = []; - } - if (manifest === void 0) { - manifest = {}; - } - return routes.map((route, index) => { - let treePath = [...parentPath, index]; - let id = typeof route.id === "string" ? route.id : treePath.join("-"); - invariant(route.index !== true || !route.children, "Cannot specify children on an index route"); - invariant(!manifest[id], "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages"); - if (isIndexRoute(route)) { - let indexRoute = _extends({}, route, mapRouteProperties(route), { - id - }); - manifest[id] = indexRoute; - return indexRoute; - } else { - let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), { - id, - children: undefined - }); - manifest[id] = pathOrLayoutRoute; - if (route.children) { - pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest); - } - return pathOrLayoutRoute; - } - }); -} -/** - * Matches the given routes to a location and returns the match data. - * - * @see https://reactrouter.com/utils/match-routes - */ -function matchRoutes(routes, locationArg, basename) { - if (basename === void 0) { - basename = "/"; - } - let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg; - let pathname = stripBasename(location.pathname || "/", basename); - if (pathname == null) { - return null; - } - let branches = flattenRoutes(routes); - rankRouteBranches(branches); - let matches = null; - for (let i = 0; matches == null && i < branches.length; ++i) { - // Incoming pathnames are generally encoded from either window.location - // or from router.navigate, but we want to match against the unencoded - // paths in the route definitions. Memory router locations won't be - // encoded here but there also shouldn't be anything to decode so this - // should be a safe operation. This avoids needing matchRoutes to be - // history-aware. - let decoded = decodePath(pathname); - matches = matchRouteBranch(branches[i], decoded); - } - return matches; -} -function convertRouteMatchToUiMatch(match, loaderData) { - let { - route, - pathname, - params - } = match; - return { - id: route.id, - pathname, - params, - data: loaderData[route.id], - handle: route.handle - }; -} -function flattenRoutes(routes, branches, parentsMeta, parentPath) { - if (branches === void 0) { - branches = []; - } - if (parentsMeta === void 0) { - parentsMeta = []; - } - if (parentPath === void 0) { - parentPath = ""; - } - let flattenRoute = (route, index, relativePath) => { - let meta = { - relativePath: relativePath === undefined ? route.path || "" : relativePath, - caseSensitive: route.caseSensitive === true, - childrenIndex: index, - route - }; - if (meta.relativePath.startsWith("/")) { - invariant(meta.relativePath.startsWith(parentPath), "Absolute route path \"" + meta.relativePath + "\" nested under path " + ("\"" + parentPath + "\" is not valid. An absolute child route path ") + "must start with the combined path of all its parent routes."); - meta.relativePath = meta.relativePath.slice(parentPath.length); - } - let path = joinPaths([parentPath, meta.relativePath]); - let routesMeta = parentsMeta.concat(meta); - // Add the children before adding this route to the array, so we traverse the - // route tree depth-first and child routes appear before their parents in - // the "flattened" version. - if (route.children && route.children.length > 0) { - invariant( - // Our types know better, but runtime JS may not! - // @ts-expect-error - route.index !== true, "Index routes must not have child routes. Please remove " + ("all child routes from route path \"" + path + "\".")); - flattenRoutes(route.children, branches, routesMeta, path); - } - // Routes without a path shouldn't ever match by themselves unless they are - // index routes, so don't add them to the list of possible branches. - if (route.path == null && !route.index) { - return; - } - branches.push({ - path, - score: computeScore(path, route.index), - routesMeta - }); - }; - routes.forEach((route, index) => { - var _route$path; - // coarse-grain check for optional params - if (route.path === "" || !((_route$path = route.path) != null && _route$path.includes("?"))) { - flattenRoute(route, index); - } else { - for (let exploded of explodeOptionalSegments(route.path)) { - flattenRoute(route, index, exploded); - } - } - }); - return branches; -} -/** - * Computes all combinations of optional path segments for a given path, - * excluding combinations that are ambiguous and of lower priority. - * - * For example, `/one/:two?/three/:four?/:five?` explodes to: - * - `/one/three` - * - `/one/:two/three` - * - `/one/three/:four` - * - `/one/three/:five` - * - `/one/:two/three/:four` - * - `/one/:two/three/:five` - * - `/one/three/:four/:five` - * - `/one/:two/three/:four/:five` - */ -function explodeOptionalSegments(path) { - let segments = path.split("/"); - if (segments.length === 0) return []; - let [first, ...rest] = segments; - // Optional path segments are denoted by a trailing `?` - let isOptional = first.endsWith("?"); - // Compute the corresponding required segment: `foo?` -> `foo` - let required = first.replace(/\?$/, ""); - if (rest.length === 0) { - // Intepret empty string as omitting an optional segment - // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three` - return isOptional ? [required, ""] : [required]; - } - let restExploded = explodeOptionalSegments(rest.join("/")); - let result = []; - // All child paths with the prefix. Do this for all children before the - // optional version for all children, so we get consistent ordering where the - // parent optional aspect is preferred as required. Otherwise, we can get - // child sections interspersed where deeper optional segments are higher than - // parent optional segments, where for example, /:two would explode _earlier_ - // then /:one. By always including the parent as required _for all children_ - // first, we avoid this issue - result.push(...restExploded.map(subpath => subpath === "" ? required : [required, subpath].join("/"))); - // Then, if this is an optional value, add all child versions without - if (isOptional) { - result.push(...restExploded); - } - // for absolute paths, ensure `/` instead of empty segment - return result.map(exploded => path.startsWith("/") && exploded === "" ? "/" : exploded); -} -function rankRouteBranches(branches) { - branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first - : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex))); -} -const paramRe = /^:[\w-]+$/; -const dynamicSegmentValue = 3; -const indexRouteValue = 2; -const emptySegmentValue = 1; -const staticSegmentValue = 10; -const splatPenalty = -2; -const isSplat = s => s === "*"; -function computeScore(path, index) { - let segments = path.split("/"); - let initialScore = segments.length; - if (segments.some(isSplat)) { - initialScore += splatPenalty; - } - if (index) { - initialScore += indexRouteValue; - } - return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore); -} -function compareIndexes(a, b) { - let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]); - return siblings ? - // If two routes are siblings, we should try to match the earlier sibling - // first. This allows people to have fine-grained control over the matching - // behavior by simply putting routes with identical paths in the order they - // want them tried. - a[a.length - 1] - b[b.length - 1] : - // Otherwise, it doesn't really make sense to rank non-siblings by index, - // so they sort equally. - 0; -} -function matchRouteBranch(branch, pathname) { - let { - routesMeta - } = branch; - let matchedParams = {}; - let matchedPathname = "/"; - let matches = []; - for (let i = 0; i < routesMeta.length; ++i) { - let meta = routesMeta[i]; - let end = i === routesMeta.length - 1; - let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/"; - let match = matchPath({ - path: meta.relativePath, - caseSensitive: meta.caseSensitive, - end - }, remainingPathname); - if (!match) return null; - Object.assign(matchedParams, match.params); - let route = meta.route; - matches.push({ - // TODO: Can this as be avoided? - params: matchedParams, - pathname: joinPaths([matchedPathname, match.pathname]), - pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])), - route - }); - if (match.pathnameBase !== "/") { - matchedPathname = joinPaths([matchedPathname, match.pathnameBase]); - } - } - return matches; -} -/** - * Returns a path with params interpolated. - * - * @see https://reactrouter.com/utils/generate-path - */ -function generatePath(originalPath, params) { - if (params === void 0) { - params = {}; - } - let path = originalPath; - if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) { - warning(false, "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\".")); - path = path.replace(/\*$/, "/*"); - } - // ensure `/` is added at the beginning if the path is absolute - const prefix = path.startsWith("/") ? "/" : ""; - const stringify = p => p == null ? "" : typeof p === "string" ? p : String(p); - const segments = path.split(/\/+/).map((segment, index, array) => { - const isLastSegment = index === array.length - 1; - // only apply the splat if it's the last segment - if (isLastSegment && segment === "*") { - const star = "*"; - // Apply the splat - return stringify(params[star]); - } - const keyMatch = segment.match(/^:([\w-]+)(\??)$/); - if (keyMatch) { - const [, key, optional] = keyMatch; - let param = params[key]; - invariant(optional === "?" || param != null, "Missing \":" + key + "\" param"); - return stringify(param); - } - // Remove any optional markers from optional static segments - return segment.replace(/\?$/g, ""); - }) - // Remove empty segments - .filter(segment => !!segment); - return prefix + segments.join("/"); -} -/** - * Performs pattern matching on a URL pathname and returns information about - * the match. - * - * @see https://reactrouter.com/utils/match-path - */ -function matchPath(pattern, pathname) { - if (typeof pattern === "string") { - pattern = { - path: pattern, - caseSensitive: false, - end: true - }; - } - let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end); - let match = pathname.match(matcher); - if (!match) return null; - let matchedPathname = match[0]; - let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1"); - let captureGroups = match.slice(1); - let params = compiledParams.reduce((memo, _ref, index) => { - let { - paramName, - isOptional - } = _ref; - // We need to compute the pathnameBase here using the raw splat value - // instead of using params["*"] later because it will be decoded then - if (paramName === "*") { - let splatValue = captureGroups[index] || ""; - pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1"); - } - const value = captureGroups[index]; - if (isOptional && !value) { - memo[paramName] = undefined; - } else { - memo[paramName] = (value || "").replace(/%2F/g, "/"); - } - return memo; - }, {}); - return { - params, - pathname: matchedPathname, - pathnameBase, - pattern - }; -} -function compilePath(path, caseSensitive, end) { - if (caseSensitive === void 0) { - caseSensitive = false; - } - if (end === void 0) { - end = true; - } - warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\".")); - let params = []; - let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below - .replace(/^\/*/, "/") // Make sure it has a leading / - .replace(/[\\.*+^${}|()[\]]/g, "\\$&") // Escape special regex chars - .replace(/\/:([\w-]+)(\?)?/g, (_, paramName, isOptional) => { - params.push({ - paramName, - isOptional: isOptional != null - }); - return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)"; - }); - if (path.endsWith("*")) { - params.push({ - paramName: "*" - }); - regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest - : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"] - } else if (end) { - // When matching to the end, ignore trailing slashes - regexpSource += "\\/*$"; - } else if (path !== "" && path !== "/") { - // If our path is non-empty and contains anything beyond an initial slash, - // then we have _some_ form of path in our regex, so we should expect to - // match only if we find the end of this path segment. Look for an optional - // non-captured trailing slash (to match a portion of the URL) or the end - // of the path (if we've matched to the end). We used to do this with a - // word boundary but that gives false positives on routes like - // /user-preferences since `-` counts as a word boundary. - regexpSource += "(?:(?=\\/|$))"; - } else ; - let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i"); - return [matcher, params]; -} -function decodePath(value) { - try { - return value.split("/").map(v => decodeURIComponent(v).replace(/\//g, "%2F")).join("/"); - } catch (error) { - warning(false, "The URL path \"" + value + "\" could not be decoded because it is is a " + "malformed URL segment. This is probably due to a bad percent " + ("encoding (" + error + ").")); - return value; - } -} -/** - * @private - */ -function stripBasename(pathname, basename) { - if (basename === "/") return pathname; - if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) { - return null; - } - // We want to leave trailing slash behavior in the user's control, so if they - // specify a basename with a trailing slash, we should support it - let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length; - let nextChar = pathname.charAt(startIndex); - if (nextChar && nextChar !== "/") { - // pathname does not start with basename/ - return null; - } - return pathname.slice(startIndex) || "/"; -} -/** - * Returns a resolved path object relative to the given pathname. - * - * @see https://reactrouter.com/utils/resolve-path - */ -function resolvePath(to, fromPathname) { - if (fromPathname === void 0) { - fromPathname = "/"; - } - let { - pathname: toPathname, - search = "", - hash = "" - } = typeof to === "string" ? parsePath(to) : to; - let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname; - return { - pathname, - search: normalizeSearch(search), - hash: normalizeHash(hash) - }; -} -function resolvePathname(relativePath, fromPathname) { - let segments = fromPathname.replace(/\/+$/, "").split("/"); - let relativeSegments = relativePath.split("/"); - relativeSegments.forEach(segment => { - if (segment === "..") { - // Keep the root "" segment so the pathname starts at / - if (segments.length > 1) segments.pop(); - } else if (segment !== ".") { - segments.push(segment); - } - }); - return segments.length > 1 ? segments.join("/") : "/"; -} -function getInvalidPathError(char, field, dest, path) { - return "Cannot include a '" + char + "' character in a manually specified " + ("`to." + field + "` field [" + JSON.stringify(path) + "]. Please separate it out to the ") + ("`to." + dest + "` field. Alternatively you may provide the full path as ") + "a string in and the router will parse it for you."; -} -/** - * @private - * - * When processing relative navigation we want to ignore ancestor routes that - * do not contribute to the path, such that index/pathless layout routes don't - * interfere. - * - * For example, when moving a route element into an index route and/or a - * pathless layout route, relative link behavior contained within should stay - * the same. Both of the following examples should link back to the root: - * - * - * - * - * - * - * - * }> // <-- Does not contribute - * // <-- Does not contribute - * - * - */ -function getPathContributingMatches(matches) { - return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0); -} -// Return the array of pathnames for the current route matches - used to -// generate the routePathnames input for resolveTo() -function getResolveToMatches(matches, v7_relativeSplatPath) { - let pathMatches = getPathContributingMatches(matches); - // When v7_relativeSplatPath is enabled, use the full pathname for the leaf - // match so we include splat values for "." links. See: - // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329 - if (v7_relativeSplatPath) { - return pathMatches.map((match, idx) => idx === matches.length - 1 ? match.pathname : match.pathnameBase); - } - return pathMatches.map(match => match.pathnameBase); -} -/** - * @private - */ -function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) { - if (isPathRelative === void 0) { - isPathRelative = false; - } - let to; - if (typeof toArg === "string") { - to = parsePath(toArg); - } else { - to = _extends({}, toArg); - invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to)); - invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to)); - invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to)); - } - let isEmptyPath = toArg === "" || to.pathname === ""; - let toPathname = isEmptyPath ? "/" : to.pathname; - let from; - // Routing is relative to the current pathname if explicitly requested. - // - // If a pathname is explicitly provided in `to`, it should be relative to the - // route context. This is explained in `Note on `` values` in our - // migration guide from v5 as a means of disambiguation between `to` values - // that begin with `/` and those that do not. However, this is problematic for - // `to` values that do not provide a pathname. `to` can simply be a search or - // hash string, in which case we should assume that the navigation is relative - // to the current location's pathname and *not* the route pathname. - if (toPathname == null) { - from = locationPathname; - } else { - let routePathnameIndex = routePathnames.length - 1; - // With relative="route" (the default), each leading .. segment means - // "go up one route" instead of "go up one URL segment". This is a key - // difference from how works and a major reason we call this a - // "to" value instead of a "href". - if (!isPathRelative && toPathname.startsWith("..")) { - let toSegments = toPathname.split("/"); - while (toSegments[0] === "..") { - toSegments.shift(); - routePathnameIndex -= 1; - } - to.pathname = toSegments.join("/"); - } - from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/"; - } - let path = resolvePath(to, from); - // Ensure the pathname has a trailing slash if the original "to" had one - let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/"); - // Or if this was a link to the current path which has a trailing slash - let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/"); - if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) { - path.pathname += "/"; - } - return path; -} -/** - * @private - */ -function getToPathname(to) { - // Empty strings should be treated the same as / paths - return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname; -} -/** - * @private - */ -const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/"); -/** - * @private - */ -const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/"); -/** - * @private - */ -const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search; -/** - * @private - */ -const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash; -/** - * This is a shortcut for creating `application/json` responses. Converts `data` - * to JSON and sets the `Content-Type` header. - */ -const json = function json(data, init) { - if (init === void 0) { - init = {}; - } - let responseInit = typeof init === "number" ? { - status: init - } : init; - let headers = new Headers(responseInit.headers); - if (!headers.has("Content-Type")) { - headers.set("Content-Type", "application/json; charset=utf-8"); - } - return new Response(JSON.stringify(data), _extends({}, responseInit, { - headers - })); -}; -class AbortedDeferredError extends Error {} -class DeferredData { - constructor(data, responseInit) { - this.pendingKeysSet = new Set(); - this.subscribers = new Set(); - this.deferredKeys = []; - invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects"); - // Set up an AbortController + Promise we can race against to exit early - // cancellation - let reject; - this.abortPromise = new Promise((_, r) => reject = r); - this.controller = new AbortController(); - let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted")); - this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort); - this.controller.signal.addEventListener("abort", onAbort); - this.data = Object.entries(data).reduce((acc, _ref2) => { - let [key, value] = _ref2; - return Object.assign(acc, { - [key]: this.trackPromise(key, value) - }); - }, {}); - if (this.done) { - // All incoming values were resolved - this.unlistenAbortSignal(); - } - this.init = responseInit; - } - trackPromise(key, value) { - if (!(value instanceof Promise)) { - return value; - } - this.deferredKeys.push(key); - this.pendingKeysSet.add(key); - // We store a little wrapper promise that will be extended with - // _data/_error props upon resolve/reject - let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error)); - // Register rejection listeners to avoid uncaught promise rejections on - // errors or aborted deferred values - promise.catch(() => {}); - Object.defineProperty(promise, "_tracked", { - get: () => true - }); - return promise; - } - onSettle(promise, key, error, data) { - if (this.controller.signal.aborted && error instanceof AbortedDeferredError) { - this.unlistenAbortSignal(); - Object.defineProperty(promise, "_error", { - get: () => error - }); - return Promise.reject(error); - } - this.pendingKeysSet.delete(key); - if (this.done) { - // Nothing left to abort! - this.unlistenAbortSignal(); - } - // If the promise was resolved/rejected with undefined, we'll throw an error as you - // should always resolve with a value or null - if (error === undefined && data === undefined) { - let undefinedError = new Error("Deferred data for key \"" + key + "\" resolved/rejected with `undefined`, " + "you must resolve/reject with a value or `null`."); - Object.defineProperty(promise, "_error", { - get: () => undefinedError - }); - this.emit(false, key); - return Promise.reject(undefinedError); - } - if (data === undefined) { - Object.defineProperty(promise, "_error", { - get: () => error - }); - this.emit(false, key); - return Promise.reject(error); - } - Object.defineProperty(promise, "_data", { - get: () => data - }); - this.emit(false, key); - return data; - } - emit(aborted, settledKey) { - this.subscribers.forEach(subscriber => subscriber(aborted, settledKey)); - } - subscribe(fn) { - this.subscribers.add(fn); - return () => this.subscribers.delete(fn); - } - cancel() { - this.controller.abort(); - this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k)); - this.emit(true); - } - async resolveData(signal) { - let aborted = false; - if (!this.done) { - let onAbort = () => this.cancel(); - signal.addEventListener("abort", onAbort); - aborted = await new Promise(resolve => { - this.subscribe(aborted => { - signal.removeEventListener("abort", onAbort); - if (aborted || this.done) { - resolve(aborted); - } - }); - }); - } - return aborted; - } - get done() { - return this.pendingKeysSet.size === 0; - } - get unwrappedData() { - invariant(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds"); - return Object.entries(this.data).reduce((acc, _ref3) => { - let [key, value] = _ref3; - return Object.assign(acc, { - [key]: unwrapTrackedPromise(value) - }); - }, {}); - } - get pendingKeys() { - return Array.from(this.pendingKeysSet); - } -} -function isTrackedPromise(value) { - return value instanceof Promise && value._tracked === true; -} -function unwrapTrackedPromise(value) { - if (!isTrackedPromise(value)) { - return value; - } - if (value._error) { - throw value._error; - } - return value._data; -} -const defer = function defer(data, init) { - if (init === void 0) { - init = {}; - } - let responseInit = typeof init === "number" ? { - status: init - } : init; - return new DeferredData(data, responseInit); -}; -/** - * A redirect response. Sets the status code and the `Location` header. - * Defaults to "302 Found". - */ -const redirect = function redirect(url, init) { - if (init === void 0) { - init = 302; - } - let responseInit = init; - if (typeof responseInit === "number") { - responseInit = { - status: responseInit - }; - } else if (typeof responseInit.status === "undefined") { - responseInit.status = 302; - } - let headers = new Headers(responseInit.headers); - headers.set("Location", url); - return new Response(null, _extends({}, responseInit, { - headers - })); -}; -/** - * A redirect response that will force a document reload to the new location. - * Sets the status code and the `Location` header. - * Defaults to "302 Found". - */ -const redirectDocument = (url, init) => { - let response = redirect(url, init); - response.headers.set("X-Remix-Reload-Document", "true"); - return response; -}; -/** - * @private - * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies - * - * We don't export the class for public use since it's an implementation - * detail, but we export the interface above so folks can build their own - * abstractions around instances via isRouteErrorResponse() - */ -class ErrorResponseImpl { - constructor(status, statusText, data, internal) { - if (internal === void 0) { - internal = false; - } - this.status = status; - this.statusText = statusText || ""; - this.internal = internal; - if (data instanceof Error) { - this.data = data.toString(); - this.error = data; - } else { - this.data = data; - } - } -} -/** - * Check if the given error is an ErrorResponse generated from a 4xx/5xx - * Response thrown from an action/loader - */ -function isRouteErrorResponse(error) { - return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error; -} - -const validMutationMethodsArr = ["post", "put", "patch", "delete"]; -const validMutationMethods = new Set(validMutationMethodsArr); -const validRequestMethodsArr = ["get", ...validMutationMethodsArr]; -const validRequestMethods = new Set(validRequestMethodsArr); -const redirectStatusCodes = new Set([301, 302, 303, 307, 308]); -const redirectPreserveMethodStatusCodes = new Set([307, 308]); -const IDLE_NAVIGATION = { - state: "idle", - location: undefined, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined -}; -const IDLE_FETCHER = { - state: "idle", - data: undefined, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined -}; -const IDLE_BLOCKER = { - state: "unblocked", - proceed: undefined, - reset: undefined, - location: undefined -}; -const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i; -const defaultMapRouteProperties = route => ({ - hasErrorBoundary: Boolean(route.hasErrorBoundary) -}); -const TRANSITIONS_STORAGE_KEY = "remix-router-transitions"; -//#endregion -//////////////////////////////////////////////////////////////////////////////// -//#region createRouter -//////////////////////////////////////////////////////////////////////////////// -/** - * Create a router and listen to history POP navigations - */ -function createRouter(init) { - const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : undefined; - const isBrowser = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined"; - const isServer = !isBrowser; - invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter"); - let mapRouteProperties; - if (init.mapRouteProperties) { - mapRouteProperties = init.mapRouteProperties; - } else if (init.detectErrorBoundary) { - // If they are still using the deprecated version, wrap it with the new API - let detectErrorBoundary = init.detectErrorBoundary; - mapRouteProperties = route => ({ - hasErrorBoundary: detectErrorBoundary(route) - }); - } else { - mapRouteProperties = defaultMapRouteProperties; - } - // Routes keyed by ID - let manifest = {}; - // Routes in tree format for matching - let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest); - let inFlightDataRoutes; - let basename = init.basename || "/"; - let dataStrategyImpl = init.unstable_dataStrategy || defaultDataStrategy; - // Config driven behavior flags - let future = _extends({ - v7_fetcherPersist: false, - v7_normalizeFormMethod: false, - v7_partialHydration: false, - v7_prependBasename: false, - v7_relativeSplatPath: false, - unstable_skipActionErrorRevalidation: false - }, init.future); - // Cleanup function for history - let unlistenHistory = null; - // Externally-provided functions to call on all state changes - let subscribers = new Set(); - // Externally-provided object to hold scroll restoration locations during routing - let savedScrollPositions = null; - // Externally-provided function to get scroll restoration keys - let getScrollRestorationKey = null; - // Externally-provided function to get current scroll position - let getScrollPosition = null; - // One-time flag to control the initial hydration scroll restoration. Because - // we don't get the saved positions from until _after_ - // the initial render, we need to manually trigger a separate updateState to - // send along the restoreScrollPosition - // Set to true if we have `hydrationData` since we assume we were SSR'd and that - // SSR did the initial scroll restoration. - let initialScrollRestored = init.hydrationData != null; - let initialMatches = matchRoutes(dataRoutes, init.history.location, basename); - let initialErrors = null; - if (initialMatches == null) { - // If we do not match a user-provided-route, fall back to the root - // to allow the error boundary to take over - let error = getInternalRouterError(404, { - pathname: init.history.location.pathname - }); - let { - matches, - route - } = getShortCircuitMatches(dataRoutes); - initialMatches = matches; - initialErrors = { - [route.id]: error - }; - } - let initialized; - let hasLazyRoutes = initialMatches.some(m => m.route.lazy); - let hasLoaders = initialMatches.some(m => m.route.loader); - if (hasLazyRoutes) { - // All initialMatches need to be loaded before we're ready. If we have lazy - // functions around still then we'll need to run them in initialize() - initialized = false; - } else if (!hasLoaders) { - // If we've got no loaders to run, then we're good to go - initialized = true; - } else if (future.v7_partialHydration) { - // If partial hydration is enabled, we're initialized so long as we were - // provided with hydrationData for every route with a loader, and no loaders - // were marked for explicit hydration - let loaderData = init.hydrationData ? init.hydrationData.loaderData : null; - let errors = init.hydrationData ? init.hydrationData.errors : null; - let isRouteInitialized = m => { - // No loader, nothing to initialize - if (!m.route.loader) { - return true; - } - // Explicitly opting-in to running on hydration - if (typeof m.route.loader === "function" && m.route.loader.hydrate === true) { - return false; - } - // Otherwise, initialized if hydrated with data or an error - return loaderData && loaderData[m.route.id] !== undefined || errors && errors[m.route.id] !== undefined; - }; - // If errors exist, don't consider routes below the boundary - if (errors) { - let idx = initialMatches.findIndex(m => errors[m.route.id] !== undefined); - initialized = initialMatches.slice(0, idx + 1).every(isRouteInitialized); - } else { - initialized = initialMatches.every(isRouteInitialized); - } - } else { - // Without partial hydration - we're initialized if we were provided any - // hydrationData - which is expected to be complete - initialized = init.hydrationData != null; - } - let router; - let state = { - historyAction: init.history.action, - location: init.history.location, - matches: initialMatches, - initialized, - navigation: IDLE_NAVIGATION, - // Don't restore on initial updateState() if we were SSR'd - restoreScrollPosition: init.hydrationData != null ? false : null, - preventScrollReset: false, - revalidation: "idle", - loaderData: init.hydrationData && init.hydrationData.loaderData || {}, - actionData: init.hydrationData && init.hydrationData.actionData || null, - errors: init.hydrationData && init.hydrationData.errors || initialErrors, - fetchers: new Map(), - blockers: new Map() - }; - // -- Stateful internal variables to manage navigations -- - // Current navigation in progress (to be committed in completeNavigation) - let pendingAction = Action.Pop; - // Should the current navigation prevent the scroll reset if scroll cannot - // be restored? - let pendingPreventScrollReset = false; - // AbortController for the active navigation - let pendingNavigationController; - // Should the current navigation enable document.startViewTransition? - let pendingViewTransitionEnabled = false; - // Store applied view transitions so we can apply them on POP - let appliedViewTransitions = new Map(); - // Cleanup function for persisting applied transitions to sessionStorage - let removePageHideEventListener = null; - // We use this to avoid touching history in completeNavigation if a - // revalidation is entirely uninterrupted - let isUninterruptedRevalidation = false; - // Use this internal flag to force revalidation of all loaders: - // - submissions (completed or interrupted) - // - useRevalidator() - // - X-Remix-Revalidate (from redirect) - let isRevalidationRequired = false; - // Use this internal array to capture routes that require revalidation due - // to a cancelled deferred on action submission - let cancelledDeferredRoutes = []; - // Use this internal array to capture fetcher loads that were cancelled by an - // action navigation and require revalidation - let cancelledFetcherLoads = []; - // AbortControllers for any in-flight fetchers - let fetchControllers = new Map(); - // Track loads based on the order in which they started - let incrementingLoadId = 0; - // Track the outstanding pending navigation data load to be compared against - // the globally incrementing load when a fetcher load lands after a completed - // navigation - let pendingNavigationLoadId = -1; - // Fetchers that triggered data reloads as a result of their actions - let fetchReloadIds = new Map(); - // Fetchers that triggered redirect navigations - let fetchRedirectIds = new Set(); - // Most recent href/match for fetcher.load calls for fetchers - let fetchLoadMatches = new Map(); - // Ref-count mounted fetchers so we know when it's ok to clean them up - let activeFetchers = new Map(); - // Fetchers that have requested a delete when using v7_fetcherPersist, - // they'll be officially removed after they return to idle - let deletedFetchers = new Set(); - // Store DeferredData instances for active route matches. When a - // route loader returns defer() we stick one in here. Then, when a nested - // promise resolves we update loaderData. If a new navigation starts we - // cancel active deferreds for eliminated routes. - let activeDeferreds = new Map(); - // Store blocker functions in a separate Map outside of router state since - // we don't need to update UI state if they change - let blockerFunctions = new Map(); - // Flag to ignore the next history update, so we can revert the URL change on - // a POP navigation that was blocked by the user without touching router state - let ignoreNextHistoryUpdate = false; - // Initialize the router, all side effects should be kicked off from here. - // Implemented as a Fluent API for ease of: - // let router = createRouter(init).initialize(); - function initialize() { - // If history informs us of a POP navigation, start the navigation but do not update - // state. We'll update our own state once the navigation completes - unlistenHistory = init.history.listen(_ref => { - let { - action: historyAction, - location, - delta - } = _ref; - // Ignore this event if it was just us resetting the URL from a - // blocked POP navigation - if (ignoreNextHistoryUpdate) { - ignoreNextHistoryUpdate = false; - return; - } - warning(blockerFunctions.size === 0 || delta != null, "You are trying to use a blocker on a POP navigation to a location " + "that was not created by @remix-run/router. This will fail silently in " + "production. This can happen if you are navigating outside the router " + "via `window.history.pushState`/`window.location.hash` instead of using " + "router navigation APIs. This can also happen if you are using " + "createHashRouter and the user manually changes the URL."); - let blockerKey = shouldBlockNavigation({ - currentLocation: state.location, - nextLocation: location, - historyAction - }); - if (blockerKey && delta != null) { - // Restore the URL to match the current UI, but don't update router state - ignoreNextHistoryUpdate = true; - init.history.go(delta * -1); - // Put the blocker into a blocked state - updateBlocker(blockerKey, { - state: "blocked", - location, - proceed() { - updateBlocker(blockerKey, { - state: "proceeding", - proceed: undefined, - reset: undefined, - location - }); - // Re-do the same POP navigation we just blocked - init.history.go(delta); - }, - reset() { - let blockers = new Map(state.blockers); - blockers.set(blockerKey, IDLE_BLOCKER); - updateState({ - blockers - }); - } - }); - return; - } - return startNavigation(historyAction, location); - }); - if (isBrowser) { - // FIXME: This feels gross. How can we cleanup the lines between - // scrollRestoration/appliedTransitions persistance? - restoreAppliedTransitions(routerWindow, appliedViewTransitions); - let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions); - routerWindow.addEventListener("pagehide", _saveAppliedTransitions); - removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions); - } - // Kick off initial data load if needed. Use Pop to avoid modifying history - // Note we don't do any handling of lazy here. For SPA's it'll get handled - // in the normal navigation flow. For SSR it's expected that lazy modules are - // resolved prior to router creation since we can't go into a fallbackElement - // UI for SSR'd apps - if (!state.initialized) { - startNavigation(Action.Pop, state.location, { - initialHydration: true - }); - } - return router; - } - // Clean up a router and it's side effects - function dispose() { - if (unlistenHistory) { - unlistenHistory(); - } - if (removePageHideEventListener) { - removePageHideEventListener(); - } - subscribers.clear(); - pendingNavigationController && pendingNavigationController.abort(); - state.fetchers.forEach((_, key) => deleteFetcher(key)); - state.blockers.forEach((_, key) => deleteBlocker(key)); - } - // Subscribe to state updates for the router - function subscribe(fn) { - subscribers.add(fn); - return () => subscribers.delete(fn); - } - // Update our state and notify the calling context of the change - function updateState(newState, opts) { - if (opts === void 0) { - opts = {}; - } - state = _extends({}, state, newState); - // Prep fetcher cleanup so we can tell the UI which fetcher data entries - // can be removed - let completedFetchers = []; - let deletedFetchersKeys = []; - if (future.v7_fetcherPersist) { - state.fetchers.forEach((fetcher, key) => { - if (fetcher.state === "idle") { - if (deletedFetchers.has(key)) { - // Unmounted from the UI and can be totally removed - deletedFetchersKeys.push(key); - } else { - // Returned to idle but still mounted in the UI, so semi-remains for - // revalidations and such - completedFetchers.push(key); - } - } - }); - } - // Iterate over a local copy so that if flushSync is used and we end up - // removing and adding a new subscriber due to the useCallback dependencies, - // we don't get ourselves into a loop calling the new subscriber immediately - [...subscribers].forEach(subscriber => subscriber(state, { - deletedFetchers: deletedFetchersKeys, - unstable_viewTransitionOpts: opts.viewTransitionOpts, - unstable_flushSync: opts.flushSync === true - })); - // Remove idle fetchers from state since we only care about in-flight fetchers. - if (future.v7_fetcherPersist) { - completedFetchers.forEach(key => state.fetchers.delete(key)); - deletedFetchersKeys.forEach(key => deleteFetcher(key)); - } - } - // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION - // and setting state.[historyAction/location/matches] to the new route. - // - Location is a required param - // - Navigation will always be set to IDLE_NAVIGATION - // - Can pass any other state in newState - function completeNavigation(location, newState, _temp) { - var _location$state, _location$state2; - let { - flushSync - } = _temp === void 0 ? {} : _temp; - // Deduce if we're in a loading/actionReload state: - // - We have committed actionData in the store - // - The current navigation was a mutation submission - // - We're past the submitting state and into the loading state - // - The location being loaded is not the result of a redirect - let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true; - let actionData; - if (newState.actionData) { - if (Object.keys(newState.actionData).length > 0) { - actionData = newState.actionData; - } else { - // Empty actionData -> clear prior actionData due to an action error - actionData = null; - } - } else if (isActionReload) { - // Keep the current data if we're wrapping up the action reload - actionData = state.actionData; - } else { - // Clear actionData on any other completed navigations - actionData = null; - } - // Always preserve any existing loaderData from re-used routes - let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData; - // On a successful navigation we can assume we got through all blockers - // so we can start fresh - let blockers = state.blockers; - if (blockers.size > 0) { - blockers = new Map(blockers); - blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER)); - } - // Always respect the user flag. Otherwise don't reset on mutation - // submission navigations unless they redirect - let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true; - if (inFlightDataRoutes) { - dataRoutes = inFlightDataRoutes; - inFlightDataRoutes = undefined; - } - if (isUninterruptedRevalidation) ; else if (pendingAction === Action.Pop) ; else if (pendingAction === Action.Push) { - init.history.push(location, location.state); - } else if (pendingAction === Action.Replace) { - init.history.replace(location, location.state); - } - let viewTransitionOpts; - // On POP, enable transitions if they were enabled on the original navigation - if (pendingAction === Action.Pop) { - // Forward takes precedence so they behave like the original navigation - let priorPaths = appliedViewTransitions.get(state.location.pathname); - if (priorPaths && priorPaths.has(location.pathname)) { - viewTransitionOpts = { - currentLocation: state.location, - nextLocation: location - }; - } else if (appliedViewTransitions.has(location.pathname)) { - // If we don't have a previous forward nav, assume we're popping back to - // the new location and enable if that location previously enabled - viewTransitionOpts = { - currentLocation: location, - nextLocation: state.location - }; - } - } else if (pendingViewTransitionEnabled) { - // Store the applied transition on PUSH/REPLACE - let toPaths = appliedViewTransitions.get(state.location.pathname); - if (toPaths) { - toPaths.add(location.pathname); - } else { - toPaths = new Set([location.pathname]); - appliedViewTransitions.set(state.location.pathname, toPaths); - } - viewTransitionOpts = { - currentLocation: state.location, - nextLocation: location - }; - } - updateState(_extends({}, newState, { - actionData, - loaderData, - historyAction: pendingAction, - location, - initialized: true, - navigation: IDLE_NAVIGATION, - revalidation: "idle", - restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches), - preventScrollReset, - blockers - }), { - viewTransitionOpts, - flushSync: flushSync === true - }); - // Reset stateful navigation vars - pendingAction = Action.Pop; - pendingPreventScrollReset = false; - pendingViewTransitionEnabled = false; - isUninterruptedRevalidation = false; - isRevalidationRequired = false; - cancelledDeferredRoutes = []; - cancelledFetcherLoads = []; - } - // Trigger a navigation event, which can either be a numerical POP or a PUSH - // replace with an optional submission - async function navigate(to, opts) { - if (typeof to === "number") { - init.history.go(to); - return; - } - let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, future.v7_relativeSplatPath, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative); - let { - path, - submission, - error - } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts); - let currentLocation = state.location; - let nextLocation = createLocation(state.location, path, opts && opts.state); - // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded - // URL from window.location, so we need to encode it here so the behavior - // remains the same as POP and non-data-router usages. new URL() does all - // the same encoding we'd get from a history.pushState/window.location read - // without having to touch history - nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation)); - let userReplace = opts && opts.replace != null ? opts.replace : undefined; - let historyAction = Action.Push; - if (userReplace === true) { - historyAction = Action.Replace; - } else if (userReplace === false) ; else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) { - // By default on submissions to the current location we REPLACE so that - // users don't have to double-click the back button to get to the prior - // location. If the user redirects to a different location from the - // action/loader this will be ignored and the redirect will be a PUSH - historyAction = Action.Replace; - } - let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined; - let flushSync = (opts && opts.unstable_flushSync) === true; - let blockerKey = shouldBlockNavigation({ - currentLocation, - nextLocation, - historyAction - }); - if (blockerKey) { - // Put the blocker into a blocked state - updateBlocker(blockerKey, { - state: "blocked", - location: nextLocation, - proceed() { - updateBlocker(blockerKey, { - state: "proceeding", - proceed: undefined, - reset: undefined, - location: nextLocation - }); - // Send the same navigation through - navigate(to, opts); - }, - reset() { - let blockers = new Map(state.blockers); - blockers.set(blockerKey, IDLE_BLOCKER); - updateState({ - blockers - }); - } - }); - return; - } - return await startNavigation(historyAction, nextLocation, { - submission, - // Send through the formData serialization error if we have one so we can - // render at the right error boundary after we match routes - pendingError: error, - preventScrollReset, - replace: opts && opts.replace, - enableViewTransition: opts && opts.unstable_viewTransition, - flushSync - }); - } - // Revalidate all current loaders. If a navigation is in progress or if this - // is interrupted by a navigation, allow this to "succeed" by calling all - // loaders during the next loader round - function revalidate() { - interruptActiveLoads(); - updateState({ - revalidation: "loading" - }); - // If we're currently submitting an action, we don't need to start a new - // navigation, we'll just let the follow up loader execution call all loaders - if (state.navigation.state === "submitting") { - return; - } - // If we're currently in an idle state, start a new navigation for the current - // action/location and mark it as uninterrupted, which will skip the history - // update in completeNavigation - if (state.navigation.state === "idle") { - startNavigation(state.historyAction, state.location, { - startUninterruptedRevalidation: true - }); - return; - } - // Otherwise, if we're currently in a loading state, just start a new - // navigation to the navigation.location but do not trigger an uninterrupted - // revalidation so that history correctly updates once the navigation completes - startNavigation(pendingAction || state.historyAction, state.navigation.location, { - overrideNavigation: state.navigation - }); - } - // Start a navigation to the given action/location. Can optionally provide a - // overrideNavigation which will override the normalLoad in the case of a redirect - // navigation - async function startNavigation(historyAction, location, opts) { - // Abort any in-progress navigations and start a new one. Unset any ongoing - // uninterrupted revalidations unless told otherwise, since we want this - // new navigation to update history normally - pendingNavigationController && pendingNavigationController.abort(); - pendingNavigationController = null; - pendingAction = historyAction; - isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true; - // Save the current scroll position every time we start a new navigation, - // and track whether we should reset scroll on completion - saveScrollPosition(state.location, state.matches); - pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; - pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true; - let routesToUse = inFlightDataRoutes || dataRoutes; - let loadingNavigation = opts && opts.overrideNavigation; - let matches = matchRoutes(routesToUse, location, basename); - let flushSync = (opts && opts.flushSync) === true; - // Short circuit with a 404 on the root error boundary if we match nothing - if (!matches) { - let error = getInternalRouterError(404, { - pathname: location.pathname - }); - let { - matches: notFoundMatches, - route - } = getShortCircuitMatches(routesToUse); - // Cancel all pending deferred on 404s since we don't keep any routes - cancelActiveDeferreds(); - completeNavigation(location, { - matches: notFoundMatches, - loaderData: {}, - errors: { - [route.id]: error - } - }, { - flushSync - }); - return; - } - // Short circuit if it's only a hash change and not a revalidation or - // mutation submission. - // - // Ignore on initial page loads because since the initial load will always - // be "same hash". For example, on /page#hash and submit a - // which will default to a navigation to /page - if (state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) { - completeNavigation(location, { - matches - }, { - flushSync - }); - return; - } - // Create a controller/Request for this navigation - pendingNavigationController = new AbortController(); - let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission); - let pendingActionResult; - if (opts && opts.pendingError) { - // If we have a pendingError, it means the user attempted a GET submission - // with binary FormData so assign here and skip to handleLoaders. That - // way we handle calling loaders above the boundary etc. It's not really - // different from an actionError in that sense. - pendingActionResult = [findNearestBoundary(matches).route.id, { - type: ResultType.error, - error: opts.pendingError - }]; - } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) { - // Call action if we received an action submission - let actionResult = await handleAction(request, location, opts.submission, matches, { - replace: opts.replace, - flushSync - }); - if (actionResult.shortCircuited) { - return; - } - pendingActionResult = actionResult.pendingActionResult; - loadingNavigation = getLoadingNavigation(location, opts.submission); - flushSync = false; - // Create a GET request for the loaders - request = createClientSideRequest(init.history, request.url, request.signal); - } - // Call loaders - let { - shortCircuited, - loaderData, - errors - } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionResult); - if (shortCircuited) { - return; - } - // Clean up now that the action/loaders have completed. Don't clean up if - // we short circuited because pendingNavigationController will have already - // been assigned to a new controller for the next navigation - pendingNavigationController = null; - completeNavigation(location, _extends({ - matches - }, getActionDataForCommit(pendingActionResult), { - loaderData, - errors - })); - } - // Call the action matched by the leaf route for this navigation and handle - // redirects/errors - async function handleAction(request, location, submission, matches, opts) { - if (opts === void 0) { - opts = {}; - } - interruptActiveLoads(); - // Put us in a submitting state - let navigation = getSubmittingNavigation(location, submission); - updateState({ - navigation - }, { - flushSync: opts.flushSync === true - }); - // Call our action and get the result - let result; - let actionMatch = getTargetMatch(matches, location); - if (!actionMatch.route.action && !actionMatch.route.lazy) { - result = { - type: ResultType.error, - error: getInternalRouterError(405, { - method: request.method, - pathname: location.pathname, - routeId: actionMatch.route.id - }) - }; - } else { - let results = await callDataStrategy("action", request, [actionMatch], matches); - result = results[0]; - if (request.signal.aborted) { - return { - shortCircuited: true - }; - } - } - if (isRedirectResult(result)) { - let replace; - if (opts && opts.replace != null) { - replace = opts.replace; - } else { - // If the user didn't explicity indicate replace behavior, replace if - // we redirected to the exact same location we're currently at to avoid - // double back-buttons - let location = normalizeRedirectLocation(result.response.headers.get("Location"), new URL(request.url), basename); - replace = location === state.location.pathname + state.location.search; - } - await startRedirectNavigation(request, result, { - submission, - replace - }); - return { - shortCircuited: true - }; - } - if (isDeferredResult(result)) { - throw getInternalRouterError(400, { - type: "defer-action" - }); - } - if (isErrorResult(result)) { - // Store off the pending error - we use it to determine which loaders - // to call and will commit it when we complete the navigation - let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); - // By default, all submissions are REPLACE navigations, but if the - // action threw an error that'll be rendered in an errorElement, we fall - // back to PUSH so that the user can use the back button to get back to - // the pre-submission form location to try again - if ((opts && opts.replace) !== true) { - pendingAction = Action.Push; - } - return { - pendingActionResult: [boundaryMatch.route.id, result] - }; - } - return { - pendingActionResult: [actionMatch.route.id, result] - }; - } - // Call all applicable loaders for the given matches, handling redirects, - // errors, etc. - async function handleLoaders(request, location, matches, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionResult) { - // Figure out the right navigation we want to use for data loading - let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission); - // If this was a redirect from an action we don't have a "submission" but - // we have it on the loading navigation so use that if available - let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation); - let routesToUse = inFlightDataRoutes || dataRoutes; - let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, future.unstable_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult); - // Cancel pending deferreds for no-longer-matched routes or routes we're - // about to reload. Note that if this is an action reload we would have - // already cancelled all pending deferreds so this would be a no-op - cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId)); - pendingNavigationLoadId = ++incrementingLoadId; - // Short circuit if we have no loaders to run - if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) { - let updatedFetchers = markFetchRedirectsDone(); - completeNavigation(location, _extends({ - matches, - loaderData: {}, - // Commit pending error if we're short circuiting - errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { - [pendingActionResult[0]]: pendingActionResult[1].error - } : null - }, getActionDataForCommit(pendingActionResult), updatedFetchers ? { - fetchers: new Map(state.fetchers) - } : {}), { - flushSync - }); - return { - shortCircuited: true - }; - } - // If this is an uninterrupted revalidation, we remain in our current idle - // state. If not, we need to switch to our loading state and load data, - // preserving any new action data or existing action data (in the case of - // a revalidation interrupting an actionReload) - // If we have partialHydration enabled, then don't update the state for the - // initial data load since it's not a "navigation" - if (!isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration)) { - revalidatingFetchers.forEach(rf => { - let fetcher = state.fetchers.get(rf.key); - let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined); - state.fetchers.set(rf.key, revalidatingFetcher); - }); - let actionData; - if (pendingActionResult && !isErrorResult(pendingActionResult[1])) { - // This is cast to `any` currently because `RouteData`uses any and it - // would be a breaking change to use any. - // TODO: v7 - change `RouteData` to use `unknown` instead of `any` - actionData = { - [pendingActionResult[0]]: pendingActionResult[1].data - }; - } else if (state.actionData) { - if (Object.keys(state.actionData).length === 0) { - actionData = null; - } else { - actionData = state.actionData; - } - } - updateState(_extends({ - navigation: loadingNavigation - }, actionData !== undefined ? { - actionData - } : {}, revalidatingFetchers.length > 0 ? { - fetchers: new Map(state.fetchers) - } : {}), { - flushSync - }); - } - revalidatingFetchers.forEach(rf => { - if (fetchControllers.has(rf.key)) { - abortFetcher(rf.key); - } - if (rf.controller) { - // Fetchers use an independent AbortController so that aborting a fetcher - // (via deleteFetcher) does not abort the triggering navigation that - // triggered the revalidation - fetchControllers.set(rf.key, rf.controller); - } - }); - // Proxy navigation abort through to revalidation fetchers - let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key)); - if (pendingNavigationController) { - pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations); - } - let { - loaderResults, - fetcherResults - } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, request); - if (request.signal.aborted) { - return { - shortCircuited: true - }; - } - // Clean up _after_ loaders have completed. Don't clean up if we short - // circuited because fetchControllers would have been aborted and - // reassigned to new controllers for the next navigation - if (pendingNavigationController) { - pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations); - } - revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key)); - // If any loaders returned a redirect Response, start a new REPLACE navigation - let redirect = findRedirect([...loaderResults, ...fetcherResults]); - if (redirect) { - if (redirect.idx >= matchesToLoad.length) { - // If this redirect came from a fetcher make sure we mark it in - // fetchRedirectIds so it doesn't get revalidated on the next set of - // loader executions - let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key; - fetchRedirectIds.add(fetcherKey); - } - await startRedirectNavigation(request, redirect.result, { - replace - }); - return { - shortCircuited: true - }; - } - // Process and commit output from loaders - let { - loaderData, - errors - } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds); - // Wire up subscribers to update loaderData as promises settle - activeDeferreds.forEach((deferredData, routeId) => { - deferredData.subscribe(aborted => { - // Note: No need to updateState here since the TrackedPromise on - // loaderData is stable across resolve/reject - // Remove this instance if we were aborted or if promises have settled - if (aborted || deferredData.done) { - activeDeferreds.delete(routeId); - } - }); - }); - // During partial hydration, preserve SSR errors for routes that don't re-run - if (future.v7_partialHydration && initialHydration && state.errors) { - Object.entries(state.errors).filter(_ref2 => { - let [id] = _ref2; - return !matchesToLoad.some(m => m.route.id === id); - }).forEach(_ref3 => { - let [routeId, error] = _ref3; - errors = Object.assign(errors || {}, { - [routeId]: error - }); - }); - } - let updatedFetchers = markFetchRedirectsDone(); - let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId); - let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0; - return _extends({ - loaderData, - errors - }, shouldUpdateFetchers ? { - fetchers: new Map(state.fetchers) - } : {}); - } - // Trigger a fetcher load/submit for the given fetcher key - function fetch(key, routeId, href, opts) { - if (isServer) { - throw new Error("router.fetch() was called during the server render, but it shouldn't be. " + "You are likely calling a useFetcher() method in the body of your component. " + "Try moving it to a useEffect or a callback."); - } - if (fetchControllers.has(key)) abortFetcher(key); - let flushSync = (opts && opts.unstable_flushSync) === true; - let routesToUse = inFlightDataRoutes || dataRoutes; - let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, future.v7_relativeSplatPath, routeId, opts == null ? void 0 : opts.relative); - let matches = matchRoutes(routesToUse, normalizedPath, basename); - if (!matches) { - setFetcherError(key, routeId, getInternalRouterError(404, { - pathname: normalizedPath - }), { - flushSync - }); - return; - } - let { - path, - submission, - error - } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts); - if (error) { - setFetcherError(key, routeId, error, { - flushSync - }); - return; - } - let match = getTargetMatch(matches, path); - pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; - if (submission && isMutationMethod(submission.formMethod)) { - handleFetcherAction(key, routeId, path, match, matches, flushSync, submission); - return; - } - // Store off the match so we can call it's shouldRevalidate on subsequent - // revalidations - fetchLoadMatches.set(key, { - routeId, - path - }); - handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission); - } - // Call the action for the matched fetcher.submit(), and then handle redirects, - // errors, and revalidation - async function handleFetcherAction(key, routeId, path, match, requestMatches, flushSync, submission) { - interruptActiveLoads(); - fetchLoadMatches.delete(key); - if (!match.route.action && !match.route.lazy) { - let error = getInternalRouterError(405, { - method: submission.formMethod, - pathname: path, - routeId: routeId - }); - setFetcherError(key, routeId, error, { - flushSync - }); - return; - } - // Put this fetcher into it's submitting state - let existingFetcher = state.fetchers.get(key); - updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), { - flushSync - }); - // Call the action for the fetcher - let abortController = new AbortController(); - let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission); - fetchControllers.set(key, abortController); - let originatingLoadId = incrementingLoadId; - let actionResults = await callDataStrategy("action", fetchRequest, [match], requestMatches); - let actionResult = actionResults[0]; - if (fetchRequest.signal.aborted) { - // We can delete this so long as we weren't aborted by our own fetcher - // re-submit which would have put _new_ controller is in fetchControllers - if (fetchControllers.get(key) === abortController) { - fetchControllers.delete(key); - } - return; - } - // When using v7_fetcherPersist, we don't want errors bubbling up to the UI - // or redirects processed for unmounted fetchers so we just revert them to - // idle - if (future.v7_fetcherPersist && deletedFetchers.has(key)) { - if (isRedirectResult(actionResult) || isErrorResult(actionResult)) { - updateFetcherState(key, getDoneFetcher(undefined)); - return; - } - // Let SuccessResult's fall through for revalidation - } else { - if (isRedirectResult(actionResult)) { - fetchControllers.delete(key); - if (pendingNavigationLoadId > originatingLoadId) { - // A new navigation was kicked off after our action started, so that - // should take precedence over this redirect navigation. We already - // set isRevalidationRequired so all loaders for the new route should - // fire unless opted out via shouldRevalidate - updateFetcherState(key, getDoneFetcher(undefined)); - return; - } else { - fetchRedirectIds.add(key); - updateFetcherState(key, getLoadingFetcher(submission)); - return startRedirectNavigation(fetchRequest, actionResult, { - fetcherSubmission: submission - }); - } - } - // Process any non-redirect errors thrown - if (isErrorResult(actionResult)) { - setFetcherError(key, routeId, actionResult.error); - return; - } - } - if (isDeferredResult(actionResult)) { - throw getInternalRouterError(400, { - type: "defer-action" - }); - } - // Start the data load for current matches, or the next location if we're - // in the middle of a navigation - let nextLocation = state.navigation.location || state.location; - let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal); - let routesToUse = inFlightDataRoutes || dataRoutes; - let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches; - invariant(matches, "Didn't find any matches after fetcher action"); - let loadId = ++incrementingLoadId; - fetchReloadIds.set(key, loadId); - let loadFetcher = getLoadingFetcher(submission, actionResult.data); - state.fetchers.set(key, loadFetcher); - let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, false, future.unstable_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, [match.route.id, actionResult]); - // Put all revalidating fetchers into the loading state, except for the - // current fetcher which we want to keep in it's current loading state which - // contains it's action submission info + action data - revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => { - let staleKey = rf.key; - let existingFetcher = state.fetchers.get(staleKey); - let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined); - state.fetchers.set(staleKey, revalidatingFetcher); - if (fetchControllers.has(staleKey)) { - abortFetcher(staleKey); - } - if (rf.controller) { - fetchControllers.set(staleKey, rf.controller); - } - }); - updateState({ - fetchers: new Map(state.fetchers) - }); - let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key)); - abortController.signal.addEventListener("abort", abortPendingFetchRevalidations); - let { - loaderResults, - fetcherResults - } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, revalidationRequest); - if (abortController.signal.aborted) { - return; - } - abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations); - fetchReloadIds.delete(key); - fetchControllers.delete(key); - revalidatingFetchers.forEach(r => fetchControllers.delete(r.key)); - let redirect = findRedirect([...loaderResults, ...fetcherResults]); - if (redirect) { - if (redirect.idx >= matchesToLoad.length) { - // If this redirect came from a fetcher make sure we mark it in - // fetchRedirectIds so it doesn't get revalidated on the next set of - // loader executions - let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key; - fetchRedirectIds.add(fetcherKey); - } - return startRedirectNavigation(revalidationRequest, redirect.result); - } - // Process and commit output from loaders - let { - loaderData, - errors - } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds); - // Since we let revalidations complete even if the submitting fetcher was - // deleted, only put it back to idle if it hasn't been deleted - if (state.fetchers.has(key)) { - let doneFetcher = getDoneFetcher(actionResult.data); - state.fetchers.set(key, doneFetcher); - } - abortStaleFetchLoads(loadId); - // If we are currently in a navigation loading state and this fetcher is - // more recent than the navigation, we want the newer data so abort the - // navigation and complete it with the fetcher data - if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) { - invariant(pendingAction, "Expected pending action"); - pendingNavigationController && pendingNavigationController.abort(); - completeNavigation(state.navigation.location, { - matches, - loaderData, - errors, - fetchers: new Map(state.fetchers) - }); - } else { - // otherwise just update with the fetcher data, preserving any existing - // loaderData for loaders that did not need to reload. We have to - // manually merge here since we aren't going through completeNavigation - updateState({ - errors, - loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors), - fetchers: new Map(state.fetchers) - }); - isRevalidationRequired = false; - } - } - // Call the matched loader for fetcher.load(), handling redirects, errors, etc. - async function handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission) { - let existingFetcher = state.fetchers.get(key); - updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined), { - flushSync - }); - // Call the loader for this fetcher route match - let abortController = new AbortController(); - let fetchRequest = createClientSideRequest(init.history, path, abortController.signal); - fetchControllers.set(key, abortController); - let originatingLoadId = incrementingLoadId; - let results = await callDataStrategy("loader", fetchRequest, [match], matches); - let result = results[0]; - // Deferred isn't supported for fetcher loads, await everything and treat it - // as a normal load. resolveDeferredData will return undefined if this - // fetcher gets aborted, so we just leave result untouched and short circuit - // below if that happens - if (isDeferredResult(result)) { - result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result; - } - // We can delete this so long as we weren't aborted by our our own fetcher - // re-load which would have put _new_ controller is in fetchControllers - if (fetchControllers.get(key) === abortController) { - fetchControllers.delete(key); - } - if (fetchRequest.signal.aborted) { - return; - } - // We don't want errors bubbling up or redirects followed for unmounted - // fetchers, so short circuit here if it was removed from the UI - if (deletedFetchers.has(key)) { - updateFetcherState(key, getDoneFetcher(undefined)); - return; - } - // If the loader threw a redirect Response, start a new REPLACE navigation - if (isRedirectResult(result)) { - if (pendingNavigationLoadId > originatingLoadId) { - // A new navigation was kicked off after our loader started, so that - // should take precedence over this redirect navigation - updateFetcherState(key, getDoneFetcher(undefined)); - return; - } else { - fetchRedirectIds.add(key); - await startRedirectNavigation(fetchRequest, result); - return; - } - } - // Process any non-redirect errors thrown - if (isErrorResult(result)) { - setFetcherError(key, routeId, result.error); - return; - } - invariant(!isDeferredResult(result), "Unhandled fetcher deferred data"); - // Put the fetcher back into an idle state - updateFetcherState(key, getDoneFetcher(result.data)); - } - /** - * Utility function to handle redirects returned from an action or loader. - * Normally, a redirect "replaces" the navigation that triggered it. So, for - * example: - * - * - user is on /a - * - user clicks a link to /b - * - loader for /b redirects to /c - * - * In a non-JS app the browser would track the in-flight navigation to /b and - * then replace it with /c when it encountered the redirect response. In - * the end it would only ever update the URL bar with /c. - * - * In client-side routing using pushState/replaceState, we aim to emulate - * this behavior and we also do not update history until the end of the - * navigation (including processed redirects). This means that we never - * actually touch history until we've processed redirects, so we just use - * the history action from the original navigation (PUSH or REPLACE). - */ - async function startRedirectNavigation(request, redirect, _temp2) { - let { - submission, - fetcherSubmission, - replace - } = _temp2 === void 0 ? {} : _temp2; - if (redirect.response.headers.has("X-Remix-Revalidate")) { - isRevalidationRequired = true; - } - let location = redirect.response.headers.get("Location"); - invariant(location, "Expected a Location header on the redirect Response"); - location = normalizeRedirectLocation(location, new URL(request.url), basename); - let redirectLocation = createLocation(state.location, location, { - _isRedirect: true - }); - if (isBrowser) { - let isDocumentReload = false; - if (redirect.response.headers.has("X-Remix-Reload-Document")) { - // Hard reload if the response contained X-Remix-Reload-Document - isDocumentReload = true; - } else if (ABSOLUTE_URL_REGEX.test(location)) { - const url = init.history.createURL(location); - isDocumentReload = - // Hard reload if it's an absolute URL to a new origin - url.origin !== routerWindow.location.origin || - // Hard reload if it's an absolute URL that does not match our basename - stripBasename(url.pathname, basename) == null; - } - if (isDocumentReload) { - if (replace) { - routerWindow.location.replace(location); - } else { - routerWindow.location.assign(location); - } - return; - } - } - // There's no need to abort on redirects, since we don't detect the - // redirect until the action/loaders have settled - pendingNavigationController = null; - let redirectHistoryAction = replace === true ? Action.Replace : Action.Push; - // Use the incoming submission if provided, fallback on the active one in - // state.navigation - let { - formMethod, - formAction, - formEncType - } = state.navigation; - if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) { - submission = getSubmissionFromNavigation(state.navigation); - } - // If this was a 307/308 submission we want to preserve the HTTP method and - // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the - // redirected location - let activeSubmission = submission || fetcherSubmission; - if (redirectPreserveMethodStatusCodes.has(redirect.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) { - await startNavigation(redirectHistoryAction, redirectLocation, { - submission: _extends({}, activeSubmission, { - formAction: location - }), - // Preserve this flag across redirects - preventScrollReset: pendingPreventScrollReset - }); - } else { - // If we have a navigation submission, we will preserve it through the - // redirect navigation - let overrideNavigation = getLoadingNavigation(redirectLocation, submission); - await startNavigation(redirectHistoryAction, redirectLocation, { - overrideNavigation, - // Send fetcher submissions through for shouldRevalidate - fetcherSubmission, - // Preserve this flag across redirects - preventScrollReset: pendingPreventScrollReset - }); - } - } - // Utility wrapper for calling dataStrategy client-side without having to - // pass around the manifest, mapRouteProperties, etc. - async function callDataStrategy(type, request, matchesToLoad, matches) { - try { - let results = await callDataStrategyImpl(dataStrategyImpl, type, request, matchesToLoad, matches, manifest, mapRouteProperties); - return await Promise.all(results.map((result, i) => { - if (isRedirectHandlerResult(result)) { - let response = result.result; - return { - type: ResultType.redirect, - response: normalizeRelativeRoutingRedirectResponse(response, request, matchesToLoad[i].route.id, matches, basename, future.v7_relativeSplatPath) - }; - } - return convertHandlerResultToDataResult(result); - })); - } catch (e) { - // If the outer dataStrategy method throws, just return the error for all - // matches - and it'll naturally bubble to the root - return matchesToLoad.map(() => ({ - type: ResultType.error, - error: e - })); - } - } - async function callLoadersAndMaybeResolveData(currentMatches, matches, matchesToLoad, fetchersToLoad, request) { - let [loaderResults, ...fetcherResults] = await Promise.all([matchesToLoad.length ? callDataStrategy("loader", request, matchesToLoad, matches) : [], ...fetchersToLoad.map(f => { - if (f.matches && f.match && f.controller) { - let fetcherRequest = createClientSideRequest(init.history, f.path, f.controller.signal); - return callDataStrategy("loader", fetcherRequest, [f.match], f.matches).then(r => r[0]); - } else { - return Promise.resolve({ - type: ResultType.error, - error: getInternalRouterError(404, { - pathname: f.path - }) - }); - } - })]); - await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, loaderResults.map(() => request.signal), false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(f => f.match), fetcherResults, fetchersToLoad.map(f => f.controller ? f.controller.signal : null), true)]); - return { - loaderResults, - fetcherResults - }; - } - function interruptActiveLoads() { - // Every interruption triggers a revalidation - isRevalidationRequired = true; - // Cancel pending route-level deferreds and mark cancelled routes for - // revalidation - cancelledDeferredRoutes.push(...cancelActiveDeferreds()); - // Abort in-flight fetcher loads - fetchLoadMatches.forEach((_, key) => { - if (fetchControllers.has(key)) { - cancelledFetcherLoads.push(key); - abortFetcher(key); - } - }); - } - function updateFetcherState(key, fetcher, opts) { - if (opts === void 0) { - opts = {}; - } - state.fetchers.set(key, fetcher); - updateState({ - fetchers: new Map(state.fetchers) - }, { - flushSync: (opts && opts.flushSync) === true - }); - } - function setFetcherError(key, routeId, error, opts) { - if (opts === void 0) { - opts = {}; - } - let boundaryMatch = findNearestBoundary(state.matches, routeId); - deleteFetcher(key); - updateState({ - errors: { - [boundaryMatch.route.id]: error - }, - fetchers: new Map(state.fetchers) - }, { - flushSync: (opts && opts.flushSync) === true - }); - } - function getFetcher(key) { - if (future.v7_fetcherPersist) { - activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1); - // If this fetcher was previously marked for deletion, unmark it since we - // have a new instance - if (deletedFetchers.has(key)) { - deletedFetchers.delete(key); - } - } - return state.fetchers.get(key) || IDLE_FETCHER; - } - function deleteFetcher(key) { - let fetcher = state.fetchers.get(key); - // Don't abort the controller if this is a deletion of a fetcher.submit() - // in it's loading phase since - we don't want to abort the corresponding - // revalidation and want them to complete and land - if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) { - abortFetcher(key); - } - fetchLoadMatches.delete(key); - fetchReloadIds.delete(key); - fetchRedirectIds.delete(key); - deletedFetchers.delete(key); - state.fetchers.delete(key); - } - function deleteFetcherAndUpdateState(key) { - if (future.v7_fetcherPersist) { - let count = (activeFetchers.get(key) || 0) - 1; - if (count <= 0) { - activeFetchers.delete(key); - deletedFetchers.add(key); - } else { - activeFetchers.set(key, count); - } - } else { - deleteFetcher(key); - } - updateState({ - fetchers: new Map(state.fetchers) - }); - } - function abortFetcher(key) { - let controller = fetchControllers.get(key); - invariant(controller, "Expected fetch controller: " + key); - controller.abort(); - fetchControllers.delete(key); - } - function markFetchersDone(keys) { - for (let key of keys) { - let fetcher = getFetcher(key); - let doneFetcher = getDoneFetcher(fetcher.data); - state.fetchers.set(key, doneFetcher); - } - } - function markFetchRedirectsDone() { - let doneKeys = []; - let updatedFetchers = false; - for (let key of fetchRedirectIds) { - let fetcher = state.fetchers.get(key); - invariant(fetcher, "Expected fetcher: " + key); - if (fetcher.state === "loading") { - fetchRedirectIds.delete(key); - doneKeys.push(key); - updatedFetchers = true; - } - } - markFetchersDone(doneKeys); - return updatedFetchers; - } - function abortStaleFetchLoads(landedId) { - let yeetedKeys = []; - for (let [key, id] of fetchReloadIds) { - if (id < landedId) { - let fetcher = state.fetchers.get(key); - invariant(fetcher, "Expected fetcher: " + key); - if (fetcher.state === "loading") { - abortFetcher(key); - fetchReloadIds.delete(key); - yeetedKeys.push(key); - } - } - } - markFetchersDone(yeetedKeys); - return yeetedKeys.length > 0; - } - function getBlocker(key, fn) { - let blocker = state.blockers.get(key) || IDLE_BLOCKER; - if (blockerFunctions.get(key) !== fn) { - blockerFunctions.set(key, fn); - } - return blocker; - } - function deleteBlocker(key) { - state.blockers.delete(key); - blockerFunctions.delete(key); - } - // Utility function to update blockers, ensuring valid state transitions - function updateBlocker(key, newBlocker) { - let blocker = state.blockers.get(key) || IDLE_BLOCKER; - // Poor mans state machine :) - // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM - invariant(blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked", "Invalid blocker state transition: " + blocker.state + " -> " + newBlocker.state); - let blockers = new Map(state.blockers); - blockers.set(key, newBlocker); - updateState({ - blockers - }); - } - function shouldBlockNavigation(_ref4) { - let { - currentLocation, - nextLocation, - historyAction - } = _ref4; - if (blockerFunctions.size === 0) { - return; - } - // We ony support a single active blocker at the moment since we don't have - // any compelling use cases for multi-blocker yet - if (blockerFunctions.size > 1) { - warning(false, "A router only supports one blocker at a time"); - } - let entries = Array.from(blockerFunctions.entries()); - let [blockerKey, blockerFunction] = entries[entries.length - 1]; - let blocker = state.blockers.get(blockerKey); - if (blocker && blocker.state === "proceeding") { - // If the blocker is currently proceeding, we don't need to re-check - // it and can let this navigation continue - return; - } - // At this point, we know we're unblocked/blocked so we need to check the - // user-provided blocker function - if (blockerFunction({ - currentLocation, - nextLocation, - historyAction - })) { - return blockerKey; - } - } - function cancelActiveDeferreds(predicate) { - let cancelledRouteIds = []; - activeDeferreds.forEach((dfd, routeId) => { - if (!predicate || predicate(routeId)) { - // Cancel the deferred - but do not remove from activeDeferreds here - - // we rely on the subscribers to do that so our tests can assert proper - // cleanup via _internalActiveDeferreds - dfd.cancel(); - cancelledRouteIds.push(routeId); - activeDeferreds.delete(routeId); - } - }); - return cancelledRouteIds; - } - // Opt in to capturing and reporting scroll positions during navigations, - // used by the component - function enableScrollRestoration(positions, getPosition, getKey) { - savedScrollPositions = positions; - getScrollPosition = getPosition; - getScrollRestorationKey = getKey || null; - // Perform initial hydration scroll restoration, since we miss the boat on - // the initial updateState() because we've not yet rendered - // and therefore have no savedScrollPositions available - if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) { - initialScrollRestored = true; - let y = getSavedScrollPosition(state.location, state.matches); - if (y != null) { - updateState({ - restoreScrollPosition: y - }); - } - } - return () => { - savedScrollPositions = null; - getScrollPosition = null; - getScrollRestorationKey = null; - }; - } - function getScrollKey(location, matches) { - if (getScrollRestorationKey) { - let key = getScrollRestorationKey(location, matches.map(m => convertRouteMatchToUiMatch(m, state.loaderData))); - return key || location.key; - } - return location.key; - } - function saveScrollPosition(location, matches) { - if (savedScrollPositions && getScrollPosition) { - let key = getScrollKey(location, matches); - savedScrollPositions[key] = getScrollPosition(); - } - } - function getSavedScrollPosition(location, matches) { - if (savedScrollPositions) { - let key = getScrollKey(location, matches); - let y = savedScrollPositions[key]; - if (typeof y === "number") { - return y; - } - } - return null; - } - function _internalSetRoutes(newRoutes) { - manifest = {}; - inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest); - } - router = { - get basename() { - return basename; - }, - get future() { - return future; - }, - get state() { - return state; - }, - get routes() { - return dataRoutes; - }, - get window() { - return routerWindow; - }, - initialize, - subscribe, - enableScrollRestoration, - navigate, - fetch, - revalidate, - // Passthrough to history-aware createHref used by useHref so we get proper - // hash-aware URLs in DOM paths - createHref: to => init.history.createHref(to), - encodeLocation: to => init.history.encodeLocation(to), - getFetcher, - deleteFetcher: deleteFetcherAndUpdateState, - dispose, - getBlocker, - deleteBlocker, - _internalFetchControllers: fetchControllers, - _internalActiveDeferreds: activeDeferreds, - // TODO: Remove setRoutes, it's temporary to avoid dealing with - // updating the tree while validating the update algorithm. - _internalSetRoutes - }; - return router; -} -//#endregion -//////////////////////////////////////////////////////////////////////////////// -//#region createStaticHandler -//////////////////////////////////////////////////////////////////////////////// -const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred"); -function createStaticHandler(routes, opts) { - invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler"); - let manifest = {}; - let basename = (opts ? opts.basename : null) || "/"; - let mapRouteProperties; - if (opts != null && opts.mapRouteProperties) { - mapRouteProperties = opts.mapRouteProperties; - } else if (opts != null && opts.detectErrorBoundary) { - // If they are still using the deprecated version, wrap it with the new API - let detectErrorBoundary = opts.detectErrorBoundary; - mapRouteProperties = route => ({ - hasErrorBoundary: detectErrorBoundary(route) - }); - } else { - mapRouteProperties = defaultMapRouteProperties; - } - // Config driven behavior flags - let future = _extends({ - v7_relativeSplatPath: false, - v7_throwAbortReason: false - }, opts ? opts.future : null); - let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest); - /** - * The query() method is intended for document requests, in which we want to - * call an optional action and potentially multiple loaders for all nested - * routes. It returns a StaticHandlerContext object, which is very similar - * to the router state (location, loaderData, actionData, errors, etc.) and - * also adds SSR-specific information such as the statusCode and headers - * from action/loaders Responses. - * - * It _should_ never throw and should report all errors through the - * returned context.errors object, properly associating errors to their error - * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be - * used to emulate React error boundaries during SSr by performing a second - * pass only down to the boundaryId. - * - * The one exception where we do not return a StaticHandlerContext is when a - * redirect response is returned or thrown from any action/loader. We - * propagate that out and return the raw Response so the HTTP server can - * return it directly. - * - * - `opts.requestContext` is an optional server context that will be passed - * to actions/loaders in the `context` parameter - * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent - * the bubbling of errors which allows single-fetch-type implementations - * where the client will handle the bubbling and we may need to return data - * for the handling route - */ - async function query(request, _temp3) { - let { - requestContext, - skipLoaderErrorBubbling, - unstable_dataStrategy - } = _temp3 === void 0 ? {} : _temp3; - let url = new URL(request.url); - let method = request.method; - let location = createLocation("", createPath(url), null, "default"); - let matches = matchRoutes(dataRoutes, location, basename); - // SSR supports HEAD requests while SPA doesn't - if (!isValidMethod(method) && method !== "HEAD") { - let error = getInternalRouterError(405, { - method - }); - let { - matches: methodNotAllowedMatches, - route - } = getShortCircuitMatches(dataRoutes); - return { - basename, - location, - matches: methodNotAllowedMatches, - loaderData: {}, - actionData: null, - errors: { - [route.id]: error - }, - statusCode: error.status, - loaderHeaders: {}, - actionHeaders: {}, - activeDeferreds: null - }; - } else if (!matches) { - let error = getInternalRouterError(404, { - pathname: location.pathname - }); - let { - matches: notFoundMatches, - route - } = getShortCircuitMatches(dataRoutes); - return { - basename, - location, - matches: notFoundMatches, - loaderData: {}, - actionData: null, - errors: { - [route.id]: error - }, - statusCode: error.status, - loaderHeaders: {}, - actionHeaders: {}, - activeDeferreds: null - }; - } - let result = await queryImpl(request, location, matches, requestContext, unstable_dataStrategy || null, skipLoaderErrorBubbling === true, null); - if (isResponse(result)) { - return result; - } - // When returning StaticHandlerContext, we patch back in the location here - // since we need it for React Context. But this helps keep our submit and - // loadRouteData operating on a Request instead of a Location - return _extends({ - location, - basename - }, result); - } - /** - * The queryRoute() method is intended for targeted route requests, either - * for fetch ?_data requests or resource route requests. In this case, we - * are only ever calling a single action or loader, and we are returning the - * returned value directly. In most cases, this will be a Response returned - * from the action/loader, but it may be a primitive or other value as well - - * and in such cases the calling context should handle that accordingly. - * - * We do respect the throw/return differentiation, so if an action/loader - * throws, then this method will throw the value. This is important so we - * can do proper boundary identification in Remix where a thrown Response - * must go to the Catch Boundary but a returned Response is happy-path. - * - * One thing to note is that any Router-initiated Errors that make sense - * to associate with a status code will be thrown as an ErrorResponse - * instance which include the raw Error, such that the calling context can - * serialize the error as they see fit while including the proper response - * code. Examples here are 404 and 405 errors that occur prior to reaching - * any user-defined loaders. - * - * - `opts.routeId` allows you to specify the specific route handler to call. - * If not provided the handler will determine the proper route by matching - * against `request.url` - * - `opts.requestContext` is an optional server context that will be passed - * to actions/loaders in the `context` parameter - */ - async function queryRoute(request, _temp4) { - let { - routeId, - requestContext, - unstable_dataStrategy - } = _temp4 === void 0 ? {} : _temp4; - let url = new URL(request.url); - let method = request.method; - let location = createLocation("", createPath(url), null, "default"); - let matches = matchRoutes(dataRoutes, location, basename); - // SSR supports HEAD requests while SPA doesn't - if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") { - throw getInternalRouterError(405, { - method - }); - } else if (!matches) { - throw getInternalRouterError(404, { - pathname: location.pathname - }); - } - let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location); - if (routeId && !match) { - throw getInternalRouterError(403, { - pathname: location.pathname, - routeId - }); - } else if (!match) { - // This should never hit I don't think? - throw getInternalRouterError(404, { - pathname: location.pathname - }); - } - let result = await queryImpl(request, location, matches, requestContext, unstable_dataStrategy || null, false, match); - if (isResponse(result)) { - return result; - } - let error = result.errors ? Object.values(result.errors)[0] : undefined; - if (error !== undefined) { - // If we got back result.errors, that means the loader/action threw - // _something_ that wasn't a Response, but it's not guaranteed/required - // to be an `instanceof Error` either, so we have to use throw here to - // preserve the "error" state outside of queryImpl. - throw error; - } - // Pick off the right state value to return - if (result.actionData) { - return Object.values(result.actionData)[0]; - } - if (result.loaderData) { - var _result$activeDeferre; - let data = Object.values(result.loaderData)[0]; - if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) { - data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id]; - } - return data; - } - return undefined; - } - async function queryImpl(request, location, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch) { - invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal"); - try { - if (isMutationMethod(request.method.toLowerCase())) { - let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch != null); - return result; - } - let result = await loadRouteData(request, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch); - return isResponse(result) ? result : _extends({}, result, { - actionData: null, - actionHeaders: {} - }); - } catch (e) { - // If the user threw/returned a Response in callLoaderOrAction for a - // `queryRoute` call, we throw the `HandlerResult` to bail out early - // and then return or throw the raw Response here accordingly - if (isHandlerResult(e) && isResponse(e.result)) { - if (e.type === ResultType.error) { - throw e.result; - } - return e.result; - } - // Redirects are always returned since they don't propagate to catch - // boundaries - if (isRedirectResponse(e)) { - return e; - } - throw e; - } - } - async function submit(request, matches, actionMatch, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, isRouteRequest) { - let result; - if (!actionMatch.route.action && !actionMatch.route.lazy) { - let error = getInternalRouterError(405, { - method: request.method, - pathname: new URL(request.url).pathname, - routeId: actionMatch.route.id - }); - if (isRouteRequest) { - throw error; - } - result = { - type: ResultType.error, - error - }; - } else { - let results = await callDataStrategy("action", request, [actionMatch], matches, isRouteRequest, requestContext, unstable_dataStrategy); - result = results[0]; - if (request.signal.aborted) { - throwStaticHandlerAbortedError(request, isRouteRequest, future); - } - } - if (isRedirectResult(result)) { - // Uhhhh - this should never happen, we should always throw these from - // callLoaderOrAction, but the type narrowing here keeps TS happy and we - // can get back on the "throw all redirect responses" train here should - // this ever happen :/ - throw new Response(null, { - status: result.response.status, - headers: { - Location: result.response.headers.get("Location") - } - }); - } - if (isDeferredResult(result)) { - let error = getInternalRouterError(400, { - type: "defer-action" - }); - if (isRouteRequest) { - throw error; - } - result = { - type: ResultType.error, - error - }; - } - if (isRouteRequest) { - // Note: This should only be non-Response values if we get here, since - // isRouteRequest should throw any Response received in callLoaderOrAction - if (isErrorResult(result)) { - throw result.error; - } - return { - matches: [actionMatch], - loaderData: {}, - actionData: { - [actionMatch.route.id]: result.data - }, - errors: null, - // Note: statusCode + headers are unused here since queryRoute will - // return the raw Response or value - statusCode: 200, - loaderHeaders: {}, - actionHeaders: {}, - activeDeferreds: null - }; - } - // Create a GET request for the loaders - let loaderRequest = new Request(request.url, { - headers: request.headers, - redirect: request.redirect, - signal: request.signal - }); - if (isErrorResult(result)) { - // Store off the pending error - we use it to determine which loaders - // to call and will commit it when we complete the navigation - let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id); - let context = await loadRouteData(loaderRequest, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, null, [boundaryMatch.route.id, result]); - // action status codes take precedence over loader status codes - return _extends({}, context, { - statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500, - actionData: null, - actionHeaders: _extends({}, result.headers ? { - [actionMatch.route.id]: result.headers - } : {}) - }); - } - let context = await loadRouteData(loaderRequest, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, null); - return _extends({}, context, { - actionData: { - [actionMatch.route.id]: result.data - } - }, result.statusCode ? { - statusCode: result.statusCode - } : {}, { - actionHeaders: result.headers ? { - [actionMatch.route.id]: result.headers - } : {} - }); - } - async function loadRouteData(request, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch, pendingActionResult) { - let isRouteRequest = routeMatch != null; - // Short circuit if we have no loaders to run (queryRoute()) - if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) { - throw getInternalRouterError(400, { - method: request.method, - pathname: new URL(request.url).pathname, - routeId: routeMatch == null ? void 0 : routeMatch.route.id - }); - } - let requestMatches = routeMatch ? [routeMatch] : pendingActionResult && isErrorResult(pendingActionResult[1]) ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) : matches; - let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy); - // Short circuit if we have no loaders to run (query()) - if (matchesToLoad.length === 0) { - return { - matches, - // Add a null for all matched routes for proper revalidation on the client - loaderData: matches.reduce((acc, m) => Object.assign(acc, { - [m.route.id]: null - }), {}), - errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { - [pendingActionResult[0]]: pendingActionResult[1].error - } : null, - statusCode: 200, - loaderHeaders: {}, - activeDeferreds: null - }; - } - let results = await callDataStrategy("loader", request, matchesToLoad, matches, isRouteRequest, requestContext, unstable_dataStrategy); - if (request.signal.aborted) { - throwStaticHandlerAbortedError(request, isRouteRequest, future); - } - // Process and commit output from loaders - let activeDeferreds = new Map(); - let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling); - // Add a null for any non-loader matches for proper revalidation on the client - let executedLoaders = new Set(matchesToLoad.map(match => match.route.id)); - matches.forEach(match => { - if (!executedLoaders.has(match.route.id)) { - context.loaderData[match.route.id] = null; - } - }); - return _extends({}, context, { - matches, - activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null - }); - } - // Utility wrapper for calling dataStrategy server-side without having to - // pass around the manifest, mapRouteProperties, etc. - async function callDataStrategy(type, request, matchesToLoad, matches, isRouteRequest, requestContext, unstable_dataStrategy) { - let results = await callDataStrategyImpl(unstable_dataStrategy || defaultDataStrategy, type, request, matchesToLoad, matches, manifest, mapRouteProperties, requestContext); - return await Promise.all(results.map((result, i) => { - if (isRedirectHandlerResult(result)) { - let response = result.result; - // Throw redirects and let the server handle them with an HTTP redirect - throw normalizeRelativeRoutingRedirectResponse(response, request, matchesToLoad[i].route.id, matches, basename, future.v7_relativeSplatPath); - } - if (isResponse(result.result) && isRouteRequest) { - // For SSR single-route requests, we want to hand Responses back - // directly without unwrapping - throw result; - } - return convertHandlerResultToDataResult(result); - })); - } - return { - dataRoutes, - query, - queryRoute - }; -} -//#endregion -//////////////////////////////////////////////////////////////////////////////// -//#region Helpers -//////////////////////////////////////////////////////////////////////////////// -/** - * Given an existing StaticHandlerContext and an error thrown at render time, - * provide an updated StaticHandlerContext suitable for a second SSR render - */ -function getStaticContextFromError(routes, context, error) { - let newContext = _extends({}, context, { - statusCode: isRouteErrorResponse(error) ? error.status : 500, - errors: { - [context._deepestRenderedBoundaryId || routes[0].id]: error - } - }); - return newContext; -} -function throwStaticHandlerAbortedError(request, isRouteRequest, future) { - if (future.v7_throwAbortReason && request.signal.reason !== undefined) { - throw request.signal.reason; - } - let method = isRouteRequest ? "queryRoute" : "query"; - throw new Error(method + "() call aborted: " + request.method + " " + request.url); -} -function isSubmissionNavigation(opts) { - return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== undefined); -} -function normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) { - let contextualMatches; - let activeRouteMatch; - if (fromRouteId) { - // Grab matches up to the calling route so our route-relative logic is - // relative to the correct source route - contextualMatches = []; - for (let match of matches) { - contextualMatches.push(match); - if (match.route.id === fromRouteId) { - activeRouteMatch = match; - break; - } - } - } else { - contextualMatches = matches; - activeRouteMatch = matches[matches.length - 1]; - } - // Resolve the relative path - let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === "path"); - // When `to` is not specified we inherit search/hash from the current - // location, unlike when to="." and we just inherit the path. - // See https://github.com/remix-run/remix/issues/927 - if (to == null) { - path.search = location.search; - path.hash = location.hash; - } - // Add an ?index param for matched index routes if we don't already have one - if ((to == null || to === "" || to === ".") && activeRouteMatch && activeRouteMatch.route.index && !hasNakedIndexQuery(path.search)) { - path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index"; - } - // If we're operating within a basename, prepend it to the pathname. If - // this is a root navigation, then just use the raw basename which allows - // the basename to have full control over the presence of a trailing slash - // on root actions - if (prependBasename && basename !== "/") { - path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]); - } - return createPath(path); -} -// Normalize navigation options by converting formMethod=GET formData objects to -// URLSearchParams so they behave identically to links with query params -function normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) { - // Return location verbatim on non-submission navigations - if (!opts || !isSubmissionNavigation(opts)) { - return { - path - }; - } - if (opts.formMethod && !isValidMethod(opts.formMethod)) { - return { - path, - error: getInternalRouterError(405, { - method: opts.formMethod - }) - }; - } - let getInvalidBodyError = () => ({ - path, - error: getInternalRouterError(400, { - type: "invalid-body" - }) - }); - // Create a Submission on non-GET navigations - let rawFormMethod = opts.formMethod || "get"; - let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase(); - let formAction = stripHashFromPath(path); - if (opts.body !== undefined) { - if (opts.formEncType === "text/plain") { - // text only support POST/PUT/PATCH/DELETE submissions - if (!isMutationMethod(formMethod)) { - return getInvalidBodyError(); - } - let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? - // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data - Array.from(opts.body.entries()).reduce((acc, _ref5) => { - let [name, value] = _ref5; - return "" + acc + name + "=" + value + "\n"; - }, "") : String(opts.body); - return { - path, - submission: { - formMethod, - formAction, - formEncType: opts.formEncType, - formData: undefined, - json: undefined, - text - } - }; - } else if (opts.formEncType === "application/json") { - // json only supports POST/PUT/PATCH/DELETE submissions - if (!isMutationMethod(formMethod)) { - return getInvalidBodyError(); - } - try { - let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body; - return { - path, - submission: { - formMethod, - formAction, - formEncType: opts.formEncType, - formData: undefined, - json, - text: undefined - } - }; - } catch (e) { - return getInvalidBodyError(); - } - } - } - invariant(typeof FormData === "function", "FormData is not available in this environment"); - let searchParams; - let formData; - if (opts.formData) { - searchParams = convertFormDataToSearchParams(opts.formData); - formData = opts.formData; - } else if (opts.body instanceof FormData) { - searchParams = convertFormDataToSearchParams(opts.body); - formData = opts.body; - } else if (opts.body instanceof URLSearchParams) { - searchParams = opts.body; - formData = convertSearchParamsToFormData(searchParams); - } else if (opts.body == null) { - searchParams = new URLSearchParams(); - formData = new FormData(); - } else { - try { - searchParams = new URLSearchParams(opts.body); - formData = convertSearchParamsToFormData(searchParams); - } catch (e) { - return getInvalidBodyError(); - } - } - let submission = { - formMethod, - formAction, - formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded", - formData, - json: undefined, - text: undefined - }; - if (isMutationMethod(submission.formMethod)) { - return { - path, - submission - }; - } - // Flatten submission onto URLSearchParams for GET submissions - let parsedPath = parsePath(path); - // On GET navigation submissions we can drop the ?index param from the - // resulting location since all loaders will run. But fetcher GET submissions - // only run a single loader so we need to preserve any incoming ?index params - if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) { - searchParams.append("index", ""); - } - parsedPath.search = "?" + searchParams; - return { - path: createPath(parsedPath), - submission - }; -} -// Filter out all routes below any caught error as they aren't going to -// render so we don't need to load them -function getLoaderMatchesUntilBoundary(matches, boundaryId) { - let boundaryMatches = matches; - if (boundaryId) { - let index = matches.findIndex(m => m.route.id === boundaryId); - if (index >= 0) { - boundaryMatches = matches.slice(0, index); - } - } - return boundaryMatches; -} -function getMatchesToLoad(history, state, matches, submission, location, isInitialLoad, skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult) { - let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : undefined; - let currentUrl = history.createURL(state.location); - let nextUrl = history.createURL(location); - // Pick navigation matches that are net-new or qualify for revalidation - let boundaryId = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[0] : undefined; - let boundaryMatches = boundaryId ? getLoaderMatchesUntilBoundary(matches, boundaryId) : matches; - // Don't revalidate loaders by default after action 4xx/5xx responses - // when the flag is enabled. They can still opt-into revalidation via - // `shouldRevalidate` via `actionResult` - let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : undefined; - let shouldSkipRevalidation = skipActionErrorRevalidation && actionStatus && actionStatus >= 400; - let navigationMatches = boundaryMatches.filter((match, index) => { - let { - route - } = match; - if (route.lazy) { - // We haven't loaded this route yet so we don't know if it's got a loader! - return true; - } - if (route.loader == null) { - return false; - } - if (isInitialLoad) { - if (typeof route.loader !== "function" || route.loader.hydrate) { - return true; - } - return state.loaderData[route.id] === undefined && ( - // Don't re-run if the loader ran and threw an error - !state.errors || state.errors[route.id] === undefined); - } - // Always call the loader on new route instances and pending defer cancellations - if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) { - return true; - } - // This is the default implementation for when we revalidate. If the route - // provides it's own implementation, then we give them full control but - // provide this value so they can leverage it if needed after they check - // their own specific use cases - let currentRouteMatch = state.matches[index]; - let nextRouteMatch = match; - return shouldRevalidateLoader(match, _extends({ - currentUrl, - currentParams: currentRouteMatch.params, - nextUrl, - nextParams: nextRouteMatch.params - }, submission, { - actionResult, - unstable_actionStatus: actionStatus, - defaultShouldRevalidate: shouldSkipRevalidation ? false : - // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate - isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search || - // Search params affect all loaders - currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch) - })); - }); - // Pick fetcher.loads that need to be revalidated - let revalidatingFetchers = []; - fetchLoadMatches.forEach((f, key) => { - // Don't revalidate: - // - on initial load (shouldn't be any fetchers then anyway) - // - if fetcher won't be present in the subsequent render - // - no longer matches the URL (v7_fetcherPersist=false) - // - was unmounted but persisted due to v7_fetcherPersist=true - if (isInitialLoad || !matches.some(m => m.route.id === f.routeId) || deletedFetchers.has(key)) { - return; - } - let fetcherMatches = matchRoutes(routesToUse, f.path, basename); - // If the fetcher path no longer matches, push it in with null matches so - // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is - // currently only a use-case for Remix HMR where the route tree can change - // at runtime and remove a route previously loaded via a fetcher - if (!fetcherMatches) { - revalidatingFetchers.push({ - key, - routeId: f.routeId, - path: f.path, - matches: null, - match: null, - controller: null - }); - return; - } - // Revalidating fetchers are decoupled from the route matches since they - // load from a static href. They revalidate based on explicit revalidation - // (submission, useRevalidator, or X-Remix-Revalidate) - let fetcher = state.fetchers.get(key); - let fetcherMatch = getTargetMatch(fetcherMatches, f.path); - let shouldRevalidate = false; - if (fetchRedirectIds.has(key)) { - // Never trigger a revalidation of an actively redirecting fetcher - shouldRevalidate = false; - } else if (cancelledFetcherLoads.includes(key)) { - // Always revalidate if the fetcher was cancelled - shouldRevalidate = true; - } else if (fetcher && fetcher.state !== "idle" && fetcher.data === undefined) { - // If the fetcher hasn't ever completed loading yet, then this isn't a - // revalidation, it would just be a brand new load if an explicit - // revalidation is required - shouldRevalidate = isRevalidationRequired; - } else { - // Otherwise fall back on any user-defined shouldRevalidate, defaulting - // to explicit revalidations only - shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({ - currentUrl, - currentParams: state.matches[state.matches.length - 1].params, - nextUrl, - nextParams: matches[matches.length - 1].params - }, submission, { - actionResult, - unstable_actionStatus: actionStatus, - defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired - })); - } - if (shouldRevalidate) { - revalidatingFetchers.push({ - key, - routeId: f.routeId, - path: f.path, - matches: fetcherMatches, - match: fetcherMatch, - controller: new AbortController() - }); - } - }); - return [navigationMatches, revalidatingFetchers]; -} -function isNewLoader(currentLoaderData, currentMatch, match) { - let isNew = - // [a] -> [a, b] - !currentMatch || - // [a, b] -> [a, c] - match.route.id !== currentMatch.route.id; - // Handle the case that we don't have data for a re-used route, potentially - // from a prior error or from a cancelled pending deferred - let isMissingData = currentLoaderData[match.route.id] === undefined; - // Always load if this is a net-new route or we don't yet have data - return isNew || isMissingData; -} -function isNewRouteInstance(currentMatch, match) { - let currentPath = currentMatch.route.path; - return ( - // param change for this match, /users/123 -> /users/456 - currentMatch.pathname !== match.pathname || - // splat param changed, which is not present in match.path - // e.g. /files/images/avatar.jpg -> files/finances.xls - currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"] - ); -} -function shouldRevalidateLoader(loaderMatch, arg) { - if (loaderMatch.route.shouldRevalidate) { - let routeChoice = loaderMatch.route.shouldRevalidate(arg); - if (typeof routeChoice === "boolean") { - return routeChoice; - } - } - return arg.defaultShouldRevalidate; -} -/** - * Execute route.lazy() methods to lazily load route modules (loader, action, - * shouldRevalidate) and update the routeManifest in place which shares objects - * with dataRoutes so those get updated as well. - */ -async function loadLazyRouteModule(route, mapRouteProperties, manifest) { - if (!route.lazy) { - return; - } - let lazyRoute = await route.lazy(); - // If the lazy route function was executed and removed by another parallel - // call then we can return - first lazy() to finish wins because the return - // value of lazy is expected to be static - if (!route.lazy) { - return; - } - let routeToUpdate = manifest[route.id]; - invariant(routeToUpdate, "No route found in manifest"); - // Update the route in place. This should be safe because there's no way - // we could yet be sitting on this route as we can't get there without - // resolving lazy() first. - // - // This is different than the HMR "update" use-case where we may actively be - // on the route being updated. The main concern boils down to "does this - // mutation affect any ongoing navigations or any current state.matches - // values?". If not, it should be safe to update in place. - let routeUpdates = {}; - for (let lazyRouteProperty in lazyRoute) { - let staticRouteValue = routeToUpdate[lazyRouteProperty]; - let isPropertyStaticallyDefined = staticRouteValue !== undefined && - // This property isn't static since it should always be updated based - // on the route updates - lazyRouteProperty !== "hasErrorBoundary"; - warning(!isPropertyStaticallyDefined, "Route \"" + routeToUpdate.id + "\" has a static property \"" + lazyRouteProperty + "\" " + "defined but its lazy function is also returning a value for this property. " + ("The lazy route property \"" + lazyRouteProperty + "\" will be ignored.")); - if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) { - routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty]; - } - } - // Mutate the route with the provided updates. Do this first so we pass - // the updated version to mapRouteProperties - Object.assign(routeToUpdate, routeUpdates); - // Mutate the `hasErrorBoundary` property on the route based on the route - // updates and remove the `lazy` function so we don't resolve the lazy - // route again. - Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), { - lazy: undefined - })); -} -// Default implementation of `dataStrategy` which fetches all loaders in parallel -function defaultDataStrategy(opts) { - return Promise.all(opts.matches.map(m => m.resolve())); -} -async function callDataStrategyImpl(dataStrategyImpl, type, request, matchesToLoad, matches, manifest, mapRouteProperties, requestContext) { - let routeIdsToLoad = matchesToLoad.reduce((acc, m) => acc.add(m.route.id), new Set()); - let loadedMatches = new Set(); - // Send all matches here to allow for a middleware-type implementation. - // handler will be a no-op for unneeded routes and we filter those results - // back out below. - let results = await dataStrategyImpl({ - matches: matches.map(match => { - let shouldLoad = routeIdsToLoad.has(match.route.id); - // `resolve` encapsulates the route.lazy, executing the - // loader/action, and mapping return values/thrown errors to a - // HandlerResult. Users can pass a callback to take fine-grained control - // over the execution of the loader/action - let resolve = handlerOverride => { - loadedMatches.add(match.route.id); - return shouldLoad ? callLoaderOrAction(type, request, match, manifest, mapRouteProperties, handlerOverride, requestContext) : Promise.resolve({ - type: ResultType.data, - result: undefined - }); - }; - return _extends({}, match, { - shouldLoad, - resolve - }); - }), - request, - params: matches[0].params, - context: requestContext - }); - // Throw if any loadRoute implementations not called since they are what - // ensures a route is fully loaded - matches.forEach(m => invariant(loadedMatches.has(m.route.id), "`match.resolve()` was not called for route id \"" + m.route.id + "\". " + "You must call `match.resolve()` on every match passed to " + "`dataStrategy` to ensure all routes are properly loaded.")); - // Filter out any middleware-only matches for which we didn't need to run handlers - return results.filter((_, i) => routeIdsToLoad.has(matches[i].route.id)); -} -// Default logic for calling a loader/action is the user has no specified a dataStrategy -async function callLoaderOrAction(type, request, match, manifest, mapRouteProperties, handlerOverride, staticContext) { - let result; - let onReject; - let runHandler = handler => { - // Setup a promise we can race against so that abort signals short circuit - let reject; - // This will never resolve so safe to type it as Promise to - // satisfy the function return value - let abortPromise = new Promise((_, r) => reject = r); - onReject = () => reject(); - request.signal.addEventListener("abort", onReject); - let actualHandler = ctx => { - if (typeof handler !== "function") { - return Promise.reject(new Error("You cannot call the handler for a route which defines a boolean " + ("\"" + type + "\" [routeId: " + match.route.id + "]"))); - } - return handler({ - request, - params: match.params, - context: staticContext - }, ...(ctx !== undefined ? [ctx] : [])); - }; - let handlerPromise; - if (handlerOverride) { - handlerPromise = handlerOverride(ctx => actualHandler(ctx)); - } else { - handlerPromise = (async () => { - try { - let val = await actualHandler(); - return { - type: "data", - result: val - }; - } catch (e) { - return { - type: "error", - result: e - }; - } - })(); - } - return Promise.race([handlerPromise, abortPromise]); - }; - try { - let handler = match.route[type]; - if (match.route.lazy) { - if (handler) { - // Run statically defined handler in parallel with lazy() - let handlerError; - let [value] = await Promise.all([ - // If the handler throws, don't let it immediately bubble out, - // since we need to let the lazy() execution finish so we know if this - // route has a boundary that can handle the error - runHandler(handler).catch(e => { - handlerError = e; - }), loadLazyRouteModule(match.route, mapRouteProperties, manifest)]); - if (handlerError !== undefined) { - throw handlerError; - } - result = value; - } else { - // Load lazy route module, then run any returned handler - await loadLazyRouteModule(match.route, mapRouteProperties, manifest); - handler = match.route[type]; - if (handler) { - // Handler still runs even if we got interrupted to maintain consistency - // with un-abortable behavior of handler execution on non-lazy or - // previously-lazy-loaded routes - result = await runHandler(handler); - } else if (type === "action") { - let url = new URL(request.url); - let pathname = url.pathname + url.search; - throw getInternalRouterError(405, { - method: request.method, - pathname, - routeId: match.route.id - }); - } else { - // lazy() route has no loader to run. Short circuit here so we don't - // hit the invariant below that errors on returning undefined. - return { - type: ResultType.data, - result: undefined - }; - } - } - } else if (!handler) { - let url = new URL(request.url); - let pathname = url.pathname + url.search; - throw getInternalRouterError(404, { - pathname - }); - } else { - result = await runHandler(handler); - } - invariant(result.result !== undefined, "You defined " + (type === "action" ? "an action" : "a loader") + " for route " + ("\"" + match.route.id + "\" but didn't return anything from your `" + type + "` ") + "function. Please return a value or `null`."); - } catch (e) { - // We should already be catching and converting normal handler executions to - // HandlerResults and returning them, so anything that throws here is an - // unexpected error we still need to wrap - return { - type: ResultType.error, - result: e - }; - } finally { - if (onReject) { - request.signal.removeEventListener("abort", onReject); - } - } - return result; -} -async function convertHandlerResultToDataResult(handlerResult) { - let { - result, - type, - status - } = handlerResult; - if (isResponse(result)) { - let data; - try { - let contentType = result.headers.get("Content-Type"); - // Check between word boundaries instead of startsWith() due to the last - // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type - if (contentType && /\bapplication\/json\b/.test(contentType)) { - if (result.body == null) { - data = null; - } else { - data = await result.json(); - } - } else { - data = await result.text(); - } - } catch (e) { - return { - type: ResultType.error, - error: e - }; - } - if (type === ResultType.error) { - return { - type: ResultType.error, - error: new ErrorResponseImpl(result.status, result.statusText, data), - statusCode: result.status, - headers: result.headers - }; - } - return { - type: ResultType.data, - data, - statusCode: result.status, - headers: result.headers - }; - } - if (type === ResultType.error) { - return { - type: ResultType.error, - error: result, - statusCode: isRouteErrorResponse(result) ? result.status : status - }; - } - if (isDeferredData(result)) { - var _result$init, _result$init2; - return { - type: ResultType.deferred, - deferredData: result, - statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status, - headers: ((_result$init2 = result.init) == null ? void 0 : _result$init2.headers) && new Headers(result.init.headers) - }; - } - return { - type: ResultType.data, - data: result, - statusCode: status - }; -} -// Support relative routing in internal redirects -function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, v7_relativeSplatPath) { - let location = response.headers.get("Location"); - invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header"); - if (!ABSOLUTE_URL_REGEX.test(location)) { - let trimmedMatches = matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1); - location = normalizeTo(new URL(request.url), trimmedMatches, basename, true, location, v7_relativeSplatPath); - response.headers.set("Location", location); - } - return response; -} -function normalizeRedirectLocation(location, currentUrl, basename) { - if (ABSOLUTE_URL_REGEX.test(location)) { - // Strip off the protocol+origin for same-origin + same-basename absolute redirects - let normalizedLocation = location; - let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation); - let isSameBasename = stripBasename(url.pathname, basename) != null; - if (url.origin === currentUrl.origin && isSameBasename) { - return url.pathname + url.search + url.hash; - } - } - return location; -} -// Utility method for creating the Request instances for loaders/actions during -// client-side navigations and fetches. During SSR we will always have a -// Request instance from the static handler (query/queryRoute) -function createClientSideRequest(history, location, signal, submission) { - let url = history.createURL(stripHashFromPath(location)).toString(); - let init = { - signal - }; - if (submission && isMutationMethod(submission.formMethod)) { - let { - formMethod, - formEncType - } = submission; - // Didn't think we needed this but it turns out unlike other methods, patch - // won't be properly normalized to uppercase and results in a 405 error. - // See: https://fetch.spec.whatwg.org/#concept-method - init.method = formMethod.toUpperCase(); - if (formEncType === "application/json") { - init.headers = new Headers({ - "Content-Type": formEncType - }); - init.body = JSON.stringify(submission.json); - } else if (formEncType === "text/plain") { - // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) - init.body = submission.text; - } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) { - // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) - init.body = convertFormDataToSearchParams(submission.formData); - } else { - // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) - init.body = submission.formData; - } - } - return new Request(url, init); -} -function convertFormDataToSearchParams(formData) { - let searchParams = new URLSearchParams(); - for (let [key, value] of formData.entries()) { - // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs - searchParams.append(key, typeof value === "string" ? value : value.name); - } - return searchParams; -} -function convertSearchParamsToFormData(searchParams) { - let formData = new FormData(); - for (let [key, value] of searchParams.entries()) { - formData.append(key, value); - } - return formData; -} -function processRouteLoaderData(matches, matchesToLoad, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling) { - // Fill in loaderData/errors from our loaders - let loaderData = {}; - let errors = null; - let statusCode; - let foundError = false; - let loaderHeaders = {}; - let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : undefined; - // Process loader results into state.loaderData/state.errors - results.forEach((result, index) => { - let id = matchesToLoad[index].route.id; - invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData"); - if (isErrorResult(result)) { - let error = result.error; - // If we have a pending action error, we report it at the highest-route - // that throws a loader error, and then clear it out to indicate that - // it was consumed - if (pendingError !== undefined) { - error = pendingError; - pendingError = undefined; - } - errors = errors || {}; - if (skipLoaderErrorBubbling) { - errors[id] = error; - } else { - // Look upwards from the matched route for the closest ancestor error - // boundary, defaulting to the root match. Prefer higher error values - // if lower errors bubble to the same boundary - let boundaryMatch = findNearestBoundary(matches, id); - if (errors[boundaryMatch.route.id] == null) { - errors[boundaryMatch.route.id] = error; - } - } - // Clear our any prior loaderData for the throwing route - loaderData[id] = undefined; - // Once we find our first (highest) error, we set the status code and - // prevent deeper status codes from overriding - if (!foundError) { - foundError = true; - statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500; - } - if (result.headers) { - loaderHeaders[id] = result.headers; - } - } else { - if (isDeferredResult(result)) { - activeDeferreds.set(id, result.deferredData); - loaderData[id] = result.deferredData.data; - // Error status codes always override success status codes, but if all - // loaders are successful we take the deepest status code. - if (result.statusCode != null && result.statusCode !== 200 && !foundError) { - statusCode = result.statusCode; - } - if (result.headers) { - loaderHeaders[id] = result.headers; - } - } else { - loaderData[id] = result.data; - // Error status codes always override success status codes, but if all - // loaders are successful we take the deepest status code. - if (result.statusCode && result.statusCode !== 200 && !foundError) { - statusCode = result.statusCode; - } - if (result.headers) { - loaderHeaders[id] = result.headers; - } - } - } - }); - // If we didn't consume the pending action error (i.e., all loaders - // resolved), then consume it here. Also clear out any loaderData for the - // throwing route - if (pendingError !== undefined && pendingActionResult) { - errors = { - [pendingActionResult[0]]: pendingError - }; - loaderData[pendingActionResult[0]] = undefined; - } - return { - loaderData, - errors, - statusCode: statusCode || 200, - loaderHeaders - }; -} -function processLoaderData(state, matches, matchesToLoad, results, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds) { - let { - loaderData, - errors - } = processRouteLoaderData(matches, matchesToLoad, results, pendingActionResult, activeDeferreds, false // This method is only called client side so we always want to bubble - ); - // Process results from our revalidating fetchers - for (let index = 0; index < revalidatingFetchers.length; index++) { - let { - key, - match, - controller - } = revalidatingFetchers[index]; - invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, "Did not find corresponding fetcher result"); - let result = fetcherResults[index]; - // Process fetcher non-redirect errors - if (controller && controller.signal.aborted) { - // Nothing to do for aborted fetchers - continue; - } else if (isErrorResult(result)) { - let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id); - if (!(errors && errors[boundaryMatch.route.id])) { - errors = _extends({}, errors, { - [boundaryMatch.route.id]: result.error - }); - } - state.fetchers.delete(key); - } else if (isRedirectResult(result)) { - // Should never get here, redirects should get processed above, but we - // keep this to type narrow to a success result in the else - invariant(false, "Unhandled fetcher revalidation redirect"); - } else if (isDeferredResult(result)) { - // Should never get here, deferred data should be awaited for fetchers - // in resolveDeferredResults - invariant(false, "Unhandled fetcher deferred data"); - } else { - let doneFetcher = getDoneFetcher(result.data); - state.fetchers.set(key, doneFetcher); - } - } - return { - loaderData, - errors - }; -} -function mergeLoaderData(loaderData, newLoaderData, matches, errors) { - let mergedLoaderData = _extends({}, newLoaderData); - for (let match of matches) { - let id = match.route.id; - if (newLoaderData.hasOwnProperty(id)) { - if (newLoaderData[id] !== undefined) { - mergedLoaderData[id] = newLoaderData[id]; - } - } else if (loaderData[id] !== undefined && match.route.loader) { - // Preserve existing keys not included in newLoaderData and where a loader - // wasn't removed by HMR - mergedLoaderData[id] = loaderData[id]; - } - if (errors && errors.hasOwnProperty(id)) { - // Don't keep any loader data below the boundary - break; - } - } - return mergedLoaderData; -} -function getActionDataForCommit(pendingActionResult) { - if (!pendingActionResult) { - return {}; - } - return isErrorResult(pendingActionResult[1]) ? { - // Clear out prior actionData on errors - actionData: {} - } : { - actionData: { - [pendingActionResult[0]]: pendingActionResult[1].data - } - }; -} -// Find the nearest error boundary, looking upwards from the leaf route (or the -// route specified by routeId) for the closest ancestor error boundary, -// defaulting to the root match -function findNearestBoundary(matches, routeId) { - let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches]; - return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0]; -} -function getShortCircuitMatches(routes) { - // Prefer a root layout route if present, otherwise shim in a route object - let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === "/") || { - id: "__shim-error-route__" - }; - return { - matches: [{ - params: {}, - pathname: "", - pathnameBase: "", - route - }], - route - }; -} -function getInternalRouterError(status, _temp5) { - let { - pathname, - routeId, - method, - type - } = _temp5 === void 0 ? {} : _temp5; - let statusText = "Unknown Server Error"; - let errorMessage = "Unknown @remix-run/router error"; - if (status === 400) { - statusText = "Bad Request"; - if (method && pathname && routeId) { - errorMessage = "You made a " + method + " request to \"" + pathname + "\" but " + ("did not provide a `loader` for route \"" + routeId + "\", ") + "so there is no way to handle the request."; - } else if (type === "defer-action") { - errorMessage = "defer() is not supported in actions"; - } else if (type === "invalid-body") { - errorMessage = "Unable to encode submission body"; - } - } else if (status === 403) { - statusText = "Forbidden"; - errorMessage = "Route \"" + routeId + "\" does not match URL \"" + pathname + "\""; - } else if (status === 404) { - statusText = "Not Found"; - errorMessage = "No route matches URL \"" + pathname + "\""; - } else if (status === 405) { - statusText = "Method Not Allowed"; - if (method && pathname && routeId) { - errorMessage = "You made a " + method.toUpperCase() + " request to \"" + pathname + "\" but " + ("did not provide an `action` for route \"" + routeId + "\", ") + "so there is no way to handle the request."; - } else if (method) { - errorMessage = "Invalid request method \"" + method.toUpperCase() + "\""; - } - } - return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true); -} -// Find any returned redirect errors, starting from the lowest match -function findRedirect(results) { - for (let i = results.length - 1; i >= 0; i--) { - let result = results[i]; - if (isRedirectResult(result)) { - return { - result, - idx: i - }; - } - } -} -function stripHashFromPath(path) { - let parsedPath = typeof path === "string" ? parsePath(path) : path; - return createPath(_extends({}, parsedPath, { - hash: "" - })); -} -function isHashChangeOnly(a, b) { - if (a.pathname !== b.pathname || a.search !== b.search) { - return false; - } - if (a.hash === "") { - // /page -> /page#hash - return b.hash !== ""; - } else if (a.hash === b.hash) { - // /page#hash -> /page#hash - return true; - } else if (b.hash !== "") { - // /page#hash -> /page#other - return true; - } - // If the hash is removed the browser will re-perform a request to the server - // /page#hash -> /page - return false; -} -function isHandlerResult(result) { - return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === ResultType.data || result.type === ResultType.error); -} -function isRedirectHandlerResult(result) { - return isResponse(result.result) && redirectStatusCodes.has(result.result.status); -} -function isDeferredResult(result) { - return result.type === ResultType.deferred; -} -function isErrorResult(result) { - return result.type === ResultType.error; -} -function isRedirectResult(result) { - return (result && result.type) === ResultType.redirect; -} -function isDeferredData(value) { - let deferred = value; - return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function"; -} -function isResponse(value) { - return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined"; -} -function isRedirectResponse(result) { - if (!isResponse(result)) { - return false; - } - let status = result.status; - let location = result.headers.get("Location"); - return status >= 300 && status <= 399 && location != null; -} -function isValidMethod(method) { - return validRequestMethods.has(method.toLowerCase()); -} -function isMutationMethod(method) { - return validMutationMethods.has(method.toLowerCase()); -} -async function resolveDeferredResults(currentMatches, matchesToLoad, results, signals, isFetcher, currentLoaderData) { - for (let index = 0; index < results.length; index++) { - let result = results[index]; - let match = matchesToLoad[index]; - // If we don't have a match, then we can have a deferred result to do - // anything with. This is for revalidating fetchers where the route was - // removed during HMR - if (!match) { - continue; - } - let currentMatch = currentMatches.find(m => m.route.id === match.route.id); - let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined; - if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) { - // Note: we do not have to touch activeDeferreds here since we race them - // against the signal in resolveDeferredData and they'll get aborted - // there if needed - let signal = signals[index]; - invariant(signal, "Expected an AbortSignal for revalidating fetcher deferred result"); - await resolveDeferredData(result, signal, isFetcher).then(result => { - if (result) { - results[index] = result || results[index]; - } - }); - } - } -} -async function resolveDeferredData(result, signal, unwrap) { - if (unwrap === void 0) { - unwrap = false; - } - let aborted = await result.deferredData.resolveData(signal); - if (aborted) { - return; - } - if (unwrap) { - try { - return { - type: ResultType.data, - data: result.deferredData.unwrappedData - }; - } catch (e) { - // Handle any TrackedPromise._error values encountered while unwrapping - return { - type: ResultType.error, - error: e - }; - } - } - return { - type: ResultType.data, - data: result.deferredData.data - }; -} -function hasNakedIndexQuery(search) { - return new URLSearchParams(search).getAll("index").some(v => v === ""); -} -function getTargetMatch(matches, location) { - let search = typeof location === "string" ? parsePath(location).search : location.search; - if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) { - // Return the leaf index route when index is present - return matches[matches.length - 1]; - } - // Otherwise grab the deepest "path contributing" match (ignoring index and - // pathless layout routes) - let pathMatches = getPathContributingMatches(matches); - return pathMatches[pathMatches.length - 1]; -} -function getSubmissionFromNavigation(navigation) { - let { - formMethod, - formAction, - formEncType, - text, - formData, - json - } = navigation; - if (!formMethod || !formAction || !formEncType) { - return; - } - if (text != null) { - return { - formMethod, - formAction, - formEncType, - formData: undefined, - json: undefined, - text - }; - } else if (formData != null) { - return { - formMethod, - formAction, - formEncType, - formData, - json: undefined, - text: undefined - }; - } else if (json !== undefined) { - return { - formMethod, - formAction, - formEncType, - formData: undefined, - json, - text: undefined - }; - } -} -function getLoadingNavigation(location, submission) { - if (submission) { - let navigation = { - state: "loading", - location, - formMethod: submission.formMethod, - formAction: submission.formAction, - formEncType: submission.formEncType, - formData: submission.formData, - json: submission.json, - text: submission.text - }; - return navigation; - } else { - let navigation = { - state: "loading", - location, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined - }; - return navigation; - } -} -function getSubmittingNavigation(location, submission) { - let navigation = { - state: "submitting", - location, - formMethod: submission.formMethod, - formAction: submission.formAction, - formEncType: submission.formEncType, - formData: submission.formData, - json: submission.json, - text: submission.text - }; - return navigation; -} -function getLoadingFetcher(submission, data) { - if (submission) { - let fetcher = { - state: "loading", - formMethod: submission.formMethod, - formAction: submission.formAction, - formEncType: submission.formEncType, - formData: submission.formData, - json: submission.json, - text: submission.text, - data - }; - return fetcher; - } else { - let fetcher = { - state: "loading", - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined, - data - }; - return fetcher; - } -} -function getSubmittingFetcher(submission, existingFetcher) { - let fetcher = { - state: "submitting", - formMethod: submission.formMethod, - formAction: submission.formAction, - formEncType: submission.formEncType, - formData: submission.formData, - json: submission.json, - text: submission.text, - data: existingFetcher ? existingFetcher.data : undefined - }; - return fetcher; -} -function getDoneFetcher(data) { - let fetcher = { - state: "idle", - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined, - data - }; - return fetcher; -} -function restoreAppliedTransitions(_window, transitions) { - try { - let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY); - if (sessionPositions) { - let json = JSON.parse(sessionPositions); - for (let [k, v] of Object.entries(json || {})) { - if (v && Array.isArray(v)) { - transitions.set(k, new Set(v || [])); - } - } - } - } catch (e) { - // no-op, use default empty object - } -} -function persistAppliedTransitions(_window, transitions) { - if (transitions.size > 0) { - let json = {}; - for (let [k, v] of transitions) { - json[k] = [...v]; - } - try { - _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json)); - } catch (error) { - warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ")."); - } - } -} -//#endregion - -export { AbortedDeferredError, Action, IDLE_BLOCKER, IDLE_FETCHER, IDLE_NAVIGATION, UNSAFE_DEFERRED_SYMBOL, DeferredData as UNSAFE_DeferredData, ErrorResponseImpl as UNSAFE_ErrorResponseImpl, convertRouteMatchToUiMatch as UNSAFE_convertRouteMatchToUiMatch, convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes, getResolveToMatches as UNSAFE_getResolveToMatches, invariant as UNSAFE_invariant, warning as UNSAFE_warning, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, createRouter, createStaticHandler, defer, generatePath, getStaticContextFromError, getToPathname, isDeferredData, isRouteErrorResponse, joinPaths, json, matchPath, matchRoutes, normalizePathname, parsePath, redirect, redirectDocument, resolvePath, resolveTo, stripBasename }; -//# sourceMappingURL=router.js.map diff --git a/node_modules/@remix-run/router/dist/router.js.map b/node_modules/@remix-run/router/dist/router.js.map deleted file mode 100644 index 457670b2..00000000 --- a/node_modules/@remix-run/router/dist/router.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"router.js","sources":["../history.ts","../utils.ts","../router.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 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, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial;\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 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;\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 () 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(\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 // eslint-disable-next-line no-console\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 // eslint-disable-next-line no-empty\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 {\n let location: Readonly = {\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 */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial) {\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 */\nexport function parsePath(path: string): Partial {\n let parsedPath: Partial = {};\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 { 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 deferred = \"deferred\",\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 * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n type: ResultType.deferred;\n deferredData: DeferredData;\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 =\n | SuccessResult\n | DeferredResult\n | RedirectResult\n | ErrorResult;\n\n/**\n * Result from a loader or action called via dataStrategy\n */\nexport interface HandlerResult {\n type: \"data\" | \"error\";\n result: unknown; // data, Error, Response, DeferredData\n status?: number;\n}\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase;\n\n/**\n * Users can specify either lowercase or uppercase form methods on ``,\n * useSubmit(), ``, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude;\n\n/**\n * In v7, 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 V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude;\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 | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_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 {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs\n extends DataFunctionArgs {}\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 | null;\n\ntype DataFunctionReturnValue = Promise | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction = {\n (\n args: LoaderFunctionArgs,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (\n args: ActionFunctionArgs,\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 unstable_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\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\nexport interface DataStrategyMatch\n extends AgnosticRouteMatch {\n shouldLoad: boolean;\n resolve: (\n handlerOverride?: (\n handler: (ctx?: unknown) => DataFunctionReturnValue\n ) => Promise\n ) => Promise;\n}\n\nexport interface DataStrategyFunctionArgs\n extends DataFunctionArgs {\n matches: DataStrategyMatch[];\n}\n\nexport interface DataStrategyFunction {\n (args: DataStrategyFunctionArgs): Promise;\n}\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;\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([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit & Required> : 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 {\n (): Promise>>;\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;\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;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam | _PathParam\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 =\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\n : // look for params in the absence of wildcards\n _PathParam;\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 =\n // if you could not find path params, fallback to `string`\n [PathParam] extends [never] ? string : PathParam;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params = {\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;\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 {}\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: number[] = [],\n manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, 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 * @see https://reactrouter.com/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename = \"/\"\n): AgnosticRouteMatch[] | 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(branches[i], decoded);\n }\n\n return matches;\n}\n\nexport interface UIMatch {\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[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta = {\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\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,\n pathname: string\n): AgnosticRouteMatch[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch[] = [];\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 if (!match) return null;\n\n Object.assign(matchedParams, match.params);\n\n let route = meta.route;\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params,\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 * @see https://reactrouter.com/utils/generate-path\n */\nexport function generatePath(\n originalPath: Path,\n params: {\n [key in PathParam]: 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;\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];\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 {\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 {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\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 = {\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 * @see https://reactrouter.com/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey,\n Path extends string\n>(\n pattern: PathPattern | Path,\n pathname: string\n): PathMatch | 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>(\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\nfunction 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 * @see https://reactrouter.com/utils/resolve-path\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\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 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 * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \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[], v7_relativeSplatPath: boolean) {\n let pathMatches = getPathContributingMatches(matches);\n\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) =>\n idx === matches.length - 1 ? match.pathname : match.pathnameBase\n );\n }\n\n return pathMatches.map((match) => match.pathnameBase);\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;\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 `` 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 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 function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\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\nexport type JsonFunction = (\n data: Data,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\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 interface TrackedPromise extends Promise {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeysSet: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record,\n init?: number | ResponseInit\n) => DeferredData;\n\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\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 */\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 */\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\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 */\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 HistoryAction,\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 DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n HandlerResult,\n ImmutableRouteKey,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\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 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 * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the future config for the router\n */\n get future(): FutureConfig;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\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 * @internal\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 * @internal\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,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\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;\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;\n\n /**\n * @internal\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 ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\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 * @internal\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 * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(key: string): Fetcher;\n\n /**\n * @internal\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 * @internal\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @internal\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 * @internal\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 * @internal\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 * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map;\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 /**\n * The action of the most recent navigation\n */\n historyAction: HistoryAction;\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;\n\n /**\n * Map of current blockers\n */\n blockers: Map;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_partialHydration: boolean;\n v7_prependBasename: boolean;\n v7_relativeSplatPath: boolean;\n unstable_skipActionErrorRevalidation: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n hydrationData?: HydrationState;\n window?: Window;\n unstable_dataStrategy?: DataStrategyFunction;\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;\n actionHeaders: Record;\n activeDeferreds: Record | null;\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 unstable_dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\n queryRoute(\n request: Request,\n opts?: {\n routeId?: string;\n requestContext?: unknown;\n unstable_dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\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 unstable_viewTransitionOpts?: ViewTransitionOpts;\n unstable_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\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n unstable_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 */\ntype FetcherStates = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\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 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 =\n FetcherStates[keyof FetcherStates];\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: HistoryAction;\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 * 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 * 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(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set(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//#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 const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\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.unstable_dataStrategy || defaultDataStrategy;\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n unstable_skipActionErrorRevalidation: false,\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();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record | 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 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) {\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 let initialized: boolean;\n let hasLazyRoutes = initialMatches.some((m) => m.route.lazy);\n let hasLoaders = initialMatches.some((m) => m.route.loader);\n if (hasLazyRoutes) {\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 (!hasLoaders) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, 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 let isRouteInitialized = (m: AgnosticDataRouteMatch) => {\n // No loader, nothing to initialize\n if (!m.route.loader) {\n return true;\n }\n // Explicitly opting-in to running on hydration\n if (\n typeof m.route.loader === \"function\" &&\n m.route.loader.hydrate === true\n ) {\n return false;\n }\n // Otherwise, initialized if hydrated with data or an error\n return (\n (loaderData && loaderData[m.route.id] !== undefined) ||\n (errors && errors[m.route.id] !== undefined)\n );\n };\n\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.slice(0, idx + 1).every(isRouteInitialized);\n } else {\n initialized = initialMatches.every(isRouteInitialized);\n }\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\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: HistoryAction = HistoryAction.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> = new Map<\n string,\n Set\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 routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\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();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\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();\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 ignoreNextHistoryUpdate = false;\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 (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\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 ignoreNextHistoryUpdate = true;\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\n 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 fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.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,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\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: deletedFetchersKeys,\n unstable_viewTransitionOpts: opts.viewTransitionOpts,\n unstable_flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n }\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>,\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 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 === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.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 === HistoryAction.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([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 = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\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 ): Promise {\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 future.v7_prependBasename,\n to,\n future.v7_relativeSplatPath,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\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 = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.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 = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.unstable_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 return 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.unstable_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 interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\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;\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;\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 { overrideNavigation: state.navigation }\n );\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: HistoryAction,\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 {\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 // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\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 load will always\n // be \"same hash\". For example, on /page#hash and submit a \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 { replace: opts.replace, flushSync }\n );\n\n if (actionResult.shortCircuited) {\n return;\n }\n\n pendingActionResult = actionResult.pendingActionResult;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = 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 { shortCircuited, loaderData, errors } = await handleLoaders(\n request,\n location,\n matches,\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,\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 opts: { replace?: boolean; flushSync?: boolean } = {}\n ): Promise {\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 // 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 request,\n [actionMatch],\n matches\n );\n result = results[0];\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, {\n submission,\n replace,\n });\n return { shortCircuited: true };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\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 are REPLACE navigations, but if the\n // action threw an error that'll be rendered in an errorElement, we fall\n // back to PUSH so that the user can use the back button to get back to\n // the pre-submission form location to try again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n pendingActionResult: [boundaryMatch.route.id, result],\n };\n }\n\n return {\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 overrideNavigation?: Navigation,\n submission?: Submission,\n fetcherSubmission?: Submission,\n replace?: boolean,\n initialHydration?: boolean,\n flushSync?: boolean,\n pendingActionResult?: PendingActionResult\n ): Promise {\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 let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n future.v7_partialHydration && initialHydration === true,\n future.unstable_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionResult\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\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 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 // If we have partialHydration enabled, then don't update the state for the\n // initial data load since it's not a \"navigation\"\n if (\n !isUninterruptedRevalidation &&\n (!future.v7_partialHydration || !initialHydration)\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\n let actionData: Record | 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 actionData = {\n [pendingActionResult[0]]: pendingActionResult[1].data as any,\n };\n } else if (state.actionData) {\n if (Object.keys(state.actionData).length === 0) {\n actionData = null;\n } else {\n actionData = state.actionData;\n }\n }\n\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData !== undefined ? { actionData } : {}),\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n revalidatingFetchers.forEach((rf) => {\n if (fetchControllers.has(rf.key)) {\n abortFetcher(rf.key);\n }\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.matches,\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 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, ...fetcherResults]);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\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 let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n await startRedirectNavigation(request, redirect.result, {\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 matchesToLoad,\n loaderResults,\n pendingActionResult,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe((aborted) => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n\n // During partial hydration, preserve SSR errors for routes that don't re-run\n if (future.v7_partialHydration && initialHydration && state.errors) {\n Object.entries(state.errors)\n .filter(([id]) => !matchesToLoad.some((m) => m.route.id === id))\n .forEach(([routeId, error]) => {\n errors = Object.assign(errors || {}, { [routeId]: error });\n });\n }\n\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n if (fetchControllers.has(key)) abortFetcher(key);\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n future.v7_relativeSplatPath,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\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 future.v7_normalizeFormMethod,\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 pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\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 handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\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 flushSync: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action && !match.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;\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 // Call the action for the fetcher\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResults = await callDataStrategy(\n \"action\",\n fetchRequest,\n [match],\n requestMatches\n );\n let actionResult = actionResults[0];\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 // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.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, {\n fetcherSubmission: submission,\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 if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\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 future.unstable_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\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 if (fetchControllers.has(staleKey)) {\n abortFetcher(staleKey);\n }\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.matches,\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, ...fetcherResults]);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\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 let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n return startRedirectNavigation(revalidationRequest, redirect.result);\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n state.matches,\n matchesToLoad,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\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 flushSync: 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 // Call the loader for this fetcher route match\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let results = await callDataStrategy(\n \"loader\",\n fetchRequest,\n [match],\n matches\n );\n let result = results[0];\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\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 (deletedFetchers.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);\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 invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\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 {\n submission,\n fetcherSubmission,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\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 redirectHistoryAction =\n replace === true ? HistoryAction.Replace : HistoryAction.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(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: location,\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\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(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\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 request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[]\n ): Promise {\n try {\n let results = await callDataStrategyImpl(\n dataStrategyImpl,\n type,\n request,\n matchesToLoad,\n matches,\n manifest,\n mapRouteProperties\n );\n\n return await Promise.all(\n results.map((result, i) => {\n if (isRedirectHandlerResult(result)) {\n let response = result.result as Response;\n return {\n type: ResultType.redirect,\n response: normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n matchesToLoad[i].route.id,\n matches,\n basename,\n future.v7_relativeSplatPath\n ),\n };\n }\n\n return convertHandlerResultToDataResult(result);\n })\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 return matchesToLoad.map(() => ({\n type: ResultType.error,\n error: e,\n }));\n }\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n let [loaderResults, ...fetcherResults] = await Promise.all([\n matchesToLoad.length\n ? callDataStrategy(\"loader\", request, matchesToLoad, matches)\n : [],\n ...fetchersToLoad.map((f) => {\n if (f.matches && f.match && f.controller) {\n let fetcherRequest = createClientSideRequest(\n init.history,\n f.path,\n f.controller.signal\n );\n return callDataStrategy(\n \"loader\",\n fetcherRequest,\n [f.match],\n f.matches\n ).then((r) => r[0]);\n } else {\n return Promise.resolve({\n type: ResultType.error,\n error: getInternalRouterError(404, {\n pathname: f.path,\n }),\n });\n }\n }),\n ]);\n\n await Promise.all([\n resolveDeferredResults(\n currentMatches,\n matchesToLoad,\n loaderResults,\n loaderResults.map(() => request.signal),\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map((f) => f.match),\n fetcherResults,\n fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)),\n true\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 // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.push(key);\n abortFetcher(key);\n }\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(key: string): Fetcher {\n if (future.v7_fetcherPersist) {\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 (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\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 deletedFetchers.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n if (future.v7_fetcherPersist) {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n } else {\n activeFetchers.set(key, count);\n }\n } else {\n deleteFetcher(key);\n }\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n invariant(controller, `Expected fetch controller: ${key}`);\n controller.abort();\n fetchControllers.delete(key);\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: HistoryAction;\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 cancelActiveDeferreds(\n predicate?: (routeId: string) => boolean\n ): string[] {\n let cancelledRouteIds: string[] = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the component\n function enableScrollRestoration(\n positions: Record,\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 \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 _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\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: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\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 const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n v7_relativeSplatPath: boolean;\n v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\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: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future: StaticHandlerFutureConfig = {\n v7_relativeSplatPath: false,\n v7_throwAbortReason: false,\n ...(opts ? opts.future : null),\n };\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 unstable_dataStrategy,\n }: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n unstable_dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\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 activeDeferreds: null,\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 activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n unstable_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 unstable_dataStrategy,\n }: {\n requestContext?: unknown;\n routeId?: string;\n unstable_dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\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 unstable_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 let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n unstable_dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null\n ): Promise | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n unstable_dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n unstable_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 `HandlerResult` to bail out early\n // and then return or throw the raw Response here accordingly\n if (isHandlerResult(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 unstable_dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n isRouteRequest: boolean\n ): Promise | 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 unstable_dataStrategy\n );\n result = results[0];\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\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 (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\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 activeDeferreds: null,\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 unstable_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 unstable_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 unstable_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 activeDeferreds: null,\n };\n }\n\n let results = await callDataStrategy(\n \"loader\",\n request,\n matchesToLoad,\n matches,\n isRouteRequest,\n requestContext,\n unstable_dataStrategy\n );\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionResult,\n activeDeferreds,\n skipLoaderErrorBubbling\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(\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 activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\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 unstable_dataStrategy: DataStrategyFunction | null\n ): Promise {\n let results = await callDataStrategyImpl(\n unstable_dataStrategy || defaultDataStrategy,\n type,\n request,\n matchesToLoad,\n matches,\n manifest,\n mapRouteProperties,\n requestContext\n );\n\n return await Promise.all(\n results.map((result, i) => {\n if (isRedirectHandlerResult(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 matchesToLoad[i].route.id,\n matches,\n basename,\n future.v7_relativeSplatPath\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 return convertHandlerResultToDataResult(result);\n })\n );\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 */\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 future: StaticHandlerFutureConfig\n) {\n if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n throw request.signal.reason;\n }\n\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\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 prependBasename: boolean,\n to: To | null,\n v7_relativeSplatPath: boolean,\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, v7_relativeSplatPath),\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 // Add an ?index param for matched index routes if we don't already have one\n if (\n (to == null || to === \"\" || to === \".\") &&\n activeRouteMatch &&\n activeRouteMatch.route.index &&\n !hasNakedIndexQuery(path.search)\n ) {\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. 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 (prependBasename && 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 normalizeFormMethod: boolean,\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 = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() 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 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) {\n let boundaryMatches = matches;\n if (boundaryId) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n boundaryMatches = matches.slice(0, index);\n }\n }\n return boundaryMatches;\n}\n\nfunction getMatchesToLoad(\n history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isInitialLoad: boolean,\n skipActionErrorRevalidation: boolean,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n deletedFetchers: Set,\n fetchLoadMatches: Map,\n fetchRedirectIds: Set,\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 boundaryId =\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? pendingActionResult[0]\n : undefined;\n let boundaryMatches = boundaryId\n ? getLoaderMatchesUntilBoundary(matches, boundaryId)\n : matches;\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 =\n skipActionErrorRevalidation && 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 (isInitialLoad) {\n if (typeof route.loader !== \"function\" || route.loader.hydrate) {\n return true;\n }\n return (\n state.loaderData[route.id] === undefined &&\n // Don't re-run if the loader ran and threw an error\n (!state.errors || state.errors[route.id] === undefined)\n );\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\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 unstable_actionStatus: 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 load (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 isInitialLoad ||\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.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.includes(key)) {\n // Always revalidate if the fetcher was cancelled\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 unstable_actionStatus: 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 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 or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\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\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 = {};\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\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // 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\nfunction defaultDataStrategy(\n opts: DataStrategyFunctionArgs\n): ReturnType {\n return Promise.all(opts.matches.map((m) => m.resolve()));\n}\n\nasync function callDataStrategyImpl(\n dataStrategyImpl: DataStrategyFunction,\n type: \"loader\" | \"action\",\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n requestContext?: unknown\n): Promise {\n let routeIdsToLoad = matchesToLoad.reduce(\n (acc, m) => acc.add(m.route.id),\n new Set()\n );\n let loadedMatches = new Set();\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: matches.map((match) => {\n let shouldLoad = routeIdsToLoad.has(match.route.id);\n // `resolve` encapsulates the route.lazy, executing the\n // loader/action, and mapping return values/thrown errors to a\n // HandlerResult. Users can pass a callback to take fine-grained control\n // over the execution of the loader/action\n let resolve: DataStrategyMatch[\"resolve\"] = (handlerOverride) => {\n loadedMatches.add(match.route.id);\n return shouldLoad\n ? callLoaderOrAction(\n type,\n request,\n match,\n manifest,\n mapRouteProperties,\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 request,\n params: matches[0].params,\n context: requestContext,\n });\n\n // Throw if any loadRoute implementations not called since they are what\n // ensures a route is fully loaded\n matches.forEach((m) =>\n invariant(\n loadedMatches.has(m.route.id),\n `\\`match.resolve()\\` was not called for route id \"${m.route.id}\". ` +\n \"You must call `match.resolve()` on every match passed to \" +\n \"`dataStrategy` to ensure all routes are properly loaded.\"\n )\n );\n\n // Filter out any middleware-only matches for which we didn't need to run handlers\n return results.filter((_, i) => routeIdsToLoad.has(matches[i].route.id));\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 manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n handlerOverride: Parameters[0],\n staticContext?: unknown\n): Promise {\n let result: HandlerResult;\n let onReject: (() => void) | undefined;\n\n let runHandler = (\n handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n ): Promise => {\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 to\n // satisfy the function return value\n let abortPromise = new Promise((_, 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;\n if (handlerOverride) {\n handlerPromise = handlerOverride((ctx: unknown) => actualHandler(ctx));\n } else {\n handlerPromise = (async () => {\n try {\n let val = await actualHandler();\n return { type: \"data\", result: val };\n } catch (e) {\n return { type: \"error\", result: e };\n }\n })();\n }\n\n return Promise.race([handlerPromise, abortPromise]);\n };\n\n try {\n let handler = match.route[type];\n\n if (match.route.lazy) {\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 loadLazyRouteModule(match.route, mapRouteProperties, manifest),\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 loadLazyRouteModule(match.route, mapRouteProperties, manifest);\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\n invariant(\n result.result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n // We should already be catching and converting normal handler executions to\n // HandlerResults 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 convertHandlerResultToDataResult(\n handlerResult: HandlerResult\n): Promise {\n let { result, type, status } = handlerResult;\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 return {\n type: ResultType.error,\n error: result,\n statusCode: isRouteErrorResponse(result) ? result.status : status,\n };\n }\n\n if (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n return { type: ResultType.data, data: result, statusCode: status };\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 v7_relativeSplatPath: boolean\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 true,\n location,\n v7_relativeSplatPath\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 matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingActionResult: PendingActionResult | undefined,\n activeDeferreds: Map,\n skipLoaderErrorBubbling: boolean\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record;\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 = {};\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 results.forEach((result, index) => {\n let id = matchesToLoad[index].route.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 loaderData[id] = undefined;\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 if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.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 (\n result.statusCode != null &&\n result.statusCode !== 200 &&\n !foundError\n ) {\n statusCode = result.statusCode;\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\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 matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingActionResult: PendingActionResult | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: DataResult[],\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionResult,\n activeDeferreds,\n false // This method is only called client side so we always want to bubble\n );\n\n // Process results from our revalidating fetchers\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let { key, match, controller } = revalidatingFetchers[index];\n invariant(\n fetcherResults !== undefined && fetcherResults[index] !== undefined,\n \"Did not find corresponding fetcher result\"\n );\n let result = fetcherResults[index];\n\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n continue;\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 if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\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 let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\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 }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\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 === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\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: DataResult[]\n): { result: RedirectResult; idx: number } | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return { result, idx: i };\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 isHandlerResult(result: unknown): result is HandlerResult {\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 isRedirectHandlerResult(result: HandlerResult) {\n return (\n isResponse(result.result) && redirectStatusCodes.has(result.result.status)\n );\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\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 isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\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 | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: (AgnosticDataRouteMatch | null)[],\n results: DataResult[],\n signals: (AbortSignal | null)[],\n isFetcher: boolean,\n currentLoaderData?: RouteData\n) {\n for (let index = 0; index < results.length; index++) {\n let result = results[index];\n let match = matchesToLoad[index];\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n let signal = signals[index];\n invariant(\n signal,\n \"Expected an AbortSignal for revalidating fetcher deferred result\"\n );\n await resolveDeferredData(result, signal, isFetcher).then((result) => {\n if (result) {\n results[index] = result || results[index];\n }\n });\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise {\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData,\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e,\n };\n }\n }\n\n return {\n type: ResultType.data,\n data: result.deferredData.data,\n };\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>\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>\n) {\n if (transitions.size > 0) {\n let json: Record = {};\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\n//#endregion\n"],"names":["Action","PopStateEventType","createMemoryHistory","options","initialEntries","initialIndex","v5Compat","entries","map","entry","index","createMemoryLocation","state","undefined","clampIndex","length","action","Pop","listener","n","Math","min","max","getCurrentLocation","to","key","location","createLocation","pathname","warning","charAt","JSON","stringify","createHref","createPath","history","createURL","URL","encodeLocation","path","parsePath","search","hash","push","Push","nextLocation","splice","delta","replace","Replace","go","nextIndex","listen","fn","createBrowserHistory","createBrowserLocation","window","globalHistory","usr","createBrowserHref","getUrlBasedHistory","createHashHistory","createHashLocation","substr","startsWith","createHashHref","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","validateHashLocation","invariant","value","message","Error","cond","console","warn","e","createKey","random","toString","getHistoryState","idx","current","_extends","_ref","parsedPath","searchIndex","getLocation","validateLocation","defaultView","getIndex","replaceState","handlePop","historyState","pushState","error","DOMException","name","assign","origin","addEventListener","removeEventListener","ResultType","immutableRouteKeys","Set","isIndexRoute","route","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","treePath","id","join","children","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","stripBasename","branches","flattenRoutes","rankRouteBranches","matches","i","decoded","decodePath","matchRouteBranch","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","meta","caseSensitive","childrenIndex","joinPaths","routesMeta","concat","score","computeScore","forEach","_route$path","includes","exploded","explodeOptionalSegments","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","sort","a","b","compareIndexes","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","initialScore","some","filter","reduce","segment","test","siblings","every","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","generatePath","originalPath","prefix","p","String","array","isLastSegment","star","keyMatch","optional","param","pattern","matcher","compiledParams","compilePath","captureGroups","memo","paramName","splatValue","regexpSource","_","RegExp","v","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","resolvePathname","normalizeSearch","normalizeHash","relativeSegments","pop","getInvalidPathError","char","field","dest","getPathContributingMatches","getResolveToMatches","v7_relativeSplatPath","pathMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","getToPathname","paths","json","init","responseInit","status","headers","Headers","has","set","Response","AbortedDeferredError","DeferredData","constructor","pendingKeysSet","subscribers","deferredKeys","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","_ref2","trackPromise","done","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","k","resolveData","resolve","size","unwrappedData","_ref3","unwrapTrackedPromise","pendingKeys","isTrackedPromise","_tracked","_error","_data","defer","redirect","redirectDocument","response","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","createRouter","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","dataRoutes","inFlightDataRoutes","dataStrategyImpl","unstable_dataStrategy","defaultDataStrategy","future","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_prependBasename","unstable_skipActionErrorRevalidation","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialErrors","getInternalRouterError","getShortCircuitMatches","initialized","hasLazyRoutes","m","lazy","hasLoaders","loader","errors","isRouteInitialized","hydrate","findIndex","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","actionData","fetchers","Map","blockers","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeFetchers","deletedFetchers","activeDeferreds","blockerFunctions","ignoreNextHistoryUpdate","initialize","blockerKey","shouldBlockNavigation","currentLocation","updateBlocker","updateState","startNavigation","restoreAppliedTransitions","_saveAppliedTransitions","persistAppliedTransitions","initialHydration","dispose","clear","deleteFetcher","deleteBlocker","newState","opts","completedFetchers","deletedFetchersKeys","fetcher","unstable_viewTransitionOpts","viewTransitionOpts","unstable_flushSync","flushSync","completeNavigation","_temp","_location$state","_location$state2","isActionReload","isMutationMethod","_isRedirect","keys","mergeLoaderData","priorPaths","toPaths","getSavedScrollPosition","navigate","normalizedPath","normalizeTo","fromRouteId","relative","submission","normalizeNavigateOptions","userReplace","pendingError","enableViewTransition","unstable_viewTransition","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","routesToUse","loadingNavigation","notFoundMatches","cancelActiveDeferreds","isHashChangeOnly","request","createClientSideRequest","pendingActionResult","findNearestBoundary","type","actionResult","handleAction","shortCircuited","getLoadingNavigation","handleLoaders","fetcherSubmission","getActionDataForCommit","getSubmittingNavigation","actionMatch","getTargetMatch","method","routeId","results","callDataStrategy","isRedirectResult","normalizeRedirectLocation","startRedirectNavigation","isDeferredResult","isErrorResult","boundaryMatch","activeSubmission","getSubmissionFromNavigation","matchesToLoad","revalidatingFetchers","getMatchesToLoad","updatedFetchers","markFetchRedirectsDone","rf","revalidatingFetcher","getLoadingFetcher","abortFetcher","abortPendingFetchRevalidations","f","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","findRedirect","fetcherKey","processLoaderData","deferredData","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","fetch","setFetcherError","handleFetcherAction","handleFetcherLoader","requestMatches","existingFetcher","updateFetcherState","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","actionResults","getDoneFetcher","revalidationRequest","loadId","loadFetcher","staleKey","doneFetcher","resolveDeferredData","_temp2","redirectLocation","isDocumentReload","redirectHistoryAction","callDataStrategyImpl","all","isRedirectHandlerResult","normalizeRelativeRoutingRedirectResponse","convertHandlerResultToDataResult","currentMatches","fetchersToLoad","fetcherRequest","resolveDeferredResults","getFetcher","deleteFetcherAndUpdateState","count","markFetchersDone","doneKeys","landedId","yeetedKeys","getBlocker","blocker","newBlocker","_ref4","blockerFunction","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","getScrollKey","_internalSetRoutes","newRoutes","_internalFetchControllers","_internalActiveDeferreds","UNSAFE_DEFERRED_SYMBOL","Symbol","createStaticHandler","v7_throwAbortReason","query","_temp3","requestContext","skipLoaderErrorBubbling","isValidMethod","methodNotAllowedMatches","statusCode","loaderHeaders","actionHeaders","queryImpl","isResponse","queryRoute","_temp4","find","values","_result$activeDeferre","routeMatch","submit","loadRouteData","isHandlerResult","isRedirectResponse","isRouteRequest","throwStaticHandlerAbortedError","Location","loaderRequest","Request","context","getLoaderMatchesUntilBoundary","processRouteLoaderData","executedLoaders","fromEntries","getStaticContextFromError","newContext","_deepestRenderedBoundaryId","reason","isSubmissionNavigation","body","prependBasename","contextualMatches","activeRouteMatch","hasNakedIndexQuery","normalizeFormMethod","isFetcher","getInvalidBodyError","rawFormMethod","toUpperCase","stripHashFromPath","FormData","URLSearchParams","_ref5","parse","searchParams","convertFormDataToSearchParams","convertSearchParamsToFormData","append","boundaryId","boundaryMatches","isInitialLoad","skipActionErrorRevalidation","currentUrl","nextUrl","actionStatus","shouldSkipRevalidation","navigationMatches","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","unstable_actionStatus","defaultShouldRevalidate","isNewRouteInstance","fetcherMatches","fetcherMatch","shouldRevalidate","currentLoaderData","currentMatch","isNew","isMissingData","currentPath","loaderMatch","arg","routeChoice","loadLazyRouteModule","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","staticRouteValue","isPropertyStaticallyDefined","routeIdsToLoad","loadedMatches","shouldLoad","handlerOverride","callLoaderOrAction","staticContext","onReject","runHandler","handler","actualHandler","ctx","handlerPromise","val","handlerError","handlerResult","contentType","isDeferredData","_result$init","_result$init2","deferred","trimmedMatches","normalizedLocation","protocol","isSameBasename","foundError","newLoaderData","mergedLoaderData","hasOwnProperty","eligibleMatches","reverse","_temp5","errorMessage","signals","isRevalidatingLoader","unwrap","getAll","_window","transitions","sessionPositions","sessionStorage","getItem","setItem"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AAEA;;AAEG;IACSA,OAsBX;AAtBD,CAAA,UAAYA,MAAM,EAAA;AAChB;;;;;;AAMG;AACHA,EAAAA,MAAA,CAAA,KAAA,CAAA,GAAA,KAAW,CAAA;AAEX;;;;AAIG;AACHA,EAAAA,MAAA,CAAA,MAAA,CAAA,GAAA,MAAa,CAAA;AAEb;;;AAGG;AACHA,EAAAA,MAAA,CAAA,SAAA,CAAA,GAAA,SAAmB,CAAA;AACrB,CAAC,EAtBWA,MAAM,KAANA,MAAM,GAsBjB,EAAA,CAAA,CAAA,CAAA;AAqKD,MAAMC,iBAAiB,GAAG,UAAU,CAAA;AA+BpC;;;AAGG;AACa,SAAAC,mBAAmBA,CACjCC,OAAA,EAAkC;AAAA,EAAA,IAAlCA,OAA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EAAElF,CAAC,CAAC,IAAIzB,MAAM,CAAC5L,OAAO,CAACwP,IAAI,IAAI,EAAE,CAAC,EAAE;QAC7C,IAAInC,CAAC,IAAIkD,KAAK,CAACC,OAAO,CAACnD,CAAC,CAAC,EAAE;AACzBse,UAAAA,WAAW,CAAC5b,GAAG,CAACwC,CAAC,EAAE,IAAI/L,GAAG,CAAC6G,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;AACrC,SAAA;AACF,OAAA;AACF,KAAA;GACF,CAAC,OAAOzI,CAAC,EAAE;AACV;AAAA,GAAA;AAEJ,CAAA;AAEA,SAASkV,yBAAyBA,CAChC4R,OAAe,EACfC,WAAqC,EAAA;AAErC,EAAA,IAAIA,WAAW,CAACjZ,IAAI,GAAG,CAAC,EAAE;IACxB,IAAIlD,IAAI,GAA6B,EAAE,CAAA;IACvC,KAAK,IAAI,CAAC+C,CAAC,EAAElF,CAAC,CAAC,IAAIse,WAAW,EAAE;AAC9Bnc,MAAAA,IAAI,CAAC+C,CAAC,CAAC,GAAG,CAAC,GAAGlF,CAAC,CAAC,CAAA;AACjB,KAAA;IACD,IAAI;AACFqe,MAAAA,OAAO,CAACG,cAAc,CAACE,OAAO,CAC5BhX,uBAAuB,EACvBvT,IAAI,CAACC,SAAS,CAAC+N,IAAI,CAAC,CACrB,CAAA;KACF,CAAC,OAAOzJ,KAAK,EAAE;AACdzE,MAAAA,OAAO,CACL,KAAK,EACyDyE,6DAAAA,GAAAA,KAAK,OAAI,CACxE,CAAA;AACF,KAAA;AACF,GAAA;AACH,CAAA;AAEA;;;;"} \ No newline at end of file diff --git a/node_modules/@remix-run/router/dist/router.umd.js b/node_modules/@remix-run/router/dist/router.umd.js deleted file mode 100644 index ad9e39f7..00000000 --- a/node_modules/@remix-run/router/dist/router.umd.js +++ /dev/null @@ -1,5026 +0,0 @@ -/** - * @remix-run/router v1.16.1 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.RemixRouter = {})); -})(this, (function (exports) { 'use strict'; - - function _extends() { - _extends = Object.assign ? Object.assign.bind() : function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - return target; - }; - return _extends.apply(this, arguments); - } - - //////////////////////////////////////////////////////////////////////////////// - //#region Types and Constants - //////////////////////////////////////////////////////////////////////////////// - - /** - * Actions represent the type of change to a location value. - */ - let Action = /*#__PURE__*/function (Action) { - Action["Pop"] = "POP"; - Action["Push"] = "PUSH"; - Action["Replace"] = "REPLACE"; - return Action; - }({}); - - /** - * The pathname, search, and hash values of a URL. - */ - - // TODO: (v7) Change the Location generic default from `any` to `unknown` and - // remove Remix `useLocation` wrapper. - /** - * An entry in a history stack. A location contains information about the - * URL path, as well as possibly some arbitrary state and a key. - */ - /** - * A change to the current location. - */ - /** - * A function that receives notifications about location changes. - */ - /** - * Describes a location that is the destination of some navigation, either via - * `history.push` or `history.replace`. This may be either a URL or the pieces - * of a URL path. - */ - /** - * A history is an interface to the navigation stack. The history serves as the - * source of truth for the current location, as well as provides a set of - * methods that may be used to change it. - * - * It is similar to the DOM's `window.history` object, but with a smaller, more - * focused API. - */ - const PopStateEventType = "popstate"; - //#endregion - - //////////////////////////////////////////////////////////////////////////////// - //#region Memory History - //////////////////////////////////////////////////////////////////////////////// - - /** - * A user-supplied object that describes a location. Used when providing - * entries to `createMemoryHistory` via its `initialEntries` option. - */ - /** - * A memory history stores locations in memory. This is useful in stateful - * environments where there is no web browser, such as node tests or React - * Native. - */ - /** - * Memory history stores the current location in memory. It is designed for use - * in stateful non-browser environments like tests and React Native. - */ - function createMemoryHistory(options) { - if (options === void 0) { - options = {}; - } - let { - initialEntries = ["/"], - initialIndex, - v5Compat = false - } = options; - let entries; // Declare so we can access from createMemoryLocation - entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : undefined)); - let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex); - let action = Action.Pop; - let listener = null; - function clampIndex(n) { - return Math.min(Math.max(n, 0), entries.length - 1); - } - function getCurrentLocation() { - return entries[index]; - } - function createMemoryLocation(to, state, key) { - if (state === void 0) { - state = null; - } - let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key); - warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to)); - return location; - } - function createHref(to) { - return typeof to === "string" ? to : createPath(to); - } - let history = { - get index() { - return index; - }, - get action() { - return action; - }, - get location() { - return getCurrentLocation(); - }, - createHref, - createURL(to) { - return new URL(createHref(to), "http://localhost"); - }, - encodeLocation(to) { - let path = typeof to === "string" ? parsePath(to) : to; - return { - pathname: path.pathname || "", - search: path.search || "", - hash: path.hash || "" - }; - }, - push(to, state) { - action = Action.Push; - let nextLocation = createMemoryLocation(to, state); - index += 1; - entries.splice(index, entries.length, nextLocation); - if (v5Compat && listener) { - listener({ - action, - location: nextLocation, - delta: 1 - }); - } - }, - replace(to, state) { - action = Action.Replace; - let nextLocation = createMemoryLocation(to, state); - entries[index] = nextLocation; - if (v5Compat && listener) { - listener({ - action, - location: nextLocation, - delta: 0 - }); - } - }, - go(delta) { - action = Action.Pop; - let nextIndex = clampIndex(index + delta); - let nextLocation = entries[nextIndex]; - index = nextIndex; - if (listener) { - listener({ - action, - location: nextLocation, - delta - }); - } - }, - listen(fn) { - listener = fn; - return () => { - listener = null; - }; - } - }; - return history; - } - //#endregion - - //////////////////////////////////////////////////////////////////////////////// - //#region Browser History - //////////////////////////////////////////////////////////////////////////////// - - /** - * A browser history stores the current location in regular URLs in a web - * browser environment. This is the standard for most web apps and provides the - * cleanest URLs the browser's address bar. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory - */ - /** - * Browser history stores the location in regular URLs. This is the standard for - * most web apps, but it requires some configuration on the server to ensure you - * serve the same app at multiple URLs. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory - */ - function createBrowserHistory(options) { - if (options === void 0) { - options = {}; - } - function createBrowserLocation(window, globalHistory) { - let { - pathname, - search, - hash - } = window.location; - return createLocation("", { - pathname, - search, - hash - }, - // state defaults to `null` because `window.history.state` does - globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default"); - } - function createBrowserHref(window, to) { - return typeof to === "string" ? to : createPath(to); - } - return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options); - } - //#endregion - - //////////////////////////////////////////////////////////////////////////////// - //#region Hash History - //////////////////////////////////////////////////////////////////////////////// - - /** - * A hash history stores the current location in the fragment identifier portion - * of the URL in a web browser environment. - * - * This is ideal for apps that do not control the server for some reason - * (because the fragment identifier is never sent to the server), including some - * shared hosting environments that do not provide fine-grained controls over - * which pages are served at which URLs. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory - */ - /** - * Hash history stores the location in window.location.hash. This makes it ideal - * for situations where you don't want to send the location to the server for - * some reason, either because you do cannot configure it or the URL space is - * reserved for something else. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory - */ - function createHashHistory(options) { - if (options === void 0) { - options = {}; - } - function createHashLocation(window, globalHistory) { - let { - pathname = "/", - search = "", - hash = "" - } = parsePath(window.location.hash.substr(1)); - - // Hash URL should always have a leading / just like window.location.pathname - // does, so if an app ends up at a route like /#something then we add a - // leading slash so all of our path-matching behaves the same as if it would - // in a browser router. This is particularly important when there exists a - // root splat route () since that matches internally against - // "/*" and we'd expect /#something to 404 in a hash router app. - if (!pathname.startsWith("/") && !pathname.startsWith(".")) { - pathname = "/" + pathname; - } - return createLocation("", { - pathname, - search, - hash - }, - // state defaults to `null` because `window.history.state` does - globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default"); - } - function createHashHref(window, to) { - let base = window.document.querySelector("base"); - let href = ""; - if (base && base.getAttribute("href")) { - let url = window.location.href; - let hashIndex = url.indexOf("#"); - href = hashIndex === -1 ? url : url.slice(0, hashIndex); - } - return href + "#" + (typeof to === "string" ? to : createPath(to)); - } - function validateHashLocation(location, to) { - warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")"); - } - return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options); - } - //#endregion - - //////////////////////////////////////////////////////////////////////////////// - //#region UTILS - //////////////////////////////////////////////////////////////////////////////// - - /** - * @private - */ - function invariant(value, message) { - if (value === false || value === null || typeof value === "undefined") { - throw new Error(message); - } - } - function warning(cond, message) { - if (!cond) { - // eslint-disable-next-line no-console - if (typeof console !== "undefined") console.warn(message); - try { - // Welcome to debugging history! - // - // This error is thrown as a convenience, so you can more easily - // find the source for a warning that appears in the console by - // enabling "pause on exceptions" in your JavaScript debugger. - throw new Error(message); - // eslint-disable-next-line no-empty - } catch (e) {} - } - } - function createKey() { - return Math.random().toString(36).substr(2, 8); - } - - /** - * For browser-based histories, we combine the state and key into an object - */ - function getHistoryState(location, index) { - return { - usr: location.state, - key: location.key, - idx: index - }; - } - - /** - * Creates a Location object with a unique key from the given Path - */ - function createLocation(current, to, state, key) { - if (state === void 0) { - state = null; - } - let location = _extends({ - pathname: typeof current === "string" ? current : current.pathname, - search: "", - hash: "" - }, typeof to === "string" ? parsePath(to) : to, { - state, - // TODO: This could be cleaned up. push/replace should probably just take - // full Locations now and avoid the need to run through this flow at all - // But that's a pretty big refactor to the current test suite so going to - // keep as is for the time being and just let any incoming keys take precedence - key: to && to.key || key || createKey() - }); - return location; - } - - /** - * Creates a string URL path from the given pathname, search, and hash components. - */ - function createPath(_ref) { - let { - pathname = "/", - search = "", - hash = "" - } = _ref; - if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search; - if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash; - return pathname; - } - - /** - * Parses a string URL path into its separate pathname, search, and hash components. - */ - function parsePath(path) { - let parsedPath = {}; - if (path) { - let hashIndex = path.indexOf("#"); - if (hashIndex >= 0) { - parsedPath.hash = path.substr(hashIndex); - path = path.substr(0, hashIndex); - } - let searchIndex = path.indexOf("?"); - if (searchIndex >= 0) { - parsedPath.search = path.substr(searchIndex); - path = path.substr(0, searchIndex); - } - if (path) { - parsedPath.pathname = path; - } - } - return parsedPath; - } - function getUrlBasedHistory(getLocation, createHref, validateLocation, options) { - if (options === void 0) { - options = {}; - } - let { - window = document.defaultView, - v5Compat = false - } = options; - let globalHistory = window.history; - let action = Action.Pop; - let listener = null; - let index = getIndex(); - // Index should only be null when we initialize. If not, it's because the - // user called history.pushState or history.replaceState directly, in which - // case we should log a warning as it will result in bugs. - if (index == null) { - index = 0; - globalHistory.replaceState(_extends({}, globalHistory.state, { - idx: index - }), ""); - } - function getIndex() { - let state = globalHistory.state || { - idx: null - }; - return state.idx; - } - function handlePop() { - action = Action.Pop; - let nextIndex = getIndex(); - let delta = nextIndex == null ? null : nextIndex - index; - index = nextIndex; - if (listener) { - listener({ - action, - location: history.location, - delta - }); - } - } - function push(to, state) { - action = Action.Push; - let location = createLocation(history.location, to, state); - if (validateLocation) validateLocation(location, to); - index = getIndex() + 1; - let historyState = getHistoryState(location, index); - let url = history.createHref(location); - - // try...catch because iOS limits us to 100 pushState calls :/ - try { - globalHistory.pushState(historyState, "", url); - } catch (error) { - // If the exception is because `state` can't be serialized, let that throw - // outwards just like a replace call would so the dev knows the cause - // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps - // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal - if (error instanceof DOMException && error.name === "DataCloneError") { - throw error; - } - // They are going to lose state here, but there is no real - // way to warn them about it since the page will refresh... - window.location.assign(url); - } - if (v5Compat && listener) { - listener({ - action, - location: history.location, - delta: 1 - }); - } - } - function replace(to, state) { - action = Action.Replace; - let location = createLocation(history.location, to, state); - if (validateLocation) validateLocation(location, to); - index = getIndex(); - let historyState = getHistoryState(location, index); - let url = history.createHref(location); - globalHistory.replaceState(historyState, "", url); - if (v5Compat && listener) { - listener({ - action, - location: history.location, - delta: 0 - }); - } - } - function createURL(to) { - // window.location.origin is "null" (the literal string value) in Firefox - // under certain conditions, notably when serving from a local HTML file - // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297 - let base = window.location.origin !== "null" ? window.location.origin : window.location.href; - let href = typeof to === "string" ? to : createPath(to); - // Treating this as a full URL will strip any trailing spaces so we need to - // pre-encode them since they might be part of a matching splat param from - // an ancestor route - href = href.replace(/ $/, "%20"); - invariant(base, "No window.location.(origin|href) available to create URL for href: " + href); - return new URL(href, base); - } - let history = { - get action() { - return action; - }, - get location() { - return getLocation(window, globalHistory); - }, - listen(fn) { - if (listener) { - throw new Error("A history only accepts one active listener"); - } - window.addEventListener(PopStateEventType, handlePop); - listener = fn; - return () => { - window.removeEventListener(PopStateEventType, handlePop); - listener = null; - }; - }, - createHref(to) { - return createHref(window, to); - }, - createURL, - encodeLocation(to) { - // Encode a Location the same way window.location would - let url = createURL(to); - return { - pathname: url.pathname, - search: url.search, - hash: url.hash - }; - }, - push, - replace, - go(n) { - return globalHistory.go(n); - } - }; - return history; - } - - //#endregion - - /** - * Map of routeId -> data returned from a loader/action/error - */ - - let ResultType = /*#__PURE__*/function (ResultType) { - ResultType["data"] = "data"; - ResultType["deferred"] = "deferred"; - ResultType["redirect"] = "redirect"; - ResultType["error"] = "error"; - return ResultType; - }({}); - - /** - * Successful result from a loader or action - */ - - /** - * Successful defer() result from a loader or action - */ - - /** - * Redirect result from a loader or action - */ - - /** - * Unsuccessful result from a loader or action - */ - - /** - * Result from a loader or action - potentially successful or unsuccessful - */ - - /** - * Result from a loader or action called via dataStrategy - */ - - /** - * Users can specify either lowercase or uppercase form methods on ``, - * useSubmit(), ``, etc. - */ - - /** - * Active navigation/fetcher form methods are exposed in lowercase on the - * RouterState - */ - - /** - * In v7, active navigation/fetcher form methods are exposed in uppercase on the - * RouterState. This is to align with the normalization done via fetch(). - */ - - // Thanks https://github.com/sindresorhus/type-fest! - - /** - * @private - * Internal interface to pass around for action submissions, not intended for - * external consumption - */ - - /** - * @private - * Arguments passed to route loader/action functions. Same for now but we keep - * this as a private implementation detail in case they diverge in the future. - */ - - // TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers: - // ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs - // Also, make them a type alias instead of an interface - /** - * Arguments passed to loader functions - */ - /** - * Arguments passed to action functions - */ - /** - * Loaders and actions can return anything except `undefined` (`null` is a - * valid return value if there is no data to return). Responses are preferred - * and will ease any future migration to Remix - */ - /** - * Route loader function signature - */ - /** - * Route action function signature - */ - /** - * Arguments passed to shouldRevalidate function - */ - /** - * Route shouldRevalidate function signature. This runs after any submission - * (navigation or fetcher), so we flatten the navigation/fetcher submission - * onto the arguments. It shouldn't matter whether it came from a navigation - * or a fetcher, what really matters is the URLs and the formData since loaders - * have to re-run based on the data models that were potentially mutated. - */ - /** - * Function provided by the framework-aware layers to set `hasErrorBoundary` - * from the framework-aware `errorElement` prop - * - * @deprecated Use `mapRouteProperties` instead - */ - /** - * Function provided by the framework-aware layers to set any framework-specific - * properties from framework-agnostic properties - */ - /** - * Keys we cannot change from within a lazy() function. We spread all other keys - * onto the route. Either they're meaningful to the router, or they'll get - * ignored. - */ - const immutableRouteKeys = new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]); - - /** - * lazy() function to load a route definition, which can add non-matching - * related properties to a route - */ - - /** - * Base RouteObject with common props shared by all types of routes - */ - - /** - * Index routes must not have children - */ - - /** - * Non-index routes may have children, but cannot have index - */ - - /** - * A route object represents a logical route, with (optionally) its child - * routes organized in a tree-like structure. - */ - - /** - * A data route object, which is just a RouteObject with a required unique ID - */ - - // Recursive helper for finding path parameters in the absence of wildcards - - /** - * Examples: - * "/a/b/*" -> "*" - * ":a" -> "a" - * "/a/:b" -> "b" - * "/a/blahblahblah:b" -> "b" - * "/:a/:b" -> "a" | "b" - * "/:a/b/:c/*" -> "a" | "c" | "*" - */ - - // Attempt to parse the given string segment. If it fails, then just return the - // plain string type as a default fallback. Otherwise, return the union of the - // parsed string literals that were referenced as dynamic segments in the route. - /** - * The parameters that were parsed from the URL path. - */ - /** - * A RouteMatch contains info about how a route matched a URL. - */ - function isIndexRoute(route) { - return route.index === true; - } - - // Walk the route tree generating unique IDs where necessary, so we are working - // solely with AgnosticDataRouteObject's within the Router - function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) { - if (parentPath === void 0) { - parentPath = []; - } - if (manifest === void 0) { - manifest = {}; - } - return routes.map((route, index) => { - let treePath = [...parentPath, index]; - let id = typeof route.id === "string" ? route.id : treePath.join("-"); - invariant(route.index !== true || !route.children, "Cannot specify children on an index route"); - invariant(!manifest[id], "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages"); - if (isIndexRoute(route)) { - let indexRoute = _extends({}, route, mapRouteProperties(route), { - id - }); - manifest[id] = indexRoute; - return indexRoute; - } else { - let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), { - id, - children: undefined - }); - manifest[id] = pathOrLayoutRoute; - if (route.children) { - pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest); - } - return pathOrLayoutRoute; - } - }); - } - - /** - * Matches the given routes to a location and returns the match data. - * - * @see https://reactrouter.com/utils/match-routes - */ - function matchRoutes(routes, locationArg, basename) { - if (basename === void 0) { - basename = "/"; - } - let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg; - let pathname = stripBasename(location.pathname || "/", basename); - if (pathname == null) { - return null; - } - let branches = flattenRoutes(routes); - rankRouteBranches(branches); - let matches = null; - for (let i = 0; matches == null && i < branches.length; ++i) { - // Incoming pathnames are generally encoded from either window.location - // or from router.navigate, but we want to match against the unencoded - // paths in the route definitions. Memory router locations won't be - // encoded here but there also shouldn't be anything to decode so this - // should be a safe operation. This avoids needing matchRoutes to be - // history-aware. - let decoded = decodePath(pathname); - matches = matchRouteBranch(branches[i], decoded); - } - return matches; - } - function convertRouteMatchToUiMatch(match, loaderData) { - let { - route, - pathname, - params - } = match; - return { - id: route.id, - pathname, - params, - data: loaderData[route.id], - handle: route.handle - }; - } - function flattenRoutes(routes, branches, parentsMeta, parentPath) { - if (branches === void 0) { - branches = []; - } - if (parentsMeta === void 0) { - parentsMeta = []; - } - if (parentPath === void 0) { - parentPath = ""; - } - let flattenRoute = (route, index, relativePath) => { - let meta = { - relativePath: relativePath === undefined ? route.path || "" : relativePath, - caseSensitive: route.caseSensitive === true, - childrenIndex: index, - route - }; - if (meta.relativePath.startsWith("/")) { - invariant(meta.relativePath.startsWith(parentPath), "Absolute route path \"" + meta.relativePath + "\" nested under path " + ("\"" + parentPath + "\" is not valid. An absolute child route path ") + "must start with the combined path of all its parent routes."); - meta.relativePath = meta.relativePath.slice(parentPath.length); - } - let path = joinPaths([parentPath, meta.relativePath]); - let routesMeta = parentsMeta.concat(meta); - - // Add the children before adding this route to the array, so we traverse the - // route tree depth-first and child routes appear before their parents in - // the "flattened" version. - if (route.children && route.children.length > 0) { - invariant( - // Our types know better, but runtime JS may not! - // @ts-expect-error - route.index !== true, "Index routes must not have child routes. Please remove " + ("all child routes from route path \"" + path + "\".")); - flattenRoutes(route.children, branches, routesMeta, path); - } - - // Routes without a path shouldn't ever match by themselves unless they are - // index routes, so don't add them to the list of possible branches. - if (route.path == null && !route.index) { - return; - } - branches.push({ - path, - score: computeScore(path, route.index), - routesMeta - }); - }; - routes.forEach((route, index) => { - var _route$path; - // coarse-grain check for optional params - if (route.path === "" || !((_route$path = route.path) != null && _route$path.includes("?"))) { - flattenRoute(route, index); - } else { - for (let exploded of explodeOptionalSegments(route.path)) { - flattenRoute(route, index, exploded); - } - } - }); - return branches; - } - - /** - * Computes all combinations of optional path segments for a given path, - * excluding combinations that are ambiguous and of lower priority. - * - * For example, `/one/:two?/three/:four?/:five?` explodes to: - * - `/one/three` - * - `/one/:two/three` - * - `/one/three/:four` - * - `/one/three/:five` - * - `/one/:two/three/:four` - * - `/one/:two/three/:five` - * - `/one/three/:four/:five` - * - `/one/:two/three/:four/:five` - */ - function explodeOptionalSegments(path) { - let segments = path.split("/"); - if (segments.length === 0) return []; - let [first, ...rest] = segments; - - // Optional path segments are denoted by a trailing `?` - let isOptional = first.endsWith("?"); - // Compute the corresponding required segment: `foo?` -> `foo` - let required = first.replace(/\?$/, ""); - if (rest.length === 0) { - // Intepret empty string as omitting an optional segment - // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three` - return isOptional ? [required, ""] : [required]; - } - let restExploded = explodeOptionalSegments(rest.join("/")); - let result = []; - - // All child paths with the prefix. Do this for all children before the - // optional version for all children, so we get consistent ordering where the - // parent optional aspect is preferred as required. Otherwise, we can get - // child sections interspersed where deeper optional segments are higher than - // parent optional segments, where for example, /:two would explode _earlier_ - // then /:one. By always including the parent as required _for all children_ - // first, we avoid this issue - result.push(...restExploded.map(subpath => subpath === "" ? required : [required, subpath].join("/"))); - - // Then, if this is an optional value, add all child versions without - if (isOptional) { - result.push(...restExploded); - } - - // for absolute paths, ensure `/` instead of empty segment - return result.map(exploded => path.startsWith("/") && exploded === "" ? "/" : exploded); - } - function rankRouteBranches(branches) { - branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first - : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex))); - } - const paramRe = /^:[\w-]+$/; - const dynamicSegmentValue = 3; - const indexRouteValue = 2; - const emptySegmentValue = 1; - const staticSegmentValue = 10; - const splatPenalty = -2; - const isSplat = s => s === "*"; - function computeScore(path, index) { - let segments = path.split("/"); - let initialScore = segments.length; - if (segments.some(isSplat)) { - initialScore += splatPenalty; - } - if (index) { - initialScore += indexRouteValue; - } - return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore); - } - function compareIndexes(a, b) { - let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]); - return siblings ? - // If two routes are siblings, we should try to match the earlier sibling - // first. This allows people to have fine-grained control over the matching - // behavior by simply putting routes with identical paths in the order they - // want them tried. - a[a.length - 1] - b[b.length - 1] : - // Otherwise, it doesn't really make sense to rank non-siblings by index, - // so they sort equally. - 0; - } - function matchRouteBranch(branch, pathname) { - let { - routesMeta - } = branch; - let matchedParams = {}; - let matchedPathname = "/"; - let matches = []; - for (let i = 0; i < routesMeta.length; ++i) { - let meta = routesMeta[i]; - let end = i === routesMeta.length - 1; - let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/"; - let match = matchPath({ - path: meta.relativePath, - caseSensitive: meta.caseSensitive, - end - }, remainingPathname); - if (!match) return null; - Object.assign(matchedParams, match.params); - let route = meta.route; - matches.push({ - // TODO: Can this as be avoided? - params: matchedParams, - pathname: joinPaths([matchedPathname, match.pathname]), - pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])), - route - }); - if (match.pathnameBase !== "/") { - matchedPathname = joinPaths([matchedPathname, match.pathnameBase]); - } - } - return matches; - } - - /** - * Returns a path with params interpolated. - * - * @see https://reactrouter.com/utils/generate-path - */ - function generatePath(originalPath, params) { - if (params === void 0) { - params = {}; - } - let path = originalPath; - if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) { - warning(false, "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\".")); - path = path.replace(/\*$/, "/*"); - } - - // ensure `/` is added at the beginning if the path is absolute - const prefix = path.startsWith("/") ? "/" : ""; - const stringify = p => p == null ? "" : typeof p === "string" ? p : String(p); - const segments = path.split(/\/+/).map((segment, index, array) => { - const isLastSegment = index === array.length - 1; - - // only apply the splat if it's the last segment - if (isLastSegment && segment === "*") { - const star = "*"; - // Apply the splat - return stringify(params[star]); - } - const keyMatch = segment.match(/^:([\w-]+)(\??)$/); - if (keyMatch) { - const [, key, optional] = keyMatch; - let param = params[key]; - invariant(optional === "?" || param != null, "Missing \":" + key + "\" param"); - return stringify(param); - } - - // Remove any optional markers from optional static segments - return segment.replace(/\?$/g, ""); - }) - // Remove empty segments - .filter(segment => !!segment); - return prefix + segments.join("/"); - } - - /** - * A PathPattern is used to match on some portion of a URL pathname. - */ - - /** - * A PathMatch contains info about how a PathPattern matched on a URL pathname. - */ - - /** - * Performs pattern matching on a URL pathname and returns information about - * the match. - * - * @see https://reactrouter.com/utils/match-path - */ - function matchPath(pattern, pathname) { - if (typeof pattern === "string") { - pattern = { - path: pattern, - caseSensitive: false, - end: true - }; - } - let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end); - let match = pathname.match(matcher); - if (!match) return null; - let matchedPathname = match[0]; - let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1"); - let captureGroups = match.slice(1); - let params = compiledParams.reduce((memo, _ref, index) => { - let { - paramName, - isOptional - } = _ref; - // We need to compute the pathnameBase here using the raw splat value - // instead of using params["*"] later because it will be decoded then - if (paramName === "*") { - let splatValue = captureGroups[index] || ""; - pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1"); - } - const value = captureGroups[index]; - if (isOptional && !value) { - memo[paramName] = undefined; - } else { - memo[paramName] = (value || "").replace(/%2F/g, "/"); - } - return memo; - }, {}); - return { - params, - pathname: matchedPathname, - pathnameBase, - pattern - }; - } - function compilePath(path, caseSensitive, end) { - if (caseSensitive === void 0) { - caseSensitive = false; - } - if (end === void 0) { - end = true; - } - warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\".")); - let params = []; - let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below - .replace(/^\/*/, "/") // Make sure it has a leading / - .replace(/[\\.*+^${}|()[\]]/g, "\\$&") // Escape special regex chars - .replace(/\/:([\w-]+)(\?)?/g, (_, paramName, isOptional) => { - params.push({ - paramName, - isOptional: isOptional != null - }); - return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)"; - }); - if (path.endsWith("*")) { - params.push({ - paramName: "*" - }); - regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest - : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"] - } else if (end) { - // When matching to the end, ignore trailing slashes - regexpSource += "\\/*$"; - } else if (path !== "" && path !== "/") { - // If our path is non-empty and contains anything beyond an initial slash, - // then we have _some_ form of path in our regex, so we should expect to - // match only if we find the end of this path segment. Look for an optional - // non-captured trailing slash (to match a portion of the URL) or the end - // of the path (if we've matched to the end). We used to do this with a - // word boundary but that gives false positives on routes like - // /user-preferences since `-` counts as a word boundary. - regexpSource += "(?:(?=\\/|$))"; - } else ; - let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i"); - return [matcher, params]; - } - function decodePath(value) { - try { - return value.split("/").map(v => decodeURIComponent(v).replace(/\//g, "%2F")).join("/"); - } catch (error) { - warning(false, "The URL path \"" + value + "\" could not be decoded because it is is a " + "malformed URL segment. This is probably due to a bad percent " + ("encoding (" + error + ").")); - return value; - } - } - - /** - * @private - */ - function stripBasename(pathname, basename) { - if (basename === "/") return pathname; - if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) { - return null; - } - - // We want to leave trailing slash behavior in the user's control, so if they - // specify a basename with a trailing slash, we should support it - let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length; - let nextChar = pathname.charAt(startIndex); - if (nextChar && nextChar !== "/") { - // pathname does not start with basename/ - return null; - } - return pathname.slice(startIndex) || "/"; - } - - /** - * Returns a resolved path object relative to the given pathname. - * - * @see https://reactrouter.com/utils/resolve-path - */ - function resolvePath(to, fromPathname) { - if (fromPathname === void 0) { - fromPathname = "/"; - } - let { - pathname: toPathname, - search = "", - hash = "" - } = typeof to === "string" ? parsePath(to) : to; - let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname; - return { - pathname, - search: normalizeSearch(search), - hash: normalizeHash(hash) - }; - } - function resolvePathname(relativePath, fromPathname) { - let segments = fromPathname.replace(/\/+$/, "").split("/"); - let relativeSegments = relativePath.split("/"); - relativeSegments.forEach(segment => { - if (segment === "..") { - // Keep the root "" segment so the pathname starts at / - if (segments.length > 1) segments.pop(); - } else if (segment !== ".") { - segments.push(segment); - } - }); - return segments.length > 1 ? segments.join("/") : "/"; - } - function getInvalidPathError(char, field, dest, path) { - return "Cannot include a '" + char + "' character in a manually specified " + ("`to." + field + "` field [" + JSON.stringify(path) + "]. Please separate it out to the ") + ("`to." + dest + "` field. Alternatively you may provide the full path as ") + "a string in and the router will parse it for you."; - } - - /** - * @private - * - * When processing relative navigation we want to ignore ancestor routes that - * do not contribute to the path, such that index/pathless layout routes don't - * interfere. - * - * For example, when moving a route element into an index route and/or a - * pathless layout route, relative link behavior contained within should stay - * the same. Both of the following examples should link back to the root: - * - * - * - * - * - * - * - * }> // <-- Does not contribute - * // <-- Does not contribute - * - * - */ - function getPathContributingMatches(matches) { - return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0); - } - - // Return the array of pathnames for the current route matches - used to - // generate the routePathnames input for resolveTo() - function getResolveToMatches(matches, v7_relativeSplatPath) { - let pathMatches = getPathContributingMatches(matches); - - // When v7_relativeSplatPath is enabled, use the full pathname for the leaf - // match so we include splat values for "." links. See: - // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329 - if (v7_relativeSplatPath) { - return pathMatches.map((match, idx) => idx === matches.length - 1 ? match.pathname : match.pathnameBase); - } - return pathMatches.map(match => match.pathnameBase); - } - - /** - * @private - */ - function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) { - if (isPathRelative === void 0) { - isPathRelative = false; - } - let to; - if (typeof toArg === "string") { - to = parsePath(toArg); - } else { - to = _extends({}, toArg); - invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to)); - invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to)); - invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to)); - } - let isEmptyPath = toArg === "" || to.pathname === ""; - let toPathname = isEmptyPath ? "/" : to.pathname; - let from; - - // Routing is relative to the current pathname if explicitly requested. - // - // If a pathname is explicitly provided in `to`, it should be relative to the - // route context. This is explained in `Note on `` values` in our - // migration guide from v5 as a means of disambiguation between `to` values - // that begin with `/` and those that do not. However, this is problematic for - // `to` values that do not provide a pathname. `to` can simply be a search or - // hash string, in which case we should assume that the navigation is relative - // to the current location's pathname and *not* the route pathname. - if (toPathname == null) { - from = locationPathname; - } else { - let routePathnameIndex = routePathnames.length - 1; - - // With relative="route" (the default), each leading .. segment means - // "go up one route" instead of "go up one URL segment". This is a key - // difference from how works and a major reason we call this a - // "to" value instead of a "href". - if (!isPathRelative && toPathname.startsWith("..")) { - let toSegments = toPathname.split("/"); - while (toSegments[0] === "..") { - toSegments.shift(); - routePathnameIndex -= 1; - } - to.pathname = toSegments.join("/"); - } - from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/"; - } - let path = resolvePath(to, from); - - // Ensure the pathname has a trailing slash if the original "to" had one - let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/"); - // Or if this was a link to the current path which has a trailing slash - let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/"); - if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) { - path.pathname += "/"; - } - return path; - } - - /** - * @private - */ - function getToPathname(to) { - // Empty strings should be treated the same as / paths - return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname; - } - - /** - * @private - */ - const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/"); - - /** - * @private - */ - const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/"); - - /** - * @private - */ - const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search; - - /** - * @private - */ - const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash; - /** - * This is a shortcut for creating `application/json` responses. Converts `data` - * to JSON and sets the `Content-Type` header. - */ - const json = function json(data, init) { - if (init === void 0) { - init = {}; - } - let responseInit = typeof init === "number" ? { - status: init - } : init; - let headers = new Headers(responseInit.headers); - if (!headers.has("Content-Type")) { - headers.set("Content-Type", "application/json; charset=utf-8"); - } - return new Response(JSON.stringify(data), _extends({}, responseInit, { - headers - })); - }; - class AbortedDeferredError extends Error {} - class DeferredData { - constructor(data, responseInit) { - this.pendingKeysSet = new Set(); - this.subscribers = new Set(); - this.deferredKeys = []; - invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects"); - - // Set up an AbortController + Promise we can race against to exit early - // cancellation - let reject; - this.abortPromise = new Promise((_, r) => reject = r); - this.controller = new AbortController(); - let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted")); - this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort); - this.controller.signal.addEventListener("abort", onAbort); - this.data = Object.entries(data).reduce((acc, _ref2) => { - let [key, value] = _ref2; - return Object.assign(acc, { - [key]: this.trackPromise(key, value) - }); - }, {}); - if (this.done) { - // All incoming values were resolved - this.unlistenAbortSignal(); - } - this.init = responseInit; - } - trackPromise(key, value) { - if (!(value instanceof Promise)) { - return value; - } - this.deferredKeys.push(key); - this.pendingKeysSet.add(key); - - // We store a little wrapper promise that will be extended with - // _data/_error props upon resolve/reject - let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error)); - - // Register rejection listeners to avoid uncaught promise rejections on - // errors or aborted deferred values - promise.catch(() => {}); - Object.defineProperty(promise, "_tracked", { - get: () => true - }); - return promise; - } - onSettle(promise, key, error, data) { - if (this.controller.signal.aborted && error instanceof AbortedDeferredError) { - this.unlistenAbortSignal(); - Object.defineProperty(promise, "_error", { - get: () => error - }); - return Promise.reject(error); - } - this.pendingKeysSet.delete(key); - if (this.done) { - // Nothing left to abort! - this.unlistenAbortSignal(); - } - - // If the promise was resolved/rejected with undefined, we'll throw an error as you - // should always resolve with a value or null - if (error === undefined && data === undefined) { - let undefinedError = new Error("Deferred data for key \"" + key + "\" resolved/rejected with `undefined`, " + "you must resolve/reject with a value or `null`."); - Object.defineProperty(promise, "_error", { - get: () => undefinedError - }); - this.emit(false, key); - return Promise.reject(undefinedError); - } - if (data === undefined) { - Object.defineProperty(promise, "_error", { - get: () => error - }); - this.emit(false, key); - return Promise.reject(error); - } - Object.defineProperty(promise, "_data", { - get: () => data - }); - this.emit(false, key); - return data; - } - emit(aborted, settledKey) { - this.subscribers.forEach(subscriber => subscriber(aborted, settledKey)); - } - subscribe(fn) { - this.subscribers.add(fn); - return () => this.subscribers.delete(fn); - } - cancel() { - this.controller.abort(); - this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k)); - this.emit(true); - } - async resolveData(signal) { - let aborted = false; - if (!this.done) { - let onAbort = () => this.cancel(); - signal.addEventListener("abort", onAbort); - aborted = await new Promise(resolve => { - this.subscribe(aborted => { - signal.removeEventListener("abort", onAbort); - if (aborted || this.done) { - resolve(aborted); - } - }); - }); - } - return aborted; - } - get done() { - return this.pendingKeysSet.size === 0; - } - get unwrappedData() { - invariant(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds"); - return Object.entries(this.data).reduce((acc, _ref3) => { - let [key, value] = _ref3; - return Object.assign(acc, { - [key]: unwrapTrackedPromise(value) - }); - }, {}); - } - get pendingKeys() { - return Array.from(this.pendingKeysSet); - } - } - function isTrackedPromise(value) { - return value instanceof Promise && value._tracked === true; - } - function unwrapTrackedPromise(value) { - if (!isTrackedPromise(value)) { - return value; - } - if (value._error) { - throw value._error; - } - return value._data; - } - const defer = function defer(data, init) { - if (init === void 0) { - init = {}; - } - let responseInit = typeof init === "number" ? { - status: init - } : init; - return new DeferredData(data, responseInit); - }; - /** - * A redirect response. Sets the status code and the `Location` header. - * Defaults to "302 Found". - */ - const redirect = function redirect(url, init) { - if (init === void 0) { - init = 302; - } - let responseInit = init; - if (typeof responseInit === "number") { - responseInit = { - status: responseInit - }; - } else if (typeof responseInit.status === "undefined") { - responseInit.status = 302; - } - let headers = new Headers(responseInit.headers); - headers.set("Location", url); - return new Response(null, _extends({}, responseInit, { - headers - })); - }; - - /** - * A redirect response that will force a document reload to the new location. - * Sets the status code and the `Location` header. - * Defaults to "302 Found". - */ - const redirectDocument = (url, init) => { - let response = redirect(url, init); - response.headers.set("X-Remix-Reload-Document", "true"); - return response; - }; - /** - * @private - * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies - * - * We don't export the class for public use since it's an implementation - * detail, but we export the interface above so folks can build their own - * abstractions around instances via isRouteErrorResponse() - */ - class ErrorResponseImpl { - constructor(status, statusText, data, internal) { - if (internal === void 0) { - internal = false; - } - this.status = status; - this.statusText = statusText || ""; - this.internal = internal; - if (data instanceof Error) { - this.data = data.toString(); - this.error = data; - } else { - this.data = data; - } - } - } - - /** - * Check if the given error is an ErrorResponse generated from a 4xx/5xx - * Response thrown from an action/loader - */ - function isRouteErrorResponse(error) { - return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error; - } - - //////////////////////////////////////////////////////////////////////////////// - //#region Types and Constants - //////////////////////////////////////////////////////////////////////////////// - - /** - * A Router instance manages all navigation and data loading/mutations - */ - /** - * State maintained internally by the router. During a navigation, all states - * reflect the the "old" location unless otherwise noted. - */ - /** - * Data that can be passed into hydrate a Router from SSR - */ - /** - * Future flags to toggle new feature behavior - */ - /** - * Initialization options for createRouter - */ - /** - * State returned from a server-side query() call - */ - /** - * A StaticHandler instance manages a singular SSR navigation/fetch event - */ - /** - * Subscriber function signature for changes to router state - */ - /** - * Function signature for determining the key to be used in scroll restoration - * for a given location - */ - /** - * Function signature for determining the current scroll position - */ - // Allowed for any navigation or fetch - // Only allowed for navigations - // Only allowed for submission navigations - /** - * Options for a navigate() call for a normal (non-submission) navigation - */ - /** - * Options for a navigate() call for a submission navigation - */ - /** - * Options to pass to navigate() for a navigation - */ - /** - * Options for a fetch() load - */ - /** - * Options for a fetch() submission - */ - /** - * Options to pass to fetch() - */ - /** - * Potential states for state.navigation - */ - /** - * Potential states for fetchers - */ - /** - * Cached info for active fetcher.load() instances so they can participate - * in revalidation - */ - /** - * Identified fetcher.load() calls that need to be revalidated - */ - const validMutationMethodsArr = ["post", "put", "patch", "delete"]; - const validMutationMethods = new Set(validMutationMethodsArr); - const validRequestMethodsArr = ["get", ...validMutationMethodsArr]; - const validRequestMethods = new Set(validRequestMethodsArr); - const redirectStatusCodes = new Set([301, 302, 303, 307, 308]); - const redirectPreserveMethodStatusCodes = new Set([307, 308]); - const IDLE_NAVIGATION = { - state: "idle", - location: undefined, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined - }; - const IDLE_FETCHER = { - state: "idle", - data: undefined, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined - }; - const IDLE_BLOCKER = { - state: "unblocked", - proceed: undefined, - reset: undefined, - location: undefined - }; - const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i; - const defaultMapRouteProperties = route => ({ - hasErrorBoundary: Boolean(route.hasErrorBoundary) - }); - const TRANSITIONS_STORAGE_KEY = "remix-router-transitions"; - - //#endregion - - //////////////////////////////////////////////////////////////////////////////// - //#region createRouter - //////////////////////////////////////////////////////////////////////////////// - - /** - * Create a router and listen to history POP navigations - */ - function createRouter(init) { - const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : undefined; - const isBrowser = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined"; - const isServer = !isBrowser; - invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter"); - let mapRouteProperties; - if (init.mapRouteProperties) { - mapRouteProperties = init.mapRouteProperties; - } else if (init.detectErrorBoundary) { - // If they are still using the deprecated version, wrap it with the new API - let detectErrorBoundary = init.detectErrorBoundary; - mapRouteProperties = route => ({ - hasErrorBoundary: detectErrorBoundary(route) - }); - } else { - mapRouteProperties = defaultMapRouteProperties; - } - - // Routes keyed by ID - let manifest = {}; - // Routes in tree format for matching - let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest); - let inFlightDataRoutes; - let basename = init.basename || "/"; - let dataStrategyImpl = init.unstable_dataStrategy || defaultDataStrategy; - // Config driven behavior flags - let future = _extends({ - v7_fetcherPersist: false, - v7_normalizeFormMethod: false, - v7_partialHydration: false, - v7_prependBasename: false, - v7_relativeSplatPath: false, - unstable_skipActionErrorRevalidation: false - }, init.future); - // Cleanup function for history - let unlistenHistory = null; - // Externally-provided functions to call on all state changes - let subscribers = new Set(); - // Externally-provided object to hold scroll restoration locations during routing - let savedScrollPositions = null; - // Externally-provided function to get scroll restoration keys - let getScrollRestorationKey = null; - // Externally-provided function to get current scroll position - let getScrollPosition = null; - // One-time flag to control the initial hydration scroll restoration. Because - // we don't get the saved positions from until _after_ - // the initial render, we need to manually trigger a separate updateState to - // send along the restoreScrollPosition - // Set to true if we have `hydrationData` since we assume we were SSR'd and that - // SSR did the initial scroll restoration. - let initialScrollRestored = init.hydrationData != null; - let initialMatches = matchRoutes(dataRoutes, init.history.location, basename); - let initialErrors = null; - if (initialMatches == null) { - // If we do not match a user-provided-route, fall back to the root - // to allow the error boundary to take over - let error = getInternalRouterError(404, { - pathname: init.history.location.pathname - }); - let { - matches, - route - } = getShortCircuitMatches(dataRoutes); - initialMatches = matches; - initialErrors = { - [route.id]: error - }; - } - let initialized; - let hasLazyRoutes = initialMatches.some(m => m.route.lazy); - let hasLoaders = initialMatches.some(m => m.route.loader); - if (hasLazyRoutes) { - // All initialMatches need to be loaded before we're ready. If we have lazy - // functions around still then we'll need to run them in initialize() - initialized = false; - } else if (!hasLoaders) { - // If we've got no loaders to run, then we're good to go - initialized = true; - } else if (future.v7_partialHydration) { - // If partial hydration is enabled, we're initialized so long as we were - // provided with hydrationData for every route with a loader, and no loaders - // were marked for explicit hydration - let loaderData = init.hydrationData ? init.hydrationData.loaderData : null; - let errors = init.hydrationData ? init.hydrationData.errors : null; - let isRouteInitialized = m => { - // No loader, nothing to initialize - if (!m.route.loader) { - return true; - } - // Explicitly opting-in to running on hydration - if (typeof m.route.loader === "function" && m.route.loader.hydrate === true) { - return false; - } - // Otherwise, initialized if hydrated with data or an error - return loaderData && loaderData[m.route.id] !== undefined || errors && errors[m.route.id] !== undefined; - }; - - // If errors exist, don't consider routes below the boundary - if (errors) { - let idx = initialMatches.findIndex(m => errors[m.route.id] !== undefined); - initialized = initialMatches.slice(0, idx + 1).every(isRouteInitialized); - } else { - initialized = initialMatches.every(isRouteInitialized); - } - } else { - // Without partial hydration - we're initialized if we were provided any - // hydrationData - which is expected to be complete - initialized = init.hydrationData != null; - } - let router; - let state = { - historyAction: init.history.action, - location: init.history.location, - matches: initialMatches, - initialized, - navigation: IDLE_NAVIGATION, - // Don't restore on initial updateState() if we were SSR'd - restoreScrollPosition: init.hydrationData != null ? false : null, - preventScrollReset: false, - revalidation: "idle", - loaderData: init.hydrationData && init.hydrationData.loaderData || {}, - actionData: init.hydrationData && init.hydrationData.actionData || null, - errors: init.hydrationData && init.hydrationData.errors || initialErrors, - fetchers: new Map(), - blockers: new Map() - }; - - // -- Stateful internal variables to manage navigations -- - // Current navigation in progress (to be committed in completeNavigation) - let pendingAction = Action.Pop; - - // Should the current navigation prevent the scroll reset if scroll cannot - // be restored? - let pendingPreventScrollReset = false; - - // AbortController for the active navigation - let pendingNavigationController; - - // Should the current navigation enable document.startViewTransition? - let pendingViewTransitionEnabled = false; - - // Store applied view transitions so we can apply them on POP - let appliedViewTransitions = new Map(); - - // Cleanup function for persisting applied transitions to sessionStorage - let removePageHideEventListener = null; - - // We use this to avoid touching history in completeNavigation if a - // revalidation is entirely uninterrupted - let isUninterruptedRevalidation = false; - - // Use this internal flag to force revalidation of all loaders: - // - submissions (completed or interrupted) - // - useRevalidator() - // - X-Remix-Revalidate (from redirect) - let isRevalidationRequired = false; - - // Use this internal array to capture routes that require revalidation due - // to a cancelled deferred on action submission - let cancelledDeferredRoutes = []; - - // Use this internal array to capture fetcher loads that were cancelled by an - // action navigation and require revalidation - let cancelledFetcherLoads = []; - - // AbortControllers for any in-flight fetchers - let fetchControllers = new Map(); - - // Track loads based on the order in which they started - let incrementingLoadId = 0; - - // Track the outstanding pending navigation data load to be compared against - // the globally incrementing load when a fetcher load lands after a completed - // navigation - let pendingNavigationLoadId = -1; - - // Fetchers that triggered data reloads as a result of their actions - let fetchReloadIds = new Map(); - - // Fetchers that triggered redirect navigations - let fetchRedirectIds = new Set(); - - // Most recent href/match for fetcher.load calls for fetchers - let fetchLoadMatches = new Map(); - - // Ref-count mounted fetchers so we know when it's ok to clean them up - let activeFetchers = new Map(); - - // Fetchers that have requested a delete when using v7_fetcherPersist, - // they'll be officially removed after they return to idle - let deletedFetchers = new Set(); - - // Store DeferredData instances for active route matches. When a - // route loader returns defer() we stick one in here. Then, when a nested - // promise resolves we update loaderData. If a new navigation starts we - // cancel active deferreds for eliminated routes. - let activeDeferreds = new Map(); - - // Store blocker functions in a separate Map outside of router state since - // we don't need to update UI state if they change - let blockerFunctions = new Map(); - - // Flag to ignore the next history update, so we can revert the URL change on - // a POP navigation that was blocked by the user without touching router state - let ignoreNextHistoryUpdate = false; - - // Initialize the router, all side effects should be kicked off from here. - // Implemented as a Fluent API for ease of: - // let router = createRouter(init).initialize(); - function initialize() { - // If history informs us of a POP navigation, start the navigation but do not update - // state. We'll update our own state once the navigation completes - unlistenHistory = init.history.listen(_ref => { - let { - action: historyAction, - location, - delta - } = _ref; - // Ignore this event if it was just us resetting the URL from a - // blocked POP navigation - if (ignoreNextHistoryUpdate) { - ignoreNextHistoryUpdate = false; - return; - } - warning(blockerFunctions.size === 0 || delta != null, "You are trying to use a blocker on a POP navigation to a location " + "that was not created by @remix-run/router. This will fail silently in " + "production. This can happen if you are navigating outside the router " + "via `window.history.pushState`/`window.location.hash` instead of using " + "router navigation APIs. This can also happen if you are using " + "createHashRouter and the user manually changes the URL."); - let blockerKey = shouldBlockNavigation({ - currentLocation: state.location, - nextLocation: location, - historyAction - }); - if (blockerKey && delta != null) { - // Restore the URL to match the current UI, but don't update router state - ignoreNextHistoryUpdate = true; - init.history.go(delta * -1); - - // Put the blocker into a blocked state - updateBlocker(blockerKey, { - state: "blocked", - location, - proceed() { - updateBlocker(blockerKey, { - state: "proceeding", - proceed: undefined, - reset: undefined, - location - }); - // Re-do the same POP navigation we just blocked - init.history.go(delta); - }, - reset() { - let blockers = new Map(state.blockers); - blockers.set(blockerKey, IDLE_BLOCKER); - updateState({ - blockers - }); - } - }); - return; - } - return startNavigation(historyAction, location); - }); - if (isBrowser) { - // FIXME: This feels gross. How can we cleanup the lines between - // scrollRestoration/appliedTransitions persistance? - restoreAppliedTransitions(routerWindow, appliedViewTransitions); - let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions); - routerWindow.addEventListener("pagehide", _saveAppliedTransitions); - removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions); - } - - // Kick off initial data load if needed. Use Pop to avoid modifying history - // Note we don't do any handling of lazy here. For SPA's it'll get handled - // in the normal navigation flow. For SSR it's expected that lazy modules are - // resolved prior to router creation since we can't go into a fallbackElement - // UI for SSR'd apps - if (!state.initialized) { - startNavigation(Action.Pop, state.location, { - initialHydration: true - }); - } - return router; - } - - // Clean up a router and it's side effects - function dispose() { - if (unlistenHistory) { - unlistenHistory(); - } - if (removePageHideEventListener) { - removePageHideEventListener(); - } - subscribers.clear(); - pendingNavigationController && pendingNavigationController.abort(); - state.fetchers.forEach((_, key) => deleteFetcher(key)); - state.blockers.forEach((_, key) => deleteBlocker(key)); - } - - // Subscribe to state updates for the router - function subscribe(fn) { - subscribers.add(fn); - return () => subscribers.delete(fn); - } - - // Update our state and notify the calling context of the change - function updateState(newState, opts) { - if (opts === void 0) { - opts = {}; - } - state = _extends({}, state, newState); - - // Prep fetcher cleanup so we can tell the UI which fetcher data entries - // can be removed - let completedFetchers = []; - let deletedFetchersKeys = []; - if (future.v7_fetcherPersist) { - state.fetchers.forEach((fetcher, key) => { - if (fetcher.state === "idle") { - if (deletedFetchers.has(key)) { - // Unmounted from the UI and can be totally removed - deletedFetchersKeys.push(key); - } else { - // Returned to idle but still mounted in the UI, so semi-remains for - // revalidations and such - completedFetchers.push(key); - } - } - }); - } - - // Iterate over a local copy so that if flushSync is used and we end up - // removing and adding a new subscriber due to the useCallback dependencies, - // we don't get ourselves into a loop calling the new subscriber immediately - [...subscribers].forEach(subscriber => subscriber(state, { - deletedFetchers: deletedFetchersKeys, - unstable_viewTransitionOpts: opts.viewTransitionOpts, - unstable_flushSync: opts.flushSync === true - })); - - // Remove idle fetchers from state since we only care about in-flight fetchers. - if (future.v7_fetcherPersist) { - completedFetchers.forEach(key => state.fetchers.delete(key)); - deletedFetchersKeys.forEach(key => deleteFetcher(key)); - } - } - - // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION - // and setting state.[historyAction/location/matches] to the new route. - // - Location is a required param - // - Navigation will always be set to IDLE_NAVIGATION - // - Can pass any other state in newState - function completeNavigation(location, newState, _temp) { - var _location$state, _location$state2; - let { - flushSync - } = _temp === void 0 ? {} : _temp; - // Deduce if we're in a loading/actionReload state: - // - We have committed actionData in the store - // - The current navigation was a mutation submission - // - We're past the submitting state and into the loading state - // - The location being loaded is not the result of a redirect - let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true; - let actionData; - if (newState.actionData) { - if (Object.keys(newState.actionData).length > 0) { - actionData = newState.actionData; - } else { - // Empty actionData -> clear prior actionData due to an action error - actionData = null; - } - } else if (isActionReload) { - // Keep the current data if we're wrapping up the action reload - actionData = state.actionData; - } else { - // Clear actionData on any other completed navigations - actionData = null; - } - - // Always preserve any existing loaderData from re-used routes - let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData; - - // On a successful navigation we can assume we got through all blockers - // so we can start fresh - let blockers = state.blockers; - if (blockers.size > 0) { - blockers = new Map(blockers); - blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER)); - } - - // Always respect the user flag. Otherwise don't reset on mutation - // submission navigations unless they redirect - let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true; - if (inFlightDataRoutes) { - dataRoutes = inFlightDataRoutes; - inFlightDataRoutes = undefined; - } - if (isUninterruptedRevalidation) ; else if (pendingAction === Action.Pop) ; else if (pendingAction === Action.Push) { - init.history.push(location, location.state); - } else if (pendingAction === Action.Replace) { - init.history.replace(location, location.state); - } - let viewTransitionOpts; - - // On POP, enable transitions if they were enabled on the original navigation - if (pendingAction === Action.Pop) { - // Forward takes precedence so they behave like the original navigation - let priorPaths = appliedViewTransitions.get(state.location.pathname); - if (priorPaths && priorPaths.has(location.pathname)) { - viewTransitionOpts = { - currentLocation: state.location, - nextLocation: location - }; - } else if (appliedViewTransitions.has(location.pathname)) { - // If we don't have a previous forward nav, assume we're popping back to - // the new location and enable if that location previously enabled - viewTransitionOpts = { - currentLocation: location, - nextLocation: state.location - }; - } - } else if (pendingViewTransitionEnabled) { - // Store the applied transition on PUSH/REPLACE - let toPaths = appliedViewTransitions.get(state.location.pathname); - if (toPaths) { - toPaths.add(location.pathname); - } else { - toPaths = new Set([location.pathname]); - appliedViewTransitions.set(state.location.pathname, toPaths); - } - viewTransitionOpts = { - currentLocation: state.location, - nextLocation: location - }; - } - updateState(_extends({}, newState, { - // matches, errors, fetchers go through as-is - actionData, - loaderData, - historyAction: pendingAction, - location, - initialized: true, - navigation: IDLE_NAVIGATION, - revalidation: "idle", - restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches), - preventScrollReset, - blockers - }), { - viewTransitionOpts, - flushSync: flushSync === true - }); - - // Reset stateful navigation vars - pendingAction = Action.Pop; - pendingPreventScrollReset = false; - pendingViewTransitionEnabled = false; - isUninterruptedRevalidation = false; - isRevalidationRequired = false; - cancelledDeferredRoutes = []; - cancelledFetcherLoads = []; - } - - // Trigger a navigation event, which can either be a numerical POP or a PUSH - // replace with an optional submission - async function navigate(to, opts) { - if (typeof to === "number") { - init.history.go(to); - return; - } - let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, future.v7_relativeSplatPath, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative); - let { - path, - submission, - error - } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts); - let currentLocation = state.location; - let nextLocation = createLocation(state.location, path, opts && opts.state); - - // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded - // URL from window.location, so we need to encode it here so the behavior - // remains the same as POP and non-data-router usages. new URL() does all - // the same encoding we'd get from a history.pushState/window.location read - // without having to touch history - nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation)); - let userReplace = opts && opts.replace != null ? opts.replace : undefined; - let historyAction = Action.Push; - if (userReplace === true) { - historyAction = Action.Replace; - } else if (userReplace === false) ; else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) { - // By default on submissions to the current location we REPLACE so that - // users don't have to double-click the back button to get to the prior - // location. If the user redirects to a different location from the - // action/loader this will be ignored and the redirect will be a PUSH - historyAction = Action.Replace; - } - let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined; - let flushSync = (opts && opts.unstable_flushSync) === true; - let blockerKey = shouldBlockNavigation({ - currentLocation, - nextLocation, - historyAction - }); - if (blockerKey) { - // Put the blocker into a blocked state - updateBlocker(blockerKey, { - state: "blocked", - location: nextLocation, - proceed() { - updateBlocker(blockerKey, { - state: "proceeding", - proceed: undefined, - reset: undefined, - location: nextLocation - }); - // Send the same navigation through - navigate(to, opts); - }, - reset() { - let blockers = new Map(state.blockers); - blockers.set(blockerKey, IDLE_BLOCKER); - updateState({ - blockers - }); - } - }); - return; - } - return await startNavigation(historyAction, nextLocation, { - submission, - // Send through the formData serialization error if we have one so we can - // render at the right error boundary after we match routes - pendingError: error, - preventScrollReset, - replace: opts && opts.replace, - enableViewTransition: opts && opts.unstable_viewTransition, - flushSync - }); - } - - // Revalidate all current loaders. If a navigation is in progress or if this - // is interrupted by a navigation, allow this to "succeed" by calling all - // loaders during the next loader round - function revalidate() { - interruptActiveLoads(); - updateState({ - revalidation: "loading" - }); - - // If we're currently submitting an action, we don't need to start a new - // navigation, we'll just let the follow up loader execution call all loaders - if (state.navigation.state === "submitting") { - return; - } - - // If we're currently in an idle state, start a new navigation for the current - // action/location and mark it as uninterrupted, which will skip the history - // update in completeNavigation - if (state.navigation.state === "idle") { - startNavigation(state.historyAction, state.location, { - startUninterruptedRevalidation: true - }); - return; - } - - // Otherwise, if we're currently in a loading state, just start a new - // navigation to the navigation.location but do not trigger an uninterrupted - // revalidation so that history correctly updates once the navigation completes - startNavigation(pendingAction || state.historyAction, state.navigation.location, { - overrideNavigation: state.navigation - }); - } - - // Start a navigation to the given action/location. Can optionally provide a - // overrideNavigation which will override the normalLoad in the case of a redirect - // navigation - async function startNavigation(historyAction, location, opts) { - // Abort any in-progress navigations and start a new one. Unset any ongoing - // uninterrupted revalidations unless told otherwise, since we want this - // new navigation to update history normally - pendingNavigationController && pendingNavigationController.abort(); - pendingNavigationController = null; - pendingAction = historyAction; - isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true; - - // Save the current scroll position every time we start a new navigation, - // and track whether we should reset scroll on completion - saveScrollPosition(state.location, state.matches); - pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; - pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true; - let routesToUse = inFlightDataRoutes || dataRoutes; - let loadingNavigation = opts && opts.overrideNavigation; - let matches = matchRoutes(routesToUse, location, basename); - let flushSync = (opts && opts.flushSync) === true; - - // Short circuit with a 404 on the root error boundary if we match nothing - if (!matches) { - let error = getInternalRouterError(404, { - pathname: location.pathname - }); - let { - matches: notFoundMatches, - route - } = getShortCircuitMatches(routesToUse); - // Cancel all pending deferred on 404s since we don't keep any routes - cancelActiveDeferreds(); - completeNavigation(location, { - matches: notFoundMatches, - loaderData: {}, - errors: { - [route.id]: error - } - }, { - flushSync - }); - return; - } - - // Short circuit if it's only a hash change and not a revalidation or - // mutation submission. - // - // Ignore on initial page loads because since the initial load will always - // be "same hash". For example, on /page#hash and submit a - // which will default to a navigation to /page - if (state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) { - completeNavigation(location, { - matches - }, { - flushSync - }); - return; - } - - // Create a controller/Request for this navigation - pendingNavigationController = new AbortController(); - let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission); - let pendingActionResult; - if (opts && opts.pendingError) { - // If we have a pendingError, it means the user attempted a GET submission - // with binary FormData so assign here and skip to handleLoaders. That - // way we handle calling loaders above the boundary etc. It's not really - // different from an actionError in that sense. - pendingActionResult = [findNearestBoundary(matches).route.id, { - type: ResultType.error, - error: opts.pendingError - }]; - } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) { - // Call action if we received an action submission - let actionResult = await handleAction(request, location, opts.submission, matches, { - replace: opts.replace, - flushSync - }); - if (actionResult.shortCircuited) { - return; - } - pendingActionResult = actionResult.pendingActionResult; - loadingNavigation = getLoadingNavigation(location, opts.submission); - flushSync = false; - - // Create a GET request for the loaders - request = createClientSideRequest(init.history, request.url, request.signal); - } - - // Call loaders - let { - shortCircuited, - loaderData, - errors - } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionResult); - if (shortCircuited) { - return; - } - - // Clean up now that the action/loaders have completed. Don't clean up if - // we short circuited because pendingNavigationController will have already - // been assigned to a new controller for the next navigation - pendingNavigationController = null; - completeNavigation(location, _extends({ - matches - }, getActionDataForCommit(pendingActionResult), { - loaderData, - errors - })); - } - - // Call the action matched by the leaf route for this navigation and handle - // redirects/errors - async function handleAction(request, location, submission, matches, opts) { - if (opts === void 0) { - opts = {}; - } - interruptActiveLoads(); - - // Put us in a submitting state - let navigation = getSubmittingNavigation(location, submission); - updateState({ - navigation - }, { - flushSync: opts.flushSync === true - }); - - // Call our action and get the result - let result; - let actionMatch = getTargetMatch(matches, location); - if (!actionMatch.route.action && !actionMatch.route.lazy) { - result = { - type: ResultType.error, - error: getInternalRouterError(405, { - method: request.method, - pathname: location.pathname, - routeId: actionMatch.route.id - }) - }; - } else { - let results = await callDataStrategy("action", request, [actionMatch], matches); - result = results[0]; - if (request.signal.aborted) { - return { - shortCircuited: true - }; - } - } - if (isRedirectResult(result)) { - let replace; - if (opts && opts.replace != null) { - replace = opts.replace; - } else { - // If the user didn't explicity indicate replace behavior, replace if - // we redirected to the exact same location we're currently at to avoid - // double back-buttons - let location = normalizeRedirectLocation(result.response.headers.get("Location"), new URL(request.url), basename); - replace = location === state.location.pathname + state.location.search; - } - await startRedirectNavigation(request, result, { - submission, - replace - }); - return { - shortCircuited: true - }; - } - if (isDeferredResult(result)) { - throw getInternalRouterError(400, { - type: "defer-action" - }); - } - if (isErrorResult(result)) { - // Store off the pending error - we use it to determine which loaders - // to call and will commit it when we complete the navigation - let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); - - // By default, all submissions are REPLACE navigations, but if the - // action threw an error that'll be rendered in an errorElement, we fall - // back to PUSH so that the user can use the back button to get back to - // the pre-submission form location to try again - if ((opts && opts.replace) !== true) { - pendingAction = Action.Push; - } - return { - pendingActionResult: [boundaryMatch.route.id, result] - }; - } - return { - pendingActionResult: [actionMatch.route.id, result] - }; - } - - // Call all applicable loaders for the given matches, handling redirects, - // errors, etc. - async function handleLoaders(request, location, matches, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionResult) { - // Figure out the right navigation we want to use for data loading - let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission); - - // If this was a redirect from an action we don't have a "submission" but - // we have it on the loading navigation so use that if available - let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation); - let routesToUse = inFlightDataRoutes || dataRoutes; - let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, future.unstable_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult); - - // Cancel pending deferreds for no-longer-matched routes or routes we're - // about to reload. Note that if this is an action reload we would have - // already cancelled all pending deferreds so this would be a no-op - cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId)); - pendingNavigationLoadId = ++incrementingLoadId; - - // Short circuit if we have no loaders to run - if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) { - let updatedFetchers = markFetchRedirectsDone(); - completeNavigation(location, _extends({ - matches, - loaderData: {}, - // Commit pending error if we're short circuiting - errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { - [pendingActionResult[0]]: pendingActionResult[1].error - } : null - }, getActionDataForCommit(pendingActionResult), updatedFetchers ? { - fetchers: new Map(state.fetchers) - } : {}), { - flushSync - }); - return { - shortCircuited: true - }; - } - - // If this is an uninterrupted revalidation, we remain in our current idle - // state. If not, we need to switch to our loading state and load data, - // preserving any new action data or existing action data (in the case of - // a revalidation interrupting an actionReload) - // If we have partialHydration enabled, then don't update the state for the - // initial data load since it's not a "navigation" - if (!isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration)) { - revalidatingFetchers.forEach(rf => { - let fetcher = state.fetchers.get(rf.key); - let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined); - state.fetchers.set(rf.key, revalidatingFetcher); - }); - let actionData; - if (pendingActionResult && !isErrorResult(pendingActionResult[1])) { - // This is cast to `any` currently because `RouteData`uses any and it - // would be a breaking change to use any. - // TODO: v7 - change `RouteData` to use `unknown` instead of `any` - actionData = { - [pendingActionResult[0]]: pendingActionResult[1].data - }; - } else if (state.actionData) { - if (Object.keys(state.actionData).length === 0) { - actionData = null; - } else { - actionData = state.actionData; - } - } - updateState(_extends({ - navigation: loadingNavigation - }, actionData !== undefined ? { - actionData - } : {}, revalidatingFetchers.length > 0 ? { - fetchers: new Map(state.fetchers) - } : {}), { - flushSync - }); - } - revalidatingFetchers.forEach(rf => { - if (fetchControllers.has(rf.key)) { - abortFetcher(rf.key); - } - if (rf.controller) { - // Fetchers use an independent AbortController so that aborting a fetcher - // (via deleteFetcher) does not abort the triggering navigation that - // triggered the revalidation - fetchControllers.set(rf.key, rf.controller); - } - }); - - // Proxy navigation abort through to revalidation fetchers - let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key)); - if (pendingNavigationController) { - pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations); - } - let { - loaderResults, - fetcherResults - } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, request); - if (request.signal.aborted) { - return { - shortCircuited: true - }; - } - - // Clean up _after_ loaders have completed. Don't clean up if we short - // circuited because fetchControllers would have been aborted and - // reassigned to new controllers for the next navigation - if (pendingNavigationController) { - pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations); - } - revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key)); - - // If any loaders returned a redirect Response, start a new REPLACE navigation - let redirect = findRedirect([...loaderResults, ...fetcherResults]); - if (redirect) { - if (redirect.idx >= matchesToLoad.length) { - // If this redirect came from a fetcher make sure we mark it in - // fetchRedirectIds so it doesn't get revalidated on the next set of - // loader executions - let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key; - fetchRedirectIds.add(fetcherKey); - } - await startRedirectNavigation(request, redirect.result, { - replace - }); - return { - shortCircuited: true - }; - } - - // Process and commit output from loaders - let { - loaderData, - errors - } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds); - - // Wire up subscribers to update loaderData as promises settle - activeDeferreds.forEach((deferredData, routeId) => { - deferredData.subscribe(aborted => { - // Note: No need to updateState here since the TrackedPromise on - // loaderData is stable across resolve/reject - // Remove this instance if we were aborted or if promises have settled - if (aborted || deferredData.done) { - activeDeferreds.delete(routeId); - } - }); - }); - - // During partial hydration, preserve SSR errors for routes that don't re-run - if (future.v7_partialHydration && initialHydration && state.errors) { - Object.entries(state.errors).filter(_ref2 => { - let [id] = _ref2; - return !matchesToLoad.some(m => m.route.id === id); - }).forEach(_ref3 => { - let [routeId, error] = _ref3; - errors = Object.assign(errors || {}, { - [routeId]: error - }); - }); - } - let updatedFetchers = markFetchRedirectsDone(); - let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId); - let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0; - return _extends({ - loaderData, - errors - }, shouldUpdateFetchers ? { - fetchers: new Map(state.fetchers) - } : {}); - } - - // Trigger a fetcher load/submit for the given fetcher key - function fetch(key, routeId, href, opts) { - if (isServer) { - throw new Error("router.fetch() was called during the server render, but it shouldn't be. " + "You are likely calling a useFetcher() method in the body of your component. " + "Try moving it to a useEffect or a callback."); - } - if (fetchControllers.has(key)) abortFetcher(key); - let flushSync = (opts && opts.unstable_flushSync) === true; - let routesToUse = inFlightDataRoutes || dataRoutes; - let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, future.v7_relativeSplatPath, routeId, opts == null ? void 0 : opts.relative); - let matches = matchRoutes(routesToUse, normalizedPath, basename); - if (!matches) { - setFetcherError(key, routeId, getInternalRouterError(404, { - pathname: normalizedPath - }), { - flushSync - }); - return; - } - let { - path, - submission, - error - } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts); - if (error) { - setFetcherError(key, routeId, error, { - flushSync - }); - return; - } - let match = getTargetMatch(matches, path); - pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; - if (submission && isMutationMethod(submission.formMethod)) { - handleFetcherAction(key, routeId, path, match, matches, flushSync, submission); - return; - } - - // Store off the match so we can call it's shouldRevalidate on subsequent - // revalidations - fetchLoadMatches.set(key, { - routeId, - path - }); - handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission); - } - - // Call the action for the matched fetcher.submit(), and then handle redirects, - // errors, and revalidation - async function handleFetcherAction(key, routeId, path, match, requestMatches, flushSync, submission) { - interruptActiveLoads(); - fetchLoadMatches.delete(key); - if (!match.route.action && !match.route.lazy) { - let error = getInternalRouterError(405, { - method: submission.formMethod, - pathname: path, - routeId: routeId - }); - setFetcherError(key, routeId, error, { - flushSync - }); - return; - } - - // Put this fetcher into it's submitting state - let existingFetcher = state.fetchers.get(key); - updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), { - flushSync - }); - - // Call the action for the fetcher - let abortController = new AbortController(); - let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission); - fetchControllers.set(key, abortController); - let originatingLoadId = incrementingLoadId; - let actionResults = await callDataStrategy("action", fetchRequest, [match], requestMatches); - let actionResult = actionResults[0]; - if (fetchRequest.signal.aborted) { - // We can delete this so long as we weren't aborted by our own fetcher - // re-submit which would have put _new_ controller is in fetchControllers - if (fetchControllers.get(key) === abortController) { - fetchControllers.delete(key); - } - return; - } - - // When using v7_fetcherPersist, we don't want errors bubbling up to the UI - // or redirects processed for unmounted fetchers so we just revert them to - // idle - if (future.v7_fetcherPersist && deletedFetchers.has(key)) { - if (isRedirectResult(actionResult) || isErrorResult(actionResult)) { - updateFetcherState(key, getDoneFetcher(undefined)); - return; - } - // Let SuccessResult's fall through for revalidation - } else { - if (isRedirectResult(actionResult)) { - fetchControllers.delete(key); - if (pendingNavigationLoadId > originatingLoadId) { - // A new navigation was kicked off after our action started, so that - // should take precedence over this redirect navigation. We already - // set isRevalidationRequired so all loaders for the new route should - // fire unless opted out via shouldRevalidate - updateFetcherState(key, getDoneFetcher(undefined)); - return; - } else { - fetchRedirectIds.add(key); - updateFetcherState(key, getLoadingFetcher(submission)); - return startRedirectNavigation(fetchRequest, actionResult, { - fetcherSubmission: submission - }); - } - } - - // Process any non-redirect errors thrown - if (isErrorResult(actionResult)) { - setFetcherError(key, routeId, actionResult.error); - return; - } - } - if (isDeferredResult(actionResult)) { - throw getInternalRouterError(400, { - type: "defer-action" - }); - } - - // Start the data load for current matches, or the next location if we're - // in the middle of a navigation - let nextLocation = state.navigation.location || state.location; - let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal); - let routesToUse = inFlightDataRoutes || dataRoutes; - let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches; - invariant(matches, "Didn't find any matches after fetcher action"); - let loadId = ++incrementingLoadId; - fetchReloadIds.set(key, loadId); - let loadFetcher = getLoadingFetcher(submission, actionResult.data); - state.fetchers.set(key, loadFetcher); - let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, false, future.unstable_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, [match.route.id, actionResult]); - - // Put all revalidating fetchers into the loading state, except for the - // current fetcher which we want to keep in it's current loading state which - // contains it's action submission info + action data - revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => { - let staleKey = rf.key; - let existingFetcher = state.fetchers.get(staleKey); - let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined); - state.fetchers.set(staleKey, revalidatingFetcher); - if (fetchControllers.has(staleKey)) { - abortFetcher(staleKey); - } - if (rf.controller) { - fetchControllers.set(staleKey, rf.controller); - } - }); - updateState({ - fetchers: new Map(state.fetchers) - }); - let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key)); - abortController.signal.addEventListener("abort", abortPendingFetchRevalidations); - let { - loaderResults, - fetcherResults - } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, revalidationRequest); - if (abortController.signal.aborted) { - return; - } - abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations); - fetchReloadIds.delete(key); - fetchControllers.delete(key); - revalidatingFetchers.forEach(r => fetchControllers.delete(r.key)); - let redirect = findRedirect([...loaderResults, ...fetcherResults]); - if (redirect) { - if (redirect.idx >= matchesToLoad.length) { - // If this redirect came from a fetcher make sure we mark it in - // fetchRedirectIds so it doesn't get revalidated on the next set of - // loader executions - let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key; - fetchRedirectIds.add(fetcherKey); - } - return startRedirectNavigation(revalidationRequest, redirect.result); - } - - // Process and commit output from loaders - let { - loaderData, - errors - } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds); - - // Since we let revalidations complete even if the submitting fetcher was - // deleted, only put it back to idle if it hasn't been deleted - if (state.fetchers.has(key)) { - let doneFetcher = getDoneFetcher(actionResult.data); - state.fetchers.set(key, doneFetcher); - } - abortStaleFetchLoads(loadId); - - // If we are currently in a navigation loading state and this fetcher is - // more recent than the navigation, we want the newer data so abort the - // navigation and complete it with the fetcher data - if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) { - invariant(pendingAction, "Expected pending action"); - pendingNavigationController && pendingNavigationController.abort(); - completeNavigation(state.navigation.location, { - matches, - loaderData, - errors, - fetchers: new Map(state.fetchers) - }); - } else { - // otherwise just update with the fetcher data, preserving any existing - // loaderData for loaders that did not need to reload. We have to - // manually merge here since we aren't going through completeNavigation - updateState({ - errors, - loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors), - fetchers: new Map(state.fetchers) - }); - isRevalidationRequired = false; - } - } - - // Call the matched loader for fetcher.load(), handling redirects, errors, etc. - async function handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission) { - let existingFetcher = state.fetchers.get(key); - updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined), { - flushSync - }); - - // Call the loader for this fetcher route match - let abortController = new AbortController(); - let fetchRequest = createClientSideRequest(init.history, path, abortController.signal); - fetchControllers.set(key, abortController); - let originatingLoadId = incrementingLoadId; - let results = await callDataStrategy("loader", fetchRequest, [match], matches); - let result = results[0]; - - // Deferred isn't supported for fetcher loads, await everything and treat it - // as a normal load. resolveDeferredData will return undefined if this - // fetcher gets aborted, so we just leave result untouched and short circuit - // below if that happens - if (isDeferredResult(result)) { - result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result; - } - - // We can delete this so long as we weren't aborted by our our own fetcher - // re-load which would have put _new_ controller is in fetchControllers - if (fetchControllers.get(key) === abortController) { - fetchControllers.delete(key); - } - if (fetchRequest.signal.aborted) { - return; - } - - // We don't want errors bubbling up or redirects followed for unmounted - // fetchers, so short circuit here if it was removed from the UI - if (deletedFetchers.has(key)) { - updateFetcherState(key, getDoneFetcher(undefined)); - return; - } - - // If the loader threw a redirect Response, start a new REPLACE navigation - if (isRedirectResult(result)) { - if (pendingNavigationLoadId > originatingLoadId) { - // A new navigation was kicked off after our loader started, so that - // should take precedence over this redirect navigation - updateFetcherState(key, getDoneFetcher(undefined)); - return; - } else { - fetchRedirectIds.add(key); - await startRedirectNavigation(fetchRequest, result); - return; - } - } - - // Process any non-redirect errors thrown - if (isErrorResult(result)) { - setFetcherError(key, routeId, result.error); - return; - } - invariant(!isDeferredResult(result), "Unhandled fetcher deferred data"); - - // Put the fetcher back into an idle state - updateFetcherState(key, getDoneFetcher(result.data)); - } - - /** - * Utility function to handle redirects returned from an action or loader. - * Normally, a redirect "replaces" the navigation that triggered it. So, for - * example: - * - * - user is on /a - * - user clicks a link to /b - * - loader for /b redirects to /c - * - * In a non-JS app the browser would track the in-flight navigation to /b and - * then replace it with /c when it encountered the redirect response. In - * the end it would only ever update the URL bar with /c. - * - * In client-side routing using pushState/replaceState, we aim to emulate - * this behavior and we also do not update history until the end of the - * navigation (including processed redirects). This means that we never - * actually touch history until we've processed redirects, so we just use - * the history action from the original navigation (PUSH or REPLACE). - */ - async function startRedirectNavigation(request, redirect, _temp2) { - let { - submission, - fetcherSubmission, - replace - } = _temp2 === void 0 ? {} : _temp2; - if (redirect.response.headers.has("X-Remix-Revalidate")) { - isRevalidationRequired = true; - } - let location = redirect.response.headers.get("Location"); - invariant(location, "Expected a Location header on the redirect Response"); - location = normalizeRedirectLocation(location, new URL(request.url), basename); - let redirectLocation = createLocation(state.location, location, { - _isRedirect: true - }); - if (isBrowser) { - let isDocumentReload = false; - if (redirect.response.headers.has("X-Remix-Reload-Document")) { - // Hard reload if the response contained X-Remix-Reload-Document - isDocumentReload = true; - } else if (ABSOLUTE_URL_REGEX.test(location)) { - const url = init.history.createURL(location); - isDocumentReload = - // Hard reload if it's an absolute URL to a new origin - url.origin !== routerWindow.location.origin || - // Hard reload if it's an absolute URL that does not match our basename - stripBasename(url.pathname, basename) == null; - } - if (isDocumentReload) { - if (replace) { - routerWindow.location.replace(location); - } else { - routerWindow.location.assign(location); - } - return; - } - } - - // There's no need to abort on redirects, since we don't detect the - // redirect until the action/loaders have settled - pendingNavigationController = null; - let redirectHistoryAction = replace === true ? Action.Replace : Action.Push; - - // Use the incoming submission if provided, fallback on the active one in - // state.navigation - let { - formMethod, - formAction, - formEncType - } = state.navigation; - if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) { - submission = getSubmissionFromNavigation(state.navigation); - } - - // If this was a 307/308 submission we want to preserve the HTTP method and - // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the - // redirected location - let activeSubmission = submission || fetcherSubmission; - if (redirectPreserveMethodStatusCodes.has(redirect.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) { - await startNavigation(redirectHistoryAction, redirectLocation, { - submission: _extends({}, activeSubmission, { - formAction: location - }), - // Preserve this flag across redirects - preventScrollReset: pendingPreventScrollReset - }); - } else { - // If we have a navigation submission, we will preserve it through the - // redirect navigation - let overrideNavigation = getLoadingNavigation(redirectLocation, submission); - await startNavigation(redirectHistoryAction, redirectLocation, { - overrideNavigation, - // Send fetcher submissions through for shouldRevalidate - fetcherSubmission, - // Preserve this flag across redirects - preventScrollReset: pendingPreventScrollReset - }); - } - } - - // Utility wrapper for calling dataStrategy client-side without having to - // pass around the manifest, mapRouteProperties, etc. - async function callDataStrategy(type, request, matchesToLoad, matches) { - try { - let results = await callDataStrategyImpl(dataStrategyImpl, type, request, matchesToLoad, matches, manifest, mapRouteProperties); - return await Promise.all(results.map((result, i) => { - if (isRedirectHandlerResult(result)) { - let response = result.result; - return { - type: ResultType.redirect, - response: normalizeRelativeRoutingRedirectResponse(response, request, matchesToLoad[i].route.id, matches, basename, future.v7_relativeSplatPath) - }; - } - return convertHandlerResultToDataResult(result); - })); - } catch (e) { - // If the outer dataStrategy method throws, just return the error for all - // matches - and it'll naturally bubble to the root - return matchesToLoad.map(() => ({ - type: ResultType.error, - error: e - })); - } - } - async function callLoadersAndMaybeResolveData(currentMatches, matches, matchesToLoad, fetchersToLoad, request) { - let [loaderResults, ...fetcherResults] = await Promise.all([matchesToLoad.length ? callDataStrategy("loader", request, matchesToLoad, matches) : [], ...fetchersToLoad.map(f => { - if (f.matches && f.match && f.controller) { - let fetcherRequest = createClientSideRequest(init.history, f.path, f.controller.signal); - return callDataStrategy("loader", fetcherRequest, [f.match], f.matches).then(r => r[0]); - } else { - return Promise.resolve({ - type: ResultType.error, - error: getInternalRouterError(404, { - pathname: f.path - }) - }); - } - })]); - await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, loaderResults.map(() => request.signal), false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(f => f.match), fetcherResults, fetchersToLoad.map(f => f.controller ? f.controller.signal : null), true)]); - return { - loaderResults, - fetcherResults - }; - } - function interruptActiveLoads() { - // Every interruption triggers a revalidation - isRevalidationRequired = true; - - // Cancel pending route-level deferreds and mark cancelled routes for - // revalidation - cancelledDeferredRoutes.push(...cancelActiveDeferreds()); - - // Abort in-flight fetcher loads - fetchLoadMatches.forEach((_, key) => { - if (fetchControllers.has(key)) { - cancelledFetcherLoads.push(key); - abortFetcher(key); - } - }); - } - function updateFetcherState(key, fetcher, opts) { - if (opts === void 0) { - opts = {}; - } - state.fetchers.set(key, fetcher); - updateState({ - fetchers: new Map(state.fetchers) - }, { - flushSync: (opts && opts.flushSync) === true - }); - } - function setFetcherError(key, routeId, error, opts) { - if (opts === void 0) { - opts = {}; - } - let boundaryMatch = findNearestBoundary(state.matches, routeId); - deleteFetcher(key); - updateState({ - errors: { - [boundaryMatch.route.id]: error - }, - fetchers: new Map(state.fetchers) - }, { - flushSync: (opts && opts.flushSync) === true - }); - } - function getFetcher(key) { - if (future.v7_fetcherPersist) { - activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1); - // If this fetcher was previously marked for deletion, unmark it since we - // have a new instance - if (deletedFetchers.has(key)) { - deletedFetchers.delete(key); - } - } - return state.fetchers.get(key) || IDLE_FETCHER; - } - function deleteFetcher(key) { - let fetcher = state.fetchers.get(key); - // Don't abort the controller if this is a deletion of a fetcher.submit() - // in it's loading phase since - we don't want to abort the corresponding - // revalidation and want them to complete and land - if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) { - abortFetcher(key); - } - fetchLoadMatches.delete(key); - fetchReloadIds.delete(key); - fetchRedirectIds.delete(key); - deletedFetchers.delete(key); - state.fetchers.delete(key); - } - function deleteFetcherAndUpdateState(key) { - if (future.v7_fetcherPersist) { - let count = (activeFetchers.get(key) || 0) - 1; - if (count <= 0) { - activeFetchers.delete(key); - deletedFetchers.add(key); - } else { - activeFetchers.set(key, count); - } - } else { - deleteFetcher(key); - } - updateState({ - fetchers: new Map(state.fetchers) - }); - } - function abortFetcher(key) { - let controller = fetchControllers.get(key); - invariant(controller, "Expected fetch controller: " + key); - controller.abort(); - fetchControllers.delete(key); - } - function markFetchersDone(keys) { - for (let key of keys) { - let fetcher = getFetcher(key); - let doneFetcher = getDoneFetcher(fetcher.data); - state.fetchers.set(key, doneFetcher); - } - } - function markFetchRedirectsDone() { - let doneKeys = []; - let updatedFetchers = false; - for (let key of fetchRedirectIds) { - let fetcher = state.fetchers.get(key); - invariant(fetcher, "Expected fetcher: " + key); - if (fetcher.state === "loading") { - fetchRedirectIds.delete(key); - doneKeys.push(key); - updatedFetchers = true; - } - } - markFetchersDone(doneKeys); - return updatedFetchers; - } - function abortStaleFetchLoads(landedId) { - let yeetedKeys = []; - for (let [key, id] of fetchReloadIds) { - if (id < landedId) { - let fetcher = state.fetchers.get(key); - invariant(fetcher, "Expected fetcher: " + key); - if (fetcher.state === "loading") { - abortFetcher(key); - fetchReloadIds.delete(key); - yeetedKeys.push(key); - } - } - } - markFetchersDone(yeetedKeys); - return yeetedKeys.length > 0; - } - function getBlocker(key, fn) { - let blocker = state.blockers.get(key) || IDLE_BLOCKER; - if (blockerFunctions.get(key) !== fn) { - blockerFunctions.set(key, fn); - } - return blocker; - } - function deleteBlocker(key) { - state.blockers.delete(key); - blockerFunctions.delete(key); - } - - // Utility function to update blockers, ensuring valid state transitions - function updateBlocker(key, newBlocker) { - let blocker = state.blockers.get(key) || IDLE_BLOCKER; - - // Poor mans state machine :) - // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM - invariant(blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked", "Invalid blocker state transition: " + blocker.state + " -> " + newBlocker.state); - let blockers = new Map(state.blockers); - blockers.set(key, newBlocker); - updateState({ - blockers - }); - } - function shouldBlockNavigation(_ref4) { - let { - currentLocation, - nextLocation, - historyAction - } = _ref4; - if (blockerFunctions.size === 0) { - return; - } - - // We ony support a single active blocker at the moment since we don't have - // any compelling use cases for multi-blocker yet - if (blockerFunctions.size > 1) { - warning(false, "A router only supports one blocker at a time"); - } - let entries = Array.from(blockerFunctions.entries()); - let [blockerKey, blockerFunction] = entries[entries.length - 1]; - let blocker = state.blockers.get(blockerKey); - if (blocker && blocker.state === "proceeding") { - // If the blocker is currently proceeding, we don't need to re-check - // it and can let this navigation continue - return; - } - - // At this point, we know we're unblocked/blocked so we need to check the - // user-provided blocker function - if (blockerFunction({ - currentLocation, - nextLocation, - historyAction - })) { - return blockerKey; - } - } - function cancelActiveDeferreds(predicate) { - let cancelledRouteIds = []; - activeDeferreds.forEach((dfd, routeId) => { - if (!predicate || predicate(routeId)) { - // Cancel the deferred - but do not remove from activeDeferreds here - - // we rely on the subscribers to do that so our tests can assert proper - // cleanup via _internalActiveDeferreds - dfd.cancel(); - cancelledRouteIds.push(routeId); - activeDeferreds.delete(routeId); - } - }); - return cancelledRouteIds; - } - - // Opt in to capturing and reporting scroll positions during navigations, - // used by the component - function enableScrollRestoration(positions, getPosition, getKey) { - savedScrollPositions = positions; - getScrollPosition = getPosition; - getScrollRestorationKey = getKey || null; - - // Perform initial hydration scroll restoration, since we miss the boat on - // the initial updateState() because we've not yet rendered - // and therefore have no savedScrollPositions available - if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) { - initialScrollRestored = true; - let y = getSavedScrollPosition(state.location, state.matches); - if (y != null) { - updateState({ - restoreScrollPosition: y - }); - } - } - return () => { - savedScrollPositions = null; - getScrollPosition = null; - getScrollRestorationKey = null; - }; - } - function getScrollKey(location, matches) { - if (getScrollRestorationKey) { - let key = getScrollRestorationKey(location, matches.map(m => convertRouteMatchToUiMatch(m, state.loaderData))); - return key || location.key; - } - return location.key; - } - function saveScrollPosition(location, matches) { - if (savedScrollPositions && getScrollPosition) { - let key = getScrollKey(location, matches); - savedScrollPositions[key] = getScrollPosition(); - } - } - function getSavedScrollPosition(location, matches) { - if (savedScrollPositions) { - let key = getScrollKey(location, matches); - let y = savedScrollPositions[key]; - if (typeof y === "number") { - return y; - } - } - return null; - } - function _internalSetRoutes(newRoutes) { - manifest = {}; - inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest); - } - router = { - get basename() { - return basename; - }, - get future() { - return future; - }, - get state() { - return state; - }, - get routes() { - return dataRoutes; - }, - get window() { - return routerWindow; - }, - initialize, - subscribe, - enableScrollRestoration, - navigate, - fetch, - revalidate, - // Passthrough to history-aware createHref used by useHref so we get proper - // hash-aware URLs in DOM paths - createHref: to => init.history.createHref(to), - encodeLocation: to => init.history.encodeLocation(to), - getFetcher, - deleteFetcher: deleteFetcherAndUpdateState, - dispose, - getBlocker, - deleteBlocker, - _internalFetchControllers: fetchControllers, - _internalActiveDeferreds: activeDeferreds, - // TODO: Remove setRoutes, it's temporary to avoid dealing with - // updating the tree while validating the update algorithm. - _internalSetRoutes - }; - return router; - } - //#endregion - - //////////////////////////////////////////////////////////////////////////////// - //#region createStaticHandler - //////////////////////////////////////////////////////////////////////////////// - - const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred"); - - /** - * Future flags to toggle new feature behavior - */ - - function createStaticHandler(routes, opts) { - invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler"); - let manifest = {}; - let basename = (opts ? opts.basename : null) || "/"; - let mapRouteProperties; - if (opts != null && opts.mapRouteProperties) { - mapRouteProperties = opts.mapRouteProperties; - } else if (opts != null && opts.detectErrorBoundary) { - // If they are still using the deprecated version, wrap it with the new API - let detectErrorBoundary = opts.detectErrorBoundary; - mapRouteProperties = route => ({ - hasErrorBoundary: detectErrorBoundary(route) - }); - } else { - mapRouteProperties = defaultMapRouteProperties; - } - // Config driven behavior flags - let future = _extends({ - v7_relativeSplatPath: false, - v7_throwAbortReason: false - }, opts ? opts.future : null); - let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest); - - /** - * The query() method is intended for document requests, in which we want to - * call an optional action and potentially multiple loaders for all nested - * routes. It returns a StaticHandlerContext object, which is very similar - * to the router state (location, loaderData, actionData, errors, etc.) and - * also adds SSR-specific information such as the statusCode and headers - * from action/loaders Responses. - * - * It _should_ never throw and should report all errors through the - * returned context.errors object, properly associating errors to their error - * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be - * used to emulate React error boundaries during SSr by performing a second - * pass only down to the boundaryId. - * - * The one exception where we do not return a StaticHandlerContext is when a - * redirect response is returned or thrown from any action/loader. We - * propagate that out and return the raw Response so the HTTP server can - * return it directly. - * - * - `opts.requestContext` is an optional server context that will be passed - * to actions/loaders in the `context` parameter - * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent - * the bubbling of errors which allows single-fetch-type implementations - * where the client will handle the bubbling and we may need to return data - * for the handling route - */ - async function query(request, _temp3) { - let { - requestContext, - skipLoaderErrorBubbling, - unstable_dataStrategy - } = _temp3 === void 0 ? {} : _temp3; - let url = new URL(request.url); - let method = request.method; - let location = createLocation("", createPath(url), null, "default"); - let matches = matchRoutes(dataRoutes, location, basename); - - // SSR supports HEAD requests while SPA doesn't - if (!isValidMethod(method) && method !== "HEAD") { - let error = getInternalRouterError(405, { - method - }); - let { - matches: methodNotAllowedMatches, - route - } = getShortCircuitMatches(dataRoutes); - return { - basename, - location, - matches: methodNotAllowedMatches, - loaderData: {}, - actionData: null, - errors: { - [route.id]: error - }, - statusCode: error.status, - loaderHeaders: {}, - actionHeaders: {}, - activeDeferreds: null - }; - } else if (!matches) { - let error = getInternalRouterError(404, { - pathname: location.pathname - }); - let { - matches: notFoundMatches, - route - } = getShortCircuitMatches(dataRoutes); - return { - basename, - location, - matches: notFoundMatches, - loaderData: {}, - actionData: null, - errors: { - [route.id]: error - }, - statusCode: error.status, - loaderHeaders: {}, - actionHeaders: {}, - activeDeferreds: null - }; - } - let result = await queryImpl(request, location, matches, requestContext, unstable_dataStrategy || null, skipLoaderErrorBubbling === true, null); - if (isResponse(result)) { - return result; - } - - // When returning StaticHandlerContext, we patch back in the location here - // since we need it for React Context. But this helps keep our submit and - // loadRouteData operating on a Request instead of a Location - return _extends({ - location, - basename - }, result); - } - - /** - * The queryRoute() method is intended for targeted route requests, either - * for fetch ?_data requests or resource route requests. In this case, we - * are only ever calling a single action or loader, and we are returning the - * returned value directly. In most cases, this will be a Response returned - * from the action/loader, but it may be a primitive or other value as well - - * and in such cases the calling context should handle that accordingly. - * - * We do respect the throw/return differentiation, so if an action/loader - * throws, then this method will throw the value. This is important so we - * can do proper boundary identification in Remix where a thrown Response - * must go to the Catch Boundary but a returned Response is happy-path. - * - * One thing to note is that any Router-initiated Errors that make sense - * to associate with a status code will be thrown as an ErrorResponse - * instance which include the raw Error, such that the calling context can - * serialize the error as they see fit while including the proper response - * code. Examples here are 404 and 405 errors that occur prior to reaching - * any user-defined loaders. - * - * - `opts.routeId` allows you to specify the specific route handler to call. - * If not provided the handler will determine the proper route by matching - * against `request.url` - * - `opts.requestContext` is an optional server context that will be passed - * to actions/loaders in the `context` parameter - */ - async function queryRoute(request, _temp4) { - let { - routeId, - requestContext, - unstable_dataStrategy - } = _temp4 === void 0 ? {} : _temp4; - let url = new URL(request.url); - let method = request.method; - let location = createLocation("", createPath(url), null, "default"); - let matches = matchRoutes(dataRoutes, location, basename); - - // SSR supports HEAD requests while SPA doesn't - if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") { - throw getInternalRouterError(405, { - method - }); - } else if (!matches) { - throw getInternalRouterError(404, { - pathname: location.pathname - }); - } - let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location); - if (routeId && !match) { - throw getInternalRouterError(403, { - pathname: location.pathname, - routeId - }); - } else if (!match) { - // This should never hit I don't think? - throw getInternalRouterError(404, { - pathname: location.pathname - }); - } - let result = await queryImpl(request, location, matches, requestContext, unstable_dataStrategy || null, false, match); - if (isResponse(result)) { - return result; - } - let error = result.errors ? Object.values(result.errors)[0] : undefined; - if (error !== undefined) { - // If we got back result.errors, that means the loader/action threw - // _something_ that wasn't a Response, but it's not guaranteed/required - // to be an `instanceof Error` either, so we have to use throw here to - // preserve the "error" state outside of queryImpl. - throw error; - } - - // Pick off the right state value to return - if (result.actionData) { - return Object.values(result.actionData)[0]; - } - if (result.loaderData) { - var _result$activeDeferre; - let data = Object.values(result.loaderData)[0]; - if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) { - data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id]; - } - return data; - } - return undefined; - } - async function queryImpl(request, location, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch) { - invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal"); - try { - if (isMutationMethod(request.method.toLowerCase())) { - let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch != null); - return result; - } - let result = await loadRouteData(request, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch); - return isResponse(result) ? result : _extends({}, result, { - actionData: null, - actionHeaders: {} - }); - } catch (e) { - // If the user threw/returned a Response in callLoaderOrAction for a - // `queryRoute` call, we throw the `HandlerResult` to bail out early - // and then return or throw the raw Response here accordingly - if (isHandlerResult(e) && isResponse(e.result)) { - if (e.type === ResultType.error) { - throw e.result; - } - return e.result; - } - // Redirects are always returned since they don't propagate to catch - // boundaries - if (isRedirectResponse(e)) { - return e; - } - throw e; - } - } - async function submit(request, matches, actionMatch, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, isRouteRequest) { - let result; - if (!actionMatch.route.action && !actionMatch.route.lazy) { - let error = getInternalRouterError(405, { - method: request.method, - pathname: new URL(request.url).pathname, - routeId: actionMatch.route.id - }); - if (isRouteRequest) { - throw error; - } - result = { - type: ResultType.error, - error - }; - } else { - let results = await callDataStrategy("action", request, [actionMatch], matches, isRouteRequest, requestContext, unstable_dataStrategy); - result = results[0]; - if (request.signal.aborted) { - throwStaticHandlerAbortedError(request, isRouteRequest, future); - } - } - if (isRedirectResult(result)) { - // Uhhhh - this should never happen, we should always throw these from - // callLoaderOrAction, but the type narrowing here keeps TS happy and we - // can get back on the "throw all redirect responses" train here should - // this ever happen :/ - throw new Response(null, { - status: result.response.status, - headers: { - Location: result.response.headers.get("Location") - } - }); - } - if (isDeferredResult(result)) { - let error = getInternalRouterError(400, { - type: "defer-action" - }); - if (isRouteRequest) { - throw error; - } - result = { - type: ResultType.error, - error - }; - } - if (isRouteRequest) { - // Note: This should only be non-Response values if we get here, since - // isRouteRequest should throw any Response received in callLoaderOrAction - if (isErrorResult(result)) { - throw result.error; - } - return { - matches: [actionMatch], - loaderData: {}, - actionData: { - [actionMatch.route.id]: result.data - }, - errors: null, - // Note: statusCode + headers are unused here since queryRoute will - // return the raw Response or value - statusCode: 200, - loaderHeaders: {}, - actionHeaders: {}, - activeDeferreds: null - }; - } - - // Create a GET request for the loaders - let loaderRequest = new Request(request.url, { - headers: request.headers, - redirect: request.redirect, - signal: request.signal - }); - if (isErrorResult(result)) { - // Store off the pending error - we use it to determine which loaders - // to call and will commit it when we complete the navigation - let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id); - let context = await loadRouteData(loaderRequest, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, null, [boundaryMatch.route.id, result]); - - // action status codes take precedence over loader status codes - return _extends({}, context, { - statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500, - actionData: null, - actionHeaders: _extends({}, result.headers ? { - [actionMatch.route.id]: result.headers - } : {}) - }); - } - let context = await loadRouteData(loaderRequest, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, null); - return _extends({}, context, { - actionData: { - [actionMatch.route.id]: result.data - } - }, result.statusCode ? { - statusCode: result.statusCode - } : {}, { - actionHeaders: result.headers ? { - [actionMatch.route.id]: result.headers - } : {} - }); - } - async function loadRouteData(request, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch, pendingActionResult) { - let isRouteRequest = routeMatch != null; - - // Short circuit if we have no loaders to run (queryRoute()) - if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) { - throw getInternalRouterError(400, { - method: request.method, - pathname: new URL(request.url).pathname, - routeId: routeMatch == null ? void 0 : routeMatch.route.id - }); - } - let requestMatches = routeMatch ? [routeMatch] : pendingActionResult && isErrorResult(pendingActionResult[1]) ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) : matches; - let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy); - - // Short circuit if we have no loaders to run (query()) - if (matchesToLoad.length === 0) { - return { - matches, - // Add a null for all matched routes for proper revalidation on the client - loaderData: matches.reduce((acc, m) => Object.assign(acc, { - [m.route.id]: null - }), {}), - errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { - [pendingActionResult[0]]: pendingActionResult[1].error - } : null, - statusCode: 200, - loaderHeaders: {}, - activeDeferreds: null - }; - } - let results = await callDataStrategy("loader", request, matchesToLoad, matches, isRouteRequest, requestContext, unstable_dataStrategy); - if (request.signal.aborted) { - throwStaticHandlerAbortedError(request, isRouteRequest, future); - } - - // Process and commit output from loaders - let activeDeferreds = new Map(); - let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling); - - // Add a null for any non-loader matches for proper revalidation on the client - let executedLoaders = new Set(matchesToLoad.map(match => match.route.id)); - matches.forEach(match => { - if (!executedLoaders.has(match.route.id)) { - context.loaderData[match.route.id] = null; - } - }); - return _extends({}, context, { - matches, - activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null - }); - } - - // Utility wrapper for calling dataStrategy server-side without having to - // pass around the manifest, mapRouteProperties, etc. - async function callDataStrategy(type, request, matchesToLoad, matches, isRouteRequest, requestContext, unstable_dataStrategy) { - let results = await callDataStrategyImpl(unstable_dataStrategy || defaultDataStrategy, type, request, matchesToLoad, matches, manifest, mapRouteProperties, requestContext); - return await Promise.all(results.map((result, i) => { - if (isRedirectHandlerResult(result)) { - let response = result.result; - // Throw redirects and let the server handle them with an HTTP redirect - throw normalizeRelativeRoutingRedirectResponse(response, request, matchesToLoad[i].route.id, matches, basename, future.v7_relativeSplatPath); - } - if (isResponse(result.result) && isRouteRequest) { - // For SSR single-route requests, we want to hand Responses back - // directly without unwrapping - throw result; - } - return convertHandlerResultToDataResult(result); - })); - } - return { - dataRoutes, - query, - queryRoute - }; - } - - //#endregion - - //////////////////////////////////////////////////////////////////////////////// - //#region Helpers - //////////////////////////////////////////////////////////////////////////////// - - /** - * Given an existing StaticHandlerContext and an error thrown at render time, - * provide an updated StaticHandlerContext suitable for a second SSR render - */ - function getStaticContextFromError(routes, context, error) { - let newContext = _extends({}, context, { - statusCode: isRouteErrorResponse(error) ? error.status : 500, - errors: { - [context._deepestRenderedBoundaryId || routes[0].id]: error - } - }); - return newContext; - } - function throwStaticHandlerAbortedError(request, isRouteRequest, future) { - if (future.v7_throwAbortReason && request.signal.reason !== undefined) { - throw request.signal.reason; - } - let method = isRouteRequest ? "queryRoute" : "query"; - throw new Error(method + "() call aborted: " + request.method + " " + request.url); - } - function isSubmissionNavigation(opts) { - return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== undefined); - } - function normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) { - let contextualMatches; - let activeRouteMatch; - if (fromRouteId) { - // Grab matches up to the calling route so our route-relative logic is - // relative to the correct source route - contextualMatches = []; - for (let match of matches) { - contextualMatches.push(match); - if (match.route.id === fromRouteId) { - activeRouteMatch = match; - break; - } - } - } else { - contextualMatches = matches; - activeRouteMatch = matches[matches.length - 1]; - } - - // Resolve the relative path - let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === "path"); - - // When `to` is not specified we inherit search/hash from the current - // location, unlike when to="." and we just inherit the path. - // See https://github.com/remix-run/remix/issues/927 - if (to == null) { - path.search = location.search; - path.hash = location.hash; - } - - // Add an ?index param for matched index routes if we don't already have one - if ((to == null || to === "" || to === ".") && activeRouteMatch && activeRouteMatch.route.index && !hasNakedIndexQuery(path.search)) { - path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index"; - } - - // If we're operating within a basename, prepend it to the pathname. If - // this is a root navigation, then just use the raw basename which allows - // the basename to have full control over the presence of a trailing slash - // on root actions - if (prependBasename && basename !== "/") { - path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]); - } - return createPath(path); - } - - // Normalize navigation options by converting formMethod=GET formData objects to - // URLSearchParams so they behave identically to links with query params - function normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) { - // Return location verbatim on non-submission navigations - if (!opts || !isSubmissionNavigation(opts)) { - return { - path - }; - } - if (opts.formMethod && !isValidMethod(opts.formMethod)) { - return { - path, - error: getInternalRouterError(405, { - method: opts.formMethod - }) - }; - } - let getInvalidBodyError = () => ({ - path, - error: getInternalRouterError(400, { - type: "invalid-body" - }) - }); - - // Create a Submission on non-GET navigations - let rawFormMethod = opts.formMethod || "get"; - let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase(); - let formAction = stripHashFromPath(path); - if (opts.body !== undefined) { - if (opts.formEncType === "text/plain") { - // text only support POST/PUT/PATCH/DELETE submissions - if (!isMutationMethod(formMethod)) { - return getInvalidBodyError(); - } - let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? - // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data - Array.from(opts.body.entries()).reduce((acc, _ref5) => { - let [name, value] = _ref5; - return "" + acc + name + "=" + value + "\n"; - }, "") : String(opts.body); - return { - path, - submission: { - formMethod, - formAction, - formEncType: opts.formEncType, - formData: undefined, - json: undefined, - text - } - }; - } else if (opts.formEncType === "application/json") { - // json only supports POST/PUT/PATCH/DELETE submissions - if (!isMutationMethod(formMethod)) { - return getInvalidBodyError(); - } - try { - let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body; - return { - path, - submission: { - formMethod, - formAction, - formEncType: opts.formEncType, - formData: undefined, - json, - text: undefined - } - }; - } catch (e) { - return getInvalidBodyError(); - } - } - } - invariant(typeof FormData === "function", "FormData is not available in this environment"); - let searchParams; - let formData; - if (opts.formData) { - searchParams = convertFormDataToSearchParams(opts.formData); - formData = opts.formData; - } else if (opts.body instanceof FormData) { - searchParams = convertFormDataToSearchParams(opts.body); - formData = opts.body; - } else if (opts.body instanceof URLSearchParams) { - searchParams = opts.body; - formData = convertSearchParamsToFormData(searchParams); - } else if (opts.body == null) { - searchParams = new URLSearchParams(); - formData = new FormData(); - } else { - try { - searchParams = new URLSearchParams(opts.body); - formData = convertSearchParamsToFormData(searchParams); - } catch (e) { - return getInvalidBodyError(); - } - } - let submission = { - formMethod, - formAction, - formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded", - formData, - json: undefined, - text: undefined - }; - if (isMutationMethod(submission.formMethod)) { - return { - path, - submission - }; - } - - // Flatten submission onto URLSearchParams for GET submissions - let parsedPath = parsePath(path); - // On GET navigation submissions we can drop the ?index param from the - // resulting location since all loaders will run. But fetcher GET submissions - // only run a single loader so we need to preserve any incoming ?index params - if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) { - searchParams.append("index", ""); - } - parsedPath.search = "?" + searchParams; - return { - path: createPath(parsedPath), - submission - }; - } - - // Filter out all routes below any caught error as they aren't going to - // render so we don't need to load them - function getLoaderMatchesUntilBoundary(matches, boundaryId) { - let boundaryMatches = matches; - if (boundaryId) { - let index = matches.findIndex(m => m.route.id === boundaryId); - if (index >= 0) { - boundaryMatches = matches.slice(0, index); - } - } - return boundaryMatches; - } - function getMatchesToLoad(history, state, matches, submission, location, isInitialLoad, skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult) { - let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : undefined; - let currentUrl = history.createURL(state.location); - let nextUrl = history.createURL(location); - - // Pick navigation matches that are net-new or qualify for revalidation - let boundaryId = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[0] : undefined; - let boundaryMatches = boundaryId ? getLoaderMatchesUntilBoundary(matches, boundaryId) : matches; - - // Don't revalidate loaders by default after action 4xx/5xx responses - // when the flag is enabled. They can still opt-into revalidation via - // `shouldRevalidate` via `actionResult` - let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : undefined; - let shouldSkipRevalidation = skipActionErrorRevalidation && actionStatus && actionStatus >= 400; - let navigationMatches = boundaryMatches.filter((match, index) => { - let { - route - } = match; - if (route.lazy) { - // We haven't loaded this route yet so we don't know if it's got a loader! - return true; - } - if (route.loader == null) { - return false; - } - if (isInitialLoad) { - if (typeof route.loader !== "function" || route.loader.hydrate) { - return true; - } - return state.loaderData[route.id] === undefined && ( - // Don't re-run if the loader ran and threw an error - !state.errors || state.errors[route.id] === undefined); - } - - // Always call the loader on new route instances and pending defer cancellations - if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) { - return true; - } - - // This is the default implementation for when we revalidate. If the route - // provides it's own implementation, then we give them full control but - // provide this value so they can leverage it if needed after they check - // their own specific use cases - let currentRouteMatch = state.matches[index]; - let nextRouteMatch = match; - return shouldRevalidateLoader(match, _extends({ - currentUrl, - currentParams: currentRouteMatch.params, - nextUrl, - nextParams: nextRouteMatch.params - }, submission, { - actionResult, - unstable_actionStatus: actionStatus, - defaultShouldRevalidate: shouldSkipRevalidation ? false : - // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate - isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search || - // Search params affect all loaders - currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch) - })); - }); - - // Pick fetcher.loads that need to be revalidated - let revalidatingFetchers = []; - fetchLoadMatches.forEach((f, key) => { - // Don't revalidate: - // - on initial load (shouldn't be any fetchers then anyway) - // - if fetcher won't be present in the subsequent render - // - no longer matches the URL (v7_fetcherPersist=false) - // - was unmounted but persisted due to v7_fetcherPersist=true - if (isInitialLoad || !matches.some(m => m.route.id === f.routeId) || deletedFetchers.has(key)) { - return; - } - let fetcherMatches = matchRoutes(routesToUse, f.path, basename); - - // If the fetcher path no longer matches, push it in with null matches so - // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is - // currently only a use-case for Remix HMR where the route tree can change - // at runtime and remove a route previously loaded via a fetcher - if (!fetcherMatches) { - revalidatingFetchers.push({ - key, - routeId: f.routeId, - path: f.path, - matches: null, - match: null, - controller: null - }); - return; - } - - // Revalidating fetchers are decoupled from the route matches since they - // load from a static href. They revalidate based on explicit revalidation - // (submission, useRevalidator, or X-Remix-Revalidate) - let fetcher = state.fetchers.get(key); - let fetcherMatch = getTargetMatch(fetcherMatches, f.path); - let shouldRevalidate = false; - if (fetchRedirectIds.has(key)) { - // Never trigger a revalidation of an actively redirecting fetcher - shouldRevalidate = false; - } else if (cancelledFetcherLoads.includes(key)) { - // Always revalidate if the fetcher was cancelled - shouldRevalidate = true; - } else if (fetcher && fetcher.state !== "idle" && fetcher.data === undefined) { - // If the fetcher hasn't ever completed loading yet, then this isn't a - // revalidation, it would just be a brand new load if an explicit - // revalidation is required - shouldRevalidate = isRevalidationRequired; - } else { - // Otherwise fall back on any user-defined shouldRevalidate, defaulting - // to explicit revalidations only - shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({ - currentUrl, - currentParams: state.matches[state.matches.length - 1].params, - nextUrl, - nextParams: matches[matches.length - 1].params - }, submission, { - actionResult, - unstable_actionStatus: actionStatus, - defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired - })); - } - if (shouldRevalidate) { - revalidatingFetchers.push({ - key, - routeId: f.routeId, - path: f.path, - matches: fetcherMatches, - match: fetcherMatch, - controller: new AbortController() - }); - } - }); - return [navigationMatches, revalidatingFetchers]; - } - function isNewLoader(currentLoaderData, currentMatch, match) { - let isNew = - // [a] -> [a, b] - !currentMatch || - // [a, b] -> [a, c] - match.route.id !== currentMatch.route.id; - - // Handle the case that we don't have data for a re-used route, potentially - // from a prior error or from a cancelled pending deferred - let isMissingData = currentLoaderData[match.route.id] === undefined; - - // Always load if this is a net-new route or we don't yet have data - return isNew || isMissingData; - } - function isNewRouteInstance(currentMatch, match) { - let currentPath = currentMatch.route.path; - return ( - // param change for this match, /users/123 -> /users/456 - currentMatch.pathname !== match.pathname || - // splat param changed, which is not present in match.path - // e.g. /files/images/avatar.jpg -> files/finances.xls - currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"] - ); - } - function shouldRevalidateLoader(loaderMatch, arg) { - if (loaderMatch.route.shouldRevalidate) { - let routeChoice = loaderMatch.route.shouldRevalidate(arg); - if (typeof routeChoice === "boolean") { - return routeChoice; - } - } - return arg.defaultShouldRevalidate; - } - - /** - * Execute route.lazy() methods to lazily load route modules (loader, action, - * shouldRevalidate) and update the routeManifest in place which shares objects - * with dataRoutes so those get updated as well. - */ - async function loadLazyRouteModule(route, mapRouteProperties, manifest) { - if (!route.lazy) { - return; - } - let lazyRoute = await route.lazy(); - - // If the lazy route function was executed and removed by another parallel - // call then we can return - first lazy() to finish wins because the return - // value of lazy is expected to be static - if (!route.lazy) { - return; - } - let routeToUpdate = manifest[route.id]; - invariant(routeToUpdate, "No route found in manifest"); - - // Update the route in place. This should be safe because there's no way - // we could yet be sitting on this route as we can't get there without - // resolving lazy() first. - // - // This is different than the HMR "update" use-case where we may actively be - // on the route being updated. The main concern boils down to "does this - // mutation affect any ongoing navigations or any current state.matches - // values?". If not, it should be safe to update in place. - let routeUpdates = {}; - for (let lazyRouteProperty in lazyRoute) { - let staticRouteValue = routeToUpdate[lazyRouteProperty]; - let isPropertyStaticallyDefined = staticRouteValue !== undefined && - // This property isn't static since it should always be updated based - // on the route updates - lazyRouteProperty !== "hasErrorBoundary"; - warning(!isPropertyStaticallyDefined, "Route \"" + routeToUpdate.id + "\" has a static property \"" + lazyRouteProperty + "\" " + "defined but its lazy function is also returning a value for this property. " + ("The lazy route property \"" + lazyRouteProperty + "\" will be ignored.")); - if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) { - routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty]; - } - } - - // Mutate the route with the provided updates. Do this first so we pass - // the updated version to mapRouteProperties - Object.assign(routeToUpdate, routeUpdates); - - // Mutate the `hasErrorBoundary` property on the route based on the route - // updates and remove the `lazy` function so we don't resolve the lazy - // route again. - Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), { - lazy: undefined - })); - } - - // Default implementation of `dataStrategy` which fetches all loaders in parallel - function defaultDataStrategy(opts) { - return Promise.all(opts.matches.map(m => m.resolve())); - } - async function callDataStrategyImpl(dataStrategyImpl, type, request, matchesToLoad, matches, manifest, mapRouteProperties, requestContext) { - let routeIdsToLoad = matchesToLoad.reduce((acc, m) => acc.add(m.route.id), new Set()); - let loadedMatches = new Set(); - - // Send all matches here to allow for a middleware-type implementation. - // handler will be a no-op for unneeded routes and we filter those results - // back out below. - let results = await dataStrategyImpl({ - matches: matches.map(match => { - let shouldLoad = routeIdsToLoad.has(match.route.id); - // `resolve` encapsulates the route.lazy, executing the - // loader/action, and mapping return values/thrown errors to a - // HandlerResult. Users can pass a callback to take fine-grained control - // over the execution of the loader/action - let resolve = handlerOverride => { - loadedMatches.add(match.route.id); - return shouldLoad ? callLoaderOrAction(type, request, match, manifest, mapRouteProperties, handlerOverride, requestContext) : Promise.resolve({ - type: ResultType.data, - result: undefined - }); - }; - return _extends({}, match, { - shouldLoad, - resolve - }); - }), - request, - params: matches[0].params, - context: requestContext - }); - - // Throw if any loadRoute implementations not called since they are what - // ensures a route is fully loaded - matches.forEach(m => invariant(loadedMatches.has(m.route.id), "`match.resolve()` was not called for route id \"" + m.route.id + "\". " + "You must call `match.resolve()` on every match passed to " + "`dataStrategy` to ensure all routes are properly loaded.")); - - // Filter out any middleware-only matches for which we didn't need to run handlers - return results.filter((_, i) => routeIdsToLoad.has(matches[i].route.id)); - } - - // Default logic for calling a loader/action is the user has no specified a dataStrategy - async function callLoaderOrAction(type, request, match, manifest, mapRouteProperties, handlerOverride, staticContext) { - let result; - let onReject; - let runHandler = handler => { - // Setup a promise we can race against so that abort signals short circuit - let reject; - // This will never resolve so safe to type it as Promise to - // satisfy the function return value - let abortPromise = new Promise((_, r) => reject = r); - onReject = () => reject(); - request.signal.addEventListener("abort", onReject); - let actualHandler = ctx => { - if (typeof handler !== "function") { - return Promise.reject(new Error("You cannot call the handler for a route which defines a boolean " + ("\"" + type + "\" [routeId: " + match.route.id + "]"))); - } - return handler({ - request, - params: match.params, - context: staticContext - }, ...(ctx !== undefined ? [ctx] : [])); - }; - let handlerPromise; - if (handlerOverride) { - handlerPromise = handlerOverride(ctx => actualHandler(ctx)); - } else { - handlerPromise = (async () => { - try { - let val = await actualHandler(); - return { - type: "data", - result: val - }; - } catch (e) { - return { - type: "error", - result: e - }; - } - })(); - } - return Promise.race([handlerPromise, abortPromise]); - }; - try { - let handler = match.route[type]; - if (match.route.lazy) { - if (handler) { - // Run statically defined handler in parallel with lazy() - let handlerError; - let [value] = await Promise.all([ - // If the handler throws, don't let it immediately bubble out, - // since we need to let the lazy() execution finish so we know if this - // route has a boundary that can handle the error - runHandler(handler).catch(e => { - handlerError = e; - }), loadLazyRouteModule(match.route, mapRouteProperties, manifest)]); - if (handlerError !== undefined) { - throw handlerError; - } - result = value; - } else { - // Load lazy route module, then run any returned handler - await loadLazyRouteModule(match.route, mapRouteProperties, manifest); - handler = match.route[type]; - if (handler) { - // Handler still runs even if we got interrupted to maintain consistency - // with un-abortable behavior of handler execution on non-lazy or - // previously-lazy-loaded routes - result = await runHandler(handler); - } else if (type === "action") { - let url = new URL(request.url); - let pathname = url.pathname + url.search; - throw getInternalRouterError(405, { - method: request.method, - pathname, - routeId: match.route.id - }); - } else { - // lazy() route has no loader to run. Short circuit here so we don't - // hit the invariant below that errors on returning undefined. - return { - type: ResultType.data, - result: undefined - }; - } - } - } else if (!handler) { - let url = new URL(request.url); - let pathname = url.pathname + url.search; - throw getInternalRouterError(404, { - pathname - }); - } else { - result = await runHandler(handler); - } - invariant(result.result !== undefined, "You defined " + (type === "action" ? "an action" : "a loader") + " for route " + ("\"" + match.route.id + "\" but didn't return anything from your `" + type + "` ") + "function. Please return a value or `null`."); - } catch (e) { - // We should already be catching and converting normal handler executions to - // HandlerResults and returning them, so anything that throws here is an - // unexpected error we still need to wrap - return { - type: ResultType.error, - result: e - }; - } finally { - if (onReject) { - request.signal.removeEventListener("abort", onReject); - } - } - return result; - } - async function convertHandlerResultToDataResult(handlerResult) { - let { - result, - type, - status - } = handlerResult; - if (isResponse(result)) { - let data; - try { - let contentType = result.headers.get("Content-Type"); - // Check between word boundaries instead of startsWith() due to the last - // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type - if (contentType && /\bapplication\/json\b/.test(contentType)) { - if (result.body == null) { - data = null; - } else { - data = await result.json(); - } - } else { - data = await result.text(); - } - } catch (e) { - return { - type: ResultType.error, - error: e - }; - } - if (type === ResultType.error) { - return { - type: ResultType.error, - error: new ErrorResponseImpl(result.status, result.statusText, data), - statusCode: result.status, - headers: result.headers - }; - } - return { - type: ResultType.data, - data, - statusCode: result.status, - headers: result.headers - }; - } - if (type === ResultType.error) { - return { - type: ResultType.error, - error: result, - statusCode: isRouteErrorResponse(result) ? result.status : status - }; - } - if (isDeferredData(result)) { - var _result$init, _result$init2; - return { - type: ResultType.deferred, - deferredData: result, - statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status, - headers: ((_result$init2 = result.init) == null ? void 0 : _result$init2.headers) && new Headers(result.init.headers) - }; - } - return { - type: ResultType.data, - data: result, - statusCode: status - }; - } - - // Support relative routing in internal redirects - function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, v7_relativeSplatPath) { - let location = response.headers.get("Location"); - invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header"); - if (!ABSOLUTE_URL_REGEX.test(location)) { - let trimmedMatches = matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1); - location = normalizeTo(new URL(request.url), trimmedMatches, basename, true, location, v7_relativeSplatPath); - response.headers.set("Location", location); - } - return response; - } - function normalizeRedirectLocation(location, currentUrl, basename) { - if (ABSOLUTE_URL_REGEX.test(location)) { - // Strip off the protocol+origin for same-origin + same-basename absolute redirects - let normalizedLocation = location; - let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation); - let isSameBasename = stripBasename(url.pathname, basename) != null; - if (url.origin === currentUrl.origin && isSameBasename) { - return url.pathname + url.search + url.hash; - } - } - return location; - } - - // Utility method for creating the Request instances for loaders/actions during - // client-side navigations and fetches. During SSR we will always have a - // Request instance from the static handler (query/queryRoute) - function createClientSideRequest(history, location, signal, submission) { - let url = history.createURL(stripHashFromPath(location)).toString(); - let init = { - signal - }; - if (submission && isMutationMethod(submission.formMethod)) { - let { - formMethod, - formEncType - } = submission; - // Didn't think we needed this but it turns out unlike other methods, patch - // won't be properly normalized to uppercase and results in a 405 error. - // See: https://fetch.spec.whatwg.org/#concept-method - init.method = formMethod.toUpperCase(); - if (formEncType === "application/json") { - init.headers = new Headers({ - "Content-Type": formEncType - }); - init.body = JSON.stringify(submission.json); - } else if (formEncType === "text/plain") { - // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) - init.body = submission.text; - } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) { - // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) - init.body = convertFormDataToSearchParams(submission.formData); - } else { - // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) - init.body = submission.formData; - } - } - return new Request(url, init); - } - function convertFormDataToSearchParams(formData) { - let searchParams = new URLSearchParams(); - for (let [key, value] of formData.entries()) { - // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs - searchParams.append(key, typeof value === "string" ? value : value.name); - } - return searchParams; - } - function convertSearchParamsToFormData(searchParams) { - let formData = new FormData(); - for (let [key, value] of searchParams.entries()) { - formData.append(key, value); - } - return formData; - } - function processRouteLoaderData(matches, matchesToLoad, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling) { - // Fill in loaderData/errors from our loaders - let loaderData = {}; - let errors = null; - let statusCode; - let foundError = false; - let loaderHeaders = {}; - let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : undefined; - - // Process loader results into state.loaderData/state.errors - results.forEach((result, index) => { - let id = matchesToLoad[index].route.id; - invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData"); - if (isErrorResult(result)) { - let error = result.error; - // If we have a pending action error, we report it at the highest-route - // that throws a loader error, and then clear it out to indicate that - // it was consumed - if (pendingError !== undefined) { - error = pendingError; - pendingError = undefined; - } - errors = errors || {}; - if (skipLoaderErrorBubbling) { - errors[id] = error; - } else { - // Look upwards from the matched route for the closest ancestor error - // boundary, defaulting to the root match. Prefer higher error values - // if lower errors bubble to the same boundary - let boundaryMatch = findNearestBoundary(matches, id); - if (errors[boundaryMatch.route.id] == null) { - errors[boundaryMatch.route.id] = error; - } - } - - // Clear our any prior loaderData for the throwing route - loaderData[id] = undefined; - - // Once we find our first (highest) error, we set the status code and - // prevent deeper status codes from overriding - if (!foundError) { - foundError = true; - statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500; - } - if (result.headers) { - loaderHeaders[id] = result.headers; - } - } else { - if (isDeferredResult(result)) { - activeDeferreds.set(id, result.deferredData); - loaderData[id] = result.deferredData.data; - // Error status codes always override success status codes, but if all - // loaders are successful we take the deepest status code. - if (result.statusCode != null && result.statusCode !== 200 && !foundError) { - statusCode = result.statusCode; - } - if (result.headers) { - loaderHeaders[id] = result.headers; - } - } else { - loaderData[id] = result.data; - // Error status codes always override success status codes, but if all - // loaders are successful we take the deepest status code. - if (result.statusCode && result.statusCode !== 200 && !foundError) { - statusCode = result.statusCode; - } - if (result.headers) { - loaderHeaders[id] = result.headers; - } - } - } - }); - - // If we didn't consume the pending action error (i.e., all loaders - // resolved), then consume it here. Also clear out any loaderData for the - // throwing route - if (pendingError !== undefined && pendingActionResult) { - errors = { - [pendingActionResult[0]]: pendingError - }; - loaderData[pendingActionResult[0]] = undefined; - } - return { - loaderData, - errors, - statusCode: statusCode || 200, - loaderHeaders - }; - } - function processLoaderData(state, matches, matchesToLoad, results, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds) { - let { - loaderData, - errors - } = processRouteLoaderData(matches, matchesToLoad, results, pendingActionResult, activeDeferreds, false // This method is only called client side so we always want to bubble - ); - - // Process results from our revalidating fetchers - for (let index = 0; index < revalidatingFetchers.length; index++) { - let { - key, - match, - controller - } = revalidatingFetchers[index]; - invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, "Did not find corresponding fetcher result"); - let result = fetcherResults[index]; - - // Process fetcher non-redirect errors - if (controller && controller.signal.aborted) { - // Nothing to do for aborted fetchers - continue; - } else if (isErrorResult(result)) { - let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id); - if (!(errors && errors[boundaryMatch.route.id])) { - errors = _extends({}, errors, { - [boundaryMatch.route.id]: result.error - }); - } - state.fetchers.delete(key); - } else if (isRedirectResult(result)) { - // Should never get here, redirects should get processed above, but we - // keep this to type narrow to a success result in the else - invariant(false, "Unhandled fetcher revalidation redirect"); - } else if (isDeferredResult(result)) { - // Should never get here, deferred data should be awaited for fetchers - // in resolveDeferredResults - invariant(false, "Unhandled fetcher deferred data"); - } else { - let doneFetcher = getDoneFetcher(result.data); - state.fetchers.set(key, doneFetcher); - } - } - return { - loaderData, - errors - }; - } - function mergeLoaderData(loaderData, newLoaderData, matches, errors) { - let mergedLoaderData = _extends({}, newLoaderData); - for (let match of matches) { - let id = match.route.id; - if (newLoaderData.hasOwnProperty(id)) { - if (newLoaderData[id] !== undefined) { - mergedLoaderData[id] = newLoaderData[id]; - } - } else if (loaderData[id] !== undefined && match.route.loader) { - // Preserve existing keys not included in newLoaderData and where a loader - // wasn't removed by HMR - mergedLoaderData[id] = loaderData[id]; - } - if (errors && errors.hasOwnProperty(id)) { - // Don't keep any loader data below the boundary - break; - } - } - return mergedLoaderData; - } - function getActionDataForCommit(pendingActionResult) { - if (!pendingActionResult) { - return {}; - } - return isErrorResult(pendingActionResult[1]) ? { - // Clear out prior actionData on errors - actionData: {} - } : { - actionData: { - [pendingActionResult[0]]: pendingActionResult[1].data - } - }; - } - - // Find the nearest error boundary, looking upwards from the leaf route (or the - // route specified by routeId) for the closest ancestor error boundary, - // defaulting to the root match - function findNearestBoundary(matches, routeId) { - let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches]; - return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0]; - } - function getShortCircuitMatches(routes) { - // Prefer a root layout route if present, otherwise shim in a route object - let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === "/") || { - id: "__shim-error-route__" - }; - return { - matches: [{ - params: {}, - pathname: "", - pathnameBase: "", - route - }], - route - }; - } - function getInternalRouterError(status, _temp5) { - let { - pathname, - routeId, - method, - type - } = _temp5 === void 0 ? {} : _temp5; - let statusText = "Unknown Server Error"; - let errorMessage = "Unknown @remix-run/router error"; - if (status === 400) { - statusText = "Bad Request"; - if (method && pathname && routeId) { - errorMessage = "You made a " + method + " request to \"" + pathname + "\" but " + ("did not provide a `loader` for route \"" + routeId + "\", ") + "so there is no way to handle the request."; - } else if (type === "defer-action") { - errorMessage = "defer() is not supported in actions"; - } else if (type === "invalid-body") { - errorMessage = "Unable to encode submission body"; - } - } else if (status === 403) { - statusText = "Forbidden"; - errorMessage = "Route \"" + routeId + "\" does not match URL \"" + pathname + "\""; - } else if (status === 404) { - statusText = "Not Found"; - errorMessage = "No route matches URL \"" + pathname + "\""; - } else if (status === 405) { - statusText = "Method Not Allowed"; - if (method && pathname && routeId) { - errorMessage = "You made a " + method.toUpperCase() + " request to \"" + pathname + "\" but " + ("did not provide an `action` for route \"" + routeId + "\", ") + "so there is no way to handle the request."; - } else if (method) { - errorMessage = "Invalid request method \"" + method.toUpperCase() + "\""; - } - } - return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true); - } - - // Find any returned redirect errors, starting from the lowest match - function findRedirect(results) { - for (let i = results.length - 1; i >= 0; i--) { - let result = results[i]; - if (isRedirectResult(result)) { - return { - result, - idx: i - }; - } - } - } - function stripHashFromPath(path) { - let parsedPath = typeof path === "string" ? parsePath(path) : path; - return createPath(_extends({}, parsedPath, { - hash: "" - })); - } - function isHashChangeOnly(a, b) { - if (a.pathname !== b.pathname || a.search !== b.search) { - return false; - } - if (a.hash === "") { - // /page -> /page#hash - return b.hash !== ""; - } else if (a.hash === b.hash) { - // /page#hash -> /page#hash - return true; - } else if (b.hash !== "") { - // /page#hash -> /page#other - return true; - } - - // If the hash is removed the browser will re-perform a request to the server - // /page#hash -> /page - return false; - } - function isHandlerResult(result) { - return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === ResultType.data || result.type === ResultType.error); - } - function isRedirectHandlerResult(result) { - return isResponse(result.result) && redirectStatusCodes.has(result.result.status); - } - function isDeferredResult(result) { - return result.type === ResultType.deferred; - } - function isErrorResult(result) { - return result.type === ResultType.error; - } - function isRedirectResult(result) { - return (result && result.type) === ResultType.redirect; - } - function isDeferredData(value) { - let deferred = value; - return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function"; - } - function isResponse(value) { - return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined"; - } - function isRedirectResponse(result) { - if (!isResponse(result)) { - return false; - } - let status = result.status; - let location = result.headers.get("Location"); - return status >= 300 && status <= 399 && location != null; - } - function isValidMethod(method) { - return validRequestMethods.has(method.toLowerCase()); - } - function isMutationMethod(method) { - return validMutationMethods.has(method.toLowerCase()); - } - async function resolveDeferredResults(currentMatches, matchesToLoad, results, signals, isFetcher, currentLoaderData) { - for (let index = 0; index < results.length; index++) { - let result = results[index]; - let match = matchesToLoad[index]; - // If we don't have a match, then we can have a deferred result to do - // anything with. This is for revalidating fetchers where the route was - // removed during HMR - if (!match) { - continue; - } - let currentMatch = currentMatches.find(m => m.route.id === match.route.id); - let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined; - if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) { - // Note: we do not have to touch activeDeferreds here since we race them - // against the signal in resolveDeferredData and they'll get aborted - // there if needed - let signal = signals[index]; - invariant(signal, "Expected an AbortSignal for revalidating fetcher deferred result"); - await resolveDeferredData(result, signal, isFetcher).then(result => { - if (result) { - results[index] = result || results[index]; - } - }); - } - } - } - async function resolveDeferredData(result, signal, unwrap) { - if (unwrap === void 0) { - unwrap = false; - } - let aborted = await result.deferredData.resolveData(signal); - if (aborted) { - return; - } - if (unwrap) { - try { - return { - type: ResultType.data, - data: result.deferredData.unwrappedData - }; - } catch (e) { - // Handle any TrackedPromise._error values encountered while unwrapping - return { - type: ResultType.error, - error: e - }; - } - } - return { - type: ResultType.data, - data: result.deferredData.data - }; - } - function hasNakedIndexQuery(search) { - return new URLSearchParams(search).getAll("index").some(v => v === ""); - } - function getTargetMatch(matches, location) { - let search = typeof location === "string" ? parsePath(location).search : location.search; - if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) { - // Return the leaf index route when index is present - return matches[matches.length - 1]; - } - // Otherwise grab the deepest "path contributing" match (ignoring index and - // pathless layout routes) - let pathMatches = getPathContributingMatches(matches); - return pathMatches[pathMatches.length - 1]; - } - function getSubmissionFromNavigation(navigation) { - let { - formMethod, - formAction, - formEncType, - text, - formData, - json - } = navigation; - if (!formMethod || !formAction || !formEncType) { - return; - } - if (text != null) { - return { - formMethod, - formAction, - formEncType, - formData: undefined, - json: undefined, - text - }; - } else if (formData != null) { - return { - formMethod, - formAction, - formEncType, - formData, - json: undefined, - text: undefined - }; - } else if (json !== undefined) { - return { - formMethod, - formAction, - formEncType, - formData: undefined, - json, - text: undefined - }; - } - } - function getLoadingNavigation(location, submission) { - if (submission) { - let navigation = { - state: "loading", - location, - formMethod: submission.formMethod, - formAction: submission.formAction, - formEncType: submission.formEncType, - formData: submission.formData, - json: submission.json, - text: submission.text - }; - return navigation; - } else { - let navigation = { - state: "loading", - location, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined - }; - return navigation; - } - } - function getSubmittingNavigation(location, submission) { - let navigation = { - state: "submitting", - location, - formMethod: submission.formMethod, - formAction: submission.formAction, - formEncType: submission.formEncType, - formData: submission.formData, - json: submission.json, - text: submission.text - }; - return navigation; - } - function getLoadingFetcher(submission, data) { - if (submission) { - let fetcher = { - state: "loading", - formMethod: submission.formMethod, - formAction: submission.formAction, - formEncType: submission.formEncType, - formData: submission.formData, - json: submission.json, - text: submission.text, - data - }; - return fetcher; - } else { - let fetcher = { - state: "loading", - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined, - data - }; - return fetcher; - } - } - function getSubmittingFetcher(submission, existingFetcher) { - let fetcher = { - state: "submitting", - formMethod: submission.formMethod, - formAction: submission.formAction, - formEncType: submission.formEncType, - formData: submission.formData, - json: submission.json, - text: submission.text, - data: existingFetcher ? existingFetcher.data : undefined - }; - return fetcher; - } - function getDoneFetcher(data) { - let fetcher = { - state: "idle", - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined, - data - }; - return fetcher; - } - function restoreAppliedTransitions(_window, transitions) { - try { - let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY); - if (sessionPositions) { - let json = JSON.parse(sessionPositions); - for (let [k, v] of Object.entries(json || {})) { - if (v && Array.isArray(v)) { - transitions.set(k, new Set(v || [])); - } - } - } - } catch (e) { - // no-op, use default empty object - } - } - function persistAppliedTransitions(_window, transitions) { - if (transitions.size > 0) { - let json = {}; - for (let [k, v] of transitions) { - json[k] = [...v]; - } - try { - _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json)); - } catch (error) { - warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ")."); - } - } - } - - //#endregion - - exports.AbortedDeferredError = AbortedDeferredError; - exports.Action = Action; - exports.IDLE_BLOCKER = IDLE_BLOCKER; - exports.IDLE_FETCHER = IDLE_FETCHER; - exports.IDLE_NAVIGATION = IDLE_NAVIGATION; - exports.UNSAFE_DEFERRED_SYMBOL = UNSAFE_DEFERRED_SYMBOL; - exports.UNSAFE_DeferredData = DeferredData; - exports.UNSAFE_ErrorResponseImpl = ErrorResponseImpl; - exports.UNSAFE_convertRouteMatchToUiMatch = convertRouteMatchToUiMatch; - exports.UNSAFE_convertRoutesToDataRoutes = convertRoutesToDataRoutes; - exports.UNSAFE_getResolveToMatches = getResolveToMatches; - exports.UNSAFE_invariant = invariant; - exports.UNSAFE_warning = warning; - exports.createBrowserHistory = createBrowserHistory; - exports.createHashHistory = createHashHistory; - exports.createMemoryHistory = createMemoryHistory; - exports.createPath = createPath; - exports.createRouter = createRouter; - exports.createStaticHandler = createStaticHandler; - exports.defer = defer; - exports.generatePath = generatePath; - exports.getStaticContextFromError = getStaticContextFromError; - exports.getToPathname = getToPathname; - exports.isDeferredData = isDeferredData; - exports.isRouteErrorResponse = isRouteErrorResponse; - exports.joinPaths = joinPaths; - exports.json = json; - exports.matchPath = matchPath; - exports.matchRoutes = matchRoutes; - exports.normalizePathname = normalizePathname; - exports.parsePath = parsePath; - exports.redirect = redirect; - exports.redirectDocument = redirectDocument; - exports.resolvePath = resolvePath; - exports.resolveTo = resolveTo; - exports.stripBasename = stripBasename; - - Object.defineProperty(exports, '__esModule', { value: true }); - -})); -//# sourceMappingURL=router.umd.js.map diff --git a/node_modules/@remix-run/router/dist/router.umd.js.map b/node_modules/@remix-run/router/dist/router.umd.js.map deleted file mode 100644 index b41079a3..00000000 --- a/node_modules/@remix-run/router/dist/router.umd.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"router.umd.js","sources":["../history.ts","../utils.ts","../router.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 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, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial;\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 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;\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 () 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(\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 // eslint-disable-next-line no-console\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 // eslint-disable-next-line no-empty\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 {\n let location: Readonly = {\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 */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial) {\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 */\nexport function parsePath(path: string): Partial {\n let parsedPath: Partial = {};\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 { 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 deferred = \"deferred\",\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 * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n type: ResultType.deferred;\n deferredData: DeferredData;\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 =\n | SuccessResult\n | DeferredResult\n | RedirectResult\n | ErrorResult;\n\n/**\n * Result from a loader or action called via dataStrategy\n */\nexport interface HandlerResult {\n type: \"data\" | \"error\";\n result: unknown; // data, Error, Response, DeferredData\n status?: number;\n}\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase;\n\n/**\n * Users can specify either lowercase or uppercase form methods on ``,\n * useSubmit(), ``, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude;\n\n/**\n * In v7, 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 V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude;\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 | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_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 {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs\n extends DataFunctionArgs {}\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 | null;\n\ntype DataFunctionReturnValue = Promise | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction = {\n (\n args: LoaderFunctionArgs,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (\n args: ActionFunctionArgs,\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 unstable_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\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\nexport interface DataStrategyMatch\n extends AgnosticRouteMatch {\n shouldLoad: boolean;\n resolve: (\n handlerOverride?: (\n handler: (ctx?: unknown) => DataFunctionReturnValue\n ) => Promise\n ) => Promise;\n}\n\nexport interface DataStrategyFunctionArgs\n extends DataFunctionArgs {\n matches: DataStrategyMatch[];\n}\n\nexport interface DataStrategyFunction {\n (args: DataStrategyFunctionArgs): Promise;\n}\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;\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([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit & Required> : 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 {\n (): Promise>>;\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;\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;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam | _PathParam\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 =\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\n : // look for params in the absence of wildcards\n _PathParam;\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 =\n // if you could not find path params, fallback to `string`\n [PathParam] extends [never] ? string : PathParam;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params = {\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;\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 {}\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: number[] = [],\n manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, 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 * @see https://reactrouter.com/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename = \"/\"\n): AgnosticRouteMatch[] | 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(branches[i], decoded);\n }\n\n return matches;\n}\n\nexport interface UIMatch {\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[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta = {\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\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,\n pathname: string\n): AgnosticRouteMatch[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch[] = [];\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 if (!match) return null;\n\n Object.assign(matchedParams, match.params);\n\n let route = meta.route;\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params,\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 * @see https://reactrouter.com/utils/generate-path\n */\nexport function generatePath(\n originalPath: Path,\n params: {\n [key in PathParam]: 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;\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];\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 {\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 {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\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 = {\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 * @see https://reactrouter.com/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey,\n Path extends string\n>(\n pattern: PathPattern | Path,\n pathname: string\n): PathMatch | 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>(\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\nfunction 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 * @see https://reactrouter.com/utils/resolve-path\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\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 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 * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \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[], v7_relativeSplatPath: boolean) {\n let pathMatches = getPathContributingMatches(matches);\n\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) =>\n idx === matches.length - 1 ? match.pathname : match.pathnameBase\n );\n }\n\n return pathMatches.map((match) => match.pathnameBase);\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;\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 `` 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 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 function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\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\nexport type JsonFunction = (\n data: Data,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\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 interface TrackedPromise extends Promise {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeysSet: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record,\n init?: number | ResponseInit\n) => DeferredData;\n\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\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 */\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 */\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\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 */\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 HistoryAction,\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 DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n HandlerResult,\n ImmutableRouteKey,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\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 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 * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the future config for the router\n */\n get future(): FutureConfig;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\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 * @internal\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 * @internal\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,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\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;\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;\n\n /**\n * @internal\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 ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\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 * @internal\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 * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(key: string): Fetcher;\n\n /**\n * @internal\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 * @internal\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @internal\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 * @internal\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 * @internal\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 * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map;\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 /**\n * The action of the most recent navigation\n */\n historyAction: HistoryAction;\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;\n\n /**\n * Map of current blockers\n */\n blockers: Map;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_partialHydration: boolean;\n v7_prependBasename: boolean;\n v7_relativeSplatPath: boolean;\n unstable_skipActionErrorRevalidation: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n hydrationData?: HydrationState;\n window?: Window;\n unstable_dataStrategy?: DataStrategyFunction;\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;\n actionHeaders: Record;\n activeDeferreds: Record | null;\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 unstable_dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\n queryRoute(\n request: Request,\n opts?: {\n routeId?: string;\n requestContext?: unknown;\n unstable_dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\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 unstable_viewTransitionOpts?: ViewTransitionOpts;\n unstable_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\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n unstable_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 */\ntype FetcherStates = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\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 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 =\n FetcherStates[keyof FetcherStates];\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: HistoryAction;\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 * 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 * 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(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set(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//#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 const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\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.unstable_dataStrategy || defaultDataStrategy;\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n unstable_skipActionErrorRevalidation: false,\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();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record | 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 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) {\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 let initialized: boolean;\n let hasLazyRoutes = initialMatches.some((m) => m.route.lazy);\n let hasLoaders = initialMatches.some((m) => m.route.loader);\n if (hasLazyRoutes) {\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 (!hasLoaders) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, 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 let isRouteInitialized = (m: AgnosticDataRouteMatch) => {\n // No loader, nothing to initialize\n if (!m.route.loader) {\n return true;\n }\n // Explicitly opting-in to running on hydration\n if (\n typeof m.route.loader === \"function\" &&\n m.route.loader.hydrate === true\n ) {\n return false;\n }\n // Otherwise, initialized if hydrated with data or an error\n return (\n (loaderData && loaderData[m.route.id] !== undefined) ||\n (errors && errors[m.route.id] !== undefined)\n );\n };\n\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.slice(0, idx + 1).every(isRouteInitialized);\n } else {\n initialized = initialMatches.every(isRouteInitialized);\n }\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\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: HistoryAction = HistoryAction.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> = new Map<\n string,\n Set\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 routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\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();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\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();\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 ignoreNextHistoryUpdate = false;\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 (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\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 ignoreNextHistoryUpdate = true;\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\n 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 fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.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,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\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: deletedFetchersKeys,\n unstable_viewTransitionOpts: opts.viewTransitionOpts,\n unstable_flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n }\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>,\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 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 === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.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 === HistoryAction.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([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 = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\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 ): Promise {\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 future.v7_prependBasename,\n to,\n future.v7_relativeSplatPath,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\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 = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.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 = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.unstable_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 return 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.unstable_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 interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\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;\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;\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 { overrideNavigation: state.navigation }\n );\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: HistoryAction,\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 {\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 // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\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 load will always\n // be \"same hash\". For example, on /page#hash and submit a \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 { replace: opts.replace, flushSync }\n );\n\n if (actionResult.shortCircuited) {\n return;\n }\n\n pendingActionResult = actionResult.pendingActionResult;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = 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 { shortCircuited, loaderData, errors } = await handleLoaders(\n request,\n location,\n matches,\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,\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 opts: { replace?: boolean; flushSync?: boolean } = {}\n ): Promise {\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 // 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 request,\n [actionMatch],\n matches\n );\n result = results[0];\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, {\n submission,\n replace,\n });\n return { shortCircuited: true };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\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 are REPLACE navigations, but if the\n // action threw an error that'll be rendered in an errorElement, we fall\n // back to PUSH so that the user can use the back button to get back to\n // the pre-submission form location to try again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n pendingActionResult: [boundaryMatch.route.id, result],\n };\n }\n\n return {\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 overrideNavigation?: Navigation,\n submission?: Submission,\n fetcherSubmission?: Submission,\n replace?: boolean,\n initialHydration?: boolean,\n flushSync?: boolean,\n pendingActionResult?: PendingActionResult\n ): Promise {\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 let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n future.v7_partialHydration && initialHydration === true,\n future.unstable_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionResult\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\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 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 // If we have partialHydration enabled, then don't update the state for the\n // initial data load since it's not a \"navigation\"\n if (\n !isUninterruptedRevalidation &&\n (!future.v7_partialHydration || !initialHydration)\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\n let actionData: Record | 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 actionData = {\n [pendingActionResult[0]]: pendingActionResult[1].data as any,\n };\n } else if (state.actionData) {\n if (Object.keys(state.actionData).length === 0) {\n actionData = null;\n } else {\n actionData = state.actionData;\n }\n }\n\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData !== undefined ? { actionData } : {}),\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n revalidatingFetchers.forEach((rf) => {\n if (fetchControllers.has(rf.key)) {\n abortFetcher(rf.key);\n }\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.matches,\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 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, ...fetcherResults]);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\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 let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n await startRedirectNavigation(request, redirect.result, {\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 matchesToLoad,\n loaderResults,\n pendingActionResult,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe((aborted) => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n\n // During partial hydration, preserve SSR errors for routes that don't re-run\n if (future.v7_partialHydration && initialHydration && state.errors) {\n Object.entries(state.errors)\n .filter(([id]) => !matchesToLoad.some((m) => m.route.id === id))\n .forEach(([routeId, error]) => {\n errors = Object.assign(errors || {}, { [routeId]: error });\n });\n }\n\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n if (fetchControllers.has(key)) abortFetcher(key);\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n future.v7_relativeSplatPath,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\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 future.v7_normalizeFormMethod,\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 pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\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 handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\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 flushSync: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action && !match.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;\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 // Call the action for the fetcher\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResults = await callDataStrategy(\n \"action\",\n fetchRequest,\n [match],\n requestMatches\n );\n let actionResult = actionResults[0];\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 // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.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, {\n fetcherSubmission: submission,\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 if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\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 future.unstable_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\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 if (fetchControllers.has(staleKey)) {\n abortFetcher(staleKey);\n }\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.matches,\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, ...fetcherResults]);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\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 let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n return startRedirectNavigation(revalidationRequest, redirect.result);\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n state.matches,\n matchesToLoad,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\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 flushSync: 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 // Call the loader for this fetcher route match\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let results = await callDataStrategy(\n \"loader\",\n fetchRequest,\n [match],\n matches\n );\n let result = results[0];\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\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 (deletedFetchers.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);\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 invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\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 {\n submission,\n fetcherSubmission,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\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 redirectHistoryAction =\n replace === true ? HistoryAction.Replace : HistoryAction.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(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: location,\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\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(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\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 request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[]\n ): Promise {\n try {\n let results = await callDataStrategyImpl(\n dataStrategyImpl,\n type,\n request,\n matchesToLoad,\n matches,\n manifest,\n mapRouteProperties\n );\n\n return await Promise.all(\n results.map((result, i) => {\n if (isRedirectHandlerResult(result)) {\n let response = result.result as Response;\n return {\n type: ResultType.redirect,\n response: normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n matchesToLoad[i].route.id,\n matches,\n basename,\n future.v7_relativeSplatPath\n ),\n };\n }\n\n return convertHandlerResultToDataResult(result);\n })\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 return matchesToLoad.map(() => ({\n type: ResultType.error,\n error: e,\n }));\n }\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n let [loaderResults, ...fetcherResults] = await Promise.all([\n matchesToLoad.length\n ? callDataStrategy(\"loader\", request, matchesToLoad, matches)\n : [],\n ...fetchersToLoad.map((f) => {\n if (f.matches && f.match && f.controller) {\n let fetcherRequest = createClientSideRequest(\n init.history,\n f.path,\n f.controller.signal\n );\n return callDataStrategy(\n \"loader\",\n fetcherRequest,\n [f.match],\n f.matches\n ).then((r) => r[0]);\n } else {\n return Promise.resolve({\n type: ResultType.error,\n error: getInternalRouterError(404, {\n pathname: f.path,\n }),\n });\n }\n }),\n ]);\n\n await Promise.all([\n resolveDeferredResults(\n currentMatches,\n matchesToLoad,\n loaderResults,\n loaderResults.map(() => request.signal),\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map((f) => f.match),\n fetcherResults,\n fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)),\n true\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 // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.push(key);\n abortFetcher(key);\n }\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(key: string): Fetcher {\n if (future.v7_fetcherPersist) {\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 (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\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 deletedFetchers.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n if (future.v7_fetcherPersist) {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n } else {\n activeFetchers.set(key, count);\n }\n } else {\n deleteFetcher(key);\n }\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n invariant(controller, `Expected fetch controller: ${key}`);\n controller.abort();\n fetchControllers.delete(key);\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: HistoryAction;\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 cancelActiveDeferreds(\n predicate?: (routeId: string) => boolean\n ): string[] {\n let cancelledRouteIds: string[] = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the component\n function enableScrollRestoration(\n positions: Record,\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 \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 _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\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: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\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 const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n v7_relativeSplatPath: boolean;\n v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\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: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future: StaticHandlerFutureConfig = {\n v7_relativeSplatPath: false,\n v7_throwAbortReason: false,\n ...(opts ? opts.future : null),\n };\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 unstable_dataStrategy,\n }: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n unstable_dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\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 activeDeferreds: null,\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 activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n unstable_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 unstable_dataStrategy,\n }: {\n requestContext?: unknown;\n routeId?: string;\n unstable_dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\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 unstable_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 let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n unstable_dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null\n ): Promise | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n unstable_dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n unstable_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 `HandlerResult` to bail out early\n // and then return or throw the raw Response here accordingly\n if (isHandlerResult(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 unstable_dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n isRouteRequest: boolean\n ): Promise | 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 unstable_dataStrategy\n );\n result = results[0];\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\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 (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\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 activeDeferreds: null,\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 unstable_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 unstable_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 unstable_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 activeDeferreds: null,\n };\n }\n\n let results = await callDataStrategy(\n \"loader\",\n request,\n matchesToLoad,\n matches,\n isRouteRequest,\n requestContext,\n unstable_dataStrategy\n );\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionResult,\n activeDeferreds,\n skipLoaderErrorBubbling\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(\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 activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\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 unstable_dataStrategy: DataStrategyFunction | null\n ): Promise {\n let results = await callDataStrategyImpl(\n unstable_dataStrategy || defaultDataStrategy,\n type,\n request,\n matchesToLoad,\n matches,\n manifest,\n mapRouteProperties,\n requestContext\n );\n\n return await Promise.all(\n results.map((result, i) => {\n if (isRedirectHandlerResult(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 matchesToLoad[i].route.id,\n matches,\n basename,\n future.v7_relativeSplatPath\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 return convertHandlerResultToDataResult(result);\n })\n );\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 */\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 future: StaticHandlerFutureConfig\n) {\n if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n throw request.signal.reason;\n }\n\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\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 prependBasename: boolean,\n to: To | null,\n v7_relativeSplatPath: boolean,\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, v7_relativeSplatPath),\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 // Add an ?index param for matched index routes if we don't already have one\n if (\n (to == null || to === \"\" || to === \".\") &&\n activeRouteMatch &&\n activeRouteMatch.route.index &&\n !hasNakedIndexQuery(path.search)\n ) {\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. 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 (prependBasename && 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 normalizeFormMethod: boolean,\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 = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() 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 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) {\n let boundaryMatches = matches;\n if (boundaryId) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n boundaryMatches = matches.slice(0, index);\n }\n }\n return boundaryMatches;\n}\n\nfunction getMatchesToLoad(\n history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isInitialLoad: boolean,\n skipActionErrorRevalidation: boolean,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n deletedFetchers: Set,\n fetchLoadMatches: Map,\n fetchRedirectIds: Set,\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 boundaryId =\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? pendingActionResult[0]\n : undefined;\n let boundaryMatches = boundaryId\n ? getLoaderMatchesUntilBoundary(matches, boundaryId)\n : matches;\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 =\n skipActionErrorRevalidation && 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 (isInitialLoad) {\n if (typeof route.loader !== \"function\" || route.loader.hydrate) {\n return true;\n }\n return (\n state.loaderData[route.id] === undefined &&\n // Don't re-run if the loader ran and threw an error\n (!state.errors || state.errors[route.id] === undefined)\n );\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\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 unstable_actionStatus: 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 load (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 isInitialLoad ||\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.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.includes(key)) {\n // Always revalidate if the fetcher was cancelled\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 unstable_actionStatus: 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 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 or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\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\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 = {};\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\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // 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\nfunction defaultDataStrategy(\n opts: DataStrategyFunctionArgs\n): ReturnType {\n return Promise.all(opts.matches.map((m) => m.resolve()));\n}\n\nasync function callDataStrategyImpl(\n dataStrategyImpl: DataStrategyFunction,\n type: \"loader\" | \"action\",\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n requestContext?: unknown\n): Promise {\n let routeIdsToLoad = matchesToLoad.reduce(\n (acc, m) => acc.add(m.route.id),\n new Set()\n );\n let loadedMatches = new Set();\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: matches.map((match) => {\n let shouldLoad = routeIdsToLoad.has(match.route.id);\n // `resolve` encapsulates the route.lazy, executing the\n // loader/action, and mapping return values/thrown errors to a\n // HandlerResult. Users can pass a callback to take fine-grained control\n // over the execution of the loader/action\n let resolve: DataStrategyMatch[\"resolve\"] = (handlerOverride) => {\n loadedMatches.add(match.route.id);\n return shouldLoad\n ? callLoaderOrAction(\n type,\n request,\n match,\n manifest,\n mapRouteProperties,\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 request,\n params: matches[0].params,\n context: requestContext,\n });\n\n // Throw if any loadRoute implementations not called since they are what\n // ensures a route is fully loaded\n matches.forEach((m) =>\n invariant(\n loadedMatches.has(m.route.id),\n `\\`match.resolve()\\` was not called for route id \"${m.route.id}\". ` +\n \"You must call `match.resolve()` on every match passed to \" +\n \"`dataStrategy` to ensure all routes are properly loaded.\"\n )\n );\n\n // Filter out any middleware-only matches for which we didn't need to run handlers\n return results.filter((_, i) => routeIdsToLoad.has(matches[i].route.id));\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 manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n handlerOverride: Parameters[0],\n staticContext?: unknown\n): Promise {\n let result: HandlerResult;\n let onReject: (() => void) | undefined;\n\n let runHandler = (\n handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n ): Promise => {\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 to\n // satisfy the function return value\n let abortPromise = new Promise((_, 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;\n if (handlerOverride) {\n handlerPromise = handlerOverride((ctx: unknown) => actualHandler(ctx));\n } else {\n handlerPromise = (async () => {\n try {\n let val = await actualHandler();\n return { type: \"data\", result: val };\n } catch (e) {\n return { type: \"error\", result: e };\n }\n })();\n }\n\n return Promise.race([handlerPromise, abortPromise]);\n };\n\n try {\n let handler = match.route[type];\n\n if (match.route.lazy) {\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 loadLazyRouteModule(match.route, mapRouteProperties, manifest),\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 loadLazyRouteModule(match.route, mapRouteProperties, manifest);\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\n invariant(\n result.result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n // We should already be catching and converting normal handler executions to\n // HandlerResults 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 convertHandlerResultToDataResult(\n handlerResult: HandlerResult\n): Promise {\n let { result, type, status } = handlerResult;\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 return {\n type: ResultType.error,\n error: result,\n statusCode: isRouteErrorResponse(result) ? result.status : status,\n };\n }\n\n if (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n return { type: ResultType.data, data: result, statusCode: status };\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 v7_relativeSplatPath: boolean\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 true,\n location,\n v7_relativeSplatPath\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 matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingActionResult: PendingActionResult | undefined,\n activeDeferreds: Map,\n skipLoaderErrorBubbling: boolean\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record;\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 = {};\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 results.forEach((result, index) => {\n let id = matchesToLoad[index].route.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 loaderData[id] = undefined;\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 if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.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 (\n result.statusCode != null &&\n result.statusCode !== 200 &&\n !foundError\n ) {\n statusCode = result.statusCode;\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\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 matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingActionResult: PendingActionResult | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: DataResult[],\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionResult,\n activeDeferreds,\n false // This method is only called client side so we always want to bubble\n );\n\n // Process results from our revalidating fetchers\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let { key, match, controller } = revalidatingFetchers[index];\n invariant(\n fetcherResults !== undefined && fetcherResults[index] !== undefined,\n \"Did not find corresponding fetcher result\"\n );\n let result = fetcherResults[index];\n\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n continue;\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 if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\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 let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\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 }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\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 === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\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: DataResult[]\n): { result: RedirectResult; idx: number } | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return { result, idx: i };\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 isHandlerResult(result: unknown): result is HandlerResult {\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 isRedirectHandlerResult(result: HandlerResult) {\n return (\n isResponse(result.result) && redirectStatusCodes.has(result.result.status)\n );\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\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 isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\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 | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: (AgnosticDataRouteMatch | null)[],\n results: DataResult[],\n signals: (AbortSignal | null)[],\n isFetcher: boolean,\n currentLoaderData?: RouteData\n) {\n for (let index = 0; index < results.length; index++) {\n let result = results[index];\n let match = matchesToLoad[index];\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n let signal = signals[index];\n invariant(\n signal,\n \"Expected an AbortSignal for revalidating fetcher deferred result\"\n );\n await resolveDeferredData(result, signal, isFetcher).then((result) => {\n if (result) {\n results[index] = result || results[index];\n }\n });\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise {\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData,\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e,\n };\n }\n }\n\n return {\n type: ResultType.data,\n data: result.deferredData.data,\n };\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>\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>\n) {\n if (transitions.size > 0) {\n let json: Record = {};\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\n//#endregion\n"],"names":["Action","PopStateEventType","createMemoryHistory","options","initialEntries","initialIndex","v5Compat","entries","map","entry","index","createMemoryLocation","state","undefined","clampIndex","length","action","Pop","listener","n","Math","min","max","getCurrentLocation","to","key","location","createLocation","pathname","warning","charAt","JSON","stringify","createHref","createPath","history","createURL","URL","encodeLocation","path","parsePath","search","hash","push","Push","nextLocation","splice","delta","replace","Replace","go","nextIndex","listen","fn","createBrowserHistory","createBrowserLocation","window","globalHistory","usr","createBrowserHref","getUrlBasedHistory","createHashHistory","createHashLocation","substr","startsWith","createHashHref","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","validateHashLocation","invariant","value","message","Error","cond","console","warn","e","createKey","random","toString","getHistoryState","idx","current","_extends","_ref","parsedPath","searchIndex","getLocation","validateLocation","defaultView","getIndex","replaceState","handlePop","historyState","pushState","error","DOMException","name","assign","origin","addEventListener","removeEventListener","ResultType","immutableRouteKeys","Set","isIndexRoute","route","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","treePath","id","join","children","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","stripBasename","branches","flattenRoutes","rankRouteBranches","matches","i","decoded","decodePath","matchRouteBranch","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","meta","caseSensitive","childrenIndex","joinPaths","routesMeta","concat","score","computeScore","forEach","_route$path","includes","exploded","explodeOptionalSegments","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","sort","a","b","compareIndexes","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","initialScore","some","filter","reduce","segment","test","siblings","every","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","generatePath","originalPath","prefix","p","String","array","isLastSegment","star","keyMatch","optional","param","pattern","matcher","compiledParams","compilePath","captureGroups","memo","paramName","splatValue","regexpSource","_","RegExp","v","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","resolvePathname","normalizeSearch","normalizeHash","relativeSegments","pop","getInvalidPathError","char","field","dest","getPathContributingMatches","getResolveToMatches","v7_relativeSplatPath","pathMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","getToPathname","paths","json","init","responseInit","status","headers","Headers","has","set","Response","AbortedDeferredError","DeferredData","constructor","pendingKeysSet","subscribers","deferredKeys","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","_ref2","trackPromise","done","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","k","resolveData","resolve","size","unwrappedData","_ref3","unwrapTrackedPromise","pendingKeys","isTrackedPromise","_tracked","_error","_data","defer","redirect","redirectDocument","response","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","createRouter","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","dataRoutes","inFlightDataRoutes","dataStrategyImpl","unstable_dataStrategy","defaultDataStrategy","future","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_prependBasename","unstable_skipActionErrorRevalidation","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialErrors","getInternalRouterError","getShortCircuitMatches","initialized","hasLazyRoutes","m","lazy","hasLoaders","loader","errors","isRouteInitialized","hydrate","findIndex","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","actionData","fetchers","Map","blockers","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeFetchers","deletedFetchers","activeDeferreds","blockerFunctions","ignoreNextHistoryUpdate","initialize","blockerKey","shouldBlockNavigation","currentLocation","updateBlocker","updateState","startNavigation","restoreAppliedTransitions","_saveAppliedTransitions","persistAppliedTransitions","initialHydration","dispose","clear","deleteFetcher","deleteBlocker","newState","opts","completedFetchers","deletedFetchersKeys","fetcher","unstable_viewTransitionOpts","viewTransitionOpts","unstable_flushSync","flushSync","completeNavigation","_temp","_location$state","_location$state2","isActionReload","isMutationMethod","_isRedirect","keys","mergeLoaderData","priorPaths","toPaths","getSavedScrollPosition","navigate","normalizedPath","normalizeTo","fromRouteId","relative","submission","normalizeNavigateOptions","userReplace","pendingError","enableViewTransition","unstable_viewTransition","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","routesToUse","loadingNavigation","notFoundMatches","cancelActiveDeferreds","isHashChangeOnly","request","createClientSideRequest","pendingActionResult","findNearestBoundary","type","actionResult","handleAction","shortCircuited","getLoadingNavigation","handleLoaders","fetcherSubmission","getActionDataForCommit","getSubmittingNavigation","actionMatch","getTargetMatch","method","routeId","results","callDataStrategy","isRedirectResult","normalizeRedirectLocation","startRedirectNavigation","isDeferredResult","isErrorResult","boundaryMatch","activeSubmission","getSubmissionFromNavigation","matchesToLoad","revalidatingFetchers","getMatchesToLoad","updatedFetchers","markFetchRedirectsDone","rf","revalidatingFetcher","getLoadingFetcher","abortFetcher","abortPendingFetchRevalidations","f","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","findRedirect","fetcherKey","processLoaderData","deferredData","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","fetch","setFetcherError","handleFetcherAction","handleFetcherLoader","requestMatches","existingFetcher","updateFetcherState","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","actionResults","getDoneFetcher","revalidationRequest","loadId","loadFetcher","staleKey","doneFetcher","resolveDeferredData","_temp2","redirectLocation","isDocumentReload","redirectHistoryAction","callDataStrategyImpl","all","isRedirectHandlerResult","normalizeRelativeRoutingRedirectResponse","convertHandlerResultToDataResult","currentMatches","fetchersToLoad","fetcherRequest","resolveDeferredResults","getFetcher","deleteFetcherAndUpdateState","count","markFetchersDone","doneKeys","landedId","yeetedKeys","getBlocker","blocker","newBlocker","_ref4","blockerFunction","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","getScrollKey","_internalSetRoutes","newRoutes","_internalFetchControllers","_internalActiveDeferreds","UNSAFE_DEFERRED_SYMBOL","Symbol","createStaticHandler","v7_throwAbortReason","query","_temp3","requestContext","skipLoaderErrorBubbling","isValidMethod","methodNotAllowedMatches","statusCode","loaderHeaders","actionHeaders","queryImpl","isResponse","queryRoute","_temp4","find","values","_result$activeDeferre","routeMatch","submit","loadRouteData","isHandlerResult","isRedirectResponse","isRouteRequest","throwStaticHandlerAbortedError","Location","loaderRequest","Request","context","getLoaderMatchesUntilBoundary","processRouteLoaderData","executedLoaders","fromEntries","getStaticContextFromError","newContext","_deepestRenderedBoundaryId","reason","isSubmissionNavigation","body","prependBasename","contextualMatches","activeRouteMatch","hasNakedIndexQuery","normalizeFormMethod","isFetcher","getInvalidBodyError","rawFormMethod","toUpperCase","stripHashFromPath","FormData","URLSearchParams","_ref5","parse","searchParams","convertFormDataToSearchParams","convertSearchParamsToFormData","append","boundaryId","boundaryMatches","isInitialLoad","skipActionErrorRevalidation","currentUrl","nextUrl","actionStatus","shouldSkipRevalidation","navigationMatches","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","unstable_actionStatus","defaultShouldRevalidate","isNewRouteInstance","fetcherMatches","fetcherMatch","shouldRevalidate","currentLoaderData","currentMatch","isNew","isMissingData","currentPath","loaderMatch","arg","routeChoice","loadLazyRouteModule","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","staticRouteValue","isPropertyStaticallyDefined","routeIdsToLoad","loadedMatches","shouldLoad","handlerOverride","callLoaderOrAction","staticContext","onReject","runHandler","handler","actualHandler","ctx","handlerPromise","val","handlerError","handlerResult","contentType","isDeferredData","_result$init","_result$init2","deferred","trimmedMatches","normalizedLocation","protocol","isSameBasename","foundError","newLoaderData","mergedLoaderData","hasOwnProperty","eligibleMatches","reverse","_temp5","errorMessage","signals","isRevalidatingLoader","unwrap","getAll","_window","transitions","sessionPositions","sessionStorage","getItem","setItem"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAA;EACA;EACA;;EAEA;EACA;EACA;AACYA,MAAAA,MAAM,0BAANA,MAAM,EAAA;IAANA,MAAM,CAAA,KAAA,CAAA,GAAA,KAAA,CAAA;IAANA,MAAM,CAAA,MAAA,CAAA,GAAA,MAAA,CAAA;IAANA,MAAM,CAAA,SAAA,CAAA,GAAA,SAAA,CAAA;EAAA,EAAA,OAANA,MAAM,CAAA;EAAA,CAAA,CAAA,EAAA,EAAA;;EAwBlB;EACA;EACA;;EAkBA;EACA;EAEA;EACA;EACA;EACA;EAgBA;EACA;EACA;EAkBA;EACA;EACA;EAKA;EACA;EACA;EACA;EACA;EAGA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAgFA,MAAMC,iBAAiB,GAAG,UAAU,CAAA;EACpC;;EAEA;EACA;EACA;;EAE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AI,EAAE,CAAC,EAAE;UAC7C,IAAInC,CAAC,IAAIkD,KAAK,CAACC,OAAO,CAACnD,CAAC,CAAC,EAAE;EACzBse,UAAAA,WAAW,CAAC5b,GAAG,CAACwC,CAAC,EAAE,IAAI/L,GAAG,CAAC6G,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;EACtC,SAAA;EACF,OAAA;EACF,KAAA;KACD,CAAC,OAAOzI,CAAC,EAAE;EACV;EAAA,GAAA;EAEJ,CAAA;EAEA,SAASkV,yBAAyBA,CAChC4R,OAAe,EACfC,WAAqC,EACrC;EACA,EAAA,IAAIA,WAAW,CAACjZ,IAAI,GAAG,CAAC,EAAE;MACxB,IAAIlD,IAA8B,GAAG,EAAE,CAAA;MACvC,KAAK,IAAI,CAAC+C,CAAC,EAAElF,CAAC,CAAC,IAAIse,WAAW,EAAE;EAC9Bnc,MAAAA,IAAI,CAAC+C,CAAC,CAAC,GAAG,CAAC,GAAGlF,CAAC,CAAC,CAAA;EAClB,KAAA;MACA,IAAI;EACFqe,MAAAA,OAAO,CAACG,cAAc,CAACE,OAAO,CAC5BhX,uBAAuB,EACvBvT,IAAI,CAACC,SAAS,CAAC+N,IAAI,CACrB,CAAC,CAAA;OACF,CAAC,OAAOzJ,KAAK,EAAE;EACdzE,MAAAA,OAAO,CACL,KAAK,EACyDyE,6DAAAA,GAAAA,KAAK,OACrE,CAAC,CAAA;EACH,KAAA;EACF,GAAA;EACF,CAAA;;EAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@remix-run/router/dist/router.umd.min.js b/node_modules/@remix-run/router/dist/router.umd.min.js deleted file mode 100644 index 691e830d..00000000 --- a/node_modules/@remix-run/router/dist/router.umd.min.js +++ /dev/null @@ -1,12 +0,0 @@ -/** - * @remix-run/router v1.16.1 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).RemixRouter={})}(this,(function(e){"use strict";function t(){return t=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0&&(t.hash=e.substr(r),e=e.substr(0,r));let a=e.indexOf("?");a>=0&&(t.search=e.substr(a),e=e.substr(0,a)),e&&(t.pathname=e)}return t}function d(e,n,u,d){void 0===d&&(d={});let{window:c=document.defaultView,v5Compat:h=!1}=d,f=c.history,p=r.Pop,m=null,y=v();function v(){return(f.state||{idx:null}).idx}function g(){p=r.Pop;let e=v(),t=null==e?null:e-y;y=e,m&&m({action:p,location:w.location,delta:t})}function b(e){let t="null"!==c.location.origin?c.location.origin:c.location.href,r="string"==typeof e?e:l(e);return r=r.replace(/ $/,"%20"),o(t,"No window.location.(origin|href) available to create URL for href: "+r),new URL(r,t)}null==y&&(y=0,f.replaceState(t({},f.state,{idx:y}),""));let w={get action(){return p},get location(){return e(c,f)},listen(e){if(m)throw new Error("A history only accepts one active listener");return c.addEventListener(a,g),m=e,()=>{c.removeEventListener(a,g),m=null}},createHref:e=>n(c,e),createURL:b,encodeLocation(e){let t=b(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:function(e,t){p=r.Push;let a=s(w.location,e,t);u&&u(a,e),y=v()+1;let o=i(a,y),n=w.createHref(a);try{f.pushState(o,"",n)}catch(e){if(e instanceof DOMException&&"DataCloneError"===e.name)throw e;c.location.assign(n)}h&&m&&m({action:p,location:w.location,delta:1})},replace:function(e,t){p=r.Replace;let a=s(w.location,e,t);u&&u(a,e),y=v();let o=i(a,y),n=w.createHref(a);f.replaceState(o,"",n),h&&m&&m({action:p,location:w.location,delta:0})},go:e=>f.go(e)};return w}let c=function(e){return e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error",e}({});const h=new Set(["lazy","caseSensitive","path","id","index","children"]);function f(e,r,a,n){return void 0===a&&(a=[]),void 0===n&&(n={}),e.map(((e,i)=>{let s=[...a,i],l="string"==typeof e.id?e.id:s.join("-");if(o(!0!==e.index||!e.children,"Cannot specify children on an index route"),o(!n[l],'Found a route id collision on id "'+l+"\". Route id's must be globally unique within Data Router usages"),function(e){return!0===e.index}(e)){let a=t({},e,r(e),{id:l});return n[l]=a,a}{let a=t({},e,r(e),{id:l,children:void 0});return n[l]=a,e.children&&(a.children=f(e.children,r,s,n)),a}}))}function p(e,t,r){void 0===r&&(r="/");let a=R(("string"==typeof t?u(t):t).pathname||"/",r);if(null==a)return null;let o=y(e);!function(e){e.sort(((e,t)=>e.score!==t.score?t.score-e.score:function(e,t){return e.length===t.length&&e.slice(0,-1).every(((e,r)=>e===t[r]))?e[e.length-1]-t[t.length-1]:0}(e.routesMeta.map((e=>e.childrenIndex)),t.routesMeta.map((e=>e.childrenIndex)))))}(o);let n=null;for(let e=0;null==n&&e{let s={relativePath:void 0===i?e.path||"":i,caseSensitive:!0===e.caseSensitive,childrenIndex:n,route:e};s.relativePath.startsWith("/")&&(o(s.relativePath.startsWith(a),'Absolute route path "'+s.relativePath+'" nested under path "'+a+'" is not valid. An absolute child route path must start with the combined path of all its parent routes.'),s.relativePath=s.relativePath.slice(a.length));let l=j([a,s.relativePath]),u=r.concat(s);e.children&&e.children.length>0&&(o(!0!==e.index,'Index routes must not have child routes. Please remove all child routes from route path "'+l+'".'),y(e.children,t,u,l)),(null!=e.path||e.index)&&t.push({path:l,score:w(l,e.index),routesMeta:u})};return e.forEach(((e,t)=>{var r;if(""!==e.path&&null!=(r=e.path)&&r.includes("?"))for(let r of v(e.path))n(e,t,r);else n(e,t)})),t}function v(e){let t=e.split("/");if(0===t.length)return[];let[r,...a]=t,o=r.endsWith("?"),n=r.replace(/\?$/,"");if(0===a.length)return o?[n,""]:[n];let i=v(a.join("/")),s=[];return s.push(...i.map((e=>""===e?n:[n,e].join("/")))),o&&s.push(...i),s.map((t=>e.startsWith("/")&&""===t?"/":t))}const g=/^:[\w-]+$/,b=e=>"*"===e;function w(e,t){let r=e.split("/"),a=r.length;return r.some(b)&&(a+=-2),t&&(a+=2),r.filter((e=>!b(e))).reduce(((e,t)=>e+(g.test(t)?3:""===t?1:10)),a)}function D(e,t){let{routesMeta:r}=e,a={},o="/",n=[];for(let e=0;e(a.push({paramName:t,isOptional:null!=r}),r?"/?([^\\/]+)?":"/([^\\/]+)")));e.endsWith("*")?(a.push({paramName:"*"}),o+="*"===e||"/*"===e?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?o+="\\/*$":""!==e&&"/"!==e&&(o+="(?:(?=\\/|$))");return[new RegExp(o,t?void 0:"i"),a]}(e.path,e.caseSensitive,e.end),o=t.match(r);if(!o)return null;let i=o[0],s=i.replace(/(.)\/+$/,"$1"),l=o.slice(1);return{params:a.reduce(((e,t,r)=>{let{paramName:a,isOptional:o}=t;if("*"===a){let e=l[r]||"";s=i.slice(0,i.length-e.length).replace(/(.)\/+$/,"$1")}const n=l[r];return e[a]=o&&!n?void 0:(n||"").replace(/%2F/g,"/"),e}),{}),pathname:i,pathnameBase:s,pattern:e}}function E(e){try{return e.split("/").map((e=>decodeURIComponent(e).replace(/\//g,"%2F"))).join("/")}catch(t){return n(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent encoding ('+t+")."),e}}function R(e,t){if("/"===t)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let r=t.endsWith("/")?t.length-1:t.length,a=e.charAt(r);return a&&"/"!==a?null:e.slice(r)||"/"}function P(e,t){void 0===t&&(t="/");let{pathname:r,search:a="",hash:o=""}="string"==typeof e?u(e):e,n=r?r.startsWith("/")?r:function(e,t){let r=t.replace(/\/+$/,"").split("/");return e.split("/").forEach((e=>{".."===e?r.length>1&&r.pop():"."!==e&&r.push(e)})),r.length>1?r.join("/"):"/"}(r,t):t;return{pathname:n,search:_(a),hash:C(o)}}function x(e,t,r,a){return"Cannot include a '"+e+"' character in a manually specified `to."+t+"` field ["+JSON.stringify(a)+"]. Please separate it out to the `to."+r+'` field. Alternatively you may provide the full path as a string in and the router will parse it for you.'}function L(e){return e.filter(((e,t)=>0===t||e.route.path&&e.route.path.length>0))}function A(e,t){let r=L(e);return t?r.map(((t,r)=>r===e.length-1?t.pathname:t.pathnameBase)):r.map((e=>e.pathnameBase))}function M(e,r,a,n){let i;void 0===n&&(n=!1),"string"==typeof e?i=u(e):(i=t({},e),o(!i.pathname||!i.pathname.includes("?"),x("?","pathname","search",i)),o(!i.pathname||!i.pathname.includes("#"),x("#","pathname","hash",i)),o(!i.search||!i.search.includes("#"),x("#","search","hash",i)));let s,l=""===e||""===i.pathname,d=l?"/":i.pathname;if(null==d)s=a;else{let e=r.length-1;if(!n&&d.startsWith("..")){let t=d.split("/");for(;".."===t[0];)t.shift(),e-=1;i.pathname=t.join("/")}s=e>=0?r[e]:"/"}let c=P(i,s),h=d&&"/"!==d&&d.endsWith("/"),f=(l||"."===d)&&a.endsWith("/");return c.pathname.endsWith("/")||!h&&!f||(c.pathname+="/"),c}const j=e=>e.join("/").replace(/\/\/+/g,"/"),k=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),_=e=>e&&"?"!==e?e.startsWith("?")?e:"?"+e:"",C=e=>e&&"#"!==e?e.startsWith("#")?e:"#"+e:"";class T extends Error{}class U{constructor(e,t){let r;this.pendingKeysSet=new Set,this.subscribers=new Set,this.deferredKeys=[],o(e&&"object"==typeof e&&!Array.isArray(e),"defer() only accepts plain objects"),this.abortPromise=new Promise(((e,t)=>r=t)),this.controller=new AbortController;let a=()=>r(new T("Deferred data aborted"));this.unlistenAbortSignal=()=>this.controller.signal.removeEventListener("abort",a),this.controller.signal.addEventListener("abort",a),this.data=Object.entries(e).reduce(((e,t)=>{let[r,a]=t;return Object.assign(e,{[r]:this.trackPromise(r,a)})}),{}),this.done&&this.unlistenAbortSignal(),this.init=t}trackPromise(e,t){if(!(t instanceof Promise))return t;this.deferredKeys.push(e),this.pendingKeysSet.add(e);let r=Promise.race([t,this.abortPromise]).then((t=>this.onSettle(r,e,void 0,t)),(t=>this.onSettle(r,e,t)));return r.catch((()=>{})),Object.defineProperty(r,"_tracked",{get:()=>!0}),r}onSettle(e,t,r,a){if(this.controller.signal.aborted&&r instanceof T)return this.unlistenAbortSignal(),Object.defineProperty(e,"_error",{get:()=>r}),Promise.reject(r);if(this.pendingKeysSet.delete(t),this.done&&this.unlistenAbortSignal(),void 0===r&&void 0===a){let r=new Error('Deferred data for key "'+t+'" resolved/rejected with `undefined`, you must resolve/reject with a value or `null`.');return Object.defineProperty(e,"_error",{get:()=>r}),this.emit(!1,t),Promise.reject(r)}return void 0===a?(Object.defineProperty(e,"_error",{get:()=>r}),this.emit(!1,t),Promise.reject(r)):(Object.defineProperty(e,"_data",{get:()=>a}),this.emit(!1,t),a)}emit(e,t){this.subscribers.forEach((r=>r(e,t)))}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}cancel(){this.controller.abort(),this.pendingKeysSet.forEach(((e,t)=>this.pendingKeysSet.delete(t))),this.emit(!0)}async resolveData(e){let t=!1;if(!this.done){let r=()=>this.cancel();e.addEventListener("abort",r),t=await new Promise((t=>{this.subscribe((a=>{e.removeEventListener("abort",r),(a||this.done)&&t(a)}))}))}return t}get done(){return 0===this.pendingKeysSet.size}get unwrappedData(){return o(null!==this.data&&this.done,"Can only unwrap data on initialized and settled deferreds"),Object.entries(this.data).reduce(((e,t)=>{let[r,a]=t;return Object.assign(e,{[r]:O(a)})}),{})}get pendingKeys(){return Array.from(this.pendingKeysSet)}}function O(e){if(!function(e){return e instanceof Promise&&!0===e._tracked}(e))return e;if(e._error)throw e._error;return e._data}const H=function(e,r){void 0===r&&(r=302);let a=r;"number"==typeof a?a={status:a}:void 0===a.status&&(a.status=302);let o=new Headers(a.headers);return o.set("Location",e),new Response(null,t({},a,{headers:o}))};class I{constructor(e,t,r,a){void 0===a&&(a=!1),this.status=e,this.statusText=t||"",this.internal=a,r instanceof Error?(this.data=r.toString(),this.error=r):this.data=r}}function z(e){return null!=e&&"number"==typeof e.status&&"string"==typeof e.statusText&&"boolean"==typeof e.internal&&"data"in e}const B=["post","put","patch","delete"],F=new Set(B),N=["get",...B],W=new Set(N),$=new Set([301,302,303,307,308]),q=new Set([307,308]),K={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Y={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},J={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},V=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,X=e=>({hasErrorBoundary:Boolean(e.hasErrorBoundary)}),G="remix-router-transitions";const Q=Symbol("deferred");function Z(e,t,r){if(r.v7_throwAbortReason&&void 0!==e.signal.reason)throw e.signal.reason;throw new Error((t?"queryRoute":"query")+"() call aborted: "+e.method+" "+e.url)}function ee(e,t,r,a,o,n,i,s){let u,d;if(i){u=[];for(let e of t)if(u.push(e),e.route.id===i){d=e;break}}else u=t,d=t[t.length-1];let c=M(o||".",A(u,n),R(e.pathname,r)||e.pathname,"path"===s);return null==o&&(c.search=e.search,c.hash=e.hash),null!=o&&""!==o&&"."!==o||!d||!d.route.index||Te(c.search)||(c.search=c.search?c.search.replace(/^\?/,"?index&"):"?index"),a&&"/"!==r&&(c.pathname="/"===c.pathname?r:j([r,c.pathname])),l(c)}function te(e,t,r,a){if(!a||!function(e){return null!=e&&("formData"in e&&null!=e.formData||"body"in e&&void 0!==e.body)}(a))return{path:r};if(a.formMethod&&!je(a.formMethod))return{path:r,error:De(405,{method:a.formMethod})};let n,i,s=()=>({path:r,error:De(400,{type:"invalid-body"})}),d=a.formMethod||"get",c=e?d.toUpperCase():d.toLowerCase(),h=Ee(r);if(void 0!==a.body){if("text/plain"===a.formEncType){if(!ke(c))return s();let e="string"==typeof a.body?a.body:a.body instanceof FormData||a.body instanceof URLSearchParams?Array.from(a.body.entries()).reduce(((e,t)=>{let[r,a]=t;return""+e+r+"="+a+"\n"}),""):String(a.body);return{path:r,submission:{formMethod:c,formAction:h,formEncType:a.formEncType,formData:void 0,json:void 0,text:e}}}if("application/json"===a.formEncType){if(!ke(c))return s();try{let e="string"==typeof a.body?JSON.parse(a.body):a.body;return{path:r,submission:{formMethod:c,formAction:h,formEncType:a.formEncType,formData:void 0,json:e,text:void 0}}}catch(e){return s()}}}if(o("function"==typeof FormData,"FormData is not available in this environment"),a.formData)n=fe(a.formData),i=a.formData;else if(a.body instanceof FormData)n=fe(a.body),i=a.body;else if(a.body instanceof URLSearchParams)n=a.body,i=pe(n);else if(null==a.body)n=new URLSearchParams,i=new FormData;else try{n=new URLSearchParams(a.body),i=pe(n)}catch(e){return s()}let f={formMethod:c,formAction:h,formEncType:a&&a.formEncType||"application/x-www-form-urlencoded",formData:i,json:void 0,text:void 0};if(ke(f.formMethod))return{path:r,submission:f};let p=u(r);return t&&p.search&&Te(p.search)&&n.append("index",""),p.search="?"+n,{path:l(p),submission:f}}function re(e,t){let r=e;if(t){let a=e.findIndex((e=>e.route.id===t));a>=0&&(r=e.slice(0,a))}return r}function ae(e,r,a,o,n,i,s,l,u,d,c,h,f,m,y,v){let g=v?xe(v[1])?v[1].error:v[1].data:void 0,b=e.createURL(r.location),w=e.createURL(n),D=v&&xe(v[1])?v[0]:void 0,S=D?re(a,D):a,E=v?v[1].statusCode:void 0,R=s&&E&&E>=400,P=S.filter(((e,a)=>{let{route:n}=e;if(n.lazy)return!0;if(null==n.loader)return!1;if(i)return!("function"==typeof n.loader&&!n.loader.hydrate)||void 0===r.loaderData[n.id]&&(!r.errors||void 0===r.errors[n.id]);if(function(e,t,r){let a=!t||r.route.id!==t.route.id,o=void 0===e[r.route.id];return a||o}(r.loaderData,r.matches[a],e)||u.some((t=>t===e.route.id)))return!0;let s=r.matches[a],d=e;return ne(e,t({currentUrl:b,currentParams:s.params,nextUrl:w,nextParams:d.params},o,{actionResult:g,unstable_actionStatus:E,defaultShouldRevalidate:!R&&(l||b.pathname+b.search===w.pathname+w.search||b.search!==w.search||oe(s,d))}))})),x=[];return h.forEach(((e,n)=>{if(i||!a.some((t=>t.route.id===e.routeId))||c.has(n))return;let s=p(m,e.path,y);if(!s)return void x.push({key:n,routeId:e.routeId,path:e.path,matches:null,match:null,controller:null});let u=r.fetchers.get(n),h=Ue(s,e.path),v=!1;v=!f.has(n)&&(!!d.includes(n)||(u&&"idle"!==u.state&&void 0===u.data?l:ne(h,t({currentUrl:b,currentParams:r.matches[r.matches.length-1].params,nextUrl:w,nextParams:a[a.length-1].params},o,{actionResult:g,unstable_actionStatus:E,defaultShouldRevalidate:!R&&l})))),v&&x.push({key:n,routeId:e.routeId,path:e.path,matches:s,match:h,controller:new AbortController})})),[P,x]}function oe(e,t){let r=e.route.path;return e.pathname!==t.pathname||null!=r&&r.endsWith("*")&&e.params["*"]!==t.params["*"]}function ne(e,t){if(e.route.shouldRevalidate){let r=e.route.shouldRevalidate(t);if("boolean"==typeof r)return r}return t.defaultShouldRevalidate}async function ie(e,r,a){if(!e.lazy)return;let i=await e.lazy();if(!e.lazy)return;let s=a[e.id];o(s,"No route found in manifest");let l={};for(let e in i){let t=void 0!==s[e]&&"hasErrorBoundary"!==e;n(!t,'Route "'+s.id+'" has a static property "'+e+'" defined but its lazy function is also returning a value for this property. The lazy route property "'+e+'" will be ignored.'),t||h.has(e)||(l[e]=i[e])}Object.assign(s,l),Object.assign(s,t({},r(s),{lazy:void 0}))}function se(e){return Promise.all(e.matches.map((e=>e.resolve())))}async function le(e,r,a,n,i,s,l,u){let d=n.reduce(((e,t)=>e.add(t.route.id)),new Set),h=new Set,f=await e({matches:i.map((e=>{let n=d.has(e.route.id);return t({},e,{shouldLoad:n,resolve:t=>(h.add(e.route.id),n?async function(e,t,r,a,n,i,s){let l,u,d=a=>{let o,n=new Promise(((e,t)=>o=t));u=()=>o(),t.signal.addEventListener("abort",u);let l,d=o=>"function"!=typeof a?Promise.reject(new Error('You cannot call the handler for a route which defines a boolean "'+e+'" [routeId: '+r.route.id+"]")):a({request:t,params:r.params,context:s},...void 0!==o?[o]:[]);return l=i?i((e=>d(e))):(async()=>{try{return{type:"data",result:await d()}}catch(e){return{type:"error",result:e}}})(),Promise.race([l,n])};try{let i=r.route[e];if(r.route.lazy)if(i){let e,[t]=await Promise.all([d(i).catch((t=>{e=t})),ie(r.route,n,a)]);if(void 0!==e)throw e;l=t}else{if(await ie(r.route,n,a),i=r.route[e],!i){if("action"===e){let e=new URL(t.url),a=e.pathname+e.search;throw De(405,{method:t.method,pathname:a,routeId:r.route.id})}return{type:c.data,result:void 0}}l=await d(i)}else{if(!i){let e=new URL(t.url);throw De(404,{pathname:e.pathname+e.search})}l=await d(i)}o(void 0!==l.result,"You defined "+("action"===e?"an action":"a loader")+' for route "'+r.route.id+"\" but didn't return anything from your `"+e+"` function. Please return a value or `null`.")}catch(e){return{type:c.error,result:e}}finally{u&&t.signal.removeEventListener("abort",u)}return l}(r,a,e,s,l,t,u):Promise.resolve({type:c.data,result:void 0}))})})),request:a,params:i[0].params,context:u});return i.forEach((e=>o(h.has(e.route.id),'`match.resolve()` was not called for route id "'+e.route.id+'". You must call `match.resolve()` on every match passed to `dataStrategy` to ensure all routes are properly loaded.'))),f.filter(((e,t)=>d.has(i[t].route.id)))}async function ue(e){let{result:t,type:r,status:a}=e;if(Me(t)){let e;try{let r=t.headers.get("Content-Type");e=r&&/\bapplication\/json\b/.test(r)?null==t.body?null:await t.json():await t.text()}catch(e){return{type:c.error,error:e}}return r===c.error?{type:c.error,error:new I(t.status,t.statusText,e),statusCode:t.status,headers:t.headers}:{type:c.data,data:e,statusCode:t.status,headers:t.headers}}return r===c.error?{type:c.error,error:t,statusCode:z(t)?t.status:a}:Ae(t)?{type:c.deferred,deferredData:t,statusCode:null==(o=t.init)?void 0:o.status,headers:(null==(n=t.init)?void 0:n.headers)&&new Headers(t.init.headers)}:{type:c.data,data:t,statusCode:a};var o,n}function de(e,t,r,a,n,i){let s=e.headers.get("Location");if(o(s,"Redirects returned/thrown from loaders/actions must have a Location header"),!V.test(s)){let o=a.slice(0,a.findIndex((e=>e.route.id===r))+1);s=ee(new URL(t.url),o,n,!0,s,i),e.headers.set("Location",s)}return e}function ce(e,t,r){if(V.test(e)){let a=e,o=a.startsWith("//")?new URL(t.protocol+a):new URL(a),n=null!=R(o.pathname,r);if(o.origin===t.origin&&n)return o.pathname+o.search+o.hash}return e}function he(e,t,r,a){let o=e.createURL(Ee(t)).toString(),n={signal:r};if(a&&ke(a.formMethod)){let{formMethod:e,formEncType:t}=a;n.method=e.toUpperCase(),"application/json"===t?(n.headers=new Headers({"Content-Type":t}),n.body=JSON.stringify(a.json)):"text/plain"===t?n.body=a.text:"application/x-www-form-urlencoded"===t&&a.formData?n.body=fe(a.formData):n.body=a.formData}return new Request(o,n)}function fe(e){let t=new URLSearchParams;for(let[r,a]of e.entries())t.append(r,"string"==typeof a?a:a.name);return t}function pe(e){let t=new FormData;for(let[r,a]of e.entries())t.append(r,a);return t}function me(e,t,r,a,n,i){let s,l={},u=null,d=!1,c={},h=a&&xe(a[1])?a[1].error:void 0;return r.forEach(((r,a)=>{let f=t[a].route.id;if(o(!Le(r),"Cannot handle redirect results in processLoaderData"),xe(r)){let t=r.error;if(void 0!==h&&(t=h,h=void 0),u=u||{},i)u[f]=t;else{let r=be(e,f);null==u[r.route.id]&&(u[r.route.id]=t)}l[f]=void 0,d||(d=!0,s=z(r.error)?r.error.status:500),r.headers&&(c[f]=r.headers)}else Pe(r)?(n.set(f,r.deferredData),l[f]=r.deferredData.data,null==r.statusCode||200===r.statusCode||d||(s=r.statusCode),r.headers&&(c[f]=r.headers)):(l[f]=r.data,r.statusCode&&200!==r.statusCode&&!d&&(s=r.statusCode),r.headers&&(c[f]=r.headers))})),void 0!==h&&a&&(u={[a[0]]:h},l[a[0]]=void 0),{loaderData:l,errors:u,statusCode:s||200,loaderHeaders:c}}function ye(e,r,a,n,i,s,l,u){let{loaderData:d,errors:c}=me(r,a,n,i,u,!1);for(let r=0;re.route.id===t))+1):[...e]).reverse().find((e=>!0===e.route.hasErrorBoundary))||e[0]}function we(e){let t=1===e.length?e[0]:e.find((e=>e.index||!e.path||"/"===e.path))||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function De(e,t){let{pathname:r,routeId:a,method:o,type:n}=void 0===t?{}:t,i="Unknown Server Error",s="Unknown @remix-run/router error";return 400===e?(i="Bad Request",o&&r&&a?s="You made a "+o+' request to "'+r+'" but did not provide a `loader` for route "'+a+'", so there is no way to handle the request.':"defer-action"===n?s="defer() is not supported in actions":"invalid-body"===n&&(s="Unable to encode submission body")):403===e?(i="Forbidden",s='Route "'+a+'" does not match URL "'+r+'"'):404===e?(i="Not Found",s='No route matches URL "'+r+'"'):405===e&&(i="Method Not Allowed",o&&r&&a?s="You made a "+o.toUpperCase()+' request to "'+r+'" but did not provide an `action` for route "'+a+'", so there is no way to handle the request.':o&&(s='Invalid request method "'+o.toUpperCase()+'"')),new I(e||500,i,new Error(s),!0)}function Se(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if(Le(r))return{result:r,idx:t}}}function Ee(e){return l(t({},"string"==typeof e?u(e):e,{hash:""}))}function Re(e){return Me(e.result)&&$.has(e.result.status)}function Pe(e){return e.type===c.deferred}function xe(e){return e.type===c.error}function Le(e){return(e&&e.type)===c.redirect}function Ae(e){let t=e;return t&&"object"==typeof t&&"object"==typeof t.data&&"function"==typeof t.subscribe&&"function"==typeof t.cancel&&"function"==typeof t.resolveData}function Me(e){return null!=e&&"number"==typeof e.status&&"string"==typeof e.statusText&&"object"==typeof e.headers&&void 0!==e.body}function je(e){return W.has(e.toLowerCase())}function ke(e){return F.has(e.toLowerCase())}async function _e(e,t,r,a,n,i){for(let s=0;se.route.id===u.route.id)),c=null!=d&&!oe(d,u)&&void 0!==(i&&i[u.route.id]);if(Pe(l)&&(n||c)){let e=a[s];o(e,"Expected an AbortSignal for revalidating fetcher deferred result"),await Ce(l,e,n).then((e=>{e&&(r[s]=e||r[s])}))}}}async function Ce(e,t,r){if(void 0===r&&(r=!1),!await e.deferredData.resolveData(t)){if(r)try{return{type:c.data,data:e.deferredData.unwrappedData}}catch(e){return{type:c.error,error:e}}return{type:c.data,data:e.deferredData.data}}}function Te(e){return new URLSearchParams(e).getAll("index").some((e=>""===e))}function Ue(e,t){let r="string"==typeof t?u(t).search:t.search;if(e[e.length-1].route.index&&Te(r||""))return e[e.length-1];let a=L(e);return a[a.length-1]}function Oe(e){let{formMethod:t,formAction:r,formEncType:a,text:o,formData:n,json:i}=e;if(t&&r&&a)return null!=o?{formMethod:t,formAction:r,formEncType:a,formData:void 0,json:void 0,text:o}:null!=n?{formMethod:t,formAction:r,formEncType:a,formData:n,json:void 0,text:void 0}:void 0!==i?{formMethod:t,formAction:r,formEncType:a,formData:void 0,json:i,text:void 0}:void 0}function He(e,t){if(t){return{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}return{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function Ie(e,t){return{state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}function ze(e,t){if(e){return{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}}return{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function Be(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}e.AbortedDeferredError=T,e.Action=r,e.IDLE_BLOCKER=J,e.IDLE_FETCHER=Y,e.IDLE_NAVIGATION=K,e.UNSAFE_DEFERRED_SYMBOL=Q,e.UNSAFE_DeferredData=U,e.UNSAFE_ErrorResponseImpl=I,e.UNSAFE_convertRouteMatchToUiMatch=m,e.UNSAFE_convertRoutesToDataRoutes=f,e.UNSAFE_getResolveToMatches=A,e.UNSAFE_invariant=o,e.UNSAFE_warning=n,e.createBrowserHistory=function(e){return void 0===e&&(e={}),d((function(e,t){let{pathname:r,search:a,hash:o}=e.location;return s("",{pathname:r,search:a,hash:o},t.state&&t.state.usr||null,t.state&&t.state.key||"default")}),(function(e,t){return"string"==typeof t?t:l(t)}),null,e)},e.createHashHistory=function(e){return void 0===e&&(e={}),d((function(e,t){let{pathname:r="/",search:a="",hash:o=""}=u(e.location.hash.substr(1));return r.startsWith("/")||r.startsWith(".")||(r="/"+r),s("",{pathname:r,search:a,hash:o},t.state&&t.state.usr||null,t.state&&t.state.key||"default")}),(function(e,t){let r=e.document.querySelector("base"),a="";if(r&&r.getAttribute("href")){let t=e.location.href,r=t.indexOf("#");a=-1===r?t:t.slice(0,r)}return a+"#"+("string"==typeof t?t:l(t))}),(function(e,t){n("/"===e.pathname.charAt(0),"relative pathnames are not supported in hash history.push("+JSON.stringify(t)+")")}),e)},e.createMemoryHistory=function(e){void 0===e&&(e={});let t,{initialEntries:a=["/"],initialIndex:o,v5Compat:i=!1}=e;t=a.map(((e,t)=>m(e,"string"==typeof e?null:e.state,0===t?"default":void 0)));let d=f(null==o?t.length-1:o),c=r.Pop,h=null;function f(e){return Math.min(Math.max(e,0),t.length-1)}function p(){return t[d]}function m(e,r,a){void 0===r&&(r=null);let o=s(t?p().pathname:"/",e,r,a);return n("/"===o.pathname.charAt(0),"relative pathnames are not supported in memory history: "+JSON.stringify(e)),o}function y(e){return"string"==typeof e?e:l(e)}return{get index(){return d},get action(){return c},get location(){return p()},createHref:y,createURL:e=>new URL(y(e),"http://localhost"),encodeLocation(e){let t="string"==typeof e?u(e):e;return{pathname:t.pathname||"",search:t.search||"",hash:t.hash||""}},push(e,a){c=r.Push;let o=m(e,a);d+=1,t.splice(d,t.length,o),i&&h&&h({action:c,location:o,delta:1})},replace(e,a){c=r.Replace;let o=m(e,a);t[d]=o,i&&h&&h({action:c,location:o,delta:0})},go(e){c=r.Pop;let a=f(d+e),o=t[a];d=a,h&&h({action:c,location:o,delta:e})},listen:e=>(h=e,()=>{h=null})}},e.createPath=l,e.createRouter=function(e){const a=e.window?e.window:"undefined"!=typeof window?window:void 0,i=void 0!==a&&void 0!==a.document&&void 0!==a.document.createElement,l=!i;let u;if(o(e.routes.length>0,"You must provide a non-empty routes array to createRouter"),e.mapRouteProperties)u=e.mapRouteProperties;else if(e.detectErrorBoundary){let t=e.detectErrorBoundary;u=e=>({hasErrorBoundary:t(e)})}else u=X;let d,h,y={},v=f(e.routes,u,void 0,y),g=e.basename||"/",b=e.unstable_dataStrategy||se,w=t({v7_fetcherPersist:!1,v7_normalizeFormMethod:!1,v7_partialHydration:!1,v7_prependBasename:!1,v7_relativeSplatPath:!1,unstable_skipActionErrorRevalidation:!1},e.future),D=null,S=new Set,E=null,P=null,x=null,L=null!=e.hydrationData,A=p(v,e.history.location,g),M=null;if(null==A){let t=De(404,{pathname:e.history.location.pathname}),{matches:r,route:a}=we(v);A=r,M={[a.id]:t}}let j,k=A.some((e=>e.route.lazy)),_=A.some((e=>e.route.loader));if(k)h=!1;else if(_)if(w.v7_partialHydration){let t=e.hydrationData?e.hydrationData.loaderData:null,r=e.hydrationData?e.hydrationData.errors:null,a=e=>!e.route.loader||("function"!=typeof e.route.loader||!0!==e.route.loader.hydrate)&&(t&&void 0!==t[e.route.id]||r&&void 0!==r[e.route.id]);if(r){let e=A.findIndex((e=>void 0!==r[e.route.id]));h=A.slice(0,e+1).every(a)}else h=A.every(a)}else h=null!=e.hydrationData;else h=!0;let C,T={historyAction:e.history.action,location:e.history.location,matches:A,initialized:h,navigation:K,restoreScrollPosition:null==e.hydrationData&&null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||M,fetchers:new Map,blockers:new Map},U=r.Pop,O=!1,H=!1,I=new Map,z=null,B=!1,F=!1,N=[],W=[],$=new Map,Q=0,Z=-1,re=new Map,oe=new Set,ne=new Map,ie=new Map,fe=new Set,pe=new Map,me=new Map,Ee=!1;function Ae(e,r){void 0===r&&(r={}),T=t({},T,e);let a=[],o=[];w.v7_fetcherPersist&&T.fetchers.forEach(((e,t)=>{"idle"===e.state&&(fe.has(t)?o.push(t):a.push(t))})),[...S].forEach((e=>e(T,{deletedFetchers:o,unstable_viewTransitionOpts:r.viewTransitionOpts,unstable_flushSync:!0===r.flushSync}))),w.v7_fetcherPersist&&(a.forEach((e=>T.fetchers.delete(e))),o.forEach((e=>Ye(e))))}function Me(a,o,n){var i,s;let l,{flushSync:u}=void 0===n?{}:n,c=null!=T.actionData&&null!=T.navigation.formMethod&&ke(T.navigation.formMethod)&&"loading"===T.navigation.state&&!0!==(null==(i=a.state)?void 0:i._isRedirect);l=o.actionData?Object.keys(o.actionData).length>0?o.actionData:null:c?T.actionData:null;let h=o.loaderData?ve(T.loaderData,o.loaderData,o.matches||[],o.errors):T.loaderData,f=T.blockers;f.size>0&&(f=new Map(f),f.forEach(((e,t)=>f.set(t,J))));let p,m=!0===O||null!=T.navigation.formMethod&&ke(T.navigation.formMethod)&&!0!==(null==(s=a.state)?void 0:s._isRedirect);if(d&&(v=d,d=void 0),B||U===r.Pop||(U===r.Push?e.history.push(a,a.state):U===r.Replace&&e.history.replace(a,a.state)),U===r.Pop){let e=I.get(T.location.pathname);e&&e.has(a.pathname)?p={currentLocation:T.location,nextLocation:a}:I.has(a.pathname)&&(p={currentLocation:a,nextLocation:T.location})}else if(H){let e=I.get(T.location.pathname);e?e.add(a.pathname):(e=new Set([a.pathname]),I.set(T.location.pathname,e)),p={currentLocation:T.location,nextLocation:a}}Ae(t({},o,{actionData:l,loaderData:h,historyAction:U,location:a,initialized:!0,navigation:K,revalidation:"idle",restoreScrollPosition:at(a,o.matches||T.matches),preventScrollReset:m,blockers:f}),{viewTransitionOpts:p,flushSync:!0===u}),U=r.Pop,O=!1,H=!1,B=!1,F=!1,N=[],W=[]}async function je(a,o,n){C&&C.abort(),C=null,U=a,B=!0===(n&&n.startUninterruptedRevalidation),function(e,t){if(E&&x){let r=rt(e,t);E[r]=x()}}(T.location,T.matches),O=!0===(n&&n.preventScrollReset),H=!0===(n&&n.enableViewTransition);let i=d||v,s=n&&n.overrideNavigation,l=p(i,o,g),u=!0===(n&&n.flushSync);if(!l){let e=De(404,{pathname:o.pathname}),{matches:t,route:r}=we(i);return tt(),void Me(o,{matches:t,loaderData:{},errors:{[r.id]:e}},{flushSync:u})}if(T.initialized&&!F&&function(e,t){if(e.pathname!==t.pathname||e.search!==t.search)return!1;if(""===e.hash)return""!==t.hash;if(e.hash===t.hash)return!0;if(""!==t.hash)return!0;return!1}(T.location,o)&&!(n&&n.submission&&ke(n.submission.formMethod)))return void Me(o,{matches:l},{flushSync:u});C=new AbortController;let h,f=he(e.history,o,C.signal,n&&n.submission);if(n&&n.pendingError)h=[be(l).route.id,{type:c.error,error:n.pendingError}];else if(n&&n.submission&&ke(n.submission.formMethod)){let t=await async function(e,t,a,o,n){void 0===n&&(n={});let i;We(),Ae({navigation:Ie(t,a)},{flushSync:!0===n.flushSync});let s=Ue(o,t);if(s.route.action||s.route.lazy){if(i=(await Fe("action",e,[s],o))[0],e.signal.aborted)return{shortCircuited:!0}}else i={type:c.error,error:De(405,{method:e.method,pathname:t.pathname,routeId:s.route.id})};if(Le(i)){let t;if(n&&null!=n.replace)t=n.replace;else{t=ce(i.response.headers.get("Location"),new URL(e.url),g)===T.location.pathname+T.location.search}return await Te(e,i,{submission:a,replace:t}),{shortCircuited:!0}}if(Pe(i))throw De(400,{type:"defer-action"});if(xe(i)){let e=be(o,s.route.id);return!0!==(n&&n.replace)&&(U=r.Push),{pendingActionResult:[e.route.id,i]}}return{pendingActionResult:[s.route.id,i]}}(f,o,n.submission,l,{replace:n.replace,flushSync:u});if(t.shortCircuited)return;h=t.pendingActionResult,s=He(o,n.submission),u=!1,f=he(e.history,f.url,f.signal)}let{shortCircuited:m,loaderData:y,errors:b}=await async function(r,a,o,n,i,s,l,u,c,h){let f=n||He(a,i),p=i||s||Oe(f),m=d||v,[y,b]=ae(e.history,T,o,p,a,w.v7_partialHydration&&!0===u,w.unstable_skipActionErrorRevalidation,F,N,W,fe,ne,oe,m,g,h);if(tt((e=>!(o&&o.some((t=>t.route.id===e)))||y&&y.some((t=>t.route.id===e)))),Z=++Q,0===y.length&&0===b.length){let e=Xe();return Me(a,t({matches:o,loaderData:{},errors:h&&xe(h[1])?{[h[0]]:h[1].error}:null},ge(h),e?{fetchers:new Map(T.fetchers)}:{}),{flushSync:c}),{shortCircuited:!0}}if(!(B||w.v7_partialHydration&&u)){let e;b.forEach((e=>{let t=T.fetchers.get(e.key),r=ze(void 0,t?t.data:void 0);T.fetchers.set(e.key,r)})),h&&!xe(h[1])?e={[h[0]]:h[1].data}:T.actionData&&(e=0===Object.keys(T.actionData).length?null:T.actionData),Ae(t({navigation:f},void 0!==e?{actionData:e}:{},b.length>0?{fetchers:new Map(T.fetchers)}:{}),{flushSync:c})}b.forEach((e=>{$.has(e.key)&&Je(e.key),e.controller&&$.set(e.key,e.controller)}));let D=()=>b.forEach((e=>Je(e.key)));C&&C.signal.addEventListener("abort",D);let{loaderResults:S,fetcherResults:E}=await Ne(T.matches,o,y,b,r);if(r.signal.aborted)return{shortCircuited:!0};C&&C.signal.removeEventListener("abort",D);b.forEach((e=>$.delete(e.key)));let R=Se([...S,...E]);if(R){if(R.idx>=y.length){let e=b[R.idx-y.length].key;oe.add(e)}return await Te(r,R.result,{replace:l}),{shortCircuited:!0}}let{loaderData:P,errors:x}=ye(T,o,y,S,h,b,E,pe);pe.forEach(((e,t)=>{e.subscribe((r=>{(r||e.done)&&pe.delete(t)}))})),w.v7_partialHydration&&u&&T.errors&&Object.entries(T.errors).filter((e=>{let[t]=e;return!y.some((e=>e.route.id===t))})).forEach((e=>{let[t,r]=e;x=Object.assign(x||{},{[t]:r})}));let L=Xe(),A=Ge(Z),M=L||A||b.length>0;return t({loaderData:P,errors:x},M?{fetchers:new Map(T.fetchers)}:{})}(f,o,l,s,n&&n.submission,n&&n.fetcherSubmission,n&&n.replace,n&&!0===n.initialHydration,u,h);m||(C=null,Me(o,t({matches:l},ge(h),{loaderData:y,errors:b})))}async function Te(n,l,u){let{submission:d,fetcherSubmission:c,replace:h}=void 0===u?{}:u;l.response.headers.has("X-Remix-Revalidate")&&(F=!0);let f=l.response.headers.get("Location");o(f,"Expected a Location header on the redirect Response"),f=ce(f,new URL(n.url),g);let p=s(T.location,f,{_isRedirect:!0});if(i){let t=!1;if(l.response.headers.has("X-Remix-Reload-Document"))t=!0;else if(V.test(f)){const r=e.history.createURL(f);t=r.origin!==a.location.origin||null==R(r.pathname,g)}if(t)return void(h?a.location.replace(f):a.location.assign(f))}C=null;let m=!0===h?r.Replace:r.Push,{formMethod:y,formAction:v,formEncType:b}=T.navigation;!d&&!c&&y&&v&&b&&(d=Oe(T.navigation));let w=d||c;if(q.has(l.response.status)&&w&&ke(w.formMethod))await je(m,p,{submission:t({},w,{formAction:f}),preventScrollReset:O});else{let e=He(p,d);await je(m,p,{overrideNavigation:e,fetcherSubmission:c,preventScrollReset:O})}}async function Fe(e,t,r,a){try{let o=await le(b,e,t,r,a,y,u);return await Promise.all(o.map(((e,o)=>{if(Re(e)){let n=e.result;return{type:c.redirect,response:de(n,t,r[o].route.id,a,g,w.v7_relativeSplatPath)}}return ue(e)})))}catch(e){return r.map((()=>({type:c.error,error:e})))}}async function Ne(t,r,a,o,n){let[i,...s]=await Promise.all([a.length?Fe("loader",n,a,r):[],...o.map((t=>{if(t.matches&&t.match&&t.controller){return Fe("loader",he(e.history,t.path,t.controller.signal),[t.match],t.matches).then((e=>e[0]))}return Promise.resolve({type:c.error,error:De(404,{pathname:t.path})})}))]);return await Promise.all([_e(t,a,i,i.map((()=>n.signal)),!1,T.loaderData),_e(t,o.map((e=>e.match)),s,o.map((e=>e.controller?e.controller.signal:null)),!0)]),{loaderResults:i,fetcherResults:s}}function We(){F=!0,N.push(...tt()),ne.forEach(((e,t)=>{$.has(t)&&(W.push(t),Je(t))}))}function $e(e,t,r){void 0===r&&(r={}),T.fetchers.set(e,t),Ae({fetchers:new Map(T.fetchers)},{flushSync:!0===(r&&r.flushSync)})}function qe(e,t,r,a){void 0===a&&(a={});let o=be(T.matches,t);Ye(e),Ae({errors:{[o.route.id]:r},fetchers:new Map(T.fetchers)},{flushSync:!0===(a&&a.flushSync)})}function Ke(e){return w.v7_fetcherPersist&&(ie.set(e,(ie.get(e)||0)+1),fe.has(e)&&fe.delete(e)),T.fetchers.get(e)||Y}function Ye(e){let t=T.fetchers.get(e);!$.has(e)||t&&"loading"===t.state&&re.has(e)||Je(e),ne.delete(e),re.delete(e),oe.delete(e),fe.delete(e),T.fetchers.delete(e)}function Je(e){let t=$.get(e);o(t,"Expected fetch controller: "+e),t.abort(),$.delete(e)}function Ve(e){for(let t of e){let e=Be(Ke(t).data);T.fetchers.set(t,e)}}function Xe(){let e=[],t=!1;for(let r of oe){let a=T.fetchers.get(r);o(a,"Expected fetcher: "+r),"loading"===a.state&&(oe.delete(r),e.push(r),t=!0)}return Ve(e),t}function Ge(e){let t=[];for(let[r,a]of re)if(a0}function Qe(e){T.blockers.delete(e),me.delete(e)}function Ze(e,t){let r=T.blockers.get(e)||J;o("unblocked"===r.state&&"blocked"===t.state||"blocked"===r.state&&"blocked"===t.state||"blocked"===r.state&&"proceeding"===t.state||"blocked"===r.state&&"unblocked"===t.state||"proceeding"===r.state&&"unblocked"===t.state,"Invalid blocker state transition: "+r.state+" -> "+t.state);let a=new Map(T.blockers);a.set(e,t),Ae({blockers:a})}function et(e){let{currentLocation:t,nextLocation:r,historyAction:a}=e;if(0===me.size)return;me.size>1&&n(!1,"A router only supports one blocker at a time");let o=Array.from(me.entries()),[i,s]=o[o.length-1],l=T.blockers.get(i);return l&&"proceeding"===l.state?void 0:s({currentLocation:t,nextLocation:r,historyAction:a})?i:void 0}function tt(e){let t=[];return pe.forEach(((r,a)=>{e&&!e(a)||(r.cancel(),t.push(a),pe.delete(a))})),t}function rt(e,t){if(P){return P(e,t.map((e=>m(e,T.loaderData))))||e.key}return e.key}function at(e,t){if(E){let r=rt(e,t),a=E[r];if("number"==typeof a)return a}return null}return j={get basename(){return g},get future(){return w},get state(){return T},get routes(){return v},get window(){return a},initialize:function(){if(D=e.history.listen((t=>{let{action:r,location:a,delta:o}=t;if(Ee)return void(Ee=!1);n(0===me.size||null!=o,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let i=et({currentLocation:T.location,nextLocation:a,historyAction:r});return i&&null!=o?(Ee=!0,e.history.go(-1*o),void Ze(i,{state:"blocked",location:a,proceed(){Ze(i,{state:"proceeding",proceed:void 0,reset:void 0,location:a}),e.history.go(o)},reset(){let e=new Map(T.blockers);e.set(i,J),Ae({blockers:e})}})):je(r,a)})),i){!function(e,t){try{let r=e.sessionStorage.getItem(G);if(r){let e=JSON.parse(r);for(let[r,a]of Object.entries(e||{}))a&&Array.isArray(a)&&t.set(r,new Set(a||[]))}}catch(e){}}(a,I);let e=()=>function(e,t){if(t.size>0){let r={};for(let[e,a]of t)r[e]=[...a];try{e.sessionStorage.setItem(G,JSON.stringify(r))}catch(e){n(!1,"Failed to save applied view transitions in sessionStorage ("+e+").")}}}(a,I);a.addEventListener("pagehide",e),z=()=>a.removeEventListener("pagehide",e)}return T.initialized||je(r.Pop,T.location,{initialHydration:!0}),j},subscribe:function(e){return S.add(e),()=>S.delete(e)},enableScrollRestoration:function(e,t,r){if(E=e,x=t,P=r||null,!L&&T.navigation===K){L=!0;let e=at(T.location,T.matches);null!=e&&Ae({restoreScrollPosition:e})}return()=>{E=null,x=null,P=null}},navigate:async function a(o,n){if("number"==typeof o)return void e.history.go(o);let i=ee(T.location,T.matches,g,w.v7_prependBasename,o,w.v7_relativeSplatPath,null==n?void 0:n.fromRouteId,null==n?void 0:n.relative),{path:l,submission:u,error:d}=te(w.v7_normalizeFormMethod,!1,i,n),c=T.location,h=s(T.location,l,n&&n.state);h=t({},h,e.history.encodeLocation(h));let f=n&&null!=n.replace?n.replace:void 0,p=r.Push;!0===f?p=r.Replace:!1===f||null!=u&&ke(u.formMethod)&&u.formAction===T.location.pathname+T.location.search&&(p=r.Replace);let m=n&&"preventScrollReset"in n?!0===n.preventScrollReset:void 0,y=!0===(n&&n.unstable_flushSync),v=et({currentLocation:c,nextLocation:h,historyAction:p});if(!v)return await je(p,h,{submission:u,pendingError:d,preventScrollReset:m,replace:n&&n.replace,enableViewTransition:n&&n.unstable_viewTransition,flushSync:y});Ze(v,{state:"blocked",location:h,proceed(){Ze(v,{state:"proceeding",proceed:void 0,reset:void 0,location:h}),a(o,n)},reset(){let e=new Map(T.blockers);e.set(v,J),Ae({blockers:e})}})},fetch:function(t,r,a,n){if(l)throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback.");$.has(t)&&Je(t);let i=!0===(n&&n.unstable_flushSync),s=d||v,u=ee(T.location,T.matches,g,w.v7_prependBasename,a,w.v7_relativeSplatPath,r,null==n?void 0:n.relative),c=p(s,u,g);if(!c)return void qe(t,r,De(404,{pathname:u}),{flushSync:i});let{path:h,submission:f,error:m}=te(w.v7_normalizeFormMethod,!0,u,n);if(m)return void qe(t,r,m,{flushSync:i});let y=Ue(c,h);O=!0===(n&&n.preventScrollReset),f&&ke(f.formMethod)?async function(t,r,a,n,i,s,l){if(We(),ne.delete(t),!n.route.action&&!n.route.lazy){let e=De(405,{method:l.formMethod,pathname:a,routeId:r});return void qe(t,r,e,{flushSync:s})}let u=T.fetchers.get(t);$e(t,function(e,t){return{state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}(l,u),{flushSync:s});let c=new AbortController,h=he(e.history,a,c.signal,l);$.set(t,c);let f=Q,m=(await Fe("action",h,[n],i))[0];if(h.signal.aborted)return void($.get(t)===c&&$.delete(t));if(w.v7_fetcherPersist&&fe.has(t)){if(Le(m)||xe(m))return void $e(t,Be(void 0))}else{if(Le(m))return $.delete(t),Z>f?void $e(t,Be(void 0)):(oe.add(t),$e(t,ze(l)),Te(h,m,{fetcherSubmission:l}));if(xe(m))return void qe(t,r,m.error)}if(Pe(m))throw De(400,{type:"defer-action"});let y=T.navigation.location||T.location,b=he(e.history,y,c.signal),D=d||v,S="idle"!==T.navigation.state?p(D,T.navigation.location,g):T.matches;o(S,"Didn't find any matches after fetcher action");let E=++Q;re.set(t,E);let R=ze(l,m.data);T.fetchers.set(t,R);let[P,x]=ae(e.history,T,S,l,y,!1,w.unstable_skipActionErrorRevalidation,F,N,W,fe,ne,oe,D,g,[n.route.id,m]);x.filter((e=>e.key!==t)).forEach((e=>{let t=e.key,r=T.fetchers.get(t),a=ze(void 0,r?r.data:void 0);T.fetchers.set(t,a),$.has(t)&&Je(t),e.controller&&$.set(t,e.controller)})),Ae({fetchers:new Map(T.fetchers)});let L=()=>x.forEach((e=>Je(e.key)));c.signal.addEventListener("abort",L);let{loaderResults:A,fetcherResults:M}=await Ne(T.matches,S,P,x,b);if(c.signal.aborted)return;c.signal.removeEventListener("abort",L),re.delete(t),$.delete(t),x.forEach((e=>$.delete(e.key)));let j=Se([...A,...M]);if(j){if(j.idx>=P.length){let e=x[j.idx-P.length].key;oe.add(e)}return Te(b,j.result)}let{loaderData:k,errors:_}=ye(T,T.matches,P,A,void 0,x,M,pe);if(T.fetchers.has(t)){let e=Be(m.data);T.fetchers.set(t,e)}Ge(E),"loading"===T.navigation.state&&E>Z?(o(U,"Expected pending action"),C&&C.abort(),Me(T.navigation.location,{matches:S,loaderData:k,errors:_,fetchers:new Map(T.fetchers)})):(Ae({errors:_,loaderData:ve(T.loaderData,k,S,_),fetchers:new Map(T.fetchers)}),F=!1)}(t,r,h,y,c,i,f):(ne.set(t,{routeId:r,path:h}),async function(t,r,a,n,i,s,l){let u=T.fetchers.get(t);$e(t,ze(l,u?u.data:void 0),{flushSync:s});let d=new AbortController,c=he(e.history,a,d.signal);$.set(t,d);let h=Q,f=(await Fe("loader",c,[n],i))[0];Pe(f)&&(f=await Ce(f,c.signal,!0)||f);$.get(t)===d&&$.delete(t);if(c.signal.aborted)return;if(fe.has(t))return void $e(t,Be(void 0));if(Le(f))return Z>h?void $e(t,Be(void 0)):(oe.add(t),void await Te(c,f));if(xe(f))return void qe(t,r,f.error);o(!Pe(f),"Unhandled fetcher deferred data"),$e(t,Be(f.data))}(t,r,h,y,c,i,f))},revalidate:function(){We(),Ae({revalidation:"loading"}),"submitting"!==T.navigation.state&&("idle"!==T.navigation.state?je(U||T.historyAction,T.navigation.location,{overrideNavigation:T.navigation}):je(T.historyAction,T.location,{startUninterruptedRevalidation:!0}))},createHref:t=>e.history.createHref(t),encodeLocation:t=>e.history.encodeLocation(t),getFetcher:Ke,deleteFetcher:function(e){if(w.v7_fetcherPersist){let t=(ie.get(e)||0)-1;t<=0?(ie.delete(e),fe.add(e)):ie.set(e,t)}else Ye(e);Ae({fetchers:new Map(T.fetchers)})},dispose:function(){D&&D(),z&&z(),S.clear(),C&&C.abort(),T.fetchers.forEach(((e,t)=>Ye(t))),T.blockers.forEach(((e,t)=>Qe(t)))},getBlocker:function(e,t){let r=T.blockers.get(e)||J;return me.get(e)!==t&&me.set(e,t),r},deleteBlocker:Qe,_internalFetchControllers:$,_internalActiveDeferreds:pe,_internalSetRoutes:function(e){y={},d=f(e,u,void 0,y)}},j},e.createStaticHandler=function(e,r){o(e.length>0,"You must provide a non-empty routes array to createStaticHandler");let a,n={},i=(r?r.basename:null)||"/";if(null!=r&&r.mapRouteProperties)a=r.mapRouteProperties;else if(null!=r&&r.detectErrorBoundary){let e=r.detectErrorBoundary;a=t=>({hasErrorBoundary:e(t)})}else a=X;let u=t({v7_relativeSplatPath:!1,v7_throwAbortReason:!1},r?r.future:null),d=f(e,a,void 0,n);async function h(e,r,a,n,i,s,l){o(e.signal,"query()/queryRoute() requests must contain an AbortController signal");try{if(ke(e.method.toLowerCase())){let o=await async function(e,r,a,o,n,i,s){let l;if(a.route.action||a.route.lazy){l=(await y("action",e,[a],r,s,o,n))[0],e.signal.aborted&&Z(e,s,u)}else{let t=De(405,{method:e.method,pathname:new URL(e.url).pathname,routeId:a.route.id});if(s)throw t;l={type:c.error,error:t}}if(Le(l))throw new Response(null,{status:l.response.status,headers:{Location:l.response.headers.get("Location")}});if(Pe(l)){let e=De(400,{type:"defer-action"});if(s)throw e;l={type:c.error,error:e}}if(s){if(xe(l))throw l.error;return{matches:[a],loaderData:{},actionData:{[a.route.id]:l.data},errors:null,statusCode:200,loaderHeaders:{},actionHeaders:{},activeDeferreds:null}}let d=new Request(e.url,{headers:e.headers,redirect:e.redirect,signal:e.signal});if(xe(l)){let e=i?a:be(r,a.route.id);return t({},await m(d,r,o,n,i,null,[e.route.id,l]),{statusCode:z(l.error)?l.error.status:null!=l.statusCode?l.statusCode:500,actionData:null,actionHeaders:t({},l.headers?{[a.route.id]:l.headers}:{})})}return t({},await m(d,r,o,n,i,null),{actionData:{[a.route.id]:l.data}},l.statusCode?{statusCode:l.statusCode}:{},{actionHeaders:l.headers?{[a.route.id]:l.headers}:{}})}(e,a,l||Ue(a,r),n,i,s,null!=l);return o}let o=await m(e,a,n,i,s,l);return Me(o)?o:t({},o,{actionData:null,actionHeaders:{}})}catch(e){if(function(e){return null!=e&&"object"==typeof e&&"type"in e&&"result"in e&&(e.type===c.data||e.type===c.error)}(e)&&Me(e.result)){if(e.type===c.error)throw e.result;return e.result}if(function(e){if(!Me(e))return!1;let t=e.status,r=e.headers.get("Location");return t>=300&&t<=399&&null!=r}(e))return e;throw e}}async function m(e,r,a,o,n,i,s){let l=null!=i;if(l&&(null==i||!i.route.loader)&&(null==i||!i.route.lazy))throw De(400,{method:e.method,pathname:new URL(e.url).pathname,routeId:null==i?void 0:i.route.id});let d=(i?[i]:s&&xe(s[1])?re(r,s[0]):r).filter((e=>e.route.loader||e.route.lazy));if(0===d.length)return{matches:r,loaderData:r.reduce(((e,t)=>Object.assign(e,{[t.route.id]:null})),{}),errors:s&&xe(s[1])?{[s[0]]:s[1].error}:null,statusCode:200,loaderHeaders:{},activeDeferreds:null};let c=await y("loader",e,d,r,l,a,o);e.signal.aborted&&Z(e,l,u);let h=new Map,f=me(r,d,c,s,h,n),p=new Set(d.map((e=>e.route.id)));return r.forEach((e=>{p.has(e.route.id)||(f.loaderData[e.route.id]=null)})),t({},f,{matches:r,activeDeferreds:h.size>0?Object.fromEntries(h.entries()):null})}async function y(e,t,r,o,s,l,d){let c=await le(d||se,e,t,r,o,n,a,l);return await Promise.all(c.map(((e,a)=>{if(Re(e)){throw de(e.result,t,r[a].route.id,o,i,u.v7_relativeSplatPath)}if(Me(e.result)&&s)throw e;return ue(e)})))}return{dataRoutes:d,query:async function(e,r){let{requestContext:a,skipLoaderErrorBubbling:o,unstable_dataStrategy:n}=void 0===r?{}:r,u=new URL(e.url),c=e.method,f=s("",l(u),null,"default"),m=p(d,f,i);if(!je(c)&&"HEAD"!==c){let e=De(405,{method:c}),{matches:t,route:r}=we(d);return{basename:i,location:f,matches:t,loaderData:{},actionData:null,errors:{[r.id]:e},statusCode:e.status,loaderHeaders:{},actionHeaders:{},activeDeferreds:null}}if(!m){let e=De(404,{pathname:f.pathname}),{matches:t,route:r}=we(d);return{basename:i,location:f,matches:t,loaderData:{},actionData:null,errors:{[r.id]:e},statusCode:e.status,loaderHeaders:{},actionHeaders:{},activeDeferreds:null}}let y=await h(e,f,m,a,n||null,!0===o,null);return Me(y)?y:t({location:f,basename:i},y)},queryRoute:async function(e,t){let{routeId:r,requestContext:a,unstable_dataStrategy:o}=void 0===t?{}:t,n=new URL(e.url),u=e.method,c=s("",l(n),null,"default"),f=p(d,c,i);if(!je(u)&&"HEAD"!==u&&"OPTIONS"!==u)throw De(405,{method:u});if(!f)throw De(404,{pathname:c.pathname});let m=r?f.find((e=>e.route.id===r)):Ue(f,c);if(r&&!m)throw De(403,{pathname:c.pathname,routeId:r});if(!m)throw De(404,{pathname:c.pathname});let y=await h(e,c,f,a,o||null,!1,m);if(Me(y))return y;let v=y.errors?Object.values(y.errors)[0]:void 0;if(void 0!==v)throw v;if(y.actionData)return Object.values(y.actionData)[0];if(y.loaderData){var g;let e=Object.values(y.loaderData)[0];return null!=(g=y.activeDeferreds)&&g[m.route.id]&&(e[Q]=y.activeDeferreds[m.route.id]),e}}}},e.defer=function(e,t){return void 0===t&&(t={}),new U(e,"number"==typeof t?{status:t}:t)},e.generatePath=function(e,t){void 0===t&&(t={});let r=e;r.endsWith("*")&&"*"!==r&&!r.endsWith("/*")&&(n(!1,'Route path "'+r+'" will be treated as if it were "'+r.replace(/\*$/,"/*")+'" because the `*` character must always follow a `/` in the pattern. To get rid of this warning, please change the route path to "'+r.replace(/\*$/,"/*")+'".'),r=r.replace(/\*$/,"/*"));const a=r.startsWith("/")?"/":"",i=e=>null==e?"":"string"==typeof e?e:String(e);return a+r.split(/\/+/).map(((e,r,a)=>{if(r===a.length-1&&"*"===e){return i(t["*"])}const n=e.match(/^:([\w-]+)(\??)$/);if(n){const[,e,r]=n;let a=t[e];return o("?"===r||null!=a,'Missing ":'+e+'" param'),i(a)}return e.replace(/\?$/g,"")})).filter((e=>!!e)).join("/")},e.getStaticContextFromError=function(e,r,a){return t({},r,{statusCode:z(a)?a.status:500,errors:{[r._deepestRenderedBoundaryId||e[0].id]:a}})},e.getToPathname=function(e){return""===e||""===e.pathname?"/":"string"==typeof e?u(e).pathname:e.pathname},e.isDeferredData=Ae,e.isRouteErrorResponse=z,e.joinPaths=j,e.json=function(e,r){void 0===r&&(r={});let a="number"==typeof r?{status:r}:r,o=new Headers(a.headers);return o.has("Content-Type")||o.set("Content-Type","application/json; charset=utf-8"),new Response(JSON.stringify(e),t({},a,{headers:o}))},e.matchPath=S,e.matchRoutes=p,e.normalizePathname=k,e.parsePath=u,e.redirect=H,e.redirectDocument=(e,t)=>{let r=H(e,t);return r.headers.set("X-Remix-Reload-Document","true"),r},e.resolvePath=P,e.resolveTo=M,e.stripBasename=R,Object.defineProperty(e,"__esModule",{value:!0})})); -//# sourceMappingURL=router.umd.min.js.map diff --git a/node_modules/@remix-run/router/dist/router.umd.min.js.map b/node_modules/@remix-run/router/dist/router.umd.min.js.map deleted file mode 100644 index 0c6def52..00000000 --- a/node_modules/@remix-run/router/dist/router.umd.min.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"router.umd.min.js","sources":["../history.ts","../utils.ts","../router.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 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, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial;\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 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;\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 () 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(\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 // eslint-disable-next-line no-console\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 // eslint-disable-next-line no-empty\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 {\n let location: Readonly = {\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 */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial) {\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 */\nexport function parsePath(path: string): Partial {\n let parsedPath: Partial = {};\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 { 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 deferred = \"deferred\",\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 * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n type: ResultType.deferred;\n deferredData: DeferredData;\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 =\n | SuccessResult\n | DeferredResult\n | RedirectResult\n | ErrorResult;\n\n/**\n * Result from a loader or action called via dataStrategy\n */\nexport interface HandlerResult {\n type: \"data\" | \"error\";\n result: unknown; // data, Error, Response, DeferredData\n status?: number;\n}\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase;\n\n/**\n * Users can specify either lowercase or uppercase form methods on ``,\n * useSubmit(), ``, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude;\n\n/**\n * In v7, 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 V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude;\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 | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_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 {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs\n extends DataFunctionArgs {}\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 | null;\n\ntype DataFunctionReturnValue = Promise | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction = {\n (\n args: LoaderFunctionArgs,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (\n args: ActionFunctionArgs,\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 unstable_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\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\nexport interface DataStrategyMatch\n extends AgnosticRouteMatch {\n shouldLoad: boolean;\n resolve: (\n handlerOverride?: (\n handler: (ctx?: unknown) => DataFunctionReturnValue\n ) => Promise\n ) => Promise;\n}\n\nexport interface DataStrategyFunctionArgs\n extends DataFunctionArgs {\n matches: DataStrategyMatch[];\n}\n\nexport interface DataStrategyFunction {\n (args: DataStrategyFunctionArgs): Promise;\n}\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;\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([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit & Required> : 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 {\n (): Promise>>;\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;\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;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam | _PathParam\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 =\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\n : // look for params in the absence of wildcards\n _PathParam;\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 =\n // if you could not find path params, fallback to `string`\n [PathParam] extends [never] ? string : PathParam;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params = {\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;\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 {}\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: number[] = [],\n manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, 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 * @see https://reactrouter.com/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename = \"/\"\n): AgnosticRouteMatch[] | 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(branches[i], decoded);\n }\n\n return matches;\n}\n\nexport interface UIMatch {\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[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta = {\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\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,\n pathname: string\n): AgnosticRouteMatch[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch[] = [];\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 if (!match) return null;\n\n Object.assign(matchedParams, match.params);\n\n let route = meta.route;\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params,\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 * @see https://reactrouter.com/utils/generate-path\n */\nexport function generatePath(\n originalPath: Path,\n params: {\n [key in PathParam]: 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;\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];\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 {\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 {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\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 = {\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 * @see https://reactrouter.com/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey,\n Path extends string\n>(\n pattern: PathPattern | Path,\n pathname: string\n): PathMatch | 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>(\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\nfunction 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 * @see https://reactrouter.com/utils/resolve-path\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\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 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 * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \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[], v7_relativeSplatPath: boolean) {\n let pathMatches = getPathContributingMatches(matches);\n\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) =>\n idx === matches.length - 1 ? match.pathname : match.pathnameBase\n );\n }\n\n return pathMatches.map((match) => match.pathnameBase);\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;\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 `` 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 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 function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\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\nexport type JsonFunction = (\n data: Data,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\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 interface TrackedPromise extends Promise {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeysSet: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record,\n init?: number | ResponseInit\n) => DeferredData;\n\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\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 */\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 */\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\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 */\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 HistoryAction,\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 DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n HandlerResult,\n ImmutableRouteKey,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\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 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 * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the future config for the router\n */\n get future(): FutureConfig;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\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 * @internal\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 * @internal\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,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\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;\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;\n\n /**\n * @internal\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 ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\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 * @internal\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 * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(key: string): Fetcher;\n\n /**\n * @internal\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 * @internal\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @internal\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 * @internal\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 * @internal\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 * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map;\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 /**\n * The action of the most recent navigation\n */\n historyAction: HistoryAction;\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;\n\n /**\n * Map of current blockers\n */\n blockers: Map;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_partialHydration: boolean;\n v7_prependBasename: boolean;\n v7_relativeSplatPath: boolean;\n unstable_skipActionErrorRevalidation: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n hydrationData?: HydrationState;\n window?: Window;\n unstable_dataStrategy?: DataStrategyFunction;\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;\n actionHeaders: Record;\n activeDeferreds: Record | null;\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 unstable_dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\n queryRoute(\n request: Request,\n opts?: {\n routeId?: string;\n requestContext?: unknown;\n unstable_dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\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 unstable_viewTransitionOpts?: ViewTransitionOpts;\n unstable_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\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n unstable_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 */\ntype FetcherStates = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\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 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 =\n FetcherStates[keyof FetcherStates];\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: HistoryAction;\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 * 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 * 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(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set(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//#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 const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\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.unstable_dataStrategy || defaultDataStrategy;\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n unstable_skipActionErrorRevalidation: false,\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();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record | 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 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) {\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 let initialized: boolean;\n let hasLazyRoutes = initialMatches.some((m) => m.route.lazy);\n let hasLoaders = initialMatches.some((m) => m.route.loader);\n if (hasLazyRoutes) {\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 (!hasLoaders) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, 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 let isRouteInitialized = (m: AgnosticDataRouteMatch) => {\n // No loader, nothing to initialize\n if (!m.route.loader) {\n return true;\n }\n // Explicitly opting-in to running on hydration\n if (\n typeof m.route.loader === \"function\" &&\n m.route.loader.hydrate === true\n ) {\n return false;\n }\n // Otherwise, initialized if hydrated with data or an error\n return (\n (loaderData && loaderData[m.route.id] !== undefined) ||\n (errors && errors[m.route.id] !== undefined)\n );\n };\n\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.slice(0, idx + 1).every(isRouteInitialized);\n } else {\n initialized = initialMatches.every(isRouteInitialized);\n }\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\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: HistoryAction = HistoryAction.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> = new Map<\n string,\n Set\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 routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\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();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\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();\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 ignoreNextHistoryUpdate = false;\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 (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\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 ignoreNextHistoryUpdate = true;\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\n 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 fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.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,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\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: deletedFetchersKeys,\n unstable_viewTransitionOpts: opts.viewTransitionOpts,\n unstable_flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n }\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>,\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 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 === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.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 === HistoryAction.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([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 = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\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 ): Promise {\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 future.v7_prependBasename,\n to,\n future.v7_relativeSplatPath,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\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 = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.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 = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.unstable_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 return 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.unstable_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 interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\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;\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;\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 { overrideNavigation: state.navigation }\n );\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: HistoryAction,\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 {\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 // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\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 load will always\n // be \"same hash\". For example, on /page#hash and submit a \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 { replace: opts.replace, flushSync }\n );\n\n if (actionResult.shortCircuited) {\n return;\n }\n\n pendingActionResult = actionResult.pendingActionResult;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = 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 { shortCircuited, loaderData, errors } = await handleLoaders(\n request,\n location,\n matches,\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,\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 opts: { replace?: boolean; flushSync?: boolean } = {}\n ): Promise {\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 // 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 request,\n [actionMatch],\n matches\n );\n result = results[0];\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, {\n submission,\n replace,\n });\n return { shortCircuited: true };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\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 are REPLACE navigations, but if the\n // action threw an error that'll be rendered in an errorElement, we fall\n // back to PUSH so that the user can use the back button to get back to\n // the pre-submission form location to try again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n pendingActionResult: [boundaryMatch.route.id, result],\n };\n }\n\n return {\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 overrideNavigation?: Navigation,\n submission?: Submission,\n fetcherSubmission?: Submission,\n replace?: boolean,\n initialHydration?: boolean,\n flushSync?: boolean,\n pendingActionResult?: PendingActionResult\n ): Promise {\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 let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n future.v7_partialHydration && initialHydration === true,\n future.unstable_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionResult\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\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 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 // If we have partialHydration enabled, then don't update the state for the\n // initial data load since it's not a \"navigation\"\n if (\n !isUninterruptedRevalidation &&\n (!future.v7_partialHydration || !initialHydration)\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\n let actionData: Record | 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 actionData = {\n [pendingActionResult[0]]: pendingActionResult[1].data as any,\n };\n } else if (state.actionData) {\n if (Object.keys(state.actionData).length === 0) {\n actionData = null;\n } else {\n actionData = state.actionData;\n }\n }\n\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData !== undefined ? { actionData } : {}),\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n revalidatingFetchers.forEach((rf) => {\n if (fetchControllers.has(rf.key)) {\n abortFetcher(rf.key);\n }\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.matches,\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 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, ...fetcherResults]);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\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 let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n await startRedirectNavigation(request, redirect.result, {\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 matchesToLoad,\n loaderResults,\n pendingActionResult,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe((aborted) => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n\n // During partial hydration, preserve SSR errors for routes that don't re-run\n if (future.v7_partialHydration && initialHydration && state.errors) {\n Object.entries(state.errors)\n .filter(([id]) => !matchesToLoad.some((m) => m.route.id === id))\n .forEach(([routeId, error]) => {\n errors = Object.assign(errors || {}, { [routeId]: error });\n });\n }\n\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n if (fetchControllers.has(key)) abortFetcher(key);\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n future.v7_relativeSplatPath,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\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 future.v7_normalizeFormMethod,\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 pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\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 handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\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 flushSync: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action && !match.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;\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 // Call the action for the fetcher\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResults = await callDataStrategy(\n \"action\",\n fetchRequest,\n [match],\n requestMatches\n );\n let actionResult = actionResults[0];\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 // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.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, {\n fetcherSubmission: submission,\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 if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\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 future.unstable_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\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 if (fetchControllers.has(staleKey)) {\n abortFetcher(staleKey);\n }\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.matches,\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, ...fetcherResults]);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\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 let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n return startRedirectNavigation(revalidationRequest, redirect.result);\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n state.matches,\n matchesToLoad,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\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 flushSync: 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 // Call the loader for this fetcher route match\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let results = await callDataStrategy(\n \"loader\",\n fetchRequest,\n [match],\n matches\n );\n let result = results[0];\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\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 (deletedFetchers.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);\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 invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\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 {\n submission,\n fetcherSubmission,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\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 redirectHistoryAction =\n replace === true ? HistoryAction.Replace : HistoryAction.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(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: location,\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\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(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\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 request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[]\n ): Promise {\n try {\n let results = await callDataStrategyImpl(\n dataStrategyImpl,\n type,\n request,\n matchesToLoad,\n matches,\n manifest,\n mapRouteProperties\n );\n\n return await Promise.all(\n results.map((result, i) => {\n if (isRedirectHandlerResult(result)) {\n let response = result.result as Response;\n return {\n type: ResultType.redirect,\n response: normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n matchesToLoad[i].route.id,\n matches,\n basename,\n future.v7_relativeSplatPath\n ),\n };\n }\n\n return convertHandlerResultToDataResult(result);\n })\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 return matchesToLoad.map(() => ({\n type: ResultType.error,\n error: e,\n }));\n }\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n let [loaderResults, ...fetcherResults] = await Promise.all([\n matchesToLoad.length\n ? callDataStrategy(\"loader\", request, matchesToLoad, matches)\n : [],\n ...fetchersToLoad.map((f) => {\n if (f.matches && f.match && f.controller) {\n let fetcherRequest = createClientSideRequest(\n init.history,\n f.path,\n f.controller.signal\n );\n return callDataStrategy(\n \"loader\",\n fetcherRequest,\n [f.match],\n f.matches\n ).then((r) => r[0]);\n } else {\n return Promise.resolve({\n type: ResultType.error,\n error: getInternalRouterError(404, {\n pathname: f.path,\n }),\n });\n }\n }),\n ]);\n\n await Promise.all([\n resolveDeferredResults(\n currentMatches,\n matchesToLoad,\n loaderResults,\n loaderResults.map(() => request.signal),\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map((f) => f.match),\n fetcherResults,\n fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)),\n true\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 // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.push(key);\n abortFetcher(key);\n }\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(key: string): Fetcher {\n if (future.v7_fetcherPersist) {\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 (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\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 deletedFetchers.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n if (future.v7_fetcherPersist) {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n } else {\n activeFetchers.set(key, count);\n }\n } else {\n deleteFetcher(key);\n }\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n invariant(controller, `Expected fetch controller: ${key}`);\n controller.abort();\n fetchControllers.delete(key);\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: HistoryAction;\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 cancelActiveDeferreds(\n predicate?: (routeId: string) => boolean\n ): string[] {\n let cancelledRouteIds: string[] = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the component\n function enableScrollRestoration(\n positions: Record,\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 \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 _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\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: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\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 const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n v7_relativeSplatPath: boolean;\n v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\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: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future: StaticHandlerFutureConfig = {\n v7_relativeSplatPath: false,\n v7_throwAbortReason: false,\n ...(opts ? opts.future : null),\n };\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 unstable_dataStrategy,\n }: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n unstable_dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\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 activeDeferreds: null,\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 activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n unstable_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 unstable_dataStrategy,\n }: {\n requestContext?: unknown;\n routeId?: string;\n unstable_dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\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 unstable_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 let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n unstable_dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null\n ): Promise | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n unstable_dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n unstable_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 `HandlerResult` to bail out early\n // and then return or throw the raw Response here accordingly\n if (isHandlerResult(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 unstable_dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n isRouteRequest: boolean\n ): Promise | 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 unstable_dataStrategy\n );\n result = results[0];\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\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 (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\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 activeDeferreds: null,\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 unstable_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 unstable_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 unstable_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 activeDeferreds: null,\n };\n }\n\n let results = await callDataStrategy(\n \"loader\",\n request,\n matchesToLoad,\n matches,\n isRouteRequest,\n requestContext,\n unstable_dataStrategy\n );\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionResult,\n activeDeferreds,\n skipLoaderErrorBubbling\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(\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 activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\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 unstable_dataStrategy: DataStrategyFunction | null\n ): Promise {\n let results = await callDataStrategyImpl(\n unstable_dataStrategy || defaultDataStrategy,\n type,\n request,\n matchesToLoad,\n matches,\n manifest,\n mapRouteProperties,\n requestContext\n );\n\n return await Promise.all(\n results.map((result, i) => {\n if (isRedirectHandlerResult(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 matchesToLoad[i].route.id,\n matches,\n basename,\n future.v7_relativeSplatPath\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 return convertHandlerResultToDataResult(result);\n })\n );\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 */\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 future: StaticHandlerFutureConfig\n) {\n if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n throw request.signal.reason;\n }\n\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\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 prependBasename: boolean,\n to: To | null,\n v7_relativeSplatPath: boolean,\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, v7_relativeSplatPath),\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 // Add an ?index param for matched index routes if we don't already have one\n if (\n (to == null || to === \"\" || to === \".\") &&\n activeRouteMatch &&\n activeRouteMatch.route.index &&\n !hasNakedIndexQuery(path.search)\n ) {\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. 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 (prependBasename && 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 normalizeFormMethod: boolean,\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 = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() 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 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) {\n let boundaryMatches = matches;\n if (boundaryId) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n boundaryMatches = matches.slice(0, index);\n }\n }\n return boundaryMatches;\n}\n\nfunction getMatchesToLoad(\n history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isInitialLoad: boolean,\n skipActionErrorRevalidation: boolean,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n deletedFetchers: Set,\n fetchLoadMatches: Map,\n fetchRedirectIds: Set,\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 boundaryId =\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? pendingActionResult[0]\n : undefined;\n let boundaryMatches = boundaryId\n ? getLoaderMatchesUntilBoundary(matches, boundaryId)\n : matches;\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 =\n skipActionErrorRevalidation && 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 (isInitialLoad) {\n if (typeof route.loader !== \"function\" || route.loader.hydrate) {\n return true;\n }\n return (\n state.loaderData[route.id] === undefined &&\n // Don't re-run if the loader ran and threw an error\n (!state.errors || state.errors[route.id] === undefined)\n );\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\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 unstable_actionStatus: 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 load (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 isInitialLoad ||\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.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.includes(key)) {\n // Always revalidate if the fetcher was cancelled\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 unstable_actionStatus: 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 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 or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\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\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 = {};\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\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // 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\nfunction defaultDataStrategy(\n opts: DataStrategyFunctionArgs\n): ReturnType {\n return Promise.all(opts.matches.map((m) => m.resolve()));\n}\n\nasync function callDataStrategyImpl(\n dataStrategyImpl: DataStrategyFunction,\n type: \"loader\" | \"action\",\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n requestContext?: unknown\n): Promise {\n let routeIdsToLoad = matchesToLoad.reduce(\n (acc, m) => acc.add(m.route.id),\n new Set()\n );\n let loadedMatches = new Set();\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: matches.map((match) => {\n let shouldLoad = routeIdsToLoad.has(match.route.id);\n // `resolve` encapsulates the route.lazy, executing the\n // loader/action, and mapping return values/thrown errors to a\n // HandlerResult. Users can pass a callback to take fine-grained control\n // over the execution of the loader/action\n let resolve: DataStrategyMatch[\"resolve\"] = (handlerOverride) => {\n loadedMatches.add(match.route.id);\n return shouldLoad\n ? callLoaderOrAction(\n type,\n request,\n match,\n manifest,\n mapRouteProperties,\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 request,\n params: matches[0].params,\n context: requestContext,\n });\n\n // Throw if any loadRoute implementations not called since they are what\n // ensures a route is fully loaded\n matches.forEach((m) =>\n invariant(\n loadedMatches.has(m.route.id),\n `\\`match.resolve()\\` was not called for route id \"${m.route.id}\". ` +\n \"You must call `match.resolve()` on every match passed to \" +\n \"`dataStrategy` to ensure all routes are properly loaded.\"\n )\n );\n\n // Filter out any middleware-only matches for which we didn't need to run handlers\n return results.filter((_, i) => routeIdsToLoad.has(matches[i].route.id));\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 manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n handlerOverride: Parameters[0],\n staticContext?: unknown\n): Promise {\n let result: HandlerResult;\n let onReject: (() => void) | undefined;\n\n let runHandler = (\n handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n ): Promise => {\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 to\n // satisfy the function return value\n let abortPromise = new Promise((_, 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;\n if (handlerOverride) {\n handlerPromise = handlerOverride((ctx: unknown) => actualHandler(ctx));\n } else {\n handlerPromise = (async () => {\n try {\n let val = await actualHandler();\n return { type: \"data\", result: val };\n } catch (e) {\n return { type: \"error\", result: e };\n }\n })();\n }\n\n return Promise.race([handlerPromise, abortPromise]);\n };\n\n try {\n let handler = match.route[type];\n\n if (match.route.lazy) {\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 loadLazyRouteModule(match.route, mapRouteProperties, manifest),\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 loadLazyRouteModule(match.route, mapRouteProperties, manifest);\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\n invariant(\n result.result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n // We should already be catching and converting normal handler executions to\n // HandlerResults 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 convertHandlerResultToDataResult(\n handlerResult: HandlerResult\n): Promise {\n let { result, type, status } = handlerResult;\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 return {\n type: ResultType.error,\n error: result,\n statusCode: isRouteErrorResponse(result) ? result.status : status,\n };\n }\n\n if (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n return { type: ResultType.data, data: result, statusCode: status };\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 v7_relativeSplatPath: boolean\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 true,\n location,\n v7_relativeSplatPath\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 matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingActionResult: PendingActionResult | undefined,\n activeDeferreds: Map,\n skipLoaderErrorBubbling: boolean\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record;\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 = {};\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 results.forEach((result, index) => {\n let id = matchesToLoad[index].route.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 loaderData[id] = undefined;\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 if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.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 (\n result.statusCode != null &&\n result.statusCode !== 200 &&\n !foundError\n ) {\n statusCode = result.statusCode;\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\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 matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingActionResult: PendingActionResult | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: DataResult[],\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionResult,\n activeDeferreds,\n false // This method is only called client side so we always want to bubble\n );\n\n // Process results from our revalidating fetchers\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let { key, match, controller } = revalidatingFetchers[index];\n invariant(\n fetcherResults !== undefined && fetcherResults[index] !== undefined,\n \"Did not find corresponding fetcher result\"\n );\n let result = fetcherResults[index];\n\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n continue;\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 if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\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 let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\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 }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\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 === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\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: DataResult[]\n): { result: RedirectResult; idx: number } | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return { result, idx: i };\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 isHandlerResult(result: unknown): result is HandlerResult {\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 isRedirectHandlerResult(result: HandlerResult) {\n return (\n isResponse(result.result) && redirectStatusCodes.has(result.result.status)\n );\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\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 isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\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 | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: (AgnosticDataRouteMatch | null)[],\n results: DataResult[],\n signals: (AbortSignal | null)[],\n isFetcher: boolean,\n currentLoaderData?: RouteData\n) {\n for (let index = 0; index < results.length; index++) {\n let result = results[index];\n let match = matchesToLoad[index];\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n let signal = signals[index];\n invariant(\n signal,\n \"Expected an AbortSignal for revalidating fetcher deferred result\"\n );\n await resolveDeferredData(result, signal, isFetcher).then((result) => {\n if (result) {\n results[index] = result || results[index];\n }\n });\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise {\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData,\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e,\n };\n }\n }\n\n return {\n type: ResultType.data,\n data: result.deferredData.data,\n };\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>\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>\n) {\n if (transitions.size > 0) {\n let json: Record = {};\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\n//#endregion\n"],"names":["Action","PopStateEventType","invariant","value","message","Error","warning","cond","console","warn","e","getHistoryState","location","index","usr","state","key","idx","createLocation","current","to","_extends","pathname","search","hash","parsePath","Math","random","toString","substr","createPath","_ref","charAt","path","parsedPath","hashIndex","indexOf","searchIndex","getUrlBasedHistory","getLocation","createHref","validateLocation","options","window","document","defaultView","v5Compat","globalHistory","history","action","Pop","listener","getIndex","handlePop","nextIndex","delta","createURL","base","origin","href","replace","URL","replaceState","listen","fn","addEventListener","removeEventListener","encodeLocation","url","push","Push","historyState","pushState","error","DOMException","name","assign","Replace","go","n","ResultType","immutableRouteKeys","Set","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","map","route","treePath","id","join","children","isIndexRoute","indexRoute","pathOrLayoutRoute","undefined","matchRoutes","locationArg","basename","stripBasename","branches","flattenRoutes","sort","a","b","score","length","slice","every","i","compareIndexes","routesMeta","meta","childrenIndex","rankRouteBranches","matches","decoded","decodePath","matchRouteBranch","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","caseSensitive","startsWith","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","getInvalidPathError","char","field","dest","JSON","stringify","getPathContributingMatches","getResolveToMatches","v7_relativeSplatPath","pathMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","from","isEmptyPath","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","paths","AbortedDeferredError","DeferredData","constructor","responseInit","reject","this","pendingKeysSet","subscribers","deferredKeys","Array","isArray","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","entries","acc","_ref2","trackPromise","done","init","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","k","async","resolve","size","unwrappedData","_ref3","unwrapTrackedPromise","pendingKeys","_tracked","isTrackedPromise","_error","_data","defer","redirect","status","headers","Headers","set","Response","ErrorResponseImpl","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","json","text","IDLE_FETCHER","IDLE_BLOCKER","proceed","reset","ABSOLUTE_URL_REGEX","defaultMapRouteProperties","hasErrorBoundary","Boolean","TRANSITIONS_STORAGE_KEY","UNSAFE_DEFERRED_SYMBOL","Symbol","throwStaticHandlerAbortedError","request","isRouteRequest","future","v7_throwAbortReason","reason","method","normalizeTo","prependBasename","fromRouteId","relative","contextualMatches","activeRouteMatch","hasNakedIndexQuery","normalizeNavigateOptions","normalizeFormMethod","isFetcher","opts","body","isSubmissionNavigation","isValidMethod","getInternalRouterError","searchParams","getInvalidBodyError","type","rawFormMethod","toUpperCase","stripHashFromPath","isMutationMethod","FormData","URLSearchParams","_ref5","String","submission","parse","convertFormDataToSearchParams","convertSearchParamsToFormData","append","getLoaderMatchesUntilBoundary","boundaryId","boundaryMatches","findIndex","m","getMatchesToLoad","isInitialLoad","skipActionErrorRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","deletedFetchers","fetchLoadMatches","fetchRedirectIds","routesToUse","pendingActionResult","actionResult","isErrorResult","currentUrl","nextUrl","actionStatus","statusCode","shouldSkipRevalidation","navigationMatches","lazy","loader","hydrate","errors","currentLoaderData","currentMatch","isNew","isMissingData","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","unstable_actionStatus","defaultShouldRevalidate","isNewRouteInstance","revalidatingFetchers","f","routeId","has","fetcherMatches","fetcher","fetchers","fetcherMatch","getTargetMatch","shouldRevalidate","currentPath","loaderMatch","arg","routeChoice","loadLazyRouteModule","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","isPropertyStaticallyDefined","defaultDataStrategy","all","callDataStrategyImpl","dataStrategyImpl","matchesToLoad","requestContext","routeIdsToLoad","loadedMatches","results","shouldLoad","handlerOverride","staticContext","onReject","runHandler","handler","handlerPromise","actualHandler","ctx","context","handlerError","callLoaderOrAction","convertHandlerResultToDataResult","handlerResult","isResponse","contentType","isDeferredData","deferred","deferredData","_result$init","_result$init2","normalizeRelativeRoutingRedirectResponse","response","trimmedMatches","normalizeRedirectLocation","normalizedLocation","protocol","isSameBasename","createClientSideRequest","Request","processRouteLoaderData","activeDeferreds","skipLoaderErrorBubbling","foundError","loaderHeaders","pendingError","isRedirectResult","boundaryMatch","findNearestBoundary","isDeferredResult","processLoaderData","fetcherResults","doneFetcher","getDoneFetcher","mergeLoaderData","newLoaderData","mergedLoaderData","hasOwnProperty","getActionDataForCommit","actionData","reverse","find","getShortCircuitMatches","_temp5","errorMessage","findRedirect","isRedirectHandlerResult","resolveData","resolveDeferredResults","currentMatches","signals","isRevalidatingLoader","resolveDeferredData","unwrap","getAll","getSubmissionFromNavigation","navigation","getLoadingNavigation","getSubmittingNavigation","getLoadingFetcher","querySelector","getAttribute","initialEntries","initialIndex","entry","createMemoryLocation","clampIndex","min","max","getCurrentLocation","nextLocation","splice","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","inFlightDataRoutes","initialized","dataRoutes","unstable_dataStrategy","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_prependBasename","unstable_skipActionErrorRevalidation","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialErrors","router","hasLazyRoutes","hasLoaders","isRouteInitialized","pendingNavigationController","historyAction","restoreScrollPosition","preventScrollReset","revalidation","Map","blockers","pendingAction","HistoryAction","pendingPreventScrollReset","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","activeFetchers","blockerFunctions","ignoreNextHistoryUpdate","updateState","newState","completedFetchers","deletedFetchersKeys","unstable_viewTransitionOpts","viewTransitionOpts","unstable_flushSync","flushSync","deleteFetcher","completeNavigation","_temp","_location$state","_location$state2","isActionReload","_isRedirect","keys","priorPaths","currentLocation","toPaths","getSavedScrollPosition","startNavigation","startUninterruptedRevalidation","getScrollKey","saveScrollPosition","enableViewTransition","loadingNavigation","overrideNavigation","notFoundMatches","cancelActiveDeferreds","isHashChangeOnly","interruptActiveLoads","actionMatch","callDataStrategy","shortCircuited","startRedirectNavigation","handleAction","fetcherSubmission","initialHydration","activeSubmission","updatedFetchers","markFetchRedirectsDone","rf","revalidatingFetcher","abortFetcher","abortPendingFetchRevalidations","loaderResults","callLoadersAndMaybeResolveData","fetcherKey","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","handleLoaders","_temp2","redirectLocation","isDocumentReload","redirectHistoryAction","fetchersToLoad","updateFetcherState","setFetcherError","getFetcher","markFetchersDone","doneKeys","landedId","yeetedKeys","deleteBlocker","updateBlocker","newBlocker","blocker","shouldBlockNavigation","_ref4","blockerKey","blockerFunction","predicate","cancelledRouteIds","dfd","y","initialize","_window","transitions","sessionPositions","sessionStorage","getItem","restoreAppliedTransitions","_saveAppliedTransitions","setItem","persistAppliedTransitions","enableScrollRestoration","positions","getPosition","getKey","navigate","normalizedPath","userReplace","unstable_viewTransition","fetch","requestMatches","existingFetcher","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","revalidationRequest","loadId","loadFetcher","staleKey","handleFetcherAction","handleFetcherLoader","revalidate","count","dispose","clear","getBlocker","_internalFetchControllers","_internalActiveDeferreds","_internalSetRoutes","newRoutes","queryImpl","routeMatch","Location","actionHeaders","loaderRequest","loadRouteData","submit","isHandlerResult","isRedirectResponse","executedLoaders","fromEntries","query","_temp3","methodNotAllowedMatches","queryRoute","_temp4","values","_result$activeDeferre","originalPath","prefix","p","array","keyMatch","optional","param","_deepestRenderedBoundaryId","redirectDocument"],"mappings":";;;;;;;;;;udAOYA,IAAAA,WAAAA,GAAM,OAANA,EAAM,IAAA,MAANA,EAAM,KAAA,OAANA,EAAM,QAAA,UAANA,CAAM,EAAA,IA2LlB,MAAMC,EAAoB,WAySnB,SAASC,EAAUC,EAA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K0K,KACtD,IAAImM,EAAWpK,EAASzM,EAAK0K,GAE7B,OADAmM,EAASlK,QAAQE,IAAI,0BAA2B,QACzCgK,CAAQ"} \ No newline at end of file diff --git a/node_modules/@remix-run/router/dist/utils.d.ts b/node_modules/@remix-run/router/dist/utils.d.ts deleted file mode 100644 index dec501fe..00000000 --- a/node_modules/@remix-run/router/dist/utils.d.ts +++ /dev/null @@ -1,520 +0,0 @@ -import type { Location, Path, To } from "./history"; -/** - * Map of routeId -> data returned from a loader/action/error - */ -export interface RouteData { - [routeId: string]: any; -} -export declare enum ResultType { - data = "data", - deferred = "deferred", - redirect = "redirect", - error = "error" -} -/** - * Successful result from a loader or action - */ -export interface SuccessResult { - type: ResultType.data; - data: unknown; - statusCode?: number; - headers?: Headers; -} -/** - * Successful defer() result from a loader or action - */ -export interface DeferredResult { - type: ResultType.deferred; - deferredData: DeferredData; - statusCode?: number; - headers?: Headers; -} -/** - * Redirect result from a loader or action - */ -export interface RedirectResult { - type: ResultType.redirect; - response: Response; -} -/** - * Unsuccessful result from a loader or action - */ -export interface ErrorResult { - type: ResultType.error; - error: unknown; - statusCode?: number; - headers?: Headers; -} -/** - * Result from a loader or action - potentially successful or unsuccessful - */ -export type DataResult = SuccessResult | DeferredResult | RedirectResult | ErrorResult; -/** - * Result from a loader or action called via dataStrategy - */ -export interface HandlerResult { - type: "data" | "error"; - result: unknown; - status?: number; -} -type LowerCaseFormMethod = "get" | "post" | "put" | "patch" | "delete"; -type UpperCaseFormMethod = Uppercase; -/** - * Users can specify either lowercase or uppercase form methods on ``, - * useSubmit(), ``, etc. - */ -export type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod; -/** - * Active navigation/fetcher form methods are exposed in lowercase on the - * RouterState - */ -export type FormMethod = LowerCaseFormMethod; -export type MutationFormMethod = Exclude; -/** - * In v7, active navigation/fetcher form methods are exposed in uppercase on the - * RouterState. This is to align with the normalization done via fetch(). - */ -export type V7_FormMethod = UpperCaseFormMethod; -export type V7_MutationFormMethod = Exclude; -export type FormEncType = "application/x-www-form-urlencoded" | "multipart/form-data" | "application/json" | "text/plain"; -type JsonObject = { - [Key in string]: JsonValue; -} & { - [Key in string]?: JsonValue | undefined; -}; -type JsonArray = JsonValue[] | readonly JsonValue[]; -type JsonPrimitive = string | number | boolean | null; -type JsonValue = JsonPrimitive | JsonObject | JsonArray; -/** - * @private - * Internal interface to pass around for action submissions, not intended for - * external consumption - */ -export type Submission = { - formMethod: FormMethod | V7_FormMethod; - formAction: string; - formEncType: FormEncType; - formData: FormData; - json: undefined; - text: undefined; -} | { - formMethod: FormMethod | V7_FormMethod; - formAction: string; - formEncType: FormEncType; - formData: undefined; - json: JsonValue; - text: undefined; -} | { - formMethod: FormMethod | V7_FormMethod; - formAction: string; - formEncType: FormEncType; - formData: undefined; - json: undefined; - text: string; -}; -/** - * @private - * Arguments passed to route loader/action functions. Same for now but we keep - * this as a private implementation detail in case they diverge in the future. - */ -interface DataFunctionArgs { - request: Request; - params: Params; - context?: Context; -} -/** - * Arguments passed to loader functions - */ -export interface LoaderFunctionArgs extends DataFunctionArgs { -} -/** - * Arguments passed to action functions - */ -export interface ActionFunctionArgs extends DataFunctionArgs { -} -/** - * Loaders and actions can return anything except `undefined` (`null` is a - * valid return value if there is no data to return). Responses are preferred - * and will ease any future migration to Remix - */ -type DataFunctionValue = Response | NonNullable | null; -type DataFunctionReturnValue = Promise | DataFunctionValue; -/** - * Route loader function signature - */ -export type LoaderFunction = { - (args: LoaderFunctionArgs, handlerCtx?: unknown): DataFunctionReturnValue; -} & { - hydrate?: boolean; -}; -/** - * Route action function signature - */ -export interface ActionFunction { - (args: ActionFunctionArgs, handlerCtx?: unknown): DataFunctionReturnValue; -} -/** - * Arguments passed to shouldRevalidate function - */ -export interface ShouldRevalidateFunctionArgs { - currentUrl: URL; - currentParams: AgnosticDataRouteMatch["params"]; - nextUrl: URL; - nextParams: AgnosticDataRouteMatch["params"]; - formMethod?: Submission["formMethod"]; - formAction?: Submission["formAction"]; - formEncType?: Submission["formEncType"]; - text?: Submission["text"]; - formData?: Submission["formData"]; - json?: Submission["json"]; - unstable_actionStatus?: number; - actionResult?: any; - defaultShouldRevalidate: boolean; -} -/** - * Route shouldRevalidate function signature. This runs after any submission - * (navigation or fetcher), so we flatten the navigation/fetcher submission - * onto the arguments. It shouldn't matter whether it came from a navigation - * or a fetcher, what really matters is the URLs and the formData since loaders - * have to re-run based on the data models that were potentially mutated. - */ -export interface ShouldRevalidateFunction { - (args: ShouldRevalidateFunctionArgs): boolean; -} -/** - * Function provided by the framework-aware layers to set `hasErrorBoundary` - * from the framework-aware `errorElement` prop - * - * @deprecated Use `mapRouteProperties` instead - */ -export interface DetectErrorBoundaryFunction { - (route: AgnosticRouteObject): boolean; -} -export interface DataStrategyMatch extends AgnosticRouteMatch { - shouldLoad: boolean; - resolve: (handlerOverride?: (handler: (ctx?: unknown) => DataFunctionReturnValue) => Promise) => Promise; -} -export interface DataStrategyFunctionArgs extends DataFunctionArgs { - matches: DataStrategyMatch[]; -} -export interface DataStrategyFunction { - (args: DataStrategyFunctionArgs): Promise; -} -/** - * Function provided by the framework-aware layers to set any framework-specific - * properties from framework-agnostic properties - */ -export interface MapRoutePropertiesFunction { - (route: AgnosticRouteObject): { - hasErrorBoundary: boolean; - } & Record; -} -/** - * Keys we cannot change from within a lazy() function. We spread all other keys - * onto the route. Either they're meaningful to the router, or they'll get - * ignored. - */ -export type ImmutableRouteKey = "lazy" | "caseSensitive" | "path" | "id" | "index" | "children"; -export declare const immutableRouteKeys: Set; -type RequireOne = Exclude<{ - [K in keyof T]: K extends Key ? Omit & Required> : never; -}[keyof T], undefined>; -/** - * lazy() function to load a route definition, which can add non-matching - * related properties to a route - */ -export interface LazyRouteFunction { - (): Promise>>; -} -/** - * Base RouteObject with common props shared by all types of routes - */ -type AgnosticBaseRouteObject = { - caseSensitive?: boolean; - path?: string; - id?: string; - loader?: LoaderFunction | boolean; - action?: ActionFunction | boolean; - hasErrorBoundary?: boolean; - shouldRevalidate?: ShouldRevalidateFunction; - handle?: any; - lazy?: LazyRouteFunction; -}; -/** - * Index routes must not have children - */ -export type AgnosticIndexRouteObject = AgnosticBaseRouteObject & { - children?: undefined; - index: true; -}; -/** - * Non-index routes may have children, but cannot have index - */ -export type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & { - children?: AgnosticRouteObject[]; - index?: false; -}; -/** - * A route object represents a logical route, with (optionally) its child - * routes organized in a tree-like structure. - */ -export type AgnosticRouteObject = AgnosticIndexRouteObject | AgnosticNonIndexRouteObject; -export type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & { - id: string; -}; -export type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & { - children?: AgnosticDataRouteObject[]; - id: string; -}; -/** - * A data route object, which is just a RouteObject with a required unique ID - */ -export type AgnosticDataRouteObject = AgnosticDataIndexRouteObject | AgnosticDataNonIndexRouteObject; -export type RouteManifest = Record; -type _PathParam = Path extends `${infer L}/${infer R}` ? _PathParam | _PathParam : Path extends `:${infer Param}` ? Param extends `${infer Optional}?` ? Optional : Param : never; -/** - * Examples: - * "/a/b/*" -> "*" - * ":a" -> "a" - * "/a/:b" -> "b" - * "/a/blahblahblah:b" -> "b" - * "/:a/:b" -> "a" | "b" - * "/:a/b/:c/*" -> "a" | "c" | "*" - */ -export type PathParam = Path extends "*" | "/*" ? "*" : Path extends `${infer Rest}/*` ? "*" | _PathParam : _PathParam; -export type ParamParseKey = [ - PathParam -] extends [never] ? string : PathParam; -/** - * The parameters that were parsed from the URL path. - */ -export type Params = { - readonly [key in Key]: string | undefined; -}; -/** - * A RouteMatch contains info about how a route matched a URL. - */ -export interface AgnosticRouteMatch { - /** - * The names and values of dynamic parameters in the URL. - */ - params: Params; - /** - * The portion of the URL pathname that was matched. - */ - pathname: string; - /** - * The portion of the URL pathname that was matched before child routes. - */ - pathnameBase: string; - /** - * The route object that was used to match. - */ - route: RouteObjectType; -} -export interface AgnosticDataRouteMatch extends AgnosticRouteMatch { -} -export declare function convertRoutesToDataRoutes(routes: AgnosticRouteObject[], mapRouteProperties: MapRoutePropertiesFunction, parentPath?: number[], manifest?: RouteManifest): AgnosticDataRouteObject[]; -/** - * Matches the given routes to a location and returns the match data. - * - * @see https://reactrouter.com/utils/match-routes - */ -export declare function matchRoutes(routes: RouteObjectType[], locationArg: Partial | string, basename?: string): AgnosticRouteMatch[] | null; -export interface UIMatch { - id: string; - pathname: string; - params: AgnosticRouteMatch["params"]; - data: Data; - handle: Handle; -} -export declare function convertRouteMatchToUiMatch(match: AgnosticDataRouteMatch, loaderData: RouteData): UIMatch; -/** - * Returns a path with params interpolated. - * - * @see https://reactrouter.com/utils/generate-path - */ -export declare function generatePath(originalPath: Path, params?: { - [key in PathParam]: string | null; -}): string; -/** - * A PathPattern is used to match on some portion of a URL pathname. - */ -export interface PathPattern { - /** - * A string to match against a URL pathname. May contain `:id`-style segments - * to indicate placeholders for dynamic parameters. May also end with `/*` to - * indicate matching the rest of the URL pathname. - */ - path: Path; - /** - * Should be `true` if the static portions of the `path` should be matched in - * the same case. - */ - caseSensitive?: boolean; - /** - * Should be `true` if this pattern should match the entire URL pathname. - */ - end?: boolean; -} -/** - * A PathMatch contains info about how a PathPattern matched on a URL pathname. - */ -export interface PathMatch { - /** - * The names and values of dynamic parameters in the URL. - */ - params: Params; - /** - * The portion of the URL pathname that was matched. - */ - pathname: string; - /** - * The portion of the URL pathname that was matched before child routes. - */ - pathnameBase: string; - /** - * The pattern that was used to match. - */ - pattern: PathPattern; -} -/** - * Performs pattern matching on a URL pathname and returns information about - * the match. - * - * @see https://reactrouter.com/utils/match-path - */ -export declare function matchPath, Path extends string>(pattern: PathPattern | Path, pathname: string): PathMatch | null; -/** - * @private - */ -export declare function stripBasename(pathname: string, basename: string): string | null; -/** - * Returns a resolved path object relative to the given pathname. - * - * @see https://reactrouter.com/utils/resolve-path - */ -export declare function resolvePath(to: To, fromPathname?: string): Path; -/** - * @private - * - * When processing relative navigation we want to ignore ancestor routes that - * do not contribute to the path, such that index/pathless layout routes don't - * interfere. - * - * For example, when moving a route element into an index route and/or a - * pathless layout route, relative link behavior contained within should stay - * the same. Both of the following examples should link back to the root: - * - * - * - * - * - * - * - * }> // <-- Does not contribute - * // <-- Does not contribute - * - * - */ -export declare function getPathContributingMatches(matches: T[]): T[]; -export declare function getResolveToMatches(matches: T[], v7_relativeSplatPath: boolean): string[]; -/** - * @private - */ -export declare function resolveTo(toArg: To, routePathnames: string[], locationPathname: string, isPathRelative?: boolean): Path; -/** - * @private - */ -export declare function getToPathname(to: To): string | undefined; -/** - * @private - */ -export declare const joinPaths: (paths: string[]) => string; -/** - * @private - */ -export declare const normalizePathname: (pathname: string) => string; -/** - * @private - */ -export declare const normalizeSearch: (search: string) => string; -/** - * @private - */ -export declare const normalizeHash: (hash: string) => string; -export type JsonFunction = (data: Data, init?: number | ResponseInit) => Response; -/** - * This is a shortcut for creating `application/json` responses. Converts `data` - * to JSON and sets the `Content-Type` header. - */ -export declare const json: JsonFunction; -export interface TrackedPromise extends Promise { - _tracked?: boolean; - _data?: any; - _error?: any; -} -export declare class AbortedDeferredError extends Error { -} -export declare class DeferredData { - private pendingKeysSet; - private controller; - private abortPromise; - private unlistenAbortSignal; - private subscribers; - data: Record; - init?: ResponseInit; - deferredKeys: string[]; - constructor(data: Record, responseInit?: ResponseInit); - private trackPromise; - private onSettle; - private emit; - subscribe(fn: (aborted: boolean, settledKey?: string) => void): () => boolean; - cancel(): void; - resolveData(signal: AbortSignal): Promise; - get done(): boolean; - get unwrappedData(): {}; - get pendingKeys(): string[]; -} -export type DeferFunction = (data: Record, init?: number | ResponseInit) => DeferredData; -export declare const defer: DeferFunction; -export type RedirectFunction = (url: string, init?: number | ResponseInit) => Response; -/** - * A redirect response. Sets the status code and the `Location` header. - * Defaults to "302 Found". - */ -export declare const redirect: RedirectFunction; -/** - * A redirect response that will force a document reload to the new location. - * Sets the status code and the `Location` header. - * Defaults to "302 Found". - */ -export declare const redirectDocument: RedirectFunction; -export type ErrorResponse = { - status: number; - statusText: string; - data: any; -}; -/** - * @private - * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies - * - * We don't export the class for public use since it's an implementation - * detail, but we export the interface above so folks can build their own - * abstractions around instances via isRouteErrorResponse() - */ -export declare class ErrorResponseImpl implements ErrorResponse { - status: number; - statusText: string; - data: any; - private error?; - private internal; - constructor(status: number, statusText: string | undefined, data: any, internal?: boolean); -} -/** - * Check if the given error is an ErrorResponse generated from a 4xx/5xx - * Response thrown from an action/loader - */ -export declare function isRouteErrorResponse(error: any): error is ErrorResponse; -export {}; diff --git a/node_modules/@remix-run/router/history.ts b/node_modules/@remix-run/router/history.ts deleted file mode 100644 index 335645db..00000000 --- a/node_modules/@remix-run/router/history.ts +++ /dev/null @@ -1,746 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -//#region Types and Constants -//////////////////////////////////////////////////////////////////////////////// - -/** - * Actions represent the type of change to a location value. - */ -export enum Action { - /** - * A POP indicates a change to an arbitrary index in the history stack, such - * as a back or forward navigation. It does not describe the direction of the - * navigation, only that the current index changed. - * - * Note: This is the default action for newly created history objects. - */ - Pop = "POP", - - /** - * A PUSH indicates a new entry being added to the history stack, such as when - * a link is clicked and a new page loads. When this happens, all subsequent - * entries in the stack are lost. - */ - Push = "PUSH", - - /** - * A REPLACE indicates the entry at the current index in the history stack - * being replaced by a new one. - */ - Replace = "REPLACE", -} - -/** - * The pathname, search, and hash values of a URL. - */ -export interface Path { - /** - * A URL pathname, beginning with a /. - */ - pathname: string; - - /** - * A URL search string, beginning with a ?. - */ - search: string; - - /** - * A URL fragment identifier, beginning with a #. - */ - hash: string; -} - -// TODO: (v7) Change the Location generic default from `any` to `unknown` and -// remove Remix `useLocation` wrapper. - -/** - * An entry in a history stack. A location contains information about the - * URL path, as well as possibly some arbitrary state and a key. - */ -export interface Location extends Path { - /** - * A value of arbitrary data associated with this location. - */ - state: State; - - /** - * A unique string associated with this location. May be used to safely store - * and retrieve data in some other storage API, like `localStorage`. - * - * Note: This value is always "default" on the initial location. - */ - key: string; -} - -/** - * A change to the current location. - */ -export interface Update { - /** - * The action that triggered the change. - */ - action: Action; - - /** - * The new location. - */ - location: Location; - - /** - * The delta between this location and the former location in the history stack - */ - delta: number | null; -} - -/** - * A function that receives notifications about location changes. - */ -export interface Listener { - (update: Update): void; -} - -/** - * Describes a location that is the destination of some navigation, either via - * `history.push` or `history.replace`. This may be either a URL or the pieces - * of a URL path. - */ -export type To = string | Partial; - -/** - * A history is an interface to the navigation stack. The history serves as the - * source of truth for the current location, as well as provides a set of - * methods that may be used to change it. - * - * It is similar to the DOM's `window.history` object, but with a smaller, more - * focused API. - */ -export interface History { - /** - * The last action that modified the current location. This will always be - * Action.Pop when a history instance is first created. This value is mutable. - */ - readonly action: Action; - - /** - * The current location. This value is mutable. - */ - readonly location: Location; - - /** - * Returns a valid href for the given `to` value that may be used as - * the value of an attribute. - * - * @param to - The destination URL - */ - createHref(to: To): string; - - /** - * Returns a URL for the given `to` value - * - * @param to - The destination URL - */ - createURL(to: To): URL; - - /** - * Encode a location the same way window.history would do (no-op for memory - * history) so we ensure our PUSH/REPLACE navigations for data routers - * behave the same as POP - * - * @param to Unencoded path - */ - encodeLocation(to: To): Path; - - /** - * Pushes a new location onto the history stack, increasing its length by one. - * If there were any entries in the stack after the current one, they are - * lost. - * - * @param to - The new URL - * @param state - Data to associate with the new location - */ - push(to: To, state?: any): void; - - /** - * Replaces the current location in the history stack with a new one. The - * location that was replaced will no longer be available. - * - * @param to - The new URL - * @param state - Data to associate with the new location - */ - replace(to: To, state?: any): void; - - /** - * Navigates `n` entries backward/forward in the history stack relative to the - * current index. For example, a "back" navigation would use go(-1). - * - * @param delta - The delta in the stack index - */ - go(delta: number): void; - - /** - * Sets up a listener that will be called whenever the current location - * changes. - * - * @param listener - A function that will be called when the location changes - * @returns unlisten - A function that may be used to stop listening - */ - listen(listener: Listener): () => void; -} - -type HistoryState = { - usr: any; - key?: string; - idx: number; -}; - -const PopStateEventType = "popstate"; -//#endregion - -//////////////////////////////////////////////////////////////////////////////// -//#region Memory History -//////////////////////////////////////////////////////////////////////////////// - -/** - * A user-supplied object that describes a location. Used when providing - * entries to `createMemoryHistory` via its `initialEntries` option. - */ -export type InitialEntry = string | Partial; - -export type MemoryHistoryOptions = { - initialEntries?: InitialEntry[]; - initialIndex?: number; - v5Compat?: boolean; -}; - -/** - * A memory history stores locations in memory. This is useful in stateful - * environments where there is no web browser, such as node tests or React - * Native. - */ -export interface MemoryHistory extends History { - /** - * The current index in the history stack. - */ - readonly index: number; -} - -/** - * Memory history stores the current location in memory. It is designed for use - * in stateful non-browser environments like tests and React Native. - */ -export function createMemoryHistory( - options: MemoryHistoryOptions = {} -): MemoryHistory { - let { initialEntries = ["/"], initialIndex, v5Compat = false } = options; - let entries: Location[]; // Declare so we can access from createMemoryLocation - entries = initialEntries.map((entry, index) => - createMemoryLocation( - entry, - typeof entry === "string" ? null : entry.state, - index === 0 ? "default" : undefined - ) - ); - let index = clampIndex( - initialIndex == null ? entries.length - 1 : initialIndex - ); - let action = Action.Pop; - let listener: Listener | null = null; - - function clampIndex(n: number): number { - return Math.min(Math.max(n, 0), entries.length - 1); - } - function getCurrentLocation(): Location { - return entries[index]; - } - function createMemoryLocation( - to: To, - state: any = null, - key?: string - ): Location { - let location = createLocation( - entries ? getCurrentLocation().pathname : "/", - to, - state, - key - ); - warning( - location.pathname.charAt(0) === "/", - `relative pathnames are not supported in memory history: ${JSON.stringify( - to - )}` - ); - return location; - } - - function createHref(to: To) { - return typeof to === "string" ? to : createPath(to); - } - - let history: MemoryHistory = { - get index() { - return index; - }, - get action() { - return action; - }, - get location() { - return getCurrentLocation(); - }, - createHref, - createURL(to) { - return new URL(createHref(to), "http://localhost"); - }, - encodeLocation(to: To) { - let path = typeof to === "string" ? parsePath(to) : to; - return { - pathname: path.pathname || "", - search: path.search || "", - hash: path.hash || "", - }; - }, - push(to, state) { - action = Action.Push; - let nextLocation = createMemoryLocation(to, state); - index += 1; - entries.splice(index, entries.length, nextLocation); - if (v5Compat && listener) { - listener({ action, location: nextLocation, delta: 1 }); - } - }, - replace(to, state) { - action = Action.Replace; - let nextLocation = createMemoryLocation(to, state); - entries[index] = nextLocation; - if (v5Compat && listener) { - listener({ action, location: nextLocation, delta: 0 }); - } - }, - go(delta) { - action = Action.Pop; - let nextIndex = clampIndex(index + delta); - let nextLocation = entries[nextIndex]; - index = nextIndex; - if (listener) { - listener({ action, location: nextLocation, delta }); - } - }, - listen(fn: Listener) { - listener = fn; - return () => { - listener = null; - }; - }, - }; - - return history; -} -//#endregion - -//////////////////////////////////////////////////////////////////////////////// -//#region Browser History -//////////////////////////////////////////////////////////////////////////////// - -/** - * A browser history stores the current location in regular URLs in a web - * browser environment. This is the standard for most web apps and provides the - * cleanest URLs the browser's address bar. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory - */ -export interface BrowserHistory extends UrlHistory {} - -export type BrowserHistoryOptions = UrlHistoryOptions; - -/** - * Browser history stores the location in regular URLs. This is the standard for - * most web apps, but it requires some configuration on the server to ensure you - * serve the same app at multiple URLs. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory - */ -export function createBrowserHistory( - options: BrowserHistoryOptions = {} -): BrowserHistory { - function createBrowserLocation( - window: Window, - globalHistory: Window["history"] - ) { - let { pathname, search, hash } = window.location; - return createLocation( - "", - { pathname, search, hash }, - // state defaults to `null` because `window.history.state` does - (globalHistory.state && globalHistory.state.usr) || null, - (globalHistory.state && globalHistory.state.key) || "default" - ); - } - - function createBrowserHref(window: Window, to: To) { - return typeof to === "string" ? to : createPath(to); - } - - return getUrlBasedHistory( - createBrowserLocation, - createBrowserHref, - null, - options - ); -} -//#endregion - -//////////////////////////////////////////////////////////////////////////////// -//#region Hash History -//////////////////////////////////////////////////////////////////////////////// - -/** - * A hash history stores the current location in the fragment identifier portion - * of the URL in a web browser environment. - * - * This is ideal for apps that do not control the server for some reason - * (because the fragment identifier is never sent to the server), including some - * shared hosting environments that do not provide fine-grained controls over - * which pages are served at which URLs. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory - */ -export interface HashHistory extends UrlHistory {} - -export type HashHistoryOptions = UrlHistoryOptions; - -/** - * Hash history stores the location in window.location.hash. This makes it ideal - * for situations where you don't want to send the location to the server for - * some reason, either because you do cannot configure it or the URL space is - * reserved for something else. - * - * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory - */ -export function createHashHistory( - options: HashHistoryOptions = {} -): HashHistory { - function createHashLocation( - window: Window, - globalHistory: Window["history"] - ) { - let { - pathname = "/", - search = "", - hash = "", - } = parsePath(window.location.hash.substr(1)); - - // Hash URL should always have a leading / just like window.location.pathname - // does, so if an app ends up at a route like /#something then we add a - // leading slash so all of our path-matching behaves the same as if it would - // in a browser router. This is particularly important when there exists a - // root splat route () since that matches internally against - // "/*" and we'd expect /#something to 404 in a hash router app. - if (!pathname.startsWith("/") && !pathname.startsWith(".")) { - pathname = "/" + pathname; - } - - return createLocation( - "", - { pathname, search, hash }, - // state defaults to `null` because `window.history.state` does - (globalHistory.state && globalHistory.state.usr) || null, - (globalHistory.state && globalHistory.state.key) || "default" - ); - } - - function createHashHref(window: Window, to: To) { - let base = window.document.querySelector("base"); - let href = ""; - - if (base && base.getAttribute("href")) { - let url = window.location.href; - let hashIndex = url.indexOf("#"); - href = hashIndex === -1 ? url : url.slice(0, hashIndex); - } - - return href + "#" + (typeof to === "string" ? to : createPath(to)); - } - - function validateHashLocation(location: Location, to: To) { - warning( - location.pathname.charAt(0) === "/", - `relative pathnames are not supported in hash history.push(${JSON.stringify( - to - )})` - ); - } - - return getUrlBasedHistory( - createHashLocation, - createHashHref, - validateHashLocation, - options - ); -} -//#endregion - -//////////////////////////////////////////////////////////////////////////////// -//#region UTILS -//////////////////////////////////////////////////////////////////////////////// - -/** - * @private - */ -export function invariant(value: boolean, message?: string): asserts value; -export function invariant( - value: T | null | undefined, - message?: string -): asserts value is T; -export function invariant(value: any, message?: string) { - if (value === false || value === null || typeof value === "undefined") { - throw new Error(message); - } -} - -export function warning(cond: any, message: string) { - if (!cond) { - // eslint-disable-next-line no-console - if (typeof console !== "undefined") console.warn(message); - - try { - // Welcome to debugging history! - // - // This error is thrown as a convenience, so you can more easily - // find the source for a warning that appears in the console by - // enabling "pause on exceptions" in your JavaScript debugger. - throw new Error(message); - // eslint-disable-next-line no-empty - } catch (e) {} - } -} - -function createKey() { - return Math.random().toString(36).substr(2, 8); -} - -/** - * For browser-based histories, we combine the state and key into an object - */ -function getHistoryState(location: Location, index: number): HistoryState { - return { - usr: location.state, - key: location.key, - idx: index, - }; -} - -/** - * Creates a Location object with a unique key from the given Path - */ -export function createLocation( - current: string | Location, - to: To, - state: any = null, - key?: string -): Readonly { - let location: Readonly = { - pathname: typeof current === "string" ? current : current.pathname, - search: "", - hash: "", - ...(typeof to === "string" ? parsePath(to) : to), - state, - // TODO: This could be cleaned up. push/replace should probably just take - // full Locations now and avoid the need to run through this flow at all - // But that's a pretty big refactor to the current test suite so going to - // keep as is for the time being and just let any incoming keys take precedence - key: (to && (to as Location).key) || key || createKey(), - }; - return location; -} - -/** - * Creates a string URL path from the given pathname, search, and hash components. - */ -export function createPath({ - pathname = "/", - search = "", - hash = "", -}: Partial) { - if (search && search !== "?") - pathname += search.charAt(0) === "?" ? search : "?" + search; - if (hash && hash !== "#") - pathname += hash.charAt(0) === "#" ? hash : "#" + hash; - return pathname; -} - -/** - * Parses a string URL path into its separate pathname, search, and hash components. - */ -export function parsePath(path: string): Partial { - let parsedPath: Partial = {}; - - if (path) { - let hashIndex = path.indexOf("#"); - if (hashIndex >= 0) { - parsedPath.hash = path.substr(hashIndex); - path = path.substr(0, hashIndex); - } - - let searchIndex = path.indexOf("?"); - if (searchIndex >= 0) { - parsedPath.search = path.substr(searchIndex); - path = path.substr(0, searchIndex); - } - - if (path) { - parsedPath.pathname = path; - } - } - - return parsedPath; -} - -export interface UrlHistory extends History {} - -export type UrlHistoryOptions = { - window?: Window; - v5Compat?: boolean; -}; - -function getUrlBasedHistory( - getLocation: (window: Window, globalHistory: Window["history"]) => Location, - createHref: (window: Window, to: To) => string, - validateLocation: ((location: Location, to: To) => void) | null, - options: UrlHistoryOptions = {} -): UrlHistory { - let { window = document.defaultView!, v5Compat = false } = options; - let globalHistory = window.history; - let action = Action.Pop; - let listener: Listener | null = null; - - let index = getIndex()!; - // Index should only be null when we initialize. If not, it's because the - // user called history.pushState or history.replaceState directly, in which - // case we should log a warning as it will result in bugs. - if (index == null) { - index = 0; - globalHistory.replaceState({ ...globalHistory.state, idx: index }, ""); - } - - function getIndex(): number { - let state = globalHistory.state || { idx: null }; - return state.idx; - } - - function handlePop() { - action = Action.Pop; - let nextIndex = getIndex(); - let delta = nextIndex == null ? null : nextIndex - index; - index = nextIndex; - if (listener) { - listener({ action, location: history.location, delta }); - } - } - - function push(to: To, state?: any) { - action = Action.Push; - let location = createLocation(history.location, to, state); - if (validateLocation) validateLocation(location, to); - - index = getIndex() + 1; - let historyState = getHistoryState(location, index); - let url = history.createHref(location); - - // try...catch because iOS limits us to 100 pushState calls :/ - try { - globalHistory.pushState(historyState, "", url); - } catch (error) { - // If the exception is because `state` can't be serialized, let that throw - // outwards just like a replace call would so the dev knows the cause - // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps - // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal - if (error instanceof DOMException && error.name === "DataCloneError") { - throw error; - } - // They are going to lose state here, but there is no real - // way to warn them about it since the page will refresh... - window.location.assign(url); - } - - if (v5Compat && listener) { - listener({ action, location: history.location, delta: 1 }); - } - } - - function replace(to: To, state?: any) { - action = Action.Replace; - let location = createLocation(history.location, to, state); - if (validateLocation) validateLocation(location, to); - - index = getIndex(); - let historyState = getHistoryState(location, index); - let url = history.createHref(location); - globalHistory.replaceState(historyState, "", url); - - if (v5Compat && listener) { - listener({ action, location: history.location, delta: 0 }); - } - } - - function createURL(to: To): URL { - // window.location.origin is "null" (the literal string value) in Firefox - // under certain conditions, notably when serving from a local HTML file - // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297 - let base = - window.location.origin !== "null" - ? window.location.origin - : window.location.href; - - let href = typeof to === "string" ? to : createPath(to); - // Treating this as a full URL will strip any trailing spaces so we need to - // pre-encode them since they might be part of a matching splat param from - // an ancestor route - href = href.replace(/ $/, "%20"); - invariant( - base, - `No window.location.(origin|href) available to create URL for href: ${href}` - ); - return new URL(href, base); - } - - let history: History = { - get action() { - return action; - }, - get location() { - return getLocation(window, globalHistory); - }, - listen(fn: Listener) { - if (listener) { - throw new Error("A history only accepts one active listener"); - } - window.addEventListener(PopStateEventType, handlePop); - listener = fn; - - return () => { - window.removeEventListener(PopStateEventType, handlePop); - listener = null; - }; - }, - createHref(to) { - return createHref(window, to); - }, - createURL, - encodeLocation(to) { - // Encode a Location the same way window.location would - let url = createURL(to); - return { - pathname: url.pathname, - search: url.search, - hash: url.hash, - }; - }, - push, - replace, - go(n) { - return globalHistory.go(n); - }, - }; - - return history; -} - -//#endregion diff --git a/node_modules/@remix-run/router/index.ts b/node_modules/@remix-run/router/index.ts deleted file mode 100644 index 8a07c5e2..00000000 --- a/node_modules/@remix-run/router/index.ts +++ /dev/null @@ -1,100 +0,0 @@ -export type { - ActionFunction, - ActionFunctionArgs, - AgnosticDataIndexRouteObject, - AgnosticDataNonIndexRouteObject, - AgnosticDataRouteMatch, - AgnosticDataRouteObject, - AgnosticIndexRouteObject, - AgnosticNonIndexRouteObject, - AgnosticRouteMatch, - AgnosticRouteObject, - DataStrategyFunction as unstable_DataStrategyFunction, - DataStrategyFunctionArgs as unstable_DataStrategyFunctionArgs, - DataStrategyMatch as unstable_DataStrategyMatch, - ErrorResponse, - FormEncType, - FormMethod, - HandlerResult as unstable_HandlerResult, - HTMLFormMethod, - JsonFunction, - LazyRouteFunction, - LoaderFunction, - LoaderFunctionArgs, - ParamParseKey, - Params, - PathMatch, - PathParam, - PathPattern, - RedirectFunction, - ShouldRevalidateFunction, - ShouldRevalidateFunctionArgs, - TrackedPromise, - UIMatch, - V7_FormMethod, -} from "./utils"; - -export { - AbortedDeferredError, - defer, - generatePath, - getToPathname, - isRouteErrorResponse, - joinPaths, - json, - matchPath, - matchRoutes, - normalizePathname, - redirect, - redirectDocument, - resolvePath, - resolveTo, - stripBasename, -} from "./utils"; - -export type { - BrowserHistory, - BrowserHistoryOptions, - HashHistory, - HashHistoryOptions, - History, - InitialEntry, - Location, - MemoryHistory, - MemoryHistoryOptions, - Path, - To, -} from "./history"; - -export { - Action, - createBrowserHistory, - createHashHistory, - createMemoryHistory, - createPath, - parsePath, -} from "./history"; - -export * from "./router"; - -/////////////////////////////////////////////////////////////////////////////// -// DANGER! PLEASE READ ME! -// We consider these exports an implementation detail and do not guarantee -// against any breaking changes, regardless of the semver release. Use with -// extreme caution and only if you understand the consequences. Godspeed. -/////////////////////////////////////////////////////////////////////////////// - -/** @internal */ -export type { RouteManifest as UNSAFE_RouteManifest } from "./utils"; -export { - DeferredData as UNSAFE_DeferredData, - ErrorResponseImpl as UNSAFE_ErrorResponseImpl, - convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes, - convertRouteMatchToUiMatch as UNSAFE_convertRouteMatchToUiMatch, - getResolveToMatches as UNSAFE_getResolveToMatches, -} from "./utils"; - -export { - invariant as UNSAFE_invariant, - warning as UNSAFE_warning, -} from "./history"; diff --git a/node_modules/@remix-run/router/package.json b/node_modules/@remix-run/router/package.json deleted file mode 100644 index 6b56d4d2..00000000 --- a/node_modules/@remix-run/router/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "@remix-run/router", - "version": "1.16.1", - "description": "Nested/Data-driven/Framework-agnostic Routing", - "keywords": [ - "remix", - "router", - "location" - ], - "repository": { - "type": "git", - "url": "https://github.com/remix-run/react-router", - "directory": "packages/router" - }, - "license": "MIT", - "author": "Remix Software ", - "sideEffects": false, - "main": "./dist/router.cjs.js", - "unpkg": "./dist/router.umd.min.js", - "module": "./dist/router.js", - "types": "./dist/index.d.ts", - "files": [ - "dist/", - "*.ts", - "CHANGELOG.md" - ], - "engines": { - "node": ">=14.0.0" - }, - "publishConfig": { - "access": "public" - } -} \ No newline at end of file diff --git a/node_modules/@remix-run/router/router.ts b/node_modules/@remix-run/router/router.ts deleted file mode 100644 index b72cb700..00000000 --- a/node_modules/@remix-run/router/router.ts +++ /dev/null @@ -1,5247 +0,0 @@ -import type { History, Location, Path, To } from "./history"; -import { - Action as HistoryAction, - createLocation, - createPath, - invariant, - parsePath, - warning, -} from "./history"; -import type { - AgnosticDataRouteMatch, - AgnosticDataRouteObject, - DataStrategyMatch, - AgnosticRouteObject, - DataResult, - DataStrategyFunction, - DataStrategyFunctionArgs, - DeferredData, - DeferredResult, - DetectErrorBoundaryFunction, - ErrorResult, - FormEncType, - FormMethod, - HTMLFormMethod, - HandlerResult, - ImmutableRouteKey, - MapRoutePropertiesFunction, - MutationFormMethod, - RedirectResult, - RouteData, - RouteManifest, - ShouldRevalidateFunctionArgs, - Submission, - SuccessResult, - UIMatch, - V7_FormMethod, - V7_MutationFormMethod, -} from "./utils"; -import { - ErrorResponseImpl, - ResultType, - convertRouteMatchToUiMatch, - convertRoutesToDataRoutes, - getPathContributingMatches, - getResolveToMatches, - immutableRouteKeys, - isRouteErrorResponse, - joinPaths, - matchRoutes, - resolveTo, - stripBasename, -} from "./utils"; - -//////////////////////////////////////////////////////////////////////////////// -//#region Types and Constants -//////////////////////////////////////////////////////////////////////////////// - -/** - * A Router instance manages all navigation and data loading/mutations - */ -export interface Router { - /** - * @internal - * PRIVATE - DO NOT USE - * - * Return the basename for the router - */ - get basename(): RouterInit["basename"]; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Return the future config for the router - */ - get future(): FutureConfig; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Return the current state of the router - */ - get state(): RouterState; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Return the routes for this router instance - */ - get routes(): AgnosticDataRouteObject[]; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Return the window associated with the router - */ - get window(): RouterInit["window"]; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Initialize the router, including adding history listeners and kicking off - * initial data fetches. Returns a function to cleanup listeners and abort - * any in-progress loads - */ - initialize(): Router; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Subscribe to router.state updates - * - * @param fn function to call with the new state - */ - subscribe(fn: RouterSubscriber): () => void; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Enable scroll restoration behavior in the router - * - * @param savedScrollPositions Object that will manage positions, in case - * it's being restored from sessionStorage - * @param getScrollPosition Function to get the active Y scroll position - * @param getKey Function to get the key to use for restoration - */ - enableScrollRestoration( - savedScrollPositions: Record, - getScrollPosition: GetScrollPositionFunction, - getKey?: GetScrollRestorationKeyFunction - ): () => void; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Navigate forward/backward in the history stack - * @param to Delta to move in the history stack - */ - navigate(to: number): Promise; - - /** - * Navigate to the given path - * @param to Path to navigate to - * @param opts Navigation options (method, submission, etc.) - */ - navigate(to: To | null, opts?: RouterNavigateOptions): Promise; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Trigger a fetcher load/submission - * - * @param key Fetcher key - * @param routeId Route that owns the fetcher - * @param href href to fetch - * @param opts Fetcher options, (method, submission, etc.) - */ - fetch( - key: string, - routeId: string, - href: string | null, - opts?: RouterFetchOptions - ): void; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Trigger a revalidation of all current route loaders and fetcher loads - */ - revalidate(): void; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Utility function to create an href for the given location - * @param location - */ - createHref(location: Location | URL): string; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Utility function to URL encode a destination path according to the internal - * history implementation - * @param to - */ - encodeLocation(to: To): Path; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Get/create a fetcher for the given key - * @param key - */ - getFetcher(key: string): Fetcher; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Delete the fetcher for a given key - * @param key - */ - deleteFetcher(key: string): void; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Cleanup listeners and abort any in-progress loads - */ - dispose(): void; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Get a navigation blocker - * @param key The identifier for the blocker - * @param fn The blocker function implementation - */ - getBlocker(key: string, fn: BlockerFunction): Blocker; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Delete a navigation blocker - * @param key The identifier for the blocker - */ - deleteBlocker(key: string): void; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * HMR needs to pass in-flight route updates to React Router - * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute) - */ - _internalSetRoutes(routes: AgnosticRouteObject[]): void; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Internal fetch AbortControllers accessed by unit tests - */ - _internalFetchControllers: Map; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Internal pending DeferredData instances accessed by unit tests - */ - _internalActiveDeferreds: Map; -} - -/** - * State maintained internally by the router. During a navigation, all states - * reflect the the "old" location unless otherwise noted. - */ -export interface RouterState { - /** - * The action of the most recent navigation - */ - historyAction: HistoryAction; - - /** - * The current location reflected by the router - */ - location: Location; - - /** - * The current set of route matches - */ - matches: AgnosticDataRouteMatch[]; - - /** - * Tracks whether we've completed our initial data load - */ - initialized: boolean; - - /** - * Current scroll position we should start at for a new view - * - number -> scroll position to restore to - * - false -> do not restore scroll at all (used during submissions) - * - null -> don't have a saved position, scroll to hash or top of page - */ - restoreScrollPosition: number | false | null; - - /** - * Indicate whether this navigation should skip resetting the scroll position - * if we are unable to restore the scroll position - */ - preventScrollReset: boolean; - - /** - * Tracks the state of the current navigation - */ - navigation: Navigation; - - /** - * Tracks any in-progress revalidations - */ - revalidation: RevalidationState; - - /** - * Data from the loaders for the current matches - */ - loaderData: RouteData; - - /** - * Data from the action for the current matches - */ - actionData: RouteData | null; - - /** - * Errors caught from loaders for the current matches - */ - errors: RouteData | null; - - /** - * Map of current fetchers - */ - fetchers: Map; - - /** - * Map of current blockers - */ - blockers: Map; -} - -/** - * Data that can be passed into hydrate a Router from SSR - */ -export type HydrationState = Partial< - Pick ->; - -/** - * Future flags to toggle new feature behavior - */ -export interface FutureConfig { - v7_fetcherPersist: boolean; - v7_normalizeFormMethod: boolean; - v7_partialHydration: boolean; - v7_prependBasename: boolean; - v7_relativeSplatPath: boolean; - unstable_skipActionErrorRevalidation: boolean; -} - -/** - * Initialization options for createRouter - */ -export interface RouterInit { - routes: AgnosticRouteObject[]; - history: History; - basename?: string; - /** - * @deprecated Use `mapRouteProperties` instead - */ - detectErrorBoundary?: DetectErrorBoundaryFunction; - mapRouteProperties?: MapRoutePropertiesFunction; - future?: Partial; - hydrationData?: HydrationState; - window?: Window; - unstable_dataStrategy?: DataStrategyFunction; -} - -/** - * State returned from a server-side query() call - */ -export interface StaticHandlerContext { - basename: Router["basename"]; - location: RouterState["location"]; - matches: RouterState["matches"]; - loaderData: RouterState["loaderData"]; - actionData: RouterState["actionData"]; - errors: RouterState["errors"]; - statusCode: number; - loaderHeaders: Record; - actionHeaders: Record; - activeDeferreds: Record | null; - _deepestRenderedBoundaryId?: string | null; -} - -/** - * A StaticHandler instance manages a singular SSR navigation/fetch event - */ -export interface StaticHandler { - dataRoutes: AgnosticDataRouteObject[]; - query( - request: Request, - opts?: { - requestContext?: unknown; - skipLoaderErrorBubbling?: boolean; - unstable_dataStrategy?: DataStrategyFunction; - } - ): Promise; - queryRoute( - request: Request, - opts?: { - routeId?: string; - requestContext?: unknown; - unstable_dataStrategy?: DataStrategyFunction; - } - ): Promise; -} - -type ViewTransitionOpts = { - currentLocation: Location; - nextLocation: Location; -}; - -/** - * Subscriber function signature for changes to router state - */ -export interface RouterSubscriber { - ( - state: RouterState, - opts: { - deletedFetchers: string[]; - unstable_viewTransitionOpts?: ViewTransitionOpts; - unstable_flushSync: boolean; - } - ): void; -} - -/** - * Function signature for determining the key to be used in scroll restoration - * for a given location - */ -export interface GetScrollRestorationKeyFunction { - (location: Location, matches: UIMatch[]): string | null; -} - -/** - * Function signature for determining the current scroll position - */ -export interface GetScrollPositionFunction { - (): number; -} - -export type RelativeRoutingType = "route" | "path"; - -// Allowed for any navigation or fetch -type BaseNavigateOrFetchOptions = { - preventScrollReset?: boolean; - relative?: RelativeRoutingType; - unstable_flushSync?: boolean; -}; - -// Only allowed for navigations -type BaseNavigateOptions = BaseNavigateOrFetchOptions & { - replace?: boolean; - state?: any; - fromRouteId?: string; - unstable_viewTransition?: boolean; -}; - -// Only allowed for submission navigations -type BaseSubmissionOptions = { - formMethod?: HTMLFormMethod; - formEncType?: FormEncType; -} & ( - | { formData: FormData; body?: undefined } - | { formData?: undefined; body: any } -); - -/** - * Options for a navigate() call for a normal (non-submission) navigation - */ -type LinkNavigateOptions = BaseNavigateOptions; - -/** - * Options for a navigate() call for a submission navigation - */ -type SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions; - -/** - * Options to pass to navigate() for a navigation - */ -export type RouterNavigateOptions = - | LinkNavigateOptions - | SubmissionNavigateOptions; - -/** - * Options for a fetch() load - */ -type LoadFetchOptions = BaseNavigateOrFetchOptions; - -/** - * Options for a fetch() submission - */ -type SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions; - -/** - * Options to pass to fetch() - */ -export type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions; - -/** - * Potential states for state.navigation - */ -export type NavigationStates = { - Idle: { - state: "idle"; - location: undefined; - formMethod: undefined; - formAction: undefined; - formEncType: undefined; - formData: undefined; - json: undefined; - text: undefined; - }; - Loading: { - state: "loading"; - location: Location; - formMethod: Submission["formMethod"] | undefined; - formAction: Submission["formAction"] | undefined; - formEncType: Submission["formEncType"] | undefined; - formData: Submission["formData"] | undefined; - json: Submission["json"] | undefined; - text: Submission["text"] | undefined; - }; - Submitting: { - state: "submitting"; - location: Location; - formMethod: Submission["formMethod"]; - formAction: Submission["formAction"]; - formEncType: Submission["formEncType"]; - formData: Submission["formData"]; - json: Submission["json"]; - text: Submission["text"]; - }; -}; - -export type Navigation = NavigationStates[keyof NavigationStates]; - -export type RevalidationState = "idle" | "loading"; - -/** - * Potential states for fetchers - */ -type FetcherStates = { - Idle: { - state: "idle"; - formMethod: undefined; - formAction: undefined; - formEncType: undefined; - text: undefined; - formData: undefined; - json: undefined; - data: TData | undefined; - }; - Loading: { - state: "loading"; - formMethod: Submission["formMethod"] | undefined; - formAction: Submission["formAction"] | undefined; - formEncType: Submission["formEncType"] | undefined; - text: Submission["text"] | undefined; - formData: Submission["formData"] | undefined; - json: Submission["json"] | undefined; - data: TData | undefined; - }; - Submitting: { - state: "submitting"; - formMethod: Submission["formMethod"]; - formAction: Submission["formAction"]; - formEncType: Submission["formEncType"]; - text: Submission["text"]; - formData: Submission["formData"]; - json: Submission["json"]; - data: TData | undefined; - }; -}; - -export type Fetcher = - FetcherStates[keyof FetcherStates]; - -interface BlockerBlocked { - state: "blocked"; - reset(): void; - proceed(): void; - location: Location; -} - -interface BlockerUnblocked { - state: "unblocked"; - reset: undefined; - proceed: undefined; - location: undefined; -} - -interface BlockerProceeding { - state: "proceeding"; - reset: undefined; - proceed: undefined; - location: Location; -} - -export type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding; - -export type BlockerFunction = (args: { - currentLocation: Location; - nextLocation: Location; - historyAction: HistoryAction; -}) => boolean; - -interface ShortCircuitable { - /** - * startNavigation does not need to complete the navigation because we - * redirected or got interrupted - */ - shortCircuited?: boolean; -} - -type PendingActionResult = [string, SuccessResult | ErrorResult]; - -interface HandleActionResult extends ShortCircuitable { - /** - * Tuple for the returned or thrown value from the current action. The routeId - * is the action route for success and the bubbled boundary route for errors. - */ - pendingActionResult?: PendingActionResult; -} - -interface HandleLoadersResult extends ShortCircuitable { - /** - * loaderData returned from the current set of loaders - */ - loaderData?: RouterState["loaderData"]; - /** - * errors thrown from the current set of loaders - */ - errors?: RouterState["errors"]; -} - -/** - * Cached info for active fetcher.load() instances so they can participate - * in revalidation - */ -interface FetchLoadMatch { - routeId: string; - path: string; -} - -/** - * Identified fetcher.load() calls that need to be revalidated - */ -interface RevalidatingFetcher extends FetchLoadMatch { - key: string; - match: AgnosticDataRouteMatch | null; - matches: AgnosticDataRouteMatch[] | null; - controller: AbortController | null; -} - -const validMutationMethodsArr: MutationFormMethod[] = [ - "post", - "put", - "patch", - "delete", -]; -const validMutationMethods = new Set( - validMutationMethodsArr -); - -const validRequestMethodsArr: FormMethod[] = [ - "get", - ...validMutationMethodsArr, -]; -const validRequestMethods = new Set(validRequestMethodsArr); - -const redirectStatusCodes = new Set([301, 302, 303, 307, 308]); -const redirectPreserveMethodStatusCodes = new Set([307, 308]); - -export const IDLE_NAVIGATION: NavigationStates["Idle"] = { - state: "idle", - location: undefined, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined, -}; - -export const IDLE_FETCHER: FetcherStates["Idle"] = { - state: "idle", - data: undefined, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined, -}; - -export const IDLE_BLOCKER: BlockerUnblocked = { - state: "unblocked", - proceed: undefined, - reset: undefined, - location: undefined, -}; - -const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i; - -const defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({ - hasErrorBoundary: Boolean(route.hasErrorBoundary), -}); - -const TRANSITIONS_STORAGE_KEY = "remix-router-transitions"; - -//#endregion - -//////////////////////////////////////////////////////////////////////////////// -//#region createRouter -//////////////////////////////////////////////////////////////////////////////// - -/** - * Create a router and listen to history POP navigations - */ -export function createRouter(init: RouterInit): Router { - const routerWindow = init.window - ? init.window - : typeof window !== "undefined" - ? window - : undefined; - const isBrowser = - typeof routerWindow !== "undefined" && - typeof routerWindow.document !== "undefined" && - typeof routerWindow.document.createElement !== "undefined"; - const isServer = !isBrowser; - - invariant( - init.routes.length > 0, - "You must provide a non-empty routes array to createRouter" - ); - - let mapRouteProperties: MapRoutePropertiesFunction; - if (init.mapRouteProperties) { - mapRouteProperties = init.mapRouteProperties; - } else if (init.detectErrorBoundary) { - // If they are still using the deprecated version, wrap it with the new API - let detectErrorBoundary = init.detectErrorBoundary; - mapRouteProperties = (route) => ({ - hasErrorBoundary: detectErrorBoundary(route), - }); - } else { - mapRouteProperties = defaultMapRouteProperties; - } - - // Routes keyed by ID - let manifest: RouteManifest = {}; - // Routes in tree format for matching - let dataRoutes = convertRoutesToDataRoutes( - init.routes, - mapRouteProperties, - undefined, - manifest - ); - let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined; - let basename = init.basename || "/"; - let dataStrategyImpl = init.unstable_dataStrategy || defaultDataStrategy; - // Config driven behavior flags - let future: FutureConfig = { - v7_fetcherPersist: false, - v7_normalizeFormMethod: false, - v7_partialHydration: false, - v7_prependBasename: false, - v7_relativeSplatPath: false, - unstable_skipActionErrorRevalidation: false, - ...init.future, - }; - // Cleanup function for history - let unlistenHistory: (() => void) | null = null; - // Externally-provided functions to call on all state changes - let subscribers = new Set(); - // Externally-provided object to hold scroll restoration locations during routing - let savedScrollPositions: Record | null = null; - // Externally-provided function to get scroll restoration keys - let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null; - // Externally-provided function to get current scroll position - let getScrollPosition: GetScrollPositionFunction | null = null; - // One-time flag to control the initial hydration scroll restoration. Because - // we don't get the saved positions from until _after_ - // the initial render, we need to manually trigger a separate updateState to - // send along the restoreScrollPosition - // Set to true if we have `hydrationData` since we assume we were SSR'd and that - // SSR did the initial scroll restoration. - let initialScrollRestored = init.hydrationData != null; - - let initialMatches = matchRoutes(dataRoutes, init.history.location, basename); - let initialErrors: RouteData | null = null; - - if (initialMatches == null) { - // If we do not match a user-provided-route, fall back to the root - // to allow the error boundary to take over - let error = getInternalRouterError(404, { - pathname: init.history.location.pathname, - }); - let { matches, route } = getShortCircuitMatches(dataRoutes); - initialMatches = matches; - initialErrors = { [route.id]: error }; - } - - let initialized: boolean; - let hasLazyRoutes = initialMatches.some((m) => m.route.lazy); - let hasLoaders = initialMatches.some((m) => m.route.loader); - if (hasLazyRoutes) { - // All initialMatches need to be loaded before we're ready. If we have lazy - // functions around still then we'll need to run them in initialize() - initialized = false; - } else if (!hasLoaders) { - // If we've got no loaders to run, then we're good to go - initialized = true; - } else if (future.v7_partialHydration) { - // If partial hydration is enabled, we're initialized so long as we were - // provided with hydrationData for every route with a loader, and no loaders - // were marked for explicit hydration - let loaderData = init.hydrationData ? init.hydrationData.loaderData : null; - let errors = init.hydrationData ? init.hydrationData.errors : null; - let isRouteInitialized = (m: AgnosticDataRouteMatch) => { - // No loader, nothing to initialize - if (!m.route.loader) { - return true; - } - // Explicitly opting-in to running on hydration - if ( - typeof m.route.loader === "function" && - m.route.loader.hydrate === true - ) { - return false; - } - // Otherwise, initialized if hydrated with data or an error - return ( - (loaderData && loaderData[m.route.id] !== undefined) || - (errors && errors[m.route.id] !== undefined) - ); - }; - - // If errors exist, don't consider routes below the boundary - if (errors) { - let idx = initialMatches.findIndex( - (m) => errors![m.route.id] !== undefined - ); - initialized = initialMatches.slice(0, idx + 1).every(isRouteInitialized); - } else { - initialized = initialMatches.every(isRouteInitialized); - } - } else { - // Without partial hydration - we're initialized if we were provided any - // hydrationData - which is expected to be complete - initialized = init.hydrationData != null; - } - - let router: Router; - let state: RouterState = { - historyAction: init.history.action, - location: init.history.location, - matches: initialMatches, - initialized, - navigation: IDLE_NAVIGATION, - // Don't restore on initial updateState() if we were SSR'd - restoreScrollPosition: init.hydrationData != null ? false : null, - preventScrollReset: false, - revalidation: "idle", - loaderData: (init.hydrationData && init.hydrationData.loaderData) || {}, - actionData: (init.hydrationData && init.hydrationData.actionData) || null, - errors: (init.hydrationData && init.hydrationData.errors) || initialErrors, - fetchers: new Map(), - blockers: new Map(), - }; - - // -- Stateful internal variables to manage navigations -- - // Current navigation in progress (to be committed in completeNavigation) - let pendingAction: HistoryAction = HistoryAction.Pop; - - // Should the current navigation prevent the scroll reset if scroll cannot - // be restored? - let pendingPreventScrollReset = false; - - // AbortController for the active navigation - let pendingNavigationController: AbortController | null; - - // Should the current navigation enable document.startViewTransition? - let pendingViewTransitionEnabled = false; - - // Store applied view transitions so we can apply them on POP - let appliedViewTransitions: Map> = new Map< - string, - Set - >(); - - // Cleanup function for persisting applied transitions to sessionStorage - let removePageHideEventListener: (() => void) | null = null; - - // We use this to avoid touching history in completeNavigation if a - // revalidation is entirely uninterrupted - let isUninterruptedRevalidation = false; - - // Use this internal flag to force revalidation of all loaders: - // - submissions (completed or interrupted) - // - useRevalidator() - // - X-Remix-Revalidate (from redirect) - let isRevalidationRequired = false; - - // Use this internal array to capture routes that require revalidation due - // to a cancelled deferred on action submission - let cancelledDeferredRoutes: string[] = []; - - // Use this internal array to capture fetcher loads that were cancelled by an - // action navigation and require revalidation - let cancelledFetcherLoads: string[] = []; - - // AbortControllers for any in-flight fetchers - let fetchControllers = new Map(); - - // Track loads based on the order in which they started - let incrementingLoadId = 0; - - // Track the outstanding pending navigation data load to be compared against - // the globally incrementing load when a fetcher load lands after a completed - // navigation - let pendingNavigationLoadId = -1; - - // Fetchers that triggered data reloads as a result of their actions - let fetchReloadIds = new Map(); - - // Fetchers that triggered redirect navigations - let fetchRedirectIds = new Set(); - - // Most recent href/match for fetcher.load calls for fetchers - let fetchLoadMatches = new Map(); - - // Ref-count mounted fetchers so we know when it's ok to clean them up - let activeFetchers = new Map(); - - // Fetchers that have requested a delete when using v7_fetcherPersist, - // they'll be officially removed after they return to idle - let deletedFetchers = new Set(); - - // Store DeferredData instances for active route matches. When a - // route loader returns defer() we stick one in here. Then, when a nested - // promise resolves we update loaderData. If a new navigation starts we - // cancel active deferreds for eliminated routes. - let activeDeferreds = new Map(); - - // Store blocker functions in a separate Map outside of router state since - // we don't need to update UI state if they change - let blockerFunctions = new Map(); - - // Flag to ignore the next history update, so we can revert the URL change on - // a POP navigation that was blocked by the user without touching router state - let ignoreNextHistoryUpdate = false; - - // Initialize the router, all side effects should be kicked off from here. - // Implemented as a Fluent API for ease of: - // let router = createRouter(init).initialize(); - function initialize() { - // If history informs us of a POP navigation, start the navigation but do not update - // state. We'll update our own state once the navigation completes - unlistenHistory = init.history.listen( - ({ action: historyAction, location, delta }) => { - // Ignore this event if it was just us resetting the URL from a - // blocked POP navigation - if (ignoreNextHistoryUpdate) { - ignoreNextHistoryUpdate = false; - return; - } - - warning( - blockerFunctions.size === 0 || delta != null, - "You are trying to use a blocker on a POP navigation to a location " + - "that was not created by @remix-run/router. This will fail silently in " + - "production. This can happen if you are navigating outside the router " + - "via `window.history.pushState`/`window.location.hash` instead of using " + - "router navigation APIs. This can also happen if you are using " + - "createHashRouter and the user manually changes the URL." - ); - - let blockerKey = shouldBlockNavigation({ - currentLocation: state.location, - nextLocation: location, - historyAction, - }); - - if (blockerKey && delta != null) { - // Restore the URL to match the current UI, but don't update router state - ignoreNextHistoryUpdate = true; - init.history.go(delta * -1); - - // Put the blocker into a blocked state - updateBlocker(blockerKey, { - state: "blocked", - location, - proceed() { - updateBlocker(blockerKey!, { - state: "proceeding", - proceed: undefined, - reset: undefined, - location, - }); - // Re-do the same POP navigation we just blocked - init.history.go(delta); - }, - reset() { - let blockers = new Map(state.blockers); - blockers.set(blockerKey!, IDLE_BLOCKER); - updateState({ blockers }); - }, - }); - return; - } - - return startNavigation(historyAction, location); - } - ); - - if (isBrowser) { - // FIXME: This feels gross. How can we cleanup the lines between - // scrollRestoration/appliedTransitions persistance? - restoreAppliedTransitions(routerWindow, appliedViewTransitions); - let _saveAppliedTransitions = () => - persistAppliedTransitions(routerWindow, appliedViewTransitions); - routerWindow.addEventListener("pagehide", _saveAppliedTransitions); - removePageHideEventListener = () => - routerWindow.removeEventListener("pagehide", _saveAppliedTransitions); - } - - // Kick off initial data load if needed. Use Pop to avoid modifying history - // Note we don't do any handling of lazy here. For SPA's it'll get handled - // in the normal navigation flow. For SSR it's expected that lazy modules are - // resolved prior to router creation since we can't go into a fallbackElement - // UI for SSR'd apps - if (!state.initialized) { - startNavigation(HistoryAction.Pop, state.location, { - initialHydration: true, - }); - } - - return router; - } - - // Clean up a router and it's side effects - function dispose() { - if (unlistenHistory) { - unlistenHistory(); - } - if (removePageHideEventListener) { - removePageHideEventListener(); - } - subscribers.clear(); - pendingNavigationController && pendingNavigationController.abort(); - state.fetchers.forEach((_, key) => deleteFetcher(key)); - state.blockers.forEach((_, key) => deleteBlocker(key)); - } - - // Subscribe to state updates for the router - function subscribe(fn: RouterSubscriber) { - subscribers.add(fn); - return () => subscribers.delete(fn); - } - - // Update our state and notify the calling context of the change - function updateState( - newState: Partial, - opts: { - flushSync?: boolean; - viewTransitionOpts?: ViewTransitionOpts; - } = {} - ): void { - state = { - ...state, - ...newState, - }; - - // Prep fetcher cleanup so we can tell the UI which fetcher data entries - // can be removed - let completedFetchers: string[] = []; - let deletedFetchersKeys: string[] = []; - - if (future.v7_fetcherPersist) { - state.fetchers.forEach((fetcher, key) => { - if (fetcher.state === "idle") { - if (deletedFetchers.has(key)) { - // Unmounted from the UI and can be totally removed - deletedFetchersKeys.push(key); - } else { - // Returned to idle but still mounted in the UI, so semi-remains for - // revalidations and such - completedFetchers.push(key); - } - } - }); - } - - // Iterate over a local copy so that if flushSync is used and we end up - // removing and adding a new subscriber due to the useCallback dependencies, - // we don't get ourselves into a loop calling the new subscriber immediately - [...subscribers].forEach((subscriber) => - subscriber(state, { - deletedFetchers: deletedFetchersKeys, - unstable_viewTransitionOpts: opts.viewTransitionOpts, - unstable_flushSync: opts.flushSync === true, - }) - ); - - // Remove idle fetchers from state since we only care about in-flight fetchers. - if (future.v7_fetcherPersist) { - completedFetchers.forEach((key) => state.fetchers.delete(key)); - deletedFetchersKeys.forEach((key) => deleteFetcher(key)); - } - } - - // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION - // and setting state.[historyAction/location/matches] to the new route. - // - Location is a required param - // - Navigation will always be set to IDLE_NAVIGATION - // - Can pass any other state in newState - function completeNavigation( - location: Location, - newState: Partial>, - { flushSync }: { flushSync?: boolean } = {} - ): void { - // Deduce if we're in a loading/actionReload state: - // - We have committed actionData in the store - // - The current navigation was a mutation submission - // - We're past the submitting state and into the loading state - // - The location being loaded is not the result of a redirect - let isActionReload = - state.actionData != null && - state.navigation.formMethod != null && - isMutationMethod(state.navigation.formMethod) && - state.navigation.state === "loading" && - location.state?._isRedirect !== true; - - let actionData: RouteData | null; - if (newState.actionData) { - if (Object.keys(newState.actionData).length > 0) { - actionData = newState.actionData; - } else { - // Empty actionData -> clear prior actionData due to an action error - actionData = null; - } - } else if (isActionReload) { - // Keep the current data if we're wrapping up the action reload - actionData = state.actionData; - } else { - // Clear actionData on any other completed navigations - actionData = null; - } - - // Always preserve any existing loaderData from re-used routes - let loaderData = newState.loaderData - ? mergeLoaderData( - state.loaderData, - newState.loaderData, - newState.matches || [], - newState.errors - ) - : state.loaderData; - - // On a successful navigation we can assume we got through all blockers - // so we can start fresh - let blockers = state.blockers; - if (blockers.size > 0) { - blockers = new Map(blockers); - blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER)); - } - - // Always respect the user flag. Otherwise don't reset on mutation - // submission navigations unless they redirect - let preventScrollReset = - pendingPreventScrollReset === true || - (state.navigation.formMethod != null && - isMutationMethod(state.navigation.formMethod) && - location.state?._isRedirect !== true); - - if (inFlightDataRoutes) { - dataRoutes = inFlightDataRoutes; - inFlightDataRoutes = undefined; - } - - if (isUninterruptedRevalidation) { - // If this was an uninterrupted revalidation then do not touch history - } else if (pendingAction === HistoryAction.Pop) { - // Do nothing for POP - URL has already been updated - } else if (pendingAction === HistoryAction.Push) { - init.history.push(location, location.state); - } else if (pendingAction === HistoryAction.Replace) { - init.history.replace(location, location.state); - } - - let viewTransitionOpts: ViewTransitionOpts | undefined; - - // On POP, enable transitions if they were enabled on the original navigation - if (pendingAction === HistoryAction.Pop) { - // Forward takes precedence so they behave like the original navigation - let priorPaths = appliedViewTransitions.get(state.location.pathname); - if (priorPaths && priorPaths.has(location.pathname)) { - viewTransitionOpts = { - currentLocation: state.location, - nextLocation: location, - }; - } else if (appliedViewTransitions.has(location.pathname)) { - // If we don't have a previous forward nav, assume we're popping back to - // the new location and enable if that location previously enabled - viewTransitionOpts = { - currentLocation: location, - nextLocation: state.location, - }; - } - } else if (pendingViewTransitionEnabled) { - // Store the applied transition on PUSH/REPLACE - let toPaths = appliedViewTransitions.get(state.location.pathname); - if (toPaths) { - toPaths.add(location.pathname); - } else { - toPaths = new Set([location.pathname]); - appliedViewTransitions.set(state.location.pathname, toPaths); - } - viewTransitionOpts = { - currentLocation: state.location, - nextLocation: location, - }; - } - - updateState( - { - ...newState, // matches, errors, fetchers go through as-is - actionData, - loaderData, - historyAction: pendingAction, - location, - initialized: true, - navigation: IDLE_NAVIGATION, - revalidation: "idle", - restoreScrollPosition: getSavedScrollPosition( - location, - newState.matches || state.matches - ), - preventScrollReset, - blockers, - }, - { - viewTransitionOpts, - flushSync: flushSync === true, - } - ); - - // Reset stateful navigation vars - pendingAction = HistoryAction.Pop; - pendingPreventScrollReset = false; - pendingViewTransitionEnabled = false; - isUninterruptedRevalidation = false; - isRevalidationRequired = false; - cancelledDeferredRoutes = []; - cancelledFetcherLoads = []; - } - - // Trigger a navigation event, which can either be a numerical POP or a PUSH - // replace with an optional submission - async function navigate( - to: number | To | null, - opts?: RouterNavigateOptions - ): Promise { - if (typeof to === "number") { - init.history.go(to); - return; - } - - let normalizedPath = normalizeTo( - state.location, - state.matches, - basename, - future.v7_prependBasename, - to, - future.v7_relativeSplatPath, - opts?.fromRouteId, - opts?.relative - ); - let { path, submission, error } = normalizeNavigateOptions( - future.v7_normalizeFormMethod, - false, - normalizedPath, - opts - ); - - let currentLocation = state.location; - let nextLocation = createLocation(state.location, path, opts && opts.state); - - // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded - // URL from window.location, so we need to encode it here so the behavior - // remains the same as POP and non-data-router usages. new URL() does all - // the same encoding we'd get from a history.pushState/window.location read - // without having to touch history - nextLocation = { - ...nextLocation, - ...init.history.encodeLocation(nextLocation), - }; - - let userReplace = opts && opts.replace != null ? opts.replace : undefined; - - let historyAction = HistoryAction.Push; - - if (userReplace === true) { - historyAction = HistoryAction.Replace; - } else if (userReplace === false) { - // no-op - } else if ( - submission != null && - isMutationMethod(submission.formMethod) && - submission.formAction === state.location.pathname + state.location.search - ) { - // By default on submissions to the current location we REPLACE so that - // users don't have to double-click the back button to get to the prior - // location. If the user redirects to a different location from the - // action/loader this will be ignored and the redirect will be a PUSH - historyAction = HistoryAction.Replace; - } - - let preventScrollReset = - opts && "preventScrollReset" in opts - ? opts.preventScrollReset === true - : undefined; - - let flushSync = (opts && opts.unstable_flushSync) === true; - - let blockerKey = shouldBlockNavigation({ - currentLocation, - nextLocation, - historyAction, - }); - - if (blockerKey) { - // Put the blocker into a blocked state - updateBlocker(blockerKey, { - state: "blocked", - location: nextLocation, - proceed() { - updateBlocker(blockerKey!, { - state: "proceeding", - proceed: undefined, - reset: undefined, - location: nextLocation, - }); - // Send the same navigation through - navigate(to, opts); - }, - reset() { - let blockers = new Map(state.blockers); - blockers.set(blockerKey!, IDLE_BLOCKER); - updateState({ blockers }); - }, - }); - return; - } - - return await startNavigation(historyAction, nextLocation, { - submission, - // Send through the formData serialization error if we have one so we can - // render at the right error boundary after we match routes - pendingError: error, - preventScrollReset, - replace: opts && opts.replace, - enableViewTransition: opts && opts.unstable_viewTransition, - flushSync, - }); - } - - // Revalidate all current loaders. If a navigation is in progress or if this - // is interrupted by a navigation, allow this to "succeed" by calling all - // loaders during the next loader round - function revalidate() { - interruptActiveLoads(); - updateState({ revalidation: "loading" }); - - // If we're currently submitting an action, we don't need to start a new - // navigation, we'll just let the follow up loader execution call all loaders - if (state.navigation.state === "submitting") { - return; - } - - // If we're currently in an idle state, start a new navigation for the current - // action/location and mark it as uninterrupted, which will skip the history - // update in completeNavigation - if (state.navigation.state === "idle") { - startNavigation(state.historyAction, state.location, { - startUninterruptedRevalidation: true, - }); - return; - } - - // Otherwise, if we're currently in a loading state, just start a new - // navigation to the navigation.location but do not trigger an uninterrupted - // revalidation so that history correctly updates once the navigation completes - startNavigation( - pendingAction || state.historyAction, - state.navigation.location, - { overrideNavigation: state.navigation } - ); - } - - // Start a navigation to the given action/location. Can optionally provide a - // overrideNavigation which will override the normalLoad in the case of a redirect - // navigation - async function startNavigation( - historyAction: HistoryAction, - location: Location, - opts?: { - initialHydration?: boolean; - submission?: Submission; - fetcherSubmission?: Submission; - overrideNavigation?: Navigation; - pendingError?: ErrorResponseImpl; - startUninterruptedRevalidation?: boolean; - preventScrollReset?: boolean; - replace?: boolean; - enableViewTransition?: boolean; - flushSync?: boolean; - } - ): Promise { - // Abort any in-progress navigations and start a new one. Unset any ongoing - // uninterrupted revalidations unless told otherwise, since we want this - // new navigation to update history normally - pendingNavigationController && pendingNavigationController.abort(); - pendingNavigationController = null; - pendingAction = historyAction; - isUninterruptedRevalidation = - (opts && opts.startUninterruptedRevalidation) === true; - - // Save the current scroll position every time we start a new navigation, - // and track whether we should reset scroll on completion - saveScrollPosition(state.location, state.matches); - pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; - - pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true; - - let routesToUse = inFlightDataRoutes || dataRoutes; - let loadingNavigation = opts && opts.overrideNavigation; - let matches = matchRoutes(routesToUse, location, basename); - let flushSync = (opts && opts.flushSync) === true; - - // Short circuit with a 404 on the root error boundary if we match nothing - if (!matches) { - let error = getInternalRouterError(404, { pathname: location.pathname }); - let { matches: notFoundMatches, route } = - getShortCircuitMatches(routesToUse); - // Cancel all pending deferred on 404s since we don't keep any routes - cancelActiveDeferreds(); - completeNavigation( - location, - { - matches: notFoundMatches, - loaderData: {}, - errors: { - [route.id]: error, - }, - }, - { flushSync } - ); - return; - } - - // Short circuit if it's only a hash change and not a revalidation or - // mutation submission. - // - // Ignore on initial page loads because since the initial load will always - // be "same hash". For example, on /page#hash and submit a - // which will default to a navigation to /page - if ( - state.initialized && - !isRevalidationRequired && - isHashChangeOnly(state.location, location) && - !(opts && opts.submission && isMutationMethod(opts.submission.formMethod)) - ) { - completeNavigation(location, { matches }, { flushSync }); - return; - } - - // Create a controller/Request for this navigation - pendingNavigationController = new AbortController(); - let request = createClientSideRequest( - init.history, - location, - pendingNavigationController.signal, - opts && opts.submission - ); - let pendingActionResult: PendingActionResult | undefined; - - if (opts && opts.pendingError) { - // If we have a pendingError, it means the user attempted a GET submission - // with binary FormData so assign here and skip to handleLoaders. That - // way we handle calling loaders above the boundary etc. It's not really - // different from an actionError in that sense. - pendingActionResult = [ - findNearestBoundary(matches).route.id, - { type: ResultType.error, error: opts.pendingError }, - ]; - } else if ( - opts && - opts.submission && - isMutationMethod(opts.submission.formMethod) - ) { - // Call action if we received an action submission - let actionResult = await handleAction( - request, - location, - opts.submission, - matches, - { replace: opts.replace, flushSync } - ); - - if (actionResult.shortCircuited) { - return; - } - - pendingActionResult = actionResult.pendingActionResult; - loadingNavigation = getLoadingNavigation(location, opts.submission); - flushSync = false; - - // Create a GET request for the loaders - request = createClientSideRequest( - init.history, - request.url, - request.signal - ); - } - - // Call loaders - let { shortCircuited, loaderData, errors } = await handleLoaders( - request, - location, - matches, - loadingNavigation, - opts && opts.submission, - opts && opts.fetcherSubmission, - opts && opts.replace, - opts && opts.initialHydration === true, - flushSync, - pendingActionResult - ); - - if (shortCircuited) { - return; - } - - // Clean up now that the action/loaders have completed. Don't clean up if - // we short circuited because pendingNavigationController will have already - // been assigned to a new controller for the next navigation - pendingNavigationController = null; - - completeNavigation(location, { - matches, - ...getActionDataForCommit(pendingActionResult), - loaderData, - errors, - }); - } - - // Call the action matched by the leaf route for this navigation and handle - // redirects/errors - async function handleAction( - request: Request, - location: Location, - submission: Submission, - matches: AgnosticDataRouteMatch[], - opts: { replace?: boolean; flushSync?: boolean } = {} - ): Promise { - interruptActiveLoads(); - - // Put us in a submitting state - let navigation = getSubmittingNavigation(location, submission); - updateState({ navigation }, { flushSync: opts.flushSync === true }); - - // Call our action and get the result - let result: DataResult; - let actionMatch = getTargetMatch(matches, location); - - if (!actionMatch.route.action && !actionMatch.route.lazy) { - result = { - type: ResultType.error, - error: getInternalRouterError(405, { - method: request.method, - pathname: location.pathname, - routeId: actionMatch.route.id, - }), - }; - } else { - let results = await callDataStrategy( - "action", - request, - [actionMatch], - matches - ); - result = results[0]; - - if (request.signal.aborted) { - return { shortCircuited: true }; - } - } - - if (isRedirectResult(result)) { - let replace: boolean; - if (opts && opts.replace != null) { - replace = opts.replace; - } else { - // If the user didn't explicity indicate replace behavior, replace if - // we redirected to the exact same location we're currently at to avoid - // double back-buttons - let location = normalizeRedirectLocation( - result.response.headers.get("Location")!, - new URL(request.url), - basename - ); - replace = location === state.location.pathname + state.location.search; - } - await startRedirectNavigation(request, result, { - submission, - replace, - }); - return { shortCircuited: true }; - } - - if (isDeferredResult(result)) { - throw getInternalRouterError(400, { type: "defer-action" }); - } - - if (isErrorResult(result)) { - // Store off the pending error - we use it to determine which loaders - // to call and will commit it when we complete the navigation - let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); - - // By default, all submissions are REPLACE navigations, but if the - // action threw an error that'll be rendered in an errorElement, we fall - // back to PUSH so that the user can use the back button to get back to - // the pre-submission form location to try again - if ((opts && opts.replace) !== true) { - pendingAction = HistoryAction.Push; - } - - return { - pendingActionResult: [boundaryMatch.route.id, result], - }; - } - - return { - pendingActionResult: [actionMatch.route.id, result], - }; - } - - // Call all applicable loaders for the given matches, handling redirects, - // errors, etc. - async function handleLoaders( - request: Request, - location: Location, - matches: AgnosticDataRouteMatch[], - overrideNavigation?: Navigation, - submission?: Submission, - fetcherSubmission?: Submission, - replace?: boolean, - initialHydration?: boolean, - flushSync?: boolean, - pendingActionResult?: PendingActionResult - ): Promise { - // Figure out the right navigation we want to use for data loading - let loadingNavigation = - overrideNavigation || getLoadingNavigation(location, submission); - - // If this was a redirect from an action we don't have a "submission" but - // we have it on the loading navigation so use that if available - let activeSubmission = - submission || - fetcherSubmission || - getSubmissionFromNavigation(loadingNavigation); - - let routesToUse = inFlightDataRoutes || dataRoutes; - let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad( - init.history, - state, - matches, - activeSubmission, - location, - future.v7_partialHydration && initialHydration === true, - future.unstable_skipActionErrorRevalidation, - isRevalidationRequired, - cancelledDeferredRoutes, - cancelledFetcherLoads, - deletedFetchers, - fetchLoadMatches, - fetchRedirectIds, - routesToUse, - basename, - pendingActionResult - ); - - // Cancel pending deferreds for no-longer-matched routes or routes we're - // about to reload. Note that if this is an action reload we would have - // already cancelled all pending deferreds so this would be a no-op - cancelActiveDeferreds( - (routeId) => - !(matches && matches.some((m) => m.route.id === routeId)) || - (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId)) - ); - - pendingNavigationLoadId = ++incrementingLoadId; - - // Short circuit if we have no loaders to run - if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) { - let updatedFetchers = markFetchRedirectsDone(); - completeNavigation( - location, - { - matches, - loaderData: {}, - // Commit pending error if we're short circuiting - errors: - pendingActionResult && isErrorResult(pendingActionResult[1]) - ? { [pendingActionResult[0]]: pendingActionResult[1].error } - : null, - ...getActionDataForCommit(pendingActionResult), - ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}), - }, - { flushSync } - ); - return { shortCircuited: true }; - } - - // If this is an uninterrupted revalidation, we remain in our current idle - // state. If not, we need to switch to our loading state and load data, - // preserving any new action data or existing action data (in the case of - // a revalidation interrupting an actionReload) - // If we have partialHydration enabled, then don't update the state for the - // initial data load since it's not a "navigation" - if ( - !isUninterruptedRevalidation && - (!future.v7_partialHydration || !initialHydration) - ) { - revalidatingFetchers.forEach((rf) => { - let fetcher = state.fetchers.get(rf.key); - let revalidatingFetcher = getLoadingFetcher( - undefined, - fetcher ? fetcher.data : undefined - ); - state.fetchers.set(rf.key, revalidatingFetcher); - }); - - let actionData: Record | null | undefined; - if (pendingActionResult && !isErrorResult(pendingActionResult[1])) { - // This is cast to `any` currently because `RouteData`uses any and it - // would be a breaking change to use any. - // TODO: v7 - change `RouteData` to use `unknown` instead of `any` - actionData = { - [pendingActionResult[0]]: pendingActionResult[1].data as any, - }; - } else if (state.actionData) { - if (Object.keys(state.actionData).length === 0) { - actionData = null; - } else { - actionData = state.actionData; - } - } - - updateState( - { - navigation: loadingNavigation, - ...(actionData !== undefined ? { actionData } : {}), - ...(revalidatingFetchers.length > 0 - ? { fetchers: new Map(state.fetchers) } - : {}), - }, - { - flushSync, - } - ); - } - - revalidatingFetchers.forEach((rf) => { - if (fetchControllers.has(rf.key)) { - abortFetcher(rf.key); - } - if (rf.controller) { - // Fetchers use an independent AbortController so that aborting a fetcher - // (via deleteFetcher) does not abort the triggering navigation that - // triggered the revalidation - fetchControllers.set(rf.key, rf.controller); - } - }); - - // Proxy navigation abort through to revalidation fetchers - let abortPendingFetchRevalidations = () => - revalidatingFetchers.forEach((f) => abortFetcher(f.key)); - if (pendingNavigationController) { - pendingNavigationController.signal.addEventListener( - "abort", - abortPendingFetchRevalidations - ); - } - - let { loaderResults, fetcherResults } = - await callLoadersAndMaybeResolveData( - state.matches, - matches, - matchesToLoad, - revalidatingFetchers, - request - ); - - if (request.signal.aborted) { - return { shortCircuited: true }; - } - - // Clean up _after_ loaders have completed. Don't clean up if we short - // circuited because fetchControllers would have been aborted and - // reassigned to new controllers for the next navigation - if (pendingNavigationController) { - pendingNavigationController.signal.removeEventListener( - "abort", - abortPendingFetchRevalidations - ); - } - revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key)); - - // If any loaders returned a redirect Response, start a new REPLACE navigation - let redirect = findRedirect([...loaderResults, ...fetcherResults]); - if (redirect) { - if (redirect.idx >= matchesToLoad.length) { - // If this redirect came from a fetcher make sure we mark it in - // fetchRedirectIds so it doesn't get revalidated on the next set of - // loader executions - let fetcherKey = - revalidatingFetchers[redirect.idx - matchesToLoad.length].key; - fetchRedirectIds.add(fetcherKey); - } - await startRedirectNavigation(request, redirect.result, { - replace, - }); - return { shortCircuited: true }; - } - - // Process and commit output from loaders - let { loaderData, errors } = processLoaderData( - state, - matches, - matchesToLoad, - loaderResults, - pendingActionResult, - revalidatingFetchers, - fetcherResults, - activeDeferreds - ); - - // Wire up subscribers to update loaderData as promises settle - activeDeferreds.forEach((deferredData, routeId) => { - deferredData.subscribe((aborted) => { - // Note: No need to updateState here since the TrackedPromise on - // loaderData is stable across resolve/reject - // Remove this instance if we were aborted or if promises have settled - if (aborted || deferredData.done) { - activeDeferreds.delete(routeId); - } - }); - }); - - // During partial hydration, preserve SSR errors for routes that don't re-run - if (future.v7_partialHydration && initialHydration && state.errors) { - Object.entries(state.errors) - .filter(([id]) => !matchesToLoad.some((m) => m.route.id === id)) - .forEach(([routeId, error]) => { - errors = Object.assign(errors || {}, { [routeId]: error }); - }); - } - - let updatedFetchers = markFetchRedirectsDone(); - let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId); - let shouldUpdateFetchers = - updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0; - - return { - loaderData, - errors, - ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}), - }; - } - - // Trigger a fetcher load/submit for the given fetcher key - function fetch( - key: string, - routeId: string, - href: string | null, - opts?: RouterFetchOptions - ) { - if (isServer) { - throw new Error( - "router.fetch() was called during the server render, but it shouldn't be. " + - "You are likely calling a useFetcher() method in the body of your component. " + - "Try moving it to a useEffect or a callback." - ); - } - - if (fetchControllers.has(key)) abortFetcher(key); - let flushSync = (opts && opts.unstable_flushSync) === true; - - let routesToUse = inFlightDataRoutes || dataRoutes; - let normalizedPath = normalizeTo( - state.location, - state.matches, - basename, - future.v7_prependBasename, - href, - future.v7_relativeSplatPath, - routeId, - opts?.relative - ); - let matches = matchRoutes(routesToUse, normalizedPath, basename); - - if (!matches) { - setFetcherError( - key, - routeId, - getInternalRouterError(404, { pathname: normalizedPath }), - { flushSync } - ); - return; - } - - let { path, submission, error } = normalizeNavigateOptions( - future.v7_normalizeFormMethod, - true, - normalizedPath, - opts - ); - - if (error) { - setFetcherError(key, routeId, error, { flushSync }); - return; - } - - let match = getTargetMatch(matches, path); - - pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; - - if (submission && isMutationMethod(submission.formMethod)) { - handleFetcherAction( - key, - routeId, - path, - match, - matches, - flushSync, - submission - ); - return; - } - - // Store off the match so we can call it's shouldRevalidate on subsequent - // revalidations - fetchLoadMatches.set(key, { routeId, path }); - handleFetcherLoader( - key, - routeId, - path, - match, - matches, - flushSync, - submission - ); - } - - // Call the action for the matched fetcher.submit(), and then handle redirects, - // errors, and revalidation - async function handleFetcherAction( - key: string, - routeId: string, - path: string, - match: AgnosticDataRouteMatch, - requestMatches: AgnosticDataRouteMatch[], - flushSync: boolean, - submission: Submission - ) { - interruptActiveLoads(); - fetchLoadMatches.delete(key); - - if (!match.route.action && !match.route.lazy) { - let error = getInternalRouterError(405, { - method: submission.formMethod, - pathname: path, - routeId: routeId, - }); - setFetcherError(key, routeId, error, { flushSync }); - return; - } - - // Put this fetcher into it's submitting state - let existingFetcher = state.fetchers.get(key); - updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), { - flushSync, - }); - - // Call the action for the fetcher - let abortController = new AbortController(); - let fetchRequest = createClientSideRequest( - init.history, - path, - abortController.signal, - submission - ); - fetchControllers.set(key, abortController); - - let originatingLoadId = incrementingLoadId; - let actionResults = await callDataStrategy( - "action", - fetchRequest, - [match], - requestMatches - ); - let actionResult = actionResults[0]; - - if (fetchRequest.signal.aborted) { - // We can delete this so long as we weren't aborted by our own fetcher - // re-submit which would have put _new_ controller is in fetchControllers - if (fetchControllers.get(key) === abortController) { - fetchControllers.delete(key); - } - return; - } - - // When using v7_fetcherPersist, we don't want errors bubbling up to the UI - // or redirects processed for unmounted fetchers so we just revert them to - // idle - if (future.v7_fetcherPersist && deletedFetchers.has(key)) { - if (isRedirectResult(actionResult) || isErrorResult(actionResult)) { - updateFetcherState(key, getDoneFetcher(undefined)); - return; - } - // Let SuccessResult's fall through for revalidation - } else { - if (isRedirectResult(actionResult)) { - fetchControllers.delete(key); - if (pendingNavigationLoadId > originatingLoadId) { - // A new navigation was kicked off after our action started, so that - // should take precedence over this redirect navigation. We already - // set isRevalidationRequired so all loaders for the new route should - // fire unless opted out via shouldRevalidate - updateFetcherState(key, getDoneFetcher(undefined)); - return; - } else { - fetchRedirectIds.add(key); - updateFetcherState(key, getLoadingFetcher(submission)); - return startRedirectNavigation(fetchRequest, actionResult, { - fetcherSubmission: submission, - }); - } - } - - // Process any non-redirect errors thrown - if (isErrorResult(actionResult)) { - setFetcherError(key, routeId, actionResult.error); - return; - } - } - - if (isDeferredResult(actionResult)) { - throw getInternalRouterError(400, { type: "defer-action" }); - } - - // Start the data load for current matches, or the next location if we're - // in the middle of a navigation - let nextLocation = state.navigation.location || state.location; - let revalidationRequest = createClientSideRequest( - init.history, - nextLocation, - abortController.signal - ); - let routesToUse = inFlightDataRoutes || dataRoutes; - let matches = - state.navigation.state !== "idle" - ? matchRoutes(routesToUse, state.navigation.location, basename) - : state.matches; - - invariant(matches, "Didn't find any matches after fetcher action"); - - let loadId = ++incrementingLoadId; - fetchReloadIds.set(key, loadId); - - let loadFetcher = getLoadingFetcher(submission, actionResult.data); - state.fetchers.set(key, loadFetcher); - - let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad( - init.history, - state, - matches, - submission, - nextLocation, - false, - future.unstable_skipActionErrorRevalidation, - isRevalidationRequired, - cancelledDeferredRoutes, - cancelledFetcherLoads, - deletedFetchers, - fetchLoadMatches, - fetchRedirectIds, - routesToUse, - basename, - [match.route.id, actionResult] - ); - - // Put all revalidating fetchers into the loading state, except for the - // current fetcher which we want to keep in it's current loading state which - // contains it's action submission info + action data - revalidatingFetchers - .filter((rf) => rf.key !== key) - .forEach((rf) => { - let staleKey = rf.key; - let existingFetcher = state.fetchers.get(staleKey); - let revalidatingFetcher = getLoadingFetcher( - undefined, - existingFetcher ? existingFetcher.data : undefined - ); - state.fetchers.set(staleKey, revalidatingFetcher); - if (fetchControllers.has(staleKey)) { - abortFetcher(staleKey); - } - if (rf.controller) { - fetchControllers.set(staleKey, rf.controller); - } - }); - - updateState({ fetchers: new Map(state.fetchers) }); - - let abortPendingFetchRevalidations = () => - revalidatingFetchers.forEach((rf) => abortFetcher(rf.key)); - - abortController.signal.addEventListener( - "abort", - abortPendingFetchRevalidations - ); - - let { loaderResults, fetcherResults } = - await callLoadersAndMaybeResolveData( - state.matches, - matches, - matchesToLoad, - revalidatingFetchers, - revalidationRequest - ); - - if (abortController.signal.aborted) { - return; - } - - abortController.signal.removeEventListener( - "abort", - abortPendingFetchRevalidations - ); - - fetchReloadIds.delete(key); - fetchControllers.delete(key); - revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key)); - - let redirect = findRedirect([...loaderResults, ...fetcherResults]); - if (redirect) { - if (redirect.idx >= matchesToLoad.length) { - // If this redirect came from a fetcher make sure we mark it in - // fetchRedirectIds so it doesn't get revalidated on the next set of - // loader executions - let fetcherKey = - revalidatingFetchers[redirect.idx - matchesToLoad.length].key; - fetchRedirectIds.add(fetcherKey); - } - return startRedirectNavigation(revalidationRequest, redirect.result); - } - - // Process and commit output from loaders - let { loaderData, errors } = processLoaderData( - state, - state.matches, - matchesToLoad, - loaderResults, - undefined, - revalidatingFetchers, - fetcherResults, - activeDeferreds - ); - - // Since we let revalidations complete even if the submitting fetcher was - // deleted, only put it back to idle if it hasn't been deleted - if (state.fetchers.has(key)) { - let doneFetcher = getDoneFetcher(actionResult.data); - state.fetchers.set(key, doneFetcher); - } - - abortStaleFetchLoads(loadId); - - // If we are currently in a navigation loading state and this fetcher is - // more recent than the navigation, we want the newer data so abort the - // navigation and complete it with the fetcher data - if ( - state.navigation.state === "loading" && - loadId > pendingNavigationLoadId - ) { - invariant(pendingAction, "Expected pending action"); - pendingNavigationController && pendingNavigationController.abort(); - - completeNavigation(state.navigation.location, { - matches, - loaderData, - errors, - fetchers: new Map(state.fetchers), - }); - } else { - // otherwise just update with the fetcher data, preserving any existing - // loaderData for loaders that did not need to reload. We have to - // manually merge here since we aren't going through completeNavigation - updateState({ - errors, - loaderData: mergeLoaderData( - state.loaderData, - loaderData, - matches, - errors - ), - fetchers: new Map(state.fetchers), - }); - isRevalidationRequired = false; - } - } - - // Call the matched loader for fetcher.load(), handling redirects, errors, etc. - async function handleFetcherLoader( - key: string, - routeId: string, - path: string, - match: AgnosticDataRouteMatch, - matches: AgnosticDataRouteMatch[], - flushSync: boolean, - submission?: Submission - ) { - let existingFetcher = state.fetchers.get(key); - updateFetcherState( - key, - getLoadingFetcher( - submission, - existingFetcher ? existingFetcher.data : undefined - ), - { flushSync } - ); - - // Call the loader for this fetcher route match - let abortController = new AbortController(); - let fetchRequest = createClientSideRequest( - init.history, - path, - abortController.signal - ); - fetchControllers.set(key, abortController); - - let originatingLoadId = incrementingLoadId; - let results = await callDataStrategy( - "loader", - fetchRequest, - [match], - matches - ); - let result = results[0]; - - // Deferred isn't supported for fetcher loads, await everything and treat it - // as a normal load. resolveDeferredData will return undefined if this - // fetcher gets aborted, so we just leave result untouched and short circuit - // below if that happens - if (isDeferredResult(result)) { - result = - (await resolveDeferredData(result, fetchRequest.signal, true)) || - result; - } - - // We can delete this so long as we weren't aborted by our our own fetcher - // re-load which would have put _new_ controller is in fetchControllers - if (fetchControllers.get(key) === abortController) { - fetchControllers.delete(key); - } - - if (fetchRequest.signal.aborted) { - return; - } - - // We don't want errors bubbling up or redirects followed for unmounted - // fetchers, so short circuit here if it was removed from the UI - if (deletedFetchers.has(key)) { - updateFetcherState(key, getDoneFetcher(undefined)); - return; - } - - // If the loader threw a redirect Response, start a new REPLACE navigation - if (isRedirectResult(result)) { - if (pendingNavigationLoadId > originatingLoadId) { - // A new navigation was kicked off after our loader started, so that - // should take precedence over this redirect navigation - updateFetcherState(key, getDoneFetcher(undefined)); - return; - } else { - fetchRedirectIds.add(key); - await startRedirectNavigation(fetchRequest, result); - return; - } - } - - // Process any non-redirect errors thrown - if (isErrorResult(result)) { - setFetcherError(key, routeId, result.error); - return; - } - - invariant(!isDeferredResult(result), "Unhandled fetcher deferred data"); - - // Put the fetcher back into an idle state - updateFetcherState(key, getDoneFetcher(result.data)); - } - - /** - * Utility function to handle redirects returned from an action or loader. - * Normally, a redirect "replaces" the navigation that triggered it. So, for - * example: - * - * - user is on /a - * - user clicks a link to /b - * - loader for /b redirects to /c - * - * In a non-JS app the browser would track the in-flight navigation to /b and - * then replace it with /c when it encountered the redirect response. In - * the end it would only ever update the URL bar with /c. - * - * In client-side routing using pushState/replaceState, we aim to emulate - * this behavior and we also do not update history until the end of the - * navigation (including processed redirects). This means that we never - * actually touch history until we've processed redirects, so we just use - * the history action from the original navigation (PUSH or REPLACE). - */ - async function startRedirectNavigation( - request: Request, - redirect: RedirectResult, - { - submission, - fetcherSubmission, - replace, - }: { - submission?: Submission; - fetcherSubmission?: Submission; - replace?: boolean; - } = {} - ) { - if (redirect.response.headers.has("X-Remix-Revalidate")) { - isRevalidationRequired = true; - } - - let location = redirect.response.headers.get("Location"); - invariant(location, "Expected a Location header on the redirect Response"); - location = normalizeRedirectLocation( - location, - new URL(request.url), - basename - ); - let redirectLocation = createLocation(state.location, location, { - _isRedirect: true, - }); - - if (isBrowser) { - let isDocumentReload = false; - - if (redirect.response.headers.has("X-Remix-Reload-Document")) { - // Hard reload if the response contained X-Remix-Reload-Document - isDocumentReload = true; - } else if (ABSOLUTE_URL_REGEX.test(location)) { - const url = init.history.createURL(location); - isDocumentReload = - // Hard reload if it's an absolute URL to a new origin - url.origin !== routerWindow.location.origin || - // Hard reload if it's an absolute URL that does not match our basename - stripBasename(url.pathname, basename) == null; - } - - if (isDocumentReload) { - if (replace) { - routerWindow.location.replace(location); - } else { - routerWindow.location.assign(location); - } - return; - } - } - - // There's no need to abort on redirects, since we don't detect the - // redirect until the action/loaders have settled - pendingNavigationController = null; - - let redirectHistoryAction = - replace === true ? HistoryAction.Replace : HistoryAction.Push; - - // Use the incoming submission if provided, fallback on the active one in - // state.navigation - let { formMethod, formAction, formEncType } = state.navigation; - if ( - !submission && - !fetcherSubmission && - formMethod && - formAction && - formEncType - ) { - submission = getSubmissionFromNavigation(state.navigation); - } - - // If this was a 307/308 submission we want to preserve the HTTP method and - // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the - // redirected location - let activeSubmission = submission || fetcherSubmission; - if ( - redirectPreserveMethodStatusCodes.has(redirect.response.status) && - activeSubmission && - isMutationMethod(activeSubmission.formMethod) - ) { - await startNavigation(redirectHistoryAction, redirectLocation, { - submission: { - ...activeSubmission, - formAction: location, - }, - // Preserve this flag across redirects - preventScrollReset: pendingPreventScrollReset, - }); - } else { - // If we have a navigation submission, we will preserve it through the - // redirect navigation - let overrideNavigation = getLoadingNavigation( - redirectLocation, - submission - ); - await startNavigation(redirectHistoryAction, redirectLocation, { - overrideNavigation, - // Send fetcher submissions through for shouldRevalidate - fetcherSubmission, - // Preserve this flag across redirects - preventScrollReset: pendingPreventScrollReset, - }); - } - } - - // Utility wrapper for calling dataStrategy client-side without having to - // pass around the manifest, mapRouteProperties, etc. - async function callDataStrategy( - type: "loader" | "action", - request: Request, - matchesToLoad: AgnosticDataRouteMatch[], - matches: AgnosticDataRouteMatch[] - ): Promise { - try { - let results = await callDataStrategyImpl( - dataStrategyImpl, - type, - request, - matchesToLoad, - matches, - manifest, - mapRouteProperties - ); - - return await Promise.all( - results.map((result, i) => { - if (isRedirectHandlerResult(result)) { - let response = result.result as Response; - return { - type: ResultType.redirect, - response: normalizeRelativeRoutingRedirectResponse( - response, - request, - matchesToLoad[i].route.id, - matches, - basename, - future.v7_relativeSplatPath - ), - }; - } - - return convertHandlerResultToDataResult(result); - }) - ); - } catch (e) { - // If the outer dataStrategy method throws, just return the error for all - // matches - and it'll naturally bubble to the root - return matchesToLoad.map(() => ({ - type: ResultType.error, - error: e, - })); - } - } - - async function callLoadersAndMaybeResolveData( - currentMatches: AgnosticDataRouteMatch[], - matches: AgnosticDataRouteMatch[], - matchesToLoad: AgnosticDataRouteMatch[], - fetchersToLoad: RevalidatingFetcher[], - request: Request - ) { - let [loaderResults, ...fetcherResults] = await Promise.all([ - matchesToLoad.length - ? callDataStrategy("loader", request, matchesToLoad, matches) - : [], - ...fetchersToLoad.map((f) => { - if (f.matches && f.match && f.controller) { - let fetcherRequest = createClientSideRequest( - init.history, - f.path, - f.controller.signal - ); - return callDataStrategy( - "loader", - fetcherRequest, - [f.match], - f.matches - ).then((r) => r[0]); - } else { - return Promise.resolve({ - type: ResultType.error, - error: getInternalRouterError(404, { - pathname: f.path, - }), - }); - } - }), - ]); - - await Promise.all([ - resolveDeferredResults( - currentMatches, - matchesToLoad, - loaderResults, - loaderResults.map(() => request.signal), - false, - state.loaderData - ), - resolveDeferredResults( - currentMatches, - fetchersToLoad.map((f) => f.match), - fetcherResults, - fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)), - true - ), - ]); - - return { - loaderResults, - fetcherResults, - }; - } - - function interruptActiveLoads() { - // Every interruption triggers a revalidation - isRevalidationRequired = true; - - // Cancel pending route-level deferreds and mark cancelled routes for - // revalidation - cancelledDeferredRoutes.push(...cancelActiveDeferreds()); - - // Abort in-flight fetcher loads - fetchLoadMatches.forEach((_, key) => { - if (fetchControllers.has(key)) { - cancelledFetcherLoads.push(key); - abortFetcher(key); - } - }); - } - - function updateFetcherState( - key: string, - fetcher: Fetcher, - opts: { flushSync?: boolean } = {} - ) { - state.fetchers.set(key, fetcher); - updateState( - { fetchers: new Map(state.fetchers) }, - { flushSync: (opts && opts.flushSync) === true } - ); - } - - function setFetcherError( - key: string, - routeId: string, - error: any, - opts: { flushSync?: boolean } = {} - ) { - let boundaryMatch = findNearestBoundary(state.matches, routeId); - deleteFetcher(key); - updateState( - { - errors: { - [boundaryMatch.route.id]: error, - }, - fetchers: new Map(state.fetchers), - }, - { flushSync: (opts && opts.flushSync) === true } - ); - } - - function getFetcher(key: string): Fetcher { - if (future.v7_fetcherPersist) { - activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1); - // If this fetcher was previously marked for deletion, unmark it since we - // have a new instance - if (deletedFetchers.has(key)) { - deletedFetchers.delete(key); - } - } - return state.fetchers.get(key) || IDLE_FETCHER; - } - - function deleteFetcher(key: string): void { - let fetcher = state.fetchers.get(key); - // Don't abort the controller if this is a deletion of a fetcher.submit() - // in it's loading phase since - we don't want to abort the corresponding - // revalidation and want them to complete and land - if ( - fetchControllers.has(key) && - !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key)) - ) { - abortFetcher(key); - } - fetchLoadMatches.delete(key); - fetchReloadIds.delete(key); - fetchRedirectIds.delete(key); - deletedFetchers.delete(key); - state.fetchers.delete(key); - } - - function deleteFetcherAndUpdateState(key: string): void { - if (future.v7_fetcherPersist) { - let count = (activeFetchers.get(key) || 0) - 1; - if (count <= 0) { - activeFetchers.delete(key); - deletedFetchers.add(key); - } else { - activeFetchers.set(key, count); - } - } else { - deleteFetcher(key); - } - updateState({ fetchers: new Map(state.fetchers) }); - } - - function abortFetcher(key: string) { - let controller = fetchControllers.get(key); - invariant(controller, `Expected fetch controller: ${key}`); - controller.abort(); - fetchControllers.delete(key); - } - - function markFetchersDone(keys: string[]) { - for (let key of keys) { - let fetcher = getFetcher(key); - let doneFetcher = getDoneFetcher(fetcher.data); - state.fetchers.set(key, doneFetcher); - } - } - - function markFetchRedirectsDone(): boolean { - let doneKeys = []; - let updatedFetchers = false; - for (let key of fetchRedirectIds) { - let fetcher = state.fetchers.get(key); - invariant(fetcher, `Expected fetcher: ${key}`); - if (fetcher.state === "loading") { - fetchRedirectIds.delete(key); - doneKeys.push(key); - updatedFetchers = true; - } - } - markFetchersDone(doneKeys); - return updatedFetchers; - } - - function abortStaleFetchLoads(landedId: number): boolean { - let yeetedKeys = []; - for (let [key, id] of fetchReloadIds) { - if (id < landedId) { - let fetcher = state.fetchers.get(key); - invariant(fetcher, `Expected fetcher: ${key}`); - if (fetcher.state === "loading") { - abortFetcher(key); - fetchReloadIds.delete(key); - yeetedKeys.push(key); - } - } - } - markFetchersDone(yeetedKeys); - return yeetedKeys.length > 0; - } - - function getBlocker(key: string, fn: BlockerFunction) { - let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER; - - if (blockerFunctions.get(key) !== fn) { - blockerFunctions.set(key, fn); - } - - return blocker; - } - - function deleteBlocker(key: string) { - state.blockers.delete(key); - blockerFunctions.delete(key); - } - - // Utility function to update blockers, ensuring valid state transitions - function updateBlocker(key: string, newBlocker: Blocker) { - let blocker = state.blockers.get(key) || IDLE_BLOCKER; - - // Poor mans state machine :) - // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM - invariant( - (blocker.state === "unblocked" && newBlocker.state === "blocked") || - (blocker.state === "blocked" && newBlocker.state === "blocked") || - (blocker.state === "blocked" && newBlocker.state === "proceeding") || - (blocker.state === "blocked" && newBlocker.state === "unblocked") || - (blocker.state === "proceeding" && newBlocker.state === "unblocked"), - `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}` - ); - - let blockers = new Map(state.blockers); - blockers.set(key, newBlocker); - updateState({ blockers }); - } - - function shouldBlockNavigation({ - currentLocation, - nextLocation, - historyAction, - }: { - currentLocation: Location; - nextLocation: Location; - historyAction: HistoryAction; - }): string | undefined { - if (blockerFunctions.size === 0) { - return; - } - - // We ony support a single active blocker at the moment since we don't have - // any compelling use cases for multi-blocker yet - if (blockerFunctions.size > 1) { - warning(false, "A router only supports one blocker at a time"); - } - - let entries = Array.from(blockerFunctions.entries()); - let [blockerKey, blockerFunction] = entries[entries.length - 1]; - let blocker = state.blockers.get(blockerKey); - - if (blocker && blocker.state === "proceeding") { - // If the blocker is currently proceeding, we don't need to re-check - // it and can let this navigation continue - return; - } - - // At this point, we know we're unblocked/blocked so we need to check the - // user-provided blocker function - if (blockerFunction({ currentLocation, nextLocation, historyAction })) { - return blockerKey; - } - } - - function cancelActiveDeferreds( - predicate?: (routeId: string) => boolean - ): string[] { - let cancelledRouteIds: string[] = []; - activeDeferreds.forEach((dfd, routeId) => { - if (!predicate || predicate(routeId)) { - // Cancel the deferred - but do not remove from activeDeferreds here - - // we rely on the subscribers to do that so our tests can assert proper - // cleanup via _internalActiveDeferreds - dfd.cancel(); - cancelledRouteIds.push(routeId); - activeDeferreds.delete(routeId); - } - }); - return cancelledRouteIds; - } - - // Opt in to capturing and reporting scroll positions during navigations, - // used by the component - function enableScrollRestoration( - positions: Record, - getPosition: GetScrollPositionFunction, - getKey?: GetScrollRestorationKeyFunction - ) { - savedScrollPositions = positions; - getScrollPosition = getPosition; - getScrollRestorationKey = getKey || null; - - // Perform initial hydration scroll restoration, since we miss the boat on - // the initial updateState() because we've not yet rendered - // and therefore have no savedScrollPositions available - if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) { - initialScrollRestored = true; - let y = getSavedScrollPosition(state.location, state.matches); - if (y != null) { - updateState({ restoreScrollPosition: y }); - } - } - - return () => { - savedScrollPositions = null; - getScrollPosition = null; - getScrollRestorationKey = null; - }; - } - - function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) { - if (getScrollRestorationKey) { - let key = getScrollRestorationKey( - location, - matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData)) - ); - return key || location.key; - } - return location.key; - } - - function saveScrollPosition( - location: Location, - matches: AgnosticDataRouteMatch[] - ): void { - if (savedScrollPositions && getScrollPosition) { - let key = getScrollKey(location, matches); - savedScrollPositions[key] = getScrollPosition(); - } - } - - function getSavedScrollPosition( - location: Location, - matches: AgnosticDataRouteMatch[] - ): number | null { - if (savedScrollPositions) { - let key = getScrollKey(location, matches); - let y = savedScrollPositions[key]; - if (typeof y === "number") { - return y; - } - } - return null; - } - - function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) { - manifest = {}; - inFlightDataRoutes = convertRoutesToDataRoutes( - newRoutes, - mapRouteProperties, - undefined, - manifest - ); - } - - router = { - get basename() { - return basename; - }, - get future() { - return future; - }, - get state() { - return state; - }, - get routes() { - return dataRoutes; - }, - get window() { - return routerWindow; - }, - initialize, - subscribe, - enableScrollRestoration, - navigate, - fetch, - revalidate, - // Passthrough to history-aware createHref used by useHref so we get proper - // hash-aware URLs in DOM paths - createHref: (to: To) => init.history.createHref(to), - encodeLocation: (to: To) => init.history.encodeLocation(to), - getFetcher, - deleteFetcher: deleteFetcherAndUpdateState, - dispose, - getBlocker, - deleteBlocker, - _internalFetchControllers: fetchControllers, - _internalActiveDeferreds: activeDeferreds, - // TODO: Remove setRoutes, it's temporary to avoid dealing with - // updating the tree while validating the update algorithm. - _internalSetRoutes, - }; - - return router; -} -//#endregion - -//////////////////////////////////////////////////////////////////////////////// -//#region createStaticHandler -//////////////////////////////////////////////////////////////////////////////// - -export const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred"); - -/** - * Future flags to toggle new feature behavior - */ -export interface StaticHandlerFutureConfig { - v7_relativeSplatPath: boolean; - v7_throwAbortReason: boolean; -} - -export interface CreateStaticHandlerOptions { - basename?: string; - /** - * @deprecated Use `mapRouteProperties` instead - */ - detectErrorBoundary?: DetectErrorBoundaryFunction; - mapRouteProperties?: MapRoutePropertiesFunction; - future?: Partial; -} - -export function createStaticHandler( - routes: AgnosticRouteObject[], - opts?: CreateStaticHandlerOptions -): StaticHandler { - invariant( - routes.length > 0, - "You must provide a non-empty routes array to createStaticHandler" - ); - - let manifest: RouteManifest = {}; - let basename = (opts ? opts.basename : null) || "/"; - let mapRouteProperties: MapRoutePropertiesFunction; - if (opts?.mapRouteProperties) { - mapRouteProperties = opts.mapRouteProperties; - } else if (opts?.detectErrorBoundary) { - // If they are still using the deprecated version, wrap it with the new API - let detectErrorBoundary = opts.detectErrorBoundary; - mapRouteProperties = (route) => ({ - hasErrorBoundary: detectErrorBoundary(route), - }); - } else { - mapRouteProperties = defaultMapRouteProperties; - } - // Config driven behavior flags - let future: StaticHandlerFutureConfig = { - v7_relativeSplatPath: false, - v7_throwAbortReason: false, - ...(opts ? opts.future : null), - }; - - let dataRoutes = convertRoutesToDataRoutes( - routes, - mapRouteProperties, - undefined, - manifest - ); - - /** - * The query() method is intended for document requests, in which we want to - * call an optional action and potentially multiple loaders for all nested - * routes. It returns a StaticHandlerContext object, which is very similar - * to the router state (location, loaderData, actionData, errors, etc.) and - * also adds SSR-specific information such as the statusCode and headers - * from action/loaders Responses. - * - * It _should_ never throw and should report all errors through the - * returned context.errors object, properly associating errors to their error - * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be - * used to emulate React error boundaries during SSr by performing a second - * pass only down to the boundaryId. - * - * The one exception where we do not return a StaticHandlerContext is when a - * redirect response is returned or thrown from any action/loader. We - * propagate that out and return the raw Response so the HTTP server can - * return it directly. - * - * - `opts.requestContext` is an optional server context that will be passed - * to actions/loaders in the `context` parameter - * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent - * the bubbling of errors which allows single-fetch-type implementations - * where the client will handle the bubbling and we may need to return data - * for the handling route - */ - async function query( - request: Request, - { - requestContext, - skipLoaderErrorBubbling, - unstable_dataStrategy, - }: { - requestContext?: unknown; - skipLoaderErrorBubbling?: boolean; - unstable_dataStrategy?: DataStrategyFunction; - } = {} - ): Promise { - let url = new URL(request.url); - let method = request.method; - let location = createLocation("", createPath(url), null, "default"); - let matches = matchRoutes(dataRoutes, location, basename); - - // SSR supports HEAD requests while SPA doesn't - if (!isValidMethod(method) && method !== "HEAD") { - let error = getInternalRouterError(405, { method }); - let { matches: methodNotAllowedMatches, route } = - getShortCircuitMatches(dataRoutes); - return { - basename, - location, - matches: methodNotAllowedMatches, - loaderData: {}, - actionData: null, - errors: { - [route.id]: error, - }, - statusCode: error.status, - loaderHeaders: {}, - actionHeaders: {}, - activeDeferreds: null, - }; - } else if (!matches) { - let error = getInternalRouterError(404, { pathname: location.pathname }); - let { matches: notFoundMatches, route } = - getShortCircuitMatches(dataRoutes); - return { - basename, - location, - matches: notFoundMatches, - loaderData: {}, - actionData: null, - errors: { - [route.id]: error, - }, - statusCode: error.status, - loaderHeaders: {}, - actionHeaders: {}, - activeDeferreds: null, - }; - } - - let result = await queryImpl( - request, - location, - matches, - requestContext, - unstable_dataStrategy || null, - skipLoaderErrorBubbling === true, - null - ); - if (isResponse(result)) { - return result; - } - - // When returning StaticHandlerContext, we patch back in the location here - // since we need it for React Context. But this helps keep our submit and - // loadRouteData operating on a Request instead of a Location - return { location, basename, ...result }; - } - - /** - * The queryRoute() method is intended for targeted route requests, either - * for fetch ?_data requests or resource route requests. In this case, we - * are only ever calling a single action or loader, and we are returning the - * returned value directly. In most cases, this will be a Response returned - * from the action/loader, but it may be a primitive or other value as well - - * and in such cases the calling context should handle that accordingly. - * - * We do respect the throw/return differentiation, so if an action/loader - * throws, then this method will throw the value. This is important so we - * can do proper boundary identification in Remix where a thrown Response - * must go to the Catch Boundary but a returned Response is happy-path. - * - * One thing to note is that any Router-initiated Errors that make sense - * to associate with a status code will be thrown as an ErrorResponse - * instance which include the raw Error, such that the calling context can - * serialize the error as they see fit while including the proper response - * code. Examples here are 404 and 405 errors that occur prior to reaching - * any user-defined loaders. - * - * - `opts.routeId` allows you to specify the specific route handler to call. - * If not provided the handler will determine the proper route by matching - * against `request.url` - * - `opts.requestContext` is an optional server context that will be passed - * to actions/loaders in the `context` parameter - */ - async function queryRoute( - request: Request, - { - routeId, - requestContext, - unstable_dataStrategy, - }: { - requestContext?: unknown; - routeId?: string; - unstable_dataStrategy?: DataStrategyFunction; - } = {} - ): Promise { - let url = new URL(request.url); - let method = request.method; - let location = createLocation("", createPath(url), null, "default"); - let matches = matchRoutes(dataRoutes, location, basename); - - // SSR supports HEAD requests while SPA doesn't - if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") { - throw getInternalRouterError(405, { method }); - } else if (!matches) { - throw getInternalRouterError(404, { pathname: location.pathname }); - } - - let match = routeId - ? matches.find((m) => m.route.id === routeId) - : getTargetMatch(matches, location); - - if (routeId && !match) { - throw getInternalRouterError(403, { - pathname: location.pathname, - routeId, - }); - } else if (!match) { - // This should never hit I don't think? - throw getInternalRouterError(404, { pathname: location.pathname }); - } - - let result = await queryImpl( - request, - location, - matches, - requestContext, - unstable_dataStrategy || null, - false, - match - ); - - if (isResponse(result)) { - return result; - } - - let error = result.errors ? Object.values(result.errors)[0] : undefined; - if (error !== undefined) { - // If we got back result.errors, that means the loader/action threw - // _something_ that wasn't a Response, but it's not guaranteed/required - // to be an `instanceof Error` either, so we have to use throw here to - // preserve the "error" state outside of queryImpl. - throw error; - } - - // Pick off the right state value to return - if (result.actionData) { - return Object.values(result.actionData)[0]; - } - - if (result.loaderData) { - let data = Object.values(result.loaderData)[0]; - if (result.activeDeferreds?.[match.route.id]) { - data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id]; - } - return data; - } - - return undefined; - } - - async function queryImpl( - request: Request, - location: Location, - matches: AgnosticDataRouteMatch[], - requestContext: unknown, - unstable_dataStrategy: DataStrategyFunction | null, - skipLoaderErrorBubbling: boolean, - routeMatch: AgnosticDataRouteMatch | null - ): Promise | Response> { - invariant( - request.signal, - "query()/queryRoute() requests must contain an AbortController signal" - ); - - try { - if (isMutationMethod(request.method.toLowerCase())) { - let result = await submit( - request, - matches, - routeMatch || getTargetMatch(matches, location), - requestContext, - unstable_dataStrategy, - skipLoaderErrorBubbling, - routeMatch != null - ); - return result; - } - - let result = await loadRouteData( - request, - matches, - requestContext, - unstable_dataStrategy, - skipLoaderErrorBubbling, - routeMatch - ); - return isResponse(result) - ? result - : { - ...result, - actionData: null, - actionHeaders: {}, - }; - } catch (e) { - // If the user threw/returned a Response in callLoaderOrAction for a - // `queryRoute` call, we throw the `HandlerResult` to bail out early - // and then return or throw the raw Response here accordingly - if (isHandlerResult(e) && isResponse(e.result)) { - if (e.type === ResultType.error) { - throw e.result; - } - return e.result; - } - // Redirects are always returned since they don't propagate to catch - // boundaries - if (isRedirectResponse(e)) { - return e; - } - throw e; - } - } - - async function submit( - request: Request, - matches: AgnosticDataRouteMatch[], - actionMatch: AgnosticDataRouteMatch, - requestContext: unknown, - unstable_dataStrategy: DataStrategyFunction | null, - skipLoaderErrorBubbling: boolean, - isRouteRequest: boolean - ): Promise | Response> { - let result: DataResult; - - if (!actionMatch.route.action && !actionMatch.route.lazy) { - let error = getInternalRouterError(405, { - method: request.method, - pathname: new URL(request.url).pathname, - routeId: actionMatch.route.id, - }); - if (isRouteRequest) { - throw error; - } - result = { - type: ResultType.error, - error, - }; - } else { - let results = await callDataStrategy( - "action", - request, - [actionMatch], - matches, - isRouteRequest, - requestContext, - unstable_dataStrategy - ); - result = results[0]; - - if (request.signal.aborted) { - throwStaticHandlerAbortedError(request, isRouteRequest, future); - } - } - - if (isRedirectResult(result)) { - // Uhhhh - this should never happen, we should always throw these from - // callLoaderOrAction, but the type narrowing here keeps TS happy and we - // can get back on the "throw all redirect responses" train here should - // this ever happen :/ - throw new Response(null, { - status: result.response.status, - headers: { - Location: result.response.headers.get("Location")!, - }, - }); - } - - if (isDeferredResult(result)) { - let error = getInternalRouterError(400, { type: "defer-action" }); - if (isRouteRequest) { - throw error; - } - result = { - type: ResultType.error, - error, - }; - } - - if (isRouteRequest) { - // Note: This should only be non-Response values if we get here, since - // isRouteRequest should throw any Response received in callLoaderOrAction - if (isErrorResult(result)) { - throw result.error; - } - - return { - matches: [actionMatch], - loaderData: {}, - actionData: { [actionMatch.route.id]: result.data }, - errors: null, - // Note: statusCode + headers are unused here since queryRoute will - // return the raw Response or value - statusCode: 200, - loaderHeaders: {}, - actionHeaders: {}, - activeDeferreds: null, - }; - } - - // Create a GET request for the loaders - let loaderRequest = new Request(request.url, { - headers: request.headers, - redirect: request.redirect, - signal: request.signal, - }); - - if (isErrorResult(result)) { - // Store off the pending error - we use it to determine which loaders - // to call and will commit it when we complete the navigation - let boundaryMatch = skipLoaderErrorBubbling - ? actionMatch - : findNearestBoundary(matches, actionMatch.route.id); - - let context = await loadRouteData( - loaderRequest, - matches, - requestContext, - unstable_dataStrategy, - skipLoaderErrorBubbling, - null, - [boundaryMatch.route.id, result] - ); - - // action status codes take precedence over loader status codes - return { - ...context, - statusCode: isRouteErrorResponse(result.error) - ? result.error.status - : result.statusCode != null - ? result.statusCode - : 500, - actionData: null, - actionHeaders: { - ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}), - }, - }; - } - - let context = await loadRouteData( - loaderRequest, - matches, - requestContext, - unstable_dataStrategy, - skipLoaderErrorBubbling, - null - ); - - return { - ...context, - actionData: { - [actionMatch.route.id]: result.data, - }, - // action status codes take precedence over loader status codes - ...(result.statusCode ? { statusCode: result.statusCode } : {}), - actionHeaders: result.headers - ? { [actionMatch.route.id]: result.headers } - : {}, - }; - } - - async function loadRouteData( - request: Request, - matches: AgnosticDataRouteMatch[], - requestContext: unknown, - unstable_dataStrategy: DataStrategyFunction | null, - skipLoaderErrorBubbling: boolean, - routeMatch: AgnosticDataRouteMatch | null, - pendingActionResult?: PendingActionResult - ): Promise< - | Omit< - StaticHandlerContext, - "location" | "basename" | "actionData" | "actionHeaders" - > - | Response - > { - let isRouteRequest = routeMatch != null; - - // Short circuit if we have no loaders to run (queryRoute()) - if ( - isRouteRequest && - !routeMatch?.route.loader && - !routeMatch?.route.lazy - ) { - throw getInternalRouterError(400, { - method: request.method, - pathname: new URL(request.url).pathname, - routeId: routeMatch?.route.id, - }); - } - - let requestMatches = routeMatch - ? [routeMatch] - : pendingActionResult && isErrorResult(pendingActionResult[1]) - ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) - : matches; - let matchesToLoad = requestMatches.filter( - (m) => m.route.loader || m.route.lazy - ); - - // Short circuit if we have no loaders to run (query()) - if (matchesToLoad.length === 0) { - return { - matches, - // Add a null for all matched routes for proper revalidation on the client - loaderData: matches.reduce( - (acc, m) => Object.assign(acc, { [m.route.id]: null }), - {} - ), - errors: - pendingActionResult && isErrorResult(pendingActionResult[1]) - ? { - [pendingActionResult[0]]: pendingActionResult[1].error, - } - : null, - statusCode: 200, - loaderHeaders: {}, - activeDeferreds: null, - }; - } - - let results = await callDataStrategy( - "loader", - request, - matchesToLoad, - matches, - isRouteRequest, - requestContext, - unstable_dataStrategy - ); - - if (request.signal.aborted) { - throwStaticHandlerAbortedError(request, isRouteRequest, future); - } - - // Process and commit output from loaders - let activeDeferreds = new Map(); - let context = processRouteLoaderData( - matches, - matchesToLoad, - results, - pendingActionResult, - activeDeferreds, - skipLoaderErrorBubbling - ); - - // Add a null for any non-loader matches for proper revalidation on the client - let executedLoaders = new Set( - matchesToLoad.map((match) => match.route.id) - ); - matches.forEach((match) => { - if (!executedLoaders.has(match.route.id)) { - context.loaderData[match.route.id] = null; - } - }); - - return { - ...context, - matches, - activeDeferreds: - activeDeferreds.size > 0 - ? Object.fromEntries(activeDeferreds.entries()) - : null, - }; - } - - // Utility wrapper for calling dataStrategy server-side without having to - // pass around the manifest, mapRouteProperties, etc. - async function callDataStrategy( - type: "loader" | "action", - request: Request, - matchesToLoad: AgnosticDataRouteMatch[], - matches: AgnosticDataRouteMatch[], - isRouteRequest: boolean, - requestContext: unknown, - unstable_dataStrategy: DataStrategyFunction | null - ): Promise { - let results = await callDataStrategyImpl( - unstable_dataStrategy || defaultDataStrategy, - type, - request, - matchesToLoad, - matches, - manifest, - mapRouteProperties, - requestContext - ); - - return await Promise.all( - results.map((result, i) => { - if (isRedirectHandlerResult(result)) { - let response = result.result as Response; - // Throw redirects and let the server handle them with an HTTP redirect - throw normalizeRelativeRoutingRedirectResponse( - response, - request, - matchesToLoad[i].route.id, - matches, - basename, - future.v7_relativeSplatPath - ); - } - if (isResponse(result.result) && isRouteRequest) { - // For SSR single-route requests, we want to hand Responses back - // directly without unwrapping - throw result; - } - - return convertHandlerResultToDataResult(result); - }) - ); - } - - return { - dataRoutes, - query, - queryRoute, - }; -} - -//#endregion - -//////////////////////////////////////////////////////////////////////////////// -//#region Helpers -//////////////////////////////////////////////////////////////////////////////// - -/** - * Given an existing StaticHandlerContext and an error thrown at render time, - * provide an updated StaticHandlerContext suitable for a second SSR render - */ -export function getStaticContextFromError( - routes: AgnosticDataRouteObject[], - context: StaticHandlerContext, - error: any -) { - let newContext: StaticHandlerContext = { - ...context, - statusCode: isRouteErrorResponse(error) ? error.status : 500, - errors: { - [context._deepestRenderedBoundaryId || routes[0].id]: error, - }, - }; - return newContext; -} - -function throwStaticHandlerAbortedError( - request: Request, - isRouteRequest: boolean, - future: StaticHandlerFutureConfig -) { - if (future.v7_throwAbortReason && request.signal.reason !== undefined) { - throw request.signal.reason; - } - - let method = isRouteRequest ? "queryRoute" : "query"; - throw new Error(`${method}() call aborted: ${request.method} ${request.url}`); -} - -function isSubmissionNavigation( - opts: BaseNavigateOrFetchOptions -): opts is SubmissionNavigateOptions { - return ( - opts != null && - (("formData" in opts && opts.formData != null) || - ("body" in opts && opts.body !== undefined)) - ); -} - -function normalizeTo( - location: Path, - matches: AgnosticDataRouteMatch[], - basename: string, - prependBasename: boolean, - to: To | null, - v7_relativeSplatPath: boolean, - fromRouteId?: string, - relative?: RelativeRoutingType -) { - let contextualMatches: AgnosticDataRouteMatch[]; - let activeRouteMatch: AgnosticDataRouteMatch | undefined; - if (fromRouteId) { - // Grab matches up to the calling route so our route-relative logic is - // relative to the correct source route - contextualMatches = []; - for (let match of matches) { - contextualMatches.push(match); - if (match.route.id === fromRouteId) { - activeRouteMatch = match; - break; - } - } - } else { - contextualMatches = matches; - activeRouteMatch = matches[matches.length - 1]; - } - - // Resolve the relative path - let path = resolveTo( - to ? to : ".", - getResolveToMatches(contextualMatches, v7_relativeSplatPath), - stripBasename(location.pathname, basename) || location.pathname, - relative === "path" - ); - - // When `to` is not specified we inherit search/hash from the current - // location, unlike when to="." and we just inherit the path. - // See https://github.com/remix-run/remix/issues/927 - if (to == null) { - path.search = location.search; - path.hash = location.hash; - } - - // Add an ?index param for matched index routes if we don't already have one - if ( - (to == null || to === "" || to === ".") && - activeRouteMatch && - activeRouteMatch.route.index && - !hasNakedIndexQuery(path.search) - ) { - path.search = path.search - ? path.search.replace(/^\?/, "?index&") - : "?index"; - } - - // If we're operating within a basename, prepend it to the pathname. If - // this is a root navigation, then just use the raw basename which allows - // the basename to have full control over the presence of a trailing slash - // on root actions - if (prependBasename && basename !== "/") { - path.pathname = - path.pathname === "/" ? basename : joinPaths([basename, path.pathname]); - } - - return createPath(path); -} - -// Normalize navigation options by converting formMethod=GET formData objects to -// URLSearchParams so they behave identically to links with query params -function normalizeNavigateOptions( - normalizeFormMethod: boolean, - isFetcher: boolean, - path: string, - opts?: BaseNavigateOrFetchOptions -): { - path: string; - submission?: Submission; - error?: ErrorResponseImpl; -} { - // Return location verbatim on non-submission navigations - if (!opts || !isSubmissionNavigation(opts)) { - return { path }; - } - - if (opts.formMethod && !isValidMethod(opts.formMethod)) { - return { - path, - error: getInternalRouterError(405, { method: opts.formMethod }), - }; - } - - let getInvalidBodyError = () => ({ - path, - error: getInternalRouterError(400, { type: "invalid-body" }), - }); - - // Create a Submission on non-GET navigations - let rawFormMethod = opts.formMethod || "get"; - let formMethod = normalizeFormMethod - ? (rawFormMethod.toUpperCase() as V7_FormMethod) - : (rawFormMethod.toLowerCase() as FormMethod); - let formAction = stripHashFromPath(path); - - if (opts.body !== undefined) { - if (opts.formEncType === "text/plain") { - // text only support POST/PUT/PATCH/DELETE submissions - if (!isMutationMethod(formMethod)) { - return getInvalidBodyError(); - } - - let text = - typeof opts.body === "string" - ? opts.body - : opts.body instanceof FormData || - opts.body instanceof URLSearchParams - ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data - Array.from(opts.body.entries()).reduce( - (acc, [name, value]) => `${acc}${name}=${value}\n`, - "" - ) - : String(opts.body); - - return { - path, - submission: { - formMethod, - formAction, - formEncType: opts.formEncType, - formData: undefined, - json: undefined, - text, - }, - }; - } else if (opts.formEncType === "application/json") { - // json only supports POST/PUT/PATCH/DELETE submissions - if (!isMutationMethod(formMethod)) { - return getInvalidBodyError(); - } - - try { - let json = - typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body; - - return { - path, - submission: { - formMethod, - formAction, - formEncType: opts.formEncType, - formData: undefined, - json, - text: undefined, - }, - }; - } catch (e) { - return getInvalidBodyError(); - } - } - } - - invariant( - typeof FormData === "function", - "FormData is not available in this environment" - ); - - let searchParams: URLSearchParams; - let formData: FormData; - - if (opts.formData) { - searchParams = convertFormDataToSearchParams(opts.formData); - formData = opts.formData; - } else if (opts.body instanceof FormData) { - searchParams = convertFormDataToSearchParams(opts.body); - formData = opts.body; - } else if (opts.body instanceof URLSearchParams) { - searchParams = opts.body; - formData = convertSearchParamsToFormData(searchParams); - } else if (opts.body == null) { - searchParams = new URLSearchParams(); - formData = new FormData(); - } else { - try { - searchParams = new URLSearchParams(opts.body); - formData = convertSearchParamsToFormData(searchParams); - } catch (e) { - return getInvalidBodyError(); - } - } - - let submission: Submission = { - formMethod, - formAction, - formEncType: - (opts && opts.formEncType) || "application/x-www-form-urlencoded", - formData, - json: undefined, - text: undefined, - }; - - if (isMutationMethod(submission.formMethod)) { - return { path, submission }; - } - - // Flatten submission onto URLSearchParams for GET submissions - let parsedPath = parsePath(path); - // On GET navigation submissions we can drop the ?index param from the - // resulting location since all loaders will run. But fetcher GET submissions - // only run a single loader so we need to preserve any incoming ?index params - if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) { - searchParams.append("index", ""); - } - parsedPath.search = `?${searchParams}`; - - return { path: createPath(parsedPath), submission }; -} - -// Filter out all routes below any caught error as they aren't going to -// render so we don't need to load them -function getLoaderMatchesUntilBoundary( - matches: AgnosticDataRouteMatch[], - boundaryId: string -) { - let boundaryMatches = matches; - if (boundaryId) { - let index = matches.findIndex((m) => m.route.id === boundaryId); - if (index >= 0) { - boundaryMatches = matches.slice(0, index); - } - } - return boundaryMatches; -} - -function getMatchesToLoad( - history: History, - state: RouterState, - matches: AgnosticDataRouteMatch[], - submission: Submission | undefined, - location: Location, - isInitialLoad: boolean, - skipActionErrorRevalidation: boolean, - isRevalidationRequired: boolean, - cancelledDeferredRoutes: string[], - cancelledFetcherLoads: string[], - deletedFetchers: Set, - fetchLoadMatches: Map, - fetchRedirectIds: Set, - routesToUse: AgnosticDataRouteObject[], - basename: string | undefined, - pendingActionResult?: PendingActionResult -): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] { - let actionResult = pendingActionResult - ? isErrorResult(pendingActionResult[1]) - ? pendingActionResult[1].error - : pendingActionResult[1].data - : undefined; - let currentUrl = history.createURL(state.location); - let nextUrl = history.createURL(location); - - // Pick navigation matches that are net-new or qualify for revalidation - let boundaryId = - pendingActionResult && isErrorResult(pendingActionResult[1]) - ? pendingActionResult[0] - : undefined; - let boundaryMatches = boundaryId - ? getLoaderMatchesUntilBoundary(matches, boundaryId) - : matches; - - // Don't revalidate loaders by default after action 4xx/5xx responses - // when the flag is enabled. They can still opt-into revalidation via - // `shouldRevalidate` via `actionResult` - let actionStatus = pendingActionResult - ? pendingActionResult[1].statusCode - : undefined; - let shouldSkipRevalidation = - skipActionErrorRevalidation && actionStatus && actionStatus >= 400; - - let navigationMatches = boundaryMatches.filter((match, index) => { - let { route } = match; - if (route.lazy) { - // We haven't loaded this route yet so we don't know if it's got a loader! - return true; - } - - if (route.loader == null) { - return false; - } - - if (isInitialLoad) { - if (typeof route.loader !== "function" || route.loader.hydrate) { - return true; - } - return ( - state.loaderData[route.id] === undefined && - // Don't re-run if the loader ran and threw an error - (!state.errors || state.errors[route.id] === undefined) - ); - } - - // Always call the loader on new route instances and pending defer cancellations - if ( - isNewLoader(state.loaderData, state.matches[index], match) || - cancelledDeferredRoutes.some((id) => id === match.route.id) - ) { - return true; - } - - // This is the default implementation for when we revalidate. If the route - // provides it's own implementation, then we give them full control but - // provide this value so they can leverage it if needed after they check - // their own specific use cases - let currentRouteMatch = state.matches[index]; - let nextRouteMatch = match; - - return shouldRevalidateLoader(match, { - currentUrl, - currentParams: currentRouteMatch.params, - nextUrl, - nextParams: nextRouteMatch.params, - ...submission, - actionResult, - unstable_actionStatus: actionStatus, - defaultShouldRevalidate: shouldSkipRevalidation - ? false - : // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate - isRevalidationRequired || - currentUrl.pathname + currentUrl.search === - nextUrl.pathname + nextUrl.search || - // Search params affect all loaders - currentUrl.search !== nextUrl.search || - isNewRouteInstance(currentRouteMatch, nextRouteMatch), - }); - }); - - // Pick fetcher.loads that need to be revalidated - let revalidatingFetchers: RevalidatingFetcher[] = []; - fetchLoadMatches.forEach((f, key) => { - // Don't revalidate: - // - on initial load (shouldn't be any fetchers then anyway) - // - if fetcher won't be present in the subsequent render - // - no longer matches the URL (v7_fetcherPersist=false) - // - was unmounted but persisted due to v7_fetcherPersist=true - if ( - isInitialLoad || - !matches.some((m) => m.route.id === f.routeId) || - deletedFetchers.has(key) - ) { - return; - } - - let fetcherMatches = matchRoutes(routesToUse, f.path, basename); - - // If the fetcher path no longer matches, push it in with null matches so - // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is - // currently only a use-case for Remix HMR where the route tree can change - // at runtime and remove a route previously loaded via a fetcher - if (!fetcherMatches) { - revalidatingFetchers.push({ - key, - routeId: f.routeId, - path: f.path, - matches: null, - match: null, - controller: null, - }); - return; - } - - // Revalidating fetchers are decoupled from the route matches since they - // load from a static href. They revalidate based on explicit revalidation - // (submission, useRevalidator, or X-Remix-Revalidate) - let fetcher = state.fetchers.get(key); - let fetcherMatch = getTargetMatch(fetcherMatches, f.path); - - let shouldRevalidate = false; - if (fetchRedirectIds.has(key)) { - // Never trigger a revalidation of an actively redirecting fetcher - shouldRevalidate = false; - } else if (cancelledFetcherLoads.includes(key)) { - // Always revalidate if the fetcher was cancelled - shouldRevalidate = true; - } else if ( - fetcher && - fetcher.state !== "idle" && - fetcher.data === undefined - ) { - // If the fetcher hasn't ever completed loading yet, then this isn't a - // revalidation, it would just be a brand new load if an explicit - // revalidation is required - shouldRevalidate = isRevalidationRequired; - } else { - // Otherwise fall back on any user-defined shouldRevalidate, defaulting - // to explicit revalidations only - shouldRevalidate = shouldRevalidateLoader(fetcherMatch, { - currentUrl, - currentParams: state.matches[state.matches.length - 1].params, - nextUrl, - nextParams: matches[matches.length - 1].params, - ...submission, - actionResult, - unstable_actionStatus: actionStatus, - defaultShouldRevalidate: shouldSkipRevalidation - ? false - : isRevalidationRequired, - }); - } - - if (shouldRevalidate) { - revalidatingFetchers.push({ - key, - routeId: f.routeId, - path: f.path, - matches: fetcherMatches, - match: fetcherMatch, - controller: new AbortController(), - }); - } - }); - - return [navigationMatches, revalidatingFetchers]; -} - -function isNewLoader( - currentLoaderData: RouteData, - currentMatch: AgnosticDataRouteMatch, - match: AgnosticDataRouteMatch -) { - let isNew = - // [a] -> [a, b] - !currentMatch || - // [a, b] -> [a, c] - match.route.id !== currentMatch.route.id; - - // Handle the case that we don't have data for a re-used route, potentially - // from a prior error or from a cancelled pending deferred - let isMissingData = currentLoaderData[match.route.id] === undefined; - - // Always load if this is a net-new route or we don't yet have data - return isNew || isMissingData; -} - -function isNewRouteInstance( - currentMatch: AgnosticDataRouteMatch, - match: AgnosticDataRouteMatch -) { - let currentPath = currentMatch.route.path; - return ( - // param change for this match, /users/123 -> /users/456 - currentMatch.pathname !== match.pathname || - // splat param changed, which is not present in match.path - // e.g. /files/images/avatar.jpg -> files/finances.xls - (currentPath != null && - currentPath.endsWith("*") && - currentMatch.params["*"] !== match.params["*"]) - ); -} - -function shouldRevalidateLoader( - loaderMatch: AgnosticDataRouteMatch, - arg: ShouldRevalidateFunctionArgs -) { - if (loaderMatch.route.shouldRevalidate) { - let routeChoice = loaderMatch.route.shouldRevalidate(arg); - if (typeof routeChoice === "boolean") { - return routeChoice; - } - } - - return arg.defaultShouldRevalidate; -} - -/** - * Execute route.lazy() methods to lazily load route modules (loader, action, - * shouldRevalidate) and update the routeManifest in place which shares objects - * with dataRoutes so those get updated as well. - */ -async function loadLazyRouteModule( - route: AgnosticDataRouteObject, - mapRouteProperties: MapRoutePropertiesFunction, - manifest: RouteManifest -) { - if (!route.lazy) { - return; - } - - let lazyRoute = await route.lazy(); - - // If the lazy route function was executed and removed by another parallel - // call then we can return - first lazy() to finish wins because the return - // value of lazy is expected to be static - if (!route.lazy) { - return; - } - - let routeToUpdate = manifest[route.id]; - invariant(routeToUpdate, "No route found in manifest"); - - // Update the route in place. This should be safe because there's no way - // we could yet be sitting on this route as we can't get there without - // resolving lazy() first. - // - // This is different than the HMR "update" use-case where we may actively be - // on the route being updated. The main concern boils down to "does this - // mutation affect any ongoing navigations or any current state.matches - // values?". If not, it should be safe to update in place. - let routeUpdates: Record = {}; - for (let lazyRouteProperty in lazyRoute) { - let staticRouteValue = - routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate]; - - let isPropertyStaticallyDefined = - staticRouteValue !== undefined && - // This property isn't static since it should always be updated based - // on the route updates - lazyRouteProperty !== "hasErrorBoundary"; - - warning( - !isPropertyStaticallyDefined, - `Route "${routeToUpdate.id}" has a static property "${lazyRouteProperty}" ` + - `defined but its lazy function is also returning a value for this property. ` + - `The lazy route property "${lazyRouteProperty}" will be ignored.` - ); - - if ( - !isPropertyStaticallyDefined && - !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey) - ) { - routeUpdates[lazyRouteProperty] = - lazyRoute[lazyRouteProperty as keyof typeof lazyRoute]; - } - } - - // Mutate the route with the provided updates. Do this first so we pass - // the updated version to mapRouteProperties - Object.assign(routeToUpdate, routeUpdates); - - // Mutate the `hasErrorBoundary` property on the route based on the route - // updates and remove the `lazy` function so we don't resolve the lazy - // route again. - Object.assign(routeToUpdate, { - // To keep things framework agnostic, we use the provided - // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to - // set the framework-aware properties (`element`/`hasErrorBoundary`) since - // the logic will differ between frameworks. - ...mapRouteProperties(routeToUpdate), - lazy: undefined, - }); -} - -// Default implementation of `dataStrategy` which fetches all loaders in parallel -function defaultDataStrategy( - opts: DataStrategyFunctionArgs -): ReturnType { - return Promise.all(opts.matches.map((m) => m.resolve())); -} - -async function callDataStrategyImpl( - dataStrategyImpl: DataStrategyFunction, - type: "loader" | "action", - request: Request, - matchesToLoad: AgnosticDataRouteMatch[], - matches: AgnosticDataRouteMatch[], - manifest: RouteManifest, - mapRouteProperties: MapRoutePropertiesFunction, - requestContext?: unknown -): Promise { - let routeIdsToLoad = matchesToLoad.reduce( - (acc, m) => acc.add(m.route.id), - new Set() - ); - let loadedMatches = new Set(); - - // Send all matches here to allow for a middleware-type implementation. - // handler will be a no-op for unneeded routes and we filter those results - // back out below. - let results = await dataStrategyImpl({ - matches: matches.map((match) => { - let shouldLoad = routeIdsToLoad.has(match.route.id); - // `resolve` encapsulates the route.lazy, executing the - // loader/action, and mapping return values/thrown errors to a - // HandlerResult. Users can pass a callback to take fine-grained control - // over the execution of the loader/action - let resolve: DataStrategyMatch["resolve"] = (handlerOverride) => { - loadedMatches.add(match.route.id); - return shouldLoad - ? callLoaderOrAction( - type, - request, - match, - manifest, - mapRouteProperties, - handlerOverride, - requestContext - ) - : Promise.resolve({ type: ResultType.data, result: undefined }); - }; - - return { - ...match, - shouldLoad, - resolve, - }; - }), - request, - params: matches[0].params, - context: requestContext, - }); - - // Throw if any loadRoute implementations not called since they are what - // ensures a route is fully loaded - matches.forEach((m) => - invariant( - loadedMatches.has(m.route.id), - `\`match.resolve()\` was not called for route id "${m.route.id}". ` + - "You must call `match.resolve()` on every match passed to " + - "`dataStrategy` to ensure all routes are properly loaded." - ) - ); - - // Filter out any middleware-only matches for which we didn't need to run handlers - return results.filter((_, i) => routeIdsToLoad.has(matches[i].route.id)); -} - -// Default logic for calling a loader/action is the user has no specified a dataStrategy -async function callLoaderOrAction( - type: "loader" | "action", - request: Request, - match: AgnosticDataRouteMatch, - manifest: RouteManifest, - mapRouteProperties: MapRoutePropertiesFunction, - handlerOverride: Parameters[0], - staticContext?: unknown -): Promise { - let result: HandlerResult; - let onReject: (() => void) | undefined; - - let runHandler = ( - handler: AgnosticRouteObject["loader"] | AgnosticRouteObject["action"] - ): Promise => { - // Setup a promise we can race against so that abort signals short circuit - let reject: () => void; - // This will never resolve so safe to type it as Promise to - // satisfy the function return value - let abortPromise = new Promise((_, r) => (reject = r)); - onReject = () => reject(); - request.signal.addEventListener("abort", onReject); - - let actualHandler = (ctx?: unknown) => { - if (typeof handler !== "function") { - return Promise.reject( - new Error( - `You cannot call the handler for a route which defines a boolean ` + - `"${type}" [routeId: ${match.route.id}]` - ) - ); - } - return handler( - { - request, - params: match.params, - context: staticContext, - }, - ...(ctx !== undefined ? [ctx] : []) - ); - }; - - let handlerPromise: Promise; - if (handlerOverride) { - handlerPromise = handlerOverride((ctx: unknown) => actualHandler(ctx)); - } else { - handlerPromise = (async () => { - try { - let val = await actualHandler(); - return { type: "data", result: val }; - } catch (e) { - return { type: "error", result: e }; - } - })(); - } - - return Promise.race([handlerPromise, abortPromise]); - }; - - try { - let handler = match.route[type]; - - if (match.route.lazy) { - if (handler) { - // Run statically defined handler in parallel with lazy() - let handlerError; - let [value] = await Promise.all([ - // If the handler throws, don't let it immediately bubble out, - // since we need to let the lazy() execution finish so we know if this - // route has a boundary that can handle the error - runHandler(handler).catch((e) => { - handlerError = e; - }), - loadLazyRouteModule(match.route, mapRouteProperties, manifest), - ]); - if (handlerError !== undefined) { - throw handlerError; - } - result = value!; - } else { - // Load lazy route module, then run any returned handler - await loadLazyRouteModule(match.route, mapRouteProperties, manifest); - - handler = match.route[type]; - if (handler) { - // Handler still runs even if we got interrupted to maintain consistency - // with un-abortable behavior of handler execution on non-lazy or - // previously-lazy-loaded routes - result = await runHandler(handler); - } else if (type === "action") { - let url = new URL(request.url); - let pathname = url.pathname + url.search; - throw getInternalRouterError(405, { - method: request.method, - pathname, - routeId: match.route.id, - }); - } else { - // lazy() route has no loader to run. Short circuit here so we don't - // hit the invariant below that errors on returning undefined. - return { type: ResultType.data, result: undefined }; - } - } - } else if (!handler) { - let url = new URL(request.url); - let pathname = url.pathname + url.search; - throw getInternalRouterError(404, { - pathname, - }); - } else { - result = await runHandler(handler); - } - - invariant( - result.result !== undefined, - `You defined ${type === "action" ? "an action" : "a loader"} for route ` + - `"${match.route.id}" but didn't return anything from your \`${type}\` ` + - `function. Please return a value or \`null\`.` - ); - } catch (e) { - // We should already be catching and converting normal handler executions to - // HandlerResults and returning them, so anything that throws here is an - // unexpected error we still need to wrap - return { type: ResultType.error, result: e }; - } finally { - if (onReject) { - request.signal.removeEventListener("abort", onReject); - } - } - - return result; -} - -async function convertHandlerResultToDataResult( - handlerResult: HandlerResult -): Promise { - let { result, type, status } = handlerResult; - - if (isResponse(result)) { - let data: any; - - try { - let contentType = result.headers.get("Content-Type"); - // Check between word boundaries instead of startsWith() due to the last - // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type - if (contentType && /\bapplication\/json\b/.test(contentType)) { - if (result.body == null) { - data = null; - } else { - data = await result.json(); - } - } else { - data = await result.text(); - } - } catch (e) { - return { type: ResultType.error, error: e }; - } - - if (type === ResultType.error) { - return { - type: ResultType.error, - error: new ErrorResponseImpl(result.status, result.statusText, data), - statusCode: result.status, - headers: result.headers, - }; - } - - return { - type: ResultType.data, - data, - statusCode: result.status, - headers: result.headers, - }; - } - - if (type === ResultType.error) { - return { - type: ResultType.error, - error: result, - statusCode: isRouteErrorResponse(result) ? result.status : status, - }; - } - - if (isDeferredData(result)) { - return { - type: ResultType.deferred, - deferredData: result, - statusCode: result.init?.status, - headers: result.init?.headers && new Headers(result.init.headers), - }; - } - - return { type: ResultType.data, data: result, statusCode: status }; -} - -// Support relative routing in internal redirects -function normalizeRelativeRoutingRedirectResponse( - response: Response, - request: Request, - routeId: string, - matches: AgnosticDataRouteMatch[], - basename: string, - v7_relativeSplatPath: boolean -) { - let location = response.headers.get("Location"); - invariant( - location, - "Redirects returned/thrown from loaders/actions must have a Location header" - ); - - if (!ABSOLUTE_URL_REGEX.test(location)) { - let trimmedMatches = matches.slice( - 0, - matches.findIndex((m) => m.route.id === routeId) + 1 - ); - location = normalizeTo( - new URL(request.url), - trimmedMatches, - basename, - true, - location, - v7_relativeSplatPath - ); - response.headers.set("Location", location); - } - - return response; -} - -function normalizeRedirectLocation( - location: string, - currentUrl: URL, - basename: string -): string { - if (ABSOLUTE_URL_REGEX.test(location)) { - // Strip off the protocol+origin for same-origin + same-basename absolute redirects - let normalizedLocation = location; - let url = normalizedLocation.startsWith("//") - ? new URL(currentUrl.protocol + normalizedLocation) - : new URL(normalizedLocation); - let isSameBasename = stripBasename(url.pathname, basename) != null; - if (url.origin === currentUrl.origin && isSameBasename) { - return url.pathname + url.search + url.hash; - } - } - return location; -} - -// Utility method for creating the Request instances for loaders/actions during -// client-side navigations and fetches. During SSR we will always have a -// Request instance from the static handler (query/queryRoute) -function createClientSideRequest( - history: History, - location: string | Location, - signal: AbortSignal, - submission?: Submission -): Request { - let url = history.createURL(stripHashFromPath(location)).toString(); - let init: RequestInit = { signal }; - - if (submission && isMutationMethod(submission.formMethod)) { - let { formMethod, formEncType } = submission; - // Didn't think we needed this but it turns out unlike other methods, patch - // won't be properly normalized to uppercase and results in a 405 error. - // See: https://fetch.spec.whatwg.org/#concept-method - init.method = formMethod.toUpperCase(); - - if (formEncType === "application/json") { - init.headers = new Headers({ "Content-Type": formEncType }); - init.body = JSON.stringify(submission.json); - } else if (formEncType === "text/plain") { - // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) - init.body = submission.text; - } else if ( - formEncType === "application/x-www-form-urlencoded" && - submission.formData - ) { - // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) - init.body = convertFormDataToSearchParams(submission.formData); - } else { - // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) - init.body = submission.formData; - } - } - - return new Request(url, init); -} - -function convertFormDataToSearchParams(formData: FormData): URLSearchParams { - let searchParams = new URLSearchParams(); - - for (let [key, value] of formData.entries()) { - // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs - searchParams.append(key, typeof value === "string" ? value : value.name); - } - - return searchParams; -} - -function convertSearchParamsToFormData( - searchParams: URLSearchParams -): FormData { - let formData = new FormData(); - for (let [key, value] of searchParams.entries()) { - formData.append(key, value); - } - return formData; -} - -function processRouteLoaderData( - matches: AgnosticDataRouteMatch[], - matchesToLoad: AgnosticDataRouteMatch[], - results: DataResult[], - pendingActionResult: PendingActionResult | undefined, - activeDeferreds: Map, - skipLoaderErrorBubbling: boolean -): { - loaderData: RouterState["loaderData"]; - errors: RouterState["errors"] | null; - statusCode: number; - loaderHeaders: Record; -} { - // Fill in loaderData/errors from our loaders - let loaderData: RouterState["loaderData"] = {}; - let errors: RouterState["errors"] | null = null; - let statusCode: number | undefined; - let foundError = false; - let loaderHeaders: Record = {}; - let pendingError = - pendingActionResult && isErrorResult(pendingActionResult[1]) - ? pendingActionResult[1].error - : undefined; - - // Process loader results into state.loaderData/state.errors - results.forEach((result, index) => { - let id = matchesToLoad[index].route.id; - invariant( - !isRedirectResult(result), - "Cannot handle redirect results in processLoaderData" - ); - if (isErrorResult(result)) { - let error = result.error; - // If we have a pending action error, we report it at the highest-route - // that throws a loader error, and then clear it out to indicate that - // it was consumed - if (pendingError !== undefined) { - error = pendingError; - pendingError = undefined; - } - - errors = errors || {}; - - if (skipLoaderErrorBubbling) { - errors[id] = error; - } else { - // Look upwards from the matched route for the closest ancestor error - // boundary, defaulting to the root match. Prefer higher error values - // if lower errors bubble to the same boundary - let boundaryMatch = findNearestBoundary(matches, id); - if (errors[boundaryMatch.route.id] == null) { - errors[boundaryMatch.route.id] = error; - } - } - - // Clear our any prior loaderData for the throwing route - loaderData[id] = undefined; - - // Once we find our first (highest) error, we set the status code and - // prevent deeper status codes from overriding - if (!foundError) { - foundError = true; - statusCode = isRouteErrorResponse(result.error) - ? result.error.status - : 500; - } - if (result.headers) { - loaderHeaders[id] = result.headers; - } - } else { - if (isDeferredResult(result)) { - activeDeferreds.set(id, result.deferredData); - loaderData[id] = result.deferredData.data; - // Error status codes always override success status codes, but if all - // loaders are successful we take the deepest status code. - if ( - result.statusCode != null && - result.statusCode !== 200 && - !foundError - ) { - statusCode = result.statusCode; - } - if (result.headers) { - loaderHeaders[id] = result.headers; - } - } else { - loaderData[id] = result.data; - // Error status codes always override success status codes, but if all - // loaders are successful we take the deepest status code. - if (result.statusCode && result.statusCode !== 200 && !foundError) { - statusCode = result.statusCode; - } - if (result.headers) { - loaderHeaders[id] = result.headers; - } - } - } - }); - - // If we didn't consume the pending action error (i.e., all loaders - // resolved), then consume it here. Also clear out any loaderData for the - // throwing route - if (pendingError !== undefined && pendingActionResult) { - errors = { [pendingActionResult[0]]: pendingError }; - loaderData[pendingActionResult[0]] = undefined; - } - - return { - loaderData, - errors, - statusCode: statusCode || 200, - loaderHeaders, - }; -} - -function processLoaderData( - state: RouterState, - matches: AgnosticDataRouteMatch[], - matchesToLoad: AgnosticDataRouteMatch[], - results: DataResult[], - pendingActionResult: PendingActionResult | undefined, - revalidatingFetchers: RevalidatingFetcher[], - fetcherResults: DataResult[], - activeDeferreds: Map -): { - loaderData: RouterState["loaderData"]; - errors?: RouterState["errors"]; -} { - let { loaderData, errors } = processRouteLoaderData( - matches, - matchesToLoad, - results, - pendingActionResult, - activeDeferreds, - false // This method is only called client side so we always want to bubble - ); - - // Process results from our revalidating fetchers - for (let index = 0; index < revalidatingFetchers.length; index++) { - let { key, match, controller } = revalidatingFetchers[index]; - invariant( - fetcherResults !== undefined && fetcherResults[index] !== undefined, - "Did not find corresponding fetcher result" - ); - let result = fetcherResults[index]; - - // Process fetcher non-redirect errors - if (controller && controller.signal.aborted) { - // Nothing to do for aborted fetchers - continue; - } else if (isErrorResult(result)) { - let boundaryMatch = findNearestBoundary(state.matches, match?.route.id); - if (!(errors && errors[boundaryMatch.route.id])) { - errors = { - ...errors, - [boundaryMatch.route.id]: result.error, - }; - } - state.fetchers.delete(key); - } else if (isRedirectResult(result)) { - // Should never get here, redirects should get processed above, but we - // keep this to type narrow to a success result in the else - invariant(false, "Unhandled fetcher revalidation redirect"); - } else if (isDeferredResult(result)) { - // Should never get here, deferred data should be awaited for fetchers - // in resolveDeferredResults - invariant(false, "Unhandled fetcher deferred data"); - } else { - let doneFetcher = getDoneFetcher(result.data); - state.fetchers.set(key, doneFetcher); - } - } - - return { loaderData, errors }; -} - -function mergeLoaderData( - loaderData: RouteData, - newLoaderData: RouteData, - matches: AgnosticDataRouteMatch[], - errors: RouteData | null | undefined -): RouteData { - let mergedLoaderData = { ...newLoaderData }; - for (let match of matches) { - let id = match.route.id; - if (newLoaderData.hasOwnProperty(id)) { - if (newLoaderData[id] !== undefined) { - mergedLoaderData[id] = newLoaderData[id]; - } else { - // No-op - this is so we ignore existing data if we have a key in the - // incoming object with an undefined value, which is how we unset a prior - // loaderData if we encounter a loader error - } - } else if (loaderData[id] !== undefined && match.route.loader) { - // Preserve existing keys not included in newLoaderData and where a loader - // wasn't removed by HMR - mergedLoaderData[id] = loaderData[id]; - } - - if (errors && errors.hasOwnProperty(id)) { - // Don't keep any loader data below the boundary - break; - } - } - return mergedLoaderData; -} - -function getActionDataForCommit( - pendingActionResult: PendingActionResult | undefined -) { - if (!pendingActionResult) { - return {}; - } - return isErrorResult(pendingActionResult[1]) - ? { - // Clear out prior actionData on errors - actionData: {}, - } - : { - actionData: { - [pendingActionResult[0]]: pendingActionResult[1].data, - }, - }; -} - -// Find the nearest error boundary, looking upwards from the leaf route (or the -// route specified by routeId) for the closest ancestor error boundary, -// defaulting to the root match -function findNearestBoundary( - matches: AgnosticDataRouteMatch[], - routeId?: string -): AgnosticDataRouteMatch { - let eligibleMatches = routeId - ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) - : [...matches]; - return ( - eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) || - matches[0] - ); -} - -function getShortCircuitMatches(routes: AgnosticDataRouteObject[]): { - matches: AgnosticDataRouteMatch[]; - route: AgnosticDataRouteObject; -} { - // Prefer a root layout route if present, otherwise shim in a route object - let route = - routes.length === 1 - ? routes[0] - : routes.find((r) => r.index || !r.path || r.path === "/") || { - id: `__shim-error-route__`, - }; - - return { - matches: [ - { - params: {}, - pathname: "", - pathnameBase: "", - route, - }, - ], - route, - }; -} - -function getInternalRouterError( - status: number, - { - pathname, - routeId, - method, - type, - }: { - pathname?: string; - routeId?: string; - method?: string; - type?: "defer-action" | "invalid-body"; - } = {} -) { - let statusText = "Unknown Server Error"; - let errorMessage = "Unknown @remix-run/router error"; - - if (status === 400) { - statusText = "Bad Request"; - if (method && pathname && routeId) { - errorMessage = - `You made a ${method} request to "${pathname}" but ` + - `did not provide a \`loader\` for route "${routeId}", ` + - `so there is no way to handle the request.`; - } else if (type === "defer-action") { - errorMessage = "defer() is not supported in actions"; - } else if (type === "invalid-body") { - errorMessage = "Unable to encode submission body"; - } - } else if (status === 403) { - statusText = "Forbidden"; - errorMessage = `Route "${routeId}" does not match URL "${pathname}"`; - } else if (status === 404) { - statusText = "Not Found"; - errorMessage = `No route matches URL "${pathname}"`; - } else if (status === 405) { - statusText = "Method Not Allowed"; - if (method && pathname && routeId) { - errorMessage = - `You made a ${method.toUpperCase()} request to "${pathname}" but ` + - `did not provide an \`action\` for route "${routeId}", ` + - `so there is no way to handle the request.`; - } else if (method) { - errorMessage = `Invalid request method "${method.toUpperCase()}"`; - } - } - - return new ErrorResponseImpl( - status || 500, - statusText, - new Error(errorMessage), - true - ); -} - -// Find any returned redirect errors, starting from the lowest match -function findRedirect( - results: DataResult[] -): { result: RedirectResult; idx: number } | undefined { - for (let i = results.length - 1; i >= 0; i--) { - let result = results[i]; - if (isRedirectResult(result)) { - return { result, idx: i }; - } - } -} - -function stripHashFromPath(path: To) { - let parsedPath = typeof path === "string" ? parsePath(path) : path; - return createPath({ ...parsedPath, hash: "" }); -} - -function isHashChangeOnly(a: Location, b: Location): boolean { - if (a.pathname !== b.pathname || a.search !== b.search) { - return false; - } - - if (a.hash === "") { - // /page -> /page#hash - return b.hash !== ""; - } else if (a.hash === b.hash) { - // /page#hash -> /page#hash - return true; - } else if (b.hash !== "") { - // /page#hash -> /page#other - return true; - } - - // If the hash is removed the browser will re-perform a request to the server - // /page#hash -> /page - return false; -} - -function isHandlerResult(result: unknown): result is HandlerResult { - return ( - result != null && - typeof result === "object" && - "type" in result && - "result" in result && - (result.type === ResultType.data || result.type === ResultType.error) - ); -} - -function isRedirectHandlerResult(result: HandlerResult) { - return ( - isResponse(result.result) && redirectStatusCodes.has(result.result.status) - ); -} - -function isDeferredResult(result: DataResult): result is DeferredResult { - return result.type === ResultType.deferred; -} - -function isErrorResult(result: DataResult): result is ErrorResult { - return result.type === ResultType.error; -} - -function isRedirectResult(result?: DataResult): result is RedirectResult { - return (result && result.type) === ResultType.redirect; -} - -export function isDeferredData(value: any): value is DeferredData { - let deferred: DeferredData = value; - return ( - deferred && - typeof deferred === "object" && - typeof deferred.data === "object" && - typeof deferred.subscribe === "function" && - typeof deferred.cancel === "function" && - typeof deferred.resolveData === "function" - ); -} - -function isResponse(value: any): value is Response { - return ( - value != null && - typeof value.status === "number" && - typeof value.statusText === "string" && - typeof value.headers === "object" && - typeof value.body !== "undefined" - ); -} - -function isRedirectResponse(result: any): result is Response { - if (!isResponse(result)) { - return false; - } - - let status = result.status; - let location = result.headers.get("Location"); - return status >= 300 && status <= 399 && location != null; -} - -function isValidMethod(method: string): method is FormMethod | V7_FormMethod { - return validRequestMethods.has(method.toLowerCase() as FormMethod); -} - -function isMutationMethod( - method: string -): method is MutationFormMethod | V7_MutationFormMethod { - return validMutationMethods.has(method.toLowerCase() as MutationFormMethod); -} - -async function resolveDeferredResults( - currentMatches: AgnosticDataRouteMatch[], - matchesToLoad: (AgnosticDataRouteMatch | null)[], - results: DataResult[], - signals: (AbortSignal | null)[], - isFetcher: boolean, - currentLoaderData?: RouteData -) { - for (let index = 0; index < results.length; index++) { - let result = results[index]; - let match = matchesToLoad[index]; - // If we don't have a match, then we can have a deferred result to do - // anything with. This is for revalidating fetchers where the route was - // removed during HMR - if (!match) { - continue; - } - - let currentMatch = currentMatches.find( - (m) => m.route.id === match!.route.id - ); - let isRevalidatingLoader = - currentMatch != null && - !isNewRouteInstance(currentMatch, match) && - (currentLoaderData && currentLoaderData[match.route.id]) !== undefined; - - if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) { - // Note: we do not have to touch activeDeferreds here since we race them - // against the signal in resolveDeferredData and they'll get aborted - // there if needed - let signal = signals[index]; - invariant( - signal, - "Expected an AbortSignal for revalidating fetcher deferred result" - ); - await resolveDeferredData(result, signal, isFetcher).then((result) => { - if (result) { - results[index] = result || results[index]; - } - }); - } - } -} - -async function resolveDeferredData( - result: DeferredResult, - signal: AbortSignal, - unwrap = false -): Promise { - let aborted = await result.deferredData.resolveData(signal); - if (aborted) { - return; - } - - if (unwrap) { - try { - return { - type: ResultType.data, - data: result.deferredData.unwrappedData, - }; - } catch (e) { - // Handle any TrackedPromise._error values encountered while unwrapping - return { - type: ResultType.error, - error: e, - }; - } - } - - return { - type: ResultType.data, - data: result.deferredData.data, - }; -} - -function hasNakedIndexQuery(search: string): boolean { - return new URLSearchParams(search).getAll("index").some((v) => v === ""); -} - -function getTargetMatch( - matches: AgnosticDataRouteMatch[], - location: Location | string -) { - let search = - typeof location === "string" ? parsePath(location).search : location.search; - if ( - matches[matches.length - 1].route.index && - hasNakedIndexQuery(search || "") - ) { - // Return the leaf index route when index is present - return matches[matches.length - 1]; - } - // Otherwise grab the deepest "path contributing" match (ignoring index and - // pathless layout routes) - let pathMatches = getPathContributingMatches(matches); - return pathMatches[pathMatches.length - 1]; -} - -function getSubmissionFromNavigation( - navigation: Navigation -): Submission | undefined { - let { formMethod, formAction, formEncType, text, formData, json } = - navigation; - if (!formMethod || !formAction || !formEncType) { - return; - } - - if (text != null) { - return { - formMethod, - formAction, - formEncType, - formData: undefined, - json: undefined, - text, - }; - } else if (formData != null) { - return { - formMethod, - formAction, - formEncType, - formData, - json: undefined, - text: undefined, - }; - } else if (json !== undefined) { - return { - formMethod, - formAction, - formEncType, - formData: undefined, - json, - text: undefined, - }; - } -} - -function getLoadingNavigation( - location: Location, - submission?: Submission -): NavigationStates["Loading"] { - if (submission) { - let navigation: NavigationStates["Loading"] = { - state: "loading", - location, - formMethod: submission.formMethod, - formAction: submission.formAction, - formEncType: submission.formEncType, - formData: submission.formData, - json: submission.json, - text: submission.text, - }; - return navigation; - } else { - let navigation: NavigationStates["Loading"] = { - state: "loading", - location, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined, - }; - return navigation; - } -} - -function getSubmittingNavigation( - location: Location, - submission: Submission -): NavigationStates["Submitting"] { - let navigation: NavigationStates["Submitting"] = { - state: "submitting", - location, - formMethod: submission.formMethod, - formAction: submission.formAction, - formEncType: submission.formEncType, - formData: submission.formData, - json: submission.json, - text: submission.text, - }; - return navigation; -} - -function getLoadingFetcher( - submission?: Submission, - data?: Fetcher["data"] -): FetcherStates["Loading"] { - if (submission) { - let fetcher: FetcherStates["Loading"] = { - state: "loading", - formMethod: submission.formMethod, - formAction: submission.formAction, - formEncType: submission.formEncType, - formData: submission.formData, - json: submission.json, - text: submission.text, - data, - }; - return fetcher; - } else { - let fetcher: FetcherStates["Loading"] = { - state: "loading", - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined, - data, - }; - return fetcher; - } -} - -function getSubmittingFetcher( - submission: Submission, - existingFetcher?: Fetcher -): FetcherStates["Submitting"] { - let fetcher: FetcherStates["Submitting"] = { - state: "submitting", - formMethod: submission.formMethod, - formAction: submission.formAction, - formEncType: submission.formEncType, - formData: submission.formData, - json: submission.json, - text: submission.text, - data: existingFetcher ? existingFetcher.data : undefined, - }; - return fetcher; -} - -function getDoneFetcher(data: Fetcher["data"]): FetcherStates["Idle"] { - let fetcher: FetcherStates["Idle"] = { - state: "idle", - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - json: undefined, - text: undefined, - data, - }; - return fetcher; -} - -function restoreAppliedTransitions( - _window: Window, - transitions: Map> -) { - try { - let sessionPositions = _window.sessionStorage.getItem( - TRANSITIONS_STORAGE_KEY - ); - if (sessionPositions) { - let json = JSON.parse(sessionPositions); - for (let [k, v] of Object.entries(json || {})) { - if (v && Array.isArray(v)) { - transitions.set(k, new Set(v || [])); - } - } - } - } catch (e) { - // no-op, use default empty object - } -} - -function persistAppliedTransitions( - _window: Window, - transitions: Map> -) { - if (transitions.size > 0) { - let json: Record = {}; - for (let [k, v] of transitions) { - json[k] = [...v]; - } - try { - _window.sessionStorage.setItem( - TRANSITIONS_STORAGE_KEY, - JSON.stringify(json) - ); - } catch (error) { - warning( - false, - `Failed to save applied view transitions in sessionStorage (${error}).` - ); - } - } -} - -//#endregion diff --git a/node_modules/@remix-run/router/utils.ts b/node_modules/@remix-run/router/utils.ts deleted file mode 100644 index 561421e7..00000000 --- a/node_modules/@remix-run/router/utils.ts +++ /dev/null @@ -1,1630 +0,0 @@ -import type { Location, Path, To } from "./history"; -import { invariant, parsePath, warning } from "./history"; - -/** - * Map of routeId -> data returned from a loader/action/error - */ -export interface RouteData { - [routeId: string]: any; -} - -export enum ResultType { - data = "data", - deferred = "deferred", - redirect = "redirect", - error = "error", -} - -/** - * Successful result from a loader or action - */ -export interface SuccessResult { - type: ResultType.data; - data: unknown; - statusCode?: number; - headers?: Headers; -} - -/** - * Successful defer() result from a loader or action - */ -export interface DeferredResult { - type: ResultType.deferred; - deferredData: DeferredData; - statusCode?: number; - headers?: Headers; -} - -/** - * Redirect result from a loader or action - */ -export interface RedirectResult { - type: ResultType.redirect; - // We keep the raw Response for redirects so we can return it verbatim - response: Response; -} - -/** - * Unsuccessful result from a loader or action - */ -export interface ErrorResult { - type: ResultType.error; - error: unknown; - statusCode?: number; - headers?: Headers; -} - -/** - * Result from a loader or action - potentially successful or unsuccessful - */ -export type DataResult = - | SuccessResult - | DeferredResult - | RedirectResult - | ErrorResult; - -/** - * Result from a loader or action called via dataStrategy - */ -export interface HandlerResult { - type: "data" | "error"; - result: unknown; // data, Error, Response, DeferredData - status?: number; -} - -type LowerCaseFormMethod = "get" | "post" | "put" | "patch" | "delete"; -type UpperCaseFormMethod = Uppercase; - -/** - * Users can specify either lowercase or uppercase form methods on ``, - * useSubmit(), ``, etc. - */ -export type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod; - -/** - * Active navigation/fetcher form methods are exposed in lowercase on the - * RouterState - */ -export type FormMethod = LowerCaseFormMethod; -export type MutationFormMethod = Exclude; - -/** - * In v7, active navigation/fetcher form methods are exposed in uppercase on the - * RouterState. This is to align with the normalization done via fetch(). - */ -export type V7_FormMethod = UpperCaseFormMethod; -export type V7_MutationFormMethod = Exclude; - -export type FormEncType = - | "application/x-www-form-urlencoded" - | "multipart/form-data" - | "application/json" - | "text/plain"; - -// Thanks https://github.com/sindresorhus/type-fest! -type JsonObject = { [Key in string]: JsonValue } & { - [Key in string]?: JsonValue | undefined; -}; -type JsonArray = JsonValue[] | readonly JsonValue[]; -type JsonPrimitive = string | number | boolean | null; -type JsonValue = JsonPrimitive | JsonObject | JsonArray; - -/** - * @private - * Internal interface to pass around for action submissions, not intended for - * external consumption - */ -export type Submission = - | { - formMethod: FormMethod | V7_FormMethod; - formAction: string; - formEncType: FormEncType; - formData: FormData; - json: undefined; - text: undefined; - } - | { - formMethod: FormMethod | V7_FormMethod; - formAction: string; - formEncType: FormEncType; - formData: undefined; - json: JsonValue; - text: undefined; - } - | { - formMethod: FormMethod | V7_FormMethod; - formAction: string; - formEncType: FormEncType; - formData: undefined; - json: undefined; - text: string; - }; - -/** - * @private - * Arguments passed to route loader/action functions. Same for now but we keep - * this as a private implementation detail in case they diverge in the future. - */ -interface DataFunctionArgs { - request: Request; - params: Params; - context?: Context; -} - -// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers: -// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs -// Also, make them a type alias instead of an interface - -/** - * Arguments passed to loader functions - */ -export interface LoaderFunctionArgs - extends DataFunctionArgs {} - -/** - * Arguments passed to action functions - */ -export interface ActionFunctionArgs - extends DataFunctionArgs {} - -/** - * Loaders and actions can return anything except `undefined` (`null` is a - * valid return value if there is no data to return). Responses are preferred - * and will ease any future migration to Remix - */ -type DataFunctionValue = Response | NonNullable | null; - -type DataFunctionReturnValue = Promise | DataFunctionValue; - -/** - * Route loader function signature - */ -export type LoaderFunction = { - ( - args: LoaderFunctionArgs, - handlerCtx?: unknown - ): DataFunctionReturnValue; -} & { hydrate?: boolean }; - -/** - * Route action function signature - */ -export interface ActionFunction { - ( - args: ActionFunctionArgs, - handlerCtx?: unknown - ): DataFunctionReturnValue; -} - -/** - * Arguments passed to shouldRevalidate function - */ -export interface ShouldRevalidateFunctionArgs { - currentUrl: URL; - currentParams: AgnosticDataRouteMatch["params"]; - nextUrl: URL; - nextParams: AgnosticDataRouteMatch["params"]; - formMethod?: Submission["formMethod"]; - formAction?: Submission["formAction"]; - formEncType?: Submission["formEncType"]; - text?: Submission["text"]; - formData?: Submission["formData"]; - json?: Submission["json"]; - unstable_actionStatus?: number; - actionResult?: any; - defaultShouldRevalidate: boolean; -} - -/** - * Route shouldRevalidate function signature. This runs after any submission - * (navigation or fetcher), so we flatten the navigation/fetcher submission - * onto the arguments. It shouldn't matter whether it came from a navigation - * or a fetcher, what really matters is the URLs and the formData since loaders - * have to re-run based on the data models that were potentially mutated. - */ -export interface ShouldRevalidateFunction { - (args: ShouldRevalidateFunctionArgs): boolean; -} - -/** - * Function provided by the framework-aware layers to set `hasErrorBoundary` - * from the framework-aware `errorElement` prop - * - * @deprecated Use `mapRouteProperties` instead - */ -export interface DetectErrorBoundaryFunction { - (route: AgnosticRouteObject): boolean; -} - -export interface DataStrategyMatch - extends AgnosticRouteMatch { - shouldLoad: boolean; - resolve: ( - handlerOverride?: ( - handler: (ctx?: unknown) => DataFunctionReturnValue - ) => Promise - ) => Promise; -} - -export interface DataStrategyFunctionArgs - extends DataFunctionArgs { - matches: DataStrategyMatch[]; -} - -export interface DataStrategyFunction { - (args: DataStrategyFunctionArgs): Promise; -} - -/** - * Function provided by the framework-aware layers to set any framework-specific - * properties from framework-agnostic properties - */ -export interface MapRoutePropertiesFunction { - (route: AgnosticRouteObject): { - hasErrorBoundary: boolean; - } & Record; -} - -/** - * Keys we cannot change from within a lazy() function. We spread all other keys - * onto the route. Either they're meaningful to the router, or they'll get - * ignored. - */ -export type ImmutableRouteKey = - | "lazy" - | "caseSensitive" - | "path" - | "id" - | "index" - | "children"; - -export const immutableRouteKeys = new Set([ - "lazy", - "caseSensitive", - "path", - "id", - "index", - "children", -]); - -type RequireOne = Exclude< - { - [K in keyof T]: K extends Key ? Omit & Required> : never; - }[keyof T], - undefined ->; - -/** - * lazy() function to load a route definition, which can add non-matching - * related properties to a route - */ -export interface LazyRouteFunction { - (): Promise>>; -} - -/** - * Base RouteObject with common props shared by all types of routes - */ -type AgnosticBaseRouteObject = { - caseSensitive?: boolean; - path?: string; - id?: string; - loader?: LoaderFunction | boolean; - action?: ActionFunction | boolean; - hasErrorBoundary?: boolean; - shouldRevalidate?: ShouldRevalidateFunction; - handle?: any; - lazy?: LazyRouteFunction; -}; - -/** - * Index routes must not have children - */ -export type AgnosticIndexRouteObject = AgnosticBaseRouteObject & { - children?: undefined; - index: true; -}; - -/** - * Non-index routes may have children, but cannot have index - */ -export type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & { - children?: AgnosticRouteObject[]; - index?: false; -}; - -/** - * A route object represents a logical route, with (optionally) its child - * routes organized in a tree-like structure. - */ -export type AgnosticRouteObject = - | AgnosticIndexRouteObject - | AgnosticNonIndexRouteObject; - -export type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & { - id: string; -}; - -export type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & { - children?: AgnosticDataRouteObject[]; - id: string; -}; - -/** - * A data route object, which is just a RouteObject with a required unique ID - */ -export type AgnosticDataRouteObject = - | AgnosticDataIndexRouteObject - | AgnosticDataNonIndexRouteObject; - -export type RouteManifest = Record; - -// Recursive helper for finding path parameters in the absence of wildcards -type _PathParam = - // split path into individual path segments - Path extends `${infer L}/${infer R}` - ? _PathParam | _PathParam - : // find params after `:` - Path extends `:${infer Param}` - ? Param extends `${infer Optional}?` - ? Optional - : Param - : // otherwise, there aren't any params present - never; - -/** - * Examples: - * "/a/b/*" -> "*" - * ":a" -> "a" - * "/a/:b" -> "b" - * "/a/blahblahblah:b" -> "b" - * "/:a/:b" -> "a" | "b" - * "/:a/b/:c/*" -> "a" | "c" | "*" - */ -export type PathParam = - // check if path is just a wildcard - Path extends "*" | "/*" - ? "*" - : // look for wildcard at the end of the path - Path extends `${infer Rest}/*` - ? "*" | _PathParam - : // look for params in the absence of wildcards - _PathParam; - -// Attempt to parse the given string segment. If it fails, then just return the -// plain string type as a default fallback. Otherwise, return the union of the -// parsed string literals that were referenced as dynamic segments in the route. -export type ParamParseKey = - // if you could not find path params, fallback to `string` - [PathParam] extends [never] ? string : PathParam; - -/** - * The parameters that were parsed from the URL path. - */ -export type Params = { - readonly [key in Key]: string | undefined; -}; - -/** - * A RouteMatch contains info about how a route matched a URL. - */ -export interface AgnosticRouteMatch< - ParamKey extends string = string, - RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject -> { - /** - * The names and values of dynamic parameters in the URL. - */ - params: Params; - /** - * The portion of the URL pathname that was matched. - */ - pathname: string; - /** - * The portion of the URL pathname that was matched before child routes. - */ - pathnameBase: string; - /** - * The route object that was used to match. - */ - route: RouteObjectType; -} - -export interface AgnosticDataRouteMatch - extends AgnosticRouteMatch {} - -function isIndexRoute( - route: AgnosticRouteObject -): route is AgnosticIndexRouteObject { - return route.index === true; -} - -// Walk the route tree generating unique IDs where necessary, so we are working -// solely with AgnosticDataRouteObject's within the Router -export function convertRoutesToDataRoutes( - routes: AgnosticRouteObject[], - mapRouteProperties: MapRoutePropertiesFunction, - parentPath: number[] = [], - manifest: RouteManifest = {} -): AgnosticDataRouteObject[] { - return routes.map((route, index) => { - let treePath = [...parentPath, index]; - let id = typeof route.id === "string" ? route.id : treePath.join("-"); - invariant( - route.index !== true || !route.children, - `Cannot specify children on an index route` - ); - invariant( - !manifest[id], - `Found a route id collision on id "${id}". Route ` + - "id's must be globally unique within Data Router usages" - ); - - if (isIndexRoute(route)) { - let indexRoute: AgnosticDataIndexRouteObject = { - ...route, - ...mapRouteProperties(route), - id, - }; - manifest[id] = indexRoute; - return indexRoute; - } else { - let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = { - ...route, - ...mapRouteProperties(route), - id, - children: undefined, - }; - manifest[id] = pathOrLayoutRoute; - - if (route.children) { - pathOrLayoutRoute.children = convertRoutesToDataRoutes( - route.children, - mapRouteProperties, - treePath, - manifest - ); - } - - return pathOrLayoutRoute; - } - }); -} - -/** - * Matches the given routes to a location and returns the match data. - * - * @see https://reactrouter.com/utils/match-routes - */ -export function matchRoutes< - RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject ->( - routes: RouteObjectType[], - locationArg: Partial | string, - basename = "/" -): AgnosticRouteMatch[] | null { - let location = - typeof locationArg === "string" ? parsePath(locationArg) : locationArg; - - let pathname = stripBasename(location.pathname || "/", basename); - - if (pathname == null) { - return null; - } - - let branches = flattenRoutes(routes); - rankRouteBranches(branches); - - let matches = null; - for (let i = 0; matches == null && i < branches.length; ++i) { - // Incoming pathnames are generally encoded from either window.location - // or from router.navigate, but we want to match against the unencoded - // paths in the route definitions. Memory router locations won't be - // encoded here but there also shouldn't be anything to decode so this - // should be a safe operation. This avoids needing matchRoutes to be - // history-aware. - let decoded = decodePath(pathname); - matches = matchRouteBranch(branches[i], decoded); - } - - return matches; -} - -export interface UIMatch { - id: string; - pathname: string; - params: AgnosticRouteMatch["params"]; - data: Data; - handle: Handle; -} - -export function convertRouteMatchToUiMatch( - match: AgnosticDataRouteMatch, - loaderData: RouteData -): UIMatch { - let { route, pathname, params } = match; - return { - id: route.id, - pathname, - params, - data: loaderData[route.id], - handle: route.handle, - }; -} - -interface RouteMeta< - RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject -> { - relativePath: string; - caseSensitive: boolean; - childrenIndex: number; - route: RouteObjectType; -} - -interface RouteBranch< - RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject -> { - path: string; - score: number; - routesMeta: RouteMeta[]; -} - -function flattenRoutes< - RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject ->( - routes: RouteObjectType[], - branches: RouteBranch[] = [], - parentsMeta: RouteMeta[] = [], - parentPath = "" -): RouteBranch[] { - let flattenRoute = ( - route: RouteObjectType, - index: number, - relativePath?: string - ) => { - let meta: RouteMeta = { - relativePath: - relativePath === undefined ? route.path || "" : relativePath, - caseSensitive: route.caseSensitive === true, - childrenIndex: index, - route, - }; - - if (meta.relativePath.startsWith("/")) { - invariant( - meta.relativePath.startsWith(parentPath), - `Absolute route path "${meta.relativePath}" nested under path ` + - `"${parentPath}" is not valid. An absolute child route path ` + - `must start with the combined path of all its parent routes.` - ); - - meta.relativePath = meta.relativePath.slice(parentPath.length); - } - - let path = joinPaths([parentPath, meta.relativePath]); - let routesMeta = parentsMeta.concat(meta); - - // Add the children before adding this route to the array, so we traverse the - // route tree depth-first and child routes appear before their parents in - // the "flattened" version. - if (route.children && route.children.length > 0) { - invariant( - // Our types know better, but runtime JS may not! - // @ts-expect-error - route.index !== true, - `Index routes must not have child routes. Please remove ` + - `all child routes from route path "${path}".` - ); - - flattenRoutes(route.children, branches, routesMeta, path); - } - - // Routes without a path shouldn't ever match by themselves unless they are - // index routes, so don't add them to the list of possible branches. - if (route.path == null && !route.index) { - return; - } - - branches.push({ - path, - score: computeScore(path, route.index), - routesMeta, - }); - }; - routes.forEach((route, index) => { - // coarse-grain check for optional params - if (route.path === "" || !route.path?.includes("?")) { - flattenRoute(route, index); - } else { - for (let exploded of explodeOptionalSegments(route.path)) { - flattenRoute(route, index, exploded); - } - } - }); - - return branches; -} - -/** - * Computes all combinations of optional path segments for a given path, - * excluding combinations that are ambiguous and of lower priority. - * - * For example, `/one/:two?/three/:four?/:five?` explodes to: - * - `/one/three` - * - `/one/:two/three` - * - `/one/three/:four` - * - `/one/three/:five` - * - `/one/:two/three/:four` - * - `/one/:two/three/:five` - * - `/one/three/:four/:five` - * - `/one/:two/three/:four/:five` - */ -function explodeOptionalSegments(path: string): string[] { - let segments = path.split("/"); - if (segments.length === 0) return []; - - let [first, ...rest] = segments; - - // Optional path segments are denoted by a trailing `?` - let isOptional = first.endsWith("?"); - // Compute the corresponding required segment: `foo?` -> `foo` - let required = first.replace(/\?$/, ""); - - if (rest.length === 0) { - // Intepret empty string as omitting an optional segment - // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three` - return isOptional ? [required, ""] : [required]; - } - - let restExploded = explodeOptionalSegments(rest.join("/")); - - let result: string[] = []; - - // All child paths with the prefix. Do this for all children before the - // optional version for all children, so we get consistent ordering where the - // parent optional aspect is preferred as required. Otherwise, we can get - // child sections interspersed where deeper optional segments are higher than - // parent optional segments, where for example, /:two would explode _earlier_ - // then /:one. By always including the parent as required _for all children_ - // first, we avoid this issue - result.push( - ...restExploded.map((subpath) => - subpath === "" ? required : [required, subpath].join("/") - ) - ); - - // Then, if this is an optional value, add all child versions without - if (isOptional) { - result.push(...restExploded); - } - - // for absolute paths, ensure `/` instead of empty segment - return result.map((exploded) => - path.startsWith("/") && exploded === "" ? "/" : exploded - ); -} - -function rankRouteBranches(branches: RouteBranch[]): void { - branches.sort((a, b) => - a.score !== b.score - ? b.score - a.score // Higher score first - : compareIndexes( - a.routesMeta.map((meta) => meta.childrenIndex), - b.routesMeta.map((meta) => meta.childrenIndex) - ) - ); -} - -const paramRe = /^:[\w-]+$/; -const dynamicSegmentValue = 3; -const indexRouteValue = 2; -const emptySegmentValue = 1; -const staticSegmentValue = 10; -const splatPenalty = -2; -const isSplat = (s: string) => s === "*"; - -function computeScore(path: string, index: boolean | undefined): number { - let segments = path.split("/"); - let initialScore = segments.length; - if (segments.some(isSplat)) { - initialScore += splatPenalty; - } - - if (index) { - initialScore += indexRouteValue; - } - - return segments - .filter((s) => !isSplat(s)) - .reduce( - (score, segment) => - score + - (paramRe.test(segment) - ? dynamicSegmentValue - : segment === "" - ? emptySegmentValue - : staticSegmentValue), - initialScore - ); -} - -function compareIndexes(a: number[], b: number[]): number { - let siblings = - a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]); - - return siblings - ? // If two routes are siblings, we should try to match the earlier sibling - // first. This allows people to have fine-grained control over the matching - // behavior by simply putting routes with identical paths in the order they - // want them tried. - a[a.length - 1] - b[b.length - 1] - : // Otherwise, it doesn't really make sense to rank non-siblings by index, - // so they sort equally. - 0; -} - -function matchRouteBranch< - ParamKey extends string = string, - RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject ->( - branch: RouteBranch, - pathname: string -): AgnosticRouteMatch[] | null { - let { routesMeta } = branch; - - let matchedParams = {}; - let matchedPathname = "/"; - let matches: AgnosticRouteMatch[] = []; - for (let i = 0; i < routesMeta.length; ++i) { - let meta = routesMeta[i]; - let end = i === routesMeta.length - 1; - let remainingPathname = - matchedPathname === "/" - ? pathname - : pathname.slice(matchedPathname.length) || "/"; - let match = matchPath( - { path: meta.relativePath, caseSensitive: meta.caseSensitive, end }, - remainingPathname - ); - - if (!match) return null; - - Object.assign(matchedParams, match.params); - - let route = meta.route; - - matches.push({ - // TODO: Can this as be avoided? - params: matchedParams as Params, - pathname: joinPaths([matchedPathname, match.pathname]), - pathnameBase: normalizePathname( - joinPaths([matchedPathname, match.pathnameBase]) - ), - route, - }); - - if (match.pathnameBase !== "/") { - matchedPathname = joinPaths([matchedPathname, match.pathnameBase]); - } - } - - return matches; -} - -/** - * Returns a path with params interpolated. - * - * @see https://reactrouter.com/utils/generate-path - */ -export function generatePath( - originalPath: Path, - params: { - [key in PathParam]: string | null; - } = {} as any -): string { - let path: string = originalPath; - if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) { - warning( - false, - `Route path "${path}" will be treated as if it were ` + - `"${path.replace(/\*$/, "/*")}" because the \`*\` character must ` + - `always follow a \`/\` in the pattern. To get rid of this warning, ` + - `please change the route path to "${path.replace(/\*$/, "/*")}".` - ); - path = path.replace(/\*$/, "/*") as Path; - } - - // ensure `/` is added at the beginning if the path is absolute - const prefix = path.startsWith("/") ? "/" : ""; - - const stringify = (p: any) => - p == null ? "" : typeof p === "string" ? p : String(p); - - const segments = path - .split(/\/+/) - .map((segment, index, array) => { - const isLastSegment = index === array.length - 1; - - // only apply the splat if it's the last segment - if (isLastSegment && segment === "*") { - const star = "*" as PathParam; - // Apply the splat - return stringify(params[star]); - } - - const keyMatch = segment.match(/^:([\w-]+)(\??)$/); - if (keyMatch) { - const [, key, optional] = keyMatch; - let param = params[key as PathParam]; - invariant(optional === "?" || param != null, `Missing ":${key}" param`); - return stringify(param); - } - - // Remove any optional markers from optional static segments - return segment.replace(/\?$/g, ""); - }) - // Remove empty segments - .filter((segment) => !!segment); - - return prefix + segments.join("/"); -} - -/** - * A PathPattern is used to match on some portion of a URL pathname. - */ -export interface PathPattern { - /** - * A string to match against a URL pathname. May contain `:id`-style segments - * to indicate placeholders for dynamic parameters. May also end with `/*` to - * indicate matching the rest of the URL pathname. - */ - path: Path; - /** - * Should be `true` if the static portions of the `path` should be matched in - * the same case. - */ - caseSensitive?: boolean; - /** - * Should be `true` if this pattern should match the entire URL pathname. - */ - end?: boolean; -} - -/** - * A PathMatch contains info about how a PathPattern matched on a URL pathname. - */ -export interface PathMatch { - /** - * The names and values of dynamic parameters in the URL. - */ - params: Params; - /** - * The portion of the URL pathname that was matched. - */ - pathname: string; - /** - * The portion of the URL pathname that was matched before child routes. - */ - pathnameBase: string; - /** - * The pattern that was used to match. - */ - pattern: PathPattern; -} - -type Mutable = { - -readonly [P in keyof T]: T[P]; -}; - -/** - * Performs pattern matching on a URL pathname and returns information about - * the match. - * - * @see https://reactrouter.com/utils/match-path - */ -export function matchPath< - ParamKey extends ParamParseKey, - Path extends string ->( - pattern: PathPattern | Path, - pathname: string -): PathMatch | null { - if (typeof pattern === "string") { - pattern = { path: pattern, caseSensitive: false, end: true }; - } - - let [matcher, compiledParams] = compilePath( - pattern.path, - pattern.caseSensitive, - pattern.end - ); - - let match = pathname.match(matcher); - if (!match) return null; - - let matchedPathname = match[0]; - let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1"); - let captureGroups = match.slice(1); - let params: Params = compiledParams.reduce>( - (memo, { paramName, isOptional }, index) => { - // We need to compute the pathnameBase here using the raw splat value - // instead of using params["*"] later because it will be decoded then - if (paramName === "*") { - let splatValue = captureGroups[index] || ""; - pathnameBase = matchedPathname - .slice(0, matchedPathname.length - splatValue.length) - .replace(/(.)\/+$/, "$1"); - } - - const value = captureGroups[index]; - if (isOptional && !value) { - memo[paramName] = undefined; - } else { - memo[paramName] = (value || "").replace(/%2F/g, "/"); - } - return memo; - }, - {} - ); - - return { - params, - pathname: matchedPathname, - pathnameBase, - pattern, - }; -} - -type CompiledPathParam = { paramName: string; isOptional?: boolean }; - -function compilePath( - path: string, - caseSensitive = false, - end = true -): [RegExp, CompiledPathParam[]] { - warning( - path === "*" || !path.endsWith("*") || path.endsWith("/*"), - `Route path "${path}" will be treated as if it were ` + - `"${path.replace(/\*$/, "/*")}" because the \`*\` character must ` + - `always follow a \`/\` in the pattern. To get rid of this warning, ` + - `please change the route path to "${path.replace(/\*$/, "/*")}".` - ); - - let params: CompiledPathParam[] = []; - let regexpSource = - "^" + - path - .replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below - .replace(/^\/*/, "/") // Make sure it has a leading / - .replace(/[\\.*+^${}|()[\]]/g, "\\$&") // Escape special regex chars - .replace( - /\/:([\w-]+)(\?)?/g, - (_: string, paramName: string, isOptional) => { - params.push({ paramName, isOptional: isOptional != null }); - return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)"; - } - ); - - if (path.endsWith("*")) { - params.push({ paramName: "*" }); - regexpSource += - path === "*" || path === "/*" - ? "(.*)$" // Already matched the initial /, just match the rest - : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"] - } else if (end) { - // When matching to the end, ignore trailing slashes - regexpSource += "\\/*$"; - } else if (path !== "" && path !== "/") { - // If our path is non-empty and contains anything beyond an initial slash, - // then we have _some_ form of path in our regex, so we should expect to - // match only if we find the end of this path segment. Look for an optional - // non-captured trailing slash (to match a portion of the URL) or the end - // of the path (if we've matched to the end). We used to do this with a - // word boundary but that gives false positives on routes like - // /user-preferences since `-` counts as a word boundary. - regexpSource += "(?:(?=\\/|$))"; - } else { - // Nothing to match for "" or "/" - } - - let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i"); - - return [matcher, params]; -} - -function decodePath(value: string) { - try { - return value - .split("/") - .map((v) => decodeURIComponent(v).replace(/\//g, "%2F")) - .join("/"); - } catch (error) { - warning( - false, - `The URL path "${value}" could not be decoded because it is is a ` + - `malformed URL segment. This is probably due to a bad percent ` + - `encoding (${error}).` - ); - - return value; - } -} - -/** - * @private - */ -export function stripBasename( - pathname: string, - basename: string -): string | null { - if (basename === "/") return pathname; - - if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) { - return null; - } - - // We want to leave trailing slash behavior in the user's control, so if they - // specify a basename with a trailing slash, we should support it - let startIndex = basename.endsWith("/") - ? basename.length - 1 - : basename.length; - let nextChar = pathname.charAt(startIndex); - if (nextChar && nextChar !== "/") { - // pathname does not start with basename/ - return null; - } - - return pathname.slice(startIndex) || "/"; -} - -/** - * Returns a resolved path object relative to the given pathname. - * - * @see https://reactrouter.com/utils/resolve-path - */ -export function resolvePath(to: To, fromPathname = "/"): Path { - let { - pathname: toPathname, - search = "", - hash = "", - } = typeof to === "string" ? parsePath(to) : to; - - let pathname = toPathname - ? toPathname.startsWith("/") - ? toPathname - : resolvePathname(toPathname, fromPathname) - : fromPathname; - - return { - pathname, - search: normalizeSearch(search), - hash: normalizeHash(hash), - }; -} - -function resolvePathname(relativePath: string, fromPathname: string): string { - let segments = fromPathname.replace(/\/+$/, "").split("/"); - let relativeSegments = relativePath.split("/"); - - relativeSegments.forEach((segment) => { - if (segment === "..") { - // Keep the root "" segment so the pathname starts at / - if (segments.length > 1) segments.pop(); - } else if (segment !== ".") { - segments.push(segment); - } - }); - - return segments.length > 1 ? segments.join("/") : "/"; -} - -function getInvalidPathError( - char: string, - field: string, - dest: string, - path: Partial -) { - return ( - `Cannot include a '${char}' character in a manually specified ` + - `\`to.${field}\` field [${JSON.stringify( - path - )}]. Please separate it out to the ` + - `\`to.${dest}\` field. Alternatively you may provide the full path as ` + - `a string in and the router will parse it for you.` - ); -} - -/** - * @private - * - * When processing relative navigation we want to ignore ancestor routes that - * do not contribute to the path, such that index/pathless layout routes don't - * interfere. - * - * For example, when moving a route element into an index route and/or a - * pathless layout route, relative link behavior contained within should stay - * the same. Both of the following examples should link back to the root: - * - * - * - * - * - * - * - * }> // <-- Does not contribute - * // <-- Does not contribute - * - * - */ -export function getPathContributingMatches< - T extends AgnosticRouteMatch = AgnosticRouteMatch ->(matches: T[]) { - return matches.filter( - (match, index) => - index === 0 || (match.route.path && match.route.path.length > 0) - ); -} - -// Return the array of pathnames for the current route matches - used to -// generate the routePathnames input for resolveTo() -export function getResolveToMatches< - T extends AgnosticRouteMatch = AgnosticRouteMatch ->(matches: T[], v7_relativeSplatPath: boolean) { - let pathMatches = getPathContributingMatches(matches); - - // When v7_relativeSplatPath is enabled, use the full pathname for the leaf - // match so we include splat values for "." links. See: - // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329 - if (v7_relativeSplatPath) { - return pathMatches.map((match, idx) => - idx === matches.length - 1 ? match.pathname : match.pathnameBase - ); - } - - return pathMatches.map((match) => match.pathnameBase); -} - -/** - * @private - */ -export function resolveTo( - toArg: To, - routePathnames: string[], - locationPathname: string, - isPathRelative = false -): Path { - let to: Partial; - if (typeof toArg === "string") { - to = parsePath(toArg); - } else { - to = { ...toArg }; - - invariant( - !to.pathname || !to.pathname.includes("?"), - getInvalidPathError("?", "pathname", "search", to) - ); - invariant( - !to.pathname || !to.pathname.includes("#"), - getInvalidPathError("#", "pathname", "hash", to) - ); - invariant( - !to.search || !to.search.includes("#"), - getInvalidPathError("#", "search", "hash", to) - ); - } - - let isEmptyPath = toArg === "" || to.pathname === ""; - let toPathname = isEmptyPath ? "/" : to.pathname; - - let from: string; - - // Routing is relative to the current pathname if explicitly requested. - // - // If a pathname is explicitly provided in `to`, it should be relative to the - // route context. This is explained in `Note on `` values` in our - // migration guide from v5 as a means of disambiguation between `to` values - // that begin with `/` and those that do not. However, this is problematic for - // `to` values that do not provide a pathname. `to` can simply be a search or - // hash string, in which case we should assume that the navigation is relative - // to the current location's pathname and *not* the route pathname. - if (toPathname == null) { - from = locationPathname; - } else { - let routePathnameIndex = routePathnames.length - 1; - - // With relative="route" (the default), each leading .. segment means - // "go up one route" instead of "go up one URL segment". This is a key - // difference from how works and a major reason we call this a - // "to" value instead of a "href". - if (!isPathRelative && toPathname.startsWith("..")) { - let toSegments = toPathname.split("/"); - - while (toSegments[0] === "..") { - toSegments.shift(); - routePathnameIndex -= 1; - } - - to.pathname = toSegments.join("/"); - } - - from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/"; - } - - let path = resolvePath(to, from); - - // Ensure the pathname has a trailing slash if the original "to" had one - let hasExplicitTrailingSlash = - toPathname && toPathname !== "/" && toPathname.endsWith("/"); - // Or if this was a link to the current path which has a trailing slash - let hasCurrentTrailingSlash = - (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/"); - if ( - !path.pathname.endsWith("/") && - (hasExplicitTrailingSlash || hasCurrentTrailingSlash) - ) { - path.pathname += "/"; - } - - return path; -} - -/** - * @private - */ -export function getToPathname(to: To): string | undefined { - // Empty strings should be treated the same as / paths - return to === "" || (to as Path).pathname === "" - ? "/" - : typeof to === "string" - ? parsePath(to).pathname - : to.pathname; -} - -/** - * @private - */ -export const joinPaths = (paths: string[]): string => - paths.join("/").replace(/\/\/+/g, "/"); - -/** - * @private - */ -export const normalizePathname = (pathname: string): string => - pathname.replace(/\/+$/, "").replace(/^\/*/, "/"); - -/** - * @private - */ -export const normalizeSearch = (search: string): string => - !search || search === "?" - ? "" - : search.startsWith("?") - ? search - : "?" + search; - -/** - * @private - */ -export const normalizeHash = (hash: string): string => - !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash; - -export type JsonFunction = ( - data: Data, - init?: number | ResponseInit -) => Response; - -/** - * This is a shortcut for creating `application/json` responses. Converts `data` - * to JSON and sets the `Content-Type` header. - */ -export const json: JsonFunction = (data, init = {}) => { - let responseInit = typeof init === "number" ? { status: init } : init; - - let headers = new Headers(responseInit.headers); - if (!headers.has("Content-Type")) { - headers.set("Content-Type", "application/json; charset=utf-8"); - } - - return new Response(JSON.stringify(data), { - ...responseInit, - headers, - }); -}; - -export interface TrackedPromise extends Promise { - _tracked?: boolean; - _data?: any; - _error?: any; -} - -export class AbortedDeferredError extends Error {} - -export class DeferredData { - private pendingKeysSet: Set = new Set(); - private controller: AbortController; - private abortPromise: Promise; - private unlistenAbortSignal: () => void; - private subscribers: Set<(aborted: boolean, settledKey?: string) => void> = - new Set(); - data: Record; - init?: ResponseInit; - deferredKeys: string[] = []; - - constructor(data: Record, responseInit?: ResponseInit) { - invariant( - data && typeof data === "object" && !Array.isArray(data), - "defer() only accepts plain objects" - ); - - // Set up an AbortController + Promise we can race against to exit early - // cancellation - let reject: (e: AbortedDeferredError) => void; - this.abortPromise = new Promise((_, r) => (reject = r)); - this.controller = new AbortController(); - let onAbort = () => - reject(new AbortedDeferredError("Deferred data aborted")); - this.unlistenAbortSignal = () => - this.controller.signal.removeEventListener("abort", onAbort); - this.controller.signal.addEventListener("abort", onAbort); - - this.data = Object.entries(data).reduce( - (acc, [key, value]) => - Object.assign(acc, { - [key]: this.trackPromise(key, value), - }), - {} - ); - - if (this.done) { - // All incoming values were resolved - this.unlistenAbortSignal(); - } - - this.init = responseInit; - } - - private trackPromise( - key: string, - value: Promise | unknown - ): TrackedPromise | unknown { - if (!(value instanceof Promise)) { - return value; - } - - this.deferredKeys.push(key); - this.pendingKeysSet.add(key); - - // We store a little wrapper promise that will be extended with - // _data/_error props upon resolve/reject - let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then( - (data) => this.onSettle(promise, key, undefined, data as unknown), - (error) => this.onSettle(promise, key, error as unknown) - ); - - // Register rejection listeners to avoid uncaught promise rejections on - // errors or aborted deferred values - promise.catch(() => {}); - - Object.defineProperty(promise, "_tracked", { get: () => true }); - return promise; - } - - private onSettle( - promise: TrackedPromise, - key: string, - error: unknown, - data?: unknown - ): unknown { - if ( - this.controller.signal.aborted && - error instanceof AbortedDeferredError - ) { - this.unlistenAbortSignal(); - Object.defineProperty(promise, "_error", { get: () => error }); - return Promise.reject(error); - } - - this.pendingKeysSet.delete(key); - - if (this.done) { - // Nothing left to abort! - this.unlistenAbortSignal(); - } - - // If the promise was resolved/rejected with undefined, we'll throw an error as you - // should always resolve with a value or null - if (error === undefined && data === undefined) { - let undefinedError = new Error( - `Deferred data for key "${key}" resolved/rejected with \`undefined\`, ` + - `you must resolve/reject with a value or \`null\`.` - ); - Object.defineProperty(promise, "_error", { get: () => undefinedError }); - this.emit(false, key); - return Promise.reject(undefinedError); - } - - if (data === undefined) { - Object.defineProperty(promise, "_error", { get: () => error }); - this.emit(false, key); - return Promise.reject(error); - } - - Object.defineProperty(promise, "_data", { get: () => data }); - this.emit(false, key); - return data; - } - - private emit(aborted: boolean, settledKey?: string) { - this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey)); - } - - subscribe(fn: (aborted: boolean, settledKey?: string) => void) { - this.subscribers.add(fn); - return () => this.subscribers.delete(fn); - } - - cancel() { - this.controller.abort(); - this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k)); - this.emit(true); - } - - async resolveData(signal: AbortSignal) { - let aborted = false; - if (!this.done) { - let onAbort = () => this.cancel(); - signal.addEventListener("abort", onAbort); - aborted = await new Promise((resolve) => { - this.subscribe((aborted) => { - signal.removeEventListener("abort", onAbort); - if (aborted || this.done) { - resolve(aborted); - } - }); - }); - } - return aborted; - } - - get done() { - return this.pendingKeysSet.size === 0; - } - - get unwrappedData() { - invariant( - this.data !== null && this.done, - "Can only unwrap data on initialized and settled deferreds" - ); - - return Object.entries(this.data).reduce( - (acc, [key, value]) => - Object.assign(acc, { - [key]: unwrapTrackedPromise(value), - }), - {} - ); - } - - get pendingKeys() { - return Array.from(this.pendingKeysSet); - } -} - -function isTrackedPromise(value: any): value is TrackedPromise { - return ( - value instanceof Promise && (value as TrackedPromise)._tracked === true - ); -} - -function unwrapTrackedPromise(value: any) { - if (!isTrackedPromise(value)) { - return value; - } - - if (value._error) { - throw value._error; - } - return value._data; -} - -export type DeferFunction = ( - data: Record, - init?: number | ResponseInit -) => DeferredData; - -export const defer: DeferFunction = (data, init = {}) => { - let responseInit = typeof init === "number" ? { status: init } : init; - - return new DeferredData(data, responseInit); -}; - -export type RedirectFunction = ( - url: string, - init?: number | ResponseInit -) => Response; - -/** - * A redirect response. Sets the status code and the `Location` header. - * Defaults to "302 Found". - */ -export const redirect: RedirectFunction = (url, init = 302) => { - let responseInit = init; - if (typeof responseInit === "number") { - responseInit = { status: responseInit }; - } else if (typeof responseInit.status === "undefined") { - responseInit.status = 302; - } - - let headers = new Headers(responseInit.headers); - headers.set("Location", url); - - return new Response(null, { - ...responseInit, - headers, - }); -}; - -/** - * A redirect response that will force a document reload to the new location. - * Sets the status code and the `Location` header. - * Defaults to "302 Found". - */ -export const redirectDocument: RedirectFunction = (url, init) => { - let response = redirect(url, init); - response.headers.set("X-Remix-Reload-Document", "true"); - return response; -}; - -export type ErrorResponse = { - status: number; - statusText: string; - data: any; -}; - -/** - * @private - * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies - * - * We don't export the class for public use since it's an implementation - * detail, but we export the interface above so folks can build their own - * abstractions around instances via isRouteErrorResponse() - */ -export class ErrorResponseImpl implements ErrorResponse { - status: number; - statusText: string; - data: any; - private error?: Error; - private internal: boolean; - - constructor( - status: number, - statusText: string | undefined, - data: any, - internal = false - ) { - this.status = status; - this.statusText = statusText || ""; - this.internal = internal; - if (data instanceof Error) { - this.data = data.toString(); - this.error = data; - } else { - this.data = data; - } - } -} - -/** - * Check if the given error is an ErrorResponse generated from a 4xx/5xx - * Response thrown from an action/loader - */ -export function isRouteErrorResponse(error: any): error is ErrorResponse { - return ( - error != null && - typeof error.status === "number" && - typeof error.statusText === "string" && - typeof error.internal === "boolean" && - "data" in error - ); -} diff --git a/node_modules/js-tokens/CHANGELOG.md b/node_modules/js-tokens/CHANGELOG.md deleted file mode 100644 index 755e6f6e..00000000 --- a/node_modules/js-tokens/CHANGELOG.md +++ /dev/null @@ -1,151 +0,0 @@ -### Version 4.0.0 (2018-01-28) ### - -- Added: Support for ES2018. The only change needed was recognizing the `s` - regex flag. -- Changed: _All_ tokens returned by the `matchToToken` function now have a - `closed` property. It is set to `undefined` for the tokens where “closed” - doesn’t make sense. This means that all tokens objects have the same shape, - which might improve performance. - -These are the breaking changes: - -- `'/a/s'.match(jsTokens)` no longer returns `['/', 'a', '/', 's']`, but - `['/a/s']`. (There are of course other variations of this.) -- Code that rely on some token objects not having the `closed` property could - now behave differently. - - -### Version 3.0.2 (2017-06-28) ### - -- No code changes. Just updates to the readme. - - -### Version 3.0.1 (2017-01-30) ### - -- Fixed: ES2015 unicode escapes with more than 6 hex digits are now matched - correctly. - - -### Version 3.0.0 (2017-01-11) ### - -This release contains one breaking change, that should [improve performance in -V8][v8-perf]: - -> So how can you, as a JavaScript developer, ensure that your RegExps are fast? -> If you are not interested in hooking into RegExp internals, make sure that -> neither the RegExp instance, nor its prototype is modified in order to get the -> best performance: -> -> ```js -> var re = /./g; -> re.exec(''); // Fast path. -> re.new_property = 'slow'; -> ``` - -This module used to export a single regex, with `.matchToToken` bolted -on, just like in the above example. This release changes the exports of -the module to avoid this issue. - -Before: - -```js -import jsTokens from "js-tokens" -// or: -var jsTokens = require("js-tokens") -var matchToToken = jsTokens.matchToToken -``` - -After: - -```js -import jsTokens, {matchToToken} from "js-tokens" -// or: -var jsTokens = require("js-tokens").default -var matchToToken = require("js-tokens").matchToToken -``` - -[v8-perf]: http://v8project.blogspot.se/2017/01/speeding-up-v8-regular-expressions.html - - -### Version 2.0.0 (2016-06-19) ### - -- Added: Support for ES2016. In other words, support for the `**` exponentiation - operator. - -These are the breaking changes: - -- `'**'.match(jsTokens)` no longer returns `['*', '*']`, but `['**']`. -- `'**='.match(jsTokens)` no longer returns `['*', '*=']`, but `['**=']`. - - -### Version 1.0.3 (2016-03-27) ### - -- Improved: Made the regex ever so slightly smaller. -- Updated: The readme. - - -### Version 1.0.2 (2015-10-18) ### - -- Improved: Limited npm package contents for a smaller download. Thanks to - @zertosh! - - -### Version 1.0.1 (2015-06-20) ### - -- Fixed: Declared an undeclared variable. - - -### Version 1.0.0 (2015-02-26) ### - -- Changed: Merged the 'operator' and 'punctuation' types into 'punctuator'. That - type is now equivalent to the Punctuator token in the ECMAScript - specification. (Backwards-incompatible change.) -- Fixed: A `-` followed by a number is now correctly matched as a punctuator - followed by a number. It used to be matched as just a number, but there is no - such thing as negative number literals. (Possibly backwards-incompatible - change.) - - -### Version 0.4.1 (2015-02-21) ### - -- Added: Support for the regex `u` flag. - - -### Version 0.4.0 (2015-02-21) ### - -- Improved: `jsTokens.matchToToken` performance. -- Added: Support for octal and binary number literals. -- Added: Support for template strings. - - -### Version 0.3.1 (2015-01-06) ### - -- Fixed: Support for unicode spaces. They used to be allowed in names (which is - very confusing), and some unicode newlines were wrongly allowed in strings and - regexes. - - -### Version 0.3.0 (2014-12-19) ### - -- Changed: The `jsTokens.names` array has been replaced with the - `jsTokens.matchToToken` function. The capturing groups of `jsTokens` are no - longer part of the public API; instead use said function. See this [gist] for - an example. (Backwards-incompatible change.) -- Changed: The empty string is now considered an “invalid” token, instead an - “empty” token (its own group). (Backwards-incompatible change.) -- Removed: component support. (Backwards-incompatible change.) - -[gist]: https://gist.github.com/lydell/be49dbf80c382c473004 - - -### Version 0.2.0 (2014-06-19) ### - -- Changed: Match ES6 function arrows (`=>`) as an operator, instead of its own - category (“functionArrow”), for simplicity. (Backwards-incompatible change.) -- Added: ES6 splats (`...`) are now matched as an operator (instead of three - punctuations). (Backwards-incompatible change.) - - -### Version 0.1.0 (2014-03-08) ### - -- Initial release. diff --git a/node_modules/js-tokens/LICENSE b/node_modules/js-tokens/LICENSE deleted file mode 100644 index 54aef52f..00000000 --- a/node_modules/js-tokens/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014, 2015, 2016, 2017, 2018 Simon Lydell - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/js-tokens/README.md b/node_modules/js-tokens/README.md deleted file mode 100644 index 00cdf163..00000000 --- a/node_modules/js-tokens/README.md +++ /dev/null @@ -1,240 +0,0 @@ -Overview [![Build Status](https://travis-ci.org/lydell/js-tokens.svg?branch=master)](https://travis-ci.org/lydell/js-tokens) -======== - -A regex that tokenizes JavaScript. - -```js -var jsTokens = require("js-tokens").default - -var jsString = "var foo=opts.foo;\n..." - -jsString.match(jsTokens) -// ["var", " ", "foo", "=", "opts", ".", "foo", ";", "\n", ...] -``` - - -Installation -============ - -`npm install js-tokens` - -```js -import jsTokens from "js-tokens" -// or: -var jsTokens = require("js-tokens").default -``` - - -Usage -===== - -### `jsTokens` ### - -A regex with the `g` flag that matches JavaScript tokens. - -The regex _always_ matches, even invalid JavaScript and the empty string. - -The next match is always directly after the previous. - -### `var token = matchToToken(match)` ### - -```js -import {matchToToken} from "js-tokens" -// or: -var matchToToken = require("js-tokens").matchToToken -``` - -Takes a `match` returned by `jsTokens.exec(string)`, and returns a `{type: -String, value: String}` object. The following types are available: - -- string -- comment -- regex -- number -- name -- punctuator -- whitespace -- invalid - -Multi-line comments and strings also have a `closed` property indicating if the -token was closed or not (see below). - -Comments and strings both come in several flavors. To distinguish them, check if -the token starts with `//`, `/*`, `'`, `"` or `` ` ``. - -Names are ECMAScript IdentifierNames, that is, including both identifiers and -keywords. You may use [is-keyword-js] to tell them apart. - -Whitespace includes both line terminators and other whitespace. - -[is-keyword-js]: https://github.com/crissdev/is-keyword-js - - -ECMAScript support -================== - -The intention is to always support the latest ECMAScript version whose feature -set has been finalized. - -If adding support for a newer version requires changes, a new version with a -major verion bump will be released. - -Currently, ECMAScript 2018 is supported. - - -Invalid code handling -===================== - -Unterminated strings are still matched as strings. JavaScript strings cannot -contain (unescaped) newlines, so unterminated strings simply end at the end of -the line. Unterminated template strings can contain unescaped newlines, though, -so they go on to the end of input. - -Unterminated multi-line comments are also still matched as comments. They -simply go on to the end of the input. - -Unterminated regex literals are likely matched as division and whatever is -inside the regex. - -Invalid ASCII characters have their own capturing group. - -Invalid non-ASCII characters are treated as names, to simplify the matching of -names (except unicode spaces which are treated as whitespace). Note: See also -the [ES2018](#es2018) section. - -Regex literals may contain invalid regex syntax. They are still matched as -regex literals. They may also contain repeated regex flags, to keep the regex -simple. - -Strings may contain invalid escape sequences. - - -Limitations -=========== - -Tokenizing JavaScript using regexes—in fact, _one single regex_—won’t be -perfect. But that’s not the point either. - -You may compare jsTokens with [esprima] by using `esprima-compare.js`. -See `npm run esprima-compare`! - -[esprima]: http://esprima.org/ - -### Template string interpolation ### - -Template strings are matched as single tokens, from the starting `` ` `` to the -ending `` ` ``, including interpolations (whose tokens are not matched -individually). - -Matching template string interpolations requires recursive balancing of `{` and -`}`—something that JavaScript regexes cannot do. Only one level of nesting is -supported. - -### Division and regex literals collision ### - -Consider this example: - -```js -var g = 9.82 -var number = bar / 2/g - -var regex = / 2/g -``` - -A human can easily understand that in the `number` line we’re dealing with -division, and in the `regex` line we’re dealing with a regex literal. How come? -Because humans can look at the whole code to put the `/` characters in context. -A JavaScript regex cannot. It only sees forwards. (Well, ES2018 regexes can also -look backwards. See the [ES2018](#es2018) section). - -When the `jsTokens` regex scans throught the above, it will see the following -at the end of both the `number` and `regex` rows: - -```js -/ 2/g -``` - -It is then impossible to know if that is a regex literal, or part of an -expression dealing with division. - -Here is a similar case: - -```js -foo /= 2/g -foo(/= 2/g) -``` - -The first line divides the `foo` variable with `2/g`. The second line calls the -`foo` function with the regex literal `/= 2/g`. Again, since `jsTokens` only -sees forwards, it cannot tell the two cases apart. - -There are some cases where we _can_ tell division and regex literals apart, -though. - -First off, we have the simple cases where there’s only one slash in the line: - -```js -var foo = 2/g -foo /= 2 -``` - -Regex literals cannot contain newlines, so the above cases are correctly -identified as division. Things are only problematic when there are more than -one non-comment slash in a single line. - -Secondly, not every character is a valid regex flag. - -```js -var number = bar / 2/e -``` - -The above example is also correctly identified as division, because `e` is not a -valid regex flag. I initially wanted to future-proof by allowing `[a-zA-Z]*` -(any letter) as flags, but it is not worth it since it increases the amount of -ambigous cases. So only the standard `g`, `m`, `i`, `y` and `u` flags are -allowed. This means that the above example will be identified as division as -long as you don’t rename the `e` variable to some permutation of `gmiyus` 1 to 6 -characters long. - -Lastly, we can look _forward_ for information. - -- If the token following what looks like a regex literal is not valid after a - regex literal, but is valid in a division expression, then the regex literal - is treated as division instead. For example, a flagless regex cannot be - followed by a string, number or name, but all of those three can be the - denominator of a division. -- Generally, if what looks like a regex literal is followed by an operator, the - regex literal is treated as division instead. This is because regexes are - seldomly used with operators (such as `+`, `*`, `&&` and `==`), but division - could likely be part of such an expression. - -Please consult the regex source and the test cases for precise information on -when regex or division is matched (should you need to know). In short, you -could sum it up as: - -If the end of a statement looks like a regex literal (even if it isn’t), it -will be treated as one. Otherwise it should work as expected (if you write sane -code). - -### ES2018 ### - -ES2018 added some nice regex improvements to the language. - -- [Unicode property escapes] should allow telling names and invalid non-ASCII - characters apart without blowing up the regex size. -- [Lookbehind assertions] should allow matching telling division and regex - literals apart in more cases. -- [Named capture groups] might simplify some things. - -These things would be nice to do, but are not critical. They probably have to -wait until the oldest maintained Node.js LTS release supports those features. - -[Unicode property escapes]: http://2ality.com/2017/07/regexp-unicode-property-escapes.html -[Lookbehind assertions]: http://2ality.com/2017/05/regexp-lookbehind-assertions.html -[Named capture groups]: http://2ality.com/2017/05/regexp-named-capture-groups.html - - -License -======= - -[MIT](LICENSE). diff --git a/node_modules/js-tokens/index.js b/node_modules/js-tokens/index.js deleted file mode 100644 index b23a4a0e..00000000 --- a/node_modules/js-tokens/index.js +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell -// License: MIT. (See LICENSE.) - -Object.defineProperty(exports, "__esModule", { - value: true -}) - -// This regex comes from regex.coffee, and is inserted here by generate-index.js -// (run `npm run build`). -exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g - -exports.matchToToken = function(match) { - var token = {type: "invalid", value: match[0], closed: undefined} - if (match[ 1]) token.type = "string" , token.closed = !!(match[3] || match[4]) - else if (match[ 5]) token.type = "comment" - else if (match[ 6]) token.type = "comment", token.closed = !!match[7] - else if (match[ 8]) token.type = "regex" - else if (match[ 9]) token.type = "number" - else if (match[10]) token.type = "name" - else if (match[11]) token.type = "punctuator" - else if (match[12]) token.type = "whitespace" - return token -} diff --git a/node_modules/js-tokens/package.json b/node_modules/js-tokens/package.json deleted file mode 100644 index 66752fab..00000000 --- a/node_modules/js-tokens/package.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "js-tokens", - "version": "4.0.0", - "author": "Simon Lydell", - "license": "MIT", - "description": "A regex that tokenizes JavaScript.", - "keywords": [ - "JavaScript", - "js", - "token", - "tokenize", - "regex" - ], - "files": [ - "index.js" - ], - "repository": "lydell/js-tokens", - "scripts": { - "test": "mocha --ui tdd", - "esprima-compare": "node esprima-compare ./index.js everything.js/es5.js", - "build": "node generate-index.js", - "dev": "npm run build && npm test" - }, - "devDependencies": { - "coffeescript": "2.1.1", - "esprima": "4.0.0", - "everything.js": "1.0.3", - "mocha": "5.0.0" - } -} diff --git a/node_modules/loose-envify/LICENSE b/node_modules/loose-envify/LICENSE deleted file mode 100644 index fbafb487..00000000 --- a/node_modules/loose-envify/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Andres Suarez - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/loose-envify/README.md b/node_modules/loose-envify/README.md deleted file mode 100644 index 7f4e07b0..00000000 --- a/node_modules/loose-envify/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# loose-envify - -[![Build Status](https://travis-ci.org/zertosh/loose-envify.svg?branch=master)](https://travis-ci.org/zertosh/loose-envify) - -Fast (and loose) selective `process.env` replacer using [js-tokens](https://github.com/lydell/js-tokens) instead of an AST. Works just like [envify](https://github.com/hughsk/envify) but much faster. - -## Gotchas - -* Doesn't handle broken syntax. -* Doesn't look inside embedded expressions in template strings. - - **this won't work:** - ```js - console.log(`the current env is ${process.env.NODE_ENV}`); - ``` -* Doesn't replace oddly-spaced or oddly-commented expressions. - - **this won't work:** - ```js - console.log(process./*won't*/env./*work*/NODE_ENV); - ``` - -## Usage/Options - -loose-envify has the exact same interface as [envify](https://github.com/hughsk/envify), including the CLI. - -## Benchmark - -``` -envify: - - $ for i in {1..5}; do node bench/bench.js 'envify'; done - 708ms - 727ms - 791ms - 719ms - 720ms - -loose-envify: - - $ for i in {1..5}; do node bench/bench.js '../'; done - 51ms - 52ms - 52ms - 52ms - 52ms -``` diff --git a/node_modules/loose-envify/cli.js b/node_modules/loose-envify/cli.js deleted file mode 100644 index c0b63cb1..00000000 --- a/node_modules/loose-envify/cli.js +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env node -'use strict'; - -var looseEnvify = require('./'); -var fs = require('fs'); - -if (process.argv[2]) { - fs.createReadStream(process.argv[2], {encoding: 'utf8'}) - .pipe(looseEnvify(process.argv[2])) - .pipe(process.stdout); -} else { - process.stdin.resume() - process.stdin - .pipe(looseEnvify(__filename)) - .pipe(process.stdout); -} diff --git a/node_modules/loose-envify/custom.js b/node_modules/loose-envify/custom.js deleted file mode 100644 index 6389bfac..00000000 --- a/node_modules/loose-envify/custom.js +++ /dev/null @@ -1,4 +0,0 @@ -// envify compatibility -'use strict'; - -module.exports = require('./loose-envify'); diff --git a/node_modules/loose-envify/index.js b/node_modules/loose-envify/index.js deleted file mode 100644 index 8cd8305d..00000000 --- a/node_modules/loose-envify/index.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('./loose-envify')(process.env); diff --git a/node_modules/loose-envify/loose-envify.js b/node_modules/loose-envify/loose-envify.js deleted file mode 100644 index b5a5be22..00000000 --- a/node_modules/loose-envify/loose-envify.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -var stream = require('stream'); -var util = require('util'); -var replace = require('./replace'); - -var jsonExtRe = /\.json$/; - -module.exports = function(rootEnv) { - rootEnv = rootEnv || process.env; - return function (file, trOpts) { - if (jsonExtRe.test(file)) { - return stream.PassThrough(); - } - var envs = trOpts ? [rootEnv, trOpts] : [rootEnv]; - return new LooseEnvify(envs); - }; -}; - -function LooseEnvify(envs) { - stream.Transform.call(this); - this._data = ''; - this._envs = envs; -} -util.inherits(LooseEnvify, stream.Transform); - -LooseEnvify.prototype._transform = function(buf, enc, cb) { - this._data += buf; - cb(); -}; - -LooseEnvify.prototype._flush = function(cb) { - var replaced = replace(this._data, this._envs); - this.push(replaced); - cb(); -}; diff --git a/node_modules/loose-envify/package.json b/node_modules/loose-envify/package.json deleted file mode 100644 index 5e3d0e27..00000000 --- a/node_modules/loose-envify/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "loose-envify", - "version": "1.4.0", - "description": "Fast (and loose) selective `process.env` replacer using js-tokens instead of an AST", - "keywords": [ - "environment", - "variables", - "browserify", - "browserify-transform", - "transform", - "source", - "configuration" - ], - "homepage": "https://github.com/zertosh/loose-envify", - "license": "MIT", - "author": "Andres Suarez ", - "main": "index.js", - "bin": { - "loose-envify": "cli.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/zertosh/loose-envify.git" - }, - "scripts": { - "test": "tap test/*.js" - }, - "dependencies": { - "js-tokens": "^3.0.0 || ^4.0.0" - }, - "devDependencies": { - "browserify": "^13.1.1", - "envify": "^3.4.0", - "tap": "^8.0.0" - } -} diff --git a/node_modules/loose-envify/replace.js b/node_modules/loose-envify/replace.js deleted file mode 100644 index ec15e81c..00000000 --- a/node_modules/loose-envify/replace.js +++ /dev/null @@ -1,65 +0,0 @@ -'use strict'; - -var jsTokens = require('js-tokens').default; - -var processEnvRe = /\bprocess\.env\.[_$a-zA-Z][$\w]+\b/; -var spaceOrCommentRe = /^(?:\s|\/[/*])/; - -function replace(src, envs) { - if (!processEnvRe.test(src)) { - return src; - } - - var out = []; - var purge = envs.some(function(env) { - return env._ && env._.indexOf('purge') !== -1; - }); - - jsTokens.lastIndex = 0 - var parts = src.match(jsTokens); - - for (var i = 0; i < parts.length; i++) { - if (parts[i ] === 'process' && - parts[i + 1] === '.' && - parts[i + 2] === 'env' && - parts[i + 3] === '.') { - var prevCodeToken = getAdjacentCodeToken(-1, parts, i); - var nextCodeToken = getAdjacentCodeToken(1, parts, i + 4); - var replacement = getReplacementString(envs, parts[i + 4], purge); - if (prevCodeToken !== '.' && - nextCodeToken !== '.' && - nextCodeToken !== '=' && - typeof replacement === 'string') { - out.push(replacement); - i += 4; - continue; - } - } - out.push(parts[i]); - } - - return out.join(''); -} - -function getAdjacentCodeToken(dir, parts, i) { - while (true) { - var part = parts[i += dir]; - if (!spaceOrCommentRe.test(part)) { - return part; - } - } -} - -function getReplacementString(envs, name, purge) { - for (var j = 0; j < envs.length; j++) { - var env = envs[j]; - if (typeof env[name] !== 'undefined') { - return JSON.stringify(env[name]); - } - } - if (purge) { - return 'undefined'; - } -} - -module.exports = replace; diff --git a/node_modules/react-dom/LICENSE b/node_modules/react-dom/LICENSE deleted file mode 100644 index b96dcb04..00000000 --- a/node_modules/react-dom/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) Facebook, Inc. and its affiliates. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/node_modules/react-dom/README.md b/node_modules/react-dom/README.md deleted file mode 100644 index ecba5cfb..00000000 --- a/node_modules/react-dom/README.md +++ /dev/null @@ -1,60 +0,0 @@ -# `react-dom` - -This package serves as the entry point to the DOM and server renderers for React. It is intended to be paired with the generic React package, which is shipped as `react` to npm. - -## Installation - -```sh -npm install react react-dom -``` - -## Usage - -### In the browser - -```js -import { createRoot } from 'react-dom/client'; - -function App() { - return
Hello World
; -} - -const root = createRoot(document.getElementById('root')); -root.render(); -``` - -### On the server - -```js -import { renderToPipeableStream } from 'react-dom/server'; - -function App() { - return
Hello World
; -} - -function handleRequest(res) { - // ... in your server handler ... - const stream = renderToPipeableStream(, { - onShellReady() { - res.statusCode = 200; - res.setHeader('Content-type', 'text/html'); - stream.pipe(res); - }, - // ... - }); -} -``` - -## API - -### `react-dom` - -See https://reactjs.org/docs/react-dom.html - -### `react-dom/client` - -See https://reactjs.org/docs/react-dom-client.html - -### `react-dom/server` - -See https://reactjs.org/docs/react-dom-server.html diff --git a/node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js b/node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js deleted file mode 100644 index 102e3ef6..00000000 --- a/node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js +++ /dev/null @@ -1,7029 +0,0 @@ -/** - * @license React - * react-dom-server-legacy.browser.development.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -'use strict'; - -if (process.env.NODE_ENV !== "production") { - (function() { -'use strict'; - -var React = require('react'); - -var ReactVersion = '18.3.1'; - -var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - -// by calls to these methods by a Babel plugin. -// -// In PROD (or in packages without access to React internals), -// they are left as they are instead. - -function warn(format) { - { - { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - printWarning('warn', format, args); - } - } -} -function error(format) { - { - { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - - printWarning('error', format, args); - } - } -} - -function printWarning(level, format, args) { - // When changing this logic, you might want to also - // update consoleWithStackDev.www.js as well. - { - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame.getStackAddendum(); - - if (stack !== '') { - format += '%s'; - args = args.concat([stack]); - } // eslint-disable-next-line react-internal/safe-string-coercion - - - var argsWithFormat = args.map(function (item) { - return String(item); - }); // Careful: RN currently depends on this prefix - - argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it - // breaks IE9: https://github.com/facebook/react/issues/13610 - // eslint-disable-next-line react-internal/no-production-logging - - Function.prototype.apply.call(console[level], console, argsWithFormat); - } -} - -function scheduleWork(callback) { - callback(); -} -function beginWriting(destination) {} -function writeChunk(destination, chunk) { - writeChunkAndReturn(destination, chunk); -} -function writeChunkAndReturn(destination, chunk) { - return destination.push(chunk); -} -function completeWriting(destination) {} -function close(destination) { - destination.push(null); -} -function stringToChunk(content) { - return content; -} -function stringToPrecomputedChunk(content) { - return content; -} -function closeWithError(destination, error) { - // $FlowFixMe: This is an Error object or the destination accepts other types. - destination.destroy(error); -} - -/* - * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol - * and Temporal.* types. See https://github.com/facebook/react/pull/22064. - * - * The functions in this module will throw an easier-to-understand, - * easier-to-debug exception with a clear errors message message explaining the - * problem. (Instead of a confusing exception thrown inside the implementation - * of the `value` object). - */ -// $FlowFixMe only called in DEV, so void return is not possible. -function typeName(value) { - { - // toStringTag is needed for namespaced types like Temporal.Instant - var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; - var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; - return type; - } -} // $FlowFixMe only called in DEV, so void return is not possible. - - -function willCoercionThrow(value) { - { - try { - testStringCoercion(value); - return false; - } catch (e) { - return true; - } - } -} - -function testStringCoercion(value) { - // If you ended up here by following an exception call stack, here's what's - // happened: you supplied an object or symbol value to React (as a prop, key, - // DOM attribute, CSS property, string ref, etc.) and when React tried to - // coerce it to a string using `'' + value`, an exception was thrown. - // - // The most common types that will cause this exception are `Symbol` instances - // and Temporal objects like `Temporal.Instant`. But any object that has a - // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this - // exception. (Library authors do this to prevent users from using built-in - // numeric operators like `+` or comparison operators like `>=` because custom - // methods are needed to perform accurate arithmetic or comparison.) - // - // To fix the problem, coerce this object or symbol value to a string before - // passing it to React. The most reliable way is usually `String(value)`. - // - // To find which value is throwing, check the browser or debugger console. - // Before this exception was thrown, there should be `console.error` output - // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the - // problem and how that type was used: key, atrribute, input value prop, etc. - // In most cases, this console output also shows the component and its - // ancestor components where the exception happened. - // - // eslint-disable-next-line react-internal/safe-string-coercion - return '' + value; -} - -function checkAttributeStringCoercion(value, attributeName) { - { - if (willCoercionThrow(value)) { - error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', attributeName, typeName(value)); - - return testStringCoercion(value); // throw (to help callers find troubleshooting comments) - } - } -} -function checkCSSPropertyStringCoercion(value, propName) { - { - if (willCoercionThrow(value)) { - error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value)); - - return testStringCoercion(value); // throw (to help callers find troubleshooting comments) - } - } -} -function checkHtmlStringCoercion(value) { - { - if (willCoercionThrow(value)) { - error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); - - return testStringCoercion(value); // throw (to help callers find troubleshooting comments) - } - } -} - -var hasOwnProperty = Object.prototype.hasOwnProperty; - -// A reserved attribute. -// It is handled by React separately and shouldn't be written to the DOM. -var RESERVED = 0; // A simple string attribute. -// Attributes that aren't in the filter are presumed to have this type. - -var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called -// "enumerated" attributes with "true" and "false" as possible values. -// When true, it should be set to a "true" string. -// When false, it should be set to a "false" string. - -var BOOLEANISH_STRING = 2; // A real boolean attribute. -// When true, it should be present (set either to an empty string or its name). -// When false, it should be omitted. - -var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value. -// When true, it should be present (set either to an empty string or its name). -// When false, it should be omitted. -// For any other value, should be present with that value. - -var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric. -// When falsy, it should be removed. - -var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric. -// When falsy, it should be removed. - -var POSITIVE_NUMERIC = 6; - -/* eslint-disable max-len */ -var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; -/* eslint-enable max-len */ - -var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; -var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$'); -var illegalAttributeNameCache = {}; -var validatedAttributeNameCache = {}; -function isAttributeNameSafe(attributeName) { - if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) { - return true; - } - - if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) { - return false; - } - - if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { - validatedAttributeNameCache[attributeName] = true; - return true; - } - - illegalAttributeNameCache[attributeName] = true; - - { - error('Invalid attribute name: `%s`', attributeName); - } - - return false; -} -function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { - if (propertyInfo !== null && propertyInfo.type === RESERVED) { - return false; - } - - switch (typeof value) { - case 'function': // $FlowIssue symbol is perfectly valid here - - case 'symbol': - // eslint-disable-line - return true; - - case 'boolean': - { - if (isCustomComponentTag) { - return false; - } - - if (propertyInfo !== null) { - return !propertyInfo.acceptsBooleans; - } else { - var prefix = name.toLowerCase().slice(0, 5); - return prefix !== 'data-' && prefix !== 'aria-'; - } - } - - default: - return false; - } -} -function getPropertyInfo(name) { - return properties.hasOwnProperty(name) ? properties[name] : null; -} - -function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) { - this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; - this.attributeName = attributeName; - this.attributeNamespace = attributeNamespace; - this.mustUseProperty = mustUseProperty; - this.propertyName = name; - this.type = type; - this.sanitizeURL = sanitizeURL; - this.removeEmptyString = removeEmptyString; -} // When adding attributes to this list, be sure to also add them to -// the `possibleStandardNames` module to ensure casing and incorrect -// name warnings. - - -var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM. - -var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular -// elements (not just inputs). Now that ReactDOMInput assigns to the -// defaultValue property -- do we need this? -'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style']; - -reservedProps.forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty - name, // attributeName - null, // attributeNamespace - false, // sanitizeURL - false); -}); // A few React string attributes have a different name. -// This is a mapping from React prop names to the attribute names. - -[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) { - var name = _ref[0], - attributeName = _ref[1]; - properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty - attributeName, // attributeName - null, // attributeNamespace - false, // sanitizeURL - false); -}); // These are "enumerated" HTML attributes that accept "true" and "false". -// In React, we let users pass `true` and `false` even though technically -// these aren't boolean attributes (they are coerced to strings). - -['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty - name.toLowerCase(), // attributeName - null, // attributeNamespace - false, // sanitizeURL - false); -}); // These are "enumerated" SVG attributes that accept "true" and "false". -// In React, we let users pass `true` and `false` even though technically -// these aren't boolean attributes (they are coerced to strings). -// Since these are SVG attributes, their attribute names are case-sensitive. - -['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty - name, // attributeName - null, // attributeNamespace - false, // sanitizeURL - false); -}); // These are HTML boolean attributes. - -['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM -// on the client side because the browsers are inconsistent. Instead we call focus(). -'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata -'itemScope'].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty - name.toLowerCase(), // attributeName - null, // attributeNamespace - false, // sanitizeURL - false); -}); // These are the few React props that we set as DOM properties -// rather than attributes. These are all booleans. - -['checked', // Note: `option.selected` is not updated if `select.multiple` is -// disabled with `removeAttribute`. We have special logic for handling this. -'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list, -// you'll need to set attributeName to name.toLowerCase() -// instead in the assignment below. -].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty - name, // attributeName - null, // attributeNamespace - false, // sanitizeURL - false); -}); // These are HTML attributes that are "overloaded booleans": they behave like -// booleans, but can also accept a string value. - -['capture', 'download' // NOTE: if you add a camelCased prop to this list, -// you'll need to set attributeName to name.toLowerCase() -// instead in the assignment below. -].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty - name, // attributeName - null, // attributeNamespace - false, // sanitizeURL - false); -}); // These are HTML attributes that must be positive numbers. - -['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list, -// you'll need to set attributeName to name.toLowerCase() -// instead in the assignment below. -].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty - name, // attributeName - null, // attributeNamespace - false, // sanitizeURL - false); -}); // These are HTML attributes that must be numbers. - -['rowSpan', 'start'].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty - name.toLowerCase(), // attributeName - null, // attributeNamespace - false, // sanitizeURL - false); -}); -var CAMELIZE = /[\-\:]([a-z])/g; - -var capitalize = function (token) { - return token[1].toUpperCase(); -}; // This is a list of all SVG attributes that need special casing, namespacing, -// or boolean value assignment. Regular attributes that just accept strings -// and have the same names are omitted, just like in the HTML attribute filter. -// Some of these attributes can be hard to find. This list was created by -// scraping the MDN documentation. - - -['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list, -// you'll need to set attributeName to name.toLowerCase() -// instead in the assignment below. -].forEach(function (attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty - attributeName, null, // attributeNamespace - false, // sanitizeURL - false); -}); // String SVG attributes with the xlink namespace. - -['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list, -// you'll need to set attributeName to name.toLowerCase() -// instead in the assignment below. -].forEach(function (attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty - attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL - false); -}); // String SVG attributes with the xml namespace. - -['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list, -// you'll need to set attributeName to name.toLowerCase() -// instead in the assignment below. -].forEach(function (attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty - attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL - false); -}); // These attribute exists both in HTML and SVG. -// The attribute name is case-sensitive in SVG so we can't just use -// the React name like we do for attributes that exist only in HTML. - -['tabIndex', 'crossOrigin'].forEach(function (attributeName) { - properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty - attributeName.toLowerCase(), // attributeName - null, // attributeNamespace - false, // sanitizeURL - false); -}); // These attributes accept URLs. These must not allow javascript: URLS. -// These will also need to accept Trusted Types object in the future. - -var xlinkHref = 'xlinkHref'; -properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty -'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL -false); -['src', 'href', 'action', 'formAction'].forEach(function (attributeName) { - properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty - attributeName.toLowerCase(), // attributeName - null, // attributeNamespace - true, // sanitizeURL - true); -}); - -/** - * CSS properties which accept numbers but are not in units of "px". - */ -var isUnitlessNumber = { - animationIterationCount: true, - aspectRatio: true, - borderImageOutset: true, - borderImageSlice: true, - borderImageWidth: true, - boxFlex: true, - boxFlexGroup: true, - boxOrdinalGroup: true, - columnCount: true, - columns: true, - flex: true, - flexGrow: true, - flexPositive: true, - flexShrink: true, - flexNegative: true, - flexOrder: true, - gridArea: true, - gridRow: true, - gridRowEnd: true, - gridRowSpan: true, - gridRowStart: true, - gridColumn: true, - gridColumnEnd: true, - gridColumnSpan: true, - gridColumnStart: true, - fontWeight: true, - lineClamp: true, - lineHeight: true, - opacity: true, - order: true, - orphans: true, - tabSize: true, - widows: true, - zIndex: true, - zoom: true, - // SVG-related properties - fillOpacity: true, - floodOpacity: true, - stopOpacity: true, - strokeDasharray: true, - strokeDashoffset: true, - strokeMiterlimit: true, - strokeOpacity: true, - strokeWidth: true -}; -/** - * @param {string} prefix vendor-specific prefix, eg: Webkit - * @param {string} key style name, eg: transitionDuration - * @return {string} style name prefixed with `prefix`, properly camelCased, eg: - * WebkitTransitionDuration - */ - -function prefixKey(prefix, key) { - return prefix + key.charAt(0).toUpperCase() + key.substring(1); -} -/** - * Support style names that may come passed in prefixed by adding permutations - * of vendor prefixes. - */ - - -var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an -// infinite loop, because it iterates over the newly added props too. - -Object.keys(isUnitlessNumber).forEach(function (prop) { - prefixes.forEach(function (prefix) { - isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; - }); -}); - -var hasReadOnlyValue = { - button: true, - checkbox: true, - image: true, - hidden: true, - radio: true, - reset: true, - submit: true -}; -function checkControlledValueProps(tagName, props) { - { - if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { - error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); - } - - if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { - error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); - } - } -} - -function isCustomComponent(tagName, props) { - if (tagName.indexOf('-') === -1) { - return typeof props.is === 'string'; - } - - switch (tagName) { - // These are reserved SVG and MathML elements. - // We don't mind this list too much because we expect it to never grow. - // The alternative is to track the namespace in a few places which is convoluted. - // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts - case 'annotation-xml': - case 'color-profile': - case 'font-face': - case 'font-face-src': - case 'font-face-uri': - case 'font-face-format': - case 'font-face-name': - case 'missing-glyph': - return false; - - default: - return true; - } -} - -var ariaProperties = { - 'aria-current': 0, - // state - 'aria-description': 0, - 'aria-details': 0, - 'aria-disabled': 0, - // state - 'aria-hidden': 0, - // state - 'aria-invalid': 0, - // state - 'aria-keyshortcuts': 0, - 'aria-label': 0, - 'aria-roledescription': 0, - // Widget Attributes - 'aria-autocomplete': 0, - 'aria-checked': 0, - 'aria-expanded': 0, - 'aria-haspopup': 0, - 'aria-level': 0, - 'aria-modal': 0, - 'aria-multiline': 0, - 'aria-multiselectable': 0, - 'aria-orientation': 0, - 'aria-placeholder': 0, - 'aria-pressed': 0, - 'aria-readonly': 0, - 'aria-required': 0, - 'aria-selected': 0, - 'aria-sort': 0, - 'aria-valuemax': 0, - 'aria-valuemin': 0, - 'aria-valuenow': 0, - 'aria-valuetext': 0, - // Live Region Attributes - 'aria-atomic': 0, - 'aria-busy': 0, - 'aria-live': 0, - 'aria-relevant': 0, - // Drag-and-Drop Attributes - 'aria-dropeffect': 0, - 'aria-grabbed': 0, - // Relationship Attributes - 'aria-activedescendant': 0, - 'aria-colcount': 0, - 'aria-colindex': 0, - 'aria-colspan': 0, - 'aria-controls': 0, - 'aria-describedby': 0, - 'aria-errormessage': 0, - 'aria-flowto': 0, - 'aria-labelledby': 0, - 'aria-owns': 0, - 'aria-posinset': 0, - 'aria-rowcount': 0, - 'aria-rowindex': 0, - 'aria-rowspan': 0, - 'aria-setsize': 0 -}; - -var warnedProperties = {}; -var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$'); -var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$'); - -function validateProperty(tagName, name) { - { - if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) { - return true; - } - - if (rARIACamel.test(name)) { - var ariaName = 'aria-' + name.slice(4).toLowerCase(); - var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM - // DOM properties, then it is an invalid aria-* attribute. - - if (correctName == null) { - error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name); - - warnedProperties[name] = true; - return true; - } // aria-* attributes should be lowercase; suggest the lowercase version. - - - if (name !== correctName) { - error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName); - - warnedProperties[name] = true; - return true; - } - } - - if (rARIA.test(name)) { - var lowerCasedName = name.toLowerCase(); - var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM - // DOM properties, then it is an invalid aria-* attribute. - - if (standardName == null) { - warnedProperties[name] = true; - return false; - } // aria-* attributes should be lowercase; suggest the lowercase version. - - - if (name !== standardName) { - error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName); - - warnedProperties[name] = true; - return true; - } - } - } - - return true; -} - -function warnInvalidARIAProps(type, props) { - { - var invalidProps = []; - - for (var key in props) { - var isValid = validateProperty(type, key); - - if (!isValid) { - invalidProps.push(key); - } - } - - var unknownPropString = invalidProps.map(function (prop) { - return '`' + prop + '`'; - }).join(', '); - - if (invalidProps.length === 1) { - error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type); - } else if (invalidProps.length > 1) { - error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type); - } - } -} - -function validateProperties(type, props) { - if (isCustomComponent(type, props)) { - return; - } - - warnInvalidARIAProps(type, props); -} - -var didWarnValueNull = false; -function validateProperties$1(type, props) { - { - if (type !== 'input' && type !== 'textarea' && type !== 'select') { - return; - } - - if (props != null && props.value === null && !didWarnValueNull) { - didWarnValueNull = true; - - if (type === 'select' && props.multiple) { - error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type); - } else { - error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type); - } - } - } -} - -// When adding attributes to the HTML or SVG allowed attribute list, be sure to -// also add them to this module to ensure casing and incorrect name -// warnings. -var possibleStandardNames = { - // HTML - accept: 'accept', - acceptcharset: 'acceptCharset', - 'accept-charset': 'acceptCharset', - accesskey: 'accessKey', - action: 'action', - allowfullscreen: 'allowFullScreen', - alt: 'alt', - as: 'as', - async: 'async', - autocapitalize: 'autoCapitalize', - autocomplete: 'autoComplete', - autocorrect: 'autoCorrect', - autofocus: 'autoFocus', - autoplay: 'autoPlay', - autosave: 'autoSave', - capture: 'capture', - cellpadding: 'cellPadding', - cellspacing: 'cellSpacing', - challenge: 'challenge', - charset: 'charSet', - checked: 'checked', - children: 'children', - cite: 'cite', - class: 'className', - classid: 'classID', - classname: 'className', - cols: 'cols', - colspan: 'colSpan', - content: 'content', - contenteditable: 'contentEditable', - contextmenu: 'contextMenu', - controls: 'controls', - controlslist: 'controlsList', - coords: 'coords', - crossorigin: 'crossOrigin', - dangerouslysetinnerhtml: 'dangerouslySetInnerHTML', - data: 'data', - datetime: 'dateTime', - default: 'default', - defaultchecked: 'defaultChecked', - defaultvalue: 'defaultValue', - defer: 'defer', - dir: 'dir', - disabled: 'disabled', - disablepictureinpicture: 'disablePictureInPicture', - disableremoteplayback: 'disableRemotePlayback', - download: 'download', - draggable: 'draggable', - enctype: 'encType', - enterkeyhint: 'enterKeyHint', - for: 'htmlFor', - form: 'form', - formmethod: 'formMethod', - formaction: 'formAction', - formenctype: 'formEncType', - formnovalidate: 'formNoValidate', - formtarget: 'formTarget', - frameborder: 'frameBorder', - headers: 'headers', - height: 'height', - hidden: 'hidden', - high: 'high', - href: 'href', - hreflang: 'hrefLang', - htmlfor: 'htmlFor', - httpequiv: 'httpEquiv', - 'http-equiv': 'httpEquiv', - icon: 'icon', - id: 'id', - imagesizes: 'imageSizes', - imagesrcset: 'imageSrcSet', - innerhtml: 'innerHTML', - inputmode: 'inputMode', - integrity: 'integrity', - is: 'is', - itemid: 'itemID', - itemprop: 'itemProp', - itemref: 'itemRef', - itemscope: 'itemScope', - itemtype: 'itemType', - keyparams: 'keyParams', - keytype: 'keyType', - kind: 'kind', - label: 'label', - lang: 'lang', - list: 'list', - loop: 'loop', - low: 'low', - manifest: 'manifest', - marginwidth: 'marginWidth', - marginheight: 'marginHeight', - max: 'max', - maxlength: 'maxLength', - media: 'media', - mediagroup: 'mediaGroup', - method: 'method', - min: 'min', - minlength: 'minLength', - multiple: 'multiple', - muted: 'muted', - name: 'name', - nomodule: 'noModule', - nonce: 'nonce', - novalidate: 'noValidate', - open: 'open', - optimum: 'optimum', - pattern: 'pattern', - placeholder: 'placeholder', - playsinline: 'playsInline', - poster: 'poster', - preload: 'preload', - profile: 'profile', - radiogroup: 'radioGroup', - readonly: 'readOnly', - referrerpolicy: 'referrerPolicy', - rel: 'rel', - required: 'required', - reversed: 'reversed', - role: 'role', - rows: 'rows', - rowspan: 'rowSpan', - sandbox: 'sandbox', - scope: 'scope', - scoped: 'scoped', - scrolling: 'scrolling', - seamless: 'seamless', - selected: 'selected', - shape: 'shape', - size: 'size', - sizes: 'sizes', - span: 'span', - spellcheck: 'spellCheck', - src: 'src', - srcdoc: 'srcDoc', - srclang: 'srcLang', - srcset: 'srcSet', - start: 'start', - step: 'step', - style: 'style', - summary: 'summary', - tabindex: 'tabIndex', - target: 'target', - title: 'title', - type: 'type', - usemap: 'useMap', - value: 'value', - width: 'width', - wmode: 'wmode', - wrap: 'wrap', - // SVG - about: 'about', - accentheight: 'accentHeight', - 'accent-height': 'accentHeight', - accumulate: 'accumulate', - additive: 'additive', - alignmentbaseline: 'alignmentBaseline', - 'alignment-baseline': 'alignmentBaseline', - allowreorder: 'allowReorder', - alphabetic: 'alphabetic', - amplitude: 'amplitude', - arabicform: 'arabicForm', - 'arabic-form': 'arabicForm', - ascent: 'ascent', - attributename: 'attributeName', - attributetype: 'attributeType', - autoreverse: 'autoReverse', - azimuth: 'azimuth', - basefrequency: 'baseFrequency', - baselineshift: 'baselineShift', - 'baseline-shift': 'baselineShift', - baseprofile: 'baseProfile', - bbox: 'bbox', - begin: 'begin', - bias: 'bias', - by: 'by', - calcmode: 'calcMode', - capheight: 'capHeight', - 'cap-height': 'capHeight', - clip: 'clip', - clippath: 'clipPath', - 'clip-path': 'clipPath', - clippathunits: 'clipPathUnits', - cliprule: 'clipRule', - 'clip-rule': 'clipRule', - color: 'color', - colorinterpolation: 'colorInterpolation', - 'color-interpolation': 'colorInterpolation', - colorinterpolationfilters: 'colorInterpolationFilters', - 'color-interpolation-filters': 'colorInterpolationFilters', - colorprofile: 'colorProfile', - 'color-profile': 'colorProfile', - colorrendering: 'colorRendering', - 'color-rendering': 'colorRendering', - contentscripttype: 'contentScriptType', - contentstyletype: 'contentStyleType', - cursor: 'cursor', - cx: 'cx', - cy: 'cy', - d: 'd', - datatype: 'datatype', - decelerate: 'decelerate', - descent: 'descent', - diffuseconstant: 'diffuseConstant', - direction: 'direction', - display: 'display', - divisor: 'divisor', - dominantbaseline: 'dominantBaseline', - 'dominant-baseline': 'dominantBaseline', - dur: 'dur', - dx: 'dx', - dy: 'dy', - edgemode: 'edgeMode', - elevation: 'elevation', - enablebackground: 'enableBackground', - 'enable-background': 'enableBackground', - end: 'end', - exponent: 'exponent', - externalresourcesrequired: 'externalResourcesRequired', - fill: 'fill', - fillopacity: 'fillOpacity', - 'fill-opacity': 'fillOpacity', - fillrule: 'fillRule', - 'fill-rule': 'fillRule', - filter: 'filter', - filterres: 'filterRes', - filterunits: 'filterUnits', - floodopacity: 'floodOpacity', - 'flood-opacity': 'floodOpacity', - floodcolor: 'floodColor', - 'flood-color': 'floodColor', - focusable: 'focusable', - fontfamily: 'fontFamily', - 'font-family': 'fontFamily', - fontsize: 'fontSize', - 'font-size': 'fontSize', - fontsizeadjust: 'fontSizeAdjust', - 'font-size-adjust': 'fontSizeAdjust', - fontstretch: 'fontStretch', - 'font-stretch': 'fontStretch', - fontstyle: 'fontStyle', - 'font-style': 'fontStyle', - fontvariant: 'fontVariant', - 'font-variant': 'fontVariant', - fontweight: 'fontWeight', - 'font-weight': 'fontWeight', - format: 'format', - from: 'from', - fx: 'fx', - fy: 'fy', - g1: 'g1', - g2: 'g2', - glyphname: 'glyphName', - 'glyph-name': 'glyphName', - glyphorientationhorizontal: 'glyphOrientationHorizontal', - 'glyph-orientation-horizontal': 'glyphOrientationHorizontal', - glyphorientationvertical: 'glyphOrientationVertical', - 'glyph-orientation-vertical': 'glyphOrientationVertical', - glyphref: 'glyphRef', - gradienttransform: 'gradientTransform', - gradientunits: 'gradientUnits', - hanging: 'hanging', - horizadvx: 'horizAdvX', - 'horiz-adv-x': 'horizAdvX', - horizoriginx: 'horizOriginX', - 'horiz-origin-x': 'horizOriginX', - ideographic: 'ideographic', - imagerendering: 'imageRendering', - 'image-rendering': 'imageRendering', - in2: 'in2', - in: 'in', - inlist: 'inlist', - intercept: 'intercept', - k1: 'k1', - k2: 'k2', - k3: 'k3', - k4: 'k4', - k: 'k', - kernelmatrix: 'kernelMatrix', - kernelunitlength: 'kernelUnitLength', - kerning: 'kerning', - keypoints: 'keyPoints', - keysplines: 'keySplines', - keytimes: 'keyTimes', - lengthadjust: 'lengthAdjust', - letterspacing: 'letterSpacing', - 'letter-spacing': 'letterSpacing', - lightingcolor: 'lightingColor', - 'lighting-color': 'lightingColor', - limitingconeangle: 'limitingConeAngle', - local: 'local', - markerend: 'markerEnd', - 'marker-end': 'markerEnd', - markerheight: 'markerHeight', - markermid: 'markerMid', - 'marker-mid': 'markerMid', - markerstart: 'markerStart', - 'marker-start': 'markerStart', - markerunits: 'markerUnits', - markerwidth: 'markerWidth', - mask: 'mask', - maskcontentunits: 'maskContentUnits', - maskunits: 'maskUnits', - mathematical: 'mathematical', - mode: 'mode', - numoctaves: 'numOctaves', - offset: 'offset', - opacity: 'opacity', - operator: 'operator', - order: 'order', - orient: 'orient', - orientation: 'orientation', - origin: 'origin', - overflow: 'overflow', - overlineposition: 'overlinePosition', - 'overline-position': 'overlinePosition', - overlinethickness: 'overlineThickness', - 'overline-thickness': 'overlineThickness', - paintorder: 'paintOrder', - 'paint-order': 'paintOrder', - panose1: 'panose1', - 'panose-1': 'panose1', - pathlength: 'pathLength', - patterncontentunits: 'patternContentUnits', - patterntransform: 'patternTransform', - patternunits: 'patternUnits', - pointerevents: 'pointerEvents', - 'pointer-events': 'pointerEvents', - points: 'points', - pointsatx: 'pointsAtX', - pointsaty: 'pointsAtY', - pointsatz: 'pointsAtZ', - prefix: 'prefix', - preservealpha: 'preserveAlpha', - preserveaspectratio: 'preserveAspectRatio', - primitiveunits: 'primitiveUnits', - property: 'property', - r: 'r', - radius: 'radius', - refx: 'refX', - refy: 'refY', - renderingintent: 'renderingIntent', - 'rendering-intent': 'renderingIntent', - repeatcount: 'repeatCount', - repeatdur: 'repeatDur', - requiredextensions: 'requiredExtensions', - requiredfeatures: 'requiredFeatures', - resource: 'resource', - restart: 'restart', - result: 'result', - results: 'results', - rotate: 'rotate', - rx: 'rx', - ry: 'ry', - scale: 'scale', - security: 'security', - seed: 'seed', - shaperendering: 'shapeRendering', - 'shape-rendering': 'shapeRendering', - slope: 'slope', - spacing: 'spacing', - specularconstant: 'specularConstant', - specularexponent: 'specularExponent', - speed: 'speed', - spreadmethod: 'spreadMethod', - startoffset: 'startOffset', - stddeviation: 'stdDeviation', - stemh: 'stemh', - stemv: 'stemv', - stitchtiles: 'stitchTiles', - stopcolor: 'stopColor', - 'stop-color': 'stopColor', - stopopacity: 'stopOpacity', - 'stop-opacity': 'stopOpacity', - strikethroughposition: 'strikethroughPosition', - 'strikethrough-position': 'strikethroughPosition', - strikethroughthickness: 'strikethroughThickness', - 'strikethrough-thickness': 'strikethroughThickness', - string: 'string', - stroke: 'stroke', - strokedasharray: 'strokeDasharray', - 'stroke-dasharray': 'strokeDasharray', - strokedashoffset: 'strokeDashoffset', - 'stroke-dashoffset': 'strokeDashoffset', - strokelinecap: 'strokeLinecap', - 'stroke-linecap': 'strokeLinecap', - strokelinejoin: 'strokeLinejoin', - 'stroke-linejoin': 'strokeLinejoin', - strokemiterlimit: 'strokeMiterlimit', - 'stroke-miterlimit': 'strokeMiterlimit', - strokewidth: 'strokeWidth', - 'stroke-width': 'strokeWidth', - strokeopacity: 'strokeOpacity', - 'stroke-opacity': 'strokeOpacity', - suppresscontenteditablewarning: 'suppressContentEditableWarning', - suppresshydrationwarning: 'suppressHydrationWarning', - surfacescale: 'surfaceScale', - systemlanguage: 'systemLanguage', - tablevalues: 'tableValues', - targetx: 'targetX', - targety: 'targetY', - textanchor: 'textAnchor', - 'text-anchor': 'textAnchor', - textdecoration: 'textDecoration', - 'text-decoration': 'textDecoration', - textlength: 'textLength', - textrendering: 'textRendering', - 'text-rendering': 'textRendering', - to: 'to', - transform: 'transform', - typeof: 'typeof', - u1: 'u1', - u2: 'u2', - underlineposition: 'underlinePosition', - 'underline-position': 'underlinePosition', - underlinethickness: 'underlineThickness', - 'underline-thickness': 'underlineThickness', - unicode: 'unicode', - unicodebidi: 'unicodeBidi', - 'unicode-bidi': 'unicodeBidi', - unicoderange: 'unicodeRange', - 'unicode-range': 'unicodeRange', - unitsperem: 'unitsPerEm', - 'units-per-em': 'unitsPerEm', - unselectable: 'unselectable', - valphabetic: 'vAlphabetic', - 'v-alphabetic': 'vAlphabetic', - values: 'values', - vectoreffect: 'vectorEffect', - 'vector-effect': 'vectorEffect', - version: 'version', - vertadvy: 'vertAdvY', - 'vert-adv-y': 'vertAdvY', - vertoriginx: 'vertOriginX', - 'vert-origin-x': 'vertOriginX', - vertoriginy: 'vertOriginY', - 'vert-origin-y': 'vertOriginY', - vhanging: 'vHanging', - 'v-hanging': 'vHanging', - videographic: 'vIdeographic', - 'v-ideographic': 'vIdeographic', - viewbox: 'viewBox', - viewtarget: 'viewTarget', - visibility: 'visibility', - vmathematical: 'vMathematical', - 'v-mathematical': 'vMathematical', - vocab: 'vocab', - widths: 'widths', - wordspacing: 'wordSpacing', - 'word-spacing': 'wordSpacing', - writingmode: 'writingMode', - 'writing-mode': 'writingMode', - x1: 'x1', - x2: 'x2', - x: 'x', - xchannelselector: 'xChannelSelector', - xheight: 'xHeight', - 'x-height': 'xHeight', - xlinkactuate: 'xlinkActuate', - 'xlink:actuate': 'xlinkActuate', - xlinkarcrole: 'xlinkArcrole', - 'xlink:arcrole': 'xlinkArcrole', - xlinkhref: 'xlinkHref', - 'xlink:href': 'xlinkHref', - xlinkrole: 'xlinkRole', - 'xlink:role': 'xlinkRole', - xlinkshow: 'xlinkShow', - 'xlink:show': 'xlinkShow', - xlinktitle: 'xlinkTitle', - 'xlink:title': 'xlinkTitle', - xlinktype: 'xlinkType', - 'xlink:type': 'xlinkType', - xmlbase: 'xmlBase', - 'xml:base': 'xmlBase', - xmllang: 'xmlLang', - 'xml:lang': 'xmlLang', - xmlns: 'xmlns', - 'xml:space': 'xmlSpace', - xmlnsxlink: 'xmlnsXlink', - 'xmlns:xlink': 'xmlnsXlink', - xmlspace: 'xmlSpace', - y1: 'y1', - y2: 'y2', - y: 'y', - ychannelselector: 'yChannelSelector', - z: 'z', - zoomandpan: 'zoomAndPan' -}; - -var validateProperty$1 = function () {}; - -{ - var warnedProperties$1 = {}; - var EVENT_NAME_REGEX = /^on./; - var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/; - var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$'); - var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$'); - - validateProperty$1 = function (tagName, name, value, eventRegistry) { - if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) { - return true; - } - - var lowerCasedName = name.toLowerCase(); - - if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') { - error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.'); - - warnedProperties$1[name] = true; - return true; - } // We can't rely on the event system being injected on the server. - - - if (eventRegistry != null) { - var registrationNameDependencies = eventRegistry.registrationNameDependencies, - possibleRegistrationNames = eventRegistry.possibleRegistrationNames; - - if (registrationNameDependencies.hasOwnProperty(name)) { - return true; - } - - var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null; - - if (registrationName != null) { - error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName); - - warnedProperties$1[name] = true; - return true; - } - - if (EVENT_NAME_REGEX.test(name)) { - error('Unknown event handler property `%s`. It will be ignored.', name); - - warnedProperties$1[name] = true; - return true; - } - } else if (EVENT_NAME_REGEX.test(name)) { - // If no event plugins have been injected, we are in a server environment. - // So we can't tell if the event name is correct for sure, but we can filter - // out known bad ones like `onclick`. We can't suggest a specific replacement though. - if (INVALID_EVENT_NAME_REGEX.test(name)) { - error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name); - } - - warnedProperties$1[name] = true; - return true; - } // Let the ARIA attribute hook validate ARIA attributes - - - if (rARIA$1.test(name) || rARIACamel$1.test(name)) { - return true; - } - - if (lowerCasedName === 'innerhtml') { - error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.'); - - warnedProperties$1[name] = true; - return true; - } - - if (lowerCasedName === 'aria') { - error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.'); - - warnedProperties$1[name] = true; - return true; - } - - if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') { - error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value); - - warnedProperties$1[name] = true; - return true; - } - - if (typeof value === 'number' && isNaN(value)) { - error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name); - - warnedProperties$1[name] = true; - return true; - } - - var propertyInfo = getPropertyInfo(name); - var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config. - - if (possibleStandardNames.hasOwnProperty(lowerCasedName)) { - var standardName = possibleStandardNames[lowerCasedName]; - - if (standardName !== name) { - error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName); - - warnedProperties$1[name] = true; - return true; - } - } else if (!isReserved && name !== lowerCasedName) { - // Unknown attributes should have lowercase casing since that's how they - // will be cased anyway with server rendering. - error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName); - - warnedProperties$1[name] = true; - return true; - } - - if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { - if (value) { - error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name); - } else { - error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name); - } - - warnedProperties$1[name] = true; - return true; - } // Now that we've validated casing, do not validate - // data types for reserved props - - - if (isReserved) { - return true; - } // Warn when a known attribute is a bad type - - - if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { - warnedProperties$1[name] = true; - return false; - } // Warn when passing the strings 'false' or 'true' into a boolean prop - - - if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) { - error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value); - - warnedProperties$1[name] = true; - return true; - } - - return true; - }; -} - -var warnUnknownProperties = function (type, props, eventRegistry) { - { - var unknownProps = []; - - for (var key in props) { - var isValid = validateProperty$1(type, key, props[key], eventRegistry); - - if (!isValid) { - unknownProps.push(key); - } - } - - var unknownPropString = unknownProps.map(function (prop) { - return '`' + prop + '`'; - }).join(', '); - - if (unknownProps.length === 1) { - error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type); - } else if (unknownProps.length > 1) { - error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type); - } - } -}; - -function validateProperties$2(type, props, eventRegistry) { - if (isCustomComponent(type, props)) { - return; - } - - warnUnknownProperties(type, props, eventRegistry); -} - -var warnValidStyle = function () {}; - -{ - // 'msTransform' is correct, but the other prefixes should be capitalized - var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; - var msPattern = /^-ms-/; - var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon - - var badStyleValueWithSemicolonPattern = /;\s*$/; - var warnedStyleNames = {}; - var warnedStyleValues = {}; - var warnedForNaNValue = false; - var warnedForInfinityValue = false; - - var camelize = function (string) { - return string.replace(hyphenPattern, function (_, character) { - return character.toUpperCase(); - }); - }; - - var warnHyphenatedStyleName = function (name) { - if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { - return; - } - - warnedStyleNames[name] = true; - - error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests - // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix - // is converted to lowercase `ms`. - camelize(name.replace(msPattern, 'ms-'))); - }; - - var warnBadVendoredStyleName = function (name) { - if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { - return; - } - - warnedStyleNames[name] = true; - - error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1)); - }; - - var warnStyleValueWithSemicolon = function (name, value) { - if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { - return; - } - - warnedStyleValues[value] = true; - - error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '')); - }; - - var warnStyleValueIsNaN = function (name, value) { - if (warnedForNaNValue) { - return; - } - - warnedForNaNValue = true; - - error('`NaN` is an invalid value for the `%s` css style property.', name); - }; - - var warnStyleValueIsInfinity = function (name, value) { - if (warnedForInfinityValue) { - return; - } - - warnedForInfinityValue = true; - - error('`Infinity` is an invalid value for the `%s` css style property.', name); - }; - - warnValidStyle = function (name, value) { - if (name.indexOf('-') > -1) { - warnHyphenatedStyleName(name); - } else if (badVendoredStyleNamePattern.test(name)) { - warnBadVendoredStyleName(name); - } else if (badStyleValueWithSemicolonPattern.test(value)) { - warnStyleValueWithSemicolon(name, value); - } - - if (typeof value === 'number') { - if (isNaN(value)) { - warnStyleValueIsNaN(name, value); - } else if (!isFinite(value)) { - warnStyleValueIsInfinity(name, value); - } - } - }; -} - -var warnValidStyle$1 = warnValidStyle; - -// code copied and modified from escape-html -var matchHtmlRegExp = /["'&<>]/; -/** - * Escapes special characters and HTML entities in a given html string. - * - * @param {string} string HTML string to escape for later insertion - * @return {string} - * @public - */ - -function escapeHtml(string) { - { - checkHtmlStringCoercion(string); - } - - var str = '' + string; - var match = matchHtmlRegExp.exec(str); - - if (!match) { - return str; - } - - var escape; - var html = ''; - var index; - var lastIndex = 0; - - for (index = match.index; index < str.length; index++) { - switch (str.charCodeAt(index)) { - case 34: - // " - escape = '"'; - break; - - case 38: - // & - escape = '&'; - break; - - case 39: - // ' - escape = '''; // modified from escape-html; used to be ''' - - break; - - case 60: - // < - escape = '<'; - break; - - case 62: - // > - escape = '>'; - break; - - default: - continue; - } - - if (lastIndex !== index) { - html += str.substring(lastIndex, index); - } - - lastIndex = index + 1; - html += escape; - } - - return lastIndex !== index ? html + str.substring(lastIndex, index) : html; -} // end code copied and modified from escape-html - -/** - * Escapes text to prevent scripting attacks. - * - * @param {*} text Text value to escape. - * @return {string} An escaped string. - */ - - -function escapeTextForBrowser(text) { - if (typeof text === 'boolean' || typeof text === 'number') { - // this shortcircuit helps perf for types that we know will never have - // special characters, especially given that this function is used often - // for numeric dom ids. - return '' + text; - } - - return escapeHtml(text); -} - -var uppercasePattern = /([A-Z])/g; -var msPattern$1 = /^ms-/; -/** - * Hyphenates a camelcased CSS property name, for example: - * - * > hyphenateStyleName('backgroundColor') - * < "background-color" - * > hyphenateStyleName('MozTransition') - * < "-moz-transition" - * > hyphenateStyleName('msTransition') - * < "-ms-transition" - * - * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix - * is converted to `-ms-`. - */ - -function hyphenateStyleName(name) { - return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern$1, '-ms-'); -} - -// and any newline or tab are filtered out as if they're not part of the URL. -// https://url.spec.whatwg.org/#url-parsing -// Tab or newline are defined as \r\n\t: -// https://infra.spec.whatwg.org/#ascii-tab-or-newline -// A C0 control is a code point in the range \u0000 NULL to \u001F -// INFORMATION SEPARATOR ONE, inclusive: -// https://infra.spec.whatwg.org/#c0-control-or-space - -/* eslint-disable max-len */ - -var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; -var didWarn = false; - -function sanitizeURL(url) { - { - if (!didWarn && isJavaScriptProtocol.test(url)) { - didWarn = true; - - error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url)); - } - } -} - -var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare - -function isArray(a) { - return isArrayImpl(a); -} - -var startInlineScript = stringToPrecomputedChunk(''); -var startScriptSrc = stringToPrecomputedChunk(''); -/** - * This escaping function is designed to work with bootstrapScriptContent only. - * because we know we are escaping the entire script. We can avoid for instance - * escaping html comment string sequences that are valid javascript as well because - * if there are no sebsequent '); -function writeCompletedSegmentInstruction(destination, responseState, contentSegmentID) { - writeChunk(destination, responseState.startInlineScript); - - if (!responseState.sentCompleteSegmentFunction) { - // The first time we write this, we'll need to include the full implementation. - responseState.sentCompleteSegmentFunction = true; - writeChunk(destination, completeSegmentScript1Full); - } else { - // Future calls can just reuse the same function. - writeChunk(destination, completeSegmentScript1Partial); - } - - writeChunk(destination, responseState.segmentPrefix); - var formattedID = stringToChunk(contentSegmentID.toString(16)); - writeChunk(destination, formattedID); - writeChunk(destination, completeSegmentScript2); - writeChunk(destination, responseState.placeholderPrefix); - writeChunk(destination, formattedID); - return writeChunkAndReturn(destination, completeSegmentScript3); -} -var completeBoundaryScript1Full = stringToPrecomputedChunk(completeBoundaryFunction + ';$RC("'); -var completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC("'); -var completeBoundaryScript2 = stringToPrecomputedChunk('","'); -var completeBoundaryScript3 = stringToPrecomputedChunk('")'); -function writeCompletedBoundaryInstruction(destination, responseState, boundaryID, contentSegmentID) { - writeChunk(destination, responseState.startInlineScript); - - if (!responseState.sentCompleteBoundaryFunction) { - // The first time we write this, we'll need to include the full implementation. - responseState.sentCompleteBoundaryFunction = true; - writeChunk(destination, completeBoundaryScript1Full); - } else { - // Future calls can just reuse the same function. - writeChunk(destination, completeBoundaryScript1Partial); - } - - if (boundaryID === null) { - throw new Error('An ID must have been assigned before we can complete the boundary.'); - } - - var formattedContentID = stringToChunk(contentSegmentID.toString(16)); - writeChunk(destination, boundaryID); - writeChunk(destination, completeBoundaryScript2); - writeChunk(destination, responseState.segmentPrefix); - writeChunk(destination, formattedContentID); - return writeChunkAndReturn(destination, completeBoundaryScript3); -} -var clientRenderScript1Full = stringToPrecomputedChunk(clientRenderFunction + ';$RX("'); -var clientRenderScript1Partial = stringToPrecomputedChunk('$RX("'); -var clientRenderScript1A = stringToPrecomputedChunk('"'); -var clientRenderScript2 = stringToPrecomputedChunk(')'); -var clientRenderErrorScriptArgInterstitial = stringToPrecomputedChunk(','); -function writeClientRenderBoundaryInstruction(destination, responseState, boundaryID, errorDigest, errorMessage, errorComponentStack) { - writeChunk(destination, responseState.startInlineScript); - - if (!responseState.sentClientRenderFunction) { - // The first time we write this, we'll need to include the full implementation. - responseState.sentClientRenderFunction = true; - writeChunk(destination, clientRenderScript1Full); - } else { - // Future calls can just reuse the same function. - writeChunk(destination, clientRenderScript1Partial); - } - - if (boundaryID === null) { - throw new Error('An ID must have been assigned before we can complete the boundary.'); - } - - writeChunk(destination, boundaryID); - writeChunk(destination, clientRenderScript1A); - - if (errorDigest || errorMessage || errorComponentStack) { - writeChunk(destination, clientRenderErrorScriptArgInterstitial); - writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorDigest || ''))); - } - - if (errorMessage || errorComponentStack) { - writeChunk(destination, clientRenderErrorScriptArgInterstitial); - writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorMessage || ''))); - } - - if (errorComponentStack) { - writeChunk(destination, clientRenderErrorScriptArgInterstitial); - writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorComponentStack))); - } - - return writeChunkAndReturn(destination, clientRenderScript2); -} -var regexForJSStringsInScripts = /[<\u2028\u2029]/g; - -function escapeJSStringsForInstructionScripts(input) { - var escaped = JSON.stringify(input); - return escaped.replace(regexForJSStringsInScripts, function (match) { - switch (match) { - // santizing breaking out of strings and script tags - case '<': - return "\\u003c"; - - case "\u2028": - return "\\u2028"; - - case "\u2029": - return "\\u2029"; - - default: - { - // eslint-disable-next-line react-internal/prod-error-codes - throw new Error('escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React'); - } - } - }); -} - -function createResponseState$1(generateStaticMarkup, identifierPrefix) { - var responseState = createResponseState(identifierPrefix, undefined); - return { - // Keep this in sync with ReactDOMServerFormatConfig - bootstrapChunks: responseState.bootstrapChunks, - startInlineScript: responseState.startInlineScript, - placeholderPrefix: responseState.placeholderPrefix, - segmentPrefix: responseState.segmentPrefix, - boundaryPrefix: responseState.boundaryPrefix, - idPrefix: responseState.idPrefix, - nextSuspenseID: responseState.nextSuspenseID, - sentCompleteSegmentFunction: responseState.sentCompleteSegmentFunction, - sentCompleteBoundaryFunction: responseState.sentCompleteBoundaryFunction, - sentClientRenderFunction: responseState.sentClientRenderFunction, - // This is an extra field for the legacy renderer - generateStaticMarkup: generateStaticMarkup - }; -} -function createRootFormatContext() { - return { - insertionMode: HTML_MODE, - // We skip the root mode because we don't want to emit the DOCTYPE in legacy mode. - selectedValue: null - }; -} -function pushTextInstance$1(target, text, responseState, textEmbedded) { - if (responseState.generateStaticMarkup) { - target.push(stringToChunk(escapeTextForBrowser(text))); - return false; - } else { - return pushTextInstance(target, text, responseState, textEmbedded); - } -} -function pushSegmentFinale$1(target, responseState, lastPushedText, textEmbedded) { - if (responseState.generateStaticMarkup) { - return; - } else { - return pushSegmentFinale(target, responseState, lastPushedText, textEmbedded); - } -} -function writeStartCompletedSuspenseBoundary$1(destination, responseState) { - if (responseState.generateStaticMarkup) { - // A completed boundary is done and doesn't need a representation in the HTML - // if we're not going to be hydrating it. - return true; - } - - return writeStartCompletedSuspenseBoundary(destination); -} -function writeStartClientRenderedSuspenseBoundary$1(destination, responseState, // flushing these error arguments are not currently supported in this legacy streaming format. -errorDigest, errorMessage, errorComponentStack) { - if (responseState.generateStaticMarkup) { - // A client rendered boundary is done and doesn't need a representation in the HTML - // since we'll never hydrate it. This is arguably an error in static generation. - return true; - } - - return writeStartClientRenderedSuspenseBoundary(destination, responseState, errorDigest, errorMessage, errorComponentStack); -} -function writeEndCompletedSuspenseBoundary$1(destination, responseState) { - if (responseState.generateStaticMarkup) { - return true; - } - - return writeEndCompletedSuspenseBoundary(destination); -} -function writeEndClientRenderedSuspenseBoundary$1(destination, responseState) { - if (responseState.generateStaticMarkup) { - return true; - } - - return writeEndClientRenderedSuspenseBoundary(destination); -} - -var assign = Object.assign; - -// ATTENTION -// When adding new symbols to this file, -// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' -// The Symbol used to tag the ReactElement-like types. -var REACT_ELEMENT_TYPE = Symbol.for('react.element'); -var REACT_PORTAL_TYPE = Symbol.for('react.portal'); -var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); -var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); -var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); -var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); -var REACT_CONTEXT_TYPE = Symbol.for('react.context'); -var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); -var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); -var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); -var REACT_MEMO_TYPE = Symbol.for('react.memo'); -var REACT_LAZY_TYPE = Symbol.for('react.lazy'); -var REACT_SCOPE_TYPE = Symbol.for('react.scope'); -var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode'); -var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden'); -var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); -var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; -var FAUX_ITERATOR_SYMBOL = '@@iterator'; -function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== 'object') { - return null; - } - - var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - - if (typeof maybeIterator === 'function') { - return maybeIterator; - } - - return null; -} - -function getWrappedName(outerType, innerType, wrapperName) { - var displayName = outerType.displayName; - - if (displayName) { - return displayName; - } - - var functionName = innerType.displayName || innerType.name || ''; - return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; -} // Keep in sync with react-reconciler/getComponentNameFromFiber - - -function getContextName(type) { - return type.displayName || 'Context'; -} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. - - -function getComponentNameFromType(type) { - if (type == null) { - // Host root, text node or just invalid type. - return null; - } - - { - if (typeof type.tag === 'number') { - error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); - } - } - - if (typeof type === 'function') { - return type.displayName || type.name || null; - } - - if (typeof type === 'string') { - return type; - } - - switch (type) { - case REACT_FRAGMENT_TYPE: - return 'Fragment'; - - case REACT_PORTAL_TYPE: - return 'Portal'; - - case REACT_PROFILER_TYPE: - return 'Profiler'; - - case REACT_STRICT_MODE_TYPE: - return 'StrictMode'; - - case REACT_SUSPENSE_TYPE: - return 'Suspense'; - - case REACT_SUSPENSE_LIST_TYPE: - return 'SuspenseList'; - - } - - if (typeof type === 'object') { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - var context = type; - return getContextName(context) + '.Consumer'; - - case REACT_PROVIDER_TYPE: - var provider = type; - return getContextName(provider._context) + '.Provider'; - - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, 'ForwardRef'); - - case REACT_MEMO_TYPE: - var outerName = type.displayName || null; - - if (outerName !== null) { - return outerName; - } - - return getComponentNameFromType(type.type) || 'Memo'; - - case REACT_LAZY_TYPE: - { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - return getComponentNameFromType(init(payload)); - } catch (x) { - return null; - } - } - - // eslint-disable-next-line no-fallthrough - } - } - - return null; -} - -// Helpers to patch console.logs to avoid logging during side-effect free -// replaying on render function. This currently only patches the object -// lazily which won't cover if the log function was extracted eagerly. -// We could also eagerly patch the method. -var disabledDepth = 0; -var prevLog; -var prevInfo; -var prevWarn; -var prevError; -var prevGroup; -var prevGroupCollapsed; -var prevGroupEnd; - -function disabledLog() {} - -disabledLog.__reactDisabledLog = true; -function disableLogs() { - { - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 - - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; // $FlowFixMe Flow thinks console is immutable. - - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - /* eslint-enable react-internal/no-production-logging */ - } - - disabledDepth++; - } -} -function reenableLogs() { - { - disabledDepth--; - - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - var props = { - configurable: true, - enumerable: true, - writable: true - }; // $FlowFixMe Flow thinks console is immutable. - - Object.defineProperties(console, { - log: assign({}, props, { - value: prevLog - }), - info: assign({}, props, { - value: prevInfo - }), - warn: assign({}, props, { - value: prevWarn - }), - error: assign({}, props, { - value: prevError - }), - group: assign({}, props, { - value: prevGroup - }), - groupCollapsed: assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: assign({}, props, { - value: prevGroupEnd - }) - }); - /* eslint-enable react-internal/no-production-logging */ - } - - if (disabledDepth < 0) { - error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); - } - } -} - -var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; -var prefix; -function describeBuiltInComponentFrame(name, source, ownerFn) { - { - if (prefix === undefined) { - // Extract the VM specific prefix used by each line. - try { - throw Error(); - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/); - prefix = match && match[1] || ''; - } - } // We use the prefix to ensure our stacks line up with native stack frames. - - - return '\n' + prefix + name; - } -} -var reentry = false; -var componentFrameCache; - -{ - var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); -} - -function describeNativeComponentFrame(fn, construct) { - // If something asked for a stack inside a fake render, it should get ignored. - if ( !fn || reentry) { - return ''; - } - - { - var frame = componentFrameCache.get(fn); - - if (frame !== undefined) { - return frame; - } - } - - var control; - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. - - Error.prepareStackTrace = undefined; - var previousDispatcher; - - { - previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function - // for warnings. - - ReactCurrentDispatcher.current = null; - disableLogs(); - } - - try { - // This should throw. - if (construct) { - // Something should be setting the props in the constructor. - var Fake = function () { - throw Error(); - }; // $FlowFixMe - - - Object.defineProperty(Fake.prototype, 'props', { - set: function () { - // We use a throwing setter instead of frozen or non-writable props - // because that won't throw in a non-strict mode function. - throw Error(); - } - }); - - if (typeof Reflect === 'object' && Reflect.construct) { - // We construct a different control for this case to include any extra - // frames added by the construct call. - try { - Reflect.construct(Fake, []); - } catch (x) { - control = x; - } - - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x) { - control = x; - } - - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x) { - control = x; - } - - fn(); - } - } catch (sample) { - // This is inlined manually because closure doesn't do it for us. - if (sample && control && typeof sample.stack === 'string') { - // This extracts the first frame from the sample that isn't also in the control. - // Skipping one frame that we assume is the frame that calls the two. - var sampleLines = sample.stack.split('\n'); - var controlLines = control.stack.split('\n'); - var s = sampleLines.length - 1; - var c = controlLines.length - 1; - - while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { - // We expect at least one stack frame to be shared. - // Typically this will be the root most one. However, stack frames may be - // cut off due to maximum stack limits. In this case, one maybe cut off - // earlier than the other. We assume that the sample is longer or the same - // and there for cut off earlier. So we should find the root most frame in - // the sample somewhere in the control. - c--; - } - - for (; s >= 1 && c >= 0; s--, c--) { - // Next we find the first one that isn't the same which should be the - // frame that called our sample function and the control. - if (sampleLines[s] !== controlLines[c]) { - // In V8, the first line is describing the message but other VMs don't. - // If we're about to return the first line, and the control is also on the same - // line, that's a pretty good indicator that our sample threw at same line as - // the control. I.e. before we entered the sample frame. So we ignore this result. - // This can happen if you passed a class to function component, or non-function. - if (s !== 1 || c !== 1) { - do { - s--; - c--; // We may still have similar intermediate frames from the construct call. - // The next one that isn't the same should be our match though. - - if (c < 0 || sampleLines[s] !== controlLines[c]) { - // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. - var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "" - // but we have a user-provided "displayName" - // splice it in to make the stack more readable. - - - if (fn.displayName && _frame.includes('')) { - _frame = _frame.replace('', fn.displayName); - } - - { - if (typeof fn === 'function') { - componentFrameCache.set(fn, _frame); - } - } // Return the line we found. - - - return _frame; - } - } while (s >= 1 && c >= 0); - } - - break; - } - } - } - } finally { - reentry = false; - - { - ReactCurrentDispatcher.current = previousDispatcher; - reenableLogs(); - } - - Error.prepareStackTrace = previousPrepareStackTrace; - } // Fallback to just using the name if we couldn't make it throw. - - - var name = fn ? fn.displayName || fn.name : ''; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; - - { - if (typeof fn === 'function') { - componentFrameCache.set(fn, syntheticFrame); - } - } - - return syntheticFrame; -} - -function describeClassComponentFrame(ctor, source, ownerFn) { - { - return describeNativeComponentFrame(ctor, true); - } -} -function describeFunctionComponentFrame(fn, source, ownerFn) { - { - return describeNativeComponentFrame(fn, false); - } -} - -function shouldConstruct(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); -} - -function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - - if (type == null) { - return ''; - } - - if (typeof type === 'function') { - { - return describeNativeComponentFrame(type, shouldConstruct(type)); - } - } - - if (typeof type === 'string') { - return describeBuiltInComponentFrame(type); - } - - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame('Suspense'); - - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame('SuspenseList'); - } - - if (typeof type === 'object') { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); - - case REACT_LAZY_TYPE: - { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); - } catch (x) {} - } - } - } - - return ''; -} - -var loggedTypeFailures = {}; -var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - -function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - ReactDebugCurrentFrame.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame.setExtraStackFrame(null); - } - } -} - -function checkPropTypes(typeSpecs, values, location, componentName, element) { - { - // $FlowFixMe This is okay but Flow doesn't know it. - var has = Function.call.bind(hasOwnProperty); - - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== 'function') { - // eslint-disable-next-line react-internal/prod-error-codes - var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); - err.name = 'Invariant Violation'; - throw err; - } - - error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); - } catch (ex) { - error$1 = ex; - } - - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - - error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); - - setCurrentlyValidatingElement(null); - } - - if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - - error('Failed %s type: %s', location, error$1.message); - - setCurrentlyValidatingElement(null); - } - } - } - } -} - -var warnedAboutMissingGetChildContext; - -{ - warnedAboutMissingGetChildContext = {}; -} - -var emptyContextObject = {}; - -{ - Object.freeze(emptyContextObject); -} - -function getMaskedContext(type, unmaskedContext) { - { - var contextTypes = type.contextTypes; - - if (!contextTypes) { - return emptyContextObject; - } - - var context = {}; - - for (var key in contextTypes) { - context[key] = unmaskedContext[key]; - } - - { - var name = getComponentNameFromType(type) || 'Unknown'; - checkPropTypes(contextTypes, context, 'context', name); - } - - return context; - } -} -function processChildContext(instance, type, parentContext, childContextTypes) { - { - // TODO (bvaughn) Replace this behavior with an invariant() in the future. - // It has only been added in Fiber to match the (unintentional) behavior in Stack. - if (typeof instance.getChildContext !== 'function') { - { - var componentName = getComponentNameFromType(type) || 'Unknown'; - - if (!warnedAboutMissingGetChildContext[componentName]) { - warnedAboutMissingGetChildContext[componentName] = true; - - error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName); - } - } - - return parentContext; - } - - var childContext = instance.getChildContext(); - - for (var contextKey in childContext) { - if (!(contextKey in childContextTypes)) { - throw new Error((getComponentNameFromType(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes."); - } - } - - { - var name = getComponentNameFromType(type) || 'Unknown'; - checkPropTypes(childContextTypes, childContext, 'child context', name); - } - - return assign({}, parentContext, childContext); - } -} - -var rendererSigil; - -{ - // Use this to detect multiple renderers using the same context - rendererSigil = {}; -} // Used to store the parent path of all context overrides in a shared linked list. -// Forming a reverse tree. - - -var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. -// This global (actually thread local) state represents what state all those "current", -// fields are currently in. - -var currentActiveSnapshot = null; - -function popNode(prev) { - { - prev.context._currentValue2 = prev.parentValue; - } -} - -function pushNode(next) { - { - next.context._currentValue2 = next.value; - } -} - -function popToNearestCommonAncestor(prev, next) { - if (prev === next) ; else { - popNode(prev); - var parentPrev = prev.parent; - var parentNext = next.parent; - - if (parentPrev === null) { - if (parentNext !== null) { - throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); - } - } else { - if (parentNext === null) { - throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); - } - - popToNearestCommonAncestor(parentPrev, parentNext); - } // On the way back, we push the new ones that weren't common. - - - pushNode(next); - } -} - -function popAllPrevious(prev) { - popNode(prev); - var parentPrev = prev.parent; - - if (parentPrev !== null) { - popAllPrevious(parentPrev); - } -} - -function pushAllNext(next) { - var parentNext = next.parent; - - if (parentNext !== null) { - pushAllNext(parentNext); - } - - pushNode(next); -} - -function popPreviousToCommonLevel(prev, next) { - popNode(prev); - var parentPrev = prev.parent; - - if (parentPrev === null) { - throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); - } - - if (parentPrev.depth === next.depth) { - // We found the same level. Now we just need to find a shared ancestor. - popToNearestCommonAncestor(parentPrev, next); - } else { - // We must still be deeper. - popPreviousToCommonLevel(parentPrev, next); - } -} - -function popNextToCommonLevel(prev, next) { - var parentNext = next.parent; - - if (parentNext === null) { - throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); - } - - if (prev.depth === parentNext.depth) { - // We found the same level. Now we just need to find a shared ancestor. - popToNearestCommonAncestor(prev, parentNext); - } else { - // We must still be deeper. - popNextToCommonLevel(prev, parentNext); - } - - pushNode(next); -} // Perform context switching to the new snapshot. -// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by -// updating all the context's current values. That way reads, always just read the current value. -// At the cost of updating contexts even if they're never read by this subtree. - - -function switchContext(newSnapshot) { - // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. - // We also need to update any new contexts that are now on the stack with the deepest value. - // The easiest way to update new contexts is to just reapply them in reverse order from the - // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack - // for that. Therefore this algorithm is recursive. - // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. - // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. - // 3) Then we reapply new contexts on the way back up the stack. - var prev = currentActiveSnapshot; - var next = newSnapshot; - - if (prev !== next) { - if (prev === null) { - // $FlowFixMe: This has to be non-null since it's not equal to prev. - pushAllNext(next); - } else if (next === null) { - popAllPrevious(prev); - } else if (prev.depth === next.depth) { - popToNearestCommonAncestor(prev, next); - } else if (prev.depth > next.depth) { - popPreviousToCommonLevel(prev, next); - } else { - popNextToCommonLevel(prev, next); - } - - currentActiveSnapshot = next; - } -} -function pushProvider(context, nextValue) { - var prevValue; - - { - prevValue = context._currentValue2; - context._currentValue2 = nextValue; - - { - if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) { - error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); - } - - context._currentRenderer2 = rendererSigil; - } - } - - var prevNode = currentActiveSnapshot; - var newNode = { - parent: prevNode, - depth: prevNode === null ? 0 : prevNode.depth + 1, - context: context, - parentValue: prevValue, - value: nextValue - }; - currentActiveSnapshot = newNode; - return newNode; -} -function popProvider(context) { - var prevSnapshot = currentActiveSnapshot; - - if (prevSnapshot === null) { - throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.'); - } - - { - if (prevSnapshot.context !== context) { - error('The parent context is not the expected context. This is probably a bug in React.'); - } - } - - { - var _value = prevSnapshot.parentValue; - - if (_value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) { - prevSnapshot.context._currentValue2 = prevSnapshot.context._defaultValue; - } else { - prevSnapshot.context._currentValue2 = _value; - } - - { - if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) { - error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); - } - - context._currentRenderer2 = rendererSigil; - } - } - - return currentActiveSnapshot = prevSnapshot.parent; -} -function getActiveContext() { - return currentActiveSnapshot; -} -function readContext(context) { - var value = context._currentValue2; - return value; -} - -/** - * `ReactInstanceMap` maintains a mapping from a public facing stateful - * instance (key) and the internal representation (value). This allows public - * methods to accept the user facing instance as an argument and map them back - * to internal methods. - * - * Note that this module is currently shared and assumed to be stateless. - * If this becomes an actual Map, that will break. - */ -function get(key) { - return key._reactInternals; -} -function set(key, value) { - key._reactInternals = value; -} - -var didWarnAboutNoopUpdateForComponent = {}; -var didWarnAboutDeprecatedWillMount = {}; -var didWarnAboutUninitializedState; -var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; -var didWarnAboutLegacyLifecyclesAndDerivedState; -var didWarnAboutUndefinedDerivedState; -var warnOnUndefinedDerivedState; -var warnOnInvalidCallback; -var didWarnAboutDirectlyAssigningPropsToState; -var didWarnAboutContextTypeAndContextTypes; -var didWarnAboutInvalidateContextType; - -{ - didWarnAboutUninitializedState = new Set(); - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); - didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); - didWarnAboutDirectlyAssigningPropsToState = new Set(); - didWarnAboutUndefinedDerivedState = new Set(); - didWarnAboutContextTypeAndContextTypes = new Set(); - didWarnAboutInvalidateContextType = new Set(); - var didWarnOnInvalidCallback = new Set(); - - warnOnInvalidCallback = function (callback, callerName) { - if (callback === null || typeof callback === 'function') { - return; - } - - var key = callerName + '_' + callback; - - if (!didWarnOnInvalidCallback.has(key)) { - didWarnOnInvalidCallback.add(key); - - error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback); - } - }; - - warnOnUndefinedDerivedState = function (type, partialState) { - if (partialState === undefined) { - var componentName = getComponentNameFromType(type) || 'Component'; - - if (!didWarnAboutUndefinedDerivedState.has(componentName)) { - didWarnAboutUndefinedDerivedState.add(componentName); - - error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName); - } - } - }; -} - -function warnNoop(publicInstance, callerName) { - { - var _constructor = publicInstance.constructor; - var componentName = _constructor && getComponentNameFromType(_constructor) || 'ReactClass'; - var warningKey = componentName + '.' + callerName; - - if (didWarnAboutNoopUpdateForComponent[warningKey]) { - return; - } - - error('%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\n\nPlease check the code for the %s component.', callerName, callerName, componentName); - - didWarnAboutNoopUpdateForComponent[warningKey] = true; - } -} - -var classComponentUpdater = { - isMounted: function (inst) { - return false; - }, - enqueueSetState: function (inst, payload, callback) { - var internals = get(inst); - - if (internals.queue === null) { - warnNoop(inst, 'setState'); - } else { - internals.queue.push(payload); - - { - if (callback !== undefined && callback !== null) { - warnOnInvalidCallback(callback, 'setState'); - } - } - } - }, - enqueueReplaceState: function (inst, payload, callback) { - var internals = get(inst); - internals.replace = true; - internals.queue = [payload]; - - { - if (callback !== undefined && callback !== null) { - warnOnInvalidCallback(callback, 'setState'); - } - } - }, - enqueueForceUpdate: function (inst, callback) { - var internals = get(inst); - - if (internals.queue === null) { - warnNoop(inst, 'forceUpdate'); - } else { - { - if (callback !== undefined && callback !== null) { - warnOnInvalidCallback(callback, 'setState'); - } - } - } - } -}; - -function applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, prevState, nextProps) { - var partialState = getDerivedStateFromProps(nextProps, prevState); - - { - warnOnUndefinedDerivedState(ctor, partialState); - } // Merge the partial state and the previous state. - - - var newState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState); - return newState; -} - -function constructClassInstance(ctor, props, maskedLegacyContext) { - var context = emptyContextObject; - var contextType = ctor.contextType; - - { - if ('contextType' in ctor) { - var isValid = // Allow null for conditional declaration - contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a - - if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { - didWarnAboutInvalidateContextType.add(ctor); - var addendum = ''; - - if (contextType === undefined) { - addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.'; - } else if (typeof contextType !== 'object') { - addendum = ' However, it is set to a ' + typeof contextType + '.'; - } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { - addendum = ' Did you accidentally pass the Context.Provider instead?'; - } else if (contextType._context !== undefined) { - // - addendum = ' Did you accidentally pass the Context.Consumer instead?'; - } else { - addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.'; - } - - error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum); - } - } - } - - if (typeof contextType === 'object' && contextType !== null) { - context = readContext(contextType); - } else { - context = maskedLegacyContext; - } - - var instance = new ctor(props, context); - - { - if (typeof ctor.getDerivedStateFromProps === 'function' && (instance.state === null || instance.state === undefined)) { - var componentName = getComponentNameFromType(ctor) || 'Component'; - - if (!didWarnAboutUninitializedState.has(componentName)) { - didWarnAboutUninitializedState.add(componentName); - - error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName); - } - } // If new component APIs are defined, "unsafe" lifecycles won't be called. - // Warn about these lifecycles if they are present. - // Don't warn about react-lifecycles-compat polyfilled methods though. - - - if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') { - var foundWillMountName = null; - var foundWillReceivePropsName = null; - var foundWillUpdateName = null; - - if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) { - foundWillMountName = 'componentWillMount'; - } else if (typeof instance.UNSAFE_componentWillMount === 'function') { - foundWillMountName = 'UNSAFE_componentWillMount'; - } - - if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { - foundWillReceivePropsName = 'componentWillReceiveProps'; - } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { - foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps'; - } - - if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { - foundWillUpdateName = 'componentWillUpdate'; - } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') { - foundWillUpdateName = 'UNSAFE_componentWillUpdate'; - } - - if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) { - var _componentName = getComponentNameFromType(ctor) || 'Component'; - - var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()'; - - if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { - didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); - - error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n " + foundWillUpdateName : ''); - } - } - } - } - - return instance; -} - -function checkClassInstance(instance, ctor, newProps) { - { - var name = getComponentNameFromType(ctor) || 'Component'; - var renderPresent = instance.render; - - if (!renderPresent) { - if (ctor.prototype && typeof ctor.prototype.render === 'function') { - error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name); - } else { - error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name); - } - } - - if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) { - error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name); - } - - if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) { - error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name); - } - - if (instance.propTypes) { - error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name); - } - - if (instance.contextType) { - error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name); - } - - { - if (instance.contextTypes) { - error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name); - } - - if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) { - didWarnAboutContextTypeAndContextTypes.add(ctor); - - error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name); - } - } - - if (typeof instance.componentShouldUpdate === 'function') { - error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name); - } - - if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') { - error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component'); - } - - if (typeof instance.componentDidUnmount === 'function') { - error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name); - } - - if (typeof instance.componentDidReceiveProps === 'function') { - error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name); - } - - if (typeof instance.componentWillRecieveProps === 'function') { - error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name); - } - - if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') { - error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name); - } - - var hasMutatedProps = instance.props !== newProps; - - if (instance.props !== undefined && hasMutatedProps) { - error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name); - } - - if (instance.defaultProps) { - error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name); - } - - if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) { - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); - - error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor)); - } - - if (typeof instance.getDerivedStateFromProps === 'function') { - error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); - } - - if (typeof instance.getDerivedStateFromError === 'function') { - error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); - } - - if (typeof ctor.getSnapshotBeforeUpdate === 'function') { - error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name); - } - - var _state = instance.state; - - if (_state && (typeof _state !== 'object' || isArray(_state))) { - error('%s.state: must be set to an object or null', name); - } - - if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') { - error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name); - } - } -} - -function callComponentWillMount(type, instance) { - var oldState = instance.state; - - if (typeof instance.componentWillMount === 'function') { - { - if ( instance.componentWillMount.__suppressDeprecationWarning !== true) { - var componentName = getComponentNameFromType(type) || 'Unknown'; - - if (!didWarnAboutDeprecatedWillMount[componentName]) { - warn( // keep this warning in sync with ReactStrictModeWarning.js - 'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code from componentWillMount to componentDidMount (preferred in most cases) ' + 'or the constructor.\n' + '\nPlease update the following components: %s', componentName); - - didWarnAboutDeprecatedWillMount[componentName] = true; - } - } - } - - instance.componentWillMount(); - } - - if (typeof instance.UNSAFE_componentWillMount === 'function') { - instance.UNSAFE_componentWillMount(); - } - - if (oldState !== instance.state) { - { - error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromType(type) || 'Component'); - } - - classComponentUpdater.enqueueReplaceState(instance, instance.state, null); - } -} - -function processUpdateQueue(internalInstance, inst, props, maskedLegacyContext) { - if (internalInstance.queue !== null && internalInstance.queue.length > 0) { - var oldQueue = internalInstance.queue; - var oldReplace = internalInstance.replace; - internalInstance.queue = null; - internalInstance.replace = false; - - if (oldReplace && oldQueue.length === 1) { - inst.state = oldQueue[0]; - } else { - var nextState = oldReplace ? oldQueue[0] : inst.state; - var dontMutate = true; - - for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) { - var partial = oldQueue[i]; - var partialState = typeof partial === 'function' ? partial.call(inst, nextState, props, maskedLegacyContext) : partial; - - if (partialState != null) { - if (dontMutate) { - dontMutate = false; - nextState = assign({}, nextState, partialState); - } else { - assign(nextState, partialState); - } - } - } - - inst.state = nextState; - } - } else { - internalInstance.queue = null; - } -} // Invokes the mount life-cycles on a previously never rendered instance. - - -function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) { - { - checkClassInstance(instance, ctor, newProps); - } - - var initialState = instance.state !== undefined ? instance.state : null; - instance.updater = classComponentUpdater; - instance.props = newProps; - instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway. - // The internal instance will be used to manage updates that happen during this mount. - - var internalInstance = { - queue: [], - replace: false - }; - set(instance, internalInstance); - var contextType = ctor.contextType; - - if (typeof contextType === 'object' && contextType !== null) { - instance.context = readContext(contextType); - } else { - instance.context = maskedLegacyContext; - } - - { - if (instance.state === newProps) { - var componentName = getComponentNameFromType(ctor) || 'Component'; - - if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { - didWarnAboutDirectlyAssigningPropsToState.add(componentName); - - error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName); - } - } - } - - var getDerivedStateFromProps = ctor.getDerivedStateFromProps; - - if (typeof getDerivedStateFromProps === 'function') { - instance.state = applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, initialState, newProps); - } // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - - - if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { - callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's - // process them now. - - processUpdateQueue(internalInstance, instance, newProps, maskedLegacyContext); - } -} - -// Ids are base 32 strings whose binary representation corresponds to the -// position of a node in a tree. -// Every time the tree forks into multiple children, we add additional bits to -// the left of the sequence that represent the position of the child within the -// current level of children. -// -// 00101 00010001011010101 -// ╰─┬─╯ ╰───────┬───────╯ -// Fork 5 of 20 Parent id -// -// The leading 0s are important. In the above example, you only need 3 bits to -// represent slot 5. However, you need 5 bits to represent all the forks at -// the current level, so we must account for the empty bits at the end. -// -// For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise, -// the zeroth id at a level would be indistinguishable from its parent. -// -// If a node has only one child, and does not materialize an id (i.e. does not -// contain a useId hook), then we don't need to allocate any space in the -// sequence. It's treated as a transparent indirection. For example, these two -// trees produce the same ids: -// -// <> <> -//
-// -// -// -// -// -// However, we cannot skip any node that materializes an id. Otherwise, a parent -// id that does not fork would be indistinguishable from its child id. For -// example, this tree does not fork, but the parent and child must have -// different ids. -// -// -// -// -// -// To handle this scenario, every time we materialize an id, we allocate a -// new level with a single slot. You can think of this as a fork with only one -// prong, or an array of children with length 1. -// -// It's possible for the size of the sequence to exceed 32 bits, the max -// size for bitwise operations. When this happens, we make more room by -// converting the right part of the id to a string and storing it in an overflow -// variable. We use a base 32 string representation, because 32 is the largest -// power of 2 that is supported by toString(). We want the base to be large so -// that the resulting ids are compact, and we want the base to be a power of 2 -// because every log2(base) bits corresponds to a single character, i.e. every -// log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without -// affecting the final result. -var emptyTreeContext = { - id: 1, - overflow: '' -}; -function getTreeId(context) { - var overflow = context.overflow; - var idWithLeadingBit = context.id; - var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); - return id.toString(32) + overflow; -} -function pushTreeContext(baseContext, totalChildren, index) { - var baseIdWithLeadingBit = baseContext.id; - var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part - // of the id; we use it to account for leading 0s. - - var baseLength = getBitLength(baseIdWithLeadingBit) - 1; - var baseId = baseIdWithLeadingBit & ~(1 << baseLength); - var slot = index + 1; - var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into - // consideration the leading 1 we use to mark the end of the sequence. - - if (length > 30) { - // We overflowed the bitwise-safe range. Fall back to slower algorithm. - // This branch assumes the length of the base id is greater than 5; it won't - // work for smaller ids, because you need 5 bits per character. - // - // We encode the id in multiple steps: first the base id, then the - // remaining digits. - // - // Each 5 bit sequence corresponds to a single base 32 character. So for - // example, if the current id is 23 bits long, we can convert 20 of those - // bits into a string of 4 characters, with 3 bits left over. - // - // First calculate how many bits in the base id represent a complete - // sequence of characters. - var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits. - - var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string. - - var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id. - - var restOfBaseId = baseId >> numberOfOverflowBits; - var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because - // we made more room, this time it won't overflow. - - var restOfLength = getBitLength(totalChildren) + restOfBaseLength; - var restOfNewBits = slot << restOfBaseLength; - var id = restOfNewBits | restOfBaseId; - var overflow = newOverflow + baseOverflow; - return { - id: 1 << restOfLength | id, - overflow: overflow - }; - } else { - // Normal path - var newBits = slot << baseLength; - - var _id = newBits | baseId; - - var _overflow = baseOverflow; - return { - id: 1 << length | _id, - overflow: _overflow - }; - } -} - -function getBitLength(number) { - return 32 - clz32(number); -} - -function getLeadingBit(id) { - return 1 << getBitLength(id) - 1; -} // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback. - - -var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. -// Based on: -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 - -var log = Math.log; -var LN2 = Math.LN2; - -function clz32Fallback(x) { - var asUint = x >>> 0; - - if (asUint === 0) { - return 32; - } - - return 31 - (log(asUint) / LN2 | 0) | 0; -} - -/** - * inlined Object.is polyfill to avoid requiring consumers ship their own - * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is - */ -function is(x, y) { - return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare - ; -} - -var objectIs = typeof Object.is === 'function' ? Object.is : is; - -var currentlyRenderingComponent = null; -var currentlyRenderingTask = null; -var firstWorkInProgressHook = null; -var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook - -var isReRender = false; // Whether an update was scheduled during the currently executing render pass. - -var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component - -var localIdCounter = 0; // Lazily created map of render-phase updates - -var renderPhaseUpdates = null; // Counter to prevent infinite loops. - -var numberOfReRenders = 0; -var RE_RENDER_LIMIT = 25; -var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook - -var currentHookNameInDev; - -function resolveCurrentlyRenderingComponent() { - if (currentlyRenderingComponent === null) { - throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.'); - } - - { - if (isInHookUserCodeInDev) { - error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks'); - } - } - - return currentlyRenderingComponent; -} - -function areHookInputsEqual(nextDeps, prevDeps) { - if (prevDeps === null) { - { - error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev); - } - - return false; - } - - { - // Don't bother comparing lengths in prod because these arrays should be - // passed inline. - if (nextDeps.length !== prevDeps.length) { - error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + nextDeps.join(', ') + "]", "[" + prevDeps.join(', ') + "]"); - } - } - - for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { - if (objectIs(nextDeps[i], prevDeps[i])) { - continue; - } - - return false; - } - - return true; -} - -function createHook() { - if (numberOfReRenders > 0) { - throw new Error('Rendered more hooks than during the previous render'); - } - - return { - memoizedState: null, - queue: null, - next: null - }; -} - -function createWorkInProgressHook() { - if (workInProgressHook === null) { - // This is the first hook in the list - if (firstWorkInProgressHook === null) { - isReRender = false; - firstWorkInProgressHook = workInProgressHook = createHook(); - } else { - // There's already a work-in-progress. Reuse it. - isReRender = true; - workInProgressHook = firstWorkInProgressHook; - } - } else { - if (workInProgressHook.next === null) { - isReRender = false; // Append to the end of the list - - workInProgressHook = workInProgressHook.next = createHook(); - } else { - // There's already a work-in-progress. Reuse it. - isReRender = true; - workInProgressHook = workInProgressHook.next; - } - } - - return workInProgressHook; -} - -function prepareToUseHooks(task, componentIdentity) { - currentlyRenderingComponent = componentIdentity; - currentlyRenderingTask = task; - - { - isInHookUserCodeInDev = false; - } // The following should have already been reset - // didScheduleRenderPhaseUpdate = false; - // localIdCounter = 0; - // firstWorkInProgressHook = null; - // numberOfReRenders = 0; - // renderPhaseUpdates = null; - // workInProgressHook = null; - - - localIdCounter = 0; -} -function finishHooks(Component, props, children, refOrContext) { - // This must be called after every function component to prevent hooks from - // being used in classes. - while (didScheduleRenderPhaseUpdate) { - // Updates were scheduled during the render phase. They are stored in - // the `renderPhaseUpdates` map. Call the component again, reusing the - // work-in-progress hooks and applying the additional updates on top. Keep - // restarting until no more updates are scheduled. - didScheduleRenderPhaseUpdate = false; - localIdCounter = 0; - numberOfReRenders += 1; // Start over from the beginning of the list - - workInProgressHook = null; - children = Component(props, refOrContext); - } - - resetHooksState(); - return children; -} -function checkDidRenderIdHook() { - // This should be called immediately after every finishHooks call. - // Conceptually, it's part of the return value of finishHooks; it's only a - // separate function to avoid using an array tuple. - var didRenderIdHook = localIdCounter !== 0; - return didRenderIdHook; -} // Reset the internal hooks state if an error occurs while rendering a component - -function resetHooksState() { - { - isInHookUserCodeInDev = false; - } - - currentlyRenderingComponent = null; - currentlyRenderingTask = null; - didScheduleRenderPhaseUpdate = false; - firstWorkInProgressHook = null; - numberOfReRenders = 0; - renderPhaseUpdates = null; - workInProgressHook = null; -} - -function readContext$1(context) { - { - if (isInHookUserCodeInDev) { - error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); - } - } - - return readContext(context); -} - -function useContext(context) { - { - currentHookNameInDev = 'useContext'; - } - - resolveCurrentlyRenderingComponent(); - return readContext(context); -} - -function basicStateReducer(state, action) { - // $FlowFixMe: Flow doesn't like mixed types - return typeof action === 'function' ? action(state) : action; -} - -function useState(initialState) { - { - currentHookNameInDev = 'useState'; - } - - return useReducer(basicStateReducer, // useReducer has a special case to support lazy useState initializers - initialState); -} -function useReducer(reducer, initialArg, init) { - { - if (reducer !== basicStateReducer) { - currentHookNameInDev = 'useReducer'; - } - } - - currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); - workInProgressHook = createWorkInProgressHook(); - - if (isReRender) { - // This is a re-render. Apply the new render phase updates to the previous - // current hook. - var queue = workInProgressHook.queue; - var dispatch = queue.dispatch; - - if (renderPhaseUpdates !== null) { - // Render phase updates are stored in a map of queue -> linked list - var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); - - if (firstRenderPhaseUpdate !== undefined) { - renderPhaseUpdates.delete(queue); - var newState = workInProgressHook.memoizedState; - var update = firstRenderPhaseUpdate; - - do { - // Process this render phase update. We don't have to check the - // priority because it will always be the same as the current - // render's. - var action = update.action; - - { - isInHookUserCodeInDev = true; - } - - newState = reducer(newState, action); - - { - isInHookUserCodeInDev = false; - } - - update = update.next; - } while (update !== null); - - workInProgressHook.memoizedState = newState; - return [newState, dispatch]; - } - } - - return [workInProgressHook.memoizedState, dispatch]; - } else { - { - isInHookUserCodeInDev = true; - } - - var initialState; - - if (reducer === basicStateReducer) { - // Special case for `useState`. - initialState = typeof initialArg === 'function' ? initialArg() : initialArg; - } else { - initialState = init !== undefined ? init(initialArg) : initialArg; - } - - { - isInHookUserCodeInDev = false; - } - - workInProgressHook.memoizedState = initialState; - - var _queue = workInProgressHook.queue = { - last: null, - dispatch: null - }; - - var _dispatch = _queue.dispatch = dispatchAction.bind(null, currentlyRenderingComponent, _queue); - - return [workInProgressHook.memoizedState, _dispatch]; - } -} - -function useMemo(nextCreate, deps) { - currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); - workInProgressHook = createWorkInProgressHook(); - var nextDeps = deps === undefined ? null : deps; - - if (workInProgressHook !== null) { - var prevState = workInProgressHook.memoizedState; - - if (prevState !== null) { - if (nextDeps !== null) { - var prevDeps = prevState[1]; - - if (areHookInputsEqual(nextDeps, prevDeps)) { - return prevState[0]; - } - } - } - } - - { - isInHookUserCodeInDev = true; - } - - var nextValue = nextCreate(); - - { - isInHookUserCodeInDev = false; - } - - workInProgressHook.memoizedState = [nextValue, nextDeps]; - return nextValue; -} - -function useRef(initialValue) { - currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); - workInProgressHook = createWorkInProgressHook(); - var previousRef = workInProgressHook.memoizedState; - - if (previousRef === null) { - var ref = { - current: initialValue - }; - - { - Object.seal(ref); - } - - workInProgressHook.memoizedState = ref; - return ref; - } else { - return previousRef; - } -} - -function useLayoutEffect(create, inputs) { - { - currentHookNameInDev = 'useLayoutEffect'; - - error('useLayoutEffect does nothing on the server, because its effect cannot ' + "be encoded into the server renderer's output format. This will lead " + 'to a mismatch between the initial, non-hydrated UI and the intended ' + 'UI. To avoid this, useLayoutEffect should only be used in ' + 'components that render exclusively on the client. ' + 'See https://reactjs.org/link/uselayouteffect-ssr for common fixes.'); - } -} - -function dispatchAction(componentIdentity, queue, action) { - if (numberOfReRenders >= RE_RENDER_LIMIT) { - throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.'); - } - - if (componentIdentity === currentlyRenderingComponent) { - // This is a render phase update. Stash it in a lazily-created map of - // queue -> linked list of updates. After this render pass, we'll restart - // and apply the stashed updates on top of the work-in-progress hook. - didScheduleRenderPhaseUpdate = true; - var update = { - action: action, - next: null - }; - - if (renderPhaseUpdates === null) { - renderPhaseUpdates = new Map(); - } - - var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); - - if (firstRenderPhaseUpdate === undefined) { - renderPhaseUpdates.set(queue, update); - } else { - // Append the update to the end of the list. - var lastRenderPhaseUpdate = firstRenderPhaseUpdate; - - while (lastRenderPhaseUpdate.next !== null) { - lastRenderPhaseUpdate = lastRenderPhaseUpdate.next; - } - - lastRenderPhaseUpdate.next = update; - } - } -} - -function useCallback(callback, deps) { - return useMemo(function () { - return callback; - }, deps); -} // TODO Decide on how to implement this hook for server rendering. -// If a mutation occurs during render, consider triggering a Suspense boundary -// and falling back to client rendering. - -function useMutableSource(source, getSnapshot, subscribe) { - resolveCurrentlyRenderingComponent(); - return getSnapshot(source._source); -} - -function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { - if (getServerSnapshot === undefined) { - throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.'); - } - - return getServerSnapshot(); -} - -function useDeferredValue(value) { - resolveCurrentlyRenderingComponent(); - return value; -} - -function unsupportedStartTransition() { - throw new Error('startTransition cannot be called during server rendering.'); -} - -function useTransition() { - resolveCurrentlyRenderingComponent(); - return [false, unsupportedStartTransition]; -} - -function useId() { - var task = currentlyRenderingTask; - var treeId = getTreeId(task.treeContext); - var responseState = currentResponseState; - - if (responseState === null) { - throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component.'); - } - - var localId = localIdCounter++; - return makeId(responseState, treeId, localId); -} - -function noop() {} - -var Dispatcher = { - readContext: readContext$1, - useContext: useContext, - useMemo: useMemo, - useReducer: useReducer, - useRef: useRef, - useState: useState, - useInsertionEffect: noop, - useLayoutEffect: useLayoutEffect, - useCallback: useCallback, - // useImperativeHandle is not run in the server environment - useImperativeHandle: noop, - // Effects are not run in the server environment. - useEffect: noop, - // Debugging effect - useDebugValue: noop, - useDeferredValue: useDeferredValue, - useTransition: useTransition, - useId: useId, - // Subscriptions are not setup in a server environment. - useMutableSource: useMutableSource, - useSyncExternalStore: useSyncExternalStore -}; - -var currentResponseState = null; -function setCurrentResponseState(responseState) { - currentResponseState = responseState; -} - -function getStackByComponentStackNode(componentStack) { - try { - var info = ''; - var node = componentStack; - - do { - switch (node.tag) { - case 0: - info += describeBuiltInComponentFrame(node.type, null, null); - break; - - case 1: - info += describeFunctionComponentFrame(node.type, null, null); - break; - - case 2: - info += describeClassComponentFrame(node.type, null, null); - break; - } - - node = node.parent; - } while (node); - - return info; - } catch (x) { - return '\nError generating stack: ' + x.message + '\n' + x.stack; - } -} - -var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; -var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; -var PENDING = 0; -var COMPLETED = 1; -var FLUSHED = 2; -var ABORTED = 3; -var ERRORED = 4; -var OPEN = 0; -var CLOSING = 1; -var CLOSED = 2; -// This is a default heuristic for how to split up the HTML content into progressive -// loading. Our goal is to be able to display additional new content about every 500ms. -// Faster than that is unnecessary and should be throttled on the client. It also -// adds unnecessary overhead to do more splits. We don't know if it's a higher or lower -// end device but higher end suffer less from the overhead than lower end does from -// not getting small enough pieces. We error on the side of low end. -// We base this on low end 3G speeds which is about 500kbits per second. We assume -// that there can be a reasonable drop off from max bandwidth which leaves you with -// as little as 80%. We can receive half of that each 500ms - at best. In practice, -// a little bandwidth is lost to processing and contention - e.g. CSS and images that -// are downloaded along with the main content. So we estimate about half of that to be -// the lower end throughput. In other words, we expect that you can at least show -// about 12.5kb of content per 500ms. Not counting starting latency for the first -// paint. -// 500 * 1024 / 8 * .8 * 0.5 / 2 -var DEFAULT_PROGRESSIVE_CHUNK_SIZE = 12800; - -function defaultErrorHandler(error) { - console['error'](error); // Don't transform to our wrapper - - return null; -} - -function noop$1() {} - -function createRequest(children, responseState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError) { - var pingedTasks = []; - var abortSet = new Set(); - var request = { - destination: null, - responseState: responseState, - progressiveChunkSize: progressiveChunkSize === undefined ? DEFAULT_PROGRESSIVE_CHUNK_SIZE : progressiveChunkSize, - status: OPEN, - fatalError: null, - nextSegmentId: 0, - allPendingTasks: 0, - pendingRootTasks: 0, - completedRootSegment: null, - abortableTasks: abortSet, - pingedTasks: pingedTasks, - clientRenderedBoundaries: [], - completedBoundaries: [], - partialBoundaries: [], - onError: onError === undefined ? defaultErrorHandler : onError, - onAllReady: onAllReady === undefined ? noop$1 : onAllReady, - onShellReady: onShellReady === undefined ? noop$1 : onShellReady, - onShellError: onShellError === undefined ? noop$1 : onShellError, - onFatalError: onFatalError === undefined ? noop$1 : onFatalError - }; // This segment represents the root fallback. - - var rootSegment = createPendingSegment(request, 0, null, rootFormatContext, // Root segments are never embedded in Text on either edge - false, false); // There is no parent so conceptually, we're unblocked to flush this segment. - - rootSegment.parentFlushed = true; - var rootTask = createTask(request, children, null, rootSegment, abortSet, emptyContextObject, rootContextSnapshot, emptyTreeContext); - pingedTasks.push(rootTask); - return request; -} - -function pingTask(request, task) { - var pingedTasks = request.pingedTasks; - pingedTasks.push(task); - - if (pingedTasks.length === 1) { - scheduleWork(function () { - return performWork(request); - }); - } -} - -function createSuspenseBoundary(request, fallbackAbortableTasks) { - return { - id: UNINITIALIZED_SUSPENSE_BOUNDARY_ID, - rootSegmentID: -1, - parentFlushed: false, - pendingTasks: 0, - forceClientRender: false, - completedSegments: [], - byteSize: 0, - fallbackAbortableTasks: fallbackAbortableTasks, - errorDigest: null - }; -} - -function createTask(request, node, blockedBoundary, blockedSegment, abortSet, legacyContext, context, treeContext) { - request.allPendingTasks++; - - if (blockedBoundary === null) { - request.pendingRootTasks++; - } else { - blockedBoundary.pendingTasks++; - } - - var task = { - node: node, - ping: function () { - return pingTask(request, task); - }, - blockedBoundary: blockedBoundary, - blockedSegment: blockedSegment, - abortSet: abortSet, - legacyContext: legacyContext, - context: context, - treeContext: treeContext - }; - - { - task.componentStack = null; - } - - abortSet.add(task); - return task; -} - -function createPendingSegment(request, index, boundary, formatContext, lastPushedText, textEmbedded) { - return { - status: PENDING, - id: -1, - // lazily assigned later - index: index, - parentFlushed: false, - chunks: [], - children: [], - formatContext: formatContext, - boundary: boundary, - lastPushedText: lastPushedText, - textEmbedded: textEmbedded - }; -} // DEV-only global reference to the currently executing task - - -var currentTaskInDEV = null; - -function getCurrentStackInDEV() { - { - if (currentTaskInDEV === null || currentTaskInDEV.componentStack === null) { - return ''; - } - - return getStackByComponentStackNode(currentTaskInDEV.componentStack); - } -} - -function pushBuiltInComponentStackInDEV(task, type) { - { - task.componentStack = { - tag: 0, - parent: task.componentStack, - type: type - }; - } -} - -function pushFunctionComponentStackInDEV(task, type) { - { - task.componentStack = { - tag: 1, - parent: task.componentStack, - type: type - }; - } -} - -function pushClassComponentStackInDEV(task, type) { - { - task.componentStack = { - tag: 2, - parent: task.componentStack, - type: type - }; - } -} - -function popComponentStackInDEV(task) { - { - if (task.componentStack === null) { - error('Unexpectedly popped too many stack frames. This is a bug in React.'); - } else { - task.componentStack = task.componentStack.parent; - } - } -} // stash the component stack of an unwinding error until it is processed - - -var lastBoundaryErrorComponentStackDev = null; - -function captureBoundaryErrorDetailsDev(boundary, error) { - { - var errorMessage; - - if (typeof error === 'string') { - errorMessage = error; - } else if (error && typeof error.message === 'string') { - errorMessage = error.message; - } else { - // eslint-disable-next-line react-internal/safe-string-coercion - errorMessage = String(error); - } - - var errorComponentStack = lastBoundaryErrorComponentStackDev || getCurrentStackInDEV(); - lastBoundaryErrorComponentStackDev = null; - boundary.errorMessage = errorMessage; - boundary.errorComponentStack = errorComponentStack; - } -} - -function logRecoverableError(request, error) { - // If this callback errors, we intentionally let that error bubble up to become a fatal error - // so that someone fixes the error reporting instead of hiding it. - var errorDigest = request.onError(error); - - if (errorDigest != null && typeof errorDigest !== 'string') { - // eslint-disable-next-line react-internal/prod-error-codes - throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead"); - } - - return errorDigest; -} - -function fatalError(request, error) { - // This is called outside error handling code such as if the root errors outside - // a suspense boundary or if the root suspense boundary's fallback errors. - // It's also called if React itself or its host configs errors. - var onShellError = request.onShellError; - onShellError(error); - var onFatalError = request.onFatalError; - onFatalError(error); - - if (request.destination !== null) { - request.status = CLOSED; - closeWithError(request.destination, error); - } else { - request.status = CLOSING; - request.fatalError = error; - } -} - -function renderSuspenseBoundary(request, task, props) { - pushBuiltInComponentStackInDEV(task, 'Suspense'); - var parentBoundary = task.blockedBoundary; - var parentSegment = task.blockedSegment; // Each time we enter a suspense boundary, we split out into a new segment for - // the fallback so that we can later replace that segment with the content. - // This also lets us split out the main content even if it doesn't suspend, - // in case it ends up generating a large subtree of content. - - var fallback = props.fallback; - var content = props.children; - var fallbackAbortSet = new Set(); - var newBoundary = createSuspenseBoundary(request, fallbackAbortSet); - var insertionIndex = parentSegment.chunks.length; // The children of the boundary segment is actually the fallback. - - var boundarySegment = createPendingSegment(request, insertionIndex, newBoundary, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them - false, false); - parentSegment.children.push(boundarySegment); // The parentSegment has a child Segment at this index so we reset the lastPushedText marker on the parent - - parentSegment.lastPushedText = false; // This segment is the actual child content. We can start rendering that immediately. - - var contentRootSegment = createPendingSegment(request, 0, null, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them - false, false); // We mark the root segment as having its parent flushed. It's not really flushed but there is - // no parent segment so there's nothing to wait on. - - contentRootSegment.parentFlushed = true; // Currently this is running synchronously. We could instead schedule this to pingedTasks. - // I suspect that there might be some efficiency benefits from not creating the suspended task - // and instead just using the stack if possible. - // TODO: Call this directly instead of messing with saving and restoring contexts. - // We can reuse the current context and task to render the content immediately without - // context switching. We just need to temporarily switch which boundary and which segment - // we're writing to. If something suspends, it'll spawn new suspended task with that context. - - task.blockedBoundary = newBoundary; - task.blockedSegment = contentRootSegment; - - try { - // We use the safe form because we don't handle suspending here. Only error handling. - renderNode(request, task, content); - pushSegmentFinale$1(contentRootSegment.chunks, request.responseState, contentRootSegment.lastPushedText, contentRootSegment.textEmbedded); - contentRootSegment.status = COMPLETED; - queueCompletedSegment(newBoundary, contentRootSegment); - - if (newBoundary.pendingTasks === 0) { - // This must have been the last segment we were waiting on. This boundary is now complete. - // Therefore we won't need the fallback. We early return so that we don't have to create - // the fallback. - popComponentStackInDEV(task); - return; - } - } catch (error) { - contentRootSegment.status = ERRORED; - newBoundary.forceClientRender = true; - newBoundary.errorDigest = logRecoverableError(request, error); - - { - captureBoundaryErrorDetailsDev(newBoundary, error); - } // We don't need to decrement any task numbers because we didn't spawn any new task. - // We don't need to schedule any task because we know the parent has written yet. - // We do need to fallthrough to create the fallback though. - - } finally { - task.blockedBoundary = parentBoundary; - task.blockedSegment = parentSegment; - } // We create suspended task for the fallback because we don't want to actually work - // on it yet in case we finish the main content, so we queue for later. - - - var suspendedFallbackTask = createTask(request, fallback, parentBoundary, boundarySegment, fallbackAbortSet, task.legacyContext, task.context, task.treeContext); - - { - suspendedFallbackTask.componentStack = task.componentStack; - } // TODO: This should be queued at a separate lower priority queue so that we only work - // on preparing fallbacks if we don't have any more main content to task on. - - - request.pingedTasks.push(suspendedFallbackTask); - popComponentStackInDEV(task); -} - -function renderHostElement(request, task, type, props) { - pushBuiltInComponentStackInDEV(task, type); - var segment = task.blockedSegment; - var children = pushStartInstance(segment.chunks, type, props, request.responseState, segment.formatContext); - segment.lastPushedText = false; - var prevContext = segment.formatContext; - segment.formatContext = getChildFormatContext(prevContext, type, props); // We use the non-destructive form because if something suspends, we still - // need to pop back up and finish this subtree of HTML. - - renderNode(request, task, children); // We expect that errors will fatal the whole task and that we don't need - // the correct context. Therefore this is not in a finally. - - segment.formatContext = prevContext; - pushEndInstance(segment.chunks, type); - segment.lastPushedText = false; - popComponentStackInDEV(task); -} - -function shouldConstruct$1(Component) { - return Component.prototype && Component.prototype.isReactComponent; -} - -function renderWithHooks(request, task, Component, props, secondArg) { - var componentIdentity = {}; - prepareToUseHooks(task, componentIdentity); - var result = Component(props, secondArg); - return finishHooks(Component, props, result, secondArg); -} - -function finishClassComponent(request, task, instance, Component, props) { - var nextChildren = instance.render(); - - { - if (instance.props !== props) { - if (!didWarnAboutReassigningProps) { - error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromType(Component) || 'a component'); - } - - didWarnAboutReassigningProps = true; - } - } - - { - var childContextTypes = Component.childContextTypes; - - if (childContextTypes !== null && childContextTypes !== undefined) { - var previousContext = task.legacyContext; - var mergedContext = processChildContext(instance, Component, previousContext, childContextTypes); - task.legacyContext = mergedContext; - renderNodeDestructive(request, task, nextChildren); - task.legacyContext = previousContext; - return; - } - } - - renderNodeDestructive(request, task, nextChildren); -} - -function renderClassComponent(request, task, Component, props) { - pushClassComponentStackInDEV(task, Component); - var maskedContext = getMaskedContext(Component, task.legacyContext) ; - var instance = constructClassInstance(Component, props, maskedContext); - mountClassInstance(instance, Component, props, maskedContext); - finishClassComponent(request, task, instance, Component, props); - popComponentStackInDEV(task); -} - -var didWarnAboutBadClass = {}; -var didWarnAboutModulePatternComponent = {}; -var didWarnAboutContextTypeOnFunctionComponent = {}; -var didWarnAboutGetDerivedStateOnFunctionComponent = {}; -var didWarnAboutReassigningProps = false; -var didWarnAboutDefaultPropsOnFunctionComponent = {}; -var didWarnAboutGenerators = false; -var didWarnAboutMaps = false; -var hasWarnedAboutUsingContextAsConsumer = false; // This would typically be a function component but we still support module pattern -// components for some reason. - -function renderIndeterminateComponent(request, task, Component, props) { - var legacyContext; - - { - legacyContext = getMaskedContext(Component, task.legacyContext); - } - - pushFunctionComponentStackInDEV(task, Component); - - { - if (Component.prototype && typeof Component.prototype.render === 'function') { - var componentName = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutBadClass[componentName]) { - error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName); - - didWarnAboutBadClass[componentName] = true; - } - } - } - - var value = renderWithHooks(request, task, Component, props, legacyContext); - var hasId = checkDidRenderIdHook(); - - { - // Support for module components is deprecated and is removed behind a flag. - // Whether or not it would crash later, we want to show a good message in DEV first. - if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { - var _componentName = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutModulePatternComponent[_componentName]) { - error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName); - - didWarnAboutModulePatternComponent[_componentName] = true; - } - } - } - - if ( // Run these checks in production only if the flag is off. - // Eventually we'll delete this branch altogether. - typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { - { - var _componentName2 = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutModulePatternComponent[_componentName2]) { - error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2); - - didWarnAboutModulePatternComponent[_componentName2] = true; - } - } - - mountClassInstance(value, Component, props, legacyContext); - finishClassComponent(request, task, value, Component, props); - } else { - - { - validateFunctionComponentInDev(Component); - } // We're now successfully past this task, and we don't have to pop back to - // the previous task every again, so we can use the destructive recursive form. - - - if (hasId) { - // This component materialized an id. We treat this as its own level, with - // a single "child" slot. - var prevTreeContext = task.treeContext; - var totalChildren = 1; - var index = 0; - task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index); - - try { - renderNodeDestructive(request, task, value); - } finally { - task.treeContext = prevTreeContext; - } - } else { - renderNodeDestructive(request, task, value); - } - } - - popComponentStackInDEV(task); -} - -function validateFunctionComponentInDev(Component) { - { - if (Component) { - if (Component.childContextTypes) { - error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component'); - } - } - - if ( Component.defaultProps !== undefined) { - var componentName = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) { - error('%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName); - - didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true; - } - } - - if (typeof Component.getDerivedStateFromProps === 'function') { - var _componentName3 = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) { - error('%s: Function components do not support getDerivedStateFromProps.', _componentName3); - - didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true; - } - } - - if (typeof Component.contextType === 'object' && Component.contextType !== null) { - var _componentName4 = getComponentNameFromType(Component) || 'Unknown'; - - if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) { - error('%s: Function components do not support contextType.', _componentName4); - - didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true; - } - } - } -} - -function resolveDefaultProps(Component, baseProps) { - if (Component && Component.defaultProps) { - // Resolve default props. Taken from ReactElement - var props = assign({}, baseProps); - var defaultProps = Component.defaultProps; - - for (var propName in defaultProps) { - if (props[propName] === undefined) { - props[propName] = defaultProps[propName]; - } - } - - return props; - } - - return baseProps; -} - -function renderForwardRef(request, task, type, props, ref) { - pushFunctionComponentStackInDEV(task, type.render); - var children = renderWithHooks(request, task, type.render, props, ref); - var hasId = checkDidRenderIdHook(); - - if (hasId) { - // This component materialized an id. We treat this as its own level, with - // a single "child" slot. - var prevTreeContext = task.treeContext; - var totalChildren = 1; - var index = 0; - task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index); - - try { - renderNodeDestructive(request, task, children); - } finally { - task.treeContext = prevTreeContext; - } - } else { - renderNodeDestructive(request, task, children); - } - - popComponentStackInDEV(task); -} - -function renderMemo(request, task, type, props, ref) { - var innerType = type.type; - var resolvedProps = resolveDefaultProps(innerType, props); - renderElement(request, task, innerType, resolvedProps, ref); -} - -function renderContextConsumer(request, task, context, props) { - // The logic below for Context differs depending on PROD or DEV mode. In - // DEV mode, we create a separate object for Context.Consumer that acts - // like a proxy to Context. This proxy object adds unnecessary code in PROD - // so we use the old behaviour (Context.Consumer references Context) to - // reduce size and overhead. The separate object references context via - // a property called "_context", which also gives us the ability to check - // in DEV mode if this property exists or not and warn if it does not. - { - if (context._context === undefined) { - // This may be because it's a Context (rather than a Consumer). - // Or it may be because it's older React where they're the same thing. - // We only want to warn if we're sure it's a new React. - if (context !== context.Consumer) { - if (!hasWarnedAboutUsingContextAsConsumer) { - hasWarnedAboutUsingContextAsConsumer = true; - - error('Rendering directly is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?'); - } - } - } else { - context = context._context; - } - } - - var render = props.children; - - { - if (typeof render !== 'function') { - error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.'); - } - } - - var newValue = readContext(context); - var newChildren = render(newValue); - renderNodeDestructive(request, task, newChildren); -} - -function renderContextProvider(request, task, type, props) { - var context = type._context; - var value = props.value; - var children = props.children; - var prevSnapshot; - - { - prevSnapshot = task.context; - } - - task.context = pushProvider(context, value); - renderNodeDestructive(request, task, children); - task.context = popProvider(context); - - { - if (prevSnapshot !== task.context) { - error('Popping the context provider did not return back to the original snapshot. This is a bug in React.'); - } - } -} - -function renderLazyComponent(request, task, lazyComponent, props, ref) { - pushBuiltInComponentStackInDEV(task, 'Lazy'); - var payload = lazyComponent._payload; - var init = lazyComponent._init; - var Component = init(payload); - var resolvedProps = resolveDefaultProps(Component, props); - renderElement(request, task, Component, resolvedProps, ref); - popComponentStackInDEV(task); -} - -function renderElement(request, task, type, props, ref) { - if (typeof type === 'function') { - if (shouldConstruct$1(type)) { - renderClassComponent(request, task, type, props); - return; - } else { - renderIndeterminateComponent(request, task, type, props); - return; - } - } - - if (typeof type === 'string') { - renderHostElement(request, task, type, props); - return; - } - - switch (type) { - // TODO: LegacyHidden acts the same as a fragment. This only works - // because we currently assume that every instance of LegacyHidden is - // accompanied by a host component wrapper. In the hidden mode, the host - // component is given a `hidden` attribute, which ensures that the - // initial HTML is not visible. To support the use of LegacyHidden as a - // true fragment, without an extra DOM node, we would have to hide the - // initial HTML in some other way. - // TODO: Add REACT_OFFSCREEN_TYPE here too with the same capability. - case REACT_LEGACY_HIDDEN_TYPE: - case REACT_DEBUG_TRACING_MODE_TYPE: - case REACT_STRICT_MODE_TYPE: - case REACT_PROFILER_TYPE: - case REACT_FRAGMENT_TYPE: - { - renderNodeDestructive(request, task, props.children); - return; - } - - case REACT_SUSPENSE_LIST_TYPE: - { - pushBuiltInComponentStackInDEV(task, 'SuspenseList'); // TODO: SuspenseList should control the boundaries. - - renderNodeDestructive(request, task, props.children); - popComponentStackInDEV(task); - return; - } - - case REACT_SCOPE_TYPE: - { - - throw new Error('ReactDOMServer does not yet support scope components.'); - } - // eslint-disable-next-line-no-fallthrough - - case REACT_SUSPENSE_TYPE: - { - { - renderSuspenseBoundary(request, task, props); - } - - return; - } - } - - if (typeof type === 'object' && type !== null) { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - { - renderForwardRef(request, task, type, props, ref); - return; - } - - case REACT_MEMO_TYPE: - { - renderMemo(request, task, type, props, ref); - return; - } - - case REACT_PROVIDER_TYPE: - { - renderContextProvider(request, task, type, props); - return; - } - - case REACT_CONTEXT_TYPE: - { - renderContextConsumer(request, task, type, props); - return; - } - - case REACT_LAZY_TYPE: - { - renderLazyComponent(request, task, type, props); - return; - } - } - } - - var info = ''; - - { - if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { - info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.'; - } - } - - throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info)); -} - -function validateIterable(iterable, iteratorFn) { - { - // We don't support rendering Generators because it's a mutation. - // See https://github.com/facebook/react/issues/12995 - if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag - iterable[Symbol.toStringTag] === 'Generator') { - if (!didWarnAboutGenerators) { - error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.'); - } - - didWarnAboutGenerators = true; - } // Warn about using Maps as children - - - if (iterable.entries === iteratorFn) { - if (!didWarnAboutMaps) { - error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.'); - } - - didWarnAboutMaps = true; - } - } -} - -function renderNodeDestructive(request, task, node) { - { - // In Dev we wrap renderNodeDestructiveImpl in a try / catch so we can capture - // a component stack at the right place in the tree. We don't do this in renderNode - // becuase it is not called at every layer of the tree and we may lose frames - try { - return renderNodeDestructiveImpl(request, task, node); - } catch (x) { - if (typeof x === 'object' && x !== null && typeof x.then === 'function') ; else { - // This is an error, stash the component stack if it is null. - lastBoundaryErrorComponentStackDev = lastBoundaryErrorComponentStackDev !== null ? lastBoundaryErrorComponentStackDev : getCurrentStackInDEV(); - } // rethrow so normal suspense logic can handle thrown value accordingly - - - throw x; - } - } -} // This function by it self renders a node and consumes the task by mutating it -// to update the current execution state. - - -function renderNodeDestructiveImpl(request, task, node) { - // Stash the node we're working on. We'll pick up from this task in case - // something suspends. - task.node = node; // Handle object types - - if (typeof node === 'object' && node !== null) { - switch (node.$$typeof) { - case REACT_ELEMENT_TYPE: - { - var element = node; - var type = element.type; - var props = element.props; - var ref = element.ref; - renderElement(request, task, type, props, ref); - return; - } - - case REACT_PORTAL_TYPE: - throw new Error('Portals are not currently supported by the server renderer. ' + 'Render them conditionally so that they only appear on the client render.'); - // eslint-disable-next-line-no-fallthrough - - case REACT_LAZY_TYPE: - { - var lazyNode = node; - var payload = lazyNode._payload; - var init = lazyNode._init; - var resolvedNode; - - { - try { - resolvedNode = init(payload); - } catch (x) { - if (typeof x === 'object' && x !== null && typeof x.then === 'function') { - // this Lazy initializer is suspending. push a temporary frame onto the stack so it can be - // popped off in spawnNewSuspendedTask. This aligns stack behavior between Lazy in element position - // vs Component position. We do not want the frame for Errors so we exclusively do this in - // the wakeable branch - pushBuiltInComponentStackInDEV(task, 'Lazy'); - } - - throw x; - } - } - - renderNodeDestructive(request, task, resolvedNode); - return; - } - } - - if (isArray(node)) { - renderChildrenArray(request, task, node); - return; - } - - var iteratorFn = getIteratorFn(node); - - if (iteratorFn) { - { - validateIterable(node, iteratorFn); - } - - var iterator = iteratorFn.call(node); - - if (iterator) { - // We need to know how many total children are in this set, so that we - // can allocate enough id slots to acommodate them. So we must exhaust - // the iterator before we start recursively rendering the children. - // TODO: This is not great but I think it's inherent to the id - // generation algorithm. - var step = iterator.next(); // If there are not entries, we need to push an empty so we start by checking that. - - if (!step.done) { - var children = []; - - do { - children.push(step.value); - step = iterator.next(); - } while (!step.done); - - renderChildrenArray(request, task, children); - return; - } - - return; - } - } - - var childString = Object.prototype.toString.call(node); - throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(node).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.'); - } - - if (typeof node === 'string') { - var segment = task.blockedSegment; - segment.lastPushedText = pushTextInstance$1(task.blockedSegment.chunks, node, request.responseState, segment.lastPushedText); - return; - } - - if (typeof node === 'number') { - var _segment = task.blockedSegment; - _segment.lastPushedText = pushTextInstance$1(task.blockedSegment.chunks, '' + node, request.responseState, _segment.lastPushedText); - return; - } - - { - if (typeof node === 'function') { - error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of from render. ' + 'Or maybe you meant to call this function rather than return it.'); - } - } -} - -function renderChildrenArray(request, task, children) { - var totalChildren = children.length; - - for (var i = 0; i < totalChildren; i++) { - var prevTreeContext = task.treeContext; - task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i); - - try { - // We need to use the non-destructive form so that we can safely pop back - // up and render the sibling if something suspends. - renderNode(request, task, children[i]); - } finally { - task.treeContext = prevTreeContext; - } - } -} - -function spawnNewSuspendedTask(request, task, x) { - // Something suspended, we'll need to create a new segment and resolve it later. - var segment = task.blockedSegment; - var insertionIndex = segment.chunks.length; - var newSegment = createPendingSegment(request, insertionIndex, null, segment.formatContext, // Adopt the parent segment's leading text embed - segment.lastPushedText, // Assume we are text embedded at the trailing edge - true); - segment.children.push(newSegment); // Reset lastPushedText for current Segment since the new Segment "consumed" it - - segment.lastPushedText = false; - var newTask = createTask(request, task.node, task.blockedBoundary, newSegment, task.abortSet, task.legacyContext, task.context, task.treeContext); - - { - if (task.componentStack !== null) { - // We pop one task off the stack because the node that suspended will be tried again, - // which will add it back onto the stack. - newTask.componentStack = task.componentStack.parent; - } - } - - var ping = newTask.ping; - x.then(ping, ping); -} // This is a non-destructive form of rendering a node. If it suspends it spawns -// a new task and restores the context of this task to what it was before. - - -function renderNode(request, task, node) { - // TODO: Store segment.children.length here and reset it in case something - // suspended partially through writing something. - // Snapshot the current context in case something throws to interrupt the - // process. - var previousFormatContext = task.blockedSegment.formatContext; - var previousLegacyContext = task.legacyContext; - var previousContext = task.context; - var previousComponentStack = null; - - { - previousComponentStack = task.componentStack; - } - - try { - return renderNodeDestructive(request, task, node); - } catch (x) { - resetHooksState(); - - if (typeof x === 'object' && x !== null && typeof x.then === 'function') { - spawnNewSuspendedTask(request, task, x); // Restore the context. We assume that this will be restored by the inner - // functions in case nothing throws so we don't use "finally" here. - - task.blockedSegment.formatContext = previousFormatContext; - task.legacyContext = previousLegacyContext; - task.context = previousContext; // Restore all active ReactContexts to what they were before. - - switchContext(previousContext); - - { - task.componentStack = previousComponentStack; - } - - return; - } else { - // Restore the context. We assume that this will be restored by the inner - // functions in case nothing throws so we don't use "finally" here. - task.blockedSegment.formatContext = previousFormatContext; - task.legacyContext = previousLegacyContext; - task.context = previousContext; // Restore all active ReactContexts to what they were before. - - switchContext(previousContext); - - { - task.componentStack = previousComponentStack; - } // We assume that we don't need the correct context. - // Let's terminate the rest of the tree and don't render any siblings. - - - throw x; - } - } -} - -function erroredTask(request, boundary, segment, error) { - // Report the error to a global handler. - var errorDigest = logRecoverableError(request, error); - - if (boundary === null) { - fatalError(request, error); - } else { - boundary.pendingTasks--; - - if (!boundary.forceClientRender) { - boundary.forceClientRender = true; - boundary.errorDigest = errorDigest; - - { - captureBoundaryErrorDetailsDev(boundary, error); - } // Regardless of what happens next, this boundary won't be displayed, - // so we can flush it, if the parent already flushed. - - - if (boundary.parentFlushed) { - // We don't have a preference where in the queue this goes since it's likely - // to error on the client anyway. However, intentionally client-rendered - // boundaries should be flushed earlier so that they can start on the client. - // We reuse the same queue for errors. - request.clientRenderedBoundaries.push(boundary); - } - } - } - - request.allPendingTasks--; - - if (request.allPendingTasks === 0) { - var onAllReady = request.onAllReady; - onAllReady(); - } -} - -function abortTaskSoft(task) { - // This aborts task without aborting the parent boundary that it blocks. - // It's used for when we didn't need this task to complete the tree. - // If task was needed, then it should use abortTask instead. - var request = this; - var boundary = task.blockedBoundary; - var segment = task.blockedSegment; - segment.status = ABORTED; - finishedTask(request, boundary, segment); -} - -function abortTask(task, request, reason) { - // This aborts the task and aborts the parent that it blocks, putting it into - // client rendered mode. - var boundary = task.blockedBoundary; - var segment = task.blockedSegment; - segment.status = ABORTED; - - if (boundary === null) { - request.allPendingTasks--; // We didn't complete the root so we have nothing to show. We can close - // the request; - - if (request.status !== CLOSED) { - request.status = CLOSED; - - if (request.destination !== null) { - close(request.destination); - } - } - } else { - boundary.pendingTasks--; - - if (!boundary.forceClientRender) { - boundary.forceClientRender = true; - - var _error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason; - - boundary.errorDigest = request.onError(_error); - - { - var errorPrefix = 'The server did not finish this Suspense boundary: '; - - if (_error && typeof _error.message === 'string') { - _error = errorPrefix + _error.message; - } else { - // eslint-disable-next-line react-internal/safe-string-coercion - _error = errorPrefix + String(_error); - } - - var previousTaskInDev = currentTaskInDEV; - currentTaskInDEV = task; - - try { - captureBoundaryErrorDetailsDev(boundary, _error); - } finally { - currentTaskInDEV = previousTaskInDev; - } - } - - if (boundary.parentFlushed) { - request.clientRenderedBoundaries.push(boundary); - } - } // If this boundary was still pending then we haven't already cancelled its fallbacks. - // We'll need to abort the fallbacks, which will also error that parent boundary. - - - boundary.fallbackAbortableTasks.forEach(function (fallbackTask) { - return abortTask(fallbackTask, request, reason); - }); - boundary.fallbackAbortableTasks.clear(); - request.allPendingTasks--; - - if (request.allPendingTasks === 0) { - var onAllReady = request.onAllReady; - onAllReady(); - } - } -} - -function queueCompletedSegment(boundary, segment) { - if (segment.chunks.length === 0 && segment.children.length === 1 && segment.children[0].boundary === null) { - // This is an empty segment. There's nothing to write, so we can instead transfer the ID - // to the child. That way any existing references point to the child. - var childSegment = segment.children[0]; - childSegment.id = segment.id; - childSegment.parentFlushed = true; - - if (childSegment.status === COMPLETED) { - queueCompletedSegment(boundary, childSegment); - } - } else { - var completedSegments = boundary.completedSegments; - completedSegments.push(segment); - } -} - -function finishedTask(request, boundary, segment) { - if (boundary === null) { - if (segment.parentFlushed) { - if (request.completedRootSegment !== null) { - throw new Error('There can only be one root segment. This is a bug in React.'); - } - - request.completedRootSegment = segment; - } - - request.pendingRootTasks--; - - if (request.pendingRootTasks === 0) { - // We have completed the shell so the shell can't error anymore. - request.onShellError = noop$1; - var onShellReady = request.onShellReady; - onShellReady(); - } - } else { - boundary.pendingTasks--; - - if (boundary.forceClientRender) ; else if (boundary.pendingTasks === 0) { - // This must have been the last segment we were waiting on. This boundary is now complete. - if (segment.parentFlushed) { - // Our parent segment already flushed, so we need to schedule this segment to be emitted. - // If it is a segment that was aborted, we'll write other content instead so we don't need - // to emit it. - if (segment.status === COMPLETED) { - queueCompletedSegment(boundary, segment); - } - } - - if (boundary.parentFlushed) { - // The segment might be part of a segment that didn't flush yet, but if the boundary's - // parent flushed, we need to schedule the boundary to be emitted. - request.completedBoundaries.push(boundary); - } // We can now cancel any pending task on the fallback since we won't need to show it anymore. - // This needs to happen after we read the parentFlushed flags because aborting can finish - // work which can trigger user code, which can start flushing, which can change those flags. - - - boundary.fallbackAbortableTasks.forEach(abortTaskSoft, request); - boundary.fallbackAbortableTasks.clear(); - } else { - if (segment.parentFlushed) { - // Our parent already flushed, so we need to schedule this segment to be emitted. - // If it is a segment that was aborted, we'll write other content instead so we don't need - // to emit it. - if (segment.status === COMPLETED) { - queueCompletedSegment(boundary, segment); - var completedSegments = boundary.completedSegments; - - if (completedSegments.length === 1) { - // This is the first time since we last flushed that we completed anything. - // We can schedule this boundary to emit its partially completed segments early - // in case the parent has already been flushed. - if (boundary.parentFlushed) { - request.partialBoundaries.push(boundary); - } - } - } - } - } - } - - request.allPendingTasks--; - - if (request.allPendingTasks === 0) { - // This needs to be called at the very end so that we can synchronously write the result - // in the callback if needed. - var onAllReady = request.onAllReady; - onAllReady(); - } -} - -function retryTask(request, task) { - var segment = task.blockedSegment; - - if (segment.status !== PENDING) { - // We completed this by other means before we had a chance to retry it. - return; - } // We restore the context to what it was when we suspended. - // We don't restore it after we leave because it's likely that we'll end up - // needing a very similar context soon again. - - - switchContext(task.context); - var prevTaskInDEV = null; - - { - prevTaskInDEV = currentTaskInDEV; - currentTaskInDEV = task; - } - - try { - // We call the destructive form that mutates this task. That way if something - // suspends again, we can reuse the same task instead of spawning a new one. - renderNodeDestructive(request, task, task.node); - pushSegmentFinale$1(segment.chunks, request.responseState, segment.lastPushedText, segment.textEmbedded); - task.abortSet.delete(task); - segment.status = COMPLETED; - finishedTask(request, task.blockedBoundary, segment); - } catch (x) { - resetHooksState(); - - if (typeof x === 'object' && x !== null && typeof x.then === 'function') { - // Something suspended again, let's pick it back up later. - var ping = task.ping; - x.then(ping, ping); - } else { - task.abortSet.delete(task); - segment.status = ERRORED; - erroredTask(request, task.blockedBoundary, segment, x); - } - } finally { - { - currentTaskInDEV = prevTaskInDEV; - } - } -} - -function performWork(request) { - if (request.status === CLOSED) { - return; - } - - var prevContext = getActiveContext(); - var prevDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = Dispatcher; - var prevGetCurrentStackImpl; - - { - prevGetCurrentStackImpl = ReactDebugCurrentFrame$1.getCurrentStack; - ReactDebugCurrentFrame$1.getCurrentStack = getCurrentStackInDEV; - } - - var prevResponseState = currentResponseState; - setCurrentResponseState(request.responseState); - - try { - var pingedTasks = request.pingedTasks; - var i; - - for (i = 0; i < pingedTasks.length; i++) { - var task = pingedTasks[i]; - retryTask(request, task); - } - - pingedTasks.splice(0, i); - - if (request.destination !== null) { - flushCompletedQueues(request, request.destination); - } - } catch (error) { - logRecoverableError(request, error); - fatalError(request, error); - } finally { - setCurrentResponseState(prevResponseState); - ReactCurrentDispatcher$1.current = prevDispatcher; - - { - ReactDebugCurrentFrame$1.getCurrentStack = prevGetCurrentStackImpl; - } - - if (prevDispatcher === Dispatcher) { - // This means that we were in a reentrant work loop. This could happen - // in a renderer that supports synchronous work like renderToString, - // when it's called from within another renderer. - // Normally we don't bother switching the contexts to their root/default - // values when leaving because we'll likely need the same or similar - // context again. However, when we're inside a synchronous loop like this - // we'll to restore the context to what it was before returning. - switchContext(prevContext); - } - } -} - -function flushSubtree(request, destination, segment) { - segment.parentFlushed = true; - - switch (segment.status) { - case PENDING: - { - // We're emitting a placeholder for this segment to be filled in later. - // Therefore we'll need to assign it an ID - to refer to it by. - var segmentID = segment.id = request.nextSegmentId++; // When this segment finally completes it won't be embedded in text since it will flush separately - - segment.lastPushedText = false; - segment.textEmbedded = false; - return writePlaceholder(destination, request.responseState, segmentID); - } - - case COMPLETED: - { - segment.status = FLUSHED; - var r = true; - var chunks = segment.chunks; - var chunkIdx = 0; - var children = segment.children; - - for (var childIdx = 0; childIdx < children.length; childIdx++) { - var nextChild = children[childIdx]; // Write all the chunks up until the next child. - - for (; chunkIdx < nextChild.index; chunkIdx++) { - writeChunk(destination, chunks[chunkIdx]); - } - - r = flushSegment(request, destination, nextChild); - } // Finally just write all the remaining chunks - - - for (; chunkIdx < chunks.length - 1; chunkIdx++) { - writeChunk(destination, chunks[chunkIdx]); - } - - if (chunkIdx < chunks.length) { - r = writeChunkAndReturn(destination, chunks[chunkIdx]); - } - - return r; - } - - default: - { - throw new Error('Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.'); - } - } -} - -function flushSegment(request, destination, segment) { - var boundary = segment.boundary; - - if (boundary === null) { - // Not a suspense boundary. - return flushSubtree(request, destination, segment); - } - - boundary.parentFlushed = true; // This segment is a Suspense boundary. We need to decide whether to - // emit the content or the fallback now. - - if (boundary.forceClientRender) { - // Emit a client rendered suspense boundary wrapper. - // We never queue the inner boundary so we'll never emit its content or partial segments. - writeStartClientRenderedSuspenseBoundary$1(destination, request.responseState, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack); // Flush the fallback. - - flushSubtree(request, destination, segment); - return writeEndClientRenderedSuspenseBoundary$1(destination, request.responseState); - } else if (boundary.pendingTasks > 0) { - // This boundary is still loading. Emit a pending suspense boundary wrapper. - // Assign an ID to refer to the future content by. - boundary.rootSegmentID = request.nextSegmentId++; - - if (boundary.completedSegments.length > 0) { - // If this is at least partially complete, we can queue it to be partially emitted early. - request.partialBoundaries.push(boundary); - } /// This is the first time we should have referenced this ID. - - - var id = boundary.id = assignSuspenseBoundaryID(request.responseState); - writeStartPendingSuspenseBoundary(destination, request.responseState, id); // Flush the fallback. - - flushSubtree(request, destination, segment); - return writeEndPendingSuspenseBoundary(destination, request.responseState); - } else if (boundary.byteSize > request.progressiveChunkSize) { - // This boundary is large and will be emitted separately so that we can progressively show - // other content. We add it to the queue during the flush because we have to ensure that - // the parent flushes first so that there's something to inject it into. - // We also have to make sure that it's emitted into the queue in a deterministic slot. - // I.e. we can't insert it here when it completes. - // Assign an ID to refer to the future content by. - boundary.rootSegmentID = request.nextSegmentId++; - request.completedBoundaries.push(boundary); // Emit a pending rendered suspense boundary wrapper. - - writeStartPendingSuspenseBoundary(destination, request.responseState, boundary.id); // Flush the fallback. - - flushSubtree(request, destination, segment); - return writeEndPendingSuspenseBoundary(destination, request.responseState); - } else { - // We can inline this boundary's content as a complete boundary. - writeStartCompletedSuspenseBoundary$1(destination, request.responseState); - var completedSegments = boundary.completedSegments; - - if (completedSegments.length !== 1) { - throw new Error('A previously unvisited boundary must have exactly one root segment. This is a bug in React.'); - } - - var contentSegment = completedSegments[0]; - flushSegment(request, destination, contentSegment); - return writeEndCompletedSuspenseBoundary$1(destination, request.responseState); - } -} - -function flushClientRenderedBoundary(request, destination, boundary) { - return writeClientRenderBoundaryInstruction(destination, request.responseState, boundary.id, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack); -} - -function flushSegmentContainer(request, destination, segment) { - writeStartSegment(destination, request.responseState, segment.formatContext, segment.id); - flushSegment(request, destination, segment); - return writeEndSegment(destination, segment.formatContext); -} - -function flushCompletedBoundary(request, destination, boundary) { - var completedSegments = boundary.completedSegments; - var i = 0; - - for (; i < completedSegments.length; i++) { - var segment = completedSegments[i]; - flushPartiallyCompletedSegment(request, destination, boundary, segment); - } - - completedSegments.length = 0; - return writeCompletedBoundaryInstruction(destination, request.responseState, boundary.id, boundary.rootSegmentID); -} - -function flushPartialBoundary(request, destination, boundary) { - var completedSegments = boundary.completedSegments; - var i = 0; - - for (; i < completedSegments.length; i++) { - var segment = completedSegments[i]; - - if (!flushPartiallyCompletedSegment(request, destination, boundary, segment)) { - i++; - completedSegments.splice(0, i); // Only write as much as the buffer wants. Something higher priority - // might want to write later. - - return false; - } - } - - completedSegments.splice(0, i); - return true; -} - -function flushPartiallyCompletedSegment(request, destination, boundary, segment) { - if (segment.status === FLUSHED) { - // We've already flushed this inline. - return true; - } - - var segmentID = segment.id; - - if (segmentID === -1) { - // This segment wasn't previously referred to. This happens at the root of - // a boundary. We make kind of a leap here and assume this is the root. - var rootSegmentID = segment.id = boundary.rootSegmentID; - - if (rootSegmentID === -1) { - throw new Error('A root segment ID must have been assigned by now. This is a bug in React.'); - } - - return flushSegmentContainer(request, destination, segment); - } else { - flushSegmentContainer(request, destination, segment); - return writeCompletedSegmentInstruction(destination, request.responseState, segmentID); - } -} - -function flushCompletedQueues(request, destination) { - - try { - // The structure of this is to go through each queue one by one and write - // until the sink tells us to stop. When we should stop, we still finish writing - // that item fully and then yield. At that point we remove the already completed - // items up until the point we completed them. - // TODO: Emit preloading. - // TODO: It's kind of unfortunate to keep checking this array after we've already - // emitted the root. - var completedRootSegment = request.completedRootSegment; - - if (completedRootSegment !== null && request.pendingRootTasks === 0) { - flushSegment(request, destination, completedRootSegment); - request.completedRootSegment = null; - writeCompletedRoot(destination, request.responseState); - } // We emit client rendering instructions for already emitted boundaries first. - // This is so that we can signal to the client to start client rendering them as - // soon as possible. - - - var clientRenderedBoundaries = request.clientRenderedBoundaries; - var i; - - for (i = 0; i < clientRenderedBoundaries.length; i++) { - var boundary = clientRenderedBoundaries[i]; - - if (!flushClientRenderedBoundary(request, destination, boundary)) { - request.destination = null; - i++; - clientRenderedBoundaries.splice(0, i); - return; - } - } - - clientRenderedBoundaries.splice(0, i); // Next we emit any complete boundaries. It's better to favor boundaries - // that are completely done since we can actually show them, than it is to emit - // any individual segments from a partially complete boundary. - - var completedBoundaries = request.completedBoundaries; - - for (i = 0; i < completedBoundaries.length; i++) { - var _boundary = completedBoundaries[i]; - - if (!flushCompletedBoundary(request, destination, _boundary)) { - request.destination = null; - i++; - completedBoundaries.splice(0, i); - return; - } - } - - completedBoundaries.splice(0, i); // Allow anything written so far to flush to the underlying sink before - // we continue with lower priorities. - - completeWriting(destination); - beginWriting(destination); // TODO: Here we'll emit data used by hydration. - // Next we emit any segments of any boundaries that are partially complete - // but not deeply complete. - - var partialBoundaries = request.partialBoundaries; - - for (i = 0; i < partialBoundaries.length; i++) { - var _boundary2 = partialBoundaries[i]; - - if (!flushPartialBoundary(request, destination, _boundary2)) { - request.destination = null; - i++; - partialBoundaries.splice(0, i); - return; - } - } - - partialBoundaries.splice(0, i); // Next we check the completed boundaries again. This may have had - // boundaries added to it in case they were too larged to be inlined. - // New ones might be added in this loop. - - var largeBoundaries = request.completedBoundaries; - - for (i = 0; i < largeBoundaries.length; i++) { - var _boundary3 = largeBoundaries[i]; - - if (!flushCompletedBoundary(request, destination, _boundary3)) { - request.destination = null; - i++; - largeBoundaries.splice(0, i); - return; - } - } - - largeBoundaries.splice(0, i); - } finally { - - if (request.allPendingTasks === 0 && request.pingedTasks.length === 0 && request.clientRenderedBoundaries.length === 0 && request.completedBoundaries.length === 0 // We don't need to check any partially completed segments because - // either they have pending task or they're complete. - ) { - { - if (request.abortableTasks.size !== 0) { - error('There was still abortable task at the root when we closed. This is a bug in React.'); - } - } // We're done. - - - close(destination); - } - } -} - -function startWork(request) { - scheduleWork(function () { - return performWork(request); - }); -} -function startFlowing(request, destination) { - if (request.status === CLOSING) { - request.status = CLOSED; - closeWithError(destination, request.fatalError); - return; - } - - if (request.status === CLOSED) { - return; - } - - if (request.destination !== null) { - // We're already flowing. - return; - } - - request.destination = destination; - - try { - flushCompletedQueues(request, destination); - } catch (error) { - logRecoverableError(request, error); - fatalError(request, error); - } -} // This is called to early terminate a request. It puts all pending boundaries in client rendered state. - -function abort(request, reason) { - try { - var abortableTasks = request.abortableTasks; - abortableTasks.forEach(function (task) { - return abortTask(task, request, reason); - }); - abortableTasks.clear(); - - if (request.destination !== null) { - flushCompletedQueues(request, request.destination); - } - } catch (error) { - logRecoverableError(request, error); - fatalError(request, error); - } -} - -function onError() {// Non-fatal errors are ignored. -} - -function renderToStringImpl(children, options, generateStaticMarkup, abortReason) { - var didFatal = false; - var fatalError = null; - var result = ''; - var destination = { - push: function (chunk) { - if (chunk !== null) { - result += chunk; - } - - return true; - }, - destroy: function (error) { - didFatal = true; - fatalError = error; - } - }; - var readyToStream = false; - - function onShellReady() { - readyToStream = true; - } - - var request = createRequest(children, createResponseState$1(generateStaticMarkup, options ? options.identifierPrefix : undefined), createRootFormatContext(), Infinity, onError, undefined, onShellReady, undefined, undefined); - startWork(request); // If anything suspended and is still pending, we'll abort it before writing. - // That way we write only client-rendered boundaries from the start. - - abort(request, abortReason); - startFlowing(request, destination); - - if (didFatal) { - throw fatalError; - } - - if (!readyToStream) { - // Note: This error message is the one we use on the client. It doesn't - // really make sense here. But this is the legacy server renderer, anyway. - // We're going to delete it soon. - throw new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To fix, ' + 'updates that suspend should be wrapped with startTransition.'); - } - - return result; -} - -function renderToString(children, options) { - return renderToStringImpl(children, options, false, 'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server'); -} - -function renderToStaticMarkup(children, options) { - return renderToStringImpl(children, options, true, 'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server'); -} - -function renderToNodeStream() { - throw new Error('ReactDOMServer.renderToNodeStream(): The streaming API is not available ' + 'in the browser. Use ReactDOMServer.renderToString() instead.'); -} - -function renderToStaticNodeStream() { - throw new Error('ReactDOMServer.renderToStaticNodeStream(): The streaming API is not available ' + 'in the browser. Use ReactDOMServer.renderToStaticMarkup() instead.'); -} - -exports.renderToNodeStream = renderToNodeStream; -exports.renderToStaticMarkup = renderToStaticMarkup; -exports.renderToStaticNodeStream = renderToStaticNodeStream; -exports.renderToString = renderToString; -exports.version = ReactVersion; - })(); -} diff --git a/node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js b/node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js deleted file mode 100644 index 15683656..00000000 --- a/node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js +++ /dev/null @@ -1,93 +0,0 @@ -/** - * @license React - * react-dom-server-legacy.browser.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ -'use strict';var aa=require("react");function l(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c