{"ast":null,"code":"\"use strict\";\n\nexports.__esModule = true;\nexports.getDomainLocale = getDomainLocale;\nexports.addLocale = addLocale;\nexports.delLocale = delLocale;\nexports.hasBasePath = hasBasePath;\nexports.addBasePath = addBasePath;\nexports.delBasePath = delBasePath;\nexports.isLocalURL = isLocalURL;\nexports.interpolateAs = interpolateAs;\nexports.resolveHref = resolveHref;\nexports.default = void 0;\n\nvar _normalizeTrailingSlash = require(\"../../../client/normalize-trailing-slash\");\n\nvar _routeLoader = require(\"../../../client/route-loader\");\n\nvar _denormalizePagePath = require(\"../../server/denormalize-page-path\");\n\nvar _normalizeLocalePath = require(\"../i18n/normalize-locale-path\");\n\nvar _mitt = _interopRequireDefault(require(\"../mitt\"));\n\nvar _utils = require(\"../utils\");\n\nvar _isDynamic = require(\"./utils/is-dynamic\");\n\nvar _parseRelativeUrl = require(\"./utils/parse-relative-url\");\n\nvar _querystring = require(\"./utils/querystring\");\n\nvar _resolveRewrites = _interopRequireDefault(require(\"./utils/resolve-rewrites\"));\n\nvar _routeMatcher = require(\"./utils/route-matcher\");\n\nvar _routeRegex = require(\"./utils/route-regex\");\n\nfunction _interopRequireDefault(obj) {\n  return obj && obj.__esModule ? obj : {\n    default: obj\n  };\n}\n/* global __NEXT_DATA__ */\n// tslint:disable:no-console\n\n\nlet detectDomainLocale;\n\nif (process.env.__NEXT_I18N_SUPPORT) {\n  detectDomainLocale = require('../i18n/detect-domain-locale').detectDomainLocale;\n}\n\nconst basePath = process.env.__NEXT_ROUTER_BASEPATH || '';\n\nfunction buildCancellationError() {\n  return Object.assign(new Error('Route Cancelled'), {\n    cancelled: true\n  });\n}\n\nfunction addPathPrefix(path, prefix) {\n  return prefix && path.startsWith('/') ? path === '/' ? (0, _normalizeTrailingSlash.normalizePathTrailingSlash)(prefix) : `${prefix}${pathNoQueryHash(path) === '/' ? path.substring(1) : path}` : path;\n}\n\nfunction getDomainLocale(path, locale, locales, domainLocales) {\n  if (process.env.__NEXT_I18N_SUPPORT) {\n    locale = locale || (0, _normalizeLocalePath.normalizeLocalePath)(path, locales).detectedLocale;\n    const detectedDomain = detectDomainLocale(domainLocales, undefined, locale);\n\n    if (detectedDomain) {\n      return `http${detectedDomain.http ? '' : 's'}://${detectedDomain.domain}${basePath || ''}${locale === detectedDomain.defaultLocale ? '' : `/${locale}`}${path}`;\n    }\n\n    return false;\n  }\n\n  return false;\n}\n\nfunction addLocale(path, locale, defaultLocale) {\n  if (process.env.__NEXT_I18N_SUPPORT) {\n    return locale && locale !== defaultLocale && !path.startsWith('/' + locale + '/') && path !== '/' + locale ? addPathPrefix(path, '/' + locale) : path;\n  }\n\n  return path;\n}\n\nfunction delLocale(path, locale) {\n  if (process.env.__NEXT_I18N_SUPPORT) {\n    return locale && (path.startsWith('/' + locale + '/') || path === '/' + locale) ? path.substr(locale.length + 1) || '/' : path;\n  }\n\n  return path;\n}\n\nfunction pathNoQueryHash(path) {\n  const queryIndex = path.indexOf('?');\n  const hashIndex = path.indexOf('#');\n\n  if (queryIndex > -1 || hashIndex > -1) {\n    path = path.substring(0, queryIndex > -1 ? queryIndex : hashIndex);\n  }\n\n  return path;\n}\n\nfunction hasBasePath(path) {\n  path = pathNoQueryHash(path);\n  return path === basePath || path.startsWith(basePath + '/');\n}\n\nfunction addBasePath(path) {\n  // we only add the basepath on relative urls\n  return addPathPrefix(path, basePath);\n}\n\nfunction delBasePath(path) {\n  path = path.slice(basePath.length);\n  if (!path.startsWith('/')) path = `/${path}`;\n  return path;\n}\n/**\n* Detects whether a given url is routable by the Next.js router (browser only).\n*/\n\n\nfunction isLocalURL(url) {\n  // prevent a hydration mismatch on href for url with anchor refs\n  if (url.startsWith('/') || url.startsWith('#')) return true;\n\n  try {\n    // absolute urls can be local if they are on the same origin\n    const locationOrigin = (0, _utils.getLocationOrigin)();\n    const resolved = new URL(url, locationOrigin);\n    return resolved.origin === locationOrigin && hasBasePath(resolved.pathname);\n  } catch (_) {\n    return false;\n  }\n}\n\nfunction interpolateAs(route, asPathname, query) {\n  let interpolatedRoute = '';\n  const dynamicRegex = (0, _routeRegex.getRouteRegex)(route);\n  const dynamicGroups = dynamicRegex.groups;\n  const dynamicMatches = // Try to match the dynamic route against the asPath\n  (asPathname !== route ? (0, _routeMatcher.getRouteMatcher)(dynamicRegex)(asPathname) : '') || // Fall back to reading the values from the href\n  // TODO: should this take priority; also need to change in the router.\n  query;\n  interpolatedRoute = route;\n  const params = Object.keys(dynamicGroups);\n\n  if (!params.every(param => {\n    let value = dynamicMatches[param] || '';\n    const {\n      repeat,\n      optional\n    } = dynamicGroups[param]; // support single-level catch-all\n    // TODO: more robust handling for user-error (passing `/`)\n\n    let replaced = `[${repeat ? '...' : ''}${param}]`;\n\n    if (optional) {\n      replaced = `${!value ? '/' : ''}[${replaced}]`;\n    }\n\n    if (repeat && !Array.isArray(value)) value = [value];\n    return (optional || param in dynamicMatches) && ( // Interpolate group into data URL if present\n    interpolatedRoute = interpolatedRoute.replace(replaced, repeat ? value.map( // these values should be fully encoded instead of just\n    // path delimiter escaped since they are being inserted\n    // into the URL and we expect URL encoded segments\n    // when parsing dynamic route params\n    segment => encodeURIComponent(segment)).join('/') : encodeURIComponent(value)) || '/');\n  })) {\n    interpolatedRoute = ''; // did not satisfy all requirements\n    // n.b. We ignore this error because we handle warning for this case in\n    // development in the `<Link>` component directly.\n  }\n\n  return {\n    params,\n    result: interpolatedRoute\n  };\n}\n\nfunction omitParmsFromQuery(query, params) {\n  const filteredQuery = {};\n  Object.keys(query).forEach(key => {\n    if (!params.includes(key)) {\n      filteredQuery[key] = query[key];\n    }\n  });\n  return filteredQuery;\n}\n/**\n* Resolves a given hyperlink with a certain router state (basePath not included).\n* Preserves absolute urls.\n*/\n\n\nfunction resolveHref(currentPath, href, resolveAs) {\n  // we use a dummy base url for relative urls\n  const base = new URL(currentPath, 'http://n');\n  const urlAsString = typeof href === 'string' ? href : (0, _utils.formatWithValidation)(href); // Return because it cannot be routed by the Next.js router\n\n  if (!isLocalURL(urlAsString)) {\n    return resolveAs ? [urlAsString] : urlAsString;\n  }\n\n  try {\n    const finalUrl = new URL(urlAsString, base);\n    finalUrl.pathname = (0, _normalizeTrailingSlash.normalizePathTrailingSlash)(finalUrl.pathname);\n    let interpolatedAs = '';\n\n    if ((0, _isDynamic.isDynamicRoute)(finalUrl.pathname) && finalUrl.searchParams && resolveAs) {\n      const query = (0, _querystring.searchParamsToUrlQuery)(finalUrl.searchParams);\n      const {\n        result,\n        params\n      } = interpolateAs(finalUrl.pathname, finalUrl.pathname, query);\n\n      if (result) {\n        interpolatedAs = (0, _utils.formatWithValidation)({\n          pathname: result,\n          hash: finalUrl.hash,\n          query: omitParmsFromQuery(query, params)\n        });\n      }\n    } // if the origin didn't change, it means we received a relative href\n\n\n    const resolvedHref = finalUrl.origin === base.origin ? finalUrl.href.slice(finalUrl.origin.length) : finalUrl.href;\n    return resolveAs ? [resolvedHref, interpolatedAs || resolvedHref] : resolvedHref;\n  } catch (_) {\n    return resolveAs ? [urlAsString] : urlAsString;\n  }\n}\n\nfunction stripOrigin(url) {\n  const origin = (0, _utils.getLocationOrigin)();\n  return url.startsWith(origin) ? url.substring(origin.length) : url;\n}\n\nfunction prepareUrlAs(router, url, as) {\n  // If url and as provided as an object representation,\n  // we'll format them into the string version here.\n  let [resolvedHref, resolvedAs] = resolveHref(router.pathname, url, true);\n  const origin = (0, _utils.getLocationOrigin)();\n  const hrefHadOrigin = resolvedHref.startsWith(origin);\n  const asHadOrigin = resolvedAs && resolvedAs.startsWith(origin);\n  resolvedHref = stripOrigin(resolvedHref);\n  resolvedAs = resolvedAs ? stripOrigin(resolvedAs) : resolvedAs;\n  const preparedUrl = hrefHadOrigin ? resolvedHref : addBasePath(resolvedHref);\n  const preparedAs = as ? stripOrigin(resolveHref(router.pathname, as)) : resolvedAs || resolvedHref;\n  return {\n    url: preparedUrl,\n    as: asHadOrigin ? preparedAs : addBasePath(preparedAs)\n  };\n}\n\nfunction resolveDynamicRoute(parsedHref, pages, applyBasePath = true) {\n  const {\n    pathname\n  } = parsedHref;\n  const cleanPathname = (0, _normalizeTrailingSlash.removePathTrailingSlash)((0, _denormalizePagePath.denormalizePagePath)(applyBasePath ? delBasePath(pathname) : pathname));\n\n  if (cleanPathname === '/404' || cleanPathname === '/_error') {\n    return parsedHref;\n  } // handle resolving href for dynamic routes\n\n\n  if (!pages.includes(cleanPathname)) {\n    // eslint-disable-next-line array-callback-return\n    pages.some(page => {\n      if ((0, _isDynamic.isDynamicRoute)(page) && (0, _routeRegex.getRouteRegex)(page).re.test(cleanPathname)) {\n        parsedHref.pathname = applyBasePath ? addBasePath(page) : page;\n        return true;\n      }\n    });\n  }\n\n  parsedHref.pathname = (0, _normalizeTrailingSlash.removePathTrailingSlash)(parsedHref.pathname);\n  return parsedHref;\n}\n\nconst manualScrollRestoration = process.env.__NEXT_SCROLL_RESTORATION && false && 'scrollRestoration' in window.history && !!function () {\n  try {\n    let v = '__next'; // eslint-disable-next-line no-sequences\n\n    return sessionStorage.setItem(v, v), sessionStorage.removeItem(v), true;\n  } catch (n) {}\n}();\nconst SSG_DATA_NOT_FOUND = Symbol('SSG_DATA_NOT_FOUND');\n\nfunction fetchRetry(url, attempts) {\n  return fetch(url, {\n    // Cookies are required to be present for Next.js' SSG \"Preview Mode\".\n    // Cookies may also be required for `getServerSideProps`.\n    //\n    // > `fetch` won’t send cookies, unless you set the credentials init\n    // > option.\n    // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch\n    //\n    // > For maximum browser compatibility when it comes to sending &\n    // > receiving cookies, always supply the `credentials: 'same-origin'`\n    // > option instead of relying on the default.\n    // https://github.com/github/fetch#caveats\n    credentials: 'same-origin'\n  }).then(res => {\n    if (!res.ok) {\n      if (attempts > 1 && res.status >= 500) {\n        return fetchRetry(url, attempts - 1);\n      }\n\n      if (res.status === 404) {\n        return res.json().then(data => {\n          if (data.notFound) {\n            return {\n              notFound: SSG_DATA_NOT_FOUND\n            };\n          }\n\n          throw new Error(`Failed to load static props`);\n        });\n      }\n\n      throw new Error(`Failed to load static props`);\n    }\n\n    return res.json();\n  });\n}\n\nfunction fetchNextData(dataHref, isServerRender) {\n  return fetchRetry(dataHref, isServerRender ? 3 : 1).catch(err => {\n    // We should only trigger a server-side transition if this was caused\n    // on a client-side transition. Otherwise, we'd get into an infinite\n    // loop.\n    if (!isServerRender) {\n      (0, _routeLoader.markAssetError)(err);\n    }\n\n    throw err;\n  });\n}\n\nclass Router {\n  /**\n  * Map of all components loaded in `Router`\n  */\n  // Static Data Cache\n  // In-flight Server Data Requests, for deduping\n  constructor(_pathname, _query, _as, {\n    initialProps,\n    pageLoader,\n    App,\n    wrapApp,\n    Component,\n    err,\n    subscription,\n    isFallback,\n    locale,\n    locales,\n    defaultLocale,\n    domainLocales,\n    isPreview\n  }) {\n    this.route = void 0;\n    this.pathname = void 0;\n    this.query = void 0;\n    this.asPath = void 0;\n    this.basePath = void 0;\n    this.components = void 0;\n    this.sdc = {};\n    this.sdr = {};\n    this.sub = void 0;\n    this.clc = void 0;\n    this.pageLoader = void 0;\n    this._bps = void 0;\n    this.events = void 0;\n    this._wrapApp = void 0;\n    this.isSsr = void 0;\n    this.isFallback = void 0;\n    this._inFlightRoute = void 0;\n    this._shallow = void 0;\n    this.locale = void 0;\n    this.locales = void 0;\n    this.defaultLocale = void 0;\n    this.domainLocales = void 0;\n    this.isReady = void 0;\n    this.isPreview = void 0;\n    this.isLocaleDomain = void 0;\n    this._idx = 0;\n\n    this.onPopState = e => {\n      const state = e.state;\n\n      if (!state) {\n        // We get state as undefined for two reasons.\n        //  1. With older safari (< 8) and older chrome (< 34)\n        //  2. When the URL changed with #\n        //\n        // In the both cases, we don't need to proceed and change the route.\n        // (as it's already changed)\n        // But we can simply replace the state with the new changes.\n        // Actually, for (1) we don't need to nothing. But it's hard to detect that event.\n        // So, doing the following for (1) does no harm.\n        const {\n          pathname,\n          query\n        } = this;\n        this.changeState('replaceState', (0, _utils.formatWithValidation)({\n          pathname: addBasePath(pathname),\n          query\n        }), (0, _utils.getURL)());\n        return;\n      }\n\n      if (!state.__N) {\n        return;\n      }\n\n      let forcedScroll;\n      const {\n        url,\n        as,\n        options,\n        idx\n      } = state;\n\n      if (process.env.__NEXT_SCROLL_RESTORATION) {\n        if (manualScrollRestoration) {\n          if (this._idx !== idx) {\n            // Snapshot current scroll position:\n            try {\n              sessionStorage.setItem('__next_scroll_' + this._idx, JSON.stringify({\n                x: self.pageXOffset,\n                y: self.pageYOffset\n              }));\n            } catch (_unused) {} // Restore old scroll position:\n\n\n            try {\n              const v = sessionStorage.getItem('__next_scroll_' + idx);\n              forcedScroll = JSON.parse(v);\n            } catch (_unused2) {\n              forcedScroll = {\n                x: 0,\n                y: 0\n              };\n            }\n          }\n        }\n      }\n\n      this._idx = idx;\n      const {\n        pathname\n      } = (0, _parseRelativeUrl.parseRelativeUrl)(url); // Make sure we don't re-render on initial load,\n      // can be caused by navigating back from an external site\n\n      if (this.isSsr && as === this.asPath && pathname === this.pathname) {\n        return;\n      } // If the downstream application returns falsy, return.\n      // They will then be responsible for handling the event.\n\n\n      if (this._bps && !this._bps(state)) {\n        return;\n      }\n\n      this.change('replaceState', url, as, Object.assign({}, options, {\n        shallow: options.shallow && this._shallow,\n        locale: options.locale || this.defaultLocale\n      }), forcedScroll);\n    }; // represents the current component key\n\n\n    this.route = (0, _normalizeTrailingSlash.removePathTrailingSlash)(_pathname); // set up the component cache (by route keys)\n\n    this.components = {}; // We should not keep the cache, if there's an error\n    // Otherwise, this cause issues when when going back and\n    // come again to the errored page.\n\n    if (_pathname !== '/_error') {\n      this.components[this.route] = {\n        Component,\n        initial: true,\n        props: initialProps,\n        err,\n        __N_SSG: initialProps && initialProps.__N_SSG,\n        __N_SSP: initialProps && initialProps.__N_SSP\n      };\n    }\n\n    this.components['/_app'] = {\n      Component: App,\n      styleSheets: [\n        /* /_app does not need its stylesheets managed */\n      ]\n    }; // Backwards compat for Router.router.events\n    // TODO: Should be remove the following major version as it was never documented\n\n    this.events = Router.events;\n    this.pageLoader = pageLoader;\n    this.pathname = _pathname;\n    this.query = _query; // if auto prerendered and dynamic route wait to update asPath\n    // until after mount to prevent hydration mismatch\n\n    const autoExportDynamic = (0, _isDynamic.isDynamicRoute)(_pathname) && self.__NEXT_DATA__.autoExport;\n\n    this.asPath = autoExportDynamic ? _pathname : _as;\n    this.basePath = basePath;\n    this.sub = subscription;\n    this.clc = null;\n    this._wrapApp = wrapApp; // make sure to ignore extra popState in safari on navigating\n    // back from external site\n\n    this.isSsr = true;\n    this.isFallback = isFallback;\n    this.isReady = !!(self.__NEXT_DATA__.gssp || self.__NEXT_DATA__.gip || !autoExportDynamic && !self.location.search);\n    this.isPreview = !!isPreview;\n    this.isLocaleDomain = false;\n\n    if (process.env.__NEXT_I18N_SUPPORT) {\n      this.locale = locale;\n      this.locales = locales;\n      this.defaultLocale = defaultLocale;\n      this.domainLocales = domainLocales;\n      this.isLocaleDomain = !!detectDomainLocale(domainLocales, self.location.hostname);\n    }\n\n    if (false) {\n      // make sure \"as\" doesn't start with double slashes or else it can\n      // throw an error as it's considered invalid\n      if (_as.substr(0, 2) !== '//') {\n        // in order for `e.state` to work on the `onpopstate` event\n        // we have to register the initial route upon initialization\n        this.changeState('replaceState', (0, _utils.formatWithValidation)({\n          pathname: addBasePath(_pathname),\n          query: _query\n        }), (0, _utils.getURL)(), {\n          locale\n        });\n      }\n\n      window.addEventListener('popstate', this.onPopState); // enable custom scroll restoration handling when available\n      // otherwise fallback to browser's default handling\n\n      if (process.env.__NEXT_SCROLL_RESTORATION) {\n        if (manualScrollRestoration) {\n          window.history.scrollRestoration = 'manual';\n        }\n      }\n    }\n  }\n\n  reload() {\n    window.location.reload();\n  }\n  /**\n  * Go back in history\n  */\n\n\n  back() {\n    window.history.back();\n  }\n  /**\n  * Performs a `pushState` with arguments\n  * @param url of the route\n  * @param as masks `url` for the browser\n  * @param options object you can define `shallow` and other options\n  */\n\n\n  push(url, as, options = {}) {\n    if (process.env.__NEXT_SCROLL_RESTORATION) {\n      // TODO: remove in the future when we update history before route change\n      // is complete, as the popstate event should handle this capture.\n      if (manualScrollRestoration) {\n        try {\n          // Snapshot scroll position right before navigating to a new page:\n          sessionStorage.setItem('__next_scroll_' + this._idx, JSON.stringify({\n            x: self.pageXOffset,\n            y: self.pageYOffset\n          }));\n        } catch (_unused3) {}\n      }\n    }\n\n    ;\n    ({\n      url,\n      as\n    } = prepareUrlAs(this, url, as));\n    return this.change('pushState', url, as, options);\n  }\n  /**\n  * Performs a `replaceState` with arguments\n  * @param url of the route\n  * @param as masks `url` for the browser\n  * @param options object you can define `shallow` and other options\n  */\n\n\n  replace(url, as, options = {}) {\n    ;\n    ({\n      url,\n      as\n    } = prepareUrlAs(this, url, as));\n    return this.change('replaceState', url, as, options);\n  }\n\n  async change(method, url, as, options, forcedScroll) {\n    var _options$scroll;\n\n    if (!isLocalURL(url)) {\n      window.location.href = url;\n      return false;\n    } // for static pages with query params in the URL we delay\n    // marking the router ready until after the query is updated\n\n\n    if (options._h) {\n      this.isReady = true;\n    } // Default to scroll reset behavior unless explicitly specified to be\n    // `false`! This makes the behavior between using `Router#push` and a\n    // `<Link />` consistent.\n\n\n    options.scroll = !!((_options$scroll = options.scroll) != null ? _options$scroll : true);\n    let localeChange = options.locale !== this.locale;\n\n    if (process.env.__NEXT_I18N_SUPPORT) {\n      this.locale = options.locale === false ? this.defaultLocale : options.locale || this.locale;\n\n      if (typeof options.locale === 'undefined') {\n        options.locale = this.locale;\n      }\n\n      const parsedAs = (0, _parseRelativeUrl.parseRelativeUrl)(hasBasePath(as) ? delBasePath(as) : as);\n      const localePathResult = (0, _normalizeLocalePath.normalizeLocalePath)(parsedAs.pathname, this.locales);\n\n      if (localePathResult.detectedLocale) {\n        this.locale = localePathResult.detectedLocale;\n        parsedAs.pathname = addBasePath(parsedAs.pathname);\n        as = (0, _utils.formatWithValidation)(parsedAs);\n        url = addBasePath((0, _normalizeLocalePath.normalizeLocalePath)(hasBasePath(url) ? delBasePath(url) : url, this.locales).pathname);\n      }\n\n      let didNavigate = false; // we need to wrap this in the env check again since regenerator runtime\n      // moves this on its own due to the return\n\n      if (process.env.__NEXT_I18N_SUPPORT) {\n        var _this$locales; // if the locale isn't configured hard navigate to show 404 page\n\n\n        if (!((_this$locales = this.locales) != null && _this$locales.includes(this.locale))) {\n          parsedAs.pathname = addLocale(parsedAs.pathname, this.locale);\n          window.location.href = (0, _utils.formatWithValidation)(parsedAs); // this was previously a return but was removed in favor\n          // of better dead code elimination with regenerator runtime\n\n          didNavigate = true;\n        }\n      }\n\n      const detectedDomain = detectDomainLocale(this.domainLocales, undefined, this.locale); // we need to wrap this in the env check again since regenerator runtime\n      // moves this on its own due to the return\n\n      if (process.env.__NEXT_I18N_SUPPORT) {\n        // if we are navigating to a domain locale ensure we redirect to the\n        // correct domain\n        if (!didNavigate && detectedDomain && this.isLocaleDomain && self.location.hostname !== detectedDomain.domain) {\n          const asNoBasePath = delBasePath(as);\n          window.location.href = `http${detectedDomain.http ? '' : 's'}://${detectedDomain.domain}${addBasePath(`${this.locale === detectedDomain.defaultLocale ? '' : `/${this.locale}`}${asNoBasePath === '/' ? '' : asNoBasePath}` || '/')}`; // this was previously a return but was removed in favor\n          // of better dead code elimination with regenerator runtime\n\n          didNavigate = true;\n        }\n      }\n\n      if (didNavigate) {\n        return new Promise(() => {});\n      }\n    }\n\n    if (!options._h) {\n      this.isSsr = false;\n    } // marking route changes as a navigation start entry\n\n\n    if (_utils.ST) {\n      performance.mark('routeChange');\n    }\n\n    const {\n      shallow = false\n    } = options;\n    const routeProps = {\n      shallow\n    };\n\n    if (this._inFlightRoute) {\n      this.abortComponentLoad(this._inFlightRoute, routeProps);\n    }\n\n    as = addBasePath(addLocale(hasBasePath(as) ? delBasePath(as) : as, options.locale, this.defaultLocale));\n    const cleanedAs = delLocale(hasBasePath(as) ? delBasePath(as) : as, this.locale);\n    this._inFlightRoute = as; // If the url change is only related to a hash change\n    // We should not proceed. We should only change the state.\n    // WARNING: `_h` is an internal option for handing Next.js client-side\n    // hydration. Your app should _never_ use this property. It may change at\n    // any time without notice.\n\n    if (!options._h && this.onlyAHashChange(cleanedAs)) {\n      this.asPath = cleanedAs;\n      Router.events.emit('hashChangeStart', as, routeProps); // TODO: do we need the resolved href when only a hash change?\n\n      this.changeState(method, url, as, options);\n      this.scrollToHash(cleanedAs);\n      this.notify(this.components[this.route], null);\n      Router.events.emit('hashChangeComplete', as, routeProps);\n      return true;\n    }\n\n    let parsed = (0, _parseRelativeUrl.parseRelativeUrl)(url);\n    let {\n      pathname,\n      query\n    } = parsed; // The build manifest needs to be loaded before auto-static dynamic pages\n    // get their query parameters to allow ensuring they can be parsed properly\n    // when rewritten to\n\n    let pages, rewrites;\n\n    try {\n      pages = await this.pageLoader.getPageList();\n      ({\n        __rewrites: rewrites\n      } = await (0, _routeLoader.getClientBuildManifest)());\n    } catch (err) {\n      // If we fail to resolve the page list or client-build manifest, we must\n      // do a server-side transition:\n      window.location.href = as;\n      return false;\n    }\n\n    parsed = resolveDynamicRoute(parsed, pages);\n\n    if (parsed.pathname !== pathname) {\n      pathname = parsed.pathname;\n      url = (0, _utils.formatWithValidation)(parsed);\n    } // url and as should always be prefixed with basePath by this\n    // point by either next/link or router.push/replace so strip the\n    // basePath from the pathname to match the pages dir 1-to-1\n\n\n    pathname = pathname ? (0, _normalizeTrailingSlash.removePathTrailingSlash)(delBasePath(pathname)) : pathname; // If asked to change the current URL we should reload the current page\n    // (not location.reload() but reload getInitialProps and other Next.js stuffs)\n    // We also need to set the method = replaceState always\n    // as this should not go into the history (That's how browsers work)\n    // We should compare the new asPath to the current asPath, not the url\n\n    if (!this.urlIsNew(cleanedAs) && !localeChange) {\n      method = 'replaceState';\n    }\n\n    let route = (0, _normalizeTrailingSlash.removePathTrailingSlash)(pathname); // we need to resolve the as value using rewrites for dynamic SSG\n    // pages to allow building the data URL correctly\n\n    let resolvedAs = as;\n\n    if (process.env.__NEXT_HAS_REWRITES && as.startsWith('/')) {\n      const rewritesResult = (0, _resolveRewrites.default)(addBasePath(addLocale(delBasePath(as), this.locale)), pages, rewrites, query, p => resolveDynamicRoute({\n        pathname: p\n      }, pages).pathname, this.locales);\n      resolvedAs = rewritesResult.asPath;\n\n      if (rewritesResult.matchedPage && rewritesResult.resolvedHref) {\n        // if this directly matches a page we need to update the href to\n        // allow the correct page chunk to be loaded\n        route = rewritesResult.resolvedHref;\n        pathname = rewritesResult.resolvedHref;\n        parsed.pathname = pathname;\n        url = (0, _utils.formatWithValidation)(parsed);\n      }\n    }\n\n    if (!isLocalURL(as)) {\n      if (true) {\n        throw new Error(`Invalid href: \"${url}\" and as: \"${as}\", received relative href and external as` + `\\nSee more info: https://err.sh/next.js/invalid-relative-url-external-as`);\n      }\n\n      window.location.href = as;\n      return false;\n    }\n\n    resolvedAs = delLocale(delBasePath(resolvedAs), this.locale);\n\n    if ((0, _isDynamic.isDynamicRoute)(route)) {\n      const parsedAs = (0, _parseRelativeUrl.parseRelativeUrl)(resolvedAs);\n      const asPathname = parsedAs.pathname;\n      const routeRegex = (0, _routeRegex.getRouteRegex)(route);\n      const routeMatch = (0, _routeMatcher.getRouteMatcher)(routeRegex)(asPathname);\n      const shouldInterpolate = route === asPathname;\n      const interpolatedAs = shouldInterpolate ? interpolateAs(route, asPathname, query) : {};\n\n      if (!routeMatch || shouldInterpolate && !interpolatedAs.result) {\n        const missingParams = Object.keys(routeRegex.groups).filter(param => !query[param]);\n\n        if (missingParams.length > 0) {\n          if (true) {\n            console.warn(`${shouldInterpolate ? `Interpolating href` : `Mismatching \\`as\\` and \\`href\\``} failed to manually provide ` + `the params: ${missingParams.join(', ')} in the \\`href\\`'s \\`query\\``);\n          }\n\n          throw new Error((shouldInterpolate ? `The provided \\`href\\` (${url}) value is missing query values (${missingParams.join(', ')}) to be interpolated properly. ` : `The provided \\`as\\` value (${asPathname}) is incompatible with the \\`href\\` value (${route}). `) + `Read more: https://err.sh/vercel/next.js/${shouldInterpolate ? 'href-interpolation-failed' : 'incompatible-href-as'}`);\n        }\n      } else if (shouldInterpolate) {\n        as = (0, _utils.formatWithValidation)(Object.assign({}, parsedAs, {\n          pathname: interpolatedAs.result,\n          query: omitParmsFromQuery(query, interpolatedAs.params)\n        }));\n      } else {\n        // Merge params into `query`, overwriting any specified in search\n        Object.assign(query, routeMatch);\n      }\n    }\n\n    Router.events.emit('routeChangeStart', as, routeProps);\n\n    try {\n      var _self$__NEXT_DATA__$p, _self$__NEXT_DATA__$p2;\n\n      let routeInfo = await this.getRouteInfo(route, pathname, query, as, resolvedAs, routeProps);\n      let {\n        error,\n        props,\n        __N_SSG,\n        __N_SSP\n      } = routeInfo; // handle redirect on client-transition\n\n      if ((__N_SSG || __N_SSP) && props) {\n        if (props.pageProps && props.pageProps.__N_REDIRECT) {\n          const destination = props.pageProps.__N_REDIRECT; // check if destination is internal (resolves to a page) and attempt\n          // client-navigation if it is falling back to hard navigation if\n          // it's not\n\n          if (destination.startsWith('/')) {\n            const parsedHref = (0, _parseRelativeUrl.parseRelativeUrl)(destination);\n            resolveDynamicRoute(parsedHref, pages, false);\n\n            if (pages.includes(parsedHref.pathname)) {\n              const {\n                url: newUrl,\n                as: newAs\n              } = prepareUrlAs(this, destination, destination);\n              return this.change(method, newUrl, newAs, options);\n            }\n          }\n\n          window.location.href = destination;\n          return new Promise(() => {});\n        }\n\n        this.isPreview = !!props.__N_PREVIEW; // handle SSG data 404\n\n        if (props.notFound === SSG_DATA_NOT_FOUND) {\n          let notFoundRoute;\n\n          try {\n            await this.fetchComponent('/404');\n            notFoundRoute = '/404';\n          } catch (_) {\n            notFoundRoute = '/_error';\n          }\n\n          routeInfo = await this.getRouteInfo(notFoundRoute, notFoundRoute, query, as, resolvedAs, {\n            shallow: false\n          });\n        }\n      }\n\n      Router.events.emit('beforeHistoryChange', as, routeProps);\n      this.changeState(method, url, as, options);\n\n      if (true) {\n        const appComp = this.components['/_app'].Component;\n        window.next.isPrerendered = appComp.getInitialProps === appComp.origGetInitialProps && !routeInfo.Component.getInitialProps;\n      } // shallow routing is only allowed for same page URL changes.\n\n\n      const isValidShallowRoute = options.shallow && this.route === route;\n\n      if (options._h && pathname === '/_error' && ((_self$__NEXT_DATA__$p = self.__NEXT_DATA__.props) == null ? void 0 : (_self$__NEXT_DATA__$p2 = _self$__NEXT_DATA__$p.pageProps) == null ? void 0 : _self$__NEXT_DATA__$p2.statusCode) === 500 && props != null && props.pageProps) {\n        // ensure statusCode is still correct for static 500 page\n        // when updating query information\n        props.pageProps.statusCode = 500;\n      }\n\n      await this.set(route, pathname, query, cleanedAs, routeInfo, forcedScroll || (isValidShallowRoute || !options.scroll ? null : {\n        x: 0,\n        y: 0\n      })).catch(e => {\n        if (e.cancelled) error = error || e;else throw e;\n      });\n\n      if (error) {\n        Router.events.emit('routeChangeError', error, cleanedAs, routeProps);\n        throw error;\n      }\n\n      if (process.env.__NEXT_I18N_SUPPORT) {\n        if (this.locale) {\n          document.documentElement.lang = this.locale;\n        }\n      }\n\n      Router.events.emit('routeChangeComplete', as, routeProps);\n      return true;\n    } catch (err) {\n      if (err.cancelled) {\n        return false;\n      }\n\n      throw err;\n    }\n  }\n\n  changeState(method, url, as, options = {}) {\n    if (true) {\n      if (typeof window.history === 'undefined') {\n        console.error(`Warning: window.history is not available.`);\n        return;\n      }\n\n      if (typeof window.history[method] === 'undefined') {\n        console.error(`Warning: window.history.${method} is not available`);\n        return;\n      }\n    }\n\n    if (method !== 'pushState' || (0, _utils.getURL)() !== as) {\n      this._shallow = options.shallow;\n      window.history[method]({\n        url,\n        as,\n        options,\n        __N: true,\n        idx: this._idx = method !== 'pushState' ? this._idx : this._idx + 1\n      }, // Most browsers currently ignores this parameter, although they may use it in the future.\n      // Passing the empty string here should be safe against future changes to the method.\n      // https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState\n      '', as);\n    }\n  }\n\n  async handleRouteInfoError(err, pathname, query, as, routeProps, loadErrorFail) {\n    if (err.cancelled) {\n      // bubble up cancellation errors\n      throw err;\n    }\n\n    if ((0, _routeLoader.isAssetError)(err) || loadErrorFail) {\n      Router.events.emit('routeChangeError', err, as, routeProps); // If we can't load the page it could be one of following reasons\n      //  1. Page doesn't exists\n      //  2. Page does exist in a different zone\n      //  3. Internal error while loading the page\n      // So, doing a hard reload is the proper way to deal with this.\n\n      window.location.href = as; // Changing the URL doesn't block executing the current code path.\n      // So let's throw a cancellation error stop the routing logic.\n\n      throw buildCancellationError();\n    }\n\n    try {\n      let Component;\n      let styleSheets;\n      let props;\n\n      if (typeof Component === 'undefined' || typeof styleSheets === 'undefined') {\n        ;\n        ({\n          page: Component,\n          styleSheets\n        } = await this.fetchComponent('/_error'));\n      }\n\n      const routeInfo = {\n        props,\n        Component,\n        styleSheets,\n        err,\n        error: err\n      };\n\n      if (!routeInfo.props) {\n        try {\n          routeInfo.props = await this.getInitialProps(Component, {\n            err,\n            pathname,\n            query\n          });\n        } catch (gipErr) {\n          console.error('Error in error page `getInitialProps`: ', gipErr);\n          routeInfo.props = {};\n        }\n      }\n\n      return routeInfo;\n    } catch (routeInfoErr) {\n      return this.handleRouteInfoError(routeInfoErr, pathname, query, as, routeProps, true);\n    }\n  }\n\n  async getRouteInfo(route, pathname, query, as, resolvedAs, routeProps) {\n    try {\n      const existingRouteInfo = this.components[route];\n\n      if (routeProps.shallow && existingRouteInfo && this.route === route) {\n        return existingRouteInfo;\n      }\n\n      const cachedRouteInfo = existingRouteInfo && 'initial' in existingRouteInfo ? undefined : existingRouteInfo;\n      const routeInfo = cachedRouteInfo ? cachedRouteInfo : await this.fetchComponent(route).then(res => ({\n        Component: res.page,\n        styleSheets: res.styleSheets,\n        __N_SSG: res.mod.__N_SSG,\n        __N_SSP: res.mod.__N_SSP\n      }));\n      const {\n        Component,\n        __N_SSG,\n        __N_SSP\n      } = routeInfo;\n\n      if (true) {\n        const {\n          isValidElementType\n        } = require('react-is');\n\n        if (!isValidElementType(Component)) {\n          throw new Error(`The default export is not a React Component in page: \"${pathname}\"`);\n        }\n      }\n\n      let dataHref;\n\n      if (__N_SSG || __N_SSP) {\n        dataHref = this.pageLoader.getDataHref((0, _utils.formatWithValidation)({\n          pathname,\n          query\n        }), resolvedAs, __N_SSG, this.locale);\n      }\n\n      const props = await this._getData(() => __N_SSG ? this._getStaticData(dataHref) : __N_SSP ? this._getServerData(dataHref) : this.getInitialProps(Component, // we provide AppTree later so this needs to be `any`\n      {\n        pathname,\n        query,\n        asPath: as\n      }));\n      routeInfo.props = props;\n      this.components[route] = routeInfo;\n      return routeInfo;\n    } catch (err) {\n      return this.handleRouteInfoError(err, pathname, query, as, routeProps);\n    }\n  }\n\n  set(route, pathname, query, as, data, resetScroll) {\n    this.isFallback = false;\n    this.route = route;\n    this.pathname = pathname;\n    this.query = query;\n    this.asPath = as;\n    return this.notify(data, resetScroll);\n  }\n  /**\n  * Callback to execute before replacing router state\n  * @param cb callback to be executed\n  */\n\n\n  beforePopState(cb) {\n    this._bps = cb;\n  }\n\n  onlyAHashChange(as) {\n    if (!this.asPath) return false;\n    const [oldUrlNoHash, oldHash] = this.asPath.split('#');\n    const [newUrlNoHash, newHash] = as.split('#'); // Makes sure we scroll to the provided hash if the url/hash are the same\n\n    if (newHash && oldUrlNoHash === newUrlNoHash && oldHash === newHash) {\n      return true;\n    } // If the urls are change, there's more than a hash change\n\n\n    if (oldUrlNoHash !== newUrlNoHash) {\n      return false;\n    } // If the hash has changed, then it's a hash only change.\n    // This check is necessary to handle both the enter and\n    // leave hash === '' cases. The identity case falls through\n    // and is treated as a next reload.\n\n\n    return oldHash !== newHash;\n  }\n\n  scrollToHash(as) {\n    const [, hash] = as.split('#'); // Scroll to top if the hash is just `#` with no value or `#top`\n    // To mirror browsers\n\n    if (hash === '' || hash === 'top') {\n      window.scrollTo(0, 0);\n      return;\n    } // First we check if the element by id is found\n\n\n    const idEl = document.getElementById(hash);\n\n    if (idEl) {\n      idEl.scrollIntoView();\n      return;\n    } // If there's no element with the id, we check the `name` property\n    // To mirror browsers\n\n\n    const nameEl = document.getElementsByName(hash)[0];\n\n    if (nameEl) {\n      nameEl.scrollIntoView();\n    }\n  }\n\n  urlIsNew(asPath) {\n    return this.asPath !== asPath;\n  }\n  /**\n  * Prefetch page code, you may wait for the data during page rendering.\n  * This feature only works in production!\n  * @param url the href of prefetched page\n  * @param asPath the as path of the prefetched page\n  */\n\n\n  async prefetch(url, asPath = url, options = {}) {\n    let parsed = (0, _parseRelativeUrl.parseRelativeUrl)(url);\n    let {\n      pathname\n    } = parsed;\n\n    if (process.env.__NEXT_I18N_SUPPORT) {\n      if (options.locale === false) {\n        pathname = (0, _normalizeLocalePath.normalizeLocalePath)(pathname, this.locales).pathname;\n        parsed.pathname = pathname;\n        url = (0, _utils.formatWithValidation)(parsed);\n        let parsedAs = (0, _parseRelativeUrl.parseRelativeUrl)(asPath);\n        const localePathResult = (0, _normalizeLocalePath.normalizeLocalePath)(parsedAs.pathname, this.locales);\n        parsedAs.pathname = localePathResult.pathname;\n        options.locale = localePathResult.detectedLocale || this.defaultLocale;\n        asPath = (0, _utils.formatWithValidation)(parsedAs);\n      }\n    }\n\n    const pages = await this.pageLoader.getPageList();\n    parsed = resolveDynamicRoute(parsed, pages, false);\n\n    if (parsed.pathname !== pathname) {\n      pathname = parsed.pathname;\n      url = (0, _utils.formatWithValidation)(parsed);\n    }\n\n    let route = (0, _normalizeTrailingSlash.removePathTrailingSlash)(pathname);\n    let resolvedAs = asPath;\n\n    if (process.env.__NEXT_HAS_REWRITES && asPath.startsWith('/')) {\n      let rewrites;\n      ({\n        __rewrites: rewrites\n      } = await (0, _routeLoader.getClientBuildManifest)());\n      const rewritesResult = (0, _resolveRewrites.default)(addBasePath(addLocale(delBasePath(asPath), this.locale)), pages, rewrites, parsed.query, p => resolveDynamicRoute({\n        pathname: p\n      }, pages).pathname, this.locales);\n\n      if (rewritesResult.matchedPage && rewritesResult.resolvedHref) {\n        // if this directly matches a page we need to update the href to\n        // allow the correct page chunk to be loaded\n        route = rewritesResult.resolvedHref;\n        pathname = rewritesResult.resolvedHref;\n        parsed.pathname = pathname;\n        url = (0, _utils.formatWithValidation)(parsed);\n        resolvedAs = rewritesResult.asPath;\n      }\n    } // Prefetch is not supported in development mode because it would trigger on-demand-entries\n\n\n    if (true) {\n      return;\n    }\n\n    await Promise.all([this.pageLoader._isSsg(url).then(isSsg => {\n      return isSsg ? this._getStaticData(this.pageLoader.getDataHref(url, resolvedAs, true, typeof options.locale !== 'undefined' ? options.locale : this.locale)) : false;\n    }), this.pageLoader[options.priority ? 'loadPage' : 'prefetch'](route)]);\n  }\n\n  async fetchComponent(route) {\n    let cancelled = false;\n\n    const cancel = this.clc = () => {\n      cancelled = true;\n    };\n\n    const componentResult = await this.pageLoader.loadPage(route);\n\n    if (cancelled) {\n      const error = new Error(`Abort fetching component for route: \"${route}\"`);\n      error.cancelled = true;\n      throw error;\n    }\n\n    if (cancel === this.clc) {\n      this.clc = null;\n    }\n\n    return componentResult;\n  }\n\n  _getData(fn) {\n    let cancelled = false;\n\n    const cancel = () => {\n      cancelled = true;\n    };\n\n    this.clc = cancel;\n    return fn().then(data => {\n      if (cancel === this.clc) {\n        this.clc = null;\n      }\n\n      if (cancelled) {\n        const err = new Error('Loading initial props cancelled');\n        err.cancelled = true;\n        throw err;\n      }\n\n      return data;\n    });\n  }\n\n  _getStaticData(dataHref) {\n    const {\n      href: cacheKey\n    } = new URL(dataHref, window.location.href);\n\n    if (false && !this.isPreview && this.sdc[cacheKey]) {\n      return Promise.resolve(this.sdc[cacheKey]);\n    }\n\n    return fetchNextData(dataHref, this.isSsr).then(data => {\n      this.sdc[cacheKey] = data;\n      return data;\n    });\n  }\n\n  _getServerData(dataHref) {\n    const {\n      href: resourceKey\n    } = new URL(dataHref, window.location.href);\n\n    if (this.sdr[resourceKey]) {\n      return this.sdr[resourceKey];\n    }\n\n    return this.sdr[resourceKey] = fetchNextData(dataHref, this.isSsr).then(data => {\n      delete this.sdr[resourceKey];\n      return data;\n    }).catch(err => {\n      delete this.sdr[resourceKey];\n      throw err;\n    });\n  }\n\n  getInitialProps(Component, ctx) {\n    const {\n      Component: App\n    } = this.components['/_app'];\n\n    const AppTree = this._wrapApp(App);\n\n    ctx.AppTree = AppTree;\n    return (0, _utils.loadGetInitialProps)(App, {\n      AppTree,\n      Component,\n      router: this,\n      ctx\n    });\n  }\n\n  abortComponentLoad(as, routeProps) {\n    if (this.clc) {\n      Router.events.emit('routeChangeError', buildCancellationError(), as, routeProps);\n      this.clc();\n      this.clc = null;\n    }\n  }\n\n  notify(data, resetScroll) {\n    return this.sub(data, this.components['/_app'].Component, resetScroll);\n  }\n\n}\n\nexports.default = Router;\nRouter.events = (0, _mitt.default)();","map":{"version":3,"sources":["../../../../next-server/lib/router/router.ts"],"names":["process","detectDomainLocale","require","basePath","Object","cancelled","prefix","path","pathNoQueryHash","locale","detectedDomain","domain","addPathPrefix","queryIndex","hashIndex","url","locationOrigin","resolved","hasBasePath","interpolatedRoute","dynamicRegex","dynamicGroups","dynamicMatches","asPathname","params","param","value","replaced","repeat","Array","optional","segment","encodeURIComponent","result","filteredQuery","key","query","base","urlAsString","isLocalURL","resolveAs","finalUrl","interpolatedAs","interpolateAs","pathname","hash","omitParmsFromQuery","resolvedHref","origin","resolveHref","router","hrefHadOrigin","asHadOrigin","resolvedAs","stripOrigin","preparedUrl","addBasePath","preparedAs","as","applyBasePath","cleanPathname","delBasePath","pages","page","parsedHref","manualScrollRestoration","window","v","sessionStorage","SSG_DATA_NOT_FOUND","Symbol","credentials","res","attempts","fetchRetry","data","notFound","isServerRender","err","Router","route","asPath","components","sdc","sdr","sub","clc","pageLoader","_bps","events","_wrapApp","isSsr","isFallback","_inFlightRoute","_shallow","locales","defaultLocale","domainLocales","isReady","isPreview","isLocaleDomain","_idx","constructor","initial","props","__N_SSG","initialProps","__N_SSP","Component","styleSheets","autoExportDynamic","self","e","state","JSON","x","y","forcedScroll","shallow","options","reload","back","push","prepareUrlAs","replace","localeChange","parsedAs","localePathResult","didNavigate","addLocale","asNoBasePath","ST","performance","routeProps","cleanedAs","delLocale","parsed","__rewrites","resolveDynamicRoute","method","rewritesResult","p","routeRegex","routeMatch","shouldInterpolate","missingParams","console","routeInfo","destination","notFoundRoute","appComp","isValidShallowRoute","error","document","changeState","__N","idx","buildCancellationError","existingRouteInfo","cachedRouteInfo","isValidElementType","dataHref","set","beforePopState","onlyAHashChange","newHash","oldUrlNoHash","oldHash","scrollToHash","idEl","nameEl","urlIsNew","Promise","isSsg","cancel","componentResult","_getData","fn","_getStaticData","href","fetchNextData","_getServerData","getInitialProps","AppTree","ctx","abortComponentLoad","notify"],"mappings":";;;;;;;;;;;;;;AAKA,IAAA,uBAAA,GAAA,OAAA,CAAA,0CAAA,CAAA;;AAKA,IAAA,YAAA,GAAA,OAAA,CAAA,8BAAA,CAAA;;AAMA,IAAA,oBAAA,GAAA,OAAA,CAAA,oCAAA,CAAA;;AACA,IAAA,oBAAA,GAAA,OAAA,CAAA,+BAAA,CAAA;;AACA,IAAA,KAAA,GAAA,sBAAA,CAAA,OAAA,CAAA,SAAA,CAAA,CAAA;;AACA,IAAA,MAAA,GAAA,OAAA,CAAA,UAAA,CAAA;;AAUA,IAAA,UAAA,GAAA,OAAA,CAAA,oBAAA,CAAA;;AACA,IAAA,iBAAA,GAAA,OAAA,CAAA,4BAAA,CAAA;;AACA,IAAA,YAAA,GAAA,OAAA,CAAA,qBAAA,CAAA;;AACA,IAAA,gBAAA,GAAA,sBAAA,CAAA,OAAA,CAAA,0BAAA,CAAA,CAAA;;AACA,IAAA,aAAA,GAAA,OAAA,CAAA,uBAAA,CAAA;;AACA,IAAA,WAAA,GAAA,OAAA,CAAA,qBAAA,CAAA;;;;;;AAlCA;AAAA;AACA;;;AA+DA,IAAA,kBAAA;;AAEA,IAAIA,OAAO,CAAPA,GAAAA,CAAJ,mBAAA,EAAqC;AACnCC,EAAAA,kBAAkB,GAAGC,OAAO,CAAPA,8BAAO,CAAPA,CAArBD,kBAAAA;AAIF;;AAAA,MAAME,QAAQ,GAAIH,OAAO,CAAPA,GAAAA,CAAD,sBAACA,IA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AAM,CAANA,MAAAA,CAAAA,IAAAA,CAAAA,kBAAAA,EAEE8E,sBAFF9E,EAAAA,EAAAA,EAAAA,EAAAA,UAAAA;AAMA,WAAA,GAAA;AACA,WAAA,GAAA,GAAA,IAAA;AAEH;AAED2G;;AAAAA,EAAAA,MAAM,CAAA,IAAA,EAAA,WAAA,EAGW;AACf,WAAO,KAAA,GAAA,CAAA,IAAA,EAEL,KAAA,UAAA,CAAA,OAAA,EAFK,SAAA,EAAP,WAAO,CAAP;AAtoC8C;;AAAA;;;AAA7B3G,M,CAoCZU,MApCYV,GAoCU,CAAA,GAAA,KAAA,CAAA,OAAA,GApCVA","sourcesContent":["/* global __NEXT_DATA__ */\n// tslint:disable:no-console\nimport { ParsedUrlQuery } from 'querystring'\nimport { ComponentType } from 'react'\nimport { UrlObject } from 'url'\nimport {\n  normalizePathTrailingSlash,\n  removePathTrailingSlash,\n} from '../../../client/normalize-trailing-slash'\nimport { GoodPageCache, StyleSheetTuple } from '../../../client/page-loader'\nimport {\n  getClientBuildManifest,\n  isAssetError,\n  markAssetError,\n} from '../../../client/route-loader'\nimport { DomainLocales } from '../../server/config'\nimport { denormalizePagePath } from '../../server/denormalize-page-path'\nimport { normalizeLocalePath } from '../i18n/normalize-locale-path'\nimport mitt, { MittEmitter } from '../mitt'\nimport {\n  AppContextType,\n  formatWithValidation,\n  getLocationOrigin,\n  getURL,\n  loadGetInitialProps,\n  NextPageContext,\n  ST,\n  NEXT_DATA,\n} from '../utils'\nimport { isDynamicRoute } from './utils/is-dynamic'\nimport { parseRelativeUrl } from './utils/parse-relative-url'\nimport { searchParamsToUrlQuery } from './utils/querystring'\nimport resolveRewrites from './utils/resolve-rewrites'\nimport { getRouteMatcher } from './utils/route-matcher'\nimport { getRouteRegex } from './utils/route-regex'\n\ndeclare global {\n  interface Window {\n    /* prod */\n    __NEXT_DATA__: NEXT_DATA\n  }\n}\n\ninterface RouteProperties {\n  shallow: boolean\n}\n\ninterface TransitionOptions {\n  shallow?: boolean\n  locale?: string | false\n  scroll?: boolean\n}\n\ninterface NextHistoryState {\n  url: string\n  as: string\n  options: TransitionOptions\n}\n\ntype HistoryState =\n  | null\n  | { __N: false }\n  | ({ __N: true; idx: number } & NextHistoryState)\n\nlet detectDomainLocale: typeof import('../i18n/detect-domain-locale').detectDomainLocale\n\nif (process.env.__NEXT_I18N_SUPPORT) {\n  detectDomainLocale = require('../i18n/detect-domain-locale')\n    .detectDomainLocale\n}\n\nconst basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''\n\nfunction buildCancellationError() {\n  return Object.assign(new Error('Route Cancelled'), {\n    cancelled: true,\n  })\n}\n\nfunction addPathPrefix(path: string, prefix?: string) {\n  return prefix && path.startsWith('/')\n    ? path === '/'\n      ? normalizePathTrailingSlash(prefix)\n      : `${prefix}${pathNoQueryHash(path) === '/' ? path.substring(1) : path}`\n    : path\n}\n\nexport function getDomainLocale(\n  path: string,\n  locale?: string | false,\n  locales?: string[],\n  domainLocales?: DomainLocales\n) {\n  if (process.env.__NEXT_I18N_SUPPORT) {\n    locale = locale || normalizeLocalePath(path, locales).detectedLocale\n\n    const detectedDomain = detectDomainLocale(domainLocales, undefined, locale)\n\n    if (detectedDomain) {\n      return `http${detectedDomain.http ? '' : 's'}://${detectedDomain.domain}${\n        basePath || ''\n      }${locale === detectedDomain.defaultLocale ? '' : `/${locale}`}${path}`\n    }\n    return false\n  }\n\n  return false\n}\n\nexport function addLocale(\n  path: string,\n  locale?: string | false,\n  defaultLocale?: string\n) {\n  if (process.env.__NEXT_I18N_SUPPORT) {\n    return locale &&\n      locale !== defaultLocale &&\n      !path.startsWith('/' + locale + '/') &&\n      path !== '/' + locale\n      ? addPathPrefix(path, '/' + locale)\n      : path\n  }\n  return path\n}\n\nexport function delLocale(path: string, locale?: string) {\n  if (process.env.__NEXT_I18N_SUPPORT) {\n    return locale &&\n      (path.startsWith('/' + locale + '/') || path === '/' + locale)\n      ? path.substr(locale.length + 1) || '/'\n      : path\n  }\n  return path\n}\n\nfunction pathNoQueryHash(path: string) {\n  const queryIndex = path.indexOf('?')\n  const hashIndex = path.indexOf('#')\n\n  if (queryIndex > -1 || hashIndex > -1) {\n    path = path.substring(0, queryIndex > -1 ? queryIndex : hashIndex)\n  }\n  return path\n}\n\nexport function hasBasePath(path: string): boolean {\n  path = pathNoQueryHash(path)\n  return path === basePath || path.startsWith(basePath + '/')\n}\n\nexport function addBasePath(path: string): string {\n  // we only add the basepath on relative urls\n  return addPathPrefix(path, basePath)\n}\n\nexport function delBasePath(path: string): string {\n  path = path.slice(basePath.length)\n  if (!path.startsWith('/')) path = `/${path}`\n  return path\n}\n\n/**\n * Detects whether a given url is routable by the Next.js router (browser only).\n */\nexport function isLocalURL(url: string): boolean {\n  // prevent a hydration mismatch on href for url with anchor refs\n  if (url.startsWith('/') || url.startsWith('#')) return true\n  try {\n    // absolute urls can be local if they are on the same origin\n    const locationOrigin = getLocationOrigin()\n    const resolved = new URL(url, locationOrigin)\n    return resolved.origin === locationOrigin && hasBasePath(resolved.pathname)\n  } catch (_) {\n    return false\n  }\n}\n\ntype Url = UrlObject | string\n\nexport function interpolateAs(\n  route: string,\n  asPathname: string,\n  query: ParsedUrlQuery\n) {\n  let interpolatedRoute = ''\n\n  const dynamicRegex = getRouteRegex(route)\n  const dynamicGroups = dynamicRegex.groups\n  const dynamicMatches =\n    // Try to match the dynamic route against the asPath\n    (asPathname !== route ? getRouteMatcher(dynamicRegex)(asPathname) : '') ||\n    // Fall back to reading the values from the href\n    // TODO: should this take priority; also need to change in the router.\n    query\n\n  interpolatedRoute = route\n  const params = Object.keys(dynamicGroups)\n\n  if (\n    !params.every((param) => {\n      let value = dynamicMatches[param] || ''\n      const { repeat, optional } = dynamicGroups[param]\n\n      // support single-level catch-all\n      // TODO: more robust handling for user-error (passing `/`)\n      let replaced = `[${repeat ? '...' : ''}${param}]`\n      if (optional) {\n        replaced = `${!value ? '/' : ''}[${replaced}]`\n      }\n      if (repeat && !Array.isArray(value)) value = [value]\n\n      return (\n        (optional || param in dynamicMatches) &&\n        // Interpolate group into data URL if present\n        (interpolatedRoute =\n          interpolatedRoute!.replace(\n            replaced,\n            repeat\n              ? (value as string[])\n                  .map(\n                    // these values should be fully encoded instead of just\n                    // path delimiter escaped since they are being inserted\n                    // into the URL and we expect URL encoded segments\n                    // when parsing dynamic route params\n                    (segment) => encodeURIComponent(segment)\n                  )\n                  .join('/')\n              : encodeURIComponent(value as string)\n          ) || '/')\n      )\n    })\n  ) {\n    interpolatedRoute = '' // did not satisfy all requirements\n\n    // n.b. We ignore this error because we handle warning for this case in\n    // development in the `<Link>` component directly.\n  }\n  return {\n    params,\n    result: interpolatedRoute,\n  }\n}\n\nfunction omitParmsFromQuery(query: ParsedUrlQuery, params: string[]) {\n  const filteredQuery: ParsedUrlQuery = {}\n\n  Object.keys(query).forEach((key) => {\n    if (!params.includes(key)) {\n      filteredQuery[key] = query[key]\n    }\n  })\n  return filteredQuery\n}\n\n/**\n * Resolves a given hyperlink with a certain router state (basePath not included).\n * Preserves absolute urls.\n */\nexport function resolveHref(\n  currentPath: string,\n  href: Url,\n  resolveAs?: boolean\n): string {\n  // we use a dummy base url for relative urls\n  const base = new URL(currentPath, 'http://n')\n  const urlAsString =\n    typeof href === 'string' ? href : formatWithValidation(href)\n  // Return because it cannot be routed by the Next.js router\n  if (!isLocalURL(urlAsString)) {\n    return (resolveAs ? [urlAsString] : urlAsString) as string\n  }\n  try {\n    const finalUrl = new URL(urlAsString, base)\n    finalUrl.pathname = normalizePathTrailingSlash(finalUrl.pathname)\n    let interpolatedAs = ''\n\n    if (\n      isDynamicRoute(finalUrl.pathname) &&\n      finalUrl.searchParams &&\n      resolveAs\n    ) {\n      const query = searchParamsToUrlQuery(finalUrl.searchParams)\n\n      const { result, params } = interpolateAs(\n        finalUrl.pathname,\n        finalUrl.pathname,\n        query\n      )\n\n      if (result) {\n        interpolatedAs = formatWithValidation({\n          pathname: result,\n          hash: finalUrl.hash,\n          query: omitParmsFromQuery(query, params),\n        })\n      }\n    }\n\n    // if the origin didn't change, it means we received a relative href\n    const resolvedHref =\n      finalUrl.origin === base.origin\n        ? finalUrl.href.slice(finalUrl.origin.length)\n        : finalUrl.href\n\n    return (resolveAs\n      ? [resolvedHref, interpolatedAs || resolvedHref]\n      : resolvedHref) as string\n  } catch (_) {\n    return (resolveAs ? [urlAsString] : urlAsString) as string\n  }\n}\n\nfunction stripOrigin(url: string) {\n  const origin = getLocationOrigin()\n\n  return url.startsWith(origin) ? url.substring(origin.length) : url\n}\n\nfunction prepareUrlAs(router: NextRouter, url: Url, as?: Url) {\n  // If url and as provided as an object representation,\n  // we'll format them into the string version here.\n  let [resolvedHref, resolvedAs] = resolveHref(router.pathname, url, true)\n  const origin = getLocationOrigin()\n  const hrefHadOrigin = resolvedHref.startsWith(origin)\n  const asHadOrigin = resolvedAs && resolvedAs.startsWith(origin)\n\n  resolvedHref = stripOrigin(resolvedHref)\n  resolvedAs = resolvedAs ? stripOrigin(resolvedAs) : resolvedAs\n\n  const preparedUrl = hrefHadOrigin ? resolvedHref : addBasePath(resolvedHref)\n  const preparedAs = as\n    ? stripOrigin(resolveHref(router.pathname, as))\n    : resolvedAs || resolvedHref\n\n  return {\n    url: preparedUrl,\n    as: asHadOrigin ? preparedAs : addBasePath(preparedAs),\n  }\n}\n\nfunction resolveDynamicRoute(\n  parsedHref: UrlObject,\n  pages: string[],\n  applyBasePath = true\n) {\n  const { pathname } = parsedHref\n  const cleanPathname = removePathTrailingSlash(\n    denormalizePagePath(applyBasePath ? delBasePath(pathname!) : pathname!)\n  )\n\n  if (cleanPathname === '/404' || cleanPathname === '/_error') {\n    return parsedHref\n  }\n\n  // handle resolving href for dynamic routes\n  if (!pages.includes(cleanPathname!)) {\n    // eslint-disable-next-line array-callback-return\n    pages.some((page) => {\n      if (isDynamicRoute(page) && getRouteRegex(page).re.test(cleanPathname!)) {\n        parsedHref.pathname = applyBasePath ? addBasePath(page) : page\n        return true\n      }\n    })\n  }\n  parsedHref.pathname = removePathTrailingSlash(parsedHref.pathname!)\n  return parsedHref\n}\n\nexport type BaseRouter = {\n  route: string\n  pathname: string\n  query: ParsedUrlQuery\n  asPath: string\n  basePath: string\n  locale?: string\n  locales?: string[]\n  defaultLocale?: string\n  domainLocales?: DomainLocales\n  isLocaleDomain: boolean\n}\n\nexport type NextRouter = BaseRouter &\n  Pick<\n    Router,\n    | 'push'\n    | 'replace'\n    | 'reload'\n    | 'back'\n    | 'prefetch'\n    | 'beforePopState'\n    | 'events'\n    | 'isFallback'\n    | 'isReady'\n    | 'isPreview'\n  >\n\nexport type PrefetchOptions = {\n  priority?: boolean\n  locale?: string | false\n}\n\nexport type PrivateRouteInfo =\n  | (Omit<CompletePrivateRouteInfo, 'styleSheets'> & { initial: true })\n  | CompletePrivateRouteInfo\n\nexport type CompletePrivateRouteInfo = {\n  Component: ComponentType\n  styleSheets: StyleSheetTuple[]\n  __N_SSG?: boolean\n  __N_SSP?: boolean\n  props?: Record<string, any>\n  err?: Error\n  error?: any\n}\n\nexport type AppProps = Pick<CompletePrivateRouteInfo, 'Component' | 'err'> & {\n  router: Router\n} & Record<string, any>\nexport type AppComponent = ComponentType<AppProps>\n\ntype Subscription = (\n  data: PrivateRouteInfo,\n  App: AppComponent,\n  resetScroll: { x: number; y: number } | null\n) => Promise<void>\n\ntype BeforePopStateCallback = (state: NextHistoryState) => boolean\n\ntype ComponentLoadCancel = (() => void) | null\n\ntype HistoryMethod = 'replaceState' | 'pushState'\n\nconst manualScrollRestoration =\n  process.env.__NEXT_SCROLL_RESTORATION &&\n  typeof window !== 'undefined' &&\n  'scrollRestoration' in window.history &&\n  !!(function () {\n    try {\n      let v = '__next'\n      // eslint-disable-next-line no-sequences\n      return sessionStorage.setItem(v, v), sessionStorage.removeItem(v), true\n    } catch (n) {}\n  })()\n\nconst SSG_DATA_NOT_FOUND = Symbol('SSG_DATA_NOT_FOUND')\n\nfunction fetchRetry(url: string, attempts: number): Promise<any> {\n  return fetch(url, {\n    // Cookies are required to be present for Next.js' SSG \"Preview Mode\".\n    // Cookies may also be required for `getServerSideProps`.\n    //\n    // > `fetch` won’t send cookies, unless you set the credentials init\n    // > option.\n    // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch\n    //\n    // > For maximum browser compatibility when it comes to sending &\n    // > receiving cookies, always supply the `credentials: 'same-origin'`\n    // > option instead of relying on the default.\n    // https://github.com/github/fetch#caveats\n    credentials: 'same-origin',\n  }).then((res) => {\n    if (!res.ok) {\n      if (attempts > 1 && res.status >= 500) {\n        return fetchRetry(url, attempts - 1)\n      }\n      if (res.status === 404) {\n        return res.json().then((data) => {\n          if (data.notFound) {\n            return { notFound: SSG_DATA_NOT_FOUND }\n          }\n          throw new Error(`Failed to load static props`)\n        })\n      }\n      throw new Error(`Failed to load static props`)\n    }\n    return res.json()\n  })\n}\n\nfunction fetchNextData(dataHref: string, isServerRender: boolean) {\n  return fetchRetry(dataHref, isServerRender ? 3 : 1).catch((err: Error) => {\n    // We should only trigger a server-side transition if this was caused\n    // on a client-side transition. Otherwise, we'd get into an infinite\n    // loop.\n\n    if (!isServerRender) {\n      markAssetError(err)\n    }\n    throw err\n  })\n}\n\nexport default class Router implements BaseRouter {\n  route: string\n  pathname: string\n  query: ParsedUrlQuery\n  asPath: string\n  basePath: string\n\n  /**\n   * Map of all components loaded in `Router`\n   */\n  components: { [pathname: string]: PrivateRouteInfo }\n  // Static Data Cache\n  sdc: { [asPath: string]: object } = {}\n  // In-flight Server Data Requests, for deduping\n  sdr: { [asPath: string]: Promise<object> } = {}\n\n  sub: Subscription\n  clc: ComponentLoadCancel\n  pageLoader: any\n  _bps: BeforePopStateCallback | undefined\n  events: MittEmitter\n  _wrapApp: (App: AppComponent) => any\n  isSsr: boolean\n  isFallback: boolean\n  _inFlightRoute?: string\n  _shallow?: boolean\n  locale?: string\n  locales?: string[]\n  defaultLocale?: string\n  domainLocales?: DomainLocales\n  isReady: boolean\n  isPreview: boolean\n  isLocaleDomain: boolean\n\n  private _idx: number = 0\n\n  static events: MittEmitter = mitt()\n\n  constructor(\n    pathname: string,\n    query: ParsedUrlQuery,\n    as: string,\n    {\n      initialProps,\n      pageLoader,\n      App,\n      wrapApp,\n      Component,\n      err,\n      subscription,\n      isFallback,\n      locale,\n      locales,\n      defaultLocale,\n      domainLocales,\n      isPreview,\n    }: {\n      subscription: Subscription\n      initialProps: any\n      pageLoader: any\n      Component: ComponentType\n      App: AppComponent\n      wrapApp: (App: AppComponent) => any\n      err?: Error\n      isFallback: boolean\n      locale?: string\n      locales?: string[]\n      defaultLocale?: string\n      domainLocales?: DomainLocales\n      isPreview?: boolean\n    }\n  ) {\n    // represents the current component key\n    this.route = removePathTrailingSlash(pathname)\n\n    // set up the component cache (by route keys)\n    this.components = {}\n    // We should not keep the cache, if there's an error\n    // Otherwise, this cause issues when when going back and\n    // come again to the errored page.\n    if (pathname !== '/_error') {\n      this.components[this.route] = {\n        Component,\n        initial: true,\n        props: initialProps,\n        err,\n        __N_SSG: initialProps && initialProps.__N_SSG,\n        __N_SSP: initialProps && initialProps.__N_SSP,\n      }\n    }\n\n    this.components['/_app'] = {\n      Component: App as ComponentType,\n      styleSheets: [\n        /* /_app does not need its stylesheets managed */\n      ],\n    }\n\n    // Backwards compat for Router.router.events\n    // TODO: Should be remove the following major version as it was never documented\n    this.events = Router.events\n\n    this.pageLoader = pageLoader\n    this.pathname = pathname\n    this.query = query\n    // if auto prerendered and dynamic route wait to update asPath\n    // until after mount to prevent hydration mismatch\n    const autoExportDynamic =\n      isDynamicRoute(pathname) && self.__NEXT_DATA__.autoExport\n\n    this.asPath = autoExportDynamic ? pathname : as\n    this.basePath = basePath\n    this.sub = subscription\n    this.clc = null\n    this._wrapApp = wrapApp\n    // make sure to ignore extra popState in safari on navigating\n    // back from external site\n    this.isSsr = true\n\n    this.isFallback = isFallback\n\n    this.isReady = !!(\n      self.__NEXT_DATA__.gssp ||\n      self.__NEXT_DATA__.gip ||\n      (!autoExportDynamic && !self.location.search)\n    )\n    this.isPreview = !!isPreview\n    this.isLocaleDomain = false\n\n    if (process.env.__NEXT_I18N_SUPPORT) {\n      this.locale = locale\n      this.locales = locales\n      this.defaultLocale = defaultLocale\n      this.domainLocales = domainLocales\n      this.isLocaleDomain = !!detectDomainLocale(\n        domainLocales,\n        self.location.hostname\n      )\n    }\n\n    if (typeof window !== 'undefined') {\n      // make sure \"as\" doesn't start with double slashes or else it can\n      // throw an error as it's considered invalid\n      if (as.substr(0, 2) !== '//') {\n        // in order for `e.state` to work on the `onpopstate` event\n        // we have to register the initial route upon initialization\n        this.changeState(\n          'replaceState',\n          formatWithValidation({ pathname: addBasePath(pathname), query }),\n          getURL(),\n          { locale }\n        )\n      }\n\n      window.addEventListener('popstate', this.onPopState)\n\n      // enable custom scroll restoration handling when available\n      // otherwise fallback to browser's default handling\n      if (process.env.__NEXT_SCROLL_RESTORATION) {\n        if (manualScrollRestoration) {\n          window.history.scrollRestoration = 'manual'\n        }\n      }\n    }\n  }\n\n  onPopState = (e: PopStateEvent): void => {\n    const state = e.state as HistoryState\n\n    if (!state) {\n      // We get state as undefined for two reasons.\n      //  1. With older safari (< 8) and older chrome (< 34)\n      //  2. When the URL changed with #\n      //\n      // In the both cases, we don't need to proceed and change the route.\n      // (as it's already changed)\n      // But we can simply replace the state with the new changes.\n      // Actually, for (1) we don't need to nothing. But it's hard to detect that event.\n      // So, doing the following for (1) does no harm.\n      const { pathname, query } = this\n      this.changeState(\n        'replaceState',\n        formatWithValidation({ pathname: addBasePath(pathname), query }),\n        getURL()\n      )\n      return\n    }\n\n    if (!state.__N) {\n      return\n    }\n\n    let forcedScroll: { x: number; y: number } | undefined\n    const { url, as, options, idx } = state\n    if (process.env.__NEXT_SCROLL_RESTORATION) {\n      if (manualScrollRestoration) {\n        if (this._idx !== idx) {\n          // Snapshot current scroll position:\n          try {\n            sessionStorage.setItem(\n              '__next_scroll_' + this._idx,\n              JSON.stringify({ x: self.pageXOffset, y: self.pageYOffset })\n            )\n          } catch {}\n\n          // Restore old scroll position:\n          try {\n            const v = sessionStorage.getItem('__next_scroll_' + idx)\n            forcedScroll = JSON.parse(v!)\n          } catch {\n            forcedScroll = { x: 0, y: 0 }\n          }\n        }\n      }\n    }\n    this._idx = idx\n\n    const { pathname } = parseRelativeUrl(url)\n\n    // Make sure we don't re-render on initial load,\n    // can be caused by navigating back from an external site\n    if (this.isSsr && as === this.asPath && pathname === this.pathname) {\n      return\n    }\n\n    // If the downstream application returns falsy, return.\n    // They will then be responsible for handling the event.\n    if (this._bps && !this._bps(state)) {\n      return\n    }\n\n    this.change(\n      'replaceState',\n      url,\n      as,\n      Object.assign<{}, TransitionOptions, TransitionOptions>({}, options, {\n        shallow: options.shallow && this._shallow,\n        locale: options.locale || this.defaultLocale,\n      }),\n      forcedScroll\n    )\n  }\n\n  reload(): void {\n    window.location.reload()\n  }\n\n  /**\n   * Go back in history\n   */\n  back() {\n    window.history.back()\n  }\n\n  /**\n   * Performs a `pushState` with arguments\n   * @param url of the route\n   * @param as masks `url` for the browser\n   * @param options object you can define `shallow` and other options\n   */\n  push(url: Url, as?: Url, options: TransitionOptions = {}) {\n    if (process.env.__NEXT_SCROLL_RESTORATION) {\n      // TODO: remove in the future when we update history before route change\n      // is complete, as the popstate event should handle this capture.\n      if (manualScrollRestoration) {\n        try {\n          // Snapshot scroll position right before navigating to a new page:\n          sessionStorage.setItem(\n            '__next_scroll_' + this._idx,\n            JSON.stringify({ x: self.pageXOffset, y: self.pageYOffset })\n          )\n        } catch {}\n      }\n    }\n    ;({ url, as } = prepareUrlAs(this, url, as))\n    return this.change('pushState', url, as, options)\n  }\n\n  /**\n   * Performs a `replaceState` with arguments\n   * @param url of the route\n   * @param as masks `url` for the browser\n   * @param options object you can define `shallow` and other options\n   */\n  replace(url: Url, as?: Url, options: TransitionOptions = {}) {\n    ;({ url, as } = prepareUrlAs(this, url, as))\n    return this.change('replaceState', url, as, options)\n  }\n\n  private async change(\n    method: HistoryMethod,\n    url: string,\n    as: string,\n    options: TransitionOptions,\n    forcedScroll?: { x: number; y: number }\n  ): Promise<boolean> {\n    if (!isLocalURL(url)) {\n      window.location.href = url\n      return false\n    }\n\n    // for static pages with query params in the URL we delay\n    // marking the router ready until after the query is updated\n    if ((options as any)._h) {\n      this.isReady = true\n    }\n\n    // Default to scroll reset behavior unless explicitly specified to be\n    // `false`! This makes the behavior between using `Router#push` and a\n    // `<Link />` consistent.\n    options.scroll = !!(options.scroll ?? true)\n\n    let localeChange = options.locale !== this.locale\n\n    if (process.env.__NEXT_I18N_SUPPORT) {\n      this.locale =\n        options.locale === false\n          ? this.defaultLocale\n          : options.locale || this.locale\n\n      if (typeof options.locale === 'undefined') {\n        options.locale = this.locale\n      }\n\n      const parsedAs = parseRelativeUrl(hasBasePath(as) ? delBasePath(as) : as)\n      const localePathResult = normalizeLocalePath(\n        parsedAs.pathname,\n        this.locales\n      )\n\n      if (localePathResult.detectedLocale) {\n        this.locale = localePathResult.detectedLocale\n        parsedAs.pathname = addBasePath(parsedAs.pathname)\n        as = formatWithValidation(parsedAs)\n        url = addBasePath(\n          normalizeLocalePath(\n            hasBasePath(url) ? delBasePath(url) : url,\n            this.locales\n          ).pathname\n        )\n      }\n      let didNavigate = false\n\n      // we need to wrap this in the env check again since regenerator runtime\n      // moves this on its own due to the return\n      if (process.env.__NEXT_I18N_SUPPORT) {\n        // if the locale isn't configured hard navigate to show 404 page\n        if (!this.locales?.includes(this.locale!)) {\n          parsedAs.pathname = addLocale(parsedAs.pathname, this.locale)\n          window.location.href = formatWithValidation(parsedAs)\n          // this was previously a return but was removed in favor\n          // of better dead code elimination with regenerator runtime\n          didNavigate = true\n        }\n      }\n\n      const detectedDomain = detectDomainLocale(\n        this.domainLocales,\n        undefined,\n        this.locale\n      )\n\n      // we need to wrap this in the env check again since regenerator runtime\n      // moves this on its own due to the return\n      if (process.env.__NEXT_I18N_SUPPORT) {\n        // if we are navigating to a domain locale ensure we redirect to the\n        // correct domain\n        if (\n          !didNavigate &&\n          detectedDomain &&\n          this.isLocaleDomain &&\n          self.location.hostname !== detectedDomain.domain\n        ) {\n          const asNoBasePath = delBasePath(as)\n          window.location.href = `http${detectedDomain.http ? '' : 's'}://${\n            detectedDomain.domain\n          }${addBasePath(\n            `${\n              this.locale === detectedDomain.defaultLocale\n                ? ''\n                : `/${this.locale}`\n            }${asNoBasePath === '/' ? '' : asNoBasePath}` || '/'\n          )}`\n          // this was previously a return but was removed in favor\n          // of better dead code elimination with regenerator runtime\n          didNavigate = true\n        }\n      }\n\n      if (didNavigate) {\n        return new Promise(() => {})\n      }\n    }\n\n    if (!(options as any)._h) {\n      this.isSsr = false\n    }\n    // marking route changes as a navigation start entry\n    if (ST) {\n      performance.mark('routeChange')\n    }\n\n    const { shallow = false } = options\n    const routeProps = { shallow }\n\n    if (this._inFlightRoute) {\n      this.abortComponentLoad(this._inFlightRoute, routeProps)\n    }\n\n    as = addBasePath(\n      addLocale(\n        hasBasePath(as) ? delBasePath(as) : as,\n        options.locale,\n        this.defaultLocale\n      )\n    )\n    const cleanedAs = delLocale(\n      hasBasePath(as) ? delBasePath(as) : as,\n      this.locale\n    )\n    this._inFlightRoute = as\n\n    // If the url change is only related to a hash change\n    // We should not proceed. We should only change the state.\n\n    // WARNING: `_h` is an internal option for handing Next.js client-side\n    // hydration. Your app should _never_ use this property. It may change at\n    // any time without notice.\n    if (!(options as any)._h && this.onlyAHashChange(cleanedAs)) {\n      this.asPath = cleanedAs\n      Router.events.emit('hashChangeStart', as, routeProps)\n      // TODO: do we need the resolved href when only a hash change?\n      this.changeState(method, url, as, options)\n      this.scrollToHash(cleanedAs)\n      this.notify(this.components[this.route], null)\n      Router.events.emit('hashChangeComplete', as, routeProps)\n      return true\n    }\n\n    let parsed = parseRelativeUrl(url)\n    let { pathname, query } = parsed\n\n    // The build manifest needs to be loaded before auto-static dynamic pages\n    // get their query parameters to allow ensuring they can be parsed properly\n    // when rewritten to\n    let pages: any, rewrites: any\n    try {\n      pages = await this.pageLoader.getPageList()\n      ;({ __rewrites: rewrites } = await getClientBuildManifest())\n    } catch (err) {\n      // If we fail to resolve the page list or client-build manifest, we must\n      // do a server-side transition:\n      window.location.href = as\n      return false\n    }\n\n    parsed = resolveDynamicRoute(parsed, pages) as typeof parsed\n\n    if (parsed.pathname !== pathname) {\n      pathname = parsed.pathname\n      url = formatWithValidation(parsed)\n    }\n\n    // url and as should always be prefixed with basePath by this\n    // point by either next/link or router.push/replace so strip the\n    // basePath from the pathname to match the pages dir 1-to-1\n    pathname = pathname\n      ? removePathTrailingSlash(delBasePath(pathname))\n      : pathname\n\n    // If asked to change the current URL we should reload the current page\n    // (not location.reload() but reload getInitialProps and other Next.js stuffs)\n    // We also need to set the method = replaceState always\n    // as this should not go into the history (That's how browsers work)\n    // We should compare the new asPath to the current asPath, not the url\n    if (!this.urlIsNew(cleanedAs) && !localeChange) {\n      method = 'replaceState'\n    }\n\n    let route = removePathTrailingSlash(pathname)\n\n    // we need to resolve the as value using rewrites for dynamic SSG\n    // pages to allow building the data URL correctly\n    let resolvedAs = as\n\n    if (process.env.__NEXT_HAS_REWRITES && as.startsWith('/')) {\n      const rewritesResult = resolveRewrites(\n        addBasePath(addLocale(delBasePath(as), this.locale)),\n        pages,\n        rewrites,\n        query,\n        (p: string) => resolveDynamicRoute({ pathname: p }, pages).pathname!,\n        this.locales\n      )\n      resolvedAs = rewritesResult.asPath\n\n      if (rewritesResult.matchedPage && rewritesResult.resolvedHref) {\n        // if this directly matches a page we need to update the href to\n        // allow the correct page chunk to be loaded\n        route = rewritesResult.resolvedHref\n        pathname = rewritesResult.resolvedHref\n        parsed.pathname = pathname\n        url = formatWithValidation(parsed)\n      }\n    }\n\n    if (!isLocalURL(as)) {\n      if (process.env.NODE_ENV !== 'production') {\n        throw new Error(\n          `Invalid href: \"${url}\" and as: \"${as}\", received relative href and external as` +\n            `\\nSee more info: https://err.sh/next.js/invalid-relative-url-external-as`\n        )\n      }\n\n      window.location.href = as\n      return false\n    }\n\n    resolvedAs = delLocale(delBasePath(resolvedAs), this.locale)\n\n    if (isDynamicRoute(route)) {\n      const parsedAs = parseRelativeUrl(resolvedAs)\n      const asPathname = parsedAs.pathname\n\n      const routeRegex = getRouteRegex(route)\n      const routeMatch = getRouteMatcher(routeRegex)(asPathname)\n      const shouldInterpolate = route === asPathname\n      const interpolatedAs = shouldInterpolate\n        ? interpolateAs(route, asPathname, query)\n        : ({} as { result: undefined; params: undefined })\n\n      if (!routeMatch || (shouldInterpolate && !interpolatedAs.result)) {\n        const missingParams = Object.keys(routeRegex.groups).filter(\n          (param) => !query[param]\n        )\n\n        if (missingParams.length > 0) {\n          if (process.env.NODE_ENV !== 'production') {\n            console.warn(\n              `${\n                shouldInterpolate\n                  ? `Interpolating href`\n                  : `Mismatching \\`as\\` and \\`href\\``\n              } failed to manually provide ` +\n                `the params: ${missingParams.join(\n                  ', '\n                )} in the \\`href\\`'s \\`query\\``\n            )\n          }\n\n          throw new Error(\n            (shouldInterpolate\n              ? `The provided \\`href\\` (${url}) value is missing query values (${missingParams.join(\n                  ', '\n                )}) to be interpolated properly. `\n              : `The provided \\`as\\` value (${asPathname}) is incompatible with the \\`href\\` value (${route}). `) +\n              `Read more: https://err.sh/vercel/next.js/${\n                shouldInterpolate\n                  ? 'href-interpolation-failed'\n                  : 'incompatible-href-as'\n              }`\n          )\n        }\n      } else if (shouldInterpolate) {\n        as = formatWithValidation(\n          Object.assign({}, parsedAs, {\n            pathname: interpolatedAs.result,\n            query: omitParmsFromQuery(query, interpolatedAs.params!),\n          })\n        )\n      } else {\n        // Merge params into `query`, overwriting any specified in search\n        Object.assign(query, routeMatch)\n      }\n    }\n\n    Router.events.emit('routeChangeStart', as, routeProps)\n\n    try {\n      let routeInfo = await this.getRouteInfo(\n        route,\n        pathname,\n        query,\n        as,\n        resolvedAs,\n        routeProps\n      )\n      let { error, props, __N_SSG, __N_SSP } = routeInfo\n\n      // handle redirect on client-transition\n      if ((__N_SSG || __N_SSP) && props) {\n        if ((props as any).pageProps && (props as any).pageProps.__N_REDIRECT) {\n          const destination = (props as any).pageProps.__N_REDIRECT\n\n          // check if destination is internal (resolves to a page) and attempt\n          // client-navigation if it is falling back to hard navigation if\n          // it's not\n          if (destination.startsWith('/')) {\n            const parsedHref = parseRelativeUrl(destination)\n            resolveDynamicRoute(parsedHref, pages, false)\n\n            if (pages.includes(parsedHref.pathname)) {\n              const { url: newUrl, as: newAs } = prepareUrlAs(\n                this,\n                destination,\n                destination\n              )\n              return this.change(method, newUrl, newAs, options)\n            }\n          }\n\n          window.location.href = destination\n          return new Promise(() => {})\n        }\n\n        this.isPreview = !!props.__N_PREVIEW\n\n        // handle SSG data 404\n        if (props.notFound === SSG_DATA_NOT_FOUND) {\n          let notFoundRoute\n\n          try {\n            await this.fetchComponent('/404')\n            notFoundRoute = '/404'\n          } catch (_) {\n            notFoundRoute = '/_error'\n          }\n\n          routeInfo = await this.getRouteInfo(\n            notFoundRoute,\n            notFoundRoute,\n            query,\n            as,\n            resolvedAs,\n            { shallow: false }\n          )\n        }\n      }\n\n      Router.events.emit('beforeHistoryChange', as, routeProps)\n      this.changeState(method, url, as, options)\n\n      if (process.env.NODE_ENV !== 'production') {\n        const appComp: any = this.components['/_app'].Component\n        ;(window as any).next.isPrerendered =\n          appComp.getInitialProps === appComp.origGetInitialProps &&\n          !(routeInfo.Component as any).getInitialProps\n      }\n\n      // shallow routing is only allowed for same page URL changes.\n      const isValidShallowRoute = options.shallow && this.route === route\n\n      if (\n        (options as any)._h &&\n        pathname === '/_error' &&\n        self.__NEXT_DATA__.props?.pageProps?.statusCode === 500 &&\n        props?.pageProps\n      ) {\n        // ensure statusCode is still correct for static 500 page\n        // when updating query information\n        props.pageProps.statusCode = 500\n      }\n\n      await this.set(\n        route,\n        pathname!,\n        query,\n        cleanedAs,\n        routeInfo,\n        forcedScroll ||\n          (isValidShallowRoute || !options.scroll ? null : { x: 0, y: 0 })\n      ).catch((e) => {\n        if (e.cancelled) error = error || e\n        else throw e\n      })\n\n      if (error) {\n        Router.events.emit('routeChangeError', error, cleanedAs, routeProps)\n        throw error\n      }\n\n      if (process.env.__NEXT_I18N_SUPPORT) {\n        if (this.locale) {\n          document.documentElement.lang = this.locale\n        }\n      }\n      Router.events.emit('routeChangeComplete', as, routeProps)\n\n      return true\n    } catch (err) {\n      if (err.cancelled) {\n        return false\n      }\n      throw err\n    }\n  }\n\n  changeState(\n    method: HistoryMethod,\n    url: string,\n    as: string,\n    options: TransitionOptions = {}\n  ): void {\n    if (process.env.NODE_ENV !== 'production') {\n      if (typeof window.history === 'undefined') {\n        console.error(`Warning: window.history is not available.`)\n        return\n      }\n\n      if (typeof window.history[method] === 'undefined') {\n        console.error(`Warning: window.history.${method} is not available`)\n        return\n      }\n    }\n\n    if (method !== 'pushState' || getURL() !== as) {\n      this._shallow = options.shallow\n      window.history[method](\n        {\n          url,\n          as,\n          options,\n          __N: true,\n          idx: this._idx = method !== 'pushState' ? this._idx : this._idx + 1,\n        } as HistoryState,\n        // Most browsers currently ignores this parameter, although they may use it in the future.\n        // Passing the empty string here should be safe against future changes to the method.\n        // https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState\n        '',\n        as\n      )\n    }\n  }\n\n  async handleRouteInfoError(\n    err: Error & { code: any; cancelled: boolean },\n    pathname: string,\n    query: ParsedUrlQuery,\n    as: string,\n    routeProps: RouteProperties,\n    loadErrorFail?: boolean\n  ): Promise<CompletePrivateRouteInfo> {\n    if (err.cancelled) {\n      // bubble up cancellation errors\n      throw err\n    }\n\n    if (isAssetError(err) || loadErrorFail) {\n      Router.events.emit('routeChangeError', err, as, routeProps)\n\n      // If we can't load the page it could be one of following reasons\n      //  1. Page doesn't exists\n      //  2. Page does exist in a different zone\n      //  3. Internal error while loading the page\n\n      // So, doing a hard reload is the proper way to deal with this.\n      window.location.href = as\n\n      // Changing the URL doesn't block executing the current code path.\n      // So let's throw a cancellation error stop the routing logic.\n      throw buildCancellationError()\n    }\n\n    try {\n      let Component: ComponentType\n      let styleSheets: StyleSheetTuple[]\n      let props: Record<string, any> | undefined\n\n      if (\n        typeof Component! === 'undefined' ||\n        typeof styleSheets! === 'undefined'\n      ) {\n        ;({ page: Component, styleSheets } = await this.fetchComponent(\n          '/_error'\n        ))\n      }\n\n      const routeInfo: CompletePrivateRouteInfo = {\n        props,\n        Component,\n        styleSheets,\n        err,\n        error: err,\n      }\n\n      if (!routeInfo.props) {\n        try {\n          routeInfo.props = await this.getInitialProps(Component, {\n            err,\n            pathname,\n            query,\n          } as any)\n        } catch (gipErr) {\n          console.error('Error in error page `getInitialProps`: ', gipErr)\n          routeInfo.props = {}\n        }\n      }\n\n      return routeInfo\n    } catch (routeInfoErr) {\n      return this.handleRouteInfoError(\n        routeInfoErr,\n        pathname,\n        query,\n        as,\n        routeProps,\n        true\n      )\n    }\n  }\n\n  async getRouteInfo(\n    route: string,\n    pathname: string,\n    query: any,\n    as: string,\n    resolvedAs: string,\n    routeProps: RouteProperties\n  ): Promise<PrivateRouteInfo> {\n    try {\n      const existingRouteInfo: PrivateRouteInfo | undefined = this.components[\n        route\n      ]\n      if (routeProps.shallow && existingRouteInfo && this.route === route) {\n        return existingRouteInfo\n      }\n\n      const cachedRouteInfo: CompletePrivateRouteInfo | undefined =\n        existingRouteInfo && 'initial' in existingRouteInfo\n          ? undefined\n          : existingRouteInfo\n      const routeInfo: CompletePrivateRouteInfo = cachedRouteInfo\n        ? cachedRouteInfo\n        : await this.fetchComponent(route).then((res) => ({\n            Component: res.page,\n            styleSheets: res.styleSheets,\n            __N_SSG: res.mod.__N_SSG,\n            __N_SSP: res.mod.__N_SSP,\n          }))\n\n      const { Component, __N_SSG, __N_SSP } = routeInfo\n\n      if (process.env.NODE_ENV !== 'production') {\n        const { isValidElementType } = require('react-is')\n        if (!isValidElementType(Component)) {\n          throw new Error(\n            `The default export is not a React Component in page: \"${pathname}\"`\n          )\n        }\n      }\n\n      let dataHref: string | undefined\n\n      if (__N_SSG || __N_SSP) {\n        dataHref = this.pageLoader.getDataHref(\n          formatWithValidation({ pathname, query }),\n          resolvedAs,\n          __N_SSG,\n          this.locale\n        )\n      }\n\n      const props = await this._getData<CompletePrivateRouteInfo>(() =>\n        __N_SSG\n          ? this._getStaticData(dataHref!)\n          : __N_SSP\n          ? this._getServerData(dataHref!)\n          : this.getInitialProps(\n              Component,\n              // we provide AppTree later so this needs to be `any`\n              {\n                pathname,\n                query,\n                asPath: as,\n              } as any\n            )\n      )\n\n      routeInfo.props = props\n      this.components[route] = routeInfo\n      return routeInfo\n    } catch (err) {\n      return this.handleRouteInfoError(err, pathname, query, as, routeProps)\n    }\n  }\n\n  set(\n    route: string,\n    pathname: string,\n    query: ParsedUrlQuery,\n    as: string,\n    data: PrivateRouteInfo,\n    resetScroll: { x: number; y: number } | null\n  ): Promise<void> {\n    this.isFallback = false\n\n    this.route = route\n    this.pathname = pathname\n    this.query = query\n    this.asPath = as\n    return this.notify(data, resetScroll)\n  }\n\n  /**\n   * Callback to execute before replacing router state\n   * @param cb callback to be executed\n   */\n  beforePopState(cb: BeforePopStateCallback) {\n    this._bps = cb\n  }\n\n  onlyAHashChange(as: string): boolean {\n    if (!this.asPath) return false\n    const [oldUrlNoHash, oldHash] = this.asPath.split('#')\n    const [newUrlNoHash, newHash] = as.split('#')\n\n    // Makes sure we scroll to the provided hash if the url/hash are the same\n    if (newHash && oldUrlNoHash === newUrlNoHash && oldHash === newHash) {\n      return true\n    }\n\n    // If the urls are change, there's more than a hash change\n    if (oldUrlNoHash !== newUrlNoHash) {\n      return false\n    }\n\n    // If the hash has changed, then it's a hash only change.\n    // This check is necessary to handle both the enter and\n    // leave hash === '' cases. The identity case falls through\n    // and is treated as a next reload.\n    return oldHash !== newHash\n  }\n\n  scrollToHash(as: string): void {\n    const [, hash] = as.split('#')\n    // Scroll to top if the hash is just `#` with no value or `#top`\n    // To mirror browsers\n    if (hash === '' || hash === 'top') {\n      window.scrollTo(0, 0)\n      return\n    }\n\n    // First we check if the element by id is found\n    const idEl = document.getElementById(hash)\n    if (idEl) {\n      idEl.scrollIntoView()\n      return\n    }\n    // If there's no element with the id, we check the `name` property\n    // To mirror browsers\n    const nameEl = document.getElementsByName(hash)[0]\n    if (nameEl) {\n      nameEl.scrollIntoView()\n    }\n  }\n\n  urlIsNew(asPath: string): boolean {\n    return this.asPath !== asPath\n  }\n\n  /**\n   * Prefetch page code, you may wait for the data during page rendering.\n   * This feature only works in production!\n   * @param url the href of prefetched page\n   * @param asPath the as path of the prefetched page\n   */\n  async prefetch(\n    url: string,\n    asPath: string = url,\n    options: PrefetchOptions = {}\n  ): Promise<void> {\n    let parsed = parseRelativeUrl(url)\n\n    let { pathname } = parsed\n\n    if (process.env.__NEXT_I18N_SUPPORT) {\n      if (options.locale === false) {\n        pathname = normalizeLocalePath!(pathname, this.locales).pathname\n        parsed.pathname = pathname\n        url = formatWithValidation(parsed)\n\n        let parsedAs = parseRelativeUrl(asPath)\n        const localePathResult = normalizeLocalePath!(\n          parsedAs.pathname,\n          this.locales\n        )\n        parsedAs.pathname = localePathResult.pathname\n        options.locale = localePathResult.detectedLocale || this.defaultLocale\n        asPath = formatWithValidation(parsedAs)\n      }\n    }\n\n    const pages = await this.pageLoader.getPageList()\n\n    parsed = resolveDynamicRoute(parsed, pages, false) as typeof parsed\n\n    if (parsed.pathname !== pathname) {\n      pathname = parsed.pathname\n      url = formatWithValidation(parsed)\n    }\n    let route = removePathTrailingSlash(pathname)\n    let resolvedAs = asPath\n\n    if (process.env.__NEXT_HAS_REWRITES && asPath.startsWith('/')) {\n      let rewrites: any[]\n      ;({ __rewrites: rewrites } = await getClientBuildManifest())\n\n      const rewritesResult = resolveRewrites(\n        addBasePath(addLocale(delBasePath(asPath), this.locale)),\n        pages,\n        rewrites,\n        parsed.query,\n        (p: string) => resolveDynamicRoute({ pathname: p }, pages).pathname!,\n        this.locales\n      )\n\n      if (rewritesResult.matchedPage && rewritesResult.resolvedHref) {\n        // if this directly matches a page we need to update the href to\n        // allow the correct page chunk to be loaded\n        route = rewritesResult.resolvedHref\n        pathname = rewritesResult.resolvedHref\n        parsed.pathname = pathname\n        url = formatWithValidation(parsed)\n        resolvedAs = rewritesResult.asPath\n      }\n    }\n\n    // Prefetch is not supported in development mode because it would trigger on-demand-entries\n    if (process.env.NODE_ENV !== 'production') {\n      return\n    }\n\n    await Promise.all([\n      this.pageLoader._isSsg(url).then((isSsg: boolean) => {\n        return isSsg\n          ? this._getStaticData(\n              this.pageLoader.getDataHref(\n                url,\n                resolvedAs,\n                true,\n                typeof options.locale !== 'undefined'\n                  ? options.locale\n                  : this.locale\n              )\n            )\n          : false\n      }),\n      this.pageLoader[options.priority ? 'loadPage' : 'prefetch'](route),\n    ])\n  }\n\n  async fetchComponent(route: string): Promise<GoodPageCache> {\n    let cancelled = false\n    const cancel = (this.clc = () => {\n      cancelled = true\n    })\n\n    const componentResult = await this.pageLoader.loadPage(route)\n\n    if (cancelled) {\n      const error: any = new Error(\n        `Abort fetching component for route: \"${route}\"`\n      )\n      error.cancelled = true\n      throw error\n    }\n\n    if (cancel === this.clc) {\n      this.clc = null\n    }\n\n    return componentResult\n  }\n\n  _getData<T>(fn: () => Promise<T>): Promise<T> {\n    let cancelled = false\n    const cancel = () => {\n      cancelled = true\n    }\n    this.clc = cancel\n    return fn().then((data) => {\n      if (cancel === this.clc) {\n        this.clc = null\n      }\n\n      if (cancelled) {\n        const err: any = new Error('Loading initial props cancelled')\n        err.cancelled = true\n        throw err\n      }\n\n      return data\n    })\n  }\n\n  _getStaticData(dataHref: string): Promise<object> {\n    const { href: cacheKey } = new URL(dataHref, window.location.href)\n    if (\n      process.env.NODE_ENV === 'production' &&\n      !this.isPreview &&\n      this.sdc[cacheKey]\n    ) {\n      return Promise.resolve(this.sdc[cacheKey])\n    }\n    return fetchNextData(dataHref, this.isSsr).then((data) => {\n      this.sdc[cacheKey] = data\n      return data\n    })\n  }\n\n  _getServerData(dataHref: string): Promise<object> {\n    const { href: resourceKey } = new URL(dataHref, window.location.href)\n    if (this.sdr[resourceKey]) {\n      return this.sdr[resourceKey]\n    }\n    return (this.sdr[resourceKey] = fetchNextData(dataHref, this.isSsr)\n      .then((data) => {\n        delete this.sdr[resourceKey]\n        return data\n      })\n      .catch((err) => {\n        delete this.sdr[resourceKey]\n        throw err\n      }))\n  }\n\n  getInitialProps(\n    Component: ComponentType,\n    ctx: NextPageContext\n  ): Promise<any> {\n    const { Component: App } = this.components['/_app']\n    const AppTree = this._wrapApp(App as AppComponent)\n    ctx.AppTree = AppTree\n    return loadGetInitialProps<AppContextType<Router>>(App, {\n      AppTree,\n      Component,\n      router: this,\n      ctx,\n    })\n  }\n\n  abortComponentLoad(as: string, routeProps: RouteProperties): void {\n    if (this.clc) {\n      Router.events.emit(\n        'routeChangeError',\n        buildCancellationError(),\n        as,\n        routeProps\n      )\n      this.clc()\n      this.clc = null\n    }\n  }\n\n  notify(\n    data: PrivateRouteInfo,\n    resetScroll: { x: number; y: number } | null\n  ): Promise<void> {\n    return this.sub(\n      data,\n      this.components['/_app'].Component as AppComponent,\n      resetScroll\n    )\n  }\n}\n"]},"metadata":{},"sourceType":"script"}