{"ast":null,"code":"/**\n * @remix-run/router v1.2.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/**\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\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\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 */\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\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$1(location.pathname.charAt(0) === \"/\", \"relative pathnames are not supported in memory history: \" + JSON.stringify(to));\n    return location;\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(to) {\n      return typeof to === \"string\" ? to : createPath(to);\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        });\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        });\n      }\n    },\n    go(delta) {\n      action = Action.Pop;\n      index = clampIndex(index + delta);\n      if (listener) {\n        listener({\n          action,\n          location: getCurrentLocation()\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 */\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 */\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    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$1(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$1(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); // 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 */\n\nfunction getHistoryState(location) {\n  return {\n    usr: location.state,\n    key: location.key\n  };\n}\n/**\n * Creates a Location object with a unique key from the given Path\n */\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 */\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 */\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 createClientSideURL(location) {\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 = typeof window !== \"undefined\" && typeof window.location !== \"undefined\" && window.location.origin !== \"null\" ? window.location.origin : window.location.href;\n  let href = typeof location === \"string\" ? location : createPath(location);\n  invariant(base, \"No window.location.(origin|href) available to create URL for href: \" + href);\n  return new URL(href, base);\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  function handlePop() {\n    action = Action.Pop;\n    if (listener) {\n      listener({\n        action,\n        location: history.location\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    let historyState = getHistoryState(location);\n    let url = history.createHref(location); // try...catch because iOS limits us to 100 pushState calls :/\n\n    try {\n      globalHistory.pushState(historyState, \"\", url);\n    } catch (error) {\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      });\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    let historyState = getHistoryState(location);\n    let url = history.createHref(location);\n    globalHistory.replaceState(historyState, \"\", url);\n    if (v5Compat && listener) {\n      listener({\n        action,\n        location: history.location\n      });\n    }\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    encodeLocation(to) {\n      // Encode a Location the same way window.location would\n      let url = createClientSideURL(typeof to === \"string\" ? to : createPath(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} //#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 = {}));\nfunction isIndexRoute(route) {\n  return route.index === true;\n} // Walk the route tree generating unique IDs where necessary so we are working\n// solely with AgnosticDataRouteObject's within the Router\n\nfunction convertRoutesToDataRoutes(routes, parentPath, allIds) {\n  if (parentPath === void 0) {\n    parentPath = [];\n  }\n  if (allIds === void 0) {\n    allIds = new Set();\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(!allIds.has(id), \"Found a route id collision on id \\\"\" + id + \"\\\".  Route \" + \"id's must be globally unique within Data Router usages\");\n    allIds.add(id);\n    if (isIndexRoute(route)) {\n      let indexRoute = _extends({}, route, {\n        id\n      });\n      return indexRoute;\n    } else {\n      let pathOrLayoutRoute = _extends({}, route, {\n        id,\n        children: route.children ? convertRoutesToDataRoutes(route.children, treePath, allIds) : undefined\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 */\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    matches = matchRouteBranch(branches[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    safelyDecodeURI(pathname));\n  }\n  return matches;\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); // 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\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    } // 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\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\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 */\n\nfunction explodeOptionalSegments(path) {\n  let segments = path.split(\"/\");\n  if (segments.length === 0) return [];\n  let [first, ...rest] = segments; // Optional path segments are denoted by a trailing `?`\n\n  let isOptional = first.endsWith(\"?\"); // Compute the corresponding required segment: `foo?` -> `foo`\n\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 = []; // 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 explodes _earlier_\n  // then /:one.  By always including the parent as required _for all children_\n  // first, we avoid this issue\n\n  result.push(...restExploded.map(subpath => subpath === \"\" ? required : [required, subpath].join(\"/\"))); // Then if this is an optional value, add all child versions without\n\n  if (isOptional) {\n    result.push(...restExploded);\n  } // for absolute paths, ensure `/` instead of empty segment\n\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 */\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  return path.replace(/^:(\\w+)/g, (_, key) => {\n    invariant(params[key] != null, \"Missing \\\":\" + key + \"\\\" param\");\n    return params[key];\n  }).replace(/\\/:(\\w+)/g, (_, key) => {\n    invariant(params[key] != null, \"Missing \\\":\" + key + \"\\\" param\");\n    return \"/\" + params[key];\n  }).replace(/(\\/?)\\*/, (_, prefix, __, str) => {\n    const star = \"*\";\n    if (params[star] == null) {\n      // If no splat was provided, trim the trailing slash _unless_ it's\n      // the entire path\n      return str === \"/*\" ? \"/\" : \"\";\n    } // Apply the splat\n\n    return \"\" + prefix + params[star];\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 */\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, paramNames] = 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 = paramNames.reduce((memo, paramName, 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.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\\/+$/, \"$1\");\n    }\n    memo[paramName] = safelyDecodeURIComponent(captureGroups[index] || \"\", paramName);\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 paramNames = [];\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) => {\n    paramNames.push(paramName);\n    return \"/([^\\\\/]+)\";\n  });\n  if (path.endsWith(\"*\")) {\n    paramNames.push(\"*\");\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, paramNames];\n}\nfunction safelyDecodeURI(value) {\n  try {\n    return decodeURI(value);\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}\nfunction safelyDecodeURIComponent(value, paramName) {\n  try {\n    return decodeURIComponent(value);\n  } catch (error) {\n    warning(false, \"The value for the URL param \\\"\" + paramName + \"\\\" will not be decoded because\" + (\" the string \\\"\" + value + \"\\\" is a malformed URL segment. This is probably\") + (\" due to a bad percent encoding (\" + error + \").\"));\n    return value;\n  }\n}\n/**\n * @private\n */\n\nfunction stripBasename(pathname, basename) {\n  if (basename === \"/\") return pathname;\n  if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n    return null;\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\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 * @private\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 React Router!\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); // eslint-disable-next-line no-empty\n    } catch (e) {}\n  }\n}\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/utils/resolve-path\n */\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 */\n\nfunction getPathContributingMatches(matches) {\n  return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);\n}\n/**\n * @private\n */\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; // 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\n  if (isPathRelative || toPathname == null) {\n    from = locationPathname;\n  } else {\n    let routePathnameIndex = routePathnames.length - 1;\n    if (toPathname.startsWith(\"..\")) {\n      let toSegments = toPathname.split(\"/\"); // Each leading .. segment means \"go up one route\" instead of \"go up one\n      // URL segment\".  This is a key difference from how <a href> works and a\n      // major reason we call this a \"to\" value instead of a \"href\".\n\n      while (toSegments[0] === \"..\") {\n        toSegments.shift();\n        routePathnameIndex -= 1;\n      }\n      to.pathname = toSegments.join(\"/\");\n    } // If there are more \"..\" segments than parent routes, resolve relative to\n    // the root / URL.\n\n    from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n  }\n  let path = resolvePath(to, from); // Ensure the pathname has a trailing slash if the original \"to\" had one\n\n  let hasExplicitTrailingSlash = toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\"); // Or if this was a link to the current path which has a trailing slash\n\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 */\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 */\n\nconst joinPaths = paths => paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n/**\n * @private\n */\n\nconst normalizePathname = pathname => pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n/**\n * @private\n */\n\nconst normalizeSearch = search => !search || search === \"?\" ? \"\" : search.startsWith(\"?\") ? search : \"?\" + search;\n/**\n * @private\n */\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 */\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) {\n    this.pendingKeys = new Set();\n    this.subscriber = undefined;\n    invariant(data && typeof data === \"object\" && !Array.isArray(data), \"defer() only accepts plain objects\"); // Set up an AbortController + Promise we can race against to exit early\n    // cancellation\n\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, _ref) => {\n      let [key, value] = _ref;\n      return Object.assign(acc, {\n        [key]: this.trackPromise(key, value)\n      });\n    }, {});\n  }\n  trackPromise(key, value) {\n    if (!(value instanceof Promise)) {\n      return value;\n    }\n    this.pendingKeys.add(key); // We store a little wrapper promise that will be extended with\n    // _data/_error props upon resolve/reject\n\n    let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, null, data), error => this.onSettle(promise, key, error)); // Register rejection listeners to avoid uncaught promise rejections on\n    // errors or aborted deferred values\n\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.pendingKeys.delete(key);\n    if (this.done) {\n      // Nothing left to abort!\n      this.unlistenAbortSignal();\n    }\n    const subscriber = this.subscriber;\n    if (error) {\n      Object.defineProperty(promise, \"_error\", {\n        get: () => error\n      });\n      subscriber && subscriber(false);\n      return Promise.reject(error);\n    }\n    Object.defineProperty(promise, \"_data\", {\n      get: () => data\n    });\n    subscriber && subscriber(false);\n    return data;\n  }\n  subscribe(fn) {\n    this.subscriber = fn;\n  }\n  cancel() {\n    this.controller.abort();\n    this.pendingKeys.forEach((v, k) => this.pendingKeys.delete(k));\n    let subscriber = this.subscriber;\n    subscriber && subscriber(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.pendingKeys.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, _ref2) => {\n      let [key, value] = _ref2;\n      return Object.assign(acc, {\n        [key]: unwrapTrackedPromise(value)\n      });\n    }, {});\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}\nfunction defer(data) {\n  return new DeferredData(data);\n}\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\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 * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n */\n\nclass ErrorResponse {\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 throw from an action/loader\n */\n\nfunction isRouteErrorResponse(e) {\n  return e instanceof ErrorResponse;\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};\nconst IDLE_FETCHER = {\n  state: \"idle\",\n  data: undefined,\n  formMethod: undefined,\n  formAction: undefined,\n  formEncType: undefined,\n  formData: undefined\n};\nconst isBrowser = typeof window !== \"undefined\" && typeof window.document !== \"undefined\" && typeof window.document.createElement !== \"undefined\";\nconst isServer = !isBrowser; //#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\n\nfunction createRouter(init) {\n  invariant(init.routes.length > 0, \"You must provide a non-empty routes array to createRouter\");\n  let dataRoutes = convertRoutesToDataRoutes(init.routes); // Cleanup function for history\n\n  let unlistenHistory = null; // Externally-provided functions to call on all state changes\n\n  let subscribers = new Set(); // Externally-provided object to hold scroll restoration locations during routing\n\n  let savedScrollPositions = null; // Externally-provided function to get scroll restoration keys\n\n  let getScrollRestorationKey = null; // Externally-provided function to get current scroll position\n\n  let getScrollPosition = null; // 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\n  let initialScrollRestored = init.hydrationData != null;\n  let initialMatches = matchRoutes(dataRoutes, init.history.location, init.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 = !initialMatches.some(m => m.route.loader) || init.hydrationData != null;\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  }; // -- Stateful internal variables to manage navigations --\n  // Current navigation in progress (to be committed in completeNavigation)\n\n  let pendingAction = Action.Pop; // Should the current navigation prevent the scroll reset if scroll cannot\n  // be restored?\n\n  let pendingPreventScrollReset = false; // AbortController for the active navigation\n\n  let pendingNavigationController; // We use this to avoid touching history in completeNavigation if a\n  // revalidation is entirely uninterrupted\n\n  let isUninterruptedRevalidation = false; // Use this internal flag to force revalidation of all loaders:\n  //  - submissions (completed or interrupted)\n  //  - useRevalidate()\n  //  - X-Remix-Revalidate (from redirect)\n\n  let isRevalidationRequired = false; // Use this internal array to capture routes that require revalidation due\n  // to a cancelled deferred on action submission\n\n  let cancelledDeferredRoutes = []; // Use this internal array to capture fetcher loads that were cancelled by an\n  // action navigation and require revalidation\n\n  let cancelledFetcherLoads = []; // AbortControllers for any in-flight fetchers\n\n  let fetchControllers = new Map(); // Track loads based on the order in which they started\n\n  let incrementingLoadId = 0; // 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\n  let pendingNavigationLoadId = -1; // Fetchers that triggered data reloads as a result of their actions\n\n  let fetchReloadIds = new Map(); // Fetchers that triggered redirect navigations from their actions\n\n  let fetchRedirectIds = new Set(); // Most recent href/match for fetcher.load calls for fetchers\n\n  let fetchLoadMatches = new Map(); // 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\n  let activeDeferreds = new Map(); // 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\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      } = _ref;\n      return startNavigation(historyAction, location);\n    }); // Kick off initial data load if needed.  Use Pop to avoid modifying history\n\n    if (!state.initialized) {\n      startNavigation(Action.Pop, state.location);\n    }\n    return router;\n  } // Clean up a router and it's side effects\n\n  function dispose() {\n    if (unlistenHistory) {\n      unlistenHistory();\n    }\n    subscribers.clear();\n    pendingNavigationController && pendingNavigationController.abort();\n    state.fetchers.forEach((_, key) => deleteFetcher(key));\n  } // Subscribe to state updates for the router\n\n  function subscribe(fn) {\n    subscribers.add(fn);\n    return () => subscribers.delete(fn);\n  } // Update our state and notify the calling context of the change\n\n  function updateState(newState) {\n    state = _extends({}, state, newState);\n    subscribers.forEach(subscriber => subscriber(state));\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\n  function completeNavigation(location, newState) {\n    var _location$state;\n\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    } // Always preserve any existing loaderData from re-used routes\n\n    let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;\n    updateState(_extends({}, newState, {\n      actionData,\n      loaderData,\n      historyAction: pendingAction,\n      location,\n      initialized: true,\n      navigation: IDLE_NAVIGATION,\n      revalidation: \"idle\",\n      // Don't restore on submission navigations\n      restoreScrollPosition: state.navigation.formData ? false : getSavedScrollPosition(location, newState.matches || state.matches),\n      preventScrollReset: pendingPreventScrollReset\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    } // Reset stateful navigation vars\n\n    pendingAction = Action.Pop;\n    pendingPreventScrollReset = false;\n    isUninterruptedRevalidation = false;\n    isRevalidationRequired = false;\n    cancelledDeferredRoutes = [];\n    cancelledFetcherLoads = [];\n  } // Trigger a navigation event, which can either be a numerical POP or a PUSH\n  // replace with an optional submission\n\n  async function navigate(to, opts) {\n    if (typeof to === \"number\") {\n      init.history.go(to);\n      return;\n    }\n    let {\n      path,\n      submission,\n      error\n    } = normalizeNavigateOptions(to, opts);\n    let location = createLocation(state.location, path, opts && opts.state); // 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\n    location = _extends({}, location, init.history.encodeLocation(location));\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    return await startNavigation(historyAction, location, {\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    });\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\n  function revalidate() {\n    interruptActiveLoads();\n    updateState({\n      revalidation: \"loading\"\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\n    if (state.navigation.state === \"submitting\") {\n      return;\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\n    if (state.navigation.state === \"idle\") {\n      startNavigation(state.historyAction, state.location, {\n        startUninterruptedRevalidation: true\n      });\n      return;\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\n    startNavigation(pendingAction || state.historyAction, state.navigation.location, {\n      overrideNavigation: state.navigation\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\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; // Save the current scroll position every time we start a new navigation,\n    // and track whether we should reset scroll on completion\n\n    saveScrollPosition(state.location, state.matches);\n    pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n    let loadingNavigation = opts && opts.overrideNavigation;\n    let matches = matchRoutes(dataRoutes, location, init.basename); // Short circuit with a 404 on the root error boundary if we match nothing\n\n    if (!matches) {\n      let error = getInternalRouterError(404, {\n        pathname: location.pathname\n      });\n      let {\n        matches: notFoundMatches,\n        route\n      } = getShortCircuitMatches(dataRoutes); // Cancel all pending deferred on 404s since we don't keep any routes\n\n      cancelActiveDeferreds();\n      completeNavigation(location, {\n        matches: notFoundMatches,\n        loaderData: {},\n        errors: {\n          [route.id]: error\n        }\n      });\n      return;\n    } // Short circuit if it's only a hash change\n\n    if (isHashChangeOnly(state.location, location)) {\n      completeNavigation(location, {\n        matches\n      });\n      return;\n    } // Create a controller/Request for this navigation\n\n    pendingNavigationController = new AbortController();\n    let request = createClientSideRequest(location, pendingNavigationController.signal, opts && opts.submission);\n    let pendingActionData;\n    let pendingError;\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      pendingError = {\n        [findNearestBoundary(matches).route.id]: opts.pendingError\n      };\n    } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {\n      // Call action if we received an action submission\n      let actionOutput = await handleAction(request, location, opts.submission, matches, {\n        replace: opts.replace\n      });\n      if (actionOutput.shortCircuited) {\n        return;\n      }\n      pendingActionData = actionOutput.pendingActionData;\n      pendingError = actionOutput.pendingActionError;\n      let navigation = _extends({\n        state: \"loading\",\n        location\n      }, opts.submission);\n      loadingNavigation = navigation; // Create a GET request for the loaders\n\n      request = new Request(request.url, {\n        signal: request.signal\n      });\n    } // Call loaders\n\n    let {\n      shortCircuited,\n      loaderData,\n      errors\n    } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.replace, pendingActionData, pendingError);\n    if (shortCircuited) {\n      return;\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\n    pendingNavigationController = null;\n    completeNavigation(location, _extends({\n      matches\n    }, pendingActionData ? {\n      actionData: pendingActionData\n    } : {}, {\n      loaderData,\n      errors\n    }));\n  } // Call the action matched by the leaf route for this navigation and handle\n  // redirects/errors\n\n  async function handleAction(request, location, submission, matches, opts) {\n    interruptActiveLoads(); // Put us in a submitting state\n\n    let navigation = _extends({\n      state: \"submitting\",\n      location\n    }, submission);\n    updateState({\n      navigation\n    }); // Call our action and get the result\n\n    let result;\n    let actionMatch = getTargetMatch(matches, location);\n    if (!actionMatch.route.action) {\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      result = await callLoaderOrAction(\"action\", request, actionMatch, matches, router.basename);\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        replace = result.location === state.location.pathname + state.location.search;\n      }\n      await startRedirectNavigation(state, result, {\n        submission,\n        replace\n      });\n      return {\n        shortCircuited: true\n      };\n    }\n    if (isErrorResult(result)) {\n      // Store off the pending error - we use it to determine which loaders\n      // to call and will commit it when we complete the navigation\n      let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); // 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\n      if ((opts && opts.replace) !== true) {\n        pendingAction = Action.Push;\n      }\n      return {\n        // Send back an empty object we can use to clear out any prior actionData\n        pendingActionData: {},\n        pendingActionError: {\n          [boundaryMatch.route.id]: result.error\n        }\n      };\n    }\n    if (isDeferredResult(result)) {\n      throw new Error(\"defer() is not supported in actions\");\n    }\n    return {\n      pendingActionData: {\n        [actionMatch.route.id]: result.data\n      }\n    };\n  } // Call all applicable loaders for the given matches, handling redirects,\n  // errors, etc.\n\n  async function handleLoaders(request, location, matches, overrideNavigation, submission, replace, pendingActionData, pendingError) {\n    // Figure out the right navigation we want to use for data loading\n    let loadingNavigation = overrideNavigation;\n    if (!loadingNavigation) {\n      let navigation = _extends({\n        state: \"loading\",\n        location,\n        formMethod: undefined,\n        formAction: undefined,\n        formEncType: undefined,\n        formData: undefined\n      }, submission);\n      loadingNavigation = navigation;\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\n    let activeSubmission = submission ? submission : loadingNavigation.formMethod && loadingNavigation.formAction && loadingNavigation.formData && loadingNavigation.formEncType ? {\n      formMethod: loadingNavigation.formMethod,\n      formAction: loadingNavigation.formAction,\n      formData: loadingNavigation.formData,\n      formEncType: loadingNavigation.formEncType\n    } : undefined;\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(state, matches, activeSubmission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches); // 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\n    cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId)); // Short circuit if we have no loaders to run\n\n    if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n      completeNavigation(location, _extends({\n        matches,\n        loaderData: {},\n        // Commit pending error if we're short circuiting\n        errors: pendingError || null\n      }, pendingActionData ? {\n        actionData: pendingActionData\n      } : {}));\n      return {\n        shortCircuited: true\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\n    if (!isUninterruptedRevalidation) {\n      revalidatingFetchers.forEach(_ref2 => {\n        let [key] = _ref2;\n        let fetcher = state.fetchers.get(key);\n        let revalidatingFetcher = {\n          state: \"loading\",\n          data: fetcher && fetcher.data,\n          formMethod: undefined,\n          formAction: undefined,\n          formEncType: undefined,\n          formData: undefined,\n          \" _hasFetcherDoneAnything \": true\n        };\n        state.fetchers.set(key, revalidatingFetcher);\n      });\n      let actionData = pendingActionData || state.actionData;\n      updateState(_extends({\n        navigation: loadingNavigation\n      }, actionData ? Object.keys(actionData).length === 0 ? {\n        actionData: null\n      } : {\n        actionData\n      } : {}, revalidatingFetchers.length > 0 ? {\n        fetchers: new Map(state.fetchers)\n      } : {}));\n    }\n    pendingNavigationLoadId = ++incrementingLoadId;\n    revalidatingFetchers.forEach(_ref3 => {\n      let [key] = _ref3;\n      return fetchControllers.set(key, pendingNavigationController);\n    });\n    let {\n      results,\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    } // 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\n    revalidatingFetchers.forEach(_ref4 => {\n      let [key] = _ref4;\n      return fetchControllers.delete(key);\n    }); // If any loaders returned a redirect Response, start a new REPLACE navigation\n\n    let redirect = findRedirect(results);\n    if (redirect) {\n      await startRedirectNavigation(state, redirect, {\n        replace\n      });\n      return {\n        shortCircuited: true\n      };\n    } // Process and commit output from loaders\n\n    let {\n      loaderData,\n      errors\n    } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds); // Wire up subscribers to update loaderData as promises settle\n\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    markFetchRedirectsDone();\n    let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n    return _extends({\n      loaderData,\n      errors\n    }, didAbortFetchLoads || revalidatingFetchers.length > 0 ? {\n      fetchers: new Map(state.fetchers)\n    } : {});\n  }\n  function getFetcher(key) {\n    return state.fetchers.get(key) || IDLE_FETCHER;\n  } // Trigger a fetcher load/submit for the given fetcher key\n\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 matches = matchRoutes(dataRoutes, href, init.basename);\n    if (!matches) {\n      setFetcherError(key, routeId, getInternalRouterError(404, {\n        pathname: href\n      }));\n      return;\n    }\n    let {\n      path,\n      submission\n    } = normalizeNavigateOptions(href, opts, true);\n    let match = getTargetMatch(matches, path);\n    if (submission && isMutationMethod(submission.formMethod)) {\n      handleFetcherAction(key, routeId, path, match, matches, submission);\n      return;\n    } // Store off the match so we can call it's shouldRevalidate on subsequent\n    // revalidations\n\n    fetchLoadMatches.set(key, [path, match, matches]);\n    handleFetcherLoader(key, routeId, path, match, matches, submission);\n  } // Call the action for the matched fetcher.submit(), and then handle redirects,\n  // errors, and revalidation\n\n  async function handleFetcherAction(key, routeId, path, match, requestMatches, submission) {\n    interruptActiveLoads();\n    fetchLoadMatches.delete(key);\n    if (!match.route.action) {\n      let error = getInternalRouterError(405, {\n        method: submission.formMethod,\n        pathname: path,\n        routeId: routeId\n      });\n      setFetcherError(key, routeId, error);\n      return;\n    } // Put this fetcher into it's submitting state\n\n    let existingFetcher = state.fetchers.get(key);\n    let fetcher = _extends({\n      state: \"submitting\"\n    }, submission, {\n      data: existingFetcher && existingFetcher.data,\n      \" _hasFetcherDoneAnything \": true\n    });\n    state.fetchers.set(key, fetcher);\n    updateState({\n      fetchers: new Map(state.fetchers)\n    }); // Call the action for the fetcher\n\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(path, abortController.signal, submission);\n    fetchControllers.set(key, abortController);\n    let actionResult = await callLoaderOrAction(\"action\", fetchRequest, match, requestMatches, router.basename);\n    if (fetchRequest.signal.aborted) {\n      // We can delete this so long as we weren't aborted by ou 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    if (isRedirectResult(actionResult)) {\n      fetchControllers.delete(key);\n      fetchRedirectIds.add(key);\n      let loadingFetcher = _extends({\n        state: \"loading\"\n      }, submission, {\n        data: undefined,\n        \" _hasFetcherDoneAnything \": true\n      });\n      state.fetchers.set(key, loadingFetcher);\n      updateState({\n        fetchers: new Map(state.fetchers)\n      });\n      return startRedirectNavigation(state, actionResult, {\n        isFetchActionRedirect: true\n      });\n    } // Process any non-redirect errors thrown\n\n    if (isErrorResult(actionResult)) {\n      setFetcherError(key, routeId, actionResult.error);\n      return;\n    }\n    if (isDeferredResult(actionResult)) {\n      invariant(false, \"defer() is not supported in actions\");\n    } // Start the data load for current matches, or the next location if we're\n    // in the middle of a navigation\n\n    let nextLocation = state.navigation.location || state.location;\n    let revalidationRequest = createClientSideRequest(nextLocation, abortController.signal);\n    let matches = state.navigation.state !== \"idle\" ? matchRoutes(dataRoutes, state.navigation.location, init.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 = _extends({\n      state: \"loading\",\n      data: actionResult.data\n    }, submission, {\n      \" _hasFetcherDoneAnything \": true\n    });\n    state.fetchers.set(key, loadFetcher);\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(state, matches, submission, nextLocation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, {\n      [match.route.id]: actionResult.data\n    }, undefined,\n    // No need to send through errors since we short circuit above\n    fetchLoadMatches); // 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\n    revalidatingFetchers.filter(_ref5 => {\n      let [staleKey] = _ref5;\n      return staleKey !== key;\n    }).forEach(_ref6 => {\n      let [staleKey] = _ref6;\n      let existingFetcher = state.fetchers.get(staleKey);\n      let revalidatingFetcher = {\n        state: \"loading\",\n        data: existingFetcher && existingFetcher.data,\n        formMethod: undefined,\n        formAction: undefined,\n        formEncType: undefined,\n        formData: undefined,\n        \" _hasFetcherDoneAnything \": true\n      };\n      state.fetchers.set(staleKey, revalidatingFetcher);\n      fetchControllers.set(staleKey, abortController);\n    });\n    updateState({\n      fetchers: new Map(state.fetchers)\n    });\n    let {\n      results,\n      loaderResults,\n      fetcherResults\n    } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);\n    if (abortController.signal.aborted) {\n      return;\n    }\n    fetchReloadIds.delete(key);\n    fetchControllers.delete(key);\n    revalidatingFetchers.forEach(_ref7 => {\n      let [staleKey] = _ref7;\n      return fetchControllers.delete(staleKey);\n    });\n    let redirect = findRedirect(results);\n    if (redirect) {\n      return startRedirectNavigation(state, redirect);\n    } // Process and commit output from loaders\n\n    let {\n      loaderData,\n      errors\n    } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);\n    let doneFetcher = {\n      state: \"idle\",\n      data: actionResult.data,\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      \" _hasFetcherDoneAnything \": true\n    };\n    state.fetchers.set(key, doneFetcher);\n    let didAbortFetchLoads = abortStaleFetchLoads(loadId); // 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\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(_extends({\n        errors,\n        loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors)\n      }, didAbortFetchLoads ? {\n        fetchers: new Map(state.fetchers)\n      } : {}));\n      isRevalidationRequired = false;\n    }\n  } // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n\n  async function handleFetcherLoader(key, routeId, path, match, matches, submission) {\n    let existingFetcher = state.fetchers.get(key); // Put this fetcher into it's loading state\n\n    let loadingFetcher = _extends({\n      state: \"loading\",\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined\n    }, submission, {\n      data: existingFetcher && existingFetcher.data,\n      \" _hasFetcherDoneAnything \": true\n    });\n    state.fetchers.set(key, loadingFetcher);\n    updateState({\n      fetchers: new Map(state.fetchers)\n    }); // Call the loader for this fetcher route match\n\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(path, abortController.signal);\n    fetchControllers.set(key, abortController);\n    let result = await callLoaderOrAction(\"loader\", fetchRequest, match, matches, router.basename); // Deferred isn't supported or 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\n    if (isDeferredResult(result)) {\n      result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;\n    } // We can delete this so long as we weren't aborted by ou our own fetcher\n    // re-load which would have put _new_ controller is in fetchControllers\n\n    if (fetchControllers.get(key) === abortController) {\n      fetchControllers.delete(key);\n    }\n    if (fetchRequest.signal.aborted) {\n      return;\n    } // If the loader threw a redirect Response, start a new REPLACE navigation\n\n    if (isRedirectResult(result)) {\n      await startRedirectNavigation(state, result);\n      return;\n    } // Process any non-redirect errors thrown\n\n    if (isErrorResult(result)) {\n      let boundaryMatch = findNearestBoundary(state.matches, routeId);\n      state.fetchers.delete(key); // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch -\n      // do we need to behave any differently with our non-redirect errors?\n      // What if it was a non-redirect Response?\n\n      updateState({\n        fetchers: new Map(state.fetchers),\n        errors: {\n          [boundaryMatch.route.id]: result.error\n        }\n      });\n      return;\n    }\n    invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\"); // Put the fetcher back into an idle state\n\n    let doneFetcher = {\n      state: \"idle\",\n      data: result.data,\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      \" _hasFetcherDoneAnything \": true\n    };\n    state.fetchers.set(key, doneFetcher);\n    updateState({\n      fetchers: new Map(state.fetchers)\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\n  async function startRedirectNavigation(state, redirect, _temp) {\n    var _window;\n    let {\n      submission,\n      replace,\n      isFetchActionRedirect\n    } = _temp === void 0 ? {} : _temp;\n    if (redirect.revalidate) {\n      isRevalidationRequired = true;\n    }\n    let redirectLocation = createLocation(state.location, redirect.location,\n    // TODO: This can be removed once we get rid of useTransition in Remix v2\n    _extends({\n      _isRedirect: true\n    }, isFetchActionRedirect ? {\n      _isFetchActionRedirect: true\n    } : {}));\n    invariant(redirectLocation, \"Expected a location on the redirect navigation\"); // Check if this an external redirect that goes to a new origin\n\n    if (typeof ((_window = window) == null ? void 0 : _window.location) !== \"undefined\") {\n      let newOrigin = createClientSideURL(redirect.location).origin;\n      if (window.location.origin !== newOrigin) {\n        if (replace) {\n          window.location.replace(redirect.location);\n        } else {\n          window.location.assign(redirect.location);\n        }\n        return;\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\n    pendingNavigationController = null;\n    let redirectHistoryAction = replace === true ? Action.Replace : Action.Push; // Use the incoming submission if provided, fallback on the active one in\n    // state.navigation\n\n    let {\n      formMethod,\n      formAction,\n      formEncType,\n      formData\n    } = state.navigation;\n    if (!submission && formMethod && formAction && formData && formEncType) {\n      submission = {\n        formMethod,\n        formAction,\n        formEncType,\n        formData\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\n    if (redirectPreserveMethodStatusCodes.has(redirect.status) && submission && isMutationMethod(submission.formMethod)) {\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        submission: _extends({}, submission, {\n          formAction: redirect.location\n        })\n      });\n    } else {\n      // Otherwise, we kick off a new loading navigation, preserving the\n      // submission info for the duration of this navigation\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        overrideNavigation: {\n          state: \"loading\",\n          location: redirectLocation,\n          formMethod: submission ? submission.formMethod : undefined,\n          formAction: submission ? submission.formAction : undefined,\n          formEncType: submission ? submission.formEncType : undefined,\n          formData: submission ? submission.formData : undefined\n        }\n      });\n    }\n  }\n  async function callLoadersAndMaybeResolveData(currentMatches, matches, matchesToLoad, fetchersToLoad, request) {\n    // Call all navigation loaders and revalidating fetcher loaders in parallel,\n    // then slice off the results into separate arrays so we can handle them\n    // accordingly\n    let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction(\"loader\", request, match, matches, router.basename)), ...fetchersToLoad.map(_ref8 => {\n      let [, href, match, fetchMatches] = _ref8;\n      return callLoaderOrAction(\"loader\", createClientSideRequest(href, request.signal), match, fetchMatches, router.basename);\n    })]);\n    let loaderResults = results.slice(0, matchesToLoad.length);\n    let fetcherResults = results.slice(matchesToLoad.length);\n    await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, request.signal, false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(_ref9 => {\n      let [,, match] = _ref9;\n      return match;\n    }), fetcherResults, request.signal, true)]);\n    return {\n      results,\n      loaderResults,\n      fetcherResults\n    };\n  }\n  function interruptActiveLoads() {\n    // Every interruption triggers a revalidation\n    isRevalidationRequired = true; // Cancel pending route-level deferreds and mark cancelled routes for\n    // revalidation\n\n    cancelledDeferredRoutes.push(...cancelActiveDeferreds()); // Abort in-flight fetcher loads\n\n    fetchLoadMatches.forEach((_, key) => {\n      if (fetchControllers.has(key)) {\n        cancelledFetcherLoads.push(key);\n        abortFetcher(key);\n      }\n    });\n  }\n  function setFetcherError(key, routeId, error) {\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  }\n  function deleteFetcher(key) {\n    if (fetchControllers.has(key)) abortFetcher(key);\n    fetchLoadMatches.delete(key);\n    fetchReloadIds.delete(key);\n    fetchRedirectIds.delete(key);\n    state.fetchers.delete(key);\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 = {\n        state: \"idle\",\n        data: fetcher.data,\n        formMethod: undefined,\n        formAction: undefined,\n        formEncType: undefined,\n        formData: undefined,\n        \" _hasFetcherDoneAnything \": true\n      };\n      state.fetchers.set(key, doneFetcher);\n    }\n  }\n  function markFetchRedirectsDone() {\n    let doneKeys = [];\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      }\n    }\n    markFetchersDone(doneKeys);\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 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  } // Opt in to capturing and reporting scroll positions during navigations,\n  // used by the <ScrollRestoration> component\n\n  function enableScrollRestoration(positions, getPosition, getKey) {\n    savedScrollPositions = positions;\n    getScrollPosition = getPosition;\n    getScrollRestorationKey = getKey || (location => location.key); // 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\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 saveScrollPosition(location, matches) {\n    if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n      let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData));\n      let key = getScrollRestorationKey(location, userMatches) || location.key;\n      savedScrollPositions[key] = getScrollPosition();\n    }\n  }\n  function getSavedScrollPosition(location, matches) {\n    if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n      let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData));\n      let key = getScrollRestorationKey(location, userMatches) || location.key;\n      let y = savedScrollPositions[key];\n      if (typeof y === \"number\") {\n        return y;\n      }\n    }\n    return null;\n  }\n  router = {\n    get basename() {\n      return init.basename;\n    },\n    get state() {\n      return state;\n    },\n    get routes() {\n      return dataRoutes;\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,\n    dispose,\n    _internalFetchControllers: fetchControllers,\n    _internalActiveDeferreds: activeDeferreds\n  };\n  return router;\n} //#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nfunction createStaticHandler(routes, opts) {\n  invariant(routes.length > 0, \"You must provide a non-empty routes array to createStaticHandler\");\n  let dataRoutes = convertRoutesToDataRoutes(routes);\n  let basename = (opts ? opts.basename : null) || \"/\";\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\n  async function query(request, _temp2) {\n    let {\n      requestContext\n    } = _temp2 === void 0 ? {} : _temp2;\n    let url = new URL(request.url);\n    let method = request.method.toLowerCase();\n    let location = createLocation(\"\", createPath(url), null, \"default\");\n    let matches = matchRoutes(dataRoutes, location, basename); // SSR supports HEAD requests while SPA doesn't\n\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      };\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      };\n    }\n    let result = await queryImpl(request, location, matches, requestContext);\n    if (isResponse(result)) {\n      return result;\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\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\n  async function queryRoute(request, _temp3) {\n    let {\n      routeId,\n      requestContext\n    } = _temp3 === void 0 ? {} : _temp3;\n    let url = new URL(request.url);\n    let method = request.method.toLowerCase();\n    let location = createLocation(\"\", createPath(url), null, \"default\");\n    let matches = matchRoutes(dataRoutes, location, basename); // SSR supports HEAD requests while SPA doesn't\n\n    if (!isValidMethod(method) && method !== \"head\") {\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, 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    } // Pick off the right state value to return\n\n    let routeData = [result.actionData, result.loaderData].find(v => v);\n    return Object.values(routeData || {})[0];\n  }\n  async function queryImpl(request, location, matches, requestContext, 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, routeMatch != null);\n        return result;\n      }\n      let result = await loadRouteData(request, matches, requestContext, 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, we throw\n      // it to bail out and then return or throw here based on whether the user\n      // returned or threw\n      if (isQueryRouteResponse(e)) {\n        if (e.type === ResultType.error && !isRedirectResponse(e.response)) {\n          throw e.response;\n        }\n        return e.response;\n      } // Redirects are always returned since they don't propagate to catch\n      // boundaries\n\n      if (isRedirectResponse(e)) {\n        return e;\n      }\n      throw e;\n    }\n  }\n  async function submit(request, matches, actionMatch, requestContext, isRouteRequest) {\n    let result;\n    if (!actionMatch.route.action) {\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      result = await callLoaderOrAction(\"action\", request, actionMatch, matches, basename, true, isRouteRequest, requestContext);\n      if (request.signal.aborted) {\n        let method = isRouteRequest ? \"queryRoute\" : \"query\";\n        throw new Error(method + \"() call aborted\");\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.status,\n        headers: {\n          Location: result.location\n        }\n      });\n    }\n    if (isDeferredResult(result)) {\n      throw new Error(\"defer() is not supported in actions\");\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      };\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      let context = await loadRouteData(request, matches, requestContext, undefined, {\n        [boundaryMatch.route.id]: result.error\n      }); // action status codes take precedence over loader status codes\n\n      return _extends({}, context, {\n        statusCode: isRouteErrorResponse(result.error) ? result.error.status : 500,\n        actionData: null,\n        actionHeaders: _extends({}, result.headers ? {\n          [actionMatch.route.id]: result.headers\n        } : {})\n      });\n    } // Create a GET request for the loaders\n\n    let loaderRequest = new Request(request.url, {\n      headers: request.headers,\n      redirect: request.redirect,\n      signal: request.signal\n    });\n    let context = await loadRouteData(loaderRequest, matches, requestContext);\n    return _extends({}, context, result.statusCode ? {\n      statusCode: result.statusCode\n    } : {}, {\n      actionData: {\n        [actionMatch.route.id]: result.data\n      },\n      actionHeaders: _extends({}, result.headers ? {\n        [actionMatch.route.id]: result.headers\n      } : {})\n    });\n  }\n  async function loadRouteData(request, matches, requestContext, routeMatch, pendingActionError) {\n    let isRouteRequest = routeMatch != null; // Short circuit if we have no loaders to run (queryRoute())\n\n    if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader)) {\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] : getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]);\n    let matchesToLoad = requestMatches.filter(m => m.route.loader); // Short circuit if we have no loaders to run (query())\n\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: pendingActionError || null,\n        statusCode: 200,\n        loaderHeaders: {}\n      };\n    }\n    let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction(\"loader\", request, match, matches, basename, true, isRouteRequest, requestContext))]);\n    if (request.signal.aborted) {\n      let method = isRouteRequest ? \"queryRoute\" : \"query\";\n      throw new Error(method + \"() call aborted\");\n    }\n    let executedLoaders = new Set();\n    results.forEach((result, i) => {\n      executedLoaders.add(matchesToLoad[i].route.id); // Can't do anything with these without the Remix side of things, so just\n      // cancel them for now\n\n      if (isDeferredResult(result)) {\n        result.deferredData.cancel();\n      }\n    }); // Process and commit output from loaders\n\n    let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionError); // Add a null for any non-loader matches for proper revalidation on the client\n\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    });\n  }\n  return {\n    dataRoutes,\n    query,\n    queryRoute\n  };\n} //#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\n\nfunction getStaticContextFromError(routes, context, error) {\n  let newContext = _extends({}, context, {\n    statusCode: 500,\n    errors: {\n      [context._deepestRenderedBoundaryId || routes[0].id]: error\n    }\n  });\n  return newContext;\n}\nfunction isSubmissionNavigation(opts) {\n  return opts != null && \"formData\" in opts;\n} // Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\n\nfunction normalizeNavigateOptions(to, opts, isFetcher) {\n  if (isFetcher === void 0) {\n    isFetcher = false;\n  }\n  let path = typeof to === \"string\" ? to : createPath(to); // Return location verbatim on non-submission navigations\n\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  } // Create a Submission on non-GET navigations\n\n  let submission;\n  if (opts.formData) {\n    submission = {\n      formMethod: opts.formMethod || \"get\",\n      formAction: stripHashFromPath(path),\n      formEncType: opts && opts.formEncType || \"application/x-www-form-urlencoded\",\n      formData: opts.formData\n    };\n    if (isMutationMethod(submission.formMethod)) {\n      return {\n        path,\n        submission\n      };\n    }\n  } // Flatten submission onto URLSearchParams for GET submissions\n\n  let parsedPath = parsePath(path);\n  try {\n    let searchParams = convertFormDataToSearchParams(opts.formData); // Since fetcher GET submissions only run a single loader (as opposed to\n    // navigation GET submissions which run all loaders), we need to preserve\n    // any incoming ?index params\n\n    if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n      searchParams.append(\"index\", \"\");\n    }\n    parsedPath.search = \"?\" + searchParams;\n  } catch (e) {\n    return {\n      path,\n      error: getInternalRouterError(400)\n    };\n  }\n  return {\n    path: createPath(parsedPath),\n    submission\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\n\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(state, matches, submission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches) {\n  let actionResult = pendingError ? Object.values(pendingError)[0] : pendingActionData ? Object.values(pendingActionData)[0] : undefined; // Pick navigation matches that are net-new or qualify for revalidation\n\n  let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n  let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n  let navigationMatches = boundaryMatches.filter((match, index) => match.route.loader != null && (isNewLoader(state.loaderData, state.matches[index], match) ||\n  // If this route had a pending deferred cancelled it must be revalidated\n  cancelledDeferredRoutes.some(id => id === match.route.id) || shouldRevalidateLoader(state.location, state.matches[index], submission, location, match, isRevalidationRequired, actionResult))); // Pick fetcher.loads that need to be revalidated\n\n  let revalidatingFetchers = [];\n  fetchLoadMatches && fetchLoadMatches.forEach((_ref10, key) => {\n    let [href, match, fetchMatches] = _ref10;\n\n    // This fetcher was cancelled from a prior action submission - force reload\n    if (cancelledFetcherLoads.includes(key)) {\n      revalidatingFetchers.push([key, href, match, fetchMatches]);\n    } else if (isRevalidationRequired) {\n      let shouldRevalidate = shouldRevalidateLoader(href, match, submission, href, match, isRevalidationRequired, actionResult);\n      if (shouldRevalidate) {\n        revalidatingFetchers.push([key, href, match, fetchMatches]);\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; // 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\n  let isMissingData = currentLoaderData[match.route.id] === undefined; // Always load if this is a net-new route or we don't yet have data\n\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 && currentPath.endsWith(\"*\") && currentMatch.params[\"*\"] !== match.params[\"*\"]\n  );\n}\nfunction shouldRevalidateLoader(currentLocation, currentMatch, submission, location, match, isRevalidationRequired, actionResult) {\n  let currentUrl = createClientSideURL(currentLocation);\n  let currentParams = currentMatch.params;\n  let nextUrl = createClientSideURL(location);\n  let nextParams = match.params; // This is the default implementation as to 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  // Note that fetchers always provide the same current/next locations so the\n  // URL-based checks here don't apply to fetcher shouldRevalidate calls\n\n  let defaultShouldRevalidate = isNewRouteInstance(currentMatch, match) ||\n  // Clicked the same link, resubmitted a GET form\n  currentUrl.toString() === nextUrl.toString() ||\n  // Search params affect all loaders\n  currentUrl.search !== nextUrl.search ||\n  // Forced revalidation due to submission, useRevalidate, or X-Remix-Revalidate\n  isRevalidationRequired;\n  if (match.route.shouldRevalidate) {\n    let routeChoice = match.route.shouldRevalidate(_extends({\n      currentUrl,\n      currentParams,\n      nextUrl,\n      nextParams\n    }, submission, {\n      actionResult,\n      defaultShouldRevalidate\n    }));\n    if (typeof routeChoice === \"boolean\") {\n      return routeChoice;\n    }\n  }\n  return defaultShouldRevalidate;\n}\nasync function callLoaderOrAction(type, request, match, matches, basename, isStaticRequest, isRouteRequest, requestContext) {\n  if (basename === void 0) {\n    basename = \"/\";\n  }\n  if (isStaticRequest === void 0) {\n    isStaticRequest = false;\n  }\n  if (isRouteRequest === void 0) {\n    isRouteRequest = false;\n  }\n  let resultType;\n  let result; // Setup a promise we can race against so that abort signals short circuit\n\n  let reject;\n  let abortPromise = new Promise((_, r) => reject = r);\n  let onReject = () => reject();\n  request.signal.addEventListener(\"abort\", onReject);\n  try {\n    let handler = match.route[type];\n    invariant(handler, \"Could not find the \" + type + \" to run on the \\\"\" + match.route.id + \"\\\" route\");\n    result = await Promise.race([handler({\n      request,\n      params: match.params,\n      context: requestContext\n    }), abortPromise]);\n    invariant(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    resultType = ResultType.error;\n    result = e;\n  } finally {\n    request.signal.removeEventListener(\"abort\", onReject);\n  }\n  if (isResponse(result)) {\n    let status = result.status; // Process redirects\n\n    if (redirectStatusCodes.has(status)) {\n      let location = result.headers.get(\"Location\");\n      invariant(location, \"Redirects returned/thrown from loaders/actions must have a Location header\");\n      let isAbsolute = /^[a-z+]+:\\/\\//i.test(location) || location.startsWith(\"//\"); // Support relative routing in internal redirects\n\n      if (!isAbsolute) {\n        let activeMatches = matches.slice(0, matches.indexOf(match) + 1);\n        let routePathnames = getPathContributingMatches(activeMatches).map(match => match.pathnameBase);\n        let resolvedLocation = resolveTo(location, routePathnames, new URL(request.url).pathname);\n        invariant(createPath(resolvedLocation), \"Unable to resolve redirect location: \" + location); // Prepend the basename to the redirect location if we have one\n\n        if (basename) {\n          let path = resolvedLocation.pathname;\n          resolvedLocation.pathname = path === \"/\" ? basename : joinPaths([basename, path]);\n        }\n        location = createPath(resolvedLocation);\n      } // Don't process redirects in the router during static requests requests.\n      // Instead, throw the Response and let the server handle it with an HTTP\n      // redirect.  We also update the Location header in place in this flow so\n      // basename and relative routing is taken into account\n\n      if (isStaticRequest) {\n        result.headers.set(\"Location\", location);\n        throw result;\n      }\n      return {\n        type: ResultType.redirect,\n        status,\n        location,\n        revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null\n      };\n    } // For SSR single-route requests, we want to hand Responses back directly\n    // without unwrapping.  We do this with the QueryRouteResponse wrapper\n    // interface so we can know whether it was returned or thrown\n\n    if (isRouteRequest) {\n      // eslint-disable-next-line no-throw-literal\n      throw {\n        type: resultType || ResultType.data,\n        response: result\n      };\n    }\n    let data;\n    let contentType = result.headers.get(\"Content-Type\"); // Check between word boundaries instead of startsWith() due to the last\n    // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n\n    if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n      data = await result.json();\n    } else {\n      data = await result.text();\n    }\n    if (resultType === ResultType.error) {\n      return {\n        type: resultType,\n        error: new ErrorResponse(status, result.statusText, data),\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 (resultType === ResultType.error) {\n    return {\n      type: resultType,\n      error: result\n    };\n  }\n  if (result instanceof DeferredData) {\n    return {\n      type: ResultType.deferred,\n      deferredData: result\n    };\n  }\n  return {\n    type: ResultType.data,\n    data: result\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)\n\nfunction createClientSideRequest(location, signal, submission) {\n  let url = createClientSideURL(stripHashFromPath(location)).toString();\n  let init = {\n    signal\n  };\n  if (submission && isMutationMethod(submission.formMethod)) {\n    let {\n      formMethod,\n      formEncType,\n      formData\n    } = submission;\n    init.method = formMethod.toUpperCase();\n    init.body = formEncType === \"application/x-www-form-urlencoded\" ? convertFormDataToSearchParams(formData) : formData;\n  } // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\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    invariant(typeof value === \"string\", 'File inputs are not supported with encType \"application/x-www-form-urlencoded\", ' + 'please use \"multipart/form-data\" instead.');\n    searchParams.append(key, value);\n  }\n  return searchParams;\n}\nfunction processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds) {\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 = {}; // Process loader results into state.loaderData/state.errors\n\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      // Look upwards from the matched route for the closest ancestor\n      // error boundary, defaulting to the root match\n      let boundaryMatch = findNearestBoundary(matches, id);\n      let error = result.error; // 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\n      if (pendingError) {\n        error = Object.values(pendingError)[0];\n        pendingError = undefined;\n      }\n      errors = errors || {}; // Prefer higher error values if lower errors bubble to the same boundary\n\n      if (errors[boundaryMatch.route.id] == null) {\n        errors[boundaryMatch.route.id] = error;\n      } // Clear our any prior loaderData for the throwing route\n\n      loaderData[id] = undefined; // Once we find our first (highest) error, we set the status code and\n      // prevent deeper status codes from overriding\n\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 if (isDeferredResult(result)) {\n      activeDeferreds && activeDeferreds.set(id, result.deferredData);\n      loaderData[id] = result.deferredData.data; // TODO: Add statusCode/headers once we wire up streaming in Remix\n    } else {\n      loaderData[id] = result.data; // Error status codes always override success status codes, but if all\n      // loaders are successful we take the deepest status code.\n\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    }\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\n  if (pendingError) {\n    errors = pendingError;\n    loaderData[Object.keys(pendingError)[0]] = undefined;\n  }\n  return {\n    loaderData,\n    errors,\n    statusCode: statusCode || 200,\n    loaderHeaders\n  };\n}\nfunction processLoaderData(state, matches, matchesToLoad, results, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds) {\n  let {\n    loaderData,\n    errors\n  } = processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds); // Process results from our revalidating fetchers\n\n  for (let index = 0; index < revalidatingFetchers.length; index++) {\n    let [key,, match] = revalidatingFetchers[index];\n    invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, \"Did not find corresponding fetcher result\");\n    let result = fetcherResults[index]; // Process fetcher non-redirect errors\n\n    if (isErrorResult(result)) {\n      let boundaryMatch = findNearestBoundary(state.matches, 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      throw new Error(\"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      throw new Error(\"Unhandled fetcher deferred data\");\n    } else {\n      let doneFetcher = {\n        state: \"idle\",\n        data: result.data,\n        formMethod: undefined,\n        formAction: undefined,\n        formEncType: undefined,\n        formData: undefined,\n        \" _hasFetcherDoneAnything \": true\n      };\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) {\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} // 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\n\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.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, _temp4) {\n  let {\n    pathname,\n    routeId,\n    method\n  } = _temp4 === void 0 ? {} : _temp4;\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 {\n      errorMessage = \"Cannot submit binary form data using GET\";\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 ErrorResponse(status || 500, statusText, new Error(errorMessage), true);\n} // Find any returned redirect errors, starting from the lowest match\n\nfunction findRedirect(results) {\n  for (let i = results.length - 1; i >= 0; i--) {\n    let result = results[i];\n    if (isRedirectResult(result)) {\n      return result;\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  return a.pathname === b.pathname && a.search === b.search && a.hash !== b.hash;\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 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 isQueryRouteResponse(obj) {\n  return obj && isResponse(obj.response) && (obj.type === ResultType.data || ResultType.error);\n}\nfunction isValidMethod(method) {\n  return validRequestMethods.has(method);\n}\nfunction isMutationMethod(method) {\n  return validMutationMethods.has(method);\n}\nasync function resolveDeferredResults(currentMatches, matchesToLoad, results, signal, isFetcher, currentLoaderData) {\n  for (let index = 0; index < results.length; index++) {\n    let result = results[index];\n    let match = matchesToLoad[index];\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      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} // Note: This should match the format exported by useMatches, so if you change\n// this please also change that :)  Eventually we'll DRY this up\n\nfunction createUseMatchesMatch(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 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  } // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n  // pathless layout routes)\n\n  let pathMatches = getPathContributingMatches(matches);\n  return pathMatches[pathMatches.length - 1];\n} //#endregion\n\nexport { AbortedDeferredError, Action, ErrorResponse, IDLE_FETCHER, IDLE_NAVIGATION, convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes, getPathContributingMatches as UNSAFE_getPathContributingMatches, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, createRouter, createStaticHandler, defer, generatePath, getStaticContextFromError, getToPathname, invariant, isRouteErrorResponse, joinPaths, json, matchPath, matchRoutes, normalizePathname, parsePath, redirect, resolvePath, resolveTo, stripBasename, warning };","map":{"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;;AAEA;;AAEG;IACSA;AAAZ,WAAYA,MAAZ,EAAkB;EAChB;;;;;;AAMG;EACHA;EAEA;;;;AAIG;;EACHA;EAEA;;;AAGG;;EACHA;AACD,CAtBD,EAAYA,MAAM,KAANA,MAAM,GAsBjB,EAtBiB,CAAlB;AA2KA,MAAMC,iBAAiB,GAAG,UAA1B;AA+BA;;;AAGG;;AACa,6BACdC,OADc,EACoB;EAAA,IAAlCA,OAAkC;IAAlCA,OAAkC,GAAF,EAAE;EAAA;EAElC,IAAI;IAAEC,cAAc,GAAG,CAAC,GAAD,CAAnB;IAA0BC,YAA1B;IAAwCC,QAAQ,GAAG;EAAnD,IAA6DH,OAAjE;EACA,IAAII,OAAJ,CAHkC;;EAIlCA,OAAO,GAAGH,cAAc,CAACI,GAAf,CAAmB,CAACC,KAAD,EAAQC,KAAR,KAC3BC,oBAAoB,CAClBF,KADkB,EAElB,OAAOA,KAAP,KAAiB,QAAjB,GAA4B,IAA5B,GAAmCA,KAAK,CAACG,KAFvB,EAGlBF,KAAK,KAAK,CAAV,GAAc,SAAd,GAA0BG,SAHR,CADZ,CAAV;EAOA,IAAIH,KAAK,GAAGI,UAAU,CACpBT,YAAY,IAAI,IAAhB,GAAuBE,OAAO,CAACQ,MAAR,GAAiB,CAAxC,GAA4CV,YADxB,CAAtB;EAGA,IAAIW,MAAM,GAAGf,MAAM,CAACgB,GAApB;EACA,IAAIC,QAAQ,GAAoB,IAAh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CAFpB,EAGE;IACA;IACA,OAAOoF,OAAO,CAACA,OAAO,CAAC5G,MAAR,GAAiB,CAAlB,CAAd;EACD,CAV0B;EAY3B;;EACA,IAAI4hB,WAAW,GAAG/U,0BAA0B,CAACjG,OAAD,CAA5C;EACA,OAAOgb,WAAW,CAACA,WAAW,CAAC5hB,MAAZ,GAAqB,CAAtB,CAAlB;AACD","names":["Action","PopStateEventType","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","history","createHref","createPath","encodeLocation","path","parsePath","search","hash","push","Push","nextLocation","splice","replace","Replace","go","delta","listen","fn","createBrowserLocation","window","globalHistory","usr","createBrowserHref","getUrlBasedHistory","createHashLocation","substr","createHashHref","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","validateHashLocation","value","message","Error","cond","console","warn","e","createKey","random","toString","getHistoryState","current","_ref","parsedPath","searchIndex","createClientSideURL","origin","invariant","URL","getLocation","validateLocation","defaultView","handlePop","historyState","pushState","error","assign","replaceState","addEventListener","removeEventListener","ResultType","isIndexRoute","route","convertRoutesToDataRoutes","routes","parentPath","allIds","Set","treePath","id","join","children","has","add","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","stripBasename","branches","flattenRoutes","rankRouteBranches","matches","i","matchRouteBranch","safelyDecodeURI","parentsMeta","flattenRoute","relativePath","meta","caseSensitive","childrenIndex","startsWith","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","match","matchPath","Object","params","pathnameBase","normalizePathname","generatePath","originalPath","_","prefix","__","str","star","pattern","matcher","paramNames","compilePath","captureGroups","memo","paramName","splatValue","safelyDecodeURIComponent","regexpSource","RegExp","decodeURI","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","resolvePathname","normalizeSearch","normalizeHash","relativeSegments","pop","getInvalidPathError","char","field","dest","getPathContributingMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","getToPathname","paths","json","data","init","responseInit","status","headers","Headers","set","Response","AbortedDeferredError","DeferredData","constructor","subscriber","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","trackPromise","pendingKeys","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","done","subscribe","cancel","abort","v","k","resolveData","resolve","size","unwrappedData","unwrapTrackedPromise","isTrackedPromise","_tracked","_error","_data","defer","redirect","ErrorResponse","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","IDLE_FETCHER","isBrowser","createElement","isServer","createRouter","dataRoutes","unlistenHistory","subscribers","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialErrors","getInternalRouterError","getShortCircuitMatches","initialized","m","loader","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","loaderData","actionData","errors","fetchers","Map","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeDeferreds","initialize","startNavigation","dispose","clear","deleteFetcher","updateState","newState","completeNavigation","isActionReload","isMutationMethod","_isRedirect","keys","mergeLoaderData","getSavedScrollPosition","navigate","opts","submission","normalizeNavigateOptions","userReplace","pendingError","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","loadingNavigation","notFoundMatches","cancelActiveDeferreds","isHashChangeOnly","request","createClientSideRequest","pendingActionData","findNearestBoundary","actionOutput","handleAction","shortCircuited","pendingActionError","Request","handleLoaders","actionMatch","getTargetMatch","type","method","routeId","callLoaderOrAction","isRedirectResult","startRedirectNavigation","isErrorResult","boundaryMatch","isDeferredResult","activeSubmission","matchesToLoad","revalidatingFetchers","getMatchesToLoad","_ref2","fetcher","revalidatingFetcher","_ref3","results","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","_ref4","findRedirect","processLoaderData","deferredData","markFetchRedirectsDone","didAbortFetchLoads","abortStaleFetchLoads","getFetcher","fetch","abortFetcher","setFetcherError","handleFetcherAction","handleFetcherLoader","requestMatches","existingFetcher","abortController","fetchRequest","actionResult","loadingFetcher","isFetchActionRedirect","revalidationRequest","loadId","loadFetcher","_ref5","staleKey","_ref6","_ref7","doneFetcher","resolveDeferredData","_temp","redirectLocation","_extends","_isFetchActionRedirect","_window","newOrigin","redirectHistoryAction","currentMatches","fetchersToLoad","all","_ref8","fetchMatches","resolveDeferredResults","_ref9","markFetchersDone","doneKeys","landedId","yeetedKeys","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","userMatches","createUseMatchesMatch","_internalFetchControllers","_internalActiveDeferreds","query","_temp2","requestContext","isValidMethod","methodNotAllowedMatches","statusCode","loaderHeaders","actionHeaders","queryImpl","isResponse","queryRoute","_temp3","find","values","routeData","routeMatch","submit","loadRouteData","isQueryRouteResponse","isRedirectResponse","response","isRouteRequest","Location","context","loaderRequest","getLoaderMatchesUntilBoundary","executedLoaders","processRouteLoaderData","getStaticContextFromError","newContext","_deepestRenderedBoundaryId","isSubmissionNavigation","isFetcher","stripHashFromPath","searchParams","convertFormDataToSearchParams","hasNakedIndexQuery","append","boundaryId","boundaryMatches","findIndex","navigationMatches","isNewLoader","shouldRevalidateLoader","shouldRevalidate","currentLoaderData","currentMatch","isNew","isMissingData","isNewRouteInstance","currentPath","currentLocation","currentUrl","currentParams","nextUrl","nextParams","defaultShouldRevalidate","routeChoice","isStaticRequest","resultType","onReject","handler","isAbsolute","activeMatches","resolvedLocation","contentType","text","deferred","toUpperCase","body","URLSearchParams","foundError","newLoaderData","mergedLoaderData","hasOwnProperty","eligibleMatches","reverse","hasErrorBoundary","_temp4","errorMessage","obj","isRevalidatingLoader","unwrap","getAll","handle","pathMatches"],"sources":["C:\\Users\\user\\Desktop\\05mediaSocial\\client\\node_modules\\@remix-run\\router\\history.ts","C:\\Users\\user\\Desktop\\05mediaSocial\\client\\node_modules\\@remix-run\\router\\utils.ts","C:\\Users\\user\\Desktop\\05mediaSocial\\client\\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/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location extends Path {\n  /**\n   * A value of arbitrary data associated with this location.\n   */\n  state: any;\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/**\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`. May be either a URL or the pieces of a\n * 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   * 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};\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  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(to) {\n      return typeof to === \"string\" ? to : createPath(to);\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 });\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 });\n      }\n    },\n    go(delta) {\n      action = Action.Pop;\n      index = clampIndex(index + delta);\n      if (listener) {\n        listener({ action, location: getCurrentLocation() });\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    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\nfunction 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): HistoryState {\n  return {\n    usr: location.state,\n    key: location.key,\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 function createClientSideURL(location: Location | string): 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    typeof window !== \"undefined\" &&\n    typeof window.location !== \"undefined\" &&\n    window.location.origin !== \"null\"\n      ? window.location.origin\n      : window.location.href;\n  let href = typeof location === \"string\" ? location : createPath(location);\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\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  function handlePop() {\n    action = Action.Pop;\n    if (listener) {\n      listener({ action, location: history.location });\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    let historyState = getHistoryState(location);\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      // 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 });\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    let historyState = getHistoryState(location);\n    let url = history.createHref(location);\n    globalHistory.replaceState(historyState, \"\", url);\n\n    if (v5Compat && listener) {\n      listener({ action, location: history.location });\n    }\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    encodeLocation(to) {\n      // Encode a Location the same way window.location would\n      let url = createClientSideURL(\n        typeof to === \"string\" ? to : createPath(to)\n      );\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 } 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: any;\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}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n  type: ResultType.redirect;\n  status: number;\n  location: string;\n  revalidate: boolean;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n  type: ResultType.error;\n  error: any;\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\nexport type MutationFormMethod = \"post\" | \"put\" | \"patch\" | \"delete\";\nexport type FormMethod = \"get\" | MutationFormMethod;\n\nexport type FormEncType =\n  | \"application/x-www-form-urlencoded\"\n  | \"multipart/form-data\";\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport interface Submission {\n  formMethod: FormMethod;\n  formAction: string;\n  formEncType: FormEncType;\n  formData: FormData;\n}\n\n/**\n * @private\n * Arguments passed to route loader/action functions.  Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs {\n  request: Request;\n  params: Params;\n  context?: any;\n}\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs extends DataFunctionArgs {}\n\n/**\n * Route loader function signature\n */\nexport interface LoaderFunction {\n  (args: LoaderFunctionArgs): Promise<Response> | Response | Promise<any> | any;\n}\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n  (args: ActionFunctionArgs): Promise<Response> | Response | Promise<any> | any;\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: {\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    formData?: Submission[\"formData\"];\n    actionResult?: DataResult;\n    defaultShouldRevalidate: boolean;\n  }): boolean;\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;\n  action?: ActionFunction;\n  hasErrorBoundary?: boolean;\n  shouldRevalidate?: ShouldRevalidateFunction;\n  handle?: any;\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\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\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 */\ntype 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 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  parentPath: number[] = [],\n  allIds: Set<string> = new Set<string>()\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      !allIds.has(id),\n      `Found a route id collision on id \"${id}\".  Route ` +\n        \"id's must be globally unique within Data Router usages\"\n    );\n    allIds.add(id);\n\n    if (isIndexRoute(route)) {\n      let indexRoute: AgnosticDataIndexRouteObject = { ...route, id };\n      return indexRoute;\n    } else {\n      let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n        ...route,\n        id,\n        children: route.children\n          ? convertRoutesToDataRoutes(route.children, treePath, allIds)\n          : undefined,\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    matches = matchRouteBranch<string, RouteObjectType>(\n      branches[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      safelyDecodeURI(pathname)\n    );\n  }\n\n  return matches;\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 explodes _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;\n  } = {} as any\n): string {\n  let path = 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  return path\n    .replace(/^:(\\w+)/g, (_, key: PathParam<Path>) => {\n      invariant(params[key] != null, `Missing \":${key}\" param`);\n      return params[key]!;\n    })\n    .replace(/\\/:(\\w+)/g, (_, key: PathParam<Path>) => {\n      invariant(params[key] != null, `Missing \":${key}\" param`);\n      return `/${params[key]!}`;\n    })\n    .replace(/(\\/?)\\*/, (_, prefix, __, str) => {\n      const star = \"*\" as PathParam<Path>;\n\n      if (params[star] == null) {\n        // If no splat was provided, trim the trailing slash _unless_ it's\n        // the entire path\n        return str === \"/*\" ? \"/\" : \"\";\n      }\n\n      // Apply the splat\n      return `${prefix}${params[star]}`;\n    });\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, paramNames] = 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 = paramNames.reduce<Mutable<Params>>(\n    (memo, paramName, 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      memo[paramName] = safelyDecodeURIComponent(\n        captureGroups[index] || \"\",\n        paramName\n      );\n      return memo;\n    },\n    {}\n  );\n\n  return {\n    params,\n    pathname: matchedPathname,\n    pathnameBase,\n    pattern,\n  };\n}\n\nfunction compilePath(\n  path: string,\n  caseSensitive = false,\n  end = true\n): [RegExp, string[]] {\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 paramNames: string[] = [];\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(/\\/:(\\w+)/g, (_: string, paramName: string) => {\n        paramNames.push(paramName);\n        return \"/([^\\\\/]+)\";\n      });\n\n  if (path.endsWith(\"*\")) {\n    paramNames.push(\"*\");\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, paramNames];\n}\n\nfunction safelyDecodeURI(value: string) {\n  try {\n    return decodeURI(value);\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\nfunction safelyDecodeURIComponent(value: string, paramName: string) {\n  try {\n    return decodeURIComponent(value);\n  } catch (error) {\n    warning(\n      false,\n      `The value for the URL param \"${paramName}\" will not be decoded because` +\n        ` the string \"${value}\" is a malformed URL segment. This is probably` +\n        ` due to a bad percent 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 * @private\n */\nexport function warning(cond: any, message: string): void {\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 React Router!\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\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/**\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 (isPathRelative || toPathname == null) {\n    from = locationPathname;\n  } else {\n    let routePathnameIndex = routePathnames.length - 1;\n\n    if (toPathname.startsWith(\"..\")) {\n      let toSegments = toPathname.split(\"/\");\n\n      // Each leading .. segment means \"go up one route\" instead of \"go up one\n      // URL segment\".  This is a key difference from how <a href> works and a\n      // major reason we call this a \"to\" value instead of a \"href\".\n      while (toSegments[0] === \"..\") {\n        toSegments.shift();\n        routePathnameIndex -= 1;\n      }\n\n      to.pathname = toSegments.join(\"/\");\n    }\n\n    // If there are more \"..\" segments than parent routes, resolve relative to\n    // the root / URL.\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 pendingKeys: Set<string | number> = new Set<string | number>();\n  private controller: AbortController;\n  private abortPromise: Promise<void>;\n  private unlistenAbortSignal: () => void;\n  private subscriber?: (aborted: boolean) => void = undefined;\n  data: Record<string, unknown>;\n\n  constructor(data: Record<string, unknown>) {\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\n  private trackPromise(\n    key: string | number,\n    value: Promise<unknown> | unknown\n  ): TrackedPromise | unknown {\n    if (!(value instanceof Promise)) {\n      return value;\n    }\n\n    this.pendingKeys.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, null, 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 | number,\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.pendingKeys.delete(key);\n\n    if (this.done) {\n      // Nothing left to abort!\n      this.unlistenAbortSignal();\n    }\n\n    const subscriber = this.subscriber;\n    if (error) {\n      Object.defineProperty(promise, \"_error\", { get: () => error });\n      subscriber && subscriber(false);\n      return Promise.reject(error);\n    }\n\n    Object.defineProperty(promise, \"_data\", { get: () => data });\n    subscriber && subscriber(false);\n    return data;\n  }\n\n  subscribe(fn: (aborted: boolean) => void) {\n    this.subscriber = fn;\n  }\n\n  cancel() {\n    this.controller.abort();\n    this.pendingKeys.forEach((v, k) => this.pendingKeys.delete(k));\n    let subscriber = this.subscriber;\n    subscriber && subscriber(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.pendingKeys.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\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 function defer(data: Record<string, unknown>) {\n  return new DeferredData(data);\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 * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n */\nexport class ErrorResponse {\n  status: number;\n  statusText: string;\n  data: any;\n  error?: Error;\n  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 throw from an action/loader\n */\nexport function isRouteErrorResponse(e: any): e is ErrorResponse {\n  return e instanceof ErrorResponse;\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n  Action as HistoryAction,\n  createLocation,\n  createPath,\n  createClientSideURL,\n  invariant,\n  parsePath,\n} from \"./history\";\nimport type {\n  DataResult,\n  AgnosticDataRouteMatch,\n  AgnosticDataRouteObject,\n  DeferredResult,\n  ErrorResult,\n  FormEncType,\n  FormMethod,\n  RedirectResult,\n  RouteData,\n  AgnosticRouteObject,\n  Submission,\n  SuccessResult,\n  AgnosticRouteMatch,\n  MutationFormMethod,\n} from \"./utils\";\nimport {\n  DeferredData,\n  ErrorResponse,\n  ResultType,\n  convertRoutesToDataRoutes,\n  getPathContributingMatches,\n  isRouteErrorResponse,\n  joinPaths,\n  matchRoutes,\n  resolveTo,\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 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   * 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): 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, opts?: RouterNavigateOptions): 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,\n    opts?: RouterNavigateOptions\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   * 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/**\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 * Initialization options for createRouter\n */\nexport interface RouterInit {\n  basename?: string;\n  routes: AgnosticRouteObject[];\n  history: History;\n  hydrationData?: HydrationState;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n  basename: Router[\"basename\"];\n  location: RouterState[\"location\"];\n  matches: RouterState[\"matches\"];\n  loaderData: RouterState[\"loaderData\"];\n  actionData: RouterState[\"actionData\"];\n  errors: RouterState[\"errors\"];\n  statusCode: number;\n  loaderHeaders: Record<string, Headers>;\n  actionHeaders: Record<string, Headers>;\n  _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n  dataRoutes: AgnosticDataRouteObject[];\n  query(\n    request: Request,\n    opts?: { requestContext?: unknown }\n  ): Promise<StaticHandlerContext | Response>;\n  queryRoute(\n    request: Request,\n    opts?: { routeId?: string; requestContext?: unknown }\n  ): Promise<any>;\n}\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n  (state: RouterState): void;\n}\n\ninterface UseMatchesMatch {\n  id: string;\n  pathname: string;\n  params: AgnosticRouteMatch[\"params\"];\n  data: unknown;\n  handle: unknown;\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: UseMatchesMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n  (): number;\n}\n\n/**\n * Options for a navigate() call for a Link navigation\n */\ntype LinkNavigateOptions = {\n  replace?: boolean;\n  state?: any;\n  preventScrollReset?: boolean;\n};\n\n/**\n * Options for a navigate() call for a Form navigation\n */\ntype SubmissionNavigateOptions = {\n  replace?: boolean;\n  state?: any;\n  formMethod?: FormMethod;\n  formEncType?: FormEncType;\n  formData: FormData;\n};\n\n/**\n * Options to pass to navigate() for either a Link or Form navigation\n */\nexport type RouterNavigateOptions =\n  | LinkNavigateOptions\n  | SubmissionNavigateOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions =\n  | Omit<LinkNavigateOptions, \"replace\">\n  | Omit<SubmissionNavigateOptions, \"replace\">;\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  };\n  Loading: {\n    state: \"loading\";\n    location: Location;\n    formMethod: FormMethod | undefined;\n    formAction: string | undefined;\n    formEncType: FormEncType | undefined;\n    formData: FormData | undefined;\n  };\n  Submitting: {\n    state: \"submitting\";\n    location: Location;\n    formMethod: FormMethod;\n    formAction: string;\n    formEncType: FormEncType;\n    formData: FormData;\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    formData: undefined;\n    data: TData | undefined;\n    \" _hasFetcherDoneAnything \"?: boolean;\n  };\n  Loading: {\n    state: \"loading\";\n    formMethod: FormMethod | undefined;\n    formAction: string | undefined;\n    formEncType: FormEncType | undefined;\n    formData: FormData | undefined;\n    data: TData | undefined;\n    \" _hasFetcherDoneAnything \"?: boolean;\n  };\n  Submitting: {\n    state: \"submitting\";\n    formMethod: FormMethod;\n    formAction: string;\n    formEncType: FormEncType;\n    formData: FormData;\n    data: TData | undefined;\n    \" _hasFetcherDoneAnything \"?: boolean;\n  };\n};\n\nexport type Fetcher<TData = any> =\n  FetcherStates<TData>[keyof FetcherStates<TData>];\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\ninterface HandleActionResult extends ShortCircuitable {\n  /**\n   * Error thrown from the current action, keyed by the route containing the\n   * error boundary to render the error.  To be committed to the state after\n   * loaders have completed\n   */\n  pendingActionError?: RouteData;\n  /**\n   * Data returned from the current action, keyed by the route owning the action.\n   * To be committed to the state after loaders have completed\n   */\n  pendingActionData?: RouteData;\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 * Tuple of [key, href, DataRouteMatch, DataRouteMatch[]] for a revalidating\n * fetcher.load()\n */\ntype RevalidatingFetcher = [\n  string,\n  string,\n  AgnosticDataRouteMatch,\n  AgnosticDataRouteMatch[]\n];\n\n/**\n * Tuple of [href, DataRouteMatch, DataRouteMatch[]] for an active\n * fetcher.load()\n */\ntype FetchLoadMatch = [\n  string,\n  AgnosticDataRouteMatch,\n  AgnosticDataRouteMatch[]\n];\n\n/**\n * Wrapper object to allow us to throw any response out from callLoaderOrAction\n * for queryRouter while preserving whether or not it was thrown or returned\n * from the loader/action\n */\ninterface QueryRouteResponse {\n  type: ResultType.data | ResultType.error;\n  response: Response;\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};\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};\n\nconst isBrowser =\n  typeof window !== \"undefined\" &&\n  typeof window.document !== \"undefined\" &&\n  typeof window.document.createElement !== \"undefined\";\nconst isServer = !isBrowser;\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  invariant(\n    init.routes.length > 0,\n    \"You must provide a non-empty routes array to createRouter\"\n  );\n\n  let dataRoutes = convertRoutesToDataRoutes(init.routes);\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(\n    dataRoutes,\n    init.history.location,\n    init.basename\n  );\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 =\n    !initialMatches.some((m) => m.route.loader) || init.hydrationData != null;\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  };\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  // 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: AbortController | 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  //  - useRevalidate()\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: string[] = [];\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  // AbortControllers for any in-flight fetchers\n  let fetchControllers = new Map<string, AbortController>();\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<string, number>();\n  // Fetchers that triggered redirect navigations from their actions\n  let fetchRedirectIds = new Set<string>();\n  // Most recent href/match for fetcher.load calls for fetchers\n  let fetchLoadMatches = new Map<string, FetchLoadMatch>();\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  // 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 }) =>\n        startNavigation(historyAction, location)\n    );\n\n    // Kick off initial data load if needed.  Use Pop to avoid modifying history\n    if (!state.initialized) {\n      startNavigation(HistoryAction.Pop, state.location);\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    subscribers.clear();\n    pendingNavigationController && pendingNavigationController.abort();\n    state.fetchers.forEach((_, key) => deleteFetcher(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(newState: Partial<RouterState>): void {\n    state = {\n      ...state,\n      ...newState,\n    };\n    subscribers.forEach((subscriber) => subscriber(state));\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  ): 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    updateState({\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      // Don't restore on submission navigations\n      restoreScrollPosition: state.navigation.formData\n        ? false\n        : getSavedScrollPosition(location, newState.matches || state.matches),\n      preventScrollReset: pendingPreventScrollReset,\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    // Reset stateful navigation vars\n    pendingAction = HistoryAction.Pop;\n    pendingPreventScrollReset = 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,\n    opts?: RouterNavigateOptions\n  ): Promise<void> {\n    if (typeof to === \"number\") {\n      init.history.go(to);\n      return;\n    }\n\n    let { path, submission, error } = normalizeNavigateOptions(to, opts);\n\n    let location = 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    location = {\n      ...location,\n      ...init.history.encodeLocation(location),\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    return await startNavigation(historyAction, location, {\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    });\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      submission?: Submission;\n      overrideNavigation?: Navigation;\n      pendingError?: ErrorResponse;\n      startUninterruptedRevalidation?: boolean;\n      preventScrollReset?: boolean;\n      replace?: 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    let loadingNavigation = opts && opts.overrideNavigation;\n    let matches = matchRoutes(dataRoutes, location, init.basename);\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(dataRoutes);\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      return;\n    }\n\n    // Short circuit if it's only a hash change\n    if (isHashChangeOnly(state.location, location)) {\n      completeNavigation(location, { matches });\n      return;\n    }\n\n    // Create a controller/Request for this navigation\n    pendingNavigationController = new AbortController();\n    let request = createClientSideRequest(\n      location,\n      pendingNavigationController.signal,\n      opts && opts.submission\n    );\n    let pendingActionData: RouteData | undefined;\n    let pendingError: RouteData | 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      pendingError = {\n        [findNearestBoundary(matches).route.id]: 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 actionOutput = await handleAction(\n        request,\n        location,\n        opts.submission,\n        matches,\n        { replace: opts.replace }\n      );\n\n      if (actionOutput.shortCircuited) {\n        return;\n      }\n\n      pendingActionData = actionOutput.pendingActionData;\n      pendingError = actionOutput.pendingActionError;\n\n      let navigation: NavigationStates[\"Loading\"] = {\n        state: \"loading\",\n        location,\n        ...opts.submission,\n      };\n      loadingNavigation = navigation;\n\n      // Create a GET request for the loaders\n      request = new Request(request.url, { signal: request.signal });\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.replace,\n      pendingActionData,\n      pendingError\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      ...(pendingActionData ? { actionData: pendingActionData } : {}),\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 }\n  ): Promise<HandleActionResult> {\n    interruptActiveLoads();\n\n    // Put us in a submitting state\n    let navigation: NavigationStates[\"Submitting\"] = {\n      state: \"submitting\",\n      location,\n      ...submission,\n    };\n    updateState({ navigation });\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) {\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      result = await callLoaderOrAction(\n        \"action\",\n        request,\n        actionMatch,\n        matches,\n        router.basename\n      );\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        replace =\n          result.location === state.location.pathname + state.location.search;\n      }\n      await startRedirectNavigation(state, result, { submission, replace });\n      return { shortCircuited: true };\n    }\n\n    if (isErrorResult(result)) {\n      // Store off the pending error - we use it to determine which loaders\n      // to call and will commit it when we complete the navigation\n      let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n      // By default, all submissions 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        // Send back an empty object we can use to clear out any prior actionData\n        pendingActionData: {},\n        pendingActionError: { [boundaryMatch.route.id]: result.error },\n      };\n    }\n\n    if (isDeferredResult(result)) {\n      throw new Error(\"defer() is not supported in actions\");\n    }\n\n    return {\n      pendingActionData: { [actionMatch.route.id]: result.data },\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    replace?: boolean,\n    pendingActionData?: RouteData,\n    pendingError?: RouteData\n  ): Promise<HandleLoadersResult> {\n    // Figure out the right navigation we want to use for data loading\n    let loadingNavigation = overrideNavigation;\n    if (!loadingNavigation) {\n      let navigation: NavigationStates[\"Loading\"] = {\n        state: \"loading\",\n        location,\n        formMethod: undefined,\n        formAction: undefined,\n        formEncType: undefined,\n        formData: undefined,\n        ...submission,\n      };\n      loadingNavigation = navigation;\n    }\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 = submission\n      ? submission\n      : loadingNavigation.formMethod &&\n        loadingNavigation.formAction &&\n        loadingNavigation.formData &&\n        loadingNavigation.formEncType\n      ? {\n          formMethod: loadingNavigation.formMethod,\n          formAction: loadingNavigation.formAction,\n          formData: loadingNavigation.formData,\n          formEncType: loadingNavigation.formEncType,\n        }\n      : undefined;\n\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n      state,\n      matches,\n      activeSubmission,\n      location,\n      isRevalidationRequired,\n      cancelledDeferredRoutes,\n      cancelledFetcherLoads,\n      pendingActionData,\n      pendingError,\n      fetchLoadMatches\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    // Short circuit if we have no loaders to run\n    if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n      completeNavigation(location, {\n        matches,\n        loaderData: {},\n        // Commit pending error if we're short circuiting\n        errors: pendingError || null,\n        ...(pendingActionData ? { actionData: pendingActionData } : {}),\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 (!isUninterruptedRevalidation) {\n      revalidatingFetchers.forEach(([key]) => {\n        let fetcher = state.fetchers.get(key);\n        let revalidatingFetcher: FetcherStates[\"Loading\"] = {\n          state: \"loading\",\n          data: fetcher && fetcher.data,\n          formMethod: undefined,\n          formAction: undefined,\n          formEncType: undefined,\n          formData: undefined,\n          \" _hasFetcherDoneAnything \": true,\n        };\n        state.fetchers.set(key, revalidatingFetcher);\n      });\n      let actionData = pendingActionData || state.actionData;\n      updateState({\n        navigation: loadingNavigation,\n        ...(actionData\n          ? Object.keys(actionData).length === 0\n            ? { actionData: null }\n            : { actionData }\n          : {}),\n        ...(revalidatingFetchers.length > 0\n          ? { fetchers: new Map(state.fetchers) }\n          : {}),\n      });\n    }\n\n    pendingNavigationLoadId = ++incrementingLoadId;\n    revalidatingFetchers.forEach(([key]) =>\n      fetchControllers.set(key, pendingNavigationController!)\n    );\n\n    let { results, 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    revalidatingFetchers.forEach(([key]) => fetchControllers.delete(key));\n\n    // If any loaders returned a redirect Response, start a new REPLACE navigation\n    let redirect = findRedirect(results);\n    if (redirect) {\n      await startRedirectNavigation(state, redirect, { replace });\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      pendingError,\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    markFetchRedirectsDone();\n    let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n\n    return {\n      loaderData,\n      errors,\n      ...(didAbortFetchLoads || revalidatingFetchers.length > 0\n        ? { fetchers: new Map(state.fetchers) }\n        : {}),\n    };\n  }\n\n  function getFetcher<TData = any>(key: string): Fetcher<TData> {\n    return state.fetchers.get(key) || IDLE_FETCHER;\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,\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\n    let matches = matchRoutes(dataRoutes, href, init.basename);\n    if (!matches) {\n      setFetcherError(\n        key,\n        routeId,\n        getInternalRouterError(404, { pathname: href })\n      );\n      return;\n    }\n\n    let { path, submission } = normalizeNavigateOptions(href, opts, true);\n    let match = getTargetMatch(matches, path);\n\n    if (submission && isMutationMethod(submission.formMethod)) {\n      handleFetcherAction(key, routeId, path, match, matches, submission);\n      return;\n    }\n\n    // Store off the match so we can call it's shouldRevalidate on subsequent\n    // revalidations\n    fetchLoadMatches.set(key, [path, match, matches]);\n    handleFetcherLoader(key, routeId, path, match, matches, submission);\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    submission: Submission\n  ) {\n    interruptActiveLoads();\n    fetchLoadMatches.delete(key);\n\n    if (!match.route.action) {\n      let error = getInternalRouterError(405, {\n        method: submission.formMethod,\n        pathname: path,\n        routeId: routeId,\n      });\n      setFetcherError(key, routeId, error);\n      return;\n    }\n\n    // Put this fetcher into it's submitting state\n    let existingFetcher = state.fetchers.get(key);\n    let fetcher: FetcherStates[\"Submitting\"] = {\n      state: \"submitting\",\n      ...submission,\n      data: existingFetcher && existingFetcher.data,\n      \" _hasFetcherDoneAnything \": true,\n    };\n    state.fetchers.set(key, fetcher);\n    updateState({ fetchers: new Map(state.fetchers) });\n\n    // Call the action for the fetcher\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(\n      path,\n      abortController.signal,\n      submission\n    );\n    fetchControllers.set(key, abortController);\n\n    let actionResult = await callLoaderOrAction(\n      \"action\",\n      fetchRequest,\n      match,\n      requestMatches,\n      router.basename\n    );\n\n    if (fetchRequest.signal.aborted) {\n      // We can delete this so long as we weren't aborted by ou 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    if (isRedirectResult(actionResult)) {\n      fetchControllers.delete(key);\n      fetchRedirectIds.add(key);\n      let loadingFetcher: FetcherStates[\"Loading\"] = {\n        state: \"loading\",\n        ...submission,\n        data: undefined,\n        \" _hasFetcherDoneAnything \": true,\n      };\n      state.fetchers.set(key, loadingFetcher);\n      updateState({ fetchers: new Map(state.fetchers) });\n\n      return startRedirectNavigation(state, actionResult, {\n        isFetchActionRedirect: true,\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      invariant(false, \"defer() is not supported in actions\");\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      nextLocation,\n      abortController.signal\n    );\n    let matches =\n      state.navigation.state !== \"idle\"\n        ? matchRoutes(dataRoutes, state.navigation.location, init.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: FetcherStates[\"Loading\"] = {\n      state: \"loading\",\n      data: actionResult.data,\n      ...submission,\n      \" _hasFetcherDoneAnything \": true,\n    };\n    state.fetchers.set(key, loadFetcher);\n\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n      state,\n      matches,\n      submission,\n      nextLocation,\n      isRevalidationRequired,\n      cancelledDeferredRoutes,\n      cancelledFetcherLoads,\n      { [match.route.id]: actionResult.data },\n      undefined, // No need to send through errors since we short circuit above\n      fetchLoadMatches\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(([staleKey]) => staleKey !== key)\n      .forEach(([staleKey]) => {\n        let existingFetcher = state.fetchers.get(staleKey);\n        let revalidatingFetcher: FetcherStates[\"Loading\"] = {\n          state: \"loading\",\n          data: existingFetcher && existingFetcher.data,\n          formMethod: undefined,\n          formAction: undefined,\n          formEncType: undefined,\n          formData: undefined,\n          \" _hasFetcherDoneAnything \": true,\n        };\n        state.fetchers.set(staleKey, revalidatingFetcher);\n        fetchControllers.set(staleKey, abortController);\n      });\n\n    updateState({ fetchers: new Map(state.fetchers) });\n\n    let { results, 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    fetchReloadIds.delete(key);\n    fetchControllers.delete(key);\n    revalidatingFetchers.forEach(([staleKey]) =>\n      fetchControllers.delete(staleKey)\n    );\n\n    let redirect = findRedirect(results);\n    if (redirect) {\n      return startRedirectNavigation(state, redirect);\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    let doneFetcher: FetcherStates[\"Idle\"] = {\n      state: \"idle\",\n      data: actionResult.data,\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      \" _hasFetcherDoneAnything \": true,\n    };\n    state.fetchers.set(key, doneFetcher);\n\n    let didAbortFetchLoads = 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        ...(didAbortFetchLoads ? { 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    submission?: Submission\n  ) {\n    let existingFetcher = state.fetchers.get(key);\n    // Put this fetcher into it's loading state\n    let loadingFetcher: FetcherStates[\"Loading\"] = {\n      state: \"loading\",\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      ...submission,\n      data: existingFetcher && existingFetcher.data,\n      \" _hasFetcherDoneAnything \": true,\n    };\n    state.fetchers.set(key, loadingFetcher);\n    updateState({ fetchers: new Map(state.fetchers) });\n\n    // Call the loader for this fetcher route match\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(path, abortController.signal);\n    fetchControllers.set(key, abortController);\n    let result: DataResult = await callLoaderOrAction(\n      \"loader\",\n      fetchRequest,\n      match,\n      matches,\n      router.basename\n    );\n\n    // Deferred isn't supported or 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 ou 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    // If the loader threw a redirect Response, start a new REPLACE navigation\n    if (isRedirectResult(result)) {\n      await startRedirectNavigation(state, result);\n      return;\n    }\n\n    // Process any non-redirect errors thrown\n    if (isErrorResult(result)) {\n      let boundaryMatch = findNearestBoundary(state.matches, routeId);\n      state.fetchers.delete(key);\n      // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch -\n      // do we need to behave any differently with our non-redirect errors?\n      // What if it was a non-redirect Response?\n      updateState({\n        fetchers: new Map(state.fetchers),\n        errors: {\n          [boundaryMatch.route.id]: result.error,\n        },\n      });\n      return;\n    }\n\n    invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n    // Put the fetcher back into an idle state\n    let doneFetcher: FetcherStates[\"Idle\"] = {\n      state: \"idle\",\n      data: result.data,\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      \" _hasFetcherDoneAnything \": true,\n    };\n    state.fetchers.set(key, doneFetcher);\n    updateState({ fetchers: new Map(state.fetchers) });\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    state: RouterState,\n    redirect: RedirectResult,\n    {\n      submission,\n      replace,\n      isFetchActionRedirect,\n    }: {\n      submission?: Submission;\n      replace?: boolean;\n      isFetchActionRedirect?: boolean;\n    } = {}\n  ) {\n    if (redirect.revalidate) {\n      isRevalidationRequired = true;\n    }\n\n    let redirectLocation = createLocation(\n      state.location,\n      redirect.location,\n      // TODO: This can be removed once we get rid of useTransition in Remix v2\n      {\n        _isRedirect: true,\n        ...(isFetchActionRedirect ? { _isFetchActionRedirect: true } : {}),\n      }\n    );\n    invariant(\n      redirectLocation,\n      \"Expected a location on the redirect navigation\"\n    );\n\n    // Check if this an external redirect that goes to a new origin\n    if (typeof window?.location !== \"undefined\") {\n      let newOrigin = createClientSideURL(redirect.location).origin;\n      if (window.location.origin !== newOrigin) {\n        if (replace) {\n          window.location.replace(redirect.location);\n        } else {\n          window.location.assign(redirect.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, formData } = state.navigation;\n    if (!submission && formMethod && formAction && formData && formEncType) {\n      submission = {\n        formMethod,\n        formAction,\n        formEncType,\n        formData,\n      };\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    if (\n      redirectPreserveMethodStatusCodes.has(redirect.status) &&\n      submission &&\n      isMutationMethod(submission.formMethod)\n    ) {\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        submission: {\n          ...submission,\n          formAction: redirect.location,\n        },\n      });\n    } else {\n      // Otherwise, we kick off a new loading navigation, preserving the\n      // submission info for the duration of this navigation\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        overrideNavigation: {\n          state: \"loading\",\n          location: redirectLocation,\n          formMethod: submission ? submission.formMethod : undefined,\n          formAction: submission ? submission.formAction : undefined,\n          formEncType: submission ? submission.formEncType : undefined,\n          formData: submission ? submission.formData : undefined,\n        },\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    // Call all navigation loaders and revalidating fetcher loaders in parallel,\n    // then slice off the results into separate arrays so we can handle them\n    // accordingly\n    let results = await Promise.all([\n      ...matchesToLoad.map((match) =>\n        callLoaderOrAction(\"loader\", request, match, matches, router.basename)\n      ),\n      ...fetchersToLoad.map(([, href, match, fetchMatches]) =>\n        callLoaderOrAction(\n          \"loader\",\n          createClientSideRequest(href, request.signal),\n          match,\n          fetchMatches,\n          router.basename\n        )\n      ),\n    ]);\n    let loaderResults = results.slice(0, matchesToLoad.length);\n    let fetcherResults = results.slice(matchesToLoad.length);\n\n    await Promise.all([\n      resolveDeferredResults(\n        currentMatches,\n        matchesToLoad,\n        loaderResults,\n        request.signal,\n        false,\n        state.loaderData\n      ),\n      resolveDeferredResults(\n        currentMatches,\n        fetchersToLoad.map(([, , match]) => match),\n        fetcherResults,\n        request.signal,\n        true\n      ),\n    ]);\n\n    return { results, loaderResults, fetcherResults };\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 setFetcherError(key: string, routeId: string, error: any) {\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  }\n\n  function deleteFetcher(key: string): void {\n    if (fetchControllers.has(key)) abortFetcher(key);\n    fetchLoadMatches.delete(key);\n    fetchReloadIds.delete(key);\n    fetchRedirectIds.delete(key);\n    state.fetchers.delete(key);\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: FetcherStates[\"Idle\"] = {\n        state: \"idle\",\n        data: fetcher.data,\n        formMethod: undefined,\n        formAction: undefined,\n        formEncType: undefined,\n        formData: undefined,\n        \" _hasFetcherDoneAnything \": true,\n      };\n      state.fetchers.set(key, doneFetcher);\n    }\n  }\n\n  function markFetchRedirectsDone(): void {\n    let doneKeys = [];\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      }\n    }\n    markFetchersDone(doneKeys);\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 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 || ((location) => location.key);\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 saveScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): void {\n    if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n      let userMatches = matches.map((m) =>\n        createUseMatchesMatch(m, state.loaderData)\n      );\n      let key = getScrollRestorationKey(location, userMatches) || location.key;\n      savedScrollPositions[key] = getScrollPosition();\n    }\n  }\n\n  function getSavedScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): number | null {\n    if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n      let userMatches = matches.map((m) =>\n        createUseMatchesMatch(m, state.loaderData)\n      );\n      let key = getScrollRestorationKey(location, userMatches) || location.key;\n      let y = savedScrollPositions[key];\n      if (typeof y === \"number\") {\n        return y;\n      }\n    }\n    return null;\n  }\n\n  router = {\n    get basename() {\n      return init.basename;\n    },\n    get state() {\n      return state;\n    },\n    get routes() {\n      return dataRoutes;\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,\n    dispose,\n    _internalFetchControllers: fetchControllers,\n    _internalActiveDeferreds: activeDeferreds,\n  };\n\n  return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport function createStaticHandler(\n  routes: AgnosticRouteObject[],\n  opts?: {\n    basename?: string;\n  }\n): StaticHandler {\n  invariant(\n    routes.length > 0,\n    \"You must provide a non-empty routes array to createStaticHandler\"\n  );\n\n  let dataRoutes = convertRoutesToDataRoutes(routes);\n  let basename = (opts ? opts.basename : null) || \"/\";\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  async function query(\n    request: Request,\n    { requestContext }: { requestContext?: unknown } = {}\n  ): Promise<StaticHandlerContext | Response> {\n    let url = new URL(request.url);\n    let method = request.method.toLowerCase();\n    let location = createLocation(\"\", createPath(url), null, \"default\");\n    let matches = matchRoutes(dataRoutes, location, basename);\n\n    // SSR supports HEAD requests while SPA doesn't\n    if (!isValidMethod(method) && method !== \"head\") {\n      let error = getInternalRouterError(405, { method });\n      let { matches: methodNotAllowedMatches, route } =\n        getShortCircuitMatches(dataRoutes);\n      return {\n        basename,\n        location,\n        matches: methodNotAllowedMatches,\n        loaderData: {},\n        actionData: null,\n        errors: {\n          [route.id]: error,\n        },\n        statusCode: error.status,\n        loaderHeaders: {},\n        actionHeaders: {},\n      };\n    } else if (!matches) {\n      let error = getInternalRouterError(404, { pathname: location.pathname });\n      let { matches: notFoundMatches, route } =\n        getShortCircuitMatches(dataRoutes);\n      return {\n        basename,\n        location,\n        matches: notFoundMatches,\n        loaderData: {},\n        actionData: null,\n        errors: {\n          [route.id]: error,\n        },\n        statusCode: error.status,\n        loaderHeaders: {},\n        actionHeaders: {},\n      };\n    }\n\n    let result = await queryImpl(request, location, matches, requestContext);\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  async function queryRoute(\n    request: Request,\n    {\n      routeId,\n      requestContext,\n    }: { requestContext?: unknown; routeId?: string } = {}\n  ): Promise<any> {\n    let url = new URL(request.url);\n    let method = request.method.toLowerCase();\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      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      match\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    let routeData = [result.actionData, result.loaderData].find((v) => v);\n    return Object.values(routeData || {})[0];\n  }\n\n  async function queryImpl(\n    request: Request,\n    location: Location,\n    matches: AgnosticDataRouteMatch[],\n    requestContext: unknown,\n    routeMatch?: AgnosticDataRouteMatch\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          routeMatch != null\n        );\n        return result;\n      }\n\n      let result = await loadRouteData(\n        request,\n        matches,\n        requestContext,\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, we throw\n      // it to bail out and then return or throw here based on whether the user\n      // returned or threw\n      if (isQueryRouteResponse(e)) {\n        if (e.type === ResultType.error && !isRedirectResponse(e.response)) {\n          throw e.response;\n        }\n        return e.response;\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    isRouteRequest: boolean\n  ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n    let result: DataResult;\n\n    if (!actionMatch.route.action) {\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      result = await callLoaderOrAction(\n        \"action\",\n        request,\n        actionMatch,\n        matches,\n        basename,\n        true,\n        isRouteRequest,\n        requestContext\n      );\n\n      if (request.signal.aborted) {\n        let method = isRouteRequest ? \"queryRoute\" : \"query\";\n        throw new Error(`${method}() call aborted`);\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.status,\n        headers: {\n          Location: result.location,\n        },\n      });\n    }\n\n    if (isDeferredResult(result)) {\n      throw new Error(\"defer() is not supported in actions\");\n    }\n\n    if (isRouteRequest) {\n      // Note: This should only be non-Response values if we get here, since\n      // isRouteRequest should throw any Response received in callLoaderOrAction\n      if (isErrorResult(result)) {\n        throw result.error;\n      }\n\n      return {\n        matches: [actionMatch],\n        loaderData: {},\n        actionData: { [actionMatch.route.id]: result.data },\n        errors: null,\n        // Note: statusCode + headers are unused here since queryRoute will\n        // return the raw Response or value\n        statusCode: 200,\n        loaderHeaders: {},\n        actionHeaders: {},\n      };\n    }\n\n    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      let context = await loadRouteData(\n        request,\n        matches,\n        requestContext,\n        undefined,\n        {\n          [boundaryMatch.route.id]: result.error,\n        }\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          : 500,\n        actionData: null,\n        actionHeaders: {\n          ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n        },\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    let context = await loadRouteData(loaderRequest, matches, requestContext);\n\n    return {\n      ...context,\n      // action status codes take precedence over loader status codes\n      ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n      actionData: {\n        [actionMatch.route.id]: result.data,\n      },\n      actionHeaders: {\n        ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n      },\n    };\n  }\n\n  async function loadRouteData(\n    request: Request,\n    matches: AgnosticDataRouteMatch[],\n    requestContext: unknown,\n    routeMatch?: AgnosticDataRouteMatch,\n    pendingActionError?: RouteData\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 (isRouteRequest && !routeMatch?.route.loader) {\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      : getLoaderMatchesUntilBoundary(\n          matches,\n          Object.keys(pendingActionError || {})[0]\n        );\n    let matchesToLoad = requestMatches.filter((m) => m.route.loader);\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: pendingActionError || null,\n        statusCode: 200,\n        loaderHeaders: {},\n      };\n    }\n\n    let results = await Promise.all([\n      ...matchesToLoad.map((match) =>\n        callLoaderOrAction(\n          \"loader\",\n          request,\n          match,\n          matches,\n          basename,\n          true,\n          isRouteRequest,\n          requestContext\n        )\n      ),\n    ]);\n\n    if (request.signal.aborted) {\n      let method = isRouteRequest ? \"queryRoute\" : \"query\";\n      throw new Error(`${method}() call aborted`);\n    }\n\n    let executedLoaders = new Set<string>();\n    results.forEach((result, i) => {\n      executedLoaders.add(matchesToLoad[i].route.id);\n      // Can't do anything with these without the Remix side of things, so just\n      // cancel them for now\n      if (isDeferredResult(result)) {\n        result.deferredData.cancel();\n      }\n    });\n\n    // Process and commit output from loaders\n    let context = processRouteLoaderData(\n      matches,\n      matchesToLoad,\n      results,\n      pendingActionError\n    );\n\n    // Add a null for any non-loader matches for proper revalidation on the client\n    matches.forEach((match) => {\n      if (!executedLoaders.has(match.route.id)) {\n        context.loaderData[match.route.id] = null;\n      }\n    });\n\n    return {\n      ...context,\n      matches,\n    };\n  }\n\n  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: 500,\n    errors: {\n      [context._deepestRenderedBoundaryId || routes[0].id]: error,\n    },\n  };\n  return newContext;\n}\n\nfunction isSubmissionNavigation(\n  opts: RouterNavigateOptions\n): opts is SubmissionNavigateOptions {\n  return opts != null && \"formData\" in opts;\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  to: To,\n  opts?: RouterNavigateOptions,\n  isFetcher = false\n): {\n  path: string;\n  submission?: Submission;\n  error?: ErrorResponse;\n} {\n  let path = typeof to === \"string\" ? to : createPath(to);\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  // Create a Submission on non-GET navigations\n  let submission: Submission | undefined;\n  if (opts.formData) {\n    submission = {\n      formMethod: opts.formMethod || \"get\",\n      formAction: stripHashFromPath(path),\n      formEncType:\n        (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n      formData: opts.formData,\n    };\n\n    if (isMutationMethod(submission.formMethod)) {\n      return { path, submission };\n    }\n  }\n\n  // Flatten submission onto URLSearchParams for GET submissions\n  let parsedPath = parsePath(path);\n  try {\n    let searchParams = convertFormDataToSearchParams(opts.formData);\n    // Since fetcher GET submissions only run a single loader (as opposed to\n    // navigation GET submissions which run all loaders), we need to preserve\n    // any incoming ?index params\n    if (\n      isFetcher &&\n      parsedPath.search &&\n      hasNakedIndexQuery(parsedPath.search)\n    ) {\n      searchParams.append(\"index\", \"\");\n    }\n    parsedPath.search = `?${searchParams}`;\n  } catch (e) {\n    return {\n      path,\n      error: getInternalRouterError(400),\n    };\n  }\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  state: RouterState,\n  matches: AgnosticDataRouteMatch[],\n  submission: Submission | undefined,\n  location: Location,\n  isRevalidationRequired: boolean,\n  cancelledDeferredRoutes: string[],\n  cancelledFetcherLoads: string[],\n  pendingActionData?: RouteData,\n  pendingError?: RouteData,\n  fetchLoadMatches?: Map<string, FetchLoadMatch>\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n  let actionResult = pendingError\n    ? Object.values(pendingError)[0]\n    : pendingActionData\n    ? Object.values(pendingActionData)[0]\n    : undefined;\n\n  // Pick navigation matches that are net-new or qualify for revalidation\n  let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n  let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n  let navigationMatches = boundaryMatches.filter(\n    (match, index) =>\n      match.route.loader != null &&\n      (isNewLoader(state.loaderData, state.matches[index], match) ||\n        // If this route had a pending deferred cancelled it must be revalidated\n        cancelledDeferredRoutes.some((id) => id === match.route.id) ||\n        shouldRevalidateLoader(\n          state.location,\n          state.matches[index],\n          submission,\n          location,\n          match,\n          isRevalidationRequired,\n          actionResult\n        ))\n  );\n\n  // Pick fetcher.loads that need to be revalidated\n  let revalidatingFetchers: RevalidatingFetcher[] = [];\n  fetchLoadMatches &&\n    fetchLoadMatches.forEach(([href, match, fetchMatches], key) => {\n      // This fetcher was cancelled from a prior action submission - force reload\n      if (cancelledFetcherLoads.includes(key)) {\n        revalidatingFetchers.push([key, href, match, fetchMatches]);\n      } else if (isRevalidationRequired) {\n        let shouldRevalidate = shouldRevalidateLoader(\n          href,\n          match,\n          submission,\n          href,\n          match,\n          isRevalidationRequired,\n          actionResult\n        );\n        if (shouldRevalidate) {\n          revalidatingFetchers.push([key, href, match, fetchMatches]);\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 &&\n      currentPath.endsWith(\"*\") &&\n      currentMatch.params[\"*\"] !== match.params[\"*\"])\n  );\n}\n\nfunction shouldRevalidateLoader(\n  currentLocation: string | Location,\n  currentMatch: AgnosticDataRouteMatch,\n  submission: Submission | undefined,\n  location: string | Location,\n  match: AgnosticDataRouteMatch,\n  isRevalidationRequired: boolean,\n  actionResult: DataResult | undefined\n) {\n  let currentUrl = createClientSideURL(currentLocation);\n  let currentParams = currentMatch.params;\n  let nextUrl = createClientSideURL(location);\n  let nextParams = match.params;\n\n  // This is the default implementation as to 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  // Note that fetchers always provide the same current/next locations so the\n  // URL-based checks here don't apply to fetcher shouldRevalidate calls\n  let defaultShouldRevalidate =\n    isNewRouteInstance(currentMatch, match) ||\n    // Clicked the same link, resubmitted a GET form\n    currentUrl.toString() === nextUrl.toString() ||\n    // Search params affect all loaders\n    currentUrl.search !== nextUrl.search ||\n    // Forced revalidation due to submission, useRevalidate, or X-Remix-Revalidate\n    isRevalidationRequired;\n\n  if (match.route.shouldRevalidate) {\n    let routeChoice = match.route.shouldRevalidate({\n      currentUrl,\n      currentParams,\n      nextUrl,\n      nextParams,\n      ...submission,\n      actionResult,\n      defaultShouldRevalidate,\n    });\n    if (typeof routeChoice === \"boolean\") {\n      return routeChoice;\n    }\n  }\n\n  return defaultShouldRevalidate;\n}\n\nasync function callLoaderOrAction(\n  type: \"loader\" | \"action\",\n  request: Request,\n  match: AgnosticDataRouteMatch,\n  matches: AgnosticDataRouteMatch[],\n  basename = \"/\",\n  isStaticRequest: boolean = false,\n  isRouteRequest: boolean = false,\n  requestContext?: unknown\n): Promise<DataResult> {\n  let resultType;\n  let result;\n\n  // Setup a promise we can race against so that abort signals short circuit\n  let reject: () => void;\n  let abortPromise = new Promise((_, r) => (reject = r));\n  let onReject = () => reject();\n  request.signal.addEventListener(\"abort\", onReject);\n\n  try {\n    let handler = match.route[type];\n    invariant<Function>(\n      handler,\n      `Could not find the ${type} to run on the \"${match.route.id}\" route`\n    );\n\n    result = await Promise.race([\n      handler({ request, params: match.params, context: requestContext }),\n      abortPromise,\n    ]);\n\n    invariant(\n      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    resultType = ResultType.error;\n    result = e;\n  } finally {\n    request.signal.removeEventListener(\"abort\", onReject);\n  }\n\n  if (isResponse(result)) {\n    let status = result.status;\n\n    // Process redirects\n    if (redirectStatusCodes.has(status)) {\n      let location = result.headers.get(\"Location\");\n      invariant(\n        location,\n        \"Redirects returned/thrown from loaders/actions must have a Location header\"\n      );\n\n      let isAbsolute =\n        /^[a-z+]+:\\/\\//i.test(location) || location.startsWith(\"//\");\n\n      // Support relative routing in internal redirects\n      if (!isAbsolute) {\n        let activeMatches = matches.slice(0, matches.indexOf(match) + 1);\n        let routePathnames = getPathContributingMatches(activeMatches).map(\n          (match) => match.pathnameBase\n        );\n        let resolvedLocation = resolveTo(\n          location,\n          routePathnames,\n          new URL(request.url).pathname\n        );\n        invariant(\n          createPath(resolvedLocation),\n          `Unable to resolve redirect location: ${location}`\n        );\n\n        // Prepend the basename to the redirect location if we have one\n        if (basename) {\n          let path = resolvedLocation.pathname;\n          resolvedLocation.pathname =\n            path === \"/\" ? basename : joinPaths([basename, path]);\n        }\n\n        location = createPath(resolvedLocation);\n      }\n\n      // Don't process redirects in the router during static requests requests.\n      // Instead, throw the Response and let the server handle it with an HTTP\n      // redirect.  We also update the Location header in place in this flow so\n      // basename and relative routing is taken into account\n      if (isStaticRequest) {\n        result.headers.set(\"Location\", location);\n        throw result;\n      }\n\n      return {\n        type: ResultType.redirect,\n        status,\n        location,\n        revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null,\n      };\n    }\n\n    // For SSR single-route requests, we want to hand Responses back directly\n    // without unwrapping.  We do this with the QueryRouteResponse wrapper\n    // interface so we can know whether it was returned or thrown\n    if (isRouteRequest) {\n      // eslint-disable-next-line no-throw-literal\n      throw {\n        type: resultType || ResultType.data,\n        response: result,\n      };\n    }\n\n    let data: any;\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      data = await result.json();\n    } else {\n      data = await result.text();\n    }\n\n    if (resultType === ResultType.error) {\n      return {\n        type: resultType,\n        error: new ErrorResponse(status, result.statusText, data),\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 (resultType === ResultType.error) {\n    return { type: resultType, error: result };\n  }\n\n  if (result instanceof DeferredData) {\n    return { type: ResultType.deferred, deferredData: result };\n  }\n\n  return { type: ResultType.data, data: result };\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  location: string | Location,\n  signal: AbortSignal,\n  submission?: Submission\n): Request {\n  let url = createClientSideURL(stripHashFromPath(location)).toString();\n  let init: RequestInit = { signal };\n\n  if (submission && isMutationMethod(submission.formMethod)) {\n    let { formMethod, formEncType, formData } = submission;\n    init.method = formMethod.toUpperCase();\n    init.body =\n      formEncType === \"application/x-www-form-urlencoded\"\n        ? convertFormDataToSearchParams(formData)\n        : formData;\n  }\n\n  // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\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    invariant(\n      typeof value === \"string\",\n      'File inputs are not supported with encType \"application/x-www-form-urlencoded\", ' +\n        'please use \"multipart/form-data\" instead.'\n    );\n    searchParams.append(key, value);\n  }\n\n  return searchParams;\n}\n\nfunction processRouteLoaderData(\n  matches: AgnosticDataRouteMatch[],\n  matchesToLoad: AgnosticDataRouteMatch[],\n  results: DataResult[],\n  pendingError: RouteData | undefined,\n  activeDeferreds?: Map<string, DeferredData>\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\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      // Look upwards from the matched route for the closest ancestor\n      // error boundary, defaulting to the root match\n      let boundaryMatch = findNearestBoundary(matches, id);\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) {\n        error = Object.values(pendingError)[0];\n        pendingError = undefined;\n      }\n\n      errors = errors || {};\n\n      // Prefer higher error values if lower errors bubble to the same boundary\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\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 if (isDeferredResult(result)) {\n      activeDeferreds && activeDeferreds.set(id, result.deferredData);\n      loaderData[id] = result.deferredData.data;\n      // TODO: Add statusCode/headers once we wire up streaming in Remix\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 (\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    }\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) {\n    errors = pendingError;\n    loaderData[Object.keys(pendingError)[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  pendingError: RouteData | 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    pendingError,\n    activeDeferreds\n  );\n\n  // Process results from our revalidating fetchers\n  for (let index = 0; index < revalidatingFetchers.length; index++) {\n    let [key, , match] = 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 (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      throw new Error(\"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      throw new Error(\"Unhandled fetcher deferred data\");\n    } else {\n      let doneFetcher: FetcherStates[\"Idle\"] = {\n        state: \"idle\",\n        data: result.data,\n        formMethod: undefined,\n        formAction: undefined,\n        formEncType: undefined,\n        formData: undefined,\n        \" _hasFetcherDoneAnything \": true,\n      };\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) {\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\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 = 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  }: {\n    pathname?: string;\n    routeId?: string;\n    method?: string;\n  } = {}\n) {\n  let statusText = \"Unknown Server Error\";\n  let errorMessage = \"Unknown @remix-run/router error\";\n\n  if (status === 400) {\n    statusText = \"Bad Request\";\n    if (method && pathname && routeId) {\n      errorMessage =\n        `You made a ${method} request to \"${pathname}\" but ` +\n        `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n        `so there is no way to handle the request.`;\n    } else {\n      errorMessage = \"Cannot submit binary form data using GET\";\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 ErrorResponse(\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(results: DataResult[]): RedirectResult | undefined {\n  for (let i = results.length - 1; i >= 0; i--) {\n    let result = results[i];\n    if (isRedirectResult(result)) {\n      return result;\n    }\n  }\n}\n\nfunction stripHashFromPath(path: To) {\n  let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n  return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n  return (\n    a.pathname === b.pathname && a.search === b.search && a.hash !== b.hash\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\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 isQueryRouteResponse(obj: any): obj is QueryRouteResponse {\n  return (\n    obj &&\n    isResponse(obj.response) &&\n    (obj.type === ResultType.data || ResultType.error)\n  );\n}\n\nfunction isValidMethod(method: string): method is FormMethod {\n  return validRequestMethods.has(method as FormMethod);\n}\n\nfunction isMutationMethod(method?: string): method is MutationFormMethod {\n  return validMutationMethods.has(method as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n  currentMatches: AgnosticDataRouteMatch[],\n  matchesToLoad: AgnosticDataRouteMatch[],\n  results: DataResult[],\n  signal: AbortSignal,\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    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      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\n// Note: This should match the format exported by useMatches, so if you change\n// this please also change that :)  Eventually we'll DRY this up\nfunction createUseMatchesMatch(\n  match: AgnosticDataRouteMatch,\n  loaderData: RouteData\n): UseMatchesMatch {\n  let { route, pathname, params } = match;\n  return {\n    id: route.id,\n    pathname,\n    params,\n    data: loaderData[route.id] as unknown,\n    handle: route.handle as unknown,\n  };\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//#endregion\n"]},"metadata":{},"sourceType":"module","externalDependencies":[]}