{"ast":null,"code":"/**\n * @remix-run/router v1.16.1\n *\n * Copyright (c) Remix Software Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.md file in the root directory of this source tree.\n *\n * @license MIT\n */\nfunction _extends() {\n  _extends = Object.assign ? Object.assign.bind() : function (target) {\n    for (var i = 1; i < arguments.length; i++) {\n      var source = arguments[i];\n      for (var key in source) {\n        if (Object.prototype.hasOwnProperty.call(source, key)) {\n          target[key] = source[key];\n        }\n      }\n    }\n    return target;\n  };\n  return _extends.apply(this, arguments);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n/**\n * Actions represent the type of change to a location value.\n */\nvar Action;\n(function (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  Action[\"Pop\"] = \"POP\";\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  Action[\"Push\"] = \"PUSH\";\n  /**\n   * A REPLACE indicates the entry at the current index in the history stack\n   * being replaced by a new one.\n   */\n  Action[\"Replace\"] = \"REPLACE\";\n})(Action || (Action = {}));\nconst PopStateEventType = \"popstate\";\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 */\nfunction createMemoryHistory(options) {\n  if (options === void 0) {\n    options = {};\n  }\n  let {\n    initialEntries = [\"/\"],\n    initialIndex,\n    v5Compat = false\n  } = options;\n  let entries; // Declare so we can access from createMemoryLocation\n  entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === \"string\" ? null : entry.state, index === 0 ? \"default\" : undefined));\n  let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);\n  let action = Action.Pop;\n  let listener = null;\n  function clampIndex(n) {\n    return Math.min(Math.max(n, 0), entries.length - 1);\n  }\n  function getCurrentLocation() {\n    return entries[index];\n  }\n  function createMemoryLocation(to, state, key) {\n    if (state === void 0) {\n      state = null;\n    }\n    let location = createLocation(entries ? getCurrentLocation().pathname : \"/\", to, state, key);\n    warning(location.pathname.charAt(0) === \"/\", \"relative pathnames are not supported in memory history: \" + JSON.stringify(to));\n    return location;\n  }\n  function createHref(to) {\n    return typeof to === \"string\" ? to : createPath(to);\n  }\n  let history = {\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) {\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({\n          action,\n          location: nextLocation,\n          delta: 1\n        });\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({\n          action,\n          location: nextLocation,\n          delta: 0\n        });\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({\n          action,\n          location: nextLocation,\n          delta\n        });\n      }\n    },\n    listen(fn) {\n      listener = fn;\n      return () => {\n        listener = null;\n      };\n    }\n  };\n  return history;\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 */\nfunction createBrowserHistory(options) {\n  if (options === void 0) {\n    options = {};\n  }\n  function createBrowserLocation(window, globalHistory) {\n    let {\n      pathname,\n      search,\n      hash\n    } = window.location;\n    return createLocation(\"\", {\n      pathname,\n      search,\n      hash\n    },\n    // state defaults to `null` because `window.history.state` does\n    globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || \"default\");\n  }\n  function createBrowserHref(window, to) {\n    return typeof to === \"string\" ? to : createPath(to);\n  }\n  return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);\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 */\nfunction createHashHistory(options) {\n  if (options === void 0) {\n    options = {};\n  }\n  function createHashLocation(window, globalHistory) {\n    let {\n      pathname = \"/\",\n      search = \"\",\n      hash = \"\"\n    } = parsePath(window.location.hash.substr(1));\n    // Hash URL should always have a leading / just like window.location.pathname\n    // does, so if an app ends up at a route like /#something then we add a\n    // leading slash so all of our path-matching behaves the same as if it would\n    // in a browser router.  This is particularly important when there exists a\n    // root splat route (<Route path=\"*\">) since that matches internally against\n    // \"/*\" and we'd expect /#something to 404 in a hash router app.\n    if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n      pathname = \"/\" + pathname;\n    }\n    return createLocation(\"\", {\n      pathname,\n      search,\n      hash\n    },\n    // state defaults to `null` because `window.history.state` does\n    globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || \"default\");\n  }\n  function createHashHref(window, to) {\n    let base = window.document.querySelector(\"base\");\n    let href = \"\";\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    return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n  }\n  function validateHashLocation(location, to) {\n    warning(location.pathname.charAt(0) === \"/\", \"relative pathnames are not supported in hash history.push(\" + JSON.stringify(to) + \")\");\n  }\n  return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);\n}\nfunction invariant(value, message) {\n  if (value === false || value === null || typeof value === \"undefined\") {\n    throw new Error(message);\n  }\n}\nfunction warning(cond, message) {\n  if (!cond) {\n    // eslint-disable-next-line no-console\n    if (typeof console !== \"undefined\") console.warn(message);\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}\nfunction createKey() {\n  return Math.random().toString(36).substr(2, 8);\n}\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location, index) {\n  return {\n    usr: location.state,\n    key: location.key,\n    idx: index\n  };\n}\n/**\n * Creates a Location object with a unique key from the given Path\n */\nfunction createLocation(current, to, state, key) {\n  if (state === void 0) {\n    state = null;\n  }\n  let location = _extends({\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.key || key || createKey()\n  });\n  return location;\n}\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nfunction createPath(_ref) {\n  let {\n    pathname = \"/\",\n    search = \"\",\n    hash = \"\"\n  } = _ref;\n  if (search && search !== \"?\") pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n  if (hash && hash !== \"#\") pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n  return pathname;\n}\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nfunction parsePath(path) {\n  let parsedPath = {};\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    let searchIndex = path.indexOf(\"?\");\n    if (searchIndex >= 0) {\n      parsedPath.search = path.substr(searchIndex);\n      path = path.substr(0, searchIndex);\n    }\n    if (path) {\n      parsedPath.pathname = path;\n    }\n  }\n  return parsedPath;\n}\nfunction getUrlBasedHistory(getLocation, createHref, validateLocation, options) {\n  if (options === void 0) {\n    options = {};\n  }\n  let {\n    window = document.defaultView,\n    v5Compat = false\n  } = options;\n  let globalHistory = window.history;\n  let action = Action.Pop;\n  let listener = null;\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(_extends({}, globalHistory.state, {\n      idx: index\n    }), \"\");\n  }\n  function getIndex() {\n    let state = globalHistory.state || {\n      idx: null\n    };\n    return state.idx;\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({\n        action,\n        location: history.location,\n        delta\n      });\n    }\n  }\n  function push(to, state) {\n    action = Action.Push;\n    let location = createLocation(history.location, to, state);\n    if (validateLocation) validateLocation(location, to);\n    index = getIndex() + 1;\n    let historyState = getHistoryState(location, index);\n    let url = history.createHref(location);\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    if (v5Compat && listener) {\n      listener({\n        action,\n        location: history.location,\n        delta: 1\n      });\n    }\n  }\n  function replace(to, state) {\n    action = Action.Replace;\n    let location = createLocation(history.location, to, state);\n    if (validateLocation) validateLocation(location, to);\n    index = getIndex();\n    let historyState = getHistoryState(location, index);\n    let url = history.createHref(location);\n    globalHistory.replaceState(historyState, \"\", url);\n    if (v5Compat && listener) {\n      listener({\n        action,\n        location: history.location,\n        delta: 0\n      });\n    }\n  }\n  function createURL(to) {\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 = window.location.origin !== \"null\" ? window.location.origin : window.location.href;\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(base, \"No window.location.(origin|href) available to create URL for href: \" + href);\n    return new URL(href, base);\n  }\n  let history = {\n    get action() {\n      return action;\n    },\n    get location() {\n      return getLocation(window, globalHistory);\n    },\n    listen(fn) {\n      if (listener) {\n        throw new Error(\"A history only accepts one active listener\");\n      }\n      window.addEventListener(PopStateEventType, handlePop);\n      listener = fn;\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  return history;\n}\n//#endregion\n\nvar ResultType;\n(function (ResultType) {\n  ResultType[\"data\"] = \"data\";\n  ResultType[\"deferred\"] = \"deferred\";\n  ResultType[\"redirect\"] = \"redirect\";\n  ResultType[\"error\"] = \"error\";\n})(ResultType || (ResultType = {}));\nconst immutableRouteKeys = new Set([\"lazy\", \"caseSensitive\", \"path\", \"id\", \"index\", \"children\"]);\nfunction isIndexRoute(route) {\n  return route.index === true;\n}\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nfunction convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) {\n  if (parentPath === void 0) {\n    parentPath = [];\n  }\n  if (manifest === void 0) {\n    manifest = {};\n  }\n  return routes.map((route, index) => {\n    let treePath = [...parentPath, index];\n    let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n    invariant(route.index !== true || !route.children, \"Cannot specify children on an index route\");\n    invariant(!manifest[id], \"Found a route id collision on id \\\"\" + id + \"\\\".  Route \" + \"id's must be globally unique within Data Router usages\");\n    if (isIndexRoute(route)) {\n      let indexRoute = _extends({}, route, mapRouteProperties(route), {\n        id\n      });\n      manifest[id] = indexRoute;\n      return indexRoute;\n    } else {\n      let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), {\n        id,\n        children: undefined\n      });\n      manifest[id] = pathOrLayoutRoute;\n      if (route.children) {\n        pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest);\n      }\n      return pathOrLayoutRoute;\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 */\nfunction matchRoutes(routes, locationArg, basename) {\n  if (basename === void 0) {\n    basename = \"/\";\n  }\n  let location = typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n  let pathname = stripBasename(location.pathname || \"/\", basename);\n  if (pathname == null) {\n    return null;\n  }\n  let branches = flattenRoutes(routes);\n  rankRouteBranches(branches);\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  return matches;\n}\nfunction convertRouteMatchToUiMatch(match, loaderData) {\n  let {\n    route,\n    pathname,\n    params\n  } = match;\n  return {\n    id: route.id,\n    pathname,\n    params,\n    data: loaderData[route.id],\n    handle: route.handle\n  };\n}\nfunction flattenRoutes(routes, branches, parentsMeta, parentPath) {\n  if (branches === void 0) {\n    branches = [];\n  }\n  if (parentsMeta === void 0) {\n    parentsMeta = [];\n  }\n  if (parentPath === void 0) {\n    parentPath = \"\";\n  }\n  let flattenRoute = (route, index, relativePath) => {\n    let meta = {\n      relativePath: relativePath === undefined ? route.path || \"\" : relativePath,\n      caseSensitive: route.caseSensitive === true,\n      childrenIndex: index,\n      route\n    };\n    if (meta.relativePath.startsWith(\"/\")) {\n      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.\");\n      meta.relativePath = meta.relativePath.slice(parentPath.length);\n    }\n    let path = joinPaths([parentPath, meta.relativePath]);\n    let routesMeta = parentsMeta.concat(meta);\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, \"Index routes must not have child routes. Please remove \" + (\"all child routes from route path \\\"\" + path + \"\\\".\"));\n      flattenRoutes(route.children, branches, routesMeta, path);\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    branches.push({\n      path,\n      score: computeScore(path, route.index),\n      routesMeta\n    });\n  };\n  routes.forEach((route, index) => {\n    var _route$path;\n    // coarse-grain check for optional params\n    if (route.path === \"\" || !((_route$path = route.path) != null && _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  return branches;\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) {\n  let segments = path.split(\"/\");\n  if (segments.length === 0) return [];\n  let [first, ...rest] = segments;\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  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  let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n  let result = [];\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(...restExploded.map(subpath => subpath === \"\" ? required : [required, subpath].join(\"/\")));\n  // Then, if this is an optional value, add all child versions without\n  if (isOptional) {\n    result.push(...restExploded);\n  }\n  // for absolute paths, ensure `/` instead of empty segment\n  return result.map(exploded => path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded);\n}\nfunction rankRouteBranches(branches) {\n  branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first\n  : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));\n}\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = s => s === \"*\";\nfunction computeScore(path, index) {\n  let segments = path.split(\"/\");\n  let initialScore = segments.length;\n  if (segments.some(isSplat)) {\n    initialScore += splatPenalty;\n  }\n  if (index) {\n    initialScore += indexRouteValue;\n  }\n  return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === \"\" ? emptySegmentValue : staticSegmentValue), initialScore);\n}\nfunction compareIndexes(a, b) {\n  let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\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}\nfunction matchRouteBranch(branch, pathname) {\n  let {\n    routesMeta\n  } = branch;\n  let matchedParams = {};\n  let matchedPathname = \"/\";\n  let matches = [];\n  for (let i = 0; i < routesMeta.length; ++i) {\n    let meta = routesMeta[i];\n    let end = i === routesMeta.length - 1;\n    let remainingPathname = matchedPathname === \"/\" ? pathname : pathname.slice(matchedPathname.length) || \"/\";\n    let match = matchPath({\n      path: meta.relativePath,\n      caseSensitive: meta.caseSensitive,\n      end\n    }, remainingPathname);\n    if (!match) return null;\n    Object.assign(matchedParams, match.params);\n    let route = meta.route;\n    matches.push({\n      // TODO: Can this as be avoided?\n      params: matchedParams,\n      pathname: joinPaths([matchedPathname, match.pathname]),\n      pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),\n      route\n    });\n    if (match.pathnameBase !== \"/\") {\n      matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n    }\n  }\n  return matches;\n}\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/utils/generate-path\n */\nfunction generatePath(originalPath, params) {\n  if (params === void 0) {\n    params = {};\n  }\n  let path = originalPath;\n  if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n    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(/\\*$/, \"/*\") + \"\\\".\"));\n    path = path.replace(/\\*$/, \"/*\");\n  }\n  // ensure `/` is added at the beginning if the path is absolute\n  const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n  const stringify = p => p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n  const segments = path.split(/\\/+/).map((segment, index, array) => {\n    const isLastSegment = index === array.length - 1;\n    // only apply the splat if it's the last segment\n    if (isLastSegment && segment === \"*\") {\n      const star = \"*\";\n      // Apply the splat\n      return stringify(params[star]);\n    }\n    const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n    if (keyMatch) {\n      const [, key, optional] = keyMatch;\n      let param = params[key];\n      invariant(optional === \"?\" || param != null, \"Missing \\\":\" + key + \"\\\" param\");\n      return stringify(param);\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  return prefix + segments.join(\"/\");\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 */\nfunction matchPath(pattern, pathname) {\n  if (typeof pattern === \"string\") {\n    pattern = {\n      path: pattern,\n      caseSensitive: false,\n      end: true\n    };\n  }\n  let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);\n  let match = pathname.match(matcher);\n  if (!match) return null;\n  let matchedPathname = match[0];\n  let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n  let captureGroups = match.slice(1);\n  let params = compiledParams.reduce((memo, _ref, index) => {\n    let {\n      paramName,\n      isOptional\n    } = _ref;\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.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\\/+$/, \"$1\");\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  return {\n    params,\n    pathname: matchedPathname,\n    pathnameBase,\n    pattern\n  };\n}\nfunction compilePath(path, caseSensitive, end) {\n  if (caseSensitive === void 0) {\n    caseSensitive = false;\n  }\n  if (end === void 0) {\n    end = true;\n  }\n  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(/\\*$/, \"/*\") + \"\\\".\"));\n  let params = [];\n  let regexpSource = \"^\" + path.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(/\\/:([\\w-]+)(\\?)?/g, (_, paramName, isOptional) => {\n    params.push({\n      paramName,\n      isOptional: isOptional != null\n    });\n    return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n  });\n  if (path.endsWith(\"*\")) {\n    params.push({\n      paramName: \"*\"\n    });\n    regexpSource += path === \"*\" || path === \"/*\" ? \"(.*)$\" // 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  let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n  return [matcher, params];\n}\nfunction decodePath(value) {\n  try {\n    return value.split(\"/\").map(v => decodeURIComponent(v).replace(/\\//g, \"%2F\")).join(\"/\");\n  } catch (error) {\n    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 + \").\"));\n    return value;\n  }\n}\n/**\n * @private\n */\nfunction stripBasename(pathname, basename) {\n  if (basename === \"/\") return pathname;\n  if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n    return null;\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(\"/\") ? basename.length - 1 : basename.length;\n  let nextChar = pathname.charAt(startIndex);\n  if (nextChar && nextChar !== \"/\") {\n    // pathname does not start with basename/\n    return null;\n  }\n  return pathname.slice(startIndex) || \"/\";\n}\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/utils/resolve-path\n */\nfunction resolvePath(to, fromPathname) {\n  if (fromPathname === void 0) {\n    fromPathname = \"/\";\n  }\n  let {\n    pathname: toPathname,\n    search = \"\",\n    hash = \"\"\n  } = typeof to === \"string\" ? parsePath(to) : to;\n  let pathname = toPathname ? toPathname.startsWith(\"/\") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;\n  return {\n    pathname,\n    search: normalizeSearch(search),\n    hash: normalizeHash(hash)\n  };\n}\nfunction resolvePathname(relativePath, fromPathname) {\n  let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n  let relativeSegments = relativePath.split(\"/\");\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  return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\nfunction getInvalidPathError(char, field, dest, path) {\n  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 <Link to=\\\"...\\\"> and the router will parse it for you.\";\n}\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same.  Both of the following examples should link back to the root:\n *\n *   <Route path=\"/\">\n *     <Route path=\"accounts\" element={<Link to=\"..\"}>\n *   </Route>\n *\n *   <Route path=\"/\">\n *     <Route path=\"accounts\">\n *       <Route element={<AccountsLayout />}>       // <-- Does not contribute\n *         <Route index element={<Link to=\"..\"} />  // <-- Does not contribute\n *       </Route\n *     </Route>\n *   </Route>\n */\nfunction getPathContributingMatches(matches) {\n  return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);\n}\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nfunction getResolveToMatches(matches, v7_relativeSplatPath) {\n  let pathMatches = getPathContributingMatches(matches);\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) => idx === matches.length - 1 ? match.pathname : match.pathnameBase);\n  }\n  return pathMatches.map(match => match.pathnameBase);\n}\n/**\n * @private\n */\nfunction resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {\n  if (isPathRelative === void 0) {\n    isPathRelative = false;\n  }\n  let to;\n  if (typeof toArg === \"string\") {\n    to = parsePath(toArg);\n  } else {\n    to = _extends({}, toArg);\n    invariant(!to.pathname || !to.pathname.includes(\"?\"), getInvalidPathError(\"?\", \"pathname\", \"search\", to));\n    invariant(!to.pathname || !to.pathname.includes(\"#\"), getInvalidPathError(\"#\", \"pathname\", \"hash\", to));\n    invariant(!to.search || !to.search.includes(\"#\"), getInvalidPathError(\"#\", \"search\", \"hash\", to));\n  }\n  let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n  let toPathname = isEmptyPath ? \"/\" : to.pathname;\n  let from;\n  // Routing is relative to the current pathname if explicitly requested.\n  //\n  // If a pathname is explicitly provided in `to`, it should be relative to the\n  // route context. This is explained in `Note on `<Link to>` values` in our\n  // migration guide from v5 as a means of disambiguation between `to` values\n  // that begin with `/` and those that do not. However, this is problematic for\n  // `to` values that do not provide a pathname. `to` can simply be a search or\n  // hash string, in which case we should assume that the navigation is relative\n  // to the current location's pathname and *not* the route pathname.\n  if (toPathname == null) {\n    from = locationPathname;\n  } else {\n    let routePathnameIndex = routePathnames.length - 1;\n    // With relative=\"route\" (the default), each leading .. segment means\n    // \"go up one route\" instead of \"go up one URL segment\".  This is a key\n    // difference from how <a href> works and a major reason we call this a\n    // \"to\" value instead of a \"href\".\n    if (!isPathRelative && toPathname.startsWith(\"..\")) {\n      let toSegments = toPathname.split(\"/\");\n      while (toSegments[0] === \"..\") {\n        toSegments.shift();\n        routePathnameIndex -= 1;\n      }\n      to.pathname = toSegments.join(\"/\");\n    }\n    from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n  }\n  let path = resolvePath(to, from);\n  // Ensure the pathname has a trailing slash if the original \"to\" had one\n  let hasExplicitTrailingSlash = toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n  // Or if this was a link to the current path which has a trailing slash\n  let hasCurrentTrailingSlash = (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n  if (!path.pathname.endsWith(\"/\") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {\n    path.pathname += \"/\";\n  }\n  return path;\n}\n/**\n * @private\n */\nfunction getToPathname(to) {\n  // Empty strings should be treated the same as / paths\n  return to === \"\" || to.pathname === \"\" ? \"/\" : typeof to === \"string\" ? parsePath(to).pathname : to.pathname;\n}\n/**\n * @private\n */\nconst joinPaths = paths => paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n/**\n * @private\n */\nconst normalizePathname = pathname => pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n/**\n * @private\n */\nconst normalizeSearch = search => !search || search === \"?\" ? \"\" : search.startsWith(\"?\") ? search : \"?\" + search;\n/**\n * @private\n */\nconst normalizeHash = hash => !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n */\nconst json = function json(data, init) {\n  if (init === void 0) {\n    init = {};\n  }\n  let responseInit = typeof init === \"number\" ? {\n    status: init\n  } : init;\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  return new Response(JSON.stringify(data), _extends({}, responseInit, {\n    headers\n  }));\n};\nclass AbortedDeferredError extends Error {}\nclass DeferredData {\n  constructor(data, responseInit) {\n    this.pendingKeysSet = new Set();\n    this.subscribers = new Set();\n    this.deferredKeys = [];\n    invariant(data && typeof data === \"object\" && !Array.isArray(data), \"defer() only accepts plain objects\");\n    // Set up an AbortController + Promise we can race against to exit early\n    // cancellation\n    let reject;\n    this.abortPromise = new Promise((_, r) => reject = r);\n    this.controller = new AbortController();\n    let onAbort = () => reject(new AbortedDeferredError(\"Deferred data aborted\"));\n    this.unlistenAbortSignal = () => this.controller.signal.removeEventListener(\"abort\", onAbort);\n    this.controller.signal.addEventListener(\"abort\", onAbort);\n    this.data = Object.entries(data).reduce((acc, _ref2) => {\n      let [key, value] = _ref2;\n      return Object.assign(acc, {\n        [key]: this.trackPromise(key, value)\n      });\n    }, {});\n    if (this.done) {\n      // All incoming values were resolved\n      this.unlistenAbortSignal();\n    }\n    this.init = responseInit;\n  }\n  trackPromise(key, value) {\n    if (!(value instanceof Promise)) {\n      return value;\n    }\n    this.deferredKeys.push(key);\n    this.pendingKeysSet.add(key);\n    // We store a little wrapper promise that will be extended with\n    // _data/_error props upon resolve/reject\n    let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error));\n    // Register rejection listeners to avoid uncaught promise rejections on\n    // errors or aborted deferred values\n    promise.catch(() => {});\n    Object.defineProperty(promise, \"_tracked\", {\n      get: () => true\n    });\n    return promise;\n  }\n  onSettle(promise, key, error, data) {\n    if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {\n      this.unlistenAbortSignal();\n      Object.defineProperty(promise, \"_error\", {\n        get: () => error\n      });\n      return Promise.reject(error);\n    }\n    this.pendingKeysSet.delete(key);\n    if (this.done) {\n      // Nothing left to abort!\n      this.unlistenAbortSignal();\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(\"Deferred data for key \\\"\" + key + \"\\\" resolved/rejected with `undefined`, \" + \"you must resolve/reject with a value or `null`.\");\n      Object.defineProperty(promise, \"_error\", {\n        get: () => undefinedError\n      });\n      this.emit(false, key);\n      return Promise.reject(undefinedError);\n    }\n    if (data === undefined) {\n      Object.defineProperty(promise, \"_error\", {\n        get: () => error\n      });\n      this.emit(false, key);\n      return Promise.reject(error);\n    }\n    Object.defineProperty(promise, \"_data\", {\n      get: () => data\n    });\n    this.emit(false, key);\n    return data;\n  }\n  emit(aborted, settledKey) {\n    this.subscribers.forEach(subscriber => subscriber(aborted, settledKey));\n  }\n  subscribe(fn) {\n    this.subscribers.add(fn);\n    return () => this.subscribers.delete(fn);\n  }\n  cancel() {\n    this.controller.abort();\n    this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n    this.emit(true);\n  }\n  async resolveData(signal) {\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  get done() {\n    return this.pendingKeysSet.size === 0;\n  }\n  get unwrappedData() {\n    invariant(this.data !== null && this.done, \"Can only unwrap data on initialized and settled deferreds\");\n    return Object.entries(this.data).reduce((acc, _ref3) => {\n      let [key, value] = _ref3;\n      return Object.assign(acc, {\n        [key]: unwrapTrackedPromise(value)\n      });\n    }, {});\n  }\n  get pendingKeys() {\n    return Array.from(this.pendingKeysSet);\n  }\n}\nfunction isTrackedPromise(value) {\n  return value instanceof Promise && value._tracked === true;\n}\nfunction unwrapTrackedPromise(value) {\n  if (!isTrackedPromise(value)) {\n    return value;\n  }\n  if (value._error) {\n    throw value._error;\n  }\n  return value._data;\n}\nconst defer = function defer(data, init) {\n  if (init === void 0) {\n    init = {};\n  }\n  let responseInit = typeof init === \"number\" ? {\n    status: init\n  } : init;\n  return new DeferredData(data, responseInit);\n};\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nconst redirect = function redirect(url, init) {\n  if (init === void 0) {\n    init = 302;\n  }\n  let responseInit = init;\n  if (typeof responseInit === \"number\") {\n    responseInit = {\n      status: responseInit\n    };\n  } else if (typeof responseInit.status === \"undefined\") {\n    responseInit.status = 302;\n  }\n  let headers = new Headers(responseInit.headers);\n  headers.set(\"Location\", url);\n  return new Response(null, _extends({}, responseInit, {\n    headers\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 */\nconst redirectDocument = (url, init) => {\n  let response = redirect(url, init);\n  response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n  return response;\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 */\nclass ErrorResponseImpl {\n  constructor(status, statusText, data, internal) {\n    if (internal === void 0) {\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 * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nfunction isRouteErrorResponse(error) {\n  return error != null && typeof error.status === \"number\" && typeof error.statusText === \"string\" && typeof error.internal === \"boolean\" && \"data\" in error;\n}\nconst validMutationMethodsArr = [\"post\", \"put\", \"patch\", \"delete\"];\nconst validMutationMethods = new Set(validMutationMethodsArr);\nconst validRequestMethodsArr = [\"get\", ...validMutationMethodsArr];\nconst validRequestMethods = new Set(validRequestMethodsArr);\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\nconst IDLE_NAVIGATION = {\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};\nconst IDLE_FETCHER = {\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};\nconst IDLE_BLOCKER = {\n  state: \"unblocked\",\n  proceed: undefined,\n  reset: undefined,\n  location: undefined\n};\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\nconst defaultMapRouteProperties = route => ({\n  hasErrorBoundary: Boolean(route.hasErrorBoundary)\n});\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n//#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n/**\n * Create a router and listen to history POP navigations\n */\nfunction createRouter(init) {\n  const routerWindow = init.window ? init.window : typeof window !== \"undefined\" ? window : undefined;\n  const isBrowser = typeof routerWindow !== \"undefined\" && typeof routerWindow.document !== \"undefined\" && typeof routerWindow.document.createElement !== \"undefined\";\n  const isServer = !isBrowser;\n  invariant(init.routes.length > 0, \"You must provide a non-empty routes array to createRouter\");\n  let mapRouteProperties;\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  // Routes keyed by ID\n  let manifest = {};\n  // Routes in tree format for matching\n  let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest);\n  let inFlightDataRoutes;\n  let basename = init.basename || \"/\";\n  let dataStrategyImpl = init.unstable_dataStrategy || defaultDataStrategy;\n  // Config driven behavior flags\n  let future = _extends({\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  // Cleanup function for history\n  let unlistenHistory = 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 = null;\n  // Externally-provided function to get scroll restoration keys\n  let getScrollRestorationKey = null;\n  // Externally-provided function to get current scroll position\n  let getScrollPosition = null;\n  // One-time flag to control the initial hydration scroll restoration.  Because\n  // we don't get the saved positions from <ScrollRestoration /> until _after_\n  // the initial render, we need to manually trigger a separate updateState to\n  // send along the restoreScrollPosition\n  // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n  // SSR did the initial scroll restoration.\n  let initialScrollRestored = init.hydrationData != null;\n  let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n  let initialErrors = null;\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 {\n      matches,\n      route\n    } = getShortCircuitMatches(dataRoutes);\n    initialMatches = matches;\n    initialErrors = {\n      [route.id]: error\n    };\n  }\n  let initialized;\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 => {\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 (typeof m.route.loader === \"function\" && m.route.loader.hydrate === true) {\n        return false;\n      }\n      // Otherwise, initialized if hydrated with data or an error\n      return loaderData && loaderData[m.route.id] !== undefined || errors && errors[m.route.id] !== undefined;\n    };\n    // If errors exist, don't consider routes below the boundary\n    if (errors) {\n      let idx = initialMatches.findIndex(m => errors[m.route.id] !== undefined);\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  let router;\n  let state = {\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  // -- Stateful internal variables to manage navigations --\n  // Current navigation in progress (to be committed in completeNavigation)\n  let pendingAction = Action.Pop;\n  // Should the current navigation prevent the scroll reset if scroll cannot\n  // be restored?\n  let pendingPreventScrollReset = false;\n  // AbortController for the active navigation\n  let pendingNavigationController;\n  // Should the current navigation enable document.startViewTransition?\n  let pendingViewTransitionEnabled = false;\n  // Store applied view transitions so we can apply them on POP\n  let appliedViewTransitions = new Map();\n  // Cleanup function for persisting applied transitions to sessionStorage\n  let removePageHideEventListener = null;\n  // We use this to avoid touching history in completeNavigation if a\n  // revalidation is entirely uninterrupted\n  let isUninterruptedRevalidation = false;\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  // Use this internal array to capture routes that require revalidation due\n  // to a cancelled deferred on action submission\n  let cancelledDeferredRoutes = [];\n  // Use this internal array to capture fetcher loads that were cancelled by an\n  // action navigation and require revalidation\n  let cancelledFetcherLoads = [];\n  // AbortControllers for any in-flight fetchers\n  let fetchControllers = new Map();\n  // Track loads based on the order in which they started\n  let incrementingLoadId = 0;\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  // Fetchers that triggered data reloads as a result of their actions\n  let fetchReloadIds = new Map();\n  // Fetchers that triggered redirect navigations\n  let fetchRedirectIds = new Set();\n  // Most recent href/match for fetcher.load calls for fetchers\n  let fetchLoadMatches = new Map();\n  // Ref-count mounted fetchers so we know when it's ok to clean them up\n  let activeFetchers = new Map();\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  // 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  // 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  // 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  // 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(_ref => {\n      let {\n        action: historyAction,\n        location,\n        delta\n      } = _ref;\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      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.\");\n      let blockerKey = shouldBlockNavigation({\n        currentLocation: state.location,\n        nextLocation: location,\n        historyAction\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        // 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({\n              blockers\n            });\n          }\n        });\n        return;\n      }\n      return startNavigation(historyAction, location);\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 = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);\n      routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n      removePageHideEventListener = () => routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\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(Action.Pop, state.location, {\n        initialHydration: true\n      });\n    }\n    return router;\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  // Subscribe to state updates for the router\n  function subscribe(fn) {\n    subscribers.add(fn);\n    return () => subscribers.delete(fn);\n  }\n  // Update our state and notify the calling context of the change\n  function updateState(newState, opts) {\n    if (opts === void 0) {\n      opts = {};\n    }\n    state = _extends({}, state, newState);\n    // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n    // can be removed\n    let completedFetchers = [];\n    let deletedFetchersKeys = [];\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    // 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 => subscriber(state, {\n      deletedFetchers: deletedFetchersKeys,\n      unstable_viewTransitionOpts: opts.viewTransitionOpts,\n      unstable_flushSync: opts.flushSync === true\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  // 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(location, newState, _temp) {\n    var _location$state, _location$state2;\n    let {\n      flushSync\n    } = _temp === void 0 ? {} : _temp;\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 = 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;\n    let actionData;\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    // Always preserve any existing loaderData from re-used routes\n    let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;\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    // Always respect the user flag.  Otherwise don't reset on mutation\n    // submission navigations unless they redirect\n    let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true;\n    if (inFlightDataRoutes) {\n      dataRoutes = inFlightDataRoutes;\n      inFlightDataRoutes = undefined;\n    }\n    if (isUninterruptedRevalidation) ;else if (pendingAction === Action.Pop) ;else if (pendingAction === Action.Push) {\n      init.history.push(location, location.state);\n    } else if (pendingAction === Action.Replace) {\n      init.history.replace(location, location.state);\n    }\n    let viewTransitionOpts;\n    // On POP, enable transitions if they were enabled on the original navigation\n    if (pendingAction === Action.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    updateState(_extends({}, newState, {\n      actionData,\n      loaderData,\n      historyAction: pendingAction,\n      location,\n      initialized: true,\n      navigation: IDLE_NAVIGATION,\n      revalidation: \"idle\",\n      restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches),\n      preventScrollReset,\n      blockers\n    }), {\n      viewTransitionOpts,\n      flushSync: flushSync === true\n    });\n    // Reset stateful navigation vars\n    pendingAction = Action.Pop;\n    pendingPreventScrollReset = false;\n    pendingViewTransitionEnabled = false;\n    isUninterruptedRevalidation = false;\n    isRevalidationRequired = false;\n    cancelledDeferredRoutes = [];\n    cancelledFetcherLoads = [];\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(to, opts) {\n    if (typeof to === \"number\") {\n      init.history.go(to);\n      return;\n    }\n    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);\n    let {\n      path,\n      submission,\n      error\n    } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts);\n    let currentLocation = state.location;\n    let nextLocation = createLocation(state.location, path, opts && opts.state);\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 = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));\n    let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n    let historyAction = Action.Push;\n    if (userReplace === true) {\n      historyAction = Action.Replace;\n    } else if (userReplace === false) ;else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {\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 = Action.Replace;\n    }\n    let preventScrollReset = opts && \"preventScrollReset\" in opts ? opts.preventScrollReset === true : undefined;\n    let flushSync = (opts && opts.unstable_flushSync) === true;\n    let blockerKey = shouldBlockNavigation({\n      currentLocation,\n      nextLocation,\n      historyAction\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({\n            blockers\n          });\n        }\n      });\n      return;\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  // 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({\n      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    // 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    // 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(pendingAction || state.historyAction, state.navigation.location, {\n      overrideNavigation: state.navigation\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(historyAction, location, opts) {\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 = (opts && opts.startUninterruptedRevalidation) === true;\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    pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\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    // Short circuit with a 404 on the root error boundary if we match nothing\n    if (!matches) {\n      let error = getInternalRouterError(404, {\n        pathname: location.pathname\n      });\n      let {\n        matches: notFoundMatches,\n        route\n      } = getShortCircuitMatches(routesToUse);\n      // Cancel all pending deferred on 404s since we don't keep any routes\n      cancelActiveDeferreds();\n      completeNavigation(location, {\n        matches: notFoundMatches,\n        loaderData: {},\n        errors: {\n          [route.id]: error\n        }\n      }, {\n        flushSync\n      });\n      return;\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 <Form method=\"post\">\n    // which will default to a navigation to /page\n    if (state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {\n      completeNavigation(location, {\n        matches\n      }, {\n        flushSync\n      });\n      return;\n    }\n    // Create a controller/Request for this navigation\n    pendingNavigationController = new AbortController();\n    let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission);\n    let pendingActionResult;\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 = [findNearestBoundary(matches).route.id, {\n        type: ResultType.error,\n        error: opts.pendingError\n      }];\n    } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {\n      // Call action if we received an action submission\n      let actionResult = await handleAction(request, location, opts.submission, matches, {\n        replace: opts.replace,\n        flushSync\n      });\n      if (actionResult.shortCircuited) {\n        return;\n      }\n      pendingActionResult = actionResult.pendingActionResult;\n      loadingNavigation = getLoadingNavigation(location, opts.submission);\n      flushSync = false;\n      // Create a GET request for the loaders\n      request = createClientSideRequest(init.history, request.url, request.signal);\n    }\n    // Call loaders\n    let {\n      shortCircuited,\n      loaderData,\n      errors\n    } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionResult);\n    if (shortCircuited) {\n      return;\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    completeNavigation(location, _extends({\n      matches\n    }, getActionDataForCommit(pendingActionResult), {\n      loaderData,\n      errors\n    }));\n  }\n  // Call the action matched by the leaf route for this navigation and handle\n  // redirects/errors\n  async function handleAction(request, location, submission, matches, opts) {\n    if (opts === void 0) {\n      opts = {};\n    }\n    interruptActiveLoads();\n    // Put us in a submitting state\n    let navigation = getSubmittingNavigation(location, submission);\n    updateState({\n      navigation\n    }, {\n      flushSync: opts.flushSync === true\n    });\n    // Call our action and get the result\n    let result;\n    let actionMatch = getTargetMatch(matches, location);\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(\"action\", request, [actionMatch], matches);\n      result = results[0];\n      if (request.signal.aborted) {\n        return {\n          shortCircuited: true\n        };\n      }\n    }\n    if (isRedirectResult(result)) {\n      let replace;\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(result.response.headers.get(\"Location\"), new URL(request.url), basename);\n        replace = location === state.location.pathname + state.location.search;\n      }\n      await startRedirectNavigation(request, result, {\n        submission,\n        replace\n      });\n      return {\n        shortCircuited: true\n      };\n    }\n    if (isDeferredResult(result)) {\n      throw getInternalRouterError(400, {\n        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      // 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 = Action.Push;\n      }\n      return {\n        pendingActionResult: [boundaryMatch.route.id, result]\n      };\n    }\n    return {\n      pendingActionResult: [actionMatch.route.id, result]\n    };\n  }\n  // Call all applicable loaders for the given matches, handling redirects,\n  // errors, etc.\n  async function handleLoaders(request, location, matches, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionResult) {\n    // Figure out the right navigation we want to use for data loading\n    let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);\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 = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    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);\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(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId));\n    pendingNavigationLoadId = ++incrementingLoadId;\n    // Short circuit if we have no loaders to run\n    if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n      let updatedFetchers = markFetchRedirectsDone();\n      completeNavigation(location, _extends({\n        matches,\n        loaderData: {},\n        // Commit pending error if we're short circuiting\n        errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {\n          [pendingActionResult[0]]: pendingActionResult[1].error\n        } : null\n      }, getActionDataForCommit(pendingActionResult), updatedFetchers ? {\n        fetchers: new Map(state.fetchers)\n      } : {}), {\n        flushSync\n      });\n      return {\n        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 (!isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration)) {\n      revalidatingFetchers.forEach(rf => {\n        let fetcher = state.fetchers.get(rf.key);\n        let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined);\n        state.fetchers.set(rf.key, revalidatingFetcher);\n      });\n      let actionData;\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\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      updateState(_extends({\n        navigation: loadingNavigation\n      }, actionData !== undefined ? {\n        actionData\n      } : {}, revalidatingFetchers.length > 0 ? {\n        fetchers: new Map(state.fetchers)\n      } : {}), {\n        flushSync\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    // Proxy navigation abort through to revalidation fetchers\n    let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key));\n    if (pendingNavigationController) {\n      pendingNavigationController.signal.addEventListener(\"abort\", abortPendingFetchRevalidations);\n    }\n    let {\n      loaderResults,\n      fetcherResults\n    } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, request);\n    if (request.signal.aborted) {\n      return {\n        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(\"abort\", abortPendingFetchRevalidations);\n    }\n    revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key));\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 = revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n        fetchRedirectIds.add(fetcherKey);\n      }\n      await startRedirectNavigation(request, redirect.result, {\n        replace\n      });\n      return {\n        shortCircuited: true\n      };\n    }\n    // Process and commit output from loaders\n    let {\n      loaderData,\n      errors\n    } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds);\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    // 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).filter(_ref2 => {\n        let [id] = _ref2;\n        return !matchesToLoad.some(m => m.route.id === id);\n      }).forEach(_ref3 => {\n        let [routeId, error] = _ref3;\n        errors = Object.assign(errors || {}, {\n          [routeId]: error\n        });\n      });\n    }\n    let updatedFetchers = markFetchRedirectsDone();\n    let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n    let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n    return _extends({\n      loaderData,\n      errors\n    }, shouldUpdateFetchers ? {\n      fetchers: new Map(state.fetchers)\n    } : {});\n  }\n  // Trigger a fetcher load/submit for the given fetcher key\n  function fetch(key, routeId, href, opts) {\n    if (isServer) {\n      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.\");\n    }\n    if (fetchControllers.has(key)) abortFetcher(key);\n    let flushSync = (opts && opts.unstable_flushSync) === true;\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, future.v7_relativeSplatPath, routeId, opts == null ? void 0 : opts.relative);\n    let matches = matchRoutes(routesToUse, normalizedPath, basename);\n    if (!matches) {\n      setFetcherError(key, routeId, getInternalRouterError(404, {\n        pathname: normalizedPath\n      }), {\n        flushSync\n      });\n      return;\n    }\n    let {\n      path,\n      submission,\n      error\n    } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts);\n    if (error) {\n      setFetcherError(key, routeId, error, {\n        flushSync\n      });\n      return;\n    }\n    let match = getTargetMatch(matches, path);\n    pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n    if (submission && isMutationMethod(submission.formMethod)) {\n      handleFetcherAction(key, routeId, path, match, matches, flushSync, submission);\n      return;\n    }\n    // Store off the match so we can call it's shouldRevalidate on subsequent\n    // revalidations\n    fetchLoadMatches.set(key, {\n      routeId,\n      path\n    });\n    handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission);\n  }\n  // Call the action for the matched fetcher.submit(), and then handle redirects,\n  // errors, and revalidation\n  async function handleFetcherAction(key, routeId, path, match, requestMatches, flushSync, submission) {\n    interruptActiveLoads();\n    fetchLoadMatches.delete(key);\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, {\n        flushSync\n      });\n      return;\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    // Call the action for the fetcher\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);\n    fetchControllers.set(key, abortController);\n    let originatingLoadId = incrementingLoadId;\n    let actionResults = await callDataStrategy(\"action\", fetchRequest, [match], requestMatches);\n    let actionResult = actionResults[0];\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    // 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      // Process any non-redirect errors thrown\n      if (isErrorResult(actionResult)) {\n        setFetcherError(key, routeId, actionResult.error);\n        return;\n      }\n    }\n    if (isDeferredResult(actionResult)) {\n      throw getInternalRouterError(400, {\n        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(init.history, nextLocation, abortController.signal);\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let matches = state.navigation.state !== \"idle\" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches;\n    invariant(matches, \"Didn't find any matches after fetcher action\");\n    let loadId = ++incrementingLoadId;\n    fetchReloadIds.set(key, loadId);\n    let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n    state.fetchers.set(key, loadFetcher);\n    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]);\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.filter(rf => rf.key !== key).forEach(rf => {\n      let staleKey = rf.key;\n      let existingFetcher = state.fetchers.get(staleKey);\n      let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined);\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    updateState({\n      fetchers: new Map(state.fetchers)\n    });\n    let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key));\n    abortController.signal.addEventListener(\"abort\", abortPendingFetchRevalidations);\n    let {\n      loaderResults,\n      fetcherResults\n    } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);\n    if (abortController.signal.aborted) {\n      return;\n    }\n    abortController.signal.removeEventListener(\"abort\", abortPendingFetchRevalidations);\n    fetchReloadIds.delete(key);\n    fetchControllers.delete(key);\n    revalidatingFetchers.forEach(r => fetchControllers.delete(r.key));\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 = revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n        fetchRedirectIds.add(fetcherKey);\n      }\n      return startRedirectNavigation(revalidationRequest, redirect.result);\n    }\n    // Process and commit output from loaders\n    let {\n      loaderData,\n      errors\n    } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);\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    abortStaleFetchLoads(loadId);\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 (state.navigation.state === \"loading\" && loadId > pendingNavigationLoadId) {\n      invariant(pendingAction, \"Expected pending action\");\n      pendingNavigationController && pendingNavigationController.abort();\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(state.loaderData, loaderData, matches, errors),\n        fetchers: new Map(state.fetchers)\n      });\n      isRevalidationRequired = false;\n    }\n  }\n  // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n  async function handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission) {\n    let existingFetcher = state.fetchers.get(key);\n    updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined), {\n      flushSync\n    });\n    // Call the loader for this fetcher route match\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);\n    fetchControllers.set(key, abortController);\n    let originatingLoadId = incrementingLoadId;\n    let results = await callDataStrategy(\"loader\", fetchRequest, [match], matches);\n    let result = results[0];\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 = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;\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    if (fetchRequest.signal.aborted) {\n      return;\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    // 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    // Process any non-redirect errors thrown\n    if (isErrorResult(result)) {\n      setFetcherError(key, routeId, result.error);\n      return;\n    }\n    invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n    // Put the fetcher back into an idle state\n    updateFetcherState(key, getDoneFetcher(result.data));\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(request, redirect, _temp2) {\n    let {\n      submission,\n      fetcherSubmission,\n      replace\n    } = _temp2 === void 0 ? {} : _temp2;\n    if (redirect.response.headers.has(\"X-Remix-Revalidate\")) {\n      isRevalidationRequired = true;\n    }\n    let location = redirect.response.headers.get(\"Location\");\n    invariant(location, \"Expected a Location header on the redirect Response\");\n    location = normalizeRedirectLocation(location, new URL(request.url), basename);\n    let redirectLocation = createLocation(state.location, location, {\n      _isRedirect: true\n    });\n    if (isBrowser) {\n      let isDocumentReload = false;\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      if (isDocumentReload) {\n        if (replace) {\n          routerWindow.location.replace(location);\n        } else {\n          routerWindow.location.assign(location);\n        }\n        return;\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    let redirectHistoryAction = replace === true ? Action.Replace : Action.Push;\n    // Use the incoming submission if provided, fallback on the active one in\n    // state.navigation\n    let {\n      formMethod,\n      formAction,\n      formEncType\n    } = state.navigation;\n    if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {\n      submission = getSubmissionFromNavigation(state.navigation);\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 (redirectPreserveMethodStatusCodes.has(redirect.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        submission: _extends({}, 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(redirectLocation, submission);\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  // Utility wrapper for calling dataStrategy client-side without having to\n  // pass around the manifest, mapRouteProperties, etc.\n  async function callDataStrategy(type, request, matchesToLoad, matches) {\n    try {\n      let results = await callDataStrategyImpl(dataStrategyImpl, type, request, matchesToLoad, matches, manifest, mapRouteProperties);\n      return await Promise.all(results.map((result, i) => {\n        if (isRedirectHandlerResult(result)) {\n          let response = result.result;\n          return {\n            type: ResultType.redirect,\n            response: normalizeRelativeRoutingRedirectResponse(response, request, matchesToLoad[i].route.id, matches, basename, future.v7_relativeSplatPath)\n          };\n        }\n        return convertHandlerResultToDataResult(result);\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  async function callLoadersAndMaybeResolveData(currentMatches, matches, matchesToLoad, fetchersToLoad, request) {\n    let [loaderResults, ...fetcherResults] = await Promise.all([matchesToLoad.length ? callDataStrategy(\"loader\", request, matchesToLoad, matches) : [], ...fetchersToLoad.map(f => {\n      if (f.matches && f.match && f.controller) {\n        let fetcherRequest = createClientSideRequest(init.history, f.path, f.controller.signal);\n        return callDataStrategy(\"loader\", fetcherRequest, [f.match], f.matches).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    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)]);\n    return {\n      loaderResults,\n      fetcherResults\n    };\n  }\n  function interruptActiveLoads() {\n    // Every interruption triggers a revalidation\n    isRevalidationRequired = true;\n    // Cancel pending route-level deferreds and mark cancelled routes for\n    // revalidation\n    cancelledDeferredRoutes.push(...cancelActiveDeferreds());\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  function updateFetcherState(key, fetcher, opts) {\n    if (opts === void 0) {\n      opts = {};\n    }\n    state.fetchers.set(key, fetcher);\n    updateState({\n      fetchers: new Map(state.fetchers)\n    }, {\n      flushSync: (opts && opts.flushSync) === true\n    });\n  }\n  function setFetcherError(key, routeId, error, opts) {\n    if (opts === void 0) {\n      opts = {};\n    }\n    let boundaryMatch = findNearestBoundary(state.matches, routeId);\n    deleteFetcher(key);\n    updateState({\n      errors: {\n        [boundaryMatch.route.id]: error\n      },\n      fetchers: new Map(state.fetchers)\n    }, {\n      flushSync: (opts && opts.flushSync) === true\n    });\n  }\n  function getFetcher(key) {\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  function deleteFetcher(key) {\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 (fetchControllers.has(key) && !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))) {\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  function deleteFetcherAndUpdateState(key) {\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({\n      fetchers: new Map(state.fetchers)\n    });\n  }\n  function abortFetcher(key) {\n    let controller = fetchControllers.get(key);\n    invariant(controller, \"Expected fetch controller: \" + key);\n    controller.abort();\n    fetchControllers.delete(key);\n  }\n  function markFetchersDone(keys) {\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  function markFetchRedirectsDone() {\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  function abortStaleFetchLoads(landedId) {\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  function getBlocker(key, fn) {\n    let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n    if (blockerFunctions.get(key) !== fn) {\n      blockerFunctions.set(key, fn);\n    }\n    return blocker;\n  }\n  function deleteBlocker(key) {\n    state.blockers.delete(key);\n    blockerFunctions.delete(key);\n  }\n  // Utility function to update blockers, ensuring valid state transitions\n  function updateBlocker(key, newBlocker) {\n    let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n    // Poor mans state machine :)\n    // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n    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);\n    let blockers = new Map(state.blockers);\n    blockers.set(key, newBlocker);\n    updateState({\n      blockers\n    });\n  }\n  function shouldBlockNavigation(_ref4) {\n    let {\n      currentLocation,\n      nextLocation,\n      historyAction\n    } = _ref4;\n    if (blockerFunctions.size === 0) {\n      return;\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    let entries = Array.from(blockerFunctions.entries());\n    let [blockerKey, blockerFunction] = entries[entries.length - 1];\n    let blocker = state.blockers.get(blockerKey);\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    // At this point, we know we're unblocked/blocked so we need to check the\n    // user-provided blocker function\n    if (blockerFunction({\n      currentLocation,\n      nextLocation,\n      historyAction\n    })) {\n      return blockerKey;\n    }\n  }\n  function cancelActiveDeferreds(predicate) {\n    let cancelledRouteIds = [];\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  // Opt in to capturing and reporting scroll positions during navigations,\n  // used by the <ScrollRestoration> component\n  function enableScrollRestoration(positions, getPosition, getKey) {\n    savedScrollPositions = positions;\n    getScrollPosition = getPosition;\n    getScrollRestorationKey = getKey || null;\n    // Perform initial hydration scroll restoration, since we miss the boat on\n    // the initial updateState() because we've not yet rendered <ScrollRestoration/>\n    // and therefore have no savedScrollPositions available\n    if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n      initialScrollRestored = true;\n      let y = getSavedScrollPosition(state.location, state.matches);\n      if (y != null) {\n        updateState({\n          restoreScrollPosition: y\n        });\n      }\n    }\n    return () => {\n      savedScrollPositions = null;\n      getScrollPosition = null;\n      getScrollRestorationKey = null;\n    };\n  }\n  function getScrollKey(location, matches) {\n    if (getScrollRestorationKey) {\n      let key = getScrollRestorationKey(location, matches.map(m => convertRouteMatchToUiMatch(m, state.loaderData)));\n      return key || location.key;\n    }\n    return location.key;\n  }\n  function saveScrollPosition(location, matches) {\n    if (savedScrollPositions && getScrollPosition) {\n      let key = getScrollKey(location, matches);\n      savedScrollPositions[key] = getScrollPosition();\n    }\n  }\n  function getSavedScrollPosition(location, matches) {\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  function _internalSetRoutes(newRoutes) {\n    manifest = {};\n    inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest);\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 => init.history.createHref(to),\n    encodeLocation: 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  return router;\n}\n//#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\nconst UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\nfunction createStaticHandler(routes, opts) {\n  invariant(routes.length > 0, \"You must provide a non-empty routes array to createStaticHandler\");\n  let manifest = {};\n  let basename = (opts ? opts.basename : null) || \"/\";\n  let mapRouteProperties;\n  if (opts != null && opts.mapRouteProperties) {\n    mapRouteProperties = opts.mapRouteProperties;\n  } else if (opts != null && 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 = _extends({\n    v7_relativeSplatPath: false,\n    v7_throwAbortReason: false\n  }, opts ? opts.future : null);\n  let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest);\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(request, _temp3) {\n    let {\n      requestContext,\n      skipLoaderErrorBubbling,\n      unstable_dataStrategy\n    } = _temp3 === void 0 ? {} : _temp3;\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    // SSR supports HEAD requests while SPA doesn't\n    if (!isValidMethod(method) && method !== \"HEAD\") {\n      let error = getInternalRouterError(405, {\n        method\n      });\n      let {\n        matches: methodNotAllowedMatches,\n        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, {\n        pathname: location.pathname\n      });\n      let {\n        matches: notFoundMatches,\n        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    let result = await queryImpl(request, location, matches, requestContext, unstable_dataStrategy || null, skipLoaderErrorBubbling === true, null);\n    if (isResponse(result)) {\n      return result;\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 _extends({\n      location,\n      basename\n    }, result);\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(request, _temp4) {\n    let {\n      routeId,\n      requestContext,\n      unstable_dataStrategy\n    } = _temp4 === void 0 ? {} : _temp4;\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    // SSR supports HEAD requests while SPA doesn't\n    if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n      throw getInternalRouterError(405, {\n        method\n      });\n    } else if (!matches) {\n      throw getInternalRouterError(404, {\n        pathname: location.pathname\n      });\n    }\n    let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location);\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, {\n        pathname: location.pathname\n      });\n    }\n    let result = await queryImpl(request, location, matches, requestContext, unstable_dataStrategy || null, false, match);\n    if (isResponse(result)) {\n      return result;\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    // Pick off the right state value to return\n    if (result.actionData) {\n      return Object.values(result.actionData)[0];\n    }\n    if (result.loaderData) {\n      var _result$activeDeferre;\n      let data = Object.values(result.loaderData)[0];\n      if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) {\n        data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n      }\n      return data;\n    }\n    return undefined;\n  }\n  async function queryImpl(request, location, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch) {\n    invariant(request.signal, \"query()/queryRoute() requests must contain an AbortController signal\");\n    try {\n      if (isMutationMethod(request.method.toLowerCase())) {\n        let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch != null);\n        return result;\n      }\n      let result = await loadRouteData(request, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch);\n      return isResponse(result) ? result : _extends({}, 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  async function submit(request, matches, actionMatch, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, isRouteRequest) {\n    let result;\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(\"action\", request, [actionMatch], matches, isRouteRequest, requestContext, unstable_dataStrategy);\n      result = results[0];\n      if (request.signal.aborted) {\n        throwStaticHandlerAbortedError(request, isRouteRequest, future);\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    if (isDeferredResult(result)) {\n      let error = getInternalRouterError(400, {\n        type: \"defer-action\"\n      });\n      if (isRouteRequest) {\n        throw error;\n      }\n      result = {\n        type: ResultType.error,\n        error\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      return {\n        matches: [actionMatch],\n        loaderData: {},\n        actionData: {\n          [actionMatch.route.id]: result.data\n        },\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    // 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    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 ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);\n      let context = await loadRouteData(loaderRequest, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, null, [boundaryMatch.route.id, result]);\n      // action status codes take precedence over loader status codes\n      return _extends({}, context, {\n        statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,\n        actionData: null,\n        actionHeaders: _extends({}, result.headers ? {\n          [actionMatch.route.id]: result.headers\n        } : {})\n      });\n    }\n    let context = await loadRouteData(loaderRequest, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, null);\n    return _extends({}, context, {\n      actionData: {\n        [actionMatch.route.id]: result.data\n      }\n    }, result.statusCode ? {\n      statusCode: result.statusCode\n    } : {}, {\n      actionHeaders: result.headers ? {\n        [actionMatch.route.id]: result.headers\n      } : {}\n    });\n  }\n  async function loadRouteData(request, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch, pendingActionResult) {\n    let isRouteRequest = routeMatch != null;\n    // Short circuit if we have no loaders to run (queryRoute())\n    if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) {\n      throw getInternalRouterError(400, {\n        method: request.method,\n        pathname: new URL(request.url).pathname,\n        routeId: routeMatch == null ? void 0 : routeMatch.route.id\n      });\n    }\n    let requestMatches = routeMatch ? [routeMatch] : pendingActionResult && isErrorResult(pendingActionResult[1]) ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) : matches;\n    let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy);\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((acc, m) => Object.assign(acc, {\n          [m.route.id]: null\n        }), {}),\n        errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {\n          [pendingActionResult[0]]: pendingActionResult[1].error\n        } : null,\n        statusCode: 200,\n        loaderHeaders: {},\n        activeDeferreds: null\n      };\n    }\n    let results = await callDataStrategy(\"loader\", request, matchesToLoad, matches, isRouteRequest, requestContext, unstable_dataStrategy);\n    if (request.signal.aborted) {\n      throwStaticHandlerAbortedError(request, isRouteRequest, future);\n    }\n    // Process and commit output from loaders\n    let activeDeferreds = new Map();\n    let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling);\n    // Add a null for any non-loader matches for proper revalidation on the client\n    let executedLoaders = new Set(matchesToLoad.map(match => match.route.id));\n    matches.forEach(match => {\n      if (!executedLoaders.has(match.route.id)) {\n        context.loaderData[match.route.id] = null;\n      }\n    });\n    return _extends({}, context, {\n      matches,\n      activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null\n    });\n  }\n  // Utility wrapper for calling dataStrategy server-side without having to\n  // pass around the manifest, mapRouteProperties, etc.\n  async function callDataStrategy(type, request, matchesToLoad, matches, isRouteRequest, requestContext, unstable_dataStrategy) {\n    let results = await callDataStrategyImpl(unstable_dataStrategy || defaultDataStrategy, type, request, matchesToLoad, matches, manifest, mapRouteProperties, requestContext);\n    return await Promise.all(results.map((result, i) => {\n      if (isRedirectHandlerResult(result)) {\n        let response = result.result;\n        // Throw redirects and let the server handle them with an HTTP redirect\n        throw normalizeRelativeRoutingRedirectResponse(response, request, matchesToLoad[i].route.id, matches, basename, future.v7_relativeSplatPath);\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      return convertHandlerResultToDataResult(result);\n    }));\n  }\n  return {\n    dataRoutes,\n    query,\n    queryRoute\n  };\n}\n//#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\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 */\nfunction getStaticContextFromError(routes, context, error) {\n  let newContext = _extends({}, context, {\n    statusCode: isRouteErrorResponse(error) ? error.status : 500,\n    errors: {\n      [context._deepestRenderedBoundaryId || routes[0].id]: error\n    }\n  });\n  return newContext;\n}\nfunction throwStaticHandlerAbortedError(request, isRouteRequest, future) {\n  if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n    throw request.signal.reason;\n  }\n  let method = isRouteRequest ? \"queryRoute\" : \"query\";\n  throw new Error(method + \"() call aborted: \" + request.method + \" \" + request.url);\n}\nfunction isSubmissionNavigation(opts) {\n  return opts != null && (\"formData\" in opts && opts.formData != null || \"body\" in opts && opts.body !== undefined);\n}\nfunction normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) {\n  let contextualMatches;\n  let activeRouteMatch;\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  // Resolve the relative path\n  let path = resolveTo(to ? to : \".\", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === \"path\");\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  // Add an ?index param for matched index routes if we don't already have one\n  if ((to == null || to === \"\" || to === \".\") && activeRouteMatch && activeRouteMatch.route.index && !hasNakedIndexQuery(path.search)) {\n    path.search = path.search ? path.search.replace(/^\\?/, \"?index&\") : \"?index\";\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 = path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n  }\n  return createPath(path);\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(normalizeFormMethod, isFetcher, path, opts) {\n  // Return location verbatim on non-submission navigations\n  if (!opts || !isSubmissionNavigation(opts)) {\n    return {\n      path\n    };\n  }\n  if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n    return {\n      path,\n      error: getInternalRouterError(405, {\n        method: opts.formMethod\n      })\n    };\n  }\n  let getInvalidBodyError = () => ({\n    path,\n    error: getInternalRouterError(400, {\n      type: \"invalid-body\"\n    })\n  });\n  // Create a Submission on non-GET navigations\n  let rawFormMethod = opts.formMethod || \"get\";\n  let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase();\n  let formAction = stripHashFromPath(path);\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      let text = typeof opts.body === \"string\" ? opts.body : opts.body instanceof FormData || 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((acc, _ref5) => {\n        let [name, value] = _ref5;\n        return \"\" + acc + name + \"=\" + value + \"\\n\";\n      }, \"\") : String(opts.body);\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      try {\n        let json = typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\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  invariant(typeof FormData === \"function\", \"FormData is not available in this environment\");\n  let searchParams;\n  let formData;\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  let submission = {\n    formMethod,\n    formAction,\n    formEncType: opts && opts.formEncType || \"application/x-www-form-urlencoded\",\n    formData,\n    json: undefined,\n    text: undefined\n  };\n  if (isMutationMethod(submission.formMethod)) {\n    return {\n      path,\n      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  return {\n    path: createPath(parsedPath),\n    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(matches, boundaryId) {\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}\nfunction getMatchesToLoad(history, state, matches, submission, location, isInitialLoad, skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult) {\n  let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : undefined;\n  let currentUrl = history.createURL(state.location);\n  let nextUrl = history.createURL(location);\n  // Pick navigation matches that are net-new or qualify for revalidation\n  let boundaryId = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[0] : undefined;\n  let boundaryMatches = boundaryId ? getLoaderMatchesUntilBoundary(matches, boundaryId) : matches;\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 ? pendingActionResult[1].statusCode : undefined;\n  let shouldSkipRevalidation = skipActionErrorRevalidation && actionStatus && actionStatus >= 400;\n  let navigationMatches = boundaryMatches.filter((match, index) => {\n    let {\n      route\n    } = 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    if (route.loader == null) {\n      return false;\n    }\n    if (isInitialLoad) {\n      if (typeof route.loader !== \"function\" || route.loader.hydrate) {\n        return true;\n      }\n      return 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    // Always call the loader on new route instances and pending defer cancellations\n    if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) {\n      return true;\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    return shouldRevalidateLoader(match, _extends({\n      currentUrl,\n      currentParams: currentRouteMatch.params,\n      nextUrl,\n      nextParams: nextRouteMatch.params\n    }, submission, {\n      actionResult,\n      unstable_actionStatus: actionStatus,\n      defaultShouldRevalidate: shouldSkipRevalidation ? false :\n      // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n      isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search ||\n      // Search params affect all loaders\n      currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch)\n    }));\n  });\n  // Pick fetcher.loads that need to be revalidated\n  let revalidatingFetchers = [];\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 (isInitialLoad || !matches.some(m => m.route.id === f.routeId) || deletedFetchers.has(key)) {\n      return;\n    }\n    let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\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    // 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    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 (fetcher && fetcher.state !== \"idle\" && fetcher.data === undefined) {\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, _extends({\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 ? false : isRevalidationRequired\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  return [navigationMatches, revalidatingFetchers];\n}\nfunction isNewLoader(currentLoaderData, currentMatch, match) {\n  let isNew =\n  // [a] -> [a, b]\n  !currentMatch ||\n  // [a, b] -> [a, c]\n  match.route.id !== currentMatch.route.id;\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  // Always load if this is a net-new route or we don't yet have data\n  return isNew || isMissingData;\n}\nfunction isNewRouteInstance(currentMatch, match) {\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 && currentPath.endsWith(\"*\") && currentMatch.params[\"*\"] !== match.params[\"*\"]\n  );\n}\nfunction shouldRevalidateLoader(loaderMatch, arg) {\n  if (loaderMatch.route.shouldRevalidate) {\n    let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n    if (typeof routeChoice === \"boolean\") {\n      return routeChoice;\n    }\n  }\n  return arg.defaultShouldRevalidate;\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(route, mapRouteProperties, manifest) {\n  if (!route.lazy) {\n    return;\n  }\n  let lazyRoute = await route.lazy();\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  let routeToUpdate = manifest[route.id];\n  invariant(routeToUpdate, \"No route found in manifest\");\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 = {};\n  for (let lazyRouteProperty in lazyRoute) {\n    let staticRouteValue = routeToUpdate[lazyRouteProperty];\n    let isPropertyStaticallyDefined = staticRouteValue !== undefined &&\n    // This property isn't static since it should always be updated based\n    // on the route updates\n    lazyRouteProperty !== \"hasErrorBoundary\";\n    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.\"));\n    if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) {\n      routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty];\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  // 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, _extends({}, mapRouteProperties(routeToUpdate), {\n    lazy: undefined\n  }));\n}\n// Default implementation of `dataStrategy` which fetches all loaders in parallel\nfunction defaultDataStrategy(opts) {\n  return Promise.all(opts.matches.map(m => m.resolve()));\n}\nasync function callDataStrategyImpl(dataStrategyImpl, type, request, matchesToLoad, matches, manifest, mapRouteProperties, requestContext) {\n  let routeIdsToLoad = matchesToLoad.reduce((acc, m) => acc.add(m.route.id), new Set());\n  let loadedMatches = new Set();\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 = handlerOverride => {\n        loadedMatches.add(match.route.id);\n        return shouldLoad ? callLoaderOrAction(type, request, match, manifest, mapRouteProperties, handlerOverride, requestContext) : Promise.resolve({\n          type: ResultType.data,\n          result: undefined\n        });\n      };\n      return _extends({}, match, {\n        shouldLoad,\n        resolve\n      });\n    }),\n    request,\n    params: matches[0].params,\n    context: requestContext\n  });\n  // Throw if any loadRoute implementations not called since they are what\n  // ensures a route is fully loaded\n  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.\"));\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// Default logic for calling a loader/action is the user has no specified a dataStrategy\nasync function callLoaderOrAction(type, request, match, manifest, mapRouteProperties, handlerOverride, staticContext) {\n  let result;\n  let onReject;\n  let runHandler = handler => {\n    // Setup a promise we can race against so that abort signals short circuit\n    let reject;\n    // This will never resolve so safe to type it as Promise<HandlerResult> 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    let actualHandler = ctx => {\n      if (typeof handler !== \"function\") {\n        return Promise.reject(new Error(\"You cannot call the handler for a route which defines a boolean \" + (\"\\\"\" + type + \"\\\" [routeId: \" + match.route.id + \"]\")));\n      }\n      return handler({\n        request,\n        params: match.params,\n        context: staticContext\n      }, ...(ctx !== undefined ? [ctx] : []));\n    };\n    let handlerPromise;\n    if (handlerOverride) {\n      handlerPromise = handlerOverride(ctx => actualHandler(ctx));\n    } else {\n      handlerPromise = (async () => {\n        try {\n          let val = await actualHandler();\n          return {\n            type: \"data\",\n            result: val\n          };\n        } catch (e) {\n          return {\n            type: \"error\",\n            result: e\n          };\n        }\n      })();\n    }\n    return Promise.race([handlerPromise, abortPromise]);\n  };\n  try {\n    let handler = match.route[type];\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        }), loadLazyRouteModule(match.route, mapRouteProperties, manifest)]);\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        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 {\n            type: ResultType.data,\n            result: undefined\n          };\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    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`.\");\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 {\n      type: ResultType.error,\n      result: e\n    };\n  } finally {\n    if (onReject) {\n      request.signal.removeEventListener(\"abort\", onReject);\n    }\n  }\n  return result;\n}\nasync function convertHandlerResultToDataResult(handlerResult) {\n  let {\n    result,\n    type,\n    status\n  } = handlerResult;\n  if (isResponse(result)) {\n    let data;\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 {\n        type: ResultType.error,\n        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    return {\n      type: ResultType.data,\n      data,\n      statusCode: result.status,\n      headers: result.headers\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  if (isDeferredData(result)) {\n    var _result$init, _result$init2;\n    return {\n      type: ResultType.deferred,\n      deferredData: result,\n      statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status,\n      headers: ((_result$init2 = result.init) == null ? void 0 : _result$init2.headers) && new Headers(result.init.headers)\n    };\n  }\n  return {\n    type: ResultType.data,\n    data: result,\n    statusCode: status\n  };\n}\n// Support relative routing in internal redirects\nfunction normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, v7_relativeSplatPath) {\n  let location = response.headers.get(\"Location\");\n  invariant(location, \"Redirects returned/thrown from loaders/actions must have a Location header\");\n  if (!ABSOLUTE_URL_REGEX.test(location)) {\n    let trimmedMatches = matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1);\n    location = normalizeTo(new URL(request.url), trimmedMatches, basename, true, location, v7_relativeSplatPath);\n    response.headers.set(\"Location\", location);\n  }\n  return response;\n}\nfunction normalizeRedirectLocation(location, currentUrl, basename) {\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(\"//\") ? new URL(currentUrl.protocol + normalizedLocation) : 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// 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(history, location, signal, submission) {\n  let url = history.createURL(stripHashFromPath(location)).toString();\n  let init = {\n    signal\n  };\n  if (submission && isMutationMethod(submission.formMethod)) {\n    let {\n      formMethod,\n      formEncType\n    } = 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    if (formEncType === \"application/json\") {\n      init.headers = new Headers({\n        \"Content-Type\": formEncType\n      });\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 (formEncType === \"application/x-www-form-urlencoded\" && submission.formData) {\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  return new Request(url, init);\n}\nfunction convertFormDataToSearchParams(formData) {\n  let searchParams = new URLSearchParams();\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  return searchParams;\n}\nfunction convertSearchParamsToFormData(searchParams) {\n  let formData = new FormData();\n  for (let [key, value] of searchParams.entries()) {\n    formData.append(key, value);\n  }\n  return formData;\n}\nfunction processRouteLoaderData(matches, matchesToLoad, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling) {\n  // Fill in loaderData/errors from our loaders\n  let loaderData = {};\n  let errors = null;\n  let statusCode;\n  let foundError = false;\n  let loaderHeaders = {};\n  let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : undefined;\n  // Process loader results into state.loaderData/state.errors\n  results.forEach((result, index) => {\n    let id = matchesToLoad[index].route.id;\n    invariant(!isRedirectResult(result), \"Cannot handle redirect results in processLoaderData\");\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      errors = errors || {};\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      // Clear our any prior loaderData for the throwing route\n      loaderData[id] = undefined;\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) ? result.error.status : 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 (result.statusCode != null && result.statusCode !== 200 && !foundError) {\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  // 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 = {\n      [pendingActionResult[0]]: pendingError\n    };\n    loaderData[pendingActionResult[0]] = undefined;\n  }\n  return {\n    loaderData,\n    errors,\n    statusCode: statusCode || 200,\n    loaderHeaders\n  };\n}\nfunction processLoaderData(state, matches, matchesToLoad, results, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds) {\n  let {\n    loaderData,\n    errors\n  } = processRouteLoaderData(matches, matchesToLoad, results, pendingActionResult, activeDeferreds, false // This method is only called client side so we always want to bubble\n  );\n  // Process results from our revalidating fetchers\n  for (let index = 0; index < revalidatingFetchers.length; index++) {\n    let {\n      key,\n      match,\n      controller\n    } = revalidatingFetchers[index];\n    invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, \"Did not find corresponding fetcher result\");\n    let result = fetcherResults[index];\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 == null ? void 0 : match.route.id);\n      if (!(errors && errors[boundaryMatch.route.id])) {\n        errors = _extends({}, 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  return {\n    loaderData,\n    errors\n  };\n}\nfunction mergeLoaderData(loaderData, newLoaderData, matches, errors) {\n  let mergedLoaderData = _extends({}, 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      }\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    if (errors && errors.hasOwnProperty(id)) {\n      // Don't keep any loader data below the boundary\n      break;\n    }\n  }\n  return mergedLoaderData;\n}\nfunction getActionDataForCommit(pendingActionResult) {\n  if (!pendingActionResult) {\n    return {};\n  }\n  return isErrorResult(pendingActionResult[1]) ? {\n    // Clear out prior actionData on errors\n    actionData: {}\n  } : {\n    actionData: {\n      [pendingActionResult[0]]: pendingActionResult[1].data\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(matches, routeId) {\n  let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches];\n  return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0];\n}\nfunction getShortCircuitMatches(routes) {\n  // Prefer a root layout route if present, otherwise shim in a route object\n  let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === \"/\") || {\n    id: \"__shim-error-route__\"\n  };\n  return {\n    matches: [{\n      params: {},\n      pathname: \"\",\n      pathnameBase: \"\",\n      route\n    }],\n    route\n  };\n}\nfunction getInternalRouterError(status, _temp5) {\n  let {\n    pathname,\n    routeId,\n    method,\n    type\n  } = _temp5 === void 0 ? {} : _temp5;\n  let statusText = \"Unknown Server Error\";\n  let errorMessage = \"Unknown @remix-run/router error\";\n  if (status === 400) {\n    statusText = \"Bad Request\";\n    if (method && pathname && routeId) {\n      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.\";\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 = \"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.\";\n    } else if (method) {\n      errorMessage = \"Invalid request method \\\"\" + method.toUpperCase() + \"\\\"\";\n    }\n  }\n  return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true);\n}\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(results) {\n  for (let i = results.length - 1; i >= 0; i--) {\n    let result = results[i];\n    if (isRedirectResult(result)) {\n      return {\n        result,\n        idx: i\n      };\n    }\n  }\n}\nfunction stripHashFromPath(path) {\n  let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n  return createPath(_extends({}, parsedPath, {\n    hash: \"\"\n  }));\n}\nfunction isHashChangeOnly(a, b) {\n  if (a.pathname !== b.pathname || a.search !== b.search) {\n    return false;\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  // If the hash is removed the browser will re-perform a request to the server\n  // /page#hash -> /page\n  return false;\n}\nfunction isHandlerResult(result) {\n  return result != null && typeof result === \"object\" && \"type\" in result && \"result\" in result && (result.type === ResultType.data || result.type === ResultType.error);\n}\nfunction isRedirectHandlerResult(result) {\n  return isResponse(result.result) && redirectStatusCodes.has(result.result.status);\n}\nfunction isDeferredResult(result) {\n  return result.type === ResultType.deferred;\n}\nfunction isErrorResult(result) {\n  return result.type === ResultType.error;\n}\nfunction isRedirectResult(result) {\n  return (result && result.type) === ResultType.redirect;\n}\nfunction isDeferredData(value) {\n  let deferred = value;\n  return deferred && typeof deferred === \"object\" && typeof deferred.data === \"object\" && typeof deferred.subscribe === \"function\" && typeof deferred.cancel === \"function\" && typeof deferred.resolveData === \"function\";\n}\nfunction isResponse(value) {\n  return value != null && typeof value.status === \"number\" && typeof value.statusText === \"string\" && typeof value.headers === \"object\" && typeof value.body !== \"undefined\";\n}\nfunction isRedirectResponse(result) {\n  if (!isResponse(result)) {\n    return false;\n  }\n  let status = result.status;\n  let location = result.headers.get(\"Location\");\n  return status >= 300 && status <= 399 && location != null;\n}\nfunction isValidMethod(method) {\n  return validRequestMethods.has(method.toLowerCase());\n}\nfunction isMutationMethod(method) {\n  return validMutationMethods.has(method.toLowerCase());\n}\nasync function resolveDeferredResults(currentMatches, matchesToLoad, results, signals, isFetcher, currentLoaderData) {\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    let currentMatch = currentMatches.find(m => m.route.id === match.route.id);\n    let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\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(signal, \"Expected an AbortSignal for revalidating fetcher deferred result\");\n      await resolveDeferredData(result, signal, isFetcher).then(result => {\n        if (result) {\n          results[index] = result || results[index];\n        }\n      });\n    }\n  }\n}\nasync function resolveDeferredData(result, signal, unwrap) {\n  if (unwrap === void 0) {\n    unwrap = false;\n  }\n  let aborted = await result.deferredData.resolveData(signal);\n  if (aborted) {\n    return;\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  return {\n    type: ResultType.data,\n    data: result.deferredData.data\n  };\n}\nfunction hasNakedIndexQuery(search) {\n  return new URLSearchParams(search).getAll(\"index\").some(v => v === \"\");\n}\nfunction getTargetMatch(matches, location) {\n  let search = typeof location === \"string\" ? parsePath(location).search : location.search;\n  if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || \"\")) {\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}\nfunction getSubmissionFromNavigation(navigation) {\n  let {\n    formMethod,\n    formAction,\n    formEncType,\n    text,\n    formData,\n    json\n  } = navigation;\n  if (!formMethod || !formAction || !formEncType) {\n    return;\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}\nfunction getLoadingNavigation(location, submission) {\n  if (submission) {\n    let navigation = {\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 = {\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}\nfunction getSubmittingNavigation(location, submission) {\n  let navigation = {\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}\nfunction getLoadingFetcher(submission, data) {\n  if (submission) {\n    let fetcher = {\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 = {\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}\nfunction getSubmittingFetcher(submission, existingFetcher) {\n  let fetcher = {\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}\nfunction getDoneFetcher(data) {\n  let fetcher = {\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}\nfunction restoreAppliedTransitions(_window, transitions) {\n  try {\n    let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY);\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}\nfunction persistAppliedTransitions(_window, transitions) {\n  if (transitions.size > 0) {\n    let json = {};\n    for (let [k, v] of transitions) {\n      json[k] = [...v];\n    }\n    try {\n      _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json));\n    } catch (error) {\n      warning(false, \"Failed to save applied view transitions in sessionStorage (\" + error + \").\");\n    }\n  }\n}\n//#endregion\n\nexport { 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 };","map":{"version":3,"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","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"],"sources":["/Users/shanyi/Desktop/Projects/UC_Trains_Voice/react-demo/node_modules/@remix-run/router/history.ts","/Users/shanyi/Desktop/Projects/UC_Trains_Voice/react-demo/node_modules/@remix-run/router/utils.ts","/Users/shanyi/Desktop/Projects/UC_Trains_Voice/react-demo/node_modules/@remix-run/router/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<State = any> extends Path {\n  /**\n   * A value of arbitrary data associated with this location.\n   */\n  state: State;\n\n  /**\n   * A unique string associated with this location. May be used to safely store\n   * and retrieve data in some other storage API, like `localStorage`.\n   *\n   * Note: This value is always \"default\" on the initial location.\n   */\n  key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n  /**\n   * The action that triggered the change.\n   */\n  action: Action;\n\n  /**\n   * The new location.\n   */\n  location: Location;\n\n  /**\n   * The delta between this location and the former location in the history stack\n   */\n  delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n  (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, 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<Path>;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n  /**\n   * The last action that modified the current location. This will always be\n   * Action.Pop when a history instance is first created. This value is mutable.\n   */\n  readonly action: Action;\n\n  /**\n   * The current location. This value is mutable.\n   */\n  readonly location: Location;\n\n  /**\n   * Returns a valid href for the given `to` value that may be used as\n   * the value of an <a href> attribute.\n   *\n   * @param to - The destination URL\n   */\n  createHref(to: To): string;\n\n  /**\n   * Returns a URL for the given `to` value\n   *\n   * @param to - The destination URL\n   */\n  createURL(to: To): URL;\n\n  /**\n   * Encode a location the same way window.history would do (no-op for memory\n   * history) so we ensure our PUSH/REPLACE navigations for data routers\n   * behave the same as POP\n   *\n   * @param to Unencoded path\n   */\n  encodeLocation(to: To): Path;\n\n  /**\n   * Pushes a new location onto the history stack, increasing its length by one.\n   * If there were any entries in the stack after the current one, they are\n   * lost.\n   *\n   * @param to - The new URL\n   * @param state - Data to associate with the new location\n   */\n  push(to: To, state?: any): void;\n\n  /**\n   * Replaces the current location in the history stack with a new one.  The\n   * location that was replaced will no longer be available.\n   *\n   * @param to - The new URL\n   * @param state - Data to associate with the new location\n   */\n  replace(to: To, state?: any): void;\n\n  /**\n   * Navigates `n` entries backward/forward in the history stack relative to the\n   * current index. For example, a \"back\" navigation would use go(-1).\n   *\n   * @param delta - The delta in the stack index\n   */\n  go(delta: number): void;\n\n  /**\n   * Sets up a listener that will be called whenever the current location\n   * changes.\n   *\n   * @param listener - A function that will be called when the location changes\n   * @returns unlisten - A function that may be used to stop listening\n   */\n  listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n  usr: any;\n  key?: string;\n  idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial<Location>;\n\nexport type MemoryHistoryOptions = {\n  initialEntries?: InitialEntry[];\n  initialIndex?: number;\n  v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n  /**\n   * The current index in the history stack.\n   */\n  readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n  options: MemoryHistoryOptions = {}\n): MemoryHistory {\n  let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n  let entries: Location[]; // Declare so we can access from createMemoryLocation\n  entries = initialEntries.map((entry, index) =>\n    createMemoryLocation(\n      entry,\n      typeof entry === \"string\" ? null : entry.state,\n      index === 0 ? \"default\" : undefined\n    )\n  );\n  let index = clampIndex(\n    initialIndex == null ? entries.length - 1 : initialIndex\n  );\n  let action = Action.Pop;\n  let listener: Listener | null = null;\n\n  function clampIndex(n: number): number {\n    return Math.min(Math.max(n, 0), entries.length - 1);\n  }\n  function getCurrentLocation(): Location {\n    return entries[index];\n  }\n  function createMemoryLocation(\n    to: To,\n    state: any = null,\n    key?: string\n  ): Location {\n    let location = createLocation(\n      entries ? getCurrentLocation().pathname : \"/\",\n      to,\n      state,\n      key\n    );\n    warning(\n      location.pathname.charAt(0) === \"/\",\n      `relative pathnames are not supported in memory history: ${JSON.stringify(\n        to\n      )}`\n    );\n    return location;\n  }\n\n  function createHref(to: To) {\n    return typeof to === \"string\" ? to : createPath(to);\n  }\n\n  let history: MemoryHistory = {\n    get index() {\n      return index;\n    },\n    get action() {\n      return action;\n    },\n    get location() {\n      return getCurrentLocation();\n    },\n    createHref,\n    createURL(to) {\n      return new URL(createHref(to), \"http://localhost\");\n    },\n    encodeLocation(to: To) {\n      let path = typeof to === \"string\" ? parsePath(to) : to;\n      return {\n        pathname: path.pathname || \"\",\n        search: path.search || \"\",\n        hash: path.hash || \"\",\n      };\n    },\n    push(to, state) {\n      action = Action.Push;\n      let nextLocation = createMemoryLocation(to, state);\n      index += 1;\n      entries.splice(index, entries.length, nextLocation);\n      if (v5Compat && listener) {\n        listener({ action, location: nextLocation, delta: 1 });\n      }\n    },\n    replace(to, state) {\n      action = Action.Replace;\n      let nextLocation = createMemoryLocation(to, state);\n      entries[index] = nextLocation;\n      if (v5Compat && listener) {\n        listener({ action, location: nextLocation, delta: 0 });\n      }\n    },\n    go(delta) {\n      action = Action.Pop;\n      let nextIndex = clampIndex(index + delta);\n      let nextLocation = entries[nextIndex];\n      index = nextIndex;\n      if (listener) {\n        listener({ action, location: nextLocation, delta });\n      }\n    },\n    listen(fn: Listener) {\n      listener = fn;\n      return () => {\n        listener = null;\n      };\n    },\n  };\n\n  return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n  options: BrowserHistoryOptions = {}\n): BrowserHistory {\n  function createBrowserLocation(\n    window: Window,\n    globalHistory: Window[\"history\"]\n  ) {\n    let { pathname, search, hash } = window.location;\n    return createLocation(\n      \"\",\n      { pathname, search, hash },\n      // state defaults to `null` because `window.history.state` does\n      (globalHistory.state && globalHistory.state.usr) || null,\n      (globalHistory.state && globalHistory.state.key) || \"default\"\n    );\n  }\n\n  function createBrowserHref(window: Window, to: To) {\n    return typeof to === \"string\" ? to : createPath(to);\n  }\n\n  return getUrlBasedHistory(\n    createBrowserLocation,\n    createBrowserHref,\n    null,\n    options\n  );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n  options: HashHistoryOptions = {}\n): HashHistory {\n  function createHashLocation(\n    window: Window,\n    globalHistory: Window[\"history\"]\n  ) {\n    let {\n      pathname = \"/\",\n      search = \"\",\n      hash = \"\",\n    } = parsePath(window.location.hash.substr(1));\n\n    // Hash URL should always have a leading / just like window.location.pathname\n    // does, so if an app ends up at a route like /#something then we add a\n    // leading slash so all of our path-matching behaves the same as if it would\n    // in a browser router.  This is particularly important when there exists a\n    // root splat route (<Route path=\"*\">) since that matches internally against\n    // \"/*\" and we'd expect /#something to 404 in a hash router app.\n    if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n      pathname = \"/\" + pathname;\n    }\n\n    return createLocation(\n      \"\",\n      { pathname, search, hash },\n      // state defaults to `null` because `window.history.state` does\n      (globalHistory.state && globalHistory.state.usr) || null,\n      (globalHistory.state && globalHistory.state.key) || \"default\"\n    );\n  }\n\n  function createHashHref(window: Window, to: To) {\n    let base = window.document.querySelector(\"base\");\n    let href = \"\";\n\n    if (base && base.getAttribute(\"href\")) {\n      let url = window.location.href;\n      let hashIndex = url.indexOf(\"#\");\n      href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n    }\n\n    return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n  }\n\n  function validateHashLocation(location: Location, to: To) {\n    warning(\n      location.pathname.charAt(0) === \"/\",\n      `relative pathnames are not supported in hash history.push(${JSON.stringify(\n        to\n      )})`\n    );\n  }\n\n  return getUrlBasedHistory(\n    createHashLocation,\n    createHashHref,\n    validateHashLocation,\n    options\n  );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant<T>(\n  value: T | null | undefined,\n  message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n  if (value === false || value === null || typeof value === \"undefined\") {\n    throw new Error(message);\n  }\n}\n\nexport function warning(cond: any, message: string) {\n  if (!cond) {\n    // 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<Location> {\n  let location: Readonly<Location> = {\n    pathname: typeof current === \"string\" ? current : current.pathname,\n    search: \"\",\n    hash: \"\",\n    ...(typeof to === \"string\" ? parsePath(to) : to),\n    state,\n    // TODO: This could be cleaned up.  push/replace should probably just take\n    // full Locations now and avoid the need to run through this flow at all\n    // But that's a pretty big refactor to the current test suite so going to\n    // keep as is for the time being and just let any incoming keys take precedence\n    key: (to && (to as Location).key) || key || createKey(),\n  };\n  return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n  pathname = \"/\",\n  search = \"\",\n  hash = \"\",\n}: Partial<Path>) {\n  if (search && search !== \"?\")\n    pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n  if (hash && hash !== \"#\")\n    pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n  return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial<Path> {\n  let parsedPath: Partial<Path> = {};\n\n  if (path) {\n    let hashIndex = path.indexOf(\"#\");\n    if (hashIndex >= 0) {\n      parsedPath.hash = path.substr(hashIndex);\n      path = path.substr(0, hashIndex);\n    }\n\n    let searchIndex = path.indexOf(\"?\");\n    if (searchIndex >= 0) {\n      parsedPath.search = path.substr(searchIndex);\n      path = path.substr(0, searchIndex);\n    }\n\n    if (path) {\n      parsedPath.pathname = path;\n    }\n  }\n\n  return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n  window?: Window;\n  v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n  getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n  createHref: (window: Window, to: To) => string,\n  validateLocation: ((location: Location, to: To) => void) | null,\n  options: UrlHistoryOptions = {}\n): UrlHistory {\n  let { window = document.defaultView!, v5Compat = false } = options;\n  let globalHistory = window.history;\n  let action = Action.Pop;\n  let listener: Listener | null = null;\n\n  let index = getIndex()!;\n  // Index should only be null when we initialize. If not, it's because the\n  // user called history.pushState or history.replaceState directly, in which\n  // case we should log a warning as it will result in bugs.\n  if (index == null) {\n    index = 0;\n    globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n  }\n\n  function getIndex(): number {\n    let state = globalHistory.state || { idx: null };\n    return state.idx;\n  }\n\n  function handlePop() {\n    action = Action.Pop;\n    let nextIndex = getIndex();\n    let delta = nextIndex == null ? null : nextIndex - index;\n    index = nextIndex;\n    if (listener) {\n      listener({ action, location: history.location, delta });\n    }\n  }\n\n  function push(to: To, state?: any) {\n    action = Action.Push;\n    let location = createLocation(history.location, to, state);\n    if (validateLocation) validateLocation(location, to);\n\n    index = getIndex() + 1;\n    let historyState = getHistoryState(location, index);\n    let url = history.createHref(location);\n\n    // try...catch because iOS limits us to 100 pushState calls :/\n    try {\n      globalHistory.pushState(historyState, \"\", url);\n    } catch (error) {\n      // If the exception is because `state` can't be serialized, let that throw\n      // outwards just like a replace call would so the dev knows the cause\n      // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n      // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n      if (error instanceof DOMException && error.name === \"DataCloneError\") {\n        throw error;\n      }\n      // They are going to lose state here, but there is no real\n      // way to warn them about it since the page will refresh...\n      window.location.assign(url);\n    }\n\n    if (v5Compat && listener) {\n      listener({ action, location: history.location, delta: 1 });\n    }\n  }\n\n  function replace(to: To, state?: any) {\n    action = Action.Replace;\n    let location = createLocation(history.location, to, state);\n    if (validateLocation) validateLocation(location, to);\n\n    index = getIndex();\n    let historyState = getHistoryState(location, index);\n    let url = history.createHref(location);\n    globalHistory.replaceState(historyState, \"\", url);\n\n    if (v5Compat && listener) {\n      listener({ action, location: history.location, delta: 0 });\n    }\n  }\n\n  function createURL(to: To): URL {\n    // window.location.origin is \"null\" (the literal string value) in Firefox\n    // under certain conditions, notably when serving from a local HTML file\n    // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n    let base =\n      window.location.origin !== \"null\"\n        ? window.location.origin\n        : window.location.href;\n\n    let href = typeof to === \"string\" ? to : createPath(to);\n    // Treating this as a full URL will strip any trailing spaces so we need to\n    // pre-encode them since they might be part of a matching splat param from\n    // an ancestor route\n    href = href.replace(/ $/, \"%20\");\n    invariant(\n      base,\n      `No window.location.(origin|href) available to create URL for href: ${href}`\n    );\n    return new URL(href, base);\n  }\n\n  let history: History = {\n    get action() {\n      return action;\n    },\n    get location() {\n      return getLocation(window, globalHistory);\n    },\n    listen(fn: Listener) {\n      if (listener) {\n        throw new Error(\"A history only accepts one active listener\");\n      }\n      window.addEventListener(PopStateEventType, handlePop);\n      listener = fn;\n\n      return () => {\n        window.removeEventListener(PopStateEventType, handlePop);\n        listener = null;\n      };\n    },\n    createHref(to) {\n      return createHref(window, to);\n    },\n    createURL,\n    encodeLocation(to) {\n      // Encode a Location the same way window.location would\n      let url = createURL(to);\n      return {\n        pathname: url.pathname,\n        search: url.search,\n        hash: url.hash,\n      };\n    },\n    push,\n    replace,\n    go(n) {\n      return globalHistory.go(n);\n    },\n  };\n\n  return history;\n}\n\n//#endregion\n","import type { 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<LowerCaseFormMethod>;\n\n/**\n * Users can specify either lowercase or uppercase form methods on `<Form>`,\n * useSubmit(), `<fetcher.Form>`, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude<FormMethod, \"get\">;\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<V7_FormMethod, \"GET\">;\n\nexport type FormEncType =\n  | \"application/x-www-form-urlencoded\"\n  | \"multipart/form-data\"\n  | \"application/json\"\n  | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n  [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n  | {\n      formMethod: FormMethod | 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<Context> {\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<Context = any>\n  extends DataFunctionArgs<Context> {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return).  Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable<unknown> | null;\n\ntype DataFunctionReturnValue = Promise<DataFunctionValue> | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction<Context = any> = {\n  (\n    args: LoaderFunctionArgs<Context>,\n    handlerCtx?: unknown\n  ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction<Context = any> {\n  (\n    args: ActionFunctionArgs<Context>,\n    handlerCtx?: unknown\n  ): DataFunctionReturnValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n  currentUrl: URL;\n  currentParams: AgnosticDataRouteMatch[\"params\"];\n  nextUrl: URL;\n  nextParams: AgnosticDataRouteMatch[\"params\"];\n  formMethod?: Submission[\"formMethod\"];\n  formAction?: Submission[\"formAction\"];\n  formEncType?: Submission[\"formEncType\"];\n  text?: Submission[\"text\"];\n  formData?: Submission[\"formData\"];\n  json?: Submission[\"json\"];\n  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<string, AgnosticDataRouteObject> {\n  shouldLoad: boolean;\n  resolve: (\n    handlerOverride?: (\n      handler: (ctx?: unknown) => DataFunctionReturnValue\n    ) => Promise<HandlerResult>\n  ) => Promise<HandlerResult>;\n}\n\nexport interface DataStrategyFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {\n  matches: DataStrategyMatch[];\n}\n\nexport interface DataStrategyFunction {\n  (args: DataStrategyFunctionArgs): Promise<HandlerResult[]>;\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<string, any>;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n  | \"lazy\"\n  | \"caseSensitive\"\n  | \"path\"\n  | \"id\"\n  | \"index\"\n  | \"children\";\n\nexport const immutableRouteKeys = new Set<ImmutableRouteKey>([\n  \"lazy\",\n  \"caseSensitive\",\n  \"path\",\n  \"id\",\n  \"index\",\n  \"children\",\n]);\n\ntype RequireOne<T, Key = keyof T> = Exclude<\n  {\n    [K in keyof T]: K extends Key ? Omit<T, K> & Required<Pick<T, K>> : never;\n  }[keyof T],\n  undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction<R extends AgnosticRouteObject> {\n  (): Promise<RequireOne<Omit<R, ImmutableRouteKey>>>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n  caseSensitive?: boolean;\n  path?: string;\n  id?: string;\n  loader?: LoaderFunction | boolean;\n  action?: ActionFunction | boolean;\n  hasErrorBoundary?: boolean;\n  shouldRevalidate?: ShouldRevalidateFunction;\n  handle?: any;\n  lazy?: LazyRouteFunction<AgnosticBaseRouteObject>;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n  children?: undefined;\n  index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n  children?: AgnosticRouteObject[];\n  index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n  | AgnosticIndexRouteObject\n  | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n  id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n  children?: AgnosticDataRouteObject[];\n  id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n  | AgnosticDataIndexRouteObject\n  | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record<string, AgnosticDataRouteObject | undefined>;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam<Path extends string> =\n  // split path into individual path segments\n  Path extends `${infer L}/${infer R}`\n    ? _PathParam<L> | _PathParam<R>\n    : // find params after `:`\n    Path extends `:${infer Param}`\n    ? Param extends `${infer Optional}?`\n      ? Optional\n      : Param\n    : // otherwise, there aren't any params present\n      never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam<Path extends string> =\n  // check if path is just a wildcard\n  Path extends \"*\" | \"/*\"\n    ? \"*\"\n    : // look for wildcard at the end of the path\n    Path extends `${infer Rest}/*`\n    ? \"*\" | _PathParam<Rest>\n    : // look for params in the absence of wildcards\n      _PathParam<Path>;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise, return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey<Segment extends string> =\n  // if you could not find path params, fallback to `string`\n  [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params<Key extends string = string> = {\n  readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n  ParamKey extends string = string,\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  /**\n   * The names and values of dynamic parameters in the URL.\n   */\n  params: Params<ParamKey>;\n  /**\n   * The portion of the URL pathname that was matched.\n   */\n  pathname: string;\n  /**\n   * The portion of the URL pathname that was matched before child routes.\n   */\n  pathnameBase: string;\n  /**\n   * The route object that was used to match.\n   */\n  route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n  extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {}\n\nfunction isIndexRoute(\n  route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n  return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n  routes: AgnosticRouteObject[],\n  mapRouteProperties: MapRoutePropertiesFunction,\n  parentPath: 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<Location> | string,\n  basename = \"/\"\n): AgnosticRouteMatch<string, RouteObjectType>[] | null {\n  let location =\n    typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n  let pathname = stripBasename(location.pathname || \"/\", basename);\n\n  if (pathname == null) {\n    return null;\n  }\n\n  let branches = flattenRoutes(routes);\n  rankRouteBranches(branches);\n\n  let matches = null;\n  for (let i = 0; matches == null && i < branches.length; ++i) {\n    // Incoming pathnames are generally encoded from either window.location\n    // or from router.navigate, but we want to match against the unencoded\n    // paths in the route definitions.  Memory router locations won't be\n    // encoded here but there also shouldn't be anything to decode so this\n    // should be a safe operation.  This avoids needing matchRoutes to be\n    // history-aware.\n    let decoded = decodePath(pathname);\n    matches = matchRouteBranch<string, RouteObjectType>(branches[i], decoded);\n  }\n\n  return matches;\n}\n\nexport interface UIMatch<Data = unknown, Handle = unknown> {\n  id: string;\n  pathname: string;\n  params: AgnosticRouteMatch[\"params\"];\n  data: Data;\n  handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n  match: AgnosticDataRouteMatch,\n  loaderData: RouteData\n): UIMatch {\n  let { route, pathname, params } = match;\n  return {\n    id: route.id,\n    pathname,\n    params,\n    data: loaderData[route.id],\n    handle: route.handle,\n  };\n}\n\ninterface RouteMeta<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  relativePath: string;\n  caseSensitive: boolean;\n  childrenIndex: number;\n  route: RouteObjectType;\n}\n\ninterface RouteBranch<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  path: string;\n  score: number;\n  routesMeta: RouteMeta<RouteObjectType>[];\n}\n\nfunction flattenRoutes<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  routes: RouteObjectType[],\n  branches: RouteBranch<RouteObjectType>[] = [],\n  parentsMeta: RouteMeta<RouteObjectType>[] = [],\n  parentPath = \"\"\n): RouteBranch<RouteObjectType>[] {\n  let flattenRoute = (\n    route: RouteObjectType,\n    index: number,\n    relativePath?: string\n  ) => {\n    let meta: RouteMeta<RouteObjectType> = {\n      relativePath:\n        relativePath === undefined ? route.path || \"\" : relativePath,\n      caseSensitive: route.caseSensitive === true,\n      childrenIndex: index,\n      route,\n    };\n\n    if (meta.relativePath.startsWith(\"/\")) {\n      invariant(\n        meta.relativePath.startsWith(parentPath),\n        `Absolute route path \"${meta.relativePath}\" nested under path ` +\n          `\"${parentPath}\" is not valid. An absolute child route path ` +\n          `must start with the combined path of all its parent routes.`\n      );\n\n      meta.relativePath = meta.relativePath.slice(parentPath.length);\n    }\n\n    let path = joinPaths([parentPath, meta.relativePath]);\n    let routesMeta = parentsMeta.concat(meta);\n\n    // Add the children before adding this route to the array, so we traverse the\n    // route tree depth-first and child routes appear before their parents in\n    // the \"flattened\" version.\n    if (route.children && route.children.length > 0) {\n      invariant(\n        // Our types know better, but runtime JS may not!\n        // @ts-expect-error\n        route.index !== true,\n        `Index routes must not have child routes. Please remove ` +\n          `all child routes from route path \"${path}\".`\n      );\n\n      flattenRoutes(route.children, branches, routesMeta, path);\n    }\n\n    // Routes without a path shouldn't ever match by themselves unless they are\n    // index routes, so don't add them to the list of possible branches.\n    if (route.path == null && !route.index) {\n      return;\n    }\n\n    branches.push({\n      path,\n      score: computeScore(path, route.index),\n      routesMeta,\n    });\n  };\n  routes.forEach((route, index) => {\n    // coarse-grain check for optional params\n    if (route.path === \"\" || !route.path?.includes(\"?\")) {\n      flattenRoute(route, index);\n    } else {\n      for (let exploded of explodeOptionalSegments(route.path)) {\n        flattenRoute(route, index, exploded);\n      }\n    }\n  });\n\n  return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n  let segments = path.split(\"/\");\n  if (segments.length === 0) return [];\n\n  let [first, ...rest] = segments;\n\n  // Optional path segments are denoted by a trailing `?`\n  let isOptional = first.endsWith(\"?\");\n  // Compute the corresponding required segment: `foo?` -> `foo`\n  let required = first.replace(/\\?$/, \"\");\n\n  if (rest.length === 0) {\n    // Intepret empty string as omitting an optional segment\n    // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n    return isOptional ? [required, \"\"] : [required];\n  }\n\n  let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n  let result: string[] = [];\n\n  // All child paths with the prefix.  Do this for all children before the\n  // optional version for all children, so we get consistent ordering where the\n  // parent optional aspect is preferred as required.  Otherwise, we can get\n  // child sections interspersed where deeper optional segments are higher than\n  // parent optional segments, where for example, /:two would explode _earlier_\n  // then /:one.  By always including the parent as required _for all children_\n  // first, we avoid this issue\n  result.push(\n    ...restExploded.map((subpath) =>\n      subpath === \"\" ? required : [required, subpath].join(\"/\")\n    )\n  );\n\n  // Then, if this is an optional value, add all child versions without\n  if (isOptional) {\n    result.push(...restExploded);\n  }\n\n  // for absolute paths, ensure `/` instead of empty segment\n  return result.map((exploded) =>\n    path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n  );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n  branches.sort((a, b) =>\n    a.score !== b.score\n      ? b.score - a.score // Higher score first\n      : compareIndexes(\n          a.routesMeta.map((meta) => meta.childrenIndex),\n          b.routesMeta.map((meta) => meta.childrenIndex)\n        )\n  );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n  let segments = path.split(\"/\");\n  let initialScore = segments.length;\n  if (segments.some(isSplat)) {\n    initialScore += splatPenalty;\n  }\n\n  if (index) {\n    initialScore += indexRouteValue;\n  }\n\n  return segments\n    .filter((s) => !isSplat(s))\n    .reduce(\n      (score, segment) =>\n        score +\n        (paramRe.test(segment)\n          ? dynamicSegmentValue\n          : segment === \"\"\n          ? emptySegmentValue\n          : staticSegmentValue),\n      initialScore\n    );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n  let siblings =\n    a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n  return siblings\n    ? // If two routes are siblings, we should try to match the earlier sibling\n      // first. This allows people to have fine-grained control over the matching\n      // behavior by simply putting routes with identical paths in the order they\n      // want them tried.\n      a[a.length - 1] - b[b.length - 1]\n    : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n      // so they sort equally.\n      0;\n}\n\nfunction matchRouteBranch<\n  ParamKey extends string = string,\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  branch: RouteBranch<RouteObjectType>,\n  pathname: string\n): AgnosticRouteMatch<ParamKey, RouteObjectType>[] | null {\n  let { routesMeta } = branch;\n\n  let matchedParams = {};\n  let matchedPathname = \"/\";\n  let matches: AgnosticRouteMatch<ParamKey, RouteObjectType>[] = [];\n  for (let i = 0; i < routesMeta.length; ++i) {\n    let meta = routesMeta[i];\n    let end = i === routesMeta.length - 1;\n    let remainingPathname =\n      matchedPathname === \"/\"\n        ? pathname\n        : pathname.slice(matchedPathname.length) || \"/\";\n    let match = matchPath(\n      { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n      remainingPathname\n    );\n\n    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<ParamKey>,\n      pathname: joinPaths([matchedPathname, match.pathname]),\n      pathnameBase: normalizePathname(\n        joinPaths([matchedPathname, match.pathnameBase])\n      ),\n      route,\n    });\n\n    if (match.pathnameBase !== \"/\") {\n      matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n    }\n  }\n\n  return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/utils/generate-path\n */\nexport function generatePath<Path extends string>(\n  originalPath: Path,\n  params: {\n    [key in PathParam<Path>]: string | null;\n  } = {} as any\n): string {\n  let path: string = originalPath;\n  if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n    warning(\n      false,\n      `Route path \"${path}\" will be treated as if it were ` +\n        `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n        `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n        `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n    );\n    path = path.replace(/\\*$/, \"/*\") as Path;\n  }\n\n  // ensure `/` is added at the beginning if the path is absolute\n  const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n  const stringify = (p: any) =>\n    p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n  const segments = path\n    .split(/\\/+/)\n    .map((segment, index, array) => {\n      const isLastSegment = index === array.length - 1;\n\n      // only apply the splat if it's the last segment\n      if (isLastSegment && segment === \"*\") {\n        const star = \"*\" as PathParam<Path>;\n        // Apply the splat\n        return stringify(params[star]);\n      }\n\n      const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n      if (keyMatch) {\n        const [, key, optional] = keyMatch;\n        let param = params[key as PathParam<Path>];\n        invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n        return stringify(param);\n      }\n\n      // Remove any optional markers from optional static segments\n      return segment.replace(/\\?$/g, \"\");\n    })\n    // Remove empty segments\n    .filter((segment) => !!segment);\n\n  return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern<Path extends string = string> {\n  /**\n   * A string to match against a URL pathname. May contain `:id`-style segments\n   * to indicate placeholders for dynamic parameters. May also end with `/*` to\n   * indicate matching the rest of the URL pathname.\n   */\n  path: Path;\n  /**\n   * Should be `true` if the static portions of the `path` should be matched in\n   * the same case.\n   */\n  caseSensitive?: boolean;\n  /**\n   * Should be `true` if this pattern should match the entire URL pathname.\n   */\n  end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch<ParamKey extends string = string> {\n  /**\n   * The names and values of dynamic parameters in the URL.\n   */\n  params: Params<ParamKey>;\n  /**\n   * The portion of the URL pathname that was matched.\n   */\n  pathname: string;\n  /**\n   * The portion of the URL pathname that was matched before child routes.\n   */\n  pathnameBase: string;\n  /**\n   * The pattern that was used to match.\n   */\n  pattern: PathPattern;\n}\n\ntype Mutable<T> = {\n  -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/utils/match-path\n */\nexport function matchPath<\n  ParamKey extends ParamParseKey<Path>,\n  Path extends string\n>(\n  pattern: PathPattern<Path> | Path,\n  pathname: string\n): PathMatch<ParamKey> | null {\n  if (typeof pattern === \"string\") {\n    pattern = { path: pattern, caseSensitive: false, end: true };\n  }\n\n  let [matcher, compiledParams] = compilePath(\n    pattern.path,\n    pattern.caseSensitive,\n    pattern.end\n  );\n\n  let match = pathname.match(matcher);\n  if (!match) return null;\n\n  let matchedPathname = match[0];\n  let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n  let captureGroups = match.slice(1);\n  let params: Params = compiledParams.reduce<Mutable<Params>>(\n    (memo, { paramName, isOptional }, index) => {\n      // We need to compute the pathnameBase here using the raw splat value\n      // instead of using params[\"*\"] later because it will be decoded then\n      if (paramName === \"*\") {\n        let splatValue = captureGroups[index] || \"\";\n        pathnameBase = matchedPathname\n          .slice(0, matchedPathname.length - splatValue.length)\n          .replace(/(.)\\/+$/, \"$1\");\n      }\n\n      const value = captureGroups[index];\n      if (isOptional && !value) {\n        memo[paramName] = undefined;\n      } else {\n        memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n      }\n      return memo;\n    },\n    {}\n  );\n\n  return {\n    params,\n    pathname: matchedPathname,\n    pathnameBase,\n    pattern,\n  };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n  path: string,\n  caseSensitive = false,\n  end = true\n): [RegExp, CompiledPathParam[]] {\n  warning(\n    path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n    `Route path \"${path}\" will be treated as if it were ` +\n      `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n      `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n      `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n  );\n\n  let params: CompiledPathParam[] = [];\n  let regexpSource =\n    \"^\" +\n    path\n      .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n      .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n      .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n      .replace(\n        /\\/:([\\w-]+)(\\?)?/g,\n        (_: string, paramName: string, isOptional) => {\n          params.push({ paramName, isOptional: isOptional != null });\n          return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n        }\n      );\n\n  if (path.endsWith(\"*\")) {\n    params.push({ paramName: \"*\" });\n    regexpSource +=\n      path === \"*\" || path === \"/*\"\n        ? \"(.*)$\" // Already matched the initial /, just match the rest\n        : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n  } else if (end) {\n    // When matching to the end, ignore trailing slashes\n    regexpSource += \"\\\\/*$\";\n  } else if (path !== \"\" && path !== \"/\") {\n    // If our path is non-empty and contains anything beyond an initial slash,\n    // then we have _some_ form of path in our regex, so we should expect to\n    // match only if we find the end of this path segment.  Look for an optional\n    // non-captured trailing slash (to match a portion of the URL) or the end\n    // of the path (if we've matched to the end).  We used to do this with a\n    // word boundary but that gives false positives on routes like\n    // /user-preferences since `-` counts as a word boundary.\n    regexpSource += \"(?:(?=\\\\/|$))\";\n  } else {\n    // Nothing to match for \"\" or \"/\"\n  }\n\n  let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n  return [matcher, params];\n}\n\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<Path>\n) {\n  return (\n    `Cannot include a '${char}' character in a manually specified ` +\n    `\\`to.${field}\\` field [${JSON.stringify(\n      path\n    )}].  Please separate it out to the ` +\n    `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n    `a string in <Link to=\"...\"> and the router will parse it for you.`\n  );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same.  Both of the following examples should link back to the root:\n *\n *   <Route path=\"/\">\n *     <Route path=\"accounts\" element={<Link to=\"..\"}>\n *   </Route>\n *\n *   <Route path=\"/\">\n *     <Route path=\"accounts\">\n *       <Route element={<AccountsLayout />}>       // <-- Does not contribute\n *         <Route index element={<Link to=\"..\"} />  // <-- Does not contribute\n *       </Route\n *     </Route>\n *   </Route>\n */\nexport function getPathContributingMatches<\n  T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n  return matches.filter(\n    (match, index) =>\n      index === 0 || (match.route.path && match.route.path.length > 0)\n  );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n  T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], 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<Path>;\n  if (typeof toArg === \"string\") {\n    to = parsePath(toArg);\n  } else {\n    to = { ...toArg };\n\n    invariant(\n      !to.pathname || !to.pathname.includes(\"?\"),\n      getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n    );\n    invariant(\n      !to.pathname || !to.pathname.includes(\"#\"),\n      getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n    );\n    invariant(\n      !to.search || !to.search.includes(\"#\"),\n      getInvalidPathError(\"#\", \"search\", \"hash\", to)\n    );\n  }\n\n  let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n  let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n  let from: string;\n\n  // Routing is relative to the current pathname if explicitly requested.\n  //\n  // If a pathname is explicitly provided in `to`, it should be relative to the\n  // route context. This is explained in `Note on `<Link to>` values` in our\n  // migration guide from v5 as a means of disambiguation between `to` values\n  // that begin with `/` and those that do not. However, this is problematic for\n  // `to` values that do not provide a pathname. `to` can simply be a search or\n  // hash string, in which case we should assume that the navigation is relative\n  // to the current location's pathname and *not* the route pathname.\n  if (toPathname == null) {\n    from = locationPathname;\n  } else {\n    let routePathnameIndex = routePathnames.length - 1;\n\n    // With relative=\"route\" (the default), each leading .. segment means\n    // \"go up one route\" instead of \"go up one URL segment\".  This is a key\n    // difference from how <a href> works and a major reason we call this a\n    // \"to\" value instead of a \"href\".\n    if (!isPathRelative && toPathname.startsWith(\"..\")) {\n      let toSegments = toPathname.split(\"/\");\n\n      while (toSegments[0] === \"..\") {\n        toSegments.shift();\n        routePathnameIndex -= 1;\n      }\n\n      to.pathname = toSegments.join(\"/\");\n    }\n\n    from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n  }\n\n  let path = resolvePath(to, from);\n\n  // Ensure the pathname has a trailing slash if the original \"to\" had one\n  let hasExplicitTrailingSlash =\n    toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n  // Or if this was a link to the current path which has a trailing slash\n  let hasCurrentTrailingSlash =\n    (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n  if (\n    !path.pathname.endsWith(\"/\") &&\n    (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n  ) {\n    path.pathname += \"/\";\n  }\n\n  return path;\n}\n\n/**\n * @private\n */\nexport 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 = <Data>(\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<any> {\n  _tracked?: boolean;\n  _data?: any;\n  _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n  private pendingKeysSet: Set<string> = new Set<string>();\n  private controller: AbortController;\n  private abortPromise: Promise<void>;\n  private unlistenAbortSignal: () => void;\n  private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n    new Set();\n  data: Record<string, unknown>;\n  init?: ResponseInit;\n  deferredKeys: string[] = [];\n\n  constructor(data: Record<string, unknown>, 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> | 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<string, unknown>,\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<string, number>,\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<void>;\n\n  /**\n   * Navigate to the given path\n   * @param to Path to navigate to\n   * @param opts Navigation options (method, submission, etc.)\n   */\n  navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;\n\n  /**\n   * @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<TData = any>(key: string): Fetcher<TData>;\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<string, AbortController>;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Internal pending DeferredData instances accessed by unit tests\n   */\n  _internalActiveDeferreds: Map<string, DeferredData>;\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<string, Fetcher>;\n\n  /**\n   * Map of current blockers\n   */\n  blockers: Map<string, Blocker>;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n  Pick<RouterState, \"loaderData\" | \"actionData\" | \"errors\">\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n  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<FutureConfig>;\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<string, Headers>;\n  actionHeaders: Record<string, Headers>;\n  activeDeferreds: Record<string, DeferredData> | 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<StaticHandlerContext | Response>;\n  queryRoute(\n    request: Request,\n    opts?: {\n      routeId?: string;\n      requestContext?: unknown;\n      unstable_dataStrategy?: DataStrategyFunction;\n    }\n  ): Promise<any>;\n}\n\ntype ViewTransitionOpts = {\n  currentLocation: Location;\n  nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n  (\n    state: RouterState,\n    opts: {\n      deletedFetchers: string[];\n      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<TData = any> = {\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<TData = any> =\n  FetcherStates<TData>[keyof FetcherStates<TData>];\n\ninterface BlockerBlocked {\n  state: \"blocked\";\n  reset(): void;\n  proceed(): void;\n  location: Location;\n}\n\ninterface BlockerUnblocked {\n  state: \"unblocked\";\n  reset: undefined;\n  proceed: undefined;\n  location: undefined;\n}\n\ninterface BlockerProceeding {\n  state: \"proceeding\";\n  reset: undefined;\n  proceed: undefined;\n  location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n  currentLocation: Location;\n  nextLocation: Location;\n  historyAction: 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<MutationFormMethod>(\n  validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n  \"get\",\n  ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set<FormMethod>(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n  state: \"idle\",\n  location: undefined,\n  formMethod: undefined,\n  formAction: undefined,\n  formEncType: undefined,\n  formData: undefined,\n  json: undefined,\n  text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n  state: \"idle\",\n  data: undefined,\n  formMethod: undefined,\n  formAction: undefined,\n  formEncType: undefined,\n  formData: undefined,\n  json: undefined,\n  text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n  state: \"unblocked\",\n  proceed: undefined,\n  reset: undefined,\n  location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n  hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#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<RouterSubscriber>();\n  // Externally-provided object to hold scroll restoration locations during routing\n  let savedScrollPositions: Record<string, number> | null = null;\n  // Externally-provided function to get scroll restoration keys\n  let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n  // Externally-provided function to get current scroll position\n  let getScrollPosition: GetScrollPositionFunction | null = null;\n  // One-time flag to control the initial hydration scroll restoration.  Because\n  // we don't get the saved positions from <ScrollRestoration /> until _after_\n  // the initial render, we need to manually trigger a separate updateState to\n  // send along the restoreScrollPosition\n  // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n  // SSR did the initial scroll restoration.\n  let initialScrollRestored = init.hydrationData != null;\n\n  let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n  let initialErrors: RouteData | null = null;\n\n  if (initialMatches == null) {\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<string, Set<string>> = new Map<\n    string,\n    Set<string>\n  >();\n\n  // Cleanup function for persisting applied transitions to sessionStorage\n  let removePageHideEventListener: (() => void) | null = null;\n\n  // We use this to avoid touching history in completeNavigation if a\n  // revalidation is entirely uninterrupted\n  let isUninterruptedRevalidation = false;\n\n  // Use this internal flag to force revalidation of all loaders:\n  //  - submissions (completed or interrupted)\n  //  - useRevalidator()\n  //  - X-Remix-Revalidate (from redirect)\n  let isRevalidationRequired = false;\n\n  // Use this internal array to capture 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<string, AbortController>();\n\n  // Track loads based on the order in which they started\n  let incrementingLoadId = 0;\n\n  // Track the outstanding pending navigation data load to be compared against\n  // the globally incrementing load when a fetcher load lands after a completed\n  // navigation\n  let pendingNavigationLoadId = -1;\n\n  // Fetchers that triggered data reloads as a result of their actions\n  let fetchReloadIds = new Map<string, number>();\n\n  // Fetchers that triggered redirect navigations\n  let fetchRedirectIds = new Set<string>();\n\n  // Most recent href/match for fetcher.load calls for fetchers\n  let fetchLoadMatches = new Map<string, FetchLoadMatch>();\n\n  // Ref-count mounted fetchers so we know when it's ok to clean them up\n  let activeFetchers = new Map<string, number>();\n\n  // Fetchers 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<string>();\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<string, DeferredData>();\n\n  // Store blocker functions in a separate Map outside of router state since\n  // we don't need to update UI state if they change\n  let blockerFunctions = new Map<string, BlockerFunction>();\n\n  // 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<RouterState>,\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<Omit<RouterState, \"action\" | \"location\" | \"navigation\">>,\n    { flushSync }: { flushSync?: boolean } = {}\n  ): void {\n    // Deduce if we're in a loading/actionReload state:\n    // - We have committed actionData in the store\n    // - The current navigation was a mutation submission\n    // - We're past the submitting state and into the loading state\n    // - The location being loaded is not the result of a redirect\n    let isActionReload =\n      state.actionData != null &&\n      state.navigation.formMethod != null &&\n      isMutationMethod(state.navigation.formMethod) &&\n      state.navigation.state === \"loading\" &&\n      location.state?._isRedirect !== true;\n\n    let actionData: RouteData | null;\n    if (newState.actionData) {\n      if (Object.keys(newState.actionData).length > 0) {\n        actionData = newState.actionData;\n      } else {\n        // Empty actionData -> clear prior actionData due to an action error\n        actionData = null;\n      }\n    } else if (isActionReload) {\n      // Keep the current data if we're wrapping up the action reload\n      actionData = state.actionData;\n    } else {\n      // Clear actionData on any other completed navigations\n      actionData = null;\n    }\n\n    // Always preserve any existing loaderData from re-used routes\n    let loaderData = newState.loaderData\n      ? mergeLoaderData(\n          state.loaderData,\n          newState.loaderData,\n          newState.matches || [],\n          newState.errors\n        )\n      : state.loaderData;\n\n    // On a successful navigation we can assume we got through all blockers\n    // so we can start fresh\n    let blockers = state.blockers;\n    if (blockers.size > 0) {\n      blockers = new Map(blockers);\n      blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n    }\n\n    // Always respect the user flag.  Otherwise don't reset on mutation\n    // submission navigations unless they redirect\n    let preventScrollReset =\n      pendingPreventScrollReset === true ||\n      (state.navigation.formMethod != null &&\n        isMutationMethod(state.navigation.formMethod) &&\n        location.state?._isRedirect !== true);\n\n    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<string>([location.pathname]);\n        appliedViewTransitions.set(state.location.pathname, toPaths);\n      }\n      viewTransitionOpts = {\n        currentLocation: state.location,\n        nextLocation: location,\n      };\n    }\n\n    updateState(\n      {\n        ...newState, // matches, errors, fetchers go through as-is\n        actionData,\n        loaderData,\n        historyAction: pendingAction,\n        location,\n        initialized: true,\n        navigation: IDLE_NAVIGATION,\n        revalidation: \"idle\",\n        restoreScrollPosition: getSavedScrollPosition(\n          location,\n          newState.matches || state.matches\n        ),\n        preventScrollReset,\n        blockers,\n      },\n      {\n        viewTransitionOpts,\n        flushSync: flushSync === true,\n      }\n    );\n\n    // Reset stateful navigation vars\n    pendingAction = 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<void> {\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<void> {\n    // Abort any in-progress navigations and start a new one. Unset any ongoing\n    // uninterrupted revalidations unless told otherwise, since we want this\n    // new navigation to update history normally\n    pendingNavigationController && pendingNavigationController.abort();\n    pendingNavigationController = null;\n    pendingAction = historyAction;\n    isUninterruptedRevalidation =\n      (opts && opts.startUninterruptedRevalidation) === true;\n\n    // Save the current scroll position every time we start a new navigation,\n    // and track whether we should reset scroll on completion\n    saveScrollPosition(state.location, state.matches);\n    pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n    pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let loadingNavigation = opts && opts.overrideNavigation;\n    let matches = matchRoutes(routesToUse, location, basename);\n    let flushSync = (opts && opts.flushSync) === true;\n\n    // 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 <Form method=\"post\">\n    // which will default to a navigation to /page\n    if (\n      state.initialized &&\n      !isRevalidationRequired &&\n      isHashChangeOnly(state.location, location) &&\n      !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n    ) {\n      completeNavigation(location, { matches }, { flushSync });\n      return;\n    }\n\n    // Create a controller/Request for this navigation\n    pendingNavigationController = new AbortController();\n    let request = createClientSideRequest(\n      init.history,\n      location,\n      pendingNavigationController.signal,\n      opts && opts.submission\n    );\n    let pendingActionResult: PendingActionResult | undefined;\n\n    if (opts && opts.pendingError) {\n      // If we have a pendingError, it means the user attempted a GET submission\n      // with binary FormData so assign here and skip to handleLoaders.  That\n      // way we handle calling loaders above the boundary etc.  It's not really\n      // different from an actionError in that sense.\n      pendingActionResult = [\n        findNearestBoundary(matches).route.id,\n        { type: ResultType.error, error: opts.pendingError },\n      ];\n    } else if (\n      opts &&\n      opts.submission &&\n      isMutationMethod(opts.submission.formMethod)\n    ) {\n      // Call action if we received an action submission\n      let actionResult = await handleAction(\n        request,\n        location,\n        opts.submission,\n        matches,\n        { 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<HandleActionResult> {\n    interruptActiveLoads();\n\n    // Put us in a submitting state\n    let navigation = getSubmittingNavigation(location, submission);\n    updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n    // 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<HandleLoadersResult> {\n    // Figure out the right navigation we want to use for data loading\n    let loadingNavigation =\n      overrideNavigation || getLoadingNavigation(location, submission);\n\n    // If this was a redirect from an action we don't have a \"submission\" but\n    // we have it on the loading navigation so use that if available\n    let activeSubmission =\n      submission ||\n      fetcherSubmission ||\n      getSubmissionFromNavigation(loadingNavigation);\n\n    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<string, RouteData> | null | undefined;\n      if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {\n        // This is cast to `any` currently because `RouteData`uses any and it\n        // would be a breaking change to use any.\n        // TODO: v7 - change `RouteData` to use `unknown` instead of `any`\n        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<DataResult[]> {\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<DataResult>({\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<TData = any>(key: string): Fetcher<TData> {\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 <ScrollRestoration> component\n  function enableScrollRestoration(\n    positions: Record<string, number>,\n    getPosition: GetScrollPositionFunction,\n    getKey?: GetScrollRestorationKeyFunction\n  ) {\n    savedScrollPositions = positions;\n    getScrollPosition = getPosition;\n    getScrollRestorationKey = getKey || null;\n\n    // Perform initial hydration scroll restoration, since we miss the boat on\n    // the initial updateState() because we've not yet rendered <ScrollRestoration/>\n    // and therefore have no savedScrollPositions available\n    if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n      initialScrollRestored = true;\n      let y = getSavedScrollPosition(state.location, state.matches);\n      if (y != null) {\n        updateState({ restoreScrollPosition: y });\n      }\n    }\n\n    return () => {\n      savedScrollPositions = null;\n      getScrollPosition = null;\n      getScrollRestorationKey = null;\n    };\n  }\n\n  function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n    if (getScrollRestorationKey) {\n      let key = getScrollRestorationKey(\n        location,\n        matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n      );\n      return key || location.key;\n    }\n    return location.key;\n  }\n\n  function saveScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): void {\n    if (savedScrollPositions && getScrollPosition) {\n      let key = getScrollKey(location, matches);\n      savedScrollPositions[key] = getScrollPosition();\n    }\n  }\n\n  function getSavedScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): number | null {\n    if (savedScrollPositions) {\n      let key = getScrollKey(location, matches);\n      let y = savedScrollPositions[key];\n      if (typeof y === \"number\") {\n        return y;\n      }\n    }\n    return null;\n  }\n\n  function _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<StaticHandlerFutureConfig>;\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<StaticHandlerContext | Response> {\n    let url = new URL(request.url);\n    let method = request.method;\n    let location = createLocation(\"\", createPath(url), null, \"default\");\n    let matches = matchRoutes(dataRoutes, location, basename);\n\n    // SSR supports HEAD requests while SPA doesn't\n    if (!isValidMethod(method) && method !== \"HEAD\") {\n      let error = getInternalRouterError(405, { method });\n      let { matches: methodNotAllowedMatches, route } =\n        getShortCircuitMatches(dataRoutes);\n      return {\n        basename,\n        location,\n        matches: methodNotAllowedMatches,\n        loaderData: {},\n        actionData: null,\n        errors: {\n          [route.id]: error,\n        },\n        statusCode: error.status,\n        loaderHeaders: {},\n        actionHeaders: {},\n        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<any> {\n    let url = new URL(request.url);\n    let method = request.method;\n    let location = createLocation(\"\", createPath(url), null, \"default\");\n    let matches = matchRoutes(dataRoutes, location, basename);\n\n    // SSR supports HEAD requests while SPA doesn't\n    if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n      throw getInternalRouterError(405, { method });\n    } else if (!matches) {\n      throw getInternalRouterError(404, { pathname: location.pathname });\n    }\n\n    let match = routeId\n      ? matches.find((m) => m.route.id === routeId)\n      : getTargetMatch(matches, location);\n\n    if (routeId && !match) {\n      throw getInternalRouterError(403, {\n        pathname: location.pathname,\n        routeId,\n      });\n    } else if (!match) {\n      // This should never hit I don't think?\n      throw getInternalRouterError(404, { pathname: location.pathname });\n    }\n\n    let result = await queryImpl(\n      request,\n      location,\n      matches,\n      requestContext,\n      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<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n    invariant(\n      request.signal,\n      \"query()/queryRoute() requests must contain an AbortController signal\"\n    );\n\n    try {\n      if (isMutationMethod(request.method.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<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n    let result: DataResult;\n\n    if (!actionMatch.route.action && !actionMatch.route.lazy) {\n      let error = getInternalRouterError(405, {\n        method: request.method,\n        pathname: new URL(request.url).pathname,\n        routeId: actionMatch.route.id,\n      });\n      if (isRouteRequest) {\n        throw error;\n      }\n      result = {\n        type: ResultType.error,\n        error,\n      };\n    } else {\n      let results = await callDataStrategy(\n        \"action\",\n        request,\n        [actionMatch],\n        matches,\n        isRouteRequest,\n        requestContext,\n        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<string, DeferredData>();\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<string>(\n      matchesToLoad.map((match) => match.route.id)\n    );\n    matches.forEach((match) => {\n      if (!executedLoaders.has(match.route.id)) {\n        context.loaderData[match.route.id] = null;\n      }\n    });\n\n    return {\n      ...context,\n      matches,\n      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<DataResult[]> {\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<string>,\n  fetchLoadMatches: Map<string, FetchLoadMatch>,\n  fetchRedirectIds: Set<string>,\n  routesToUse: AgnosticDataRouteObject[],\n  basename: string | undefined,\n  pendingActionResult?: PendingActionResult\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n  let actionResult = pendingActionResult\n    ? isErrorResult(pendingActionResult[1])\n      ? pendingActionResult[1].error\n      : pendingActionResult[1].data\n    : undefined;\n  let currentUrl = history.createURL(state.location);\n  let nextUrl = history.createURL(location);\n\n  // Pick navigation matches that are net-new or qualify for revalidation\n  let 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<string, any> = {};\n  for (let lazyRouteProperty in lazyRoute) {\n    let staticRouteValue =\n      routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n    let isPropertyStaticallyDefined =\n      staticRouteValue !== undefined &&\n      // This property isn't static since it should always be updated based\n      // on the route updates\n      lazyRouteProperty !== \"hasErrorBoundary\";\n\n    warning(\n      !isPropertyStaticallyDefined,\n      `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n        `defined but its lazy function is also returning a value for this property. ` +\n        `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n    );\n\n    if (\n      !isPropertyStaticallyDefined &&\n      !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n    ) {\n      routeUpdates[lazyRouteProperty] =\n        lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n    }\n  }\n\n  // Mutate the route with the provided updates.  Do this first so we pass\n  // the updated version to mapRouteProperties\n  Object.assign(routeToUpdate, routeUpdates);\n\n  // Mutate the `hasErrorBoundary` property on the route based on the route\n  // updates and remove the `lazy` function so we don't resolve the lazy\n  // route again.\n  Object.assign(routeToUpdate, {\n    // To keep things framework agnostic, we use the provided\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<DataStrategyFunction> {\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<HandlerResult[]> {\n  let routeIdsToLoad = matchesToLoad.reduce(\n    (acc, m) => acc.add(m.route.id),\n    new Set<string>()\n  );\n  let loadedMatches = new Set<string>();\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<DataStrategyMatch[\"resolve\"]>[0],\n  staticContext?: unknown\n): Promise<HandlerResult> {\n  let result: HandlerResult;\n  let onReject: (() => void) | undefined;\n\n  let runHandler = (\n    handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n  ): Promise<HandlerResult> => {\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<HandlerResult> to\n    // satisfy the function return value\n    let abortPromise = new Promise<HandlerResult>((_, 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<HandlerResult>;\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<DataResult> {\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<string, DeferredData>,\n  skipLoaderErrorBubbling: boolean\n): {\n  loaderData: RouterState[\"loaderData\"];\n  errors: RouterState[\"errors\"] | null;\n  statusCode: number;\n  loaderHeaders: Record<string, Headers>;\n} {\n  // Fill in loaderData/errors from our loaders\n  let loaderData: RouterState[\"loaderData\"] = {};\n  let errors: RouterState[\"errors\"] | null = null;\n  let statusCode: number | undefined;\n  let foundError = false;\n  let loaderHeaders: Record<string, Headers> = {};\n  let pendingError =\n    pendingActionResult && isErrorResult(pendingActionResult[1])\n      ? pendingActionResult[1].error\n      : undefined;\n\n  // Process loader results into state.loaderData/state.errors\n  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<string, DeferredData>\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<SuccessResult | ErrorResult | undefined> {\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<string, Set<string>>\n) {\n  try {\n    let sessionPositions = _window.sessionStorage.getItem(\n      TRANSITIONS_STORAGE_KEY\n    );\n    if (sessionPositions) {\n      let json = JSON.parse(sessionPositions);\n      for (let [k, v] of Object.entries(json || {})) {\n        if (v && Array.isArray(v)) {\n          transitions.set(k, new Set(v || []));\n        }\n      }\n    }\n  } catch (e) {\n    // no-op, use default empty object\n  }\n}\n\nfunction persistAppliedTransitions(\n  _window: Window,\n  transitions: Map<string, Set<string>>\n) {\n  if (transitions.size > 0) {\n    let json: Record<string, string[]> = {};\n    for (let [k, v] of transitions) {\n      json[k] = [...v];\n    }\n    try {\n      _window.sessionStorage.setItem(\n        TRANSITIONS_STORAGE_KEY,\n        JSON.stringify(json)\n      );\n    } catch (error) {\n      warning(\n        false,\n        `Failed to save applied view transitions in sessionStorage (${error}).`\n      );\n    }\n  }\n}\n\n//#endregion\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AAEA;;AAEG;IACSA,MAAA;AAAZ,WAAYA,MAAM;EAChB;;;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