{"version":3,"file":"server.runtime.prod.js","sources":["webpack://next/../../node_modules/.pnpm/react@19.3.0-canary-3f0b9e61-20260317/node_modules/react/cjs/react.production.js","webpack://next/../../node_modules/.pnpm/react@19.3.0-canary-3f0b9e61-20260317/node_modules/react/index.js","webpack://next/../next-env/dist/index.js","webpack://next/./dist/compiled/@edge-runtime/cookies/index.js","webpack://next/./dist/compiled/bytes/index.js","webpack://next/./dist/compiled/cookie/index.js","webpack://next/./dist/compiled/fresh/index.js","webpack://next/./dist/compiled/p-queue/index.js","webpack://next/./dist/compiled/path-to-regexp/index.js","webpack://next/./src/lib/format-server-error.ts","webpack://next/./src/server/node-environment-baseline.ts","webpack://next/./src/server/node-polyfill-crypto.ts","webpack://next/./src/shared/lib/isomorphic/path.js","webpack://next/./src/shared/lib/modern-browserslist-target.js","webpack://next/webpack/runtime/compat_get_default_export","webpack://next/webpack/runtime/define_property_getters","webpack://next/webpack/runtime/has_own_property","webpack://next/webpack/runtime/make_namespace_object","webpack://next/./src/server/patch-error-inspect.ts","webpack://next/./src/server/node-environment-extensions/web-crypto.tsx","webpack://next/./src/server/app-render/staged-rendering.ts","webpack://next/./src/server/node-environment-extensions/date.tsx","webpack://next/./src/server/lib/trace/constants.ts","webpack://next/./src/client/components/redirect-status-code.ts","webpack://next/./src/server/route-kind.ts","webpack://next/./src/server/response-cache/types.ts","webpack://next/./src/lib/picocolors.ts","webpack://next/./src/server/lib/lru-cache.ts","webpack://next/./src/server/lib/source-maps.ts","webpack://next/./src/server/lib/parse-stack.ts","webpack://next/./src/server/node-environment-extensions/error-inspect.tsx","webpack://next/./src/server/node-environment-extensions/console-exit.tsx","webpack://next/./src/shared/lib/invariant-error.ts","webpack://next/./src/server/app-render/dynamic-rendering.ts","webpack://next/./src/server/dynamic-rendering-utils.ts","webpack://next/./src/server/node-environment-extensions/io-utils.tsx","webpack://next/./src/server/node-environment-extensions/random.tsx","webpack://next/./src/server/node-environment-extensions/node-crypto.tsx","webpack://next/./src/server/require-hook.ts","webpack://next/./src/shared/lib/utils.ts","webpack://next/./src/lib/route-pattern-normalizer.ts","webpack://next/./src/shared/lib/router/utils/route-match-utils.ts","webpack://next/./src/shared/lib/router/utils/route-matcher.ts","webpack://next/./src/server/request-meta.ts","webpack://next/./src/shared/lib/entry-constants.ts","webpack://next/./src/shared/lib/constants.ts","webpack://next/./src/lib/find-pages-dir.ts","webpack://next/./src/server/web/spec-extension/adapters/reflect.ts","webpack://next/./src/server/web/spec-extension/adapters/headers.ts","webpack://next/./src/lib/constants.ts","webpack://next/./src/server/api-utils/index.ts","webpack://next/./src/server/api-utils/get-cookie-parser.ts","webpack://next/./src/server/base-http/index.ts","webpack://next/./src/server/base-http/node.ts","webpack://next/./src/server/send-payload.ts","webpack://next/./src/server/lib/cache-control.ts","webpack://next/./src/server/lib/etag.ts","webpack://next/./src/shared/lib/router/utils/querystring.ts","webpack://next/./src/shared/lib/router/utils/parse-url.ts","webpack://next/./src/shared/lib/router/utils/parse-relative-url.ts","webpack://next/./src/build/output/log.ts","webpack://next/./src/shared/lib/size-limit.ts","webpack://next/./src/server/config-shared.ts","webpack://next/./src/shared/lib/image-config.ts","webpack://next/./src/shared/lib/errors/canary-only-config-error.ts","webpack://next/./src/server/lib/is-ipv6.ts","webpack://next/./src/shared/lib/page-path/ensure-leading-slash.ts","webpack://next/./src/shared/lib/router/utils/app-paths.ts","webpack://next/./src/shared/lib/segment.ts","webpack://next/./src/shared/lib/router/utils/interception-routes.ts","webpack://next/./src/shared/lib/router/utils/is-dynamic.ts","webpack://next/./src/shared/lib/router/utils/html-bots.ts","webpack://next/./src/shared/lib/router/utils/is-bot.ts","webpack://next/./src/server/stream-utils/node-web-streams-helper.ts","webpack://next/./src/server/stream-utils/encoded-tags.ts","webpack://next/./src/server/web/utils.ts","webpack://next/./src/shared/lib/router/utils/remove-trailing-slash.ts","webpack://next/./src/shared/lib/router/utils/parse-path.ts","webpack://next/./src/shared/lib/router/utils/add-path-prefix.ts","webpack://next/./src/shared/lib/router/utils/add-path-suffix.ts","webpack://next/./src/shared/lib/router/utils/path-has-prefix.ts","webpack://next/./src/shared/lib/get-hostname.ts","webpack://next/./src/shared/lib/i18n/normalize-locale-path.ts","webpack://next/./src/shared/lib/router/utils/remove-path-prefix.ts","webpack://next/./src/shared/lib/router/utils/get-next-pathname-info.ts","webpack://next/./src/server/web/next-url.ts","webpack://next/./src/shared/lib/i18n/detect-domain-locale.ts","webpack://next/./src/shared/lib/router/utils/format-next-pathname-info.ts","webpack://next/./src/shared/lib/router/utils/add-locale.ts","webpack://next/./src/server/web/error.ts","webpack://next/./src/server/web/spec-extension/request.ts","webpack://next/./src/server/web/spec-extension/adapters/next-request.ts","webpack://next/./src/lib/detached-promise.ts","webpack://next/./src/server/client-component-renderer-logger.ts","webpack://next/./src/server/pipe-readable.ts","webpack://next/./src/server/render-result.ts","webpack://next/./src/shared/lib/page-path/normalize-path-sep.ts","webpack://next/./src/shared/lib/page-path/denormalize-page-path.ts","webpack://next/./src/shared/lib/router/utils/path-match.ts","webpack://next/./src/shared/lib/escape-regexp.ts","webpack://next/./src/shared/lib/router/utils/get-dynamic-param.ts","webpack://next/./src/shared/lib/router/utils/route-regex.ts","webpack://next/./src/shared/lib/router/utils/prepare-destination.ts","webpack://next/./src/server/lib/decode-query-path-parameter.ts","webpack://next/./src/shared/lib/router/utils/format-url.ts","webpack://next/./src/server/server-utils.ts","webpack://next/./src/lib/is-error.ts","webpack://next/./src/shared/lib/is-plain-object.ts","webpack://next/./src/client/components/app-router-headers.ts","webpack://next/./src/server/normalizers/locale-route-normalizer.ts","webpack://next/./src/shared/lib/router/utils/sorted-routes.ts","webpack://next/./src/server/route-matchers/route-matcher.ts","webpack://next/./src/server/route-matchers/locale-route-matcher.ts","webpack://next/./src/server/route-matcher-managers/default-route-matcher-manager.ts","webpack://next/./src/server/normalizers/normalizers.ts","webpack://next/./src/server/normalizers/prefixing-normalizer.ts","webpack://next/./src/shared/lib/page-path/normalize-page-path.ts","webpack://next/./src/server/normalizers/underscore-normalizer.ts","webpack://next/./src/server/normalizers/built/app/app-bundle-path-normalizer.ts","webpack://next/./src/server/normalizers/built/app/app-filename-normalizer.ts","webpack://next/./src/lib/is-app-route-route.ts","webpack://next/./src/lib/metadata/is-metadata-route.ts","webpack://next/./src/server/normalizers/wrap-normalizer-fn.ts","webpack://next/./src/server/normalizers/built/app/app-pathname-normalizer.ts","webpack://next/./src/server/normalizers/built/app/index.ts","webpack://next/./src/server/route-matchers/app-page-route-matcher.ts","webpack://next/./src/server/route-matcher-providers/helpers/cached-route-matcher-provider.ts","webpack://next/./src/server/route-matcher-providers/manifest-route-matcher-provider.ts","webpack://next/./src/server/route-matcher-providers/app-page-route-matcher-provider.ts","webpack://next/./src/lib/is-app-page-route.ts","webpack://next/./src/server/route-matchers/app-route-route-matcher.ts","webpack://next/./src/server/route-matcher-providers/app-route-route-matcher-provider.ts","webpack://next/./src/lib/is-api-route.ts","webpack://next/./src/server/route-matchers/pages-api-route-matcher.ts","webpack://next/./src/server/normalizers/built/pages/pages-bundle-path-normalizer.ts","webpack://next/./src/server/normalizers/built/pages/pages-filename-normalizer.ts","webpack://next/./src/server/normalizers/built/pages/index.ts","webpack://next/./src/server/route-matcher-providers/pages-api-route-matcher-provider.ts","webpack://next/./src/server/route-matchers/pages-route-matcher.ts","webpack://next/./src/server/route-matcher-providers/pages-route-matcher-provider.ts","webpack://next/./src/server/route-matcher-providers/helpers/manifest-loaders/server-manifest-loader.ts","webpack://next/./src/server/lib/i18n-provider.ts","webpack://next/./src/server/send-response.ts","webpack://next/./src/server/lib/match-next-data-pathname.ts","webpack://next/./src/server/normalizers/request/suffix.ts","webpack://next/./src/server/normalizers/request/rsc.ts","webpack://next/./src/server/normalizers/request/prefix.ts","webpack://next/./src/server/normalizers/request/next-data.ts","webpack://next/./src/server/lib/to-route.ts","webpack://next/./src/server/app-render/async-local-storage.ts","webpack://next/./src/server/after/builtin-request-context.ts","webpack://next/./src/server/web/spec-extension/fetch-event.ts","webpack://next/./src/server/web/spec-extension/response.ts","webpack://next/./src/server/web/spec-extension/adapters/request-cookies.ts","webpack://next/./src/server/lib/cache-handlers/default.ts","webpack://next/./src/server/use-cache/handlers.ts","webpack://next/./src/server/web/adapter.ts","webpack://next/./src/server/normalizers/request/segment-prefix-rsc.ts","webpack://next/./src/server/app-render/get-short-dynamic-param-type.tsx","webpack://next/./src/server/lib/postponed-request-body.ts","webpack://next/./src/server/base-server.ts","webpack://next/./src/server/app-render/strip-flight-headers.ts","webpack://next/./src/shared/lib/router/utils/get-route-from-asset-path.ts","webpack://next/./src/server/lib/format-hostname.ts","webpack://next/./src/server/lib/experimental/ppr.ts","webpack://next/./src/server/lib/patch-set-header.ts","webpack://next/./src/server/lib/fix-mojibake.ts","webpack://next/./src/lib/url.ts","webpack://next/./src/server/lib/streaming-metadata.ts","webpack://next/./src/server/utils.ts","webpack://next/./src/lib/fallback.ts","webpack://next/./src/server/lib/server-action-request-meta.ts","webpack://next/./src/server/route-modules/checks.ts","webpack://next/./src/server/request/fallback-params.ts","webpack://next/./src/server/require.ts","webpack://next/./src/lib/interop-default.ts","webpack://next/./src/lib/wait.ts","webpack://next/./src/server/app-render/manifests-singleton.ts","webpack://next/./src/server/load-components.ts","webpack://next/./src/shared/lib/router/utils/middleware-route-matcher.ts","webpack://next/./src/server/response-cache/index.ts","webpack://next/./src/lib/multi-file-writer.ts","webpack://next/./src/server/lib/incremental-cache/file-system-cache.ts","webpack://next/./src/server/lib/incremental-cache/index.ts","webpack://next/./src/server/lib/node-fs-methods.ts","webpack://next/./src/server/lib/mock-request.ts","webpack://next/./src/lib/format-dynamic-import-path.ts","webpack://next/./src/lib/is-interception-route-rewrite.ts","webpack://next/./src/server/lib/async-callback-set.ts","webpack://next/./src/server/lib/module-loader/node-module-loader.ts","webpack://next/./src/server/lib/router-utils/router-server-context.ts","webpack://next/./src/server/lib/router-utils/is-postpone.ts","webpack://next/./src/server/node-environment-extensions/process-error-handlers.ts","webpack://next/./src/server/next-server.ts","webpack://next/./src/server/route-matches/pages-api-route-match.ts","webpack://next/./src/server/node-environment-extensions/global-behaviors.tsx","webpack://next/./src/server/setup-http-agent-env.ts","webpack://next/./src/lib/static-env.ts","webpack://next/./src/server/body-streams.ts"],"sourcesContent":["/**\n * @license React\n * react.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n  REACT_PORTAL_TYPE = Symbol.for(\"react.portal\"),\n  REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\"),\n  REACT_STRICT_MODE_TYPE = Symbol.for(\"react.strict_mode\"),\n  REACT_PROFILER_TYPE = Symbol.for(\"react.profiler\"),\n  REACT_CONSUMER_TYPE = Symbol.for(\"react.consumer\"),\n  REACT_CONTEXT_TYPE = Symbol.for(\"react.context\"),\n  REACT_FORWARD_REF_TYPE = Symbol.for(\"react.forward_ref\"),\n  REACT_SUSPENSE_TYPE = Symbol.for(\"react.suspense\"),\n  REACT_MEMO_TYPE = Symbol.for(\"react.memo\"),\n  REACT_LAZY_TYPE = Symbol.for(\"react.lazy\"),\n  REACT_ACTIVITY_TYPE = Symbol.for(\"react.activity\"),\n  REACT_VIEW_TRANSITION_TYPE = Symbol.for(\"react.view_transition\"),\n  MAYBE_ITERATOR_SYMBOL = Symbol.iterator;\nfunction getIteratorFn(maybeIterable) {\n  if (null === maybeIterable || \"object\" !== typeof maybeIterable) return null;\n  maybeIterable =\n    (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) ||\n    maybeIterable[\"@@iterator\"];\n  return \"function\" === typeof maybeIterable ? maybeIterable : null;\n}\nvar ReactNoopUpdateQueue = {\n    isMounted: function () {\n      return !1;\n    },\n    enqueueForceUpdate: function () {},\n    enqueueReplaceState: function () {},\n    enqueueSetState: function () {}\n  },\n  assign = Object.assign,\n  emptyObject = {};\nfunction Component(props, context, updater) {\n  this.props = props;\n  this.context = context;\n  this.refs = emptyObject;\n  this.updater = updater || ReactNoopUpdateQueue;\n}\nComponent.prototype.isReactComponent = {};\nComponent.prototype.setState = function (partialState, callback) {\n  if (\n    \"object\" !== typeof partialState &&\n    \"function\" !== typeof partialState &&\n    null != partialState\n  )\n    throw Error(\n      \"takes an object of state variables to update or a function which returns an object of state variables.\"\n    );\n  this.updater.enqueueSetState(this, partialState, callback, \"setState\");\n};\nComponent.prototype.forceUpdate = function (callback) {\n  this.updater.enqueueForceUpdate(this, callback, \"forceUpdate\");\n};\nfunction ComponentDummy() {}\nComponentDummy.prototype = Component.prototype;\nfunction PureComponent(props, context, updater) {\n  this.props = props;\n  this.context = context;\n  this.refs = emptyObject;\n  this.updater = updater || ReactNoopUpdateQueue;\n}\nvar pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());\npureComponentPrototype.constructor = PureComponent;\nassign(pureComponentPrototype, Component.prototype);\npureComponentPrototype.isPureReactComponent = !0;\nvar isArrayImpl = Array.isArray;\nfunction noop() {}\nvar ReactSharedInternals = { H: null, A: null, T: null, S: null },\n  hasOwnProperty = Object.prototype.hasOwnProperty;\nfunction ReactElement(type, key, props) {\n  var refProp = props.ref;\n  return {\n    $$typeof: REACT_ELEMENT_TYPE,\n    type: type,\n    key: key,\n    ref: void 0 !== refProp ? refProp : null,\n    props: props\n  };\n}\nfunction cloneAndReplaceKey(oldElement, newKey) {\n  return ReactElement(oldElement.type, newKey, oldElement.props);\n}\nfunction isValidElement(object) {\n  return (\n    \"object\" === typeof object &&\n    null !== object &&\n    object.$$typeof === REACT_ELEMENT_TYPE\n  );\n}\nfunction escape(key) {\n  var escaperLookup = { \"=\": \"=0\", \":\": \"=2\" };\n  return (\n    \"$\" +\n    key.replace(/[=:]/g, function (match) {\n      return escaperLookup[match];\n    })\n  );\n}\nvar userProvidedKeyEscapeRegex = /\\/+/g;\nfunction getElementKey(element, index) {\n  return \"object\" === typeof element && null !== element && null != element.key\n    ? escape(\"\" + element.key)\n    : index.toString(36);\n}\nfunction resolveThenable(thenable) {\n  switch (thenable.status) {\n    case \"fulfilled\":\n      return thenable.value;\n    case \"rejected\":\n      throw thenable.reason;\n    default:\n      switch (\n        (\"string\" === typeof thenable.status\n          ? thenable.then(noop, noop)\n          : ((thenable.status = \"pending\"),\n            thenable.then(\n              function (fulfilledValue) {\n                \"pending\" === thenable.status &&\n                  ((thenable.status = \"fulfilled\"),\n                  (thenable.value = fulfilledValue));\n              },\n              function (error) {\n                \"pending\" === thenable.status &&\n                  ((thenable.status = \"rejected\"), (thenable.reason = error));\n              }\n            )),\n        thenable.status)\n      ) {\n        case \"fulfilled\":\n          return thenable.value;\n        case \"rejected\":\n          throw thenable.reason;\n      }\n  }\n  throw thenable;\n}\nfunction mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {\n  var type = typeof children;\n  if (\"undefined\" === type || \"boolean\" === type) children = null;\n  var invokeCallback = !1;\n  if (null === children) invokeCallback = !0;\n  else\n    switch (type) {\n      case \"bigint\":\n      case \"string\":\n      case \"number\":\n        invokeCallback = !0;\n        break;\n      case \"object\":\n        switch (children.$$typeof) {\n          case REACT_ELEMENT_TYPE:\n          case REACT_PORTAL_TYPE:\n            invokeCallback = !0;\n            break;\n          case REACT_LAZY_TYPE:\n            return (\n              (invokeCallback = children._init),\n              mapIntoArray(\n                invokeCallback(children._payload),\n                array,\n                escapedPrefix,\n                nameSoFar,\n                callback\n              )\n            );\n        }\n    }\n  if (invokeCallback)\n    return (\n      (callback = callback(children)),\n      (invokeCallback =\n        \"\" === nameSoFar ? \".\" + getElementKey(children, 0) : nameSoFar),\n      isArrayImpl(callback)\n        ? ((escapedPrefix = \"\"),\n          null != invokeCallback &&\n            (escapedPrefix =\n              invokeCallback.replace(userProvidedKeyEscapeRegex, \"$&/\") + \"/\"),\n          mapIntoArray(callback, array, escapedPrefix, \"\", function (c) {\n            return c;\n          }))\n        : null != callback &&\n          (isValidElement(callback) &&\n            (callback = cloneAndReplaceKey(\n              callback,\n              escapedPrefix +\n                (null == callback.key ||\n                (children && children.key === callback.key)\n                  ? \"\"\n                  : (\"\" + callback.key).replace(\n                      userProvidedKeyEscapeRegex,\n                      \"$&/\"\n                    ) + \"/\") +\n                invokeCallback\n            )),\n          array.push(callback)),\n      1\n    );\n  invokeCallback = 0;\n  var nextNamePrefix = \"\" === nameSoFar ? \".\" : nameSoFar + \":\";\n  if (isArrayImpl(children))\n    for (var i = 0; i < children.length; i++)\n      (nameSoFar = children[i]),\n        (type = nextNamePrefix + getElementKey(nameSoFar, i)),\n        (invokeCallback += mapIntoArray(\n          nameSoFar,\n          array,\n          escapedPrefix,\n          type,\n          callback\n        ));\n  else if (((i = getIteratorFn(children)), \"function\" === typeof i))\n    for (\n      children = i.call(children), i = 0;\n      !(nameSoFar = children.next()).done;\n\n    )\n      (nameSoFar = nameSoFar.value),\n        (type = nextNamePrefix + getElementKey(nameSoFar, i++)),\n        (invokeCallback += mapIntoArray(\n          nameSoFar,\n          array,\n          escapedPrefix,\n          type,\n          callback\n        ));\n  else if (\"object\" === type) {\n    if (\"function\" === typeof children.then)\n      return mapIntoArray(\n        resolveThenable(children),\n        array,\n        escapedPrefix,\n        nameSoFar,\n        callback\n      );\n    array = String(children);\n    throw Error(\n      \"Objects are not valid as a React child (found: \" +\n        (\"[object Object]\" === array\n          ? \"object with keys {\" + Object.keys(children).join(\", \") + \"}\"\n          : array) +\n        \"). If you meant to render a collection of children, use an array instead.\"\n    );\n  }\n  return invokeCallback;\n}\nfunction mapChildren(children, func, context) {\n  if (null == children) return children;\n  var result = [],\n    count = 0;\n  mapIntoArray(children, result, \"\", \"\", function (child) {\n    return func.call(context, child, count++);\n  });\n  return result;\n}\nfunction lazyInitializer(payload) {\n  if (-1 === payload._status) {\n    var ctor = payload._result,\n      thenable = ctor();\n    thenable.then(\n      function (moduleObject) {\n        if (0 === payload._status || -1 === payload._status)\n          (payload._status = 1),\n            (payload._result = moduleObject),\n            void 0 === thenable.status &&\n              ((thenable.status = \"fulfilled\"),\n              (thenable.value = moduleObject));\n      },\n      function (error) {\n        if (0 === payload._status || -1 === payload._status)\n          (payload._status = 2),\n            (payload._result = error),\n            void 0 === thenable.status &&\n              ((thenable.status = \"rejected\"), (thenable.reason = error));\n      }\n    );\n    -1 === payload._status &&\n      ((payload._status = 0), (payload._result = thenable));\n  }\n  if (1 === payload._status) return payload._result.default;\n  throw payload._result;\n}\nvar reportGlobalError =\n  \"function\" === typeof reportError\n    ? reportError\n    : function (error) {\n        if (\n          \"object\" === typeof window &&\n          \"function\" === typeof window.ErrorEvent\n        ) {\n          var event = new window.ErrorEvent(\"error\", {\n            bubbles: !0,\n            cancelable: !0,\n            message:\n              \"object\" === typeof error &&\n              null !== error &&\n              \"string\" === typeof error.message\n                ? String(error.message)\n                : String(error),\n            error: error\n          });\n          if (!window.dispatchEvent(event)) return;\n        } else if (\n          \"object\" === typeof process &&\n          \"function\" === typeof process.emit\n        ) {\n          process.emit(\"uncaughtException\", error);\n          return;\n        }\n        console.error(error);\n      };\nfunction startTransition(scope) {\n  var prevTransition = ReactSharedInternals.T,\n    currentTransition = {};\n  currentTransition.types =\n    null !== prevTransition ? prevTransition.types : null;\n  ReactSharedInternals.T = currentTransition;\n  try {\n    var returnValue = scope(),\n      onStartTransitionFinish = ReactSharedInternals.S;\n    null !== onStartTransitionFinish &&\n      onStartTransitionFinish(currentTransition, returnValue);\n    \"object\" === typeof returnValue &&\n      null !== returnValue &&\n      \"function\" === typeof returnValue.then &&\n      returnValue.then(noop, reportGlobalError);\n  } catch (error) {\n    reportGlobalError(error);\n  } finally {\n    null !== prevTransition &&\n      null !== currentTransition.types &&\n      (prevTransition.types = currentTransition.types),\n      (ReactSharedInternals.T = prevTransition);\n  }\n}\nfunction addTransitionType(type) {\n  var transition = ReactSharedInternals.T;\n  if (null !== transition) {\n    var transitionTypes = transition.types;\n    null === transitionTypes\n      ? (transition.types = [type])\n      : -1 === transitionTypes.indexOf(type) && transitionTypes.push(type);\n  } else startTransition(addTransitionType.bind(null, type));\n}\nvar Children = {\n  map: mapChildren,\n  forEach: function (children, forEachFunc, forEachContext) {\n    mapChildren(\n      children,\n      function () {\n        forEachFunc.apply(this, arguments);\n      },\n      forEachContext\n    );\n  },\n  count: function (children) {\n    var n = 0;\n    mapChildren(children, function () {\n      n++;\n    });\n    return n;\n  },\n  toArray: function (children) {\n    return (\n      mapChildren(children, function (child) {\n        return child;\n      }) || []\n    );\n  },\n  only: function (children) {\n    if (!isValidElement(children))\n      throw Error(\n        \"React.Children.only expected to receive a single React element child.\"\n      );\n    return children;\n  }\n};\nexports.Activity = REACT_ACTIVITY_TYPE;\nexports.Children = Children;\nexports.Component = Component;\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.Profiler = REACT_PROFILER_TYPE;\nexports.PureComponent = PureComponent;\nexports.StrictMode = REACT_STRICT_MODE_TYPE;\nexports.Suspense = REACT_SUSPENSE_TYPE;\nexports.ViewTransition = REACT_VIEW_TRANSITION_TYPE;\nexports.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE =\n  ReactSharedInternals;\nexports.__COMPILER_RUNTIME = {\n  __proto__: null,\n  c: function (size) {\n    return ReactSharedInternals.H.useMemoCache(size);\n  }\n};\nexports.addTransitionType = addTransitionType;\nexports.cache = function (fn) {\n  return function () {\n    return fn.apply(null, arguments);\n  };\n};\nexports.cacheSignal = function () {\n  return null;\n};\nexports.cloneElement = function (element, config, children) {\n  if (null === element || void 0 === element)\n    throw Error(\n      \"The argument must be a React element, but you passed \" + element + \".\"\n    );\n  var props = assign({}, element.props),\n    key = element.key;\n  if (null != config)\n    for (propName in (void 0 !== config.key && (key = \"\" + config.key), config))\n      !hasOwnProperty.call(config, propName) ||\n        \"key\" === propName ||\n        \"__self\" === propName ||\n        \"__source\" === propName ||\n        (\"ref\" === propName && void 0 === config.ref) ||\n        (props[propName] = config[propName]);\n  var propName = arguments.length - 2;\n  if (1 === propName) props.children = children;\n  else if (1 < propName) {\n    for (var childArray = Array(propName), i = 0; i < propName; i++)\n      childArray[i] = arguments[i + 2];\n    props.children = childArray;\n  }\n  return ReactElement(element.type, key, props);\n};\nexports.createContext = function (defaultValue) {\n  defaultValue = {\n    $$typeof: REACT_CONTEXT_TYPE,\n    _currentValue: defaultValue,\n    _currentValue2: defaultValue,\n    _threadCount: 0,\n    Provider: null,\n    Consumer: null\n  };\n  defaultValue.Provider = defaultValue;\n  defaultValue.Consumer = {\n    $$typeof: REACT_CONSUMER_TYPE,\n    _context: defaultValue\n  };\n  return defaultValue;\n};\nexports.createElement = function (type, config, children) {\n  var propName,\n    props = {},\n    key = null;\n  if (null != config)\n    for (propName in (void 0 !== config.key && (key = \"\" + config.key), config))\n      hasOwnProperty.call(config, propName) &&\n        \"key\" !== propName &&\n        \"__self\" !== propName &&\n        \"__source\" !== propName &&\n        (props[propName] = config[propName]);\n  var childrenLength = arguments.length - 2;\n  if (1 === childrenLength) props.children = children;\n  else if (1 < childrenLength) {\n    for (var childArray = Array(childrenLength), i = 0; i < childrenLength; i++)\n      childArray[i] = arguments[i + 2];\n    props.children = childArray;\n  }\n  if (type && type.defaultProps)\n    for (propName in ((childrenLength = type.defaultProps), childrenLength))\n      void 0 === props[propName] &&\n        (props[propName] = childrenLength[propName]);\n  return ReactElement(type, key, props);\n};\nexports.createRef = function () {\n  return { current: null };\n};\nexports.forwardRef = function (render) {\n  return { $$typeof: REACT_FORWARD_REF_TYPE, render: render };\n};\nexports.isValidElement = isValidElement;\nexports.lazy = function (ctor) {\n  return {\n    $$typeof: REACT_LAZY_TYPE,\n    _payload: { _status: -1, _result: ctor },\n    _init: lazyInitializer\n  };\n};\nexports.memo = function (type, compare) {\n  return {\n    $$typeof: REACT_MEMO_TYPE,\n    type: type,\n    compare: void 0 === compare ? null : compare\n  };\n};\nexports.startTransition = startTransition;\nexports.unstable_useCacheRefresh = function () {\n  return ReactSharedInternals.H.useCacheRefresh();\n};\nexports.use = function (usable) {\n  return ReactSharedInternals.H.use(usable);\n};\nexports.useActionState = function (action, initialState, permalink) {\n  return ReactSharedInternals.H.useActionState(action, initialState, permalink);\n};\nexports.useCallback = function (callback, deps) {\n  return ReactSharedInternals.H.useCallback(callback, deps);\n};\nexports.useContext = function (Context) {\n  return ReactSharedInternals.H.useContext(Context);\n};\nexports.useDebugValue = function () {};\nexports.useDeferredValue = function (value, initialValue) {\n  return ReactSharedInternals.H.useDeferredValue(value, initialValue);\n};\nexports.useEffect = function (create, deps) {\n  return ReactSharedInternals.H.useEffect(create, deps);\n};\nexports.useEffectEvent = function (callback) {\n  return ReactSharedInternals.H.useEffectEvent(callback);\n};\nexports.useId = function () {\n  return ReactSharedInternals.H.useId();\n};\nexports.useImperativeHandle = function (ref, create, deps) {\n  return ReactSharedInternals.H.useImperativeHandle(ref, create, deps);\n};\nexports.useInsertionEffect = function (create, deps) {\n  return ReactSharedInternals.H.useInsertionEffect(create, deps);\n};\nexports.useLayoutEffect = function (create, deps) {\n  return ReactSharedInternals.H.useLayoutEffect(create, deps);\n};\nexports.useMemo = function (create, deps) {\n  return ReactSharedInternals.H.useMemo(create, deps);\n};\nexports.useOptimistic = function (passthrough, reducer) {\n  return ReactSharedInternals.H.useOptimistic(passthrough, reducer);\n};\nexports.useReducer = function (reducer, initialArg, init) {\n  return ReactSharedInternals.H.useReducer(reducer, initialArg, init);\n};\nexports.useRef = function (initialValue) {\n  return ReactSharedInternals.H.useRef(initialValue);\n};\nexports.useState = function (initialState) {\n  return ReactSharedInternals.H.useState(initialState);\n};\nexports.useSyncExternalStore = function (\n  subscribe,\n  getSnapshot,\n  getServerSnapshot\n) {\n  return ReactSharedInternals.H.useSyncExternalStore(\n    subscribe,\n    getSnapshot,\n    getServerSnapshot\n  );\n};\nexports.useTransition = function () {\n  return ReactSharedInternals.H.useTransition();\n};\nexports.version = \"19.3.0-canary-3f0b9e61-20260317\";\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n  module.exports = require('./cjs/react.production.js');\n} else {\n  module.exports = require('./cjs/react.development.js');\n}\n","(()=>{var e={383:e=>{\"use strict\";function _searchLast(e,t){const n=Array.from(e.matchAll(t));return n.length>0?n.slice(-1)[0].index:-1}function _interpolate(e,t,n){const r=_searchLast(e,/(?!(?<=\\\\))\\$/g);if(r===-1)return e;const o=e.slice(r);const s=/((?!(?<=\\\\))\\${?([\\w]+)(?::-([^}\\\\]*))?}?)/;const i=o.match(s);if(i!=null){const[,r,o,s]=i;return _interpolate(e.replace(r,t[o]||s||n.parsed[o]||\"\"),t,n)}return e}function _resolveEscapeSequences(e){return e.replace(/\\\\\\$/g,\"$\")}function expand(e){const t=e.ignoreProcessEnv?{}:process.env;for(const n in e.parsed){const r=Object.prototype.hasOwnProperty.call(t,n)?t[n]:e.parsed[n];e.parsed[n]=_resolveEscapeSequences(_interpolate(r,t,e))}for(const n in e.parsed){t[n]=e.parsed[n]}return e}e.exports.j=expand},234:(e,t,n)=>{const r=n(147);const o=n(17);const s=n(37);const i=n(113);const c=n(803);const a=c.version;const p=/(?:^|^)\\s*(?:export\\s+)?([\\w.-]+)(?:\\s*=\\s*?|:\\s+?)(\\s*'(?:\\\\'|[^'])*'|\\s*\"(?:\\\\\"|[^\"])*\"|\\s*`(?:\\\\`|[^`])*`|[^#\\r\\n]+)?\\s*(?:#.*)?(?:$|$)/gm;function parse(e){const t={};let n=e.toString();n=n.replace(/\\r\\n?/gm,\"\\n\");let r;while((r=p.exec(n))!=null){const e=r[1];let n=r[2]||\"\";n=n.trim();const o=n[0];n=n.replace(/^(['\"`])([\\s\\S]*)\\1$/gm,\"$2\");if(o==='\"'){n=n.replace(/\\\\n/g,\"\\n\");n=n.replace(/\\\\r/g,\"\\r\")}t[e]=n}return t}function _parseVault(e){const t=_vaultPath(e);const n=l.configDotenv({path:t});if(!n.parsed){throw new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`)}const r=_dotenvKey(e).split(\",\");const o=r.length;let s;for(let e=0;e<o;e++){try{const t=r[e].trim();const o=_instructions(n,t);s=l.decrypt(o.ciphertext,o.key);break}catch(t){if(e+1>=o){throw t}}}return l.parse(s)}function _log(e){console.log(`[dotenv@${a}][INFO] ${e}`)}function _warn(e){console.log(`[dotenv@${a}][WARN] ${e}`)}function _debug(e){console.log(`[dotenv@${a}][DEBUG] ${e}`)}function _dotenvKey(e){if(e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0){return e.DOTENV_KEY}if(process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0){return process.env.DOTENV_KEY}return\"\"}function _instructions(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===\"ERR_INVALID_URL\"){throw new Error(\"INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenv.org/vault/.env.vault?environment=development\")}throw e}const r=n.password;if(!r){throw new Error(\"INVALID_DOTENV_KEY: Missing key part\")}const o=n.searchParams.get(\"environment\");if(!o){throw new Error(\"INVALID_DOTENV_KEY: Missing environment part\")}const s=`DOTENV_VAULT_${o.toUpperCase()}`;const i=e.parsed[s];if(!i){throw new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${s} in your .env.vault file.`)}return{ciphertext:i,key:r}}function _vaultPath(e){let t=o.resolve(process.cwd(),\".env\");if(e&&e.path&&e.path.length>0){t=e.path}return t.endsWith(\".vault\")?t:`${t}.vault`}function _resolveHome(e){return e[0]===\"~\"?o.join(s.homedir(),e.slice(1)):e}function _configVault(e){_log(\"Loading env from encrypted .env.vault\");const t=l._parseVault(e);let n=process.env;if(e&&e.processEnv!=null){n=e.processEnv}l.populate(n,t,e);return{parsed:t}}function configDotenv(e){let t=o.resolve(process.cwd(),\".env\");let n=\"utf8\";const s=Boolean(e&&e.debug);if(e){if(e.path!=null){t=_resolveHome(e.path)}if(e.encoding!=null){n=e.encoding}}try{const o=l.parse(r.readFileSync(t,{encoding:n}));let s=process.env;if(e&&e.processEnv!=null){s=e.processEnv}l.populate(s,o,e);return{parsed:o}}catch(e){if(s){_debug(`Failed to load ${t} ${e.message}`)}return{error:e}}}function config(e){const t=_vaultPath(e);if(_dotenvKey(e).length===0){return l.configDotenv(e)}if(!r.existsSync(t)){_warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`);return l.configDotenv(e)}return l._configVault(e)}function decrypt(e,t){const n=Buffer.from(t.slice(-64),\"hex\");let r=Buffer.from(e,\"base64\");const o=r.slice(0,12);const s=r.slice(-16);r=r.slice(12,-16);try{const e=i.createDecipheriv(\"aes-256-gcm\",n,o);e.setAuthTag(s);return`${e.update(r)}${e.final()}`}catch(e){const t=e instanceof RangeError;const n=e.message===\"Invalid key length\";const r=e.message===\"Unsupported state or unable to authenticate data\";if(t||n){const e=\"INVALID_DOTENV_KEY: It must be 64 characters long (or more)\";throw new Error(e)}else if(r){const e=\"DECRYPTION_FAILED: Please check your DOTENV_KEY\";throw new Error(e)}else{console.error(\"Error: \",e.code);console.error(\"Error: \",e.message);throw e}}}function populate(e,t,n={}){const r=Boolean(n&&n.debug);const o=Boolean(n&&n.override);if(typeof t!==\"object\"){throw new Error(\"OBJECT_REQUIRED: Please check the processEnv argument being passed to populate\")}for(const n of Object.keys(t)){if(Object.prototype.hasOwnProperty.call(e,n)){if(o===true){e[n]=t[n]}if(r){if(o===true){_debug(`\"${n}\" is already defined and WAS overwritten`)}else{_debug(`\"${n}\" is already defined and was NOT overwritten`)}}}else{e[n]=t[n]}}}const l={configDotenv:configDotenv,_configVault:_configVault,_parseVault:_parseVault,config:config,decrypt:decrypt,parse:parse,populate:populate};e.exports.configDotenv=l.configDotenv;e.exports._configVault=l._configVault;e.exports._parseVault=l._parseVault;e.exports.config=l.config;e.exports.decrypt=l.decrypt;e.exports.parse=l.parse;e.exports.populate=l.populate;e.exports=l},113:e=>{\"use strict\";e.exports=require(\"crypto\")},147:e=>{\"use strict\";e.exports=require(\"fs\")},37:e=>{\"use strict\";e.exports=require(\"os\")},17:e=>{\"use strict\";e.exports=require(\"path\")},803:e=>{\"use strict\";e.exports=JSON.parse('{\"name\":\"dotenv\",\"version\":\"16.3.1\",\"description\":\"Loads environment variables from .env file\",\"main\":\"lib/main.js\",\"types\":\"lib/main.d.ts\",\"exports\":{\".\":{\"types\":\"./lib/main.d.ts\",\"require\":\"./lib/main.js\",\"default\":\"./lib/main.js\"},\"./config\":\"./config.js\",\"./config.js\":\"./config.js\",\"./lib/env-options\":\"./lib/env-options.js\",\"./lib/env-options.js\":\"./lib/env-options.js\",\"./lib/cli-options\":\"./lib/cli-options.js\",\"./lib/cli-options.js\":\"./lib/cli-options.js\",\"./package.json\":\"./package.json\"},\"scripts\":{\"dts-check\":\"tsc --project tests/types/tsconfig.json\",\"lint\":\"standard\",\"lint-readme\":\"standard-markdown\",\"pretest\":\"npm run lint && npm run dts-check\",\"test\":\"tap tests/*.js --100 -Rspec\",\"prerelease\":\"npm test\",\"release\":\"standard-version\"},\"repository\":{\"type\":\"git\",\"url\":\"git://github.com/motdotla/dotenv.git\"},\"funding\":\"https://github.com/motdotla/dotenv?sponsor=1\",\"keywords\":[\"dotenv\",\"env\",\".env\",\"environment\",\"variables\",\"config\",\"settings\"],\"readmeFilename\":\"README.md\",\"license\":\"BSD-2-Clause\",\"devDependencies\":{\"@definitelytyped/dtslint\":\"^0.0.133\",\"@types/node\":\"^18.11.3\",\"decache\":\"^4.6.1\",\"sinon\":\"^14.0.1\",\"standard\":\"^17.0.0\",\"standard-markdown\":\"^7.1.0\",\"standard-version\":\"^9.5.0\",\"tap\":\"^16.3.0\",\"tar\":\"^6.1.11\",\"typescript\":\"^4.8.4\"},\"engines\":{\"node\":\">=12\"},\"browser\":{\"fs\":false}}')}};var t={};function __nccwpck_require__(n){var r=t[n];if(r!==undefined){return r.exports}var o=t[n]={exports:{}};var s=true;try{e[n](o,o.exports,__nccwpck_require__);s=false}finally{if(s)delete t[n]}return o.exports}(()=>{__nccwpck_require__.n=e=>{var t=e&&e.__esModule?()=>e[\"default\"]:()=>e;__nccwpck_require__.d(t,{a:t});return t}})();(()=>{__nccwpck_require__.d=(e,t)=>{for(var n in t){if(__nccwpck_require__.o(t,n)&&!__nccwpck_require__.o(e,n)){Object.defineProperty(e,n,{enumerable:true,get:t[n]})}}}})();(()=>{__nccwpck_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)})();(()=>{__nccwpck_require__.r=e=>{if(typeof Symbol!==\"undefined\"&&Symbol.toStringTag){Object.defineProperty(e,Symbol.toStringTag,{value:\"Module\"})}Object.defineProperty(e,\"__esModule\",{value:true})}})();if(typeof __nccwpck_require__!==\"undefined\")__nccwpck_require__.ab=__dirname+\"/\";var n={};(()=>{\"use strict\";__nccwpck_require__.r(n);__nccwpck_require__.d(n,{initialEnv:()=>a,updateInitialEnv:()=>updateInitialEnv,processEnv:()=>processEnv,resetEnv:()=>resetEnv,loadEnvConfig:()=>loadEnvConfig});var e=__nccwpck_require__(147);var t=__nccwpck_require__.n(e);var r=__nccwpck_require__(17);var o=__nccwpck_require__.n(r);var s=__nccwpck_require__(234);var i=__nccwpck_require__.n(s);var c=__nccwpck_require__(383);let a=undefined;let p=undefined;let l=undefined;let u=[];let _=[];function updateInitialEnv(e){Object.assign(a||{},e)}function replaceProcessEnv(e){Object.keys(process.env).forEach((t=>{if(!t.startsWith(\"__NEXT_PRIVATE\")){if(e[t]===undefined||e[t]===\"\"){delete process.env[t]}}}));Object.entries(e).forEach((([e,t])=>{process.env[e]=t}))}function processEnv(e,t,n=console,o=false,i){var p;if(!a){a=Object.assign({},process.env)}if(!o&&(process.env.__NEXT_PROCESSED_ENV||e.length===0)){return[process.env]}process.env.__NEXT_PROCESSED_ENV=\"true\";const l=Object.assign({},a);const u={};for(const o of e){try{let e={};e.parsed=s.parse(o.contents);e=(0,c.j)(e);if(e.parsed&&!_.some((e=>e.contents===o.contents&&e.path===o.path))){i===null||i===void 0?void 0:i(o.path)}for(const t of Object.keys(e.parsed||{})){if(typeof u[t]===\"undefined\"&&typeof l[t]===\"undefined\"){u[t]=(p=e.parsed)===null||p===void 0?void 0:p[t]}}o.env=e.parsed||{}}catch(e){n.error(`Failed to load env from ${r.join(t||\"\",o.path)}`,e)}}return[Object.assign(process.env,u),u]}function resetEnv(){if(a){replaceProcessEnv(a)}}function loadEnvConfig(t,n,o=console,s=false,i){if(!a){a=Object.assign({},process.env)}if(p&&!s){return{combinedEnv:p,parsedEnv:l,loadedEnvFiles:u}}replaceProcessEnv(a);_=u;u=[];const c=process.env.NODE_ENV===\"test\";const d=c?\"test\":n?\"development\":\"production\";const f=[`.env.${d}.local`,d!==\"test\"&&`.env.local`,`.env.${d}`,\".env\"].filter(Boolean);for(const n of f){const s=r.join(t,n);try{const t=e.statSync(s);if(!t.isFile()&&!t.isFIFO()){continue}const r=e.readFileSync(s,\"utf8\");u.push({path:n,contents:r,env:{}})}catch(e){if(e.code!==\"ENOENT\"){o.error(`Failed to load env from ${n}`,e)}}}[p,l]=processEnv(u,t,o,s,i);return{combinedEnv:p,parsedEnv:l,loadedEnvFiles:u}}})();module.exports=n})();","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n  for (var name in all)\n    __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n  if (from && typeof from === \"object\" || typeof from === \"function\") {\n    for (let key of __getOwnPropNames(from))\n      if (!__hasOwnProp.call(to, key) && key !== except)\n        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n  }\n  return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// src/index.ts\nvar src_exports = {};\n__export(src_exports, {\n  RequestCookies: () => RequestCookies,\n  ResponseCookies: () => ResponseCookies,\n  parseCookie: () => parseCookie,\n  parseSetCookie: () => parseSetCookie,\n  stringifyCookie: () => stringifyCookie\n});\nmodule.exports = __toCommonJS(src_exports);\n\n// src/serialize.ts\nfunction stringifyCookie(c) {\n  var _a;\n  const attrs = [\n    \"path\" in c && c.path && `Path=${c.path}`,\n    \"expires\" in c && (c.expires || c.expires === 0) && `Expires=${(typeof c.expires === \"number\" ? new Date(c.expires) : c.expires).toUTCString()}`,\n    \"maxAge\" in c && typeof c.maxAge === \"number\" && `Max-Age=${c.maxAge}`,\n    \"domain\" in c && c.domain && `Domain=${c.domain}`,\n    \"secure\" in c && c.secure && \"Secure\",\n    \"httpOnly\" in c && c.httpOnly && \"HttpOnly\",\n    \"sameSite\" in c && c.sameSite && `SameSite=${c.sameSite}`,\n    \"partitioned\" in c && c.partitioned && \"Partitioned\",\n    \"priority\" in c && c.priority && `Priority=${c.priority}`\n  ].filter(Boolean);\n  const stringified = `${c.name}=${encodeURIComponent((_a = c.value) != null ? _a : \"\")}`;\n  return attrs.length === 0 ? stringified : `${stringified}; ${attrs.join(\"; \")}`;\n}\nfunction parseCookie(cookie) {\n  const map = /* @__PURE__ */ new Map();\n  for (const pair of cookie.split(/; */)) {\n    if (!pair)\n      continue;\n    const splitAt = pair.indexOf(\"=\");\n    if (splitAt === -1) {\n      map.set(pair, \"true\");\n      continue;\n    }\n    const [key, value] = [pair.slice(0, splitAt), pair.slice(splitAt + 1)];\n    try {\n      map.set(key, decodeURIComponent(value != null ? value : \"true\"));\n    } catch {\n    }\n  }\n  return map;\n}\nfunction parseSetCookie(setCookie) {\n  if (!setCookie) {\n    return void 0;\n  }\n  const [[name, value], ...attributes] = parseCookie(setCookie);\n  const {\n    domain,\n    expires,\n    httponly,\n    maxage,\n    path,\n    samesite,\n    secure,\n    partitioned,\n    priority\n  } = Object.fromEntries(\n    attributes.map(([key, value2]) => [\n      key.toLowerCase().replace(/-/g, \"\"),\n      value2\n    ])\n  );\n  const cookie = {\n    name,\n    value: decodeURIComponent(value),\n    domain,\n    ...expires && { expires: new Date(expires) },\n    ...httponly && { httpOnly: true },\n    ...typeof maxage === \"string\" && { maxAge: Number(maxage) },\n    path,\n    ...samesite && { sameSite: parseSameSite(samesite) },\n    ...secure && { secure: true },\n    ...priority && { priority: parsePriority(priority) },\n    ...partitioned && { partitioned: true }\n  };\n  return compact(cookie);\n}\nfunction compact(t) {\n  const newT = {};\n  for (const key in t) {\n    if (t[key]) {\n      newT[key] = t[key];\n    }\n  }\n  return newT;\n}\nvar SAME_SITE = [\"strict\", \"lax\", \"none\"];\nfunction parseSameSite(string) {\n  string = string.toLowerCase();\n  return SAME_SITE.includes(string) ? string : void 0;\n}\nvar PRIORITY = [\"low\", \"medium\", \"high\"];\nfunction parsePriority(string) {\n  string = string.toLowerCase();\n  return PRIORITY.includes(string) ? string : void 0;\n}\nfunction splitCookiesString(cookiesString) {\n  if (!cookiesString)\n    return [];\n  var cookiesStrings = [];\n  var pos = 0;\n  var start;\n  var ch;\n  var lastComma;\n  var nextStart;\n  var cookiesSeparatorFound;\n  function skipWhitespace() {\n    while (pos < cookiesString.length && /\\s/.test(cookiesString.charAt(pos))) {\n      pos += 1;\n    }\n    return pos < cookiesString.length;\n  }\n  function notSpecialChar() {\n    ch = cookiesString.charAt(pos);\n    return ch !== \"=\" && ch !== \";\" && ch !== \",\";\n  }\n  while (pos < cookiesString.length) {\n    start = pos;\n    cookiesSeparatorFound = false;\n    while (skipWhitespace()) {\n      ch = cookiesString.charAt(pos);\n      if (ch === \",\") {\n        lastComma = pos;\n        pos += 1;\n        skipWhitespace();\n        nextStart = pos;\n        while (pos < cookiesString.length && notSpecialChar()) {\n          pos += 1;\n        }\n        if (pos < cookiesString.length && cookiesString.charAt(pos) === \"=\") {\n          cookiesSeparatorFound = true;\n          pos = nextStart;\n          cookiesStrings.push(cookiesString.substring(start, lastComma));\n          start = pos;\n        } else {\n          pos = lastComma + 1;\n        }\n      } else {\n        pos += 1;\n      }\n    }\n    if (!cookiesSeparatorFound || pos >= cookiesString.length) {\n      cookiesStrings.push(cookiesString.substring(start, cookiesString.length));\n    }\n  }\n  return cookiesStrings;\n}\n\n// src/request-cookies.ts\nvar RequestCookies = class {\n  constructor(requestHeaders) {\n    /** @internal */\n    this._parsed = /* @__PURE__ */ new Map();\n    this._headers = requestHeaders;\n    const header = requestHeaders.get(\"cookie\");\n    if (header) {\n      const parsed = parseCookie(header);\n      for (const [name, value] of parsed) {\n        this._parsed.set(name, { name, value });\n      }\n    }\n  }\n  [Symbol.iterator]() {\n    return this._parsed[Symbol.iterator]();\n  }\n  /**\n   * The amount of cookies received from the client\n   */\n  get size() {\n    return this._parsed.size;\n  }\n  get(...args) {\n    const name = typeof args[0] === \"string\" ? args[0] : args[0].name;\n    return this._parsed.get(name);\n  }\n  getAll(...args) {\n    var _a;\n    const all = Array.from(this._parsed);\n    if (!args.length) {\n      return all.map(([_, value]) => value);\n    }\n    const name = typeof args[0] === \"string\" ? args[0] : (_a = args[0]) == null ? void 0 : _a.name;\n    return all.filter(([n]) => n === name).map(([_, value]) => value);\n  }\n  has(name) {\n    return this._parsed.has(name);\n  }\n  set(...args) {\n    const [name, value] = args.length === 1 ? [args[0].name, args[0].value] : args;\n    const map = this._parsed;\n    map.set(name, { name, value });\n    this._headers.set(\n      \"cookie\",\n      Array.from(map).map(([_, value2]) => stringifyCookie(value2)).join(\"; \")\n    );\n    return this;\n  }\n  /**\n   * Delete the cookies matching the passed name or names in the request.\n   */\n  delete(names) {\n    const map = this._parsed;\n    const result = !Array.isArray(names) ? map.delete(names) : names.map((name) => map.delete(name));\n    this._headers.set(\n      \"cookie\",\n      Array.from(map).map(([_, value]) => stringifyCookie(value)).join(\"; \")\n    );\n    return result;\n  }\n  /**\n   * Delete all the cookies in the cookies in the request.\n   */\n  clear() {\n    this.delete(Array.from(this._parsed.keys()));\n    return this;\n  }\n  /**\n   * Format the cookies in the request as a string for logging\n   */\n  [Symbol.for(\"edge-runtime.inspect.custom\")]() {\n    return `RequestCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`;\n  }\n  toString() {\n    return [...this._parsed.values()].map((v) => `${v.name}=${encodeURIComponent(v.value)}`).join(\"; \");\n  }\n};\n\n// src/response-cookies.ts\nvar ResponseCookies = class {\n  constructor(responseHeaders) {\n    /** @internal */\n    this._parsed = /* @__PURE__ */ new Map();\n    var _a, _b, _c;\n    this._headers = responseHeaders;\n    const setCookie = (_c = (_b = (_a = responseHeaders.getSetCookie) == null ? void 0 : _a.call(responseHeaders)) != null ? _b : responseHeaders.get(\"set-cookie\")) != null ? _c : [];\n    const cookieStrings = Array.isArray(setCookie) ? setCookie : splitCookiesString(setCookie);\n    for (const cookieString of cookieStrings) {\n      const parsed = parseSetCookie(cookieString);\n      if (parsed)\n        this._parsed.set(parsed.name, parsed);\n    }\n  }\n  /**\n   * {@link https://wicg.github.io/cookie-store/#CookieStore-get CookieStore#get} without the Promise.\n   */\n  get(...args) {\n    const key = typeof args[0] === \"string\" ? args[0] : args[0].name;\n    return this._parsed.get(key);\n  }\n  /**\n   * {@link https://wicg.github.io/cookie-store/#CookieStore-getAll CookieStore#getAll} without the Promise.\n   */\n  getAll(...args) {\n    var _a;\n    const all = Array.from(this._parsed.values());\n    if (!args.length) {\n      return all;\n    }\n    const key = typeof args[0] === \"string\" ? args[0] : (_a = args[0]) == null ? void 0 : _a.name;\n    return all.filter((c) => c.name === key);\n  }\n  has(name) {\n    return this._parsed.has(name);\n  }\n  /**\n   * {@link https://wicg.github.io/cookie-store/#CookieStore-set CookieStore#set} without the Promise.\n   */\n  set(...args) {\n    const [name, value, cookie] = args.length === 1 ? [args[0].name, args[0].value, args[0]] : args;\n    const map = this._parsed;\n    map.set(name, normalizeCookie({ name, value, ...cookie }));\n    replace(map, this._headers);\n    return this;\n  }\n  /**\n   * {@link https://wicg.github.io/cookie-store/#CookieStore-delete CookieStore#delete} without the Promise.\n   */\n  delete(...args) {\n    const [name, options] = typeof args[0] === \"string\" ? [args[0]] : [args[0].name, args[0]];\n    return this.set({ ...options, name, value: \"\", expires: /* @__PURE__ */ new Date(0) });\n  }\n  [Symbol.for(\"edge-runtime.inspect.custom\")]() {\n    return `ResponseCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`;\n  }\n  toString() {\n    return [...this._parsed.values()].map(stringifyCookie).join(\"; \");\n  }\n};\nfunction replace(bag, headers) {\n  headers.delete(\"set-cookie\");\n  for (const [, value] of bag) {\n    const serialized = stringifyCookie(value);\n    headers.append(\"set-cookie\", serialized);\n  }\n}\nfunction normalizeCookie(cookie = { name: \"\", value: \"\" }) {\n  if (typeof cookie.expires === \"number\") {\n    cookie.expires = new Date(cookie.expires);\n  }\n  if (cookie.maxAge) {\n    cookie.expires = new Date(Date.now() + cookie.maxAge * 1e3);\n  }\n  if (cookie.path === null || cookie.path === void 0) {\n    cookie.path = \"/\";\n  }\n  return cookie;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n  RequestCookies,\n  ResponseCookies,\n  parseCookie,\n  parseSetCookie,\n  stringifyCookie\n});\n","(()=>{\"use strict\";var e={56:e=>{\n/*!\n * bytes\n * Copyright(c) 2012-2014 TJ Holowaychuk\n * Copyright(c) 2015 Jed Watson\n * MIT Licensed\n */\ne.exports=bytes;e.exports.format=format;e.exports.parse=parse;var r=/\\B(?=(\\d{3})+(?!\\d))/g;var a=/(?:\\.0*|(\\.[^0]+)0+)$/;var t={b:1,kb:1<<10,mb:1<<20,gb:1<<30,tb:Math.pow(1024,4),pb:Math.pow(1024,5)};var i=/^((-|\\+)?(\\d+(?:\\.\\d+)?)) *(kb|mb|gb|tb|pb)$/i;function bytes(e,r){if(typeof e===\"string\"){return parse(e)}if(typeof e===\"number\"){return format(e,r)}return null}function format(e,i){if(!Number.isFinite(e)){return null}var n=Math.abs(e);var o=i&&i.thousandsSeparator||\"\";var s=i&&i.unitSeparator||\"\";var f=i&&i.decimalPlaces!==undefined?i.decimalPlaces:2;var u=Boolean(i&&i.fixedDecimals);var p=i&&i.unit||\"\";if(!p||!t[p.toLowerCase()]){if(n>=t.pb){p=\"PB\"}else if(n>=t.tb){p=\"TB\"}else if(n>=t.gb){p=\"GB\"}else if(n>=t.mb){p=\"MB\"}else if(n>=t.kb){p=\"KB\"}else{p=\"B\"}}var b=e/t[p.toLowerCase()];var l=b.toFixed(f);if(!u){l=l.replace(a,\"$1\")}if(o){l=l.split(\".\").map((function(e,a){return a===0?e.replace(r,o):e})).join(\".\")}return l+s+p}function parse(e){if(typeof e===\"number\"&&!isNaN(e)){return e}if(typeof e!==\"string\"){return null}var r=i.exec(e);var a;var n=\"b\";if(!r){a=parseInt(e,10);n=\"b\"}else{a=parseFloat(r[1]);n=r[4].toLowerCase()}return Math.floor(t[n]*a)}}};var r={};function __nccwpck_require__(a){var t=r[a];if(t!==undefined){return t.exports}var i=r[a]={exports:{}};var n=true;try{e[a](i,i.exports,__nccwpck_require__);n=false}finally{if(n)delete r[a]}return i.exports}if(typeof __nccwpck_require__!==\"undefined\")__nccwpck_require__.ab=__dirname+\"/\";var a=__nccwpck_require__(56);module.exports=a})();","(()=>{\"use strict\";if(typeof __nccwpck_require__!==\"undefined\")__nccwpck_require__.ab=__dirname+\"/\";var e={};(()=>{var r=e;\n/*!\n * cookie\n * Copyright(c) 2012-2014 Roman Shtylman\n * Copyright(c) 2015 Douglas Christopher Wilson\n * MIT Licensed\n */r.parse=parse;r.serialize=serialize;var i=decodeURIComponent;var t=encodeURIComponent;var a=/; */;var n=/^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;function parse(e,r){if(typeof e!==\"string\"){throw new TypeError(\"argument str must be a string\")}var t={};var n=r||{};var o=e.split(a);var s=n.decode||i;for(var p=0;p<o.length;p++){var f=o[p];var u=f.indexOf(\"=\");if(u<0){continue}var v=f.substr(0,u).trim();var c=f.substr(++u,f.length).trim();if('\"'==c[0]){c=c.slice(1,-1)}if(undefined==t[v]){t[v]=tryDecode(c,s)}}return t}function serialize(e,r,i){var a=i||{};var o=a.encode||t;if(typeof o!==\"function\"){throw new TypeError(\"option encode is invalid\")}if(!n.test(e)){throw new TypeError(\"argument name is invalid\")}var s=o(r);if(s&&!n.test(s)){throw new TypeError(\"argument val is invalid\")}var p=e+\"=\"+s;if(null!=a.maxAge){var f=a.maxAge-0;if(isNaN(f)||!isFinite(f)){throw new TypeError(\"option maxAge is invalid\")}p+=\"; Max-Age=\"+Math.floor(f)}if(a.domain){if(!n.test(a.domain)){throw new TypeError(\"option domain is invalid\")}p+=\"; Domain=\"+a.domain}if(a.path){if(!n.test(a.path)){throw new TypeError(\"option path is invalid\")}p+=\"; Path=\"+a.path}if(a.expires){if(typeof a.expires.toUTCString!==\"function\"){throw new TypeError(\"option expires is invalid\")}p+=\"; Expires=\"+a.expires.toUTCString()}if(a.httpOnly){p+=\"; HttpOnly\"}if(a.secure){p+=\"; Secure\"}if(a.sameSite){var u=typeof a.sameSite===\"string\"?a.sameSite.toLowerCase():a.sameSite;switch(u){case true:p+=\"; SameSite=Strict\";break;case\"lax\":p+=\"; SameSite=Lax\";break;case\"strict\":p+=\"; SameSite=Strict\";break;case\"none\":p+=\"; SameSite=None\";break;default:throw new TypeError(\"option sameSite is invalid\")}}return p}function tryDecode(e,r){try{return r(e)}catch(r){return e}}})();module.exports=e})();","(()=>{\"use strict\";var e={695:e=>{\n/*!\n * fresh\n * Copyright(c) 2012 TJ Holowaychuk\n * Copyright(c) 2016-2017 Douglas Christopher Wilson\n * MIT Licensed\n */\nvar r=/(?:^|,)\\s*?no-cache\\s*?(?:,|$)/;e.exports=fresh;function fresh(e,a){var t=e[\"if-modified-since\"];var s=e[\"if-none-match\"];if(!t&&!s){return false}var i=e[\"cache-control\"];if(i&&r.test(i)){return false}if(s&&s!==\"*\"){var f=a[\"etag\"];if(!f){return false}var n=true;var u=parseTokenList(s);for(var _=0;_<u.length;_++){var o=u[_];if(o===f||o===\"W/\"+f||\"W/\"+o===f){n=false;break}}if(n){return false}}if(t){var p=a[\"last-modified\"];var v=!p||!(parseHttpDate(p)<=parseHttpDate(t));if(v){return false}}return true}function parseHttpDate(e){var r=e&&Date.parse(e);return typeof r===\"number\"?r:NaN}function parseTokenList(e){var r=0;var a=[];var t=0;for(var s=0,i=e.length;s<i;s++){switch(e.charCodeAt(s)){case 32:if(t===r){t=r=s+1}break;case 44:a.push(e.substring(t,r));t=r=s+1;break;default:r=s+1;break}}a.push(e.substring(t,r));return a}}};var r={};function __nccwpck_require__(a){var t=r[a];if(t!==undefined){return t.exports}var s=r[a]={exports:{}};var i=true;try{e[a](s,s.exports,__nccwpck_require__);i=false}finally{if(i)delete r[a]}return s.exports}if(typeof __nccwpck_require__!==\"undefined\")__nccwpck_require__.ab=__dirname+\"/\";var a=__nccwpck_require__(695);module.exports=a})();","(()=>{\"use strict\";var e={993:e=>{var t=Object.prototype.hasOwnProperty,n=\"~\";function Events(){}if(Object.create){Events.prototype=Object.create(null);if(!(new Events).__proto__)n=false}function EE(e,t,n){this.fn=e;this.context=t;this.once=n||false}function addListener(e,t,r,i,s){if(typeof r!==\"function\"){throw new TypeError(\"The listener must be a function\")}var o=new EE(r,i||e,s),u=n?n+t:t;if(!e._events[u])e._events[u]=o,e._eventsCount++;else if(!e._events[u].fn)e._events[u].push(o);else e._events[u]=[e._events[u],o];return e}function clearEvent(e,t){if(--e._eventsCount===0)e._events=new Events;else delete e._events[t]}function EventEmitter(){this._events=new Events;this._eventsCount=0}EventEmitter.prototype.eventNames=function eventNames(){var e=[],r,i;if(this._eventsCount===0)return e;for(i in r=this._events){if(t.call(r,i))e.push(n?i.slice(1):i)}if(Object.getOwnPropertySymbols){return e.concat(Object.getOwnPropertySymbols(r))}return e};EventEmitter.prototype.listeners=function listeners(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,s=r.length,o=new Array(s);i<s;i++){o[i]=r[i].fn}return o};EventEmitter.prototype.listenerCount=function listenerCount(e){var t=n?n+e:e,r=this._events[t];if(!r)return 0;if(r.fn)return 1;return r.length};EventEmitter.prototype.emit=function emit(e,t,r,i,s,o){var u=n?n+e:e;if(!this._events[u])return false;var a=this._events[u],l=arguments.length,c,h;if(a.fn){if(a.once)this.removeListener(e,a.fn,undefined,true);switch(l){case 1:return a.fn.call(a.context),true;case 2:return a.fn.call(a.context,t),true;case 3:return a.fn.call(a.context,t,r),true;case 4:return a.fn.call(a.context,t,r,i),true;case 5:return a.fn.call(a.context,t,r,i,s),true;case 6:return a.fn.call(a.context,t,r,i,s,o),true}for(h=1,c=new Array(l-1);h<l;h++){c[h-1]=arguments[h]}a.fn.apply(a.context,c)}else{var _=a.length,f;for(h=0;h<_;h++){if(a[h].once)this.removeListener(e,a[h].fn,undefined,true);switch(l){case 1:a[h].fn.call(a[h].context);break;case 2:a[h].fn.call(a[h].context,t);break;case 3:a[h].fn.call(a[h].context,t,r);break;case 4:a[h].fn.call(a[h].context,t,r,i);break;default:if(!c)for(f=1,c=new Array(l-1);f<l;f++){c[f-1]=arguments[f]}a[h].fn.apply(a[h].context,c)}}}return true};EventEmitter.prototype.on=function on(e,t,n){return addListener(this,e,t,n,false)};EventEmitter.prototype.once=function once(e,t,n){return addListener(this,e,t,n,true)};EventEmitter.prototype.removeListener=function removeListener(e,t,r,i){var s=n?n+e:e;if(!this._events[s])return this;if(!t){clearEvent(this,s);return this}var o=this._events[s];if(o.fn){if(o.fn===t&&(!i||o.once)&&(!r||o.context===r)){clearEvent(this,s)}}else{for(var u=0,a=[],l=o.length;u<l;u++){if(o[u].fn!==t||i&&!o[u].once||r&&o[u].context!==r){a.push(o[u])}}if(a.length)this._events[s]=a.length===1?a[0]:a;else clearEvent(this,s)}return this};EventEmitter.prototype.removeAllListeners=function removeAllListeners(e){var t;if(e){t=n?n+e:e;if(this._events[t])clearEvent(this,t)}else{this._events=new Events;this._eventsCount=0}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.addListener=EventEmitter.prototype.on;EventEmitter.prefixed=n;EventEmitter.EventEmitter=EventEmitter;if(true){e.exports=EventEmitter}},213:e=>{e.exports=(e,t)=>{t=t||(()=>{});return e.then((e=>new Promise((e=>{e(t())})).then((()=>e))),(e=>new Promise((e=>{e(t())})).then((()=>{throw e}))))}},574:(e,t)=>{Object.defineProperty(t,\"__esModule\",{value:true});function lowerBound(e,t,n){let r=0;let i=e.length;while(i>0){const s=i/2|0;let o=r+s;if(n(e[o],t)<=0){r=++o;i-=s+1}else{i=s}}return r}t[\"default\"]=lowerBound},821:(e,t,n)=>{Object.defineProperty(t,\"__esModule\",{value:true});const r=n(574);class PriorityQueue{constructor(){this._queue=[]}enqueue(e,t){t=Object.assign({priority:0},t);const n={priority:t.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority){this._queue.push(n);return}const i=r.default(this._queue,n,((e,t)=>t.priority-e.priority));this._queue.splice(i,0,n)}dequeue(){const e=this._queue.shift();return e===null||e===void 0?void 0:e.run}filter(e){return this._queue.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this._queue.length}}t[\"default\"]=PriorityQueue},816:(e,t,n)=>{const r=n(213);class TimeoutError extends Error{constructor(e){super(e);this.name=\"TimeoutError\"}}const pTimeout=(e,t,n)=>new Promise(((i,s)=>{if(typeof t!==\"number\"||t<0){throw new TypeError(\"Expected `milliseconds` to be a positive number\")}if(t===Infinity){i(e);return}const o=setTimeout((()=>{if(typeof n===\"function\"){try{i(n())}catch(e){s(e)}return}const r=typeof n===\"string\"?n:`Promise timed out after ${t} milliseconds`;const o=n instanceof Error?n:new TimeoutError(r);if(typeof e.cancel===\"function\"){e.cancel()}s(o)}),t);r(e.then(i,s),(()=>{clearTimeout(o)}))}));e.exports=pTimeout;e.exports[\"default\"]=pTimeout;e.exports.TimeoutError=TimeoutError}};var t={};function __nccwpck_require__(n){var r=t[n];if(r!==undefined){return r.exports}var i=t[n]={exports:{}};var s=true;try{e[n](i,i.exports,__nccwpck_require__);s=false}finally{if(s)delete t[n]}return i.exports}if(typeof __nccwpck_require__!==\"undefined\")__nccwpck_require__.ab=__dirname+\"/\";var n={};(()=>{var e=n;Object.defineProperty(e,\"__esModule\",{value:true});const t=__nccwpck_require__(993);const r=__nccwpck_require__(816);const i=__nccwpck_require__(821);const empty=()=>{};const s=new r.TimeoutError;class PQueue extends t{constructor(e){var t,n,r,s;super();this._intervalCount=0;this._intervalEnd=0;this._pendingCount=0;this._resolveEmpty=empty;this._resolveIdle=empty;e=Object.assign({carryoverConcurrencyCount:false,intervalCap:Infinity,interval:0,concurrency:Infinity,autoStart:true,queueClass:i.default},e);if(!(typeof e.intervalCap===\"number\"&&e.intervalCap>=1)){throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:\"\"}\\` (${typeof e.intervalCap})`)}if(e.interval===undefined||!(Number.isFinite(e.interval)&&e.interval>=0)){throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${(s=(r=e.interval)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:\"\"}\\` (${typeof e.interval})`)}this._carryoverConcurrencyCount=e.carryoverConcurrencyCount;this._isIntervalIgnored=e.intervalCap===Infinity||e.interval===0;this._intervalCap=e.intervalCap;this._interval=e.interval;this._queue=new e.queueClass;this._queueClass=e.queueClass;this.concurrency=e.concurrency;this._timeout=e.timeout;this._throwOnTimeout=e.throwOnTimeout===true;this._isPaused=e.autoStart===false}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--;this._tryToStartAnother();this.emit(\"next\")}_resolvePromises(){this._resolveEmpty();this._resolveEmpty=empty;if(this._pendingCount===0){this._resolveIdle();this._resolveIdle=empty;this.emit(\"idle\")}}_onResumeInterval(){this._onInterval();this._initializeIntervalIfNeeded();this._timeoutId=undefined}_isIntervalPaused(){const e=Date.now();if(this._intervalId===undefined){const t=this._intervalEnd-e;if(t<0){this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}else{if(this._timeoutId===undefined){this._timeoutId=setTimeout((()=>{this._onResumeInterval()}),t)}return true}}return false}_tryToStartAnother(){if(this._queue.size===0){if(this._intervalId){clearInterval(this._intervalId)}this._intervalId=undefined;this._resolvePromises();return false}if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const t=this._queue.dequeue();if(!t){return false}this.emit(\"active\");t();if(e){this._initializeIntervalIfNeeded()}return true}}return false}_initializeIntervalIfNeeded(){if(this._isIntervalIgnored||this._intervalId!==undefined){return}this._intervalId=setInterval((()=>{this._onInterval()}),this._interval);this._intervalEnd=Date.now()+this._interval}_onInterval(){if(this._intervalCount===0&&this._pendingCount===0&&this._intervalId){clearInterval(this._intervalId);this._intervalId=undefined}this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;this._processQueue()}_processQueue(){while(this._tryToStartAnother()){}}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e===\"number\"&&e>=1)){throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${e}\\` (${typeof e})`)}this._concurrency=e;this._processQueue()}async add(e,t={}){return new Promise(((n,i)=>{const run=async()=>{this._pendingCount++;this._intervalCount++;try{const o=this._timeout===undefined&&t.timeout===undefined?e():r.default(Promise.resolve(e()),t.timeout===undefined?this._timeout:t.timeout,(()=>{if(t.throwOnTimeout===undefined?this._throwOnTimeout:t.throwOnTimeout){i(s)}return undefined}));n(await o)}catch(e){i(e)}this._next()};this._queue.enqueue(run,t);this._tryToStartAnother();this.emit(\"add\")}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){if(!this._isPaused){return this}this._isPaused=false;this._processQueue();return this}pause(){this._isPaused=true}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size===0){return}return new Promise((e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t();e()}}))}async onIdle(){if(this._pendingCount===0&&this._queue.size===0){return}return new Promise((e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t();e()}}))}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}e[\"default\"]=PQueue})();module.exports=n})();","(()=>{\"use strict\";if(typeof __nccwpck_require__!==\"undefined\")__nccwpck_require__.ab=__dirname+\"/\";var e={};(()=>{var n=e;Object.defineProperty(n,\"__esModule\",{value:true});n.pathToRegexp=n.tokensToRegexp=n.regexpToFunction=n.match=n.tokensToFunction=n.compile=n.parse=void 0;function lexer(e){var n=[];var r=0;while(r<e.length){var t=e[r];if(t===\"*\"||t===\"+\"||t===\"?\"){n.push({type:\"MODIFIER\",index:r,value:e[r++]});continue}if(t===\"\\\\\"){n.push({type:\"ESCAPED_CHAR\",index:r++,value:e[r++]});continue}if(t===\"{\"){n.push({type:\"OPEN\",index:r,value:e[r++]});continue}if(t===\"}\"){n.push({type:\"CLOSE\",index:r,value:e[r++]});continue}if(t===\":\"){var a=\"\";var i=r+1;while(i<e.length){var o=e.charCodeAt(i);if(o>=48&&o<=57||o>=65&&o<=90||o>=97&&o<=122||o===95){a+=e[i++];continue}break}if(!a)throw new TypeError(\"Missing parameter name at \".concat(r));n.push({type:\"NAME\",index:r,value:a});r=i;continue}if(t===\"(\"){var c=1;var f=\"\";var i=r+1;if(e[i]===\"?\"){throw new TypeError('Pattern cannot start with \"?\" at '.concat(i))}while(i<e.length){if(e[i]===\"\\\\\"){f+=e[i++]+e[i++];continue}if(e[i]===\")\"){c--;if(c===0){i++;break}}else if(e[i]===\"(\"){c++;if(e[i+1]!==\"?\"){throw new TypeError(\"Capturing groups are not allowed at \".concat(i))}}f+=e[i++]}if(c)throw new TypeError(\"Unbalanced pattern at \".concat(r));if(!f)throw new TypeError(\"Missing pattern at \".concat(r));n.push({type:\"PATTERN\",index:r,value:f});r=i;continue}n.push({type:\"CHAR\",index:r,value:e[r++]})}n.push({type:\"END\",index:r,value:\"\"});return n}function parse(e,n){if(n===void 0){n={}}var r=lexer(e);var t=n.prefixes,a=t===void 0?\"./\":t,i=n.delimiter,o=i===void 0?\"/#?\":i;var c=[];var f=0;var u=0;var p=\"\";var tryConsume=function(e){if(u<r.length&&r[u].type===e)return r[u++].value};var mustConsume=function(e){var n=tryConsume(e);if(n!==undefined)return n;var t=r[u],a=t.type,i=t.index;throw new TypeError(\"Unexpected \".concat(a,\" at \").concat(i,\", expected \").concat(e))};var consumeText=function(){var e=\"\";var n;while(n=tryConsume(\"CHAR\")||tryConsume(\"ESCAPED_CHAR\")){e+=n}return e};var isSafe=function(e){for(var n=0,r=o;n<r.length;n++){var t=r[n];if(e.indexOf(t)>-1)return true}return false};var safePattern=function(e){var n=c[c.length-1];var r=e||(n&&typeof n===\"string\"?n:\"\");if(n&&!r){throw new TypeError('Must have text between two parameters, missing text after \"'.concat(n.name,'\"'))}if(!r||isSafe(r))return\"[^\".concat(escapeString(o),\"]+?\");return\"(?:(?!\".concat(escapeString(r),\")[^\").concat(escapeString(o),\"])+?\")};while(u<r.length){var v=tryConsume(\"CHAR\");var s=tryConsume(\"NAME\");var d=tryConsume(\"PATTERN\");if(s||d){var g=v||\"\";if(a.indexOf(g)===-1){p+=g;g=\"\"}if(p){c.push(p);p=\"\"}c.push({name:s||f++,prefix:g,suffix:\"\",pattern:d||safePattern(g),modifier:tryConsume(\"MODIFIER\")||\"\"});continue}var x=v||tryConsume(\"ESCAPED_CHAR\");if(x){p+=x;continue}if(p){c.push(p);p=\"\"}var h=tryConsume(\"OPEN\");if(h){var g=consumeText();var l=tryConsume(\"NAME\")||\"\";var m=tryConsume(\"PATTERN\")||\"\";var T=consumeText();mustConsume(\"CLOSE\");c.push({name:l||(m?f++:\"\"),pattern:l&&!m?safePattern(g):m,prefix:g,suffix:T,modifier:tryConsume(\"MODIFIER\")||\"\"});continue}mustConsume(\"END\")}return c}n.parse=parse;function compile(e,n){return tokensToFunction(parse(e,n),n)}n.compile=compile;function tokensToFunction(e,n){if(n===void 0){n={}}var r=flags(n);var t=n.encode,a=t===void 0?function(e){return e}:t,i=n.validate,o=i===void 0?true:i;var c=e.map((function(e){if(typeof e===\"object\"){return new RegExp(\"^(?:\".concat(e.pattern,\")$\"),r)}}));return function(n){var r=\"\";for(var t=0;t<e.length;t++){var i=e[t];if(typeof i===\"string\"){r+=i;continue}var f=n?n[i.name]:undefined;var u=i.modifier===\"?\"||i.modifier===\"*\";var p=i.modifier===\"*\"||i.modifier===\"+\";if(Array.isArray(f)){if(!p){throw new TypeError('Expected \"'.concat(i.name,'\" to not repeat, but got an array'))}if(f.length===0){if(u)continue;throw new TypeError('Expected \"'.concat(i.name,'\" to not be empty'))}for(var v=0;v<f.length;v++){var s=a(f[v],i);if(o&&!c[t].test(s)){throw new TypeError('Expected all \"'.concat(i.name,'\" to match \"').concat(i.pattern,'\", but got \"').concat(s,'\"'))}r+=i.prefix+s+i.suffix}continue}if(typeof f===\"string\"||typeof f===\"number\"){var s=a(String(f),i);if(o&&!c[t].test(s)){throw new TypeError('Expected \"'.concat(i.name,'\" to match \"').concat(i.pattern,'\", but got \"').concat(s,'\"'))}r+=i.prefix+s+i.suffix;continue}if(u)continue;var d=p?\"an array\":\"a string\";throw new TypeError('Expected \"'.concat(i.name,'\" to be ').concat(d))}return r}}n.tokensToFunction=tokensToFunction;function match(e,n){var r=[];var t=pathToRegexp(e,r,n);return regexpToFunction(t,r,n)}n.match=match;function regexpToFunction(e,n,r){if(r===void 0){r={}}var t=r.decode,a=t===void 0?function(e){return e}:t;return function(r){var t=e.exec(r);if(!t)return false;var i=t[0],o=t.index;var c=Object.create(null);var _loop_1=function(e){if(t[e]===undefined)return\"continue\";var r=n[e-1];if(r.modifier===\"*\"||r.modifier===\"+\"){c[r.name]=t[e].split(r.prefix+r.suffix).map((function(e){return a(e,r)}))}else{c[r.name]=a(t[e],r)}};for(var f=1;f<t.length;f++){_loop_1(f)}return{path:i,index:o,params:c}}}n.regexpToFunction=regexpToFunction;function escapeString(e){return e.replace(/([.+*?=^!:${}()[\\]|/\\\\])/g,\"\\\\$1\")}function flags(e){return e&&e.sensitive?\"\":\"i\"}function regexpToRegexp(e,n){if(!n)return e;var r=/\\((?:\\?<(.*?)>)?(?!\\?)/g;var t=0;var a=r.exec(e.source);while(a){n.push({name:a[1]||t++,prefix:\"\",suffix:\"\",modifier:\"\",pattern:\"\"});a=r.exec(e.source)}return e}function arrayToRegexp(e,n,r){var t=e.map((function(e){return pathToRegexp(e,n,r).source}));return new RegExp(\"(?:\".concat(t.join(\"|\"),\")\"),flags(r))}function stringToRegexp(e,n,r){return tokensToRegexp(parse(e,r),n,r)}function tokensToRegexp(e,n,r){if(r===void 0){r={}}var t=r.strict,a=t===void 0?false:t,i=r.start,o=i===void 0?true:i,c=r.end,f=c===void 0?true:c,u=r.encode,p=u===void 0?function(e){return e}:u,v=r.delimiter,s=v===void 0?\"/#?\":v,d=r.endsWith,g=d===void 0?\"\":d;var x=\"[\".concat(escapeString(g),\"]|$\");var h=\"[\".concat(escapeString(s),\"]\");var l=o?\"^\":\"\";for(var m=0,T=e;m<T.length;m++){var E=T[m];if(typeof E===\"string\"){l+=escapeString(p(E))}else{var w=escapeString(p(E.prefix));var y=escapeString(p(E.suffix));if(E.pattern){if(n)n.push(E);if(w||y){if(E.modifier===\"+\"||E.modifier===\"*\"){var R=E.modifier===\"*\"?\"?\":\"\";l+=\"(?:\".concat(w,\"((?:\").concat(E.pattern,\")(?:\").concat(y).concat(w,\"(?:\").concat(E.pattern,\"))*)\").concat(y,\")\").concat(R)}else{l+=\"(?:\".concat(w,\"(\").concat(E.pattern,\")\").concat(y,\")\").concat(E.modifier)}}else{if(E.modifier===\"+\"||E.modifier===\"*\"){throw new TypeError('Can not repeat \"'.concat(E.name,'\" without a prefix and suffix'))}l+=\"(\".concat(E.pattern,\")\").concat(E.modifier)}}else{l+=\"(?:\".concat(w).concat(y,\")\").concat(E.modifier)}}}if(f){if(!a)l+=\"\".concat(h,\"?\");l+=!r.endsWith?\"$\":\"(?=\".concat(x,\")\")}else{var A=e[e.length-1];var _=typeof A===\"string\"?h.indexOf(A[A.length-1])>-1:A===undefined;if(!a){l+=\"(?:\".concat(h,\"(?=\").concat(x,\"))?\")}if(!_){l+=\"(?=\".concat(h,\"|\").concat(x,\")\")}}return new RegExp(l,flags(r))}n.tokensToRegexp=tokensToRegexp;function pathToRegexp(e,n,r){if(e instanceof RegExp)return regexpToRegexp(e,n);if(Array.isArray(e))return arrayToRegexp(e,n,r);return stringToRegexp(e,n,r)}n.pathToRegexp=pathToRegexp})();module.exports=e})();","const invalidServerComponentReactHooks = [\n  'useDeferredValue',\n  'useEffect',\n  'useEffectEvent',\n  'useImperativeHandle',\n  'useInsertionEffect',\n  'useLayoutEffect',\n  'useReducer',\n  'useRef',\n  'useState',\n  'useSyncExternalStore',\n  'useTransition',\n  'experimental_useOptimistic',\n  'useOptimistic',\n]\n\nfunction setMessage(error: Error, message: string): void {\n  error.message = message\n  if (error.stack) {\n    const lines = error.stack.split('\\n')\n    lines[0] = message\n    error.stack = lines.join('\\n')\n  }\n}\n\n/**\n * Input:\n * Error: Something went wrong\n    at funcName (/path/to/file.js:10:5)\n    at anotherFunc (/path/to/file.js:15:10)\n \n * Output:\n    at funcName (/path/to/file.js:10:5)\n    at anotherFunc (/path/to/file.js:15:10) \n */\nexport function getStackWithoutErrorMessage(error: Error): string {\n  const stack = error.stack\n  if (!stack) return ''\n  return stack.replace(/^[^\\n]*\\n/, '')\n}\n\nexport function formatServerError(error: Error): void {\n  if (typeof error?.message !== 'string') return\n\n  if (\n    error.message.includes(\n      'Class extends value undefined is not a constructor or null'\n    )\n  ) {\n    const addedMessage =\n      'This might be caused by a React Class Component being rendered in a Server Component, React Class Components only works in Client Components. Read more: https://nextjs.org/docs/messages/class-component-in-server-component'\n\n    // If this error instance already has the message, don't add it again\n    if (error.message.includes(addedMessage)) return\n\n    setMessage(\n      error,\n      `${error.message}\n\n${addedMessage}`\n    )\n    return\n  }\n\n  if (error.message.includes('createContext is not a function')) {\n    setMessage(\n      error,\n      'createContext only works in Client Components. Add the \"use client\" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component'\n    )\n    return\n  }\n\n  for (const clientHook of invalidServerComponentReactHooks) {\n    const regex = new RegExp(`\\\\b${clientHook}\\\\b.*is not a function`)\n    if (regex.test(error.message)) {\n      setMessage(\n        error,\n        `${clientHook} only works in Client Components. Add the \"use client\" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/react-client-hook-in-server-component`\n      )\n      return\n    }\n  }\n}\n","// This file should be imported before any others. It sets up the environment\n// for later imports to work properly.\n\n// expose AsyncLocalStorage on global for react usage if it isn't already provided by the environment\nif (typeof (globalThis as any).AsyncLocalStorage !== 'function') {\n  const { AsyncLocalStorage } =\n    require('async_hooks') as typeof import('async_hooks')\n  ;(globalThis as any).AsyncLocalStorage = AsyncLocalStorage\n}\n\nif (typeof (globalThis as any).WebSocket !== 'function') {\n  Object.defineProperty(globalThis, 'WebSocket', {\n    configurable: true,\n    get() {\n      return (\n        require('next/dist/compiled/ws') as typeof import('next/dist/compiled/ws')\n      ).WebSocket\n    },\n    set(value) {\n      Object.defineProperty(globalThis, 'WebSocket', {\n        configurable: true,\n        writable: true,\n        value,\n      })\n    },\n  })\n}\n","// Polyfill crypto() in the Node.js environment\n\nif (!global.crypto) {\n  let webcrypto: Crypto | undefined\n\n  Object.defineProperty(global, 'crypto', {\n    enumerable: false,\n    configurable: true,\n    get() {\n      if (!webcrypto) {\n        // @ts-expect-error -- TODO: Is this actually safe?\n        webcrypto = (require('node:crypto') as typeof import('node:crypto'))\n          .webcrypto\n      }\n      return webcrypto\n    },\n    set(value: Crypto) {\n      webcrypto = value\n    },\n  })\n}\n","/**\n * This module is for next.js server internal usage of path module.\n * It will use native path module for nodejs runtime.\n * It will use path-browserify polyfill for edge runtime.\n */\nlet path\n\nif (process.env.NEXT_RUNTIME === 'edge') {\n  path = require('next/dist/compiled/path-browserify')\n} else {\n  path = require('path')\n}\n\nmodule.exports = path\n","// Note: This file is JS because it's used by the taskfile-swc.js file, which is JS.\n// Keep file changes in sync with the corresponding `.d.ts` files.\n\n/**\n * These are the minimum browser versions that we consider \"modern\" and thus compile for by default.\n * This list was generated using `pnpm browserslist \"baseline widely available\"` on 2025-10-01.\n */\nconst MODERN_BROWSERSLIST_TARGET = [\n  'chrome 111',\n  'edge 111',\n  'firefox 111',\n  'safari 16.4',\n]\n\nmodule.exports = MODERN_BROWSERSLIST_TARGET\n","// getDefaultExport function for compatibility with non-ESM modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};\n","__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n        if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n            Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n        }\n    }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { findSourceMap as nativeFindSourceMap } from 'module'\nimport * as path from 'path'\nimport * as url from 'url'\nimport type * as util from 'util'\nimport { SourceMapConsumer as SyncSourceMapConsumer } from 'next/dist/compiled/source-map'\nimport {\n  type ModernSourceMapPayload,\n  devirtualizeReactServerURL,\n  findApplicableSourceMapPayload,\n  ignoreListAnonymousStackFramesIfSandwiched as ignoreListAnonymousStackFramesIfSandwichedGeneric,\n  sourceMapIgnoreListsEverything,\n} from './lib/source-maps'\nimport { parseStack, type StackFrame } from './lib/parse-stack'\nimport type { IgnorableStackFrame } from '../next-devtools/server/shared'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { dim, italic } from '../lib/picocolors'\n\ntype FindSourceMapPayload = (\n  sourceURL: string\n) => ModernSourceMapPayload | undefined\n// Find a source map using the bundler's API.\n// This is only a fallback for when Node.js fails to due to bugs e.g. https://github.com/nodejs/node/issues/52102\n// TODO: Remove once all supported Node.js versions are fixed.\n// TODO(veil): Set from Webpack as well\nlet bundlerFindSourceMapPayload: FindSourceMapPayload = () => undefined\n\nexport function setBundlerFindSourceMapImplementation(\n  findSourceMapImplementation: FindSourceMapPayload\n): void {\n  bundlerFindSourceMapPayload = findSourceMapImplementation\n}\n\n// Code frame renderer - injected by dev/build to avoid hard dependency on native bindings\ntype CodeFrameRenderer = (\n  frame: IgnorableStackFrame,\n  source: string | null,\n  colors: boolean\n) => string | null\n\nlet codeFrameRenderer: CodeFrameRenderer | undefined\n\nexport function setCodeFrameRenderer(renderer: CodeFrameRenderer): void {\n  codeFrameRenderer = renderer\n}\n\nfunction getOriginalCodeFrame(\n  frame: IgnorableStackFrame,\n  source: string | null,\n  colors: boolean = process.stdout.isTTY\n): string | null {\n  if (!codeFrameRenderer) {\n    // No renderer available - gracefully degrade\n    return null\n  }\n  return codeFrameRenderer(frame, source, colors)\n}\n\ntype SourceMapCache = Map<\n  string,\n  null | { map: SyncSourceMapConsumer; payload: ModernSourceMapPayload }\n>\n\nfunction frameToString(\n  methodName: string | null,\n  sourceURL: string | null,\n  line1: number | null,\n  column1: number | null\n): string {\n  let sourceLocation = line1 !== null ? `:${line1}` : ''\n  if (column1 !== null && sourceLocation !== '') {\n    sourceLocation += `:${column1}`\n  }\n\n  let fileLocation: string | null\n  if (\n    sourceURL !== null &&\n    sourceURL.startsWith('file://') &&\n    URL.canParse(sourceURL)\n  ) {\n    // If not relative to CWD, the path is ambiguous to IDEs and clicking will prompt to select the file first.\n    // In a multi-app repo, this leads to potentially larger file names but will make clicking snappy.\n    // There's no tradeoff for the cases where `dir` in `next dev [dir]` is omitted\n    // since relative to cwd is both the shortest and snappiest.\n    fileLocation = path.relative(process.cwd(), url.fileURLToPath(sourceURL))\n  } else if (sourceURL !== null && sourceURL.startsWith('/')) {\n    fileLocation = path.relative(process.cwd(), sourceURL)\n  } else {\n    fileLocation = sourceURL\n  }\n\n  return methodName\n    ? `    at ${methodName} (${fileLocation}${sourceLocation})`\n    : `    at ${fileLocation}${sourceLocation}`\n}\n\nfunction computeErrorName(error: Error): string {\n  // TODO: Node.js seems to use a different algorithm\n  // class ReadonlyRequestCookiesError extends Error {}` would read `ReadonlyRequestCookiesError: [...]`\n  // in the stack i.e. seems like under certain conditions it favors the constructor name.\n  return error.name || 'Error'\n}\n\nfunction prepareUnsourcemappedStackTrace(\n  error: Error,\n  structuredStackTrace: any[]\n): string {\n  const name = computeErrorName(error)\n  const message = error.message || ''\n  let stack = name + ': ' + message\n  for (let i = 0; i < structuredStackTrace.length; i++) {\n    stack += '\\n    at ' + structuredStackTrace[i].toString()\n  }\n  return stack\n}\n\nfunction shouldIgnoreListGeneratedFrame(file: string): boolean {\n  return file.startsWith('node:') || file.includes('node_modules')\n}\n\nfunction shouldIgnoreListOriginalFrame(file: string): boolean {\n  return file.includes('node_modules')\n}\n\ninterface SourcemappableStackFrame extends StackFrame {\n  file: NonNullable<StackFrame['file']>\n}\n\ninterface SourceMappedFrame {\n  stack: IgnorableStackFrame\n  // DEV only\n  code: string | null\n}\n\nfunction createUnsourcemappedFrame(\n  frame: SourcemappableStackFrame\n): SourceMappedFrame {\n  return {\n    stack: {\n      file: frame.file,\n      line1: frame.line1,\n      column1: frame.column1,\n      methodName: frame.methodName,\n      arguments: frame.arguments,\n      ignored: shouldIgnoreListGeneratedFrame(frame.file),\n    },\n    code: null,\n  }\n}\n\nfunction ignoreListAnonymousStackFramesIfSandwiched(\n  sourceMappedFrames: Array<{\n    stack: IgnorableStackFrame\n    code: string | null\n  }>\n) {\n  return ignoreListAnonymousStackFramesIfSandwichedGeneric(\n    sourceMappedFrames,\n    (frame) => frame.stack.file === '<anonymous>',\n    (frame) => frame.stack.ignored,\n    (frame) => frame.stack.methodName,\n    (frame) => {\n      frame.stack.ignored = true\n    }\n  )\n}\n\n/**\n * @param frame\n * @param sourceMapCache\n * @returns The original frame if not sourcemapped.\n */\nfunction getSourcemappedFrameIfPossible(\n  frame: SourcemappableStackFrame,\n  sourceMapCache: SourceMapCache,\n  inspectOptions: util.InspectOptions\n): {\n  stack: IgnorableStackFrame\n  code: string | null\n} {\n  const sourceMapCacheEntry = sourceMapCache.get(frame.file)\n  let sourceMapConsumer: SyncSourceMapConsumer\n  let sourceMapPayload: ModernSourceMapPayload\n  if (sourceMapCacheEntry === undefined) {\n    let sourceURL = frame.file\n    // e.g. \"/Users/foo/APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js\"\n    // or \"C:\\Users\\foo\\APP\\.next\\server\\chunks\\ssr\\[root-of-the-server]__2934a0._.js\"\n    // will be keyed by Node.js as \"file:///APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js\".\n    // This is likely caused by `callsite.toString()` in `Error.prepareStackTrace converting file URLs to paths.\n    //\n    // But frame.file might also be \"webpack-internal:///(rsc)/./app/bad-sourcemap/page.js\" or\n    // \"<anonymous>\" or \"node:internal/process/task_queues\" here\n    if (path.isAbsolute(frame.file)) {\n      sourceURL = url.pathToFileURL(frame.file).toString()\n    }\n    let maybeSourceMapPayload: ModernSourceMapPayload | undefined\n    try {\n      const sourceMap = nativeFindSourceMap(sourceURL)\n      maybeSourceMapPayload = sourceMap?.payload\n    } catch (cause) {\n      // We should not log an actual error instance here because that will re-enter\n      // this codepath during error inspection and could lead to infinite recursion.\n      console.error(\n        `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n      )\n      // If loading fails once, it'll fail every time.\n      // So set the cache to avoid duplicate errors.\n      sourceMapCache.set(frame.file, null)\n      // Don't even fall back to the bundler because it might be not as strict\n      // with regards to parsing and then we fail later once we consume the\n      // source map payload.\n      // This essentially avoids a redundant error where we fail here and then\n      // later on consumption because the bundler just handed back an invalid\n      // source map.\n      return createUnsourcemappedFrame(frame)\n    }\n    if (maybeSourceMapPayload === undefined) {\n      maybeSourceMapPayload = bundlerFindSourceMapPayload(sourceURL)\n    }\n\n    if (maybeSourceMapPayload === undefined) {\n      return createUnsourcemappedFrame(frame)\n    }\n    sourceMapPayload = maybeSourceMapPayload\n    try {\n      // Pass the source map URL as the second parameter so that the consumer\n      // can resolve relative paths in the source map's `sources` array. This is\n      // a guess! Turbopack places .map files as siblings to the chunks so this\n      // is sufficient to compute relative paths but is actually wrong (the\n      // chunk and sourcemap have different content hashes). We are using the\n      // node API to read the sourcemap and it doesn't give us access to the\n      // URI. Devirtualize `about://React/Server/file:///path/to/chunk.js?4` to\n      // `file:///path/to/chunk.js` so that relative `sources` in the source map\n      // resolve against the real chunk URL, not the virtual one.\n      const sourceMapURL = devirtualizeReactServerURL(sourceURL) + '.map'\n      sourceMapConsumer = new SyncSourceMapConsumer(\n        sourceMapPayload,\n        // @ts-expect-error: our typings don't include this parameter but it is here.\n        sourceMapURL\n      )\n    } catch (cause) {\n      // We should not log an actual error instance here because that will re-enter\n      // this codepath during error inspection and could lead to infinite recursion.\n      console.error(\n        `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n      )\n      // If creating the consumer fails once, it'll fail every time.\n      // So set the cache to avoid duplicate errors.\n      sourceMapCache.set(frame.file, null)\n      return createUnsourcemappedFrame(frame)\n    }\n    sourceMapCache.set(frame.file, {\n      map: sourceMapConsumer,\n      payload: sourceMapPayload,\n    })\n  } else if (sourceMapCacheEntry === null) {\n    // We failed earlier getting the payload or consumer.\n    // Just return an unsourcemapped frame.\n    // Errors will already be logged.\n    return createUnsourcemappedFrame(frame)\n  } else {\n    sourceMapConsumer = sourceMapCacheEntry.map\n    sourceMapPayload = sourceMapCacheEntry.payload\n  }\n\n  const sourcePosition = sourceMapConsumer.originalPositionFor({\n    column: (frame.column1 ?? 1) - 1,\n    line: frame.line1 ?? 1,\n  })\n\n  const applicableSourceMap = findApplicableSourceMapPayload(\n    (frame.line1 ?? 1) - 1,\n    (frame.column1 ?? 1) - 1,\n    sourceMapPayload\n  )\n  let ignored =\n    applicableSourceMap !== undefined &&\n    sourceMapIgnoreListsEverything(applicableSourceMap)\n  if (sourcePosition.source === null) {\n    return {\n      stack: {\n        arguments: frame.arguments,\n        file: frame.file,\n        line1: frame.line1,\n        column1: frame.column1,\n        methodName: frame.methodName,\n        ignored: ignored || shouldIgnoreListGeneratedFrame(frame.file),\n      },\n      code: null,\n    }\n  }\n\n  // TODO(veil): Upstream a method to sourcemap consumer that immediately says if a frame is ignored or not.\n  if (applicableSourceMap === undefined) {\n    console.error('No applicable source map found in sections for frame', frame)\n  } else if (!ignored && shouldIgnoreListOriginalFrame(sourcePosition.source)) {\n    // Externals may be libraries that don't ship ignoreLists.\n    // This is really taking control away from libraries.\n    // They should still ship `ignoreList` so that attached debuggers ignore-list their frames.\n    // TODO: Maybe only ignore library sourcemaps if `ignoreList` is absent?\n    // Though keep in mind that Turbopack omits empty `ignoreList`.\n    // So if we establish this convention, we should communicate it to the ecosystem.\n    ignored = true\n  } else if (!ignored) {\n    // TODO: O(n^2). Consider moving `ignoreList` into a Set\n    const sourceIndex = applicableSourceMap.sources.indexOf(\n      sourcePosition.source\n    )\n    ignored = applicableSourceMap.ignoreList?.includes(sourceIndex) ?? false\n  }\n\n  const originalFrame: IgnorableStackFrame = {\n    // We ignore the sourcemapped name since it won't be the correct name.\n    // The callsite will point to the column of the variable name instead of the\n    // name of the enclosing function.\n    // TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.\n    methodName: frame.methodName\n      ?.replace('__WEBPACK_DEFAULT_EXPORT__', 'default')\n      ?.replace('__webpack_exports__.', ''),\n    file: sourcePosition.source,\n    line1: sourcePosition.line,\n    column1: sourcePosition.column + 1,\n    // TODO: c&p from async createOriginalStackFrame but why not frame.arguments?\n    arguments: [],\n    ignored,\n  }\n\n  /** undefined = not yet computed */\n  let codeFrame: string | null | undefined\n\n  return {\n    stack: originalFrame,\n    get code() {\n      if (codeFrame === undefined) {\n        const sourceContent: string | null =\n          sourceMapConsumer.sourceContentFor(\n            sourcePosition.source,\n            /* returnNullOnMissing */ true\n          ) ?? null\n        codeFrame = getOriginalCodeFrame(\n          originalFrame,\n          sourceContent,\n          inspectOptions.colors\n        )\n      }\n      return codeFrame\n    },\n  }\n}\n\nfunction parseAndSourceMap(\n  error: Error,\n  inspectOptions: util.InspectOptions\n): string {\n  const showIgnoreListed = process.env.__NEXT_SHOW_IGNORE_LISTED === 'true'\n  // We overwrote Error.prepareStackTrace earlier so error.stack is not sourcemapped.\n  let unparsedStack = String(error.stack)\n  // We could just read it from `error.stack`.\n  // This works around cases where a 3rd party `Error.prepareStackTrace` implementation\n  // doesn't implement the name computation correctly.\n  const errorName = computeErrorName(error)\n\n  let idx = unparsedStack.indexOf('react_stack_bottom_frame')\n  if (idx !== -1) {\n    idx = unparsedStack.lastIndexOf('\\n', idx)\n  } else {\n    idx = unparsedStack.indexOf('react-stack-bottom-frame')\n    if (idx !== -1) {\n      idx = unparsedStack.lastIndexOf('\\n', idx)\n    }\n  }\n  if (idx !== -1 && !showIgnoreListed) {\n    // Cut off everything after the bottom frame since it'll be React internals.\n    unparsedStack = unparsedStack.slice(0, idx)\n  }\n\n  const unsourcemappedStack = parseStack(unparsedStack)\n  const sourceMapCache: SourceMapCache = new Map()\n\n  const sourceMappedFrames: Array<{\n    stack: IgnorableStackFrame\n    code: string | null\n  }> = []\n  let sourceFrame: null | string = null\n  for (const frame of unsourcemappedStack) {\n    if (frame.file === null) {\n      sourceMappedFrames.push({\n        code: null,\n        stack: {\n          file: frame.file,\n          line1: frame.line1,\n          column1: frame.column1,\n          methodName: frame.methodName,\n          arguments: frame.arguments,\n          ignored: false,\n        },\n      })\n    } else {\n      const sourcemappedFrame = getSourcemappedFrameIfPossible(\n        // We narrowed this earlier by bailing if `frame.file` is null.\n        frame as SourcemappableStackFrame,\n        sourceMapCache,\n        inspectOptions\n      )\n      sourceMappedFrames.push(sourcemappedFrame)\n\n      // We can determine the sourceframe here.\n      // anonymous frames won't have a sourceframe so we don't need to scan\n      // all stacks again to check if they are sandwiched between ignored frames.\n      if (\n        sourceFrame === null &&\n        // TODO: Is this the right choice?\n        !sourcemappedFrame.stack.ignored &&\n        sourcemappedFrame.code !== null\n      ) {\n        sourceFrame = sourcemappedFrame.code\n      }\n    }\n  }\n\n  ignoreListAnonymousStackFramesIfSandwiched(sourceMappedFrames)\n\n  let sourceMappedStack = ''\n  for (let i = 0; i < sourceMappedFrames.length; i++) {\n    const frame = sourceMappedFrames[i]\n\n    if (!frame.stack.ignored) {\n      sourceMappedStack +=\n        '\\n' +\n        frameToString(\n          frame.stack.methodName,\n          frame.stack.file,\n          frame.stack.line1,\n          frame.stack.column1\n        )\n    } else if (showIgnoreListed) {\n      sourceMappedStack +=\n        '\\n' +\n        dim(\n          frameToString(\n            frame.stack.methodName,\n            frame.stack.file,\n            frame.stack.line1,\n            frame.stack.column1\n          )\n        )\n    }\n  }\n\n  if (sourceMappedStack === '' && sourceMappedFrames.length > 0) {\n    // The `at` marker is important so that Node.js doesn't add square brackets\n    // around the stringified error i.e. this results in\n    // Error: message\n    //   at <ignore-listed frames>\n    // instead of\n    // [Error: message\n    //   at <ignore-listed frames>]\n    sourceMappedStack = '\\n    at ' + italic('ignore-listed frames')\n  }\n\n  return (\n    errorName +\n    ': ' +\n    error.message +\n    sourceMappedStack +\n    (sourceFrame !== null ? '\\n' + sourceFrame : '')\n  )\n}\n\nfunction sourceMapError(\n  this: void,\n  error: Error,\n  inspectOptions: util.InspectOptions\n): Error {\n  // Setting an undefined `cause` would print `[cause]: undefined`\n  const options = error.cause !== undefined ? { cause: error.cause } : undefined\n\n  // Create a new Error object with the source mapping applied and then use native\n  // Node.js formatting on the result.\n  const newError =\n    error instanceof AggregateError\n      ? // Preserve AggregateError's `errors` instance property\n        new AggregateError(error.errors, error.message, options)\n      : new Error(error.message, options)\n\n  // TODO: Ensure `class MyError extends Error {}` prints `MyError` as the name\n  newError.stack = parseAndSourceMap(error, inspectOptions)\n\n  for (const key in error) {\n    if (!Object.prototype.hasOwnProperty.call(newError, key)) {\n      // @ts-expect-error -- We're copying all enumerable properties.\n      // So they definitely exist on `this` and obviously have no type on `newError` (yet)\n      newError[key] = error[key]\n    }\n  }\n\n  return newError\n}\n\nexport function patchErrorInspectNodeJS(\n  errorConstructor: ErrorConstructor\n): void {\n  const inspectSymbol = Symbol.for('nodejs.util.inspect.custom')\n\n  errorConstructor.prepareStackTrace = prepareUnsourcemappedStackTrace\n\n  // @ts-expect-error -- TODO upstream types\n  errorConstructor.prototype[inspectSymbol] = function (\n    depth: number,\n    inspectOptions: util.InspectOptions,\n    inspect: typeof util.inspect\n  ): string {\n    // avoid false-positive dynamic i/o warnings e.g. due to usage of `Math.random` in `source-map`.\n    return workUnitAsyncStorage.exit(() => {\n      const newError = sourceMapError(this, inspectOptions)\n\n      const originalCustomInspect = (newError as any)[inspectSymbol]\n      // Prevent infinite recursion.\n      // { customInspect: false } would result in `error.cause` not using our inspect.\n      Object.defineProperty(newError, inspectSymbol, {\n        value: undefined,\n        enumerable: false,\n        writable: true,\n      })\n      try {\n        return inspect(newError, {\n          ...inspectOptions,\n          depth,\n        })\n      } finally {\n        ;(newError as any)[inspectSymbol] = originalCustomInspect\n      }\n    })\n  }\n}\n\nexport function patchErrorInspectEdgeLite(\n  errorConstructor: ErrorConstructor\n): void {\n  const inspectSymbol = Symbol.for('edge-runtime.inspect.custom')\n\n  errorConstructor.prepareStackTrace = prepareUnsourcemappedStackTrace\n\n  // @ts-expect-error -- TODO upstream types\n  errorConstructor.prototype[inspectSymbol] = function ({\n    format,\n  }: {\n    format: (...args: unknown[]) => string\n  }): string {\n    // avoid false-positive dynamic i/o warnings e.g. due to usage of `Math.random` in `source-map`.\n    return workUnitAsyncStorage.exit(() => {\n      const newError = sourceMapError(this, {})\n\n      const originalCustomInspect = (newError as any)[inspectSymbol]\n      // Prevent infinite recursion.\n      Object.defineProperty(newError, inspectSymbol, {\n        value: undefined,\n        enumerable: false,\n        writable: true,\n      })\n      try {\n        return format(newError)\n      } finally {\n        ;(newError as any)[inspectSymbol] = originalCustomInspect\n      }\n    })\n  }\n}\n","/**\n * We extend Web Crypto APIs during builds and revalidates to ensure that prerenders don't observe random bytes\n * When cacheComponents is enabled. Random bytes are a form of IO even if they resolve synchronously. When cacheComponents is\n * enabled we need to ensure that random bytes are excluded from prerenders unless they are cached.\n *\n *\n * The extensions here never error nor alter the underlying return values and thus should be transparent to callers.\n */\n\nimport { io } from './io-utils'\n\nlet webCrypto: typeof crypto\nif (process.env.NEXT_RUNTIME === 'edge') {\n  webCrypto = crypto\n} else {\n  if (typeof crypto === 'undefined') {\n    // @ts-expect-error -- TODO: Is this actually safe?\n    webCrypto = (require('node:crypto') as typeof import('node:crypto'))\n      .webcrypto\n  } else {\n    webCrypto = crypto\n  }\n}\n\nconst getRandomValuesExpression = '`crypto.getRandomValues()`'\ntry {\n  const _getRandomValues = webCrypto.getRandomValues\n  webCrypto.getRandomValues = function getRandomValues() {\n    io(getRandomValuesExpression, 'crypto')\n    return _getRandomValues.apply(webCrypto, arguments as any)\n  }\n} catch {\n  console.error(\n    `Failed to install ${getRandomValuesExpression} extension. When using \\`cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n  )\n}\n\nconst randomUUIDExpression = '`crypto.randomUUID()`'\ntry {\n  const _randomUUID = webCrypto.randomUUID\n  webCrypto.randomUUID = function randomUUID() {\n    io(randomUUIDExpression, 'crypto')\n    return _randomUUID.apply(webCrypto, arguments as any)\n  } as typeof _randomUUID\n} catch {\n  console.error(\n    `Failed to install ${getRandomValuesExpression} extension. When using \\`cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n  )\n}\n","import { InvariantError } from '../../shared/lib/invariant-error'\nimport { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'\n\nexport enum RenderStage {\n  Before = 1,\n  EarlyStatic = 2,\n  Static = 3,\n  EarlyRuntime = 4,\n  Runtime = 5,\n  Dynamic = 6,\n  Abandoned = 7,\n}\n\nexport type AdvanceableRenderStage =\n  | RenderStage.Static\n  | RenderStage.EarlyRuntime\n  | RenderStage.Runtime\n  | RenderStage.Dynamic\n\nexport class StagedRenderingController {\n  currentStage: RenderStage = RenderStage.Before\n\n  syncInterruptReason: Error | null = null\n  staticStageEndTime: number = Infinity\n  runtimeStageEndTime: number = Infinity\n\n  private staticStageListeners: Array<() => void> = []\n  private earlyRuntimeStageListeners: Array<() => void> = []\n  private runtimeStageListeners: Array<() => void> = []\n  private dynamicStageListeners: Array<() => void> = []\n\n  private staticStagePromise = createPromiseWithResolvers<void>()\n  private earlyRuntimeStagePromise = createPromiseWithResolvers<void>()\n  private runtimeStagePromise = createPromiseWithResolvers<void>()\n  private dynamicStagePromise = createPromiseWithResolvers<void>()\n\n  constructor(\n    private abortSignal: AbortSignal | null,\n    private abandonController: AbortController | null,\n    private shouldTrackSyncIO: boolean\n  ) {\n    if (abortSignal) {\n      abortSignal.addEventListener(\n        'abort',\n        () => {\n          // Reject all stage promises that haven't already been resolved.\n          // If a promise was already resolved via advanceStage, the reject\n          // is a no-op. The ignoreReject handler suppresses unhandled\n          // rejection warnings for promises that no one is awaiting.\n          const { reason } = abortSignal\n          this.staticStagePromise.promise.catch(ignoreReject)\n          this.staticStagePromise.reject(reason)\n          this.earlyRuntimeStagePromise.promise.catch(ignoreReject)\n          this.earlyRuntimeStagePromise.reject(reason)\n          this.runtimeStagePromise.promise.catch(ignoreReject)\n          this.runtimeStagePromise.reject(reason)\n          this.dynamicStagePromise.promise.catch(ignoreReject)\n          this.dynamicStagePromise.reject(reason)\n        },\n        { once: true }\n      )\n    }\n\n    if (abandonController) {\n      abandonController.signal.addEventListener(\n        'abort',\n        () => {\n          this.abandonRender()\n        },\n        { once: true }\n      )\n    }\n  }\n\n  onStage(stage: AdvanceableRenderStage, callback: () => void) {\n    if (this.currentStage >= stage) {\n      callback()\n    } else if (stage === RenderStage.Static) {\n      this.staticStageListeners.push(callback)\n    } else if (stage === RenderStage.EarlyRuntime) {\n      this.earlyRuntimeStageListeners.push(callback)\n    } else if (stage === RenderStage.Runtime) {\n      this.runtimeStageListeners.push(callback)\n    } else if (stage === RenderStage.Dynamic) {\n      this.dynamicStageListeners.push(callback)\n    } else {\n      // This should never happen\n      throw new InvariantError(`Invalid render stage: ${stage}`)\n    }\n  }\n\n  shouldTrackSyncInterrupt(): boolean {\n    if (!this.shouldTrackSyncIO) {\n      return false\n    }\n\n    switch (this.currentStage) {\n      case RenderStage.Before:\n        // If we haven't started the render yet, it can't be interrupted.\n        return false\n      case RenderStage.EarlyStatic:\n      case RenderStage.Static:\n        return true\n      case RenderStage.EarlyRuntime:\n        // EarlyRuntime is for runtime-prefetchable segments. Sync IO\n        // should error because it would abort a runtime prefetch.\n        return true\n      case RenderStage.Runtime:\n        // Runtime is for non-prefetchable segments. Sync IO is fine there\n        // because in practice this segment will never be runtime prefetched\n        return false\n      case RenderStage.Dynamic:\n      case RenderStage.Abandoned:\n        return false\n      default:\n        return false\n    }\n  }\n\n  syncInterruptCurrentStageWithReason(reason: Error) {\n    if (this.currentStage === RenderStage.Before) {\n      return\n    }\n\n    // If the render has already been abandoned, there's nothing to interrupt.\n    if (this.currentStage === RenderStage.Abandoned) {\n      return\n    }\n\n    // If Sync IO occurs during an abandonable render, we trigger the abandon.\n    // The abandon listener will call abandonRender which advances through\n    // stages to let caches fill before marking as Abandoned.\n    if (this.abandonController) {\n      this.abandonController.abort()\n      return\n    }\n\n    if (this.abortSignal) {\n      // If this is an abortable render, we capture the interruption reason and stop advancing.\n      // We don't release any more promises.\n      // The caller is expected to abort the signal.\n      this.syncInterruptReason = reason\n      this.currentStage = RenderStage.Abandoned\n      return\n    }\n\n    // If we're in a non-abandonable & non-abortable render,\n    // we need to advance to the Dynamic stage and capture the interruption reason.\n    // (in dev, this will be the restarted render)\n    switch (this.currentStage) {\n      case RenderStage.EarlyStatic:\n      case RenderStage.Static:\n      case RenderStage.EarlyRuntime: {\n        // EarlyRuntime is for runtime-prefetchable segments. Sync IO here\n        // means the prefetch would be aborted too early.\n        this.syncInterruptReason = reason\n        this.advanceStage(RenderStage.Dynamic)\n        return\n      }\n      case RenderStage.Runtime: {\n        // canSyncInterrupt returns false for Runtime, so we should\n        // never get here. Defensive no-op.\n        return\n      }\n      case RenderStage.Dynamic:\n      default:\n    }\n  }\n\n  getSyncInterruptReason() {\n    return this.syncInterruptReason\n  }\n\n  getStaticStageEndTime() {\n    return this.staticStageEndTime\n  }\n\n  getRuntimeStageEndTime() {\n    return this.runtimeStageEndTime\n  }\n\n  private abandonRender() {\n    // In staged rendering, only the initial render is abandonable.\n    // We can abandon the initial render if\n    //   1. We notice a cache miss, and need to wait for caches to fill\n    //   2. A sync IO error occurs, and the render should be interrupted\n    //      (this might be a lazy intitialization of a module,\n    //       so we still want to restart in this case and see if it still occurs)\n    // In either case, we'll be doing another render after this one,\n    // so we only want to unblock the next stage, not Dynamic, because\n    // unblocking the dynamic stage would likely lead to wasted (uncached) IO.\n    const { currentStage } = this\n    switch (currentStage) {\n      case RenderStage.EarlyStatic: {\n        this.resolveStaticStage()\n      }\n      // intentional fallthrough\n      case RenderStage.Static: {\n        this.resolveEarlyRuntimeStage()\n      }\n      // intentional fallthrough\n      case RenderStage.EarlyRuntime: {\n        this.resolveRuntimeStage()\n      }\n      // intentional fallthrough\n      case RenderStage.Runtime: {\n        this.currentStage = RenderStage.Abandoned\n        return\n      }\n      case RenderStage.Dynamic:\n      case RenderStage.Before:\n      case RenderStage.Abandoned:\n        break\n      default: {\n        currentStage satisfies never\n      }\n    }\n  }\n\n  advanceStage(\n    stage:\n      | RenderStage.EarlyStatic\n      | RenderStage.Static\n      | RenderStage.EarlyRuntime\n      | RenderStage.Runtime\n      | RenderStage.Dynamic\n  ) {\n    // If we're already at the target stage or beyond, do nothing.\n    // (this can happen e.g. if sync IO advanced us to the dynamic stage)\n    if (stage <= this.currentStage) {\n      return\n    }\n\n    let currentStage = this.currentStage\n    this.currentStage = stage\n\n    if (currentStage < RenderStage.Static && stage >= RenderStage.Static) {\n      this.resolveStaticStage()\n    }\n    if (\n      currentStage < RenderStage.EarlyRuntime &&\n      stage >= RenderStage.EarlyRuntime\n    ) {\n      this.resolveEarlyRuntimeStage()\n    }\n    if (currentStage < RenderStage.Runtime && stage >= RenderStage.Runtime) {\n      this.staticStageEndTime = performance.now() + performance.timeOrigin\n      this.resolveRuntimeStage()\n    }\n    if (currentStage < RenderStage.Dynamic && stage >= RenderStage.Dynamic) {\n      this.runtimeStageEndTime = performance.now() + performance.timeOrigin\n      this.resolveDynamicStage()\n      return\n    }\n  }\n\n  /** Fire the `onStage` listeners for the static stage and unblock any promises waiting for it. */\n  private resolveStaticStage() {\n    const staticListeners = this.staticStageListeners\n    for (let i = 0; i < staticListeners.length; i++) {\n      staticListeners[i]()\n    }\n    staticListeners.length = 0\n    this.staticStagePromise.resolve()\n  }\n\n  /** Fire the `onStage` listeners for the early runtime stage and unblock any promises waiting for it. */\n  private resolveEarlyRuntimeStage() {\n    const earlyRuntimeListeners = this.earlyRuntimeStageListeners\n    for (let i = 0; i < earlyRuntimeListeners.length; i++) {\n      earlyRuntimeListeners[i]()\n    }\n    earlyRuntimeListeners.length = 0\n    this.earlyRuntimeStagePromise.resolve()\n  }\n\n  /** Fire the `onStage` listeners for the runtime stage and unblock any promises waiting for it. */\n  private resolveRuntimeStage() {\n    const runtimeListeners = this.runtimeStageListeners\n    for (let i = 0; i < runtimeListeners.length; i++) {\n      runtimeListeners[i]()\n    }\n    runtimeListeners.length = 0\n    this.runtimeStagePromise.resolve()\n  }\n\n  /** Fire the `onStage` listeners for the dynamic stage and unblock any promises waiting for it. */\n  private resolveDynamicStage() {\n    const dynamicListeners = this.dynamicStageListeners\n    for (let i = 0; i < dynamicListeners.length; i++) {\n      dynamicListeners[i]()\n    }\n    dynamicListeners.length = 0\n    this.dynamicStagePromise.resolve()\n  }\n\n  private getStagePromise(stage: AdvanceableRenderStage): Promise<void> {\n    switch (stage) {\n      case RenderStage.Static: {\n        return this.staticStagePromise.promise\n      }\n      case RenderStage.EarlyRuntime: {\n        return this.earlyRuntimeStagePromise.promise\n      }\n      case RenderStage.Runtime: {\n        return this.runtimeStagePromise.promise\n      }\n      case RenderStage.Dynamic: {\n        return this.dynamicStagePromise.promise\n      }\n      default: {\n        stage satisfies never\n        throw new InvariantError(`Invalid render stage: ${stage}`)\n      }\n    }\n  }\n\n  waitForStage(stage: AdvanceableRenderStage) {\n    return this.getStagePromise(stage)\n  }\n\n  delayUntilStage<T>(\n    stage: AdvanceableRenderStage,\n    displayName: string | undefined,\n    resolvedValue: T\n  ) {\n    const ioTriggerPromise = this.getStagePromise(stage)\n\n    const promise = makeDevtoolsIOPromiseFromIOTrigger(\n      ioTriggerPromise,\n      displayName,\n      resolvedValue\n    )\n\n    // Analogously to `makeHangingPromise`, we might reject this promise if the signal is invoked.\n    // (e.g. in the case where we don't want want the render to proceed to the dynamic stage and abort it).\n    // We shouldn't consider this an unhandled rejection, so we attach a noop catch handler here to suppress this warning.\n    if (this.abortSignal) {\n      promise.catch(ignoreReject)\n    }\n    return promise\n  }\n}\n\nfunction ignoreReject() {}\n\n// TODO(restart-on-cache-miss): the layering of `delayUntilStage`,\n// `makeDevtoolsIOPromiseFromIOTrigger` and and `makeDevtoolsIOAwarePromise`\n// is confusing, we should clean it up.\nfunction makeDevtoolsIOPromiseFromIOTrigger<T>(\n  ioTrigger: Promise<any>,\n  displayName: string | undefined,\n  resolvedValue: T\n): Promise<T> {\n  // If we create a `new Promise` and give it a displayName\n  // (with no userspace code above us in the stack)\n  // React Devtools will use it as the IO cause when determining \"suspended by\".\n  // In particular, it should shadow any inner IO that resolved/rejected the promise\n  // (in case of staged rendering, this will be the `setTimeout` that triggers the relevant stage)\n  const promise = new Promise<T>((resolve, reject) => {\n    ioTrigger.then(resolve.bind(null, resolvedValue), reject)\n  })\n  if (displayName !== undefined) {\n    // @ts-expect-error\n    promise.displayName = displayName\n  }\n  return promise\n}\n","/**\n * We extend `Date` during builds and revalidates to ensure that prerenders don't observe the clock as a source of IO\n * When cacheComponents is enabled. The current time is a form of IO even though it resolves synchronously. When cacheComponents is\n * enabled we need to ensure that clock time is excluded from prerenders unless it is cached.\n *\n * There is tension here because time is used for both output and introspection. While arbitrary we intend to reserve\n * `Date` for output use cases and `performance` for introspection use cases. If you want to measure\n * how long something takes use `performance.timeOrigin` and `performance.now()` rather than `Date.now()` for instance.\n *\n * The extensions here never error nor alter the underlying Date objects, strings, and numbers created and thus should be transparent to callers.\n */\nimport { io } from './io-utils'\n\nfunction createNow(originalNow: typeof Date.now) {\n  return {\n    now: function now() {\n      io('`Date.now()`', 'time')\n      return originalNow()\n    },\n  }['now'.slice() as 'now'].bind(null)\n}\n\nfunction createDate(originalConstructor: typeof Date): typeof Date {\n  const properties = Object.getOwnPropertyDescriptors(originalConstructor)\n  properties.now.value = createNow(originalConstructor.now)\n\n  const apply = Reflect.apply\n  const construct = Reflect.construct\n\n  const newConstructor = Object.defineProperties(\n    // Ideally this should not minify the name.\n    function Date() {\n      if (new.target === undefined) {\n        io('`Date()`', 'time')\n        return apply(originalConstructor, undefined, arguments)\n      }\n      if (arguments.length === 0) {\n        io('`new Date()`', 'time')\n      }\n      return construct(originalConstructor, arguments, new.target)\n    },\n    properties\n  )\n  Object.defineProperty(originalConstructor.prototype, 'constructor', {\n    value: newConstructor,\n  })\n  return newConstructor as typeof Date\n}\n\ntry {\n  // eslint-disable-next-line no-native-reassign\n  Date = createDate(Date)\n} catch {\n  console.error(\n    'Failed to install `Date` class extension. When using `cacheComponents`, APIs that read the current time will not correctly trigger dynamic behavior.'\n  )\n}\n","/**\n * Contains predefined constants for the trace span name in next/server.\n *\n * Currently, next/server/tracer is internal implementation only for tracking\n * next.js's implementation only with known span names defined here.\n **/\n\n// eslint typescript has a bug with TS enums\n\nenum BaseServerSpan {\n  handleRequest = 'BaseServer.handleRequest',\n  run = 'BaseServer.run',\n  pipe = 'BaseServer.pipe',\n  getStaticHTML = 'BaseServer.getStaticHTML',\n  render = 'BaseServer.render',\n  renderToResponseWithComponents = 'BaseServer.renderToResponseWithComponents',\n  renderToResponse = 'BaseServer.renderToResponse',\n  renderToHTML = 'BaseServer.renderToHTML',\n  renderError = 'BaseServer.renderError',\n  renderErrorToResponse = 'BaseServer.renderErrorToResponse',\n  renderErrorToHTML = 'BaseServer.renderErrorToHTML',\n  render404 = 'BaseServer.render404',\n}\n\nenum LoadComponentsSpan {\n  loadDefaultErrorComponents = 'LoadComponents.loadDefaultErrorComponents',\n  loadComponents = 'LoadComponents.loadComponents',\n}\n\nenum NextServerSpan {\n  getRequestHandler = 'NextServer.getRequestHandler',\n  getRequestHandlerWithMetadata = 'NextServer.getRequestHandlerWithMetadata',\n  getServer = 'NextServer.getServer',\n  getServerRequestHandler = 'NextServer.getServerRequestHandler',\n  createServer = 'createServer.createServer',\n}\n\nenum NextNodeServerSpan {\n  compression = 'NextNodeServer.compression',\n  getBuildId = 'NextNodeServer.getBuildId',\n  createComponentTree = 'NextNodeServer.createComponentTree',\n  clientComponentLoading = 'NextNodeServer.clientComponentLoading',\n  getLayoutOrPageModule = 'NextNodeServer.getLayoutOrPageModule',\n  generateStaticRoutes = 'NextNodeServer.generateStaticRoutes',\n  generateFsStaticRoutes = 'NextNodeServer.generateFsStaticRoutes',\n  generatePublicRoutes = 'NextNodeServer.generatePublicRoutes',\n  generateImageRoutes = 'NextNodeServer.generateImageRoutes.route',\n  sendRenderResult = 'NextNodeServer.sendRenderResult',\n  proxyRequest = 'NextNodeServer.proxyRequest',\n  runApi = 'NextNodeServer.runApi',\n  render = 'NextNodeServer.render',\n  renderHTML = 'NextNodeServer.renderHTML',\n  imageOptimizer = 'NextNodeServer.imageOptimizer',\n  getPagePath = 'NextNodeServer.getPagePath',\n  getRoutesManifest = 'NextNodeServer.getRoutesManifest',\n  findPageComponents = 'NextNodeServer.findPageComponents',\n  getFontManifest = 'NextNodeServer.getFontManifest',\n  getServerComponentManifest = 'NextNodeServer.getServerComponentManifest',\n  getRequestHandler = 'NextNodeServer.getRequestHandler',\n  renderToHTML = 'NextNodeServer.renderToHTML',\n  renderError = 'NextNodeServer.renderError',\n  renderErrorToHTML = 'NextNodeServer.renderErrorToHTML',\n  render404 = 'NextNodeServer.render404',\n  startResponse = 'NextNodeServer.startResponse',\n\n  // nested inner span, does not require parent scope name\n  route = 'route',\n  onProxyReq = 'onProxyReq',\n  apiResolver = 'apiResolver',\n  internalFetch = 'internalFetch',\n}\n\nenum StartServerSpan {\n  startServer = 'startServer.startServer',\n}\n\nenum RenderSpan {\n  getServerSideProps = 'Render.getServerSideProps',\n  getStaticProps = 'Render.getStaticProps',\n  renderToString = 'Render.renderToString',\n  renderDocument = 'Render.renderDocument',\n  createBodyResult = 'Render.createBodyResult',\n}\n\nenum AppRenderSpan {\n  renderToString = 'AppRender.renderToString',\n  renderToReadableStream = 'AppRender.renderToReadableStream',\n  getBodyResult = 'AppRender.getBodyResult',\n  fetch = 'AppRender.fetch',\n}\n\nenum RouterSpan {\n  executeRoute = 'Router.executeRoute',\n}\n\nenum NodeSpan {\n  runHandler = 'Node.runHandler',\n}\n\nenum AppRouteRouteHandlersSpan {\n  runHandler = 'AppRouteRouteHandlers.runHandler',\n}\n\nenum ResolveMetadataSpan {\n  generateMetadata = 'ResolveMetadata.generateMetadata',\n  generateViewport = 'ResolveMetadata.generateViewport',\n}\n\nenum MiddlewareSpan {\n  execute = 'Middleware.execute',\n}\n\ntype SpanTypes =\n  | `${BaseServerSpan}`\n  | `${LoadComponentsSpan}`\n  | `${NextServerSpan}`\n  | `${StartServerSpan}`\n  | `${NextNodeServerSpan}`\n  | `${RenderSpan}`\n  | `${RouterSpan}`\n  | `${AppRenderSpan}`\n  | `${NodeSpan}`\n  | `${AppRouteRouteHandlersSpan}`\n  | `${ResolveMetadataSpan}`\n  | `${MiddlewareSpan}`\n\n// This list is used to filter out spans that are not relevant to the user\nexport const NextVanillaSpanAllowlist = new Set([\n  MiddlewareSpan.execute,\n  BaseServerSpan.handleRequest,\n  RenderSpan.getServerSideProps,\n  RenderSpan.getStaticProps,\n  AppRenderSpan.fetch,\n  AppRenderSpan.getBodyResult,\n  RenderSpan.renderDocument,\n  NodeSpan.runHandler,\n  AppRouteRouteHandlersSpan.runHandler,\n  ResolveMetadataSpan.generateMetadata,\n  ResolveMetadataSpan.generateViewport,\n  NextNodeServerSpan.createComponentTree,\n  NextNodeServerSpan.findPageComponents,\n  NextNodeServerSpan.getLayoutOrPageModule,\n  NextNodeServerSpan.startResponse,\n  NextNodeServerSpan.clientComponentLoading,\n])\n\n// These Spans are allowed to be always logged\n// when the otel log prefix env is set\nexport const LogSpanAllowList = new Set([\n  NextNodeServerSpan.findPageComponents,\n  NextNodeServerSpan.createComponentTree,\n  NextNodeServerSpan.clientComponentLoading,\n])\n\nexport {\n  BaseServerSpan,\n  LoadComponentsSpan,\n  NextServerSpan,\n  NextNodeServerSpan,\n  StartServerSpan,\n  RenderSpan,\n  RouterSpan,\n  AppRenderSpan,\n  NodeSpan,\n  AppRouteRouteHandlersSpan,\n  ResolveMetadataSpan,\n  MiddlewareSpan,\n}\n\nexport type { SpanTypes }\n","export enum RedirectStatusCode {\n  SeeOther = 303,\n  TemporaryRedirect = 307,\n  PermanentRedirect = 308,\n}\n","export const enum RouteKind {\n  /**\n   * `PAGES` represents all the React pages that are under `pages/`.\n   */\n  PAGES = 'PAGES',\n  /**\n   * `PAGES_API` represents all the API routes under `pages/api/`.\n   */\n  PAGES_API = 'PAGES_API',\n  /**\n   * `APP_PAGE` represents all the React pages that are under `app/` with the\n   * filename of `page.{j,t}s{,x}`.\n   */\n  APP_PAGE = 'APP_PAGE',\n  /**\n   * `APP_ROUTE` represents all the API routes and metadata routes that are under `app/` with the\n   * filename of `route.{j,t}s{,x}`.\n   */\n  APP_ROUTE = 'APP_ROUTE',\n\n  /**\n   * `IMAGE` represents all the images that are generated by `next/image`.\n   */\n  IMAGE = 'IMAGE',\n}\n","import type { OutgoingHttpHeaders } from 'http'\nimport type RenderResult from '../render-result'\nimport type { CacheControl, Revalidate } from '../lib/cache-control'\nimport type { RouteKind } from '../route-kind'\n\nexport interface ResponseCacheBase {\n  get(\n    key: string | null,\n    responseGenerator: ResponseGenerator,\n    context: {\n      isOnDemandRevalidate?: boolean\n      isPrefetch?: boolean\n      incrementalCache: IncrementalCache\n      /**\n       * This is a hint to the cache to help it determine what kind of route\n       * this is so it knows where to look up the cache entry from. If not\n       * provided it will test the filesystem to check.\n       */\n      routeKind: RouteKind\n\n      /**\n       * True if this is a fallback request.\n       */\n      isFallback?: boolean\n\n      /**\n       * True if the route is enabled for PPR.\n       */\n      isRoutePPREnabled?: boolean\n    }\n  ): Promise<ResponseCacheEntry | null>\n}\n\n// The server components HMR cache might store other data as well in the future,\n// at which point this should be refactored to a discriminated union type.\nexport interface ServerComponentsHmrCache {\n  get(key: string): CachedFetchData | undefined\n  set(key: string, data: CachedFetchData): void\n}\n\nexport type CachedFetchData = {\n  headers: Record<string, string>\n  body: string\n  url: string\n  status?: number\n}\n\nexport const enum CachedRouteKind {\n  APP_PAGE = 'APP_PAGE',\n  APP_ROUTE = 'APP_ROUTE',\n  PAGES = 'PAGES',\n  FETCH = 'FETCH',\n  REDIRECT = 'REDIRECT',\n  IMAGE = 'IMAGE',\n}\n\nexport interface CachedFetchValue {\n  kind: CachedRouteKind.FETCH\n  data: CachedFetchData\n  // tags are only present with file-system-cache\n  // fetch cache stores tags outside of cache entry\n  tags?: string[]\n  revalidate: number\n}\n\nexport interface CachedRedirectValue {\n  kind: CachedRouteKind.REDIRECT\n  props: Object\n}\n\nexport interface CachedAppPageValue {\n  kind: CachedRouteKind.APP_PAGE\n  // this needs to be a RenderResult so since renderResponse\n  // expects that type instead of a string\n  html: RenderResult\n  rscData: Buffer | undefined\n  status: number | undefined\n  postponed: string | undefined\n  headers: OutgoingHttpHeaders | undefined\n  segmentData: Map<string, Buffer> | undefined\n}\n\nexport interface CachedPageValue {\n  kind: CachedRouteKind.PAGES\n  // this needs to be a RenderResult so since renderResponse\n  // expects that type instead of a string\n  html: RenderResult\n  pageData: Object\n  status: number | undefined\n  headers: OutgoingHttpHeaders | undefined\n}\n\nexport interface CachedRouteValue {\n  kind: CachedRouteKind.APP_ROUTE\n  // this needs to be a RenderResult so since renderResponse\n  // expects that type instead of a string\n  body: Buffer\n  status: number\n  headers: OutgoingHttpHeaders\n}\n\nexport interface CachedImageValue {\n  kind: CachedRouteKind.IMAGE\n  etag: string\n  upstreamEtag: string\n  buffer: Buffer\n  extension: string\n  revalidate?: number\n  isMiss?: boolean\n  isStale?: boolean\n}\n\nexport interface IncrementalCachedAppPageValue {\n  kind: CachedRouteKind.APP_PAGE\n  // this needs to be a string since the cache expects to store\n  // the string value\n  html: string\n  rscData: Buffer | undefined\n  headers: OutgoingHttpHeaders | undefined\n  postponed: string | undefined\n  status: number | undefined\n  segmentData: Map<string, Buffer> | undefined\n}\n\nexport interface IncrementalCachedPageValue {\n  kind: CachedRouteKind.PAGES\n  // this needs to be a string since the cache expects to store\n  // the string value\n  html: string\n  pageData: Object\n  headers: OutgoingHttpHeaders | undefined\n  status: number | undefined\n}\n\nexport interface IncrementalResponseCacheEntry {\n  cacheControl?: CacheControl\n  /**\n   * timestamp in milliseconds to revalidate after\n   */\n  revalidateAfter?: Revalidate\n  /**\n   * `-1` here dictates a blocking revalidate should be used\n   */\n  isStale?: boolean | -1\n  isMiss?: boolean\n  isFallback?: boolean\n  value: Exclude<IncrementalCacheValue, CachedFetchValue> | null\n}\n\nexport interface IncrementalFetchCacheEntry {\n  /**\n   * `-1` here dictates a blocking revalidate should be used\n   */\n  isStale?: boolean | -1\n  value: CachedFetchValue\n}\n\nexport type IncrementalCacheEntry =\n  | IncrementalResponseCacheEntry\n  | IncrementalFetchCacheEntry\n\nexport type IncrementalCacheValue =\n  | CachedRedirectValue\n  | IncrementalCachedPageValue\n  | IncrementalCachedAppPageValue\n  | CachedImageValue\n  | CachedFetchValue\n  | CachedRouteValue\n\nexport type ResponseCacheValue =\n  | CachedRedirectValue\n  | CachedPageValue\n  | CachedAppPageValue\n  | CachedImageValue\n  | CachedRouteValue\n\nexport type ResponseCacheEntry = {\n  cacheControl?: CacheControl\n  value: ResponseCacheValue | null\n  isStale?: boolean | -1\n  isMiss?: boolean\n  isFallback?: boolean\n}\n\n/**\n * @param hasResolved whether the responseGenerator has resolved it's promise\n * @param previousCacheEntry the previous cache entry if it exists or the current\n */\nexport type ResponseGenerator = (state: {\n  hasResolved: boolean\n  previousCacheEntry?: IncrementalResponseCacheEntry | null\n  isRevalidating?: boolean\n  span?: any\n\n  /**\n   * When true, this indicates that the response generator is being called in a\n   * context where the response must be generated statically.\n   *\n   * CRITICAL: This should only currently be used when revalidating due to a\n   * dynamic RSC request.\n   */\n  forceStaticRender?: boolean\n}) => Promise<ResponseCacheEntry | null>\n\nexport const enum IncrementalCacheKind {\n  APP_PAGE = 'APP_PAGE',\n  APP_ROUTE = 'APP_ROUTE',\n  PAGES = 'PAGES',\n  FETCH = 'FETCH',\n  IMAGE = 'IMAGE',\n}\n\nexport interface GetIncrementalFetchCacheContext {\n  kind: IncrementalCacheKind.FETCH\n  revalidate?: Revalidate\n  fetchUrl?: string\n  fetchIdx?: number\n  tags?: string[]\n  softTags?: string[]\n}\n\nexport interface GetIncrementalResponseCacheContext {\n  kind: Exclude<IncrementalCacheKind, IncrementalCacheKind.FETCH>\n\n  /**\n   * True if the route is enabled for PPR.\n   */\n  isRoutePPREnabled?: boolean\n\n  /**\n   * True if this is a fallback request.\n   */\n  isFallback: boolean\n}\n\nexport interface SetIncrementalFetchCacheContext {\n  fetchCache: true\n  fetchUrl?: string\n  fetchIdx?: number\n  tags?: string[]\n  isImplicitBuildTimeCache?: boolean\n}\n\nexport interface SetIncrementalResponseCacheContext {\n  fetchCache?: false\n  cacheControl?: CacheControl\n\n  /**\n   * True if the route is enabled for PPR.\n   */\n  isRoutePPREnabled?: boolean\n\n  /**\n   * True if this is a fallback request.\n   */\n  isFallback?: boolean\n}\n\nexport interface IncrementalResponseCache {\n  get(\n    cacheKey: string,\n    ctx: GetIncrementalResponseCacheContext\n  ): Promise<IncrementalResponseCacheEntry | null>\n  set(\n    key: string,\n    data: Exclude<IncrementalCacheValue, CachedFetchValue> | null,\n    ctx: SetIncrementalResponseCacheContext\n  ): Promise<void>\n}\n\nexport interface IncrementalCache extends IncrementalResponseCache {\n  get(\n    cacheKey: string,\n    ctx: GetIncrementalFetchCacheContext\n  ): Promise<IncrementalFetchCacheEntry | null>\n  get(\n    cacheKey: string,\n    ctx: GetIncrementalResponseCacheContext\n  ): Promise<IncrementalResponseCacheEntry | null>\n  set(\n    key: string,\n    data: CachedFetchValue | null,\n    ctx: SetIncrementalFetchCacheContext\n  ): Promise<void>\n  set(\n    key: string,\n    data: Exclude<IncrementalCacheValue, CachedFetchValue> | null,\n    ctx: SetIncrementalResponseCacheContext\n  ): Promise<void>\n  revalidateTag(\n    tags: string | string[],\n    durations?: { expire?: number }\n  ): Promise<void>\n}\n","// ISC License\n\n// Copyright (c) 2021 Alexey Raspopov, Kostiantyn Denysov, Anton Verinov\n\n// Permission to use, copy, modify, and/or distribute this software for any\n// purpose with or without fee is hereby granted, provided that the above\n// copyright notice and this permission notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n//\n// https://github.com/alexeyraspopov/picocolors/blob/b6261487e7b81aaab2440e397a356732cad9e342/picocolors.js#L1\n\nconst { env, stdout } = globalThis?.process ?? {}\n\nconst enabled =\n  env &&\n  !env.NO_COLOR &&\n  (env.FORCE_COLOR || (stdout?.isTTY && !env.CI && env.TERM !== 'dumb'))\n\nconst replaceClose = (\n  str: string,\n  close: string,\n  replace: string,\n  index: number\n): string => {\n  const start = str.substring(0, index) + replace\n  const end = str.substring(index + close.length)\n  const nextIndex = end.indexOf(close)\n  return ~nextIndex\n    ? start + replaceClose(end, close, replace, nextIndex)\n    : start + end\n}\n\nconst formatter = (open: string, close: string, replace = open) => {\n  if (!enabled) return String\n  return (input: string) => {\n    const string = '' + input\n    const index = string.indexOf(close, open.length)\n    return ~index\n      ? open + replaceClose(string, close, replace, index) + close\n      : open + string + close\n  }\n}\n\nexport const reset = enabled ? (s: string) => `\\x1b[0m${s}\\x1b[0m` : String\nexport const bold = formatter('\\x1b[1m', '\\x1b[22m', '\\x1b[22m\\x1b[1m')\nexport const dim = formatter('\\x1b[2m', '\\x1b[22m', '\\x1b[22m\\x1b[2m')\nexport const italic = formatter('\\x1b[3m', '\\x1b[23m')\nexport const underline = formatter('\\x1b[4m', '\\x1b[24m')\nexport const inverse = formatter('\\x1b[7m', '\\x1b[27m')\nexport const hidden = formatter('\\x1b[8m', '\\x1b[28m')\nexport const strikethrough = formatter('\\x1b[9m', '\\x1b[29m')\nexport const black = formatter('\\x1b[30m', '\\x1b[39m')\nexport const red = formatter('\\x1b[31m', '\\x1b[39m')\nexport const green = formatter('\\x1b[32m', '\\x1b[39m')\nexport const yellow = formatter('\\x1b[33m', '\\x1b[39m')\nexport const blue = formatter('\\x1b[34m', '\\x1b[39m')\nexport const magenta = formatter('\\x1b[35m', '\\x1b[39m')\nexport const purple = formatter('\\x1b[38;2;173;127;168m', '\\x1b[39m')\nexport const cyan = formatter('\\x1b[36m', '\\x1b[39m')\nexport const white = formatter('\\x1b[37m', '\\x1b[39m')\nexport const gray = formatter('\\x1b[90m', '\\x1b[39m')\nexport const bgBlack = formatter('\\x1b[40m', '\\x1b[49m')\nexport const bgRed = formatter('\\x1b[41m', '\\x1b[49m')\nexport const bgGreen = formatter('\\x1b[42m', '\\x1b[49m')\nexport const bgYellow = formatter('\\x1b[43m', '\\x1b[49m')\nexport const bgBlue = formatter('\\x1b[44m', '\\x1b[49m')\nexport const bgMagenta = formatter('\\x1b[45m', '\\x1b[49m')\nexport const bgCyan = formatter('\\x1b[46m', '\\x1b[49m')\nexport const bgWhite = formatter('\\x1b[47m', '\\x1b[49m')\n","/**\n * Node in the doubly-linked list used for LRU tracking.\n * Each node represents a cache entry with bidirectional pointers.\n */\nclass LRUNode<T> {\n  public readonly key: string\n  public data: T\n  public size: number\n  public prev: LRUNode<T> | SentinelNode<T> | null = null\n  public next: LRUNode<T> | SentinelNode<T> | null = null\n\n  constructor(key: string, data: T, size: number) {\n    this.key = key\n    this.data = data\n    this.size = size\n  }\n}\n\n/**\n * Sentinel node used for head/tail boundaries.\n * These nodes don't contain actual cache data but simplify list operations.\n */\nclass SentinelNode<T> {\n  public prev: LRUNode<T> | SentinelNode<T> | null = null\n  public next: LRUNode<T> | SentinelNode<T> | null = null\n}\n\n/**\n * LRU (Least Recently Used) Cache implementation using a doubly-linked list\n * and hash map for O(1) operations.\n *\n * Algorithm:\n * - Uses a doubly-linked list to maintain access order (most recent at head)\n * - Hash map provides O(1) key-to-node lookup\n * - Sentinel head/tail nodes simplify edge case handling\n * - Size-based eviction supports custom size calculation functions\n *\n * Data Structure Layout:\n * HEAD <-> [most recent] <-> ... <-> [least recent] <-> TAIL\n *\n * Operations:\n * - get(): Move accessed node to head (mark as most recent)\n * - set(): Add new node at head, evict from tail if over capacity\n * - Eviction: Remove least recent node (tail.prev) when size exceeds limit\n */\nexport class LRUCache<T> {\n  private readonly cache: Map<string, LRUNode<T>> = new Map()\n  private readonly head: SentinelNode<T>\n  private readonly tail: SentinelNode<T>\n  private totalSize: number = 0\n  private readonly maxSize: number\n  private readonly calculateSize: ((value: T) => number) | undefined\n  private readonly onEvict: ((key: string, value: T) => void) | undefined\n\n  constructor(\n    maxSize: number,\n    calculateSize?: (value: T) => number,\n    onEvict?: (key: string, value: T) => void\n  ) {\n    this.maxSize = maxSize\n    this.calculateSize = calculateSize\n    this.onEvict = onEvict\n\n    // Create sentinel nodes to simplify doubly-linked list operations\n    // HEAD <-> TAIL (empty list)\n    this.head = new SentinelNode<T>()\n    this.tail = new SentinelNode<T>()\n    this.head.next = this.tail\n    this.tail.prev = this.head\n  }\n\n  /**\n   * Adds a node immediately after the head (marks as most recently used).\n   * Used when inserting new items or when an item is accessed.\n   * PRECONDITION: node must be disconnected (prev/next should be null)\n   */\n  private addToHead(node: LRUNode<T>): void {\n    node.prev = this.head\n    node.next = this.head.next\n    // head.next is always non-null (points to tail or another node)\n    this.head.next!.prev = node\n    this.head.next = node\n  }\n\n  /**\n   * Removes a node from its current position in the doubly-linked list.\n   * Updates the prev/next pointers of adjacent nodes to maintain list integrity.\n   * PRECONDITION: node must be connected (prev/next are non-null)\n   */\n  private removeNode(node: LRUNode<T>): void {\n    // Connected nodes always have non-null prev/next\n    node.prev!.next = node.next\n    node.next!.prev = node.prev\n  }\n\n  /**\n   * Moves an existing node to the head position (marks as most recently used).\n   * This is the core LRU operation - accessed items become most recent.\n   */\n  private moveToHead(node: LRUNode<T>): void {\n    this.removeNode(node)\n    this.addToHead(node)\n  }\n\n  /**\n   * Removes and returns the least recently used node (the one before tail).\n   * This is called during eviction when the cache exceeds capacity.\n   * PRECONDITION: cache is not empty (ensured by caller)\n   */\n  private removeTail(): LRUNode<T> {\n    const lastNode = this.tail.prev as LRUNode<T>\n    // tail.prev is always non-null and always LRUNode when cache is not empty\n    this.removeNode(lastNode)\n    return lastNode\n  }\n\n  /**\n   * Sets a key-value pair in the cache.\n   * If the key exists, updates the value and moves to head.\n   * If new, adds at head and evicts from tail if necessary.\n   *\n   * Time Complexity:\n   * - O(1) for uniform item sizes\n   * - O(k) where k is the number of items evicted (can be O(N) for variable sizes)\n   */\n  public set(key: string, value: T): boolean {\n    const size = this.calculateSize?.(value) ?? 1\n    if (size <= 0) {\n      throw new Error(\n        `LRUCache: calculateSize returned ${size}, but size must be > 0. ` +\n          `Items with size 0 would never be evicted, causing unbounded cache growth.`\n      )\n    }\n    if (size > this.maxSize) {\n      console.warn('Single item size exceeds maxSize')\n      return false\n    }\n\n    const existing = this.cache.get(key)\n    if (existing) {\n      // Update existing node: adjust size and move to head (most recent)\n      existing.data = value\n      this.totalSize = this.totalSize - existing.size + size\n      existing.size = size\n      this.moveToHead(existing)\n    } else {\n      // Add new node at head (most recent position)\n      const newNode = new LRUNode(key, value, size)\n      this.cache.set(key, newNode)\n      this.addToHead(newNode)\n      this.totalSize += size\n    }\n\n    // Evict least recently used items until under capacity\n    while (this.totalSize > this.maxSize && this.cache.size > 0) {\n      const tail = this.removeTail()\n      this.cache.delete(tail.key)\n      this.totalSize -= tail.size\n      this.onEvict?.(tail.key, tail.data)\n    }\n\n    return true\n  }\n\n  /**\n   * Checks if a key exists in the cache.\n   * This is a pure query operation - does NOT update LRU order.\n   *\n   * Time Complexity: O(1)\n   */\n  public has(key: string): boolean {\n    return this.cache.has(key)\n  }\n\n  /**\n   * Retrieves a value by key and marks it as most recently used.\n   * Moving to head maintains the LRU property for future evictions.\n   *\n   * Time Complexity: O(1)\n   */\n  public get(key: string): T | undefined {\n    const node = this.cache.get(key)\n    if (!node) return undefined\n\n    // Mark as most recently used by moving to head\n    this.moveToHead(node)\n\n    return node.data\n  }\n\n  /**\n   * Returns an iterator over the cache entries. The order is outputted in the\n   * order of most recently used to least recently used.\n   */\n  public *[Symbol.iterator](): IterableIterator<[string, T]> {\n    let current = this.head.next\n    while (current && current !== this.tail) {\n      // Between head and tail, current is always LRUNode\n      const node = current as LRUNode<T>\n      yield [node.key, node.data]\n      current = current.next\n    }\n  }\n\n  /**\n   * Removes a specific key from the cache.\n   * Updates both the hash map and doubly-linked list.\n   *\n   * Note: This is an explicit removal and does NOT trigger the `onEvict`\n   * callback. Use this for intentional deletions where eviction tracking\n   * is not needed.\n   *\n   * Time Complexity: O(1)\n   */\n  public remove(key: string): void {\n    const node = this.cache.get(key)\n    if (!node) return\n\n    this.removeNode(node)\n    this.cache.delete(key)\n    this.totalSize -= node.size\n  }\n\n  /**\n   * Returns the number of items in the cache.\n   */\n  public get size(): number {\n    return this.cache.size\n  }\n\n  /**\n   * Returns the current total size of all cached items.\n   * This uses the custom size calculation if provided.\n   */\n  public get currentSize(): number {\n    return this.totalSize\n  }\n}\n","import type { SourceMap } from 'module'\nimport { LRUCache } from './lru-cache'\n\nfunction noSourceMap(): SourceMap | undefined {\n  return undefined\n}\n\n// Edge runtime does not implement `module`\nconst findSourceMap =\n  process.env.NEXT_RUNTIME === 'edge'\n    ? noSourceMap\n    : (require('module') as typeof import('module')).findSourceMap\n\n/**\n * https://tc39.es/source-map/#index-map\n */\ninterface IndexSourceMapSection {\n  offset: {\n    line: number\n    column: number\n  }\n  map: BasicSourceMapPayload\n}\n\n// TODO(veil): Upstream types\n/** https://tc39.es/ecma426/#sec-index-source-map */\ninterface IndexSourceMap {\n  version: number\n  file: string\n  sections: IndexSourceMapSection[]\n}\n\n/** https://tc39.es/ecma426/#sec-source-map-format */\nexport interface BasicSourceMapPayload {\n  version: number\n  // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n  /** WARNING: `file` is optional. */\n  file: string\n  sourceRoot?: string\n  // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n  /** WARNING: `sources[number]` can be `null`. */\n  sources: Array<string>\n  names: Array<string>\n  mappings: string\n  ignoreList?: number[]\n}\n\nexport type ModernSourceMapPayload = BasicSourceMapPayload | IndexSourceMap\n\nexport function sourceMapIgnoreListsEverything(\n  sourceMap: BasicSourceMapPayload\n): boolean {\n  return (\n    sourceMap.ignoreList !== undefined &&\n    sourceMap.sources.length === sourceMap.ignoreList.length\n  )\n}\n\n/**\n * Finds the sourcemap payload applicable to a given frame.\n * Equal to the input unless an Index Source Map is used.\n * @param line0 - The line number of the frame, 0-based.\n * @param column0 - The column number of the frame, 0-based.\n */\nexport function findApplicableSourceMapPayload(\n  line0: number,\n  column0: number,\n  payload: ModernSourceMapPayload\n): BasicSourceMapPayload | undefined {\n  if ('sections' in payload) {\n    if (payload.sections.length === 0) {\n      return undefined\n    }\n\n    // Sections must not overlap and must be sorted: https://tc39.es/source-map/#section-object\n    // Therefore the last section that has an offset less than or equal to the frame is the applicable one.\n    const sections = payload.sections\n    let left = 0\n    let right = sections.length - 1\n    let result: IndexSourceMapSection | null = null\n\n    while (left <= right) {\n      // fast Math.floor\n      const middle = ~~((left + right) / 2)\n      const section = sections[middle]\n      const offset = section.offset\n\n      if (\n        offset.line < line0 ||\n        (offset.line === line0 && offset.column <= column0)\n      ) {\n        result = section\n        left = middle + 1\n      } else {\n        right = middle - 1\n      }\n    }\n\n    return result === null ? undefined : result.map\n  } else {\n    return payload\n  }\n}\n\nconst didWarnAboutInvalidSourceMapDEV = new Set<string>()\n\nexport function filterStackFrameDEV(\n  sourceURL: string,\n  functionName: string,\n  line1: number,\n  column1: number\n): boolean {\n  if (sourceURL === '') {\n    // The default implementation filters out <anonymous> stack frames\n    // but we want to retain them because current Server Components and\n    // built-in Components in parent stacks don't have source location.\n    // Filter out frames that show up in Promises to get good names in React's\n    // Server Request track until we come up with a better heuristic.\n    return functionName !== 'new Promise'\n  }\n  if (sourceURL.startsWith('node:') || sourceURL.includes('node_modules')) {\n    return false\n  }\n  try {\n    // Node.js loads source maps eagerly so this call is cheap.\n    // TODO: ESM sourcemaps are O(1) but CommonJS sourcemaps are O(Number of CJS modules).\n    // Make sure this doesn't adversely affect performance when CJS is used by Next.js.\n    const sourceMap = findSourceMap(sourceURL)\n    if (sourceMap === undefined) {\n      // No source map assoicated.\n      // TODO: Node.js types should reflect that `findSourceMap` can return `undefined`.\n      return true\n    }\n    const sourceMapPayload = findApplicableSourceMapPayload(\n      line1 - 1,\n      column1 - 1,\n      sourceMap.payload\n    )\n    if (sourceMapPayload === undefined) {\n      // No source map section applicable to the frame.\n      return true\n    }\n    return !sourceMapIgnoreListsEverything(sourceMapPayload)\n  } catch (cause) {\n    if (process.env.NODE_ENV !== 'production') {\n      // TODO: Share cache with patch-error-inspect\n      if (!didWarnAboutInvalidSourceMapDEV.has(sourceURL)) {\n        didWarnAboutInvalidSourceMapDEV.add(sourceURL)\n        // We should not log an actual error instance here because that will re-enter\n        // this codepath during error inspection and could lead to infinite recursion.\n        console.error(\n          `${sourceURL}: Invalid source map. Only conformant source maps can be used to filter stack frames. Cause: ${cause}`\n        )\n      }\n    }\n\n    return true\n  }\n}\n\nconst invalidSourceMap = Symbol('invalid-source-map')\nconst sourceMapURLs = new LRUCache<string | typeof invalidSourceMap>(\n  512 * 1024 * 1024,\n  (url) =>\n    url === invalidSourceMap\n      ? // Ideally we'd account for key length. So we just guestimate a small source map\n        // so that we don't create a huge cache with empty source maps.\n        8 * 1024\n      : // these URLs contain only ASCII characters so .length is equal to Buffer.byteLength\n        url.length\n)\nexport function findSourceMapURLDEV(\n  scriptNameOrSourceURL: string\n): string | null {\n  let sourceMapURL = sourceMapURLs.get(scriptNameOrSourceURL)\n  if (sourceMapURL === undefined) {\n    let sourceMapPayload: ModernSourceMapPayload | undefined\n    try {\n      sourceMapPayload = findSourceMap(scriptNameOrSourceURL)?.payload\n    } catch (cause) {\n      console.error(\n        `${scriptNameOrSourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n      )\n    }\n\n    if (sourceMapPayload === undefined) {\n      sourceMapURL = invalidSourceMap\n    } else {\n      // TODO: Might be more efficient to extract the relevant section from Index Maps.\n      // Unclear if that search is worth the smaller payload we have to stringify.\n      const sourceMapJSON = JSON.stringify(sourceMapPayload)\n      const sourceMapURLData = Buffer.from(sourceMapJSON, 'utf8').toString(\n        'base64'\n      )\n      sourceMapURL = `data:application/json;base64,${sourceMapURLData}`\n    }\n\n    sourceMapURLs.set(scriptNameOrSourceURL, sourceMapURL)\n  }\n\n  return sourceMapURL === invalidSourceMap ? null : sourceMapURL\n}\n\nexport function devirtualizeReactServerURL(sourceURL: string): string {\n  if (sourceURL.startsWith('about://React/')) {\n    // about://React/Server/file://<filename>?42 => file://<filename>\n    const envIdx = sourceURL.indexOf('/', 'about://React/'.length)\n    const suffixIdx = sourceURL.lastIndexOf('?')\n    if (envIdx > -1 && suffixIdx > -1) {\n      return decodeURI(sourceURL.slice(envIdx + 1, suffixIdx))\n    }\n  }\n  return sourceURL\n}\n\nfunction isAnonymousFrameLikelyJSNative(methodName: string): boolean {\n  // Anonymous frames can also be produced in React parent stacks either from\n  // host components or Server Components. We don't want to ignore those.\n  // This could hide user-space methods that are named like native JS methods but\n  // should you really do that?\n  return (\n    // e.g. JSON.parse\n    methodName.startsWith('JSON.') ||\n    // E.g. Promise.withResolves\n    methodName.startsWith('Function.') ||\n    // various JS built-ins\n    methodName.startsWith('Promise.') ||\n    methodName.startsWith('Array.') ||\n    methodName.startsWith('Set.') ||\n    methodName.startsWith('Map.')\n  )\n}\n\nexport function ignoreListAnonymousStackFramesIfSandwiched<Frame>(\n  frames: Frame[],\n  isAnonymousFrame: (frame: Frame) => boolean,\n  isIgnoredFrame: (frame: Frame) => boolean,\n  getMethodName: (frame: Frame) => string,\n  /** only passes frames for which `isAnonymousFrame` and their method is a native JS method or `isIgnoredFrame` return true */\n  ignoreFrame: (frame: Frame) => void\n): void {\n  for (let i = 1; i < frames.length; i++) {\n    const currentFrame = frames[i]\n    if (\n      !(\n        isAnonymousFrame(currentFrame) &&\n        isAnonymousFrameLikelyJSNative(getMethodName(currentFrame))\n      )\n    ) {\n      continue\n    }\n\n    const previousFrameIsIgnored = isIgnoredFrame(frames[i - 1])\n    if (previousFrameIsIgnored && i < frames.length - 1) {\n      let ignoreSandwich = false\n      let j = i + 1\n      for (j; j < frames.length; j++) {\n        const nextFrame = frames[j]\n        const nextFrameIsAnonymous =\n          isAnonymousFrame(nextFrame) &&\n          isAnonymousFrameLikelyJSNative(getMethodName(nextFrame))\n        if (nextFrameIsAnonymous) {\n          continue\n        }\n\n        const nextFrameIsIgnored = isIgnoredFrame(nextFrame)\n        if (nextFrameIsIgnored) {\n          ignoreSandwich = true\n          break\n        }\n      }\n\n      if (ignoreSandwich) {\n        for (i; i < j; i++) {\n          ignoreFrame(frames[i])\n        }\n      }\n    }\n  }\n}\n","import { parse } from 'next/dist/compiled/stacktrace-parser'\n\nconst regexNextStatic = /\\/_next(\\/static\\/.+)/\n\nexport interface StackFrame {\n  file: string | null\n  methodName: string\n  arguments: string[]\n  /** 1-based */\n  line1: number | null\n  /** 1-based */\n  column1: number | null\n}\n\nexport function parseStack(\n  stack: string,\n  distDir = process.env.__NEXT_DIST_DIR\n): StackFrame[] {\n  if (!stack) return []\n\n  // throw away eval information that stacktrace-parser doesn't support\n  // adapted from https://github.com/stacktracejs/error-stack-parser/blob/9f33c224b5d7b607755eb277f9d51fcdb7287e24/error-stack-parser.js#L59C33-L59C62\n  stack = stack\n    .split('\\n')\n    .map((line) => {\n      if (line.includes('(eval ')) {\n        line = line\n          .replace(/eval code/g, 'eval')\n          .replace(/\\(eval at [^()]* \\(/, '(file://')\n          .replace(/\\),.*$/g, ')')\n      }\n\n      return line\n    })\n    .join('\\n')\n\n  const frames = parse(stack)\n  return frames.map((frame) => {\n    try {\n      const url = new URL(frame.file!)\n      const res = regexNextStatic.exec(url.pathname)\n      if (res) {\n        const effectiveDistDir = distDir\n          ?.replace(/\\\\/g, '/')\n          ?.replace(/\\/$/, '')\n        if (effectiveDistDir) {\n          frame.file =\n            'file://' + effectiveDistDir.concat(res.pop()!) + url.search\n        }\n      }\n    } catch {}\n    return {\n      file: frame.file,\n      line1: frame.lineNumber,\n      column1: frame.column,\n      methodName: frame.methodName,\n      arguments: frame.arguments,\n    }\n  })\n}\n","import { patchErrorInspectNodeJS } from '../patch-error-inspect'\n\npatchErrorInspectNodeJS(globalThis.Error)\n","/**\n * Patches console methods to exit the workUnitAsyncStorage so that inside the host implementation\n * sync IO can be called. This is relevant for example with runtimes that patch console methods to\n * prepend a timestamp to the log output.\n *\n * Note that this will only exit for already installed patched console methods. If you further patch\n * the console method after this and add any sync IO there it will trigger sync IO warnings while prerendering.\n *\n * This is a pragmatic concession because layering the patches if you install your own log implementation\n * after they are installed is very tricky to do correctly because the order matters\n */\n\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\n\ntype ConsoleMethodName = keyof Console\n\nfunction patchConsoleMethod(methodName: ConsoleMethodName): void {\n  const descriptor = Object.getOwnPropertyDescriptor(console, methodName)\n  if (\n    descriptor &&\n    (descriptor.configurable || descriptor.writable) &&\n    typeof descriptor.value === 'function'\n  ) {\n    const originalMethod = descriptor.value\n    const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name')\n    let wrapperMethod = function (...args: any[]) {\n      return workUnitAsyncStorage.exit(() =>\n        originalMethod.apply(console, args)\n      )\n    }\n    if (originalName) {\n      Object.defineProperty(wrapperMethod, 'name', originalName)\n    }\n    Object.defineProperty(console, methodName, {\n      value: wrapperMethod,\n    })\n  }\n}\n\n// We patch the same methods that React and our dev patch do.\n// We may find other methods that could benefit from patching but if\n// they exist we ought to consider patching them in all three places\npatchConsoleMethod('error')\npatchConsoleMethod('assert')\npatchConsoleMethod('debug')\npatchConsoleMethod('dir')\npatchConsoleMethod('dirxml')\npatchConsoleMethod('group')\npatchConsoleMethod('groupCollapsed')\npatchConsoleMethod('groupEnd')\npatchConsoleMethod('info')\npatchConsoleMethod('log')\npatchConsoleMethod('table')\npatchConsoleMethod('trace')\npatchConsoleMethod('warn')\n","export class InvariantError extends Error {\n  constructor(message: string, options?: ErrorOptions) {\n    super(\n      `Invariant: ${message.endsWith('.') ? message : message + '.'} This is a bug in Next.js.`,\n      options\n    )\n    this.name = 'InvariantError'\n  }\n}\n","/**\n * The functions provided by this module are used to communicate certain properties\n * about the currently running code so that Next.js can make decisions on how to handle\n * the current execution in different rendering modes such as pre-rendering, resuming, and SSR.\n *\n * Today Next.js treats all code as potentially static. Certain APIs may only make sense when dynamically rendering.\n * Traditionally this meant deopting the entire render to dynamic however with PPR we can now deopt parts\n * of a React tree as dynamic while still keeping other parts static. There are really two different kinds of\n * Dynamic indications.\n *\n * The first is simply an intention to be dynamic. unstable_noStore is an example of this where\n * the currently executing code simply declares that the current scope is dynamic but if you use it\n * inside unstable_cache it can still be cached. This type of indication can be removed if we ever\n * make the default dynamic to begin with because the only way you would ever be static is inside\n * a cache scope which this indication does not affect.\n *\n * The second is an indication that a dynamic data source was read. This is a stronger form of dynamic\n * because it means that it is inappropriate to cache this at all. using a dynamic data source inside\n * unstable_cache should error. If you want to use some dynamic data inside unstable_cache you should\n * read that data outside the cache and pass it in as an argument to the cached function.\n */\n\nimport type { WorkStore } from '../app-render/work-async-storage.external'\nimport type {\n  WorkUnitStore,\n  PrerenderStoreLegacy,\n  PrerenderStoreModern,\n  ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\n\n// Once postpone is in stable we should switch to importing the postpone export directly\nimport React from 'react'\n\nimport { DynamicServerError } from '../../client/components/hooks-server-context'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n  throwForMissingRequestStore,\n  workUnitAsyncStorage,\n} from './work-unit-async-storage.external'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { makeHangingPromise, getRuntimeStage } from '../dynamic-rendering-utils'\nimport {\n  METADATA_BOUNDARY_NAME,\n  VIEWPORT_BOUNDARY_NAME,\n  OUTLET_BOUNDARY_NAME,\n  ROOT_LAYOUT_BOUNDARY_NAME,\n} from '../../lib/framework/boundary-constants'\nimport { scheduleOnNextTick } from '../../lib/scheduler'\nimport { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { INSTANT_VALIDATION_BOUNDARY_NAME } from './instant-validation/boundary-constants'\nimport type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'\nimport type { InstantValidationSampleTracking } from './instant-validation/instant-samples'\n\nconst hasPostpone = typeof React.unstable_postpone === 'function'\n\nexport type DynamicAccess = {\n  /**\n   * If debugging, this will contain the stack trace of where the dynamic access\n   * occurred. This is used to provide more information to the user about why\n   * their page is being rendered dynamically.\n   */\n  stack?: string\n\n  /**\n   * The expression that was accessed dynamically.\n   */\n  expression: string\n}\n\n// Stores dynamic reasons used during an RSC render.\nexport type DynamicTrackingState = {\n  /**\n   * When true, stack information will also be tracked during dynamic access.\n   */\n  readonly isDebugDynamicAccesses: boolean | undefined\n\n  /**\n   * The dynamic accesses that occurred during the render.\n   */\n  readonly dynamicAccesses: Array<DynamicAccess>\n\n  syncDynamicErrorWithStack: null | Error\n}\n\n// Stores dynamic reasons used during an SSR render.\nexport type DynamicValidationState = {\n  hasSuspenseAboveBody: boolean\n  hasDynamicMetadata: boolean\n  dynamicMetadata: null | Error\n  hasDynamicViewport: boolean\n  hasAllowedDynamic: boolean\n  dynamicErrors: Array<Error>\n}\n\nexport function createDynamicTrackingState(\n  isDebugDynamicAccesses: boolean | undefined\n): DynamicTrackingState {\n  return {\n    isDebugDynamicAccesses,\n    dynamicAccesses: [],\n    syncDynamicErrorWithStack: null,\n  }\n}\n\nexport function createDynamicValidationState(): DynamicValidationState {\n  return {\n    hasSuspenseAboveBody: false,\n    hasDynamicMetadata: false,\n    dynamicMetadata: null,\n    hasDynamicViewport: false,\n    hasAllowedDynamic: false,\n    dynamicErrors: [],\n  }\n}\n\nexport function getFirstDynamicReason(\n  trackingState: DynamicTrackingState\n): undefined | string {\n  return trackingState.dynamicAccesses[0]?.expression\n}\n\n/**\n * This function communicates that the current scope should be treated as dynamic.\n *\n * In most cases this function is a no-op but if called during\n * a PPR prerender it will postpone the current sub-tree and calling\n * it during a normal prerender will cause the entire prerender to abort\n */\nexport function markCurrentScopeAsDynamic(\n  store: WorkStore,\n  workUnitStore: undefined | Exclude<WorkUnitStore, PrerenderStoreModern>,\n  expression: string\n): void {\n  if (workUnitStore) {\n    switch (workUnitStore.type) {\n      case 'cache':\n      case 'unstable-cache':\n        // Inside cache scopes, marking a scope as dynamic has no effect,\n        // because the outer cache scope creates a cache boundary. This is\n        // subtly different from reading a dynamic data source, which is\n        // forbidden inside a cache scope.\n        return\n      case 'private-cache':\n        // A private cache scope is already dynamic by definition.\n        return\n      case 'prerender-legacy':\n      case 'prerender-ppr':\n      case 'request':\n      case 'generate-static-params':\n        break\n      default:\n        workUnitStore satisfies never\n    }\n  }\n\n  // If we're forcing dynamic rendering or we're forcing static rendering, we\n  // don't need to do anything here because the entire page is already dynamic\n  // or it's static and it should not throw or postpone here.\n  if (store.forceDynamic || store.forceStatic) return\n\n  if (store.dynamicShouldError) {\n    throw new StaticGenBailoutError(\n      `Route ${store.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n    )\n  }\n\n  if (workUnitStore) {\n    switch (workUnitStore.type) {\n      case 'prerender-ppr':\n        return postponeWithTracking(\n          store.route,\n          expression,\n          workUnitStore.dynamicTracking\n        )\n      case 'prerender-legacy':\n        workUnitStore.revalidate = 0\n\n        // We aren't prerendering, but we are generating a static page. We need\n        // to bail out of static generation.\n        const err = new DynamicServerError(\n          `Route ${store.route} couldn't be rendered statically because it used ${expression}. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n        )\n        store.dynamicUsageDescription = expression\n        store.dynamicUsageStack = err.stack\n\n        throw err\n      case 'request':\n        if (process.env.NODE_ENV !== 'production') {\n          workUnitStore.usedDynamic = true\n        }\n        break\n      case 'generate-static-params':\n        break\n      default:\n        workUnitStore satisfies never\n    }\n  }\n}\n\n/**\n * This function is meant to be used when prerendering without cacheComponents or PPR.\n * When called during a build it will cause Next.js to consider the route as dynamic.\n *\n * @internal\n */\nexport function throwToInterruptStaticGeneration(\n  expression: string,\n  store: WorkStore,\n  prerenderStore: PrerenderStoreLegacy\n): never {\n  // We aren't prerendering but we are generating a static page. We need to bail out of static generation\n  const err = new DynamicServerError(\n    `Route ${store.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n  )\n\n  prerenderStore.revalidate = 0\n\n  store.dynamicUsageDescription = expression\n  store.dynamicUsageStack = err.stack\n\n  throw err\n}\n\n/**\n * This function should be used to track whether something dynamic happened even when\n * we are in a dynamic render. This is useful for Dev where all renders are dynamic but\n * we still track whether dynamic APIs were accessed for helpful messaging\n *\n * @internal\n */\nexport function trackDynamicDataInDynamicRender(workUnitStore: WorkUnitStore) {\n  switch (workUnitStore.type) {\n    case 'cache':\n    case 'unstable-cache':\n      // Inside cache scopes, marking a scope as dynamic has no effect,\n      // because the outer cache scope creates a cache boundary. This is\n      // subtly different from reading a dynamic data source, which is\n      // forbidden inside a cache scope.\n      return\n    case 'private-cache':\n      // A private cache scope is already dynamic by definition.\n      return\n    case 'prerender':\n    case 'prerender-runtime':\n    case 'prerender-legacy':\n    case 'prerender-ppr':\n    case 'prerender-client':\n    case 'validation-client':\n    case 'generate-static-params':\n      break\n    case 'request':\n      if (process.env.NODE_ENV !== 'production') {\n        workUnitStore.usedDynamic = true\n      }\n      break\n    default:\n      workUnitStore satisfies never\n  }\n}\n\nfunction abortOnSynchronousDynamicDataAccess(\n  route: string,\n  expression: string,\n  prerenderStore: PrerenderStoreModern\n): void {\n  const reason = `Route ${route} needs to bail out of prerendering at this point because it used ${expression}.`\n\n  const error = createPrerenderInterruptedError(reason)\n\n  prerenderStore.controller.abort(error)\n\n  const dynamicTracking = prerenderStore.dynamicTracking\n  if (dynamicTracking) {\n    dynamicTracking.dynamicAccesses.push({\n      // When we aren't debugging, we don't need to create another error for the\n      // stack trace.\n      stack: dynamicTracking.isDebugDynamicAccesses\n        ? new Error().stack\n        : undefined,\n      expression,\n    })\n  }\n}\n\nexport function abortOnSynchronousPlatformIOAccess(\n  route: string,\n  expression: string,\n  errorWithStack: Error,\n  prerenderStore: PrerenderStoreModern\n): void {\n  const dynamicTracking = prerenderStore.dynamicTracking\n  abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore)\n  // It is important that we set this tracking value after aborting. Aborts are executed\n  // synchronously except for the case where you abort during render itself. By setting this\n  // value late we can use it to determine if any of the aborted tasks are the task that\n  // called the sync IO expression in the first place.\n  if (dynamicTracking) {\n    if (dynamicTracking.syncDynamicErrorWithStack === null) {\n      dynamicTracking.syncDynamicErrorWithStack = errorWithStack\n    }\n  }\n}\n\n/**\n * use this function when prerendering with cacheComponents. If we are doing a\n * prospective prerender we don't actually abort because we want to discover\n * all caches for the shell. If this is the actual prerender we do abort.\n *\n * This function accepts a prerenderStore but the caller should ensure we're\n * actually running in cacheComponents mode.\n *\n * @internal\n */\nexport function abortAndThrowOnSynchronousRequestDataAccess(\n  route: string,\n  expression: string,\n  errorWithStack: Error,\n  prerenderStore: PrerenderStoreModern\n): never {\n  const prerenderSignal = prerenderStore.controller.signal\n  if (prerenderSignal.aborted === false) {\n    // TODO it would be better to move this aborted check into the callsite so we can avoid making\n    // the error object when it isn't relevant to the aborting of the prerender however\n    // since we need the throw semantics regardless of whether we abort it is easier to land\n    // this way. See how this was handled with `abortOnSynchronousPlatformIOAccess` for a closer\n    // to ideal implementation\n    abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore)\n    // It is important that we set this tracking value after aborting. Aborts are executed\n    // synchronously except for the case where you abort during render itself. By setting this\n    // value late we can use it to determine if any of the aborted tasks are the task that\n    // called the sync IO expression in the first place.\n    const dynamicTracking = prerenderStore.dynamicTracking\n    if (dynamicTracking) {\n      if (dynamicTracking.syncDynamicErrorWithStack === null) {\n        dynamicTracking.syncDynamicErrorWithStack = errorWithStack\n      }\n    }\n  }\n  throw createPrerenderInterruptedError(\n    `Route ${route} needs to bail out of prerendering at this point because it used ${expression}.`\n  )\n}\n\n/**\n * This component will call `React.postpone` that throws the postponed error.\n */\ntype PostponeProps = {\n  reason: string\n  route: string\n}\nexport function Postpone({ reason, route }: PostponeProps): never {\n  const prerenderStore = workUnitAsyncStorage.getStore()\n  const dynamicTracking =\n    prerenderStore && prerenderStore.type === 'prerender-ppr'\n      ? prerenderStore.dynamicTracking\n      : null\n  postponeWithTracking(route, reason, dynamicTracking)\n}\n\nexport function postponeWithTracking(\n  route: string,\n  expression: string,\n  dynamicTracking: null | DynamicTrackingState\n): never {\n  assertPostpone()\n  if (dynamicTracking) {\n    dynamicTracking.dynamicAccesses.push({\n      // When we aren't debugging, we don't need to create another error for the\n      // stack trace.\n      stack: dynamicTracking.isDebugDynamicAccesses\n        ? new Error().stack\n        : undefined,\n      expression,\n    })\n  }\n\n  React.unstable_postpone(createPostponeReason(route, expression))\n}\n\nfunction createPostponeReason(route: string, expression: string) {\n  return (\n    `Route ${route} needs to bail out of prerendering at this point because it used ${expression}. ` +\n    `React throws this special object to indicate where. It should not be caught by ` +\n    `your own try/catch. Learn more: https://nextjs.org/docs/messages/ppr-caught-error`\n  )\n}\n\nexport function isDynamicPostpone(err: unknown) {\n  if (\n    typeof err === 'object' &&\n    err !== null &&\n    typeof (err as any).message === 'string'\n  ) {\n    return isDynamicPostponeReason((err as any).message)\n  }\n  return false\n}\n\nfunction isDynamicPostponeReason(reason: string) {\n  return (\n    reason.includes(\n      'needs to bail out of prerendering at this point because it used'\n    ) &&\n    reason.includes(\n      'Learn more: https://nextjs.org/docs/messages/ppr-caught-error'\n    )\n  )\n}\n\nif (isDynamicPostponeReason(createPostponeReason('%%%', '^^^')) === false) {\n  throw new Error(\n    'Invariant: isDynamicPostpone misidentified a postpone reason. This is a bug in Next.js'\n  )\n}\n\nconst NEXT_PRERENDER_INTERRUPTED = 'NEXT_PRERENDER_INTERRUPTED'\n\nfunction createPrerenderInterruptedError(message: string): Error {\n  const error = new Error(message)\n  ;(error as any).digest = NEXT_PRERENDER_INTERRUPTED\n  return error\n}\n\ntype DigestError = Error & {\n  digest: string\n}\n\nexport function isPrerenderInterruptedError(\n  error: unknown\n): error is DigestError {\n  return (\n    typeof error === 'object' &&\n    error !== null &&\n    (error as any).digest === NEXT_PRERENDER_INTERRUPTED &&\n    'name' in error &&\n    'message' in error &&\n    error instanceof Error\n  )\n}\n\nexport function accessedDynamicData(\n  dynamicAccesses: Array<DynamicAccess>\n): boolean {\n  return dynamicAccesses.length > 0\n}\n\nexport function consumeDynamicAccess(\n  serverDynamic: DynamicTrackingState,\n  clientDynamic: DynamicTrackingState\n): DynamicTrackingState['dynamicAccesses'] {\n  // We mutate because we only call this once we are no longer writing\n  // to the dynamicTrackingState and it's more efficient than creating a new\n  // array.\n  serverDynamic.dynamicAccesses.push(...clientDynamic.dynamicAccesses)\n  return serverDynamic.dynamicAccesses\n}\n\nexport function formatDynamicAPIAccesses(\n  dynamicAccesses: Array<DynamicAccess>\n): string[] {\n  return dynamicAccesses\n    .filter(\n      (access): access is Required<DynamicAccess> =>\n        typeof access.stack === 'string' && access.stack.length > 0\n    )\n    .map(({ expression, stack }) => {\n      stack = stack\n        .split('\\n')\n        // Remove the \"Error: \" prefix from the first line of the stack trace as\n        // well as the first 4 lines of the stack trace which is the distance\n        // from the user code and the `new Error().stack` call.\n        .slice(4)\n        .filter((line) => {\n          // Exclude Next.js internals from the stack trace.\n          if (line.includes('node_modules/next/')) {\n            return false\n          }\n\n          // Exclude anonymous functions from the stack trace.\n          if (line.includes(' (<anonymous>)')) {\n            return false\n          }\n\n          // Exclude Node.js internals from the stack trace.\n          if (line.includes(' (node:')) {\n            return false\n          }\n\n          return true\n        })\n        .join('\\n')\n      return `Dynamic API Usage Debug - ${expression}:\\n${stack}`\n    })\n}\n\nfunction assertPostpone() {\n  if (!hasPostpone) {\n    throw new Error(\n      `Invariant: React.unstable_postpone is not defined. This suggests the wrong version of React was loaded. This is a bug in Next.js`\n    )\n  }\n}\n\n/**\n * This is a bit of a hack to allow us to abort a render using a Postpone instance instead of an Error which changes React's\n * abort semantics slightly.\n */\nexport function createRenderInBrowserAbortSignal(): AbortSignal {\n  const controller = new AbortController()\n  controller.abort(new BailoutToCSRError('Render in Browser'))\n  return controller.signal\n}\n\n/**\n * In a prerender, we may end up with hanging Promises as inputs due them\n * stalling on connection() or because they're loading dynamic data. In that\n * case we need to abort the encoding of arguments since they'll never complete.\n */\nexport function createHangingInputAbortSignal(\n  workUnitStore: WorkUnitStore\n): AbortSignal | undefined {\n  switch (workUnitStore.type) {\n    case 'prerender':\n    case 'prerender-runtime':\n      const controller = new AbortController()\n\n      if (workUnitStore.cacheSignal) {\n        // If we have a cacheSignal it means we're in a prospective render. If\n        // the input we're waiting on is coming from another cache, we do want\n        // to wait for it so that we can resolve this cache entry too.\n        workUnitStore.cacheSignal.inputReady().then(() => {\n          controller.abort()\n        })\n      } else {\n        // Otherwise we're in the final render and we should already have all\n        // our caches filled.\n        // If the prerender uses stages, we have wait until the runtime stage,\n        // at which point all runtime inputs will be resolved.\n        // (otherwise, a runtime prerender might consider `cookies()` hanging\n        //  even though they'd resolve in the next task.)\n        //\n        // We might still be waiting on some microtasks so we\n        // wait one tick before giving up. When we give up, we still want to\n        // render the content of this cache as deeply as we can so that we can\n        // suspend as deeply as possible in the tree or not at all if we don't\n        // end up waiting for the input.\n        if (\n          // eslint-disable-next-line no-restricted-syntax -- We are discriminating between two different refined types and don't need an addition exhaustive switch here\n          workUnitStore.type === 'prerender-runtime' &&\n          workUnitStore.stagedRendering\n        ) {\n          const { stagedRendering } = workUnitStore\n          stagedRendering\n            .waitForStage(getRuntimeStage(stagedRendering))\n            .then(() => scheduleOnNextTick(() => controller.abort()))\n        } else {\n          scheduleOnNextTick(() => controller.abort())\n        }\n      }\n\n      return controller.signal\n    case 'prerender-client':\n    case 'validation-client':\n    case 'prerender-ppr':\n    case 'prerender-legacy':\n    case 'request':\n    case 'cache':\n    case 'private-cache':\n    case 'unstable-cache':\n    case 'generate-static-params':\n      return undefined\n    default:\n      workUnitStore satisfies never\n  }\n}\n\nexport function annotateDynamicAccess(\n  expression: string,\n  prerenderStore: PrerenderStoreModern | ValidationStoreClient\n) {\n  const dynamicTracking = prerenderStore.dynamicTracking\n  if (dynamicTracking) {\n    dynamicTracking.dynamicAccesses.push({\n      stack: dynamicTracking.isDebugDynamicAccesses\n        ? new Error().stack\n        : undefined,\n      expression,\n    })\n  }\n}\n\nexport function useDynamicRouteParams(expression: string) {\n  const workStore = workAsyncStorage.getStore()\n  const workUnitStore = workUnitAsyncStorage.getStore()\n  if (workStore && workUnitStore) {\n    switch (workUnitStore.type) {\n      case 'prerender-client':\n      case 'prerender': {\n        const fallbackParams = workUnitStore.fallbackRouteParams\n\n        if (fallbackParams && fallbackParams.size > 0) {\n          // We are in a prerender with cacheComponents semantics. We are going to\n          // hang here and never resolve. This will cause the currently\n          // rendering component to effectively be a dynamic hole.\n          React.use(\n            makeHangingPromise(\n              workUnitStore.renderSignal,\n              workStore.route,\n              expression\n            )\n          )\n        }\n        break\n      }\n      case 'prerender-ppr': {\n        const fallbackParams = workUnitStore.fallbackRouteParams\n        if (fallbackParams && fallbackParams.size > 0) {\n          return postponeWithTracking(\n            workStore.route,\n            expression,\n            workUnitStore.dynamicTracking\n          )\n        }\n        break\n      }\n      case 'validation-client': {\n        // Don't check fallbackRouteParams here. We handle params that weren't\n        // provided in the samples using a proxy that throws when accessed.\n        break\n      }\n      case 'prerender-runtime':\n        throw new InvariantError(\n          `\\`${expression}\\` was called during a runtime prerender. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`\n        )\n      case 'cache':\n      case 'private-cache':\n        throw new InvariantError(\n          `\\`${expression}\\` was called inside a cache scope. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`\n        )\n      case 'generate-static-params':\n        throw new InvariantError(\n          `\\`${expression}\\` was called in \\`generateStaticParams\\`. Next.js should be preventing ${expression} from being included in server component files statically, but did not in this case.`\n        )\n      case 'prerender-legacy':\n      case 'request':\n      case 'unstable-cache':\n        break\n      default:\n        workUnitStore satisfies never\n    }\n  }\n}\n\nexport function useDynamicSearchParams(expression: string) {\n  const workStore = workAsyncStorage.getStore()\n  const workUnitStore = workUnitAsyncStorage.getStore()\n\n  if (!workStore) {\n    // We assume pages router context and just return\n    return\n  }\n\n  if (!workUnitStore) {\n    throwForMissingRequestStore(expression)\n  }\n\n  switch (workUnitStore.type) {\n    case 'validation-client':\n      // During instant validation we try to behave as close to client as possible,\n      // so this shouldn't hang during SSR.\n      return\n    case 'prerender-client': {\n      React.use(\n        makeHangingPromise(\n          workUnitStore.renderSignal,\n          workStore.route,\n          expression\n        )\n      )\n      break\n    }\n    case 'prerender-legacy':\n    case 'prerender-ppr': {\n      if (workStore.forceStatic) {\n        return\n      }\n      throw new BailoutToCSRError(expression)\n    }\n    case 'prerender':\n    case 'prerender-runtime':\n      throw new InvariantError(\n        `\\`${expression}\\` was called from a Server Component. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`\n      )\n    case 'cache':\n    case 'unstable-cache':\n    case 'private-cache':\n      throw new InvariantError(\n        `\\`${expression}\\` was called inside a cache scope. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`\n      )\n    case 'generate-static-params':\n      throw new InvariantError(\n        `\\`${expression}\\` was called in \\`generateStaticParams\\`. Next.js should be preventing ${expression} from being included in server component files statically, but did not in this case.`\n      )\n    case 'request':\n      return\n    default:\n      workUnitStore satisfies never\n  }\n}\n\nconst hasSuspenseRegex = /\\n\\s+at Suspense \\(<anonymous>\\)/\n\n// Common implicit body tags that React will treat as body when placed directly in html\nconst bodyAndImplicitTags =\n  'body|div|main|section|article|aside|header|footer|nav|form|p|span|h1|h2|h3|h4|h5|h6'\n\n// Detects when RootLayoutBoundary (our framework marker component) appears\n// after Suspense in the component stack, indicating the root layout is wrapped\n// within a Suspense boundary. Ensures no body/html/implicit-body components are in between.\n//\n// Example matches:\n//   at Suspense (<anonymous>)\n//   at __next_root_layout_boundary__ (<anonymous>)\n//\n// Or with other components in between (but not body/html/implicit-body):\n//   at Suspense (<anonymous>)\n//   at SomeComponent (<anonymous>)\n//   at __next_root_layout_boundary__ (<anonymous>)\nconst hasSuspenseBeforeRootLayoutWithoutBodyOrImplicitBodyRegex = new RegExp(\n  `\\\\n\\\\s+at Suspense \\\\(<anonymous>\\\\)(?:(?!\\\\n\\\\s+at (?:${bodyAndImplicitTags}) \\\\(<anonymous>\\\\))[\\\\s\\\\S])*?\\\\n\\\\s+at ${ROOT_LAYOUT_BOUNDARY_NAME} \\\\([^\\\\n]*\\\\)`\n)\n\nconst hasMetadataRegex = new RegExp(\n  `\\\\n\\\\s+at ${METADATA_BOUNDARY_NAME}[\\\\n\\\\s]`\n)\nconst hasViewportRegex = new RegExp(\n  `\\\\n\\\\s+at ${VIEWPORT_BOUNDARY_NAME}[\\\\n\\\\s]`\n)\nconst hasOutletRegex = new RegExp(`\\\\n\\\\s+at ${OUTLET_BOUNDARY_NAME}[\\\\n\\\\s]`)\n\nconst hasInstantValidationBoundaryRegex = new RegExp(\n  `\\\\n\\\\s+at ${INSTANT_VALIDATION_BOUNDARY_NAME}[\\\\n\\\\s]`\n)\n\nexport function trackAllowedDynamicAccess(\n  workStore: WorkStore,\n  componentStack: string,\n  dynamicValidation: DynamicValidationState,\n  clientDynamic: DynamicTrackingState\n) {\n  if (hasOutletRegex.test(componentStack)) {\n    // We don't need to track that this is dynamic. It is only so when something else is also dynamic.\n    return\n  } else if (hasMetadataRegex.test(componentStack)) {\n    dynamicValidation.hasDynamicMetadata = true\n    return\n  } else if (hasViewportRegex.test(componentStack)) {\n    dynamicValidation.hasDynamicViewport = true\n    return\n  } else if (\n    hasSuspenseBeforeRootLayoutWithoutBodyOrImplicitBodyRegex.test(\n      componentStack\n    )\n  ) {\n    // For Suspense within body, the prelude wouldn't be empty so it wouldn't violate the empty static shells rule.\n    // But if you have Suspense above body, the prelude is empty but we allow that because having Suspense\n    // is an explicit signal from the user that they acknowledge the empty shell and want dynamic rendering.\n    dynamicValidation.hasAllowedDynamic = true\n    dynamicValidation.hasSuspenseAboveBody = true\n    return\n  } else if (hasSuspenseRegex.test(componentStack)) {\n    // this error had a Suspense boundary above it so we don't need to report it as a source\n    // of disallowed\n    dynamicValidation.hasAllowedDynamic = true\n    return\n  } else if (clientDynamic.syncDynamicErrorWithStack) {\n    // This task was the task that called the sync error.\n    dynamicValidation.dynamicErrors.push(\n      clientDynamic.syncDynamicErrorWithStack\n    )\n    return\n  } else {\n    const message =\n      `Route \"${workStore.route}\": Uncached data was accessed outside of ` +\n      '<Suspense>. This delays the entire page from rendering, resulting in a ' +\n      'slow user experience. Learn more: ' +\n      'https://nextjs.org/docs/messages/blocking-route'\n    const error = addErrorContext(new Error(message), componentStack, null)\n    dynamicValidation.dynamicErrors.push(error)\n    return\n  }\n}\n\nexport enum DynamicHoleKind {\n  /** We know that this hole is caused by runtime data. */\n  Runtime = 1,\n  /** We know that this hole is caused by dynamic data. */\n  Dynamic = 2,\n}\n\n/** Stores dynamic reasons used during an SSR render in instant validation. */\nexport type InstantValidationState = {\n  hasDynamicMetadata: boolean\n  hasAllowedClientDynamicAboveBoundary: boolean\n  dynamicMetadata: null | Error\n  hasDynamicViewport: boolean\n  hasAllowedDynamic: boolean\n  dynamicErrors: Array<Error>\n  validationPreventingErrors: Array<Error>\n  thrownErrorsOutsideBoundary: Array<unknown>\n  createInstantStack: (() => Error) | null\n}\n\nexport function createInstantValidationState(\n  createInstantStack: (() => Error) | null\n): InstantValidationState {\n  return {\n    hasDynamicMetadata: false,\n    hasAllowedClientDynamicAboveBoundary: false,\n    dynamicMetadata: null,\n    hasDynamicViewport: false,\n    hasAllowedDynamic: false,\n    dynamicErrors: [],\n    validationPreventingErrors: [],\n    thrownErrorsOutsideBoundary: [],\n    createInstantStack,\n  }\n}\n\nexport function trackDynamicHoleInNavigation(\n  workStore: WorkStore,\n  componentStack: string,\n  dynamicValidation: InstantValidationState,\n  clientDynamic: DynamicTrackingState,\n  kind: DynamicHoleKind,\n  boundaryState: ValidationBoundaryTracking\n) {\n  if (hasOutletRegex.test(componentStack)) {\n    // We don't need to track that this is dynamic. It is only so when something else is also dynamic.\n    return\n  }\n  if (hasMetadataRegex.test(componentStack)) {\n    const usageDescription =\n      kind === DynamicHoleKind.Runtime\n        ? `Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateMetadata\\` or you have file-based metadata such as icons that depend on dynamic params segments.`\n        : `Uncached data or \\`connection()\\` was accessed inside \\`generateMetadata\\`.`\n    const message = `Route \"${workStore.route}\": ${usageDescription} Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`\n    const error = addErrorContext(\n      new Error(message),\n      componentStack,\n      dynamicValidation.createInstantStack\n    )\n    dynamicValidation.dynamicMetadata = error\n    return\n  }\n  if (hasViewportRegex.test(componentStack)) {\n    const usageDescription =\n      kind === DynamicHoleKind.Runtime\n        ? `Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateViewport\\`.`\n        : `Uncached data or \\`connection()\\` was accessed inside \\`generateViewport\\`.`\n    const message = `Route \"${workStore.route}\": ${usageDescription} This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`\n    const error = addErrorContext(\n      new Error(message),\n      componentStack,\n      dynamicValidation.createInstantStack\n    )\n    dynamicValidation.dynamicErrors.push(error)\n    return\n  }\n\n  const boundaryLocation =\n    hasInstantValidationBoundaryRegex.exec(componentStack)\n  if (!boundaryLocation) {\n    // We don't see the validation boundary in the component stack,\n    // so this hole must be coming from a shared parent.\n    // Shared parents are fully resolved and don't have RSC holes,\n    // but they can still suspend in a client component during SSR.\n\n    // If we managed to render all the validation boundaries, that means\n    // that the client holes aren't blocking validation and we can disregard them.\n    // Note that we don't even care whether they have suspense or not.\n    if (boundaryState.expectedIds.size === boundaryState.renderedIds.size) {\n      dynamicValidation.hasAllowedClientDynamicAboveBoundary = true\n      dynamicValidation.hasAllowedDynamic = true // Holes outside the boundary contribute to allowing dynamic metadata\n      return\n    } else {\n      // TODO(instant-validation) TODO(NAR-787)\n      // If shared parents blocked us from validating, we should only log\n      // the errors from the innermost (segments), i.e. omit layouts whose\n      // slots managed to render (because clearly they didn't block validation)\n      const message = `Route \"${workStore.route}\": Could not validate \\`unstable_instant\\` because a Client Component in a parent segment prevented the page from rendering.`\n      const error = addErrorContext(\n        new Error(message),\n        componentStack,\n        dynamicValidation.createInstantStack\n      )\n      dynamicValidation.validationPreventingErrors.push(error)\n      return\n    }\n  } else {\n    // The hole originates inside the validation boundary.\n    //\n    // Check if we have a Suspense above the hole, but below the validation boundary.\n    // If we do, then this dynamic usage wouldn't block a navigation to this subtree.\n    // Conversely, if the nearest suspense is above the validation boundary, then this subtree would block.\n    //\n    // Note that in the component stack, children come before parents.\n    //\n    // Valid:\n    //   ...\n    //   at Suspense\n    //   ...\n    //   at __next_prefetch_validation_boundary__\n    //\n    // Invalid:\n    //   ...\n    //   at __next_prefetch_validation_boundary__\n    //   ...\n    //   at Suspense\n    //\n    const suspenseLocation = hasSuspenseRegex.exec(componentStack)\n    if (suspenseLocation) {\n      if (suspenseLocation.index < boundaryLocation.index) {\n        dynamicValidation.hasAllowedDynamic = true\n        return\n      } else {\n        // invalid - fallthrough\n      }\n    }\n  }\n\n  if (clientDynamic.syncDynamicErrorWithStack) {\n    // This task was the task that called the sync error.\n    const syncError = clientDynamic.syncDynamicErrorWithStack\n    if (\n      dynamicValidation.createInstantStack !== null &&\n      syncError.cause === undefined\n    ) {\n      syncError.cause = dynamicValidation.createInstantStack()\n    }\n    dynamicValidation.dynamicErrors.push(syncError)\n    return\n  }\n\n  const usageDescription =\n    kind === DynamicHoleKind.Runtime\n      ? `Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed outside of \\`<Suspense>\\`.`\n      : `Uncached data or \\`connection()\\` was accessed outside of \\`<Suspense>\\`.`\n  const message = `Route \"${workStore.route}\": ${usageDescription} This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route`\n  const error = addErrorContext(\n    new Error(message),\n    componentStack,\n    dynamicValidation.createInstantStack\n  )\n  dynamicValidation.dynamicErrors.push(error)\n  return\n}\n\nexport function trackThrownErrorInNavigation(\n  workStore: WorkStore,\n  dynamicValidation: InstantValidationState,\n  thrownValue: unknown,\n  componentStack: string\n) {\n  const boundaryLocation =\n    hasInstantValidationBoundaryRegex.exec(componentStack)\n  if (!boundaryLocation) {\n    // There's no validation boundary on the component stack.\n    // This error may have blocked a boundary from rendering.\n\n    // Wrap the error to provide component context.\n    // This helps for errors from node_modules which would otherwise\n    // have no useful stack information due to ignore-listing,\n    // e.g. next/dynamic with `ssr: false`.\n    const error = addErrorContext(\n      new Error(\n        'An error occurred while attempting to validate instant UI. This error may be preventing the validation from completing.',\n        { cause: thrownValue }\n      ),\n      componentStack,\n      null\n    )\n    dynamicValidation.thrownErrorsOutsideBoundary.push(error)\n  } else {\n    // There's validation boundary on the component stack,\n    // so we know this error didn't block a validation boundary from rendering.\n    // However, this error might be hiding be hiding dynamic content that would\n    // cause validation to fail.\n    const suspenseLocation = hasSuspenseRegex.exec(componentStack)\n    if (suspenseLocation) {\n      if (suspenseLocation.index < boundaryLocation.index) {\n        // There's a Suspense below the validation boundary but above this error's location.\n        // This subtree can't fail instant validation because any potential\n        // dynamic holes would be guarded by the Suspense anyway,\n        // so we can allow this.\n        return\n      } else {\n        // invalid - fallthrough\n      }\n    }\n    const message = `Route \"${workStore.route}\": Could not validate \\`unstable_instant\\` because an error prevented the target segment from rendering.`\n    const error = addErrorContext(\n      new Error(message, { cause: thrownValue }),\n      componentStack,\n      null // TODO(instant-validation-build): conflicting use of cause\n    )\n    dynamicValidation.validationPreventingErrors.push(error)\n  }\n}\n\nexport function trackDynamicHoleInRuntimeShell(\n  workStore: WorkStore,\n  componentStack: string,\n  dynamicValidation: DynamicValidationState,\n  clientDynamic: DynamicTrackingState\n) {\n  if (hasOutletRegex.test(componentStack)) {\n    // We don't need to track that this is dynamic. It is only so when something else is also dynamic.\n    return\n  } else if (hasMetadataRegex.test(componentStack)) {\n    const message = `Route \"${workStore.route}\": Uncached data or \\`connection()\\` was accessed inside \\`generateMetadata\\`. Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`\n    const error = addErrorContext(new Error(message), componentStack, null)\n    dynamicValidation.dynamicMetadata = error\n    return\n  } else if (hasViewportRegex.test(componentStack)) {\n    // TODO(instant-validation): If the page only has holes caused by runtime data,\n    // we won't find out if there's a suspense-above-body and error for dynamic viewport\n    // even if there is in fact a suspense-above-body\n    const message = `Route \"${workStore.route}\": Uncached data or \\`connection()\\` was accessed inside \\`generateViewport\\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`\n    const error = addErrorContext(new Error(message), componentStack, null)\n    dynamicValidation.dynamicErrors.push(error)\n    return\n  } else if (\n    hasSuspenseBeforeRootLayoutWithoutBodyOrImplicitBodyRegex.test(\n      componentStack\n    )\n  ) {\n    // For Suspense within body, the prelude wouldn't be empty so it wouldn't violate the empty static shells rule.\n    // But if you have Suspense above body, the prelude is empty but we allow that because having Suspense\n    // is an explicit signal from the user that they acknowledge the empty shell and want dynamic rendering.\n    dynamicValidation.hasAllowedDynamic = true\n    dynamicValidation.hasSuspenseAboveBody = true\n    return\n  } else if (hasSuspenseRegex.test(componentStack)) {\n    // this error had a Suspense boundary above it so we don't need to report it as a source\n    // of disallowed\n    dynamicValidation.hasAllowedDynamic = true\n    return\n  } else if (clientDynamic.syncDynamicErrorWithStack) {\n    // This task was the task that called the sync error.\n    dynamicValidation.dynamicErrors.push(\n      clientDynamic.syncDynamicErrorWithStack\n    )\n    return\n  }\n\n  const message = `Route \"${workStore.route}\": Uncached data or \\`connection()\\` was accessed outside of \\`<Suspense>\\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route`\n  const error = addErrorContext(new Error(message), componentStack, null)\n  dynamicValidation.dynamicErrors.push(error)\n  return\n}\n\nexport function trackDynamicHoleInStaticShell(\n  workStore: WorkStore,\n  componentStack: string,\n  dynamicValidation: DynamicValidationState,\n  clientDynamic: DynamicTrackingState\n) {\n  if (hasOutletRegex.test(componentStack)) {\n    // We don't need to track that this is dynamic. It is only so when something else is also dynamic.\n    return\n  } else if (hasMetadataRegex.test(componentStack)) {\n    const message = `Route \"${workStore.route}\": Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateMetadata\\` or you have file-based metadata such as icons that depend on dynamic params segments. Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`\n    const error = addErrorContext(new Error(message), componentStack, null)\n    dynamicValidation.dynamicMetadata = error\n    return\n  } else if (hasViewportRegex.test(componentStack)) {\n    const message = `Route \"${workStore.route}\": Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateViewport\\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`\n    const error = addErrorContext(new Error(message), componentStack, null)\n    dynamicValidation.dynamicErrors.push(error)\n    return\n  } else if (\n    hasSuspenseBeforeRootLayoutWithoutBodyOrImplicitBodyRegex.test(\n      componentStack\n    )\n  ) {\n    // For Suspense within body, the prelude wouldn't be empty so it wouldn't violate the empty static shells rule.\n    // But if you have Suspense above body, the prelude is empty but we allow that because having Suspense\n    // is an explicit signal from the user that they acknowledge the empty shell and want dynamic rendering.\n    dynamicValidation.hasAllowedDynamic = true\n    dynamicValidation.hasSuspenseAboveBody = true\n    return\n  } else if (hasSuspenseRegex.test(componentStack)) {\n    // this error had a Suspense boundary above it so we don't need to report it as a source\n    // of disallowed\n    dynamicValidation.hasAllowedDynamic = true\n    return\n  } else if (clientDynamic.syncDynamicErrorWithStack) {\n    // This task was the task that called the sync error.\n    dynamicValidation.dynamicErrors.push(\n      clientDynamic.syncDynamicErrorWithStack\n    )\n    return\n  } else {\n    const message = `Route \"${workStore.route}\": Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed outside of \\`<Suspense>\\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route`\n    const error = addErrorContext(new Error(message), componentStack, null)\n    dynamicValidation.dynamicErrors.push(error)\n    return\n  }\n}\n\n/**\n * In dev mode, we prefer using the owner stack, otherwise the provided\n * component stack is used.\n *\n * Accepts an already-created Error so the SWC error-code plugin can see the\n * `new Error(...)` call at each call site and auto-assign error codes.\n */\nfunction addErrorContext(\n  error: Error,\n  componentStack: string,\n  createInstantStack: (() => Error) | null\n) {\n  const ownerStack =\n    process.env.NODE_ENV !== 'production' && React.captureOwnerStack\n      ? React.captureOwnerStack()\n      : null\n\n  if (createInstantStack !== null) {\n    error.cause = createInstantStack()\n  }\n  // TODO go back to owner stack here if available. This is temporarily using componentStack to get the right\n  //\n  error.stack =\n    error.name + ': ' + error.message + (ownerStack || componentStack)\n  return error\n}\n\nexport enum PreludeState {\n  Full = 0,\n  Empty = 1,\n  Errored = 2,\n}\n\nexport function logDisallowedDynamicError(\n  workStore: WorkStore,\n  error: Error\n): void {\n  console.error(error)\n\n  if (process.env.NODE_ENV !== 'development') {\n    console.error(`To get a more detailed stack trace and pinpoint the issue, try one of the following:\n  - Start the app in development mode by running \\`next dev\\`, then open \"${workStore.route}\" in your browser to investigate the error.\n  - Rerun the production build with \\`next build --debug-prerender\\` to generate better stack traces.`)\n  } else if (!process.env.__NEXT_DEV_SERVER) {\n    console.error(\n      `To debug the issue, start the app in development mode by running \\`next dev\\`, then open \"${workStore.route}\" in your browser to investigate the error.`\n    )\n  }\n}\n\nexport function throwIfDisallowedDynamic(\n  workStore: WorkStore,\n  prelude: PreludeState,\n  dynamicValidation: DynamicValidationState,\n  serverDynamic: DynamicTrackingState\n): void {\n  if (serverDynamic.syncDynamicErrorWithStack) {\n    logDisallowedDynamicError(\n      workStore,\n      serverDynamic.syncDynamicErrorWithStack\n    )\n    throw new StaticGenBailoutError()\n  }\n\n  if (prelude !== PreludeState.Full) {\n    if (dynamicValidation.hasSuspenseAboveBody) {\n      // This route has opted into allowing fully dynamic rendering\n      // by including a Suspense boundary above the body. In this case\n      // a lack of a shell is not considered disallowed so we simply return\n      return\n    }\n\n    // We didn't have any sync bailouts but there may be user code which\n    // blocked the root. We would have captured these during the prerender\n    // and can log them here and then terminate the build/validating render\n    const dynamicErrors = dynamicValidation.dynamicErrors\n    if (dynamicErrors.length > 0) {\n      for (let i = 0; i < dynamicErrors.length; i++) {\n        logDisallowedDynamicError(workStore, dynamicErrors[i])\n      }\n\n      throw new StaticGenBailoutError()\n    }\n\n    // If we got this far then the only other thing that could be blocking\n    // the root is dynamic Viewport. If this is dynamic then\n    // you need to opt into that by adding a Suspense boundary above the body\n    // to indicate your are ok with fully dynamic rendering.\n    if (dynamicValidation.hasDynamicViewport) {\n      console.error(\n        `Route \"${workStore.route}\" has a \\`generateViewport\\` that depends on Request data (\\`cookies()\\`, etc...) or uncached external data (\\`fetch(...)\\`, etc...) without explicitly allowing fully dynamic rendering. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`\n      )\n      throw new StaticGenBailoutError()\n    }\n\n    if (prelude === PreludeState.Empty) {\n      // If we ever get this far then we messed up the tracking of invalid dynamic.\n      // We still adhere to the constraint that you must produce a shell but invite the\n      // user to report this as a bug in Next.js.\n      console.error(\n        `Route \"${workStore.route}\" did not produce a static shell and Next.js was unable to determine a reason. This is a bug in Next.js.`\n      )\n      throw new StaticGenBailoutError()\n    }\n  } else {\n    if (\n      dynamicValidation.hasAllowedDynamic === false &&\n      dynamicValidation.hasDynamicMetadata\n    ) {\n      console.error(\n        `Route \"${workStore.route}\" has a \\`generateMetadata\\` that depends on Request data (\\`cookies()\\`, etc...) or uncached external data (\\`fetch(...)\\`, etc...) when the rest of the route does not. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`\n      )\n      throw new StaticGenBailoutError()\n    }\n  }\n}\n\nexport function getStaticShellDisallowedDynamicReasons(\n  workStore: WorkStore,\n  prelude: PreludeState,\n  dynamicValidation: DynamicValidationState,\n  configAllowsBlocking: boolean\n): Array<Error> {\n  if (configAllowsBlocking || dynamicValidation.hasSuspenseAboveBody) {\n    // This route has opted into allowing fully dynamic rendering\n    // by including a Suspense boundary above the body. In this case\n    // a lack of a shell is not considered disallowed so we simply return\n    return []\n  }\n\n  if (prelude !== PreludeState.Full) {\n    // We didn't have any sync bailouts but there may be user code which\n    // blocked the root. We would have captured these during the prerender\n    // and can log them here and then terminate the build/validating render\n    const dynamicErrors = dynamicValidation.dynamicErrors\n    if (dynamicErrors.length > 0) {\n      return dynamicErrors\n    }\n\n    if (prelude === PreludeState.Empty) {\n      // If we ever get this far then we messed up the tracking of invalid dynamic.\n      // We still adhere to the constraint that you must produce a shell but invite the\n      // user to report this as a bug in Next.js.\n      return [\n        new InvariantError(\n          `Route \"${workStore.route}\" did not produce a static shell and Next.js was unable to determine a reason.`\n        ),\n      ]\n    }\n  } else {\n    // We have a prelude but we might still have dynamic metadata without any other dynamic access\n    if (\n      dynamicValidation.hasAllowedDynamic === false &&\n      dynamicValidation.dynamicErrors.length === 0 &&\n      dynamicValidation.dynamicMetadata\n    ) {\n      return [dynamicValidation.dynamicMetadata]\n    }\n  }\n  // We had a non-empty prelude and there are no dynamic holes\n  return []\n}\n\nexport function getNavigationDisallowedDynamicReasons(\n  workStore: WorkStore,\n  prelude: PreludeState,\n  dynamicValidation: InstantValidationState,\n  validationSampleTracking: InstantValidationSampleTracking | null,\n  boundaryState: ValidationBoundaryTracking\n): Array<Error> {\n  // If we have errors related to missing samples, those should take precedence over everything else.\n  if (validationSampleTracking) {\n    const { missingSampleErrors } = validationSampleTracking\n    if (missingSampleErrors.length > 0) {\n      return missingSampleErrors\n    }\n  }\n\n  const { validationPreventingErrors } = dynamicValidation\n  if (validationPreventingErrors.length > 0) {\n    return validationPreventingErrors\n  }\n\n  if (boundaryState.renderedIds.size < boundaryState.expectedIds.size) {\n    const { thrownErrorsOutsideBoundary, createInstantStack } =\n      dynamicValidation\n    if (thrownErrorsOutsideBoundary.length === 0) {\n      const message = `Route \"${workStore.route}\": Could not validate \\`unstable_instant\\` because the target segment was prevented from rendering for an unknown reason.`\n      const error =\n        createInstantStack !== null ? createInstantStack() : new Error()\n      error.name = 'Error'\n      error.message = message\n      return [error]\n    } else if (thrownErrorsOutsideBoundary.length === 1) {\n      const message = `Route \"${workStore.route}\": Could not validate \\`unstable_instant\\` because the target segment was prevented from rendering, likely due to the following error.`\n      const error =\n        createInstantStack !== null ? createInstantStack() : new Error()\n      error.name = 'Error'\n      error.message = message\n      return [error, thrownErrorsOutsideBoundary[0] as Error]\n    } else {\n      const message = `Route \"${workStore.route}\": Could not validate \\`unstable_instant\\` because the target segment was prevented from rendering, likely due to one of the following errors.`\n      const error =\n        createInstantStack !== null ? createInstantStack() : new Error()\n      error.name = 'Error'\n      error.message = message\n      return [error, ...(thrownErrorsOutsideBoundary as Error[])]\n    }\n  }\n\n  // NOTE: We don't care about Suspense above body here,\n  // we're only concerned with the validation boundary\n  if (prelude !== PreludeState.Full) {\n    const dynamicErrors = dynamicValidation.dynamicErrors\n    if (dynamicErrors.length > 0) {\n      return dynamicErrors\n    }\n\n    if (prelude === PreludeState.Empty) {\n      // If a client component suspended prevented us from rendering a shell\n      // but didn't block validation, we don't require a prelude.\n      if (dynamicValidation.hasAllowedClientDynamicAboveBoundary) {\n        return []\n      }\n      // If we ever get this far then we messed up the tracking of invalid dynamic.\n      return [\n        new InvariantError(\n          `Route \"${workStore.route}\" failed to render during instant validation and Next.js was unable to determine a reason.`\n        ),\n      ]\n    }\n  } else {\n    const dynamicErrors = dynamicValidation.dynamicErrors\n    if (dynamicErrors.length > 0) {\n      return dynamicErrors\n    }\n\n    if (\n      dynamicValidation.hasAllowedDynamic === false &&\n      dynamicValidation.dynamicMetadata\n    ) {\n      return [dynamicValidation.dynamicMetadata]\n    }\n  }\n  // We had a non-empty prelude and there are no dynamic holes\n  return []\n}\n","import {\n  RenderStage,\n  type AdvanceableRenderStage,\n  type StagedRenderingController,\n} from './app-render/staged-rendering'\nimport type {\n  PrerenderStoreModernRuntime,\n  RequestStore,\n} from './app-render/work-unit-async-storage.external'\n\nexport function isHangingPromiseRejectionError(\n  err: unknown\n): err is HangingPromiseRejectionError {\n  if (typeof err !== 'object' || err === null || !('digest' in err)) {\n    return false\n  }\n\n  return err.digest === HANGING_PROMISE_REJECTION\n}\n\nconst HANGING_PROMISE_REJECTION = 'HANGING_PROMISE_REJECTION'\n\nclass HangingPromiseRejectionError extends Error {\n  public readonly digest = HANGING_PROMISE_REJECTION\n\n  constructor(\n    public readonly route: string,\n    public readonly expression: string\n  ) {\n    super(\n      `During prerendering, ${expression} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${expression} to a different context by using \\`setTimeout\\`, \\`after\\`, or similar functions you may observe this error and you should handle it in that context. This occurred at route \"${route}\".`\n    )\n  }\n}\n\ntype AbortListeners = Array<(err: unknown) => void>\nconst abortListenersBySignal = new WeakMap<AbortSignal, AbortListeners>()\n\n/**\n * This function constructs a promise that will never resolve. This is primarily\n * useful for cacheComponents where we use promise resolution timing to determine which\n * parts of a render can be included in a prerender.\n *\n * @internal\n */\nexport function makeHangingPromise<T>(\n  signal: AbortSignal,\n  route: string,\n  expression: string\n): Promise<T> {\n  if (signal.aborted) {\n    return Promise.reject(new HangingPromiseRejectionError(route, expression))\n  } else {\n    const hangingPromise = new Promise<T>((_, reject) => {\n      const boundRejection = reject.bind(\n        null,\n        new HangingPromiseRejectionError(route, expression)\n      )\n      let currentListeners = abortListenersBySignal.get(signal)\n      if (currentListeners) {\n        currentListeners.push(boundRejection)\n      } else {\n        const listeners = [boundRejection]\n        abortListenersBySignal.set(signal, listeners)\n        signal.addEventListener(\n          'abort',\n          () => {\n            for (let i = 0; i < listeners.length; i++) {\n              listeners[i]()\n            }\n          },\n          { once: true }\n        )\n      }\n    })\n    // We are fine if no one actually awaits this promise. We shouldn't consider this an unhandled rejection so\n    // we attach a noop catch handler here to suppress this warning. If you actually await somewhere or construct\n    // your own promise out of it you'll need to ensure you handle the error when it rejects.\n    hangingPromise.catch(ignoreReject)\n    return hangingPromise\n  }\n}\n\nfunction ignoreReject() {}\n\nexport function makeDevtoolsIOAwarePromise<T>(\n  underlying: T,\n  requestStore: RequestStore,\n  stage: AdvanceableRenderStage\n): Promise<T> {\n  if (requestStore.stagedRendering) {\n    // We resolve each stage in a timeout, so React DevTools will pick this up as IO.\n    return requestStore.stagedRendering.delayUntilStage(\n      stage,\n      undefined,\n      underlying\n    )\n  }\n  // in React DevTools if we resolve in a setTimeout we will observe\n  // the promise resolution as something that can suspend a boundary or root.\n  return new Promise<T>((resolve) => {\n    // Must use setTimeout to be considered IO React DevTools. setImmediate will not work.\n    setTimeout(() => {\n      resolve(underlying)\n    }, 0)\n  })\n}\n\n/**\n * Returns the appropriate runtime stage for the current point in the render.\n * Runtime-prefetchable segments render in the early stages and should wait\n * for EarlyRuntime. Non-prefetchable segments render in the later stages\n * and should wait for Runtime.\n */\nexport function getRuntimeStage(\n  stagedRendering: StagedRenderingController\n): RenderStage.EarlyRuntime | RenderStage.Runtime {\n  if (\n    stagedRendering.currentStage === RenderStage.EarlyStatic ||\n    stagedRendering.currentStage === RenderStage.EarlyRuntime\n  ) {\n    return RenderStage.EarlyRuntime\n  }\n  return RenderStage.Runtime\n}\n\n/**\n * Delays until the appropriate runtime stage based on the current stage of\n * the rendering pipeline:\n *\n * - Early stages → wait for EarlyRuntime\n *   (for runtime-prefetchable segments)\n * - Later stages → wait for Runtime\n *   (for segments not using runtime prefetch)\n *\n * This ensures that cookies()/headers()/etc. resolve at the right time for\n * each segment type.\n */\nexport function delayUntilRuntimeStage<T>(\n  prerenderStore: PrerenderStoreModernRuntime,\n  result: Promise<T>\n): Promise<T> {\n  const { stagedRendering } = prerenderStore\n  if (!stagedRendering) {\n    return result\n  }\n  return stagedRendering\n    .waitForStage(getRuntimeStage(stagedRendering))\n    .then(() => result)\n}\n","import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { abortOnSynchronousPlatformIOAccess } from '../app-render/dynamic-rendering'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { RenderStage } from '../app-render/staged-rendering'\n\nimport { getServerReact, getClientReact } from '../runtime-reacts.external'\n\ntype ApiType = 'time' | 'random' | 'crypto'\n\nexport function io(expression: string, type: ApiType) {\n  const workUnitStore = workUnitAsyncStorage.getStore()\n  const workStore = workAsyncStorage.getStore()\n\n  if (!workUnitStore || !workStore) {\n    return\n  }\n\n  switch (workUnitStore.type) {\n    case 'prerender':\n    case 'prerender-runtime': {\n      const prerenderSignal = workUnitStore.controller.signal\n\n      if (prerenderSignal.aborted === false) {\n        // If the prerender signal is already aborted we don't need to construct\n        // any stacks because something else actually terminated the prerender.\n        let message: string\n        switch (type) {\n          case 'time':\n            message = `Route \"${workStore.route}\" used ${expression} before accessing either uncached data (e.g. \\`fetch()\\`) or Request data (e.g. \\`cookies()\\`, \\`headers()\\`, \\`connection()\\`, and \\`searchParams\\`). Accessing the current time in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time`\n            break\n          case 'random':\n            message = `Route \"${workStore.route}\" used ${expression} before accessing either uncached data (e.g. \\`fetch()\\`) or Request data (e.g. \\`cookies()\\`, \\`headers()\\`, \\`connection()\\`, and \\`searchParams\\`). Accessing random values synchronously in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-random`\n            break\n          case 'crypto':\n            message = `Route \"${workStore.route}\" used ${expression} before accessing either uncached data (e.g. \\`fetch()\\`) or Request data (e.g. \\`cookies()\\`, \\`headers()\\`, \\`connection()\\`, and \\`searchParams\\`). Accessing random cryptographic values synchronously in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto`\n            break\n          default:\n            throw new InvariantError(\n              'Unknown expression type in abortOnSynchronousPlatformIOAccess.'\n            )\n        }\n\n        abortOnSynchronousPlatformIOAccess(\n          workStore.route,\n          expression,\n          applyOwnerStack(new Error(message)),\n          workUnitStore\n        )\n      }\n      break\n    }\n    case 'prerender-client': {\n      const prerenderSignal = workUnitStore.controller.signal\n\n      if (prerenderSignal.aborted === false) {\n        // If the prerender signal is already aborted we don't need to construct\n        // any stacks because something else actually terminated the prerender.\n        let message: string\n        switch (type) {\n          case 'time':\n            message = `Route \"${workStore.route}\" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time-client`\n            break\n          case 'random':\n            message = `Route \"${workStore.route}\" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-random-client`\n            break\n          case 'crypto':\n            message = `Route \"${workStore.route}\" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto-client`\n            break\n          default:\n            throw new InvariantError(\n              'Unknown expression type in abortOnSynchronousPlatformIOAccess.'\n            )\n        }\n\n        abortOnSynchronousPlatformIOAccess(\n          workStore.route,\n          expression,\n          applyOwnerStack(new Error(message)),\n          workUnitStore\n        )\n      }\n      break\n    }\n    case 'request': {\n      const stageController = workUnitStore.stagedRendering\n      if (stageController && stageController.shouldTrackSyncInterrupt()) {\n        let message: string\n        if (\n          stageController.currentStage === RenderStage.Static ||\n          stageController.currentStage === RenderStage.EarlyStatic\n        ) {\n          switch (type) {\n            case 'time':\n              message = `Route \"${workStore.route}\" used ${expression} before accessing either uncached data (e.g. \\`fetch()\\`) or Request data (e.g. \\`cookies()\\`, \\`headers()\\`, \\`connection()\\`, and \\`searchParams\\`). Accessing the current time in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time`\n              break\n            case 'random':\n              message = `Route \"${workStore.route}\" used ${expression} before accessing either uncached data (e.g. \\`fetch()\\`) or Request data (e.g. \\`cookies()\\`, \\`headers()\\`, \\`connection()\\`, and \\`searchParams\\`). Accessing random values synchronously in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-random`\n              break\n            case 'crypto':\n              message = `Route \"${workStore.route}\" used ${expression} before accessing either uncached data (e.g. \\`fetch()\\`) or Request data (e.g. \\`cookies()\\`, \\`headers()\\`, \\`connection()\\`, and \\`searchParams\\`). Accessing random cryptographic values synchronously in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto`\n              break\n            default:\n              throw new InvariantError(\n                'Unknown expression type in abortOnSynchronousPlatformIOAccess.'\n              )\n          }\n        } else {\n          // We're in the Runtime stage.\n          // We only error for Sync IO in the Runtime stage if the route has a runtime prefetch config.\n          // This check is implemented in `stageController.canSyncInterrupt()` --\n          // if runtime prefetching isn't enabled, then we won't get here.\n\n          let accessStatement: string\n          let additionalInfoLink: string\n\n          switch (type) {\n            case 'time':\n              accessStatement = 'the current time'\n              additionalInfoLink =\n                'https://nextjs.org/docs/messages/next-prerender-runtime-current-time'\n              break\n            case 'random':\n              accessStatement = 'random values synchronously'\n              additionalInfoLink =\n                'https://nextjs.org/docs/messages/next-prerender-runtime-random'\n              break\n            case 'crypto':\n              accessStatement = 'random cryptographic values synchronously'\n              additionalInfoLink =\n                'https://nextjs.org/docs/messages/next-prerender-runtime-crypto'\n              break\n            default:\n              throw new InvariantError(\n                'Unknown expression type in abortOnSynchronousPlatformIOAccess.'\n              )\n          }\n\n          message = `Route \"${workStore.route}\" used ${expression} before accessing either uncached data (e.g. \\`fetch()\\`) or awaiting \\`connection()\\`. When configured for Runtime prefetching, accessing ${accessStatement} in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: ${additionalInfoLink}`\n        }\n\n        const syncIOError = applyOwnerStack(new Error(message))\n        stageController.syncInterruptCurrentStageWithReason(syncIOError)\n\n        // A build-time validation render uses a 'request' store type, but may be abortable.\n        // If we're in the second, restarted render of the restart-on-cache miss flow,\n        // Sync IO is an error, and unlike dev, there's no need to continue the render past the sync IO,\n        // so we can abort it.\n        if (\n          workUnitStore.controller &&\n          !workUnitStore.controller.signal.aborted\n        ) {\n          workUnitStore.controller.abort(syncIOError)\n        }\n      }\n      break\n    }\n    case 'validation-client':\n    case 'prerender-ppr':\n    case 'prerender-legacy':\n    case 'cache':\n    case 'private-cache':\n    case 'unstable-cache':\n    case 'generate-static-params':\n      break\n    default:\n      workUnitStore satisfies never\n  }\n}\n\nfunction applyOwnerStack(error: Error) {\n  // TODO: Instead of stitching the stacks here, we should log the original\n  // error as-is when it occurs, and let `patchErrorInspect` handle adding the\n  // owner stack, instead of logging it deferred in the `LogSafely` component\n  // via `throwIfDisallowedDynamic`.\n  if (process.env.NODE_ENV !== 'production') {\n    const ownerStack =\n      getClientReact()?.captureOwnerStack?.() ??\n      getServerReact()?.captureOwnerStack?.()\n\n    if (ownerStack) {\n      let stack = ownerStack\n\n      if (error.stack) {\n        const frames: string[] = []\n\n        for (const frame of error.stack.split('\\n').slice(1)) {\n          if (frame.includes('react_stack_bottom_frame')) {\n            break\n          }\n\n          frames.push(frame)\n        }\n\n        stack = '\\n' + frames.join('\\n') + stack\n      }\n\n      error.stack = error.name + ': ' + error.message + stack\n    }\n  }\n\n  return error\n}\n","/**\n * We extend Math.random() during builds and revalidates to ensure that prerenders don't observe randomness\n * When cacheComponents is enabled. randomness is a form of IO even though it resolves synchronously. When cacheComponents is\n * enabled we need to ensure that randomness is excluded from prerenders.\n *\n * The extensions here never error nor alter the random generation itself and thus should be transparent to callers.\n */\n\nimport { io } from './io-utils'\n\nconst expression = '`Math.random()`'\ntry {\n  const _random = Math.random\n  Math.random = function random() {\n    io(expression, 'random')\n    return _random.apply(null, arguments as any)\n\n    // We bind here to alter the `toString` printing to match `Math.random`'s native `toString`.\n    // eslint-disable-next-line no-extra-bind\n  }.bind(null)\n  Object.defineProperty(Math.random, 'name', { value: 'random' })\n} catch {\n  console.error(\n    `Failed to install ${expression} extension. When using \\`cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n  )\n}\n","/**\n * We extend node:crypto APIs during builds and revalidates to ensure that prerenders don't observe random bytes\n * When cacheComponents is enabled. Random bytes are a form of IO even if they resolve synchronously. When cacheComponents is\n * enabled we need to ensure that random bytes are excluded from prerenders unless they are cached.\n *\n *\n * The extensions here never error nor alter the underlying return values and thus should be transparent to callers.\n */\n\nimport { io } from './io-utils'\n\nif (process.env.NEXT_RUNTIME === 'edge') {\n  // nothing to patch\n} else {\n  const nodeCrypto = require('node:crypto') as typeof import('node:crypto')\n\n  // require('node:crypto').getRandomValues is an alias for\n  // crypto.getRandomValues which is extended in web-crypto.tsx\n\n  // require('node:crypto').randomUUID is not an alias for crypto.randomUUID\n\n  const randomUUIDExpression = \"`require('node:crypto').randomUUID()`\"\n  try {\n    const _randomUUID = nodeCrypto.randomUUID\n    nodeCrypto.randomUUID = function randomUUID() {\n      io(randomUUIDExpression, 'random')\n      return _randomUUID.apply(this, arguments as any)\n    }\n  } catch {\n    console.error(\n      `Failed to install ${randomUUIDExpression} extension. When using \\`cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n    )\n  }\n\n  const randomBytesExpression = \"`require('node:crypto').randomBytes(size)`\"\n  try {\n    const _randomBytes = nodeCrypto.randomBytes\n    // @ts-expect-error -- TODO: tell TS the overloads are preserved\n    nodeCrypto.randomBytes = function randomBytes() {\n      if (typeof arguments[1] !== 'function') {\n        // randomBytes is sync if the second arg is undefined\n        io(randomBytesExpression, 'random')\n      }\n      return _randomBytes.apply(this, arguments as any)\n    }\n  } catch {\n    console.error(\n      `Failed to install ${randomBytesExpression} extension. When using \\`cacheComponents\\` calling this function without a callback argument will not correctly trigger dynamic behavior.`\n    )\n  }\n\n  const randomFillSyncExpression =\n    \"`require('node:crypto').randomFillSync(...)`\"\n  try {\n    const _randomFillSync = nodeCrypto.randomFillSync\n    // @ts-expect-error -- TODO: tell TS the overloads are preserved\n    nodeCrypto.randomFillSync = function randomFillSync() {\n      io(randomFillSyncExpression, 'random')\n      return _randomFillSync.apply(this, arguments as any)\n    }\n  } catch {\n    console.error(\n      `Failed to install ${randomFillSyncExpression} extension. When using \\`cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n    )\n  }\n\n  const randomIntExpression = \"`require('node:crypto').randomInt(min, max)`\"\n  try {\n    const _randomInt = nodeCrypto.randomInt\n    // @ts-expect-error -- TODO: tell TS the overloads are preserved\n    nodeCrypto.randomInt = function randomInt() {\n      if (typeof arguments[2] !== 'function') {\n        // randomInt is sync if the third arg is undefined\n        io(randomIntExpression, 'random')\n      }\n      return _randomInt.apply(this, arguments as any)\n    }\n  } catch {\n    console.error(\n      `Failed to install ${randomBytesExpression} extension. When using \\`cacheComponents\\` calling this function without a callback argument will not correctly trigger dynamic behavior.`\n    )\n  }\n\n  const generatePrimeSyncExpression =\n    \"`require('node:crypto').generatePrimeSync(...)`\"\n  try {\n    const _generatePrimeSync = nodeCrypto.generatePrimeSync\n    // @ts-expect-error -- TODO: tell TS the overloads are preserved\n    nodeCrypto.generatePrimeSync = function generatePrimeSync() {\n      io(generatePrimeSyncExpression, 'random')\n      return _generatePrimeSync.apply(this, arguments as any)\n    }\n  } catch {\n    console.error(\n      `Failed to install ${generatePrimeSyncExpression} extension. When using \\`cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n    )\n  }\n\n  const generateKeyPairSyncExpression =\n    \"`require('node:crypto').generateKeyPairSync(...)`\"\n  try {\n    const _generateKeyPairSync = nodeCrypto.generateKeyPairSync\n    // @ts-expect-error -- TODO: tell TS the overloads are preserved\n    nodeCrypto.generateKeyPairSync = function generateKeyPairSync() {\n      io(generateKeyPairSyncExpression, 'random')\n      return _generateKeyPairSync.apply(this, arguments as any)\n    }\n  } catch {\n    console.error(\n      `Failed to install ${generateKeyPairSyncExpression} extension. When using \\`cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n    )\n  }\n\n  const generateKeySyncExpression =\n    \"`require('node:crypto').generateKeySync(...)`\"\n  try {\n    const _generateKeySync = nodeCrypto.generateKeySync\n    nodeCrypto.generateKeySync = function generateKeySync() {\n      io(generateKeySyncExpression, 'random')\n      return _generateKeySync.apply(this, arguments as any)\n    }\n  } catch {\n    console.error(\n      `Failed to install ${generateKeySyncExpression} extension. When using \\`cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n    )\n  }\n}\n","// Synchronously inject a require hook for webpack and webpack/. It's required to use the internal ncc webpack version.\n// This is needed for userland plugins to attach to the same webpack instance as Next.js'.\n// Individually compiled modules are as defined for the compilation in bundles/webpack/packages/*.\n\n// This module will only be loaded once per process.\nconst path = require('path') as typeof import('path')\nconst mod = require('module') as typeof import('module')\nconst originalRequire = mod.prototype.require\nconst resolveFilename =\n  // @ts-expect-error\n  mod._resolveFilename\n\nlet resolve: typeof require.resolve = process.env.NEXT_MINIMAL\n  ? // @ts-ignore\n    __non_webpack_require__.resolve\n  : require.resolve\n\nexport const hookPropertyMap = new Map()\n\nexport const defaultOverrides: Record<string, string> = {}\n\ntry {\n  Object.assign(defaultOverrides, {\n    'styled-jsx': path.dirname(resolve('styled-jsx/package.json')),\n    'styled-jsx/style': resolve('styled-jsx/style'),\n    'styled-jsx/style.js': resolve('styled-jsx/style'),\n  })\n} catch (_) {}\n\nconst toResolveMap = (map: Record<string, string>): [string, string][] => {\n  const resolveMap: [string, string][] = []\n  for (const [key, value] of Object.entries(map)) {\n    try {\n      resolveMap.push([key, resolve(value)])\n    } catch {}\n  }\n  return resolveMap\n}\n\nexport function addHookAliases(aliases: [string, string][] = []) {\n  for (const [key, value] of aliases) {\n    hookPropertyMap.set(key, value)\n  }\n}\n\naddHookAliases(toResolveMap(defaultOverrides))\n\n// @ts-expect-error\nmod._resolveFilename = function (\n  originalResolveFilename: (\n    request: string,\n    parent: string,\n    isMain: boolean,\n    opts: any\n  ) => string,\n  requestMap: Map<string, string>,\n  request: string,\n  parent: string,\n  isMain: boolean,\n  options: any\n) {\n  const hookResolved = requestMap.get(request)\n  if (hookResolved) request = hookResolved\n\n  return originalResolveFilename.call(mod, request, parent, isMain, options)\n\n  // We use `bind` here to avoid referencing outside variables to create potential memory leaks.\n}.bind(null, resolveFilename, hookPropertyMap)\n\n// @ts-expect-error\n// This is a hack to make sure that if a user requires a Next.js module that wasn't bundled\n// that needs to point to the rendering runtime version, it will point to the correct one.\n// This can happen on `pages` when a user requires a dependency that uses next/image for example.\nmod.prototype.require = function (request: string) {\n  if (request.endsWith('.shared-runtime')) {\n    return originalRequire.call(\n      this,\n      `next/dist/server/route-modules/pages/vendored/contexts/${path.basename(\n        request,\n        '.shared-runtime'\n      )}`\n    )\n  }\n\n  return originalRequire.call(this, request)\n}\n","import type { HtmlProps } from './html-context.shared-runtime'\nimport type { ComponentType, JSX } from 'react'\nimport type { DomainLocale } from '../../server/config'\nimport type { Env } from '@next/env'\nimport type { IncomingMessage, ServerResponse } from 'http'\nimport type { NextRouter } from './router/router'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { PreviewData } from '../../types'\nimport type { COMPILER_NAMES } from './constants'\nimport type fs from 'fs'\n\nexport type NextComponentType<\n  Context extends BaseContext = NextPageContext,\n  InitialProps = {},\n  Props = {},\n> = ComponentType<Props> & {\n  /**\n   * Used for initial page load data population. Data returned from `getInitialProps` is serialized when server rendered.\n   * Make sure to return plain `Object` without using `Date`, `Map`, `Set`.\n   * @param context Context of `page`\n   */\n  getInitialProps?(context: Context): InitialProps | Promise<InitialProps>\n}\n\nexport type DocumentType = NextComponentType<\n  DocumentContext,\n  DocumentInitialProps,\n  DocumentProps\n>\n\nexport type AppType<P = {}> = NextComponentType<\n  AppContextType,\n  P,\n  AppPropsType<any, P>\n>\n\nexport type AppTreeType = ComponentType<\n  AppInitialProps & { [name: string]: any }\n>\n\n/**\n * Web vitals provided to _app.reportWebVitals by Core Web Vitals plugin developed by Google Chrome team.\n * https://nextjs.org/blog/next-9-4#integrated-web-vitals-reporting\n */\nexport const WEB_VITALS = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'] as const\nexport type NextWebVitalsMetric = {\n  id: string\n  startTime: number\n  value: number\n  attribution?: { [key: string]: unknown }\n} & (\n  | {\n      label: 'web-vital'\n      name: (typeof WEB_VITALS)[number]\n    }\n  | {\n      label: 'custom'\n      name:\n        | 'Next.js-hydration'\n        | 'Next.js-route-change-to-render'\n        | 'Next.js-render'\n    }\n)\n\nexport type Enhancer<C> = (Component: C) => C\n\nexport type ComponentsEnhancer =\n  | {\n      enhanceApp?: Enhancer<AppType>\n      enhanceComponent?: Enhancer<NextComponentType>\n    }\n  | Enhancer<NextComponentType>\n\nexport type RenderPageResult = {\n  html: string\n  head?: Array<JSX.Element | null>\n}\n\nexport type RenderPage = (\n  options?: ComponentsEnhancer\n) => DocumentInitialProps | Promise<DocumentInitialProps>\n\nexport type BaseContext = {\n  res?: ServerResponse\n  [k: string]: any\n}\n\nexport type NEXT_DATA = {\n  props: Record<string, any>\n  page: string\n  query: ParsedUrlQuery\n  buildId: string\n  assetPrefix?: string\n  nextExport?: boolean\n  autoExport?: boolean\n  isFallback?: boolean\n  isExperimentalCompile?: boolean\n  dynamicIds?: (string | number)[]\n  err?: Error & {\n    statusCode?: number\n    source?: typeof COMPILER_NAMES.server | typeof COMPILER_NAMES.edgeServer\n  }\n  gsp?: boolean\n  gssp?: boolean\n  customServer?: boolean\n  gip?: boolean\n  appGip?: boolean\n  locale?: string\n  locales?: readonly string[]\n  defaultLocale?: string\n  domainLocales?: readonly DomainLocale[]\n  scriptLoader?: any[]\n  isPreview?: boolean\n  notFoundSrcPage?: string\n}\n\n/**\n * `Next` context\n */\nexport interface NextPageContext {\n  /**\n   * Error object if encountered during rendering\n   */\n  err?: (Error & { statusCode?: number }) | null\n  /**\n   * `HTTP` request object.\n   */\n  req?: IncomingMessage\n  /**\n   * `HTTP` response object.\n   */\n  res?: ServerResponse\n  /**\n   * Path section of `URL`.\n   */\n  pathname: string\n  /**\n   * Query string section of `URL` parsed as an object.\n   */\n  query: ParsedUrlQuery\n  /**\n   * `String` of the actual path including query.\n   */\n  asPath?: string\n  /**\n   * The currently active locale\n   */\n  locale?: string\n  /**\n   * All configured locales\n   */\n  locales?: readonly string[]\n  /**\n   * The configured default locale\n   */\n  defaultLocale?: string\n  /**\n   * `Component` the tree of the App to use if needing to render separately\n   */\n  AppTree: AppTreeType\n}\n\nexport type AppContextType<Router extends NextRouter = NextRouter> = {\n  Component: NextComponentType<NextPageContext>\n  AppTree: AppTreeType\n  ctx: NextPageContext\n  router: Router\n}\n\nexport type AppInitialProps<PageProps = any> = {\n  pageProps: PageProps\n}\n\nexport type AppPropsType<\n  Router extends NextRouter = NextRouter,\n  PageProps = {},\n> = AppInitialProps<PageProps> & {\n  Component: NextComponentType<NextPageContext, any, any>\n  router: Router\n  __N_SSG?: boolean\n  __N_SSP?: boolean\n}\n\nexport type DocumentContext = NextPageContext & {\n  renderPage: RenderPage\n  defaultGetInitialProps(\n    ctx: DocumentContext,\n    options?: { nonce?: string }\n  ): Promise<DocumentInitialProps>\n}\n\nexport type DocumentInitialProps = RenderPageResult & {\n  styles?: React.ReactElement[] | Iterable<React.ReactNode> | JSX.Element\n}\n\nexport type DocumentProps = DocumentInitialProps & HtmlProps\n\n/**\n * Next `API` route request\n */\nexport interface NextApiRequest extends IncomingMessage {\n  /**\n   * Object of `query` values from url\n   */\n  query: Partial<{\n    [key: string]: string | string[]\n  }>\n  /**\n   * Object of `cookies` from header\n   */\n  cookies: Partial<{\n    [key: string]: string\n  }>\n\n  body: any\n\n  env: Env\n\n  draftMode?: boolean\n\n  preview?: boolean\n  /**\n   * Preview data set on the request, if any\n   * */\n  previewData?: PreviewData\n}\n\n/**\n * Send body of response\n */\ntype Send<T> = (body: T) => void\n\n/**\n * Next `API` route response\n */\nexport type NextApiResponse<Data = any> = ServerResponse & {\n  /**\n   * Send data `any` data in response\n   */\n  send: Send<Data>\n  /**\n   * Send data `json` data in response\n   */\n  json: Send<Data>\n  status: (statusCode: number) => NextApiResponse<Data>\n  redirect(url: string): NextApiResponse<Data>\n  redirect(status: number, url: string): NextApiResponse<Data>\n\n  /**\n   * Set draft mode\n   */\n  setDraftMode: (options: { enable: boolean }) => NextApiResponse<Data>\n\n  /**\n   * Set preview data for Next.js' prerender mode\n   */\n  setPreviewData: (\n    data: object | string,\n    options?: {\n      /**\n       * Specifies the number (in seconds) for the preview session to last for.\n       * The given number will be converted to an integer by rounding down.\n       * By default, no maximum age is set and the preview session finishes\n       * when the client shuts down (browser is closed).\n       */\n      maxAge?: number\n      /**\n       * Specifies the path for the preview session to work under. By default,\n       * the path is considered the \"default path\", i.e., any pages under \"/\".\n       */\n      path?: string\n    }\n  ) => NextApiResponse<Data>\n\n  /**\n   * Clear preview data for Next.js' prerender mode\n   */\n  clearPreviewData: (options?: { path?: string }) => NextApiResponse<Data>\n\n  /**\n   * Revalidate a specific page and regenerate it using On-Demand Incremental\n   * Static Regeneration.\n   * The path should be an actual path, not a rewritten path. E.g. for\n   * \"/blog/[slug]\" this should be \"/blog/post-1\".\n   * @link https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation-with-revalidatepath\n   */\n  revalidate: (\n    urlPath: string,\n    opts?: {\n      unstable_onlyGenerated?: boolean\n    }\n  ) => Promise<void>\n}\n\n/**\n * Next `API` route handler\n */\nexport type NextApiHandler<T = any> = (\n  req: NextApiRequest,\n  res: NextApiResponse<T>\n) => unknown | Promise<unknown>\n\n/**\n * Utils\n */\nexport function execOnce<T extends (...args: any[]) => ReturnType<T>>(\n  fn: T\n): T {\n  let used = false\n  let result: ReturnType<T>\n\n  return ((...args: any[]) => {\n    if (!used) {\n      used = true\n      result = fn(...args)\n    }\n    return result\n  }) as T\n}\n\n// Scheme: https://tools.ietf.org/html/rfc3986#section-3.1\n// Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3\nconst ABSOLUTE_URL_REGEX = /^[a-zA-Z][a-zA-Z\\d+\\-.]*?:/\nexport const isAbsoluteUrl = (url: string) => ABSOLUTE_URL_REGEX.test(url)\n\nexport function getLocationOrigin() {\n  const { protocol, hostname, port } = window.location\n  return `${protocol}//${hostname}${port ? ':' + port : ''}`\n}\n\nexport function getURL() {\n  const { href } = window.location\n  const origin = getLocationOrigin()\n  return href.substring(origin.length)\n}\n\nexport function getDisplayName<P>(Component: ComponentType<P>) {\n  return typeof Component === 'string'\n    ? Component\n    : Component.displayName || Component.name || 'Unknown'\n}\n\nexport function isResSent(res: ServerResponse) {\n  return res.finished || res.headersSent\n}\n\nexport function normalizeRepeatedSlashes(url: string) {\n  const urlParts = url.split('?')\n  const urlNoQuery = urlParts[0]\n\n  return (\n    urlNoQuery\n      // first we replace any non-encoded backslashes with forward\n      // then normalize repeated forward slashes\n      .replace(/\\\\/g, '/')\n      .replace(/\\/\\/+/g, '/') +\n    (urlParts[1] ? `?${urlParts.slice(1).join('?')}` : '')\n  )\n}\n\nexport async function loadGetInitialProps<\n  C extends BaseContext,\n  IP = {},\n  P = {},\n>(App: NextComponentType<C, IP, P>, ctx: C): Promise<IP> {\n  if (process.env.NODE_ENV !== 'production') {\n    if (App.prototype?.getInitialProps) {\n      const message = `\"${getDisplayName(\n        App\n      )}.getInitialProps()\" is defined as an instance method - visit https://nextjs.org/docs/messages/get-initial-props-as-an-instance-method for more information.`\n      throw new Error(message)\n    }\n  }\n  // when called from _app `ctx` is nested in `ctx`\n  const res = ctx.res || (ctx.ctx && ctx.ctx.res)\n\n  if (!App.getInitialProps) {\n    if (ctx.ctx && ctx.Component) {\n      // @ts-ignore pageProps default\n      return {\n        pageProps: await loadGetInitialProps(ctx.Component, ctx.ctx),\n      }\n    }\n    return {} as IP\n  }\n\n  const props = await App.getInitialProps(ctx)\n\n  if (res && isResSent(res)) {\n    return props\n  }\n\n  if (!props) {\n    const message = `\"${getDisplayName(\n      App\n    )}.getInitialProps()\" should resolve to an object. But found \"${props}\" instead.`\n    throw new Error(message)\n  }\n\n  if (process.env.NODE_ENV !== 'production') {\n    if (Object.keys(props).length === 0 && !ctx.ctx) {\n      console.warn(\n        `${getDisplayName(\n          App\n        )} returned an empty object from \\`getInitialProps\\`. This de-optimizes and prevents automatic static optimization. https://nextjs.org/docs/messages/empty-object-getInitialProps`\n      )\n    }\n  }\n\n  return props\n}\n\nexport const SP = typeof performance !== 'undefined'\nexport const ST =\n  SP &&\n  (['mark', 'measure', 'getEntriesByName'] as const).every(\n    (method) => typeof performance[method] === 'function'\n  )\n\nexport class DecodeError extends Error {}\nexport class NormalizeError extends Error {}\nexport class PageNotFoundError extends Error {\n  code: string\n\n  constructor(page: string) {\n    super()\n    this.code = 'ENOENT'\n    this.name = 'PageNotFoundError'\n    this.message = `Cannot find module for page: ${page}`\n  }\n}\n\nexport class MissingStaticPage extends Error {\n  constructor(page: string, message: string) {\n    super()\n    this.message = `Failed to load static file for page: ${page} ${message}`\n  }\n}\n\nexport class MiddlewareNotFoundError extends Error {\n  code: string\n  constructor() {\n    super()\n    this.code = 'ENOENT'\n    this.message = `Cannot find the middleware module`\n  }\n}\n\nexport interface CacheFs {\n  existsSync: typeof fs.existsSync\n  readFile: typeof fs.promises.readFile\n  readFileSync: typeof fs.readFileSync\n  writeFile(f: string, d: any): Promise<void>\n  mkdir(dir: string): Promise<void | string>\n  stat(f: string): Promise<{ mtime: Date }>\n}\n\nexport function stringifyError(error: Error) {\n  return JSON.stringify({ message: error.message, stack: error.stack })\n}\n","import type { Token } from 'next/dist/compiled/path-to-regexp'\n\n/**\n * Route pattern normalization utilities for path-to-regexp compatibility.\n *\n * path-to-regexp 6.3.0+ introduced stricter validation that rejects certain\n * patterns commonly used in Next.js interception routes. This module provides\n * normalization functions to make Next.js route patterns compatible with the\n * updated library while preserving all functionality.\n */\n\n/**\n * Internal separator used to normalize adjacent parameter patterns.\n * This unique marker is inserted between adjacent parameters and stripped out\n * during parameter extraction to avoid conflicts with real URL content.\n */\nexport const PARAM_SEPARATOR = '_NEXTSEP_'\n\n/**\n * Detects if a route pattern needs normalization for path-to-regexp compatibility.\n */\nexport function hasAdjacentParameterIssues(route: string): boolean {\n  if (typeof route !== 'string') return false\n\n  // Check for interception route markers followed immediately by parameters\n  // Pattern: /(.):param, /(..):param, /(...):param, /(.)(.):param etc.\n  // These patterns cause \"Must have text between two parameters\" errors\n  if (/\\/\\(\\.{1,3}\\):[^/\\s]+/.test(route)) {\n    return true\n  }\n\n  // Check for basic adjacent parameters without separators\n  // Pattern: :param1:param2 (but not :param* or other URL patterns)\n  if (/:[a-zA-Z_][a-zA-Z0-9_]*:[a-zA-Z_][a-zA-Z0-9_]*/.test(route)) {\n    return true\n  }\n\n  return false\n}\n\n/**\n * Normalizes route patterns that have adjacent parameters without text between them.\n * Inserts a unique separator that can be safely stripped out later.\n */\nexport function normalizeAdjacentParameters(route: string): string {\n  let normalized = route\n\n  // Handle interception route patterns: (.):param -> (.)_NEXTSEP_:param\n  normalized = normalized.replace(\n    /(\\([^)]*\\)):([^/\\s]+)/g,\n    `$1${PARAM_SEPARATOR}:$2`\n  )\n\n  // Handle other adjacent parameter patterns: :param1:param2 -> :param1_NEXTSEP_:param2\n  normalized = normalized.replace(/:([^:/\\s)]+)(?=:)/g, `:$1${PARAM_SEPARATOR}`)\n\n  return normalized\n}\n\n/**\n * Normalizes tokens that have repeating modifiers (* or +) but empty prefix and suffix.\n *\n * path-to-regexp 6.3.0+ introduced validation that throws:\n * \"Can not repeat without prefix/suffix\"\n *\n * This occurs when a token has modifier: '*' or '+' with both prefix: '' and suffix: ''\n */\nexport function normalizeTokensForRegexp(tokens: Token[]): Token[] {\n  return tokens.map((token) => {\n    // Token union type: Token = string | TokenObject\n    // Literal path segments are strings, parameters/wildcards are objects\n    if (\n      typeof token === 'object' &&\n      token !== null &&\n      // Not all token objects have 'modifier' property (e.g., simple text tokens)\n      'modifier' in token &&\n      // Only repeating modifiers (* or +) cause the validation error\n      // Other modifiers like '?' (optional) are fine\n      (token.modifier === '*' || token.modifier === '+') &&\n      // Token objects can have different shapes depending on route pattern\n      'prefix' in token &&\n      'suffix' in token &&\n      // Both prefix and suffix must be empty strings\n      // This is what causes the validation error in path-to-regexp\n      token.prefix === '' &&\n      token.suffix === ''\n    ) {\n      // Add minimal prefix to satisfy path-to-regexp validation\n      // We use '/' as it's the most common path delimiter and won't break route matching\n      // The prefix gets used in regex generation but doesn't affect parameter extraction\n      return {\n        ...token,\n        prefix: '/',\n      }\n    }\n    return token\n  })\n}\n\n/**\n * Strips normalization separators from compiled pathname.\n * This removes separators that were inserted by normalizeAdjacentParameters\n * to satisfy path-to-regexp validation.\n *\n * Only removes separators in the specific contexts where they were inserted:\n * - After interception route markers: (.)_NEXTSEP_ -> (.)\n *\n * This targeted approach ensures we don't accidentally remove the separator\n * from legitimate user content.\n */\nexport function stripNormalizedSeparators(pathname: string): string {\n  // Remove separator after interception route markers\n  // Pattern: (.)_NEXTSEP_ -> (.), (..)_NEXTSEP_ -> (..), etc.\n  // The separator appears after the closing paren of interception markers\n  return pathname.replace(new RegExp(`\\\\)${PARAM_SEPARATOR}`, 'g'), ')')\n}\n\n/**\n * Strips normalization separators from extracted route parameters.\n * Used by both server and client code to clean up parameters after route matching.\n */\nexport function stripParameterSeparators(\n  params: Record<string, any>\n): Record<string, any> {\n  const cleaned: Record<string, any> = {}\n\n  for (const [key, value] of Object.entries(params)) {\n    if (typeof value === 'string') {\n      // Remove the separator if it appears at the start of parameter values\n      cleaned[key] = value.replace(new RegExp(`^${PARAM_SEPARATOR}`), '')\n    } else if (Array.isArray(value)) {\n      // Handle array parameters (from repeated route segments)\n      cleaned[key] = value.map((item) =>\n        typeof item === 'string'\n          ? item.replace(new RegExp(`^${PARAM_SEPARATOR}`), '')\n          : item\n      )\n    } else {\n      cleaned[key] = value\n    }\n  }\n\n  return cleaned\n}\n","/**\n * Client-safe utilities for route matching that don't import server-side\n * utilities to avoid bundling issues with Turbopack\n */\n\nimport type {\n  Key,\n  TokensToRegexpOptions,\n  ParseOptions,\n  TokensToFunctionOptions,\n} from 'next/dist/compiled/path-to-regexp'\nimport {\n  pathToRegexp,\n  compile,\n  regexpToFunction,\n} from 'next/dist/compiled/path-to-regexp'\nimport {\n  hasAdjacentParameterIssues,\n  normalizeAdjacentParameters,\n  stripParameterSeparators,\n  stripNormalizedSeparators,\n} from '../../../../lib/route-pattern-normalizer'\n\n/**\n * Client-safe wrapper around pathToRegexp that handles path-to-regexp 6.3.0+ validation errors.\n * This includes both \"Can not repeat without prefix/suffix\" and \"Must have text between parameters\" errors.\n */\nexport function safePathToRegexp(\n  route: string | RegExp | Array<string | RegExp>,\n  keys?: Key[],\n  options?: TokensToRegexpOptions & ParseOptions\n): RegExp {\n  if (typeof route !== 'string') {\n    return pathToRegexp(route, keys, options)\n  }\n\n  // Check if normalization is needed and cache the result\n  const needsNormalization = hasAdjacentParameterIssues(route)\n  const routeToUse = needsNormalization\n    ? normalizeAdjacentParameters(route)\n    : route\n\n  try {\n    return pathToRegexp(routeToUse, keys, options)\n  } catch (error) {\n    // Only try normalization if we haven't already normalized\n    if (!needsNormalization) {\n      try {\n        const normalizedRoute = normalizeAdjacentParameters(route)\n        return pathToRegexp(normalizedRoute, keys, options)\n      } catch (retryError) {\n        // If that doesn't work, fall back to original error\n        throw error\n      }\n    }\n    throw error\n  }\n}\n\n/**\n * Client-safe wrapper around compile that handles path-to-regexp 6.3.0+ validation errors.\n * No server-side error reporting to avoid bundling issues.\n * When normalization is applied, the returned compiler function automatically strips\n * the internal separator from the output URL.\n */\nexport function safeCompile(\n  route: string,\n  options?: TokensToFunctionOptions & ParseOptions\n) {\n  // Check if normalization is needed and cache the result\n  const needsNormalization = hasAdjacentParameterIssues(route)\n  const routeToUse = needsNormalization\n    ? normalizeAdjacentParameters(route)\n    : route\n\n  try {\n    const compiler = compile(routeToUse, options)\n\n    // If we normalized the route, wrap the compiler to strip separators from output\n    // The normalization inserts _NEXTSEP_ as a literal string in the pattern to satisfy\n    // path-to-regexp validation, but we don't want it in the final compiled URL\n    if (needsNormalization) {\n      return (params: any) => {\n        return stripNormalizedSeparators(compiler(params))\n      }\n    }\n\n    return compiler\n  } catch (error) {\n    // Only try normalization if we haven't already normalized\n    if (!needsNormalization) {\n      try {\n        const normalizedRoute = normalizeAdjacentParameters(route)\n        const compiler = compile(normalizedRoute, options)\n\n        // Wrap the compiler to strip separators from output\n        return (params: any) => {\n          return stripNormalizedSeparators(compiler(params))\n        }\n      } catch (retryError) {\n        // If that doesn't work, fall back to original error\n        throw error\n      }\n    }\n    throw error\n  }\n}\n\n/**\n * Client-safe wrapper around regexpToFunction that automatically cleans parameters.\n */\nexport function safeRegexpToFunction<\n  T extends Record<string, any> = Record<string, any>,\n>(regexp: RegExp, keys?: Key[]): (pathname: string) => { params: T } | false {\n  const originalMatcher = regexpToFunction<T>(regexp, keys || [])\n\n  return (pathname: string) => {\n    const result = originalMatcher(pathname)\n    if (!result) return false\n\n    // Clean parameters before returning\n    return {\n      ...result,\n      params: stripParameterSeparators(result.params as any) as T,\n    }\n  }\n}\n\n/**\n * Safe wrapper for route matcher functions that automatically cleans parameters.\n * This is client-safe and doesn't import path-to-regexp.\n */\nexport function safeRouteMatcher<T extends Record<string, any>>(\n  matcherFn: (pathname: string) => false | T\n): (pathname: string) => false | T {\n  return (pathname: string) => {\n    const result = matcherFn(pathname)\n    if (!result) return false\n\n    // Clean parameters before returning\n    return stripParameterSeparators(result) as T\n  }\n}\n","import type { Group } from './route-regex'\nimport { DecodeError } from '../../utils'\nimport type { Params } from '../../../../server/request/params'\nimport { safeRouteMatcher } from './route-match-utils'\n\nexport interface RouteMatchFn {\n  (pathname: string): false | Params\n}\n\ntype RouteMatcherOptions = {\n  // We only use the exec method of the RegExp object. This helps us avoid using\n  // type assertions that the passed in properties are of the correct type.\n  re: Pick<RegExp, 'exec'>\n  groups: Record<string, Group>\n}\n\nexport function getRouteMatcher({\n  re,\n  groups,\n}: RouteMatcherOptions): RouteMatchFn {\n  const rawMatcher = (pathname: string) => {\n    const routeMatch = re.exec(pathname)\n    if (!routeMatch) return false\n\n    const decode = (param: string) => {\n      try {\n        return decodeURIComponent(param)\n      } catch {\n        throw new DecodeError('failed to decode param')\n      }\n    }\n\n    const params: Params = {}\n    for (const [key, group] of Object.entries(groups)) {\n      const match = routeMatch[group.pos]\n      if (match !== undefined) {\n        if (group.repeat) {\n          params[key] = match.split('/').map((entry) => decode(entry))\n        } else {\n          params[key] = decode(match)\n        }\n      }\n    }\n\n    return params\n  }\n\n  // Wrap with safe matcher to handle parameter cleaning\n  return safeRouteMatcher(rawMatcher)\n}\n","import type { IncomingMessage, ServerResponse } from 'http'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { BaseNextRequest } from './base-http'\nimport type { CloneableBody } from './body-streams'\nimport type { RouteMatch } from './route-matches/route-match'\nimport type { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers'\nimport type {\n  ResponseCacheEntry,\n  ServerComponentsHmrCache,\n} from './response-cache'\nimport type { PagesDevOverlayBridgeType } from '../next-devtools/userspace/pages/pages-dev-overlay-setup'\nimport type { OpaqueFallbackRouteParams } from './request/fallback-params'\nimport type { IncrementalCache } from './lib/incremental-cache'\nimport type { RevalidateFn } from './lib/router-utils/router-server-context'\nimport type { NextRequest } from './web/exports'\n\n// FIXME: (wyattjoh) this is a temporary solution to allow us to pass data between bundled modules\nexport const NEXT_REQUEST_META = Symbol.for('NextInternalRequestMeta')\n\nexport type NextIncomingMessage = (\n  | BaseNextRequest\n  | IncomingMessage\n  | NextRequest\n) & {\n  [NEXT_REQUEST_META]?: RequestMeta\n}\n\n/**\n * The callback function to call when a response cache entry was generated or\n * looked up in the cache. When it returns true, the server assumes that the\n * handler has already responded to the request and will not do so itself.\n */\nexport type OnCacheEntryHandler = (\n  /**\n   * The response cache entry that was generated or looked up in the cache.\n   */\n  cacheEntry: ResponseCacheEntry,\n\n  /**\n   * The request metadata.\n   */\n  requestMeta: {\n    /**\n     * The URL that was used to make the request.\n     */\n    url: string | undefined\n  }\n) => Promise<boolean | void> | boolean | void\n\nexport interface RequestMeta {\n  /**\n   * The query that was used to make the request.\n   */\n  initQuery?: ParsedUrlQuery\n\n  /**\n   * The URL that was used to make the request.\n   */\n  initURL?: string\n\n  /**\n   * The protocol that was used to make the request.\n   */\n  initProtocol?: string\n\n  /**\n   * The body that was read from the request. This is used to allow the body to\n   * be read multiple times.\n   */\n  clonableBody?: CloneableBody\n\n  /**\n   * True when the request matched a locale domain that was configured in the\n   * next.config.js file.\n   */\n  isLocaleDomain?: boolean\n\n  /**\n   * True when the request had locale information stripped from the pathname\n   * part of the URL.\n   */\n  didStripLocale?: boolean\n\n  /**\n   * If the request had its URL rewritten, this is the pathname it was rewritten\n   * to (not a full URL, just the pathname).\n   */\n  rewrittenPathname?: string\n\n  /**\n   * The resolved pathname for the request. Dynamic route params are\n   * interpolated, the pathname is decoded, and the trailing slash is removed.\n   */\n  resolvedPathname?: string\n\n  /**\n   * The cookies that were added by middleware and were added to the response.\n   */\n  middlewareCookie?: string[]\n\n  /**\n   * The match on the request for a given route.\n   */\n  match?: RouteMatch\n\n  /**\n   * The incremental cache to use for the request.\n   */\n  incrementalCache?: IncrementalCache\n\n  /**\n   * The server components HMR cache, only for dev.\n   */\n  serverComponentsHmrCache?: ServerComponentsHmrCache\n\n  /**\n   * Equals the segment path that was used for the prefetch RSC request.\n   */\n  segmentPrefetchRSCRequest?: string\n\n  /**\n   * True when the request is for the prefetch flight data.\n   */\n  isPrefetchRSCRequest?: true\n\n  /**\n   * True when the request is for the flight data.\n   */\n  isRSCRequest?: true\n\n  /**\n   * A search param set by the Next.js client when performing RSC requests.\n   * Because some CDNs do not vary their cache entries on our custom headers,\n   * this search param represents a hash of the header values. For any cached\n   * RSC request, we should verify that the hash matches before responding.\n   * Otherwise this can lead to cache poisoning.\n   * TODO: Consider not using custom request headers at all, and instead encode\n   * everything into the search param.\n   */\n  cacheBustingSearchParam?: string\n\n  /**\n   * True when the request is for the `/_next/data` route using the pages\n   * router.\n   */\n  isNextDataReq?: true\n\n  /**\n   * Postponed state to use for resumption. If present it's assumed that the\n   * request is for a page that has postponed (there are no guarantees that the\n   * page actually has postponed though as it would incur an additional cache\n   * lookup).\n   */\n  postponed?: string\n\n  /**\n   * The action body extracted from a server action request when the postponed\n   * state was prepended to the body by the proxy. This allows the action\n   * handler to read the action payload without re-reading the consumed stream.\n   */\n  actionBody?: Buffer\n\n  /**\n   * If provided, this will be called when a response cache entry was generated\n   * or looked up in the cache.\n   *\n   * @deprecated Use `onCacheEntryV2` instead.\n   */\n  onCacheEntry?: OnCacheEntryHandler\n\n  /**\n   * If provided, this will be called when a response cache entry was generated\n   * or looked up in the cache.\n   */\n  onCacheEntryV2?: OnCacheEntryHandler\n\n  /**\n   * The previous revalidate before rendering 404 page for notFound: true\n   */\n  notFoundRevalidate?: number | false\n\n  /**\n   * In development, the original source page that returned a 404.\n   */\n  developmentNotFoundSourcePage?: string\n\n  /**\n   * The path we routed to and should be invoked\n   */\n  invokePath?: string\n\n  /**\n   * The specific page output we should be matching\n   */\n  invokeOutput?: string\n\n  /**\n   * The status we are invoking the request with from routing\n   */\n  invokeStatus?: number\n\n  /**\n   * The routing error we are invoking with\n   */\n  invokeError?: Error\n\n  /**\n   * The query parsed for the invocation\n   */\n  invokeQuery?: Record<string, undefined | string | string[]>\n\n  /**\n   * Whether the request is a middleware invocation\n   */\n  middlewareInvoke?: boolean\n\n  /**\n   * Whether the request should render the fallback shell or not.\n   */\n  renderFallbackShell?: boolean\n\n  /**\n   * Whether the request is for the custom error page.\n   */\n  customErrorRender?: true\n\n  /**\n   * Whether to bubble up the NoFallbackError to the caller when a 404 is\n   * returned.\n   */\n  bubbleNoFallback?: true\n\n  /**\n   * True when the request had locale information inferred from the default\n   * locale.\n   */\n  localeInferredFromDefault?: true\n\n  /**\n   * The locale that was inferred or explicitly set for the request.\n   */\n  locale?: string\n\n  /**\n   * The default locale that was inferred or explicitly set for the request.\n   */\n  defaultLocale?: string\n\n  /**\n   * The relative project dir the server is running in from project root\n   */\n  relativeProjectDir?: string\n\n  /**\n   * The dist directory the server is currently using\n   */\n  distDir?: string\n\n  /**\n    Optional hostname used by route handlers when constructing absolute URLs.\n    hostname: '127.0.0.1',\n   */\n  hostname?: string\n\n  /**\n   Optional internal revalidate function to avoid revalidating over the network\n   */\n  revalidate?: RevalidateFn\n\n  /**\n   Optional function to render the 404 page for pages router `notFound: true`\n   */\n  render404?: (\n    req: IncomingMessage,\n    res: ServerResponse,\n    parsedUrl?: UrlWithParsedQuery,\n    setHeaders?: boolean\n  ) => Promise<void>\n\n  /**\n   * The query after resolving routes\n   */\n  query?: ParsedUrlQuery\n\n  /**\n   * The params after resolving routes\n   */\n  params?: ParsedUrlQuery\n\n  /**\n   * ErrorOverlay component to use in development for pages router\n   */\n  PagesErrorDebug?: PagesDevOverlayBridgeType\n\n  /**\n   * Whether server is in minimal mode (this will be replaced with more\n   * specific flags in future)\n   */\n  minimalMode?: boolean\n\n  /**\n   * The fallback params for this route. In dev, used for validating prerenders.\n   * In production, used to defer params resolution during staged rendering.\n   */\n  fallbackParams?: OpaqueFallbackRouteParams\n\n  /**\n   * DEV only: Request timings in process.hrtime.bigint()\n   */\n  devRequestTimingStart?: bigint\n  devRequestTimingMiddlewareStart?: bigint\n  devRequestTimingMiddlewareEnd?: bigint\n  devRequestTimingInternalsEnd?: bigint\n\n  /**\n   * DEV only: The duration of getStaticPaths/generateStaticParams in process.hrtime.bigint()\n   */\n  devGenerateStaticParamsDuration?: bigint\n\n  /**\n   * DEV only: Server action log info to be logged after the request log\n   */\n  devServerActionLog?: {\n    functionName: string\n    args: unknown[]\n    location: string\n    duration: number\n  }\n}\n\n/**\n * Gets the request metadata. If no key is provided, the entire metadata object\n * is returned.\n *\n * @param req the request to get the metadata from\n * @param key the key to get from the metadata (optional)\n * @returns the value for the key or the entire metadata object\n */\nexport function getRequestMeta(\n  req: NextIncomingMessage,\n  key?: undefined\n): RequestMeta\nexport function getRequestMeta<K extends keyof RequestMeta>(\n  req: NextIncomingMessage,\n  key: K\n): RequestMeta[K]\nexport function getRequestMeta<K extends keyof RequestMeta>(\n  req: NextIncomingMessage,\n  key?: K\n): RequestMeta | RequestMeta[K] {\n  const meta = req[NEXT_REQUEST_META] || {}\n  return typeof key === 'string' ? meta[key] : meta\n}\n\n/**\n * Sets the request metadata.\n *\n * @param req the request to set the metadata on\n * @param meta the metadata to set\n * @returns the mutated request metadata\n */\nexport function setRequestMeta(req: NextIncomingMessage, meta: RequestMeta) {\n  req[NEXT_REQUEST_META] = meta\n  return meta\n}\n\n/**\n * Adds a value to the request metadata.\n *\n * @param request the request to mutate\n * @param key the key to set\n * @param value the value to set\n * @returns the mutated request metadata\n */\nexport function addRequestMeta<K extends keyof RequestMeta>(\n  request: NextIncomingMessage,\n  key: K,\n  value: RequestMeta[K]\n) {\n  const meta = getRequestMeta(request)\n  meta[key] = value\n  return setRequestMeta(request, meta)\n}\n\n/**\n * Removes a key from the request metadata.\n *\n * @param request the request to mutate\n * @param key the key to remove\n * @returns the mutated request metadata\n */\nexport function removeRequestMeta<K extends keyof RequestMeta>(\n  request: NextIncomingMessage,\n  key: K\n) {\n  const meta = getRequestMeta(request)\n  delete meta[key]\n  return setRequestMeta(request, meta)\n}\n\ntype NextQueryMetadata = {\n  /**\n   * The `_rsc` query parameter used for cache busting to ensure that the RSC\n   * requests do not get cached by the browser explicitly.\n   */\n  [NEXT_RSC_UNION_QUERY]?: string\n}\n\nexport type NextParsedUrlQuery = ParsedUrlQuery & NextQueryMetadata\n\n/**\n * subset of `url.parse` return value\n */\ninterface LegacyUrl {\n  auth?: string | null\n  hash: string | null\n  hostname: string | null\n  href: string\n  pathname: string | null\n  protocol: string | null\n  search: string | null\n  slashes: boolean | null\n  port: string | null\n  query: string | null | ParsedUrlQuery\n}\ninterface LegacyUrlWithParsedQuery extends LegacyUrl {\n  query: ParsedUrlQuery\n}\n\n// TODO: Remove in favor of WHATWG URLs\nexport interface NextUrlWithParsedQuery extends LegacyUrlWithParsedQuery {\n  query: NextParsedUrlQuery\n}\n","export const UNDERSCORE_NOT_FOUND_ROUTE = '/_not-found'\nexport const UNDERSCORE_NOT_FOUND_ROUTE_ENTRY = `${UNDERSCORE_NOT_FOUND_ROUTE}/page`\nexport const UNDERSCORE_GLOBAL_ERROR_ROUTE = '/_global-error'\nexport const UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY = `${UNDERSCORE_GLOBAL_ERROR_ROUTE}/page`\n","import MODERN_BROWSERSLIST_TARGET from './modern-browserslist-target'\n\nexport { MODERN_BROWSERSLIST_TARGET }\n\nexport type ValueOf<T> = Required<T>[keyof T]\n\nexport const COMPILER_NAMES = {\n  client: 'client',\n  server: 'server',\n  edgeServer: 'edge-server',\n} as const\n\nexport type CompilerNameValues = ValueOf<typeof COMPILER_NAMES>\n\nexport const COMPILER_INDEXES: {\n  [compilerKey in CompilerNameValues]: number\n} = {\n  [COMPILER_NAMES.client]: 0,\n  [COMPILER_NAMES.server]: 1,\n  [COMPILER_NAMES.edgeServer]: 2,\n} as const\n\n// Re-export entry constants for backward compatibility\nexport {\n  UNDERSCORE_NOT_FOUND_ROUTE,\n  UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,\n  UNDERSCORE_GLOBAL_ERROR_ROUTE,\n  UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY,\n} from './entry-constants'\n\nexport enum AdapterOutputType {\n  /**\n   * `PAGES` represents all the React pages that are under `pages/`.\n   */\n  PAGES = 'PAGES',\n\n  /**\n   * `PAGES_API` represents all the API routes under `pages/api/`.\n   */\n  PAGES_API = 'PAGES_API',\n  /**\n   * `APP_PAGE` represents all the React pages that are under `app/` with the\n   * filename of `page.{j,t}s{,x}`.\n   */\n  APP_PAGE = 'APP_PAGE',\n\n  /**\n   * `APP_ROUTE` represents all the API routes and metadata routes that are under `app/` with the\n   * filename of `route.{j,t}s{,x}`.\n   */\n  APP_ROUTE = 'APP_ROUTE',\n\n  /**\n   * `PRERENDER` represents an ISR enabled route that might\n   * have a seeded cache entry or fallback generated during build\n   */\n  PRERENDER = 'PRERENDER',\n\n  /**\n   * `STATIC_FILE` represents a static file (ie /_next/static)\n   */\n  STATIC_FILE = 'STATIC_FILE',\n\n  /**\n   * `MIDDLEWARE` represents the middleware output if present\n   */\n  MIDDLEWARE = 'MIDDLEWARE',\n}\n\nexport const PHASE_EXPORT = 'phase-export'\nexport const PHASE_ANALYZE = 'phase-analyze'\nexport const PHASE_PRODUCTION_BUILD = 'phase-production-build'\nexport const PHASE_PRODUCTION_SERVER = 'phase-production-server'\nexport const PHASE_DEVELOPMENT_SERVER = 'phase-development-server'\nexport const PHASE_TEST = 'phase-test'\nexport const PHASE_INFO = 'phase-info'\n\nexport type PHASE_TYPE =\n  | typeof PHASE_INFO\n  | typeof PHASE_TEST\n  | typeof PHASE_EXPORT\n  | typeof PHASE_ANALYZE\n  | typeof PHASE_PRODUCTION_BUILD\n  | typeof PHASE_PRODUCTION_SERVER\n  | typeof PHASE_DEVELOPMENT_SERVER\n\nexport const PAGES_MANIFEST = 'pages-manifest.json'\nexport const APP_PATHS_MANIFEST = 'app-paths-manifest.json'\nexport const APP_PATH_ROUTES_MANIFEST = 'app-path-routes-manifest.json'\nexport const BUILD_MANIFEST = 'build-manifest.json'\nexport const FUNCTIONS_CONFIG_MANIFEST = 'functions-config-manifest.json'\nexport const SUBRESOURCE_INTEGRITY_MANIFEST = 'subresource-integrity-manifest'\nexport const NEXT_FONT_MANIFEST = 'next-font-manifest'\nexport const EXPORT_MARKER = 'export-marker.json'\nexport const EXPORT_DETAIL = 'export-detail.json'\nexport const PRERENDER_MANIFEST = 'prerender-manifest.json'\nexport const PREFETCH_HINTS = 'prefetch-hints.json'\nexport const ROUTES_MANIFEST = 'routes-manifest.json'\nexport const IMAGES_MANIFEST = 'images-manifest.json'\nexport const SERVER_FILES_MANIFEST = 'required-server-files'\nexport const DEV_CLIENT_PAGES_MANIFEST = '_devPagesManifest.json'\nexport const MIDDLEWARE_MANIFEST = 'middleware-manifest.json'\nexport const TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST =\n  '_clientMiddlewareManifest.js'\nexport const TURBOPACK_CLIENT_BUILD_MANIFEST = 'client-build-manifest.json'\nexport const DEV_CLIENT_MIDDLEWARE_MANIFEST = '_devMiddlewareManifest.json'\nexport const REACT_LOADABLE_MANIFEST = 'react-loadable-manifest.json'\nexport const SERVER_DIRECTORY = 'server'\nexport const CONFIG_FILES = [\n  'next.config.js',\n  'next.config.mjs',\n  'next.config.ts',\n  // process.features can be undefined on Edge runtime\n  // TODO: Remove `as any` once we bump @types/node to v22.10.0+\n  ...((process?.features as any)?.typescript ? ['next.config.mts'] : []),\n]\nexport const BUILD_ID_FILE = 'BUILD_ID'\nexport const BLOCKED_PAGES = ['/_document', '/_app', '/_error']\nexport const CLIENT_PUBLIC_FILES_PATH = 'public'\nexport const CLIENT_STATIC_FILES_PATH = 'static'\nexport const STRING_LITERAL_DROP_BUNDLE = '__NEXT_DROP_CLIENT_FILE__'\nexport const NEXT_BUILTIN_DOCUMENT = '__NEXT_BUILTIN_DOCUMENT__'\nexport const BARREL_OPTIMIZATION_PREFIX = '__barrel_optimize__'\n\n// server/[entry]/page_client-reference-manifest.js\nexport const CLIENT_REFERENCE_MANIFEST = 'client-reference-manifest'\n// server/server-reference-manifest\nexport const SERVER_REFERENCE_MANIFEST = 'server-reference-manifest'\n// server/middleware-build-manifest.js\nexport const MIDDLEWARE_BUILD_MANIFEST = 'middleware-build-manifest'\n// server/middleware-react-loadable-manifest.js\nexport const MIDDLEWARE_REACT_LOADABLE_MANIFEST =\n  'middleware-react-loadable-manifest'\n// server/interception-route-rewrite-manifest.js\nexport const INTERCEPTION_ROUTE_REWRITE_MANIFEST =\n  'interception-route-rewrite-manifest'\n// server/dynamic-css-manifest.js\nexport const DYNAMIC_CSS_MANIFEST = 'dynamic-css-manifest'\n\n// static/runtime/main.js\nexport const CLIENT_STATIC_FILES_RUNTIME_MAIN = `main`\nexport const CLIENT_STATIC_FILES_RUNTIME_MAIN_APP = `${CLIENT_STATIC_FILES_RUNTIME_MAIN}-app`\n// next internal client components chunk for layouts\nexport const APP_CLIENT_INTERNALS = 'app-pages-internals'\n// static/runtime/react-refresh.js\nexport const CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH = `react-refresh`\n// static/runtime/webpack.js\nexport const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = `webpack`\n// static/runtime/polyfills.js\nexport const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS = 'polyfills'\nexport const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL = Symbol(\n  CLIENT_STATIC_FILES_RUNTIME_POLYFILLS\n)\nexport const DEFAULT_RUNTIME_WEBPACK = 'webpack-runtime'\nexport const EDGE_RUNTIME_WEBPACK = 'edge-runtime-webpack'\nexport const STATIC_PROPS_ID = '__N_SSG'\nexport const SERVER_PROPS_ID = '__N_SSP'\nexport const DEFAULT_SERIF_FONT = {\n  name: 'Times New Roman',\n  xAvgCharWidth: 821,\n  azAvgWidth: 854.3953488372093,\n  unitsPerEm: 2048,\n}\nexport const DEFAULT_SANS_SERIF_FONT = {\n  name: 'Arial',\n  xAvgCharWidth: 904,\n  azAvgWidth: 934.5116279069767,\n  unitsPerEm: 2048,\n}\nexport const STATIC_STATUS_PAGES = ['/500']\nexport const TRACE_OUTPUT_VERSION = 1\n// in `MB`\nexport const TURBO_TRACE_DEFAULT_MEMORY_LIMIT = 6000\n\nexport const RSC_MODULE_TYPES = {\n  client: 'client',\n  server: 'server',\n} as const\n\n// comparing\n// https://nextjs.org/docs/api-reference/edge-runtime\n// with\n// https://nodejs.org/docs/latest/api/globals.html\nexport const EDGE_UNSUPPORTED_NODE_APIS = [\n  'clearImmediate',\n  'setImmediate',\n  'BroadcastChannel',\n  'ByteLengthQueuingStrategy',\n  'CompressionStream',\n  'CountQueuingStrategy',\n  'DecompressionStream',\n  'DomException',\n  'MessageChannel',\n  'MessageEvent',\n  'MessagePort',\n  'ReadableByteStreamController',\n  'ReadableStreamBYOBRequest',\n  'ReadableStreamDefaultController',\n  'TransformStreamDefaultController',\n  'WritableStreamDefaultController',\n]\n\nexport const SYSTEM_ENTRYPOINTS = new Set<string>([\n  CLIENT_STATIC_FILES_RUNTIME_MAIN,\n  CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,\n  CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,\n])\n","import fs from 'fs'\nimport path from 'path'\n\nexport function findDir(dir: string, name: 'pages' | 'app'): string | null {\n  // prioritize ./${name} over ./src/${name}\n  let curDir = path.join(dir, name)\n  if (fs.existsSync(curDir)) return curDir\n\n  curDir = path.join(dir, 'src', name)\n  if (fs.existsSync(curDir)) return curDir\n\n  return null\n}\n\nexport function findPagesDir(dir: string): {\n  pagesDir: string | undefined\n  appDir: string | undefined\n} {\n  const pagesDir = findDir(dir, 'pages') || undefined\n  const appDir = findDir(dir, 'app') || undefined\n\n  if (appDir == null && pagesDir == null) {\n    throw new Error(\n      \"> Couldn't find any `pages` or `app` directory. Please create one under the project root\"\n    )\n  }\n\n  if (pagesDir && appDir) {\n    const pagesParent = path.dirname(pagesDir)\n    const appParent = path.dirname(appDir)\n    if (pagesParent !== appParent) {\n      throw new Error(\n        '> `pages` and `app` directories should be under the same folder'\n      )\n    }\n  }\n\n  return {\n    pagesDir,\n    appDir,\n  }\n}\n","export class ReflectAdapter {\n  static get<T extends object>(\n    target: T,\n    prop: string | symbol,\n    receiver: unknown\n  ): any {\n    const value = Reflect.get(target, prop, receiver)\n    if (typeof value === 'function') {\n      return value.bind(target)\n    }\n\n    return value\n  }\n\n  static set<T extends object>(\n    target: T,\n    prop: string | symbol,\n    value: any,\n    receiver: any\n  ): boolean {\n    return Reflect.set(target, prop, value, receiver)\n  }\n\n  static has<T extends object>(target: T, prop: string | symbol): boolean {\n    return Reflect.has(target, prop)\n  }\n\n  static deleteProperty<T extends object>(\n    target: T,\n    prop: string | symbol\n  ): boolean {\n    return Reflect.deleteProperty(target, prop)\n  }\n}\n","import type { IncomingHttpHeaders } from 'http'\n\nimport { ReflectAdapter } from './reflect'\n\n/**\n * @internal\n */\nexport class ReadonlyHeadersError extends Error {\n  constructor() {\n    super(\n      'Headers cannot be modified. Read more: https://nextjs.org/docs/app/api-reference/functions/headers'\n    )\n  }\n\n  public static callable() {\n    throw new ReadonlyHeadersError()\n  }\n}\n\nexport type ReadonlyHeaders = Headers & {\n  /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */\n  append(...args: any[]): void\n  /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */\n  set(...args: any[]): void\n  /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */\n  delete(...args: any[]): void\n}\nexport class HeadersAdapter extends Headers {\n  private readonly headers: IncomingHttpHeaders\n\n  constructor(headers: IncomingHttpHeaders) {\n    // We've already overridden the methods that would be called, so we're just\n    // calling the super constructor to ensure that the instanceof check works.\n    super()\n\n    this.headers = new Proxy(headers, {\n      get(target, prop, receiver) {\n        // Because this is just an object, we expect that all \"get\" operations\n        // are for properties. If it's a \"get\" for a symbol, we'll just return\n        // the symbol.\n        if (typeof prop === 'symbol') {\n          return ReflectAdapter.get(target, prop, receiver)\n        }\n\n        const lowercased = prop.toLowerCase()\n\n        // Let's find the original casing of the key. This assumes that there is\n        // no mixed case keys (e.g. \"Content-Type\" and \"content-type\") in the\n        // headers object.\n        const original = Object.keys(headers).find(\n          (o) => o.toLowerCase() === lowercased\n        )\n\n        // If the original casing doesn't exist, return undefined.\n        if (typeof original === 'undefined') return\n\n        // If the original casing exists, return the value.\n        return ReflectAdapter.get(target, original, receiver)\n      },\n      set(target, prop, value, receiver) {\n        if (typeof prop === 'symbol') {\n          return ReflectAdapter.set(target, prop, value, receiver)\n        }\n\n        const lowercased = prop.toLowerCase()\n\n        // Let's find the original casing of the key. This assumes that there is\n        // no mixed case keys (e.g. \"Content-Type\" and \"content-type\") in the\n        // headers object.\n        const original = Object.keys(headers).find(\n          (o) => o.toLowerCase() === lowercased\n        )\n\n        // If the original casing doesn't exist, use the prop as the key.\n        return ReflectAdapter.set(target, original ?? prop, value, receiver)\n      },\n      has(target, prop) {\n        if (typeof prop === 'symbol') return ReflectAdapter.has(target, prop)\n\n        const lowercased = prop.toLowerCase()\n\n        // Let's find the original casing of the key. This assumes that there is\n        // no mixed case keys (e.g. \"Content-Type\" and \"content-type\") in the\n        // headers object.\n        const original = Object.keys(headers).find(\n          (o) => o.toLowerCase() === lowercased\n        )\n\n        // If the original casing doesn't exist, return false.\n        if (typeof original === 'undefined') return false\n\n        // If the original casing exists, return true.\n        return ReflectAdapter.has(target, original)\n      },\n      deleteProperty(target, prop) {\n        if (typeof prop === 'symbol')\n          return ReflectAdapter.deleteProperty(target, prop)\n\n        const lowercased = prop.toLowerCase()\n\n        // Let's find the original casing of the key. This assumes that there is\n        // no mixed case keys (e.g. \"Content-Type\" and \"content-type\") in the\n        // headers object.\n        const original = Object.keys(headers).find(\n          (o) => o.toLowerCase() === lowercased\n        )\n\n        // If the original casing doesn't exist, return true.\n        if (typeof original === 'undefined') return true\n\n        // If the original casing exists, delete the property.\n        return ReflectAdapter.deleteProperty(target, original)\n      },\n    })\n  }\n\n  /**\n   * Seals a Headers instance to prevent modification by throwing an error when\n   * any mutating method is called.\n   */\n  public static seal(headers: Headers): ReadonlyHeaders {\n    return new Proxy<ReadonlyHeaders>(headers, {\n      get(target, prop, receiver) {\n        switch (prop) {\n          case 'append':\n          case 'delete':\n          case 'set':\n            return ReadonlyHeadersError.callable\n          default:\n            return ReflectAdapter.get(target, prop, receiver)\n        }\n      },\n    })\n  }\n\n  /**\n   * Merges a header value into a string. This stores multiple values as an\n   * array, so we need to merge them into a string.\n   *\n   * @param value a header value\n   * @returns a merged header value (a string)\n   */\n  private merge(value: string | string[]): string {\n    if (Array.isArray(value)) return value.join(', ')\n\n    return value\n  }\n\n  /**\n   * Creates a Headers instance from a plain object or a Headers instance.\n   *\n   * @param headers a plain object or a Headers instance\n   * @returns a headers instance\n   */\n  public static from(headers: IncomingHttpHeaders | Headers): Headers {\n    if (headers instanceof Headers) return headers\n\n    return new HeadersAdapter(headers)\n  }\n\n  public append(name: string, value: string): void {\n    const existing = this.headers[name]\n    if (typeof existing === 'string') {\n      this.headers[name] = [existing, value]\n    } else if (Array.isArray(existing)) {\n      existing.push(value)\n    } else {\n      this.headers[name] = value\n    }\n  }\n\n  public delete(name: string): void {\n    delete this.headers[name]\n  }\n\n  public get(name: string): string | null {\n    const value = this.headers[name]\n    if (typeof value !== 'undefined') return this.merge(value)\n\n    return null\n  }\n\n  public has(name: string): boolean {\n    return typeof this.headers[name] !== 'undefined'\n  }\n\n  public set(name: string, value: string): void {\n    this.headers[name] = value\n  }\n\n  public forEach(\n    callbackfn: (value: string, name: string, parent: Headers) => void,\n    thisArg?: any\n  ): void {\n    for (const [name, value] of this.entries()) {\n      callbackfn.call(thisArg, value, name, this)\n    }\n  }\n\n  public *entries(): HeadersIterator<[string, string]> {\n    for (const key of Object.keys(this.headers)) {\n      const name = key.toLowerCase()\n      // We assert here that this is a string because we got it from the\n      // Object.keys() call above.\n      const value = this.get(name) as string\n\n      yield [name, value] as [string, string]\n    }\n  }\n\n  public *keys(): HeadersIterator<string> {\n    for (const key of Object.keys(this.headers)) {\n      const name = key.toLowerCase()\n      yield name\n    }\n  }\n\n  public *values(): HeadersIterator<string> {\n    for (const key of Object.keys(this.headers)) {\n      // We assert here that this is a string because we got it from the\n      // Object.keys() call above.\n      const value = this.get(key) as string\n\n      yield value\n    }\n  }\n\n  public [Symbol.iterator](): HeadersIterator<[string, string]> {\n    return this.entries()\n  }\n}\n","import type { ServerRuntime } from '../types'\n\nexport const TEXT_PLAIN_CONTENT_TYPE_HEADER = 'text/plain'\nexport const HTML_CONTENT_TYPE_HEADER = 'text/html; charset=utf-8'\nexport const JSON_CONTENT_TYPE_HEADER = 'application/json; charset=utf-8'\nexport const NEXT_QUERY_PARAM_PREFIX = 'nxtP'\nexport const NEXT_INTERCEPTION_MARKER_PREFIX = 'nxtI'\n\nexport const MATCHED_PATH_HEADER = 'x-matched-path'\nexport const PRERENDER_REVALIDATE_HEADER = 'x-prerender-revalidate'\nexport const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER =\n  'x-prerender-revalidate-if-generated'\n\nexport const RSC_SEGMENTS_DIR_SUFFIX = '.segments'\nexport const RSC_SEGMENT_SUFFIX = '.segment.rsc'\nexport const RSC_SUFFIX = '.rsc'\nexport const ACTION_SUFFIX = '.action'\nexport const NEXT_DATA_SUFFIX = '.json'\nexport const NEXT_META_SUFFIX = '.meta'\nexport const NEXT_BODY_SUFFIX = '.body'\n\nexport const NEXT_NAV_DEPLOYMENT_ID_HEADER = 'x-nextjs-deployment-id'\n\nexport const NEXT_CACHE_TAGS_HEADER = 'x-next-cache-tags'\nexport const NEXT_CACHE_REVALIDATED_TAGS_HEADER = 'x-next-revalidated-tags'\nexport const NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER =\n  'x-next-revalidate-tag-token'\n\nexport const NEXT_RESUME_HEADER = 'next-resume'\nexport const NEXT_RESUME_STATE_LENGTH_HEADER = 'x-next-resume-state-length'\n\n// if these change make sure we update the related\n// documentation as well\nexport const NEXT_CACHE_TAG_MAX_ITEMS = 128\nexport const NEXT_CACHE_TAG_MAX_LENGTH = 256\nexport const NEXT_CACHE_SOFT_TAG_MAX_LENGTH = 1024\nexport const NEXT_CACHE_IMPLICIT_TAG_ID = '_N_T_'\nexport const NEXT_CACHE_ROOT_PARAM_TAG_ID = '_N_RP_'\n\n// in seconds\nexport const CACHE_ONE_YEAR_SECONDS = 31536000\n\n// in seconds, represents revalidate=false. I.e. never revaliate.\n// We use this value since it can be represented as a V8 SMI for optimal performance.\n// It can also be serialized as JSON if it ever leaks accidentally as an actual value.\nexport const INFINITE_CACHE = 0xfffffffe\n\n// Patterns to detect middleware files\nexport const MIDDLEWARE_FILENAME = 'middleware'\nexport const MIDDLEWARE_LOCATION_REGEXP = `(?:src/)?${MIDDLEWARE_FILENAME}`\n\n// Patterns to detect proxy files (replacement for middleware)\nexport const PROXY_FILENAME = 'proxy'\nexport const PROXY_LOCATION_REGEXP = `(?:src/)?${PROXY_FILENAME}`\n\n// Pattern to detect instrumentation hooks file\nexport const INSTRUMENTATION_HOOK_FILENAME = 'instrumentation'\n\n// Because on Windows absolute paths in the generated code can break because of numbers, eg 1 in the path,\n// we have to use a private alias\nexport const PAGES_DIR_ALIAS = 'private-next-pages'\nexport const DOT_NEXT_ALIAS = 'private-dot-next'\nexport const ROOT_DIR_ALIAS = 'private-next-root-dir'\nexport const APP_DIR_ALIAS = 'private-next-app-dir'\nexport const RSC_MOD_REF_PROXY_ALIAS = 'private-next-rsc-mod-ref-proxy'\nexport const RSC_ACTION_VALIDATE_ALIAS = 'private-next-rsc-action-validate'\nexport const RSC_ACTION_PROXY_ALIAS = 'private-next-rsc-server-reference'\nexport const RSC_CACHE_WRAPPER_ALIAS = 'private-next-rsc-cache-wrapper'\nexport const RSC_DYNAMIC_IMPORT_WRAPPER_ALIAS =\n  'private-next-rsc-track-dynamic-import'\nexport const RSC_ACTION_ENCRYPTION_ALIAS = 'private-next-rsc-action-encryption'\nexport const RSC_ACTION_CLIENT_WRAPPER_ALIAS =\n  'private-next-rsc-action-client-wrapper'\n\nexport const PUBLIC_DIR_MIDDLEWARE_CONFLICT = `You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict`\n\nexport const SSG_GET_INITIAL_PROPS_CONFLICT = `You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps`\n\nexport const SERVER_PROPS_GET_INIT_PROPS_CONFLICT = `You can not use getInitialProps with getServerSideProps. Please remove getInitialProps.`\n\nexport const SERVER_PROPS_SSG_CONFLICT = `You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps`\n\nexport const STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR = `can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props`\n\nexport const SERVER_PROPS_EXPORT_ERROR = `pages with \\`getServerSideProps\\` can not be exported. See more info here: https://nextjs.org/docs/messages/gssp-export`\n\nexport const GSP_NO_RETURNED_VALUE =\n  'Your `getStaticProps` function did not return an object. Did you forget to add a `return`?'\nexport const GSSP_NO_RETURNED_VALUE =\n  'Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?'\n\nexport const UNSTABLE_REVALIDATE_RENAME_ERROR =\n  'The `unstable_revalidate` property is available for general use.\\n' +\n  'Please use `revalidate` instead.'\n\nexport const GSSP_COMPONENT_MEMBER_ERROR = `can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member`\n\nexport const NON_STANDARD_NODE_ENV = `You are using a non-standard \"NODE_ENV\" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env`\n\nexport const SSG_FALLBACK_EXPORT_ERROR = `Pages with \\`fallback\\` enabled in \\`getStaticPaths\\` can not be exported. See more info here: https://nextjs.org/docs/messages/ssg-fallback-true-export`\n\nexport const ESLINT_DEFAULT_DIRS = ['app', 'pages', 'components', 'lib', 'src']\n\nexport const SERVER_RUNTIME: Record<string, ServerRuntime> = {\n  edge: 'edge',\n  experimentalEdge: 'experimental-edge',\n  nodejs: 'nodejs',\n}\n\nexport const WEB_SOCKET_MAX_RECONNECTIONS = 12\n\n/**\n * The names of the webpack layers. These layers are the primitives for the\n * webpack chunks.\n */\nconst WEBPACK_LAYERS_NAMES = {\n  /**\n   * The layer for the shared code between the client and server bundles.\n   */\n  shared: 'shared',\n  /**\n   * The layer for server-only runtime and picking up `react-server` export conditions.\n   * Including app router RSC pages and app router custom routes and metadata routes.\n   */\n  reactServerComponents: 'rsc',\n  /**\n   * Server Side Rendering layer for app (ssr).\n   */\n  serverSideRendering: 'ssr',\n  /**\n   * The browser client bundle layer for actions.\n   */\n  actionBrowser: 'action-browser',\n  /**\n   * The Node.js bundle layer for the API routes.\n   */\n  apiNode: 'api-node',\n  /**\n   * The Edge Lite bundle layer for the API routes.\n   */\n  apiEdge: 'api-edge',\n  /**\n   * The layer for the middleware code.\n   */\n  middleware: 'middleware',\n  /**\n   * The layer for the instrumentation hooks.\n   */\n  instrument: 'instrument',\n  /**\n   * The layer for assets on the edge.\n   */\n  edgeAsset: 'edge-asset',\n  /**\n   * The browser client bundle layer for App directory.\n   */\n  appPagesBrowser: 'app-pages-browser',\n  /**\n   * The browser client bundle layer for Pages directory.\n   */\n  pagesDirBrowser: 'pages-dir-browser',\n  /**\n   * The Edge Lite bundle layer for Pages directory.\n   */\n  pagesDirEdge: 'pages-dir-edge',\n  /**\n   * The Node.js bundle layer for Pages directory.\n   */\n  pagesDirNode: 'pages-dir-node',\n} as const\n\nexport type WebpackLayerName =\n  (typeof WEBPACK_LAYERS_NAMES)[keyof typeof WEBPACK_LAYERS_NAMES]\n\nconst WEBPACK_LAYERS = {\n  ...WEBPACK_LAYERS_NAMES,\n  GROUP: {\n    builtinReact: [\n      WEBPACK_LAYERS_NAMES.reactServerComponents,\n      WEBPACK_LAYERS_NAMES.actionBrowser,\n    ],\n    serverOnly: [\n      WEBPACK_LAYERS_NAMES.reactServerComponents,\n      WEBPACK_LAYERS_NAMES.actionBrowser,\n      WEBPACK_LAYERS_NAMES.instrument,\n      WEBPACK_LAYERS_NAMES.middleware,\n    ],\n    neutralTarget: [\n      // pages api\n      WEBPACK_LAYERS_NAMES.apiNode,\n      WEBPACK_LAYERS_NAMES.apiEdge,\n    ],\n    clientOnly: [\n      WEBPACK_LAYERS_NAMES.serverSideRendering,\n      WEBPACK_LAYERS_NAMES.appPagesBrowser,\n    ],\n    bundled: [\n      WEBPACK_LAYERS_NAMES.reactServerComponents,\n      WEBPACK_LAYERS_NAMES.actionBrowser,\n      WEBPACK_LAYERS_NAMES.serverSideRendering,\n      WEBPACK_LAYERS_NAMES.appPagesBrowser,\n      WEBPACK_LAYERS_NAMES.shared,\n      WEBPACK_LAYERS_NAMES.instrument,\n      WEBPACK_LAYERS_NAMES.middleware,\n    ],\n    appPages: [\n      // app router pages and layouts\n      WEBPACK_LAYERS_NAMES.reactServerComponents,\n      WEBPACK_LAYERS_NAMES.serverSideRendering,\n      WEBPACK_LAYERS_NAMES.appPagesBrowser,\n      WEBPACK_LAYERS_NAMES.actionBrowser,\n    ],\n  },\n}\n\nconst WEBPACK_RESOURCE_QUERIES = {\n  edgeSSREntry: '__next_edge_ssr_entry__',\n  metadata: '__next_metadata__',\n  metadataRoute: '__next_metadata_route__',\n  metadataImageMeta: '__next_metadata_image_meta__',\n}\n\nexport { WEBPACK_LAYERS, WEBPACK_RESOURCE_QUERIES }\n","import type { IncomingMessage } from 'http'\nimport type { BaseNextRequest } from '../base-http'\nimport type { CookieSerializeOptions } from 'next/dist/compiled/cookie'\nimport type { NextApiResponse } from '../../shared/lib/utils'\n\nimport { HeadersAdapter } from '../web/spec-extension/adapters/headers'\nimport {\n  PRERENDER_REVALIDATE_HEADER,\n  PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER,\n} from '../../lib/constants'\nimport { getTracer } from '../lib/trace/tracer'\nimport { NodeSpan } from '../lib/trace/constants'\n\nexport type NextApiRequestCookies = Partial<{ [key: string]: string }>\nexport type NextApiRequestQuery = Partial<{ [key: string]: string | string[] }>\n\nexport type __ApiPreviewProps = {\n  previewModeId: string\n  previewModeEncryptionKey: string\n  previewModeSigningKey: string\n}\n\nexport function wrapApiHandler<T extends (...args: any[]) => any>(\n  page: string,\n  handler: T\n): T {\n  return ((...args) => {\n    getTracer().setRootSpanAttribute('next.route', page)\n    // Call API route method\n    return getTracer().trace(\n      NodeSpan.runHandler,\n      {\n        spanName: `executing api route (pages) ${page}`,\n      },\n      () => handler(...args)\n    )\n  }) as T\n}\n\n/**\n *\n * @param res response object\n * @param statusCode `HTTP` status code of response\n */\nexport function sendStatusCode(\n  res: NextApiResponse,\n  statusCode: number\n): NextApiResponse<any> {\n  res.statusCode = statusCode\n  return res\n}\n\n/**\n *\n * @param res response object\n * @param [statusOrUrl] `HTTP` status code of redirect\n * @param url URL of redirect\n */\nexport function redirect(\n  res: NextApiResponse,\n  statusOrUrl: string | number,\n  url?: string\n): NextApiResponse<any> {\n  if (typeof statusOrUrl === 'string') {\n    url = statusOrUrl\n    statusOrUrl = 307\n  }\n  if (typeof statusOrUrl !== 'number' || typeof url !== 'string') {\n    throw new Error(\n      `Invalid redirect arguments. Please use a single argument URL, e.g. res.redirect('/destination') or use a status code and URL, e.g. res.redirect(307, '/destination').`\n    )\n  }\n  res.writeHead(statusOrUrl, { Location: url })\n  res.write(url)\n  res.end()\n  return res\n}\n\nexport function checkIsOnDemandRevalidate(\n  req: Request | IncomingMessage | BaseNextRequest,\n  previewProps: __ApiPreviewProps\n): {\n  isOnDemandRevalidate: boolean\n  revalidateOnlyGenerated: boolean\n} {\n  const headers = HeadersAdapter.from(req.headers)\n\n  const previewModeId = headers.get(PRERENDER_REVALIDATE_HEADER)\n  const isOnDemandRevalidate = previewModeId === previewProps.previewModeId\n\n  const revalidateOnlyGenerated = headers.has(\n    PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER\n  )\n\n  return { isOnDemandRevalidate, revalidateOnlyGenerated }\n}\n\nexport const COOKIE_NAME_PRERENDER_BYPASS = `__prerender_bypass`\nexport const COOKIE_NAME_PRERENDER_DATA = `__next_preview_data`\n\nexport const RESPONSE_LIMIT_DEFAULT = 4 * 1024 * 1024\n\nexport const SYMBOL_PREVIEW_DATA = Symbol(COOKIE_NAME_PRERENDER_DATA)\nexport const SYMBOL_CLEARED_COOKIES = Symbol(COOKIE_NAME_PRERENDER_BYPASS)\n\nexport function clearPreviewData<T>(\n  res: NextApiResponse<T>,\n  options: {\n    path?: string\n  } = {}\n): NextApiResponse<T> {\n  if (SYMBOL_CLEARED_COOKIES in res) {\n    return res\n  }\n\n  const { serialize } =\n    require('next/dist/compiled/cookie') as typeof import('next/dist/compiled/cookie')\n  const previous = res.getHeader('Set-Cookie')\n  res.setHeader(`Set-Cookie`, [\n    ...(typeof previous === 'string'\n      ? [previous]\n      : Array.isArray(previous)\n        ? previous\n        : []),\n    serialize(COOKIE_NAME_PRERENDER_BYPASS, '', {\n      // To delete a cookie, set `expires` to a date in the past:\n      // https://tools.ietf.org/html/rfc6265#section-4.1.1\n      // `Max-Age: 0` is not valid, thus ignored, and the cookie is persisted.\n      expires: new Date(0),\n      httpOnly: true,\n      sameSite: process.env.NODE_ENV !== 'development' ? 'none' : 'lax',\n      secure: process.env.NODE_ENV !== 'development',\n      path: '/',\n      ...(options.path !== undefined\n        ? ({ path: options.path } as CookieSerializeOptions)\n        : undefined),\n    }),\n    serialize(COOKIE_NAME_PRERENDER_DATA, '', {\n      // To delete a cookie, set `expires` to a date in the past:\n      // https://tools.ietf.org/html/rfc6265#section-4.1.1\n      // `Max-Age: 0` is not valid, thus ignored, and the cookie is persisted.\n      expires: new Date(0),\n      httpOnly: true,\n      sameSite: process.env.NODE_ENV !== 'development' ? 'none' : 'lax',\n      secure: process.env.NODE_ENV !== 'development',\n      path: '/',\n      ...(options.path !== undefined\n        ? ({ path: options.path } as CookieSerializeOptions)\n        : undefined),\n    }),\n  ])\n\n  Object.defineProperty(res, SYMBOL_CLEARED_COOKIES, {\n    value: true,\n    enumerable: false,\n  })\n  return res\n}\n\n/**\n * Custom error class\n */\nexport class ApiError extends Error {\n  readonly statusCode: number\n\n  constructor(statusCode: number, message: string) {\n    super(message)\n    this.statusCode = statusCode\n  }\n}\n\n/**\n * Sends error in `response`\n * @param res response object\n * @param statusCode of response\n * @param message of response\n */\nexport function sendError(\n  res: NextApiResponse,\n  statusCode: number,\n  message: string\n): void {\n  res.statusCode = statusCode\n  res.statusMessage = message\n  res.end(message)\n}\n\ninterface LazyProps {\n  req: IncomingMessage\n}\n\n/**\n * Execute getter function only if its needed\n * @param LazyProps `req` and `params` for lazyProp\n * @param prop name of property\n * @param getter function to get data\n */\nexport function setLazyProp<T>(\n  { req }: LazyProps,\n  prop: string,\n  getter: () => T\n): void {\n  const opts = { configurable: true, enumerable: true }\n  const optsReset = { ...opts, writable: true }\n\n  Object.defineProperty(req, prop, {\n    ...opts,\n    get: () => {\n      const value = getter()\n      // we set the property on the object to avoid recalculating it\n      Object.defineProperty(req, prop, { ...optsReset, value })\n      return value\n    },\n    set: (value) => {\n      Object.defineProperty(req, prop, { ...optsReset, value })\n    },\n  })\n}\n","import type { NextApiRequestCookies } from '.'\n\n/**\n * Parse cookies from the `headers` of request\n * @param req request object\n */\n\nexport function getCookieParser(headers: {\n  [key: string]: string | string[] | null | undefined\n}): () => NextApiRequestCookies {\n  return function parseCookie(): NextApiRequestCookies {\n    const { cookie } = headers\n\n    if (!cookie) {\n      return {}\n    }\n\n    const { parse: parseCookieFn } =\n      require('next/dist/compiled/cookie') as typeof import('next/dist/compiled/cookie')\n    return parseCookieFn(Array.isArray(cookie) ? cookie.join('; ') : cookie)\n  }\n}\n","import type { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http'\nimport type { I18NConfig } from '../config-shared'\n\nimport { RedirectStatusCode } from '../../client/components/redirect-status-code'\nimport type { NextApiRequestCookies } from '../api-utils'\nimport { getCookieParser } from '../api-utils/get-cookie-parser'\n\nexport interface BaseNextRequestConfig {\n  basePath: string | undefined\n  i18n?: I18NConfig\n  trailingSlash?: boolean | undefined\n}\n\nexport type FetchMetric = {\n  url: string\n  idx: number\n  end: number\n  start: number\n  method: string\n  status: number\n  cacheReason: string\n  cacheStatus: 'hit' | 'miss' | 'skip' | 'hmr'\n  cacheWarning?: string\n}\n\nexport type FetchMetrics = Array<FetchMetric>\n\nexport abstract class BaseNextRequest<Body = any> {\n  protected _cookies: NextApiRequestCookies | undefined\n  public abstract headers: IncomingHttpHeaders\n  public abstract fetchMetrics: FetchMetric[] | undefined\n\n  constructor(\n    public method: string,\n    public url: string,\n    public body: Body\n  ) {}\n\n  // Utils implemented using the abstract methods above\n\n  public get cookies() {\n    if (this._cookies) return this._cookies\n    return (this._cookies = getCookieParser(this.headers)())\n  }\n}\n\nexport abstract class BaseNextResponse<Destination = any> {\n  abstract statusCode: number | undefined\n  abstract statusMessage: string | undefined\n  abstract get sent(): boolean\n\n  constructor(public destination: Destination) {}\n\n  /**\n   * Sets a value for the header overwriting existing values\n   */\n  abstract setHeader(name: string, value: string | string[]): this\n\n  /**\n   * Removes a header\n   */\n  abstract removeHeader(name: string): this\n\n  /**\n   * Appends value for the given header name\n   */\n  abstract appendHeader(name: string, value: string): this\n\n  /**\n   * Get all values for a header as an array or undefined if no value is present\n   */\n  abstract getHeaderValues(name: string): string[] | undefined\n\n  abstract hasHeader(name: string): boolean\n\n  /**\n   * Get values for a header concatenated using `,` or undefined if no value is present\n   */\n  abstract getHeader(name: string): string | undefined\n\n  abstract getHeaders(): OutgoingHttpHeaders\n\n  abstract body(value: string): this\n\n  abstract send(): void\n\n  abstract onClose(callback: () => void): void\n\n  // Utils implemented using the abstract methods above\n\n  public redirect(destination: string, statusCode: number) {\n    this.setHeader('Location', destination)\n    this.statusCode = statusCode\n\n    // Since IE11 doesn't support the 308 header add backwards\n    // compatibility using refresh header\n    if (statusCode === RedirectStatusCode.PermanentRedirect) {\n      this.setHeader('Refresh', `0;url=${destination}`)\n    }\n\n    return this\n  }\n}\n","import type { ServerResponse, IncomingMessage } from 'http'\nimport type { Writable, Readable } from 'stream'\n\nimport { SYMBOL_CLEARED_COOKIES } from '../api-utils'\nimport type { NextApiRequestCookies } from '../api-utils'\n\nimport { NEXT_REQUEST_META } from '../request-meta'\nimport type { RequestMeta } from '../request-meta'\n\nimport { BaseNextRequest, BaseNextResponse, type FetchMetric } from './index'\nimport type { OutgoingHttpHeaders } from 'node:http'\n\ntype Req = IncomingMessage & {\n  [NEXT_REQUEST_META]?: RequestMeta\n  cookies?: NextApiRequestCookies\n  fetchMetrics?: FetchMetric[]\n}\n\nexport class NodeNextRequest extends BaseNextRequest<Readable> {\n  public headers = this._req.headers\n  public fetchMetrics: FetchMetric[] | undefined = this._req?.fetchMetrics;\n\n  [NEXT_REQUEST_META]: RequestMeta = this._req[NEXT_REQUEST_META] || {}\n\n  constructor(private _req: Req) {\n    super(_req.method!.toUpperCase(), _req.url!, _req)\n  }\n\n  get originalRequest() {\n    // Need to mimic these changes to the original req object for places where we use it:\n    // render.tsx, api/ssg requests\n    this._req[NEXT_REQUEST_META] = this[NEXT_REQUEST_META]\n    this._req.url = this.url\n    this._req.cookies = this.cookies\n    return this._req\n  }\n\n  set originalRequest(value: Req) {\n    this._req = value\n  }\n\n  private streaming = false\n\n  /**\n   * Returns the request body as a Web Readable Stream. The body here can only\n   * be read once as the body will start flowing as soon as the data handler\n   * is attached.\n   *\n   * @internal\n   */\n  public stream() {\n    if (this.streaming) {\n      throw new Error(\n        'Invariant: NodeNextRequest.stream() can only be called once'\n      )\n    }\n    this.streaming = true\n\n    return new ReadableStream({\n      start: (controller) => {\n        this._req.on('data', (chunk) => {\n          controller.enqueue(new Uint8Array(chunk))\n        })\n        this._req.on('end', () => {\n          controller.close()\n        })\n        this._req.on('error', (err) => {\n          controller.error(err)\n        })\n      },\n    })\n  }\n}\n\nexport class NodeNextResponse extends BaseNextResponse<Writable> {\n  private textBody: string | undefined = undefined\n\n  public [SYMBOL_CLEARED_COOKIES]?: boolean\n\n  get originalResponse() {\n    if (SYMBOL_CLEARED_COOKIES in this) {\n      this._res[SYMBOL_CLEARED_COOKIES] = this[SYMBOL_CLEARED_COOKIES]\n    }\n\n    return this._res\n  }\n\n  constructor(\n    private _res: ServerResponse & { [SYMBOL_CLEARED_COOKIES]?: boolean }\n  ) {\n    super(_res)\n  }\n\n  get sent() {\n    return this._res.finished || this._res.headersSent\n  }\n\n  get statusCode() {\n    return this._res.statusCode\n  }\n\n  set statusCode(value: number) {\n    this._res.statusCode = value\n  }\n\n  get statusMessage() {\n    return this._res.statusMessage\n  }\n\n  set statusMessage(value: string) {\n    this._res.statusMessage = value\n  }\n\n  setHeader(name: string, value: string | string[]): this {\n    this._res.setHeader(name, value)\n    return this\n  }\n\n  removeHeader(name: string): this {\n    this._res.removeHeader(name)\n    return this\n  }\n\n  getHeaderValues(name: string): string[] | undefined {\n    const values = this._res.getHeader(name)\n\n    if (values === undefined) return undefined\n\n    return (Array.isArray(values) ? values : [values]).map((value) =>\n      value.toString()\n    )\n  }\n\n  hasHeader(name: string): boolean {\n    return this._res.hasHeader(name)\n  }\n\n  getHeader(name: string): string | undefined {\n    const values = this.getHeaderValues(name)\n    return Array.isArray(values) ? values.join(',') : undefined\n  }\n\n  getHeaders(): OutgoingHttpHeaders {\n    return this._res.getHeaders()\n  }\n\n  appendHeader(name: string, value: string): this {\n    const currentValues = this.getHeaderValues(name) ?? []\n\n    if (!currentValues.includes(value)) {\n      this._res.setHeader(name, [...currentValues, value])\n    }\n\n    return this\n  }\n\n  body(value: string) {\n    this.textBody = value\n    return this\n  }\n\n  send() {\n    this._res.end(this.textBody)\n  }\n\n  public onClose(callback: () => void) {\n    this.originalResponse.on('close', callback)\n  }\n}\n","import type { IncomingMessage, ServerResponse } from 'http'\nimport type RenderResult from './render-result'\nimport type { CacheControl } from './lib/cache-control'\n\nimport { isResSent } from '../shared/lib/utils'\nimport { generateETag } from './lib/etag'\nimport fresh from 'next/dist/compiled/fresh'\nimport { getCacheControlHeader } from './lib/cache-control'\nimport { HTML_CONTENT_TYPE_HEADER } from '../lib/constants'\n\nexport function sendEtagResponse(\n  req: IncomingMessage,\n  res: ServerResponse,\n  etag: string | undefined\n): boolean {\n  if (etag) {\n    /**\n     * The server generating a 304 response MUST generate any of the\n     * following header fields that would have been sent in a 200 (OK)\n     * response to the same request: Cache-Control, Content-Location, Date,\n     * ETag, Expires, and Vary. https://tools.ietf.org/html/rfc7232#section-4.1\n     */\n    res.setHeader('ETag', etag)\n  }\n\n  if (fresh(req.headers, { etag })) {\n    res.statusCode = 304\n    res.end()\n    return true\n  }\n\n  return false\n}\n\nexport async function sendRenderResult({\n  req,\n  res,\n  result,\n  generateEtags,\n  poweredByHeader,\n  cacheControl,\n}: {\n  req: IncomingMessage\n  res: ServerResponse\n  result: RenderResult\n  generateEtags: boolean\n  poweredByHeader: boolean\n  cacheControl: CacheControl | undefined\n}): Promise<void> {\n  if (isResSent(res)) {\n    return\n  }\n\n  if (poweredByHeader && result.contentType === HTML_CONTENT_TYPE_HEADER) {\n    res.setHeader('X-Powered-By', 'Next.js')\n  }\n\n  // If cache control is already set on the response we don't\n  // override it to allow users to customize it via next.config\n  if (cacheControl && !res.getHeader('Cache-Control')) {\n    res.setHeader('Cache-Control', getCacheControlHeader(cacheControl))\n  }\n\n  const payload = result.isDynamic ? null : result.toUnchunkedString()\n\n  if (generateEtags && payload !== null) {\n    const etag = generateETag(payload)\n    if (sendEtagResponse(req, res, etag)) {\n      return\n    }\n  }\n\n  if (!res.getHeader('Content-Type') && result.contentType) {\n    res.setHeader('Content-Type', result.contentType)\n  }\n\n  if (payload) {\n    res.setHeader('Content-Length', Buffer.byteLength(payload))\n  }\n\n  if (req.method === 'HEAD') {\n    res.end(null)\n    return\n  }\n\n  if (payload !== null) {\n    res.end(payload)\n    return\n  }\n\n  // Pipe the render result to the response after we get a writer for it.\n  await result.pipeToNodeResponse(res)\n}\n","import { CACHE_ONE_YEAR_SECONDS } from '../../lib/constants'\n\n/**\n * The revalidate option used internally for pages. A value of `false` means\n * that the page should not be revalidated. A number means that the page\n * should be revalidated after the given number of seconds (this also includes\n * `1` which means to revalidate after 1 second). A value of `0` is not a valid\n * value for this option.\n */\nexport type Revalidate = number | false\n\nexport interface CacheControl {\n  revalidate: Revalidate\n  expire: number | undefined\n}\n\nexport function getCacheControlHeader({\n  revalidate,\n  expire,\n}: CacheControl): string {\n  const swrHeader =\n    typeof revalidate === 'number' &&\n    expire !== undefined &&\n    revalidate < expire\n      ? `, stale-while-revalidate=${expire - revalidate}`\n      : ''\n\n  if (revalidate === 0) {\n    return 'private, no-cache, no-store, max-age=0, must-revalidate'\n  } else if (typeof revalidate === 'number') {\n    return `s-maxage=${revalidate}${swrHeader}`\n  }\n\n  return `s-maxage=${CACHE_ONE_YEAR_SECONDS}${swrHeader}`\n}\n","/**\n * FNV-1a Hash implementation\n * @author Travis Webb (tjwebb) <me@traviswebb.com>\n *\n * Ported from https://github.com/tjwebb/fnv-plus/blob/master/index.js\n *\n * Simplified, optimized and add modified for 52 bit, which provides a larger hash space\n * and still making use of Javascript's 53-bit integer space.\n */\nexport const fnv1a52 = (str: string) => {\n  const len = str.length\n  let i = 0,\n    t0 = 0,\n    v0 = 0x2325,\n    t1 = 0,\n    v1 = 0x8422,\n    t2 = 0,\n    v2 = 0x9ce4,\n    t3 = 0,\n    v3 = 0xcbf2\n\n  while (i < len) {\n    v0 ^= str.charCodeAt(i++)\n    t0 = v0 * 435\n    t1 = v1 * 435\n    t2 = v2 * 435\n    t3 = v3 * 435\n    t2 += v0 << 8\n    t3 += v1 << 8\n    t1 += t0 >>> 16\n    v0 = t0 & 65535\n    t2 += t1 >>> 16\n    v1 = t1 & 65535\n    v3 = (t3 + (t2 >>> 16)) & 65535\n    v2 = t2 & 65535\n  }\n\n  return (\n    (v3 & 15) * 281474976710656 +\n    v2 * 4294967296 +\n    v1 * 65536 +\n    (v0 ^ (v3 >> 4))\n  )\n}\n\nexport const generateETag = (payload: string, weak = false) => {\n  const prefix = weak ? 'W/\"' : '\"'\n  return (\n    prefix + fnv1a52(payload).toString(36) + payload.length.toString(36) + '\"'\n  )\n}\n","import type { ParsedUrlQuery } from 'querystring'\n\nexport function searchParamsToUrlQuery(\n  searchParams: URLSearchParams\n): ParsedUrlQuery {\n  const query: ParsedUrlQuery = {}\n  for (const [key, value] of searchParams.entries()) {\n    const existing = query[key]\n    if (typeof existing === 'undefined') {\n      query[key] = value\n    } else if (Array.isArray(existing)) {\n      existing.push(value)\n    } else {\n      query[key] = [existing, value]\n    }\n  }\n  return query\n}\n\nfunction stringifyUrlQueryParam(param: unknown): string {\n  if (typeof param === 'string') {\n    return param\n  }\n\n  if (\n    (typeof param === 'number' && !isNaN(param)) ||\n    typeof param === 'boolean'\n  ) {\n    return String(param)\n  } else {\n    return ''\n  }\n}\n\nexport function urlQueryToSearchParams(query: ParsedUrlQuery): URLSearchParams {\n  const searchParams = new URLSearchParams()\n  for (const [key, value] of Object.entries(query)) {\n    if (Array.isArray(value)) {\n      for (const item of value) {\n        searchParams.append(key, stringifyUrlQueryParam(item))\n      }\n    } else {\n      searchParams.set(key, stringifyUrlQueryParam(value))\n    }\n  }\n  return searchParams\n}\n\nexport function assign(\n  target: URLSearchParams,\n  ...searchParamsList: URLSearchParams[]\n): URLSearchParams {\n  for (const searchParams of searchParamsList) {\n    for (const key of searchParams.keys()) {\n      target.delete(key)\n    }\n\n    for (const [key, value] of searchParams.entries()) {\n      target.append(key, value)\n    }\n  }\n\n  return target\n}\n","import type { ParsedUrlQuery } from 'querystring'\n\nimport { searchParamsToUrlQuery } from './querystring'\nimport { parseRelativeUrl } from './parse-relative-url'\n\nexport interface ParsedUrl {\n  auth: string | null\n  hash: string\n  hostname: string | null\n  href: string\n  origin?: string | null\n  pathname: string\n  port: string | null\n  protocol: string | null\n  query: ParsedUrlQuery\n  search: string\n  slashes: boolean | null\n}\n\nexport function parseUrl(url: string): ParsedUrl {\n  if (url.startsWith('/')) {\n    return parseRelativeUrl(url)\n  }\n\n  const parsedURL = new URL(url)\n  const username = parsedURL.username\n  const password = parsedURL.password\n  const auth = username\n    ? password\n      ? `${username}:${password}`\n      : username\n    : null\n  const pathname = parsedURL.pathname\n  const search = parsedURL.search\n  return {\n    auth,\n    hash: parsedURL.hash,\n    hostname: parsedURL.hostname,\n    href: parsedURL.href,\n    pathname,\n    port: parsedURL.port,\n    protocol: parsedURL.protocol,\n    query: searchParamsToUrlQuery(parsedURL.searchParams),\n    search,\n    origin: parsedURL.origin,\n    slashes:\n      parsedURL.href.slice(\n        parsedURL.protocol.length,\n        parsedURL.protocol.length + 2\n      ) === '//',\n  }\n}\n","import type { ParsedUrlQuery } from 'querystring'\nimport { getLocationOrigin } from '../../utils'\nimport { searchParamsToUrlQuery } from './querystring'\n\nexport interface ParsedRelativeUrl {\n  auth: string | null\n  hash: string\n  host: string | null\n  hostname: string | null\n  href: string\n  pathname: string\n  port: string | null\n  protocol: string | null\n  query: ParsedUrlQuery\n  search: string\n  slashes: null\n}\n\n/**\n * Parses path-relative urls (e.g. `/hello/world?foo=bar`). If url isn't path-relative\n * (e.g. `./hello`) then at least base must be.\n * Absolute urls are rejected with one exception, in the browser, absolute urls that are on\n * the current origin will be parsed as relative\n */\nexport function parseRelativeUrl(\n  url: string,\n  base?: string,\n  parseQuery?: true\n): ParsedRelativeUrl\nexport function parseRelativeUrl(\n  url: string,\n  base: string | undefined,\n  parseQuery: false\n): Omit<ParsedRelativeUrl, 'query'>\nexport function parseRelativeUrl(\n  url: string,\n  base?: string,\n  parseQuery = true\n): ParsedRelativeUrl | Omit<ParsedRelativeUrl, 'query'> {\n  const globalBase = new URL(\n    typeof window === 'undefined' ? 'http://n' : getLocationOrigin()\n  )\n\n  const resolvedBase = base\n    ? new URL(base, globalBase)\n    : url.startsWith('.')\n      ? new URL(\n          typeof window === 'undefined' ? 'http://n' : window.location.href\n        )\n      : globalBase\n\n  const { pathname, searchParams, search, hash, href, origin } = url.startsWith(\n    '/'\n  )\n    ? // 'http://localhost:3000///' would be received as '///' in Node.js' IncomingMessage\n      // See https://nodejs.org/api/http.html#messageurl\n      // Not using `origin` to support other protocols\n      new URL(`${resolvedBase.protocol}//${resolvedBase.host}${url}`)\n    : new URL(url, resolvedBase)\n\n  if (origin !== globalBase.origin) {\n    throw new Error(`invariant: invalid relative URL, router received ${url}`)\n  }\n\n  return {\n    auth: null,\n    host: null,\n    hostname: null,\n    pathname,\n    port: null,\n    protocol: null,\n    query: parseQuery ? searchParamsToUrlQuery(searchParams) : undefined,\n    search,\n    hash,\n    href: href.slice(origin.length),\n    // We don't know for relative URLs at this point since we set a custom, internal\n    // base that isn't surfaced to users.\n    slashes: null,\n  }\n}\n","import { bold, green, magenta, red, yellow, white } from '../../lib/picocolors'\nimport { LRUCache } from '../../server/lib/lru-cache'\n\nexport const prefixes = {\n  wait: white(bold('○')),\n  error: red(bold('⨯')),\n  warn: yellow(bold('⚠')),\n  ready: '▲', // no color\n  info: white(bold(' ')),\n  event: green(bold('✓')),\n  trace: magenta(bold('»')),\n} as const\n\nconst LOGGING_METHOD = {\n  log: 'log',\n  warn: 'warn',\n  error: 'error',\n} as const\n\nfunction prefixedLog(prefixType: keyof typeof prefixes, ...message: any[]) {\n  if ((message[0] === '' || message[0] === undefined) && message.length === 1) {\n    message.shift()\n  }\n\n  const consoleMethod: keyof typeof LOGGING_METHOD =\n    prefixType in LOGGING_METHOD\n      ? LOGGING_METHOD[prefixType as keyof typeof LOGGING_METHOD]\n      : 'log'\n\n  const prefix = prefixes[prefixType]\n  // If there's no message, don't print the prefix but a new line\n  if (message.length === 0) {\n    console[consoleMethod]('')\n  } else {\n    // Ensure if there's ANSI escape codes it's concatenated into one string.\n    // Chrome DevTool can only handle color if it's in one string.\n    if (message.length === 1 && typeof message[0] === 'string') {\n      console[consoleMethod](prefix + ' ' + message[0])\n    } else {\n      console[consoleMethod](prefix, ...message)\n    }\n  }\n}\n\nexport function bootstrap(message: string) {\n  console.log(message)\n}\n\nexport function wait(...message: any[]) {\n  prefixedLog('wait', ...message)\n}\n\nexport function error(...message: any[]) {\n  prefixedLog('error', ...message)\n}\n\nexport function warn(...message: any[]) {\n  prefixedLog('warn', ...message)\n}\n\nexport function ready(...message: any[]) {\n  prefixedLog('ready', ...message)\n}\n\nexport function info(...message: any[]) {\n  prefixedLog('info', ...message)\n}\n\nexport function event(...message: any[]) {\n  prefixedLog('event', ...message)\n}\n\nexport function trace(...message: any[]) {\n  prefixedLog('trace', ...message)\n}\n\nconst warnOnceCache = new LRUCache<string>(10_000, (value) => value.length)\nexport function warnOnce(...message: any[]) {\n  const key = message.join(' ')\n  if (!warnOnceCache.has(key)) {\n    warnOnceCache.set(key, key)\n    warn(...message)\n  }\n}\n\nconst errorOnceCache = new LRUCache<string>(10_000, (value) => value.length)\nexport function errorOnce(...message: any[]) {\n  const key = message.join(' ')\n  if (!errorOnceCache.has(key)) {\n    errorOnceCache.set(key, key)\n    error(...message)\n  }\n}\n","import type { SizeLimit } from '../../types'\n\nexport const DEFAULT_MAX_POSTPONED_STATE_SIZE: SizeLimit = '100 MB'\n\n// 100MB in bytes. Not using the parseSizeLimit for performance as parseMaxPostponedStateSize is in the hot path for rendering.\nconst DEFAULT_MAX_POSTPONED_STATE_SIZE_BYTES = 104_857_600\n\nfunction parseSizeLimit(size: SizeLimit): number | undefined {\n  const bytes = (\n    require('next/dist/compiled/bytes') as typeof import('next/dist/compiled/bytes')\n  ).parse(size)\n  if (bytes === null || isNaN(bytes) || bytes < 1) {\n    return undefined\n  }\n  return bytes\n}\n\n/**\n * Parses the maxPostponedStateSize config value, using the default if not provided.\n */\nexport function parseMaxPostponedStateSize(\n  size: SizeLimit | undefined\n): number | undefined {\n  if (!size) {\n    return DEFAULT_MAX_POSTPONED_STATE_SIZE_BYTES\n  }\n  return parseSizeLimit(size)\n}\n","import os from 'os'\nimport type { webpack } from 'next/dist/compiled/webpack/webpack'\nimport type { Header, Redirect, Rewrite } from '../lib/load-custom-routes'\nimport { imageConfigDefault } from '../shared/lib/image-config'\nimport type {\n  ImageConfig,\n  ImageConfigComplete,\n} from '../shared/lib/image-config'\nimport type { SubresourceIntegrityAlgorithm } from '../build/webpack/plugins/subresource-integrity-plugin'\nimport type { WEB_VITALS } from '../shared/lib/utils'\nimport type { NextParsedUrlQuery } from './request-meta'\nimport type { SizeLimit } from '../types'\nimport type { SupportedTestRunners } from '../cli/next-test'\nimport type { ExperimentalPPRConfig } from './lib/experimental/ppr'\nimport { INFINITE_CACHE } from '../lib/constants'\nimport { isStableBuild } from '../shared/lib/errors/canary-only-config-error'\nimport type { FallbackRouteParam } from '../build/static-paths/types'\n\n/**\n * Resolved form of the prefetchInlining config after normalization in\n * config.ts. User input (true, partial objects) is converted to this shape.\n */\nexport type PrefetchInliningConfig =\n  | false\n  | { maxSize: number; maxBundleSize: number }\n\nexport type NextConfigComplete = Required<Omit<NextConfig, 'configFile'>> & {\n  images: Required<ImageConfigComplete>\n  typescript: TypeScriptConfig\n  configFile: string | undefined\n  configFileName: string\n  // override NextConfigComplete.experimental.htmlLimitedBots to string\n  // because it's not defined in NextConfigComplete.experimental\n  htmlLimitedBots: string | undefined\n  experimental: ExperimentalConfig & {\n    // Normalized by config.ts: true and partial objects become resolved objects\n    prefetchInlining?: PrefetchInliningConfig\n  }\n  // The root directory of the distDir. In development mode, this is the parent directory of `distDir`\n  // since development builds use `{distDir}/dev`. This is used to ensure that the bundler doesn't\n  // traverse into the output directory.\n  distDirRoot: string\n}\n\nexport type I18NDomains = readonly DomainLocale[]\n\nexport interface I18NConfig {\n  defaultLocale: string\n  domains?: I18NDomains\n  localeDetection?: false\n  locales: readonly string[]\n}\n\nexport interface DomainLocale {\n  defaultLocale: string\n  domain: string\n  http?: true\n  locales?: readonly string[]\n}\n\nexport interface TypeScriptConfig {\n  /** Do not run TypeScript during production builds (`next build`). */\n  ignoreBuildErrors?: boolean\n  /** Relative path to a custom tsconfig file */\n  tsconfigPath?: string\n}\n\nexport interface EmotionConfig {\n  sourceMap?: boolean\n  autoLabel?: 'dev-only' | 'always' | 'never'\n  labelFormat?: string\n  importMap?: {\n    [importName: string]: {\n      [exportName: string]: {\n        canonicalImport?: [string, string]\n        styledBaseImport?: [string, string]\n      }\n    }\n  }\n}\n\nexport interface StyledComponentsConfig {\n  /**\n   * Enabled by default in development, disabled in production to reduce file size,\n   * setting this will override the default for all environments.\n   */\n  displayName?: boolean\n  topLevelImportPaths?: string[]\n  ssr?: boolean\n  fileName?: boolean\n  meaninglessFileNames?: string[]\n  minify?: boolean\n  transpileTemplateLiterals?: boolean\n  namespace?: string\n  pure?: boolean\n  cssProp?: boolean\n}\n\nexport type JSONValue =\n  | string\n  | number\n  | boolean\n  | JSONValue[]\n  | { [k: string]: JSONValue }\n\n// At the moment, Turbopack options must be JSON-serializable, so restrict values.\nexport type TurbopackLoaderOptions = Record<string, JSONValue>\n\nexport type TurbopackLoaderItem =\n  | string\n  | {\n      loader: string\n      options?: TurbopackLoaderOptions\n    }\n\nexport type TurbopackLoaderBuiltinCondition =\n  | 'browser'\n  | 'foreign'\n  | 'development'\n  | 'production'\n  | 'node'\n  | 'edge-light'\n\nexport type TurbopackRuleCondition =\n  | { all: TurbopackRuleCondition[] }\n  | { any: TurbopackRuleCondition[] }\n  | { not: TurbopackRuleCondition }\n  | TurbopackLoaderBuiltinCondition\n  | {\n      path?: string | RegExp\n      content?: RegExp\n      query?: string | RegExp\n      contentType?: string | RegExp\n    }\n\n/**\n * The module type to use for matched files. This determines how files are\n * processed without requiring a custom loader.\n *\n * - `'asset'` - Emit the file and return its URL (like webpack's `asset/resource`)\n * - `'ecmascript'` - Process as JavaScript module\n * - `'typescript'` - Process as TypeScript module\n * - `'css'` - Process as CSS file\n * - `'css-module'` - Process as CSS module\n * - `'wasm'` - Process as WebAssembly module\n * - `'raw'` - Return raw file contents as a string\n * - `'node'` - Process as native Node.js addon\n * - `'bytes'` - Inline file contents as bytes in JavaScript\n *\n * @see [Module Types](https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#module-types)\n */\nexport type TurbopackModuleType =\n  | 'asset'\n  | 'ecmascript'\n  | 'typescript'\n  | 'css'\n  | 'css-module'\n  | 'wasm'\n  | 'raw'\n  | 'node'\n  | 'bytes'\n  | 'text'\n\nexport type TurbopackRuleConfigItem = {\n  /** Loaders to apply to matched files. */\n  loaders?: TurbopackLoaderItem[]\n  /** Rename the file extension for loader output (e.g., `'*.js'`). */\n  as?: string\n  /** Additional conditions for when this rule applies. */\n  condition?: TurbopackRuleCondition\n  /**\n   * Set the module type directly without using a loader.\n   * @see [Module Types](https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#module-types)\n   */\n  type?: TurbopackModuleType\n}\n\n/**\n * This can be an object representing a single configuration, or a list of\n * loaders and/or rule configuration objects.\n *\n * - A list of loader path strings or objects is the \"shorthand\" syntax.\n * - A list of rule configuration objects can be useful when each configuration\n *   object has different `condition` fields, but still match the same top-level\n *   path glob.\n */\nexport type TurbopackRuleConfigCollection =\n  | TurbopackRuleConfigItem\n  | (TurbopackLoaderItem | TurbopackRuleConfigItem)[]\n\nexport interface TurbopackOptions {\n  /**\n   * (`next --turbopack` only) A mapping of aliased imports to modules to load in their place.\n   *\n   * @see [Resolve Alias](https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#resolving-aliases)\n   */\n  resolveAlias?: Record<\n    string,\n    string | string[] | Record<string, string | string[]>\n  >\n\n  /**\n   * (`next --turbopack` only) A list of extensions to resolve when importing files.\n   *\n   * @see [Resolve Extensions](https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#resolving-custom-extensions)\n   */\n  resolveExtensions?: string[]\n\n  /**\n   * (`next --turbopack` only) A list of webpack loaders to apply when running with Turbopack.\n   *\n   * @see [Turbopack Loaders](https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#configuring-webpack-loaders)\n   */\n  rules?: Record<string, TurbopackRuleConfigCollection>\n\n  /**\n   * This is the repo root usually and only files above this\n   * directory can be resolved by turbopack.\n   */\n  root?: string\n\n  /**\n   * Enables generation of debug IDs in JavaScript bundles and source maps.\n   * These debug IDs help with debugging and error tracking by providing stable identifiers.\n   *\n   * @see https://github.com/tc39/ecma426/blob/main/proposals/debug-id.md TC39 Debug ID Proposal\n   */\n  debugIds?: boolean\n\n  /**\n   * An array of issue filter rules to ignore specific Turbopack issues.\n   * Each rule must have a `path` field (mandatory) and optionally `title`\n   * and `description`. String paths are treated as glob patterns. String\n   * titles/descriptions are exact matches. RegExp values match anywhere\n   * within the string (use `^` and `$` anchors for full-string matching).\n   */\n  ignoreIssue?: Array<{\n    path: string | RegExp\n    title?: string | RegExp\n    description?: string | RegExp\n  }>\n}\n\nexport interface WebpackConfigContext {\n  /** Next.js root directory */\n  dir: string\n  /** Indicates if the compilation will be done in development */\n  dev: boolean\n  /** It's `true` for server-side compilation, and `false` for client-side compilation */\n  isServer: boolean\n  /**  The build id, used as a unique identifier between builds */\n  buildId: string\n  /** The next.config.js merged with default values */\n  config: NextConfigComplete\n  /** Default loaders used internally by Next.js */\n  defaultLoaders: {\n    /** Default babel-loader configuration */\n    babel: any\n  }\n  /** Number of total Next.js pages */\n  totalPages: number\n  /** The webpack configuration */\n  webpack: any\n  /** The current server runtime */\n  nextRuntime?: 'nodejs' | 'edge'\n}\n\nexport interface NextJsWebpackConfig {\n  (\n    /** Existing Webpack config */\n    config: any,\n    context: WebpackConfigContext\n  ): any\n}\n\n/**\n * Set of options for React Compiler that Next.js currently supports.\n *\n * These options may be changed in breaking ways at any time without notice\n * while support for React Compiler is experimental.\n *\n * @see https://react.dev/reference/react-compiler/configuration\n */\nexport interface ReactCompilerOptions {\n  /**\n   * Controls the strategy for determining which functions the React Compiler\n   * will optimize.\n   *\n   * The default is `'infer'`, which uses intelligent heuristics to identify\n   * React components and hooks.\n   *\n   * When using `infer`, Next.js applies its own heuristics before calling\n   * `react-compiler`. This improves compilation performance by avoiding extra\n   * invocations of Babel and reducing redundant parsing of code.\n   *\n   * @see https://react.dev/reference/react-compiler/compilationMode\n   */\n  compilationMode?: 'infer' | 'annotation' | 'all'\n  /**\n   * Controls how the React Compiler handles errors during compilation.\n   *\n   * The default is `'none'`, which skips components which cannot be compiled.\n   *\n   * @see https://react.dev/reference/react-compiler/panicThreshold\n   */\n  panicThreshold?: 'none' | 'critical_errors' | 'all_errors'\n}\n\nexport interface IncomingRequestLoggingConfig {\n  /**\n   * A regular expression array to match incoming requests that should not be logged.\n   * You can specify multiple patterns to match incoming requests that should not be logged.\n   */\n  ignore?: RegExp[]\n}\n\nexport interface LoggingConfig {\n  fetches?: {\n    fullUrl?: boolean\n    /**\n     * If true, fetch requests that are restored from the HMR cache are logged\n     * during an HMR refresh request, i.e. when editing a server component.\n     */\n    hmrRefreshes?: boolean\n  }\n\n  /**\n   * If set to false, incoming request logging is disabled.\n   * You can specify a pattern to match incoming requests that should not be logged.\n   */\n  incomingRequests?: boolean | IncomingRequestLoggingConfig\n\n  /**\n   * If false, Server Function invocation logging is disabled.\n   * @default true\n   */\n  serverFunctions?: boolean\n\n  /**\n   * Forward browser console logs to terminal.\n   * - `false`: Disable browser log forwarding\n   * - `true`: Forward all browser console output to terminal\n   * - `'warn'`: Forward warnings and errors to terminal\n   * - `'error'`: Forward only errors to terminal\n   */\n  browserToTerminal?: boolean | 'error' | 'warn'\n}\n\n/**\n * All recognized lightningcss feature names.\n * Individual features map 1:1 to lightningcss `Features` bitflags.\n * Composite names (`selectors`, `media-queries`, `colors`) enable a group of\n * related individual features at once.\n *\n * The name→bitmask mapping is duplicated in:\n * - JS:   `packages/next/src/build/webpack/loaders/lightningcss-loader/src/features.ts`\n * - Rust: `crates/next-core/src/next_config.rs` (`lightningcss_feature_names_to_mask`)\n */\nexport const LIGHTNINGCSS_FEATURE_NAMES = [\n  // Individual features (bit 0–20)\n  'nesting',\n  'not-selector-list',\n  'dir-selector',\n  'lang-selector-list',\n  'is-selector',\n  'text-decoration-thickness-percent',\n  'media-interval-syntax',\n  'media-range-syntax',\n  'custom-media-queries',\n  'clamp-function',\n  'color-function',\n  'oklab-colors',\n  'lab-colors',\n  'p3-colors',\n  'hex-alpha-colors',\n  'space-separated-color-notation',\n  'font-family-system-ui',\n  'double-position-gradients',\n  'vendor-prefixes',\n  'logical-properties',\n  'light-dark',\n  // Composite groups\n  'selectors',\n  'media-queries',\n  'colors',\n] as const\n\nexport type LightningCssFeature = (typeof LIGHTNINGCSS_FEATURE_NAMES)[number]\n\nexport interface LightningCssFeatures {\n  include?: LightningCssFeature[]\n  exclude?: LightningCssFeature[]\n}\n\nexport interface ExperimentalConfig {\n  appNewScrollHandler?: boolean\n  useSkewCookie?: boolean\n  /** @deprecated use top-level `cacheHandlers` instead */\n  cacheHandlers?: NextConfig['cacheHandlers']\n  multiZoneDraftMode?: boolean\n  appNavFailHandling?: boolean\n  prerenderEarlyExit?: boolean\n  linkNoTouchStart?: boolean\n  caseSensitiveRoutes?: boolean\n  /**\n   * The origins that are allowed to write the rewritten headers when\n   * performing a non-relative rewrite. When undefined, no non-relative\n   * rewrites will get the rewrite headers.\n   */\n  clientParamParsingOrigins?: string[]\n  cachedNavigations?: boolean\n  /**\n   * Enables partial fallback shells for cache-components routes while the\n   * feature stabilizes.\n   */\n  partialFallbacks?: boolean\n  dynamicOnHover?: boolean\n  optimisticRouting?: boolean\n  varyParams?: boolean\n  prefetchInlining?:\n    | boolean\n    | {\n        maxSize?: number\n        maxBundleSize?: number\n      }\n  preloadEntriesOnStart?: boolean\n  clientRouterFilter?: boolean\n  clientRouterFilterRedirects?: boolean\n  /**\n   * This config can be used to override the cache behavior for the client router.\n   * These values indicate the time, in seconds, that the cache should be considered\n   * reusable. When the `prefetch` Link prop is left unspecified, this will use the `dynamic` value.\n   * When the `prefetch` Link prop is set to `true`, this will use the `static` value.\n   */\n  staleTimes?: {\n    dynamic?: number\n    /** Must be greater than or equal to 30 seconds, to ensure prefetching is not completely wasteful */\n    static?: number\n  }\n  /**\n   * @deprecated use top-level `cacheLife` instead\n   */\n  cacheLife?: NextConfig['cacheLife']\n  // decimal for percent for possible false positives\n  // e.g. 0.01 for 10% potential false matches lower\n  // percent increases size of the filter\n  clientRouterFilterAllowedRate?: number\n  /**\n   * @deprecated Use `externalProxyRewritesResolve` instead.\n   */\n  externalMiddlewareRewritesResolve?: boolean\n  externalProxyRewritesResolve?: boolean\n  /**\n   * Exposes the Instant Navigation Testing API in production builds. This\n   * API is always available in development mode.\n   *\n   * The testing API allows e2e tests to control navigation timing, enabling\n   * deterministic assertions on prefetched/cached UI before dynamic data\n   * streams in.\n   *\n   * WARNING: This flag is intended for profiling and testing purposes only.\n   * Do not enable in user-facing production deployments.\n   */\n  exposeTestingApiInProductionBuild?: boolean\n  /**\n   * Show the Instant Navigation Mode toggle in the dev tools indicator.\n   * When enabled, a menu item lets you lock navigations to only show\n   * the cached/prefetched state.\n   */\n  instantNavigationDevToolsToggle?: boolean\n  extensionAlias?: Record<string, any>\n  allowedRevalidateHeaderKeys?: string[]\n  fetchCacheKeyPrefix?: string\n  imgOptConcurrency?: number | null\n  imgOptTimeoutInSeconds?: number\n  imgOptMaxInputPixels?: number\n  imgOptSequentialRead?: boolean | null\n  imgOptSkipMetadata?: boolean | null\n  optimisticClientCache?: boolean\n  /**\n   * @deprecated use config.expireTime instead\n   */\n  expireTime?: number\n  /**\n   * @deprecated Use `proxyPrefetch` instead.\n   */\n  middlewarePrefetch?: 'strict' | 'flexible'\n  proxyPrefetch?: 'strict' | 'flexible'\n  manualClientBasePath?: boolean\n  /**\n   * CSS Chunking strategy. Defaults to `true` (\"loose\" mode), which guesses dependencies\n   * between CSS files to keep ordering of them.\n   * An alternative is 'strict', which will try to keep correct ordering as\n   * much as possible, even when this leads to many requests.\n   */\n  cssChunking?: boolean | 'strict'\n  disablePostcssPresetEnv?: boolean\n  cpus?: number\n  memoryBasedWorkersCount?: boolean\n  proxyTimeout?: number\n  isrFlushToDisk?: boolean\n  workerThreads?: boolean\n  // optimizeCss can be boolean or critters' option object\n  // Use Record<string, unknown> as critters doesn't export its Option type\n  // https://github.com/GoogleChromeLabs/critters/blob/a590c05f9197b656d2aeaae9369df2483c26b072/packages/critters/src/index.d.ts\n  optimizeCss?: boolean | Record<string, unknown>\n  nextScriptWorkers?: boolean\n  scrollRestoration?: boolean\n  externalDir?: boolean\n  disableOptimizedLoading?: boolean\n\n  /** @deprecated A no-op as of Next 16, size metrics were removed from the build output. */\n  gzipSize?: boolean\n  craCompat?: boolean\n  esmExternals?: boolean | 'loose'\n  fullySpecified?: boolean\n  urlImports?: NonNullable<webpack.Configuration['experiments']>['buildHttp']\n  swcTraceProfiling?: boolean\n  forceSwcTransforms?: boolean\n\n  swcPlugins?: Array<[string, Record<string, unknown>]>\n  largePageDataBytes?: number\n  /**\n   * If set to `false`, webpack won't fall back to polyfill Node.js modules in the browser\n   * Full list of old polyfills is accessible here:\n   * [webpack/webpack#ModuleNotoundError.js#L13-L42](https://github.com/webpack/webpack/blob/2a0536cf510768111a3a6dceeb14cb79b9f59273/lib/ModuleNotFoundError.js#L13-L42)\n   */\n  fallbackNodePolyfills?: false\n  sri?: {\n    algorithm?: SubresourceIntegrityAlgorithm\n  }\n\n  webVitalsAttribution?: Array<(typeof WEB_VITALS)[number]>\n\n  /**\n   * Automatically apply the \"modularizeImports\" optimization to imports of the specified packages.\n   */\n  optimizePackageImports?: string[]\n\n  /**\n   * Optimize React APIs for server builds.\n   */\n  optimizeServerReact?: boolean\n\n  /**\n   * Type-checks props and return values of pages.\n   * Requires literal values for segment config (e.g. `export const dynamic = 'force-static' as const`).\n   */\n  strictRouteTypes?: boolean\n\n  /**\n   * Displays an indicator when a React Transition has no other indicator rendered.\n   * This includes displaying an indicator on client-side navigations.\n   */\n  transitionIndicator?: boolean\n\n  /**\n   * Enables experimental gesture transition APIs for optimistic client\n   * navigations. Requires experimental React.\n   */\n  gestureTransition?: boolean\n\n  /**\n   * A target memory limit for turbo, in bytes.\n   */\n  turbopackMemoryLimit?: number\n\n  /**\n   * Selects the runtime backend used by Turbopack for Node.js evaluation.\n   */\n  turbopackPluginRuntimeStrategy?: 'workerThreads' | 'childProcesses'\n\n  /**\n   * Enable minification. Defaults to true in build mode and false in dev mode.\n   */\n  turbopackMinify?: boolean\n\n  /**\n   * Enable support for `with {type: \"bytes\"}` for ESM imports.\n   */\n  turbopackImportTypeBytes?: boolean\n\n  /**\n   * Enable support for `with {type: \"text\"}` for ESM imports.\n   */\n  turbopackImportTypeText?: boolean\n\n  /**\n   * Enable scope hoisting. Defaults to true in build mode. Always disabled in development mode.\n   */\n  turbopackScopeHoisting?: boolean\n\n  /**\n   * Enable nested async chunking for client side assets. Defaults to true in build mode and false in dev mode.\n   * This optimization computes all possible paths through dynamic imports in the applications to figure out the modules needed at dynamic imports for every path.\n   */\n  turbopackClientSideNestedAsyncChunking?: boolean\n\n  /**\n   * Enable nested async chunking for server side assets. Defaults to false in dev and build mode.\n   * This optimization computes all possible paths through dynamic imports in the applications to figure out the modules needed at dynamic imports for every path.\n   */\n  turbopackServerSideNestedAsyncChunking?: boolean\n\n  /**\n   * Enable filesystem cache for the turbopack dev server.\n   *\n   * Defaults to `true`.\n   */\n  turbopackFileSystemCacheForDev?: boolean\n\n  /**\n   * Enable filesystem cache for the turbopack build.\n   *\n   * Defaults to `false`.\n   */\n  turbopackFileSystemCacheForBuild?: boolean\n\n  /**\n   * Enable source maps. Defaults to true.\n   */\n  turbopackSourceMaps?: boolean\n\n  /**\n   * Enable extraction of source maps from input files. Defaults to true.\n   */\n  turbopackInputSourceMaps?: boolean\n\n  /**\n   * Enable tree shaking for the turbopack dev server and build.\n   */\n  turbopackTreeShaking?: boolean\n\n  /**\n   * Enable removing unused imports for turbopack dev server and build.\n   */\n  turbopackRemoveUnusedImports?: boolean\n\n  /**\n   * Enable removing unused exports for turbopack dev server and build.\n   */\n  turbopackRemoveUnusedExports?: boolean\n\n  /**\n   * Enable local analysis to infer side effect free modules. When enabled, Turbopack will\n   * analyze module code to determine if it has side effects. This can improve tree shaking\n   * and bundle size at the cost of some additional analysis.\n   *\n   * Defaults to `true`\n   */\n  turbopackInferModuleSideEffects?: boolean\n\n  /**\n   * Set this to `false` to disable the automatic configuration of the babel loader when a Babel\n   * configuration file is present. This option is enabled by default.\n   *\n   * If this is set to `false`, but `reactCompiler` is `true`, the built-in Babel will\n   * still be configured, but any Babel configuration files on disk will be ignored. If you wish to\n   * use React Compiler with a different manually-configured `babel-loader`, you should disable both\n   * this and `reactCompiler`.\n   */\n  turbopackUseBuiltinBabel?: boolean\n\n  /**\n   * Set this to `false` to disable the automatic configuration of the sass loader. The sass loader\n   * configuration is enabled by default.\n   */\n  turbopackUseBuiltinSass?: boolean\n\n  /**\n   * The module ID strategy to use for Turbopack.\n   * If not set, the default is `'named'` for development and `'deterministic'`\n   * for production.\n   */\n  turbopackModuleIds?: 'named' | 'deterministic'\n\n  /**\n   * For use with `@next/mdx`. Compile MDX files using the new Rust compiler.\n   * @see https://nextjs.org/docs/app/api-reference/next-config-js/mdxRs\n   */\n  mdxRs?:\n    | boolean\n    | {\n        development?: boolean\n        jsx?: boolean\n        jsxRuntime?: string\n        jsxImportSource?: string\n        providerImportSource?: string\n        mdxType?: 'gfm' | 'commonmark'\n      }\n\n  /**\n   * Enable type checking for Link and Router.push, etc.\n   * @deprecated Use `typedRoutes` instead — this feature is now stable.\n   * @see https://nextjs.org/docs/app/api-reference/config/typescript#statically-typed-links\n   */\n  typedRoutes?: boolean\n\n  /**\n   * Enable type-checking and autocompletion for environment variables.\n   *\n   * @default false\n   */\n  typedEnv?: boolean\n\n  /**\n   * Runs the compilations for server and edge in parallel instead of in serial.\n   * This will make builds faster if there is enough server and edge functions\n   * in the application at the cost of more memory.\n   *\n   * NOTE: This option is only valid when the build process can use workers. See\n   * the documentation for `webpackBuildWorker` for more details.\n   */\n  parallelServerCompiles?: boolean\n\n  /**\n   * Runs the logic to collect build traces for the server routes in parallel\n   * with other work during the compilation. This will increase the speed of\n   * the build at the cost of more memory. This option may incur some additional\n   * work compared to if the option was disabled since the work is started\n   * before data from the client compilation is available to potentially reduce\n   * the amount of code that needs to be traced. Despite that, this may still\n   * result in faster builds for some applications.\n   *\n   * Valid values are:\n   * - `true`: Collect the server build traces in parallel.\n   * - `false`: Do not collect the server build traces in parallel.\n   * - `undefined`: Collect server build traces in parallel only in the `experimental-compile` mode.\n   *\n   * NOTE: This option is only valid when the build process can use workers. See\n   * the documentation for `webpackBuildWorker` for more details.\n   */\n  parallelServerBuildTraces?: boolean\n\n  /**\n   * Run the Webpack build in a separate process to optimize memory usage during build.\n   * Valid values are:\n   * - `false`: Disable the Webpack build worker\n   * - `true`: Enable the Webpack build worker\n   * - `undefined`: Enable the Webpack build worker only if the webpack config is not customized\n   */\n  webpackBuildWorker?: boolean\n\n  /**\n   * Enables optimizations to reduce memory usage in Webpack. This reduces the max size of the heap\n   * but may increase compile times slightly.\n   * Valid values are:\n   * - `false`: Disable Webpack memory optimizations (default).\n   * - `true`: Enables Webpack memory optimizations.\n   */\n  webpackMemoryOptimizations?: boolean\n\n  /**\n   * The array of the meta tags to the client injected by tracing propagation data.\n   */\n  clientTraceMetadata?: string[]\n\n  /**\n   * @deprecated This configuration option has been merged into `cacheComponents`.\n   * The Partial Prerendering feature is still available via `cacheComponents`.\n   */\n  ppr?: ExperimentalPPRConfig\n\n  /**\n   * Enables experimental taint APIs in React.\n   * Using this feature will enable the `react@experimental` for the `app` directory.\n   */\n  taint?: boolean\n\n  /**\n   * Uninstalls all \"unhandledRejection\" and \"uncaughtException\" listeners from\n   * the global process so that we can override the behavior, which in some\n   * runtimes is to exit the process.\n   *\n   * This is experimental until we've considered the impact in various\n   * deployment environments.\n   */\n  removeUncaughtErrorAndRejectionListeners?: boolean\n\n  /**\n   * During an RSC request, validates that the request headers match the\n   * cache-busting search parameter sent by the client.\n   */\n  validateRSCRequestHeaders?: boolean\n\n  serverActions?: {\n    /**\n     * Allows adjusting body parser size limit for server actions.\n     */\n    bodySizeLimit?: SizeLimit\n\n    /**\n     * Allowed origins that can bypass Server Action's CSRF check. This is helpful\n     * when you have reverse proxy in front of your app.\n     * @example\n     * [\"my-app.com\", \"*.my-app.com\"]\n     */\n    allowedOrigins?: string[]\n  }\n\n  /**\n   * Allows adjusting the maximum size of the postponed state body for PPR\n   * resume requests. This includes the Resume Data Cache (RDC) which may grow\n   * large for some applications.\n   * @default '100 MB'\n   */\n  maxPostponedStateSize?: SizeLimit\n\n  /**\n   * enables the minification of server code.\n   */\n  serverMinification?: boolean\n\n  /**\n   * Enables source maps generation for the server production bundle.\n   */\n  serverSourceMaps?: boolean\n\n  /**\n   * @internal Used by the Next.js internals only.\n   */\n  trustHostHeader?: boolean\n  /**\n   * @internal Used by the Next.js internals only.\n   */\n  isExperimentalCompile?: boolean\n\n  useWasmBinary?: boolean\n\n  /**\n   * Use lightningcss instead of postcss-loader\n   */\n  useLightningcss?: boolean\n\n  /**\n   * Configure which CSS features lightningcss should always transpile\n   * (include) or never transpile (exclude), regardless of browser targets.\n   * Requires `useLightningcss: true`.\n   */\n  lightningCssFeatures?: LightningCssFeatures\n\n  /**\n   * Enables view transitions by using the {@link https://react.dev/reference/react/ViewTransition ViewTransition} Component.\n   */\n  viewTransition?: boolean\n\n  /**\n   * Enables `fetch` requests to be proxied to the experimental test proxy server\n   */\n  testProxy?: boolean\n\n  /**\n   * Set a default test runner to be used by `next experimental-test`.\n   */\n  defaultTestRunner?: SupportedTestRunners\n  /**\n   * Allow NODE_ENV=development even for `next build`.\n   */\n  allowDevelopmentBuild?: true\n  /**\n   * @deprecated use `config.bundlePagesRouterDependencies` instead\n   *\n   */\n  bundlePagesExternals?: boolean\n  /**\n   * @deprecated use `config.serverExternalPackages` instead\n   *\n   */\n  serverComponentsExternalPackages?: string[]\n\n  /**\n   * When enabled, in dev mode, Next.js will send React's debug info through the\n   * WebSocket connection, instead of including it in the main RSC payload.\n   */\n  reactDebugChannel?: boolean\n\n  /**\n   * @deprecated use top-level `cacheComponents` instead\n   */\n  cacheComponents?: boolean\n\n  /**\n   * The number of times to retry static generation (per page) before giving up.\n   */\n  staticGenerationRetryCount?: number\n\n  /**\n   * The amount of pages to export per worker during static generation.\n   */\n  staticGenerationMaxConcurrency?: number\n\n  /**\n   * The minimum number of pages to be chunked into each export worker.\n   */\n  staticGenerationMinPagesPerWorker?: number\n\n  /**\n   * Allows previously fetched data to be re-used when editing server components.\n   */\n  serverComponentsHmrCache?: boolean\n\n  /**\n   * Render <style> tags inline in the HTML for imported CSS assets.\n   * Supports app-router in production mode only.\n   */\n  inlineCss?: boolean\n\n  // TODO: Remove this config when the API is stable.\n  /**\n   * This config allows you to enable the experimental navigation API `forbidden` and `unauthorized`.\n   */\n  authInterrupts?: boolean\n\n  /**\n   * Enables the use of the `\"use cache\"` directive.\n   */\n  useCache?: boolean\n\n  /**\n   * Enables detection and reporting of slow modules during development builds.\n   * Enabling this may impact build performance to ensure accurate measurements.\n   */\n  slowModuleDetection?: {\n    /**\n     * The time threshold in milliseconds for identifying slow modules.\n     * Modules taking longer than this build time threshold will be reported.\n     */\n    buildTimeThresholdMs: number\n  }\n\n  /**\n   * Enables using the global-not-found.js file in the app directory\n   *\n   */\n  globalNotFound?: boolean\n\n  /**\n   * Enable debug information to be forwarded from browser to dev server stdout/stderr.\n   *\n   * - `'warn'` (default): Forward warnings and errors to terminal\n   * - `'error'`: Forward only errors to terminal\n   * - `'verbose'`: Forward all browser console output to terminal\n   * - `true`: Same as 'verbose' - forward all browser console output to terminal\n   * - `false`: Disable browser log forwarding to terminal\n   * - Object: Enable with custom configuration\n   *\n   * @deprecated Use `logging.browserToTerminal` instead.\n   */\n  browserDebugInfoInTerminal?:\n    | boolean\n    | 'error'\n    | 'warn'\n    | 'verbose'\n    | {\n        /**\n         * Minimum log level to show in terminal.\n         * @default 'verbose' (for object config, to preserve backward compatibility)\n         */\n        level?: 'error' | 'warn' | 'verbose'\n\n        /**\n         * Option to limit stringification at a specific nesting depth when logging circular objects.\n         * @default 5\n         */\n        depthLimit?: number\n\n        /**\n         * Maximum number of properties/elements to stringify when logging objects/arrays with circular references.\n         * @default 100\n         */\n        edgeLimit?: number\n        /**\n         * Whether to include source location information in debug output when available\n         */\n        showSourceLocation?: boolean\n      }\n\n  /**\n   * Enable accessing root params via the `next/root-params` module.\n   */\n  rootParams?: boolean\n\n  /**\n   * Body size limit for request bodies with middleware configured.\n   * Defaults to 10MB. Can be specified as a number (bytes) or string (e.g. '5mb').\n   *\n   * @deprecated Use `proxyClientMaxBodySize` instead.\n   */\n  middlewareClientMaxBodySize?: SizeLimit\n\n  /**\n   * Body size limit for request bodies with proxy configured.\n   * Defaults to 10MB. Can be specified as a number (bytes) or string (e.g. '5mb').\n   */\n  proxyClientMaxBodySize?: SizeLimit\n\n  /**\n   * Enable the Model Context Protocol (MCP) server for AI-assisted development.\n   * When enabled, Next.js will expose an MCP server at `/_next/mcp` that provides\n   * code intelligence and project context to AI assistants.\n   *\n   * @default true\n   */\n  mcpServer?: boolean\n\n  /**\n   * Acquires a lockfile at `<distDir>/lock` when starting `next dev` or `next\n   * build`. Failing to acquire the lock causes the process to exit with an\n   * error message.\n   *\n   * This is because if multiple processes write to the same `distDir` at the\n   * same time, it can mangle the state of the directory. Disabling this option\n   * is not recommended.\n   *\n   * @default true\n   */\n  lockDistDir?: boolean\n\n  /**\n   * Hide logs that occur after a render has already aborted.\n   * This can help reduce noise in the console when dealing with aborted renders.\n   *\n   * @default false\n   */\n  hideLogsAfterAbort?: boolean\n\n  /**\n   * Whether `process.env.NEXT_DEPLOYMENT_ID` is available at runtime in the server (and `next\n   * build` doesn't need to embed the deployment ID value into the build output).\n   *\n   * @default false\n   */\n  runtimeServerDeploymentId?: boolean\n\n  /**\n   * A different token to use for static assets (as opposed to config.deploymentId) which\n   * doesn't have to be unique per deployment.\n   */\n  immutableAssetToken?: string\n\n  /**\n   * An array of paths in app or pages directories that should wait to be processed\n   * until all other entries have been processed. This is useful for deferring\n   * compilation of certain routes during development and build.\n   */\n  deferredEntries?: string[]\n\n  /**\n   * An async function that is called and awaited before processing deferred entries.\n   * This callback runs after all non-deferred entries have been compiled.\n   */\n  onBeforeDeferredEntries?: () => Promise<void>\n\n  /**\n   * Whether to report inlined system environment variables as warnings or errors.\n   * Only supported for Turbopack.\n   */\n  reportSystemEnvInlining?: 'error' | 'warn'\n}\n\nexport type ExportPathMap = {\n  [path: string]: {\n    page: string\n    query?: NextParsedUrlQuery\n\n    /**\n     * When true, this indicates that this is a pages router page that should\n     * be rendered as a fallback.\n     *\n     * @internal\n     */\n    _pagesFallback?: boolean\n\n    /**\n     * The locale that this page should be rendered in.\n     *\n     * @internal\n     */\n    _locale?: string\n\n    /**\n     * The path that was used to generate the page.\n     *\n     * @internal\n     */\n    _ssgPath?: string\n\n    /**\n     * The parameters that are currently unknown.\n     *\n     * @internal\n     */\n    _fallbackRouteParams?: readonly FallbackRouteParam[]\n\n    /**\n     * @internal\n     */\n    _isAppDir?: boolean\n\n    /**\n     * @internal\n     */\n    _isDynamicError?: boolean\n\n    /**\n     * @internal\n     */\n    _isRoutePPREnabled?: boolean\n\n    /**\n     * When true, the page is prerendered as a fallback shell, while allowing\n     * any dynamic accesses to result in an empty shell. This is the case when\n     * the app has `experimental.ppr` and `cacheComponents` enabled, and\n     * there are also routes prerendered with a more complete set of params.\n     * Prerendering those routes would catch any invalid dynamic accesses.\n     *\n     * @internal\n     */\n    _allowEmptyStaticShell?: boolean\n\n    /**\n     * When true, run build-time instant validation for this export path.\n     * Only set on the first export entry per page, since validation uses\n     * unstable_instant.samples (not actual params from generateStaticParams),\n     * so the result is the same for all param combinations.\n     *\n     * @internal\n     */\n    _runInstantValidation?: boolean\n  }\n}\n\n/**\n * Next.js can be configured through a `next.config.js` file in the root of your project directory.\n *\n * This can change the behavior, enable experimental features, and configure other advanced options.\n *\n * Read more: [Next.js Docs: `next.config.js`](https://nextjs.org/docs/app/api-reference/config/next-config-js)\n */\nexport interface NextConfig {\n  allowedDevOrigins?: string[]\n\n  exportPathMap?: (\n    defaultMap: ExportPathMap,\n    ctx: {\n      dev: boolean\n      dir: string\n      outDir: string | null\n      distDir: string\n      buildId: string\n    }\n  ) => Promise<ExportPathMap> | ExportPathMap\n\n  /**\n   * Internationalization configuration\n   *\n   * @see [Internationalization docs](https://nextjs.org/docs/advanced-features/i18n-routing)\n   */\n  i18n?: I18NConfig | null\n\n  /**\n   * @see [Next.js TypeScript documentation](https://nextjs.org/docs/app/api-reference/config/typescript)\n   */\n  typescript?: TypeScriptConfig\n\n  /**\n   * Enable type checking for Link and Router.push, etc.\n   * This feature requires TypeScript in your project.\n   *\n   * @see [Typed Links documentation](https://nextjs.org/docs/app/api-reference/config/typescript#statically-typed-links)\n   */\n  typedRoutes?: boolean\n\n  /**\n   * Headers allow you to set custom HTTP headers for an incoming request path.\n   *\n   * @see [Headers configuration documentation](https://nextjs.org/docs/app/api-reference/config/next-config-js/headers)\n   */\n  headers?: () => Promise<Header[]> | Header[]\n\n  /**\n   * Rewrites allow you to map an incoming request path to a different destination path.\n   *\n   * @see [Rewrites configuration documentation](https://nextjs.org/docs/app/api-reference/config/next-config-js/rewrites)\n   */\n  rewrites?: () =>\n    | Promise<\n        | Rewrite[]\n        | {\n            beforeFiles?: Rewrite[]\n            afterFiles?: Rewrite[]\n            fallback?: Rewrite[]\n          }\n      >\n    | Rewrite[]\n    | {\n        beforeFiles?: Rewrite[]\n        afterFiles?: Rewrite[]\n        fallback?: Rewrite[]\n      }\n\n  /**\n   * Redirects allow you to redirect an incoming request path to a different destination path.\n   *\n   * @see [Redirects configuration documentation](https://nextjs.org/docs/app/api-reference/config/next-config-js/redirects)\n   */\n  redirects?: () => Promise<Redirect[]> | Redirect[]\n\n  /**\n   * @see [Moment.js locales excluded by default](https://nextjs.org/docs/upgrading#momentjs-locales-excluded-by-default)\n   */\n  excludeDefaultMomentLocales?: boolean\n\n  /**\n   * Before continuing to add custom webpack configuration to your application make sure Next.js doesn't already support your use-case\n   *\n   * @see [Custom Webpack Config documentation](https://nextjs.org/docs/app/api-reference/config/next-config-js/webpack)\n   */\n  webpack?: NextJsWebpackConfig | null\n\n  /**\n   * By default Next.js will redirect urls with trailing slashes to their counterpart without a trailing slash.\n   *\n   * @default false\n   * @see [Trailing Slash Configuration](https://nextjs.org/docs/app/api-reference/config/next-config-js/trailingSlash)\n   */\n  trailingSlash?: boolean\n\n  /**\n   * Next.js comes with built-in support for environment variables\n   *\n   * @see [Environment Variables documentation](https://nextjs.org/docs/app/api-reference/config/next-config-js/env)\n   */\n  env?: Record<string, string | undefined>\n\n  /**\n   * Destination directory (defaults to `.next`)\n   */\n  distDir?: string\n\n  /**\n   * The build output directory (defaults to `.next`) is now cleared by default except for the Next.js caches.\n   */\n  cleanDistDir?: boolean\n\n  /**\n   * To set up a CDN, you can set up an asset prefix and configure your CDN's origin to resolve to the domain that Next.js is hosted on.\n   *\n   * @see [CDN Support with Asset Prefix](https://nextjs.org/docs/app/api-reference/config/next-config-js/assetPrefix)\n   */\n  assetPrefix?: string\n\n  /**\n   * The default cache handler for the Pages and App Router uses the filesystem cache. This requires no configuration, however, you can customize the cache handler if you prefer.\n   *\n   * @see [Configuring Caching](https://nextjs.org/docs/app/building-your-application/deploying#configuring-caching) and the [API Reference](https://nextjs.org/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath).\n   */\n  cacheHandler?: string | undefined\n\n  /**\n   * Path to a custom adapter module for deployment platform integration.\n   * Can also be set via the `NEXT_ADAPTER_PATH` environment variable.\n   */\n  adapterPath?: string\n\n  cacheHandlers?: {\n    default?: string\n    remote?: string\n    static?: string\n    [handlerName: string]: string | undefined\n  }\n\n  /**\n   * Configure the in-memory cache size in bytes. Defaults to 50 MB.\n   * If `cacheMaxMemorySize: 0`, this disables in-memory caching entirely.\n   *\n   * @see [Configuring Caching](https://nextjs.org/docs/app/building-your-application/deploying#configuring-caching).\n   */\n  cacheMaxMemorySize?: number\n\n  /**\n   * By default, `Next` will serve each file in the `pages` folder under a pathname matching the filename.\n   * To disable this behavior and prevent routing based set this to `true`.\n   *\n   * @default true\n   * @see [Disabling file-system routing](https://nextjs.org/docs/advanced-features/custom-server#disabling-file-system-routing)\n   */\n  useFileSystemPublicRoutes?: boolean\n\n  /**\n   * @see [Configuring the build ID](https://nextjs.org/docs/app/api-reference/config/next-config-js/generateBuildId)\n   */\n  generateBuildId?: () => string | null | Promise<string | null>\n\n  /** @see [Disabling ETag Configuration](https://nextjs.org/docs/app/api-reference/config/next-config-js/generateEtags) */\n  generateEtags?: boolean\n\n  /** @see [Including non-page files in the pages directory](https://nextjs.org/docs/app/api-reference/config/next-config-js/pageExtensions) */\n  pageExtensions?: string[]\n\n  /** @see [Compression documentation](https://nextjs.org/docs/app/api-reference/config/next-config-js/compress) */\n  compress?: boolean\n\n  /** @see [Disabling x-powered-by](https://nextjs.org/docs/app/api-reference/config/next-config-js/poweredByHeader) */\n  poweredByHeader?: boolean\n\n  /** @see [Using the Image Component](https://nextjs.org/docs/app/api-reference/next-config-js/images) */\n  images?: ImageConfig\n\n  /** Configure indicators in development environment */\n  devIndicators?:\n    | false\n    | {\n        /**\n         * Position of the development tools indicator in the browser window.\n         * @default \"bottom-left\"\n         * */\n        position?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'\n      }\n\n  /**\n   * Next.js exposes some options that give you some control over how the server will dispose or keep in memory built pages in development.\n   *\n   * @see [Configuring `onDemandEntries`](https://nextjs.org/docs/app/api-reference/config/next-config-js/onDemandEntries)\n   */\n  onDemandEntries?: {\n    /** period (in ms) where the server will keep pages in the buffer */\n    maxInactiveAge?: number\n    /** number of pages that should be kept simultaneously without being disposed */\n    pagesBufferLength?: number\n  }\n\n  /**\n   * A unique identifier for a deployment that will be included in each request's query string or header.\n   */\n  deploymentId?: string\n\n  /**\n   * Deploy a Next.js application under a sub-path of a domain\n   *\n   * @see [Base path configuration](https://nextjs.org/docs/app/api-reference/config/next-config-js/basePath)\n   */\n  basePath?: string\n\n  /** @see [Customizing sass options](https://nextjs.org/docs/app/api-reference/next-config-js/sassOptions) */\n  sassOptions?: {\n    implementation?: string\n    [key: string]: any\n  }\n\n  /**\n   * Enable browser source map generation during the production build\n   *\n   * @see [Source Maps](https://nextjs.org/docs/advanced-features/source-maps)\n   */\n  productionBrowserSourceMaps?: boolean\n\n  /**\n   * Enable {@link https://nextjs.org/docs/app/api-reference/config/next-config-js/reactCompiler React Compiler in Next.js}.\n   * Configuration accepts partial config object of the Compiler.\n   * If provided, the Compiler will be enabled.\n   */\n  reactCompiler?: boolean | ReactCompilerOptions\n\n  /**\n   * Enable react profiling in production\n   *\n   */\n  reactProductionProfiling?: boolean\n\n  /**\n   * The Next.js runtime is Strict Mode-compliant.\n   *\n   * @see [React Strict Mode](https://nextjs.org/docs/app/api-reference/config/next-config-js/reactStrictMode)\n   */\n  reactStrictMode?: boolean | null\n\n  /**\n   * The maximum length of the headers that are emitted by React and added to\n   * the response.\n   *\n   * @see [React Max Headers Length](https://nextjs.org/docs/app/api-reference/config/next-config-js/reactMaxHeadersLength)\n   */\n  reactMaxHeadersLength?: number\n\n  /**\n   * Next.js enables HTTP Keep-Alive by default.\n   * You may want to disable HTTP Keep-Alive for certain `fetch()` calls or globally.\n   *\n   * @see [Disabling HTTP Keep-Alive](https://nextjs.org/docs/app/api-reference/next-config-js/httpAgentOptions)\n   */\n  httpAgentOptions?: { keepAlive?: boolean }\n\n  /**\n   * Timeout after waiting to generate static pages in seconds\n   *\n   * @default 60\n   */\n  staticPageGenerationTimeout?: number\n\n  /**\n   * Add `\"crossorigin\"` attribute to generated `<script>` elements generated by `<Head />` or `<NextScript />` components\n   *\n   *\n   * @see [`crossorigin` attribute documentation](https://developer.mozilla.org/docs/Web/HTML/Attributes/crossorigin)\n   */\n  crossOrigin?: 'anonymous' | 'use-credentials'\n\n  /**\n   * Optionally enable compiler transforms\n   *\n   * @see [Supported Compiler Options](https://nextjs.org/docs/advanced-features/compiler#supported-features)\n   */\n  compiler?: {\n    reactRemoveProperties?:\n      | boolean\n      | {\n          properties?: string[]\n        }\n    relay?: {\n      src: string\n      artifactDirectory?: string\n      language?: 'typescript' | 'javascript' | 'flow'\n      eagerEsModules?: boolean\n    }\n    removeConsole?:\n      | boolean\n      | {\n          exclude?: string[]\n        }\n    styledComponents?: boolean | StyledComponentsConfig\n    emotion?: boolean | EmotionConfig\n\n    styledJsx?:\n      | boolean\n      | {\n          useLightningcss?: boolean\n        }\n\n    /**\n     * Replaces variables in your code during compile time. Each key will be\n     * replaced with the respective values.\n     */\n    define?: Record<string, string>\n\n    /**\n     * Replaces server-only (Node.js and Edge) variables in your code during compile time.\n     * Each key will be replaced with the respective values.\n     */\n    defineServer?: Record<string, string>\n\n    /**\n     * A hook function that executes after production build compilation finishes,\n     * but before running post-compilation tasks such as type checking and\n     * static page generation.\n     */\n    runAfterProductionCompile?: (metadata: {\n      /**\n       * The root directory of the project\n       */\n      projectDir: string\n      /**\n       * The build output directory (defaults to `.next`)\n       */\n      distDir: string\n    }) => Promise<void>\n  }\n\n  /**\n   * The type of build output.\n   * - `undefined`: The default build output, `.next` directory, that works with production mode `next start` or a hosting provider like Vercel\n   * - `'standalone'`: A standalone build output, `.next/standalone` directory, that only includes necessary files/dependencies. Useful for self-hosting in a Docker container.\n   * - `'export'`: An exported build output, `out` directory, that only includes static HTML/CSS/JS. Useful for self-hosting without a Node.js server.\n   * @see [Output File Tracing](https://nextjs.org/docs/advanced-features/output-file-tracing)\n   * @see [Static HTML Export](https://nextjs.org/docs/advanced-features/static-html-export)\n   */\n  output?: 'standalone' | 'export'\n\n  /**\n   * Automatically transpile and bundle dependencies from local packages (like monorepos) or from external dependencies (`node_modules`). This replaces the\n   * `next-transpile-modules` package.\n   * @see [transpilePackages](https://nextjs.org/docs/advanced-features/compiler#module-transpilation)\n   */\n  transpilePackages?: string[]\n\n  /**\n   * Options for Turbopack. Temporarily also available as `experimental.turbo` for compatibility.\n   */\n  turbopack?: TurbopackOptions\n\n  /**\n   * @deprecated Use `skipProxyUrlNormalize` instead.\n   */\n  skipMiddlewareUrlNormalize?: boolean\n\n  skipProxyUrlNormalize?: boolean\n\n  skipTrailingSlashRedirect?: boolean\n\n  modularizeImports?: Record<\n    string,\n    {\n      transform: string | Record<string, string>\n      preventFullImport?: boolean\n      skipDefaultConversion?: boolean\n    }\n  >\n\n  /**\n   * Logging configuration. Set to `false` to disable logging.\n   */\n  logging?: LoggingConfig | false\n\n  /**\n   * Enables source maps while generating static pages.\n   * Helps with errors during the prerender phase in `next build`.\n   */\n  enablePrerenderSourceMaps?: boolean\n\n  /**\n   * When enabled, in development and build, Next.js will automatically cache\n   * page-level components and functions for faster builds and rendering. This\n   * includes Partial Prerendering support.\n   *\n   * @see [Cache Components documentation](https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents)\n   */\n  cacheComponents?: boolean\n\n  cacheLife?: {\n    [profile: string]: {\n      // How long the client can cache a value without checking with the server.\n      stale?: number\n      // How frequently you want the cache to refresh on the server.\n      // Stale values may be served while revalidating.\n      revalidate?: number\n      // In the worst case scenario, where you haven't had traffic in a while,\n      // how stale can a value be until you prefer deopting to dynamic.\n      // Must be longer than revalidate.\n      expire?: number\n    }\n  }\n\n  /**\n   * period (in seconds) where the server allow to serve stale cache\n   */\n  expireTime?: number\n\n  /**\n   * Enable experimental features. Note that all experimental features are subject to breaking changes in the future.\n   */\n  experimental?: ExperimentalConfig\n\n  /**\n   * Enables the bundling of node_modules packages (externals) for pages server-side bundles.\n   * @see https://nextjs.org/docs/pages/api-reference/next-config-js/bundlePagesRouterDependencies\n   */\n  bundlePagesRouterDependencies?: boolean\n\n  /**\n   * A list of packages that should be treated as external in the server build.\n   * @see https://nextjs.org/docs/app/api-reference/next-config-js/serverExternalPackages\n   */\n  serverExternalPackages?: string[]\n\n  /**\n   * This is the repo root usually and only files above this\n   * directory are traced and included.\n   */\n  outputFileTracingRoot?: string\n\n  /**\n   * This allows manually excluding traced files if too many\n   * are included incorrectly on a per-page basis.\n   */\n  outputFileTracingExcludes?: Record<string, string[]>\n\n  /**\n   * This allows manually including traced files if some\n   * were not detected on a per-page basis.\n   */\n  outputFileTracingIncludes?: Record<string, string[]>\n\n  watchOptions?: {\n    pollIntervalMs?: number\n  }\n\n  /**\n   * User Agent of bots that can handle streaming metadata.\n   * Besides the default behavior, Next.js act differently on serving metadata to bots based on their capability.\n   *\n   * @default\n   * /Mediapartners-Google|Slurp|DuckDuckBot|baiduspider|yandex|sogou|bitlybot|tumblr|vkShare|quora link preview|redditbot|ia_archiver|Bingbot|BingPreview|applebot|facebookexternalhit|facebookcatalog|Twitterbot|LinkedInBot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview/i\n   */\n  htmlLimitedBots?: RegExp\n\n  /**\n   * @internal\n   */\n  configFile?: string | undefined\n\n  /**\n   * @internal\n   */\n  configOrigin?: string | undefined\n\n  /**\n   * @internal\n   */\n  _originalRedirects?: any\n\n  /**\n   * @internal\n   */\n  _originalRewrites?: any\n}\n\nexport const defaultConfig = Object.freeze({\n  env: {},\n  webpack: null,\n  typescript: {\n    ignoreBuildErrors: false,\n    tsconfigPath: undefined,\n  },\n  typedRoutes: false,\n  distDir: '.next',\n  cleanDistDir: true,\n  assetPrefix: '',\n  cacheHandler: process.env.NEXT_CACHE_HANDLER_PATH,\n  // default to 50MB limit\n  cacheMaxMemorySize: 50 * 1024 * 1024,\n  configOrigin: 'default',\n  useFileSystemPublicRoutes: true,\n  generateBuildId: () => null,\n  generateEtags: true,\n  pageExtensions: ['tsx', 'ts', 'jsx', 'js'],\n  poweredByHeader: true,\n  compress: true,\n  images: imageConfigDefault,\n  devIndicators: {\n    position: 'bottom-left',\n  },\n  onDemandEntries: {\n    maxInactiveAge: 60 * 1000,\n    pagesBufferLength: 5,\n  },\n  basePath: '',\n  sassOptions: {},\n  trailingSlash: false,\n  i18n: null,\n  productionBrowserSourceMaps: false,\n  excludeDefaultMomentLocales: true,\n  reactProductionProfiling: false,\n  reactStrictMode: null,\n  reactMaxHeadersLength: 6000,\n  httpAgentOptions: {\n    keepAlive: true,\n  },\n  logging: {\n    serverFunctions: true,\n  } satisfies LoggingConfig,\n  compiler: {},\n  expireTime: process.env.NEXT_PRIVATE_CDN_CONSUMED_SWR_CACHE_CONTROL\n    ? undefined\n    : 31536000, // one year\n  staticPageGenerationTimeout: 60,\n  output: !!process.env.NEXT_PRIVATE_STANDALONE ? 'standalone' : undefined,\n  modularizeImports: undefined,\n  outputFileTracingRoot: process.env.NEXT_PRIVATE_OUTPUT_TRACE_ROOT || '',\n  allowedDevOrigins: undefined,\n  // Will default to cacheComponents value.\n  enablePrerenderSourceMaps: undefined,\n  cacheComponents: false,\n  cacheLife: {\n    default: {\n      stale: undefined, // defaults to staleTimes.static\n      revalidate: 60 * 15, // 15 minutes\n      expire: INFINITE_CACHE,\n    },\n    seconds: {\n      stale: 30, // 30 seconds\n      revalidate: 1, // 1 second\n      expire: 60, // 1 minute\n    },\n    minutes: {\n      stale: 60 * 5, // 5 minutes\n      revalidate: 60, // 1 minute\n      expire: 60 * 60, // 1 hour\n    },\n    hours: {\n      stale: 60 * 5, // 5 minutes\n      revalidate: 60 * 60, // 1 hour\n      expire: 60 * 60 * 24, // 1 day\n    },\n    days: {\n      stale: 60 * 5, // 5 minutes\n      revalidate: 60 * 60 * 24, // 1 day\n      expire: 60 * 60 * 24 * 7, // 1 week\n    },\n    weeks: {\n      stale: 60 * 5, // 5 minutes\n      revalidate: 60 * 60 * 24 * 7, // 1 week\n      expire: 60 * 60 * 24 * 30, // 1 month\n    },\n    max: {\n      stale: 60 * 5, // 5 minutes\n      revalidate: 60 * 60 * 24 * 30, // 1 month\n      expire: 60 * 60 * 24 * 365, // 1 year\n    },\n  },\n  cacheHandlers: {\n    default: process.env.NEXT_DEFAULT_CACHE_HANDLER_PATH,\n    remote: process.env.NEXT_REMOTE_CACHE_HANDLER_PATH,\n    static: process.env.NEXT_STATIC_CACHE_HANDLER_PATH,\n  },\n  adapterPath: process.env.NEXT_ADAPTER_PATH || undefined,\n  experimental: {\n    appNewScrollHandler: false,\n    useSkewCookie: false,\n    cssChunking: true,\n    multiZoneDraftMode: false,\n    appNavFailHandling: false,\n    prerenderEarlyExit: true,\n    serverMinification: true,\n    linkNoTouchStart: false,\n    caseSensitiveRoutes: false,\n    clientParamParsingOrigins: undefined,\n    cachedNavigations: false,\n    partialFallbacks: false,\n    dynamicOnHover: false,\n    varyParams: false,\n    prefetchInlining: false,\n    preloadEntriesOnStart: true,\n    clientRouterFilter: true,\n    clientRouterFilterRedirects: false,\n    fetchCacheKeyPrefix: '',\n    proxyPrefetch: 'flexible',\n    optimisticClientCache: true,\n    manualClientBasePath: false,\n    cpus: Math.max(\n      1,\n      (Number(process.env.CIRCLE_NODE_TOTAL) ||\n        (os.cpus() || { length: 1 }).length) - 1\n    ),\n    memoryBasedWorkersCount: false,\n    imgOptConcurrency: null,\n    imgOptTimeoutInSeconds: 7,\n    imgOptMaxInputPixels: 268_402_689, // https://sharp.pixelplumbing.com/api-constructor#:~:text=%5Boptions.limitInputPixels%5D\n    imgOptSequentialRead: null,\n    imgOptSkipMetadata: null,\n    isrFlushToDisk: true,\n    workerThreads: false,\n    proxyTimeout: undefined,\n    optimizeCss: false,\n    nextScriptWorkers: false,\n    scrollRestoration: false,\n    externalDir: false,\n    disableOptimizedLoading: false,\n    gzipSize: true,\n    craCompat: false,\n    esmExternals: true,\n    fullySpecified: false,\n    swcTraceProfiling: false,\n    forceSwcTransforms: false,\n    swcPlugins: undefined,\n    largePageDataBytes: 128 * 1000, // 128KB by default\n    disablePostcssPresetEnv: undefined,\n    urlImports: undefined,\n    typedEnv: false,\n    clientTraceMetadata: undefined,\n    parallelServerCompiles: false,\n    parallelServerBuildTraces: false,\n    ppr: false,\n    authInterrupts: false,\n    webpackBuildWorker: undefined,\n    webpackMemoryOptimizations: false,\n    optimizeServerReact: true,\n    strictRouteTypes: false,\n    viewTransition: false,\n    removeUncaughtErrorAndRejectionListeners: false,\n    validateRSCRequestHeaders: !!(\n      process.env.__NEXT_TEST_MODE || !isStableBuild()\n    ),\n    staleTimes: {\n      dynamic: 0,\n      static: 300,\n    },\n    allowDevelopmentBuild: undefined,\n    reactDebugChannel: true,\n    staticGenerationRetryCount: undefined,\n    serverComponentsHmrCache: true,\n    staticGenerationMaxConcurrency: 8,\n    staticGenerationMinPagesPerWorker: 25,\n    transitionIndicator: false,\n    gestureTransition: false,\n    inlineCss: false,\n    useCache: undefined,\n    slowModuleDetection: undefined,\n    globalNotFound: false,\n    browserDebugInfoInTerminal: 'warn',\n    lockDistDir: true,\n    proxyClientMaxBodySize: 10_485_760, // 10MB\n    hideLogsAfterAbort: false,\n    mcpServer: true,\n    turbopackFileSystemCacheForDev: true,\n    turbopackFileSystemCacheForBuild: false,\n    turbopackInferModuleSideEffects: true,\n    turbopackPluginRuntimeStrategy: 'childProcesses',\n  },\n  htmlLimitedBots: undefined,\n  bundlePagesRouterDependencies: false,\n} satisfies NextConfig)\n\nexport async function normalizeConfig(phase: string, config: any) {\n  if (typeof config === 'function') {\n    config = config(phase, { defaultConfig })\n  }\n  // Support `new Promise` and `async () =>` as return values of the config export\n  return await config\n}\n\n// This should be a supertype of NextConfigComplete\n//\n// The Vercel builder needs these fields (read `config` in required-server-files.json)\n// {\n//   pageExtensions: string[];\n//   experimental?: {\n//     cacheComponents?: boolean;\n//     clientParamParsingOrigins?: string[];\n//     clientSegmentCache?: boolean;\n//     ppr?: boolean | 'incremental';\n//     serverActions?: Record<string, never>;\n//   };\n// };\nexport interface NextConfigRuntime {\n  // Can be undefined, particularly when experimental.runtimeServerDeploymentId is true\n  deploymentId?: NextConfigComplete['deploymentId']\n\n  configFileName?: string\n  // Should only be included when using isExperimentalCompile\n  env?: NextConfigComplete['env']\n\n  distDir: NextConfigComplete['distDir']\n  cacheComponents: NextConfigComplete['cacheComponents']\n  htmlLimitedBots: NextConfigComplete['htmlLimitedBots']\n  assetPrefix: NextConfigComplete['assetPrefix']\n  output: NextConfigComplete['output']\n  crossOrigin: NextConfigComplete['crossOrigin']\n  trailingSlash: NextConfigComplete['trailingSlash']\n  images: NextConfigComplete['images']\n  reactMaxHeadersLength: NextConfigComplete['reactMaxHeadersLength']\n  cacheLife: NextConfigComplete['cacheLife']\n  basePath: NextConfigComplete['basePath']\n  expireTime: NextConfigComplete['expireTime']\n  generateEtags: NextConfigComplete['generateEtags']\n  poweredByHeader: NextConfigComplete['poweredByHeader']\n  cacheHandler: NextConfigComplete['cacheHandler']\n  cacheHandlers: NextConfigComplete['cacheHandlers']\n  cacheMaxMemorySize: NextConfigComplete['cacheMaxMemorySize']\n  compress: NextConfigComplete['compress']\n  i18n: NextConfigComplete['i18n']\n  httpAgentOptions: NextConfigComplete['httpAgentOptions']\n  skipProxyUrlNormalize: NextConfigComplete['skipProxyUrlNormalize']\n  pageExtensions: NextConfigComplete['pageExtensions']\n  useFileSystemPublicRoutes: NextConfigComplete['useFileSystemPublicRoutes']\n  logging?: NextConfigComplete['logging']\n  adapterPath?: NextConfigComplete['adapterPath']\n\n  experimental: Pick<\n    NextConfigComplete['experimental'],\n    | 'ppr'\n    | 'taint'\n    | 'serverActions'\n    | 'staleTimes'\n    | 'dynamicOnHover'\n    | 'optimisticRouting'\n    | 'inlineCss'\n    | 'prefetchInlining'\n    | 'authInterrupts'\n    | 'clientTraceMetadata'\n    | 'clientParamParsingOrigins'\n    | 'allowedRevalidateHeaderKeys'\n    | 'fetchCacheKeyPrefix'\n    | 'isrFlushToDisk'\n    | 'optimizeCss'\n    | 'nextScriptWorkers'\n    | 'disableOptimizedLoading'\n    | 'largePageDataBytes'\n    | 'serverComponentsHmrCache'\n    | 'caseSensitiveRoutes'\n    | 'validateRSCRequestHeaders'\n    | 'sri'\n    | 'useSkewCookie'\n    | 'preloadEntriesOnStart'\n    | 'hideLogsAfterAbort'\n    | 'removeUncaughtErrorAndRejectionListeners'\n    | 'imgOptConcurrency'\n    | 'imgOptMaxInputPixels'\n    | 'imgOptSequentialRead'\n    | 'imgOptSkipMetadata'\n    | 'imgOptTimeoutInSeconds'\n    | 'proxyClientMaxBodySize'\n    | 'proxyTimeout'\n    | 'testProxy'\n    | 'runtimeServerDeploymentId'\n    | 'maxPostponedStateSize'\n    | 'cachedNavigations'\n    | 'partialFallbacks'\n    | 'exposeTestingApiInProductionBuild'\n    | 'immutableAssetToken'\n  > & {\n    // Pick on @internal fields generates invalid .d.ts files\n    /** @internal */\n    trustHostHeader?: NextConfigComplete['experimental']['trustHostHeader']\n    /** @internal */\n    isExperimentalCompile?: NextConfigComplete['experimental']['isExperimentalCompile']\n  }\n}\n\nexport function getNextConfigRuntime(\n  config: NextConfigComplete | NextConfigRuntime\n): NextConfigRuntime {\n  // This config filter is a breaking change, so only do it if experimental.runtimeServerDeploymentId is enabled\n  if (!config.experimental.runtimeServerDeploymentId) {\n    return config\n  }\n\n  let ex = config.experimental\n\n  type Requiredish<T> = {\n    [K in keyof Required<T>]: T[K]\n  }\n\n  let experimental = ex\n    ? ({\n        ppr: ex.ppr,\n        taint: ex.taint,\n        serverActions: ex.serverActions,\n        staleTimes: ex.staleTimes,\n        dynamicOnHover: ex.dynamicOnHover,\n        optimisticRouting: ex.optimisticRouting,\n        inlineCss: ex.inlineCss,\n        prefetchInlining: ex.prefetchInlining,\n        authInterrupts: ex.authInterrupts,\n        clientTraceMetadata: ex.clientTraceMetadata,\n        clientParamParsingOrigins: ex.clientParamParsingOrigins,\n        allowedRevalidateHeaderKeys: ex.allowedRevalidateHeaderKeys,\n        fetchCacheKeyPrefix: ex.fetchCacheKeyPrefix,\n        isrFlushToDisk: ex.isrFlushToDisk,\n        optimizeCss: ex.optimizeCss,\n        nextScriptWorkers: ex.nextScriptWorkers,\n        disableOptimizedLoading: ex.disableOptimizedLoading,\n        largePageDataBytes: ex.largePageDataBytes,\n        serverComponentsHmrCache: ex.serverComponentsHmrCache,\n        caseSensitiveRoutes: ex.caseSensitiveRoutes,\n        validateRSCRequestHeaders: ex.validateRSCRequestHeaders,\n        sri: ex.sri,\n        useSkewCookie: ex.useSkewCookie,\n        preloadEntriesOnStart: ex.preloadEntriesOnStart,\n        hideLogsAfterAbort: ex.hideLogsAfterAbort,\n        removeUncaughtErrorAndRejectionListeners:\n          ex.removeUncaughtErrorAndRejectionListeners,\n        imgOptConcurrency: ex.imgOptConcurrency,\n        imgOptMaxInputPixels: ex.imgOptMaxInputPixels,\n        imgOptSequentialRead: ex.imgOptSequentialRead,\n        imgOptSkipMetadata: ex.imgOptSkipMetadata,\n        imgOptTimeoutInSeconds: ex.imgOptTimeoutInSeconds,\n        proxyClientMaxBodySize: ex.proxyClientMaxBodySize,\n        proxyTimeout: ex.proxyTimeout,\n        testProxy: ex.testProxy,\n        runtimeServerDeploymentId: ex.runtimeServerDeploymentId,\n        maxPostponedStateSize: ex.maxPostponedStateSize,\n        cachedNavigations: ex.cachedNavigations,\n        partialFallbacks: ex.partialFallbacks,\n        exposeTestingApiInProductionBuild: ex.exposeTestingApiInProductionBuild,\n        immutableAssetToken: ex.immutableAssetToken,\n\n        trustHostHeader: ex.trustHostHeader,\n        isExperimentalCompile: ex.isExperimentalCompile,\n      } satisfies Requiredish<NextConfigRuntime['experimental']>)\n    : {}\n\n  let runtimeConfig: Requiredish<NextConfigRuntime> = {\n    deploymentId: config.experimental.runtimeServerDeploymentId\n      ? ''\n      : config.deploymentId,\n\n    configFileName: undefined,\n    env: undefined,\n\n    distDir: config.distDir,\n    cacheComponents: config.cacheComponents,\n    htmlLimitedBots: config.htmlLimitedBots,\n    assetPrefix: config.assetPrefix,\n    output: config.output,\n    crossOrigin: config.crossOrigin,\n    trailingSlash: config.trailingSlash,\n    images: config.images,\n    reactMaxHeadersLength: config.reactMaxHeadersLength,\n    cacheLife: config.cacheLife,\n    basePath: config.basePath,\n    expireTime: config.expireTime,\n    generateEtags: config.generateEtags,\n    poweredByHeader: config.poweredByHeader,\n    cacheHandler: config.cacheHandler,\n    cacheHandlers: config.cacheHandlers,\n    // The full adapterPath might be non-deterministic across builds and doesn't\n    // actually matter at runtime, so replace it with a placeholder if it's set.\n    adapterPath: config.adapterPath ? '<omitted but set>' : undefined,\n    cacheMaxMemorySize: config.cacheMaxMemorySize,\n    compress: config.compress,\n    i18n: config.i18n,\n    httpAgentOptions: config.httpAgentOptions,\n    skipProxyUrlNormalize: config.skipProxyUrlNormalize,\n    pageExtensions: config.pageExtensions,\n    useFileSystemPublicRoutes: config.useFileSystemPublicRoutes,\n    logging: config.logging,\n\n    experimental,\n  }\n\n  if (config.experimental.isExperimentalCompile) {\n    runtimeConfig.env = config.env\n  }\n\n  return runtimeConfig\n}\n\n// Re-export from shared lib for backwards compatibility\nexport {\n  DEFAULT_MAX_POSTPONED_STATE_SIZE,\n  parseMaxPostponedStateSize,\n} from '../shared/lib/size-limit'\n","export const VALID_LOADERS = [\n  'default',\n  'imgix',\n  'cloudinary',\n  'akamai',\n  'custom',\n] as const\n\nexport type LoaderValue = (typeof VALID_LOADERS)[number]\n\nexport type ImageLoaderProps = {\n  src: string\n  width: number\n  quality?: number\n}\n\nexport type ImageLoaderPropsWithConfig = ImageLoaderProps & {\n  config: Readonly<ImageConfig>\n}\n\nexport type LocalPattern = {\n  /**\n   * Can be literal or wildcard.\n   * Single `*` matches a single path segment.\n   * Double `**` matches any number of path segments.\n   */\n  pathname?: string\n\n  /**\n   * Can be literal query string such as `?v=1` or\n   * empty string meaning no query string.\n   */\n  search?: string\n}\n\nexport type RemotePattern = {\n  /**\n   * Must be `http` or `https`.\n   */\n  protocol?: 'http' | 'https'\n\n  /**\n   * Can be literal or wildcard.\n   * Single `*` matches a single subdomain.\n   * Double `**` matches any number of subdomains.\n   */\n  hostname: string\n\n  /**\n   * Can be literal port such as `8080` or empty string\n   * meaning no port.\n   */\n  port?: string\n\n  /**\n   * Can be literal or wildcard.\n   * Single `*` matches a single path segment.\n   * Double `**` matches any number of path segments.\n   */\n  pathname?: string\n\n  /**\n   * Can be literal query string such as `?v=1` or\n   * empty string meaning no query string.\n   */\n  search?: string\n}\n\ntype ImageFormat = 'image/avif' | 'image/webp'\n\n/**\n * Image configurations\n *\n * @see [Image configuration options](https://nextjs.org/docs/api-reference/next/image#configuration-options)\n */\nexport type ImageConfigComplete = {\n  /** @see [Device sizes documentation](https://nextjs.org/docs/api-reference/next/image#device-sizes) */\n  deviceSizes: number[]\n\n  /** @see [Image sizing documentation](https://nextjs.org/docs/app/building-your-application/optimizing/images#image-sizing) */\n  imageSizes: number[]\n\n  /** @see [Image loaders configuration](https://nextjs.org/docs/api-reference/next/legacy/image#loader) */\n  loader: LoaderValue\n\n  /** @see [Image loader configuration](https://nextjs.org/docs/app/api-reference/components/image#path) */\n  path: string\n\n  /** @see [Image loader configuration](https://nextjs.org/docs/api-reference/next/image#loader-configuration) */\n  loaderFile: string\n\n  /**\n   * @deprecated Use `remotePatterns` instead.\n   */\n  domains: string[]\n\n  /** @see [Disable static image import configuration](https://nextjs.org/docs/api-reference/next/image#disable-static-imports) */\n  disableStaticImages: boolean\n\n  /** @see [Cache behavior](https://nextjs.org/docs/api-reference/next/image#caching-behavior) */\n  minimumCacheTTL: number\n\n  /** @see [Acceptable formats](https://nextjs.org/docs/api-reference/next/image#acceptable-formats) */\n  formats: ImageFormat[]\n\n  /** @see [Maximum Disk Cache Size (in bytes)](https://nextjs.org/docs/api-reference/next/image#maximumdiskcachesize) */\n  maximumDiskCacheSize: number | undefined\n\n  /** @see [Maximum Redirects](https://nextjs.org/docs/api-reference/next/image#maximumredirects) */\n  maximumRedirects: number\n\n  /** @see [Maximum Response Body](https://nextjs.org/docs/api-reference/next/image#maximumresponsebody) */\n  maximumResponseBody: number\n\n  /** @see [Dangerously Allow Local IP](https://nextjs.org/docs/api-reference/next/image#dangerously-allow-local-ip) */\n  dangerouslyAllowLocalIP: boolean\n\n  /** @see [Dangerously Allow SVG](https://nextjs.org/docs/api-reference/next/image#dangerously-allow-svg) */\n  dangerouslyAllowSVG: boolean\n\n  /** @see [Content Security Policy](https://nextjs.org/docs/api-reference/next/image#contentsecuritypolicy) */\n  contentSecurityPolicy: string\n\n  /** @see [Content Disposition Type](https://nextjs.org/docs/api-reference/next/image#contentdispositiontype) */\n  contentDispositionType: 'inline' | 'attachment'\n\n  /** @see [Remote Patterns](https://nextjs.org/docs/api-reference/next/image#remotepatterns) */\n  remotePatterns: Array<URL | RemotePattern>\n\n  /** @see [Local Patterns](https://nextjs.org/docs/api-reference/next/image#localPatterns) */\n  localPatterns: LocalPattern[] | undefined\n\n  /** @see [Qualities](https://nextjs.org/docs/api-reference/next/image#qualities) */\n  qualities: number[] | undefined\n\n  /** @see [Unoptimized](https://nextjs.org/docs/api-reference/next/image#unoptimized) */\n  unoptimized: boolean\n\n  /**\n   * When true, the `cacheHandler` configured in next.config.js will also be used\n   * for caching optimized images. When false, images use the default filesystem cache.\n   * @see [Image Optimization Caching](https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheHandler#image-optimization-caching)\n   */\n  customCacheHandler: boolean\n}\n\nexport type ImageConfig = Partial<ImageConfigComplete>\n\nexport const imageConfigDefault: ImageConfigComplete = {\n  deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],\n  imageSizes: [32, 48, 64, 96, 128, 256, 384],\n  path: '/_next/image',\n  loader: 'default',\n  loaderFile: '',\n  /**\n   * @deprecated Use `remotePatterns` instead to protect your application from malicious users.\n   */\n  domains: [],\n  disableStaticImages: false,\n  minimumCacheTTL: 14400, // 4 hours\n  formats: ['image/webp'],\n  maximumDiskCacheSize: undefined, // auto-detect by default\n  maximumRedirects: 3,\n  maximumResponseBody: 50_000_000, // 50 MB\n  dangerouslyAllowLocalIP: false,\n  dangerouslyAllowSVG: false,\n  contentSecurityPolicy: `script-src 'none'; frame-src 'none'; sandbox;`,\n  contentDispositionType: 'attachment',\n  localPatterns: undefined, // default: allow all local images\n  remotePatterns: [], // default: allow no remote images\n  qualities: [75],\n  unoptimized: false,\n  customCacheHandler: false,\n}\n","export function isStableBuild() {\n  return (\n    !process.env.__NEXT_VERSION?.includes('canary') &&\n    !process.env.__NEXT_TEST_MODE &&\n    !process.env.NEXT_PRIVATE_LOCAL_DEV\n  )\n}\n\nexport class CanaryOnlyConfigError extends Error {\n  constructor(arg: { feature: string } | string) {\n    if (typeof arg === 'object' && 'feature' in arg) {\n      super(\n        `The experimental feature \"${arg.feature}\" can only be enabled when using the latest canary version of Next.js.`\n      )\n    } else {\n      super(arg)\n    }\n\n    // This error is meant to interrupt the server start/build process\n    // but the stack trace isn't meaningful, as it points to internal code.\n    this.stack = undefined\n  }\n}\n","// Regex from `node/lib/internal/net.js`: https://github.com/nodejs/node/blob/9fc57006c27564ed7f75eee090eca86786508f51/lib/internal/net.js#L19-L29\n// License included below:\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nconst v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'\nconst v4Str = `(${v4Seg}[.]){3}${v4Seg}`\nconst v6Seg = '(?:[0-9a-fA-F]{1,4})'\nconst IPv6Reg = new RegExp(\n  '^(' +\n    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +\n    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +\n    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +\n    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +\n    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +\n    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +\n    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +\n    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +\n    ')(%[0-9a-zA-Z-.:]{1,})?$'\n)\n\nexport function isIPv6(s: string) {\n  return IPv6Reg.test(s)\n}\n","/**\n * For a given page path, this function ensures that there is a leading slash.\n * If there is not a leading slash, one is added, otherwise it is noop.\n */\nexport function ensureLeadingSlash(path: string) {\n  return path.startsWith('/') ? path : `/${path}`\n}\n","import { ensureLeadingSlash } from '../../page-path/ensure-leading-slash'\nimport { isGroupSegment } from '../../segment'\n\n/**\n * Normalizes an app route so it represents the actual request path. Essentially\n * performing the following transformations:\n *\n * - `/(dashboard)/user/[id]/page` to `/user/[id]`\n * - `/(dashboard)/account/page` to `/account`\n * - `/user/[id]/page` to `/user/[id]`\n * - `/account/page` to `/account`\n * - `/page` to `/`\n * - `/(dashboard)/user/[id]/route` to `/user/[id]`\n * - `/(dashboard)/account/route` to `/account`\n * - `/user/[id]/route` to `/user/[id]`\n * - `/account/route` to `/account`\n * - `/route` to `/`\n * - `/` to `/`\n *\n * @param route the app route to normalize\n * @returns the normalized pathname\n */\nexport function normalizeAppPath(route: string) {\n  return ensureLeadingSlash(\n    route.split('/').reduce((pathname, segment, index, segments) => {\n      // Empty segments are ignored.\n      if (!segment) {\n        return pathname\n      }\n\n      // Groups are ignored.\n      if (isGroupSegment(segment)) {\n        return pathname\n      }\n\n      // Parallel segments are ignored.\n      if (segment[0] === '@') {\n        return pathname\n      }\n\n      // The last segment (if it's a leaf) should be ignored.\n      if (\n        (segment === 'page' || segment === 'route') &&\n        index === segments.length - 1\n      ) {\n        return pathname\n      }\n\n      return `${pathname}/${segment}`\n    }, '')\n  )\n}\n\n/**\n * Comparator for sorting app paths so that parallel slot paths (containing\n * `/@`) come before the children/root page path. This ensures the last item\n * is always the children page, which is what `renderPageComponent` reads via\n * `appPaths[appPaths.length - 1]`.\n *\n * Without this, route group prefixes like `(group)` (char code 0x28) sort\n * before `@` (0x40), causing the children page to sort first instead of last\n * and leading to a manifest mismatch / 404 in webpack dev mode.\n */\nexport function compareAppPaths(a: string, b: string): number {\n  const aHasSlot = a.includes('/@')\n  const bHasSlot = b.includes('/@')\n  if (aHasSlot && !bHasSlot) return -1\n  if (!aHasSlot && bHasSlot) return 1\n  return a.localeCompare(b)\n}\n\n/**\n * Strips the `.rsc` extension if it's in the pathname.\n * Since this function is used on full urls it checks `?` for searchParams handling.\n */\nexport function normalizeRscURL(url: string) {\n  return url.replace(\n    /\\.rsc($|\\?)/,\n    // $1 ensures `?` is preserved\n    '$1'\n  )\n}\n","import type { FlightRouterState, Segment } from './app-router-types'\n\nexport function getSegmentValue(segment: Segment) {\n  return Array.isArray(segment) ? segment[1] : segment\n}\n\nexport function isGroupSegment(segment: string) {\n  // Use array[0] for performant purpose\n  return segment[0] === '(' && segment.endsWith(')')\n}\n\nexport function isParallelRouteSegment(segment: string) {\n  return segment.startsWith('@') && segment !== '@children'\n}\n\nexport function addSearchParamsIfPageSegment(\n  segment: Segment,\n  searchParams: Record<string, string | string[] | undefined>\n) {\n  const isPageSegment = segment.includes(PAGE_SEGMENT_KEY)\n\n  if (isPageSegment) {\n    const stringifiedQuery = JSON.stringify(searchParams)\n    return stringifiedQuery !== '{}'\n      ? PAGE_SEGMENT_KEY + '?' + stringifiedQuery\n      : PAGE_SEGMENT_KEY\n  }\n\n  return segment\n}\n\nexport function computeSelectedLayoutSegment(\n  segments: string[] | null,\n  parallelRouteKey: string\n): string | null {\n  if (!segments || segments.length === 0) {\n    return null\n  }\n\n  // For 'children', use first segment; for other parallel routes, use last segment\n  const rawSegment =\n    parallelRouteKey === 'children'\n      ? segments[0]\n      : segments[segments.length - 1]\n\n  // If the default slot is showing, return null since it's not technically \"selected\" (it's a fallback)\n  // Returning an internal value like `__DEFAULT__` would be confusing\n  return rawSegment === DEFAULT_SEGMENT_KEY ? null : rawSegment\n}\n\n/** Get the canonical parameters from the current level to the leaf node. */\nexport function getSelectedLayoutSegmentPath(\n  tree: FlightRouterState,\n  parallelRouteKey: string,\n  first = true,\n  segmentPath: string[] = []\n): string[] {\n  let node: FlightRouterState\n  if (first) {\n    // Use the provided parallel route key on the first parallel route\n    node = tree[1][parallelRouteKey]\n  } else {\n    // After first parallel route prefer children, if there's no children pick the first parallel route.\n    const parallelRoutes = tree[1]\n    node = parallelRoutes.children ?? Object.values(parallelRoutes)[0]\n  }\n\n  if (!node) return segmentPath\n  const segment = node[0]\n\n  let segmentValue = getSegmentValue(segment)\n\n  if (!segmentValue || segmentValue.startsWith(PAGE_SEGMENT_KEY)) {\n    return segmentPath\n  }\n\n  segmentPath.push(segmentValue)\n\n  return getSelectedLayoutSegmentPath(\n    node,\n    parallelRouteKey,\n    false,\n    segmentPath\n  )\n}\n\nexport const PAGE_SEGMENT_KEY = '__PAGE__'\nexport const DEFAULT_SEGMENT_KEY = '__DEFAULT__'\nexport const NOT_FOUND_SEGMENT_KEY = '/_not-found'\n","import { normalizeAppPath } from './app-paths'\n\n// order matters here, the first match will be used\nexport const INTERCEPTION_ROUTE_MARKERS = [\n  '(..)(..)',\n  '(.)',\n  '(..)',\n  '(...)',\n] as const\n\nexport type InterceptionMarker = (typeof INTERCEPTION_ROUTE_MARKERS)[number]\n\nexport function isInterceptionRouteAppPath(path: string): boolean {\n  // TODO-APP: add more serious validation\n  return (\n    path\n      .split('/')\n      .find((segment) =>\n        INTERCEPTION_ROUTE_MARKERS.find((m) => segment.startsWith(m))\n      ) !== undefined\n  )\n}\n\ntype InterceptionRouteInformation = {\n  /**\n   * The intercepting route. This is the route that is being intercepted or the\n   * route that the user was coming from. This is matched by the Next-Url\n   * header.\n   */\n  interceptingRoute: string\n\n  /**\n   * The intercepted route. This is the route that is being intercepted or the\n   * route that the user is going to. This is matched by the request pathname.\n   */\n  interceptedRoute: string\n}\n\nexport function extractInterceptionRouteInformation(\n  path: string\n): InterceptionRouteInformation {\n  let interceptingRoute: string | undefined\n  let marker: (typeof INTERCEPTION_ROUTE_MARKERS)[number] | undefined\n  let interceptedRoute: string | undefined\n\n  for (const segment of path.split('/')) {\n    marker = INTERCEPTION_ROUTE_MARKERS.find((m) => segment.startsWith(m))\n    if (marker) {\n      ;[interceptingRoute, interceptedRoute] = path.split(marker, 2)\n      break\n    }\n  }\n\n  if (!interceptingRoute || !marker || !interceptedRoute) {\n    throw new Error(\n      `Invalid interception route: ${path}. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>`\n    )\n  }\n\n  interceptingRoute = normalizeAppPath(interceptingRoute) // normalize the path, e.g. /(blog)/feed -> /feed\n\n  switch (marker) {\n    case '(.)':\n      // (.) indicates that we should match with sibling routes, so we just need to append the intercepted route to the intercepting route\n      if (interceptingRoute === '/') {\n        interceptedRoute = `/${interceptedRoute}`\n      } else {\n        interceptedRoute = interceptingRoute + '/' + interceptedRoute\n      }\n      break\n    case '(..)':\n      // (..) indicates that we should match at one level up, so we need to remove the last segment of the intercepting route\n      if (interceptingRoute === '/') {\n        throw new Error(\n          `Invalid interception route: ${path}. Cannot use (..) marker at the root level, use (.) instead.`\n        )\n      }\n      interceptedRoute = interceptingRoute\n        .split('/')\n        .slice(0, -1)\n        .concat(interceptedRoute)\n        .join('/')\n      break\n    case '(...)':\n      // (...) will match the route segment in the root directory, so we need to use the root directory to prepend the intercepted route\n      interceptedRoute = '/' + interceptedRoute\n      break\n    case '(..)(..)':\n      // (..)(..) indicates that we should match at two levels up, so we need to remove the last two segments of the intercepting route\n\n      const splitInterceptingRoute = interceptingRoute.split('/')\n      if (splitInterceptingRoute.length <= 2) {\n        throw new Error(\n          `Invalid interception route: ${path}. Cannot use (..)(..) marker at the root level or one level up.`\n        )\n      }\n\n      interceptedRoute = splitInterceptingRoute\n        .slice(0, -2)\n        .concat(interceptedRoute)\n        .join('/')\n      break\n    default:\n      throw new Error('Invariant: unexpected marker')\n  }\n\n  return { interceptingRoute, interceptedRoute }\n}\n","import {\n  extractInterceptionRouteInformation,\n  isInterceptionRouteAppPath,\n} from './interception-routes'\n\n// Identify /.*[param].*/ in route string\nconst TEST_ROUTE = /\\/[^/]*\\[[^/]+\\][^/]*(?=\\/|$)/\n\n// Identify /[param]/ in route string\nconst TEST_STRICT_ROUTE = /\\/\\[[^/]+\\](?=\\/|$)/\n\n/**\n * Check if a route is dynamic.\n *\n * @param route - The route to check.\n * @param strict - Whether to use strict mode which prohibits segments with prefixes/suffixes (default: true).\n * @returns Whether the route is dynamic.\n */\nexport function isDynamicRoute(route: string, strict: boolean = true): boolean {\n  if (isInterceptionRouteAppPath(route)) {\n    route = extractInterceptionRouteInformation(route).interceptedRoute\n  }\n\n  if (strict) {\n    return TEST_STRICT_ROUTE.test(route)\n  }\n\n  return TEST_ROUTE.test(route)\n}\n","// This regex contains the bots that we need to do a blocking render for and can't safely stream the response\n// due to how they parse the DOM. For example, they might explicitly check for metadata in the `head` tag, so we can't stream metadata tags after the `head` was sent.\n// Note: The pattern [\\w-]+-Google captures all Google crawlers with \"-Google\" suffix (e.g., Mediapartners-Google, AdsBot-Google, Storebot-Google)\n// as well as crawlers starting with \"Google-\" (e.g., Google-PageRenderer, Google-InspectionTool)\nexport const HTML_LIMITED_BOT_UA_RE =\n  /[\\w-]+-Google|Google-[\\w-]+|Chrome-Lighthouse|Slurp|DuckDuckBot|baiduspider|yandex|sogou|bitlybot|tumblr|vkShare|quora link preview|redditbot|ia_archiver|Bingbot|BingPreview|applebot|facebookexternalhit|facebookcatalog|Twitterbot|LinkedInBot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|Yeti|googleweblight/i\n","import { HTML_LIMITED_BOT_UA_RE } from './html-bots'\n\n// Bot crawler that will spin up a headless browser and execute JS.\n// Only the main Googlebot search crawler executes JavaScript, not other Google crawlers.\n// x-ref: https://developers.google.com/search/docs/crawling-indexing/google-common-crawlers\n// This regex specifically matches \"Googlebot\" but NOT \"Mediapartners-Google\", \"AdsBot-Google\", etc.\nconst HEADLESS_BROWSER_BOT_UA_RE = /Googlebot(?!-)|Googlebot$/i\n\nexport const HTML_LIMITED_BOT_UA_RE_STRING = HTML_LIMITED_BOT_UA_RE.source\n\nexport { HTML_LIMITED_BOT_UA_RE }\n\nfunction isDomBotUA(userAgent: string) {\n  return HEADLESS_BROWSER_BOT_UA_RE.test(userAgent)\n}\n\nfunction isHtmlLimitedBotUA(userAgent: string) {\n  return HTML_LIMITED_BOT_UA_RE.test(userAgent)\n}\n\nexport function isBot(userAgent: string): boolean {\n  return isDomBotUA(userAgent) || isHtmlLimitedBotUA(userAgent)\n}\n\nexport function getBotType(userAgent: string): 'dom' | 'html' | undefined {\n  if (isDomBotUA(userAgent)) {\n    return 'dom'\n  }\n  if (isHtmlLimitedBotUA(userAgent)) {\n    return 'html'\n  }\n  return undefined\n}\n","import type { ReactDOMServerReadableStream } from 'react-dom/server'\nimport { getTracer } from '../lib/trace/tracer'\nimport { AppRenderSpan } from '../lib/trace/constants'\nimport { DetachedPromise } from '../../lib/detached-promise'\nimport {\n  scheduleImmediate,\n  atLeastOneTask,\n  waitAtLeastOneReactRenderTask,\n} from '../../lib/scheduler'\nimport { ENCODED_TAGS } from './encoded-tags'\nimport {\n  indexOfUint8Array,\n  isEquivalentUint8Arrays,\n  removeFromUint8Array,\n} from './uint8array-helpers'\nimport { MISSING_ROOT_TAGS_ERROR } from '../../shared/lib/errors/constants'\nimport {\n  RSC_HEADER,\n  NEXT_ROUTER_PREFETCH_HEADER,\n  NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n  NEXT_RSC_UNION_QUERY,\n  NEXT_INSTANT_PREFETCH_HEADER,\n} from '../../client/components/app-router-headers'\nimport { computeCacheBustingSearchParam } from '../../shared/lib/router/utils/cache-busting-search-param'\n\nfunction voidCatch() {\n  // this catcher is designed to be used with pipeTo where we expect the underlying\n  // pipe implementation to forward errors but we don't want the pipeTo promise to reject\n  // and be unhandled\n}\n\n// We can share the same encoder instance everywhere\n// Notably we cannot do the same for TextDecoder because it is stateful\n// when handling streaming data\nconst encoder = new TextEncoder()\n\nexport function chainStreams<T>(\n  ...streams: ReadableStream<T>[]\n): ReadableStream<T> {\n  // If we have no streams, return an empty stream. This behavior is\n  // intentional as we're now providing the `RenderResult.EMPTY` value.\n  if (streams.length === 0) {\n    return new ReadableStream<T>({\n      start(controller) {\n        controller.close()\n      },\n    })\n  }\n\n  // If we only have 1 stream we fast path it by returning just this stream\n  if (streams.length === 1) {\n    return streams[0]\n  }\n\n  const { readable, writable } = new TransformStream()\n\n  // We always initiate pipeTo immediately. We know we have at least 2 streams\n  // so we need to avoid closing the writable when this one finishes.\n  let promise = streams[0].pipeTo(writable, { preventClose: true })\n\n  let i = 1\n  for (; i < streams.length - 1; i++) {\n    const nextStream = streams[i]\n    promise = promise.then(() =>\n      nextStream.pipeTo(writable, { preventClose: true })\n    )\n  }\n\n  // We can omit the length check because we halted before the last stream and there\n  // is at least two streams so the lastStream here will always be defined\n  const lastStream = streams[i]\n  promise = promise.then(() => lastStream.pipeTo(writable))\n\n  // Catch any errors from the streams and ignore them, they will be handled\n  // by whatever is consuming the readable stream.\n  promise.catch(voidCatch)\n\n  return readable\n}\n\nexport function streamFromString(str: string): ReadableStream<Uint8Array> {\n  return new ReadableStream({\n    start(controller) {\n      controller.enqueue(encoder.encode(str))\n      controller.close()\n    },\n  })\n}\n\nexport function streamFromBuffer(chunk: Buffer): ReadableStream<Uint8Array> {\n  return new ReadableStream({\n    start(controller) {\n      controller.enqueue(chunk)\n      controller.close()\n    },\n  })\n}\n\nasync function streamToChunks(\n  stream: ReadableStream<Uint8Array>\n): Promise<Array<Uint8Array>> {\n  const reader = stream.getReader()\n  const chunks: Array<Uint8Array> = []\n\n  while (true) {\n    const { done, value } = await reader.read()\n    if (done) {\n      break\n    }\n\n    chunks.push(value)\n  }\n\n  return chunks\n}\n\nfunction concatUint8Arrays(chunks: Array<Uint8Array>): Uint8Array {\n  const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0)\n  const result = new Uint8Array(totalLength)\n  let offset = 0\n  for (const chunk of chunks) {\n    result.set(chunk, offset)\n    offset += chunk.length\n  }\n  return result\n}\n\nexport async function streamToUint8Array(\n  stream: ReadableStream<Uint8Array>\n): Promise<Uint8Array> {\n  return concatUint8Arrays(await streamToChunks(stream))\n}\n\nexport async function streamToBuffer(\n  stream: ReadableStream<Uint8Array>\n): Promise<Buffer> {\n  return Buffer.concat(await streamToChunks(stream))\n}\n\nexport async function streamToString(\n  stream: ReadableStream<Uint8Array>,\n  signal?: AbortSignal\n): Promise<string> {\n  const decoder = new TextDecoder('utf-8', { fatal: true })\n  let string = ''\n\n  for await (const chunk of stream) {\n    if (signal?.aborted) {\n      return string\n    }\n\n    string += decoder.decode(chunk, { stream: true })\n  }\n\n  string += decoder.decode()\n\n  return string\n}\n\nexport type BufferedTransformOptions = {\n  /**\n   * Flush synchronously once the buffer reaches this many bytes.\n   */\n  readonly maxBufferByteLength?: number\n}\n\nexport function createBufferedTransformStream(\n  options: BufferedTransformOptions = {}\n): TransformStream<Uint8Array, Uint8Array> {\n  const { maxBufferByteLength = Infinity } = options\n\n  let bufferedChunks: Array<Uint8Array> = []\n  let bufferByteLength: number = 0\n  let pending: DetachedPromise<void> | undefined\n\n  const flush = (controller: TransformStreamDefaultController) => {\n    try {\n      if (bufferedChunks.length === 0) {\n        return\n      }\n\n      const chunk = new Uint8Array(bufferByteLength)\n      let copiedBytes = 0\n\n      for (let i = 0; i < bufferedChunks.length; i++) {\n        const bufferedChunk = bufferedChunks[i]\n        chunk.set(bufferedChunk, copiedBytes)\n        copiedBytes += bufferedChunk.byteLength\n      }\n      // We just wrote all the buffered chunks so we need to reset the bufferedChunks array\n      // and our bufferByteLength to prepare for the next round of buffered chunks\n      bufferedChunks.length = 0\n      bufferByteLength = 0\n      controller.enqueue(chunk)\n    } catch {\n      // If an error occurs while enqueuing, it can't be due to this\n      // transformer. It's most likely caused by the controller having been\n      // errored (for example, if the stream was cancelled).\n    }\n  }\n\n  const scheduleFlush = (controller: TransformStreamDefaultController) => {\n    if (pending) {\n      return\n    }\n\n    const detached = new DetachedPromise<void>()\n    pending = detached\n\n    scheduleImmediate(() => {\n      try {\n        flush(controller)\n      } finally {\n        pending = undefined\n        detached.resolve()\n      }\n    })\n  }\n\n  return new TransformStream({\n    transform(chunk, controller) {\n      // Combine the previous buffer with the new chunk.\n      bufferedChunks.push(chunk)\n      bufferByteLength += chunk.byteLength\n\n      if (bufferByteLength >= maxBufferByteLength) {\n        flush(controller)\n      } else {\n        scheduleFlush(controller)\n      }\n    },\n    flush() {\n      return pending?.promise\n    },\n  })\n}\n\n// TODO this is currently unused but once we add proper output:export support, it needs to be\n// revisited. See https://github.com/vercel/next.js/pull/89478 for more details\n//\n// function createPrefetchCommentStream(\n//   isBuildTimePrerendering: boolean,\n//   buildId: string\n// ): TransformStream<Uint8Array, Uint8Array> {\n//   // Insert an extra comment at the beginning of the HTML document. This must\n//   // come after the DOCTYPE, which is inserted by React.\n//   //\n//   // The first chunk sent by React will contain the doctype. After that, we can\n//   // pass through the rest of the chunks as-is.\n//   let didTransformFirstChunk = false\n//   return new TransformStream({\n//     transform(chunk, controller) {\n//       if (isBuildTimePrerendering && !didTransformFirstChunk) {\n//         didTransformFirstChunk = true\n//         const decoder = new TextDecoder('utf-8', { fatal: true })\n//         const chunkStr = decoder.decode(chunk, {\n//           stream: true,\n//         })\n//         const updatedChunkStr = insertBuildIdComment(chunkStr, buildId)\n//         controller.enqueue(encoder.encode(updatedChunkStr))\n//         return\n//       }\n//       controller.enqueue(chunk)\n//     },\n//   })\n// }\n\nexport function renderToInitialFizzStream({\n  ReactDOMServer,\n  element,\n  streamOptions,\n}: {\n  ReactDOMServer: {\n    renderToReadableStream: typeof import('react-dom/server').renderToReadableStream\n  }\n  element: React.ReactElement\n  streamOptions?: Parameters<typeof ReactDOMServer.renderToReadableStream>[1]\n}): Promise<ReactDOMServerReadableStream> {\n  return getTracer().trace(AppRenderSpan.renderToReadableStream, async () =>\n    ReactDOMServer.renderToReadableStream(element, streamOptions)\n  )\n}\n\nfunction createMetadataTransformStream(\n  insert: () => Promise<string> | string\n): TransformStream<Uint8Array, Uint8Array> {\n  let chunkIndex = -1\n  let isMarkRemoved = false\n\n  return new TransformStream({\n    async transform(chunk, controller) {\n      let iconMarkIndex = -1\n      let closedHeadIndex = -1\n      chunkIndex++\n\n      if (isMarkRemoved) {\n        controller.enqueue(chunk)\n        return\n      }\n      let iconMarkLength = 0\n      // Only search for the closed head tag once\n      if (iconMarkIndex === -1) {\n        iconMarkIndex = indexOfUint8Array(chunk, ENCODED_TAGS.META.ICON_MARK)\n        if (iconMarkIndex === -1) {\n          controller.enqueue(chunk)\n          return\n        } else {\n          // When we found the `<meta name=\"«nxt-icon»\"` tag prefix, we will remove it from the chunk.\n          // Its close tag could either be `/>` or `>`, checking the next char to ensure we cover both cases.\n          iconMarkLength = ENCODED_TAGS.META.ICON_MARK.length\n          // Check if next char is /, this is for xml mode.\n          if (chunk[iconMarkIndex + iconMarkLength] === 47) {\n            iconMarkLength += 2\n          } else {\n            // The last char is `>`\n            iconMarkLength++\n          }\n        }\n      }\n\n      // Check if icon mark is inside <head> tag in the first chunk.\n      if (chunkIndex === 0) {\n        closedHeadIndex = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.HEAD)\n        if (iconMarkIndex !== -1) {\n          // The mark icon is located in the 1st chunk before the head tag.\n          // We do not need to insert the script tag in this case because it's in the head.\n          // Just remove the icon mark from the chunk.\n          if (iconMarkIndex < closedHeadIndex) {\n            const replaced = new Uint8Array(chunk.length - iconMarkLength)\n\n            // Remove the icon mark from the chunk.\n            replaced.set(chunk.subarray(0, iconMarkIndex))\n            replaced.set(\n              chunk.subarray(iconMarkIndex + iconMarkLength),\n              iconMarkIndex\n            )\n            chunk = replaced\n          } else {\n            // The icon mark is after the head tag, replace and insert the script tag at that position.\n            const insertion = await insert()\n            const encodedInsertion = encoder.encode(insertion)\n            const insertionLength = encodedInsertion.length\n            const replaced = new Uint8Array(\n              chunk.length - iconMarkLength + insertionLength\n            )\n            replaced.set(chunk.subarray(0, iconMarkIndex))\n            replaced.set(encodedInsertion, iconMarkIndex)\n            replaced.set(\n              chunk.subarray(iconMarkIndex + iconMarkLength),\n              iconMarkIndex + insertionLength\n            )\n            chunk = replaced\n          }\n          isMarkRemoved = true\n        }\n        // If there's no icon mark located, it will be handled later when if present in the following chunks.\n      } else {\n        // When it's appeared in the following chunks, we'll need to\n        // remove the mark and then insert the script tag at that position.\n        const insertion = await insert()\n        const encodedInsertion = encoder.encode(insertion)\n        const insertionLength = encodedInsertion.length\n        // Replace the icon mark with the hoist script or empty string.\n        const replaced = new Uint8Array(\n          chunk.length - iconMarkLength + insertionLength\n        )\n        // Set the first part of the chunk, before the icon mark.\n        replaced.set(chunk.subarray(0, iconMarkIndex))\n        // Set the insertion after the icon mark.\n        replaced.set(encodedInsertion, iconMarkIndex)\n\n        // Set the rest of the chunk after the icon mark.\n        replaced.set(\n          chunk.subarray(iconMarkIndex + iconMarkLength),\n          iconMarkIndex + insertionLength\n        )\n        chunk = replaced\n        isMarkRemoved = true\n      }\n      controller.enqueue(chunk)\n    },\n  })\n}\n\nfunction createHeadInsertionTransformStream(\n  insert: () => Promise<string>\n): TransformStream<Uint8Array, Uint8Array> {\n  let inserted = false\n\n  // We need to track if this transform saw any bytes because if it didn't\n  // we won't want to insert any server HTML at all\n  let hasBytes = false\n\n  return new TransformStream({\n    async transform(chunk, controller) {\n      hasBytes = true\n\n      const insertion = await insert()\n      if (inserted) {\n        if (insertion) {\n          const encodedInsertion = encoder.encode(insertion)\n          controller.enqueue(encodedInsertion)\n        }\n        controller.enqueue(chunk)\n      } else {\n        // TODO (@Ethan-Arrowood): Replace the generic `indexOfUint8Array` method with something finely tuned for the subset of things actually being checked for.\n        const index = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.HEAD)\n        // In fully static rendering or non PPR rendering cases:\n        // `/head>` will always be found in the chunk in first chunk rendering.\n        if (index !== -1) {\n          if (insertion) {\n            const encodedInsertion = encoder.encode(insertion)\n            // Get the total count of the bytes in the chunk and the insertion\n            // e.g.\n            // chunk = <head><meta charset=\"utf-8\"></head>\n            // insertion = <script>...</script>\n            // output = <head><meta charset=\"utf-8\"> [ <script>...</script> ] </head>\n            const insertedHeadContent = new Uint8Array(\n              chunk.length + encodedInsertion.length\n            )\n            // Append the first part of the chunk, before the head tag\n            insertedHeadContent.set(chunk.slice(0, index))\n            // Append the server inserted content\n            insertedHeadContent.set(encodedInsertion, index)\n            // Append the rest of the chunk\n            insertedHeadContent.set(\n              chunk.slice(index),\n              index + encodedInsertion.length\n            )\n            controller.enqueue(insertedHeadContent)\n          } else {\n            controller.enqueue(chunk)\n          }\n          inserted = true\n        } else {\n          // This will happens in PPR rendering during next start, when the page is partially rendered.\n          // When the page resumes, the head tag will be found in the middle of the chunk.\n          // Where we just need to append the insertion and chunk to the current stream.\n          // e.g.\n          // PPR-static: <head>...</head><body> [ resume content ] </body>\n          // PPR-resume: [ insertion ] [ rest content ]\n          if (insertion) {\n            controller.enqueue(encoder.encode(insertion))\n          }\n          controller.enqueue(chunk)\n          inserted = true\n        }\n      }\n    },\n    async flush(controller) {\n      // Check before closing if there's anything remaining to insert.\n      if (hasBytes) {\n        const insertion = await insert()\n        if (insertion) {\n          controller.enqueue(encoder.encode(insertion))\n        }\n      }\n    },\n  })\n}\n\nfunction createClientResumeScriptInsertionTransformStream(): TransformStream<\n  Uint8Array,\n  Uint8Array\n> {\n  const segmentPath = '/_full'\n  const cacheBustingHeader = computeCacheBustingSearchParam(\n    '1', //            headers[NEXT_ROUTER_PREFETCH_HEADER]\n    '/_full', //       headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]\n    undefined, //      headers[NEXT_ROUTER_STATE_TREE_HEADER]\n    undefined //       headers[NEXT_URL]\n  )\n  const searchStr = `${NEXT_RSC_UNION_QUERY}=${cacheBustingHeader}`\n  const NEXT_CLIENT_RESUME_SCRIPT = `<script>__NEXT_CLIENT_RESUME=fetch(location.pathname+'?${searchStr}',{credentials:'same-origin',headers:{'${RSC_HEADER}': '1','${NEXT_ROUTER_PREFETCH_HEADER}': '1','${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}': '${segmentPath}'}})</script>`\n\n  let didAlreadyInsert = false\n  return new TransformStream({\n    transform(chunk, controller) {\n      if (didAlreadyInsert) {\n        // Already inserted the script into the head. Pass through.\n        controller.enqueue(chunk)\n        return\n      }\n      // TODO (@Ethan-Arrowood): Replace the generic `indexOfUint8Array` method with something finely tuned for the subset of things actually being checked for.\n      const headClosingTagIndex = indexOfUint8Array(\n        chunk,\n        ENCODED_TAGS.CLOSED.HEAD\n      )\n\n      if (headClosingTagIndex === -1) {\n        // In fully static rendering or non PPR rendering cases:\n        // `/head>` will always be found in the chunk in first chunk rendering.\n        controller.enqueue(chunk)\n        return\n      }\n\n      const encodedInsertion = encoder.encode(NEXT_CLIENT_RESUME_SCRIPT)\n      // Get the total count of the bytes in the chunk and the insertion\n      // e.g.\n      // chunk = <head><meta charset=\"utf-8\"></head>\n      // insertion = <script>...</script>\n      // output = <head><meta charset=\"utf-8\"> [ <script>...</script> ] </head>\n      const insertedHeadContent = new Uint8Array(\n        chunk.length + encodedInsertion.length\n      )\n      // Append the first part of the chunk, before the head tag\n      insertedHeadContent.set(chunk.slice(0, headClosingTagIndex))\n      // Append the server inserted content\n      insertedHeadContent.set(encodedInsertion, headClosingTagIndex)\n      // Append the rest of the chunk\n      insertedHeadContent.set(\n        chunk.slice(headClosingTagIndex),\n        headClosingTagIndex + encodedInsertion.length\n      )\n\n      controller.enqueue(insertedHeadContent)\n      didAlreadyInsert = true\n    },\n  })\n}\n\n/**\n * Creates a transform stream that injects an inline script as the first\n * element inside <head>. Used during instant navigation testing to set\n * self.__next_instant_test before any async bootstrap scripts execute.\n */\nexport function createInstantTestScriptInsertionTransformStream(\n  requestId: string | null\n): TransformStream<Uint8Array, Uint8Array> {\n  // Kick off a fetch for the static RSC payload. This is the hydration\n  // source for the locked static shell — same as the __NEXT_CLIENT_RESUME\n  // fetch used for fallback routes, but with NEXT_INSTANT_PREFETCH_HEADER\n  // so the server returns static-only data.\n  //\n  // The fetch promise is stored as self.__next_instant_test, which doubles\n  // as the feature flag (truthy = instant test mode). The client processes\n  // this as a fallback prerender payload for hydration.\n  const segmentPath = '/_full'\n  const cacheBustingHeader = computeCacheBustingSearchParam(\n    '1',\n    segmentPath,\n    undefined,\n    undefined\n  )\n  const searchStr = `${NEXT_RSC_UNION_QUERY}=${cacheBustingHeader}`\n  // In dev mode, inject self.__next_r (request ID) so that HMR WebSocket\n  // and debug channel initialization don't crash. The static shell\n  // bypasses renderToFizzStream which normally injects this via\n  // bootstrapScriptContent.\n  const requestIdScript =\n    requestId !== null ? `self.__next_r=${JSON.stringify(requestId)};` : ''\n  const INSTANT_TEST_SCRIPT = `<script>${requestIdScript}self.__next_instant_test=fetch(location.pathname+'?${searchStr}',{credentials:'same-origin',headers:{'${RSC_HEADER}':'1','${NEXT_ROUTER_PREFETCH_HEADER}':'1','${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}':'${segmentPath}','${NEXT_INSTANT_PREFETCH_HEADER}':'1'}})</script>`\n\n  let didAlreadyInsert = false\n  return new TransformStream({\n    transform(chunk, controller) {\n      if (didAlreadyInsert) {\n        // Already inserted the script into the head. Pass through.\n        controller.enqueue(chunk)\n        return\n      }\n\n      // Find the opening <head tag (may have attributes like <head class=\"...\">)\n      const headOpenIndex = indexOfUint8Array(chunk, ENCODED_TAGS.OPENING.HEAD)\n\n      if (headOpenIndex === -1) {\n        controller.enqueue(chunk)\n        return\n      }\n\n      // Find the closing > of the <head ...> tag\n      const headCloseAngle = chunk.indexOf(\n        62, // '>'\n        headOpenIndex + ENCODED_TAGS.OPENING.HEAD.length\n      )\n      if (headCloseAngle === -1) {\n        controller.enqueue(chunk)\n        return\n      }\n\n      const encodedInsertion = encoder.encode(INSTANT_TEST_SCRIPT)\n      const insertionPoint = headCloseAngle + 1\n      // e.g.\n      // chunk = <!DOCTYPE html><html><head><meta charset=\"utf-8\">...\n      // insertion = <script>self.__next_instant_test=fetch(...)</script>\n      // output = <!DOCTYPE html><html><head> [ <script>...</script> ] <meta charset=\"utf-8\">...\n      const insertedHeadContent = new Uint8Array(\n        chunk.length + encodedInsertion.length\n      )\n      insertedHeadContent.set(chunk.slice(0, insertionPoint))\n      insertedHeadContent.set(encodedInsertion, insertionPoint)\n      insertedHeadContent.set(\n        chunk.slice(insertionPoint),\n        insertionPoint + encodedInsertion.length\n      )\n\n      controller.enqueue(insertedHeadContent)\n      didAlreadyInsert = true\n    },\n    flush(controller) {\n      // Append closing tags so the browser can parse the full document.\n      controller.enqueue(ENCODED_TAGS.CLOSED.BODY_AND_HTML)\n    },\n  })\n}\n\n// Suffix after main body content - scripts before </body>,\n// but wait for the major chunks to be enqueued.\nfunction createDeferredSuffixStream(\n  suffix: string\n): TransformStream<Uint8Array, Uint8Array> {\n  let flushed = false\n  let pending: DetachedPromise<void> | undefined\n\n  const flush = (controller: TransformStreamDefaultController) => {\n    const detached = new DetachedPromise<void>()\n    pending = detached\n\n    scheduleImmediate(() => {\n      try {\n        controller.enqueue(encoder.encode(suffix))\n      } catch {\n        // If an error occurs while enqueuing it can't be due to this\n        // transformers fault. It's likely due to the controller being\n        // errored due to the stream being cancelled.\n      } finally {\n        pending = undefined\n        detached.resolve()\n      }\n    })\n  }\n\n  return new TransformStream({\n    transform(chunk, controller) {\n      controller.enqueue(chunk)\n\n      // If we've already flushed, we're done.\n      if (flushed) return\n\n      // Schedule the flush to happen.\n      flushed = true\n      flush(controller)\n    },\n    flush(controller) {\n      if (pending) return pending.promise\n      if (flushed) return\n\n      // Flush now.\n      controller.enqueue(encoder.encode(suffix))\n    },\n  })\n}\n\nfunction createFlightDataInjectionTransformStream(\n  stream: ReadableStream<Uint8Array>,\n  delayDataUntilFirstHtmlChunk: boolean\n): TransformStream<Uint8Array, Uint8Array> {\n  let htmlStreamFinished = false\n\n  let pull: Promise<void> | null = null\n  let donePulling = false\n\n  function startOrContinuePulling(\n    controller: TransformStreamDefaultController\n  ) {\n    if (!pull) {\n      pull = startPulling(controller)\n    }\n    return pull\n  }\n\n  async function startPulling(controller: TransformStreamDefaultController) {\n    const reader = stream.getReader()\n\n    if (delayDataUntilFirstHtmlChunk) {\n      // NOTE: streaming flush\n      // We are buffering here for the inlined data stream because the\n      // \"shell\" stream might be chunkenized again by the underlying stream\n      // implementation, e.g. with a specific high-water mark. To ensure it's\n      // the safe timing to pipe the data stream, this extra tick is\n      // necessary.\n\n      // We don't start reading until we've left the current Task to ensure\n      // that it's inserted after flushing the shell. Note that this implementation\n      // might get stale if impl details of Fizz change in the future.\n      await atLeastOneTask()\n    }\n\n    try {\n      while (true) {\n        const { done, value } = await reader.read()\n        if (done) {\n          donePulling = true\n          return\n        }\n\n        // We want to prioritize HTML over RSC data.\n        // The SSR render is based on the same RSC stream, so when we get a new RSC chunk,\n        // we're likely to produce an HTML chunk as well, so give it a chance to flush first.\n        if (!delayDataUntilFirstHtmlChunk && !htmlStreamFinished) {\n          await atLeastOneTask()\n        }\n        controller.enqueue(value)\n      }\n    } catch (err) {\n      controller.error(err)\n    }\n  }\n\n  return new TransformStream({\n    start(controller) {\n      if (!delayDataUntilFirstHtmlChunk) {\n        startOrContinuePulling(controller)\n      }\n    },\n    transform(chunk, controller) {\n      controller.enqueue(chunk)\n\n      // Start the streaming if it hasn't already been started yet.\n      if (delayDataUntilFirstHtmlChunk) {\n        startOrContinuePulling(controller)\n      }\n    },\n    flush(controller) {\n      htmlStreamFinished = true\n      if (donePulling) {\n        return\n      }\n      return startOrContinuePulling(controller)\n    },\n  })\n}\n\nconst CLOSE_TAG = '</body></html>'\n\n/**\n * This transform stream moves the suffix to the end of the stream, so results\n * like `</body></html><script>...</script>` will be transformed to\n * `<script>...</script></body></html>`.\n */\nfunction createMoveSuffixStream(): TransformStream<Uint8Array, Uint8Array> {\n  let foundSuffix = false\n\n  return new TransformStream({\n    transform(chunk, controller) {\n      if (foundSuffix) {\n        return controller.enqueue(chunk)\n      }\n\n      const index = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.BODY_AND_HTML)\n      if (index > -1) {\n        foundSuffix = true\n\n        // If the whole chunk is the suffix, then don't write anything, it will\n        // be written in the flush.\n        if (chunk.length === ENCODED_TAGS.CLOSED.BODY_AND_HTML.length) {\n          return\n        }\n\n        // Write out the part before the suffix.\n        const before = chunk.slice(0, index)\n        controller.enqueue(before)\n\n        // In the case where the suffix is in the middle of the chunk, we need\n        // to split the chunk into two parts.\n        if (chunk.length > ENCODED_TAGS.CLOSED.BODY_AND_HTML.length + index) {\n          // Write out the part after the suffix.\n          const after = chunk.slice(\n            index + ENCODED_TAGS.CLOSED.BODY_AND_HTML.length\n          )\n          controller.enqueue(after)\n        }\n      } else {\n        controller.enqueue(chunk)\n      }\n    },\n    flush(controller) {\n      // Even if we didn't find the suffix, the HTML is not valid if we don't\n      // add it, so insert it at the end.\n      controller.enqueue(ENCODED_TAGS.CLOSED.BODY_AND_HTML)\n    },\n  })\n}\n\nfunction createStripDocumentClosingTagsTransform(): TransformStream<\n  Uint8Array,\n  Uint8Array\n> {\n  return new TransformStream({\n    transform(chunk, controller) {\n      // We rely on the assumption that chunks will never break across a code unit.\n      // This is reasonable because we currently concat all of React's output from a single\n      // flush into one chunk before streaming it forward which means the chunk will represent\n      // a single coherent utf-8 string. This is not safe to use if we change our streaming to no\n      // longer do this large buffered chunk\n      if (\n        isEquivalentUint8Arrays(chunk, ENCODED_TAGS.CLOSED.BODY_AND_HTML) ||\n        isEquivalentUint8Arrays(chunk, ENCODED_TAGS.CLOSED.BODY) ||\n        isEquivalentUint8Arrays(chunk, ENCODED_TAGS.CLOSED.HTML)\n      ) {\n        // the entire chunk is the closing tags; return without enqueueing anything.\n        return\n      }\n\n      // We assume these tags will go at together at the end of the document and that\n      // they won't appear anywhere else in the document. This is not really a safe assumption\n      // but until we revamp our streaming infra this is a performant way to string the tags\n      chunk = removeFromUint8Array(chunk, ENCODED_TAGS.CLOSED.BODY)\n      chunk = removeFromUint8Array(chunk, ENCODED_TAGS.CLOSED.HTML)\n\n      controller.enqueue(chunk)\n    },\n  })\n}\n\nfunction createHtmlDataDplIdTransformStream(\n  dplId: string\n): TransformStream<Uint8Array, Uint8Array> {\n  let didTransform = false\n\n  return new TransformStream({\n    transform(chunk, controller) {\n      if (didTransform) {\n        controller.enqueue(chunk)\n        return\n      }\n\n      const htmlTagIndex = indexOfUint8Array(chunk, ENCODED_TAGS.OPENING.HTML)\n      if (htmlTagIndex === -1) {\n        controller.enqueue(chunk)\n        return\n      }\n\n      // Insert the data-dpl-id attribute right after \"<html \"\n      const insertionPoint = htmlTagIndex + ENCODED_TAGS.OPENING.HTML.length\n      const attribute = ` data-dpl-id=\"${dplId}\"`\n      const encodedAttribute = encoder.encode(attribute)\n      const modifiedChunk = new Uint8Array(\n        chunk.length + encodedAttribute.length\n      )\n\n      // Copy everything before the insertion point\n      modifiedChunk.set(chunk.subarray(0, insertionPoint))\n      // Insert the attribute\n      modifiedChunk.set(encodedAttribute, insertionPoint)\n      // Copy everything after\n      modifiedChunk.set(\n        chunk.subarray(insertionPoint),\n        insertionPoint + encodedAttribute.length\n      )\n\n      controller.enqueue(modifiedChunk)\n      didTransform = true\n    },\n  })\n}\n\n/*\n * Checks if the root layout is missing the html or body tags\n * and if so, it will inject a script tag to throw an error in the browser, showing the user\n * the error message in the error overlay.\n */\nexport function createRootLayoutValidatorStream(): TransformStream<\n  Uint8Array,\n  Uint8Array\n> {\n  let foundHtml = false\n  let foundBody = false\n  return new TransformStream({\n    async transform(chunk, controller) {\n      // Peek into the streamed chunk to see if the tags are present.\n      if (\n        !foundHtml &&\n        indexOfUint8Array(chunk, ENCODED_TAGS.OPENING.HTML) > -1\n      ) {\n        foundHtml = true\n      }\n\n      if (\n        !foundBody &&\n        indexOfUint8Array(chunk, ENCODED_TAGS.OPENING.BODY) > -1\n      ) {\n        foundBody = true\n      }\n\n      controller.enqueue(chunk)\n    },\n    flush(controller) {\n      const missingTags: ('html' | 'body')[] = []\n      if (!foundHtml) missingTags.push('html')\n      if (!foundBody) missingTags.push('body')\n\n      if (!missingTags.length) return\n\n      controller.enqueue(\n        encoder.encode(\n          `<html id=\"__next_error__\">\n            <template\n              data-next-error-message=\"Missing ${missingTags\n                .map((c) => `<${c}>`)\n                .join(\n                  missingTags.length > 1 ? ' and ' : ''\n                )} tags in the root layout.\\nRead more at https://nextjs.org/docs/messages/missing-root-layout-tags\"\n              data-next-error-digest=\"${MISSING_ROOT_TAGS_ERROR}\"\n              data-next-error-stack=\"\"\n            ></template>\n          `\n        )\n      )\n    },\n  })\n}\n\nfunction chainTransformers<T>(\n  readable: ReadableStream<T>,\n  transformers: ReadonlyArray<TransformStream<T, T> | null>\n): ReadableStream<T> {\n  let stream = readable\n  for (const transformer of transformers) {\n    if (!transformer) continue\n\n    stream = stream.pipeThrough(transformer)\n  }\n  return stream\n}\n\nexport type ContinueStreamOptions = {\n  inlinedDataStream: ReadableStream<Uint8Array> | undefined\n  isStaticGeneration: boolean\n  deploymentId: string | undefined\n  getServerInsertedHTML: () => Promise<string>\n  getServerInsertedMetadata: () => Promise<string>\n  validateRootLayout?: boolean\n  /**\n   * Suffix to inject after the buffered data, but before the close tags.\n   */\n  suffix?: string | undefined\n}\n\nexport async function continueFizzStream(\n  renderStream: ReactDOMServerReadableStream,\n  {\n    suffix,\n    inlinedDataStream,\n    isStaticGeneration,\n    deploymentId,\n    getServerInsertedHTML,\n    getServerInsertedMetadata,\n    validateRootLayout,\n  }: ContinueStreamOptions\n): Promise<ReadableStream<Uint8Array>> {\n  // Suffix itself might contain close tags at the end, so we need to split it.\n  const suffixUnclosed = suffix ? suffix.split(CLOSE_TAG, 1)[0] : null\n\n  if (isStaticGeneration) {\n    // If we're generating static HTML we need to wait for it to resolve before continuing.\n    await renderStream.allReady\n  } else {\n    // Otherwise, we want to make sure Fizz is done with all microtasky work\n    // before we start pulling the stream and cause a flush.\n    await waitAtLeastOneReactRenderTask()\n  }\n\n  return chainTransformers(renderStream, [\n    // Buffer everything to avoid flushing too frequently\n    createBufferedTransformStream(),\n\n    // Insert data-dpl-id attribute on the html tag\n    deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,\n\n    // Transform metadata\n    createMetadataTransformStream(getServerInsertedMetadata),\n\n    // Insert suffix content\n    suffixUnclosed != null && suffixUnclosed.length > 0\n      ? createDeferredSuffixStream(suffixUnclosed)\n      : null,\n\n    // Insert the inlined data (Flight data, form state, etc.) stream into the HTML\n    inlinedDataStream\n      ? createFlightDataInjectionTransformStream(inlinedDataStream, true)\n      : null,\n\n    // Validate the root layout for missing html or body tags\n    validateRootLayout ? createRootLayoutValidatorStream() : null,\n\n    // Close tags should always be deferred to the end\n    createMoveSuffixStream(),\n\n    // Special head insertions\n    // TODO-APP: Insert server side html to end of head in app layout rendering, to avoid\n    // hydration errors. Remove this once it's ready to be handled by react itself.\n    createHeadInsertionTransformStream(getServerInsertedHTML),\n  ])\n}\n\ntype ContinueDynamicPrerenderOptions = {\n  getServerInsertedHTML: () => Promise<string>\n  getServerInsertedMetadata: () => Promise<string>\n  deploymentId: string | undefined\n}\n\nexport async function continueDynamicPrerender(\n  prerenderStream: ReadableStream<Uint8Array>,\n  {\n    getServerInsertedHTML,\n    getServerInsertedMetadata,\n    deploymentId,\n  }: ContinueDynamicPrerenderOptions\n) {\n  return chainTransformers(prerenderStream, [\n    // Buffer everything to avoid flushing too frequently\n    createBufferedTransformStream(),\n    createStripDocumentClosingTagsTransform(),\n    // Insert data-dpl-id attribute on the html tag\n    deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,\n    // Insert generated tags to head\n    createHeadInsertionTransformStream(getServerInsertedHTML),\n    // Transform metadata\n    createMetadataTransformStream(getServerInsertedMetadata),\n  ])\n}\n\ntype ContinueStaticPrerenderOptions = {\n  inlinedDataStream: ReadableStream<Uint8Array>\n  getServerInsertedHTML: () => Promise<string>\n  getServerInsertedMetadata: () => Promise<string>\n  deploymentId: string | undefined\n}\n\nexport async function continueStaticPrerender(\n  prerenderStream: ReadableStream<Uint8Array>,\n  {\n    inlinedDataStream,\n    getServerInsertedHTML,\n    getServerInsertedMetadata,\n    deploymentId,\n  }: ContinueStaticPrerenderOptions\n) {\n  return chainTransformers(prerenderStream, [\n    // Buffer everything to avoid flushing too frequently\n    createBufferedTransformStream(),\n    // Add build id comment to start of the HTML document (in export mode)\n    // Insert data-dpl-id attribute on the html tag\n    deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,\n    // Insert generated tags to head\n    createHeadInsertionTransformStream(getServerInsertedHTML),\n    // Transform metadata\n    createMetadataTransformStream(getServerInsertedMetadata),\n    // Insert the inlined data (Flight data, form state, etc.) stream into the HTML\n    createFlightDataInjectionTransformStream(inlinedDataStream, true),\n    // Close tags should always be deferred to the end\n    createMoveSuffixStream(),\n  ])\n}\n\nexport async function continueStaticFallbackPrerender(\n  prerenderStream: ReadableStream<Uint8Array>,\n  {\n    inlinedDataStream,\n    getServerInsertedHTML,\n    getServerInsertedMetadata,\n    deploymentId,\n  }: ContinueStaticPrerenderOptions\n) {\n  // Same as `continueStaticPrerender`, but also inserts an additional script\n  // to instruct the client to start fetching the hydration data as early\n  // as possible.\n  return chainTransformers(prerenderStream, [\n    // Buffer everything to avoid flushing too frequently\n    createBufferedTransformStream(),\n    // Insert data-dpl-id attribute on the html tag\n    deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,\n    // Insert generated tags to head\n    createHeadInsertionTransformStream(getServerInsertedHTML),\n    // Insert the client resume script into the head\n    createClientResumeScriptInsertionTransformStream(),\n    // Transform metadata\n    createMetadataTransformStream(getServerInsertedMetadata),\n    // Insert the inlined data (Flight data, form state, etc.) stream into the HTML\n    createFlightDataInjectionTransformStream(inlinedDataStream, true),\n    // Close tags should always be deferred to the end\n    createMoveSuffixStream(),\n  ])\n}\n\ntype ContinueResumeOptions = {\n  inlinedDataStream: ReadableStream<Uint8Array>\n  getServerInsertedHTML: () => Promise<string>\n  getServerInsertedMetadata: () => Promise<string>\n  delayDataUntilFirstHtmlChunk: boolean\n  deploymentId: string | undefined\n}\n\nexport async function continueDynamicHTMLResume(\n  renderStream: ReadableStream<Uint8Array>,\n  {\n    delayDataUntilFirstHtmlChunk,\n    inlinedDataStream,\n    getServerInsertedHTML,\n    getServerInsertedMetadata,\n    deploymentId,\n  }: ContinueResumeOptions\n) {\n  return chainTransformers(renderStream, [\n    // Buffer everything to avoid flushing too frequently\n    createBufferedTransformStream(),\n    // Insert data-dpl-id attribute on the html tag\n    deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,\n    // Insert generated tags to head\n    createHeadInsertionTransformStream(getServerInsertedHTML),\n    // Transform metadata\n    createMetadataTransformStream(getServerInsertedMetadata),\n    // Insert the inlined data (Flight data, form state, etc.) stream into the HTML\n    createFlightDataInjectionTransformStream(\n      inlinedDataStream,\n      delayDataUntilFirstHtmlChunk\n    ),\n    // Close tags should always be deferred to the end\n    createMoveSuffixStream(),\n  ])\n}\n\nexport function createDocumentClosingStream(): ReadableStream<Uint8Array> {\n  return streamFromString(CLOSE_TAG)\n}\n\n// ---------------------------------------------------------------------------\n// Runtime prefetch transform (Web streams)\n// ---------------------------------------------------------------------------\n\n/**\n * Web TransformStream that replaces the runtime prefetch sentinel in an RSC\n * payload stream: `[<sentinel>]` -> `[<isPartial>,<staleTime>]`.\n *\n * This is the web equivalent of createRuntimePrefetchNodeTransform\n * in node-stream-helpers.ts.\n */\nexport function createRuntimePrefetchTransformStream(\n  sentinel: number,\n  isPartial: boolean,\n  staleTime: number\n): TransformStream<Uint8Array, Uint8Array> {\n  const enc = new TextEncoder()\n\n  // Search for: [<sentinel>]\n  // Replace with: [<isPartial>,<staleTime>]\n  const search = enc.encode(`[${sentinel}]`)\n  const first = search[0]\n  const replace = enc.encode(`[${isPartial},${staleTime}]`)\n  const searchLen = search.length\n\n  let currentChunk: Uint8Array | null = null\n  let found = false\n\n  function processChunk(\n    controller: TransformStreamDefaultController<Uint8Array>,\n    nextChunk: null | Uint8Array\n  ) {\n    if (found) {\n      if (nextChunk) {\n        controller.enqueue(nextChunk)\n      }\n      return\n    }\n\n    if (currentChunk) {\n      // We can't search past the index that can contain a full match\n      let exclusiveUpperBound = currentChunk.length - (searchLen - 1)\n      if (nextChunk) {\n        // If we have any overflow bytes we can search up to the chunk's final byte\n        exclusiveUpperBound += Math.min(nextChunk.length, searchLen - 1)\n      }\n      if (exclusiveUpperBound < 1) {\n        // we can't match the current chunk.\n        controller.enqueue(currentChunk)\n        currentChunk = nextChunk // advance so we don't process this chunk again\n        return\n      }\n\n      let currentIndex = currentChunk.indexOf(first)\n\n      // check the current candidate match if it is within the bounds of our search space for the currentChunk\n      candidateLoop: while (\n        -1 < currentIndex &&\n        currentIndex < exclusiveUpperBound\n      ) {\n        // We already know index 0 matches because we used indexOf to find the candidateIndex so we start at index 1\n        let matchIndex = 1\n        while (matchIndex < searchLen) {\n          const candidateIndex = currentIndex + matchIndex\n          const candidateValue =\n            candidateIndex < currentChunk.length\n              ? currentChunk[candidateIndex]\n              : // if we ever hit this condition it is because there is a nextChunk we can read from\n                nextChunk![candidateIndex - currentChunk.length]\n          if (candidateValue !== search[matchIndex]) {\n            // No match, reset and continue the search from the next position\n            currentIndex = currentChunk.indexOf(first, currentIndex + 1)\n            continue candidateLoop\n          }\n          matchIndex++\n        }\n        // We found a complete match. currentIndex is our starting point to replace the value.\n        found = true\n        // enqueue everything up to the match\n        controller.enqueue(currentChunk.subarray(0, currentIndex))\n        // enqueue the replacement value\n        controller.enqueue(replace)\n        // If there are bytes in the currentChunk after the match enqueue them\n        if (currentIndex + searchLen < currentChunk.length) {\n          controller.enqueue(currentChunk.slice(currentIndex + searchLen))\n        }\n        // If we have a next chunk we enqueue it now\n        if (nextChunk) {\n          // if replacement spills over to the next chunk we first exclude the replaced bytes\n          const overflowBytes = currentIndex + searchLen - currentChunk.length\n          const truncatedChunk =\n            overflowBytes > 0 ? nextChunk!.subarray(overflowBytes) : nextChunk\n          controller.enqueue(truncatedChunk)\n        }\n        // We are now in found mode and don't need to track currentChunk anymore\n        currentChunk = null\n        return\n      }\n      // No match found in this chunk, emit it and wait for the next one\n      controller.enqueue(currentChunk)\n    }\n\n    // Advance to the next chunk\n    currentChunk = nextChunk\n  }\n\n  return new TransformStream<Uint8Array, Uint8Array>({\n    transform(chunk, controller) {\n      processChunk(controller, chunk)\n    },\n    flush(controller) {\n      processChunk(controller, null)\n    },\n  })\n}\n","export const ENCODED_TAGS = {\n  // opening tags do not have the closing `>` since they can contain other attributes such as `<body className=''>`\n  OPENING: {\n    // <html\n    HTML: new Uint8Array([60, 104, 116, 109, 108]),\n    // <head\n    HEAD: new Uint8Array([60, 104, 101, 97, 100]),\n    // <body\n    BODY: new Uint8Array([60, 98, 111, 100, 121]),\n  },\n  CLOSED: {\n    // </head>\n    HEAD: new Uint8Array([60, 47, 104, 101, 97, 100, 62]),\n    // </body>\n    BODY: new Uint8Array([60, 47, 98, 111, 100, 121, 62]),\n    // </html>\n    HTML: new Uint8Array([60, 47, 104, 116, 109, 108, 62]),\n    // </body></html>\n    BODY_AND_HTML: new Uint8Array([\n      60, 47, 98, 111, 100, 121, 62, 60, 47, 104, 116, 109, 108, 62,\n    ]),\n  },\n  META: {\n    // Only the match the prefix cause the suffix can be different wether it's xml compatible or not \">\" or \"/>\"\n    // <meta name=\"«nxt-icon»\"\n    // This is a special mark that will be replaced by the icon insertion script tag.\n    ICON_MARK: new Uint8Array([\n      60, 109, 101, 116, 97, 32, 110, 97, 109, 101, 61, 34, 194, 171, 110, 120,\n      116, 45, 105, 99, 111, 110, 194, 187, 34,\n    ]),\n  },\n} as const\n","import type { OutgoingHttpHeaders } from 'http'\nimport {\n  NEXT_INTERCEPTION_MARKER_PREFIX,\n  NEXT_QUERY_PARAM_PREFIX,\n} from '../../lib/constants'\n\n/**\n * Converts a Node.js IncomingHttpHeaders object to a Headers object. Any\n * headers with multiple values will be joined with a comma and space. Any\n * headers that have an undefined value will be ignored and others will be\n * coerced to strings.\n *\n * @param nodeHeaders the headers object to convert\n * @returns the converted headers object\n */\nexport function fromNodeOutgoingHttpHeaders(\n  nodeHeaders: OutgoingHttpHeaders\n): Headers {\n  const headers = new Headers()\n  for (let [key, value] of Object.entries(nodeHeaders)) {\n    const values = Array.isArray(value) ? value : [value]\n    for (let v of values) {\n      if (typeof v === 'undefined') continue\n      if (typeof v === 'number') {\n        v = v.toString()\n      }\n\n      headers.append(key, v)\n    }\n  }\n  return headers\n}\n\n/*\n  Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas\n  that are within a single set-cookie field-value, such as in the Expires portion.\n  This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2\n  Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128\n  React Native's fetch does this for *every* header, including set-cookie.\n  \n  Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25\n  Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation\n*/\nexport function splitCookiesString(cookiesString: string) {\n  var cookiesStrings = []\n  var pos = 0\n  var start\n  var ch\n  var lastComma\n  var nextStart\n  var cookiesSeparatorFound\n\n  function skipWhitespace() {\n    while (pos < cookiesString.length && /\\s/.test(cookiesString.charAt(pos))) {\n      pos += 1\n    }\n    return pos < cookiesString.length\n  }\n\n  function notSpecialChar() {\n    ch = cookiesString.charAt(pos)\n\n    return ch !== '=' && ch !== ';' && ch !== ','\n  }\n\n  while (pos < cookiesString.length) {\n    start = pos\n    cookiesSeparatorFound = false\n\n    while (skipWhitespace()) {\n      ch = cookiesString.charAt(pos)\n      if (ch === ',') {\n        // ',' is a cookie separator if we have later first '=', not ';' or ','\n        lastComma = pos\n        pos += 1\n\n        skipWhitespace()\n        nextStart = pos\n\n        while (pos < cookiesString.length && notSpecialChar()) {\n          pos += 1\n        }\n\n        // currently special character\n        if (pos < cookiesString.length && cookiesString.charAt(pos) === '=') {\n          // we found cookies separator\n          cookiesSeparatorFound = true\n          // pos is inside the next cookie, so back up and return it.\n          pos = nextStart\n          cookiesStrings.push(cookiesString.substring(start, lastComma))\n          start = pos\n        } else {\n          // in param ',' or param separator ';',\n          // we continue from that comma\n          pos = lastComma + 1\n        }\n      } else {\n        pos += 1\n      }\n    }\n\n    if (!cookiesSeparatorFound || pos >= cookiesString.length) {\n      cookiesStrings.push(cookiesString.substring(start, cookiesString.length))\n    }\n  }\n\n  return cookiesStrings\n}\n\n/**\n * Converts a Headers object to a Node.js OutgoingHttpHeaders object. This is\n * required to support the set-cookie header, which may have multiple values.\n *\n * @param headers the headers object to convert\n * @returns the converted headers object\n */\nexport function toNodeOutgoingHttpHeaders(\n  headers: Headers\n): OutgoingHttpHeaders {\n  const nodeHeaders: OutgoingHttpHeaders = {}\n  const cookies: string[] = []\n  if (headers) {\n    for (const [key, value] of headers.entries()) {\n      if (key.toLowerCase() === 'set-cookie') {\n        // We may have gotten a comma joined string of cookies, or multiple\n        // set-cookie headers. We need to merge them into one header array\n        // to represent all the cookies.\n        cookies.push(...splitCookiesString(value))\n        nodeHeaders[key] = cookies.length === 1 ? cookies[0] : cookies\n      } else {\n        nodeHeaders[key] = value\n      }\n    }\n  }\n  return nodeHeaders\n}\n\n/**\n * Validate the correctness of a user-provided URL.\n */\nexport function validateURL(url: string | URL): string {\n  try {\n    return String(new URL(String(url)))\n  } catch (error: any) {\n    throw new Error(\n      `URL is malformed \"${String(\n        url\n      )}\". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`,\n      { cause: error }\n    )\n  }\n}\n\n/**\n * Normalizes `nxtP` and `nxtI` query param values to remove the prefix.\n * This function does not mutate the input key.\n */\nexport function normalizeNextQueryParam(key: string): null | string {\n  const prefixes = [NEXT_QUERY_PARAM_PREFIX, NEXT_INTERCEPTION_MARKER_PREFIX]\n  for (const prefix of prefixes) {\n    if (key !== prefix && key.startsWith(prefix)) {\n      return key.substring(prefix.length)\n    }\n  }\n  return null\n}\n","/**\n * Removes the trailing slash for a given route or page path. Preserves the\n * root page. Examples:\n *   - `/foo/bar/` -> `/foo/bar`\n *   - `/foo/bar` -> `/foo/bar`\n *   - `/` -> `/`\n */\nexport function removeTrailingSlash(route: string) {\n  return route.replace(/\\/$/, '') || '/'\n}\n","/**\n * Given a path this function will find the pathname, query and hash and return\n * them. This is useful to parse full paths on the client side.\n * @param path A path to parse e.g. /foo/bar?id=1#hash\n */\nexport function parsePath(path: string) {\n  const hashIndex = path.indexOf('#')\n  const queryIndex = path.indexOf('?')\n  const hasQuery = queryIndex > -1 && (hashIndex < 0 || queryIndex < hashIndex)\n\n  if (hasQuery || hashIndex > -1) {\n    return {\n      pathname: path.substring(0, hasQuery ? queryIndex : hashIndex),\n      query: hasQuery\n        ? path.substring(queryIndex, hashIndex > -1 ? hashIndex : undefined)\n        : '',\n      hash: hashIndex > -1 ? path.slice(hashIndex) : '',\n    }\n  }\n\n  return { pathname: path, query: '', hash: '' }\n}\n","import { parsePath } from './parse-path'\n\n/**\n * Adds the provided prefix to the given path. It first ensures that the path\n * is indeed starting with a slash.\n */\nexport function addPathPrefix(path: string, prefix?: string) {\n  if (!path.startsWith('/') || !prefix) {\n    return path\n  }\n\n  const { pathname, query, hash } = parsePath(path)\n  return `${prefix}${pathname}${query}${hash}`\n}\n","import { parsePath } from './parse-path'\n\n/**\n * Similarly to `addPathPrefix`, this function adds a suffix at the end on the\n * provided path. It also works only for paths ensuring the argument starts\n * with a slash.\n */\nexport function addPathSuffix(path: string, suffix?: string) {\n  if (!path.startsWith('/') || !suffix) {\n    return path\n  }\n\n  const { pathname, query, hash } = parsePath(path)\n  return `${pathname}${suffix}${query}${hash}`\n}\n","import { parsePath } from './parse-path'\n\n/**\n * Checks if a given path starts with a given prefix. It ensures it matches\n * exactly without containing extra chars. e.g. prefix /docs should replace\n * for /docs, /docs/, /docs/a but not /docsss\n * @param path The path to check.\n * @param prefix The prefix to check against.\n */\nexport function pathHasPrefix(path: string, prefix: string) {\n  if (typeof path !== 'string') {\n    return false\n  }\n\n  const { pathname } = parsePath(path)\n  return pathname === prefix || pathname.startsWith(prefix + '/')\n}\n","import type { OutgoingHttpHeaders } from 'http'\n\n/**\n * Takes an object with a hostname property (like a parsed URL) and some\n * headers that may contain Host and returns the preferred hostname.\n * @param parsed An object containing a hostname property.\n * @param headers A dictionary with headers containing a `host`.\n */\nexport function getHostname(\n  parsed: { hostname?: string | null },\n  headers?: OutgoingHttpHeaders\n): string | undefined {\n  // Get the hostname from the headers if it exists, otherwise use the parsed\n  // hostname.\n  let hostname: string\n  if (headers?.host && !Array.isArray(headers.host)) {\n    hostname = headers.host.toString().split(':', 1)[0]\n  } else if (parsed.hostname) {\n    hostname = parsed.hostname\n  } else return\n\n  return hostname.toLowerCase()\n}\n","export interface PathLocale {\n  detectedLocale?: string\n  pathname: string\n}\n\n/**\n * A cache of lowercased locales for each list of locales. This is stored as a\n * WeakMap so if the locales are garbage collected, the cache entry will be\n * removed as well.\n */\nconst cache = new WeakMap<readonly string[], readonly string[]>()\n\n/**\n * For a pathname that may include a locale from a list of locales, it\n * removes the locale from the pathname returning it alongside with the\n * detected locale.\n *\n * @param pathname A pathname that may include a locale.\n * @param locales A list of locales.\n * @returns The detected locale and pathname without locale\n */\nexport function normalizeLocalePath(\n  pathname: string,\n  locales?: readonly string[]\n): PathLocale {\n  // If locales is undefined, return the pathname as is.\n  if (!locales) return { pathname }\n\n  // Get the cached lowercased locales or create a new cache entry.\n  let lowercasedLocales = cache.get(locales)\n  if (!lowercasedLocales) {\n    lowercasedLocales = locales.map((locale) => locale.toLowerCase())\n    cache.set(locales, lowercasedLocales)\n  }\n\n  let detectedLocale: string | undefined\n\n  // The first segment will be empty, because it has a leading `/`. If\n  // there is no further segment, there is no locale (or it's the default).\n  const segments = pathname.split('/', 2)\n\n  // If there's no second segment (ie, the pathname is just `/`), there's no\n  // locale.\n  if (!segments[1]) return { pathname }\n\n  // The second segment will contain the locale part if any.\n  const segment = segments[1].toLowerCase()\n\n  // See if the segment matches one of the locales. If it doesn't, there is\n  // no locale (or it's the default).\n  const index = lowercasedLocales.indexOf(segment)\n  if (index < 0) return { pathname }\n\n  // Return the case-sensitive locale.\n  detectedLocale = locales[index]\n\n  // Remove the `/${locale}` part of the pathname.\n  pathname = pathname.slice(detectedLocale.length + 1) || '/'\n\n  return { pathname, detectedLocale }\n}\n","import { pathHasPrefix } from './path-has-prefix'\n\n/**\n * Given a path and a prefix it will remove the prefix when it exists in the\n * given path. It ensures it matches exactly without containing extra chars\n * and if the prefix is not there it will be noop.\n *\n * @param path The path to remove the prefix from.\n * @param prefix The prefix to be removed.\n */\nexport function removePathPrefix(path: string, prefix: string): string {\n  // If the path doesn't start with the prefix we can return it as is. This\n  // protects us from situations where the prefix is a substring of the path\n  // prefix such as:\n  //\n  // For prefix: /blog\n  //\n  //   /blog -> true\n  //   /blog/ -> true\n  //   /blog/1 -> true\n  //   /blogging -> false\n  //   /blogging/ -> false\n  //   /blogging/1 -> false\n  if (!pathHasPrefix(path, prefix)) {\n    return path\n  }\n\n  // Remove the prefix from the path via slicing.\n  const withoutPrefix = path.slice(prefix.length)\n\n  // If the path without the prefix starts with a `/` we can return it as is.\n  if (withoutPrefix.startsWith('/')) {\n    return withoutPrefix\n  }\n\n  // If the path without the prefix doesn't start with a `/` we need to add it\n  // back to the path to make sure it's a valid path.\n  return `/${withoutPrefix}`\n}\n","import { normalizeLocalePath } from '../../i18n/normalize-locale-path'\nimport { removePathPrefix } from './remove-path-prefix'\nimport { pathHasPrefix } from './path-has-prefix'\nimport type { I18NProvider } from '../../../../server/lib/i18n-provider'\n\nexport interface NextPathnameInfo {\n  /**\n   * The base path in case the pathname included it.\n   */\n  basePath?: string\n  /**\n   * The buildId for when the parsed URL is a data URL. Parsing it can be\n   * disabled with the `parseData` option.\n   */\n  buildId?: string\n  /**\n   * If there was a locale in the pathname, this will hold its value.\n   */\n  locale?: string\n  /**\n   * The processed pathname without a base path, locale, or data URL elements\n   * when parsing it is enabled.\n   */\n  pathname: string\n  /**\n   * A boolean telling if the pathname had a trailingSlash. This can be only\n   * true if trailingSlash is enabled.\n   */\n  trailingSlash?: boolean\n}\n\ninterface Options {\n  /**\n   * When passed to true, this function will also parse Nextjs data URLs.\n   */\n  parseData?: boolean\n  /**\n   * A partial of the Next.js configuration to parse the URL.\n   */\n  nextConfig?: {\n    basePath?: string\n    i18n?: { locales?: readonly string[] } | null\n    trailingSlash?: boolean\n  }\n\n  /**\n   * If provided, this normalizer will be used to detect the locale instead of\n   * the default locale detection.\n   */\n  i18nProvider?: I18NProvider\n}\n\nexport function getNextPathnameInfo(\n  pathname: string,\n  options: Options\n): NextPathnameInfo {\n  const { basePath, i18n, trailingSlash } = options.nextConfig ?? {}\n  const info: NextPathnameInfo = {\n    pathname,\n    trailingSlash: pathname !== '/' ? pathname.endsWith('/') : trailingSlash,\n  }\n\n  if (basePath && pathHasPrefix(info.pathname, basePath)) {\n    info.pathname = removePathPrefix(info.pathname, basePath)\n    info.basePath = basePath\n  }\n  let pathnameNoDataPrefix = info.pathname\n\n  if (\n    info.pathname.startsWith('/_next/data/') &&\n    info.pathname.endsWith('.json')\n  ) {\n    const paths = info.pathname\n      .replace(/^\\/_next\\/data\\//, '')\n      .replace(/\\.json$/, '')\n      .split('/')\n\n    const buildId = paths[0]\n    info.buildId = buildId\n    pathnameNoDataPrefix =\n      paths[1] !== 'index' ? `/${paths.slice(1).join('/')}` : '/'\n\n    // update pathname with normalized if enabled although\n    // we use normalized to populate locale info still\n    if (options.parseData === true) {\n      info.pathname = pathnameNoDataPrefix\n    }\n  }\n\n  // If provided, use the locale route normalizer to detect the locale instead\n  // of the function below.\n  if (i18n) {\n    let result = options.i18nProvider\n      ? options.i18nProvider.analyze(info.pathname)\n      : normalizeLocalePath(info.pathname, i18n.locales)\n\n    info.locale = result.detectedLocale\n    info.pathname = result.pathname ?? info.pathname\n\n    if (!result.detectedLocale && info.buildId) {\n      result = options.i18nProvider\n        ? options.i18nProvider.analyze(pathnameNoDataPrefix)\n        : normalizeLocalePath(pathnameNoDataPrefix, i18n.locales)\n\n      if (result.detectedLocale) {\n        info.locale = result.detectedLocale\n      }\n    }\n  }\n  return info\n}\n","import type { OutgoingHttpHeaders } from 'http'\nimport type { DomainLocale, I18NConfig } from '../config-shared'\nimport type { I18NProvider } from '../lib/i18n-provider'\n\nimport { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale'\nimport { formatNextPathnameInfo } from '../../shared/lib/router/utils/format-next-pathname-info'\nimport { getHostname } from '../../shared/lib/get-hostname'\nimport { getNextPathnameInfo } from '../../shared/lib/router/utils/get-next-pathname-info'\n\ninterface Options {\n  base?: string | URL\n  headers?: OutgoingHttpHeaders\n  forceLocale?: boolean\n  nextConfig?: {\n    basePath?: string\n    i18n?: I18NConfig | null\n    trailingSlash?: boolean\n  }\n  i18nProvider?: I18NProvider\n}\n\nconst REGEX_LOCALHOST_HOSTNAME =\n  /^(?:127(?:\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|\\[::1\\]|localhost)$/\n\nfunction parseURL(url: string | URL, base?: string | URL) {\n  const parsed = new URL(String(url), base && String(base))\n  if (REGEX_LOCALHOST_HOSTNAME.test(parsed.hostname)) {\n    parsed.hostname = 'localhost'\n  }\n  return parsed\n}\n\nconst Internal = Symbol('NextURLInternal')\n\nexport class NextURL {\n  private [Internal]: {\n    basePath: string\n    buildId?: string\n    flightSearchParameters?: Record<string, string>\n    defaultLocale?: string\n    domainLocale?: DomainLocale\n    locale?: string\n    options: Options\n    trailingSlash?: boolean\n    url: URL\n  }\n\n  constructor(input: string | URL, base?: string | URL, opts?: Options)\n  constructor(input: string | URL, opts?: Options)\n  constructor(\n    input: string | URL,\n    baseOrOpts?: string | URL | Options,\n    opts?: Options\n  ) {\n    let base: undefined | string | URL\n    let options: Options\n\n    if (\n      (typeof baseOrOpts === 'object' && 'pathname' in baseOrOpts) ||\n      typeof baseOrOpts === 'string'\n    ) {\n      base = baseOrOpts\n      options = opts || {}\n    } else {\n      options = opts || baseOrOpts || {}\n    }\n\n    this[Internal] = {\n      url: parseURL(input, base ?? options.base),\n      options: options,\n      basePath: '',\n    }\n\n    this.analyze()\n  }\n\n  private analyze() {\n    const info = getNextPathnameInfo(this[Internal].url.pathname, {\n      nextConfig: this[Internal].options.nextConfig,\n      parseData: !process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE,\n      i18nProvider: this[Internal].options.i18nProvider,\n    })\n\n    const hostname = getHostname(\n      this[Internal].url,\n      this[Internal].options.headers\n    )\n    this[Internal].domainLocale = this[Internal].options.i18nProvider\n      ? this[Internal].options.i18nProvider.detectDomainLocale(hostname)\n      : detectDomainLocale(\n          this[Internal].options.nextConfig?.i18n?.domains,\n          hostname\n        )\n\n    const defaultLocale =\n      this[Internal].domainLocale?.defaultLocale ||\n      this[Internal].options.nextConfig?.i18n?.defaultLocale\n\n    this[Internal].url.pathname = info.pathname\n    this[Internal].defaultLocale = defaultLocale\n    this[Internal].basePath = info.basePath ?? ''\n    this[Internal].buildId = info.buildId\n    this[Internal].locale = info.locale ?? defaultLocale\n    this[Internal].trailingSlash = info.trailingSlash\n  }\n\n  private formatPathname() {\n    return formatNextPathnameInfo({\n      basePath: this[Internal].basePath,\n      buildId: this[Internal].buildId,\n      defaultLocale: !this[Internal].options.forceLocale\n        ? this[Internal].defaultLocale\n        : undefined,\n      locale: this[Internal].locale,\n      pathname: this[Internal].url.pathname,\n      trailingSlash: this[Internal].trailingSlash,\n    })\n  }\n\n  private formatSearch() {\n    return this[Internal].url.search\n  }\n\n  public get buildId() {\n    return this[Internal].buildId\n  }\n\n  public set buildId(buildId: string | undefined) {\n    this[Internal].buildId = buildId\n  }\n\n  public get locale() {\n    return this[Internal].locale ?? ''\n  }\n\n  public set locale(locale: string) {\n    if (\n      !this[Internal].locale ||\n      !this[Internal].options.nextConfig?.i18n?.locales.includes(locale)\n    ) {\n      throw new TypeError(\n        `The NextURL configuration includes no locale \"${locale}\"`\n      )\n    }\n\n    this[Internal].locale = locale\n  }\n\n  get defaultLocale() {\n    return this[Internal].defaultLocale\n  }\n\n  get domainLocale() {\n    return this[Internal].domainLocale\n  }\n\n  get searchParams() {\n    return this[Internal].url.searchParams\n  }\n\n  get host() {\n    return this[Internal].url.host\n  }\n\n  set host(value: string) {\n    this[Internal].url.host = value\n  }\n\n  get hostname() {\n    return this[Internal].url.hostname\n  }\n\n  set hostname(value: string) {\n    this[Internal].url.hostname = value\n  }\n\n  get port() {\n    return this[Internal].url.port\n  }\n\n  set port(value: string) {\n    this[Internal].url.port = value\n  }\n\n  get protocol() {\n    return this[Internal].url.protocol\n  }\n\n  set protocol(value: string) {\n    this[Internal].url.protocol = value\n  }\n\n  get href() {\n    const pathname = this.formatPathname()\n    const search = this.formatSearch()\n    return `${this.protocol}//${this.host}${pathname}${search}${this.hash}`\n  }\n\n  set href(url: string) {\n    this[Internal].url = parseURL(url)\n    this.analyze()\n  }\n\n  get origin() {\n    return this[Internal].url.origin\n  }\n\n  get pathname() {\n    return this[Internal].url.pathname\n  }\n\n  set pathname(value: string) {\n    this[Internal].url.pathname = value\n  }\n\n  get hash() {\n    return this[Internal].url.hash\n  }\n\n  set hash(value: string) {\n    this[Internal].url.hash = value\n  }\n\n  get search() {\n    return this[Internal].url.search\n  }\n\n  set search(value: string) {\n    this[Internal].url.search = value\n  }\n\n  get password() {\n    return this[Internal].url.password\n  }\n\n  set password(value: string) {\n    this[Internal].url.password = value\n  }\n\n  get username() {\n    return this[Internal].url.username\n  }\n\n  set username(value: string) {\n    this[Internal].url.username = value\n  }\n\n  get basePath() {\n    return this[Internal].basePath\n  }\n\n  set basePath(value: string) {\n    this[Internal].basePath = value.startsWith('/') ? value : `/${value}`\n  }\n\n  toString() {\n    return this.href\n  }\n\n  toJSON() {\n    return this.href\n  }\n\n  [Symbol.for('edge-runtime.inspect.custom')]() {\n    return {\n      href: this.href,\n      origin: this.origin,\n      protocol: this.protocol,\n      username: this.username,\n      password: this.password,\n      host: this.host,\n      hostname: this.hostname,\n      port: this.port,\n      pathname: this.pathname,\n      search: this.search,\n      searchParams: this.searchParams,\n      hash: this.hash,\n    }\n  }\n\n  clone() {\n    return new NextURL(String(this), this[Internal].options)\n  }\n}\n","import type { DomainLocale } from '../../../server/config-shared'\n\nexport function detectDomainLocale(\n  domainItems?: readonly DomainLocale[],\n  hostname?: string,\n  detectedLocale?: string\n) {\n  if (!domainItems) return\n\n  if (detectedLocale) {\n    detectedLocale = detectedLocale.toLowerCase()\n  }\n\n  for (const item of domainItems) {\n    // remove port if present\n    const domainHostname = item.domain?.split(':', 1)[0].toLowerCase()\n    if (\n      hostname === domainHostname ||\n      detectedLocale === item.defaultLocale.toLowerCase() ||\n      item.locales?.some((locale) => locale.toLowerCase() === detectedLocale)\n    ) {\n      return item\n    }\n  }\n}\n","import type { NextPathnameInfo } from './get-next-pathname-info'\nimport { removeTrailingSlash } from './remove-trailing-slash'\nimport { addPathPrefix } from './add-path-prefix'\nimport { addPathSuffix } from './add-path-suffix'\nimport { addLocale } from './add-locale'\n\ninterface ExtendedInfo extends NextPathnameInfo {\n  defaultLocale?: string\n  ignorePrefix?: boolean\n}\n\nexport function formatNextPathnameInfo(info: ExtendedInfo) {\n  let pathname = addLocale(\n    info.pathname,\n    info.locale,\n    info.buildId ? undefined : info.defaultLocale,\n    info.ignorePrefix\n  )\n\n  if (info.buildId || !info.trailingSlash) {\n    pathname = removeTrailingSlash(pathname)\n  }\n\n  if (info.buildId) {\n    pathname = addPathSuffix(\n      addPathPrefix(pathname, `/_next/data/${info.buildId}`),\n      info.pathname === '/' ? 'index.json' : '.json'\n    )\n  }\n\n  pathname = addPathPrefix(pathname, info.basePath)\n  return !info.buildId && info.trailingSlash\n    ? !pathname.endsWith('/')\n      ? addPathSuffix(pathname, '/')\n      : pathname\n    : removeTrailingSlash(pathname)\n}\n","import { addPathPrefix } from './add-path-prefix'\nimport { pathHasPrefix } from './path-has-prefix'\n\n/**\n * For a given path and a locale, if the locale is given, it will prefix the\n * locale. The path shouldn't be an API path. If a default locale is given the\n * prefix will be omitted if the locale is already the default locale.\n */\nexport function addLocale(\n  path: string,\n  locale?: string | false,\n  defaultLocale?: string,\n  ignorePrefix?: boolean\n) {\n  // If no locale was given or the locale is the default locale, we don't need\n  // to prefix the path.\n  if (!locale || locale === defaultLocale) return path\n\n  const lower = path.toLowerCase()\n\n  // If the path is an API path or the path already has the locale prefix, we\n  // don't need to prefix the path.\n  if (!ignorePrefix) {\n    if (pathHasPrefix(lower, '/api')) return path\n    if (pathHasPrefix(lower, `/${locale.toLowerCase()}`)) return path\n  }\n\n  // Add the locale prefix to the path.\n  return addPathPrefix(path, `/${locale}`)\n}\n","export class PageSignatureError extends Error {\n  constructor({ page }: { page: string }) {\n    super(`The middleware \"${page}\" accepts an async API directly with the form:\n  \n  export function middleware(request, event) {\n    return NextResponse.redirect('/new-location')\n  }\n  \n  Read more: https://nextjs.org/docs/messages/middleware-new-signature\n  `)\n  }\n}\n\nexport class RemovedPageError extends Error {\n  constructor() {\n    super(`The request.page has been deprecated in favour of \\`URLPattern\\`.\n  Read more: https://nextjs.org/docs/messages/middleware-request-page\n  `)\n  }\n}\n\nexport class RemovedUAError extends Error {\n  constructor() {\n    super(`The request.ua has been removed in favour of \\`userAgent\\` function.\n  Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent\n  `)\n  }\n}\n","import type { I18NConfig } from '../../config-shared'\nimport { NextURL } from '../next-url'\nimport { toNodeOutgoingHttpHeaders, validateURL } from '../utils'\nimport { RemovedUAError, RemovedPageError } from '../error'\nimport { RequestCookies } from './cookies'\n\nexport const INTERNALS = Symbol('internal request')\n\n/**\n * This class extends the [Web `Request` API](https://developer.mozilla.org/docs/Web/API/Request) with additional convenience methods.\n *\n * Read more: [Next.js Docs: `NextRequest`](https://nextjs.org/docs/app/api-reference/functions/next-request)\n */\nexport class NextRequest extends Request {\n  /** @internal */\n  [INTERNALS]: {\n    cookies: RequestCookies\n    url: string\n    nextUrl: NextURL\n  }\n\n  constructor(input: URL | RequestInfo, init: RequestInit = {}) {\n    const url =\n      typeof input !== 'string' && 'url' in input ? input.url : String(input)\n\n    validateURL(url)\n\n    // node Request instance requires duplex option when a body\n    // is present or it errors, we don't handle this for\n    // Request being passed in since it would have already\n    // errored if this wasn't configured\n    if (process.env.NEXT_RUNTIME !== 'edge') {\n      if (init.body && init.duplex !== 'half') {\n        init.duplex = 'half'\n      }\n    }\n\n    if (input instanceof Request) super(input, init)\n    else super(url, init)\n\n    const nextUrl = new NextURL(url, {\n      headers: toNodeOutgoingHttpHeaders(this.headers),\n      nextConfig: init.nextConfig,\n    })\n    this[INTERNALS] = {\n      cookies: new RequestCookies(this.headers),\n      nextUrl,\n      url: process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE\n        ? url\n        : nextUrl.toString(),\n    }\n  }\n\n  [Symbol.for('edge-runtime.inspect.custom')]() {\n    return {\n      cookies: this.cookies,\n      nextUrl: this.nextUrl,\n      url: this.url,\n      // rest of props come from Request\n      bodyUsed: this.bodyUsed,\n      cache: this.cache,\n      credentials: this.credentials,\n      destination: this.destination,\n      headers: Object.fromEntries(this.headers),\n      integrity: this.integrity,\n      keepalive: this.keepalive,\n      method: this.method,\n      mode: this.mode,\n      redirect: this.redirect,\n      referrer: this.referrer,\n      referrerPolicy: this.referrerPolicy,\n      signal: this.signal,\n    }\n  }\n\n  public get cookies() {\n    return this[INTERNALS].cookies\n  }\n\n  public get nextUrl() {\n    return this[INTERNALS].nextUrl\n  }\n\n  /**\n   * @deprecated\n   * `page` has been deprecated in favour of `URLPattern`.\n   * Read more: https://nextjs.org/docs/messages/middleware-request-page\n   */\n  public get page() {\n    throw new RemovedPageError()\n  }\n\n  /**\n   * @deprecated\n   * `ua` has been removed in favour of \\`userAgent\\` function.\n   * Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent\n   */\n  public get ua() {\n    throw new RemovedUAError()\n  }\n\n  public get url() {\n    return this[INTERNALS].url\n  }\n}\n\nexport interface RequestInit extends globalThis.RequestInit {\n  nextConfig?: {\n    basePath?: string\n    i18n?: I18NConfig | null\n    trailingSlash?: boolean\n  }\n  signal?: AbortSignal\n  // see https://github.com/whatwg/fetch/pull/1457\n  duplex?: 'half'\n}\n","import type { BaseNextRequest } from '../../../base-http'\nimport type { NodeNextRequest } from '../../../base-http/node'\nimport type { WebNextRequest } from '../../../base-http/web'\nimport type { Writable } from 'node:stream'\n\nimport { getRequestMeta } from '../../../request-meta'\nimport { fromNodeOutgoingHttpHeaders } from '../../utils'\nimport { NextRequest } from '../request'\nimport { isNodeNextRequest, isWebNextRequest } from '../../../base-http/helpers'\n\nexport const ResponseAbortedName = 'ResponseAborted'\nexport class ResponseAborted extends Error {\n  public readonly name = ResponseAbortedName\n}\n\n/**\n * Creates an AbortController tied to the closing of a ServerResponse (or other\n * appropriate Writable).\n *\n * If the `close` event is fired before the `finish` event, then we'll send the\n * `abort` signal.\n */\nexport function createAbortController(response: Writable): AbortController {\n  const controller = new AbortController()\n\n  // If `finish` fires first, then `res.end()` has been called and the close is\n  // just us finishing the stream on our side. If `close` fires first, then we\n  // know the client disconnected before we finished.\n  response.once('close', () => {\n    if (response.writableFinished) return\n\n    controller.abort(new ResponseAborted())\n  })\n\n  return controller\n}\n\n/**\n * Creates an AbortSignal tied to the closing of a ServerResponse (or other\n * appropriate Writable).\n *\n * This cannot be done with the request (IncomingMessage or Readable) because\n * the `abort` event will not fire if to data has been fully read (because that\n * will \"close\" the readable stream and nothing fires after that).\n */\nexport function signalFromNodeResponse(response: Writable): AbortSignal {\n  const { errored, destroyed } = response\n  if (errored || destroyed) {\n    return AbortSignal.abort(errored ?? new ResponseAborted())\n  }\n\n  const { signal } = createAbortController(response)\n  return signal\n}\n\nexport class NextRequestAdapter {\n  public static fromBaseNextRequest(\n    request: BaseNextRequest,\n    signal: AbortSignal\n  ): NextRequest {\n    if (\n      // The type check here ensures that `req` is correctly typed, and the\n      // environment variable check provides dead code elimination.\n      process.env.NEXT_RUNTIME === 'edge' &&\n      isWebNextRequest(request)\n    ) {\n      return NextRequestAdapter.fromWebNextRequest(request)\n    } else if (\n      // The type check here ensures that `req` is correctly typed, and the\n      // environment variable check provides dead code elimination.\n      process.env.NEXT_RUNTIME !== 'edge' &&\n      isNodeNextRequest(request)\n    ) {\n      return NextRequestAdapter.fromNodeNextRequest(request, signal)\n    } else {\n      throw new Error('Invariant: Unsupported NextRequest type')\n    }\n  }\n\n  public static fromNodeNextRequest(\n    request: NodeNextRequest,\n    signal: AbortSignal\n  ): NextRequest {\n    // HEAD and GET requests can not have a body.\n    let body: BodyInit | null = null\n    if (request.method !== 'GET' && request.method !== 'HEAD' && request.body) {\n      // @ts-expect-error - this is handled by undici, when streams/web land use it instead\n      body = request.body\n    }\n\n    let url: URL\n    if (request.url.startsWith('http')) {\n      url = new URL(request.url)\n    } else {\n      // Grab the full URL from the request metadata.\n      const base = getRequestMeta(request, 'initURL')\n      if (!base || !base.startsWith('http')) {\n        // Because the URL construction relies on the fact that the URL provided\n        // is absolute, we need to provide a base URL. We can't use the request\n        // URL because it's relative, so we use a dummy URL instead.\n        url = new URL(request.url, 'http://n')\n      } else {\n        url = new URL(request.url, base)\n      }\n    }\n\n    return new NextRequest(url, {\n      method: request.method,\n      headers: fromNodeOutgoingHttpHeaders(request.headers),\n      duplex: 'half',\n      signal,\n      // geo\n      // ip\n      // nextConfig\n\n      // body can not be passed if request was aborted\n      // or we get a Request body was disturbed error\n      ...(signal.aborted\n        ? {}\n        : {\n            body,\n          }),\n    })\n  }\n\n  public static fromWebNextRequest(request: WebNextRequest): NextRequest {\n    // HEAD and GET requests can not have a body.\n    let body: ReadableStream | null = null\n    if (request.method !== 'GET' && request.method !== 'HEAD') {\n      body = request.body\n    }\n\n    return new NextRequest(request.url, {\n      method: request.method,\n      headers: fromNodeOutgoingHttpHeaders(request.headers),\n      duplex: 'half',\n      signal: request.request.signal,\n      // geo\n      // ip\n      // nextConfig\n\n      // body can not be passed if request was aborted\n      // or we get a Request body was disturbed error\n      ...(request.request.signal.aborted\n        ? {}\n        : {\n            body,\n          }),\n    })\n  }\n}\n","/**\n * A `Promise.withResolvers` implementation that exposes the `resolve` and\n * `reject` functions on a `Promise`.\n *\n * @see https://tc39.es/proposal-promise-with-resolvers/\n */\nexport class DetachedPromise<T = any> {\n  public readonly resolve: (value: T | PromiseLike<T>) => void\n  public readonly reject: (reason: any) => void\n  public readonly promise: Promise<T>\n\n  constructor() {\n    let resolve: (value: T | PromiseLike<T>) => void\n    let reject: (reason: any) => void\n\n    // Create the promise and assign the resolvers to the object.\n    this.promise = new Promise<T>((res, rej) => {\n      resolve = res\n      reject = rej\n    })\n\n    // We know that resolvers is defined because the Promise constructor runs\n    // synchronously.\n    this.resolve = resolve!\n    this.reject = reject!\n  }\n}\n","import type { AppPageModule } from './route-modules/app-page/module'\n\n// Combined load times for loading client components\nlet clientComponentLoadStart = 0\nlet clientComponentLoadTimes = 0\nlet clientComponentLoadCount = 0\n\nexport function wrapClientComponentLoader(\n  ComponentMod: AppPageModule\n): AppPageModule['__next_app__'] {\n  if (!('performance' in globalThis)) {\n    return ComponentMod.__next_app__\n  }\n\n  return {\n    require: (...args) => {\n      const startTime = performance.now()\n\n      if (clientComponentLoadStart === 0) {\n        clientComponentLoadStart = startTime\n      }\n\n      try {\n        clientComponentLoadCount += 1\n        return ComponentMod.__next_app__.require(...args)\n      } finally {\n        clientComponentLoadTimes += performance.now() - startTime\n      }\n    },\n    loadChunk: (...args) => {\n      const startTime = performance.now()\n      const result = ComponentMod.__next_app__.loadChunk(...args)\n      // Avoid wrapping `loadChunk`'s result in an extra promise in case something like React depends on its identity.\n      // We only need to know when it's settled.\n      result.finally(() => {\n        clientComponentLoadTimes += performance.now() - startTime\n      })\n      return result\n    },\n  }\n}\n\nexport function getClientComponentLoaderMetrics(\n  options: { reset?: boolean } = {}\n) {\n  const metrics =\n    clientComponentLoadStart === 0\n      ? undefined\n      : {\n          clientComponentLoadStart,\n          clientComponentLoadTimes,\n          clientComponentLoadCount,\n        }\n\n  if (options.reset) {\n    clientComponentLoadStart = 0\n    clientComponentLoadTimes = 0\n    clientComponentLoadCount = 0\n  }\n\n  return metrics\n}\n","import type { ServerResponse } from 'node:http'\n\nimport {\n  ResponseAbortedName,\n  createAbortController,\n} from './web/spec-extension/adapters/next-request'\nimport { DetachedPromise } from '../lib/detached-promise'\nimport { getTracer } from './lib/trace/tracer'\nimport { NextNodeServerSpan } from './lib/trace/constants'\nimport { getClientComponentLoaderMetrics } from './client-component-renderer-logger'\n\nexport function isAbortError(e: any): e is Error & { name: 'AbortError' } {\n  return e?.name === 'AbortError' || e?.name === ResponseAbortedName\n}\n\nfunction createWriterFromResponse(\n  res: ServerResponse,\n  waitUntilForEnd?: Promise<unknown>\n): WritableStream<Uint8Array> {\n  let started = false\n\n  // Create a promise that will resolve once the response has drained. See\n  // https://nodejs.org/api/stream.html#stream_event_drain\n  let drained = new DetachedPromise<void>()\n  function onDrain() {\n    drained.resolve()\n  }\n  res.on('drain', onDrain)\n\n  // If the finish event fires, it means we shouldn't block and wait for the\n  // drain event.\n  res.once('close', () => {\n    res.off('drain', onDrain)\n    drained.resolve()\n  })\n\n  // Create a promise that will resolve once the response has finished. See\n  // https://nodejs.org/api/http.html#event-finish_1\n  const finished = new DetachedPromise<void>()\n  res.once('finish', () => {\n    finished.resolve()\n  })\n\n  // Create a writable stream that will write to the response.\n  return new WritableStream<Uint8Array>({\n    write: async (chunk) => {\n      // You'd think we'd want to use `start` instead of placing this in `write`\n      // but this ensures that we don't actually flush the headers until we've\n      // started writing chunks.\n      if (!started) {\n        started = true\n\n        if (\n          'performance' in globalThis &&\n          process.env.NEXT_OTEL_PERFORMANCE_PREFIX\n        ) {\n          const metrics = getClientComponentLoaderMetrics()\n          if (metrics) {\n            performance.measure(\n              `${process.env.NEXT_OTEL_PERFORMANCE_PREFIX}:next-client-component-loading`,\n              {\n                start: metrics.clientComponentLoadStart,\n                end:\n                  metrics.clientComponentLoadStart +\n                  metrics.clientComponentLoadTimes,\n              }\n            )\n          }\n        }\n\n        res.flushHeaders()\n        getTracer().trace(\n          NextNodeServerSpan.startResponse,\n          {\n            spanName: 'start response',\n          },\n          () => undefined\n        )\n      }\n\n      try {\n        const ok = res.write(chunk)\n\n        // Added by the `compression` middleware, this is a function that will\n        // flush the partially-compressed response to the client.\n        if ('flush' in res && typeof res.flush === 'function') {\n          res.flush()\n        }\n\n        // If the write returns false, it means there's some backpressure, so\n        // wait until it's streamed before continuing.\n        if (!ok) {\n          await drained.promise\n\n          // Reset the drained promise so that we can wait for the next drain event.\n          drained = new DetachedPromise<void>()\n        }\n      } catch (err) {\n        res.end()\n        throw new Error('failed to write chunk to response', { cause: err })\n      }\n    },\n    abort: (err) => {\n      if (res.writableFinished) return\n\n      res.destroy(err)\n    },\n    close: async () => {\n      // if a waitUntil promise was passed, wait for it to resolve before\n      // ending the response.\n      if (waitUntilForEnd) {\n        await waitUntilForEnd\n      }\n\n      if (res.writableFinished) return\n\n      res.end()\n      return finished.promise\n    },\n  })\n}\n\nexport async function pipeToNodeResponse(\n  readable: ReadableStream<Uint8Array>,\n  res: ServerResponse,\n  waitUntilForEnd?: Promise<unknown>\n) {\n  try {\n    // If the response has already errored, then just return now.\n    const { errored, destroyed } = res\n    if (errored || destroyed) return\n\n    // Create a new AbortController so that we can abort the readable if the\n    // client disconnects.\n    const controller = createAbortController(res)\n\n    const writer = createWriterFromResponse(res, waitUntilForEnd)\n\n    await readable.pipeTo(writer, { signal: controller.signal })\n  } catch (err: any) {\n    // If this isn't related to an abort error, re-throw it.\n    if (isAbortError(err)) return\n\n    throw new Error('failed to pipe response', { cause: err })\n  }\n}\n","import type { OutgoingHttpHeaders, ServerResponse } from 'http'\nimport type { CacheControl } from './lib/cache-control'\nimport type { FetchMetrics } from './base-http'\nimport type { PrefetchHints } from '../shared/lib/app-router-types'\n\nimport {\n  chainStreams,\n  streamFromBuffer,\n  streamFromString,\n  streamToString,\n} from './stream-utils/node-web-streams-helper'\nimport { isAbortError, pipeToNodeResponse } from './pipe-readable'\nimport type { RenderResumeDataCache } from './resume-data-cache/resume-data-cache'\nimport { InvariantError } from '../shared/lib/invariant-error'\nimport type {\n  HTML_CONTENT_TYPE_HEADER,\n  JSON_CONTENT_TYPE_HEADER,\n  TEXT_PLAIN_CONTENT_TYPE_HEADER,\n} from '../lib/constants'\nimport type { RSC_CONTENT_TYPE_HEADER } from '../client/components/app-router-headers'\n\ntype ContentTypeOption =\n  | typeof RSC_CONTENT_TYPE_HEADER // For App Page RSC responses\n  | typeof HTML_CONTENT_TYPE_HEADER // For App Page, Pages HTML responses\n  | typeof JSON_CONTENT_TYPE_HEADER // For API routes, Next.js data requests\n  | typeof TEXT_PLAIN_CONTENT_TYPE_HEADER // For simplified errors\n\nexport type AppPageRenderResultMetadata = {\n  flightData?: Buffer\n  cacheControl?: CacheControl\n  staticBailoutInfo?: {\n    stack?: string\n    description?: string\n  }\n\n  /**\n   * The postponed state if the render had postponed and needs to be resumed.\n   */\n  postponed?: string\n\n  /**\n   * The headers to set on the response that were added by the render.\n   */\n  headers?: OutgoingHttpHeaders\n  statusCode?: number\n  fetchTags?: string\n  fetchMetrics?: FetchMetrics\n\n  segmentData?: Map<string, Buffer>\n\n  /**\n   * Per-route prefetch hints computed at build time (e.g. segment inlining\n   * decisions based on gzip sizes). Written to prefetch-hints.json by the\n   * build pipeline.\n   */\n  prefetchHints?: PrefetchHints\n\n  /**\n   * In development, the resume data cache is warmed up before the render. This\n   * is attached to the metadata so that it can be used during the render. When\n   * prerendering, the filled resume data cache is also attached to the metadata\n   * so that it can be used when prerendering matching fallback shells.\n   */\n  renderResumeDataCache?: RenderResumeDataCache\n}\n\nexport type PagesRenderResultMetadata = {\n  pageData?: any\n  cacheControl?: CacheControl\n  assetQueryString?: string\n  mutableAssetQueryString?: string\n  isNotFound?: boolean\n  isRedirect?: boolean\n}\n\nexport type StaticRenderResultMetadata = {}\n\nexport type RenderResultMetadata = AppPageRenderResultMetadata &\n  PagesRenderResultMetadata &\n  StaticRenderResultMetadata\n\nexport type RenderResultResponse =\n  | ReadableStream<Uint8Array>[]\n  | ReadableStream<Uint8Array>\n  | string\n  | Buffer\n  | null\n\nexport type RenderResultOptions<\n  Metadata extends RenderResultMetadata = RenderResultMetadata,\n> = {\n  contentType: ContentTypeOption | null\n  waitUntil?: Promise<unknown>\n  metadata: Metadata\n}\n\nexport default class RenderResult<\n  Metadata extends RenderResultMetadata = RenderResultMetadata,\n> {\n  /**\n   * The detected content type for the response. This is used to set the\n   * `Content-Type` header.\n   */\n  public readonly contentType: ContentTypeOption | null\n\n  /**\n   * The metadata for the response. This is used to set the revalidation times\n   * and other metadata.\n   */\n  public readonly metadata: Readonly<Metadata>\n\n  /**\n   * The response itself. This can be a string, a stream, or null. If it's a\n   * string, then it's a static response. If it's a stream, then it's a\n   * dynamic response. If it's null, then the response was not found or was\n   * already sent.\n   */\n  private response: RenderResultResponse\n\n  /**\n   * A render result that represents an empty response. This is used to\n   * represent a response that was not found or was already sent.\n   */\n  public static readonly EMPTY = new RenderResult<StaticRenderResultMetadata>(\n    null,\n    { metadata: {}, contentType: null }\n  )\n\n  /**\n   * Creates a new RenderResult instance from a static response.\n   *\n   * @param value the static response value\n   * @param contentType the content type of the response\n   * @returns a new RenderResult instance\n   */\n  public static fromStatic(\n    value: string | Buffer,\n    contentType: ContentTypeOption\n  ) {\n    return new RenderResult<StaticRenderResultMetadata>(value, {\n      metadata: {},\n      contentType,\n    })\n  }\n\n  private readonly waitUntil?: Promise<unknown>\n\n  constructor(\n    response: RenderResultResponse,\n    { contentType, waitUntil, metadata }: RenderResultOptions<Metadata>\n  ) {\n    this.response = response\n    this.contentType = contentType\n    this.metadata = metadata\n    this.waitUntil = waitUntil\n  }\n\n  public assignMetadata(metadata: Metadata) {\n    Object.assign(this.metadata, metadata)\n  }\n\n  /**\n   * Returns true if the response is null. It can be null if the response was\n   * not found or was already sent.\n   */\n  public get isNull(): boolean {\n    return this.response === null\n  }\n\n  /**\n   * Returns false if the response is a string. It can be a string if the page\n   * was prerendered. If it's not, then it was generated dynamically.\n   */\n  public get isDynamic(): boolean {\n    return typeof this.response !== 'string'\n  }\n\n  /**\n   * Returns the response if it is a string. If the page was dynamic, this will\n   * return a promise if the `stream` option is true, or it will throw an error.\n   *\n   * @param stream Whether or not to return a promise if the response is dynamic\n   * @returns The response as a string\n   */\n  public toUnchunkedString(stream?: false): string\n  public toUnchunkedString(stream: true): Promise<string>\n  public toUnchunkedString(stream = false): Promise<string> | string {\n    if (this.response === null) {\n      // If the response is null, return an empty string. This behavior is\n      // intentional as we're now providing the `RenderResult.EMPTY` value.\n      return ''\n    }\n\n    if (typeof this.response !== 'string') {\n      if (!stream) {\n        throw new InvariantError(\n          'dynamic responses cannot be unchunked. This is a bug in Next.js'\n        )\n      }\n\n      return streamToString(this.readable)\n    }\n\n    return this.response\n  }\n\n  /**\n   * Returns a readable stream of the response.\n   */\n  private get readable(): ReadableStream<Uint8Array> {\n    if (this.response === null) {\n      // If the response is null, return an empty stream. This behavior is\n      // intentional as we're now providing the `RenderResult.EMPTY` value.\n      return new ReadableStream<Uint8Array>({\n        start(controller) {\n          controller.close()\n        },\n      })\n    }\n\n    if (typeof this.response === 'string') {\n      return streamFromString(this.response)\n    }\n\n    if (Buffer.isBuffer(this.response)) {\n      return streamFromBuffer(this.response)\n    }\n\n    // If the response is an array of streams, then chain them together.\n    if (Array.isArray(this.response)) {\n      return chainStreams(...this.response)\n    }\n\n    return this.response\n  }\n\n  /**\n   * Coerces the response to an array of streams. This will convert the response\n   * to an array of streams if it is not already one.\n   *\n   * @returns An array of streams\n   */\n  private coerce(): ReadableStream<Uint8Array>[] {\n    if (this.response === null) {\n      // If the response is null, return an empty stream. This behavior is\n      // intentional as we're now providing the `RenderResult.EMPTY` value.\n      return []\n    }\n\n    if (typeof this.response === 'string') {\n      return [streamFromString(this.response)]\n    } else if (Array.isArray(this.response)) {\n      return this.response\n    } else if (Buffer.isBuffer(this.response)) {\n      return [streamFromBuffer(this.response)]\n    } else {\n      return [this.response]\n    }\n  }\n\n  /**\n   * Pipes the response through a transform stream. This converts the response\n   * to a single readable stream (chaining if needed) and pipes it through the\n   * provided transform.\n   *\n   * @param transform The transform stream to pipe through\n   */\n  public pipeThrough(transform: TransformStream<Uint8Array, Uint8Array>): void {\n    this.response = this.readable.pipeThrough(transform)\n  }\n\n  /**\n   * Unshifts a new stream to the response. This will convert the response to an\n   * array of streams if it is not already one and will add the new stream to\n   * the start of the array. When this response is piped, all of the streams\n   * will be piped one after the other.\n   *\n   * @param readable The new stream to unshift\n   */\n  public unshift(readable: ReadableStream<Uint8Array>): void {\n    // Coerce the response to an array of streams.\n    this.response = this.coerce()\n\n    // Add the new stream to the start of the array.\n    this.response.unshift(readable)\n  }\n\n  /**\n   * Chains a new stream to the response. This will convert the response to an\n   * array of streams if it is not already one and will add the new stream to\n   * the end. When this response is piped, all of the streams will be piped\n   * one after the other.\n   *\n   * @param readable The new stream to chain\n   */\n  public push(readable: ReadableStream<Uint8Array>): void {\n    // Coerce the response to an array of streams.\n    this.response = this.coerce()\n\n    // Add the new stream to the end of the array.\n    this.response.push(readable)\n  }\n\n  /**\n   * Pipes the response to a writable stream. This will close/cancel the\n   * writable stream if an error is encountered. If this doesn't throw, then\n   * the writable stream will be closed or aborted.\n   *\n   * @param writable Writable stream to pipe the response to\n   */\n  public async pipeTo(writable: WritableStream<Uint8Array>): Promise<void> {\n    try {\n      await this.readable.pipeTo(writable, {\n        // We want to close the writable stream ourselves so that we can wait\n        // for the waitUntil promise to resolve before closing it. If an error\n        // is encountered, we'll abort the writable stream if we swallowed the\n        // error.\n        preventClose: true,\n      })\n\n      // If there is a waitUntil promise, wait for it to resolve before\n      // closing the writable stream.\n      if (this.waitUntil) await this.waitUntil\n\n      // Close the writable stream.\n      await writable.close()\n    } catch (err) {\n      // If this is an abort error, we should abort the writable stream (as we\n      // took ownership of it when we started piping). We don't need to re-throw\n      // because we handled the error.\n      if (isAbortError(err)) {\n        // Abort the writable stream if an error is encountered.\n        await writable.abort(err)\n\n        return\n      }\n\n      // We're not aborting the writer here as when this method throws it's not\n      // clear as to how so the caller should assume it's their responsibility\n      // to clean up the writer.\n      throw err\n    }\n  }\n\n  /**\n   * Pipes the response to a node response. This will close/cancel the node\n   * response if an error is encountered.\n   *\n   * @param res\n   */\n  public async pipeToNodeResponse(res: ServerResponse) {\n    await pipeToNodeResponse(this.readable, res, this.waitUntil)\n  }\n}\n","/**\n * For a given page path, this function ensures that there is no backslash\n * escaping slashes in the path. Example:\n *  - `foo\\/bar\\/baz` -> `foo/bar/baz`\n */\nexport function normalizePathSep(path: string): string {\n  return path.replace(/\\\\/g, '/')\n}\n","import { isDynamicRoute } from '../router/utils'\nimport { normalizePathSep } from './normalize-path-sep'\n\n/**\n * Performs the opposite transformation of `normalizePagePath`. Note that\n * this function is not idempotent either in cases where there are multiple\n * leading `/index` for the page. Examples:\n *  - `/index` -> `/`\n *  - `/index/foo` -> `/foo`\n *  - `/index/index` -> `/index`\n */\nexport function denormalizePagePath(page: string) {\n  let _page = normalizePathSep(page)\n  return _page.startsWith('/index/') && !isDynamicRoute(_page)\n    ? _page.slice(6)\n    : _page !== '/index'\n      ? _page\n      : '/'\n}\n","import type { Key } from 'next/dist/compiled/path-to-regexp'\nimport { regexpToFunction } from 'next/dist/compiled/path-to-regexp'\nimport { pathToRegexp } from 'next/dist/compiled/path-to-regexp'\n\ninterface Options {\n  /**\n   * A transformer function that will be applied to the regexp generated\n   * from the provided path and path-to-regexp.\n   */\n  regexModifier?: (regex: string) => string\n  /**\n   * When true the function will remove all unnamed parameters\n   * from the matched parameters.\n   */\n  removeUnnamedParams?: boolean\n  /**\n   * When true the regexp won't allow an optional trailing delimiter\n   * to match.\n   */\n  strict?: boolean\n\n  /**\n   * When true the matcher will be case-sensitive, defaults to false\n   */\n  sensitive?: boolean\n}\n\nexport type PatchMatcher = (\n  pathname: string,\n  params?: Record<string, any>\n) => Record<string, any> | false\n\n/**\n * Generates a path matcher function for a given path and options based on\n * path-to-regexp. By default the match will be case insensitive, non strict\n * and delimited by `/`.\n */\nexport function getPathMatch(path: string, options?: Options): PatchMatcher {\n  const keys: Key[] = []\n  const regexp = pathToRegexp(path, keys, {\n    delimiter: '/',\n    sensitive:\n      typeof options?.sensitive === 'boolean' ? options.sensitive : false,\n    strict: options?.strict,\n  })\n\n  const matcher = regexpToFunction<Record<string, any>>(\n    options?.regexModifier\n      ? new RegExp(options.regexModifier(regexp.source), regexp.flags)\n      : regexp,\n    keys\n  )\n\n  /**\n   * A matcher function that will check if a given pathname matches the path\n   * given in the builder function. When the path does not match it will return\n   * `false` but if it does it will return an object with the matched params\n   * merged with the params provided in the second argument.\n   */\n  return (pathname, params) => {\n    // If no pathname is provided it's not a match.\n    if (typeof pathname !== 'string') return false\n\n    const match = matcher(pathname)\n\n    // If the path did not match `false` will be returned.\n    if (!match) return false\n\n    /**\n     * If unnamed params are not allowed they must be removed from\n     * the matched parameters. path-to-regexp uses \"string\" for named and\n     * \"number\" for unnamed parameters.\n     */\n    if (options?.removeUnnamedParams) {\n      for (const key of keys) {\n        if (typeof key.name === 'number') {\n          delete match.params[key.name]\n        }\n      }\n    }\n\n    return { ...params, ...match.params }\n  }\n}\n","// regexp is based on https://github.com/sindresorhus/escape-string-regexp\nconst reHasRegExp = /[|\\\\{}()[\\]^$+*?.-]/\nconst reReplaceRegExp = /[|\\\\{}()[\\]^$+*?.-]/g\n\nexport function escapeStringRegexp(str: string) {\n  // see also: https://github.com/lodash/lodash/blob/2da024c3b4f9947a48517639de7560457cd4ec6c/escapeRegExp.js#L23\n  if (reHasRegExp.test(str)) {\n    return str.replace(reReplaceRegExp, '\\\\$&')\n  }\n  return str\n}\n","import type { DynamicParam } from '../../../../server/app-render/app-render'\nimport type { LoaderTree } from '../../../../server/lib/app-dir-module'\nimport type { OpaqueFallbackRouteParams } from '../../../../server/request/fallback-params'\nimport type { Params } from '../../../../server/request/params'\nimport type { DynamicParamTypesShort } from '../../app-router-types'\nimport { InvariantError } from '../../invariant-error'\nimport { parseLoaderTree } from './parse-loader-tree'\nimport { parseAppRoute, parseAppRouteSegment } from '../routes/app'\nimport { resolveParamValue } from './resolve-param-value'\n\n/**\n * Gets the value of a param from the params object. This correctly handles the\n * case where the param is a fallback route param and encodes the resulting\n * value.\n *\n * @param interpolatedParams - The params object.\n * @param segmentKey - The key of the segment.\n * @param fallbackRouteParams - The fallback route params.\n * @returns The value of the param.\n */\nfunction getParamValue(\n  interpolatedParams: Params,\n  segmentKey: string,\n  fallbackRouteParams: OpaqueFallbackRouteParams | null\n) {\n  let value = interpolatedParams[segmentKey]\n\n  if (fallbackRouteParams?.has(segmentKey)) {\n    // We know that the fallback route params has the segment key because we\n    // checked that above.\n    const [searchValue] = fallbackRouteParams.get(segmentKey)!\n    value = searchValue\n  } else if (Array.isArray(value)) {\n    value = value.map((i) => encodeURIComponent(i))\n  } else if (typeof value === 'string') {\n    value = encodeURIComponent(value)\n  }\n\n  return value\n}\n\nexport function interpolateParallelRouteParams(\n  loaderTree: LoaderTree,\n  params: Params,\n  pagePath: string,\n  fallbackRouteParams: OpaqueFallbackRouteParams | null\n): Params {\n  const interpolated = structuredClone(params)\n\n  // Stack-based traversal with depth tracking\n  const stack: Array<{ tree: LoaderTree; depth: number }> = [\n    { tree: loaderTree, depth: 0 },\n  ]\n\n  // Parse the route from the provided page path.\n  const route = parseAppRoute(pagePath, true)\n\n  while (stack.length > 0) {\n    const { tree, depth } = stack.pop()!\n    const { segment, parallelRoutes } = parseLoaderTree(tree)\n\n    const appSegment = parseAppRouteSegment(segment)\n\n    if (\n      appSegment?.type === 'dynamic' &&\n      !interpolated.hasOwnProperty(appSegment.param.paramName) &&\n      // If the param is in the fallback route params, we don't need to\n      // interpolate it because it's already marked as being unknown.\n      !fallbackRouteParams?.has(appSegment.param.paramName)\n    ) {\n      const { paramName, paramType } = appSegment.param\n\n      const paramValue = resolveParamValue(\n        paramName,\n        paramType,\n        depth,\n        route,\n        interpolated\n      )\n\n      if (paramValue !== undefined) {\n        interpolated[paramName] = paramValue\n      } else if (paramType !== 'optional-catchall') {\n        throw new InvariantError(\n          `Could not resolve param value for segment: ${paramName}`\n        )\n      }\n    }\n\n    // Calculate next depth - increment if this is not a route group and not empty\n    let nextDepth = depth\n    if (\n      appSegment &&\n      appSegment.type !== 'route-group' &&\n      appSegment.type !== 'parallel-route'\n    ) {\n      nextDepth++\n    }\n\n    // Add all parallel routes to the stack for processing\n    for (const parallelRoute of Object.values(parallelRoutes)) {\n      stack.push({ tree: parallelRoute, depth: nextDepth })\n    }\n  }\n\n  return interpolated\n}\n\n/**\n *\n * Shared logic on client and server for creating a dynamic param value.\n *\n * This code needs to be shared with the client so it can extract dynamic route\n * params from the URL without a server request.\n *\n * Because everything in this module is sent to the client, we should aim to\n * keep this code as simple as possible. The special case handling for catchall\n * and optional is, alas, unfortunate.\n */\nexport function getDynamicParam(\n  interpolatedParams: Params,\n  segmentKey: string,\n  dynamicParamType: DynamicParamTypesShort,\n  fallbackRouteParams: OpaqueFallbackRouteParams | null,\n  staticSiblings: readonly string[] | null\n): DynamicParam {\n  let value: string | string[] | undefined = getParamValue(\n    interpolatedParams,\n    segmentKey,\n    fallbackRouteParams\n  )\n\n  // handle the case where an optional catchall does not have a value,\n  // e.g. `/dashboard/[[...slug]]` when requesting `/dashboard`\n  if (!value || value.length === 0) {\n    if (dynamicParamType === 'oc') {\n      return {\n        param: segmentKey,\n        value: null,\n        type: dynamicParamType,\n        treeSegment: [segmentKey, '', dynamicParamType, staticSiblings],\n      }\n    }\n\n    throw new InvariantError(\n      `Missing value for segment key: \"${segmentKey}\" with dynamic param type: ${dynamicParamType}`\n    )\n  }\n\n  const paramCacheKey = Array.isArray(value) ? value.join('/') : value\n\n  return {\n    param: segmentKey,\n    // The value that is passed to user code.\n    value,\n    // The value that is rendered in the router tree.\n    // TODO: If the number of static siblings exceeds some threshold (e.g.,\n    // dozens or hundreds), consider sending a Bloom filter instead of the full\n    // array to reduce payload size. The client would then use the Bloom filter\n    // to check membership with a small false positive rate.\n    treeSegment: [segmentKey, paramCacheKey, dynamicParamType, staticSiblings],\n    type: dynamicParamType,\n  }\n}\n\n/**\n * Regular expression pattern used to match route parameters.\n * Matches both single parameters and parameter groups.\n * Examples:\n *   - `[[...slug]]` matches parameter group with key 'slug', repeat: true, optional: true\n *   - `[...slug]` matches parameter group with key 'slug', repeat: true, optional: false\n *   - `[[foo]]` matches parameter with key 'foo', repeat: false, optional: true\n *   - `[bar]` matches parameter with key 'bar', repeat: false, optional: false\n */\nexport const PARAMETER_PATTERN = /^([^[]*)\\[((?:\\[[^\\]]*\\])|[^\\]]+)\\](.*)$/\n\n/**\n * Parses a given parameter from a route to a data structure that can be used\n * to generate the parametrized route.\n * Examples:\n *   - `[[...slug]]` -> `{ key: 'slug', repeat: true, optional: true }`\n *   - `[...slug]` -> `{ key: 'slug', repeat: true, optional: false }`\n *   - `[[foo]]` -> `{ key: 'foo', repeat: false, optional: true }`\n *   - `[bar]` -> `{ key: 'bar', repeat: false, optional: false }`\n *   - `fizz` -> `{ key: 'fizz', repeat: false, optional: false }`\n * @param param - The parameter to parse.\n * @returns The parsed parameter as a data structure.\n */\nexport function parseParameter(param: string) {\n  const match = param.match(PARAMETER_PATTERN)\n\n  if (!match) {\n    return parseMatchedParameter(param)\n  }\n\n  return parseMatchedParameter(match[2])\n}\n\n/**\n * Parses a matched parameter from the PARAMETER_PATTERN regex to a data structure that can be used\n * to generate the parametrized route.\n * Examples:\n *   - `[...slug]` -> `{ key: 'slug', repeat: true, optional: true }`\n *   - `...slug` -> `{ key: 'slug', repeat: true, optional: false }`\n *   - `[foo]` -> `{ key: 'foo', repeat: false, optional: true }`\n *   - `bar` -> `{ key: 'bar', repeat: false, optional: false }`\n * @param param - The matched parameter to parse.\n * @returns The parsed parameter as a data structure.\n */\nexport function parseMatchedParameter(param: string) {\n  const optional = param.startsWith('[') && param.endsWith(']')\n  if (optional) {\n    param = param.slice(1, -1)\n  }\n  const repeat = param.startsWith('...')\n  if (repeat) {\n    param = param.slice(3)\n  }\n  return { key: param, repeat, optional }\n}\n","import {\n  NEXT_INTERCEPTION_MARKER_PREFIX,\n  NEXT_QUERY_PARAM_PREFIX,\n} from '../../../../lib/constants'\nimport { INTERCEPTION_ROUTE_MARKERS } from './interception-routes'\nimport { escapeStringRegexp } from '../../escape-regexp'\nimport { removeTrailingSlash } from './remove-trailing-slash'\nimport { PARAMETER_PATTERN, parseMatchedParameter } from './get-dynamic-param'\n\nexport interface Group {\n  pos: number\n  repeat: boolean\n  optional: boolean\n}\n\nexport interface RouteRegex {\n  groups: { [groupName: string]: Group }\n  re: RegExp\n}\n\nexport type RegexReference = {\n  names: Record<string, string>\n  intercepted: Record<string, string>\n}\n\ntype GetNamedRouteRegexOptions = {\n  /**\n   * Whether to prefix the route keys with the NEXT_INTERCEPTION_MARKER_PREFIX\n   * or NEXT_QUERY_PARAM_PREFIX. This is only relevant when creating the\n   * routes-manifest during the build.\n   */\n  prefixRouteKeys: boolean\n\n  /**\n   * Whether to include the suffix in the route regex. This means that when you\n   * have something like `/[...slug].json` the `.json` part will be included\n   * in the regex, yielding `/(.*).json` as the regex.\n   */\n  includeSuffix?: boolean\n\n  /**\n   * Whether to include the prefix in the route regex. This means that when you\n   * have something like `/[...slug].json` the `/` part will be included\n   * in the regex, yielding `^/(.*).json$` as the regex.\n   *\n   * Note that interception markers will already be included without the need\n   */\n  includePrefix?: boolean\n\n  /**\n   * Whether to exclude the optional trailing slash from the route regex.\n   */\n  excludeOptionalTrailingSlash?: boolean\n\n  /**\n   * Whether to backtrack duplicate keys. This is only relevant when creating\n   * the routes-manifest during the build.\n   */\n  backreferenceDuplicateKeys?: boolean\n\n  /**\n   * If provided, this will be used as the reference for the dynamic parameter\n   * keys instead of generating them in context. This is currently only used for\n   * interception routes.\n   */\n  reference?: RegexReference\n}\n\ntype GetRouteRegexOptions = {\n  /**\n   * Whether to include extra parts in the route regex. This means that when you\n   * have something like `/[...slug].json` the `.json` part will be included\n   * in the regex, yielding `/(.*).json` as the regex.\n   */\n  includeSuffix?: boolean\n\n  /**\n   * Whether to include the prefix in the route regex. This means that when you\n   * have something like `/[...slug].json` the `/` part will be included\n   * in the regex, yielding `^/(.*).json$` as the regex.\n   *\n   * Note that interception markers will already be included without the need\n   * of adding this option.\n   */\n  includePrefix?: boolean\n\n  /**\n   * Whether to exclude the optional trailing slash from the route regex.\n   */\n  excludeOptionalTrailingSlash?: boolean\n}\n\nfunction getParametrizedRoute(\n  route: string,\n  includeSuffix: boolean,\n  includePrefix: boolean\n) {\n  const groups: { [groupName: string]: Group } = {}\n  let groupIndex = 1\n\n  const segments: string[] = []\n  for (const segment of removeTrailingSlash(route).slice(1).split('/')) {\n    const markerMatch = INTERCEPTION_ROUTE_MARKERS.find((m) =>\n      segment.startsWith(m)\n    )\n    const paramMatches = segment.match(PARAMETER_PATTERN) // Check for parameters\n\n    if (markerMatch && paramMatches && paramMatches[2]) {\n      const { key, optional, repeat } = parseMatchedParameter(paramMatches[2])\n      groups[key] = { pos: groupIndex++, repeat, optional }\n      segments.push(`/${escapeStringRegexp(markerMatch)}([^/]+?)`)\n    } else if (paramMatches && paramMatches[2]) {\n      const { key, repeat, optional } = parseMatchedParameter(paramMatches[2])\n      groups[key] = { pos: groupIndex++, repeat, optional }\n\n      if (includePrefix && paramMatches[1]) {\n        segments.push(`/${escapeStringRegexp(paramMatches[1])}`)\n      }\n\n      let s = repeat ? (optional ? '(?:/(.+?))?' : '/(.+?)') : '/([^/]+?)'\n\n      // Remove the leading slash if includePrefix already added it.\n      if (includePrefix && paramMatches[1]) {\n        s = s.substring(1)\n      }\n\n      segments.push(s)\n    } else {\n      segments.push(`/${escapeStringRegexp(segment)}`)\n    }\n\n    // If there's a suffix, add it to the segments if it's enabled.\n    if (includeSuffix && paramMatches && paramMatches[3]) {\n      segments.push(escapeStringRegexp(paramMatches[3]))\n    }\n  }\n\n  return {\n    parameterizedRoute: segments.join(''),\n    groups,\n  }\n}\n\n/**\n * From a normalized route this function generates a regular expression and\n * a corresponding groups object intended to be used to store matching groups\n * from the regular expression.\n */\nexport function getRouteRegex(\n  normalizedRoute: string,\n  {\n    includeSuffix = false,\n    includePrefix = false,\n    excludeOptionalTrailingSlash = false,\n  }: GetRouteRegexOptions = {}\n): RouteRegex {\n  const { parameterizedRoute, groups } = getParametrizedRoute(\n    normalizedRoute,\n    includeSuffix,\n    includePrefix\n  )\n\n  let re = parameterizedRoute\n  if (!excludeOptionalTrailingSlash) {\n    re += '(?:/)?'\n  }\n\n  return {\n    re: new RegExp(`^${re}$`),\n    groups: groups,\n  }\n}\n\n/**\n * Builds a function to generate a minimal routeKey using only a-z and minimal\n * number of characters.\n */\nfunction buildGetSafeRouteKey() {\n  let i = 0\n\n  return () => {\n    let routeKey = ''\n    let j = ++i\n    while (j > 0) {\n      routeKey += String.fromCharCode(97 + ((j - 1) % 26))\n      j = Math.floor((j - 1) / 26)\n    }\n    return routeKey\n  }\n}\n\nfunction getSafeKeyFromSegment({\n  interceptionMarker,\n  getSafeRouteKey,\n  segment,\n  routeKeys,\n  keyPrefix,\n  backreferenceDuplicateKeys,\n}: {\n  interceptionMarker?: string\n  getSafeRouteKey: () => string\n  segment: string\n  routeKeys: Record<string, string>\n  keyPrefix?: string\n  backreferenceDuplicateKeys: boolean\n}) {\n  const { key, optional, repeat } = parseMatchedParameter(segment)\n\n  // replace any non-word characters since they can break\n  // the named regex\n  let cleanedKey = key.replace(/\\W/g, '')\n\n  if (keyPrefix) {\n    cleanedKey = `${keyPrefix}${cleanedKey}`\n  }\n  let invalidKey = false\n\n  // check if the key is still invalid and fallback to using a known\n  // safe key\n  if (cleanedKey.length === 0 || cleanedKey.length > 30) {\n    invalidKey = true\n  }\n  if (!isNaN(parseInt(cleanedKey.slice(0, 1)))) {\n    invalidKey = true\n  }\n\n  if (invalidKey) {\n    cleanedKey = getSafeRouteKey()\n  }\n\n  const duplicateKey = cleanedKey in routeKeys\n\n  if (keyPrefix) {\n    routeKeys[cleanedKey] = `${keyPrefix}${key}`\n  } else {\n    routeKeys[cleanedKey] = key\n  }\n\n  // if the segment has an interception marker, make sure that's part of the regex pattern\n  // this is to ensure that the route with the interception marker doesn't incorrectly match\n  // the non-intercepted route (ie /app/(.)[username] should not match /app/[username])\n  const interceptionPrefix = interceptionMarker\n    ? escapeStringRegexp(interceptionMarker)\n    : ''\n\n  let pattern: string\n  if (duplicateKey && backreferenceDuplicateKeys) {\n    // Use a backreference to the key to ensure that the key is the same value\n    // in each of the placeholders.\n    pattern = `\\\\k<${cleanedKey}>`\n  } else if (repeat) {\n    pattern = `(?<${cleanedKey}>.+?)`\n  } else {\n    pattern = `(?<${cleanedKey}>[^/]+?)`\n  }\n\n  return {\n    key,\n    pattern: optional\n      ? `(?:/${interceptionPrefix}${pattern})?`\n      : `/${interceptionPrefix}${pattern}`,\n    cleanedKey: cleanedKey,\n    optional,\n    repeat,\n  }\n}\n\nfunction getNamedParametrizedRoute(\n  route: string,\n  prefixRouteKeys: boolean,\n  includeSuffix: boolean,\n  includePrefix: boolean,\n  backreferenceDuplicateKeys: boolean,\n  reference: RegexReference = { names: {}, intercepted: {} }\n) {\n  const getSafeRouteKey = buildGetSafeRouteKey()\n  const routeKeys: { [named: string]: string } = {}\n\n  const segments: string[] = []\n  const inverseParts: string[] = []\n\n  // Ensure we don't mutate the original reference object.\n  reference = structuredClone(reference)\n\n  for (const segment of removeTrailingSlash(route).slice(1).split('/')) {\n    const hasInterceptionMarker = INTERCEPTION_ROUTE_MARKERS.some((m) =>\n      segment.startsWith(m)\n    )\n\n    const paramMatches = segment.match(PARAMETER_PATTERN) // Check for parameters\n\n    const interceptionMarker = hasInterceptionMarker\n      ? paramMatches?.[1]\n      : undefined\n\n    let keyPrefix: string | undefined\n    if (interceptionMarker && paramMatches?.[2]) {\n      keyPrefix = prefixRouteKeys ? NEXT_INTERCEPTION_MARKER_PREFIX : undefined\n      reference.intercepted[paramMatches[2]] = interceptionMarker\n    } else if (paramMatches?.[2] && reference.intercepted[paramMatches[2]]) {\n      keyPrefix = prefixRouteKeys ? NEXT_INTERCEPTION_MARKER_PREFIX : undefined\n    } else {\n      keyPrefix = prefixRouteKeys ? NEXT_QUERY_PARAM_PREFIX : undefined\n    }\n\n    if (interceptionMarker && paramMatches && paramMatches[2]) {\n      // If there's an interception marker, add it to the segments.\n      const { key, pattern, cleanedKey, repeat, optional } =\n        getSafeKeyFromSegment({\n          getSafeRouteKey,\n          interceptionMarker,\n          segment: paramMatches[2],\n          routeKeys,\n          keyPrefix,\n          backreferenceDuplicateKeys,\n        })\n\n      segments.push(pattern)\n      inverseParts.push(\n        `/${paramMatches[1]}:${reference.names[key] ?? cleanedKey}${repeat ? (optional ? '*' : '+') : ''}`\n      )\n      reference.names[key] ??= cleanedKey\n    } else if (paramMatches && paramMatches[2]) {\n      // If there's a prefix, add it to the segments if it's enabled.\n      if (includePrefix && paramMatches[1]) {\n        segments.push(`/${escapeStringRegexp(paramMatches[1])}`)\n        inverseParts.push(`/${paramMatches[1]}`)\n      }\n\n      const { key, pattern, cleanedKey, repeat, optional } =\n        getSafeKeyFromSegment({\n          getSafeRouteKey,\n          segment: paramMatches[2],\n          routeKeys,\n          keyPrefix,\n          backreferenceDuplicateKeys,\n        })\n\n      // Remove the leading slash if includePrefix already added it.\n      let s = pattern\n      if (includePrefix && paramMatches[1]) {\n        s = s.substring(1)\n      }\n\n      segments.push(s)\n      inverseParts.push(\n        `/:${reference.names[key] ?? cleanedKey}${repeat ? (optional ? '*' : '+') : ''}`\n      )\n      reference.names[key] ??= cleanedKey\n    } else {\n      segments.push(`/${escapeStringRegexp(segment)}`)\n      inverseParts.push(`/${segment}`)\n    }\n\n    // If there's a suffix, add it to the segments if it's enabled.\n    if (includeSuffix && paramMatches && paramMatches[3]) {\n      segments.push(escapeStringRegexp(paramMatches[3]))\n      inverseParts.push(paramMatches[3])\n    }\n  }\n\n  return {\n    namedParameterizedRoute: segments.join(''),\n    routeKeys,\n    pathToRegexpPattern: inverseParts.join(''),\n    reference,\n  }\n}\n\n/**\n * This function extends `getRouteRegex` generating also a named regexp where\n * each group is named along with a routeKeys object that indexes the assigned\n * named group with its corresponding key. When the routeKeys need to be\n * prefixed to uniquely identify internally the \"prefixRouteKey\" arg should\n * be \"true\" currently this is only the case when creating the routes-manifest\n * during the build\n */\nexport function getNamedRouteRegex(\n  normalizedRoute: string,\n  options: GetNamedRouteRegexOptions\n) {\n  const result = getNamedParametrizedRoute(\n    normalizedRoute,\n    options.prefixRouteKeys,\n    options.includeSuffix ?? false,\n    options.includePrefix ?? false,\n    options.backreferenceDuplicateKeys ?? false,\n    options.reference\n  )\n\n  let namedRegex = result.namedParameterizedRoute\n  if (!options.excludeOptionalTrailingSlash) {\n    namedRegex += '(?:/)?'\n  }\n\n  return {\n    ...getRouteRegex(normalizedRoute, options),\n    namedRegex: `^${namedRegex}$`,\n    routeKeys: result.routeKeys,\n    pathToRegexpPattern: result.pathToRegexpPattern,\n    reference: result.reference,\n  }\n}\n\n/**\n * Generates a named regexp.\n * This is intended to be using for build time only.\n */\nexport function getNamedMiddlewareRegex(\n  normalizedRoute: string,\n  options: {\n    catchAll?: boolean\n  }\n) {\n  const { parameterizedRoute } = getParametrizedRoute(\n    normalizedRoute,\n    false,\n    false\n  )\n  const { catchAll = true } = options\n  if (parameterizedRoute === '/') {\n    let catchAllRegex = catchAll ? '.*' : ''\n    return {\n      namedRegex: `^/${catchAllRegex}$`,\n    }\n  }\n\n  const { namedParameterizedRoute } = getNamedParametrizedRoute(\n    normalizedRoute,\n    false,\n    false,\n    false,\n    false,\n    undefined\n  )\n  let catchAllGroupedRegex = catchAll ? '(?:(/.*)?)' : ''\n  return {\n    namedRegex: `^${namedParameterizedRoute}${catchAllGroupedRegex}$`,\n  }\n}\n","import type { IncomingMessage } from 'http'\nimport type { Key } from 'next/dist/compiled/path-to-regexp'\nimport type { NextParsedUrlQuery } from '../../../../server/request-meta'\nimport type { RouteHas } from '../../../../lib/load-custom-routes'\nimport type { BaseNextRequest } from '../../../../server/base-http'\n\nimport { escapeStringRegexp } from '../../escape-regexp'\nimport { parseUrl, type ParsedUrl } from './parse-url'\nimport {\n  INTERCEPTION_ROUTE_MARKERS,\n  isInterceptionRouteAppPath,\n} from './interception-routes'\nimport { getCookieParser } from '../../../../server/api-utils/get-cookie-parser'\nimport type { Params } from '../../../../server/request/params'\nimport { safePathToRegexp, safeCompile } from './route-match-utils'\n\n/**\n * Ensure only a-zA-Z are used for param names for proper interpolating\n * with path-to-regexp\n */\nfunction getSafeParamName(paramName: string) {\n  let newParamName = ''\n\n  for (let i = 0; i < paramName.length; i++) {\n    const charCode = paramName.charCodeAt(i)\n\n    if (\n      (charCode > 64 && charCode < 91) || // A-Z\n      (charCode > 96 && charCode < 123) // a-z\n    ) {\n      newParamName += paramName[i]\n    }\n  }\n  return newParamName\n}\n\nfunction escapeSegment(str: string, segmentName: string) {\n  return str.replace(\n    new RegExp(`:${escapeStringRegexp(segmentName)}`, 'g'),\n    `__ESC_COLON_${segmentName}`\n  )\n}\n\nfunction unescapeSegments(str: string) {\n  return str.replace(/__ESC_COLON_/gi, ':')\n}\n\nexport function matchHas(\n  req: BaseNextRequest | IncomingMessage,\n  query: Params,\n  has: RouteHas[] = [],\n  missing: RouteHas[] = []\n): false | Params {\n  const params: Params = {}\n\n  const hasMatch = (hasItem: RouteHas) => {\n    let value\n    let key = hasItem.key\n\n    switch (hasItem.type) {\n      case 'header': {\n        key = key!.toLowerCase()\n        value = req.headers[key] as string\n        break\n      }\n      case 'cookie': {\n        if ('cookies' in req) {\n          value = req.cookies[hasItem.key]\n        } else {\n          const cookies = getCookieParser(req.headers)()\n          value = cookies[hasItem.key]\n        }\n\n        break\n      }\n      case 'query': {\n        value = query[key!]\n        break\n      }\n      case 'host': {\n        const { host } = req?.headers || {}\n        // remove port from host if present\n        const hostname = host?.split(':', 1)[0].toLowerCase()\n        value = hostname\n        break\n      }\n      default: {\n        break\n      }\n    }\n\n    if (!hasItem.value && value) {\n      params[getSafeParamName(key!)] = value\n      return true\n    } else if (value) {\n      const matcher = new RegExp(`^${hasItem.value}$`)\n      const matches = Array.isArray(value)\n        ? value.slice(-1)[0].match(matcher)\n        : value.match(matcher)\n\n      if (matches) {\n        if (Array.isArray(matches)) {\n          if (matches.groups) {\n            Object.keys(matches.groups).forEach((groupKey) => {\n              params[groupKey] = matches.groups![groupKey]\n            })\n          } else if (hasItem.type === 'host' && matches[0]) {\n            params.host = matches[0]\n          }\n        }\n        return true\n      }\n    }\n    return false\n  }\n\n  const allMatch =\n    has.every((item) => hasMatch(item)) &&\n    !missing.some((item) => hasMatch(item))\n\n  if (allMatch) {\n    return params\n  }\n  return false\n}\n\nexport function compileNonPath(value: string, params: Params): string {\n  if (!value.includes(':')) {\n    return value\n  }\n\n  for (const key of Object.keys(params)) {\n    if (value.includes(`:${key}`)) {\n      value = value\n        .replace(\n          new RegExp(`:${key}\\\\*`, 'g'),\n          `:${key}--ESCAPED_PARAM_ASTERISKS`\n        )\n        .replace(\n          new RegExp(`:${key}\\\\?`, 'g'),\n          `:${key}--ESCAPED_PARAM_QUESTION`\n        )\n        .replace(new RegExp(`:${key}\\\\+`, 'g'), `:${key}--ESCAPED_PARAM_PLUS`)\n        .replace(\n          new RegExp(`:${key}(?!\\\\w)`, 'g'),\n          `--ESCAPED_PARAM_COLON${key}`\n        )\n    }\n  }\n  value = value\n    .replace(/(:|\\*|\\?|\\+|\\(|\\)|\\{|\\})/g, '\\\\$1')\n    .replace(/--ESCAPED_PARAM_PLUS/g, '+')\n    .replace(/--ESCAPED_PARAM_COLON/g, ':')\n    .replace(/--ESCAPED_PARAM_QUESTION/g, '?')\n    .replace(/--ESCAPED_PARAM_ASTERISKS/g, '*')\n\n  // the value needs to start with a forward-slash to be compiled\n  // correctly\n  return safeCompile(`/${value}`, { validate: false })(params).slice(1)\n}\n\nexport function parseDestination(args: {\n  destination: string\n  params: Readonly<Params>\n  query: Readonly<NextParsedUrlQuery>\n}): ParsedUrl {\n  let escaped = args.destination\n  for (const param of Object.keys({ ...args.params, ...args.query })) {\n    if (!param) continue\n\n    escaped = escapeSegment(escaped, param)\n  }\n\n  const parsed = parseUrl(escaped)\n\n  let pathname = parsed.pathname\n  if (pathname) {\n    pathname = unescapeSegments(pathname)\n  }\n\n  let href = parsed.href\n  if (href) {\n    href = unescapeSegments(href)\n  }\n\n  let hostname = parsed.hostname\n  if (hostname) {\n    hostname = unescapeSegments(hostname)\n  }\n\n  let hash = parsed.hash\n  if (hash) {\n    hash = unescapeSegments(hash)\n  }\n\n  let search = parsed.search\n  if (search) {\n    search = unescapeSegments(search)\n  }\n\n  let origin = parsed.origin\n  if (origin) {\n    origin = unescapeSegments(origin)\n  }\n\n  return {\n    ...parsed,\n    pathname,\n    hostname,\n    href,\n    hash,\n    search,\n    origin,\n  }\n}\n\nexport function prepareDestination(args: {\n  appendParamsToQuery: boolean\n  destination: string\n  params: Params\n  query: NextParsedUrlQuery\n}) {\n  const parsedDestination = parseDestination(args)\n\n  const {\n    hostname: destHostname,\n    query: destQuery,\n    search: destSearch,\n  } = parsedDestination\n\n  // The following code assumes that the pathname here includes the hash if it's\n  // present.\n  let destPath = parsedDestination.pathname\n  if (parsedDestination.hash) {\n    destPath = `${destPath}${parsedDestination.hash}`\n  }\n\n  const destParams: (string | number)[] = []\n\n  const destPathParamKeys: Key[] = []\n  safePathToRegexp(destPath, destPathParamKeys)\n  for (const key of destPathParamKeys) {\n    destParams.push(key.name)\n  }\n\n  if (destHostname) {\n    const destHostnameParamKeys: Key[] = []\n    safePathToRegexp(destHostname, destHostnameParamKeys)\n    for (const key of destHostnameParamKeys) {\n      destParams.push(key.name)\n    }\n  }\n\n  const destPathCompiler = safeCompile(\n    destPath,\n    // we don't validate while compiling the destination since we should\n    // have already validated before we got to this point and validating\n    // breaks compiling destinations with named pattern params from the source\n    // e.g. /something:hello(.*) -> /another/:hello is broken with validation\n    // since compile validation is meant for reversing and not for inserting\n    // params from a separate path-regex into another\n    { validate: false }\n  )\n\n  let destHostnameCompiler\n  if (destHostname) {\n    destHostnameCompiler = safeCompile(destHostname, { validate: false })\n  }\n\n  // update any params in query values\n  for (const [key, strOrArray] of Object.entries(destQuery)) {\n    // the value needs to start with a forward-slash to be compiled\n    // correctly\n    if (Array.isArray(strOrArray)) {\n      destQuery[key] = strOrArray.map((value) =>\n        compileNonPath(unescapeSegments(value), args.params)\n      )\n    } else if (typeof strOrArray === 'string') {\n      destQuery[key] = compileNonPath(unescapeSegments(strOrArray), args.params)\n    }\n  }\n\n  // add path params to query if it's not a redirect and not\n  // already defined in destination query or path\n  let paramKeys = Object.keys(args.params).filter(\n    (name) => name !== 'nextInternalLocale'\n  )\n\n  if (\n    args.appendParamsToQuery &&\n    !paramKeys.some((key) => destParams.includes(key))\n  ) {\n    for (const key of paramKeys) {\n      if (!(key in destQuery)) {\n        destQuery[key] = args.params[key]\n      }\n    }\n  }\n\n  let newUrl\n\n  // The compiler also that the interception route marker is an unnamed param, hence '0',\n  // so we need to add it to the params object.\n  if (isInterceptionRouteAppPath(destPath)) {\n    for (const segment of destPath.split('/')) {\n      const marker = INTERCEPTION_ROUTE_MARKERS.find((m) =>\n        segment.startsWith(m)\n      )\n      if (marker) {\n        if (marker === '(..)(..)') {\n          args.params['0'] = '(..)'\n          args.params['1'] = '(..)'\n        } else {\n          args.params['0'] = marker\n        }\n        break\n      }\n    }\n  }\n\n  try {\n    newUrl = destPathCompiler(args.params)\n\n    const [pathname, hash] = newUrl.split('#', 2)\n    if (destHostnameCompiler) {\n      parsedDestination.hostname = destHostnameCompiler(args.params)\n    }\n    parsedDestination.pathname = pathname\n    parsedDestination.hash = `${hash ? '#' : ''}${hash || ''}`\n    parsedDestination.search = destSearch\n      ? compileNonPath(destSearch, args.params)\n      : ''\n  } catch (err: any) {\n    if (err.message.match(/Expected .*? to not repeat, but got an array/)) {\n      throw new Error(\n        `To use a multi-match in the destination you must add \\`*\\` at the end of the param name to signify it should repeat. https://nextjs.org/docs/messages/invalid-multi-match`\n      )\n    }\n    throw err\n  }\n\n  // Query merge order lowest priority to highest\n  // 1. initial URL query values\n  // 2. path segment values\n  // 3. destination specified query values\n  parsedDestination.query = {\n    ...args.query,\n    ...parsedDestination.query,\n  }\n\n  return {\n    newUrl,\n    destQuery,\n    parsedDestination,\n  }\n}\n","/**\n * Decodes a query path parameter.\n *\n * @param value - The value to decode.\n * @returns The decoded value.\n */\nexport function decodeQueryPathParameter(value: string) {\n  // When deployed to Vercel, the value may be encoded, so this attempts to\n  // decode it and returns the original value if it fails.\n  try {\n    return decodeURIComponent(value)\n  } catch {\n    return value\n  }\n}\n","// Format function modified from nodejs\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { UrlObject } from 'url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport * as querystring from './querystring'\n\nconst slashedProtocols = /https?|ftp|gopher|file/\n\nexport function formatUrl(urlObj: UrlObject) {\n  let { auth, hostname } = urlObj\n  let protocol = urlObj.protocol || ''\n  let pathname = urlObj.pathname || ''\n  let hash = urlObj.hash || ''\n  let query = urlObj.query || ''\n  let host: string | false = false\n\n  auth = auth ? encodeURIComponent(auth).replace(/%3A/i, ':') + '@' : ''\n\n  if (urlObj.host) {\n    host = auth + urlObj.host\n  } else if (hostname) {\n    host = auth + (~hostname.indexOf(':') ? `[${hostname}]` : hostname)\n    if (urlObj.port) {\n      host += ':' + urlObj.port\n    }\n  }\n\n  if (query && typeof query === 'object') {\n    query = String(querystring.urlQueryToSearchParams(query as ParsedUrlQuery))\n  }\n\n  let search = urlObj.search || (query && `?${query}`) || ''\n\n  if (protocol && !protocol.endsWith(':')) protocol += ':'\n\n  if (\n    urlObj.slashes ||\n    ((!protocol || slashedProtocols.test(protocol)) && host !== false)\n  ) {\n    host = '//' + (host || '')\n    if (pathname && pathname[0] !== '/') pathname = '/' + pathname\n  } else if (!host) {\n    host = ''\n  }\n\n  if (hash && hash[0] !== '#') hash = '#' + hash\n  if (search && search[0] !== '?') search = '?' + search\n\n  pathname = pathname.replace(/[?#]/g, encodeURIComponent)\n  search = search.replace('#', '%23')\n\n  return `${protocol}${host}${pathname}${search}${hash}`\n}\n\nexport const urlObjectKeys = [\n  'auth',\n  'hash',\n  'host',\n  'hostname',\n  'href',\n  'path',\n  'pathname',\n  'port',\n  'protocol',\n  'query',\n  'search',\n  'slashes',\n]\n\nexport function formatWithValidation(url: UrlObject): string {\n  if (process.env.NODE_ENV === 'development') {\n    if (url !== null && typeof url === 'object') {\n      Object.keys(url).forEach((key) => {\n        if (!urlObjectKeys.includes(key)) {\n          console.warn(\n            `Unknown key passed via urlObject into url.format: ${key}`\n          )\n        }\n      })\n    }\n  }\n\n  return formatUrl(url)\n}\n","import type { Rewrite } from '../lib/load-custom-routes'\nimport type { RouteMatchFn } from '../shared/lib/router/utils/route-matcher'\nimport type { NextConfig } from './config'\nimport type { BaseNextRequest } from './base-http'\nimport type { NextUrlWithParsedQuery } from './request-meta'\nimport type { ParsedUrlQuery } from 'querystring'\n\nimport { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'\nimport { getPathMatch } from '../shared/lib/router/utils/path-match'\nimport { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'\nimport { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'\nimport {\n  matchHas,\n  prepareDestination,\n} from '../shared/lib/router/utils/prepare-destination'\nimport { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'\nimport { normalizeRscURL } from '../shared/lib/router/utils/app-paths'\nimport {\n  NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER,\n  NEXT_CACHE_REVALIDATED_TAGS_HEADER,\n  NEXT_INTERCEPTION_MARKER_PREFIX,\n  NEXT_QUERY_PARAM_PREFIX,\n} from '../lib/constants'\nimport { normalizeNextQueryParam } from './web/utils'\nimport type { IncomingHttpHeaders, IncomingMessage } from 'http'\nimport { decodeQueryPathParameter } from './lib/decode-query-path-parameter'\nimport type { DeepReadonly } from '../shared/lib/deep-readonly'\nimport { parseReqUrl } from '../lib/url'\nimport { formatUrl } from '../shared/lib/router/utils/format-url'\n\nfunction filterInternalQuery(\n  query: Record<string, undefined | string | string[]>,\n  paramKeys: string[]\n) {\n  // this is used to pass query information in rewrites\n  // but should not be exposed in final query\n  delete query['nextInternalLocale']\n\n  for (const key in query) {\n    const isNextQueryPrefix =\n      key !== NEXT_QUERY_PARAM_PREFIX && key.startsWith(NEXT_QUERY_PARAM_PREFIX)\n\n    const isNextInterceptionMarkerPrefix =\n      key !== NEXT_INTERCEPTION_MARKER_PREFIX &&\n      key.startsWith(NEXT_INTERCEPTION_MARKER_PREFIX)\n\n    if (\n      isNextQueryPrefix ||\n      isNextInterceptionMarkerPrefix ||\n      paramKeys.includes(key)\n    ) {\n      delete query[key]\n    }\n  }\n}\n\nexport function normalizeCdnUrl(\n  req: BaseNextRequest | IncomingMessage,\n  paramKeys: string[]\n) {\n  // make sure to normalize req.url from CDNs to strip dynamic and rewrite\n  // params from the query which are added during routing\n  const _parsedUrl = parseReqUrl(req.url!)\n\n  // we can't normalize if we can't parse\n  if (!_parsedUrl) {\n    return req.url\n  }\n  delete (_parsedUrl as any).search\n  filterInternalQuery(_parsedUrl.query, paramKeys)\n\n  req.url = formatUrl(_parsedUrl)\n}\n\nexport function interpolateDynamicPath(\n  pathname: string,\n  params: ParsedUrlQuery,\n  defaultRouteRegex?: ReturnType<typeof getNamedRouteRegex> | undefined\n) {\n  if (!defaultRouteRegex) return pathname\n\n  for (const param of Object.keys(defaultRouteRegex.groups)) {\n    const { optional, repeat } = defaultRouteRegex.groups[param]\n    let builtParam = `[${repeat ? '...' : ''}${param}]`\n\n    if (optional) {\n      builtParam = `[${builtParam}]`\n    }\n\n    let paramValue: string\n    const value = params[param]\n\n    if (Array.isArray(value)) {\n      paramValue = value.map((v) => v && encodeURIComponent(v)).join('/')\n    } else if (value) {\n      paramValue = encodeURIComponent(value)\n    } else {\n      paramValue = ''\n    }\n\n    if (paramValue || optional) {\n      pathname = pathname.replaceAll(builtParam, paramValue)\n    }\n  }\n\n  return pathname\n}\n\nexport function normalizeDynamicRouteParams(\n  query: ParsedUrlQuery,\n  defaultRouteRegex: ReturnType<typeof getNamedRouteRegex>,\n  defaultRouteMatches: ParsedUrlQuery,\n  ignoreMissingOptional: boolean\n) {\n  let hasValidParams = true\n  let params: ParsedUrlQuery = {}\n\n  for (const key of Object.keys(defaultRouteRegex.groups)) {\n    let value: string | string[] | undefined = query[key]\n\n    if (typeof value === 'string') {\n      value = normalizeRscURL(value)\n    } else if (Array.isArray(value)) {\n      value = value.map(normalizeRscURL)\n    }\n\n    // if the value matches the default value we can't rely\n    // on the parsed params, this is used to signal if we need\n    // to parse x-now-route-matches or not\n    const defaultValue = defaultRouteMatches![key]\n    const isOptional = defaultRouteRegex!.groups[key].optional\n\n    const isDefaultValue = Array.isArray(defaultValue)\n      ? defaultValue.some((defaultVal) => {\n          return Array.isArray(value)\n            ? value.some((val) => val.includes(defaultVal))\n            : value?.includes(defaultVal)\n        })\n      : value?.includes(defaultValue as string)\n\n    if (\n      isDefaultValue ||\n      (typeof value === 'undefined' && !(isOptional && ignoreMissingOptional))\n    ) {\n      return { params: {}, hasValidParams: false }\n    }\n\n    // non-provided optional values should be undefined so normalize\n    // them to undefined\n    if (\n      isOptional &&\n      (!value ||\n        (Array.isArray(value) &&\n          value.length === 1 &&\n          // fallback optional catch-all SSG pages have\n          // [[...paramName]] for the root path on Vercel\n          (value[0] === 'index' || value[0] === `[[...${key}]]`)) ||\n        value === 'index' ||\n        value === `[[...${key}]]`)\n    ) {\n      value = undefined\n      delete query[key]\n    }\n\n    // query values from the proxy aren't already split into arrays\n    // so make sure to normalize catch-all values\n    if (\n      value &&\n      typeof value === 'string' &&\n      defaultRouteRegex!.groups[key].repeat\n    ) {\n      value = value.split('/')\n    }\n\n    if (value) {\n      params[key] = value\n    }\n  }\n\n  return {\n    params,\n    hasValidParams,\n  }\n}\n\nexport function getServerUtils({\n  page,\n  i18n,\n  basePath,\n  rewrites,\n  pageIsDynamic,\n  trailingSlash,\n  caseSensitive,\n}: {\n  page: string\n  i18n?: NextConfig['i18n']\n  basePath: string\n  rewrites: DeepReadonly<{\n    fallback?: ReadonlyArray<Rewrite>\n    afterFiles?: ReadonlyArray<Rewrite>\n    beforeFiles?: ReadonlyArray<Rewrite>\n  }>\n  pageIsDynamic: boolean\n  trailingSlash?: boolean\n  caseSensitive: boolean\n}) {\n  let defaultRouteRegex: ReturnType<typeof getNamedRouteRegex> | undefined\n  let dynamicRouteMatcher: RouteMatchFn | undefined\n  let defaultRouteMatches: ParsedUrlQuery | undefined\n\n  if (pageIsDynamic) {\n    defaultRouteRegex = getNamedRouteRegex(page, {\n      prefixRouteKeys: false,\n    })\n    dynamicRouteMatcher = getRouteMatcher(defaultRouteRegex)\n    defaultRouteMatches = dynamicRouteMatcher(page) as ParsedUrlQuery\n  }\n\n  function handleRewrites(\n    req: BaseNextRequest | IncomingMessage,\n    parsedUrl: DeepReadonly<NextUrlWithParsedQuery>\n  ) {\n    // Here we deep clone the parsedUrl to avoid mutating the original. We also\n    // cast this to a mutable type so we can mutate it within this scope.\n    const rewrittenParsedUrl = structuredClone(\n      parsedUrl\n    ) as NextUrlWithParsedQuery\n    const rewriteParams: Record<string, string> = {}\n    let fsPathname = rewrittenParsedUrl.pathname\n\n    const matchesPage = () => {\n      const fsPathnameNoSlash = removeTrailingSlash(fsPathname || '')\n      return (\n        fsPathnameNoSlash === removeTrailingSlash(page) ||\n        dynamicRouteMatcher?.(fsPathnameNoSlash)\n      )\n    }\n\n    const checkRewrite = (rewrite: DeepReadonly<Rewrite>): boolean => {\n      const matcher = getPathMatch(\n        rewrite.source + (trailingSlash ? '(/)?' : ''),\n        {\n          removeUnnamedParams: true,\n          strict: true,\n          sensitive: !!caseSensitive,\n        }\n      )\n\n      if (!rewrittenParsedUrl.pathname) return false\n\n      let params = matcher(rewrittenParsedUrl.pathname)\n\n      if ((rewrite.has || rewrite.missing) && params) {\n        const hasParams = matchHas(\n          req,\n          rewrittenParsedUrl.query,\n          rewrite.has as Rewrite['has'],\n          rewrite.missing as Rewrite['missing']\n        )\n\n        if (hasParams) {\n          Object.assign(params, hasParams)\n        } else {\n          params = false\n        }\n      }\n\n      if (params) {\n        const { parsedDestination, destQuery } = prepareDestination({\n          appendParamsToQuery: true,\n          destination: rewrite.destination,\n          params: params,\n          query: rewrittenParsedUrl.query,\n        })\n\n        // if the rewrite destination is external break rewrite chain\n        if (parsedDestination.protocol) {\n          return true\n        }\n\n        Object.assign(rewriteParams, destQuery, params)\n        Object.assign(rewrittenParsedUrl.query, parsedDestination.query)\n        delete (parsedDestination as any).query\n\n        Object.assign(rewrittenParsedUrl, parsedDestination)\n\n        fsPathname = rewrittenParsedUrl.pathname\n        if (!fsPathname) return false\n\n        if (basePath) {\n          fsPathname = fsPathname.replace(new RegExp(`^${basePath}`), '') || '/'\n        }\n\n        if (i18n) {\n          const result = normalizeLocalePath(fsPathname, i18n.locales)\n          fsPathname = result.pathname\n          rewrittenParsedUrl.query.nextInternalLocale =\n            result.detectedLocale || params.nextInternalLocale\n        }\n\n        if (fsPathname === page) {\n          return true\n        }\n\n        if (pageIsDynamic && dynamicRouteMatcher) {\n          const dynamicParams = dynamicRouteMatcher(fsPathname)\n          if (dynamicParams) {\n            rewrittenParsedUrl.query = {\n              ...rewrittenParsedUrl.query,\n              ...dynamicParams,\n            }\n            return true\n          }\n        }\n      }\n\n      return false\n    }\n\n    for (const rewrite of rewrites.beforeFiles || []) {\n      checkRewrite(rewrite)\n    }\n\n    if (fsPathname !== page) {\n      let finished = false\n\n      for (const rewrite of rewrites.afterFiles || []) {\n        finished = checkRewrite(rewrite)\n        if (finished) break\n      }\n\n      if (!finished && !matchesPage()) {\n        for (const rewrite of rewrites.fallback || []) {\n          finished = checkRewrite(rewrite)\n          if (finished) break\n        }\n      }\n    }\n\n    return { rewriteParams, rewrittenParsedUrl }\n  }\n\n  function getParamsFromRouteMatches(routeMatchesHeader: string) {\n    // If we don't have a default route regex, we can't get params from route\n    // matches\n    if (!defaultRouteRegex) return null\n\n    const { groups, routeKeys } = defaultRouteRegex\n\n    const matcher = getRouteMatcher({\n      re: {\n        // Simulate a RegExp match from the \\`req.url\\` input\n        exec: (str: string) => {\n          // Normalize all the prefixed query params.\n          const obj: Record<string, string> = Object.fromEntries(\n            new URLSearchParams(str)\n          )\n          for (const [key, value] of Object.entries(obj)) {\n            const normalizedKey = normalizeNextQueryParam(key)\n            if (!normalizedKey) continue\n\n            obj[normalizedKey] = value\n            delete obj[key]\n          }\n\n          // Use all the named route keys.\n          const result = {} as RegExpExecArray\n          for (const keyName of Object.keys(routeKeys)) {\n            const paramName = routeKeys[keyName]\n\n            // If this param name is not a valid parameter name, then skip it.\n            if (!paramName) continue\n\n            const group = groups[paramName]\n            const value = obj[keyName]\n\n            // When we're missing a required param, we can't match the route.\n            if (!group.optional && !value) return null\n\n            result[group.pos] = value\n          }\n\n          return result\n        },\n      },\n      groups,\n    })\n\n    const routeMatches = matcher(routeMatchesHeader)\n    if (!routeMatches) return null\n\n    return routeMatches\n  }\n\n  function normalizeQueryParams(\n    query: Record<string, string | string[] | undefined>,\n    routeParamKeys: Set<string>\n  ) {\n    // this is used to pass query information in rewrites\n    // but should not be exposed in final query\n    delete query['nextInternalLocale']\n\n    for (const [key, value] of Object.entries(query)) {\n      const normalizedKey = normalizeNextQueryParam(key)\n      if (!normalizedKey) continue\n\n      // Remove the prefixed key from the query params because we want\n      // to consume it for the dynamic route matcher.\n      delete query[key]\n      routeParamKeys.add(normalizedKey)\n\n      if (typeof value === 'undefined') continue\n\n      query[normalizedKey] = Array.isArray(value)\n        ? value.map((v) => decodeQueryPathParameter(v))\n        : decodeQueryPathParameter(value)\n    }\n  }\n\n  return {\n    handleRewrites,\n    defaultRouteRegex,\n    dynamicRouteMatcher,\n    defaultRouteMatches,\n    normalizeQueryParams,\n    getParamsFromRouteMatches,\n    /**\n     * Normalize dynamic route params.\n     *\n     * @param query - The query params to normalize.\n     * @param ignoreMissingOptional - Whether to ignore missing optional params.\n     * @returns The normalized params and whether they are valid.\n     */\n    normalizeDynamicRouteParams: (\n      query: ParsedUrlQuery,\n      ignoreMissingOptional: boolean\n    ) => {\n      if (!defaultRouteRegex || !defaultRouteMatches) {\n        return { params: {}, hasValidParams: false }\n      }\n\n      return normalizeDynamicRouteParams(\n        query,\n        defaultRouteRegex,\n        defaultRouteMatches,\n        ignoreMissingOptional\n      )\n    },\n\n    normalizeCdnUrl: (\n      req: BaseNextRequest | IncomingMessage,\n      paramKeys: string[]\n    ) => normalizeCdnUrl(req, paramKeys),\n\n    interpolateDynamicPath: (\n      pathname: string,\n      params: Record<string, undefined | string | string[]>\n    ) => interpolateDynamicPath(pathname, params, defaultRouteRegex),\n\n    filterInternalQuery: (query: ParsedUrlQuery, paramKeys: string[]) =>\n      filterInternalQuery(query, paramKeys),\n  }\n}\n\nexport function getPreviouslyRevalidatedTags(\n  headers: IncomingHttpHeaders,\n  previewModeId: string | undefined\n): string[] {\n  return typeof headers[NEXT_CACHE_REVALIDATED_TAGS_HEADER] === 'string' &&\n    headers[NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER] === previewModeId\n    ? headers[NEXT_CACHE_REVALIDATED_TAGS_HEADER].split(',')\n    : []\n}\n","import { isPlainObject } from '../shared/lib/is-plain-object'\n\n// We allow some additional attached properties for Next.js errors\nexport interface NextError extends Error {\n  type?: string\n  page?: string\n  code?: string | number\n  cancelled?: boolean\n  digest?: string\n}\n\n/**\n * This is a safe stringify function that handles circular references.\n * We're using a simpler version here to avoid introducing\n * the dependency `safe-stable-stringify` into production bundle.\n *\n * This helper is used both in development and production.\n */\nfunction safeStringifyLite(obj: any) {\n  const seen = new WeakSet()\n\n  return JSON.stringify(obj, (_key, value) => {\n    // If value is an object and already seen, replace with \"[Circular]\"\n    if (typeof value === 'object' && value !== null) {\n      if (seen.has(value)) {\n        return '[Circular]'\n      }\n      seen.add(value)\n    }\n    return value\n  })\n}\n\n/**\n * Checks whether the given value is a NextError.\n * This can be used to print a more detailed error message with properties like `code` & `digest`.\n */\nexport default function isError(err: unknown): err is NextError {\n  return (\n    typeof err === 'object' && err !== null && 'name' in err && 'message' in err\n  )\n}\n\nexport function getProperError(err: unknown): Error {\n  if (isError(err)) {\n    return err\n  }\n\n  if (process.env.NODE_ENV === 'development') {\n    // provide better error for case where `throw undefined`\n    // is called in development\n    if (typeof err === 'undefined') {\n      return new Error(\n        'An undefined error was thrown, ' +\n          'see here for more info: https://nextjs.org/docs/messages/threw-undefined'\n      )\n    }\n\n    if (err === null) {\n      return new Error(\n        'A null error was thrown, ' +\n          'see here for more info: https://nextjs.org/docs/messages/threw-undefined'\n      )\n    }\n  }\n\n  return new Error(isPlainObject(err) ? safeStringifyLite(err) : err + '')\n}\n","export function getObjectClassLabel(value: any): string {\n  return Object.prototype.toString.call(value)\n}\n\nexport function isPlainObject(value: any): boolean {\n  if (getObjectClassLabel(value) !== '[object Object]') {\n    return false\n  }\n\n  const prototype = Object.getPrototypeOf(value)\n\n  /**\n   * this used to be previously:\n   *\n   * `return prototype === null || prototype === Object.prototype`\n   *\n   * but Edge Runtime expose Object from vm, being that kind of type-checking wrongly fail.\n   *\n   * It was changed to the current implementation since it's resilient to serialization.\n   */\n  return prototype === null || prototype.hasOwnProperty('isPrototypeOf')\n}\n","export const RSC_HEADER = 'rsc' as const\nexport const ACTION_HEADER = 'next-action' as const\n// TODO: Instead of sending the full router state, we only need to send the\n// segment path. Saves bytes. Then we could also use this field for segment\n// prefetches, which also need to specify a particular segment.\nexport const NEXT_ROUTER_STATE_TREE_HEADER = 'next-router-state-tree' as const\nexport const NEXT_ROUTER_PREFETCH_HEADER = 'next-router-prefetch' as const\n// This contains the path to the segment being prefetched.\n// TODO: If we change next-router-state-tree to be a segment path, we can use\n// that instead. Then next-router-prefetch and next-router-segment-prefetch can\n// be merged into a single enum.\nexport const NEXT_ROUTER_SEGMENT_PREFETCH_HEADER =\n  'next-router-segment-prefetch' as const\nexport const NEXT_HMR_REFRESH_HEADER = 'next-hmr-refresh' as const\nexport const NEXT_HMR_REFRESH_HASH_COOKIE = '__next_hmr_refresh_hash__' as const\nexport const NEXT_URL = 'next-url' as const\nexport const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const\n\n// Header for the Instant Navigation Testing API. In development and testing\n// builds, static pre-renders normally don't happen. This header tells the\n// server to perform a static pre-render anyway, allowing tests to assert on\n// the prefetched UI. Not exposed in production builds by default.\nexport const NEXT_INSTANT_PREFETCH_HEADER =\n  'next-instant-navigation-testing-prefetch' as const\n\n// Cookie for the Instant Navigation Testing API. Used for MPA navigations\n// (page reload, full page load) where we can't set request headers. When set,\n// the server renders only the static shell. Not exposed in production builds\n// by default.\nexport const NEXT_INSTANT_TEST_COOKIE =\n  'next-instant-navigation-testing' as const\n\nexport const FLIGHT_HEADERS = [\n  RSC_HEADER,\n  NEXT_ROUTER_STATE_TREE_HEADER,\n  NEXT_ROUTER_PREFETCH_HEADER,\n  NEXT_HMR_REFRESH_HEADER,\n  NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n] as const\n\nexport const NEXT_RSC_UNION_QUERY = '_rsc' as const\n\nexport const NEXT_ROUTER_STALE_TIME_HEADER = 'x-nextjs-stale-time' as const\nexport const NEXT_DID_POSTPONE_HEADER = 'x-nextjs-postponed' as const\nexport const NEXT_REWRITTEN_PATH_HEADER = 'x-nextjs-rewritten-path' as const\nexport const NEXT_REWRITTEN_QUERY_HEADER = 'x-nextjs-rewritten-query' as const\nexport const NEXT_IS_PRERENDER_HEADER = 'x-nextjs-prerender' as const\nexport const NEXT_ACTION_NOT_FOUND_HEADER = 'x-nextjs-action-not-found' as const\nexport const NEXT_REQUEST_ID_HEADER = 'x-nextjs-request-id' as const\nexport const NEXT_HTML_REQUEST_ID_HEADER = 'x-nextjs-html-request-id' as const\n\n// TODO: Should this include nextjs in the name, like the others?\nexport const NEXT_ACTION_REVALIDATED_HEADER = 'x-action-revalidated' as const\n","import type { I18NProvider } from '../lib/i18n-provider'\nimport type { Normalizer } from './normalizer'\n\n/**\n * Normalizes the pathname by removing the locale prefix if any.\n */\nexport class LocaleRouteNormalizer implements Normalizer {\n  constructor(private readonly provider: I18NProvider) {}\n\n  /**\n   * Normalizes the pathname by removing the locale prefix if any.\n   *\n   * @param pathname The pathname to normalize.\n   * @returns The pathname without the locale prefix (if any).\n   */\n  public normalize(pathname: string): string {\n    const match = this.provider.analyze(pathname)\n    return match.pathname\n  }\n}\n","class UrlNode {\n  placeholder: boolean = true\n  children: Map<string, UrlNode> = new Map()\n  slugName: string | null = null\n  restSlugName: string | null = null\n  optionalRestSlugName: string | null = null\n\n  insert(urlPath: string): void {\n    this._insert(urlPath.split('/').filter(Boolean), [], false)\n  }\n\n  smoosh(): string[] {\n    return this._smoosh()\n  }\n\n  private _smoosh(prefix: string = '/'): string[] {\n    const childrenPaths = [...this.children.keys()].sort()\n    if (this.slugName !== null) {\n      childrenPaths.splice(childrenPaths.indexOf('[]'), 1)\n    }\n    if (this.restSlugName !== null) {\n      childrenPaths.splice(childrenPaths.indexOf('[...]'), 1)\n    }\n    if (this.optionalRestSlugName !== null) {\n      childrenPaths.splice(childrenPaths.indexOf('[[...]]'), 1)\n    }\n\n    const routes = childrenPaths\n      .map((c) => this.children.get(c)!._smoosh(`${prefix}${c}/`))\n      .reduce((prev, curr) => [...prev, ...curr], [])\n\n    if (this.slugName !== null) {\n      routes.push(\n        ...this.children.get('[]')!._smoosh(`${prefix}[${this.slugName}]/`)\n      )\n    }\n\n    if (!this.placeholder) {\n      const r = prefix === '/' ? '/' : prefix.slice(0, -1)\n      if (this.optionalRestSlugName != null) {\n        throw new Error(\n          `You cannot define a route with the same specificity as a optional catch-all route (\"${r}\" and \"${r}[[...${this.optionalRestSlugName}]]\").`\n        )\n      }\n\n      routes.unshift(r)\n    }\n\n    if (this.restSlugName !== null) {\n      routes.push(\n        ...this.children\n          .get('[...]')!\n          ._smoosh(`${prefix}[...${this.restSlugName}]/`)\n      )\n    }\n\n    if (this.optionalRestSlugName !== null) {\n      routes.push(\n        ...this.children\n          .get('[[...]]')!\n          ._smoosh(`${prefix}[[...${this.optionalRestSlugName}]]/`)\n      )\n    }\n\n    return routes\n  }\n\n  private _insert(\n    urlPaths: string[],\n    slugNames: string[],\n    isCatchAll: boolean\n  ): void {\n    if (urlPaths.length === 0) {\n      this.placeholder = false\n      return\n    }\n\n    if (isCatchAll) {\n      throw new Error(`Catch-all must be the last part of the URL.`)\n    }\n\n    // The next segment in the urlPaths list\n    let nextSegment = urlPaths[0]\n\n    // Check if the segment matches `[something]`\n    if (nextSegment.startsWith('[') && nextSegment.endsWith(']')) {\n      // Strip `[` and `]`, leaving only `something`\n      let segmentName = nextSegment.slice(1, -1)\n\n      let isOptional = false\n      if (segmentName.startsWith('[') && segmentName.endsWith(']')) {\n        // Strip optional `[` and `]`, leaving only `something`\n        segmentName = segmentName.slice(1, -1)\n        isOptional = true\n      }\n\n      if (segmentName.startsWith('…')) {\n        throw new Error(\n          `Detected a three-dot character ('…') at ('${segmentName}'). Did you mean ('...')?`\n        )\n      }\n\n      if (segmentName.startsWith('...')) {\n        // Strip `...`, leaving only `something`\n        segmentName = segmentName.substring(3)\n        isCatchAll = true\n      }\n\n      if (segmentName.startsWith('[') || segmentName.endsWith(']')) {\n        throw new Error(\n          `Segment names may not start or end with extra brackets ('${segmentName}').`\n        )\n      }\n\n      if (segmentName.startsWith('.')) {\n        throw new Error(\n          `Segment names may not start with erroneous periods ('${segmentName}').`\n        )\n      }\n\n      function handleSlug(previousSlug: string | null, nextSlug: string) {\n        if (previousSlug !== null) {\n          // If the specific segment already has a slug but the slug is not `something`\n          // This prevents collisions like:\n          // pages/[post]/index.js\n          // pages/[id]/index.js\n          // Because currently multiple dynamic params on the same segment level are not supported\n          if (previousSlug !== nextSlug) {\n            // TODO: This error seems to be confusing for users, needs an error link, the description can be based on above comment.\n            throw new Error(\n              `You cannot use different slug names for the same dynamic path ('${previousSlug}' !== '${nextSlug}').`\n            )\n          }\n        }\n\n        slugNames.forEach((slug) => {\n          if (slug === nextSlug) {\n            throw new Error(\n              `You cannot have the same slug name \"${nextSlug}\" repeat within a single dynamic path`\n            )\n          }\n\n          if (slug.replace(/\\W/g, '') === nextSegment.replace(/\\W/g, '')) {\n            throw new Error(\n              `You cannot have the slug names \"${slug}\" and \"${nextSlug}\" differ only by non-word symbols within a single dynamic path`\n            )\n          }\n        })\n\n        slugNames.push(nextSlug)\n      }\n\n      if (isCatchAll) {\n        if (isOptional) {\n          if (this.restSlugName != null) {\n            throw new Error(\n              `You cannot use both an required and optional catch-all route at the same level (\"[...${this.restSlugName}]\" and \"${urlPaths[0]}\" ).`\n            )\n          }\n\n          handleSlug(this.optionalRestSlugName, segmentName)\n          // slugName is kept as it can only be one particular slugName\n          this.optionalRestSlugName = segmentName\n          // nextSegment is overwritten to [[...]] so that it can later be sorted specifically\n          nextSegment = '[[...]]'\n        } else {\n          if (this.optionalRestSlugName != null) {\n            throw new Error(\n              `You cannot use both an optional and required catch-all route at the same level (\"[[...${this.optionalRestSlugName}]]\" and \"${urlPaths[0]}\").`\n            )\n          }\n\n          handleSlug(this.restSlugName, segmentName)\n          // slugName is kept as it can only be one particular slugName\n          this.restSlugName = segmentName\n          // nextSegment is overwritten to [...] so that it can later be sorted specifically\n          nextSegment = '[...]'\n        }\n      } else {\n        if (isOptional) {\n          throw new Error(\n            `Optional route parameters are not yet supported (\"${urlPaths[0]}\").`\n          )\n        }\n        handleSlug(this.slugName, segmentName)\n        // slugName is kept as it can only be one particular slugName\n        this.slugName = segmentName\n        // nextSegment is overwritten to [] so that it can later be sorted specifically\n        nextSegment = '[]'\n      }\n    }\n\n    // If this UrlNode doesn't have the nextSegment yet we create a new child UrlNode\n    if (!this.children.has(nextSegment)) {\n      this.children.set(nextSegment, new UrlNode())\n    }\n\n    this.children\n      .get(nextSegment)!\n      ._insert(urlPaths.slice(1), slugNames, isCatchAll)\n  }\n}\n\n/**\n * @deprecated Use `sortSortableRoutes` or `sortPages` instead.\n */\nexport function getSortedRoutes(\n  normalizedPages: ReadonlyArray<string>\n): string[] {\n  // First the UrlNode is created, and every UrlNode can have only 1 dynamic segment\n  // Eg you can't have pages/[post]/abc.js and pages/[hello]/something-else.js\n  // Only 1 dynamic segment per nesting level\n\n  // So in the case that is test/integration/dynamic-routing it'll be this:\n  // pages/[post]/comments.js\n  // pages/blog/[post]/comment/[id].js\n  // Both are fine because `pages/[post]` and `pages/blog` are on the same level\n  // So in this case `UrlNode` created here has `this.slugName === 'post'`\n  // And since your PR passed through `slugName` as an array basically it'd including it in too many possibilities\n  // Instead what has to be passed through is the upwards path's dynamic names\n  const root = new UrlNode()\n\n  // Here the `root` gets injected multiple paths, and insert will break them up into sublevels\n  normalizedPages.forEach((pagePath) => root.insert(pagePath))\n  // Smoosh will then sort those sublevels up to the point where you get the correct route definition priority\n  return root.smoosh()\n}\n\n/**\n * @deprecated Use `sortSortableRouteObjects` or `sortPageObjects` instead.\n */\nexport function getSortedRouteObjects<T>(\n  objects: T[],\n  getter: (obj: T) => string\n): T[] {\n  // We're assuming here that all the pathnames are unique, that way we can\n  // sort the list and use the index as the key.\n  const indexes: Record<string, number> = {}\n  const pathnames: string[] = []\n  for (let i = 0; i < objects.length; i++) {\n    const pathname = getter(objects[i])\n    indexes[pathname] = i\n    pathnames[i] = pathname\n  }\n\n  // Sort the pathnames.\n  const sorted = getSortedRoutes(pathnames)\n\n  // Map the sorted pathnames back to the original objects using the new sorted\n  // index.\n  return sorted.map((pathname) => objects[indexes[pathname]])\n}\n","import type { RouteMatch } from '../route-matches/route-match'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { Params } from '../request/params'\n\nimport { isDynamicRoute } from '../../shared/lib/router/utils'\nimport {\n  getRouteMatcher,\n  type RouteMatchFn,\n} from '../../shared/lib/router/utils/route-matcher'\nimport { getRouteRegex } from '../../shared/lib/router/utils/route-regex'\n\ntype RouteMatchResult = {\n  params?: Params\n}\n\nexport class RouteMatcher<D extends RouteDefinition = RouteDefinition> {\n  private readonly dynamic?: RouteMatchFn\n\n  /**\n   * When set, this is an array of all the other matchers that are duplicates of\n   * this one. This is used by the managers to warn the users about possible\n   * duplicate matches on routes.\n   */\n  public duplicated?: Array<RouteMatcher>\n\n  constructor(public readonly definition: D) {\n    if (isDynamicRoute(definition.pathname)) {\n      this.dynamic = getRouteMatcher(getRouteRegex(definition.pathname))\n    }\n  }\n\n  /**\n   * Identity returns the identity part of the matcher. This is used to compare\n   * a unique matcher to another. This is also used when sorting dynamic routes,\n   * so it must contain the pathname part.\n   */\n  public get identity(): string {\n    return this.definition.pathname\n  }\n\n  public get isDynamic() {\n    return this.dynamic !== undefined\n  }\n\n  public match(pathname: string): RouteMatch<D> | null {\n    const result = this.test(pathname)\n    if (!result) return null\n\n    return { definition: this.definition, params: result.params }\n  }\n\n  public test(pathname: string): RouteMatchResult | null {\n    if (this.dynamic) {\n      const params = this.dynamic(pathname)\n      if (!params) return null\n\n      return { params }\n    }\n\n    if (pathname === this.definition.pathname) {\n      return {}\n    }\n\n    return null\n  }\n}\n","import type { LocaleAnalysisResult } from '../lib/i18n-provider'\nimport type { LocaleRouteDefinition } from '../route-definitions/locale-route-definition'\nimport type { LocaleRouteMatch } from '../route-matches/locale-route-match'\nimport { RouteMatcher } from './route-matcher'\n\nexport type LocaleMatcherMatchOptions = {\n  /**\n   * If defined, this indicates to the matcher that the request should be\n   * treated as locale-aware. If this is undefined, it means that this\n   * application was not configured for additional locales.\n   */\n  i18n?: LocaleAnalysisResult\n}\n\nexport class LocaleRouteMatcher<\n  D extends LocaleRouteDefinition = LocaleRouteDefinition,\n> extends RouteMatcher<D> {\n  /**\n   * Identity returns the identity part of the matcher. This is used to compare\n   * a unique matcher to another. This is also used when sorting dynamic routes,\n   * so it must contain the pathname part as well.\n   */\n  public get identity(): string {\n    return `${this.definition.pathname}?__nextLocale=${this.definition.i18n?.locale}`\n  }\n\n  /**\n   * Match will attempt to match the given pathname against this route while\n   * also taking into account the locale information.\n   *\n   * @param pathname The pathname to match against.\n   * @param options The options to use when matching.\n   * @returns The match result, or `null` if there was no match.\n   */\n  public match(\n    pathname: string,\n    options?: LocaleMatcherMatchOptions\n  ): LocaleRouteMatch<D> | null {\n    // This is like the parent `match` method but instead this injects the\n    // additional `options` into the\n    const result = this.test(pathname, options)\n    if (!result) return null\n\n    return {\n      definition: this.definition,\n      params: result.params,\n      detectedLocale:\n        // If the options have a detected locale, then use that, otherwise use\n        // the route's locale.\n        options?.i18n?.detectedLocale ?? this.definition.i18n?.locale,\n    }\n  }\n\n  /**\n   * Test will attempt to match the given pathname against this route while\n   * also taking into account the locale information.\n   *\n   * @param pathname The pathname to match against.\n   * @param options The options to use when matching.\n   * @returns The match result, or `null` if there was no match.\n   */\n  public test(pathname: string, options?: LocaleMatcherMatchOptions) {\n    // If this route has locale information and we have detected a locale, then\n    // we need to compare the detected locale to the route's locale.\n    if (this.definition.i18n && options?.i18n) {\n      // If we have detected a locale and it does not match this route's locale,\n      // then this isn't a match!\n      if (\n        this.definition.i18n.locale &&\n        options.i18n.detectedLocale &&\n        this.definition.i18n.locale !== options.i18n.detectedLocale\n      ) {\n        return null\n      }\n\n      // Perform regular matching against the locale stripped pathname now, the\n      // locale information matches!\n      return super.test(options.i18n.pathname)\n    }\n\n    // If we don't have locale information, then we can just perform regular\n    // matching.\n    return super.test(pathname)\n  }\n}\n","import { isDynamicRoute } from '../../shared/lib/router/utils'\nimport type { RouteKind } from '../route-kind'\nimport type { RouteMatch } from '../route-matches/route-match'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { RouteMatcherProvider } from '../route-matcher-providers/route-matcher-provider'\nimport type { RouteMatcher } from '../route-matchers/route-matcher'\nimport type { MatchOptions, RouteMatcherManager } from './route-matcher-manager'\nimport { getSortedRoutes } from '../../shared/lib/router/utils'\nimport { LocaleRouteMatcher } from '../route-matchers/locale-route-matcher'\nimport { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-slash'\nimport { DetachedPromise } from '../../lib/detached-promise'\n\ninterface RouteMatchers {\n  static: ReadonlyArray<RouteMatcher>\n  dynamic: ReadonlyArray<RouteMatcher>\n  duplicates: Record<string, ReadonlyArray<RouteMatcher>>\n}\n\nexport class DefaultRouteMatcherManager implements RouteMatcherManager {\n  private readonly providers: Array<RouteMatcherProvider> = []\n  protected readonly matchers: RouteMatchers = {\n    static: [],\n    dynamic: [],\n    duplicates: {},\n  }\n  private lastCompilationID = this.compilationID\n\n  /**\n   * When this value changes, it indicates that a change has been introduced\n   * that requires recompilation.\n   */\n  private get compilationID() {\n    return this.providers.length\n  }\n\n  private waitTillReadyPromise?: Promise<void>\n  public async waitTillReady(): Promise<void> {\n    if (this.waitTillReadyPromise) {\n      await this.waitTillReadyPromise\n      delete this.waitTillReadyPromise\n    }\n  }\n\n  private previousMatchers: ReadonlyArray<RouteMatcher> = []\n  public async reload() {\n    const { promise, resolve, reject } = new DetachedPromise<void>()\n    this.waitTillReadyPromise = promise\n\n    // Grab the compilation ID for this run, we'll verify it at the end to\n    // ensure that if any routes were added before reloading is finished that\n    // we error out.\n    const compilationID = this.compilationID\n\n    try {\n      // Collect all the matchers from each provider.\n      const matchers: Array<RouteMatcher> = []\n\n      // Get all the providers matchers.\n      const providersMatchers: ReadonlyArray<ReadonlyArray<RouteMatcher>> =\n        await Promise.all(this.providers.map((provider) => provider.matchers()))\n\n      // Use this to detect duplicate pathnames.\n      const all = new Map<string, RouteMatcher>()\n      const duplicates: Record<string, RouteMatcher[]> = {}\n      for (const providerMatchers of providersMatchers) {\n        for (const matcher of providerMatchers) {\n          // Reset duplicated matches when reloading from pages conflicting state.\n          if (matcher.duplicated) delete matcher.duplicated\n          // Test to see if the matcher being added is a duplicate.\n          const duplicate = all.get(matcher.definition.pathname)\n          if (duplicate) {\n            // This looks a little weird, but essentially if the pathname\n            // already exists in the duplicates map, then we got that array\n            // reference. Otherwise, we create a new array with the original\n            // duplicate first. Then we push the new matcher into the duplicate\n            // array, and reset it to the duplicates object (which may be a\n            // no-op if the pathname already existed in the duplicates object).\n            // Then we set the array of duplicates on both the original\n            // duplicate object and the new one, so we can keep them in sync.\n            // If a new duplicate is found, and it matches an existing pathname,\n            // the retrieval of the `other` will actually return the array\n            // reference used by all other duplicates. This is why ReadonlyArray\n            // is so important! Array's are always references!\n            const others = duplicates[matcher.definition.pathname] ?? [\n              duplicate,\n            ]\n            others.push(matcher)\n            duplicates[matcher.definition.pathname] = others\n\n            // Add duplicated details to each route.\n            duplicate.duplicated = others\n            matcher.duplicated = others\n\n            // TODO: see if we should error for duplicates in production?\n          }\n\n          matchers.push(matcher)\n\n          // Add the matcher's pathname to the set.\n          all.set(matcher.definition.pathname, matcher)\n        }\n      }\n\n      // Update the duplicate matchers. This is used in the development manager\n      // to warn about duplicates.\n      this.matchers.duplicates = duplicates\n\n      // If the cache is the same as what we just parsed, we can exit now. We\n      // can tell by using the `===` which compares object identity, which for\n      // the manifest matchers, will return the same matcher each time.\n      if (\n        this.previousMatchers.length === matchers.length &&\n        this.previousMatchers.every(\n          (cachedMatcher, index) => cachedMatcher === matchers[index]\n        )\n      ) {\n        return\n      }\n      this.previousMatchers = matchers\n\n      // For matchers that are for static routes, filter them now.\n      this.matchers.static = matchers.filter((matcher) => !matcher.isDynamic)\n\n      // For matchers that are for dynamic routes, filter them and sort them now.\n      const dynamic = matchers.filter((matcher) => matcher.isDynamic)\n\n      // As `getSortedRoutes` only takes an array of strings, we need to create\n      // a map of the pathnames (used for sorting) and the matchers. When we\n      // have locales, there may be multiple matches for the same pathname. To\n      // handle this, we keep a map of all the indexes (in `reference`) and\n      // merge them in later.\n\n      const reference = new Map<string, number[]>()\n      const pathnames = new Array<string>()\n      for (let index = 0; index < dynamic.length; index++) {\n        // Grab the pathname from the definition.\n        const pathname = dynamic[index].definition.pathname\n\n        // Grab the index in the dynamic array, push it into the reference.\n        const indexes = reference.get(pathname) ?? []\n        indexes.push(index)\n\n        // If this is the first one set it. If it isn't, we don't need to\n        // because pushing above on the array will mutate the array already\n        // stored there because array's are always a reference!\n        if (indexes.length === 1) reference.set(pathname, indexes)\n        // Otherwise, continue, we've already added this pathname before.\n        else continue\n\n        pathnames.push(pathname)\n      }\n\n      // Sort the array of pathnames.\n      const sorted = getSortedRoutes(pathnames)\n\n      // For each of the sorted pathnames, iterate over them, grabbing the list\n      // of indexes and merging them back into the new `sortedDynamicMatchers`\n      // array. The order of the same matching pathname doesn't matter because\n      // they will have other matching characteristics (like the locale) that\n      // is considered.\n      const sortedDynamicMatchers: Array<RouteMatcher> = []\n      for (const pathname of sorted) {\n        const indexes = reference.get(pathname)\n        if (!Array.isArray(indexes)) {\n          throw new Error('Invariant: expected to find identity in indexes map')\n        }\n\n        const dynamicMatches = indexes.map((index) => dynamic[index])\n\n        sortedDynamicMatchers.push(...dynamicMatches)\n      }\n\n      this.matchers.dynamic = sortedDynamicMatchers\n\n      // This means that there was a new matcher pushed while we were waiting\n      if (this.compilationID !== compilationID) {\n        throw new Error(\n          'Invariant: expected compilation to finish before new matchers were added, possible missing await'\n        )\n      }\n    } catch (err) {\n      reject(err)\n    } finally {\n      // The compilation ID matched, so mark the complication as finished.\n      this.lastCompilationID = compilationID\n      resolve()\n    }\n  }\n\n  public push(provider: RouteMatcherProvider): void {\n    this.providers.push(provider)\n  }\n\n  public async test(pathname: string, options: MatchOptions): Promise<boolean> {\n    // See if there's a match for the pathname...\n    const match = await this.match(pathname, options)\n\n    // This default implementation only needs to check to see if there _was_ a\n    // match. The development matcher actually changes it's behavior by not\n    // recompiling the routes.\n    return match !== null\n  }\n\n  public async match(\n    pathname: string,\n    options: MatchOptions\n  ): Promise<RouteMatch<RouteDefinition<RouteKind>> | null> {\n    // \"Iterate\" over the match options. Once we found a single match, exit with\n    // it, otherwise return null below. If no match is found, the inner block\n    // won't be called.\n    for await (const match of this.matchAll(pathname, options)) {\n      return match\n    }\n\n    return null\n  }\n\n  /**\n   * This is a point for other managers to override to inject other checking\n   * behavior like duplicate route checking on a per-request basis.\n   *\n   * @param pathname the pathname to validate against\n   * @param matcher the matcher to validate/test with\n   * @returns the match if found\n   */\n  protected validate(\n    pathname: string,\n    matcher: RouteMatcher,\n    options: MatchOptions\n  ): RouteMatch | null {\n    if (matcher instanceof LocaleRouteMatcher) {\n      return matcher.match(pathname, options)\n    }\n\n    // If the locale was inferred from the default locale, then it will have\n    // already added a locale to the pathname. We need to remove it before\n    // matching because this matcher is not locale aware.\n    if (options.i18n?.inferredFromDefault) {\n      return matcher.match(options.i18n.pathname)\n    }\n\n    return matcher.match(pathname)\n  }\n\n  public async *matchAll(\n    pathname: string,\n    options: MatchOptions\n  ): AsyncGenerator<RouteMatch<RouteDefinition<RouteKind>>, null, undefined> {\n    // Guard against the matcher manager from being run before it needs to be\n    // recompiled. This was preferred to re-running the compilation here because\n    // it should be re-ran only when it changes. If a match is attempted before\n    // this is done, it indicates that there is a case where a provider is added\n    // before it was recompiled (an error). We also don't want to affect request\n    // times.\n    if (this.lastCompilationID !== this.compilationID) {\n      throw new Error(\n        'Invariant: expected routes to have been loaded before match'\n      )\n    }\n\n    // Ensure that path matching is done with a leading slash.\n    pathname = ensureLeadingSlash(pathname)\n\n    // If this pathname doesn't look like a dynamic route, and this pathname is\n    // listed in the normalized list of routes, then return it. This ensures\n    // that when a route like `/user/[id]` is encountered, it doesn't just match\n    // with the list of normalized routes.\n    if (!isDynamicRoute(pathname)) {\n      for (const matcher of this.matchers.static) {\n        const match = this.validate(pathname, matcher, options)\n        if (!match) continue\n\n        yield match\n      }\n    }\n\n    // If we should skip handling dynamic routes, exit now.\n    if (options?.skipDynamic) return null\n\n    // Loop over the dynamic matchers, yielding each match.\n    for (const matcher of this.matchers.dynamic) {\n      const match = this.validate(pathname, matcher, options)\n      if (!match) continue\n\n      yield match\n    }\n\n    // We tried direct matching against the pathname and against all the dynamic\n    // paths, so there was no match.\n    return null\n  }\n}\n","import type { Normalizer } from './normalizer'\n\n/**\n * Normalizers combines many normalizers into a single normalizer interface that\n * will normalize the inputted pathname with each normalizer in order.\n */\nexport class Normalizers implements Normalizer {\n  constructor(private readonly normalizers: Array<Normalizer> = []) {}\n\n  public push(normalizer: Normalizer) {\n    this.normalizers.push(normalizer)\n  }\n\n  public normalize(pathname: string): string {\n    return this.normalizers.reduce<string>(\n      (normalized, normalizer) => normalizer.normalize(normalized),\n      pathname\n    )\n  }\n}\n","import path from '../../shared/lib/isomorphic/path'\nimport type { Normalizer } from './normalizer'\n\nexport class PrefixingNormalizer implements Normalizer {\n  private readonly prefix: string\n\n  constructor(...prefixes: ReadonlyArray<string>) {\n    this.prefix = path.posix.join(...prefixes)\n  }\n\n  public normalize(pathname: string): string {\n    return path.posix.join(this.prefix, pathname)\n  }\n}\n","import { ensureLeadingSlash } from './ensure-leading-slash'\nimport { isDynamicRoute } from '../router/utils'\nimport { NormalizeError } from '../utils'\n\n/**\n * Takes a page and transforms it into its file counterpart ensuring that the\n * output is normalized. Note this function is not idempotent because a page\n * `/index` can be referencing `/index/index.js` and `/index/index` could be\n * referencing `/index/index/index.js`. Examples:\n *  - `/` -> `/index`\n *  - `/index/foo` -> `/index/index/foo`\n *  - `/index` -> `/index/index`\n */\nexport function normalizePagePath(page: string): string {\n  const normalized =\n    /^\\/index(\\/|$)/.test(page) && !isDynamicRoute(page)\n      ? `/index${page}`\n      : page === '/'\n        ? '/index'\n        : ensureLeadingSlash(page)\n\n  if (process.env.NEXT_RUNTIME !== 'edge') {\n    const { posix } = require('path') as typeof import('path')\n    const resolvedPage = posix.normalize(normalized)\n    if (resolvedPage !== normalized) {\n      throw new NormalizeError(\n        `Requested and resolved page mismatch: ${normalized} ${resolvedPage}`\n      )\n    }\n  }\n\n  return normalized\n}\n","import type { Normalizer } from './normalizer'\n\n/**\n * UnderscoreNormalizer replaces all instances of %5F with _.\n */\nexport class UnderscoreNormalizer implements Normalizer {\n  public normalize(pathname: string): string {\n    return pathname.replace(/%5F/g, '_')\n  }\n}\n","import { Normalizers } from '../../normalizers'\nimport type { Normalizer } from '../../normalizer'\nimport { PrefixingNormalizer } from '../../prefixing-normalizer'\nimport { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path'\nimport { UnderscoreNormalizer } from '../../underscore-normalizer'\n\nexport class AppBundlePathNormalizer extends PrefixingNormalizer {\n  constructor() {\n    super('app')\n  }\n\n  public normalize(page: string): string {\n    return super.normalize(normalizePagePath(page))\n  }\n}\n\nexport class DevAppBundlePathNormalizer extends Normalizers {\n  constructor(pageNormalizer: Normalizer, isTurbopack: boolean) {\n    const normalizers = [\n      // This should normalize the filename to a page.\n      pageNormalizer,\n      // Normalize the app page to a pathname.\n      new AppBundlePathNormalizer(),\n    ]\n\n    // %5F to _ replacement should only happen with Turbopack.\n    if (isTurbopack) {\n      normalizers.unshift(new UnderscoreNormalizer())\n    }\n    super(normalizers)\n  }\n\n  public normalize(filename: string): string {\n    return super.normalize(filename)\n  }\n}\n","import { SERVER_DIRECTORY } from '../../../../shared/lib/constants'\nimport { PrefixingNormalizer } from '../../prefixing-normalizer'\n\nexport class AppFilenameNormalizer extends PrefixingNormalizer {\n  constructor(distDir: string) {\n    super(distDir, SERVER_DIRECTORY)\n  }\n\n  public normalize(manifestFilename: string): string {\n    return super.normalize(manifestFilename)\n  }\n}\n","export function isAppRouteRoute(route: string): boolean {\n  return route.endsWith('/route')\n}\n","import type { PageExtensions } from '../../build/page-extensions-type'\nimport { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport { isAppRouteRoute } from '../is-app-route-route'\n\nexport const STATIC_METADATA_IMAGES = {\n  icon: {\n    filename: 'icon',\n    extensions: ['ico', 'jpg', 'jpeg', 'png', 'svg'],\n  },\n  apple: {\n    filename: 'apple-icon',\n    extensions: ['jpg', 'jpeg', 'png'],\n  },\n  favicon: {\n    filename: 'favicon',\n    extensions: ['ico'],\n  },\n  openGraph: {\n    filename: 'opengraph-image',\n    extensions: ['jpg', 'jpeg', 'png', 'gif'],\n  },\n  twitter: {\n    filename: 'twitter-image',\n    extensions: ['jpg', 'jpeg', 'png', 'gif'],\n  },\n} as const\n\n// Match routes that are metadata routes, e.g. /sitemap.xml, /favicon.<ext>, /<icon>.<ext>, etc.\n// TODO-METADATA: support more metadata routes with more extensions\nexport const DEFAULT_METADATA_ROUTE_EXTENSIONS = ['js', 'jsx', 'ts', 'tsx']\n\n// Match the file extension with the dynamic multi-routes extensions\n// e.g. ([xml, js], null) -> can match `/sitemap.xml/route`, `sitemap.js/route`\n// e.g. ([png], [ts]) -> can match `/opengraph-image.png`, `/opengraph-image.ts`\nexport const getExtensionRegexString = (\n  staticExtensions: readonly string[],\n  dynamicExtensions: readonly string[] | null\n) => {\n  let result: string\n  // If there's no possible multi dynamic routes, will not match any <name>[].<ext> files\n  if (!dynamicExtensions || dynamicExtensions.length === 0) {\n    result = `(\\\\.(?:${staticExtensions.join('|')}))`\n  } else {\n    result = `(?:\\\\.(${staticExtensions.join('|')})|(\\\\.(${dynamicExtensions.join('|')})))`\n  }\n  return result\n}\n\n/**\n * Matches the static metadata files, e.g. /robots.txt, /sitemap.xml, /favicon.ico, etc.\n * @param appDirRelativePath the relative file path to app/\n * @returns if the path is a static metadata file route\n */\nexport function isStaticMetadataFile(appDirRelativePath: string) {\n  return isMetadataRouteFile(appDirRelativePath, [], true)\n}\n\n// Pre-compiled static regexes for common cases\nconst FAVICON_REGEX = /^[\\\\/]favicon\\.ico$/\nconst ROBOTS_TXT_REGEX = /^[\\\\/]robots\\.txt$/\nconst MANIFEST_JSON_REGEX = /^[\\\\/]manifest\\.json$/\nconst MANIFEST_WEBMANIFEST_REGEX = /^[\\\\/]manifest\\.webmanifest$/\nconst SITEMAP_XML_REGEX = /[\\\\/]sitemap\\.xml$/\n\n// Cache for compiled regex patterns based on parameters\nconst compiledRegexCache = new Map<string, RegExp[]>()\n\n// Fast path checks for common metadata files\nfunction fastPathCheck(normalizedPath: string): boolean | null {\n  // Check favicon.ico first (most common)\n  if (FAVICON_REGEX.test(normalizedPath)) return true\n\n  // Check other common static files\n  if (ROBOTS_TXT_REGEX.test(normalizedPath)) return true\n  if (MANIFEST_JSON_REGEX.test(normalizedPath)) return true\n  if (MANIFEST_WEBMANIFEST_REGEX.test(normalizedPath)) return true\n  if (SITEMAP_XML_REGEX.test(normalizedPath)) return true\n\n  // Quick negative check - if it doesn't contain any metadata keywords, skip\n  if (\n    !normalizedPath.includes('robots') &&\n    !normalizedPath.includes('manifest') &&\n    !normalizedPath.includes('sitemap') &&\n    !normalizedPath.includes('icon') &&\n    !normalizedPath.includes('apple-icon') &&\n    !normalizedPath.includes('opengraph-image') &&\n    !normalizedPath.includes('twitter-image') &&\n    !normalizedPath.includes('favicon')\n  ) {\n    return false\n  }\n\n  return null // Continue with full regex matching\n}\n\nfunction getCompiledRegexes(\n  pageExtensions: PageExtensions,\n  strictlyMatchExtensions: boolean\n): RegExp[] {\n  // Create cache key\n  const cacheKey = `${pageExtensions.join(',')}|${strictlyMatchExtensions}`\n\n  const cached = compiledRegexCache.get(cacheKey)\n  if (cached) {\n    return cached\n  }\n\n  // Pre-compute common strings\n  const trailingMatcher = strictlyMatchExtensions ? '$' : '?$'\n  const variantsMatcher = '\\\\d?'\n  const groupSuffix = strictlyMatchExtensions ? '' : '(-\\\\w{6})?'\n  const suffixMatcher = variantsMatcher + groupSuffix\n\n  // Pre-compute extension arrays to avoid repeated concatenation\n  const robotsExts =\n    pageExtensions.length > 0 ? [...pageExtensions, 'txt'] : ['txt']\n  const manifestExts =\n    pageExtensions.length > 0\n      ? [...pageExtensions, 'webmanifest', 'json']\n      : ['webmanifest', 'json']\n\n  const regexes = [\n    new RegExp(\n      `^[\\\\\\\\/]robots${getExtensionRegexString(robotsExts, null)}${trailingMatcher}`\n    ),\n    new RegExp(\n      `^[\\\\\\\\/]manifest${getExtensionRegexString(manifestExts, null)}${trailingMatcher}`\n    ),\n    // FAVICON_REGEX removed - already handled in fastPathCheck\n    new RegExp(\n      `[\\\\\\\\/]sitemap${getExtensionRegexString(['xml'], pageExtensions)}${trailingMatcher}`\n    ),\n    new RegExp(\n      `[\\\\\\\\/]icon${suffixMatcher}${getExtensionRegexString(\n        STATIC_METADATA_IMAGES.icon.extensions,\n        pageExtensions\n      )}${trailingMatcher}`\n    ),\n    new RegExp(\n      `[\\\\\\\\/]apple-icon${suffixMatcher}${getExtensionRegexString(\n        STATIC_METADATA_IMAGES.apple.extensions,\n        pageExtensions\n      )}${trailingMatcher}`\n    ),\n    new RegExp(\n      `[\\\\\\\\/]opengraph-image${suffixMatcher}${getExtensionRegexString(\n        STATIC_METADATA_IMAGES.openGraph.extensions,\n        pageExtensions\n      )}${trailingMatcher}`\n    ),\n    new RegExp(\n      `[\\\\\\\\/]twitter-image${suffixMatcher}${getExtensionRegexString(\n        STATIC_METADATA_IMAGES.twitter.extensions,\n        pageExtensions\n      )}${trailingMatcher}`\n    ),\n  ]\n\n  compiledRegexCache.set(cacheKey, regexes)\n  return regexes\n}\n\n/**\n * Determine if the file is a metadata route file entry\n * @param appDirRelativePath the relative file path to app/\n * @param pageExtensions the js extensions, such as ['js', 'jsx', 'ts', 'tsx']\n * @param strictlyMatchExtensions if it's true, match the file with page extension, otherwise match the file with default corresponding extension\n * @returns if the file is a metadata route file\n */\nexport function isMetadataRouteFile(\n  appDirRelativePath: string,\n  pageExtensions: PageExtensions,\n  strictlyMatchExtensions: boolean\n): boolean {\n  // Early exit for empty or obviously non-metadata paths\n  if (!appDirRelativePath || appDirRelativePath.length < 2) {\n    return false\n  }\n\n  const normalizedPath = normalizePathSep(appDirRelativePath)\n\n  // Fast path check for common cases\n  const fastResult = fastPathCheck(normalizedPath)\n  if (fastResult !== null) {\n    return fastResult\n  }\n\n  // Get compiled regexes from cache\n  const regexes = getCompiledRegexes(pageExtensions, strictlyMatchExtensions)\n\n  // Use for loop instead of .some() for better performance\n  for (let i = 0; i < regexes.length; i++) {\n    if (regexes[i].test(normalizedPath)) {\n      return true\n    }\n  }\n\n  return false\n}\n\n// Check if the route is a static metadata route, with /route suffix\n// e.g. /favicon.ico/route, /icon.png/route, etc.\n// But skip the text routes like robots.txt since they might also be dynamic.\n// Checking route path is not enough to determine if text routes is dynamic.\nexport function isStaticMetadataRoute(route: string) {\n  // extract ext with regex\n  const pathname = route.replace(/\\/route$/, '')\n\n  const matched =\n    isAppRouteRoute(route) &&\n    isMetadataRouteFile(pathname, [], true) &&\n    // These routes can either be built by static or dynamic entrypoints,\n    // so we assume they're dynamic\n    pathname !== '/robots.txt' &&\n    pathname !== '/manifest.webmanifest' &&\n    !pathname.endsWith('/sitemap.xml')\n\n  return matched\n}\n\n/**\n * Determine if a page or pathname is a metadata page.\n *\n * The input is a page or pathname, which can be with or without page suffix /foo/page or /foo.\n * But it will not contain the /route suffix.\n *\n * .e.g\n * /robots -> true\n * /sitemap -> true\n * /foo -> false\n */\nexport function isMetadataPage(page: string) {\n  const matched = !isAppRouteRoute(page) && isMetadataRouteFile(page, [], false)\n\n  return matched\n}\n\n/*\n * Determine if a Next.js route is a metadata route.\n * `route` will has a route suffix.\n *\n * e.g.\n * /app/robots/route -> true\n * /robots/route -> true\n * /sitemap/[__metadata_id__]/route -> true\n * /app/sitemap/page -> false\n * /icon-a102f4/route -> true\n */\nexport function isMetadataRoute(route: string): boolean {\n  let page = normalizeAppPath(route)\n    .replace(/^\\/?app\\//, '')\n    // Remove the dynamic route id\n    .replace('/[__metadata_id__]', '')\n    // Remove the /route suffix\n    .replace(/\\/route$/, '')\n\n  if (page[0] !== '/') page = '/' + page\n\n  const matched = isAppRouteRoute(route) && isMetadataRouteFile(page, [], false)\n\n  return matched\n}\n","import type { Normalizer } from './normalizer'\n\nexport function wrapNormalizerFn(fn: (pathname: string) => string): Normalizer {\n  return { normalize: fn }\n}\n","import { normalizeAppPath } from '../../../../shared/lib/router/utils/app-paths'\nimport { Normalizers } from '../../normalizers'\nimport { wrapNormalizerFn } from '../../wrap-normalizer-fn'\nimport { UnderscoreNormalizer } from '../../underscore-normalizer'\nimport type { Normalizer } from '../../normalizer'\n\nexport class AppPathnameNormalizer extends Normalizers {\n  constructor() {\n    super([\n      // The pathname to match should have the trailing `/page` and other route\n      // group information stripped from it.\n      wrapNormalizerFn(normalizeAppPath),\n      // The page should have the `%5F` characters replaced with `_` characters.\n      new UnderscoreNormalizer(),\n    ])\n  }\n\n  public normalize(page: string): string {\n    return super.normalize(page)\n  }\n}\n\nexport class DevAppPathnameNormalizer extends Normalizers {\n  constructor(pageNormalizer: Normalizer) {\n    super([\n      // This should normalize the filename to a page.\n      pageNormalizer,\n      // Normalize the app page to a pathname.\n      new AppPathnameNormalizer(),\n    ])\n  }\n\n  public normalize(filename: string): string {\n    return super.normalize(filename)\n  }\n}\n","import {\n  AppBundlePathNormalizer,\n  DevAppBundlePathNormalizer,\n} from './app-bundle-path-normalizer'\nimport { AppFilenameNormalizer } from './app-filename-normalizer'\nimport { DevAppPageNormalizer } from './app-page-normalizer'\nimport {\n  AppPathnameNormalizer,\n  DevAppPathnameNormalizer,\n} from './app-pathname-normalizer'\n\nexport class AppNormalizers {\n  public readonly filename: AppFilenameNormalizer\n  public readonly pathname: AppPathnameNormalizer\n  public readonly bundlePath: AppBundlePathNormalizer\n\n  constructor(distDir: string) {\n    this.filename = new AppFilenameNormalizer(distDir)\n    this.pathname = new AppPathnameNormalizer()\n    this.bundlePath = new AppBundlePathNormalizer()\n  }\n}\n\nexport class DevAppNormalizers {\n  public readonly page: DevAppPageNormalizer\n  public readonly pathname: DevAppPathnameNormalizer\n  public readonly bundlePath: DevAppBundlePathNormalizer\n\n  constructor(\n    appDir: string,\n    extensions: ReadonlyArray<string>,\n    isTurbopack: boolean\n  ) {\n    this.page = new DevAppPageNormalizer(appDir, extensions, isTurbopack)\n    this.pathname = new DevAppPathnameNormalizer(this.page)\n    this.bundlePath = new DevAppBundlePathNormalizer(this.page, isTurbopack)\n  }\n}\n","import { RouteMatcher } from './route-matcher'\nimport type { AppPageRouteDefinition } from '../route-definitions/app-page-route-definition'\n\nexport class AppPageRouteMatcher extends RouteMatcher<AppPageRouteDefinition> {\n  public get identity(): string {\n    return `${this.definition.pathname}?__nextPage=${this.definition.page}`\n  }\n}\n","import type { RouteMatcherProvider } from '../route-matcher-provider'\nimport type { RouteMatcher } from '../../route-matchers/route-matcher'\n\ninterface LoaderComparable<D> {\n  load(): Promise<D>\n  compare(left: D, right: D): boolean\n}\n\n/**\n * This will memoize the matchers if the loaded data is comparable.\n */\nexport abstract class CachedRouteMatcherProvider<\n  M extends RouteMatcher = RouteMatcher,\n  D = any,\n> implements RouteMatcherProvider<M>\n{\n  private data?: D\n  private cached: ReadonlyArray<M> = []\n\n  constructor(private readonly loader: LoaderComparable<D>) {}\n\n  protected abstract transform(data: D): Promise<ReadonlyArray<M>>\n\n  public async matchers(): Promise<readonly M[]> {\n    const data = await this.loader.load()\n    if (!data) return []\n\n    // Return the cached matchers if the data has not changed.\n    if (this.data && this.loader.compare(this.data, data)) return this.cached\n    this.data = data\n\n    // Transform the manifest into matchers.\n    const matchers = await this.transform(data)\n\n    // Cache the matchers.\n    this.cached = matchers\n\n    return matchers\n  }\n}\n","import type { RouteMatcher } from '../route-matchers/route-matcher'\nimport type {\n  Manifest,\n  ManifestLoader,\n} from './helpers/manifest-loaders/manifest-loader'\nimport { CachedRouteMatcherProvider } from './helpers/cached-route-matcher-provider'\n\nexport abstract class ManifestRouteMatcherProvider<\n  M extends RouteMatcher = RouteMatcher,\n> extends CachedRouteMatcherProvider<M, Manifest | null> {\n  constructor(manifestName: string, manifestLoader: ManifestLoader) {\n    super({\n      load: async () => manifestLoader.load(manifestName),\n      compare: (left, right) => left === right,\n    })\n  }\n}\n","import { isAppPageRoute } from '../../lib/is-app-page-route'\n\nimport { APP_PATHS_MANIFEST } from '../../shared/lib/constants'\nimport { AppNormalizers } from '../normalizers/built/app'\nimport { RouteKind } from '../route-kind'\nimport { AppPageRouteMatcher } from '../route-matchers/app-page-route-matcher'\nimport type {\n  Manifest,\n  ManifestLoader,\n} from './helpers/manifest-loaders/manifest-loader'\nimport { ManifestRouteMatcherProvider } from './manifest-route-matcher-provider'\n\nexport class AppPageRouteMatcherProvider extends ManifestRouteMatcherProvider<AppPageRouteMatcher> {\n  private readonly normalizers: AppNormalizers\n\n  constructor(distDir: string, manifestLoader: ManifestLoader) {\n    super(APP_PATHS_MANIFEST, manifestLoader)\n\n    this.normalizers = new AppNormalizers(distDir)\n  }\n\n  protected async transform(\n    manifest: Manifest\n  ): Promise<ReadonlyArray<AppPageRouteMatcher>> {\n    // This matcher only matches app pages.\n    const pages = Object.keys(manifest).filter((page) => isAppPageRoute(page))\n\n    // Collect all the app paths for each page. This could include any parallel\n    // routes.\n    const allAppPaths: Record<string, string[]> = {}\n    for (const page of pages) {\n      const pathname = this.normalizers.pathname.normalize(page)\n      if (pathname in allAppPaths) allAppPaths[pathname].push(page)\n      else allAppPaths[pathname] = [page]\n    }\n\n    // Format the routes.\n    const matchers: Array<AppPageRouteMatcher> = []\n    for (const [pathname, appPaths] of Object.entries(allAppPaths)) {\n      // TODO-APP: (wyattjoh) this is a hack right now, should be more deterministic\n      const page = appPaths[0]\n\n      const filename = this.normalizers.filename.normalize(manifest[page])\n      const bundlePath = this.normalizers.bundlePath.normalize(page)\n\n      matchers.push(\n        new AppPageRouteMatcher({\n          kind: RouteKind.APP_PAGE,\n          pathname,\n          page,\n          bundlePath,\n          filename,\n          appPaths,\n        })\n      )\n    }\n\n    return matchers\n  }\n}\n","export function isAppPageRoute(route: string): boolean {\n  return route.endsWith('/page')\n}\n","import { RouteMatcher } from './route-matcher'\nimport type { AppRouteRouteDefinition } from '../route-definitions/app-route-route-definition'\n\nexport class AppRouteRouteMatcher extends RouteMatcher<AppRouteRouteDefinition> {}\n","import { isAppRouteRoute } from '../../lib/is-app-route-route'\nimport { APP_PATHS_MANIFEST } from '../../shared/lib/constants'\nimport { RouteKind } from '../route-kind'\nimport { AppRouteRouteMatcher } from '../route-matchers/app-route-route-matcher'\nimport type {\n  Manifest,\n  ManifestLoader,\n} from './helpers/manifest-loaders/manifest-loader'\nimport { ManifestRouteMatcherProvider } from './manifest-route-matcher-provider'\nimport { AppNormalizers } from '../normalizers/built/app'\n\nexport class AppRouteRouteMatcherProvider extends ManifestRouteMatcherProvider<AppRouteRouteMatcher> {\n  private readonly normalizers: AppNormalizers\n\n  constructor(distDir: string, manifestLoader: ManifestLoader) {\n    super(APP_PATHS_MANIFEST, manifestLoader)\n\n    this.normalizers = new AppNormalizers(distDir)\n  }\n\n  protected async transform(\n    manifest: Manifest\n  ): Promise<ReadonlyArray<AppRouteRouteMatcher>> {\n    // This matcher only matches app routes.\n    const pages = Object.keys(manifest).filter((page) => isAppRouteRoute(page))\n\n    // Format the routes.\n    const matchers: Array<AppRouteRouteMatcher> = []\n    for (const page of pages) {\n      const filename = this.normalizers.filename.normalize(manifest[page])\n      const pathname = this.normalizers.pathname.normalize(page)\n      const bundlePath = this.normalizers.bundlePath.normalize(page)\n\n      matchers.push(\n        new AppRouteRouteMatcher({\n          kind: RouteKind.APP_ROUTE,\n          pathname,\n          page,\n          bundlePath,\n          filename,\n        })\n      )\n    }\n\n    return matchers\n  }\n}\n","export function isAPIRoute(value?: string) {\n  return value === '/api' || Boolean(value?.startsWith('/api/'))\n}\n","import type { PagesAPIRouteDefinition } from '../route-definitions/pages-api-route-definition'\nimport { LocaleRouteMatcher } from './locale-route-matcher'\nimport { RouteMatcher } from './route-matcher'\n\nexport class PagesAPIRouteMatcher extends RouteMatcher<PagesAPIRouteDefinition> {}\n\nexport class PagesAPILocaleRouteMatcher extends LocaleRouteMatcher<PagesAPIRouteDefinition> {}\n","import { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path'\nimport type { Normalizer } from '../../normalizer'\nimport { Normalizers } from '../../normalizers'\nimport { PrefixingNormalizer } from '../../prefixing-normalizer'\nimport { wrapNormalizerFn } from '../../wrap-normalizer-fn'\n\nexport class PagesBundlePathNormalizer extends Normalizers {\n  constructor() {\n    super([\n      // The bundle path should have the trailing `/index` stripped from\n      // it.\n      wrapNormalizerFn(normalizePagePath),\n      // The page should prefixed with `pages/`.\n      new PrefixingNormalizer('pages'),\n    ])\n  }\n\n  public normalize(page: string): string {\n    return super.normalize(page)\n  }\n}\n\nexport class DevPagesBundlePathNormalizer extends Normalizers {\n  constructor(pagesNormalizer: Normalizer) {\n    super([\n      // This should normalize the filename to a page.\n      pagesNormalizer,\n      // Normalize the app page to a pathname.\n      new PagesBundlePathNormalizer(),\n    ])\n  }\n\n  public normalize(filename: string): string {\n    return super.normalize(filename)\n  }\n}\n","import { SERVER_DIRECTORY } from '../../../../shared/lib/constants'\nimport { PrefixingNormalizer } from '../../prefixing-normalizer'\n\nexport class PagesFilenameNormalizer extends PrefixingNormalizer {\n  constructor(distDir: string) {\n    super(distDir, SERVER_DIRECTORY)\n  }\n\n  public normalize(manifestFilename: string): string {\n    return super.normalize(manifestFilename)\n  }\n}\n","import {\n  DevPagesBundlePathNormalizer,\n  PagesBundlePathNormalizer,\n} from './pages-bundle-path-normalizer'\nimport { PagesFilenameNormalizer } from './pages-filename-normalizer'\nimport { DevPagesPageNormalizer } from './pages-page-normalizer'\nimport { DevPagesPathnameNormalizer } from './pages-pathname-normalizer'\n\nexport class PagesNormalizers {\n  public readonly filename: PagesFilenameNormalizer\n  public readonly bundlePath: PagesBundlePathNormalizer\n\n  constructor(distDir: string) {\n    this.filename = new PagesFilenameNormalizer(distDir)\n    this.bundlePath = new PagesBundlePathNormalizer()\n\n    // You'd think that we'd require a `pathname` normalizer here, but for\n    // `/pages` we have to handle i18n routes, which means that we need to\n    // analyze the page path to determine the locale prefix and it's locale.\n  }\n}\n\nexport class DevPagesNormalizers {\n  public readonly page: DevPagesPageNormalizer\n  public readonly pathname: DevPagesPathnameNormalizer\n  public readonly bundlePath: DevPagesBundlePathNormalizer\n\n  constructor(pagesDir: string, extensions: ReadonlyArray<string>) {\n    this.page = new DevPagesPageNormalizer(pagesDir, extensions)\n    this.pathname = new DevPagesPathnameNormalizer(pagesDir, extensions)\n    this.bundlePath = new DevPagesBundlePathNormalizer(this.page)\n  }\n}\n","import { isAPIRoute } from '../../lib/is-api-route'\nimport { PAGES_MANIFEST } from '../../shared/lib/constants'\nimport { RouteKind } from '../route-kind'\nimport {\n  PagesAPILocaleRouteMatcher,\n  PagesAPIRouteMatcher,\n} from '../route-matchers/pages-api-route-matcher'\nimport type {\n  Manifest,\n  ManifestLoader,\n} from './helpers/manifest-loaders/manifest-loader'\nimport { ManifestRouteMatcherProvider } from './manifest-route-matcher-provider'\nimport type { I18NProvider } from '../lib/i18n-provider'\nimport { PagesNormalizers } from '../normalizers/built/pages'\n\nexport class PagesAPIRouteMatcherProvider extends ManifestRouteMatcherProvider<PagesAPIRouteMatcher> {\n  private readonly normalizers: PagesNormalizers\n\n  constructor(\n    distDir: string,\n    manifestLoader: ManifestLoader,\n    private readonly i18nProvider?: I18NProvider\n  ) {\n    super(PAGES_MANIFEST, manifestLoader)\n\n    this.normalizers = new PagesNormalizers(distDir)\n  }\n\n  protected async transform(\n    manifest: Manifest\n  ): Promise<ReadonlyArray<PagesAPIRouteMatcher>> {\n    // This matcher is only for Pages API routes.\n    const pathnames = Object.keys(manifest).filter((pathname) =>\n      isAPIRoute(pathname)\n    )\n\n    const matchers: Array<PagesAPIRouteMatcher> = []\n\n    for (const page of pathnames) {\n      if (this.i18nProvider) {\n        // Match the locale on the page name, or default to the default locale.\n        const { detectedLocale, pathname } = this.i18nProvider.analyze(page)\n\n        matchers.push(\n          new PagesAPILocaleRouteMatcher({\n            kind: RouteKind.PAGES_API,\n            pathname,\n            page,\n            bundlePath: this.normalizers.bundlePath.normalize(page),\n            filename: this.normalizers.filename.normalize(manifest[page]),\n            i18n: {\n              locale: detectedLocale,\n            },\n          })\n        )\n      } else {\n        matchers.push(\n          new PagesAPIRouteMatcher({\n            kind: RouteKind.PAGES_API,\n            // In `pages/`, the page is the same as the pathname.\n            pathname: page,\n            page,\n            bundlePath: this.normalizers.bundlePath.normalize(page),\n            filename: this.normalizers.filename.normalize(manifest[page]),\n          })\n        )\n      }\n    }\n\n    return matchers\n  }\n}\n","import type { PagesRouteDefinition } from '../route-definitions/pages-route-definition'\nimport { LocaleRouteMatcher } from './locale-route-matcher'\nimport { RouteMatcher } from './route-matcher'\n\nexport class PagesRouteMatcher extends RouteMatcher<PagesRouteDefinition> {}\n\nexport class PagesLocaleRouteMatcher extends LocaleRouteMatcher<PagesRouteDefinition> {}\n","import { isAPIRoute } from '../../lib/is-api-route'\nimport { BLOCKED_PAGES, PAGES_MANIFEST } from '../../shared/lib/constants'\nimport { RouteKind } from '../route-kind'\nimport {\n  PagesLocaleRouteMatcher,\n  PagesRouteMatcher,\n} from '../route-matchers/pages-route-matcher'\nimport type {\n  Manifest,\n  ManifestLoader,\n} from './helpers/manifest-loaders/manifest-loader'\nimport { ManifestRouteMatcherProvider } from './manifest-route-matcher-provider'\nimport type { I18NProvider } from '../lib/i18n-provider'\nimport { PagesNormalizers } from '../normalizers/built/pages'\n\nexport class PagesRouteMatcherProvider extends ManifestRouteMatcherProvider<PagesRouteMatcher> {\n  private readonly normalizers: PagesNormalizers\n\n  constructor(\n    distDir: string,\n    manifestLoader: ManifestLoader,\n    private readonly i18nProvider?: I18NProvider\n  ) {\n    super(PAGES_MANIFEST, manifestLoader)\n\n    this.normalizers = new PagesNormalizers(distDir)\n  }\n\n  protected async transform(\n    manifest: Manifest\n  ): Promise<ReadonlyArray<PagesRouteMatcher>> {\n    // This matcher is only for Pages routes, not Pages API routes which are\n    // included in this manifest.\n    const pathnames = Object.keys(manifest)\n      .filter((pathname) => !isAPIRoute(pathname))\n      // Remove any blocked pages (page that can't be routed to, like error or\n      // internal pages).\n      .filter((pathname) => {\n        const normalized =\n          this.i18nProvider?.analyze(pathname).pathname ?? pathname\n\n        // Skip any blocked pages.\n        if (BLOCKED_PAGES.includes(normalized)) return false\n\n        return true\n      })\n\n    const matchers: Array<PagesRouteMatcher> = []\n    for (const page of pathnames) {\n      if (this.i18nProvider) {\n        // Match the locale on the page name, or default to the default locale.\n        const { detectedLocale, pathname } = this.i18nProvider.analyze(page)\n\n        matchers.push(\n          new PagesLocaleRouteMatcher({\n            kind: RouteKind.PAGES,\n            pathname,\n            page,\n            bundlePath: this.normalizers.bundlePath.normalize(page),\n            filename: this.normalizers.filename.normalize(manifest[page]),\n            i18n: {\n              locale: detectedLocale,\n            },\n          })\n        )\n      } else {\n        matchers.push(\n          new PagesRouteMatcher({\n            kind: RouteKind.PAGES,\n            // In `pages/`, the page is the same as the pathname.\n            pathname: page,\n            page,\n            bundlePath: this.normalizers.bundlePath.normalize(page),\n            filename: this.normalizers.filename.normalize(manifest[page]),\n          })\n        )\n      }\n    }\n\n    return matchers\n  }\n}\n","import type { Manifest, ManifestLoader } from './manifest-loader'\n\nexport class ServerManifestLoader implements ManifestLoader {\n  constructor(private readonly getter: (name: string) => Manifest | null) {}\n\n  public load(name: string): Manifest | null {\n    return this.getter(name)\n  }\n}\n","import type { DomainLocale, I18NConfig } from '../config-shared'\nimport { getRequestMeta, type NextIncomingMessage } from '../request-meta'\n\n/**\n * The result of matching a locale aware route.\n */\nexport interface LocaleAnalysisResult {\n  /**\n   * The pathname without the locale prefix (if any).\n   */\n  pathname: string\n\n  /**\n   * The detected locale. If no locale was detected, this will be `undefined`.\n   */\n  detectedLocale?: string\n\n  /**\n   * True if the locale was inferred from the default locale.\n   */\n  inferredFromDefault: boolean\n}\n\ntype LocaleAnalysisOptions = {\n  /**\n   * When provided, it will be used as the default locale if the locale\n   * cannot be inferred from the pathname.\n   */\n  defaultLocale?: string\n}\n\n/**\n * The I18NProvider is used to match locale aware routes, detect the locale from\n * the pathname and hostname and normalize the pathname by removing the locale\n * prefix.\n */\nexport class I18NProvider {\n  private readonly lowerCaseLocales: ReadonlyArray<string>\n  private readonly lowerCaseDomains?: ReadonlyArray<\n    DomainLocale & {\n      // The configuration references a domain with an optional port, but the\n      // hostname is always the domain without the port and is used for\n      // matching.\n      hostname: string\n    }\n  >\n\n  constructor(public readonly config: Readonly<I18NConfig>) {\n    if (!config.locales.length) {\n      throw new Error('Invariant: No locales provided')\n    }\n\n    this.lowerCaseLocales = config.locales.map((locale) => locale.toLowerCase())\n    this.lowerCaseDomains = config.domains?.map((domainLocale) => {\n      const domain = domainLocale.domain.toLowerCase()\n      return {\n        defaultLocale: domainLocale.defaultLocale.toLowerCase(),\n        hostname: domain.split(':', 1)[0],\n        domain,\n        locales: domainLocale.locales?.map((locale) => locale.toLowerCase()),\n        http: domainLocale.http,\n      }\n    })\n  }\n\n  /**\n   * Detects the domain locale from the hostname and the detected locale if\n   * provided.\n   *\n   * @param hostname The hostname to detect the domain locale from, this must be lowercased.\n   * @param detectedLocale The detected locale to use if the hostname does not match.\n   * @returns The domain locale if found, `undefined` otherwise.\n   */\n  public detectDomainLocale(\n    hostname?: string,\n    detectedLocale?: string\n  ): DomainLocale | undefined {\n    if (!hostname || !this.lowerCaseDomains || !this.config.domains) return\n\n    if (detectedLocale) detectedLocale = detectedLocale.toLowerCase()\n\n    for (let i = 0; i < this.lowerCaseDomains.length; i++) {\n      const domainLocale = this.lowerCaseDomains[i]\n      if (\n        // We assume that the hostname is already lowercased.\n        domainLocale.hostname === hostname ||\n        // Configuration validation ensures that the locale is not repeated in\n        // other domains locales.\n        domainLocale.locales?.some((locale) => locale === detectedLocale)\n      ) {\n        return this.config.domains[i]\n      }\n    }\n\n    return\n  }\n\n  /**\n   * Pulls the pre-computed locale and inference results from the query\n   * object.\n   *\n   * @param req the request object\n   * @param pathname the pathname that could contain a locale prefix\n   * @returns the locale analysis result\n   */\n  public fromRequest(\n    req: NextIncomingMessage,\n    pathname: string\n  ): LocaleAnalysisResult {\n    const detectedLocale = getRequestMeta(req, 'locale')\n\n    // If a locale was detected on the query, analyze the pathname to ensure\n    // that the locale matches.\n    if (detectedLocale) {\n      const analysis = this.analyze(pathname)\n\n      // If the analysis contained a locale we should validate it against the\n      // query and strip it from the pathname.\n      if (analysis.detectedLocale) {\n        if (analysis.detectedLocale !== detectedLocale) {\n          console.warn(\n            `The detected locale does not match the locale in the query. Expected to find '${detectedLocale}' in '${pathname}' but found '${analysis.detectedLocale}'}`\n          )\n        }\n\n        pathname = analysis.pathname\n      }\n    }\n\n    return {\n      pathname,\n      detectedLocale,\n      inferredFromDefault:\n        getRequestMeta(req, 'localeInferredFromDefault') ?? false,\n    }\n  }\n\n  /**\n   * Analyzes the pathname for a locale and returns the pathname without it.\n   *\n   * @param pathname The pathname that could contain a locale prefix.\n   * @param options The options to use when matching the locale.\n   * @returns The matched locale and the pathname without the locale prefix\n   *          (if any).\n   */\n  public analyze(\n    pathname: string,\n    options: LocaleAnalysisOptions = {}\n  ): LocaleAnalysisResult {\n    let detectedLocale: string | undefined = options.defaultLocale\n\n    // By default, we assume that the default locale was inferred if there was\n    // no detected locale.\n    let inferredFromDefault = typeof detectedLocale === 'string'\n\n    // The first segment will be empty, because it has a leading `/`. If\n    // there is no further segment, there is no locale (or it's the default).\n    const segments = pathname.split('/', 2)\n    if (!segments[1])\n      return {\n        detectedLocale,\n        pathname,\n        inferredFromDefault,\n      }\n\n    // The second segment will contain the locale part if any.\n    const segment = segments[1].toLowerCase()\n\n    // See if the segment matches one of the locales. If it doesn't, there is\n    // no locale (or it's the default).\n    const index = this.lowerCaseLocales.indexOf(segment)\n    if (index < 0)\n      return {\n        detectedLocale,\n        pathname,\n        inferredFromDefault,\n      }\n\n    // Return the case-sensitive locale.\n    detectedLocale = this.config.locales[index]\n    inferredFromDefault = false\n\n    // Remove the `/${locale}` part of the pathname.\n    pathname = pathname.slice(detectedLocale.length + 1) || '/'\n\n    return {\n      detectedLocale,\n      pathname,\n      inferredFromDefault,\n    }\n  }\n}\n","import type { BaseNextRequest, BaseNextResponse } from './base-http'\nimport { isNodeNextResponse } from './base-http/helpers'\n\nimport { pipeToNodeResponse } from './pipe-readable'\nimport { splitCookiesString } from './web/utils'\n\n/**\n * Sends the response on the underlying next response object.\n *\n * @param req the underlying request object\n * @param res the underlying response object\n * @param response the response to send\n */\nexport async function sendResponse(\n  req: BaseNextRequest,\n  res: BaseNextResponse,\n  response: Response,\n  waitUntil?: Promise<unknown>\n): Promise<void> {\n  if (\n    // The type check here ensures that `req` is correctly typed, and the\n    // environment variable check provides dead code elimination.\n    process.env.NEXT_RUNTIME !== 'edge' &&\n    isNodeNextResponse(res)\n  ) {\n    // Copy over the response status.\n    res.statusCode = response.status\n    res.statusMessage = response.statusText\n\n    // TODO: this is not spec-compliant behavior and we should not restrict\n    // headers that are allowed to appear many times.\n    //\n    // See:\n    // https://github.com/vercel/next.js/pull/70127\n    const headersWithMultipleValuesAllowed = [\n      // can add more headers to this list if needed\n      'set-cookie',\n      'www-authenticate',\n      'proxy-authenticate',\n      'vary',\n    ]\n\n    // Copy over the response headers.\n    response.headers?.forEach((value, name) => {\n      // `x-middleware-set-cookie` is an internal header not needed for the response\n      if (name.toLowerCase() === 'x-middleware-set-cookie') {\n        return\n      }\n\n      // The append handling is special cased for `set-cookie`.\n      if (name.toLowerCase() === 'set-cookie') {\n        // TODO: (wyattjoh) replace with native response iteration when we can upgrade undici\n        for (const cookie of splitCookiesString(value)) {\n          res.appendHeader(name, cookie)\n        }\n      } else {\n        // only append the header if it is either not present in the outbound response\n        // or if the header supports multiple values\n        const isHeaderPresent = typeof res.getHeader(name) !== 'undefined'\n        if (\n          headersWithMultipleValuesAllowed.includes(name.toLowerCase()) ||\n          !isHeaderPresent\n        ) {\n          res.appendHeader(name, value)\n        }\n      }\n    })\n\n    /**\n     * The response can't be directly piped to the underlying response. The\n     * following is duplicated from the edge runtime handler.\n     *\n     * See packages/next/server/next-server.ts\n     */\n\n    const { originalResponse } = res\n\n    // A response body must not be sent for HEAD requests. See https://httpwg.org/specs/rfc9110.html#HEAD\n    if (response.body && req.method !== 'HEAD') {\n      await pipeToNodeResponse(response.body, originalResponse, waitUntil)\n    } else {\n      originalResponse.end()\n    }\n  }\n}\n","import { getPathMatch } from '../../shared/lib/router/utils/path-match'\n\nconst matcher = getPathMatch('/_next/data/:path*')\n\nexport function matchNextDataPathname(pathname: string | null | undefined) {\n  if (typeof pathname !== 'string') return false\n\n  return matcher(pathname)\n}\n","import type { Normalizer } from '../normalizer'\n\nexport class SuffixPathnameNormalizer implements Normalizer {\n  constructor(private readonly suffix: string) {}\n\n  public match(pathname: string) {\n    // If the pathname doesn't end in the suffix, we don't match.\n    if (!pathname.endsWith(this.suffix)) return false\n\n    return true\n  }\n\n  public normalize(pathname: string, matched?: boolean): string {\n    // If we're not matched and we don't match, we don't need to normalize.\n    if (!matched && !this.match(pathname)) return pathname\n\n    return pathname.substring(0, pathname.length - this.suffix.length)\n  }\n}\n","import type { PathnameNormalizer } from './pathname-normalizer'\n\nimport { RSC_SUFFIX } from '../../../lib/constants'\nimport { SuffixPathnameNormalizer } from './suffix'\n\nexport class RSCPathnameNormalizer\n  extends SuffixPathnameNormalizer\n  implements PathnameNormalizer\n{\n  constructor() {\n    super(RSC_SUFFIX)\n  }\n}\n","import type { Normalizer } from '../normalizer'\n\nexport class PrefixPathnameNormalizer implements Normalizer {\n  constructor(private readonly prefix: string) {\n    if (prefix.endsWith('/')) {\n      throw new Error(\n        `PrefixPathnameNormalizer: prefix \"${prefix}\" should not end with a slash`\n      )\n    }\n  }\n\n  public match(pathname: string) {\n    // If the pathname doesn't start with the prefix, we don't match.\n    if (pathname !== this.prefix && !pathname.startsWith(this.prefix + '/')) {\n      return false\n    }\n\n    return true\n  }\n\n  public normalize(pathname: string, matched?: boolean): string {\n    // If we're not matched and we don't match, we don't need to normalize.\n    if (!matched && !this.match(pathname)) return pathname\n\n    if (pathname.length === this.prefix.length) {\n      return '/'\n    }\n\n    return pathname.substring(this.prefix.length)\n  }\n}\n","import type { PathnameNormalizer } from './pathname-normalizer'\n\nimport { denormalizePagePath } from '../../../shared/lib/page-path/denormalize-page-path'\nimport { PrefixPathnameNormalizer } from './prefix'\nimport { SuffixPathnameNormalizer } from './suffix'\n\nexport class NextDataPathnameNormalizer implements PathnameNormalizer {\n  private readonly prefix: PrefixPathnameNormalizer\n  private readonly suffix = new SuffixPathnameNormalizer('.json')\n  constructor(buildID: string) {\n    if (!buildID) {\n      throw new Error('Invariant: buildID is required')\n    }\n\n    this.prefix = new PrefixPathnameNormalizer(`/_next/data/${buildID}`)\n  }\n\n  public match(pathname: string) {\n    return this.prefix.match(pathname) && this.suffix.match(pathname)\n  }\n\n  public normalize(pathname: string, matched?: boolean): string {\n    // If we're not matched and we don't match, we don't need to normalize.\n    if (!matched && !this.match(pathname)) return pathname\n\n    pathname = this.prefix.normalize(pathname, true)\n    pathname = this.suffix.normalize(pathname, true)\n\n    return denormalizePagePath(pathname)\n  }\n}\n","/**\n * This transforms a URL pathname into a route. It removes any trailing slashes\n * and the `/index` suffix.\n *\n * @param pathname - The URL path that needs to be optimized.\n * @returns - The route\n *\n * @example\n * // returns '/example'\n * toRoute('/example/index/');\n *\n * @example\n * // returns '/example'\n * toRoute('/example/');\n *\n * @example\n * // returns '/'\n * toRoute('/index/');\n *\n * @example\n * // returns '/'\n * toRoute('/');\n */\nexport function toRoute(pathname: string): string {\n  return pathname.replace(/(?:\\/index)?\\/?$/, '') || '/'\n}\n","import type { AsyncLocalStorage } from 'async_hooks'\n\nconst sharedAsyncLocalStorageNotAvailableError = new Error(\n  'Invariant: AsyncLocalStorage accessed in runtime where it is not available'\n)\n\nclass FakeAsyncLocalStorage<Store extends {}>\n  implements AsyncLocalStorage<Store>\n{\n  disable(): void {\n    throw sharedAsyncLocalStorageNotAvailableError\n  }\n\n  getStore(): Store | undefined {\n    // This fake implementation of AsyncLocalStorage always returns `undefined`.\n    return undefined\n  }\n\n  run<R>(): R {\n    throw sharedAsyncLocalStorageNotAvailableError\n  }\n\n  exit<R>(): R {\n    throw sharedAsyncLocalStorageNotAvailableError\n  }\n\n  enterWith(): void {\n    throw sharedAsyncLocalStorageNotAvailableError\n  }\n\n  static bind<T>(fn: T): T {\n    return fn\n  }\n}\n\nconst maybeGlobalAsyncLocalStorage =\n  typeof globalThis !== 'undefined' && (globalThis as any).AsyncLocalStorage\n\nexport function createAsyncLocalStorage<\n  Store extends {},\n>(): AsyncLocalStorage<Store> {\n  if (maybeGlobalAsyncLocalStorage) {\n    return new maybeGlobalAsyncLocalStorage()\n  }\n  return new FakeAsyncLocalStorage()\n}\n\nexport function bindSnapshot<T>(\n  // WARNING: Don't pass a named function to this argument! See: https://github.com/facebook/react/pull/34911\n  fn: T\n): T {\n  if (maybeGlobalAsyncLocalStorage) {\n    return maybeGlobalAsyncLocalStorage.bind(fn)\n  }\n  return FakeAsyncLocalStorage.bind(fn)\n}\n\nexport function createSnapshot(): <R, TArgs extends any[]>(\n  fn: (...args: TArgs) => R,\n  ...args: TArgs\n) => R {\n  if (maybeGlobalAsyncLocalStorage) {\n    return maybeGlobalAsyncLocalStorage.snapshot()\n  }\n  return function (fn: any, ...args: any[]) {\n    return fn(...args)\n  }\n}\n","import { createAsyncLocalStorage } from '../app-render/async-local-storage'\n\nexport function getBuiltinRequestContext():\n  | BuiltinRequestContextValue\n  | undefined {\n  const _globalThis = globalThis as GlobalThisWithRequestContext\n  const ctx = _globalThis[NEXT_REQUEST_CONTEXT_SYMBOL]\n  return ctx?.get()\n}\n\nconst NEXT_REQUEST_CONTEXT_SYMBOL = Symbol.for('@next/request-context')\n\ntype GlobalThisWithRequestContext = typeof globalThis & {\n  [NEXT_REQUEST_CONTEXT_SYMBOL]?: BuiltinRequestContext\n}\n\n/** A request context provided by the platform. */\nexport type BuiltinRequestContext = {\n  get(): BuiltinRequestContextValue | undefined\n}\n\nexport type RunnableBuiltinRequestContext = BuiltinRequestContext & {\n  run<T>(value: BuiltinRequestContextValue, callback: () => T): T\n}\n\nexport type BuiltinRequestContextValue = {\n  waitUntil?: WaitUntil\n}\nexport type WaitUntil = (promise: Promise<any>) => void\n\n/** \"@next/request-context\" has a different signature from AsyncLocalStorage,\n * matching [AsyncContext.Variable](https://github.com/tc39/proposal-async-context).\n * We don't need a full AsyncContext adapter here, just having `.get()` is enough\n */\nexport function createLocalRequestContext(): RunnableBuiltinRequestContext {\n  const storage = createAsyncLocalStorage<BuiltinRequestContextValue>()\n  return {\n    get: () => storage.getStore(),\n    run: (value, callback) => storage.run(value, callback),\n  }\n}\n","import type { WaitUntil } from '../../after/builtin-request-context'\nimport { PageSignatureError } from '../error'\nimport type { NextRequest } from './request'\n\nconst responseSymbol = Symbol('response')\nconst passThroughSymbol = Symbol('passThrough')\nconst waitUntilSymbol = Symbol('waitUntil')\n\nclass FetchEvent {\n  // TODO(after): get rid of the 'internal' variant and always use an external waitUntil\n  // (this means removing `FetchEventResult.waitUntil` which also requires a builder change)\n  readonly [waitUntilSymbol]:\n    | { kind: 'internal'; promises: Promise<any>[] }\n    | { kind: 'external'; function: WaitUntil };\n\n  [responseSymbol]?: Promise<Response>;\n  [passThroughSymbol] = false\n\n  constructor(_request: Request, waitUntil?: WaitUntil) {\n    this[waitUntilSymbol] = waitUntil\n      ? { kind: 'external', function: waitUntil }\n      : { kind: 'internal', promises: [] }\n  }\n\n  // TODO: is this dead code? NextFetchEvent never lets this get called\n  respondWith(response: Response | Promise<Response>): void {\n    if (!this[responseSymbol]) {\n      this[responseSymbol] = Promise.resolve(response)\n    }\n  }\n\n  // TODO: is this dead code? passThroughSymbol is unused\n  passThroughOnException(): void {\n    this[passThroughSymbol] = true\n  }\n\n  waitUntil(promise: Promise<any>): void {\n    if (this[waitUntilSymbol].kind === 'external') {\n      // if we received an external waitUntil, we delegate to it\n      // TODO(after): this will make us not go through `getServerError(error, 'edge-server')` in `sandbox`\n      const waitUntil = this[waitUntilSymbol].function\n      return waitUntil(promise)\n    } else {\n      // if we didn't receive an external waitUntil, we make it work on our own\n      // (and expect the caller to do something with the promises)\n      this[waitUntilSymbol].promises.push(promise)\n    }\n  }\n}\n\nexport function getWaitUntilPromiseFromEvent(\n  event: FetchEvent\n): Promise<void> | undefined {\n  return event[waitUntilSymbol].kind === 'internal'\n    ? Promise.all(event[waitUntilSymbol].promises).then(() => {})\n    : undefined\n}\n\nexport class NextFetchEvent extends FetchEvent {\n  sourcePage: string\n\n  constructor(params: {\n    request: NextRequest\n    page: string\n    context: { waitUntil: WaitUntil } | undefined\n  }) {\n    super(params.request, params.context?.waitUntil)\n    this.sourcePage = params.page\n  }\n\n  /**\n   * @deprecated The `request` is now the first parameter and the API is now async.\n   *\n   * Read more: https://nextjs.org/docs/messages/middleware-new-signature\n   */\n  get request() {\n    throw new PageSignatureError({\n      page: this.sourcePage,\n    })\n  }\n\n  /**\n   * @deprecated Using `respondWith` is no longer needed.\n   *\n   * Read more: https://nextjs.org/docs/messages/middleware-new-signature\n   */\n  respondWith() {\n    throw new PageSignatureError({\n      page: this.sourcePage,\n    })\n  }\n}\n","import { stringifyCookie } from '../../web/spec-extension/cookies'\nimport type { I18NConfig } from '../../config-shared'\nimport { NextURL } from '../next-url'\nimport { toNodeOutgoingHttpHeaders, validateURL } from '../utils'\nimport { ReflectAdapter } from './adapters/reflect'\n\nimport { ResponseCookies } from './cookies'\n\nconst INTERNALS = Symbol('internal response')\nconst REDIRECTS = new Set([301, 302, 303, 307, 308])\n\nfunction handleMiddlewareField(\n  init: MiddlewareResponseInit | undefined,\n  headers: Headers\n) {\n  if (init?.request?.headers) {\n    if (!(init.request.headers instanceof Headers)) {\n      throw new Error('request.headers must be an instance of Headers')\n    }\n\n    const keys = []\n    for (const [key, value] of init.request.headers) {\n      headers.set('x-middleware-request-' + key, value)\n      keys.push(key)\n    }\n\n    headers.set('x-middleware-override-headers', keys.join(','))\n  }\n}\n\n/**\n * This class extends the [Web `Response` API](https://developer.mozilla.org/docs/Web/API/Response) with additional convenience methods.\n *\n * Read more: [Next.js Docs: `NextResponse`](https://nextjs.org/docs/app/api-reference/functions/next-response)\n */\nexport class NextResponse<Body = unknown> extends Response {\n  [INTERNALS]: {\n    cookies: ResponseCookies\n    url?: NextURL\n    body?: Body\n  }\n\n  constructor(body?: BodyInit | null, init: ResponseInit = {}) {\n    super(body, init)\n\n    const headers = this.headers\n    const cookies = new ResponseCookies(headers)\n\n    const cookiesProxy = new Proxy(cookies, {\n      get(target, prop, receiver) {\n        switch (prop) {\n          case 'delete':\n          case 'set': {\n            return (...args: [string, string]) => {\n              const result = Reflect.apply(target[prop], target, args)\n              const newHeaders = new Headers(headers)\n\n              if (result instanceof ResponseCookies) {\n                headers.set(\n                  'x-middleware-set-cookie',\n                  result\n                    .getAll()\n                    .map((cookie) => stringifyCookie(cookie))\n                    .join(',')\n                )\n              }\n\n              handleMiddlewareField(init, newHeaders)\n              return result\n            }\n          }\n          default:\n            return ReflectAdapter.get(target, prop, receiver)\n        }\n      },\n    })\n\n    this[INTERNALS] = {\n      cookies: cookiesProxy,\n      url: init.url\n        ? new NextURL(init.url, {\n            headers: toNodeOutgoingHttpHeaders(headers),\n            nextConfig: init.nextConfig,\n          })\n        : undefined,\n    }\n  }\n\n  [Symbol.for('edge-runtime.inspect.custom')]() {\n    return {\n      cookies: this.cookies,\n      url: this.url,\n      // rest of props come from Response\n      body: this.body,\n      bodyUsed: this.bodyUsed,\n      headers: Object.fromEntries(this.headers),\n      ok: this.ok,\n      redirected: this.redirected,\n      status: this.status,\n      statusText: this.statusText,\n      type: this.type,\n    }\n  }\n\n  public get cookies() {\n    return this[INTERNALS].cookies\n  }\n\n  static json<JsonBody>(\n    body: JsonBody,\n    init?: ResponseInit\n  ): NextResponse<JsonBody> {\n    const response: Response = Response.json(body, init)\n    return new NextResponse(response.body, response)\n  }\n\n  static redirect(url: string | NextURL | URL, init?: number | ResponseInit) {\n    const status = typeof init === 'number' ? init : (init?.status ?? 307)\n    if (!REDIRECTS.has(status)) {\n      throw new RangeError(\n        'Failed to execute \"redirect\" on \"response\": Invalid status code'\n      )\n    }\n    const initObj = typeof init === 'object' ? init : {}\n    const headers = new Headers(initObj?.headers)\n    headers.set('Location', validateURL(url))\n\n    return new NextResponse(null, {\n      ...initObj,\n      headers,\n      status,\n    })\n  }\n\n  static rewrite(\n    destination: string | NextURL | URL,\n    init?: MiddlewareResponseInit\n  ) {\n    const headers = new Headers(init?.headers)\n    headers.set('x-middleware-rewrite', validateURL(destination))\n\n    handleMiddlewareField(init, headers)\n    return new NextResponse(null, { ...init, headers })\n  }\n\n  static next(init?: MiddlewareResponseInit) {\n    const headers = new Headers(init?.headers)\n    headers.set('x-middleware-next', '1')\n\n    handleMiddlewareField(init, headers)\n    return new NextResponse(null, { ...init, headers })\n  }\n}\n\ninterface ResponseInit extends globalThis.ResponseInit {\n  nextConfig?: {\n    basePath?: string\n    i18n?: I18NConfig\n    trailingSlash?: boolean\n  }\n  url?: string\n}\n\ninterface ModifiedRequest {\n  /**\n   * If this is set, the request headers will be overridden with this value.\n   */\n  headers?: Headers\n}\n\ninterface MiddlewareResponseInit extends globalThis.ResponseInit {\n  /**\n   * These fields will override the request from clients.\n   */\n  request?: ModifiedRequest\n}\n","import { RequestCookies } from '../cookies'\n\nimport { ResponseCookies } from '../cookies'\nimport { ReflectAdapter } from './reflect'\nimport { workAsyncStorage } from '../../../app-render/work-async-storage.external'\nimport type { RequestStore } from '../../../app-render/work-unit-async-storage.external'\nimport { ActionDidRevalidateStaticAndDynamic } from '../../../../shared/lib/action-revalidation-kind'\n\n/**\n * @internal\n */\nexport class ReadonlyRequestCookiesError extends Error {\n  constructor() {\n    super(\n      'Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options'\n    )\n  }\n\n  public static callable() {\n    throw new ReadonlyRequestCookiesError()\n  }\n}\n\n// We use this to type some APIs but we don't construct instances directly\nexport type { ResponseCookies }\n\n// The `cookies()` API is a mix of request and response cookies. For `.get()` methods,\n// we want to return the request cookie if it exists. For mutative methods like `.set()`,\n// we want to return the response cookie.\nexport type ReadonlyRequestCookies = Omit<\n  RequestCookies,\n  'set' | 'clear' | 'delete'\n> &\n  Pick<ResponseCookies, 'set' | 'delete'>\n\nexport class RequestCookiesAdapter {\n  public static seal(cookies: RequestCookies): ReadonlyRequestCookies {\n    return new Proxy(cookies as any, {\n      get(target, prop, receiver) {\n        switch (prop) {\n          case 'clear':\n          case 'delete':\n          case 'set':\n            return ReadonlyRequestCookiesError.callable\n          default:\n            return ReflectAdapter.get(target, prop, receiver)\n        }\n      },\n    })\n  }\n}\n\nconst SYMBOL_MODIFY_COOKIE_VALUES = Symbol.for('next.mutated.cookies')\n\nexport function getModifiedCookieValues(\n  cookies: ResponseCookies\n): ResponseCookie[] {\n  const modified: ResponseCookie[] | undefined = (cookies as unknown as any)[\n    SYMBOL_MODIFY_COOKIE_VALUES\n  ]\n  if (!modified || !Array.isArray(modified) || modified.length === 0) {\n    return []\n  }\n\n  return modified\n}\n\ntype SetCookieArgs =\n  | [key: string, value: string, cookie?: Partial<ResponseCookie>]\n  | [options: ResponseCookie]\n\nexport function appendMutableCookies(\n  headers: Headers,\n  mutableCookies: ResponseCookies\n): boolean {\n  const modifiedCookieValues = getModifiedCookieValues(mutableCookies)\n  if (modifiedCookieValues.length === 0) {\n    return false\n  }\n\n  // Return a new response that extends the response with\n  // the modified cookies as fallbacks. `res` cookies\n  // will still take precedence.\n  const resCookies = new ResponseCookies(headers)\n  const returnedCookies = resCookies.getAll()\n\n  // Set the modified cookies as fallbacks.\n  for (const cookie of modifiedCookieValues) {\n    resCookies.set(cookie)\n  }\n\n  // Set the original cookies as the final values.\n  for (const cookie of returnedCookies) {\n    resCookies.set(cookie)\n  }\n\n  return true\n}\n\ntype ResponseCookie = NonNullable<\n  ReturnType<InstanceType<typeof ResponseCookies>['get']>\n>\n\nexport class MutableRequestCookiesAdapter {\n  public static wrap(\n    cookies: RequestCookies,\n    onUpdateCookies?: (cookies: string[]) => void\n  ): ResponseCookies {\n    const responseCookies = new ResponseCookies(new Headers())\n    for (const cookie of cookies.getAll()) {\n      responseCookies.set(cookie)\n    }\n\n    let modifiedValues: ResponseCookie[] = []\n    const modifiedCookies = new Set<string>()\n    const updateResponseCookies = () => {\n      // TODO-APP: change method of getting workStore\n      const workStore = workAsyncStorage.getStore()\n      if (workStore) {\n        workStore.pathWasRevalidated = ActionDidRevalidateStaticAndDynamic\n      }\n\n      const allCookies = responseCookies.getAll()\n      modifiedValues = allCookies.filter((c) => modifiedCookies.has(c.name))\n      if (onUpdateCookies) {\n        const serializedCookies: string[] = []\n        for (const cookie of modifiedValues) {\n          const tempCookies = new ResponseCookies(new Headers())\n          tempCookies.set(cookie)\n          serializedCookies.push(tempCookies.toString())\n        }\n\n        onUpdateCookies(serializedCookies)\n      }\n    }\n\n    const wrappedCookies = new Proxy(responseCookies, {\n      get(target, prop, receiver) {\n        switch (prop) {\n          // A special symbol to get the modified cookie values\n          case SYMBOL_MODIFY_COOKIE_VALUES:\n            return modifiedValues\n\n          // TODO: Throw error if trying to set a cookie after the response\n          // headers have been set.\n          case 'delete':\n            return function (...args: [string] | [ResponseCookie]) {\n              modifiedCookies.add(\n                typeof args[0] === 'string' ? args[0] : args[0].name\n              )\n              try {\n                target.delete(...args)\n                return wrappedCookies\n              } finally {\n                updateResponseCookies()\n              }\n            }\n          case 'set':\n            return function (...args: SetCookieArgs) {\n              modifiedCookies.add(\n                typeof args[0] === 'string' ? args[0] : args[0].name\n              )\n              try {\n                target.set(...args)\n                return wrappedCookies\n              } finally {\n                updateResponseCookies()\n              }\n            }\n\n          default:\n            return ReflectAdapter.get(target, prop, receiver)\n        }\n      },\n    })\n\n    return wrappedCookies\n  }\n}\n\nexport function createCookiesWithMutableAccessCheck(\n  requestStore: RequestStore\n): ResponseCookies {\n  const wrappedCookies = new Proxy(requestStore.mutableCookies, {\n    get(target, prop, receiver) {\n      switch (prop) {\n        case 'delete':\n          return function (...args: [string] | [ResponseCookie]) {\n            ensureCookiesAreStillMutable(requestStore, 'cookies().delete')\n            target.delete(...args)\n            return wrappedCookies\n          }\n        case 'set':\n          return function (...args: SetCookieArgs) {\n            ensureCookiesAreStillMutable(requestStore, 'cookies().set')\n            target.set(...args)\n            return wrappedCookies\n          }\n\n        default:\n          return ReflectAdapter.get(target, prop, receiver)\n      }\n    },\n  })\n  return wrappedCookies\n}\n\nexport function areCookiesMutableInCurrentPhase(requestStore: RequestStore) {\n  return requestStore.phase === 'action'\n}\n\n/** Ensure that cookies() starts throwing on mutation\n * if we changed phases and can no longer mutate.\n *\n * This can happen when going:\n *   'render' -> 'after'\n *   'action' -> 'render'\n * */\nfunction ensureCookiesAreStillMutable(\n  requestStore: RequestStore,\n  _callingExpression: string\n) {\n  if (!areCookiesMutableInCurrentPhase(requestStore)) {\n    // TODO: maybe we can give a more precise error message based on callingExpression?\n    throw new ReadonlyRequestCookiesError()\n  }\n}\n\nexport function responseCookiesToRequestCookies(\n  responseCookies: ResponseCookies\n): RequestCookies {\n  const requestCookies = new RequestCookies(new Headers())\n  for (const cookie of responseCookies.getAll()) {\n    requestCookies.set(cookie)\n  }\n  return requestCookies\n}\n","/**\n * This is the default \"use cache\" handler it defaults to an in-memory store.\n * In-memory caches are fragile and should not use stale-while-revalidate\n * semantics on the caches because it's not worth warming up an entry that's\n * likely going to get evicted before we get to use it anyway. However, we also\n * don't want to reuse a stale entry for too long so stale entries should be\n * considered expired/missing in such cache handlers.\n */\n\nimport { LRUCache } from '../lru-cache'\nimport type { CacheEntry, CacheHandler } from './types'\nimport {\n  areTagsExpired,\n  areTagsStale,\n  tagsManifest,\n  type TagManifestEntry,\n} from '../incremental-cache/tags-manifest.external'\n\ntype PrivateCacheEntry = {\n  entry: CacheEntry\n\n  // For the default cache we store errored cache\n  // entries and allow them to be used up to 3 times\n  // after that we want to dispose it and try for fresh\n\n  // If an entry is errored we return no entry\n  // three times so that we retry hitting origin (MISS)\n  // and then if it still fails to set after the third we\n  // return the errored content and use expiration of\n  // Math.min(30, entry.expiration)\n  isErrored: boolean\n  errorRetryCount: number\n\n  // compute size on set since we need to read size\n  // of the ReadableStream for LRU evicting\n  size: number\n}\n\nexport function createDefaultCacheHandler(maxSize: number): CacheHandler {\n  // If the max size is 0, return a cache handler that doesn't cache anything,\n  // this avoids an unnecessary LRUCache instance and potential memory\n  // allocation.\n  if (maxSize === 0) {\n    return {\n      get: () => Promise.resolve(undefined),\n      set: () => Promise.resolve(),\n      refreshTags: () => Promise.resolve(),\n      getExpiration: () => Promise.resolve(0),\n      updateTags: () => Promise.resolve(),\n    }\n  }\n\n  const memoryCache = new LRUCache<PrivateCacheEntry>(\n    maxSize,\n    (entry) => entry.size\n  )\n  const pendingSets = new Map<string, Promise<void>>()\n\n  const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE\n    ? console.debug.bind(console, 'DefaultCacheHandler:')\n    : undefined\n\n  return {\n    async get(cacheKey) {\n      const pendingPromise = pendingSets.get(cacheKey)\n\n      if (pendingPromise) {\n        debug?.('get', cacheKey, 'pending')\n        await pendingPromise\n      }\n\n      const privateEntry = memoryCache.get(cacheKey)\n\n      if (!privateEntry) {\n        debug?.('get', cacheKey, 'not found')\n        return undefined\n      }\n\n      const entry = privateEntry.entry\n      if (\n        performance.timeOrigin + performance.now() >\n        entry.timestamp + entry.revalidate * 1000\n      ) {\n        // In-memory caches should expire after revalidate time because it is\n        // unlikely that a new entry will be able to be used before it is dropped\n        // from the cache.\n        debug?.('get', cacheKey, 'expired')\n\n        return undefined\n      }\n\n      let revalidate = entry.revalidate\n\n      if (areTagsExpired(entry.tags, entry.timestamp)) {\n        debug?.('get', cacheKey, 'had expired tag')\n        return undefined\n      }\n\n      if (areTagsStale(entry.tags, entry.timestamp)) {\n        debug?.('get', cacheKey, 'had stale tag')\n        revalidate = -1\n      }\n\n      const [returnStream, newSaved] = entry.value.tee()\n      entry.value = newSaved\n\n      debug?.('get', cacheKey, 'found', {\n        tags: entry.tags,\n        timestamp: entry.timestamp,\n        expire: entry.expire,\n        revalidate,\n      })\n\n      return {\n        ...entry,\n        revalidate,\n        value: returnStream,\n      }\n    },\n\n    async set(cacheKey, pendingEntry) {\n      debug?.('set', cacheKey, 'start')\n\n      let resolvePending: () => void = () => {}\n      const pendingPromise = new Promise<void>((resolve) => {\n        resolvePending = resolve\n      })\n      pendingSets.set(cacheKey, pendingPromise)\n\n      const entry = await pendingEntry\n\n      let size = 0\n\n      try {\n        const [value, clonedValue] = entry.value.tee()\n        entry.value = value\n        const reader = clonedValue.getReader()\n\n        for (let chunk; !(chunk = await reader.read()).done; ) {\n          size += Buffer.from(chunk.value).byteLength\n        }\n\n        memoryCache.set(cacheKey, {\n          entry,\n          isErrored: false,\n          errorRetryCount: 0,\n          size,\n        })\n\n        debug?.('set', cacheKey, 'done')\n      } catch (err) {\n        // TODO: store partial buffer with error after we retry 3 times\n        debug?.('set', cacheKey, 'failed', err)\n      } finally {\n        resolvePending()\n        pendingSets.delete(cacheKey)\n      }\n    },\n\n    async refreshTags() {\n      // Nothing to do for an in-memory cache handler.\n    },\n\n    async getExpiration(tags) {\n      const expirations = tags.map((tag) => {\n        const entry = tagsManifest.get(tag)\n        if (!entry) return 0\n        // Return the most recent timestamp (either expired or stale)\n        return entry.expired || 0\n      })\n\n      const expiration = Math.max(...expirations, 0)\n\n      debug?.('getExpiration', { tags, expiration })\n\n      return expiration\n    },\n\n    async updateTags(tags, durations) {\n      const now = Math.round(performance.timeOrigin + performance.now())\n      debug?.('updateTags', { tags, timestamp: now })\n\n      for (const tag of tags) {\n        // TODO: update file-system-cache?\n        const existingEntry = tagsManifest.get(tag) || {}\n\n        if (durations) {\n          // Use provided durations directly\n          const updates: TagManifestEntry = { ...existingEntry }\n\n          // mark as stale immediately\n          updates.stale = now\n\n          if (durations.expire !== undefined) {\n            updates.expired = now + durations.expire * 1000 // Convert seconds to ms\n          }\n\n          tagsManifest.set(tag, updates)\n        } else {\n          // Update expired field for immediate expiration (default behavior when no durations provided)\n          tagsManifest.set(tag, { ...existingEntry, expired: now })\n        }\n      }\n    },\n  }\n}\n","import { createDefaultCacheHandler } from '../lib/cache-handlers/default'\nimport type { CacheHandler } from '../lib/cache-handlers/types'\n\nconst debug = process.env.NEXT_PRIVATE_DEBUG_CACHE\n  ? (message: string, ...args: any[]) => {\n      console.log(`use-cache: ${message}`, ...args)\n    }\n  : undefined\n\nconst handlersSymbol = Symbol.for('@next/cache-handlers')\nconst handlersMapSymbol = Symbol.for('@next/cache-handlers-map')\nconst handlersSetSymbol = Symbol.for('@next/cache-handlers-set')\n\n/**\n * The reference to the cache handlers. We store the cache handlers on the\n * global object so that we can access the same instance across different\n * boundaries (such as different copies of the same module).\n */\nconst reference: typeof globalThis & {\n  [handlersSymbol]?: {\n    RemoteCache?: CacheHandler\n    DefaultCache?: CacheHandler\n  }\n  [handlersMapSymbol]?: Map<string, CacheHandler>\n  [handlersSetSymbol]?: Set<CacheHandler>\n} = globalThis\n\n/**\n * Initialize the cache handlers.\n * @param cacheMaxMemorySize - The maximum memory size of the cache in bytes, if\n *  not provided, the default memory size will be used.\n * @returns `true` if the cache handlers were initialized, `false` if they were already initialized.\n */\nexport function initializeCacheHandlers(cacheMaxMemorySize: number): boolean {\n  // If the cache handlers have already been initialized, don't do it again.\n  if (reference[handlersMapSymbol]) {\n    debug?.('cache handlers already initialized')\n    return false\n  }\n\n  debug?.('initializing cache handlers')\n  reference[handlersMapSymbol] = new Map<string, CacheHandler>()\n\n  // Initialize the cache from the symbol contents first.\n  if (reference[handlersSymbol]) {\n    let fallback: CacheHandler\n    if (reference[handlersSymbol].DefaultCache) {\n      debug?.('setting \"default\" cache handler from symbol')\n      fallback = reference[handlersSymbol].DefaultCache\n    } else {\n      debug?.('setting \"default\" cache handler from default')\n      fallback = createDefaultCacheHandler(cacheMaxMemorySize)\n    }\n\n    reference[handlersMapSymbol].set('default', fallback)\n\n    if (reference[handlersSymbol].RemoteCache) {\n      debug?.('setting \"remote\" cache handler from symbol')\n      reference[handlersMapSymbol].set(\n        'remote',\n        reference[handlersSymbol].RemoteCache\n      )\n    } else {\n      debug?.('setting \"remote\" cache handler from default')\n      reference[handlersMapSymbol].set('remote', fallback)\n    }\n  } else {\n    const handler = createDefaultCacheHandler(cacheMaxMemorySize)\n\n    debug?.('setting \"default\" cache handler from default')\n    reference[handlersMapSymbol].set('default', handler)\n    debug?.('setting \"remote\" cache handler from default')\n    reference[handlersMapSymbol].set('remote', handler)\n  }\n\n  // Create a set of the cache handlers.\n  reference[handlersSetSymbol] = new Set(reference[handlersMapSymbol].values())\n\n  return true\n}\n\n/**\n * Get a cache handler by kind.\n * @param kind - The kind of cache handler to get.\n * @returns The cache handler, or `undefined` if it does not exist.\n * @throws If the cache handlers are not initialized.\n */\nexport function getCacheHandler(kind: string): CacheHandler | undefined {\n  // This should never be called before initializeCacheHandlers.\n  if (!reference[handlersMapSymbol]) {\n    throw new Error('Cache handlers not initialized')\n  }\n\n  return reference[handlersMapSymbol].get(kind)\n}\n\n/**\n * Get a set iterator over the cache handlers.\n * @returns An iterator over the cache handlers, or `undefined` if they are not\n * initialized.\n */\nexport function getCacheHandlers(): SetIterator<CacheHandler> | undefined {\n  if (!reference[handlersSetSymbol]) {\n    return undefined\n  }\n\n  return reference[handlersSetSymbol].values()\n}\n\n/**\n * Get a map iterator over the cache handlers (keyed by kind).\n * @returns An iterator over the cache handler entries, or `undefined` if they\n * are not initialized.\n * @throws If the cache handlers are not initialized.\n */\nexport function getCacheHandlerEntries():\n  | MapIterator<[string, CacheHandler]>\n  | undefined {\n  if (!reference[handlersMapSymbol]) {\n    return undefined\n  }\n\n  return reference[handlersMapSymbol].entries()\n}\n\n/**\n * Set a cache handler by kind.\n * @param kind - The kind of cache handler to set.\n * @param cacheHandler - The cache handler to set.\n */\nexport function setCacheHandler(\n  kind: string,\n  cacheHandler: CacheHandler\n): void {\n  // This should never be called before initializeCacheHandlers.\n  if (!reference[handlersMapSymbol] || !reference[handlersSetSymbol]) {\n    throw new Error('Cache handlers not initialized')\n  }\n\n  debug?.('setting cache handler for \"%s\"', kind)\n  reference[handlersMapSymbol].set(kind, cacheHandler)\n  reference[handlersSetSymbol].add(cacheHandler)\n}\n","import type { RequestData, FetchEventResult } from './types'\nimport type { RequestInit } from './spec-extension/request'\nimport { PageSignatureError } from './error'\nimport { fromNodeOutgoingHttpHeaders, normalizeNextQueryParam } from './utils'\nimport {\n  NextFetchEvent,\n  getWaitUntilPromiseFromEvent,\n} from './spec-extension/fetch-event'\nimport { NextRequest } from './spec-extension/request'\nimport { NextResponse } from './spec-extension/response'\nimport {\n  parseRelativeURL,\n  getRelativeURL,\n} from '../../shared/lib/router/utils/relativize-url'\nimport { NextURL } from './next-url'\nimport { stripInternalSearchParams } from '../internal-utils'\nimport { normalizeRscURL } from '../../shared/lib/router/utils/app-paths'\nimport {\n  FLIGHT_HEADERS,\n  NEXT_REWRITTEN_PATH_HEADER,\n  NEXT_REWRITTEN_QUERY_HEADER,\n  NEXT_RSC_UNION_QUERY,\n  RSC_HEADER,\n} from '../../client/components/app-router-headers'\nimport { ensureInstrumentationRegistered } from './globals'\nimport { createRequestStoreForAPI } from '../async-storage/request-store'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { createWorkStore } from '../async-storage/work-store'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { NEXT_ROUTER_PREFETCH_HEADER } from '../../client/components/app-router-headers'\nimport { getTracer } from '../lib/trace/tracer'\nimport type { TextMapGetter } from 'next/dist/compiled/@opentelemetry/api'\nimport { MiddlewareSpan } from '../lib/trace/constants'\nimport { CloseController } from './web-on-close'\nimport { getEdgePreviewProps } from './get-edge-preview-props'\nimport { getBuiltinRequestContext } from '../after/builtin-request-context'\nimport { getImplicitTags } from '../lib/implicit-tags'\nimport { setRequestMeta } from '../request-meta'\n\nexport class NextRequestHint extends NextRequest {\n  sourcePage: string\n  fetchMetrics: FetchEventResult['fetchMetrics'] | undefined\n\n  constructor(params: {\n    init: RequestInit\n    input: Request | string\n    page: string\n  }) {\n    super(params.input, params.init)\n    this.sourcePage = params.page\n  }\n\n  get request() {\n    throw new PageSignatureError({ page: this.sourcePage })\n  }\n\n  respondWith() {\n    throw new PageSignatureError({ page: this.sourcePage })\n  }\n\n  waitUntil() {\n    throw new PageSignatureError({ page: this.sourcePage })\n  }\n}\n\nconst headersGetter: TextMapGetter<Headers> = {\n  keys: (headers) => Array.from(headers.keys()),\n  get: (headers, key) => headers.get(key) ?? undefined,\n}\n\nexport type AdapterOptions = {\n  handler: (req: NextRequestHint, event: NextFetchEvent) => Promise<Response>\n  page: string\n  request: RequestData\n  IncrementalCache?: typeof import('../lib/incremental-cache').IncrementalCache\n  incrementalCacheHandler?: typeof import('../lib/incremental-cache').CacheHandler\n  bypassNextUrl?: boolean\n}\n\n// This has to be compatible with what the Vercel builder does as well:\n// https://github.com/vercel/vercel/blob/0e0a6eb9f12216202ae2f5ee37e4ada1796361fd/packages/next/src/edge-function-source/get-edge-function.ts#L112-L136\nexport type EdgeHandler = (opts: {\n  request: AdapterOptions['request']\n}) => Promise<FetchEventResult>\n\nlet propagator: <T>(request: NextRequestHint, fn: () => T) => T = (\n  request,\n  fn\n) => {\n  const tracer = getTracer()\n  return tracer.withPropagatedContext(request.headers, fn, headersGetter)\n}\n\nlet testApisIntercepted = false\n\nfunction ensureTestApisIntercepted() {\n  if (!testApisIntercepted) {\n    testApisIntercepted = true\n    if (process.env.NEXT_PRIVATE_TEST_PROXY === 'true') {\n      const { interceptTestApis, wrapRequestHandler } =\n        // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm\n        require('next/dist/experimental/testmode/server-edge') as typeof import('../../experimental/testmode/server-edge')\n      interceptTestApis()\n      propagator = wrapRequestHandler(propagator)\n    }\n  }\n}\n\nexport async function adapter(\n  params: AdapterOptions\n): Promise<FetchEventResult> {\n  ensureTestApisIntercepted()\n  await ensureInstrumentationRegistered()\n\n  // TODO-APP: use explicit marker for this\n  const isEdgeRendering =\n    typeof (globalThis as any).__BUILD_MANIFEST !== 'undefined'\n\n  params.request.url = normalizeRscURL(params.request.url)\n\n  const requestURL = params.bypassNextUrl\n    ? new URL(params.request.url)\n    : new NextURL(params.request.url, {\n        headers: params.request.headers,\n        nextConfig: params.request.nextConfig,\n      })\n\n  // Iterator uses an index to keep track of the current iteration. Because of deleting and appending below we can't just use the iterator.\n  // Instead we use the keys before iteration.\n  const keys = [...requestURL.searchParams.keys()]\n  for (const key of keys) {\n    const value = requestURL.searchParams.getAll(key)\n\n    const normalizedKey = normalizeNextQueryParam(key)\n    if (normalizedKey) {\n      requestURL.searchParams.delete(normalizedKey)\n      for (const val of value) {\n        requestURL.searchParams.append(normalizedKey, val)\n      }\n      requestURL.searchParams.delete(key)\n    }\n  }\n\n  // Ensure users only see page requests, never data requests.\n  let buildId = process.env.__NEXT_BUILD_ID || ''\n  if ('buildId' in requestURL) {\n    buildId = (requestURL as NextURL).buildId || ''\n    requestURL.buildId = ''\n  }\n\n  const requestHeaders = fromNodeOutgoingHttpHeaders(params.request.headers)\n  const isNextDataRequest = requestHeaders.has('x-nextjs-data')\n  const isRSCRequest = requestHeaders.get(RSC_HEADER) === '1'\n\n  if (isNextDataRequest && requestURL.pathname === '/index') {\n    requestURL.pathname = '/'\n  }\n\n  const flightHeaders = new Map()\n\n  // Headers should only be stripped for middleware\n  if (!isEdgeRendering && !process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) {\n    for (const header of FLIGHT_HEADERS) {\n      const value = requestHeaders.get(header)\n      if (value !== null) {\n        flightHeaders.set(header, value)\n        requestHeaders.delete(header)\n      }\n    }\n  }\n\n  const normalizeURL = process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE\n    ? new URL(params.request.url)\n    : requestURL\n\n  const rscHash = normalizeURL.searchParams.get(NEXT_RSC_UNION_QUERY)\n\n  const request = new NextRequestHint({\n    page: params.page,\n    // Strip internal query parameters off the request.\n    input: process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE\n      ? normalizeURL.toString()\n      : stripInternalSearchParams(normalizeURL).toString(),\n    init: {\n      body: params.request.body,\n      headers: requestHeaders,\n      method: params.request.method,\n      nextConfig: params.request.nextConfig,\n      signal: params.request.signal,\n    },\n  })\n\n  if (params.request.requestMeta) {\n    setRequestMeta(request, params.request.requestMeta)\n  }\n\n  /**\n   * This allows to identify the request as a data request. The user doesn't\n   * need to know about this property neither use it. We add it for testing\n   * purposes.\n   */\n  if (isNextDataRequest) {\n    Object.defineProperty(request, '__isData', {\n      enumerable: false,\n      value: true,\n    })\n  }\n\n  if (\n    // If we are inside of the next start sandbox\n    // leverage the shared instance if not we need\n    // to create a fresh cache instance each time\n    !(globalThis as any).__incrementalCacheShared &&\n    (params as any).IncrementalCache\n  ) {\n    ;(globalThis as any).__incrementalCache = new (\n      params as {\n        IncrementalCache: typeof import('../lib/incremental-cache').IncrementalCache\n      }\n    ).IncrementalCache({\n      CurCacheHandler: params.incrementalCacheHandler,\n      minimalMode: process.env.NODE_ENV !== 'development',\n      fetchCacheKeyPrefix: process.env.__NEXT_FETCH_CACHE_KEY_PREFIX,\n      dev: process.env.NODE_ENV === 'development',\n      requestHeaders: params.request.headers as any,\n\n      getPrerenderManifest: () => {\n        return {\n          version: -1 as any, // letting us know this doesn't conform to spec\n          routes: {},\n          dynamicRoutes: {},\n          notFoundRoutes: [],\n          preview: getEdgePreviewProps(),\n        }\n      },\n    })\n  }\n\n  // if we're in an edge runtime sandbox, we should use the waitUntil\n  // that we receive from the enclosing NextServer\n  const outerWaitUntil =\n    params.request.waitUntil ?? getBuiltinRequestContext()?.waitUntil\n\n  const event = new NextFetchEvent({\n    request,\n    page: params.page,\n    context: outerWaitUntil ? { waitUntil: outerWaitUntil } : undefined,\n  })\n  let response\n  let cookiesFromResponse\n\n  response = await propagator(request, () => {\n    // we only care to make async storage available for middleware\n    const isMiddleware =\n      params.page === '/middleware' ||\n      params.page === '/src/middleware' ||\n      params.page === '/proxy' ||\n      params.page === '/src/proxy'\n\n    if (isMiddleware) {\n      // if we're in an edge function, we only get a subset of `nextConfig` (no `experimental`),\n      // so we have to inject it via DefinePlugin.\n      // in `next start` this will be passed normally (see `NextNodeServer.runMiddleware`).\n\n      const waitUntil = event.waitUntil.bind(event)\n      const closeController = new CloseController()\n\n      return getTracer().trace(\n        MiddlewareSpan.execute,\n        {\n          spanName: `middleware ${request.method}`,\n          attributes: {\n            'http.target': request.nextUrl.pathname,\n            'http.method': request.method,\n          },\n        },\n        async () => {\n          try {\n            const onUpdateCookies = (cookies: Array<string>) => {\n              cookiesFromResponse = cookies\n            }\n            const previewProps = getEdgePreviewProps()\n            const page = '/' // Fake Work\n            const fallbackRouteParams = null\n\n            const implicitTags = await getImplicitTags(\n              page,\n              request.nextUrl.pathname,\n              fallbackRouteParams\n            )\n\n            const requestStore = createRequestStoreForAPI(\n              request,\n              request.nextUrl,\n              implicitTags,\n              onUpdateCookies,\n              previewProps\n            )\n\n            const workStore = createWorkStore({\n              page,\n              renderOpts: {\n                cacheLifeProfiles:\n                  params.request.nextConfig?.experimental?.cacheLife,\n                cacheComponents: false,\n                experimental: {\n                  isRoutePPREnabled: false,\n                  authInterrupts:\n                    !!params.request.nextConfig?.experimental?.authInterrupts,\n                },\n                supportsDynamicResponse: true,\n                waitUntil,\n                onClose: closeController.onClose.bind(closeController),\n                onAfterTaskError: undefined,\n              },\n              isPrefetchRequest:\n                request.headers.get(NEXT_ROUTER_PREFETCH_HEADER) === '1',\n              buildId: buildId ?? '',\n              previouslyRevalidatedTags: [],\n            })\n\n            return await workAsyncStorage.run(workStore, () =>\n              workUnitAsyncStorage.run(\n                requestStore,\n                params.handler,\n                request,\n                event\n              )\n            )\n          } finally {\n            // middleware cannot stream, so we can consider the response closed\n            // as soon as the handler returns.\n            // we can delay running it until a bit later --\n            // if it's needed, we'll have a `waitUntil` lock anyway.\n            setTimeout(() => {\n              closeController.dispatchClose()\n            }, 0)\n          }\n        }\n      )\n    }\n    return params.handler(request, event)\n  })\n\n  // check if response is a Response object\n  if (response && !(response instanceof Response)) {\n    throw new TypeError('Expected an instance of Response to be returned')\n  }\n\n  if (response && cookiesFromResponse) {\n    response.headers.set('set-cookie', cookiesFromResponse)\n  }\n\n  /**\n   * For rewrites we must always include the locale in the final pathname\n   * so we re-create the NextURL forcing it to include it when the it is\n   * an internal rewrite. Also we make sure the outgoing rewrite URL is\n   * a data URL if the request was a data request.\n   */\n  const rewrite = response?.headers.get('x-middleware-rewrite')\n  if (response && rewrite && (isRSCRequest || !isEdgeRendering)) {\n    const destination = new NextURL(rewrite, {\n      forceLocale: true,\n      headers: params.request.headers,\n      nextConfig: params.request.nextConfig,\n    })\n\n    if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE && !isEdgeRendering) {\n      if (destination.host === request.nextUrl.host) {\n        destination.buildId = buildId || destination.buildId\n        response.headers.set('x-middleware-rewrite', String(destination))\n      }\n    }\n\n    /**\n     * When the request is a data request we must show if there was a rewrite\n     * with an internal header so the client knows which component to load\n     * from the data request.\n     */\n    const { url: relativeDestination, isRelative } = parseRelativeURL(\n      destination.toString(),\n      requestURL.toString()\n    )\n\n    if (\n      !isEdgeRendering &&\n      isNextDataRequest &&\n      // if the rewrite is external and external rewrite\n      // resolving config is enabled don't add this header\n      // so the upstream app can set it instead\n      !(\n        process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE &&\n        relativeDestination.match(/http(s)?:\\/\\//)\n      )\n    ) {\n      response.headers.set('x-nextjs-rewrite', relativeDestination)\n    }\n\n    // Check to see if this is a non-relative rewrite. If it is, we need\n    // to check to see if it's an allowed origin to receive the rewritten\n    // headers.\n    const isAllowedOrigin = !isRelative\n      ? params.request.nextConfig?.experimental?.clientParamParsingOrigins?.some(\n          (origin) => new RegExp(origin).test(destination.origin)\n        )\n      : false\n\n    // If this is an RSC request, and the pathname or search has changed, and\n    // this isn't an external rewrite, we need to set the rewritten pathname and\n    // query headers.\n    if (isRSCRequest && (isRelative || isAllowedOrigin)) {\n      if (requestURL.pathname !== destination.pathname) {\n        response.headers.set(NEXT_REWRITTEN_PATH_HEADER, destination.pathname)\n      }\n      if (requestURL.search !== destination.search) {\n        response.headers.set(\n          NEXT_REWRITTEN_QUERY_HEADER,\n          // remove the leading ? from the search string\n          destination.search.slice(1)\n        )\n      }\n    }\n  }\n\n  /**\n   * Always forward the `_rsc` search parameter to the rewritten URL for RSC requests,\n   * unless it's already present. This is necessary to ensure that RSC hash validation\n   * works correctly after a rewrite. For internal rewrites, the server can validate the\n   * RSC hash using the original URL, so forwarding the `_rsc` parameter is less critical.\n   * However, for external rewrites (where the request is proxied to another Next.js server),\n   * the external server does not have access to the original URL or its search parameters.\n   * In these cases, forwarding the `_rsc` parameter is essential so that the external server\n   * can perform the correct RSC hash validation.\n   */\n  if (response && rewrite && isRSCRequest && rscHash) {\n    const rewriteURL = new URL(rewrite)\n    if (!rewriteURL.searchParams.has(NEXT_RSC_UNION_QUERY)) {\n      rewriteURL.searchParams.set(NEXT_RSC_UNION_QUERY, rscHash)\n      response.headers.set('x-middleware-rewrite', rewriteURL.toString())\n    }\n  }\n\n  /**\n   * For redirects we will not include the locale in case when it is the\n   * default and we must also make sure the outgoing URL is a data one if\n   * the incoming request was a data request.\n   */\n  const redirect = response?.headers.get('Location')\n  if (response && redirect && !isEdgeRendering) {\n    const redirectURL = new NextURL(redirect, {\n      forceLocale: false,\n      headers: params.request.headers,\n      nextConfig: params.request.nextConfig,\n    })\n\n    /**\n     * Responses created from redirects have immutable headers so we have\n     * to clone the response to be able to modify it.\n     */\n    response = new Response(response.body, response)\n\n    if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) {\n      if (redirectURL.host === requestURL.host) {\n        redirectURL.buildId = buildId || redirectURL.buildId\n        response.headers.set(\n          'Location',\n          getRelativeURL(redirectURL, requestURL)\n        )\n      }\n    }\n\n    /**\n     * When the request is a data request we can't use the location header as\n     * it may end up with CORS error. Instead we map to an internal header so\n     * the client knows the destination.\n     */\n    if (isNextDataRequest) {\n      response.headers.delete('Location')\n      response.headers.set(\n        'x-nextjs-redirect',\n        getRelativeURL(redirectURL.toString(), requestURL.toString())\n      )\n    }\n  }\n\n  const finalResponse = response ? response : NextResponse.next()\n\n  // Flight headers are not overridable / removable so they are applied at the end.\n  const middlewareOverrideHeaders = finalResponse.headers.get(\n    'x-middleware-override-headers'\n  )\n  const overwrittenHeaders: string[] = []\n  if (middlewareOverrideHeaders) {\n    for (const [key, value] of flightHeaders) {\n      finalResponse.headers.set(`x-middleware-request-${key}`, value)\n      overwrittenHeaders.push(key)\n    }\n\n    if (overwrittenHeaders.length > 0) {\n      finalResponse.headers.set(\n        'x-middleware-override-headers',\n        middlewareOverrideHeaders + ',' + overwrittenHeaders.join(',')\n      )\n    }\n  }\n\n  return {\n    response: finalResponse,\n    waitUntil: getWaitUntilPromiseFromEvent(event) ?? Promise.resolve(),\n    fetchMetrics: request.fetchMetrics,\n  }\n}\n","import type { PathnameNormalizer } from './pathname-normalizer'\n\nimport {\n  RSC_SEGMENT_SUFFIX,\n  RSC_SEGMENTS_DIR_SUFFIX,\n} from '../../../lib/constants'\nimport { escapeStringRegexp } from '../../../shared/lib/escape-regexp'\n\nconst PATTERN = new RegExp(\n  `^(/.*)${escapeStringRegexp(RSC_SEGMENTS_DIR_SUFFIX)}(/.*)${escapeStringRegexp(RSC_SEGMENT_SUFFIX)}$`\n)\n\nexport class SegmentPrefixRSCPathnameNormalizer implements PathnameNormalizer {\n  public match(pathname: string): boolean {\n    return PATTERN.test(pathname)\n  }\n\n  public extract(pathname: string) {\n    const match = pathname.match(PATTERN)\n    if (!match) return null\n\n    return { originalPathname: match[1], segmentPath: match[2] }\n  }\n\n  public normalize(pathname: string): string {\n    const match = this.extract(pathname)\n    if (!match) return pathname\n\n    return match.originalPathname\n  }\n}\n","import type {\n  DynamicParamTypes,\n  DynamicParamTypesShort,\n} from '../../shared/lib/app-router-types'\n\nexport const dynamicParamTypes: Record<\n  DynamicParamTypes,\n  DynamicParamTypesShort\n> = {\n  catchall: 'c',\n  'catchall-intercepted-(..)(..)': 'ci(..)(..)',\n  'catchall-intercepted-(.)': 'ci(.)',\n  'catchall-intercepted-(..)': 'ci(..)',\n  'catchall-intercepted-(...)': 'ci(...)',\n  'optional-catchall': 'oc',\n  dynamic: 'd',\n  'dynamic-intercepted-(..)(..)': 'di(..)(..)',\n  'dynamic-intercepted-(.)': 'di(.)',\n  'dynamic-intercepted-(..)': 'di(..)',\n  'dynamic-intercepted-(...)': 'di(...)',\n}\n","import {\n  DEFAULT_MAX_POSTPONED_STATE_SIZE,\n  parseMaxPostponedStateSize,\n} from '../../shared/lib/size-limit'\nimport type { SizeLimit } from '../../types'\n\nconst INVALID_MAX_POSTPONED_STATE_SIZE_ERROR_MESSAGE =\n  'maxPostponedStateSize must be a valid number (bytes) or filesize format string (e.g., \"5mb\")'\n\nexport type PostponedRequestBodyChunk = Buffer | Uint8Array | string\n\nexport function getMaxPostponedStateSize(\n  configuredMaxPostponedStateSize: SizeLimit | undefined\n): {\n  maxPostponedStateSize: SizeLimit\n  maxPostponedStateSizeBytes: number\n} {\n  const maxPostponedStateSize =\n    configuredMaxPostponedStateSize ?? DEFAULT_MAX_POSTPONED_STATE_SIZE\n  const maxPostponedStateSizeBytes = parseMaxPostponedStateSize(\n    configuredMaxPostponedStateSize\n  )\n\n  if (maxPostponedStateSizeBytes === undefined) {\n    throw new Error(INVALID_MAX_POSTPONED_STATE_SIZE_ERROR_MESSAGE)\n  }\n\n  return { maxPostponedStateSize, maxPostponedStateSizeBytes }\n}\n\nexport function getPostponedStateExceededErrorMessage(\n  maxPostponedStateSize: SizeLimit\n): string {\n  return (\n    `Postponed state exceeded ${maxPostponedStateSize} limit. ` +\n    `To configure the limit, see: https://nextjs.org/docs/app/api-reference/config/next-config-js/max-postponed-state-size`\n  )\n}\n\nfunction toBuffer(chunk: PostponedRequestBodyChunk): Buffer {\n  return Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n}\n\nexport async function readBodyWithSizeLimit(\n  body: AsyncIterable<PostponedRequestBodyChunk>,\n  maxBodySizeBytes: number\n): Promise<Buffer | null> {\n  const chunks: Array<Buffer> = []\n  let size = 0\n\n  for await (const chunk of body) {\n    const buffer = toBuffer(chunk)\n    size += buffer.byteLength\n    if (size > maxBodySizeBytes) {\n      return null\n    }\n    chunks.push(buffer)\n  }\n\n  return Buffer.concat(chunks)\n}\n","import type { __ApiPreviewProps } from './api-utils'\nimport type {\n  GenericComponentMod,\n  LoadComponentsReturnType,\n} from './load-components'\nimport type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher'\nimport type { Params } from './request/params'\nimport type { NextConfig, NextConfigRuntime } from './config-shared'\nimport { parseMaxPostponedStateSize } from './config-shared'\nimport type {\n  NextParsedUrlQuery,\n  NextUrlWithParsedQuery,\n  RequestMeta,\n} from './request-meta'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { RenderOptsPartial as PagesRenderOptsPartial } from './render'\nimport type {\n  RenderOptsPartial as AppRenderOptsPartial,\n  ServerOnInstrumentationRequestError,\n} from './app-render/types'\nimport type { ServerComponentsHmrCache } from './response-cache'\nimport {\n  NormalizeError,\n  DecodeError,\n  normalizeRepeatedSlashes,\n  MissingStaticPage,\n} from '../shared/lib/utils'\nimport type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'\nimport type { BaseNextRequest, BaseNextResponse } from './base-http'\nimport type {\n  ManifestRewriteRoute,\n  ManifestRoute,\n  PrerenderManifest,\n} from '../build'\nimport type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'\nimport type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'\nimport type { PagesAPIRouteMatch } from './route-matches/pages-api-route-match'\nimport type {\n  Server as HTTPServer,\n  IncomingMessage,\n  ServerResponse as HTTPServerResponse,\n} from 'http'\nimport type { ProxyMatcher } from '../build/analysis/get-page-static-info'\nimport type { TLSSocket } from 'tls'\nimport type { PathnameNormalizer } from './normalizers/request/pathname-normalizer'\nimport type { InstrumentationModule } from './instrumentation/types'\n\nimport * as path from 'path'\nimport { format as formatUrl } from 'url'\nimport { formatHostname } from './lib/format-hostname'\nimport {\n  APP_PATHS_MANIFEST,\n  NEXT_BUILTIN_DOCUMENT,\n  PAGES_MANIFEST,\n  STATIC_STATUS_PAGES,\n  UNDERSCORE_NOT_FOUND_ROUTE,\n  UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,\n} from '../shared/lib/constants'\nimport { isDynamicRoute } from '../shared/lib/router/utils'\nimport { execOnce } from '../shared/lib/utils'\nimport { isBlockedPage } from './utils'\nimport { getBotType, isBot } from '../shared/lib/router/utils/is-bot'\nimport RenderResult from './render-result'\nimport { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'\nimport { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'\nimport * as Log from '../build/output/log'\nimport { getServerUtils } from './server-utils'\nimport isError, { getProperError } from '../lib/is-error'\nimport {\n  addRequestMeta,\n  getRequestMeta,\n  removeRequestMeta,\n  setRequestMeta,\n} from './request-meta'\nimport { removePathPrefix } from '../shared/lib/router/utils/remove-path-prefix'\nimport { normalizeAppPath } from '../shared/lib/router/utils/app-paths'\nimport { getHostname } from '../shared/lib/get-hostname'\nimport {\n  parseUrl,\n  parseUrl as parseUrlUtil,\n} from '../shared/lib/router/utils/parse-url'\nimport { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'\nimport {\n  RSC_HEADER,\n  NEXT_RSC_UNION_QUERY,\n  NEXT_ROUTER_PREFETCH_HEADER,\n  NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n  NEXT_URL,\n  NEXT_ROUTER_STATE_TREE_HEADER,\n  NEXT_INSTANT_TEST_COOKIE,\n} from '../client/components/app-router-headers'\nimport type {\n  MatchOptions,\n  RouteMatcherManager,\n} from './route-matcher-managers/route-matcher-manager'\nimport { LocaleRouteNormalizer } from './normalizers/locale-route-normalizer'\nimport { DefaultRouteMatcherManager } from './route-matcher-managers/default-route-matcher-manager'\nimport { AppPageRouteMatcherProvider } from './route-matcher-providers/app-page-route-matcher-provider'\nimport { AppRouteRouteMatcherProvider } from './route-matcher-providers/app-route-route-matcher-provider'\nimport { PagesAPIRouteMatcherProvider } from './route-matcher-providers/pages-api-route-matcher-provider'\nimport { PagesRouteMatcherProvider } from './route-matcher-providers/pages-route-matcher-provider'\nimport { ServerManifestLoader } from './route-matcher-providers/helpers/manifest-loaders/server-manifest-loader'\nimport {\n  getTracer,\n  isBubbledError,\n  SpanKind,\n  SpanStatusCode,\n} from './lib/trace/tracer'\nimport { BaseServerSpan } from './lib/trace/constants'\nimport { I18NProvider } from './lib/i18n-provider'\nimport { sendResponse } from './send-response'\nimport { normalizeNextQueryParam } from './web/utils'\nimport {\n  HTML_CONTENT_TYPE_HEADER,\n  JSON_CONTENT_TYPE_HEADER,\n  MATCHED_PATH_HEADER,\n  NEXT_RESUME_HEADER,\n} from '../lib/constants'\nimport { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'\nimport { matchNextDataPathname } from './lib/match-next-data-pathname'\nimport getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-asset-path'\nimport { RSCPathnameNormalizer } from './normalizers/request/rsc'\nimport { stripFlightHeaders } from './app-render/strip-flight-headers'\nimport {\n  isAppPageRouteModule,\n  isAppRouteRouteModule,\n} from './route-modules/checks'\nimport { NextDataPathnameNormalizer } from './normalizers/request/next-data'\nimport { getIsPossibleServerAction } from './lib/server-action-request-meta'\nimport { isInterceptionRouteAppPath } from '../shared/lib/router/utils/interception-routes'\nimport { toRoute } from './lib/to-route'\nimport type { DeepReadonly } from '../shared/lib/deep-readonly'\nimport { isNodeNextRequest, isNodeNextResponse } from './base-http/helpers'\nimport { patchSetHeaderWithCookieSupport } from './lib/patch-set-header'\nimport { checkIsAppPPREnabled } from './lib/experimental/ppr'\nimport {\n  getBuiltinRequestContext,\n  type WaitUntil,\n} from './after/builtin-request-context'\nimport { NextRequestHint } from './web/adapter'\nimport type { RouteModule } from './route-modules/route-module'\nimport { type FallbackMode, parseFallbackField } from '../lib/fallback'\nimport { SegmentPrefixRSCPathnameNormalizer } from './normalizers/request/segment-prefix-rsc'\nimport { shouldServeStreamingMetadata } from './lib/streaming-metadata'\nimport { decodeQueryPathParameter } from './lib/decode-query-path-parameter'\nimport { NoFallbackError } from '../shared/lib/no-fallback-error.external'\nimport { fixMojibake } from './lib/fix-mojibake'\nimport { computeCacheBustingSearchParam } from '../shared/lib/router/utils/cache-busting-search-param'\nimport { setCacheBustingSearchParamWithHash } from '../client/components/router-reducer/set-cache-busting-search-param'\nimport type { CacheControl } from './lib/cache-control'\nimport type { PrerenderedRoute } from '../build/static-paths/types'\nimport { createOpaqueFallbackRouteParams } from './request/fallback-params'\nimport { RouteKind } from './route-kind'\nimport type { ErrorModule } from './load-default-error-components'\nimport {\n  getMaxPostponedStateSize,\n  getPostponedStateExceededErrorMessage,\n  readBodyWithSizeLimit,\n} from './lib/postponed-request-body'\n\nexport type FindComponentsResult<\n  NextModule extends GenericComponentMod = GenericComponentMod,\n> = {\n  components: LoadComponentsReturnType<NextModule>\n  query: NextParsedUrlQuery\n}\n\nexport interface MiddlewareRoutingItem {\n  page: string\n  match: MiddlewareRouteMatch\n  matchers?: ProxyMatcher[]\n}\n\nexport type RouteHandler<\n  ServerRequest extends BaseNextRequest = BaseNextRequest,\n  ServerResponse extends BaseNextResponse = BaseNextResponse,\n> = (\n  req: ServerRequest,\n  res: ServerResponse,\n  parsedUrl: NextUrlWithParsedQuery\n) => PromiseLike<boolean> | boolean\n\n/**\n * The normalized route manifest is the same as the route manifest, but with\n * the rewrites normalized to the object shape that the router expects.\n */\nexport type NormalizedRouteManifest = {\n  readonly dynamicRoutes: ReadonlyArray<ManifestRoute>\n  readonly rewrites: {\n    readonly beforeFiles: ReadonlyArray<ManifestRewriteRoute>\n    readonly afterFiles: ReadonlyArray<ManifestRewriteRoute>\n    readonly fallback: ReadonlyArray<ManifestRewriteRoute>\n  }\n}\n\nexport interface Options {\n  /**\n   * Object containing the configuration next.config.js\n   */\n  conf: NextConfig\n  /**\n   * Set to false when the server was created by Next.js\n   */\n  customServer?: boolean\n  /**\n   * Tells if Next.js is running in dev mode\n   */\n  dev?: boolean\n  /**\n   * Enables the experimental testing mode.\n   */\n  experimentalTestProxy?: boolean\n\n  /**\n   * Whether or not the dev server is running in experimental HTTPS mode\n   */\n  experimentalHttpsServer?: boolean\n  /**\n   * Where the Next project is located\n   */\n  dir?: string\n  /**\n   * Tells if Next.js is at the platform-level\n   */\n  minimalMode?: boolean\n  /**\n   * Hide error messages containing server information\n   */\n  quiet?: boolean\n  /**\n   * The hostname the server is running behind\n   */\n  hostname?: string\n  /**\n   * The port the server is running behind\n   */\n  port?: number\n  /**\n   * The HTTP Server that Next.js is running behind\n   */\n  httpServer?: HTTPServer\n}\n\nexport type RenderOpts = PagesRenderOptsPartial & AppRenderOptsPartial\n\nexport type LoadedRenderOpts<\n  NextModule extends GenericComponentMod = GenericComponentMod,\n> = RenderOpts & LoadComponentsReturnType<NextModule> & RequestLifecycleOpts\n\nexport type RequestLifecycleOpts = {\n  waitUntil: ((promise: Promise<any>) => void) | undefined\n  onClose: (callback: () => void) => void\n  onAfterTaskError: ((error: unknown) => void) | undefined\n}\n\ntype BaseRenderOpts = RenderOpts & {\n  poweredByHeader: boolean\n  generateEtags: boolean\n  previewProps: __ApiPreviewProps\n}\n\n/**\n * The public interface for rendering with the server programmatically. This\n * would typically only allow the base request or response to extend it, but\n * because this can be programmatically accessed, we assume that it could also\n * be the base Node.js request and response types.\n */\nexport interface BaseRequestHandler<\n  ServerRequest extends BaseNextRequest | IncomingMessage = BaseNextRequest,\n  ServerResponse extends\n    | BaseNextResponse\n    | HTTPServerResponse = BaseNextResponse,\n> {\n  (\n    req: ServerRequest,\n    res: ServerResponse,\n    parsedUrl?: NextUrlWithParsedQuery | undefined\n  ): Promise<void> | void\n}\n\nexport type RequestContext<\n  ServerRequest extends BaseNextRequest = BaseNextRequest,\n  ServerResponse extends BaseNextResponse = BaseNextResponse,\n> = {\n  req: ServerRequest\n  res: ServerResponse\n  pathname: string\n  query: NextParsedUrlQuery\n  renderOpts: RenderOpts\n}\n\n// Internal wrapper around build errors at development\n// time, to prevent us from propagating or logging them\nexport class WrappedBuildError extends Error {\n  innerError: Error\n\n  constructor(innerError: Error) {\n    super()\n    this.innerError = innerError\n  }\n}\n\ntype ResponsePayload = {\n  body: RenderResult\n  cacheControl?: CacheControl\n}\n\nexport type NextEnabledDirectories = {\n  readonly pages: boolean\n  readonly app: boolean\n}\n\nexport default abstract class Server<\n  ServerOptions extends Options = Options,\n  ServerRequest extends BaseNextRequest = BaseNextRequest,\n  ServerResponse extends BaseNextResponse = BaseNextResponse,\n> {\n  public readonly hostname?: string\n  public readonly fetchHostname?: string\n  public readonly port?: number\n  protected readonly dir: string\n  protected readonly quiet: boolean\n  protected readonly nextConfig: NextConfigRuntime\n  protected readonly distDir: string\n  protected readonly publicDir: string\n  protected readonly hasStaticDir: boolean\n  protected readonly pagesManifest?: PagesManifest\n  protected readonly appPathsManifest?: PagesManifest\n  protected readonly buildId: string\n  protected readonly deploymentId: string\n  protected readonly dev: boolean\n  protected readonly minimalMode: boolean\n  protected readonly renderOpts: BaseRenderOpts\n  protected readonly serverOptions: Readonly<ServerOptions>\n  protected readonly appPathRoutes?: Record<string, string[]>\n  protected readonly clientReferenceManifest?: DeepReadonly<ClientReferenceManifest>\n  protected interceptionRoutePatterns: RegExp[]\n  protected nextFontManifest?: DeepReadonly<NextFontManifest>\n  protected instrumentation: InstrumentationModule | undefined\n\n  protected abstract getPublicDir(): string\n  protected abstract getHasStaticDir(): boolean\n  protected abstract getPagesManifest(): PagesManifest | undefined\n  protected abstract getAppPathsManifest(): PagesManifest | undefined\n  protected abstract getBuildId(): string\n  protected abstract getinterceptionRoutePatterns(): RegExp[]\n\n  protected readonly enabledDirectories: NextEnabledDirectories\n  protected abstract getEnabledDirectories(dev: boolean): NextEnabledDirectories\n\n  protected readonly experimentalTestProxy?: boolean\n\n  protected abstract findPageComponents(params: {\n    locale: string | undefined\n    page: string\n    query: NextParsedUrlQuery\n    params: Params\n    isAppPath: boolean\n    // The following parameters are used in the development server's\n    // implementation.\n    sriEnabled?: boolean\n    appPaths?: ReadonlyArray<string> | null\n    shouldEnsure?: boolean\n    url?: string\n  }): Promise<FindComponentsResult | null>\n  protected abstract getPrerenderManifest(): DeepReadonly<PrerenderManifest>\n  protected abstract getNextFontManifest():\n    | DeepReadonly<NextFontManifest>\n    | undefined\n  protected abstract attachRequestMeta(\n    req: ServerRequest,\n    parsedUrl: NextUrlWithParsedQuery\n  ): void\n  protected abstract hasPage(pathname: string): Promise<boolean>\n\n  protected abstract sendRenderResult(\n    req: ServerRequest,\n    res: ServerResponse,\n    options: {\n      result: RenderResult\n      generateEtags: boolean\n      poweredByHeader: boolean\n      cacheControl: CacheControl | undefined\n    }\n  ): Promise<void>\n\n  protected abstract runApi(\n    req: ServerRequest,\n    res: ServerResponse,\n    query: ParsedUrlQuery,\n    match: PagesAPIRouteMatch\n  ): Promise<boolean>\n\n  protected abstract renderHTML(\n    req: ServerRequest,\n    res: ServerResponse,\n    pathname: string,\n    query: NextParsedUrlQuery,\n    renderOpts: LoadedRenderOpts\n  ): Promise<RenderResult>\n\n  protected abstract getIncrementalCache(options: {\n    requestHeaders: Record<string, undefined | string | string[]>\n  }): Promise<import('./lib/incremental-cache').IncrementalCache>\n\n  protected getServerComponentsHmrCache():\n    | ServerComponentsHmrCache\n    | undefined {\n    return this.nextConfig.experimental.serverComponentsHmrCache\n      ? (globalThis as any).__serverComponentsHmrCache\n      : undefined\n  }\n\n  protected abstract loadEnvConfig(params: {\n    dev: boolean\n    forceReload: boolean\n  }): void\n\n  // TODO-APP: (wyattjoh): Make protected again. Used for turbopack in route-resolver.ts right now.\n  public readonly matchers: RouteMatcherManager\n  protected readonly i18nProvider?: I18NProvider\n  protected readonly localeNormalizer?: LocaleRouteNormalizer\n\n  protected readonly normalizers: {\n    readonly rsc: RSCPathnameNormalizer | undefined\n    readonly segmentPrefetchRSC: SegmentPrefixRSCPathnameNormalizer | undefined\n    readonly data: NextDataPathnameNormalizer | undefined\n  }\n\n  private readonly isAppPPREnabled: boolean\n\n  /**\n   * This is used to persist cache scopes across\n   * prefetch -> full route requests for cache components\n   * it's only fully used in dev\n   */\n\n  public constructor(options: ServerOptions) {\n    const {\n      dir = '.',\n      quiet = false,\n      conf,\n      dev = false,\n      minimalMode = false,\n      hostname,\n      port,\n      experimentalTestProxy,\n    } = options\n\n    this.dev = dev\n    this.experimentalTestProxy = experimentalTestProxy\n    this.serverOptions = options\n\n    this.dir = path.resolve(/* turbopackIgnore: true */ dir)\n\n    this.quiet = quiet\n    this.loadEnvConfig({ dev, forceReload: false })\n\n    // TODO: should conf be normalized to prevent missing\n    // values from causing issues as this can be user provided\n    this.nextConfig = conf as NextConfigRuntime\n\n    if (this.nextConfig.experimental.runtimeServerDeploymentId) {\n      if (!process.env.NEXT_DEPLOYMENT_ID) {\n        throw new Error(\n          'process.env.NEXT_DEPLOYMENT_ID is missing but runtimeServerDeploymentId is enabled'\n        )\n      }\n      this.deploymentId = process.env.NEXT_DEPLOYMENT_ID\n    } else {\n      let id = this.nextConfig.experimental.useSkewCookie\n        ? ''\n        : this.nextConfig.deploymentId || ''\n\n      this.deploymentId = id\n      process.env.NEXT_DEPLOYMENT_ID = id\n    }\n    ;(globalThis as any).NEXT_CLIENT_ASSET_SUFFIX =\n      this.nextConfig.experimental.immutableAssetToken || this.deploymentId\n        ? `?dpl=${this.nextConfig.experimental.immutableAssetToken || this.deploymentId}`\n        : ''\n\n    this.hostname = hostname\n    if (this.hostname) {\n      // we format the hostname so that it can be fetched\n      this.fetchHostname = formatHostname(this.hostname)\n    }\n    this.port = port\n    this.distDir = path.join(\n      /* turbopackIgnore: true */ this.dir,\n      this.nextConfig.distDir\n    )\n    this.publicDir = this.getPublicDir()\n    this.hasStaticDir = !minimalMode && this.getHasStaticDir()\n\n    this.i18nProvider = this.nextConfig.i18n?.locales\n      ? new I18NProvider(this.nextConfig.i18n)\n      : undefined\n\n    // Configure the locale normalizer, it's used for routes inside `pages/`.\n    this.localeNormalizer = this.i18nProvider\n      ? new LocaleRouteNormalizer(this.i18nProvider)\n      : undefined\n\n    const { assetPrefix, generateEtags } = this.nextConfig\n\n    this.buildId = this.getBuildId()\n    // this is a hack to avoid Webpack knowing this is equal to this.minimalMode\n    // because we replace this.minimalMode to true in production bundles.\n    const minimalModeKey = 'minimalMode'\n    this[minimalModeKey] =\n      minimalMode || !!process.env.NEXT_PRIVATE_MINIMAL_MODE\n\n    this.enabledDirectories = this.getEnabledDirectories(dev)\n\n    this.isAppPPREnabled =\n      this.enabledDirectories.app &&\n      checkIsAppPPREnabled(this.nextConfig.experimental.ppr)\n\n    this.normalizers = {\n      // We should normalize the pathname from the RSC prefix only in minimal\n      // mode as otherwise that route is not exposed external to the server as\n      // we instead only rely on the headers.\n      rsc:\n        this.enabledDirectories.app && this.minimalMode\n          ? new RSCPathnameNormalizer()\n          : undefined,\n      segmentPrefetchRSC: this.minimalMode\n        ? new SegmentPrefixRSCPathnameNormalizer()\n        : undefined,\n      data: this.enabledDirectories.pages\n        ? new NextDataPathnameNormalizer(this.buildId)\n        : undefined,\n    }\n\n    this.nextFontManifest = this.getNextFontManifest()\n\n    this.renderOpts = {\n      dir: this.dir,\n      supportsDynamicResponse: true,\n      trailingSlash: this.nextConfig.trailingSlash,\n      poweredByHeader: this.nextConfig.poweredByHeader,\n      generateEtags,\n      previewProps: this.getPrerenderManifest().preview,\n      basePath: this.nextConfig.basePath,\n      images: this.nextConfig.images,\n      optimizeCss: this.nextConfig.experimental.optimizeCss,\n      nextConfigOutput: this.nextConfig.output,\n      nextScriptWorkers: this.nextConfig.experimental.nextScriptWorkers,\n      disableOptimizedLoading:\n        this.nextConfig.experimental.disableOptimizedLoading,\n      domainLocales: this.nextConfig.i18n?.domains,\n      distDir: this.distDir,\n      serverComponents: this.enabledDirectories.app,\n      cacheLifeProfiles: this.nextConfig.cacheLife,\n      enableTainting: this.nextConfig.experimental.taint,\n      crossOrigin: this.nextConfig.crossOrigin\n        ? this.nextConfig.crossOrigin\n        : undefined,\n      largePageDataBytes: this.nextConfig.experimental.largePageDataBytes,\n\n      isExperimentalCompile: this.nextConfig.experimental.isExperimentalCompile,\n      // `htmlLimitedBots` is passed to server as serialized config in string format\n      htmlLimitedBots: this.nextConfig.htmlLimitedBots,\n      cacheComponents: this.nextConfig.cacheComponents ?? false,\n      experimental: {\n        expireTime: this.nextConfig.expireTime,\n        staleTimes: this.nextConfig.experimental.staleTimes,\n        clientTraceMetadata: this.nextConfig.experimental.clientTraceMetadata,\n        clientParamParsingOrigins:\n          this.nextConfig.experimental.clientParamParsingOrigins,\n        dynamicOnHover: this.nextConfig.experimental.dynamicOnHover ?? false,\n        optimisticRouting:\n          this.nextConfig.experimental.optimisticRouting ?? false,\n        inlineCss: this.nextConfig.experimental.inlineCss ?? false,\n        prefetchInlining:\n          this.nextConfig.experimental.prefetchInlining ?? false,\n        authInterrupts: !!this.nextConfig.experimental.authInterrupts,\n        cachedNavigations:\n          this.nextConfig.experimental.cachedNavigations ?? false,\n        maxPostponedStateSizeBytes: parseMaxPostponedStateSize(\n          this.nextConfig.experimental.maxPostponedStateSize\n        ),\n      },\n      onInstrumentationRequestError:\n        this.instrumentationOnRequestError.bind(this),\n      prefetchHints: {},\n      reactMaxHeadersLength: this.nextConfig.reactMaxHeadersLength,\n      logServerFunctions:\n        typeof this.nextConfig.logging === 'object' &&\n        Boolean(this.nextConfig.logging.serverFunctions),\n    }\n\n    this.pagesManifest = this.getPagesManifest()\n    this.appPathsManifest = this.getAppPathsManifest()\n    this.appPathRoutes = this.getAppPathRoutes()\n    this.interceptionRoutePatterns = this.getinterceptionRoutePatterns()\n\n    // Configure the routes.\n    this.matchers = this.getRouteMatchers()\n\n    // Start route compilation. We don't wait for the routes to finish loading\n    // because we use the `waitTillReady` promise below in `handleRequest` to\n    // wait. Also we can't `await` in the constructor.\n    void this.matchers.reload()\n\n    this.setAssetPrefix(assetPrefix)\n  }\n\n  protected reloadMatchers() {\n    return this.matchers.reload()\n  }\n\n  private handleRSCRequest: RouteHandler<ServerRequest, ServerResponse> = (\n    req,\n    _res,\n    parsedUrl\n  ) => {\n    if (!parsedUrl.pathname) return false\n\n    if (this.normalizers.segmentPrefetchRSC?.match(parsedUrl.pathname)) {\n      const result = this.normalizers.segmentPrefetchRSC.extract(\n        parsedUrl.pathname\n      )\n      if (!result) return false\n\n      const { originalPathname, segmentPath } = result\n      parsedUrl.pathname = originalPathname\n\n      // Mark the request as a router prefetch request.\n      req.headers[RSC_HEADER] = '1'\n      req.headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'\n      req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] = segmentPath\n\n      addRequestMeta(req, 'isRSCRequest', true)\n      addRequestMeta(req, 'isPrefetchRSCRequest', true)\n      addRequestMeta(req, 'segmentPrefetchRSCRequest', segmentPath)\n    } else if (this.normalizers.rsc?.match(parsedUrl.pathname)) {\n      parsedUrl.pathname = this.normalizers.rsc.normalize(\n        parsedUrl.pathname,\n        true\n      )\n\n      // Mark the request as a RSC request.\n      req.headers[RSC_HEADER] = '1'\n      addRequestMeta(req, 'isRSCRequest', true)\n    } else if (req.headers['x-now-route-matches']) {\n      // If we didn't match, return with the flight headers stripped. If in\n      // minimal mode we didn't match based on the path, this can't be a RSC\n      // request. This is because Vercel only sends this header during\n      // revalidation requests and we want the cache to instead depend on the\n      // request path for flight information.\n      stripFlightHeaders(req.headers)\n\n      return false\n    } else if (req.headers[RSC_HEADER] === '1') {\n      addRequestMeta(req, 'isRSCRequest', true)\n\n      if (req.headers[NEXT_ROUTER_PREFETCH_HEADER] === '1') {\n        addRequestMeta(req, 'isPrefetchRSCRequest', true)\n\n        const segmentPrefetchRSCRequest =\n          req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]\n        if (typeof segmentPrefetchRSCRequest === 'string') {\n          addRequestMeta(\n            req,\n            'segmentPrefetchRSCRequest',\n            segmentPrefetchRSCRequest\n          )\n        }\n      }\n    } else {\n      // Otherwise just return without doing anything.\n      return false\n    }\n\n    if (req.url) {\n      const parsed = parseUrl(req.url)\n      parsed.pathname = parsedUrl.pathname\n      req.url = formatUrl(parsed)\n    }\n\n    return false\n  }\n\n  private handleNextDataRequest: RouteHandler<ServerRequest, ServerResponse> =\n    async (req, res, parsedUrl) => {\n      const middleware = await this.getMiddleware()\n      const params = matchNextDataPathname(parsedUrl.pathname)\n\n      // ignore for non-next data URLs\n      if (!params || !params.path) {\n        return false\n      }\n\n      if (params.path[0] !== this.buildId) {\n        // Ignore if its a middleware request when we aren't on edge.\n        if (getRequestMeta(req, 'middlewareInvoke')) {\n          return false\n        }\n\n        // Make sure to 404 if the buildId isn't correct\n        await this.render404(req, res, parsedUrl)\n        return true\n      }\n\n      // remove buildId from URL\n      params.path.shift()\n\n      const lastParam = params.path[params.path.length - 1]\n\n      // show 404 if it doesn't end with .json\n      if (typeof lastParam !== 'string' || !lastParam.endsWith('.json')) {\n        await this.render404(req, res, parsedUrl)\n        return true\n      }\n\n      // re-create page's pathname\n      let pathname = `/${params.path.join('/')}`\n      pathname = getRouteFromAssetPath(pathname, '.json')\n\n      // ensure trailing slash is normalized per config\n      if (middleware) {\n        if (this.nextConfig.trailingSlash && !pathname.endsWith('/')) {\n          pathname += '/'\n        }\n        if (\n          !this.nextConfig.trailingSlash &&\n          pathname.length > 1 &&\n          pathname.endsWith('/')\n        ) {\n          pathname = pathname.substring(0, pathname.length - 1)\n        }\n      }\n\n      if (this.i18nProvider) {\n        // Remove the port from the hostname if present.\n        const hostname = req?.headers.host?.split(':', 1)[0].toLowerCase()\n\n        const domainLocale = this.i18nProvider.detectDomainLocale(hostname)\n        const defaultLocale =\n          domainLocale?.defaultLocale ?? this.i18nProvider.config.defaultLocale\n\n        const localePathResult = this.i18nProvider.analyze(pathname)\n\n        // If the locale is detected from the path, we need to remove it\n        // from the pathname.\n        if (localePathResult.detectedLocale) {\n          pathname = localePathResult.pathname\n        }\n\n        // Update the query with the detected locale and default locale.\n        addRequestMeta(req, 'locale', localePathResult.detectedLocale)\n        addRequestMeta(req, 'defaultLocale', defaultLocale)\n\n        // If the locale is not detected from the path, we need to mark that\n        // it was not inferred from default.\n        if (!localePathResult.detectedLocale) {\n          removeRequestMeta(req, 'localeInferredFromDefault')\n        }\n\n        // If no locale was detected and we don't have middleware, we need\n        // to render a 404 page.\n        if (!localePathResult.detectedLocale && !middleware) {\n          addRequestMeta(req, 'locale', defaultLocale)\n          await this.render404(req, res, parsedUrl)\n          return true\n        }\n      }\n\n      parsedUrl.pathname = pathname\n      addRequestMeta(req, 'isNextDataReq', true)\n\n      return false\n    }\n\n  protected handleNextImageRequest: RouteHandler<\n    ServerRequest,\n    ServerResponse\n  > = () => false\n\n  protected handleCatchallRenderRequest: RouteHandler<\n    ServerRequest,\n    ServerResponse\n  > = () => false\n\n  protected handleCatchallMiddlewareRequest: RouteHandler<\n    ServerRequest,\n    ServerResponse\n  > = () => false\n\n  protected getRouteMatchers(): RouteMatcherManager {\n    // Create a new manifest loader that get's the manifests from the server.\n    const manifestLoader = new ServerManifestLoader((name) => {\n      switch (name) {\n        case PAGES_MANIFEST:\n          return this.getPagesManifest() ?? null\n        case APP_PATHS_MANIFEST:\n          return this.getAppPathsManifest() ?? null\n        default:\n          return null\n      }\n    })\n\n    // Configure the matchers and handlers.\n    const matchers: RouteMatcherManager = new DefaultRouteMatcherManager()\n\n    // Match pages under `pages/`.\n    matchers.push(\n      new PagesRouteMatcherProvider(\n        this.distDir,\n        manifestLoader,\n        this.i18nProvider\n      )\n    )\n\n    // Match api routes under `pages/api/`.\n    matchers.push(\n      new PagesAPIRouteMatcherProvider(\n        this.distDir,\n        manifestLoader,\n        this.i18nProvider\n      )\n    )\n\n    // If the app directory is enabled, then add the app matchers and handlers.\n    if (this.enabledDirectories.app) {\n      // Match app pages under `app/`.\n      matchers.push(\n        new AppPageRouteMatcherProvider(this.distDir, manifestLoader)\n      )\n      matchers.push(\n        new AppRouteRouteMatcherProvider(this.distDir, manifestLoader)\n      )\n    }\n\n    return matchers\n  }\n\n  protected async instrumentationOnRequestError(\n    ...args: Parameters<ServerOnInstrumentationRequestError>\n  ) {\n    const [err, req, ctx] = args\n\n    if (this.instrumentation) {\n      try {\n        await this.instrumentation.onRequestError?.(\n          err,\n          {\n            path: req.url || '',\n            method: req.method || 'GET',\n            // Normalize middleware headers and other server request headers\n            headers:\n              req instanceof NextRequestHint\n                ? Object.fromEntries(req.headers.entries())\n                : req.headers,\n          },\n          ctx\n        )\n      } catch (handlerErr) {\n        // Log the soft error and continue, since errors can thrown from react stream handler\n        console.error('Error in instrumentation.onRequestError:', handlerErr)\n      }\n    }\n  }\n\n  public logError(err: unknown): void {\n    if (this.quiet) return\n    Log.error(err)\n  }\n\n  public async handleRequest(\n    req: ServerRequest,\n    res: ServerResponse,\n    parsedUrl?: NextUrlWithParsedQuery\n  ): Promise<void> {\n    await this.prepare()\n    const method = req.method.toUpperCase()\n    const tracer = getTracer()\n\n    return tracer.withPropagatedContext(req.headers, () => {\n      // Capture the parent span before creating the handleRequest span.\n      // When deployed with an adapter, the platform's runtime may create its\n      // own OTEL HTTP server span before Next.js runs. We propagate http.route\n      // to this parent span so APM tools (e.g. Datadog) can derive the\n      // resource name correctly.\n      const parentSpan = tracer.getActiveScopeSpan()\n\n      return tracer.trace(\n        BaseServerSpan.handleRequest,\n        {\n          spanName: `${method}`,\n          kind: SpanKind.SERVER,\n          attributes: {\n            'http.method': method,\n            'http.target': req.url,\n          },\n        },\n        async (span) =>\n          this.handleRequestImpl(req, res, parsedUrl).finally(() => {\n            if (!span) return\n\n            const isRSCRequest = getRequestMeta(req, 'isRSCRequest') ?? false\n            span.setAttributes({\n              'http.status_code': res.statusCode,\n              'next.rsc': isRSCRequest,\n            })\n\n            if (res.statusCode && res.statusCode >= 500) {\n              // For 5xx status codes: SHOULD be set to 'Error' span status.\n              // x-ref: https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status\n              span.setStatus({\n                code: SpanStatusCode.ERROR,\n              })\n              // For span status 'Error', SHOULD set 'error.type' attribute.\n              span.setAttribute('error.type', res.statusCode.toString())\n            }\n\n            const rootSpanAttributes = tracer.getRootSpanAttributes()\n            // We were unable to get attributes, probably OTEL is not enabled\n            if (!rootSpanAttributes) return\n\n            if (\n              rootSpanAttributes.get('next.span_type') !==\n              BaseServerSpan.handleRequest\n            ) {\n              console.warn(\n                `Unexpected root span type '${rootSpanAttributes.get(\n                  'next.span_type'\n                )}'. Please report this Next.js issue https://github.com/vercel/next.js`\n              )\n              return\n            }\n\n            const route = rootSpanAttributes.get('next.route')\n            if (route) {\n              const name = isRSCRequest\n                ? `RSC ${method} ${route}`\n                : `${method} ${route}`\n\n              span.setAttributes({\n                'next.route': route,\n                'http.route': route,\n                'next.span_name': name,\n              })\n              span.updateName(name)\n\n              // Propagate http.route to the parent span if one exists and\n              // is different from the handleRequest span. This ensures APM\n              // tools that read attributes from the outermost span (e.g.\n              // a platform-created HTTP span) can derive the resource name.\n              if (parentSpan && parentSpan !== span) {\n                parentSpan.setAttribute('http.route', route)\n              }\n            } else {\n              span.updateName(isRSCRequest ? `RSC ${method}` : `${method}`)\n            }\n          })\n      )\n    })\n  }\n\n  private async handleRequestImpl(\n    req: ServerRequest,\n    res: ServerResponse,\n    parsedUrl?: NextUrlWithParsedQuery\n  ): Promise<void> {\n    try {\n      // Wait for the matchers to be ready.\n      await this.matchers.waitTillReady()\n\n      // ensure cookies set in middleware are merged and\n      // not overridden by API routes/getServerSideProps\n      patchSetHeaderWithCookieSupport(\n        req,\n        isNodeNextResponse(res) ? res.originalResponse : res\n      )\n\n      const urlParts = (req.url || '').split('?', 1)\n      const urlNoQuery = urlParts[0]\n\n      // this normalizes repeated slashes in the path e.g. hello//world ->\n      // hello/world or backslashes to forward slashes, this does not\n      // handle trailing slash as that is handled the same as a next.config.js\n      // redirect\n      if (urlNoQuery?.match(/(\\\\|\\/\\/)/)) {\n        const cleanUrl = normalizeRepeatedSlashes(req.url!)\n        res.redirect(cleanUrl, 308).body(cleanUrl).send()\n        return\n      }\n\n      // Parse url if parsedUrl not provided\n      if (!parsedUrl || typeof parsedUrl !== 'object') {\n        if (!req.url) {\n          throw new Error('Invariant: url can not be undefined')\n        }\n\n        parsedUrl = parseUrl(req.url)\n      }\n\n      if (!parsedUrl.pathname) {\n        throw new Error(\"Invariant: pathname can't be empty\")\n      }\n\n      // Parse the querystring ourselves if the user doesn't handle querystring parsing\n      if (typeof parsedUrl.query === 'string') {\n        parsedUrl.query = Object.fromEntries(\n          new URLSearchParams(parsedUrl.query)\n        )\n      }\n\n      // Update the `x-forwarded-*` headers.\n      const { originalRequest = null } = isNodeNextRequest(req) ? req : {}\n      const xForwardedProto = originalRequest?.headers['x-forwarded-proto']\n      const isHttps = xForwardedProto\n        ? xForwardedProto === 'https'\n        : !!(originalRequest?.socket as TLSSocket)?.encrypted\n\n      req.headers['x-forwarded-host'] ??= req.headers['host'] ?? this.hostname\n      req.headers['x-forwarded-port'] ??= this.port\n        ? this.port.toString()\n        : isHttps\n          ? '443'\n          : '80'\n      req.headers['x-forwarded-proto'] ??= isHttps ? 'https' : 'http'\n      req.headers['x-forwarded-for'] ??= originalRequest?.socket?.remoteAddress\n\n      // This should be done before any normalization of the pathname happens as\n      // it captures the initial URL.\n      this.attachRequestMeta(req, parsedUrl)\n\n      let finished = await this.handleRSCRequest(req, res, parsedUrl)\n      if (finished) return\n\n      const domainLocale = this.i18nProvider?.detectDomainLocale(\n        getHostname(parsedUrl, req.headers)\n      )\n\n      const defaultLocale =\n        domainLocale?.defaultLocale || this.nextConfig.i18n?.defaultLocale\n      addRequestMeta(req, 'defaultLocale', defaultLocale)\n\n      const url = parseUrlUtil(req.url.replace(/^\\/+/, '/'))\n      const pathnameInfo = getNextPathnameInfo(url.pathname, {\n        nextConfig: this.nextConfig,\n        i18nProvider: this.i18nProvider,\n      })\n      url.pathname = pathnameInfo.pathname\n\n      if (pathnameInfo.basePath) {\n        req.url = removePathPrefix(req.url!, this.nextConfig.basePath)\n      }\n\n      const useMatchedPathHeader =\n        this.minimalMode && typeof req.headers[MATCHED_PATH_HEADER] === 'string'\n\n      // TODO: merge handling with invokePath\n      if (useMatchedPathHeader) {\n        try {\n          if (this.enabledDirectories.app) {\n            // ensure /index path is normalized for prerender\n            // in minimal mode\n            if (req.url.match(/^\\/index($|\\?)/)) {\n              req.url = req.url.replace(/^\\/index/, '/')\n            }\n            parsedUrl.pathname =\n              parsedUrl.pathname === '/index' ? '/' : parsedUrl.pathname\n          }\n\n          // x-matched-path is the source of truth, it tells what page\n          // should be rendered because we don't process rewrites in minimalMode\n          let { pathname: matchedPath } = new URL(\n            fixMojibake(req.headers[MATCHED_PATH_HEADER] as string),\n            'http://localhost'\n          )\n\n          let { pathname: urlPathname } = new URL(req.url, 'http://localhost')\n\n          // For ISR the URL is normalized to the prerenderPath so if\n          // it's a data request the URL path will be the data URL,\n          // basePath is already stripped by this point\n          if (this.normalizers.data?.match(urlPathname)) {\n            addRequestMeta(req, 'isNextDataReq', true)\n          }\n\n          // It's important to execute the following block even it the request\n          // matches a pages data route from above.\n          if (\n            this.isAppPPREnabled &&\n            this.minimalMode &&\n            req.headers[NEXT_RESUME_HEADER] === '1' &&\n            req.method === 'POST'\n          ) {\n            const { maxPostponedStateSize, maxPostponedStateSizeBytes } =\n              getMaxPostponedStateSize(\n                this.nextConfig.experimental.maxPostponedStateSize\n              )\n\n            // Decode the postponed state from the request body, it will come as\n            // an array of buffers, so collect them and then concat them to form\n            // the string.\n            const body = await readBodyWithSizeLimit(\n              req.body,\n              maxPostponedStateSizeBytes\n            )\n            if (body === null) {\n              res.statusCode = 413\n              res\n                .body(\n                  getPostponedStateExceededErrorMessage(maxPostponedStateSize)\n                )\n                .send()\n              return\n            }\n            const postponed = body.toString('utf8')\n\n            addRequestMeta(req, 'postponed', postponed)\n          }\n\n          // If the request is a next data request and it has a postponed state,\n          // we should error, as it represents an unprocessable request.\n          if (\n            getRequestMeta(req, 'isNextDataReq') &&\n            getRequestMeta(req, 'postponed')\n          ) {\n            // The server understood that this is a PPR resume request, as the\n            // headers were included to correctly indicate a resume request, but\n            // because the request URL indicates that this should render a next\n            // data route (a pages router route), this represents an\n            // unprocessable request.\n            res.statusCode = 422\n            res.send()\n            return\n          }\n\n          matchedPath = this.normalize(matchedPath)\n          const normalizedUrlPath = this.stripNextDataPath(urlPathname)\n\n          matchedPath = denormalizePagePath(matchedPath)\n\n          // Perform locale detection and normalization.\n          const localeAnalysisResult = this.i18nProvider?.analyze(matchedPath, {\n            defaultLocale,\n          })\n\n          // The locale result will be defined even if the locale was not\n          // detected for the request because it will be inferred from the\n          // default locale.\n          if (localeAnalysisResult) {\n            addRequestMeta(req, 'locale', localeAnalysisResult.detectedLocale)\n\n            // If the detected locale was inferred from the default locale, we\n            // need to modify the metadata on the request to indicate that.\n            if (localeAnalysisResult.inferredFromDefault) {\n              addRequestMeta(req, 'localeInferredFromDefault', true)\n            } else {\n              removeRequestMeta(req, 'localeInferredFromDefault')\n            }\n          }\n\n          let srcPathname = matchedPath\n          let pageIsDynamic = isDynamicRoute(srcPathname)\n          let paramsResult: {\n            params: ParsedUrlQuery | false\n            hasValidParams: boolean\n          } = {\n            params: false,\n            hasValidParams: false,\n          }\n\n          const match = await this.matchers.match(srcPathname, {\n            i18n: localeAnalysisResult,\n          })\n\n          if (!pageIsDynamic && match) {\n            // Update the source pathname to the matched page's pathname.\n            srcPathname = match.definition.pathname\n\n            // The page is dynamic if the params are defined. We know at this\n            // stage that the matched path is not a static page if the params\n            // were parsed from the matched path header.\n            if (typeof match.params !== 'undefined') {\n              pageIsDynamic = true\n              paramsResult.params = match.params\n              paramsResult.hasValidParams = true\n            }\n          }\n\n          // The rest of this function can't handle i18n properly, so ensure we\n          // restore the pathname with the locale information stripped from it\n          // now that we're done matching if we're using i18n.\n          if (localeAnalysisResult) {\n            matchedPath = localeAnalysisResult.pathname\n          }\n\n          const utils = getServerUtils({\n            pageIsDynamic,\n            page: srcPathname,\n            i18n: this.nextConfig.i18n,\n            basePath: this.nextConfig.basePath,\n            rewrites: this.getRoutesManifest()?.rewrites || {\n              beforeFiles: [],\n              afterFiles: [],\n              fallback: [],\n            },\n            caseSensitive: !!this.nextConfig.experimental.caseSensitiveRoutes,\n          })\n\n          // Ensure parsedUrl.pathname includes locale before processing\n          // rewrites or they won't match correctly.\n          if (defaultLocale && !pathnameInfo.locale) {\n            parsedUrl.pathname = `/${defaultLocale}${parsedUrl.pathname}`\n          }\n\n          // Store a copy of `parsedUrl.query` before calling handleRewrites.\n          // Since `handleRewrites` might add new queries to `parsedUrl.query`.\n          const originQueryParams = { ...parsedUrl.query }\n\n          const pathnameBeforeRewrite = parsedUrl.pathname\n          const { rewriteParams, rewrittenParsedUrl } = utils.handleRewrites(\n            req,\n            parsedUrl\n          )\n          const rewriteParamKeys = Object.keys(rewriteParams)\n\n          // Create a copy of the query params to avoid mutating the original\n          // object. This prevents any overlapping query params that have the\n          // same normalized key from causing issues.\n          const rewrittenQueryParams = { ...rewrittenParsedUrl.query }\n          const didRewrite =\n            pathnameBeforeRewrite !== rewrittenParsedUrl.pathname\n\n          if (didRewrite && rewrittenParsedUrl.pathname) {\n            addRequestMeta(\n              req,\n              'rewrittenPathname',\n              rewrittenParsedUrl.pathname\n            )\n          }\n\n          const routeParamKeys = new Set<string>()\n          for (const [key, value] of Object.entries(parsedUrl.query)) {\n            const normalizedKey = normalizeNextQueryParam(key)\n            if (!normalizedKey) continue\n\n            // Remove the prefixed key from the query params because we want\n            // to consume it for the dynamic route matcher.\n            delete parsedUrl.query[key]\n            routeParamKeys.add(normalizedKey)\n\n            if (typeof value === 'undefined') continue\n\n            rewrittenQueryParams[normalizedKey] = Array.isArray(value)\n              ? value.map((v) => decodeQueryPathParameter(v))\n              : decodeQueryPathParameter(value)\n          }\n\n          // interpolate dynamic params and normalize URL if needed\n          if (pageIsDynamic) {\n            let params: ParsedUrlQuery | false = {}\n\n            // If we don't already have valid params, try to parse them from\n            // the query params.\n            if (!paramsResult.hasValidParams) {\n              paramsResult = utils.normalizeDynamicRouteParams(\n                rewrittenQueryParams,\n                false\n              )\n            }\n\n            // for prerendered ISR paths we attempt parsing the route\n            // params from the URL directly as route-matches may not\n            // contain the correct values due to the filesystem path\n            // matching before the dynamic route has been matched\n            if (\n              !paramsResult.hasValidParams &&\n              !isDynamicRoute(normalizedUrlPath)\n            ) {\n              let matcherParams = utils.dynamicRouteMatcher?.(normalizedUrlPath)\n\n              if (matcherParams) {\n                utils.normalizeDynamicRouteParams(matcherParams, false)\n                Object.assign(paramsResult.params, matcherParams)\n                paramsResult.hasValidParams = true\n              }\n            }\n\n            // if an action request is bypassing a prerender and we\n            // don't have the params in the URL since it was prerendered\n            // and matched during handle: 'filesystem' rather than dynamic route\n            // resolving we need to parse the params from the matched-path.\n            // Note: this is similar to above case but from match-path instead\n            // of from the request URL since a rewrite could cause that to not\n            // match the src pathname\n            if (\n              // we can have a collision with /index and a top-level /[slug]\n              matchedPath !== '/index' &&\n              !paramsResult.hasValidParams &&\n              !isDynamicRoute(matchedPath)\n            ) {\n              let matcherParams = utils.dynamicRouteMatcher?.(matchedPath)\n\n              if (matcherParams) {\n                const curParamsResult = utils.normalizeDynamicRouteParams(\n                  matcherParams,\n                  false\n                )\n\n                if (curParamsResult.hasValidParams) {\n                  Object.assign(params, matcherParams)\n                  paramsResult = curParamsResult\n                }\n              }\n            }\n\n            if (paramsResult.hasValidParams) {\n              params = paramsResult.params\n            }\n\n            const routeMatchesHeader = req.headers['x-now-route-matches']\n            if (\n              typeof routeMatchesHeader === 'string' &&\n              routeMatchesHeader &&\n              isDynamicRoute(matchedPath) &&\n              !paramsResult.hasValidParams\n            ) {\n              const routeMatches =\n                utils.getParamsFromRouteMatches(routeMatchesHeader)\n\n              if (routeMatches) {\n                paramsResult = utils.normalizeDynamicRouteParams(\n                  routeMatches,\n                  true\n                )\n\n                if (paramsResult.hasValidParams) {\n                  params = paramsResult.params\n                }\n              }\n            }\n\n            // Try to parse the params from the query if we couldn't parse them\n            // from the route matches but ignore missing optional params.\n            if (!paramsResult.hasValidParams) {\n              paramsResult = utils.normalizeDynamicRouteParams(\n                rewrittenQueryParams,\n                true\n              )\n\n              if (paramsResult.hasValidParams) {\n                params = paramsResult.params\n              }\n            }\n\n            // If the pathname being requested is the same as the source\n            // pathname, and we don't have valid params, we want to use the\n            // default route matches.\n            if (\n              utils.defaultRouteMatches &&\n              normalizedUrlPath === srcPathname &&\n              !paramsResult.hasValidParams\n            ) {\n              params = utils.defaultRouteMatches\n\n              // If the route matches header is an empty string, we want to\n              // render a fallback shell. This is because we know this came from\n              // a prerender (it has the header) but it's values were filtered\n              // out (because the allowQuery was empty). If it was undefined\n              // then we know that the request is hitting the lambda directly.\n              if (routeMatchesHeader === '') {\n                addRequestMeta(req, 'renderFallbackShell', true)\n              }\n            }\n\n            if (params) {\n              matchedPath = utils.interpolateDynamicPath(srcPathname, params)\n              req.url = utils.interpolateDynamicPath(req.url!, params)\n\n              // If the request is for a segment prefetch, we need to update the\n              // segment prefetch request path to include the interpolated\n              // params.\n              let segmentPrefetchRSCRequest = getRequestMeta(\n                req,\n                'segmentPrefetchRSCRequest'\n              )\n              if (\n                segmentPrefetchRSCRequest &&\n                isDynamicRoute(segmentPrefetchRSCRequest, false)\n              ) {\n                segmentPrefetchRSCRequest = utils.interpolateDynamicPath(\n                  segmentPrefetchRSCRequest,\n                  params\n                )\n\n                req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] =\n                  segmentPrefetchRSCRequest\n                addRequestMeta(\n                  req,\n                  'segmentPrefetchRSCRequest',\n                  segmentPrefetchRSCRequest\n                )\n              }\n            }\n          }\n\n          if (pageIsDynamic || didRewrite) {\n            utils.normalizeCdnUrl(req, [\n              ...rewriteParamKeys,\n              ...Object.keys(utils.defaultRouteRegex?.groups || {}),\n            ])\n          }\n\n          // Remove the route `params` keys from `parsedUrl.query` if they are\n          // not in the original query params.\n          // If it's used in both route `params` and query `searchParams`, it should be kept.\n          for (const key of routeParamKeys) {\n            if (!(key in originQueryParams)) {\n              delete parsedUrl.query[key]\n            }\n          }\n\n          parsedUrl.pathname = matchedPath\n          url.pathname = parsedUrl.pathname\n\n          // For Pages Router routes, use the normalized queryParams from\n          // handleRewrites to ensure catch-all routes get proper array values.\n          // App Router routes should not include rewrite query params as they\n          // affect RSC payload.\n          if (\n            match?.definition.kind === RouteKind.PAGES ||\n            match?.definition.kind === RouteKind.PAGES_API\n          ) {\n            parsedUrl.query = rewrittenQueryParams\n          }\n\n          finished = await this.normalizeAndAttachMetadata(req, res, parsedUrl)\n          if (finished) return\n        } catch (err) {\n          if (err instanceof DecodeError || err instanceof NormalizeError) {\n            res.statusCode = 400\n            return this.renderError(null, req, res, '/_error', {})\n          }\n          throw err\n        }\n      }\n\n      addRequestMeta(req, 'isLocaleDomain', Boolean(domainLocale))\n\n      if (pathnameInfo.locale) {\n        req.url = formatUrl(url)\n        addRequestMeta(req, 'didStripLocale', true)\n      }\n\n      // If we aren't in minimal mode or there is no locale in the query\n      // string, add the locale to the query string.\n      if (!this.minimalMode || !getRequestMeta(req, 'locale')) {\n        // If the locale is in the pathname, add it to the query string.\n        if (pathnameInfo.locale) {\n          addRequestMeta(req, 'locale', pathnameInfo.locale)\n        }\n        // If the default locale is available, add it to the query string and\n        // mark it as inferred rather than implicit.\n        else if (defaultLocale) {\n          addRequestMeta(req, 'locale', defaultLocale)\n          addRequestMeta(req, 'localeInferredFromDefault', true)\n        }\n      }\n\n      // set incremental cache to request meta so it can\n      // be passed down for edge functions and the fetch disk\n      // cache can be leveraged locally\n      if (\n        !(this.serverOptions as any).webServerConfig &&\n        !getRequestMeta(req, 'incrementalCache')\n      ) {\n        const incrementalCache = await this.getIncrementalCache({\n          requestHeaders: Object.assign({}, req.headers),\n        })\n\n        incrementalCache.resetRequestCache()\n        addRequestMeta(req, 'incrementalCache', incrementalCache)\n        // This is needed for pages router to leverage unstable_cache\n        // TODO: re-work this handling to not use global and use a AsyncStore\n        ;(globalThis as any).__incrementalCache = incrementalCache\n      }\n\n      // set server components HMR cache to request meta so it can be passed\n      // down for edge functions\n      if (!getRequestMeta(req, 'serverComponentsHmrCache')) {\n        addRequestMeta(\n          req,\n          'serverComponentsHmrCache',\n          this.getServerComponentsHmrCache()\n        )\n      }\n\n      // when invokePath is specified we can short short circuit resolving\n      // we only honor this header if we are inside of a render worker to\n      // prevent external users coercing the routing path\n      const invokePath = getRequestMeta(req, 'invokePath')\n      const useInvokePath = !useMatchedPathHeader && invokePath\n\n      if (useInvokePath) {\n        const invokeStatus = getRequestMeta(req, 'invokeStatus')\n        if (invokeStatus) {\n          const invokeQuery = getRequestMeta(req, 'invokeQuery')\n\n          if (invokeQuery) {\n            Object.assign(parsedUrl.query, invokeQuery)\n          }\n\n          res.statusCode = invokeStatus\n          let err: Error | null = getRequestMeta(req, 'invokeError') || null\n\n          return this.renderError(err, req, res, '/_error', parsedUrl.query)\n        }\n\n        const parsedMatchedPath = new URL(invokePath || '/', 'http://n')\n        const invokePathnameInfo = getNextPathnameInfo(\n          parsedMatchedPath.pathname,\n          {\n            nextConfig: this.nextConfig,\n            parseData: false,\n          }\n        )\n\n        if (invokePathnameInfo.locale) {\n          addRequestMeta(req, 'locale', invokePathnameInfo.locale)\n        }\n\n        if (parsedUrl.pathname !== parsedMatchedPath.pathname) {\n          parsedUrl.pathname = parsedMatchedPath.pathname\n          addRequestMeta(req, 'rewrittenPathname', invokePathnameInfo.pathname)\n        }\n        const normalizeResult = normalizeLocalePath(\n          removePathPrefix(parsedUrl.pathname, this.nextConfig.basePath || ''),\n          this.nextConfig.i18n?.locales\n        )\n\n        if (normalizeResult.detectedLocale) {\n          addRequestMeta(req, 'locale', normalizeResult.detectedLocale)\n        }\n        parsedUrl.pathname = normalizeResult.pathname\n\n        for (const key of Object.keys(parsedUrl.query)) {\n          delete parsedUrl.query[key]\n        }\n        const invokeQuery = getRequestMeta(req, 'invokeQuery')\n\n        if (invokeQuery) {\n          Object.assign(parsedUrl.query, invokeQuery)\n        }\n\n        finished = await this.normalizeAndAttachMetadata(req, res, parsedUrl)\n        if (finished) return\n\n        await this.handleCatchallRenderRequest(req, res, parsedUrl)\n        return\n      }\n\n      if (getRequestMeta(req, 'middlewareInvoke')) {\n        finished = await this.normalizeAndAttachMetadata(req, res, parsedUrl)\n        if (finished) return\n\n        finished = await this.handleCatchallMiddlewareRequest(\n          req,\n          res,\n          parsedUrl\n        )\n        if (finished) return\n\n        const err = new Error()\n        ;(err as any).result = {\n          response: new Response(null, {\n            headers: {\n              'x-middleware-next': '1',\n            },\n          }),\n        }\n        ;(err as any).bubble = true\n        throw err\n      }\n\n      // This wasn't a request via the matched path or the invoke path, so\n      // prepare for a legacy run by removing the base path.\n\n      // ensure we strip the basePath when not using an invoke header\n      if (!useMatchedPathHeader && pathnameInfo.basePath) {\n        parsedUrl.pathname = removePathPrefix(\n          parsedUrl.pathname,\n          pathnameInfo.basePath\n        )\n      }\n\n      res.statusCode = 200\n      return await this.run(req, res, parsedUrl)\n    } catch (err: any) {\n      if (err instanceof NoFallbackError) {\n        throw err\n      }\n\n      if (\n        (err && typeof err === 'object' && err.code === 'ERR_INVALID_URL') ||\n        err instanceof DecodeError ||\n        err instanceof NormalizeError\n      ) {\n        res.statusCode = 400\n        return this.renderError(null, req, res, '/_error', {})\n      }\n\n      if (this.minimalMode || this.dev || (isBubbledError(err) && err.bubble)) {\n        throw err\n      }\n      this.logError(getProperError(err))\n      res.statusCode = 500\n      res.body('Internal Server Error').send()\n    }\n  }\n\n  /**\n   * Normalizes a pathname without attaching any metadata from any matched\n   * normalizer.\n   *\n   * @param pathname the pathname to normalize\n   * @returns the normalized pathname\n   */\n  private normalize = (pathname: string) => {\n    const normalizers: Array<PathnameNormalizer> = []\n\n    if (this.normalizers.data) {\n      normalizers.push(this.normalizers.data)\n    }\n\n    // We have to put the segment prefetch normalizer before the RSC normalizer\n    // because the RSC normalizer will match the prefetch RSC routes too.\n    if (this.normalizers.segmentPrefetchRSC) {\n      normalizers.push(this.normalizers.segmentPrefetchRSC)\n    }\n\n    if (this.normalizers.rsc) {\n      normalizers.push(this.normalizers.rsc)\n    }\n\n    for (const normalizer of normalizers) {\n      if (!normalizer.match(pathname)) continue\n\n      return normalizer.normalize(pathname, true)\n    }\n\n    return pathname\n  }\n\n  private normalizeAndAttachMetadata: RouteHandler<\n    ServerRequest,\n    ServerResponse\n  > = async (req, res, url) => {\n    let finished = await this.handleNextImageRequest(req, res, url)\n    if (finished) return true\n\n    if (this.enabledDirectories.pages) {\n      finished = await this.handleNextDataRequest(req, res, url)\n      if (finished) return true\n    }\n\n    return false\n  }\n\n  /**\n   * @internal - this method is internal to Next.js and should not be used directly by end-users\n   */\n  public getRequestHandlerWithMetadata(\n    meta: RequestMeta\n  ): BaseRequestHandler<ServerRequest, ServerResponse> {\n    const handler = this.getRequestHandler()\n    return (req, res, parsedUrl) => {\n      setRequestMeta(req, meta)\n      return handler(req, res, parsedUrl)\n    }\n  }\n\n  public getRequestHandler(): BaseRequestHandler<\n    ServerRequest,\n    ServerResponse\n  > {\n    return this.handleRequest.bind(this)\n  }\n\n  protected abstract handleUpgrade(\n    req: ServerRequest,\n    socket: any,\n    head?: any\n  ): Promise<void>\n\n  public setAssetPrefix(prefix?: string): void {\n    this.nextConfig.assetPrefix = prefix ? prefix.replace(/\\/$/, '') : ''\n  }\n\n  protected prepared: boolean = false\n  protected preparedPromise: Promise<void> | null = null\n  /**\n   * Runs async initialization of server.\n   * It is idempotent, won't fire underlying initialization more than once.\n   */\n  public async prepare(): Promise<void> {\n    if (this.prepared) return\n\n    // Get instrumentation module\n    if (!this.instrumentation) {\n      this.instrumentation = await this.loadInstrumentationModule()\n    }\n    if (this.preparedPromise === null) {\n      this.preparedPromise = this.prepareImpl().then(() => {\n        this.prepared = true\n        this.preparedPromise = null\n      })\n    }\n    return this.preparedPromise\n  }\n  protected async prepareImpl(): Promise<void> {}\n  protected async loadInstrumentationModule(): Promise<any> {}\n\n  public async close(): Promise<void> {}\n\n  protected getAppPathRoutes(): Record<string, string[]> {\n    const appPathRoutes: Record<string, string[]> = {}\n\n    Object.keys(this.appPathsManifest || {}).forEach((entry) => {\n      const normalizedPath = normalizeAppPath(entry)\n      if (!appPathRoutes[normalizedPath]) {\n        appPathRoutes[normalizedPath] = []\n      }\n      appPathRoutes[normalizedPath].push(entry)\n    })\n    return appPathRoutes\n  }\n\n  protected async run(\n    req: ServerRequest,\n    res: ServerResponse,\n    parsedUrl: NextUrlWithParsedQuery\n  ): Promise<void> {\n    return getTracer().trace(BaseServerSpan.run, async () =>\n      this.runImpl(req, res, parsedUrl)\n    )\n  }\n\n  private async runImpl(\n    req: ServerRequest,\n    res: ServerResponse,\n    parsedUrl: NextUrlWithParsedQuery\n  ): Promise<void> {\n    await this.handleCatchallRenderRequest(req, res, parsedUrl)\n  }\n\n  private async pipe(\n    fn: (\n      ctx: RequestContext<ServerRequest, ServerResponse>\n    ) => Promise<ResponsePayload | null>,\n    partialContext: Omit<\n      RequestContext<ServerRequest, ServerResponse>,\n      'renderOpts'\n    >\n  ): Promise<void> {\n    return getTracer().trace(BaseServerSpan.pipe, async () =>\n      this.pipeImpl(fn, partialContext)\n    )\n  }\n\n  private async pipeImpl(\n    fn: (\n      ctx: RequestContext<ServerRequest, ServerResponse>\n    ) => Promise<ResponsePayload | null>,\n    partialContext: Omit<\n      RequestContext<ServerRequest, ServerResponse>,\n      'renderOpts'\n    >\n  ): Promise<void> {\n    const ua = partialContext.req.headers['user-agent'] || ''\n\n    const ctx: RequestContext<ServerRequest, ServerResponse> = {\n      ...partialContext,\n      renderOpts: {\n        ...this.renderOpts,\n        // `renderOpts.botType` is accumulated in `this.renderImpl()`\n        supportsDynamicResponse: !this.renderOpts.botType,\n        serveStreamingMetadata: shouldServeStreamingMetadata(\n          ua,\n          this.nextConfig.htmlLimitedBots\n        ),\n      },\n    }\n\n    const payload = await fn(ctx)\n    if (payload === null) {\n      return\n    }\n    const { req, res } = ctx\n    const originalStatus = res.statusCode\n    const { body } = payload\n    let { cacheControl } = payload\n    if (!res.sent) {\n      const { generateEtags, poweredByHeader } = this.renderOpts\n\n      // In dev, we should not cache pages for any reason.\n      if (this.dev) {\n        res.setHeader('Cache-Control', 'no-cache, must-revalidate')\n        cacheControl = undefined\n      }\n\n      if (cacheControl && cacheControl.expire === undefined) {\n        cacheControl.expire = this.nextConfig.expireTime\n      }\n\n      await this.sendRenderResult(req, res, {\n        result: body,\n        generateEtags,\n        poweredByHeader,\n        cacheControl,\n      })\n      res.statusCode = originalStatus\n    }\n  }\n\n  private async getStaticHTML(\n    fn: (\n      ctx: RequestContext<ServerRequest, ServerResponse>\n    ) => Promise<ResponsePayload | null>,\n    partialContext: Omit<\n      RequestContext<ServerRequest, ServerResponse>,\n      'renderOpts'\n    >\n  ): Promise<string | null> {\n    const ctx: RequestContext<ServerRequest, ServerResponse> = {\n      ...partialContext,\n      renderOpts: {\n        ...this.renderOpts,\n        supportsDynamicResponse: false,\n      },\n    }\n    const payload = await fn(ctx)\n    if (payload === null) {\n      return null\n    }\n    return payload.body.toUnchunkedString()\n  }\n\n  public async render(\n    req: ServerRequest,\n    res: ServerResponse,\n    pathname: string,\n    query: NextParsedUrlQuery = {},\n    parsedUrl?: NextUrlWithParsedQuery,\n    internalRender = false\n  ): Promise<void> {\n    return getTracer().trace(BaseServerSpan.render, async () =>\n      this.renderImpl(req, res, pathname, query, parsedUrl, internalRender)\n    )\n  }\n\n  protected getWaitUntil(): WaitUntil | undefined {\n    const builtinRequestContext = getBuiltinRequestContext()\n    if (builtinRequestContext) {\n      // the platform provided a request context.\n      // use the `waitUntil` from there, whether actually present or not --\n      // if not present, `after` will error.\n\n      // NOTE: if we're in an edge runtime sandbox, this context will be used to forward the outer waitUntil.\n      return builtinRequestContext.waitUntil\n    }\n\n    if (this.minimalMode) {\n      // we're built for a serverless environment, and `waitUntil` is not available,\n      // but using a noop would likely lead to incorrect behavior,\n      // because we have no way of keeping the invocation alive.\n      // return nothing, and `after` will error if used.\n      //\n      // NOTE: for edge functions, `NextWebServer` always runs in minimal mode.\n      //\n      // NOTE: if we're in an edge runtime sandbox, waitUntil will be passed in using \"@next/request-context\",\n      // so we won't get here.\n      return undefined\n    }\n\n    return this.getInternalWaitUntil()\n  }\n\n  protected getInternalWaitUntil(): WaitUntil | undefined {\n    return undefined\n  }\n\n  private async renderImpl(\n    req: ServerRequest,\n    res: ServerResponse,\n    pathname: string,\n    query: NextParsedUrlQuery = {},\n    parsedUrl?: NextUrlWithParsedQuery,\n    internalRender = false\n  ): Promise<void> {\n    if (!pathname.startsWith('/')) {\n      console.warn(\n        `Cannot render page with path \"${pathname}\", did you mean \"/${pathname}\"?. See more info here: https://nextjs.org/docs/messages/render-no-starting-slash`\n      )\n    }\n\n    if (\n      this.serverOptions.customServer &&\n      pathname === '/index' &&\n      !(await this.hasPage('/index'))\n    ) {\n      // maintain backwards compatibility for custom server\n      // (see custom-server integration tests)\n      pathname = '/'\n    }\n\n    const ua = req.headers['user-agent'] || ''\n    this.renderOpts.botType = getBotType(ua)\n\n    // we allow custom servers to call render for all URLs\n    // so check if we need to serve a static _next file or not.\n    // we don't modify the URL for _next/data request but still\n    // call render so we special case this to prevent an infinite loop\n    if (\n      !internalRender &&\n      !this.minimalMode &&\n      !getRequestMeta(req, 'isNextDataReq') &&\n      (req.url?.match(/^\\/_next\\//) ||\n        (this.hasStaticDir && req.url!.match(/^\\/static\\//)))\n    ) {\n      return this.handleRequest(req, res, parsedUrl)\n    }\n\n    if (isBlockedPage(pathname)) {\n      return this.render404(req, res, parsedUrl)\n    }\n\n    return this.pipe((ctx) => this.renderToResponse(ctx), {\n      req,\n      res,\n      pathname,\n      query,\n    })\n  }\n\n  protected async getStaticPaths({\n    pathname,\n  }: {\n    pathname: string\n    urlPathname: string\n    requestHeaders: import('./lib/incremental-cache').IncrementalCache['requestHeaders']\n    page: string\n    isAppPath: boolean\n  }): Promise<{\n    staticPaths?: string[]\n    prerenderedRoutes?: PrerenderedRoute[]\n    fallbackMode?: FallbackMode\n  }> {\n    // Read whether or not fallback should exist from the manifest.\n    const fallbackField =\n      this.getPrerenderManifest().dynamicRoutes[pathname]?.fallback\n\n    return {\n      // `staticPaths` is intentionally set to `undefined` as it should've\n      // been caught when checking disk data.\n      staticPaths: undefined,\n      fallbackMode: parseFallbackField(fallbackField),\n    }\n  }\n\n  private async renderToResponseWithComponents(\n    requestContext: RequestContext<ServerRequest, ServerResponse>,\n    findComponentsResult: FindComponentsResult\n  ): Promise<ResponsePayload | null> {\n    return getTracer().trace(\n      BaseServerSpan.renderToResponseWithComponents,\n      async () =>\n        this.renderToResponseWithComponentsImpl(\n          requestContext,\n          findComponentsResult\n        )\n    )\n  }\n\n  protected pathCouldBeIntercepted(resolvedPathname: string): boolean {\n    return (\n      isInterceptionRouteAppPath(resolvedPathname) ||\n      this.interceptionRoutePatterns.some((regexp) => {\n        return regexp.test(resolvedPathname)\n      })\n    )\n  }\n\n  protected setVaryHeader(\n    req: ServerRequest,\n    res: ServerResponse,\n    isAppPath: boolean,\n    resolvedPathname: string\n  ): void {\n    const baseVaryHeader = `${RSC_HEADER}, ${NEXT_ROUTER_STATE_TREE_HEADER}, ${NEXT_ROUTER_PREFETCH_HEADER}, ${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}`\n    const isRSCRequest = getRequestMeta(req, 'isRSCRequest') ?? false\n\n    let addedNextUrlToVary = false\n\n    if (isAppPath && this.pathCouldBeIntercepted(resolvedPathname)) {\n      // Interception route responses can vary based on the `Next-URL` header.\n      // We use the Vary header to signal this behavior to the client to properly cache the response.\n      res.appendHeader('vary', `${baseVaryHeader}, ${NEXT_URL}`)\n      addedNextUrlToVary = true\n    } else if (isAppPath || isRSCRequest) {\n      // We don't need to include `Next-URL` in the Vary header for non-interception routes since it won't affect the response.\n      // We also set this header for pages to avoid caching issues when navigating between pages and app.\n      res.appendHeader('vary', baseVaryHeader)\n    }\n\n    if (!addedNextUrlToVary) {\n      // Remove `Next-URL` from the request headers we determined it wasn't necessary to include in the Vary header.\n      // This is to avoid any dependency on the `Next-URL` header being present when preparing the response.\n      delete req.headers[NEXT_URL]\n    }\n  }\n\n  private async renderToResponseWithComponentsImpl(\n    {\n      req,\n      res,\n      pathname,\n      renderOpts: opts,\n    }: RequestContext<ServerRequest, ServerResponse>,\n    { components, query }: FindComponentsResult\n  ): Promise<ResponsePayload | null> {\n    if (pathname === UNDERSCORE_NOT_FOUND_ROUTE) {\n      pathname = '/404'\n    }\n    const isErrorPathname = pathname === '/_error'\n    const is404Page =\n      pathname === '/404' || (isErrorPathname && res.statusCode === 404)\n    const is500Page =\n      pathname === '/500' || (isErrorPathname && res.statusCode === 500)\n    const isAppPath = components.isAppPath === true\n\n    const hasServerProps = !!components.getServerSideProps\n    const isPossibleServerAction = getIsPossibleServerAction(req)\n    let isSSG = !!components.getStaticProps\n    // NOTE: Don't delete headers[RSC] yet, it still needs to be used in renderToHTML later\n    const isRSCRequest = getRequestMeta(req, 'isRSCRequest') ?? false\n\n    // Not all CDNs respect the Vary header when caching. We must assume that\n    // only the URL is used to vary the responses. The Next client computes a\n    // hash of the header values and sends it as a search param. Before\n    // responding to a request, we must verify that the hash matches the\n    // expected value. Neglecting to do this properly can lead to cache\n    // poisoning attacks on certain CDNs.\n    if (\n      !this.minimalMode &&\n      this.nextConfig.experimental.validateRSCRequestHeaders &&\n      isRSCRequest &&\n      // In the event that we're serving a NoFallbackError, the headers will\n      // already be stripped so this comparison will always fail, resulting in\n      // a redirect loop.\n      !is404Page\n    ) {\n      const headers = req.headers\n\n      const prefetchHeaderValue = headers[NEXT_ROUTER_PREFETCH_HEADER]\n      const routerPrefetch =\n        prefetchHeaderValue !== undefined\n          ? // We only recognize '1' and '2'. Strip all other values here.\n            prefetchHeaderValue === '1' || prefetchHeaderValue === '2'\n            ? prefetchHeaderValue\n            : undefined\n          : // For runtime prefetches, we always perform a dynamic request,\n            // so we don't expect the header to be stripped by an intermediate layer.\n            // This should only happen for static prefetches, so we only handle those here.\n            getRequestMeta(req, 'isPrefetchRSCRequest')\n            ? '1'\n            : undefined\n\n      const segmentPrefetchRSCRequest =\n        headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] ||\n        getRequestMeta(req, 'segmentPrefetchRSCRequest')\n\n      const expectedHash = computeCacheBustingSearchParam(\n        routerPrefetch,\n        segmentPrefetchRSCRequest,\n        headers[NEXT_ROUTER_STATE_TREE_HEADER],\n        headers[NEXT_URL]\n      )\n      const actualHash =\n        getRequestMeta(req, 'cacheBustingSearchParam') ??\n        new URL(req.url || '', 'http://localhost').searchParams.get(\n          NEXT_RSC_UNION_QUERY\n        )\n\n      if (expectedHash !== actualHash) {\n        // The hash sent by the client does not match the expected value.\n        // Redirect to the URL with the correct cache-busting search param.\n        // This prevents cache poisoning attacks on CDNs that don't respect Vary headers.\n        // Note: When no headers are present, expectedHash is empty string and client\n        // must send `_rsc` param, otherwise actualHash is null and hash check fails.\n        const url = new URL(req.url || '', 'http://localhost')\n        setCacheBustingSearchParamWithHash(url, expectedHash)\n        res.statusCode = 307\n        res.setHeader('location', `${url.pathname}${url.search}`)\n        res.body('').send()\n        return null\n      }\n    }\n\n    // Compute the iSSG cache key. We use the rewritten pathname since\n    // pages with fallback: false are allowed to be rewritten to\n    // and we need to look up the path by the rewritten path\n    let urlPathname = parseUrl(req.url || '').pathname || '/'\n\n    let resolvedUrlPathname =\n      getRequestMeta(req, 'rewrittenPathname') || urlPathname\n\n    this.setVaryHeader(req, res, isAppPath, resolvedUrlPathname)\n\n    let staticPaths: string[] | undefined\n    let hasFallback = false\n\n    const prerenderManifest = this.getPrerenderManifest()\n\n    if (\n      hasFallback ||\n      staticPaths?.includes(resolvedUrlPathname) ||\n      // this signals revalidation in deploy environments\n      // TODO: make this more generic\n      req.headers['x-now-route-matches']\n    ) {\n      isSSG = true\n    } else if (!this.dev) {\n      isSSG ||= !!prerenderManifest.routes[toRoute(pathname)]\n    }\n\n    // Toggle whether or not this is a Data request\n    const isNextDataRequest =\n      !!(\n        getRequestMeta(req, 'isNextDataReq') ||\n        (req.headers['x-nextjs-data'] &&\n          (this.serverOptions as any).webServerConfig)\n      ) &&\n      (isSSG || hasServerProps)\n\n    // when we are handling a middleware prefetch and it doesn't\n    // resolve to a static data route we bail early to avoid\n    // unexpected SSR invocations\n    if (\n      !isSSG &&\n      req.headers['x-middleware-prefetch'] &&\n      !(is404Page || pathname === '/_error')\n    ) {\n      res.setHeader(MATCHED_PATH_HEADER, pathname)\n      res.setHeader('x-middleware-skip', '1')\n      res.setHeader(\n        'cache-control',\n        'private, no-cache, no-store, max-age=0, must-revalidate'\n      )\n      res.body('{}').send()\n      return null\n    }\n\n    // normalize req.url for SSG paths as it is not exposed\n    // to getStaticProps and the asPath should not expose /_next/data\n    if (\n      isSSG &&\n      this.minimalMode &&\n      req.headers[MATCHED_PATH_HEADER] &&\n      req.url.startsWith('/_next/data')\n    ) {\n      req.url = this.stripNextDataPath(req.url)\n    }\n\n    const locale = getRequestMeta(req, 'locale')\n\n    if (\n      !!req.headers['x-nextjs-data'] &&\n      (!res.statusCode || res.statusCode === 200)\n    ) {\n      res.setHeader(\n        'x-nextjs-matched-path',\n        `${locale ? `/${locale}` : ''}${pathname}`\n      )\n    }\n\n    let routeModule: RouteModule | undefined\n    if (components.routeModule) {\n      routeModule = components.routeModule\n    }\n\n    /**\n     * If the route being rendered is an app page, and the ppr feature has been\n     * enabled, then the given route _could_ support PPR.\n     */\n    const couldSupportPPR: boolean =\n      this.isAppPPREnabled &&\n      typeof routeModule !== 'undefined' &&\n      isAppPageRouteModule(routeModule)\n\n    // When enabled, this will allow the use of the `?__nextppronly` query to\n    // enable debugging of the static shell.\n    const hasDebugStaticShellQuery =\n      process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING === '1' &&\n      typeof query.__nextppronly !== 'undefined' &&\n      couldSupportPPR\n\n    // Whether the testing API is exposed (dev mode or explicit flag)\n    const exposeTestingApi =\n      this.dev === true ||\n      this.nextConfig.experimental.exposeTestingApiInProductionBuild === true\n\n    // Check for the instant test cookie for MPA navigations (page reload, full\n    // page load) in the Instant Navigation Testing API. Only applies to\n    // document requests (no RSC header) - RSC requests should proceed normally\n    // even during a locked scope, with blocking happening on the client side.\n    const hasInstantTestCookie =\n      exposeTestingApi &&\n      req.headers[RSC_HEADER] === undefined &&\n      typeof req.headers.cookie === 'string' &&\n      req.headers.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=') &&\n      couldSupportPPR\n\n    // This page supports PPR if it is marked as being `PARTIALLY_STATIC` in the\n    // prerender manifest and this is an app page.\n    const isRoutePPREnabled: boolean =\n      couldSupportPPR &&\n      ((\n        prerenderManifest.routes[pathname] ??\n        prerenderManifest.dynamicRoutes[pathname]\n      )?.renderingMode === 'PARTIALLY_STATIC' ||\n        // Ideally we'd want to check the appConfig to see if this page has PPR\n        // enabled or not, but that would require plumbing the appConfig through\n        // to the server during development. We assume that the page supports it\n        // but only during development or when the testing API is exposed.\n        ((hasDebugStaticShellQuery || hasInstantTestCookie) &&\n          (exposeTestingApi || this.experimentalTestProxy === true)))\n\n    // If we're in minimal mode, then try to get the postponed information from\n    // the request metadata. If available, use it for resuming the postponed\n    // render.\n    const minimalPostponed = isRoutePPREnabled\n      ? getRequestMeta(req, 'postponed')\n      : undefined\n\n    // we need to ensure the status code if /404 is visited directly\n    if (is404Page && !isNextDataRequest && !isRSCRequest) {\n      res.statusCode = 404\n    }\n\n    // ensure correct status is set when visiting a status page\n    // directly e.g. /500\n    if (STATIC_STATUS_PAGES.includes(pathname)) {\n      res.statusCode = parseInt(pathname.slice(1), 10)\n    }\n\n    if (\n      // Server actions can use non-GET/HEAD methods.\n      !isPossibleServerAction &&\n      // Resume can use non-GET/HEAD methods.\n      !minimalPostponed &&\n      !is404Page &&\n      !is500Page &&\n      pathname !== '/_error' &&\n      req.method !== 'HEAD' &&\n      req.method !== 'GET' &&\n      (typeof components.Component === 'string' || isSSG)\n    ) {\n      res.statusCode = 405\n      res.setHeader('Allow', ['GET', 'HEAD'])\n      res.body('Method Not Allowed').send()\n      return null\n    }\n\n    // handle static page\n    if (typeof components.Component === 'string') {\n      return {\n        body: RenderResult.fromStatic(\n          components.Component,\n          HTML_CONTENT_TYPE_HEADER\n        ),\n      }\n    }\n\n    if (opts.supportsDynamicResponse === true) {\n      const ua = req.headers['user-agent'] || ''\n      const isBotRequest = isBot(ua)\n      const isSupportedDocument =\n        typeof components.Document?.getInitialProps !== 'function' ||\n        // The built-in `Document` component also supports dynamic HTML for concurrent mode.\n        NEXT_BUILTIN_DOCUMENT in components.Document\n\n      // Disable dynamic HTML in cases that we know it won't be generated,\n      // so that we can continue generating a cache key when possible.\n      // TODO-APP: should the first render for a dynamic app path\n      // be static so we can collect revalidate and populate the\n      // cache if there are no dynamic data requirements\n      opts.supportsDynamicResponse =\n        !isSSG && !isBotRequest && isSupportedDocument\n    }\n\n    // In development, we always want to generate dynamic HTML.\n    if (!isNextDataRequest && isAppPath && this.dev) {\n      opts.supportsDynamicResponse = true\n    }\n\n    if (isSSG && this.minimalMode && req.headers[MATCHED_PATH_HEADER]) {\n      // the url value is already correct when the matched-path header is set\n      resolvedUrlPathname = urlPathname\n    }\n\n    urlPathname = removeTrailingSlash(urlPathname)\n    resolvedUrlPathname = removeTrailingSlash(resolvedUrlPathname)\n    if (this.localeNormalizer) {\n      resolvedUrlPathname = this.localeNormalizer.normalize(resolvedUrlPathname)\n    }\n\n    // remove /_next/data prefix from urlPathname so it matches\n    // for direct page visit and /_next/data visit\n    if (isNextDataRequest) {\n      resolvedUrlPathname = this.stripNextDataPath(resolvedUrlPathname)\n      urlPathname = this.stripNextDataPath(urlPathname)\n    }\n\n    // use existing incrementalCache instance if available\n    const incrementalCache: import('./lib/incremental-cache').IncrementalCache =\n      await this.getIncrementalCache({\n        requestHeaders: Object.assign({}, req.headers),\n      })\n\n    // TODO: investigate, this is not safe across multiple concurrent requests\n    incrementalCache.resetRequestCache()\n\n    if (\n      routeModule?.isDev &&\n      isDynamicRoute(pathname) &&\n      (components.getStaticPaths || isAppPath)\n    ) {\n      let getStaticPathsStart: bigint | undefined\n      if (this.dev) {\n        getStaticPathsStart = process.hrtime.bigint()\n      }\n\n      const pathsResults = await this.getStaticPaths({\n        pathname,\n        urlPathname,\n        requestHeaders: req.headers,\n        page: components.page,\n        isAppPath,\n      })\n\n      if (this.dev && getStaticPathsStart && pathsResults.staticPaths?.length) {\n        addRequestMeta(\n          req,\n          'devGenerateStaticParamsDuration',\n          process.hrtime.bigint() - getStaticPathsStart\n        )\n      }\n\n      if (isAppPath && this.nextConfig.cacheComponents) {\n        if (pathsResults.prerenderedRoutes?.length) {\n          let smallestFallbackRouteParams = null\n          for (const route of pathsResults.prerenderedRoutes) {\n            const fallbackRouteParams = route.fallbackRouteParams\n            if (!fallbackRouteParams || fallbackRouteParams.length === 0) {\n              // There are no fallback route params so we don't need to continue\n              smallestFallbackRouteParams = null\n              break\n            }\n            if (\n              smallestFallbackRouteParams === null ||\n              fallbackRouteParams.length < smallestFallbackRouteParams.length\n            ) {\n              smallestFallbackRouteParams = fallbackRouteParams\n            }\n          }\n          if (smallestFallbackRouteParams) {\n            addRequestMeta(\n              req,\n              'fallbackParams',\n              createOpaqueFallbackRouteParams(smallestFallbackRouteParams)!\n            )\n          }\n        }\n      }\n    }\n\n    // An OPTIONS request to a page handler is invalid.\n    if (\n      req.method === 'OPTIONS' &&\n      !is404Page &&\n      (!routeModule || !isAppRouteRouteModule(routeModule))\n    ) {\n      await sendResponse(req, res, new Response(null, { status: 400 }))\n      return null\n    }\n\n    const request = isNodeNextRequest(req) ? req.originalRequest : req\n    const response = isNodeNextResponse(res) ? res.originalResponse : res\n\n    const parsedInitUrl = parseUrl(getRequestMeta(req, 'initURL') || req.url)\n    let initPathname = parsedInitUrl.pathname || '/'\n\n    for (const normalizer of [\n      this.normalizers.segmentPrefetchRSC,\n      this.normalizers.rsc,\n    ]) {\n      if (normalizer?.match(initPathname)) {\n        initPathname = normalizer.normalize(initPathname)\n      }\n    }\n\n    // On minimal mode, the request url of dynamic route can be a\n    // literal dynamic route ('/[slug]') instead of actual URL, so overwriting to initPathname\n    // will transform back the resolved url to the dynamic route pathname.\n    if (!(this.minimalMode && isErrorPathname)) {\n      request.url = `${initPathname}${parsedInitUrl.search || ''}`\n    }\n\n    // propagate the request context for dev\n    setRequestMeta(request, getRequestMeta(req))\n    addRequestMeta(request, 'distDir', this.distDir)\n    addRequestMeta(request, 'query', query)\n    addRequestMeta(request, 'params', opts.params)\n    addRequestMeta(request, 'minimalMode', this.minimalMode)\n\n    if (opts.err) {\n      addRequestMeta(request, 'invokeError', opts.err)\n    }\n\n    const maybeDevRequest: ServerRequest | IncomingMessage =\n      // we need to capture fetch metrics when they are set\n      // and can't wait for handler to resolve as the fetch\n      // metrics are logged on response close which happens\n      // before handler resolves\n      process.env.NODE_ENV === 'development'\n        ? new Proxy(request, {\n            get(target: any, prop) {\n              if (typeof target[prop] === 'function') {\n                return target[prop].bind(target)\n              }\n              return target[prop]\n            },\n            set(target: any, prop, value) {\n              if (prop === 'fetchMetrics') {\n                ;(req as any).fetchMetrics = value\n              }\n              target[prop] = value\n              return true\n            },\n          })\n        : request\n\n    // @ts-expect-error This isn't entirely correct, but the ServerRequest type param seems overly\n    // generic anyway.\n    let handlerReq: IncomingMessage = maybeDevRequest\n    // @ts-expect-error This isn't entirely correct, but the ServerResponse type param seems overly\n    // generic anyway.\n    let handlerRes: HTTPServerResponse = response\n\n    await components.ComponentMod.handler(handlerReq, handlerRes, {\n      waitUntil: this.getWaitUntil(),\n    })\n\n    // response is handled fully in handler\n    return null\n  }\n\n  private stripNextDataPath(filePath: string, stripLocale = true) {\n    if (filePath.includes(this.buildId)) {\n      const splitPath = filePath.substring(\n        filePath.indexOf(this.buildId) + this.buildId.length\n      )\n\n      filePath = denormalizePagePath(splitPath.replace(/\\.json$/, ''))\n    }\n\n    if (this.localeNormalizer && stripLocale) {\n      return this.localeNormalizer.normalize(filePath)\n    }\n    return filePath\n  }\n\n  // map the route to the actual bundle name\n  protected getOriginalAppPaths(route: string) {\n    if (this.enabledDirectories.app) {\n      const originalAppPath = this.appPathRoutes?.[route]\n\n      if (!originalAppPath) {\n        return null\n      }\n\n      return originalAppPath\n    }\n    return null\n  }\n\n  protected async renderPageComponent(\n    ctx: RequestContext<ServerRequest, ServerResponse>,\n    bubbleNoFallback: boolean\n  ) {\n    const { query, pathname } = ctx\n\n    const appPaths = this.getOriginalAppPaths(pathname)\n    const isAppPath = Array.isArray(appPaths)\n\n    let page = pathname\n    if (isAppPath) {\n      // the last item in the array is the root page, if there are parallel routes\n      page = appPaths[appPaths.length - 1]\n    }\n\n    const result = await this.findPageComponents({\n      locale: getRequestMeta(ctx.req, 'locale'),\n      page,\n      query,\n      params: ctx.renderOpts.params || {},\n      isAppPath,\n      sriEnabled: !!this.nextConfig.experimental.sri?.algorithm,\n      appPaths,\n      // Ensuring for loading page component routes is done via the matcher.\n      shouldEnsure: false,\n    })\n    if (result) {\n      getTracer().setRootSpanAttribute('next.route', pathname)\n      try {\n        return await this.renderToResponseWithComponents(ctx, result)\n      } catch (err) {\n        const isNoFallbackError = err instanceof NoFallbackError\n\n        if (!isNoFallbackError || (isNoFallbackError && bubbleNoFallback)) {\n          throw err\n        }\n      }\n    }\n    return false\n  }\n\n  private async renderToResponse(\n    ctx: RequestContext<ServerRequest, ServerResponse>\n  ): Promise<ResponsePayload | null> {\n    return getTracer().trace(\n      BaseServerSpan.renderToResponse,\n      {\n        spanName: `rendering page`,\n        attributes: {\n          'next.route': ctx.pathname,\n        },\n      },\n      async () => {\n        return this.renderToResponseImpl(ctx)\n      }\n    )\n  }\n\n  protected abstract getMiddleware(): Promise<MiddlewareRoutingItem | undefined>\n  protected abstract getFallbackErrorComponents(\n    url?: string\n  ): Promise<LoadComponentsReturnType<ErrorModule> | null>\n  protected abstract getRoutesManifest(): NormalizedRouteManifest | undefined\n\n  private async renderToResponseImpl(\n    ctx: RequestContext<ServerRequest, ServerResponse>\n  ): Promise<ResponsePayload | null> {\n    const { req, res, query, pathname } = ctx\n    let page = pathname\n    const bubbleNoFallback =\n      getRequestMeta(ctx.req, 'bubbleNoFallback') ?? false\n\n    if (\n      !this.minimalMode &&\n      this.nextConfig.experimental.validateRSCRequestHeaders\n    ) {\n      addRequestMeta(\n        ctx.req,\n        'cacheBustingSearchParam',\n        query[NEXT_RSC_UNION_QUERY]\n      )\n    }\n    delete query[NEXT_RSC_UNION_QUERY]\n\n    const options: MatchOptions = {\n      i18n: this.i18nProvider?.fromRequest(req, pathname),\n    }\n\n    const existingMatch = getRequestMeta(ctx.req, 'match')\n\n    let fastPath = true\n    // when a specific invoke-output is meant to be matched\n    // ensure a prior dynamic route/page doesn't take priority\n    const invokeOutput = getRequestMeta(ctx.req, 'invokeOutput')\n\n    if (\n      (!this.minimalMode &&\n        typeof invokeOutput === 'string' &&\n        isDynamicRoute(invokeOutput || '') &&\n        invokeOutput !== existingMatch?.definition.pathname) ||\n      // Parallel routes are matched in `existingMatch` but since currently\n      // there can be multiple matches it's not guaranteed to be the right match\n      // therefor we need to opt-out of the fast path for parallel routes.\n      existingMatch?.definition.page.includes('/@')\n    ) {\n      fastPath = false\n    }\n\n    try {\n      for await (const match of fastPath && existingMatch\n        ? [existingMatch]\n        : this.matchers.matchAll(pathname, options)) {\n        if (\n          !this.minimalMode &&\n          typeof invokeOutput === 'string' &&\n          isDynamicRoute(invokeOutput || '') &&\n          invokeOutput !== match.definition.pathname\n        ) {\n          continue\n        }\n\n        const result = await this.renderPageComponent(\n          {\n            ...ctx,\n            pathname: match.definition.pathname,\n            renderOpts: {\n              ...ctx.renderOpts,\n              params: match.params,\n            },\n          },\n          bubbleNoFallback\n        )\n        if (result !== false) return result\n      }\n\n      // currently edge functions aren't receiving the x-matched-path\n      // header so we need to fallback to matching the current page\n      // when we weren't able to match via dynamic route to handle\n      // the rewrite case\n      // @ts-expect-error extended in child class web-server\n      if (this.serverOptions.webServerConfig) {\n        // @ts-expect-error extended in child class web-server\n        ctx.pathname = this.serverOptions.webServerConfig.page\n        const result = await this.renderPageComponent(ctx, bubbleNoFallback)\n        if (result !== false) return result\n      }\n    } catch (error) {\n      const err = getProperError(error)\n\n      if (error instanceof MissingStaticPage) {\n        console.error(\n          'Invariant: failed to load static page',\n          JSON.stringify(\n            {\n              page,\n              url: ctx.req.url,\n              matchedPath: ctx.req.headers[MATCHED_PATH_HEADER],\n              initUrl: getRequestMeta(ctx.req, 'initURL'),\n              didRewrite: !!getRequestMeta(ctx.req, 'rewrittenPathname'),\n              rewrittenPathname: getRequestMeta(ctx.req, 'rewrittenPathname'),\n            },\n            null,\n            2\n          )\n        )\n        throw err\n      }\n\n      if (err instanceof NoFallbackError && bubbleNoFallback) {\n        throw err\n      }\n      if (err instanceof DecodeError || err instanceof NormalizeError) {\n        res.statusCode = 400\n        return await this.renderErrorToResponse(ctx, err)\n      }\n\n      res.statusCode = 500\n\n      // if pages/500 is present we still need to trigger\n      // /_error `getInitialProps` to allow reporting error\n      if (await this.hasPage('/500')) {\n        addRequestMeta(ctx.req, 'customErrorRender', true)\n        await this.renderErrorToResponse(ctx, err)\n        removeRequestMeta(ctx.req, 'customErrorRender')\n      }\n\n      const isWrappedError = err instanceof WrappedBuildError\n\n      if (!isWrappedError) {\n        if (this.minimalMode || this.dev) {\n          if (isError(err)) err.page = page\n          throw err\n        }\n        this.logError(getProperError(err))\n      }\n      const response = await this.renderErrorToResponse(\n        ctx,\n        isWrappedError ? (err as WrappedBuildError).innerError : err\n      )\n      return response\n    }\n\n    const middleware = await this.getMiddleware()\n    if (\n      middleware &&\n      !!ctx.req.headers['x-nextjs-data'] &&\n      (!res.statusCode || res.statusCode === 200 || res.statusCode === 404)\n    ) {\n      const locale = getRequestMeta(req, 'locale')\n\n      res.setHeader(\n        'x-nextjs-matched-path',\n        `${locale ? `/${locale}` : ''}${pathname}`\n      )\n      res.statusCode = 200\n      res.setHeader('Content-Type', JSON_CONTENT_TYPE_HEADER)\n      res.body('{}')\n      res.send()\n      return null\n    }\n\n    res.statusCode = 404\n    return this.renderErrorToResponse(ctx, null)\n  }\n\n  public async renderToHTML(\n    req: ServerRequest,\n    res: ServerResponse,\n    pathname: string,\n    query: ParsedUrlQuery = {}\n  ): Promise<string | null> {\n    return getTracer().trace(BaseServerSpan.renderToHTML, async () => {\n      return this.renderToHTMLImpl(req, res, pathname, query)\n    })\n  }\n\n  private async renderToHTMLImpl(\n    req: ServerRequest,\n    res: ServerResponse,\n    pathname: string,\n    query: ParsedUrlQuery = {}\n  ): Promise<string | null> {\n    return this.getStaticHTML((ctx) => this.renderToResponse(ctx), {\n      req,\n      res,\n      pathname,\n      query,\n    })\n  }\n\n  public async renderError(\n    err: Error | null,\n    req: ServerRequest,\n    res: ServerResponse,\n    pathname: string,\n    query: NextParsedUrlQuery = {},\n    setHeaders = true\n  ): Promise<void> {\n    return getTracer().trace(BaseServerSpan.renderError, async () => {\n      return this.renderErrorImpl(err, req, res, pathname, query, setHeaders)\n    })\n  }\n\n  private async renderErrorImpl(\n    err: Error | null,\n    req: ServerRequest,\n    res: ServerResponse,\n    pathname: string,\n    query: NextParsedUrlQuery = {},\n    setHeaders = true\n  ): Promise<void> {\n    if (setHeaders) {\n      res.setHeader(\n        'Cache-Control',\n        'private, no-cache, no-store, max-age=0, must-revalidate'\n      )\n    }\n\n    return this.pipe(\n      async (ctx) => {\n        const response = await this.renderErrorToResponse(ctx, err)\n        if (this.minimalMode && res.statusCode === 500) {\n          throw err\n        }\n        return response\n      },\n      { req, res, pathname, query }\n    )\n  }\n\n  private customErrorNo404Warn = execOnce(() => {\n    Log.warn(\n      `You have added a custom /_error page without a custom /404 page. This prevents the 404 page from being auto statically optimized.\\nSee here for info: https://nextjs.org/docs/messages/custom-error-no-custom-404`\n    )\n  })\n\n  private async renderErrorToResponse(\n    ctx: RequestContext<ServerRequest, ServerResponse>,\n    err: Error | null\n  ): Promise<ResponsePayload | null> {\n    return getTracer().trace(BaseServerSpan.renderErrorToResponse, async () => {\n      return this.renderErrorToResponseImpl(ctx, err)\n    })\n  }\n\n  protected async renderErrorToResponseImpl(\n    ctx: RequestContext<ServerRequest, ServerResponse>,\n    err: Error | null\n  ): Promise<ResponsePayload | null> {\n    // Short-circuit favicon.ico in development to avoid compiling 404 page when the app has no favicon.ico.\n    // Since favicon.ico is automatically requested by the browser.\n    if (this.dev && ctx.pathname === '/favicon.ico') {\n      return {\n        body: RenderResult.EMPTY,\n      }\n    }\n    const { res, query } = ctx\n\n    try {\n      let result: null | FindComponentsResult = null\n\n      const is404 = res.statusCode === 404\n      let using404Page = false\n      const hasAppDir = this.enabledDirectories.app\n\n      if (is404) {\n        if (hasAppDir) {\n          // Use the not-found entry in app directory\n          result = await this.findPageComponents({\n            locale: getRequestMeta(ctx.req, 'locale'),\n            page: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,\n            query,\n            params: {},\n            isAppPath: true,\n            shouldEnsure: true,\n            url: ctx.req.url,\n          })\n          using404Page = result !== null\n        }\n\n        if (!result && (await this.hasPage('/404'))) {\n          result = await this.findPageComponents({\n            locale: getRequestMeta(ctx.req, 'locale'),\n            page: '/404',\n            query,\n            params: {},\n            isAppPath: false,\n            // Ensuring can't be done here because you never \"match\" a 404 route.\n            shouldEnsure: true,\n            url: ctx.req.url,\n          })\n          using404Page = result !== null\n        }\n      }\n      let statusPage = `/${res.statusCode}`\n\n      if (\n        !getRequestMeta(ctx.req, 'customErrorRender') &&\n        !result &&\n        STATIC_STATUS_PAGES.includes(statusPage)\n      ) {\n        // skip ensuring /500 in dev mode as it isn't used and the\n        // dev overlay is used instead\n        if (statusPage !== '/500' || !this.dev) {\n          if (!result && hasAppDir) {\n            // Otherwise if app router present, load app router built-in 500 page\n            result = await this.findPageComponents({\n              locale: getRequestMeta(ctx.req, 'locale'),\n              page: statusPage,\n              query,\n              params: {},\n              isAppPath: true,\n              // Ensuring can't be done here because you never \"match\" a 500\n              // route.\n              shouldEnsure: true,\n              url: ctx.req.url,\n            })\n          }\n          // If the above App Router result is empty, fallback to pages router 500 page\n          result = await this.findPageComponents({\n            locale: getRequestMeta(ctx.req, 'locale'),\n            page: statusPage,\n            query,\n            params: {},\n            isAppPath: false,\n            // Ensuring can't be done here because you never \"match\" a 500\n            // route.\n            shouldEnsure: true,\n            url: ctx.req.url,\n          })\n        }\n      }\n\n      if (!result) {\n        result = await this.findPageComponents({\n          locale: getRequestMeta(ctx.req, 'locale'),\n          page: '/_error',\n          query,\n          params: {},\n          isAppPath: false,\n          // Ensuring can't be done here because you never \"match\" an error\n          // route.\n          shouldEnsure: true,\n          url: ctx.req.url,\n        })\n        statusPage = '/_error'\n      }\n\n      if (\n        process.env.NODE_ENV !== 'production' &&\n        !using404Page &&\n        (await this.hasPage('/_error')) &&\n        !(await this.hasPage('/404'))\n      ) {\n        this.customErrorNo404Warn()\n      }\n\n      if (!result) {\n        // this can occur when a project directory has been moved/deleted\n        // which is handled in the parent process in development\n        if (this.dev) {\n          return {\n            // wait for dev-server to restart before refreshing\n            body: RenderResult.fromStatic(\n              `\n              <pre>missing required error components, refreshing...</pre>\n              <script>\n                async function check() {\n                  const res = await fetch(location.href).catch(() => ({}))\n\n                  if (res.status === 200) {\n                    location.reload()\n                  } else {\n                    setTimeout(check, 1000)\n                  }\n                }\n                check()\n              </script>`,\n              HTML_CONTENT_TYPE_HEADER\n            ),\n          }\n        }\n\n        throw new WrappedBuildError(\n          new Error('missing required error components')\n        )\n      }\n\n      // If the page has a route module, use it for the new match. If it doesn't\n      // have a route module, remove the match.\n      if (result.components.routeModule) {\n        addRequestMeta(ctx.req, 'match', {\n          definition: result.components.routeModule.definition,\n          params: undefined,\n        })\n      } else {\n        removeRequestMeta(ctx.req, 'match')\n      }\n\n      try {\n        return await this.renderToResponseWithComponents(\n          {\n            ...ctx,\n            pathname: statusPage,\n            renderOpts: {\n              ...ctx.renderOpts,\n              err,\n            },\n          },\n          result\n        )\n      } catch (maybeFallbackError) {\n        if (maybeFallbackError instanceof NoFallbackError) {\n          throw new Error('invariant: failed to render error page')\n        }\n        throw maybeFallbackError\n      }\n    } catch (error) {\n      const renderToHtmlError = getProperError(error)\n      const isWrappedError = renderToHtmlError instanceof WrappedBuildError\n      if (!isWrappedError) {\n        this.logError(renderToHtmlError)\n      }\n      res.statusCode = 500\n      const fallbackComponents = await this.getFallbackErrorComponents(\n        ctx.req.url\n      )\n\n      if (fallbackComponents) {\n        // There was an error, so use it's definition from the route module\n        // to add the match to the request.\n        addRequestMeta(ctx.req, 'match', {\n          definition: fallbackComponents.routeModule!.definition,\n          params: undefined,\n        })\n\n        return this.renderToResponseWithComponents(\n          {\n            ...ctx,\n            pathname: '/_error',\n            renderOpts: {\n              ...ctx.renderOpts,\n              // We render `renderToHtmlError` here because `err` is\n              // already captured in the stacktrace.\n              err: isWrappedError\n                ? renderToHtmlError.innerError\n                : renderToHtmlError,\n            },\n          },\n          {\n            query,\n            components: fallbackComponents,\n          }\n        )\n      }\n      return {\n        body: RenderResult.fromStatic('Internal Server Error', 'text/plain'),\n      }\n    }\n  }\n\n  public async renderErrorToHTML(\n    err: Error | null,\n    req: ServerRequest,\n    res: ServerResponse,\n    pathname: string,\n    query: ParsedUrlQuery = {}\n  ): Promise<string | null> {\n    return this.getStaticHTML((ctx) => this.renderErrorToResponse(ctx, err), {\n      req,\n      res,\n      pathname,\n      query,\n    })\n  }\n\n  public async render404(\n    req: ServerRequest,\n    res: ServerResponse,\n    parsedUrl?: Pick<NextUrlWithParsedQuery, 'pathname' | 'query'>,\n    setHeaders = true\n  ): Promise<void> {\n    const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(req.url)\n\n    // Ensure the locales are provided on the request meta.\n    if (this.nextConfig.i18n) {\n      if (!getRequestMeta(req, 'locale')) {\n        addRequestMeta(req, 'locale', this.nextConfig.i18n.defaultLocale)\n      }\n      addRequestMeta(req, 'defaultLocale', this.nextConfig.i18n.defaultLocale)\n    }\n\n    res.statusCode = 404\n    return this.renderError(null, req, res, pathname!, query, setHeaders)\n  }\n}\n","import type { IncomingHttpHeaders } from 'node:http'\n\nimport { FLIGHT_HEADERS } from '../../client/components/app-router-headers'\n\n/**\n * Removes the flight headers from the request.\n *\n * @param req the request to strip the headers from\n */\nexport function stripFlightHeaders(headers: IncomingHttpHeaders) {\n  for (const header of FLIGHT_HEADERS) {\n    delete headers[header]\n  }\n}\n","// Translate a pages asset path (relative from a common prefix) back into its logical route\n\nimport { isDynamicRoute } from './is-dynamic'\n\n// \"asset path\" being its javascript file, data file, prerendered html,...\nexport default function getRouteFromAssetPath(\n  assetPath: string,\n  ext: string = ''\n): string {\n  assetPath = assetPath.replace(/\\\\/g, '/')\n  assetPath =\n    ext && assetPath.endsWith(ext) ? assetPath.slice(0, -ext.length) : assetPath\n  if (assetPath.startsWith('/index/') && !isDynamicRoute(assetPath)) {\n    assetPath = assetPath.slice(6)\n  } else if (assetPath === '/index') {\n    assetPath = '/'\n  }\n  return assetPath\n}\n","import { isIPv6 } from './is-ipv6'\n\n/**\n * Formats a hostname so that it is a valid host that can be fetched by wrapping\n * IPv6 hosts with brackets.\n * @param hostname\n * @returns\n */\nexport function formatHostname(hostname: string): string {\n  return isIPv6(hostname) ? `[${hostname}]` : hostname\n}\n","/**\n * If set to `incremental`, only those leaf pages that export\n * `experimental_ppr = true` will have partial prerendering enabled. If any\n * page exports this value as `false` or does not export it at all will not\n * have partial prerendering enabled. If set to a boolean, the options for\n * `experimental_ppr` will be ignored.\n */\n\nexport type ExperimentalPPRConfig = boolean | 'incremental'\n\n/**\n * Returns true if partial prerendering is enabled for the application. It does\n * not tell you if a given route has PPR enabled, as that requires analysis of\n * the route's configuration.\n *\n * @see {@link checkIsRoutePPREnabled} - for checking if a specific route has PPR enabled.\n */\nexport function checkIsAppPPREnabled(\n  config: ExperimentalPPRConfig | undefined\n): boolean {\n  // If the config is undefined, partial prerendering is disabled.\n  if (typeof config === 'undefined') return false\n\n  // If the config is a boolean, use it directly.\n  if (typeof config === 'boolean') return config\n\n  // If the config is a string, it must be 'incremental' to enable partial\n  // prerendering.\n  if (config === 'incremental') return true\n\n  return false\n}\n\n/**\n * Returns true if partial prerendering is supported for the current page with\n * the provided app configuration. If the application doesn't have partial\n * prerendering enabled, this function will always return false. If you want to\n * check if the application has partial prerendering enabled\n *\n * @see {@link checkIsAppPPREnabled} for checking if the application has PPR enabled.\n */\nexport function checkIsRoutePPREnabled(\n  config: ExperimentalPPRConfig | undefined\n): boolean {\n  // If the config is undefined, partial prerendering is disabled.\n  if (typeof config === 'undefined') return false\n\n  // If the config is a boolean, use it directly.\n  if (typeof config === 'boolean') return config\n\n  return false\n}\n","import { getRequestMeta, type NextIncomingMessage } from '../request-meta'\n\ntype PatchableResponse = {\n  setHeader(key: string, value: string | string[]): PatchableResponse\n}\n\n/**\n * Ensure cookies set in middleware are merged and not overridden by API\n * routes/getServerSideProps.\n *\n * @param req Incoming request\n * @param res Outgoing response\n */\nexport function patchSetHeaderWithCookieSupport(\n  req: NextIncomingMessage,\n  res: PatchableResponse\n) {\n  const setHeader = res.setHeader.bind(res)\n  res.setHeader = (\n    name: string,\n    value: string | string[]\n  ): PatchableResponse => {\n    // When renders /_error after page is failed, it could attempt to set\n    // headers after headers.\n    if ('headersSent' in res && res.headersSent) {\n      return res\n    }\n\n    if (name.toLowerCase() === 'set-cookie') {\n      const middlewareValue = getRequestMeta(req, 'middlewareCookie')\n\n      if (\n        !middlewareValue ||\n        !Array.isArray(value) ||\n        !value.every((item, idx) => item === middlewareValue[idx])\n      ) {\n        value = [\n          // TODO: (wyattjoh) find out why this is called multiple times resulting in duplicate cookies being added\n          ...new Set([\n            ...(middlewareValue || []),\n            ...(typeof value === 'string'\n              ? [value]\n              : Array.isArray(value)\n                ? value\n                : []),\n          ]),\n        ]\n      }\n    }\n\n    return setHeader(name, value)\n  }\n}\n","// x-matched-path header can be decoded incorrectly\n// and should only be utf8 characters so this fixes\n// incorrectly encoded values\nexport function fixMojibake(input: string): string {\n  // Convert each character's char code to a byte\n  const bytes = new Uint8Array(input.length)\n  for (let i = 0; i < input.length; i++) {\n    bytes[i] = input.charCodeAt(i)\n  }\n\n  // Decode the bytes as proper UTF-8\n  const decoder = new TextDecoder('utf-8')\n  return decoder.decode(bytes)\n}\n","import type { UrlWithParsedQuery } from 'url'\nimport { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers'\n\nconst DUMMY_ORIGIN = 'http://n'\n\nexport function isFullStringUrl(url: string) {\n  return /https?:\\/\\//.test(url)\n}\n\nexport function parseUrl(url: string): URL | undefined {\n  let parsed: URL | undefined = undefined\n  try {\n    parsed = new URL(url, DUMMY_ORIGIN)\n  } catch {}\n  return parsed\n}\n\nexport function parseReqUrl(url: string): UrlWithParsedQuery | undefined {\n  const parsedUrl: URL | undefined = parseUrl(url)\n\n  if (!parsedUrl) {\n    return\n  }\n\n  const query: Record<string, string | string[]> = {}\n\n  for (const key of parsedUrl.searchParams.keys()) {\n    const values = parsedUrl.searchParams.getAll(key)\n    query[key] = values.length > 1 ? values : values[0]\n  }\n\n  const legacyUrl: UrlWithParsedQuery = {\n    query,\n    hash: parsedUrl.hash,\n    search: parsedUrl.search,\n    path: parsedUrl.pathname,\n    pathname: parsedUrl.pathname,\n    href: `${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`,\n    host: '',\n    hostname: '',\n    auth: '',\n    protocol: '',\n    slashes: null,\n    port: '',\n  }\n  return legacyUrl\n}\n\nexport function stripNextRscUnionQuery(relativeUrl: string): string {\n  const urlInstance = new URL(relativeUrl, DUMMY_ORIGIN)\n  urlInstance.searchParams.delete(NEXT_RSC_UNION_QUERY)\n\n  return urlInstance.pathname + urlInstance.search\n}\n","import {\n  getBotType,\n  HTML_LIMITED_BOT_UA_RE_STRING,\n} from '../../shared/lib/router/utils/is-bot'\nimport type { BaseNextRequest } from '../base-http'\n\nexport function shouldServeStreamingMetadata(\n  userAgent: string,\n  htmlLimitedBots: string | undefined\n): boolean {\n  const blockingMetadataUARegex = new RegExp(\n    htmlLimitedBots || HTML_LIMITED_BOT_UA_RE_STRING,\n    'i'\n  )\n  // Only block metadata for HTML-limited bots\n  if (userAgent && blockingMetadataUARegex.test(userAgent)) {\n    return false\n  }\n  return true\n}\n\n// When the request UA is a html-limited bot, we should do a dynamic render.\n// In this case, postpone state is not sent.\nexport function isHtmlBotRequest(req: {\n  headers: BaseNextRequest['headers']\n}): boolean {\n  const ua = req.headers['user-agent'] || ''\n  const botType = getBotType(ua)\n\n  return botType === 'html'\n}\n","import { BLOCKED_PAGES } from '../shared/lib/constants'\n\nexport function isBlockedPage(page: string): boolean {\n  return BLOCKED_PAGES.includes(page)\n}\n\ntype AnyFunc<T> = (this: T, ...args: any) => any\nexport function debounce<T, F extends AnyFunc<T>>(\n  fn: F,\n  ms: number,\n  maxWait = Infinity\n) {\n  let timeoutId: undefined | NodeJS.Timeout\n\n  // The time the debouncing function was first called during this debounce queue.\n  let startTime = 0\n  // The time the debouncing function was last called.\n  let lastCall = 0\n\n  // The arguments and this context of the last call to the debouncing function.\n  let args: Parameters<F>, context: T\n\n  // A helper used to that either invokes the debounced function, or\n  // reschedules the timer if a more recent call was made.\n  function run() {\n    const now = Date.now()\n    const diff = lastCall + ms - now\n\n    // If the diff is non-positive, then we've waited at least `ms`\n    // milliseconds since the last call. Or if we've waited for longer than the\n    // max wait time, we must call the debounced function.\n    if (diff <= 0 || startTime + maxWait >= now) {\n      // It's important to clear the timeout id before invoking the debounced\n      // function, in case the function calls the debouncing function again.\n      timeoutId = undefined\n      fn.apply(context, args)\n    } else {\n      // Else, a new call was made after the original timer was scheduled. We\n      // didn't clear the timeout (doing so is very slow), so now we need to\n      // reschedule the timer for the time difference.\n      timeoutId = setTimeout(run, diff)\n    }\n  }\n\n  return function (this: T, ...passedArgs: Parameters<F>) {\n    // The arguments and this context of the most recent call are saved so the\n    // debounced function can be invoked with them later.\n    args = passedArgs\n    context = this\n\n    // Instead of constantly clearing and scheduling a timer, we record the\n    // time of the last call. If a second call comes in before the timer fires,\n    // then we'll reschedule in the run function. Doing this is considerably\n    // faster.\n    lastCall = Date.now()\n\n    // Only schedule a new timer if we're not currently waiting.\n    if (timeoutId === undefined) {\n      startTime = lastCall\n      timeoutId = setTimeout(run, ms)\n    }\n  }\n}\n","/**\n * Describes the different fallback modes that a given page can have.\n */\nexport const enum FallbackMode {\n  /**\n   * A BLOCKING_STATIC_RENDER fallback will block the request until the page is\n   * generated. No fallback page will be rendered, and users will have to wait\n   * to render the page.\n   */\n  BLOCKING_STATIC_RENDER = 'BLOCKING_STATIC_RENDER',\n\n  /**\n   * When set to PRERENDER, a fallback page will be sent to users in place of\n   * forcing them to wait for the page to be generated. This allows the user to\n   * see a rendered page earlier.\n   */\n  PRERENDER = 'PRERENDER',\n\n  /**\n   * When set to NOT_FOUND, pages that are not already prerendered will result\n   * in a not found response.\n   */\n  NOT_FOUND = 'NOT_FOUND',\n}\n\n/**\n * The fallback value returned from the `getStaticPaths` function.\n */\nexport type GetStaticPathsFallback = boolean | 'blocking'\n\n/**\n * Parses the fallback field from the prerender manifest.\n *\n * @param fallbackField The fallback field from the prerender manifest.\n * @returns The fallback mode.\n */\nexport function parseFallbackField(\n  fallbackField: string | boolean | null | undefined\n): FallbackMode | undefined {\n  if (typeof fallbackField === 'string') {\n    return FallbackMode.PRERENDER\n  } else if (fallbackField === null) {\n    return FallbackMode.BLOCKING_STATIC_RENDER\n  } else if (fallbackField === false) {\n    return FallbackMode.NOT_FOUND\n  } else if (fallbackField === undefined) {\n    return undefined\n  } else {\n    throw new Error(\n      `Invalid fallback option: ${fallbackField}. Fallback option must be a string, null, undefined, or false.`\n    )\n  }\n}\n\nexport function fallbackModeToFallbackField(\n  fallback: FallbackMode,\n  page: string | undefined\n): string | false | null {\n  switch (fallback) {\n    case FallbackMode.BLOCKING_STATIC_RENDER:\n      return null\n    case FallbackMode.NOT_FOUND:\n      return false\n    case FallbackMode.PRERENDER:\n      if (!page) {\n        throw new Error(\n          `Invariant: expected a page to be provided when fallback mode is \"${fallback}\"`\n        )\n      }\n\n      return page\n    default:\n      throw new Error(`Invalid fallback mode: ${fallback}`)\n  }\n}\n\n/**\n * Parses the fallback from the static paths result.\n *\n * @param result The result from the static paths function.\n * @returns The fallback mode.\n */\nexport function parseStaticPathsResult(\n  result: GetStaticPathsFallback\n): FallbackMode {\n  if (result === true) {\n    return FallbackMode.PRERENDER\n  } else if (result === 'blocking') {\n    return FallbackMode.BLOCKING_STATIC_RENDER\n  } else {\n    return FallbackMode.NOT_FOUND\n  }\n}\n","import type { IncomingMessage } from 'http'\nimport type { BaseNextRequest } from '../base-http'\nimport type { NextRequest } from '../web/exports'\nimport { ACTION_HEADER } from '../../client/components/app-router-headers'\n\nexport function getServerActionRequestMetadata(\n  req: IncomingMessage | BaseNextRequest | NextRequest\n): {\n  actionId: string | null\n  isURLEncodedAction: boolean\n  isMultipartAction: boolean\n  isFetchAction: boolean\n  isPossibleServerAction: boolean\n} {\n  let actionId: string | null\n  let contentType: string | null\n\n  if (req.headers instanceof Headers) {\n    actionId = req.headers.get(ACTION_HEADER) ?? null\n    contentType = req.headers.get('content-type')\n  } else {\n    actionId = (req.headers[ACTION_HEADER] as string) ?? null\n    contentType = req.headers['content-type'] ?? null\n  }\n\n  // We don't actually support URL encoded actions, and the action handler will bail out if it sees one.\n  // But we still want it to flow through to the action handler, to prevent changes in behavior when a regular\n  // page component tries to handle a POST.\n  const isURLEncodedAction = Boolean(\n    req.method === 'POST' && contentType === 'application/x-www-form-urlencoded'\n  )\n  const isMultipartAction = Boolean(\n    req.method === 'POST' && contentType?.startsWith('multipart/form-data')\n  )\n  const isFetchAction = Boolean(\n    actionId !== undefined &&\n      typeof actionId === 'string' &&\n      req.method === 'POST'\n  )\n\n  const isPossibleServerAction = Boolean(\n    isFetchAction || isURLEncodedAction || isMultipartAction\n  )\n\n  return {\n    actionId,\n    isURLEncodedAction,\n    isMultipartAction,\n    isFetchAction,\n    isPossibleServerAction,\n  }\n}\n\nexport function getIsPossibleServerAction(\n  req: IncomingMessage | BaseNextRequest | NextRequest\n): boolean {\n  return getServerActionRequestMetadata(req).isPossibleServerAction\n}\n","import type { AppRouteRouteModule } from './app-route/module'\nimport type { AppPageRouteModule } from './app-page/module'\nimport type { PagesRouteModule } from './pages/module'\nimport type { PagesAPIRouteModule } from './pages-api/module'\n\nimport type { RouteModule } from './route-module'\n\nimport { RouteKind } from '../route-kind'\n\nexport function isAppRouteRouteModule(\n  routeModule: RouteModule\n): routeModule is AppRouteRouteModule {\n  return routeModule.definition.kind === RouteKind.APP_ROUTE\n}\n\nexport function isAppPageRouteModule(\n  routeModule: RouteModule\n): routeModule is AppPageRouteModule {\n  return routeModule.definition.kind === RouteKind.APP_PAGE\n}\n\nexport function isPagesRouteModule(\n  routeModule: RouteModule\n): routeModule is PagesRouteModule {\n  return routeModule.definition.kind === RouteKind.PAGES\n}\n\nexport function isPagesAPIRouteModule(\n  routeModule: RouteModule\n): routeModule is PagesAPIRouteModule {\n  return routeModule.definition.kind === RouteKind.PAGES_API\n}\n","import { resolveRouteParamsFromTree } from '../../build/static-paths/utils'\nimport type { FallbackRouteParam } from '../../build/static-paths/types'\nimport type { DynamicParamTypesShort } from '../../shared/lib/app-router-types'\nimport { dynamicParamTypes } from '../app-render/get-short-dynamic-param-type'\nimport type AppPageRouteModule from '../route-modules/app-page/module'\nimport { parseAppRoute } from '../../shared/lib/router/routes/app'\nimport { extractPathnameRouteParamSegmentsFromLoaderTree } from '../../build/static-paths/app/extract-pathname-route-param-segments-from-loader-tree'\n\nexport type OpaqueFallbackRouteParamValue = [\n  /**\n   * The search value of the fallback route param. This is the opaque key\n   * that will be used to replace the dynamic param in the postponed state.\n   */\n  searchValue: string,\n\n  /**\n   * The dynamic param type of the fallback route param. This is the type of\n   * the dynamic param that will be used to replace the dynamic param in the\n   * postponed state.\n   */\n  dynamicParamType: DynamicParamTypesShort,\n]\n\n/**\n * An opaque fallback route params object. This is used to store the fallback\n * route params in a way that is not easily accessible to the client.\n */\nexport type OpaqueFallbackRouteParams = ReadonlyMap<\n  string,\n  OpaqueFallbackRouteParamValue\n>\n\n/**\n * The entries of the opaque fallback route params object.\n *\n * @param key the key of the fallback route param\n * @param value the value of the fallback route param\n */\nexport type OpaqueFallbackRouteParamEntries =\n  ReturnType<OpaqueFallbackRouteParams['entries']> extends MapIterator<\n    [infer K, infer V]\n  >\n    ? ReadonlyArray<[K, V]>\n    : never\n\n/**\n * Creates an opaque fallback route params object from the fallback route params.\n *\n * @param fallbackRouteParams the fallback route params\n * @returns the opaque fallback route params\n */\nexport function createOpaqueFallbackRouteParams(\n  fallbackRouteParams: readonly FallbackRouteParam[]\n): OpaqueFallbackRouteParams | null {\n  // If there are no fallback route params, we can return early.\n  if (fallbackRouteParams.length === 0) return null\n\n  // As we're creating unique keys for each of the dynamic route params, we only\n  // need to generate a unique ID once per request because each of the keys will\n  // be also be unique.\n  const uniqueID = Math.random().toString(16).slice(2)\n\n  const keys = new Map<string, OpaqueFallbackRouteParamValue>()\n\n  // Generate a unique key for the fallback route param, if this key is found\n  // in the static output, it represents a bug in cache components.\n  for (const { paramName, paramType } of fallbackRouteParams) {\n    keys.set(paramName, [\n      `%%drp:${paramName}:${uniqueID}%%`,\n      dynamicParamTypes[paramType],\n    ])\n  }\n\n  return keys\n}\n\n/**\n * Gets the fallback route params for a given page. This is an expensive\n * operation because it requires parsing the loader tree to extract the fallback\n * route params.\n *\n * @param page the page\n * @param routeModule the route module\n * @returns the opaque fallback route params\n */\nexport function getFallbackRouteParams(\n  page: string,\n  routeModule: AppPageRouteModule\n) {\n  const route = parseAppRoute(page, true)\n\n  // Extract the pathname-contributing segments from the loader tree. This\n  // mirrors the logic in buildAppStaticPaths where we determine which segments\n  // actually contribute to the pathname.\n  const { pathnameRouteParamSegments, params } =\n    extractPathnameRouteParamSegmentsFromLoaderTree(\n      routeModule.userland.loaderTree,\n      route\n    )\n\n  // Create fallback route params for the pathname segments.\n  const fallbackRouteParams: FallbackRouteParam[] =\n    pathnameRouteParamSegments.map(({ paramName, paramType }) => ({\n      paramName,\n      paramType,\n    }))\n\n  // Resolve route params from the loader tree. This mutates the\n  // fallbackRouteParams array to add any route params that are\n  // unknown at request time.\n  //\n  // The page parameter contains placeholders like [slug], which helps\n  // resolveRouteParamsFromTree determine which params are unknown.\n  resolveRouteParamsFromTree(\n    routeModule.userland.loaderTree,\n    params, // Static params extracted from the page\n    route, // The page pattern with placeholders\n    fallbackRouteParams // Will be mutated to add route params\n  )\n\n  // Convert the fallback route params to an opaque format that can be safely\n  // used in the postponed state without exposing implementation details.\n  return createOpaqueFallbackRouteParams(fallbackRouteParams)\n}\n","import path from 'path'\nimport {\n  PAGES_MANIFEST,\n  SERVER_DIRECTORY,\n  APP_PATHS_MANIFEST,\n} from '../shared/lib/constants'\nimport { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'\nimport type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'\nimport { PageNotFoundError, MissingStaticPage } from '../shared/lib/utils'\nimport { LRUCache } from '../server/lib/lru-cache'\nimport { loadManifest } from './load-manifest.external'\nimport { promises } from 'fs'\n\nconst isDev = process.env.NODE_ENV === 'development'\nconst pagePathCache = !isDev ? new LRUCache<string | null>(1000) : null\n\nexport function getMaybePagePath(\n  page: string,\n  distDir: string,\n  locales: readonly string[] | undefined,\n  isAppPath: boolean\n): string | null {\n  const cacheKey = `${page}:${distDir}:${locales}:${isAppPath}`\n\n  let pagePath = pagePathCache?.get(cacheKey)\n\n  // If we have a cached path, we can return it directly.\n  if (pagePath) return pagePath\n\n  const serverBuildPath = path.join(\n    /* turbopackIgnore: true */ distDir,\n    SERVER_DIRECTORY\n  )\n  let appPathsManifest: undefined | PagesManifest\n\n  if (isAppPath) {\n    appPathsManifest = loadManifest(\n      path.join(\n        /* turbopackIgnore: true */ serverBuildPath,\n        APP_PATHS_MANIFEST\n      ),\n      !isDev\n    ) as PagesManifest\n  }\n  const pagesManifest = loadManifest(\n    path.join(/* turbopackIgnore: true */ serverBuildPath, PAGES_MANIFEST),\n    !isDev\n  ) as PagesManifest\n\n  try {\n    page = denormalizePagePath(normalizePagePath(page))\n  } catch (err) {\n    console.error(err)\n    throw new PageNotFoundError(page)\n  }\n\n  const checkManifest = (manifest: PagesManifest) => {\n    let curPath = manifest[page]\n\n    if (!manifest[curPath] && locales) {\n      const manifestNoLocales: typeof pagesManifest = {}\n\n      for (const key of Object.keys(manifest)) {\n        manifestNoLocales[normalizeLocalePath(key, locales).pathname] =\n          pagesManifest[key]\n      }\n      curPath = manifestNoLocales[page]\n    }\n    return curPath\n  }\n\n  if (appPathsManifest) {\n    pagePath = checkManifest(appPathsManifest)\n  }\n\n  if (!pagePath) {\n    pagePath = checkManifest(pagesManifest)\n  }\n\n  if (!pagePath) {\n    pagePathCache?.set(cacheKey, null)\n    return null\n  }\n\n  // Handle absolute paths (e.g., built-in components)\n  if (path.isAbsolute(pagePath)) {\n    // Use the absolute path as-is\n    pagePathCache?.set(cacheKey, pagePath)\n    return pagePath\n  }\n\n  pagePath = path.join(/* turbopackIgnore: true */ serverBuildPath, pagePath)\n\n  pagePathCache?.set(cacheKey, pagePath)\n  return pagePath\n}\n\nexport function getPagePath(\n  page: string,\n  distDir: string,\n  locales: string[] | undefined,\n  isAppPath: boolean\n): string {\n  const pagePath = getMaybePagePath(page, distDir, locales, isAppPath)\n\n  if (!pagePath) {\n    throw new PageNotFoundError(page)\n  }\n\n  return pagePath\n}\n\nexport async function requirePage(\n  page: string,\n  distDir: string,\n  isAppPath: boolean\n): Promise<any> {\n  const pagePath = getPagePath(page, distDir, undefined, isAppPath)\n  if (pagePath.endsWith('.html')) {\n    return promises\n      .readFile(/* turbopackIgnore: true */ pagePath, 'utf8')\n      .catch((err) => {\n        throw new MissingStaticPage(page, err.message)\n      })\n  }\n\n  const mod = process.env.NEXT_MINIMAL\n    ? // @ts-ignore\n      __non_webpack_require__(pagePath)\n    : require(/* turbopackIgnore: true */ pagePath)\n  return mod\n}\n","export function interopDefault<T>(mod: { default: T } | T): T {\n  // @ts-ignore\n  return mod.default || mod\n}\n","/**\n * Wait for a given number of milliseconds and then resolve.\n *\n * @param ms the number of milliseconds to wait\n */\nexport async function wait(ms: number) {\n  return new Promise((resolve) => setTimeout(resolve, ms))\n}\n","import type { ActionManifest } from '../../build/webpack/plugins/flight-client-entry-plugin'\nimport type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'\nimport type { DeepReadonly } from '../../shared/lib/deep-readonly'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { workAsyncStorage } from './work-async-storage.external'\n\nexport interface ServerModuleMap {\n  readonly [name: string]: {\n    readonly id: string | number\n    readonly name: string\n    readonly chunks: Readonly<Array<string>> // currently not used\n    readonly async?: boolean\n  }\n}\n\n// This is a global singleton that is, among other things, also used to\n// encode/decode bound args of server function closures. This can't be using a\n// AsyncLocalStorage as it might happen at the module level.\nconst MANIFESTS_SINGLETON = Symbol.for('next.server.manifests')\n\ninterface ManifestsSingleton {\n  readonly clientReferenceManifestsPerRoute: Map<\n    string,\n    DeepReadonly<ClientReferenceManifest>\n  >\n  readonly proxiedClientReferenceManifest: DeepReadonly<ClientReferenceManifest>\n  serverActionsManifest: DeepReadonly<ActionManifest>\n  serverModuleMap: ServerModuleMap\n}\n\ntype GlobalThisWithManifests = typeof globalThis & {\n  [MANIFESTS_SINGLETON]?: ManifestsSingleton\n}\n\ntype ClientReferenceManifestMappingProp =\n  | 'clientModules'\n  | 'rscModuleMapping'\n  | 'edgeRscModuleMapping'\n  | 'ssrModuleMapping'\n  | 'edgeSSRModuleMapping'\n\nconst globalThisWithManifests = globalThis as GlobalThisWithManifests\n\nfunction createProxiedClientReferenceManifest(\n  clientReferenceManifestsPerRoute: Map<\n    string,\n    DeepReadonly<ClientReferenceManifest>\n  >\n): DeepReadonly<ClientReferenceManifest> {\n  const createMappingProxy = (prop: ClientReferenceManifestMappingProp) => {\n    return new Proxy(\n      {},\n      {\n        get(_, id: string) {\n          const workStore = workAsyncStorage.getStore()\n\n          if (workStore) {\n            const currentManifest = clientReferenceManifestsPerRoute.get(\n              workStore.route\n            )\n\n            if (currentManifest?.[prop][id]) {\n              return currentManifest[prop][id]\n            }\n\n            // In development, we also check all other manifests to see if the\n            // module exists there. This is to support a scenario where React's\n            // I/O tracking (dev-only) creates a connection from one page to\n            // another through an emitted async I/O node that references client\n            // components from the other page, e.g. in owner props.\n            // TODO: Maybe we need to add a `debugBundlerConfig` option to React\n            // to avoid this workaround. The current workaround has the\n            // disadvantage that one might accidentally or intentionally share\n            // client references across pages (e.g. by storing them in a global\n            // variable), which would then only be caught in production.\n            if (process.env.NODE_ENV !== 'production') {\n              for (const [\n                route,\n                manifest,\n              ] of clientReferenceManifestsPerRoute) {\n                if (route === workStore.route) {\n                  continue\n                }\n\n                const entry = manifest[prop][id]\n\n                if (entry !== undefined) {\n                  return entry\n                }\n              }\n            }\n          } else {\n            // If there's no work store defined, we can assume that a client\n            // reference manifest is needed during module evaluation, e.g. to\n            // create a server function using a higher-order function. This\n            // might also use client components which need to be serialized by\n            // Flight, and therefore client references need to be resolvable. In\n            // that case we search all page manifests to find the module.\n            for (const manifest of clientReferenceManifestsPerRoute.values()) {\n              const entry = manifest[prop][id]\n\n              if (entry !== undefined) {\n                return entry\n              }\n            }\n          }\n\n          return undefined\n        },\n      }\n    )\n  }\n\n  const mappingProxies = new Map<\n    ClientReferenceManifestMappingProp,\n    ReturnType<typeof createMappingProxy>\n  >()\n\n  return new Proxy(\n    {},\n    {\n      get(_, prop) {\n        const workStore = workAsyncStorage.getStore()\n\n        switch (prop) {\n          case 'moduleLoading':\n          case 'entryCSSFiles':\n          case 'entryJSFiles': {\n            if (!workStore) {\n              throw new InvariantError(\n                `Cannot access \"${prop}\" without a work store.`\n              )\n            }\n\n            const currentManifest = clientReferenceManifestsPerRoute.get(\n              workStore.route\n            )\n\n            if (!currentManifest) {\n              throw new InvariantError(\n                `The client reference manifest for route \"${workStore.route}\" does not exist.`\n              )\n            }\n\n            return currentManifest[prop]\n          }\n          case 'clientModules':\n          case 'rscModuleMapping':\n          case 'edgeRscModuleMapping':\n          case 'ssrModuleMapping':\n          case 'edgeSSRModuleMapping': {\n            let proxy = mappingProxies.get(prop)\n\n            if (!proxy) {\n              proxy = createMappingProxy(prop)\n              mappingProxies.set(prop, proxy)\n            }\n\n            return proxy\n          }\n          default: {\n            throw new InvariantError(\n              `This is a proxied client reference manifest. The property \"${String(prop)}\" is not handled.`\n            )\n          }\n        }\n      },\n    }\n  ) as DeepReadonly<ClientReferenceManifest>\n}\n\n/**\n * This function creates a Flight-acceptable server module map proxy from our\n * Server Reference Manifest similar to our client module map. This is because\n * our manifest contains a lot of internal Next.js data that are relevant to the\n * runtime, workers, etc. that React doesn't need to know.\n */\nfunction createServerModuleMap(): ServerModuleMap {\n  return new Proxy(\n    {},\n    {\n      get: (_, id: string) => {\n        const workers =\n          getServerActionsManifest()[\n            process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'\n          ]?.[id]?.workers\n\n        if (!workers) {\n          return undefined\n        }\n\n        const workStore = workAsyncStorage.getStore()\n\n        let workerEntry:\n          | { moduleId: string | number; async: boolean }\n          | undefined\n\n        if (workStore) {\n          workerEntry = workers[normalizeWorkerPageName(workStore.page)]\n        } else {\n          // If there's no work store defined, we can assume that a server\n          // module map is needed during module evaluation, e.g. to create a\n          // server action using a higher-order function. Therefore it should be\n          // safe to return any entry from the manifest that matches the action\n          // ID. They all refer to the same module ID, which must also exist in\n          // the current page bundle. TODO: This is currently not guaranteed in\n          // Turbopack, and needs to be fixed.\n          workerEntry = Object.values(workers).at(0)\n        }\n\n        if (!workerEntry) {\n          return undefined\n        }\n\n        const { moduleId, async } = workerEntry\n\n        return { id: moduleId, name: id, chunks: [], async }\n      },\n    }\n  )\n}\n\n/**\n * The flight entry loader keys actions by bundlePath. bundlePath corresponds\n * with the relative path (including 'app') to the page entrypoint.\n */\nfunction normalizeWorkerPageName(pageName: string) {\n  if (pathHasPrefix(pageName, 'app')) {\n    return pageName\n  }\n\n  return 'app' + pageName\n}\n\n/**\n * Converts a bundlePath (relative path to the entrypoint) to a routable page\n * name.\n */\nfunction denormalizeWorkerPageName(bundlePath: string) {\n  return normalizeAppPath(removePathPrefix(bundlePath, 'app'))\n}\n\n/**\n * Checks if the requested action has a worker for the current page.\n * If not, it returns the first worker that has a handler for the action.\n */\nexport function selectWorkerForForwarding(\n  actionId: string,\n  pageName: string\n): string | undefined {\n  const serverActionsManifest = getServerActionsManifest()\n  const workers =\n    serverActionsManifest[\n      process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'\n    ][actionId]?.workers\n\n  // There are no workers to handle this action, nothing to forward to.\n  if (!workers) {\n    return\n  }\n\n  // If there is an entry for the current page, we don't need to forward.\n  if (workers[normalizeWorkerPageName(pageName)]) {\n    return\n  }\n\n  // Otherwise, grab the first worker that has a handler for this action id.\n  return denormalizeWorkerPageName(Object.keys(workers)[0])\n}\n\nexport function setManifestsSingleton({\n  page,\n  clientReferenceManifest,\n  serverActionsManifest: rawServerActionsManifest,\n}: {\n  page: string\n  clientReferenceManifest: DeepReadonly<ClientReferenceManifest>\n  serverActionsManifest: DeepReadonly<ActionManifest>\n}) {\n  const existingSingleton = globalThisWithManifests[MANIFESTS_SINGLETON]\n\n  const serverActionsManifest: DeepReadonly<ActionManifest> = {\n    encryptionKey: rawServerActionsManifest.encryptionKey,\n    // Use null-prototypes for the action objects to prevent prototype pollution\n    // from affecting action ID lookups.\n    node: Object.assign(Object.create(null), rawServerActionsManifest.node),\n    edge: Object.assign(Object.create(null), rawServerActionsManifest.edge),\n  }\n\n  if (existingSingleton) {\n    existingSingleton.clientReferenceManifestsPerRoute.set(\n      normalizeAppPath(page),\n      clientReferenceManifest\n    )\n\n    existingSingleton.serverActionsManifest = serverActionsManifest\n  } else {\n    const clientReferenceManifestsPerRoute = new Map<\n      string,\n      DeepReadonly<ClientReferenceManifest>\n    >([[normalizeAppPath(page), clientReferenceManifest]])\n\n    const proxiedClientReferenceManifest = createProxiedClientReferenceManifest(\n      clientReferenceManifestsPerRoute\n    )\n\n    globalThisWithManifests[MANIFESTS_SINGLETON] = {\n      clientReferenceManifestsPerRoute,\n      proxiedClientReferenceManifest,\n      serverActionsManifest,\n      serverModuleMap: createServerModuleMap(),\n    }\n  }\n}\n\nfunction getManifestsSingleton(): ManifestsSingleton {\n  const manifestSingleton = globalThisWithManifests[MANIFESTS_SINGLETON]\n\n  if (!manifestSingleton) {\n    throw new InvariantError('The manifests singleton was not initialized.')\n  }\n\n  return manifestSingleton\n}\n\nexport function getClientReferenceManifest(): DeepReadonly<ClientReferenceManifest> {\n  return getManifestsSingleton().proxiedClientReferenceManifest\n}\n\nexport function getServerActionsManifest(): DeepReadonly<ActionManifest> {\n  return getManifestsSingleton().serverActionsManifest\n}\n\nexport function getServerModuleMap() {\n  return getManifestsSingleton().serverModuleMap\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type {\n  AppType,\n  DocumentType,\n  NextComponentType,\n} from '../shared/lib/utils'\nimport type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'\nimport type {\n  PageConfig,\n  GetStaticPaths,\n  GetServerSideProps,\n  GetStaticProps,\n} from '../types'\nimport type { RouteModule } from './route-modules/route-module'\nimport type { BuildManifest } from './get-page-files'\nimport type { ActionManifest } from '../build/webpack/plugins/flight-client-entry-plugin'\n\nimport {\n  BUILD_MANIFEST,\n  REACT_LOADABLE_MANIFEST,\n  CLIENT_REFERENCE_MANIFEST,\n  SERVER_REFERENCE_MANIFEST,\n  DYNAMIC_CSS_MANIFEST,\n  SUBRESOURCE_INTEGRITY_MANIFEST,\n} from '../shared/lib/constants'\nimport { join } from 'path'\nimport { requirePage } from './require'\nimport { interopDefault } from '../lib/interop-default'\nimport { getTracer } from './lib/trace/tracer'\nimport { LoadComponentsSpan } from './lib/trace/constants'\nimport { evalManifest, loadManifest } from './load-manifest.external'\nimport { wait } from '../lib/wait'\nimport { setManifestsSingleton } from './app-render/manifests-singleton'\nimport type { DeepReadonly } from '../shared/lib/deep-readonly'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { isStaticMetadataRoute } from '../lib/metadata/is-metadata-route'\n\nexport type ManifestItem = {\n  id: number | string\n  files: string[]\n}\n\nexport type ReactLoadableManifest = { [moduleId: string]: ManifestItem }\n/**\n * This manifest prevents removing server rendered <link> tags after client\n * navigation. This is only needed under `Pages dir && Production && Webpack`.\n * @see https://github.com/vercel/next.js/pull/72959\n */\nexport type DynamicCssManifest = string[]\n\n/**\n * A manifest entry type for the react-loadable-manifest.json.\n *\n * The whole manifest.json is a type of `Record<pathname, LoadableManifest>`\n * where pathname is a string-based key points to the path of the page contains\n * each dynamic imports.\n */\nexport interface LoadableManifest {\n  [k: string]: { id: string | number; files: string[] }\n}\n\nexport type GenericComponentMod = {\n  handler(\n    req: IncomingMessage,\n    res: ServerResponse,\n    ctx: {\n      waitUntil?: (prom: Promise<void>) => void\n    }\n  ): Promise<void | null>\n}\n\nexport type LoadComponentsReturnType<\n  NextModule extends GenericComponentMod = GenericComponentMod,\n> = {\n  Component: NextComponentType\n  pageConfig: PageConfig\n  buildManifest: DeepReadonly<BuildManifest>\n  subresourceIntegrityManifest?: DeepReadonly<Record<string, string>>\n  reactLoadableManifest: DeepReadonly<ReactLoadableManifest>\n  dynamicCssManifest?: DeepReadonly<DynamicCssManifest>\n  Document: DocumentType\n  App: AppType\n  getStaticProps?: GetStaticProps\n  getStaticPaths?: GetStaticPaths\n  getServerSideProps?: GetServerSideProps\n  ComponentMod: NextModule\n  routeModule: RouteModule\n  isAppPath?: boolean\n  page: string\n  multiZoneDraftMode?: boolean\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts.\n */\nexport async function loadManifestWithRetries<T extends object>(\n  manifestPath: string,\n  attempts = 3\n) {\n  while (true) {\n    try {\n      return loadManifest<T>(manifestPath)\n    } catch (err) {\n      attempts--\n      if (attempts <= 0) throw err\n\n      await wait(100)\n    }\n  }\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts, or return undefined.\n */\nexport async function tryLoadManifestWithRetries<T extends object>(\n  manifestPath: string,\n  attempts = 3\n) {\n  try {\n    return await loadManifestWithRetries<T>(manifestPath, attempts)\n  } catch (err) {\n    return undefined\n  }\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts.\n */\nexport async function evalManifestWithRetries<T extends object>(\n  manifestPath: string,\n  attempts = 3\n) {\n  while (true) {\n    try {\n      return evalManifest<T>(manifestPath)\n    } catch (err) {\n      attempts--\n      if (attempts <= 0) throw err\n\n      await wait(100)\n    }\n  }\n}\n\nasync function tryLoadClientReferenceManifest(\n  manifestPath: string,\n  entryName: string,\n  attempts?: number\n): Promise<DeepReadonly<ClientReferenceManifest> | undefined> {\n  try {\n    const context = await evalManifestWithRetries<{\n      __RSC_MANIFEST: { [key: string]: ClientReferenceManifest }\n    }>(manifestPath, attempts)\n    return context.__RSC_MANIFEST[entryName]\n  } catch (err) {\n    return undefined\n  }\n}\n\nasync function loadComponentsImpl<\n  N extends GenericComponentMod = GenericComponentMod,\n>({\n  distDir,\n  page,\n  isAppPath,\n  isDev,\n  sriEnabled,\n  // When route modules are used, which is the case for the server calls to loadComponents, it no longer needs manifest to be loaded here.\n  // Static generation still needs the manifests to be loaded here.\n  // In the future static generation will also use route modules, and we will remove this flag.\n  needsManifestsForLegacyReasons,\n}: {\n  distDir: string\n  page: string\n  isAppPath: boolean\n  isDev: boolean\n  sriEnabled: boolean\n  needsManifestsForLegacyReasons: boolean\n}): Promise<LoadComponentsReturnType<N>> {\n  let DocumentMod = {}\n  let AppMod = {}\n  if (!isAppPath) {\n    ;[DocumentMod, AppMod] = await Promise.all([\n      requirePage('/_document', distDir, false),\n      requirePage('/_app', distDir, false),\n    ])\n  }\n\n  if (needsManifestsForLegacyReasons) {\n    // In dev mode we retry loading a manifest file to handle a race condition\n    // that can occur while app and pages are compiling at the same time, and the\n    // build-manifest is still being written to disk while an app path is\n    // attempting to load.\n    const manifestLoadAttempts = isDev ? 3 : 1\n\n    let reactLoadableManifestPath: string\n    if (!process.env.TURBOPACK) {\n      reactLoadableManifestPath = join(\n        /* turbopackIgnore: true */ distDir,\n        REACT_LOADABLE_MANIFEST\n      )\n    } else if (isAppPath) {\n      reactLoadableManifestPath = join(\n        /* turbopackIgnore: true */ distDir,\n        'server',\n        'app',\n        page,\n        REACT_LOADABLE_MANIFEST\n      )\n    } else {\n      reactLoadableManifestPath = join(\n        /* turbopackIgnore: true */ distDir,\n        'server',\n        'pages',\n        normalizePagePath(page),\n        REACT_LOADABLE_MANIFEST\n      )\n    }\n\n    // Make sure to avoid loading the manifest for static metadata routes for better performance.\n    const hasClientManifest = !isStaticMetadataRoute(page)\n\n    // Load the manifest files first\n    //\n    // Loading page-specific manifests shouldn't throw an error if the manifest couldn't be found, so\n    // that the `requirePage` call below will throw the correct error in that case\n    // (a `PageNotFoundError`).\n    const [\n      buildManifest,\n      reactLoadableManifest,\n      dynamicCssManifest,\n      clientReferenceManifest,\n      serverActionsManifest,\n      subresourceIntegrityManifest,\n    ] = await Promise.all([\n      loadManifestWithRetries<BuildManifest>(\n        join(/* turbopackIgnore: true */ distDir, BUILD_MANIFEST),\n        manifestLoadAttempts\n      ),\n      tryLoadManifestWithRetries<ReactLoadableManifest>(\n        reactLoadableManifestPath,\n        manifestLoadAttempts\n      ),\n      // This manifest will only exist in Pages dir && Production && Webpack.\n      isAppPath || process.env.TURBOPACK\n        ? undefined\n        : loadManifestWithRetries<DynamicCssManifest>(\n            join(\n              /* turbopackIgnore: true */ distDir,\n              `${DYNAMIC_CSS_MANIFEST}.json`\n            ),\n            manifestLoadAttempts\n          ).catch(() => undefined),\n      isAppPath && hasClientManifest\n        ? tryLoadClientReferenceManifest(\n            join(\n              /* turbopackIgnore: true */ distDir,\n              'server',\n              'app',\n              page.replace(/%5F/g, '_') +\n                '_' +\n                CLIENT_REFERENCE_MANIFEST +\n                '.js'\n            ),\n            page.replace(/%5F/g, '_'),\n            manifestLoadAttempts\n          )\n        : undefined,\n      isAppPath\n        ? loadManifestWithRetries<ActionManifest>(\n            join(\n              /* turbopackIgnore: true */ distDir,\n              'server',\n              SERVER_REFERENCE_MANIFEST + '.json'\n            ),\n            manifestLoadAttempts\n          ).catch(() => null)\n        : null,\n      sriEnabled\n        ? loadManifestWithRetries<DeepReadonly<Record<string, string>>>(\n            join(\n              /* turbopackIgnore: true */ distDir,\n              'server',\n              SUBRESOURCE_INTEGRITY_MANIFEST + '.json'\n            )\n          ).catch(() => undefined)\n        : undefined,\n    ])\n\n    // Before requiring the actual page module, we have to set the reference\n    // manifests to our global store so Server Action's encryption util can access\n    // to them at the top level of the page module.\n    if (serverActionsManifest && clientReferenceManifest) {\n      setManifestsSingleton({\n        page,\n        clientReferenceManifest,\n        serverActionsManifest,\n      })\n    }\n\n    const ComponentMod = await requirePage(page, distDir, isAppPath)\n\n    const Component = interopDefault(ComponentMod)\n    const Document = interopDefault(DocumentMod)\n    const App = interopDefault(AppMod)\n\n    const { getServerSideProps, getStaticProps, getStaticPaths, routeModule } =\n      ComponentMod\n\n    return {\n      // @ts-expect-error this is indeed `{} || AppType` and not always `AppType`\n      App,\n      // @ts-expect-error this is indeed `{} || DocumentType` and not always `DocumentType`\n      Document,\n      Component,\n      buildManifest,\n      subresourceIntegrityManifest,\n      reactLoadableManifest: reactLoadableManifest || {},\n      dynamicCssManifest,\n      pageConfig: ComponentMod.config || {},\n      ComponentMod,\n      getServerSideProps,\n      getStaticProps,\n      getStaticPaths,\n      isAppPath,\n      page,\n      routeModule,\n    }\n  } else {\n    const ComponentMod = await requirePage(page, distDir, isAppPath)\n\n    const Component = interopDefault(ComponentMod)\n    const Document = interopDefault(DocumentMod)\n    const App = interopDefault(AppMod)\n\n    const { getServerSideProps, getStaticProps, getStaticPaths, routeModule } =\n      ComponentMod\n\n    return {\n      App,\n      Document,\n      Component,\n      pageConfig: ComponentMod.config || {},\n      ComponentMod,\n      getServerSideProps,\n      getStaticProps,\n      getStaticPaths,\n      isAppPath,\n      page,\n      routeModule,\n    } as any // temporary `as any` to make TypeScript not fail so that the tests will run on the PR.\n  }\n}\n\nexport const loadComponents = getTracer().wrap(\n  LoadComponentsSpan.loadComponents,\n  loadComponentsImpl\n)\n","import type { BaseNextRequest } from '../../../../server/base-http'\nimport type { ProxyMatcher } from '../../../../build/analysis/get-page-static-info'\nimport type { Params } from '../../../../server/request/params'\nimport { matchHas } from './prepare-destination'\n\nexport interface MiddlewareRouteMatch {\n  (\n    pathname: string | null | undefined,\n    request: BaseNextRequest,\n    query: Params\n  ): boolean\n}\n\nexport function getMiddlewareRouteMatcher(\n  matchers: ProxyMatcher[]\n): MiddlewareRouteMatch {\n  return (\n    pathname: string | null | undefined,\n    req: BaseNextRequest,\n    query: Params\n  ) => {\n    for (const matcher of matchers) {\n      const routeMatch = new RegExp(matcher.regexp).exec(pathname!)\n      if (!routeMatch) {\n        continue\n      }\n\n      if (matcher.has || matcher.missing) {\n        const hasParams = matchHas(req, query, matcher.has, matcher.missing)\n        if (!hasParams) {\n          continue\n        }\n      }\n\n      return true\n    }\n\n    return false\n  }\n}\n","import type {\n  ResponseCacheEntry,\n  ResponseGenerator,\n  ResponseCacheBase,\n  IncrementalResponseCacheEntry,\n  IncrementalResponseCache,\n} from './types'\n\nimport { Batcher } from '../../lib/batcher'\nimport { LRUCache } from '../lib/lru-cache'\nimport { warnOnce } from '../../build/output/log'\nimport { scheduleOnNextTick } from '../../lib/scheduler'\nimport {\n  fromResponseCacheEntry,\n  routeKindToIncrementalCacheKind,\n  toResponseCacheEntry,\n} from './utils'\nimport type { RouteKind } from '../route-kind'\n\n/**\n * Parses an environment variable as a positive integer, returning the fallback\n * if the value is missing, not a number, or not positive.\n */\nfunction parsePositiveInt(\n  envValue: string | undefined,\n  fallback: number\n): number {\n  if (!envValue) return fallback\n  const parsed = parseInt(envValue, 10)\n  return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback\n}\n\n/**\n * Default TTL (in milliseconds) for minimal mode response cache entries.\n * Used for cache hit validation as a fallback for providers that don't\n * send the x-invocation-id header yet.\n *\n * 10 seconds chosen because:\n * - Long enough to dedupe rapid successive requests (e.g., page + data)\n * - Short enough to not serve stale data across unrelated requests\n *\n * Can be configured via `NEXT_PRIVATE_RESPONSE_CACHE_TTL` environment variable.\n */\nconst DEFAULT_TTL_MS = parsePositiveInt(\n  process.env.NEXT_PRIVATE_RESPONSE_CACHE_TTL,\n  10_000\n)\n\n/**\n * Default maximum number of entries in the response cache.\n * Can be configured via `NEXT_PRIVATE_RESPONSE_CACHE_MAX_SIZE` environment variable.\n */\nconst DEFAULT_MAX_SIZE = parsePositiveInt(\n  process.env.NEXT_PRIVATE_RESPONSE_CACHE_MAX_SIZE,\n  150\n)\n\n/**\n * Separator used in compound cache keys to join pathname and invocationID.\n * Using null byte (\\0) since it cannot appear in valid URL paths or UUIDs.\n */\nconst KEY_SEPARATOR = '\\0'\n\n/**\n * Sentinel value used for TTL-based cache entries (when invocationID is undefined).\n * Chosen to be a clearly reserved marker for internal cache keys.\n */\nconst TTL_SENTINEL = '__ttl_sentinel__'\n\n/**\n * Entry stored in the LRU cache.\n */\ntype CacheEntry = {\n  entry: IncrementalResponseCacheEntry | null\n  /**\n   * TTL expiration timestamp in milliseconds. Used as a fallback for\n   * cache hit validation when providers don't send x-invocation-id.\n   * Memory pressure is managed by LRU eviction rather than timers.\n   */\n  expiresAt: number\n}\n\n/**\n * Creates a compound cache key from pathname and invocationID.\n */\nfunction createCacheKey(\n  pathname: string,\n  invocationID: string | undefined\n): string {\n  return `${pathname}${KEY_SEPARATOR}${invocationID ?? TTL_SENTINEL}`\n}\n\n/**\n * Extracts the invocationID from a compound cache key.\n * Returns undefined if the key used TTL_SENTINEL.\n */\nfunction extractInvocationID(compoundKey: string): string | undefined {\n  const separatorIndex = compoundKey.lastIndexOf(KEY_SEPARATOR)\n  if (separatorIndex === -1) return undefined\n\n  const invocationID = compoundKey.slice(separatorIndex + 1)\n  return invocationID === TTL_SENTINEL ? undefined : invocationID\n}\n\nexport * from './types'\n\nexport default class ResponseCache implements ResponseCacheBase {\n  private readonly getBatcher = Batcher.create<\n    { key: string; isOnDemandRevalidate: boolean },\n    IncrementalResponseCacheEntry | null,\n    string\n  >({\n    // Ensure on-demand revalidate doesn't block normal requests, it should be\n    // safe to run an on-demand revalidate for the same key as a normal request.\n    cacheKeyFn: ({ key, isOnDemandRevalidate }) =>\n      `${key}-${isOnDemandRevalidate ? '1' : '0'}`,\n    // We wait to do any async work until after we've added our promise to\n    // `pendingResponses` to ensure that any any other calls will reuse the\n    // same promise until we've fully finished our work.\n    schedulerFn: scheduleOnNextTick,\n  })\n\n  private readonly revalidateBatcher = Batcher.create<\n    string,\n    IncrementalResponseCacheEntry | null\n  >({\n    // We wait to do any async work until after we've added our promise to\n    // `pendingResponses` to ensure that any any other calls will reuse the\n    // same promise until we've fully finished our work.\n    schedulerFn: scheduleOnNextTick,\n  })\n\n  /**\n   * LRU cache for minimal mode using compound keys (pathname + invocationID).\n   * This allows multiple invocations to cache the same pathname without\n   * overwriting each other's entries.\n   */\n  private readonly cache: LRUCache<CacheEntry>\n\n  /**\n   * Set of invocation IDs that have had cache entries evicted.\n   * Used to detect when the cache size may be too small.\n   * Bounded to prevent memory growth.\n   */\n  private readonly evictedInvocationIDs: Set<string> = new Set()\n\n  /**\n   * The configured max size, stored for logging.\n   */\n  private readonly maxSize: number\n\n  /**\n   * The configured TTL for cache entries in milliseconds.\n   */\n  private readonly ttl: number\n\n  // we don't use minimal_mode name here as this.minimal_mode is\n  // statically replace for server runtimes but we need it to\n  // be dynamic here\n  private minimal_mode?: boolean\n\n  constructor(\n    minimal_mode: boolean,\n    maxSize: number = DEFAULT_MAX_SIZE,\n    ttl: number = DEFAULT_TTL_MS\n  ) {\n    this.minimal_mode = minimal_mode\n    this.maxSize = maxSize\n    this.ttl = ttl\n\n    // Create the LRU cache with eviction tracking\n    this.cache = new LRUCache(maxSize, undefined, (compoundKey) => {\n      const invocationID = extractInvocationID(compoundKey)\n      if (invocationID) {\n        // Bound to 100 entries to prevent unbounded memory growth.\n        // FIFO eviction is acceptable here because:\n        // 1. Invocations are short-lived (single request lifecycle), so older\n        //    invocations are unlikely to still be active after 100 newer ones\n        // 2. This warning mechanism is best-effort for developer guidance—\n        //    missing occasional eviction warnings doesn't affect correctness\n        // 3. If a long-running invocation is somehow evicted and then has\n        //    another cache entry evicted, it will simply be re-added\n        if (this.evictedInvocationIDs.size >= 100) {\n          const first = this.evictedInvocationIDs.values().next().value\n          if (first) this.evictedInvocationIDs.delete(first)\n        }\n        this.evictedInvocationIDs.add(invocationID)\n      }\n    })\n  }\n\n  /**\n   * Gets the response cache entry for the given key.\n   *\n   * @param key - The key to get the response cache entry for.\n   * @param responseGenerator - The response generator to use to generate the response cache entry.\n   * @param context - The context for the get request.\n   * @returns The response cache entry.\n   */\n  public async get(\n    key: string | null,\n    responseGenerator: ResponseGenerator,\n    context: {\n      routeKind: RouteKind\n      isOnDemandRevalidate?: boolean\n      isPrefetch?: boolean\n      incrementalCache: IncrementalResponseCache\n      isRoutePPREnabled?: boolean\n      isFallback?: boolean\n      waitUntil?: (prom: Promise<any>) => void\n\n      /**\n       * The invocation ID from the infrastructure. Used to scope the\n       * in-memory cache to a single revalidation request in minimal mode.\n       */\n      invocationID?: string\n    }\n  ): Promise<ResponseCacheEntry | null> {\n    // If there is no key for the cache, we can't possibly look this up in the\n    // cache so just return the result of the response generator.\n    if (!key) {\n      return responseGenerator({\n        hasResolved: false,\n        previousCacheEntry: null,\n      })\n    }\n\n    // Check minimal mode cache before doing any other work.\n    if (this.minimal_mode) {\n      const cacheKey = createCacheKey(key, context.invocationID)\n      const cachedItem = this.cache.get(cacheKey)\n\n      if (cachedItem) {\n        // With invocationID: exact match found - always a hit\n        // With TTL mode: must check expiration\n        if (context.invocationID !== undefined) {\n          return toResponseCacheEntry(cachedItem.entry)\n        }\n\n        // TTL mode: check expiration\n        const now = Date.now()\n        if (cachedItem.expiresAt > now) {\n          return toResponseCacheEntry(cachedItem.entry)\n        }\n\n        // TTL expired - clean up\n        this.cache.remove(cacheKey)\n      }\n\n      // Warn if this invocation had entries evicted - indicates cache may be too small.\n      if (\n        context.invocationID &&\n        this.evictedInvocationIDs.has(context.invocationID)\n      ) {\n        warnOnce(\n          `Response cache entry was evicted for invocation ${context.invocationID}. ` +\n            `Consider increasing NEXT_PRIVATE_RESPONSE_CACHE_MAX_SIZE (current: ${this.maxSize}).`\n        )\n      }\n    }\n\n    const {\n      incrementalCache,\n      isOnDemandRevalidate = false,\n      isFallback = false,\n      isRoutePPREnabled = false,\n      isPrefetch = false,\n      waitUntil,\n      routeKind,\n      invocationID,\n    } = context\n\n    const response = await this.getBatcher.batch(\n      { key, isOnDemandRevalidate },\n      ({ resolve }) => {\n        const promise = this.handleGet(\n          key,\n          responseGenerator,\n          {\n            incrementalCache,\n            isOnDemandRevalidate,\n            isFallback,\n            isRoutePPREnabled,\n            isPrefetch,\n            routeKind,\n            invocationID,\n          },\n          resolve\n        )\n\n        // We need to ensure background revalidates are passed to waitUntil.\n        if (waitUntil) waitUntil(promise)\n\n        return promise\n      }\n    )\n\n    return toResponseCacheEntry(response)\n  }\n\n  /**\n   * Handles the get request for the response cache.\n   *\n   * @param key - The key to get the response cache entry for.\n   * @param responseGenerator - The response generator to use to generate the response cache entry.\n   * @param context - The context for the get request.\n   * @param resolve - The resolve function to use to resolve the response cache entry.\n   * @returns The response cache entry.\n   */\n  private async handleGet(\n    key: string,\n    responseGenerator: ResponseGenerator,\n    context: {\n      incrementalCache: IncrementalResponseCache\n      isOnDemandRevalidate: boolean\n      isFallback: boolean\n      isRoutePPREnabled: boolean\n      isPrefetch: boolean\n      routeKind: RouteKind\n      invocationID: string | undefined\n    },\n    resolve: (value: IncrementalResponseCacheEntry | null) => void\n  ): Promise<IncrementalResponseCacheEntry | null> {\n    let previousIncrementalCacheEntry: IncrementalResponseCacheEntry | null =\n      null\n    let resolved = false\n\n    try {\n      // Get the previous cache entry if not in minimal mode\n      previousIncrementalCacheEntry = !this.minimal_mode\n        ? await context.incrementalCache.get(key, {\n            kind: routeKindToIncrementalCacheKind(context.routeKind),\n            isRoutePPREnabled: context.isRoutePPREnabled,\n            isFallback: context.isFallback,\n          })\n        : null\n\n      if (previousIncrementalCacheEntry && !context.isOnDemandRevalidate) {\n        resolve(previousIncrementalCacheEntry)\n        resolved = true\n\n        if (!previousIncrementalCacheEntry.isStale || context.isPrefetch) {\n          // The cached value is still valid, so we don't need to update it yet.\n          return previousIncrementalCacheEntry\n        }\n      }\n\n      // Revalidate the cache entry\n      const incrementalResponseCacheEntry = await this.revalidate(\n        key,\n        context.incrementalCache,\n        context.isRoutePPREnabled,\n        context.isFallback,\n        responseGenerator,\n        previousIncrementalCacheEntry,\n        previousIncrementalCacheEntry !== null && !context.isOnDemandRevalidate,\n        undefined,\n        context.invocationID\n      )\n\n      // Handle null response\n      if (!incrementalResponseCacheEntry) {\n        // Remove the cache item if it was set so we don't use it again.\n        if (this.minimal_mode) {\n          const cacheKey = createCacheKey(key, context.invocationID)\n          this.cache.remove(cacheKey)\n        }\n        return null\n      }\n\n      // Resolve for on-demand revalidation or if not already resolved\n      if (context.isOnDemandRevalidate && !resolved) {\n        return incrementalResponseCacheEntry\n      }\n\n      return incrementalResponseCacheEntry\n    } catch (err) {\n      // If we've already resolved the cache entry, we can't reject as we\n      // already resolved the cache entry so log the error here.\n      if (resolved) {\n        console.error(err)\n        return null\n      }\n\n      throw err\n    }\n  }\n\n  /**\n   * Revalidates the cache entry for the given key.\n   *\n   * @param key - The key to revalidate the cache entry for.\n   * @param incrementalCache - The incremental cache to use to revalidate the cache entry.\n   * @param isRoutePPREnabled - Whether the route is PPR enabled.\n   * @param isFallback - Whether the route is a fallback.\n   * @param responseGenerator - The response generator to use to generate the response cache entry.\n   * @param previousIncrementalCacheEntry - The previous cache entry to use to revalidate the cache entry.\n   * @param hasResolved - Whether the response has been resolved.\n   * @param waitUntil - Optional function to register background work.\n   * @param invocationID - The invocation ID for cache key scoping.\n   * @returns The revalidated cache entry.\n   */\n  public async revalidate(\n    key: string,\n    incrementalCache: IncrementalResponseCache,\n    isRoutePPREnabled: boolean,\n    isFallback: boolean,\n    responseGenerator: ResponseGenerator,\n    previousIncrementalCacheEntry: IncrementalResponseCacheEntry | null,\n    hasResolved: boolean,\n    waitUntil?: (prom: Promise<any>) => void,\n    invocationID?: string\n  ) {\n    return this.revalidateBatcher.batch(key, () => {\n      const promise = this.handleRevalidate(\n        key,\n        incrementalCache,\n        isRoutePPREnabled,\n        isFallback,\n        responseGenerator,\n        previousIncrementalCacheEntry,\n        hasResolved,\n        invocationID\n      )\n\n      // We need to ensure background revalidates are passed to waitUntil.\n      if (waitUntil) waitUntil(promise)\n\n      return promise\n    })\n  }\n\n  private async handleRevalidate(\n    key: string,\n    incrementalCache: IncrementalResponseCache,\n    isRoutePPREnabled: boolean,\n    isFallback: boolean,\n    responseGenerator: ResponseGenerator,\n    previousIncrementalCacheEntry: IncrementalResponseCacheEntry | null,\n    hasResolved: boolean,\n    invocationID: string | undefined\n  ) {\n    try {\n      // Generate the response cache entry using the response generator.\n      const responseCacheEntry = await responseGenerator({\n        hasResolved,\n        previousCacheEntry: previousIncrementalCacheEntry,\n        isRevalidating: true,\n      })\n      if (!responseCacheEntry) {\n        return null\n      }\n\n      // Convert the response cache entry to an incremental response cache entry.\n      const incrementalResponseCacheEntry = await fromResponseCacheEntry({\n        ...responseCacheEntry,\n        isMiss: !previousIncrementalCacheEntry,\n      })\n\n      // We want to persist the result only if it has a cache control value\n      // defined.\n      if (incrementalResponseCacheEntry.cacheControl) {\n        if (this.minimal_mode) {\n          // Set TTL expiration for cache hit validation. Entries are validated\n          // by invocationID when available, with TTL as a fallback for providers\n          // that don't send x-invocation-id. Memory is managed by LRU eviction.\n          const cacheKey = createCacheKey(key, invocationID)\n          this.cache.set(cacheKey, {\n            entry: incrementalResponseCacheEntry,\n            expiresAt: Date.now() + this.ttl,\n          })\n        } else {\n          await incrementalCache.set(key, incrementalResponseCacheEntry.value, {\n            cacheControl: incrementalResponseCacheEntry.cacheControl,\n            isRoutePPREnabled,\n            isFallback,\n          })\n        }\n      }\n\n      return incrementalResponseCacheEntry\n    } catch (err) {\n      // When a path is erroring we automatically re-set the existing cache\n      // with new revalidate and expire times to prevent non-stop retrying.\n      if (previousIncrementalCacheEntry?.cacheControl) {\n        const revalidate = Math.min(\n          Math.max(\n            previousIncrementalCacheEntry.cacheControl.revalidate || 3,\n            3\n          ),\n          30\n        )\n        const expire =\n          previousIncrementalCacheEntry.cacheControl.expire === undefined\n            ? undefined\n            : Math.max(\n                revalidate + 3,\n                previousIncrementalCacheEntry.cacheControl.expire\n              )\n\n        await incrementalCache.set(key, previousIncrementalCacheEntry.value, {\n          cacheControl: { revalidate: revalidate, expire: expire },\n          isRoutePPREnabled,\n          isFallback,\n        })\n      }\n\n      // We haven't resolved yet, so let's throw to indicate an error.\n      throw err\n    }\n  }\n}\n","import path from '../shared/lib/isomorphic/path'\nimport type { CacheFs } from '../shared/lib/utils'\n\n/**\n * A task to be written.\n */\ntype Task = [\n  /**\n   * The directory to create.\n   */\n  directory: string,\n\n  /**\n   * The promise to create the directory.\n   */\n  mkdir: Promise<unknown>,\n\n  /**\n   * The promises to write the files that are dependent on the directory being\n   * created.\n   */\n  writeFile: Promise<unknown>[],\n]\n/**\n * MultiFileWriter is a utility for writing multiple files in parallel that\n * guarantees that all files will be written after their containing directory\n * is created, and that the directory will only be created once.\n */\nexport class MultiFileWriter {\n  /**\n   * The tasks to be written.\n   */\n  private readonly tasks: Task[] = []\n\n  constructor(\n    /**\n     * The file system methods to use.\n     */\n    private readonly fs: Pick<CacheFs, 'mkdir' | 'writeFile'>\n  ) {}\n\n  /**\n   * Finds or creates a task for a directory.\n   *\n   * @param directory - The directory to find or create a task for.\n   * @returns The task for the directory.\n   */\n  private findOrCreateTask(directory: string): Task {\n    // See if this directory already has a task to create it.\n    for (const task of this.tasks) {\n      if (task[0] === directory) {\n        return task\n      }\n    }\n\n    const promise = this.fs.mkdir(directory)\n\n    // Attach a catch handler so that it doesn't throw an unhandled promise\n    // rejection warning.\n    promise.catch(() => {})\n\n    // Otherwise, create a new task for this directory.\n    const task: Task = [directory, promise, []]\n    this.tasks.push(task)\n\n    return task\n  }\n\n  /**\n   * Appends a file to the writer to be written after its containing directory\n   * is created. The file writer should be awaited after all the files have been\n   * appended. Any async operation that occurs between appending and awaiting\n   * may cause an unhandled promise rejection warning and potentially crash the\n   * process.\n   *\n   * @param filePath - The path to the file to write.\n   * @param data - The data to write to the file.\n   */\n  public append(filePath: string, data: Buffer | string): void {\n    // Find or create a task for the directory that contains the file.\n    const task = this.findOrCreateTask(path.dirname(filePath))\n\n    const promise = task[1].then(() => this.fs.writeFile(filePath, data))\n\n    // Attach a catch handler so that it doesn't throw an unhandled promise\n    // rejection warning.\n    promise.catch(() => {})\n\n    // Add the file write to the task AFTER the directory promise has resolved.\n    task[2].push(promise)\n  }\n\n  /**\n   * Returns a promise that resolves when all the files have been written.\n   */\n  public wait(): Promise<unknown> {\n    return Promise.all(this.tasks.flatMap((task) => task[2]))\n  }\n}\n","import type { RouteMetadata } from '../../../export/routes/types'\nimport type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from '.'\nimport type { CacheFs } from '../../../shared/lib/utils'\nimport type { TagManifestEntry } from './tags-manifest.external'\nimport {\n  CachedRouteKind,\n  IncrementalCacheKind,\n  type CachedFetchValue,\n  type IncrementalCacheValue,\n  type SetIncrementalFetchCacheContext,\n  type SetIncrementalResponseCacheContext,\n} from '../../response-cache'\n\nimport type { LRUCache } from '../lru-cache'\nimport path from '../../../shared/lib/isomorphic/path'\nimport {\n  NEXT_CACHE_TAGS_HEADER,\n  NEXT_DATA_SUFFIX,\n  NEXT_META_SUFFIX,\n  RSC_SEGMENT_SUFFIX,\n  RSC_SEGMENTS_DIR_SUFFIX,\n  RSC_SUFFIX,\n} from '../../../lib/constants'\nimport { areTagsExpired, tagsManifest } from './tags-manifest.external'\nimport { MultiFileWriter } from '../../../lib/multi-file-writer'\nimport { getMemoryCache } from './memory-cache.external'\n\ntype FileSystemCacheContext = Omit<\n  CacheHandlerContext,\n  'fs' | 'serverDistDir'\n> & {\n  fs: CacheFs\n  serverDistDir: string\n}\n\nexport default class FileSystemCache implements CacheHandler {\n  private fs: FileSystemCacheContext['fs']\n  private flushToDisk?: FileSystemCacheContext['flushToDisk']\n  private serverDistDir: FileSystemCacheContext['serverDistDir']\n  private revalidatedTags: string[]\n  private static debug: boolean = !!process.env.NEXT_PRIVATE_DEBUG_CACHE\n  private static memoryCache: LRUCache<CacheHandlerValue> | undefined\n\n  constructor(ctx: FileSystemCacheContext) {\n    this.fs = ctx.fs\n    this.flushToDisk = ctx.flushToDisk\n    this.serverDistDir = ctx.serverDistDir\n    this.revalidatedTags = ctx.revalidatedTags\n\n    if (ctx.maxMemoryCacheSize) {\n      if (!FileSystemCache.memoryCache) {\n        if (FileSystemCache.debug) {\n          console.log('FileSystemCache: using memory store for fetch cache')\n        }\n\n        FileSystemCache.memoryCache = getMemoryCache(ctx.maxMemoryCacheSize)\n      } else if (FileSystemCache.debug) {\n        console.log('FileSystemCache: memory store already initialized')\n      }\n    } else if (FileSystemCache.debug) {\n      console.log('FileSystemCache: not using memory store for fetch cache')\n    }\n  }\n\n  public resetRequestCache(): void {}\n\n  public async revalidateTag(\n    tags: string | string[],\n    durations?: { expire?: number }\n  ) {\n    tags = typeof tags === 'string' ? [tags] : tags\n\n    if (FileSystemCache.debug) {\n      console.log('FileSystemCache: revalidateTag', tags, durations)\n    }\n\n    if (tags.length === 0) {\n      return\n    }\n\n    const now = Date.now()\n\n    for (const tag of tags) {\n      const existingEntry = tagsManifest.get(tag) || {}\n\n      if (durations) {\n        // Use provided durations directly\n        const updates: TagManifestEntry = { ...existingEntry }\n\n        // mark as stale immediately\n        updates.stale = now\n\n        if (durations.expire !== undefined) {\n          updates.expired = now + durations.expire * 1000 // Convert seconds to ms\n        }\n\n        tagsManifest.set(tag, updates)\n      } else {\n        // Update expired field for immediate expiration (default behavior when no durations provided)\n        tagsManifest.set(tag, { ...existingEntry, expired: now })\n      }\n    }\n  }\n\n  public async get(...args: Parameters<CacheHandler['get']>) {\n    const [key, ctx] = args\n    const { kind } = ctx\n\n    let data = FileSystemCache.memoryCache?.get(key)\n\n    if (FileSystemCache.debug) {\n      if (kind === IncrementalCacheKind.FETCH) {\n        console.log('FileSystemCache: get', key, ctx.tags, kind, !!data)\n      } else {\n        console.log('FileSystemCache: get', key, kind, !!data)\n      }\n    }\n\n    // let's check the disk for seed data\n    if (!data && process.env.NEXT_RUNTIME !== 'edge') {\n      try {\n        if (kind === IncrementalCacheKind.APP_ROUTE) {\n          const filePath = this.getFilePath(\n            `${key}.body`,\n            IncrementalCacheKind.APP_ROUTE\n          )\n          const fileData = await this.fs.readFile(filePath)\n          const { mtime } = await this.fs.stat(filePath)\n\n          const meta = JSON.parse(\n            await this.fs.readFile(\n              filePath.replace(/\\.body$/, NEXT_META_SUFFIX),\n              'utf8'\n            )\n          )\n\n          data = {\n            lastModified: mtime.getTime(),\n            value: {\n              kind: CachedRouteKind.APP_ROUTE,\n              body: fileData,\n              headers: meta.headers,\n              status: meta.status,\n            },\n          }\n        } else {\n          const filePath = this.getFilePath(\n            kind === IncrementalCacheKind.FETCH ? key : `${key}.html`,\n            kind\n          )\n\n          const fileData = await this.fs.readFile(filePath, 'utf8')\n          const { mtime } = await this.fs.stat(filePath)\n\n          if (kind === IncrementalCacheKind.FETCH) {\n            const { tags, fetchIdx, fetchUrl } = ctx\n\n            if (!this.flushToDisk) return null\n\n            const lastModified = mtime.getTime()\n            const parsedData: CachedFetchValue = JSON.parse(fileData)\n            data = {\n              lastModified,\n              value: parsedData,\n            }\n\n            if (data.value?.kind === CachedRouteKind.FETCH) {\n              const storedTags = data.value?.tags\n\n              // update stored tags if a new one is being added\n              // TODO: remove this when we can send the tags\n              // via header on GET same as SET\n              if (!tags?.every((tag) => storedTags?.includes(tag))) {\n                if (FileSystemCache.debug) {\n                  console.log(\n                    'FileSystemCache: tags vs storedTags mismatch',\n                    tags,\n                    storedTags\n                  )\n                }\n                await this.set(key, data.value, {\n                  fetchCache: true,\n                  tags,\n                  fetchIdx,\n                  fetchUrl,\n                })\n              }\n            }\n          } else if (kind === IncrementalCacheKind.APP_PAGE) {\n            // We try to load the metadata file, but if it fails, we don't\n            // error. We also don't load it if this is a fallback.\n            let meta: RouteMetadata | undefined\n            try {\n              meta = JSON.parse(\n                await this.fs.readFile(\n                  filePath.replace(/\\.html$/, NEXT_META_SUFFIX),\n                  'utf8'\n                )\n              )\n            } catch {}\n\n            let maybeSegmentData: Map<string, Buffer> | undefined\n            if (meta?.segmentPaths) {\n              // Collect all the segment data for this page.\n              // TODO: To optimize file system reads, we should consider creating\n              // separate cache entries for each segment, rather than storing them\n              // all on the page's entry. Though the behavior is\n              // identical regardless.\n              const segmentData: Map<string, Buffer> = new Map()\n              maybeSegmentData = segmentData\n              const segmentsDir = key + RSC_SEGMENTS_DIR_SUFFIX\n              await Promise.all(\n                meta.segmentPaths.map(async (segmentPath: string) => {\n                  const segmentDataFilePath = this.getFilePath(\n                    segmentsDir + segmentPath + RSC_SEGMENT_SUFFIX,\n                    IncrementalCacheKind.APP_PAGE\n                  )\n                  try {\n                    segmentData.set(\n                      segmentPath,\n                      await this.fs.readFile(segmentDataFilePath)\n                    )\n                  } catch {\n                    // This shouldn't happen, but if for some reason we fail to\n                    // load a segment from the filesystem, treat it the same as if\n                    // the segment is dynamic and does not have a prefetch.\n                  }\n                })\n              )\n            }\n\n            let rscData: Buffer | undefined\n            if (\n              !ctx.isFallback &&\n              (!ctx.isRoutePPREnabled || meta?.postponed == null)\n            ) {\n              rscData = await this.fs.readFile(\n                this.getFilePath(\n                  `${key}${RSC_SUFFIX}`,\n                  IncrementalCacheKind.APP_PAGE\n                )\n              )\n            }\n\n            data = {\n              lastModified: mtime.getTime(),\n              value: {\n                kind: CachedRouteKind.APP_PAGE,\n                html: fileData,\n                rscData,\n                postponed: meta?.postponed,\n                headers: meta?.headers,\n                status: meta?.status,\n                segmentData: maybeSegmentData,\n              },\n            }\n          } else if (kind === IncrementalCacheKind.PAGES) {\n            let meta: RouteMetadata | undefined\n            let pageData: string | object = {}\n\n            if (!ctx.isFallback) {\n              pageData = JSON.parse(\n                await this.fs.readFile(\n                  this.getFilePath(\n                    `${key}${NEXT_DATA_SUFFIX}`,\n                    IncrementalCacheKind.PAGES\n                  ),\n                  'utf8'\n                )\n              )\n            }\n\n            data = {\n              lastModified: mtime.getTime(),\n              value: {\n                kind: CachedRouteKind.PAGES,\n                html: fileData,\n                pageData,\n                headers: meta?.headers,\n                status: meta?.status,\n              },\n            }\n          } else {\n            throw new Error(\n              `Invariant: Unexpected route kind ${kind} in file system cache.`\n            )\n          }\n        }\n\n        if (data) {\n          FileSystemCache.memoryCache?.set(key, data)\n        }\n      } catch {\n        return null\n      }\n    }\n\n    if (\n      data?.value?.kind === CachedRouteKind.APP_PAGE ||\n      data?.value?.kind === CachedRouteKind.APP_ROUTE ||\n      data?.value?.kind === CachedRouteKind.PAGES\n    ) {\n      const tagsHeader = data.value.headers?.[NEXT_CACHE_TAGS_HEADER]\n      if (typeof tagsHeader === 'string') {\n        const cacheTags = tagsHeader.split(',')\n\n        // we trigger a blocking validation if an ISR page\n        // had a tag revalidated, if we want to be a background\n        // revalidation instead we return data.lastModified = -1\n        if (\n          cacheTags.length > 0 &&\n          areTagsExpired(cacheTags, data.lastModified)\n        ) {\n          if (FileSystemCache.debug) {\n            console.log('FileSystemCache: expired tags', cacheTags)\n          }\n\n          return null\n        }\n      }\n    } else if (data?.value?.kind === CachedRouteKind.FETCH) {\n      const combinedTags =\n        ctx.kind === IncrementalCacheKind.FETCH\n          ? [...(ctx.tags || []), ...(ctx.softTags || [])]\n          : []\n\n      // When revalidate tag is called we don't return stale data so it's\n      // updated right away.\n      if (combinedTags.some((tag) => this.revalidatedTags.includes(tag))) {\n        if (FileSystemCache.debug) {\n          console.log('FileSystemCache: was revalidated', combinedTags)\n        }\n\n        return null\n      }\n\n      if (areTagsExpired(combinedTags, data.lastModified)) {\n        if (FileSystemCache.debug) {\n          console.log('FileSystemCache: expired tags', combinedTags)\n        }\n\n        return null\n      }\n    }\n\n    return data ?? null\n  }\n\n  public async set(\n    key: string,\n    data: IncrementalCacheValue | null,\n    ctx: SetIncrementalFetchCacheContext | SetIncrementalResponseCacheContext\n  ) {\n    FileSystemCache.memoryCache?.set(key, {\n      value: data,\n      lastModified: Date.now(),\n    })\n\n    if (FileSystemCache.debug) {\n      console.log('FileSystemCache: set', key)\n    }\n\n    if (!this.flushToDisk || !data) return\n\n    // Create a new writer that will prepare to write all the files to disk\n    // after their containing directory is created.\n    const writer = new MultiFileWriter(this.fs)\n\n    if (data.kind === CachedRouteKind.APP_ROUTE) {\n      const filePath = this.getFilePath(\n        `${key}.body`,\n        IncrementalCacheKind.APP_ROUTE\n      )\n\n      writer.append(filePath, data.body)\n\n      const meta: RouteMetadata = {\n        headers: data.headers,\n        status: data.status,\n        postponed: undefined,\n        segmentPaths: undefined,\n        prefetchHints: undefined,\n      }\n\n      writer.append(\n        filePath.replace(/\\.body$/, NEXT_META_SUFFIX),\n        JSON.stringify(meta, null, 2)\n      )\n    } else if (\n      data.kind === CachedRouteKind.PAGES ||\n      data.kind === CachedRouteKind.APP_PAGE\n    ) {\n      const isAppPath = data.kind === CachedRouteKind.APP_PAGE\n      const htmlPath = this.getFilePath(\n        `${key}.html`,\n        isAppPath ? IncrementalCacheKind.APP_PAGE : IncrementalCacheKind.PAGES\n      )\n\n      writer.append(htmlPath, data.html)\n\n      // Fallbacks don't generate a data file.\n      if (!ctx.fetchCache && !ctx.isFallback && !ctx.isRoutePPREnabled) {\n        writer.append(\n          this.getFilePath(\n            `${key}${isAppPath ? RSC_SUFFIX : NEXT_DATA_SUFFIX}`,\n            isAppPath\n              ? IncrementalCacheKind.APP_PAGE\n              : IncrementalCacheKind.PAGES\n          ),\n          isAppPath ? data.rscData! : JSON.stringify(data.pageData)\n        )\n      }\n\n      if (data?.kind === CachedRouteKind.APP_PAGE) {\n        let segmentPaths: string[] | undefined\n        if (data.segmentData) {\n          segmentPaths = []\n          const segmentsDir = htmlPath.replace(\n            /\\.html$/,\n            RSC_SEGMENTS_DIR_SUFFIX\n          )\n\n          for (const [segmentPath, buffer] of data.segmentData) {\n            segmentPaths.push(segmentPath)\n            const segmentDataFilePath =\n              segmentsDir + segmentPath + RSC_SEGMENT_SUFFIX\n            writer.append(segmentDataFilePath, buffer)\n          }\n        }\n\n        const meta: RouteMetadata = {\n          headers: data.headers,\n          status: data.status,\n          postponed: data.postponed,\n          segmentPaths,\n          prefetchHints: undefined,\n        }\n\n        writer.append(\n          htmlPath.replace(/\\.html$/, NEXT_META_SUFFIX),\n          JSON.stringify(meta)\n        )\n      }\n    } else if (data.kind === CachedRouteKind.FETCH) {\n      const filePath = this.getFilePath(key, IncrementalCacheKind.FETCH)\n      writer.append(\n        filePath,\n        JSON.stringify({\n          ...data,\n          tags: ctx.fetchCache ? ctx.tags : [],\n        })\n      )\n    }\n\n    // Wait for all FS operations to complete.\n    await writer.wait()\n  }\n\n  private getFilePath(pathname: string, kind: IncrementalCacheKind): string {\n    switch (kind) {\n      case IncrementalCacheKind.FETCH:\n        // we store in .next/cache/fetch-cache so it can be persisted\n        // across deploys\n        return path.join(\n          this.serverDistDir,\n          '..',\n          'cache',\n          'fetch-cache',\n          pathname\n        )\n      case IncrementalCacheKind.PAGES:\n        return path.join(this.serverDistDir, 'pages', pathname)\n      case IncrementalCacheKind.IMAGE:\n      case IncrementalCacheKind.APP_PAGE:\n      case IncrementalCacheKind.APP_ROUTE:\n        return path.join(this.serverDistDir, 'app', pathname)\n      default:\n        throw new Error(`Unexpected file path kind: ${kind}`)\n    }\n  }\n}\n","import type { CacheFs } from '../../../shared/lib/utils'\nimport type { PrerenderManifest } from '../../../build'\nimport {\n  type IncrementalCacheValue,\n  type IncrementalCacheEntry,\n  type IncrementalCache as IncrementalCacheType,\n  IncrementalCacheKind,\n  CachedRouteKind,\n  type IncrementalResponseCacheEntry,\n  type IncrementalFetchCacheEntry,\n  type GetIncrementalFetchCacheContext,\n  type GetIncrementalResponseCacheContext,\n  type CachedFetchValue,\n  type SetIncrementalFetchCacheContext,\n  type SetIncrementalResponseCacheContext,\n} from '../../response-cache'\nimport type { DeepReadonly } from '../../../shared/lib/deep-readonly'\nimport FileSystemCache from './file-system-cache'\nimport { normalizePagePath } from '../../../shared/lib/page-path/normalize-page-path'\n\nimport {\n  CACHE_ONE_YEAR_SECONDS,\n  NEXT_CACHE_TAGS_HEADER,\n  PRERENDER_REVALIDATE_HEADER,\n} from '../../../lib/constants'\nimport { toRoute } from '../to-route'\nimport { SharedCacheControls } from './shared-cache-controls.external'\nimport {\n  getPrerenderResumeDataCache,\n  getRenderResumeDataCache,\n  workUnitAsyncStorage,\n} from '../../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport type { Revalidate } from '../cache-control'\nimport { getPreviouslyRevalidatedTags } from '../../server-utils'\nimport { workAsyncStorage } from '../../app-render/work-async-storage.external'\nimport { DetachedPromise } from '../../../lib/detached-promise'\nimport { areTagsExpired, areTagsStale } from './tags-manifest.external'\n\nexport interface CacheHandlerContext {\n  fs?: CacheFs\n  dev?: boolean\n  flushToDisk?: boolean\n  serverDistDir?: string\n  maxMemoryCacheSize?: number\n  fetchCacheKeyPrefix?: string\n  prerenderManifest?: PrerenderManifest\n  revalidatedTags: string[]\n  _requestHeaders: IncrementalCache['requestHeaders']\n}\n\nexport interface CacheHandlerValue {\n  lastModified: number\n  age?: number\n  cacheState?: string\n  value: IncrementalCacheValue | null\n}\n\nexport class CacheHandler {\n  // eslint-disable-next-line\n  constructor(_ctx: CacheHandlerContext) {}\n\n  public async get(\n    _cacheKey: string,\n    _ctx: GetIncrementalFetchCacheContext | GetIncrementalResponseCacheContext\n  ): Promise<CacheHandlerValue | null> {\n    return {} as any\n  }\n\n  public async set(\n    _cacheKey: string,\n    _data: IncrementalCacheValue | null,\n    _ctx: SetIncrementalFetchCacheContext | SetIncrementalResponseCacheContext\n  ): Promise<void> {}\n\n  public async revalidateTag(\n    _tags: string | string[],\n    _durations?: { expire?: number }\n  ): Promise<void> {}\n\n  public resetRequestCache(): void {}\n}\n\nexport class IncrementalCache implements IncrementalCacheType {\n  readonly dev?: boolean\n  readonly disableForTestmode?: boolean\n  readonly cacheHandler?: CacheHandler\n  readonly hasCustomCacheHandler: boolean\n  readonly prerenderManifest: DeepReadonly<PrerenderManifest>\n  readonly requestHeaders: Record<string, undefined | string | string[]>\n  readonly allowedRevalidateHeaderKeys?: string[]\n  readonly minimalMode?: boolean\n  readonly fetchCacheKeyPrefix?: string\n  readonly isOnDemandRevalidate?: boolean\n  readonly revalidatedTags?: readonly string[]\n\n  private static readonly debug: boolean =\n    !!process.env.NEXT_PRIVATE_DEBUG_CACHE\n  private readonly locks = new Map<string, Promise<void>>()\n\n  /**\n   * The cache controls for routes. This will source the values from the\n   * prerender manifest until the in-memory cache is updated with new values.\n   */\n  private readonly cacheControls: SharedCacheControls\n\n  constructor({\n    fs,\n    dev,\n    flushToDisk,\n    minimalMode,\n    serverDistDir,\n    requestHeaders,\n    maxMemoryCacheSize,\n    getPrerenderManifest,\n    fetchCacheKeyPrefix,\n    CurCacheHandler,\n    allowedRevalidateHeaderKeys,\n  }: {\n    fs?: CacheFs\n    dev: boolean\n    minimalMode?: boolean\n    serverDistDir?: string\n    flushToDisk?: boolean\n    allowedRevalidateHeaderKeys?: string[]\n    requestHeaders: IncrementalCache['requestHeaders']\n    maxMemoryCacheSize?: number\n    getPrerenderManifest: () => DeepReadonly<PrerenderManifest>\n    fetchCacheKeyPrefix?: string\n    CurCacheHandler?: typeof CacheHandler\n  }) {\n    this.hasCustomCacheHandler = Boolean(CurCacheHandler)\n\n    const cacheHandlersSymbol = Symbol.for('@next/cache-handlers')\n    const _globalThis: typeof globalThis & {\n      [cacheHandlersSymbol]?: {\n        FetchCache?: typeof CacheHandler\n      }\n    } = globalThis\n\n    if (!CurCacheHandler) {\n      // if we have a global cache handler available leverage it\n      const globalCacheHandler = _globalThis[cacheHandlersSymbol]\n\n      if (globalCacheHandler?.FetchCache) {\n        CurCacheHandler = globalCacheHandler.FetchCache\n        if (IncrementalCache.debug) {\n          console.log('IncrementalCache: using global FetchCache cache handler')\n        }\n      } else {\n        if (fs && serverDistDir) {\n          if (IncrementalCache.debug) {\n            console.log('IncrementalCache: using filesystem cache handler')\n          }\n          CurCacheHandler = FileSystemCache\n        }\n      }\n    } else if (IncrementalCache.debug) {\n      console.log(\n        'IncrementalCache: using custom cache handler',\n        CurCacheHandler.name\n      )\n    }\n\n    if (process.env.__NEXT_TEST_MAX_ISR_CACHE) {\n      // Allow cache size to be overridden for testing purposes\n      maxMemoryCacheSize = parseInt(process.env.__NEXT_TEST_MAX_ISR_CACHE, 10)\n    }\n    this.dev = dev\n    this.disableForTestmode = process.env.NEXT_PRIVATE_TEST_PROXY === 'true'\n    // this is a hack to avoid Webpack knowing this is equal to this.minimalMode\n    // because we replace this.minimalMode to true in production bundles.\n    const minimalModeKey = 'minimalMode'\n    this[minimalModeKey] = minimalMode\n    this.requestHeaders = requestHeaders\n    this.allowedRevalidateHeaderKeys = allowedRevalidateHeaderKeys\n    this.prerenderManifest = getPrerenderManifest()\n    this.cacheControls = new SharedCacheControls(this.prerenderManifest)\n    this.fetchCacheKeyPrefix = fetchCacheKeyPrefix\n    let revalidatedTags: string[] = []\n\n    if (\n      requestHeaders[PRERENDER_REVALIDATE_HEADER] ===\n      this.prerenderManifest?.preview?.previewModeId\n    ) {\n      this.isOnDemandRevalidate = true\n    }\n\n    if (minimalMode) {\n      revalidatedTags = this.revalidatedTags = getPreviouslyRevalidatedTags(\n        requestHeaders,\n        this.prerenderManifest?.preview?.previewModeId\n      )\n    }\n\n    if (CurCacheHandler) {\n      this.cacheHandler = new CurCacheHandler({\n        dev,\n        fs,\n        flushToDisk,\n        serverDistDir,\n        revalidatedTags,\n        maxMemoryCacheSize,\n        _requestHeaders: requestHeaders,\n        fetchCacheKeyPrefix,\n      })\n    }\n  }\n\n  private calculateRevalidate(\n    pathname: string,\n    fromTime: number,\n    dev: boolean,\n    isFallback: boolean | undefined\n  ): Revalidate {\n    // in development we don't have a prerender-manifest\n    // and default to always revalidating to allow easier debugging\n    if (dev)\n      return Math.floor(performance.timeOrigin + performance.now() - 1000)\n\n    const cacheControl = this.cacheControls.get(toRoute(pathname))\n\n    // if an entry isn't present in routes we fallback to a default\n    // of revalidating after 1 second unless it's a fallback request.\n    const initialRevalidateSeconds = cacheControl\n      ? cacheControl.revalidate\n      : isFallback\n        ? false\n        : 1\n\n    const revalidateAfter =\n      typeof initialRevalidateSeconds === 'number'\n        ? initialRevalidateSeconds * 1000 + fromTime\n        : initialRevalidateSeconds\n\n    return revalidateAfter\n  }\n\n  _getPathname(pathname: string, fetchCache?: boolean) {\n    return fetchCache ? pathname : normalizePagePath(pathname)\n  }\n\n  resetRequestCache() {\n    this.cacheHandler?.resetRequestCache?.()\n  }\n\n  async lock(cacheKey: string): Promise<() => Promise<void> | void> {\n    // Wait for any existing lock on this cache key to be released\n    // This implements a simple queue-based locking mechanism\n    while (true) {\n      const lock = this.locks.get(cacheKey)\n\n      if (IncrementalCache.debug) {\n        console.log('IncrementalCache: lock get', cacheKey, !!lock)\n      }\n\n      // If no lock exists, we can proceed to acquire it\n      if (!lock) break\n\n      // Wait for the existing lock to be released before trying again\n      await lock\n    }\n\n    // Create a new detached promise that will represent this lock\n    // The resolve function (unlock) will be returned to the caller\n    const { resolve, promise } = new DetachedPromise<void>()\n\n    if (IncrementalCache.debug) {\n      console.log('IncrementalCache: successfully locked', cacheKey)\n    }\n\n    // Store the lock promise in the locks map\n    this.locks.set(cacheKey, promise)\n\n    return () => {\n      // Resolve the promise to release the lock.\n      resolve()\n\n      // Remove the lock from the map once it's released so that future gets\n      // can acquire the lock.\n      this.locks.delete(cacheKey)\n    }\n  }\n\n  async revalidateTag(\n    tags: string | string[],\n    durations?: { expire?: number }\n  ): Promise<void> {\n    return this.cacheHandler?.revalidateTag(tags, durations)\n  }\n\n  // x-ref: https://github.com/facebook/react/blob/2655c9354d8e1c54ba888444220f63e836925caa/packages/react/src/ReactFetch.js#L23\n  async generateCacheKey(\n    url: string,\n    init: RequestInit | Request = {}\n  ): Promise<string> {\n    // this should be bumped anytime a fix is made to cache entries\n    // that should bust the cache\n    const MAIN_KEY_PREFIX = 'v3'\n\n    const bodyChunks: string[] = []\n\n    const encoder = new TextEncoder()\n    const decoder = new TextDecoder()\n\n    if (init.body) {\n      // handle Uint8Array body\n      if (init.body instanceof Uint8Array) {\n        bodyChunks.push(decoder.decode(init.body))\n        ;(init as any)._ogBody = init.body\n      } // handle ReadableStream body\n      else if (typeof (init.body as any).getReader === 'function') {\n        const readableBody = init.body as ReadableStream<Uint8Array | string>\n\n        const chunks: Uint8Array[] = []\n\n        try {\n          await readableBody.pipeTo(\n            new WritableStream({\n              write(chunk) {\n                if (typeof chunk === 'string') {\n                  chunks.push(encoder.encode(chunk))\n                  bodyChunks.push(chunk)\n                } else {\n                  chunks.push(chunk)\n                  bodyChunks.push(decoder.decode(chunk, { stream: true }))\n                }\n              },\n            })\n          )\n\n          // Flush the decoder.\n          bodyChunks.push(decoder.decode())\n\n          // Create a new buffer with all the chunks.\n          const length = chunks.reduce((total, arr) => total + arr.length, 0)\n          const arrayBuffer = new Uint8Array(length)\n\n          // Push each of the chunks into the new array buffer.\n          let offset = 0\n          for (const chunk of chunks) {\n            arrayBuffer.set(chunk, offset)\n            offset += chunk.length\n          }\n\n          ;(init as any)._ogBody = arrayBuffer\n        } catch (err) {\n          console.error('Problem reading body', err)\n        }\n      } // handle FormData or URLSearchParams bodies\n      else if (typeof (init.body as any).keys === 'function') {\n        const formData = init.body as FormData\n        ;(init as any)._ogBody = init.body\n        for (const key of new Set([...formData.keys()])) {\n          const values = formData.getAll(key)\n          bodyChunks.push(\n            `${key}=${(\n              await Promise.all(\n                values.map(async (val) => {\n                  if (typeof val === 'string') {\n                    return val\n                  } else {\n                    return await val.text()\n                  }\n                })\n              )\n            ).join(',')}`\n          )\n        }\n        // handle blob body\n      } else if (typeof (init.body as any).arrayBuffer === 'function') {\n        const blob = init.body as Blob\n        const arrayBuffer = await blob.arrayBuffer()\n        bodyChunks.push(await blob.text())\n        ;(init as any)._ogBody = new Blob([arrayBuffer], { type: blob.type })\n      } else if (typeof init.body === 'string') {\n        bodyChunks.push(init.body)\n        ;(init as any)._ogBody = init.body\n      }\n    }\n\n    const headers =\n      typeof (init.headers || {}).keys === 'function'\n        ? Object.fromEntries(init.headers as Headers)\n        : Object.assign({}, init.headers)\n\n    // w3c trace context headers can break request caching and deduplication\n    // so we remove them from the cache key\n    if ('traceparent' in headers) delete headers['traceparent']\n    if ('tracestate' in headers) delete headers['tracestate']\n\n    const cacheString = JSON.stringify([\n      MAIN_KEY_PREFIX,\n      this.fetchCacheKeyPrefix || '',\n      url,\n      init.method,\n      headers,\n      init.mode,\n      init.redirect,\n      init.credentials,\n      init.referrer,\n      init.referrerPolicy,\n      init.integrity,\n      init.cache,\n      bodyChunks,\n    ])\n\n    if (process.env.NEXT_RUNTIME === 'edge') {\n      function bufferToHex(buffer: ArrayBuffer): string {\n        return Array.prototype.map\n          .call(new Uint8Array(buffer), (b) => b.toString(16).padStart(2, '0'))\n          .join('')\n      }\n      const buffer = encoder.encode(cacheString)\n      return bufferToHex(await crypto.subtle.digest('SHA-256', buffer))\n    } else {\n      const crypto = require('crypto') as typeof import('crypto')\n      return crypto.createHash('sha256').update(cacheString).digest('hex')\n    }\n  }\n\n  async get(\n    cacheKey: string,\n    ctx: GetIncrementalFetchCacheContext\n  ): Promise<IncrementalFetchCacheEntry | null>\n  async get(\n    cacheKey: string,\n    ctx: GetIncrementalResponseCacheContext\n  ): Promise<IncrementalResponseCacheEntry | null>\n  async get(\n    cacheKey: string,\n    ctx: GetIncrementalFetchCacheContext | GetIncrementalResponseCacheContext\n  ): Promise<IncrementalCacheEntry | null> {\n    // Unlike other caches if we have a resume data cache, we use it even if\n    // testmode would normally disable it or if requestHeaders say 'no-cache'.\n    if (ctx.kind === IncrementalCacheKind.FETCH) {\n      const workUnitStore = workUnitAsyncStorage.getStore()\n      const resumeDataCache = workUnitStore\n        ? getRenderResumeDataCache(workUnitStore)\n        : null\n      if (resumeDataCache) {\n        const memoryCacheData = resumeDataCache.fetch.get(cacheKey)\n        if (memoryCacheData?.kind === CachedRouteKind.FETCH) {\n          // Check if any tags were recently revalidated before returning RDC entry.\n          // When a server action calls updateTag(), the re-render should see fresh\n          // data instead of stale RDC data.\n          const workStore = workAsyncStorage.getStore()\n          const combinedTags = [...(ctx.tags || []), ...(ctx.softTags || [])]\n          const hasRevalidatedTag = combinedTags.some(\n            (tag) =>\n              this.revalidatedTags?.includes(tag) ||\n              workStore?.pendingRevalidatedTags?.some(\n                (item) => item.tag === tag\n              )\n          )\n\n          if (hasRevalidatedTag) {\n            if (IncrementalCache.debug) {\n              console.log('IncrementalCache: rdc:revalidated-tag', cacheKey)\n            }\n            // Fall through to cacheHandler lookup\n          } else {\n            if (IncrementalCache.debug) {\n              console.log('IncrementalCache: rdc:hit', cacheKey)\n            }\n\n            return { isStale: false, value: memoryCacheData }\n          }\n        } else if (IncrementalCache.debug) {\n          console.log('IncrementalCache: rdc:miss', cacheKey)\n        }\n      } else {\n        if (IncrementalCache.debug) {\n          console.log('IncrementalCache: rdc:no-resume-data')\n        }\n      }\n    }\n\n    // we don't leverage the prerender cache in dev mode\n    // so that getStaticProps is always called for easier debugging\n    if (\n      this.disableForTestmode ||\n      (this.dev &&\n        (ctx.kind !== IncrementalCacheKind.FETCH ||\n          this.requestHeaders['cache-control'] === 'no-cache'))\n    ) {\n      return null\n    }\n\n    cacheKey = this._getPathname(\n      cacheKey,\n      ctx.kind === IncrementalCacheKind.FETCH\n    )\n\n    const cacheData = await this.cacheHandler?.get(cacheKey, ctx)\n\n    if (ctx.kind === IncrementalCacheKind.FETCH) {\n      if (!cacheData) {\n        return null\n      }\n\n      if (cacheData.value?.kind !== CachedRouteKind.FETCH) {\n        throw new InvariantError(\n          `Expected cached value for cache key ${JSON.stringify(cacheKey)} to be a \"FETCH\" kind, got ${JSON.stringify(cacheData.value?.kind)} instead.`\n        )\n      }\n\n      const workStore = workAsyncStorage.getStore()\n      const combinedTags = [...(ctx.tags || []), ...(ctx.softTags || [])]\n      // if a tag was revalidated we don't return stale data\n      if (\n        combinedTags.some(\n          (tag) =>\n            this.revalidatedTags?.includes(tag) ||\n            workStore?.pendingRevalidatedTags?.some((item) => item.tag === tag)\n        )\n      ) {\n        if (IncrementalCache.debug) {\n          console.log('IncrementalCache: expired tag', cacheKey)\n        }\n\n        return null\n      }\n\n      // As we're able to get the cache entry for this fetch, and the prerender\n      // resume data cache (RDC) is available, it must have been populated by a\n      // previous fetch, but was not yet present in the in-memory cache. This\n      // could be the case when performing multiple renders in parallel during\n      // build time where we de-duplicate the fetch calls.\n      //\n      // We add it to the RDC so that the next fetch call will be able to use it\n      // and it won't have to reach into the fetch cache implementation.\n      const workUnitStore = workUnitAsyncStorage.getStore()\n      if (workUnitStore) {\n        const prerenderResumeDataCache =\n          getPrerenderResumeDataCache(workUnitStore)\n        if (prerenderResumeDataCache) {\n          if (IncrementalCache.debug) {\n            console.log('IncrementalCache: rdc:set', cacheKey)\n          }\n\n          prerenderResumeDataCache.fetch.set(cacheKey, cacheData.value)\n        }\n      }\n\n      const revalidate = ctx.revalidate || cacheData.value.revalidate\n      const age =\n        (performance.timeOrigin +\n          performance.now() -\n          (cacheData.lastModified || 0)) /\n        1000\n\n      let isStale = age > revalidate\n      const data = cacheData.value.data\n\n      if (areTagsExpired(combinedTags, cacheData.lastModified)) {\n        return null\n      } else if (areTagsStale(combinedTags, cacheData.lastModified)) {\n        isStale = true\n      }\n\n      return {\n        isStale,\n        value: { kind: CachedRouteKind.FETCH, data, revalidate },\n      }\n    } else if (cacheData?.value?.kind === CachedRouteKind.FETCH) {\n      throw new InvariantError(\n        `Expected cached value for cache key ${JSON.stringify(cacheKey)} not to be a ${JSON.stringify(ctx.kind)} kind, got \"FETCH\" instead.`\n      )\n    }\n\n    let entry: IncrementalResponseCacheEntry | null = null\n    const { isFallback } = ctx\n    const cacheControl = this.cacheControls.get(toRoute(cacheKey))\n\n    let isStale: boolean | -1 | undefined\n    let revalidateAfter: Revalidate\n\n    if (cacheData?.lastModified === -1) {\n      isStale = -1\n      revalidateAfter = -1 * CACHE_ONE_YEAR_SECONDS * 1000\n    } else {\n      const now = performance.timeOrigin + performance.now()\n      const lastModified = cacheData?.lastModified || now\n\n      revalidateAfter = this.calculateRevalidate(\n        cacheKey,\n        lastModified,\n        this.dev ?? false,\n        ctx.isFallback\n      )\n\n      isStale =\n        revalidateAfter !== false && revalidateAfter < now ? true : undefined\n\n      // If the stale time couldn't be determined based on the revalidation\n      // time, we check if the tags are expired or stale.\n      if (\n        isStale === undefined &&\n        (cacheData?.value?.kind === CachedRouteKind.APP_PAGE ||\n          cacheData?.value?.kind === CachedRouteKind.APP_ROUTE)\n      ) {\n        const tagsHeader = cacheData.value.headers?.[NEXT_CACHE_TAGS_HEADER]\n\n        if (typeof tagsHeader === 'string') {\n          const cacheTags = tagsHeader.split(',')\n\n          if (cacheTags.length > 0) {\n            if (areTagsExpired(cacheTags, lastModified)) {\n              isStale = -1\n            } else if (areTagsStale(cacheTags, lastModified)) {\n              isStale = true\n            }\n          }\n        }\n      }\n    }\n\n    if (cacheData) {\n      entry = {\n        isStale,\n        cacheControl,\n        revalidateAfter,\n        value: cacheData.value,\n        isFallback,\n      }\n    }\n\n    if (\n      !cacheData &&\n      this.prerenderManifest.notFoundRoutes.includes(cacheKey)\n    ) {\n      // for the first hit after starting the server the cache\n      // may not have a way to save notFound: true so if\n      // the prerender-manifest marks this as notFound then we\n      // return that entry and trigger a cache set to give it a\n      // chance to update in-memory entries\n      entry = {\n        isStale,\n        value: null,\n        cacheControl,\n        revalidateAfter,\n        isFallback,\n      }\n      this.set(cacheKey, entry.value, { ...ctx, cacheControl })\n    }\n    return entry\n  }\n\n  async set(\n    pathname: string,\n    data: CachedFetchValue | null,\n    ctx: SetIncrementalFetchCacheContext\n  ): Promise<void>\n  async set(\n    pathname: string,\n    data: Exclude<IncrementalCacheValue, CachedFetchValue> | null,\n    ctx: SetIncrementalResponseCacheContext\n  ): Promise<void>\n  async set(\n    pathname: string,\n    data: IncrementalCacheValue | null,\n    ctx: SetIncrementalFetchCacheContext | SetIncrementalResponseCacheContext\n  ): Promise<void> {\n    // Even if we otherwise disable caching for testMode or if no fetchCache is\n    // configured we still always stash results in the resume data cache if one\n    // exists. This is because this is a transient in memory cache that\n    // populates caches ahead of a dynamic render in dev mode to allow the RSC\n    // debug info to have the right environment associated to it.\n    if (data?.kind === CachedRouteKind.FETCH) {\n      const workUnitStore = workUnitAsyncStorage.getStore()\n      const prerenderResumeDataCache = workUnitStore\n        ? getPrerenderResumeDataCache(workUnitStore)\n        : null\n      if (prerenderResumeDataCache) {\n        if (IncrementalCache.debug) {\n          console.log('IncrementalCache: rdc:set', pathname)\n        }\n\n        prerenderResumeDataCache.fetch.set(pathname, data)\n      }\n    }\n\n    if (this.disableForTestmode || (this.dev && !ctx.fetchCache)) return\n\n    pathname = this._getPathname(pathname, ctx.fetchCache)\n\n    // FetchCache has upper limit of 2MB per-entry currently\n    const itemSize = JSON.stringify(data).length\n    if (\n      ctx.fetchCache &&\n      itemSize > 2 * 1024 * 1024 &&\n      // We ignore the size limit when custom cache handler is being used, as it\n      // might not have this limit\n      !this.hasCustomCacheHandler &&\n      // We also ignore the size limit when it's an implicit build-time-only\n      // caching that the user isn't even aware of.\n      !ctx.isImplicitBuildTimeCache\n    ) {\n      const warningText = `Failed to set Next.js data cache for ${ctx.fetchUrl || pathname}, items over 2MB can not be cached (${itemSize} bytes)`\n\n      if (this.dev) {\n        throw new Error(warningText)\n      }\n      console.warn(warningText)\n      return\n    }\n\n    try {\n      if (!ctx.fetchCache && ctx.cacheControl) {\n        this.cacheControls.set(toRoute(pathname), ctx.cacheControl)\n      }\n\n      await this.cacheHandler?.set(pathname, data, ctx)\n    } catch (error) {\n      console.warn('Failed to update prerender cache for', pathname, error)\n    }\n  }\n}\n","import type { CacheFs } from '../../shared/lib/utils'\n\nimport fs from 'fs'\n\nexport const nodeFs: CacheFs = {\n  existsSync: fs.existsSync,\n  readFile: fs.promises.readFile,\n  readFileSync: fs.readFileSync,\n  writeFile: (f, d) => fs.promises.writeFile(f, d),\n  mkdir: (dir) => fs.promises.mkdir(dir, { recursive: true }),\n  stat: (f) => fs.promises.stat(f),\n}\n","import type {\n  ServerResponse,\n  OutgoingHttpHeaders,\n  OutgoingHttpHeader,\n  IncomingMessage,\n  IncomingHttpHeaders,\n} from 'http'\nimport type { Socket } from 'net'\nimport type { TLSSocket } from 'tls'\n\nimport Stream from 'stream'\nimport {\n  fromNodeOutgoingHttpHeaders,\n  toNodeOutgoingHttpHeaders,\n} from '../web/utils'\n\ninterface MockedRequestOptions {\n  url: string\n  headers: IncomingHttpHeaders\n  method: string\n  readable?: Stream.Readable\n  socket?: Socket | null\n}\n\nexport class MockedRequest extends Stream.Readable implements IncomingMessage {\n  public url: string\n  public readonly statusCode?: number | undefined\n  public readonly statusMessage?: string | undefined\n  public readonly headers: IncomingHttpHeaders\n  public readonly method: string\n\n  // This is hardcoded for now, but can be updated to be configurable if needed.\n  public readonly httpVersion = '1.0'\n  public readonly httpVersionMajor = 1\n  public readonly httpVersionMinor = 0\n\n  private bodyReadable?: Stream.Readable\n\n  // If we don't actually have a socket, we'll just use a mock one that\n  // always returns false for the `encrypted` property and undefined for the\n  // `remoteAddress` property.\n  public socket: Socket = new Proxy<TLSSocket>({} as TLSSocket, {\n    get: (_target, prop) => {\n      if (prop !== 'encrypted' && prop !== 'remoteAddress') {\n        throw new Error('Method not implemented')\n      }\n\n      if (prop === 'remoteAddress') return undefined\n      // For this mock request, always ensure we just respond with the encrypted\n      // set to false to ensure there's no odd leakages.\n      return false\n    },\n  })\n\n  constructor({\n    url,\n    headers,\n    method,\n    socket = null,\n    readable,\n  }: MockedRequestOptions) {\n    super()\n\n    this.url = url\n    this.headers = headers\n    this.method = method\n\n    if (readable) {\n      this.bodyReadable = readable\n      this.bodyReadable.on('end', () => this.emit('end'))\n      this.bodyReadable.on('close', () => this.emit('close'))\n    }\n\n    if (socket) {\n      this.socket = socket\n    }\n  }\n\n  public get headersDistinct(): NodeJS.Dict<string[]> {\n    const headers: NodeJS.Dict<string[]> = {}\n    for (const [key, value] of Object.entries(this.headers)) {\n      if (!value) continue\n\n      headers[key] = Array.isArray(value) ? value : [value]\n    }\n\n    return headers\n  }\n\n  public _read(size: number): void {\n    if (this.bodyReadable) {\n      return this.bodyReadable._read(size)\n    } else {\n      this.emit('end')\n      this.emit('close')\n    }\n  }\n\n  /**\n   * The `connection` property is just an alias for the `socket` property.\n   *\n   * @deprecated — since v13.0.0 - Use socket instead.\n   */\n  public get connection(): Socket {\n    return this.socket\n  }\n\n  // The following methods are not implemented as they are not used in the\n  // Next.js codebase.\n\n  public get aborted(): boolean {\n    throw new Error('Method not implemented')\n  }\n\n  public get complete(): boolean {\n    throw new Error('Method not implemented')\n  }\n\n  public get trailers(): NodeJS.Dict<string> {\n    throw new Error('Method not implemented')\n  }\n\n  public get trailersDistinct(): NodeJS.Dict<string[]> {\n    throw new Error('Method not implemented')\n  }\n\n  public get rawTrailers(): string[] {\n    throw new Error('Method not implemented')\n  }\n\n  public get rawHeaders(): string[] {\n    throw new Error('Method not implemented.')\n  }\n\n  public setTimeout(): this {\n    throw new Error('Method not implemented.')\n  }\n}\n\nexport interface MockedResponseOptions {\n  statusCode?: number\n  socket?: Socket | null\n  headers?: OutgoingHttpHeaders\n  resWriter?: (chunk: Uint8Array | Buffer | string) => boolean\n}\n\nexport class MockedResponse extends Stream.Writable implements ServerResponse {\n  public statusCode: number\n  public statusMessage: string = ''\n  public finished = false\n  public headersSent = false\n  public readonly socket: Socket | null\n\n  /**\n   * A promise that resolves to `true` when the response has been streamed.\n   *\n   * @internal - used internally by Next.js\n   */\n  public readonly hasStreamed: Promise<boolean>\n\n  /**\n   * A list of buffers that have been written to the response.\n   *\n   * @internal - used internally by Next.js\n   */\n  public readonly buffers: Buffer[] = []\n\n  /**\n   * The headers object that contains the headers that were initialized on the\n   * response and any that were added subsequently.\n   *\n   * @internal - used internally by Next.js\n   */\n  public readonly headers: Headers\n\n  private resWriter: MockedResponseOptions['resWriter']\n\n  public readonly headPromise: Promise<void>\n  private headPromiseResolve?: () => void\n\n  constructor(res: MockedResponseOptions = {}) {\n    super()\n\n    this.statusCode = res.statusCode ?? 200\n    this.socket = res.socket ?? null\n    this.headers = res.headers\n      ? fromNodeOutgoingHttpHeaders(res.headers)\n      : new Headers()\n\n    this.headPromise = new Promise<void>((resolve) => {\n      this.headPromiseResolve = resolve\n    })\n\n    // Attach listeners for the `finish`, `end`, and `error` events to the\n    // `MockedResponse` instance.\n    this.hasStreamed = new Promise<boolean>((resolve, reject) => {\n      this.on('finish', () => resolve(true))\n      this.on('end', () => resolve(true))\n      this.on('error', (err) => reject(err))\n    }).then((val) => {\n      this.headPromiseResolve?.()\n      return val\n    })\n\n    if (res.resWriter) {\n      this.resWriter = res.resWriter\n    }\n  }\n\n  public appendHeader(name: string, value: string | string[]): this {\n    const values = Array.isArray(value) ? value : [value]\n    for (const v of values) {\n      this.headers.append(name, v)\n    }\n\n    return this\n  }\n\n  /**\n   * Returns true if the response has been sent, false otherwise.\n   *\n   * @internal - used internally by Next.js\n   */\n  public get isSent() {\n    return this.finished || this.headersSent\n  }\n\n  /**\n   * The `connection` property is just an alias for the `socket` property.\n   *\n   * @deprecated — since v13.0.0 - Use socket instead.\n   */\n  public get connection(): Socket | null {\n    return this.socket\n  }\n\n  public write(chunk: Uint8Array | Buffer | string) {\n    if (this.resWriter) {\n      return this.resWriter(chunk)\n    }\n    this.buffers.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))\n\n    return true\n  }\n\n  public end() {\n    this.finished = true\n    return super.end(...arguments)\n  }\n\n  /**\n   * This method is a no-op because the `MockedResponse` instance is not\n   * actually connected to a socket. This method is not specified on the\n   * interface type for `ServerResponse` but is called by Node.js.\n   *\n   * @see https://github.com/nodejs/node/pull/7949\n   */\n  public _implicitHeader() {}\n\n  public _write(\n    chunk: Buffer | string,\n    _encoding: string,\n    callback: () => void\n  ) {\n    this.write(chunk)\n\n    // According to Node.js documentation, the callback MUST be invoked to\n    // signal that the write completed successfully. If this callback is not\n    // invoked, the 'finish' event will not be emitted.\n    //\n    // https://nodejs.org/docs/latest-v16.x/api/stream.html#writable_writechunk-encoding-callback\n    callback()\n  }\n\n  public writeHead(\n    statusCode: number,\n    statusMessage?: string | undefined,\n    headers?: OutgoingHttpHeaders | OutgoingHttpHeader[] | undefined\n  ): this\n  public writeHead(\n    statusCode: number,\n    headers?: OutgoingHttpHeaders | OutgoingHttpHeader[] | undefined\n  ): this\n  public writeHead(\n    statusCode: number,\n    statusMessage?:\n      | string\n      | OutgoingHttpHeaders\n      | OutgoingHttpHeader[]\n      | undefined,\n    headers?: OutgoingHttpHeaders | OutgoingHttpHeader[] | undefined\n  ): this {\n    if (!headers && typeof statusMessage !== 'string') {\n      headers = statusMessage\n    } else if (typeof statusMessage === 'string' && statusMessage.length > 0) {\n      this.statusMessage = statusMessage\n    }\n\n    if (headers) {\n      // When headers have been set with response.setHeader(), they will be\n      // merged with any headers passed to response.writeHead(), with the\n      // headers passed to response.writeHead() given precedence.\n      //\n      // https://nodejs.org/api/http.html#responsewriteheadstatuscode-statusmessage-headers\n      //\n      // For this reason, we need to only call `set` to ensure that this will\n      // overwrite any existing headers.\n      if (Array.isArray(headers)) {\n        // headers may be an Array where the keys and values are in the same list.\n        // It is not a list of tuples. So, the even-numbered offsets are key\n        // values, and the odd-numbered offsets are the associated values. The\n        // array is in the same format as request.rawHeaders.\n        for (let i = 0; i < headers.length; i += 2) {\n          // The header key is always a string according to the spec.\n          this.setHeader(headers[i] as string, headers[i + 1])\n        }\n      } else {\n        for (const [key, value] of Object.entries(headers)) {\n          // Skip undefined values\n          if (typeof value === 'undefined') continue\n\n          this.setHeader(key, value)\n        }\n      }\n    }\n\n    this.statusCode = statusCode\n    this.headersSent = true\n    this.headPromiseResolve?.()\n\n    return this\n  }\n\n  public hasHeader(name: string): boolean {\n    return this.headers.has(name)\n  }\n\n  public getHeader(name: string): string | undefined {\n    return this.headers.get(name) ?? undefined\n  }\n\n  public getHeaders(): OutgoingHttpHeaders {\n    return toNodeOutgoingHttpHeaders(this.headers)\n  }\n\n  public getHeaderNames(): string[] {\n    return Array.from(this.headers.keys())\n  }\n\n  public setHeader(name: string, value: OutgoingHttpHeader) {\n    if (Array.isArray(value)) {\n      // Because `set` here should override any existing values, we need to\n      // delete the existing values before setting the new ones via `append`.\n      this.headers.delete(name)\n\n      for (const v of value) {\n        this.headers.append(name, v)\n      }\n    } else if (typeof value === 'number') {\n      this.headers.set(name, value.toString())\n    } else {\n      this.headers.set(name, value)\n    }\n\n    return this\n  }\n\n  public removeHeader(name: string): void {\n    this.headers.delete(name)\n  }\n\n  public flushHeaders(): void {\n    // This is a no-op because we don't actually have a socket to flush the\n    // headers to.\n  }\n\n  // The following methods are not implemented as they are not used in the\n  // Next.js codebase.\n\n  public get strictContentLength(): boolean {\n    throw new Error('Method not implemented.')\n  }\n\n  public writeEarlyHints() {\n    throw new Error('Method not implemented.')\n  }\n\n  public get req(): IncomingMessage {\n    throw new Error('Method not implemented.')\n  }\n\n  public assignSocket() {\n    throw new Error('Method not implemented.')\n  }\n\n  public detachSocket(): void {\n    throw new Error('Method not implemented.')\n  }\n\n  public writeContinue(): void {\n    throw new Error('Method not implemented.')\n  }\n\n  public writeProcessing(): void {\n    throw new Error('Method not implemented.')\n  }\n\n  public get upgrading(): boolean {\n    throw new Error('Method not implemented.')\n  }\n\n  public get chunkedEncoding(): boolean {\n    throw new Error('Method not implemented.')\n  }\n\n  public get shouldKeepAlive(): boolean {\n    throw new Error('Method not implemented.')\n  }\n\n  public get useChunkedEncodingByDefault(): boolean {\n    throw new Error('Method not implemented.')\n  }\n\n  public get sendDate(): boolean {\n    throw new Error('Method not implemented.')\n  }\n\n  public setTimeout(): this {\n    throw new Error('Method not implemented.')\n  }\n\n  public addTrailers(): void {\n    throw new Error('Method not implemented.')\n  }\n\n  public setHeaders(): this {\n    throw new Error('Method not implemented.')\n  }\n}\n\ninterface RequestResponseMockerOptions {\n  url: string\n  headers?: IncomingHttpHeaders\n  method?: string\n  bodyReadable?: Stream.Readable\n  resWriter?: (chunk: Uint8Array | Buffer | string) => boolean\n  socket?: Socket | null\n}\n\nexport function createRequestResponseMocks({\n  url,\n  headers = {},\n  method = 'GET',\n  bodyReadable,\n  resWriter,\n  socket = null,\n}: RequestResponseMockerOptions) {\n  return {\n    req: new MockedRequest({\n      url,\n      headers,\n      method,\n      socket,\n      readable: bodyReadable,\n    }),\n    res: new MockedResponse({ socket, resWriter }),\n  }\n}\n","import path from 'path'\nimport { pathToFileURL } from 'url'\n\n/**\n * The path for a dynamic route must be URLs with a valid scheme.\n *\n * When an absolute Windows path is passed to it, it interprets the beginning of the path as a protocol (`C:`).\n * Therefore, it is important to always construct a complete path.\n * @param dir File directory\n * @param filePath Absolute or relative path\n */\nexport const formatDynamicImportPath = (dir: string, filePath: string) => {\n  const absoluteFilePath = path.isAbsolute(filePath)\n    ? filePath\n    : path.join(dir, filePath)\n  const formattedFilePath = pathToFileURL(absoluteFilePath).toString()\n\n  return formattedFilePath\n}\n","import { NEXT_URL } from '../client/components/app-router-headers'\nimport type { Rewrite } from './load-custom-routes'\nimport type { DeepReadonly } from '../shared/lib/deep-readonly'\n\nexport function isInterceptionRouteRewrite(route: DeepReadonly<Rewrite>) {\n  // When we generate interception rewrites in the above implementation, we always do so with only a single `has` condition.\n  return route.has?.[0]?.key === NEXT_URL\n}\n","export class AsyncCallbackSet {\n  private callbacks: (() => Promise<void>)[] = []\n\n  public add(callback: () => Promise<void>) {\n    this.callbacks.push(callback)\n  }\n\n  public async runAll(): Promise<void> {\n    if (!this.callbacks.length) {\n      return\n    }\n    const callbacks = this.callbacks\n    this.callbacks = []\n    await Promise.allSettled(\n      callbacks.map(\n        // NOTE: wrapped in an async function to protect against synchronous exceptions\n        async (f) => f()\n      )\n    )\n  }\n}\n","import type { ModuleLoader } from './module-loader'\n\n/**\n * Loads a module using `await require(id)`.\n */\nexport class NodeModuleLoader implements ModuleLoader {\n  public async load<M>(id: string): Promise<M> {\n    if (process.env.NEXT_RUNTIME !== 'edge') {\n      // Need to `await` to cover the case that route is marked ESM modules by ESM escalation.\n      return await (process.env.NEXT_MINIMAL\n        ? // @ts-ignore\n          __non_webpack_require__(id)\n        : require(id))\n    }\n\n    throw new Error('NodeModuleLoader is not supported in edge runtime.')\n  }\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { NextConfigRuntime } from '../../config-shared'\nimport type { UrlWithParsedQuery } from 'node:url'\nimport type { ServerCacheStatus } from '../../../next-devtools/dev-overlay/cache-indicator'\n\nexport type RevalidateFn = (config: {\n  urlPath: string\n  headers: { [key: string]: string | string[] }\n  opts: { unstable_onlyGenerated?: boolean }\n}) => Promise<void>\n\n// The RouterServerContext contains instance specific\n// information that isn't available/relevant when\n// deployed in serverless environments, the key is\n// the relative project dir this allows separate contexts\n// when running multiple next instances in same process\nexport type RouterServerContext = Record<\n  string,\n  {\n    // hostname the server is started with\n    hostname?: string\n    // revalidate function to bypass going through network\n    // to invoke revalidate request (uses mocked req/res)\n    revalidate?: RevalidateFn\n    // function to render the 404 page\n    render404?: (\n      req: IncomingMessage,\n      res: ServerResponse,\n      parsedUrl?: UrlWithParsedQuery,\n      setHeaders?: boolean\n    ) => Promise<void>\n    // exposing nextConfig for dev mode specifically\n    nextConfig?: NextConfigRuntime\n    // whether running in custom server mode\n    isCustomServer?: boolean\n    // whether test proxy is enabled\n    experimentalTestProxy?: boolean\n    // allow dev server to log with original stack\n    logErrorWithOriginalStack?: (err: unknown, type: string) => void\n    // allow setting ISR status in dev\n    setIsrStatus?: (key: string, value: boolean | undefined) => void\n    setReactDebugChannel?: (\n      debugChannel: { readable: ReadableStream<Uint8Array> },\n      htmlRequestId: string,\n      requestId: string\n    ) => void\n    setCacheStatus?: (status: ServerCacheStatus, htmlRequestId: string) => void\n    sendErrorsToBrowser?: (\n      errorsRscStream: ReadableStream<Uint8Array>,\n      htmlRequestId: string\n    ) => void\n    // indicates request handlers are already wrapped by next-server tracing\n    isWrappedByNextServer?: boolean\n  }\n>\n\nexport const RouterServerContextSymbol = Symbol.for(\n  '@next/router-server-methods'\n)\n\nexport const routerServerGlobal = globalThis as typeof globalThis & {\n  [RouterServerContextSymbol]?: RouterServerContext\n}\n","const REACT_POSTPONE_TYPE: symbol = Symbol.for('react.postpone')\n\nexport function isPostpone(error: any): boolean {\n  return (\n    typeof error === 'object' &&\n    error !== null &&\n    error.$$typeof === REACT_POSTPONE_TYPE\n  )\n}\n","import { isPostpone } from '../lib/router-utils/is-postpone'\n\nlet _global = globalThis as typeof globalThis & {\n  nextInitializedProcessErrorHandlers?: boolean\n}\n\nexport function installProcessErrorHandlers(\n  shouldRemoveUncaughtErrorAndRejectionListeners: boolean\n) {\n  if (_global.nextInitializedProcessErrorHandlers) return\n  _global.nextInitializedProcessErrorHandlers = true\n  // The conventional wisdom of Node.js and other runtimes is to treat\n  // unhandled errors as fatal and exit the process.\n  //\n  // But Next.js is not a generic JS runtime — it's a specialized runtime for\n  // React Server Components.\n  //\n  // Many unhandled rejections are due to the late-awaiting pattern for\n  // prefetching data. In Next.js it's OK to call an async function without\n  // immediately awaiting it, to start the request as soon as possible\n  // without blocking unncessarily on the result. These can end up\n  // triggering an \"unhandledRejection\" if it later turns out that the\n  // data is not needed to render the page. Example:\n  //\n  //     const promise = fetchData()\n  //     const shouldShow = await checkCondition()\n  //     if (shouldShow) {\n  //       return <Component promise={promise} />\n  //     }\n  //\n  // In this example, `fetchData` is called immediately to start the request\n  // as soon as possible, but if `shouldShow` is false, then it will be\n  // discarded without unwrapping its result. If it errors, it will trigger\n  // an \"unhandledRejection\" event.\n  //\n  // Ideally, we would suppress these rejections completely without warning,\n  // because we don't consider them real errors. (TODO: Currently we do warn.)\n  //\n  // But regardless of whether we do or don't warn, we definitely shouldn't\n  // crash the entire process.\n  //\n  // Even a \"legit\" unhandled error unrelated to prefetching shouldn't\n  // prevent the rest of the page from rendering.\n  //\n  // So, we're going to intentionally override the default error handling\n  // behavior of the outer JS runtime to be more forgiving\n\n  // Remove any existing \"unhandledRejection\" and \"uncaughtException\" handlers.\n  // This is gated behind an experimental flag until we've considered the impact\n  // in various deployment environments. It's possible this may always need to\n  // be configurable.\n  if (shouldRemoveUncaughtErrorAndRejectionListeners) {\n    process.removeAllListeners('uncaughtException')\n    process.removeAllListeners('unhandledRejection')\n  }\n\n  // Install a new handler to prevent the process from crashing.\n  process.on('unhandledRejection', (reason: unknown) => {\n    if (isPostpone(reason)) {\n      // React postpones that are unhandled might end up logged here but they're\n      // not really errors. They're just part of rendering.\n      return\n    }\n    // Immediately log the error.\n    // TODO: Ideally, if we knew that this error was triggered by application\n    // code, we would suppress it entirely without logging. We can't reliably\n    // detect all of these, but when cacheComponents is enabled, we could suppress\n    // at least some of them by waiting to log the error until after all in-\n    // progress renders have completed. Then, only log errors for which there\n    // was not a corresponding \"rejectionHandled\" event.\n    console.error(reason)\n  })\n\n  process.on('rejectionHandled', () => {\n    // TODO: See note in the unhandledRejection handler above. In the future,\n    // we may use the \"rejectionHandled\" event to de-queue an error from\n    // being logged.\n  })\n\n  // Unhandled exceptions are errors triggered by non-async functions, so this\n  // is unrelated to the late-awaiting pattern. However, for similar reasons,\n  // we still shouldn't crash the process. Just log it.\n  process.on('uncaughtException', (reason: unknown) => {\n    if (isPostpone(reason)) {\n      return\n    }\n    console.error(reason)\n  })\n}\n","import './node-environment'\nimport './require-hook'\nimport './node-polyfill-crypto'\n\nimport type { CacheFs } from '../shared/lib/utils'\nimport {\n  DecodeError,\n  PageNotFoundError,\n  MiddlewareNotFoundError,\n} from '../shared/lib/utils'\nimport type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin'\nimport type RenderResult from './render-result'\nimport type { FetchEventResult } from './web/types'\nimport type { PrerenderManifest, RoutesManifest } from '../build'\nimport type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'\nimport type {\n  NextParsedUrlQuery,\n  NextUrlWithParsedQuery,\n  RequestMeta,\n} from './request-meta'\nimport type { Params } from './request/params'\nimport type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher'\nimport type { RouteMatch } from './route-matches/route-match'\nimport type { IncomingMessage, ServerResponse } from 'http'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { ParsedUrl } from '../shared/lib/router/utils/parse-url'\nimport type { CacheControl } from './lib/cache-control'\nimport type { WaitUntil } from './after/builtin-request-context'\nimport type { AppPageModule } from './route-modules/app-page/module'\nimport type { AppRouteModule } from './route-modules/app-route/module.compiled'\nimport type { ErrorModule } from './load-default-error-components'\nimport type { PagesModule } from './route-modules/pages/module.compiled'\n\nimport fs from 'fs'\nimport { join, relative } from 'path'\nimport { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'\nimport { addRequestMeta, getRequestMeta, setRequestMeta } from './request-meta'\nimport {\n  PAGES_MANIFEST,\n  BUILD_ID_FILE,\n  MIDDLEWARE_MANIFEST,\n  PREFETCH_HINTS,\n  PRERENDER_MANIFEST,\n  ROUTES_MANIFEST,\n  CLIENT_PUBLIC_FILES_PATH,\n  APP_PATHS_MANIFEST,\n  SERVER_DIRECTORY,\n  NEXT_FONT_MANIFEST,\n  UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,\n  FUNCTIONS_CONFIG_MANIFEST,\n} from '../shared/lib/constants'\nimport { findDir } from '../lib/find-pages-dir'\nimport { NodeNextRequest, NodeNextResponse } from './base-http/node'\nimport { sendRenderResult } from './send-payload'\nimport { parseUrl } from '../shared/lib/router/utils/parse-url'\nimport * as Log from '../build/output/log'\n\nimport type {\n  Options,\n  FindComponentsResult,\n  MiddlewareRoutingItem,\n  RequestContext,\n  NormalizedRouteManifest,\n  LoadedRenderOpts,\n  RouteHandler,\n  NextEnabledDirectories,\n  BaseRequestHandler,\n} from './base-server'\nimport BaseServer from './base-server'\nimport { getMaybePagePath, getPagePath } from './require'\nimport { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { loadComponents } from './load-components'\nimport type { LoadComponentsReturnType } from './load-components'\nimport isError, { getProperError } from '../lib/is-error'\nimport { splitCookiesString, toNodeOutgoingHttpHeaders } from './web/utils'\nimport { getMiddlewareRouteMatcher } from '../shared/lib/router/utils/middleware-route-matcher'\nimport { loadEnvConfig } from '@next/env'\nimport { urlQueryToSearchParams } from '../shared/lib/router/utils/querystring'\nimport { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'\nimport { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'\nimport { getCloneableBody } from './body-streams'\nimport { checkIsOnDemandRevalidate } from './api-utils'\nimport ResponseCache, {\n  CachedRouteKind,\n  type IncrementalResponseCacheEntry,\n} from './response-cache'\nimport {\n  IncrementalCache,\n  type CacheHandler as ICacheHandler,\n} from './lib/incremental-cache'\nimport { normalizeAppPath } from '../shared/lib/router/utils/app-paths'\n\nimport { setHttpClientAndAgentOptions } from './setup-http-agent-env'\n\nimport { isPagesAPIRouteMatch } from './route-matches/pages-api-route-match'\nimport type { PagesAPIRouteMatch } from './route-matches/pages-api-route-match'\nimport type { MatchOptions } from './route-matcher-managers/route-matcher-manager'\nimport { BubbledError, getTracer } from './lib/trace/tracer'\nimport { NextNodeServerSpan } from './lib/trace/constants'\nimport { nodeFs } from './lib/node-fs-methods'\nimport { getRouteRegex } from '../shared/lib/router/utils/route-regex'\nimport { pipeToNodeResponse } from './pipe-readable'\nimport { createRequestResponseMocks } from './lib/mock-request'\nimport { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers'\nimport { signalFromNodeResponse } from './web/spec-extension/adapters/next-request'\nimport { loadManifest } from './load-manifest.external'\nimport { lazyRenderAppPage } from './route-modules/app-page/module.render'\nimport { lazyRenderPagesPage } from './route-modules/pages/module.render'\nimport { interopDefault } from '../lib/interop-default'\nimport { formatDynamicImportPath } from '../lib/format-dynamic-import-path'\nimport type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'\nimport { isInterceptionRouteRewrite } from '../lib/is-interception-route-rewrite'\nimport type { ServerOnInstrumentationRequestError } from './app-render/types'\nimport type { PrefetchHints } from '../shared/lib/app-router-types'\nimport { RouteKind } from './route-kind'\nimport { InvariantError } from '../shared/lib/invariant-error'\nimport { AwaiterOnce } from './after/awaiter'\nimport { AsyncCallbackSet } from './lib/async-callback-set'\nimport { initializeCacheHandlers, setCacheHandler } from './use-cache/handlers'\nimport type { UnwrapPromise } from '../lib/coalesced-function'\nimport { populateStaticEnv } from '../lib/static-env'\nimport { NodeModuleLoader } from './lib/module-loader/node-module-loader'\nimport { NoFallbackError } from '../shared/lib/no-fallback-error.external'\nimport {\n  ensureInstrumentationRegistered,\n  getInstrumentationModule,\n} from './lib/router-utils/instrumentation-globals.external'\nimport {\n  RouterServerContextSymbol,\n  routerServerGlobal,\n} from './lib/router-utils/router-server-context'\nimport { installGlobalBehaviors } from './node-environment-extensions/global-behaviors'\nimport { installProcessErrorHandlers } from './node-environment-extensions/process-error-handlers'\n\nexport * from './base-server'\n\n// For module that can be both CJS or ESM\nconst dynamicImportEsmDefault = process.env.NEXT_MINIMAL\n  ? (id: string) =>\n      import(/* webpackIgnore: true */ id).then((mod) => mod.default || mod)\n  : (id: string) => import(id).then((mod) => mod.default || mod)\n\nexport type NodeRequestHandler = BaseRequestHandler<\n  IncomingMessage | NodeNextRequest,\n  ServerResponse | NodeNextResponse\n>\n\ntype NodeRouteHandler = RouteHandler<NodeNextRequest, NodeNextResponse>\n\nconst MiddlewareMatcherCache = new WeakMap<\n  MiddlewareManifest['middleware'][string],\n  MiddlewareRouteMatch\n>()\n\nfunction getMiddlewareMatcher(\n  info: MiddlewareManifest['middleware'][string]\n): MiddlewareRouteMatch {\n  const stored = MiddlewareMatcherCache.get(info)\n  if (stored) {\n    return stored\n  }\n\n  if (!Array.isArray(info.matchers)) {\n    throw new Error(\n      `Invariant: invalid matchers for middleware ${JSON.stringify(info)}`\n    )\n  }\n\n  const matcher = getMiddlewareRouteMatcher(info.matchers)\n  MiddlewareMatcherCache.set(info, matcher)\n  return matcher\n}\n\nexport default class NextNodeServer extends BaseServer<\n  Options,\n  NodeNextRequest,\n  NodeNextResponse\n> {\n  protected middlewareManifestPath: string\n  private _serverDistDir: string | undefined\n  private imageResponseCache?: ResponseCache\n  private imageCacheHandler?: ICacheHandler\n  protected renderWorkersPromises?: Promise<void>\n  protected dynamicRoutes?: {\n    match: import('../shared/lib/router/utils/route-matcher').RouteMatchFn\n    page: string\n    re: RegExp\n  }[]\n  private routerServerHandler?: (\n    req: IncomingMessage,\n    res: ServerResponse\n  ) => void\n\n  protected cleanupListeners = new AsyncCallbackSet()\n  protected internalWaitUntil: WaitUntil | undefined\n  private isDev: boolean\n  private sriEnabled: boolean\n\n  constructor(options: Options) {\n    // Initialize super class\n    super(options)\n\n    installGlobalBehaviors(this.nextConfig)\n\n    // Load prefetch hints from the build output. This must happen before\n    // any render to ensure segment inlining decisions are available.\n    this.renderOpts.prefetchHints = this.getPrefetchHints()\n\n    const isDev = options.dev ?? false\n    this.isDev = isDev\n    this.sriEnabled = Boolean(options.conf.experimental?.sri?.algorithm)\n\n    /**\n     * This sets environment variable to be used at the time of SSR by head.tsx.\n     * Using this from process.env allows targeting SSR by calling\n     * `process.env.__NEXT_OPTIMIZE_CSS`.\n     */\n    if (this.renderOpts.optimizeCss) {\n      process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)\n    }\n    if (this.renderOpts.nextScriptWorkers) {\n      process.env.__NEXT_SCRIPT_WORKERS = JSON.stringify(true)\n    }\n\n    if (!this.minimalMode) {\n      this.imageResponseCache = new ResponseCache(this.minimalMode)\n    }\n\n    if (\n      !options.dev &&\n      !this.minimalMode &&\n      this.nextConfig.experimental.preloadEntriesOnStart\n    ) {\n      this.unstable_preloadEntries()\n    }\n\n    if (!options.dev) {\n      const { dynamicRoutes = [] } = this.getRoutesManifest() ?? {}\n      this.dynamicRoutes = dynamicRoutes.map((r) => {\n        // TODO: can we just re-use the regex from the manifest?\n        const regex = getRouteRegex(r.page)\n        const match = getRouteMatcher(regex)\n\n        return {\n          match,\n          page: r.page,\n          re: regex.re,\n        }\n      })\n    }\n\n    // ensure options are set when loadConfig isn't called\n    setHttpClientAndAgentOptions(this.nextConfig)\n\n    // Intercept fetch and other testmode apis.\n    if (this.serverOptions.experimentalTestProxy) {\n      process.env.NEXT_PRIVATE_TEST_PROXY = 'true'\n      const { interceptTestApis } =\n        // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm\n        require('next/dist/experimental/testmode/server') as typeof import('../experimental/testmode/server')\n      interceptTestApis()\n    }\n\n    this.middlewareManifestPath = join(\n      /* turbopackIgnore: true */ this.serverDistDir,\n      MIDDLEWARE_MANIFEST\n    )\n\n    // This is just optimization to fire prepare as soon as possible. It will be\n    // properly awaited later. We add the catch here to ensure that it does not\n    // cause a unhandled promise rejection. The promise rejection will be\n    // handled later on via the `await` when the request handler is called.\n    if (!options.dev) {\n      this.prepare().catch((err) => {\n        console.error('Failed to prepare server', err)\n      })\n    }\n\n    // when using compile mode static env isn't inlined so we\n    // need to populate in normal runtime env\n    if (this.renderOpts.isExperimentalCompile) {\n      // immutableAssetToken only works with Turbopack, and `isExperimentalCompile` isn't supported\n      // with that anyway, so we can assign immutableAssetToken to deploymentId here\n      populateStaticEnv(this.nextConfig, this.deploymentId || '')\n    }\n\n    const shouldRemoveUncaughtErrorAndRejectionListeners = Boolean(\n      options.conf.experimental?.removeUncaughtErrorAndRejectionListeners\n    )\n    installProcessErrorHandlers(shouldRemoveUncaughtErrorAndRejectionListeners)\n  }\n\n  public async unstable_preloadEntries(): Promise<void> {\n    // Ensure prepare process will be finished before preloading entries.\n    await this.prepare()\n\n    const appPathsManifest = this.getAppPathsManifest()\n    const pagesManifest = this.getPagesManifest()\n\n    await this.loadCustomCacheHandlers()\n\n    for (const page of Object.keys(pagesManifest || {})) {\n      try {\n        await loadComponents({\n          distDir: this.distDir,\n          page,\n          isAppPath: false,\n          isDev: this.isDev,\n          sriEnabled: this.sriEnabled,\n          needsManifestsForLegacyReasons: false,\n        })\n      } catch (_err) {\n        // Intentionally ignored because this is a preload step.\n      }\n    }\n\n    for (const page of Object.keys(appPathsManifest || {})) {\n      try {\n        const { ComponentMod } = await loadComponents<\n          AppPageModule | AppRouteModule\n        >({\n          distDir: this.distDir,\n          page,\n          isAppPath: true,\n          isDev: this.isDev,\n          sriEnabled: this.sriEnabled,\n          needsManifestsForLegacyReasons: false,\n        })\n        // we need to ensure fetch is patched before we require the page,\n        // otherwise if the fetch is patched by user code, we will be patching it\n        // too late and there won't be any caching behaviors\n        ComponentMod.patchFetch()\n      } catch (_err) {\n        // Intentionally ignored because this is a preload step.\n      }\n    }\n  }\n\n  protected async handleUpgrade(): Promise<void> {\n    // The web server does not support web sockets, it's only used for HMR in\n    // development.\n  }\n\n  protected async loadInstrumentationModule() {\n    if (!this.serverOptions.dev) {\n      try {\n        this.instrumentation = await getInstrumentationModule(\n          this.dir,\n          this.nextConfig.distDir\n        )\n      } catch (err: any) {\n        if (err.code !== 'MODULE_NOT_FOUND') {\n          throw new Error(\n            'An error occurred while loading the instrumentation hook',\n            { cause: err }\n          )\n        }\n      }\n    }\n    return this.instrumentation\n  }\n\n  protected async prepareImpl() {\n    await super.prepareImpl()\n    await this.runInstrumentationHookIfAvailable()\n  }\n\n  protected async runInstrumentationHookIfAvailable() {\n    await ensureInstrumentationRegistered(this.dir, this.nextConfig.distDir)\n  }\n\n  protected loadEnvConfig({\n    dev,\n    forceReload,\n  }: {\n    dev: boolean\n    forceReload: boolean\n  }) {\n    loadEnvConfig(\n      this.dir,\n      dev,\n      Log,\n      forceReload,\n      forceReload\n        ? (envFilePath) => {\n            Log.info(`Reload env: ${envFilePath}`)\n          }\n        : undefined\n    )\n  }\n\n  private async loadCustomCacheHandlers() {\n    const { cacheMaxMemorySize, cacheHandlers } = this.nextConfig\n    if (!cacheHandlers) return\n\n    // If we've already initialized the cache handlers interface, don't do it\n    // again.\n    if (!initializeCacheHandlers(cacheMaxMemorySize)) return\n\n    for (const [kind, handler] of Object.entries(cacheHandlers)) {\n      if (!handler) continue\n\n      setCacheHandler(\n        kind,\n        interopDefault(\n          await dynamicImportEsmDefault(\n            formatDynamicImportPath(this.distDir, handler)\n          )\n        )\n      )\n    }\n  }\n\n  protected async getIncrementalCache({\n    requestHeaders,\n  }: {\n    requestHeaders: IncrementalCache['requestHeaders']\n  }) {\n    const dev = !!this.dev\n    let CacheHandler: any\n    const { cacheHandler } = this.nextConfig\n\n    if (cacheHandler) {\n      CacheHandler = interopDefault(\n        await dynamicImportEsmDefault(\n          formatDynamicImportPath(this.distDir, cacheHandler)\n        )\n      )\n    }\n\n    await this.loadCustomCacheHandlers()\n\n    // incremental-cache is request specific\n    // although can have shared caches in module scope\n    // per-cache handler\n    return new IncrementalCache({\n      fs: this.getCacheFilesystem(),\n      dev,\n      requestHeaders,\n      allowedRevalidateHeaderKeys:\n        this.nextConfig.experimental.allowedRevalidateHeaderKeys,\n      minimalMode: this.minimalMode,\n      serverDistDir: this.serverDistDir,\n      fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,\n      maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize,\n      flushToDisk:\n        !this.minimalMode && this.nextConfig.experimental.isrFlushToDisk,\n      getPrerenderManifest: () => this.getPrerenderManifest(),\n      CurCacheHandler: CacheHandler,\n    })\n  }\n\n  protected getPublicDir(): string {\n    return join(/* turbopackIgnore: true */ this.dir, CLIENT_PUBLIC_FILES_PATH)\n  }\n\n  protected getHasStaticDir(): boolean {\n    return fs.existsSync(\n      /* turbopackIgnore: true */ join(\n        /* turbopackIgnore: true */ this.dir,\n        'static'\n      )\n    )\n  }\n\n  protected getPagesManifest(): PagesManifest | undefined {\n    return loadManifest(\n      join(/* turbopackIgnore: true */ this.serverDistDir, PAGES_MANIFEST)\n    ) as PagesManifest\n  }\n\n  protected getAppPathsManifest(): PagesManifest | undefined {\n    if (!this.enabledDirectories.app) return undefined\n\n    return loadManifest(\n      join(/* turbopackIgnore: true */ this.serverDistDir, APP_PATHS_MANIFEST)\n    ) as PagesManifest\n  }\n\n  protected getinterceptionRoutePatterns(): RegExp[] {\n    if (!this.enabledDirectories.app) return []\n\n    const routesManifest = this.getRoutesManifest()\n    return (\n      routesManifest?.rewrites.beforeFiles\n        .filter(isInterceptionRouteRewrite)\n        .map((rewrite) => new RegExp(rewrite.regex)) ?? []\n    )\n  }\n\n  protected async hasPage(pathname: string): Promise<boolean> {\n    return !!getMaybePagePath(\n      pathname,\n      this.distDir,\n      this.nextConfig.i18n?.locales,\n      this.enabledDirectories.app\n    )\n  }\n\n  protected getBuildId(): string {\n    const buildIdFile = join(\n      /* turbopackIgnore: true */ this.distDir,\n      BUILD_ID_FILE\n    )\n    try {\n      return fs\n        .readFileSync(/* turbopackIgnore: true */ buildIdFile, 'utf8')\n        .trim()\n    } catch (err: any) {\n      if (err.code === 'ENOENT') {\n        throw new Error(\n          `Could not find a production build in the '${this.distDir}' directory. Try building your app with 'next build' before starting the production server. https://nextjs.org/docs/messages/production-start-no-build-id`\n        )\n      }\n\n      throw err\n    }\n  }\n\n  protected getEnabledDirectories(dev: boolean): NextEnabledDirectories {\n    const dir = dev ? this.dir : this.serverDistDir\n\n    return {\n      app: findDir(dir, 'app') ? true : false,\n      pages: findDir(dir, 'pages') ? true : false,\n    }\n  }\n\n  protected sendRenderResult(\n    req: NodeNextRequest,\n    res: NodeNextResponse,\n    options: {\n      result: RenderResult\n      generateEtags: boolean\n      poweredByHeader: boolean\n      cacheControl: CacheControl | undefined\n    }\n  ): Promise<void> {\n    return sendRenderResult({\n      req: req.originalRequest,\n      res: res.originalResponse,\n      result: options.result,\n      generateEtags: options.generateEtags,\n      poweredByHeader: options.poweredByHeader,\n      cacheControl: options.cacheControl,\n    })\n  }\n\n  protected async runApi(\n    req: NodeNextRequest,\n    res: NodeNextResponse,\n    query: ParsedUrlQuery,\n    match: PagesAPIRouteMatch\n  ): Promise<boolean> {\n    const edgeFunctionsPages = this.getEdgeFunctionsPages()\n\n    for (const edgeFunctionsPage of edgeFunctionsPages) {\n      if (edgeFunctionsPage === match.definition.pathname) {\n        const handledAsEdgeFunction = await this.runEdgeFunction({\n          req,\n          res,\n          query,\n          params: match.params,\n          page: match.definition.pathname,\n          appPaths: null,\n        })\n\n        if (handledAsEdgeFunction) {\n          return true\n        }\n      }\n    }\n    // The module supports minimal mode, load the minimal module.\n    // Restore original URL as the handler handles it's own parsing\n    const parsedInitUrl = parseUrl(getRequestMeta(req, 'initURL') || req.url)\n    req.url = `${parsedInitUrl.pathname}${parsedInitUrl.search || ''}`\n\n    const loader = new NodeModuleLoader()\n    const module = (await loader.load(match.definition.filename)) as {\n      handler: (\n        req: IncomingMessage,\n        res: ServerResponse,\n        ctx: {\n          waitUntil: ReturnType<BaseServer['getWaitUntil']>\n        }\n      ) => Promise<void>\n    }\n    addRequestMeta(\n      req.originalRequest,\n      'relativeProjectDir',\n      relative(process.cwd(), this.dir)\n    )\n    addRequestMeta(req.originalRequest, 'distDir', this.distDir)\n    await module.handler(req.originalRequest, res.originalResponse, {\n      waitUntil: this.getWaitUntil(),\n    })\n    return true\n  }\n\n  protected async renderHTML(\n    req: NodeNextRequest,\n    res: NodeNextResponse,\n    pathname: string,\n    query: NextParsedUrlQuery,\n    renderOpts: LoadedRenderOpts\n  ): Promise<RenderResult> {\n    return getTracer().trace(NextNodeServerSpan.renderHTML, async () =>\n      this.renderHTMLImpl(req, res, pathname, query, renderOpts)\n    )\n  }\n\n  private async renderHTMLImpl(\n    req: NodeNextRequest,\n    res: NodeNextResponse,\n    pathname: string,\n    query: NextParsedUrlQuery,\n    renderOpts: LoadedRenderOpts\n  ): Promise<RenderResult> {\n    if (process.env.NEXT_MINIMAL) {\n      throw new Error(\n        'Invariant: renderHTML should not be called in minimal mode'\n      )\n      // the `else` branch is needed for tree-shaking\n    } else {\n      // Due to the way we pass data by mutating `renderOpts`, we can't extend the\n      // object here but only updating its `nextFontManifest` field.\n      // https://github.com/vercel/next.js/blob/df7cbd904c3bd85f399d1ce90680c0ecf92d2752/packages/next/server/render.tsx#L947-L952\n      renderOpts.nextFontManifest = this.nextFontManifest\n\n      if (this.enabledDirectories.app && renderOpts.isAppPath) {\n        return lazyRenderAppPage(\n          req,\n          res,\n          pathname,\n          query,\n          // This code path does not service revalidations for unknown param\n          // shells. As a result, we don't need to pass in the unknown params.\n          null,\n          renderOpts as LoadedRenderOpts<AppPageModule>,\n          this.getServerComponentsHmrCache(),\n          {\n            buildId: this.buildId,\n            deploymentId: this.deploymentId,\n            clientAssetToken:\n              this.nextConfig.experimental.immutableAssetToken ??\n              this.deploymentId,\n          }\n        )\n      } else {\n        // TODO: re-enable this once we've refactored to use implicit matches\n        // throw new Error('Invariant: render should have used routeModule')\n\n        return lazyRenderPagesPage(\n          req.originalRequest,\n          res.originalResponse,\n          pathname,\n          query,\n          renderOpts as LoadedRenderOpts<PagesModule>,\n          {\n            buildId: this.buildId,\n            deploymentId: this.deploymentId,\n            clientAssetToken:\n              this.nextConfig.experimental.immutableAssetToken ??\n              this.deploymentId,\n            customServer: this.serverOptions.customServer || undefined,\n          },\n          {\n            isFallback: false,\n            isDraftMode: renderOpts.isDraftMode,\n            developmentNotFoundSourcePage: getRequestMeta(\n              req,\n              'developmentNotFoundSourcePage'\n            ),\n          }\n        )\n      }\n    }\n  }\n\n  protected async imageOptimizer(\n    req: NodeNextRequest,\n    res: NodeNextResponse,\n    paramsResult: import('./image-optimizer').ImageParamsResult,\n    previousCacheEntry?: IncrementalResponseCacheEntry | null\n  ): Promise<{\n    buffer: Buffer\n    contentType: string\n    maxAge: number\n    upstreamEtag: string\n    etag: string\n  }> {\n    if (process.env.NEXT_MINIMAL) {\n      throw new Error(\n        'invariant: imageOptimizer should not be called in minimal mode'\n      )\n    } else {\n      const { imageOptimizer, fetchExternalImage, fetchInternalImage } =\n        require('./image-optimizer') as typeof import('./image-optimizer')\n\n      const handleInternalReq = async (\n        newReq: IncomingMessage,\n        newRes: ServerResponse\n      ) => {\n        if (newReq.url === req.url) {\n          throw new Error(`Invariant attempted to optimize _next/image itself`)\n        }\n\n        if (!this.routerServerHandler) {\n          throw new Error(`Invariant missing routerServerHandler`)\n        }\n\n        await this.routerServerHandler(newReq, newRes)\n        return\n      }\n\n      let { href } = paramsResult\n\n      if (\n        process.env.__NEXT_TEST_MODE &&\n        process.env.IS_TURBOPACK_TEST &&\n        !paramsResult.isAbsolute\n      ) {\n        // Forward the dpl query param from the original /_next/image request to the\n        // internal static file request so that the static file validation in\n        // resolve-routes.ts can verify it.\n        const dpl =\n          typeof req.url === 'string'\n            ? new URL(req.url, 'http://n').searchParams.get('dpl')\n            : undefined\n        if (dpl) {\n          href += `${href.includes('?') ? '&' : '?'}dpl=${dpl}`\n        }\n      }\n\n      const imageUpstream = paramsResult.isAbsolute\n        ? await fetchExternalImage(\n            href,\n            this.nextConfig.images.dangerouslyAllowLocalIP,\n            this.nextConfig.images.maximumResponseBody,\n            this.nextConfig.images.maximumRedirects\n          )\n        : await fetchInternalImage(\n            href,\n            req.originalRequest,\n            res.originalResponse,\n            handleInternalReq\n          )\n\n      return imageOptimizer(imageUpstream, paramsResult, this.nextConfig, {\n        isDev: this.dev,\n        previousCacheEntry,\n      })\n    }\n  }\n\n  protected getPagePath(pathname: string, locales?: string[]): string {\n    return getPagePath(\n      pathname,\n      this.distDir,\n      locales,\n      this.enabledDirectories.app\n    )\n  }\n\n  protected async renderPageComponent(\n    ctx: RequestContext<NodeNextRequest, NodeNextResponse>,\n    bubbleNoFallback: boolean\n  ) {\n    const edgeFunctionsPages = this.getEdgeFunctionsPages() || []\n    if (edgeFunctionsPages.length) {\n      const appPaths = this.getOriginalAppPaths(ctx.pathname)\n      const isAppPath = Array.isArray(appPaths)\n\n      let page = ctx.pathname\n      if (isAppPath) {\n        // When it's an array, we need to pass all parallel routes to the loader.\n        page = appPaths[0]\n      }\n\n      for (const edgeFunctionsPage of edgeFunctionsPages) {\n        if (edgeFunctionsPage === page) {\n          await this.runEdgeFunction({\n            req: ctx.req,\n            res: ctx.res,\n            query: ctx.query,\n            params: ctx.renderOpts.params,\n            page,\n            appPaths,\n          })\n          return null\n        }\n      }\n    }\n\n    return super.renderPageComponent(ctx, bubbleNoFallback)\n  }\n\n  protected async findPageComponents({\n    locale,\n    page,\n    query,\n    params,\n    isAppPath,\n    url,\n  }: {\n    locale: string | undefined\n    page: string\n    query: NextParsedUrlQuery\n    params: Params\n    isAppPath: boolean\n    // The following parameters are used in the development server's\n    // implementation.\n    sriEnabled?: boolean\n    appPaths?: ReadonlyArray<string> | null\n    shouldEnsure: boolean\n    url?: string\n  }): Promise<FindComponentsResult | null> {\n    return getTracer().trace(\n      NextNodeServerSpan.findPageComponents,\n      {\n        spanName: 'resolve page components',\n        attributes: {\n          'next.route': isAppPath ? normalizeAppPath(page) : page,\n        },\n      },\n      () =>\n        this.findPageComponentsImpl({\n          locale,\n          page,\n          query,\n          params,\n          isAppPath,\n          url,\n        })\n    )\n  }\n\n  private async findPageComponentsImpl({\n    locale,\n    page,\n    query,\n    params,\n    isAppPath,\n    url: _url,\n  }: {\n    locale: string | undefined\n    page: string\n    query: NextParsedUrlQuery\n    params: Params\n    isAppPath: boolean\n    url?: string\n  }): Promise<FindComponentsResult | null> {\n    const pagePaths: string[] = [page]\n\n    if (locale) {\n      pagePaths.unshift(\n        ...pagePaths.map((path) => `/${locale}${path === '/' ? '' : path}`)\n      )\n    }\n\n    for (const pagePath of pagePaths) {\n      try {\n        const components = await loadComponents({\n          distDir: this.distDir,\n          page: pagePath,\n          isAppPath,\n          isDev: this.isDev,\n          sriEnabled: this.sriEnabled,\n          needsManifestsForLegacyReasons: false,\n        })\n\n        if (\n          locale &&\n          typeof components.Component === 'string' &&\n          !pagePath.startsWith(`/${locale}/`) &&\n          pagePath !== `/${locale}`\n        ) {\n          // if loading an static HTML file the locale is required\n          // to be present since all HTML files are output under their locale\n          continue\n        }\n\n        return {\n          components,\n          query: {\n            ...(!this.renderOpts.isExperimentalCompile &&\n            components.getStaticProps\n              ? {}\n              : query),\n            // For appDir params is excluded.\n            ...((isAppPath ? {} : params) || {}),\n          },\n        }\n      } catch (err) {\n        // we should only not throw if we failed to find the page\n        // in the pages-manifest\n        if (!(err instanceof PageNotFoundError)) {\n          throw err\n        }\n      }\n    }\n    return null\n  }\n\n  protected getNextFontManifest(): NextFontManifest | undefined {\n    return loadManifest(\n      join(\n        /* turbopackIgnore: true */ this.distDir,\n        'server',\n        NEXT_FONT_MANIFEST + '.json'\n      )\n    ) as NextFontManifest\n  }\n\n  protected handleNextImageRequest: NodeRouteHandler = async (\n    req,\n    res,\n    parsedUrl\n  ) => {\n    if (!parsedUrl.pathname || !parsedUrl.pathname.startsWith('/_next/image')) {\n      return false\n    }\n    // Ignore if its a middleware request\n    if (getRequestMeta(req, 'middlewareInvoke')) {\n      return false\n    }\n\n    if (\n      this.minimalMode ||\n      this.nextConfig.output === 'export' ||\n      process.env.NEXT_MINIMAL\n    ) {\n      res.statusCode = 400\n      res.body('Bad Request').send()\n      return true\n      // the `else` branch is needed for tree-shaking\n    } else {\n      const { ImageOptimizerCache } =\n        require('./image-optimizer') as typeof import('./image-optimizer')\n\n      // Load custom cache handler if configured and opt-in via images.customCacheHandler\n      // Cache the handler instance to preserve state across requests\n      if (\n        !this.imageCacheHandler &&\n        this.nextConfig.images.customCacheHandler\n      ) {\n        const { cacheHandler } = this.nextConfig\n        if (cacheHandler) {\n          const CacheHandler = interopDefault(\n            await dynamicImportEsmDefault(\n              formatDynamicImportPath(this.distDir, cacheHandler)\n            )\n          )\n          this.imageCacheHandler = new CacheHandler({\n            dev: !!this.dev,\n            flushToDisk: this.nextConfig.experimental.isrFlushToDisk,\n            serverDistDir: this.serverDistDir,\n            maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize,\n            revalidatedTags: [],\n            _requestHeaders: {},\n          })\n        }\n      }\n\n      const imageOptimizerCache = new ImageOptimizerCache({\n        distDir: this.distDir,\n        nextConfig: this.nextConfig,\n        cacheHandler: this.imageCacheHandler,\n      })\n\n      const { sendResponse, ImageError } =\n        require('./image-optimizer') as typeof import('./image-optimizer')\n\n      if (!this.imageResponseCache) {\n        throw new Error('invariant image optimizer cache was not initialized')\n      }\n      const imagesConfig = this.nextConfig.images\n\n      if (imagesConfig.loader !== 'default' || imagesConfig.unoptimized) {\n        await this.render404(req, res)\n        return true\n      }\n\n      const paramsResult = ImageOptimizerCache.validateParams(\n        req.originalRequest,\n        parsedUrl.query,\n        this.nextConfig,\n        !!this.dev\n      )\n\n      if ('errorMessage' in paramsResult) {\n        res.statusCode = 400\n        res.body(paramsResult.errorMessage).send()\n        return true\n      }\n\n      const cacheKey = ImageOptimizerCache.getCacheKey(paramsResult)\n\n      try {\n        const { getExtension } =\n          require('./serve-static') as typeof import('./serve-static')\n        const cacheEntry = await this.imageResponseCache.get(\n          cacheKey,\n          async ({ previousCacheEntry }) => {\n            const { buffer, contentType, maxAge, upstreamEtag, etag } =\n              await this.imageOptimizer(\n                req,\n                res,\n                paramsResult,\n                previousCacheEntry\n              )\n\n            return {\n              value: {\n                kind: CachedRouteKind.IMAGE,\n                buffer,\n                etag,\n                extension: getExtension(contentType) as string,\n                upstreamEtag,\n              },\n              cacheControl: { revalidate: maxAge, expire: undefined },\n            }\n          },\n          {\n            routeKind: RouteKind.IMAGE,\n            incrementalCache: imageOptimizerCache,\n            isFallback: false,\n          }\n        )\n\n        if (cacheEntry?.value?.kind !== CachedRouteKind.IMAGE) {\n          throw new Error(\n            'invariant did not get entry from image response cache'\n          )\n        }\n\n        sendResponse(\n          req.originalRequest,\n          res.originalResponse,\n          paramsResult.href,\n          cacheEntry.value.extension,\n          cacheEntry.value.buffer,\n          cacheEntry.value.etag,\n          paramsResult.isStatic,\n          cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT',\n          imagesConfig,\n          cacheEntry.cacheControl?.revalidate || 0,\n          Boolean(this.dev)\n        )\n        return true\n      } catch (err) {\n        if (err instanceof ImageError) {\n          res.statusCode = err.statusCode\n          res.body(err.message).send()\n          return true\n        }\n        throw err\n      }\n    }\n  }\n\n  protected handleCatchallRenderRequest: NodeRouteHandler = async (\n    req,\n    res,\n    parsedUrl\n  ) => {\n    let { pathname, query } = parsedUrl\n    if (!pathname) {\n      throw new Error('Invariant: pathname is undefined')\n    }\n\n    // When in minimal mode we do not bubble the fallback as the\n    // router-server is not present to handle the error\n    addRequestMeta(req, 'bubbleNoFallback', this.minimalMode ? undefined : true)\n\n    // This is needed to expose render404 and nextConfig\n    // for environments without router-server\n    if (!routerServerGlobal[RouterServerContextSymbol]) {\n      routerServerGlobal[RouterServerContextSymbol] = {}\n    }\n    const relativeProjectDir = relative(process.cwd(), this.dir)\n    const existingServerContext =\n      routerServerGlobal[RouterServerContextSymbol][relativeProjectDir]\n\n    if (!existingServerContext) {\n      routerServerGlobal[RouterServerContextSymbol][relativeProjectDir] = {\n        render404: this.render404.bind(this),\n      }\n    }\n    routerServerGlobal[RouterServerContextSymbol][\n      relativeProjectDir\n    ].nextConfig = this.nextConfig\n    routerServerGlobal[RouterServerContextSymbol][\n      relativeProjectDir\n    ].isWrappedByNextServer = true\n\n    try {\n      // next.js core assumes page path without trailing slash\n      pathname = removeTrailingSlash(pathname)\n\n      const options: MatchOptions = {\n        i18n: this.i18nProvider?.fromRequest(req, pathname),\n      }\n      const match = await this.matchers.match(pathname, options)\n\n      // If we don't have a match, try to render it anyways.\n      if (!match) {\n        await this.render(req, res, pathname, query, parsedUrl, true)\n\n        return true\n      }\n\n      // Add the match to the request so we don't have to re-run the matcher\n      // for the same request.\n      addRequestMeta(req, 'match', match)\n\n      // TODO-APP: move this to a route handler\n      const edgeFunctionsPages = this.getEdgeFunctionsPages()\n      for (const edgeFunctionsPage of edgeFunctionsPages) {\n        // If the page doesn't match the edge function page, skip it.\n        if (edgeFunctionsPage !== match.definition.page) continue\n\n        if (this.nextConfig.output === 'export') {\n          await this.render404(req, res, parsedUrl)\n          return true\n        }\n        delete query[NEXT_RSC_UNION_QUERY]\n\n        // If we handled the request, we can return early.\n        // For api routes edge runtime\n        try {\n          const handled = await this.runEdgeFunction({\n            req,\n            res,\n            query,\n            params: match.params,\n            page: match.definition.page,\n            match,\n            appPaths: null,\n          })\n          if (handled) return true\n        } catch (apiError) {\n          const silenceLog = false\n          await this.instrumentationOnRequestError(\n            apiError,\n            req,\n            {\n              routePath: match.definition.page,\n              routerKind: 'Pages Router',\n              routeType: 'route',\n              // Edge runtime does not support ISR\n              revalidateReason: undefined,\n            },\n            silenceLog\n          )\n          throw apiError\n        }\n      }\n\n      // If the route was detected as being a Pages API route, then handle\n      // it.\n      // TODO: move this behavior into a route handler.\n      if (isPagesAPIRouteMatch(match)) {\n        if (this.nextConfig.output === 'export') {\n          await this.render404(req, res, parsedUrl)\n          return true\n        }\n\n        const handled = await this.handleApiRequest(req, res, query, match)\n        if (handled) return true\n      }\n\n      await this.render(req, res, pathname, query, parsedUrl, true)\n\n      return true\n    } catch (err: any) {\n      if (err instanceof NoFallbackError) {\n        throw err\n      }\n\n      try {\n        if (this.dev) {\n          const { formatServerError } =\n            require('../lib/format-server-error') as typeof import('../lib/format-server-error')\n          formatServerError(err)\n          this.logErrorWithOriginalStack(err)\n        } else {\n          this.logError(err)\n        }\n        res.statusCode = 500\n        await this.renderError(err, req, res, pathname, query)\n        return true\n      } catch {}\n\n      throw err\n    }\n  }\n\n  // Used in development only, overloaded in next-dev-server\n  protected logErrorWithOriginalStack(\n    _err?: unknown,\n    _type?: 'unhandledRejection' | 'uncaughtException' | 'warning' | 'app-dir'\n  ): void {\n    throw new Error(\n      'Invariant: logErrorWithOriginalStack can only be called on the development server'\n    )\n  }\n\n  // Used in development only, overloaded in next-dev-server\n  protected async ensurePage(_opts: {\n    page: string\n    clientOnly: boolean\n    appPaths?: ReadonlyArray<string> | null\n    match?: RouteMatch\n    url?: string\n  }): Promise<void> {\n    throw new Error(\n      'Invariant: ensurePage can only be called on the development server'\n    )\n  }\n\n  /**\n   * Resolves `API` request, in development builds on demand\n   * @param req http request\n   * @param res http response\n   * @param pathname path of request\n   */\n  protected async handleApiRequest(\n    req: NodeNextRequest,\n    res: NodeNextResponse,\n    query: ParsedUrlQuery,\n    match: PagesAPIRouteMatch\n  ): Promise<boolean> {\n    return this.runApi(req, res, query, match)\n  }\n\n  protected getCacheFilesystem(): CacheFs {\n    return nodeFs\n  }\n\n  protected normalizeReq(\n    req: NodeNextRequest | IncomingMessage\n  ): NodeNextRequest {\n    return !(req instanceof NodeNextRequest) ? new NodeNextRequest(req) : req\n  }\n\n  protected normalizeRes(\n    res: NodeNextResponse | ServerResponse\n  ): NodeNextResponse {\n    return !(res instanceof NodeNextResponse) ? new NodeNextResponse(res) : res\n  }\n\n  public getRequestHandler(): NodeRequestHandler {\n    const handler = this.makeRequestHandler()\n    if (this.serverOptions.experimentalTestProxy) {\n      const { wrapRequestHandlerNode } =\n        // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm\n        require('next/dist/experimental/testmode/server') as typeof import('../experimental/testmode/server')\n      return wrapRequestHandlerNode(handler)\n    }\n    return handler\n  }\n\n  /**\n   * @internal - this method is internal to Next.js and should not be used directly by end-users\n   */\n  public getRequestHandlerWithMetadata(meta: RequestMeta): NodeRequestHandler {\n    const handler = this.makeRequestHandler()\n    return (req, res, parsedUrl) => {\n      setRequestMeta(req, meta)\n      return handler(req, res, parsedUrl)\n    }\n  }\n\n  private makeRequestHandler(): NodeRequestHandler {\n    // This is just optimization to fire prepare as soon as possible. It will be\n    // properly awaited later. We add the catch here to ensure that it does not\n    // cause an unhandled promise rejection. The promise rejection will be\n    // handled later on via the `await` when the request handler is called.\n    this.prepare().catch((err) => {\n      console.error('Failed to prepare server', err)\n    })\n\n    const handler = super.getRequestHandler()\n\n    return (req, res, parsedUrl) =>\n      handler(this.normalizeReq(req), this.normalizeRes(res), parsedUrl)\n  }\n\n  public async revalidate({\n    urlPath,\n    headers,\n    opts,\n  }: {\n    urlPath: string\n    headers: { [key: string]: string | string[] }\n    opts: { unstable_onlyGenerated?: boolean }\n  }) {\n    const mocked = createRequestResponseMocks({\n      url: urlPath,\n      headers,\n    })\n\n    const handler = this.getRequestHandler()\n    await handler(\n      new NodeNextRequest(mocked.req),\n      new NodeNextResponse(mocked.res)\n    )\n    await mocked.res.hasStreamed\n\n    if (\n      mocked.res.getHeader('x-nextjs-cache') !== 'REVALIDATED' &&\n      mocked.res.statusCode !== 200 &&\n      !(mocked.res.statusCode === 404 && opts.unstable_onlyGenerated)\n    ) {\n      throw new Error(`Invalid response ${mocked.res.statusCode}`)\n    }\n  }\n\n  public async render(\n    req: NodeNextRequest | IncomingMessage,\n    res: NodeNextResponse | ServerResponse,\n    pathname: string,\n    query?: NextParsedUrlQuery,\n    parsedUrl?: NextUrlWithParsedQuery,\n    internal = false\n  ): Promise<void> {\n    return super.render(\n      this.normalizeReq(req),\n      this.normalizeRes(res),\n      pathname,\n      query,\n      parsedUrl,\n      internal\n    )\n  }\n\n  public async renderToHTML(\n    req: NodeNextRequest | IncomingMessage,\n    res: NodeNextResponse | ServerResponse,\n    pathname: string,\n    query?: ParsedUrlQuery\n  ): Promise<string | null> {\n    return super.renderToHTML(\n      this.normalizeReq(req),\n      this.normalizeRes(res),\n      pathname,\n      query\n    )\n  }\n\n  protected async renderErrorToResponseImpl(\n    ctx: RequestContext<NodeNextRequest, NodeNextResponse>,\n    err: Error | null\n  ) {\n    const { req, res, query } = ctx\n    const is404 = res.statusCode === 404\n\n    if (is404 && this.enabledDirectories.app) {\n      if (this.dev) {\n        await this.ensurePage({\n          page: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,\n          clientOnly: false,\n          url: req.url,\n        }).catch(() => {})\n      }\n\n      if (\n        this.getEdgeFunctionsPages().includes(UNDERSCORE_NOT_FOUND_ROUTE_ENTRY)\n      ) {\n        await this.runEdgeFunction({\n          req,\n          res,\n          query: query || {},\n          params: {},\n          page: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,\n          appPaths: null,\n        })\n        return null\n      }\n    }\n    return super.renderErrorToResponseImpl(ctx, err)\n  }\n\n  public async renderError(\n    err: Error | null,\n    req: NodeNextRequest | IncomingMessage,\n    res: NodeNextResponse | ServerResponse,\n    pathname: string,\n    query?: NextParsedUrlQuery,\n    setHeaders?: boolean\n  ): Promise<void> {\n    return super.renderError(\n      err,\n      this.normalizeReq(req),\n      this.normalizeRes(res),\n      pathname,\n      query,\n      setHeaders\n    )\n  }\n\n  public async renderErrorToHTML(\n    err: Error | null,\n    req: NodeNextRequest | IncomingMessage,\n    res: NodeNextResponse | ServerResponse,\n    pathname: string,\n    query?: ParsedUrlQuery\n  ): Promise<string | null> {\n    return super.renderErrorToHTML(\n      err,\n      this.normalizeReq(req),\n      this.normalizeRes(res),\n      pathname,\n      query\n    )\n  }\n\n  public async render404(\n    req: NodeNextRequest | IncomingMessage,\n    res: NodeNextResponse | ServerResponse,\n    parsedUrl?: NextUrlWithParsedQuery,\n    setHeaders?: boolean\n  ): Promise<void> {\n    return super.render404(\n      this.normalizeReq(req),\n      this.normalizeRes(res),\n      parsedUrl,\n      setHeaders\n    )\n  }\n\n  protected getMiddlewareManifest(): MiddlewareManifest | null {\n    if (this.minimalMode) {\n      return null\n    } else {\n      const manifest: MiddlewareManifest = require(this.middlewareManifestPath)\n      return manifest\n    }\n  }\n\n  /** Returns the middleware routing item if there is one. */\n  protected async getMiddleware(): Promise<MiddlewareRoutingItem | undefined> {\n    const manifest = this.getMiddlewareManifest()\n    const middleware = manifest?.middleware?.['/']\n    if (!middleware) {\n      const middlewareModule = await this.loadNodeMiddleware()\n\n      if (middlewareModule) {\n        return {\n          match: getMiddlewareRouteMatcher(\n            middlewareModule.config?.matchers || [\n              { regexp: '.*', originalSource: '/:path*' },\n            ]\n          ),\n          page: '/',\n        }\n      }\n\n      return\n    }\n\n    return {\n      match: getMiddlewareMatcher(middleware),\n      page: '/',\n    }\n  }\n\n  protected getEdgeFunctionsPages(): string[] {\n    const manifest = this.getMiddlewareManifest()\n    if (!manifest) {\n      return []\n    }\n\n    return Object.keys(manifest.functions)\n  }\n\n  /**\n   * Get information for the edge function located in the provided page\n   * folder. If the edge function info can't be found it will throw\n   * an error.\n   */\n  protected getEdgeFunctionInfo(params: {\n    page: string\n    /** Whether we should look for a middleware or not */\n    middleware: boolean\n  }): {\n    name: string\n    paths: string[]\n    wasm: { filePath: string; name: string }[]\n    env: { [key: string]: string }\n    assets?: { filePath: string; name: string }[]\n  } | null {\n    const manifest = this.getMiddlewareManifest()\n    if (!manifest) {\n      return null\n    }\n\n    let foundPage: string\n\n    try {\n      foundPage = denormalizePagePath(normalizePagePath(params.page))\n    } catch (err) {\n      return null\n    }\n\n    let pageInfo = params.middleware\n      ? manifest.middleware[foundPage]\n      : manifest.functions[foundPage]\n\n    if (!pageInfo) {\n      if (!params.middleware) {\n        throw new PageNotFoundError(foundPage)\n      }\n      return null\n    }\n\n    return {\n      name: pageInfo.name,\n      paths: pageInfo.files.map((file) =>\n        join(/* turbopackIgnore: true */ this.distDir, file)\n      ),\n      wasm: (pageInfo.wasm ?? []).map((binding) => ({\n        ...binding,\n        filePath: join(\n          /* turbopackIgnore: true */ this.distDir,\n          binding.filePath\n        ),\n      })),\n      assets:\n        pageInfo.assets &&\n        pageInfo.assets.map((binding) => {\n          return {\n            ...binding,\n            filePath: join(\n              /* turbopackIgnore: true */ this.distDir,\n              binding.filePath\n            ),\n          }\n        }),\n      env: pageInfo.env,\n    }\n  }\n\n  private async loadNodeMiddleware() {\n    if (!process.env.NEXT_MINIMAL) {\n      try {\n        const functionsConfig = this.dev\n          ? {}\n          : require(\n              join(\n                /* turbopackIgnore: true */ this.distDir,\n                'server',\n                FUNCTIONS_CONFIG_MANIFEST\n              )\n            )\n\n        if (this.dev || functionsConfig?.functions?.['/_middleware']) {\n          // if used with top level await, this will be a promise\n          return require(\n            join(\n              /* turbopackIgnore: true */ this.distDir,\n              'server',\n              'middleware.js'\n            )\n          )\n        }\n      } catch (err) {\n        if (\n          isError(err) &&\n          err.code !== 'ENOENT' &&\n          err.code !== 'MODULE_NOT_FOUND'\n        ) {\n          throw err\n        }\n      }\n    }\n  }\n\n  /**\n   * Checks if a middleware exists. This method is useful for the development\n   * server where we need to check the filesystem. Here we just check the\n   * middleware manifest.\n   */\n  protected async hasMiddleware(pathname: string): Promise<boolean> {\n    const info = this.getEdgeFunctionInfo({ page: pathname, middleware: true })\n    const nodeMiddleware = await this.loadNodeMiddleware()\n\n    if (!info && nodeMiddleware) {\n      return true\n    }\n    return Boolean(info && info.paths.length > 0)\n  }\n\n  /**\n   * A placeholder for a function to be defined in the development server.\n   * It will make sure that the root middleware or an edge function has been compiled\n   * so that we can run it.\n   */\n  protected async ensureMiddleware(_url?: string) {}\n  protected async ensureEdgeFunction(_params: {\n    page: string\n    appPaths: string[] | null\n    url?: string\n  }) {}\n\n  /**\n   * This method gets all middleware matchers and execute them when the request\n   * matches. It will make sure that each middleware exists and is compiled and\n   * ready to be invoked. The development server will decorate it to add warns\n   * and errors with rich traces.\n   */\n  protected async runMiddleware(params: {\n    request: NodeNextRequest\n    response: NodeNextResponse\n    parsedUrl: ParsedUrl\n    parsed: NextUrlWithParsedQuery\n    onWarning?: (warning: Error) => void\n  }) {\n    if (process.env.NEXT_MINIMAL) {\n      throw new Error(\n        'invariant: runMiddleware should not be called in minimal mode'\n      )\n    }\n\n    // Middleware is skipped for on-demand revalidate requests\n    if (\n      checkIsOnDemandRevalidate(params.request, this.renderOpts.previewProps)\n        .isOnDemandRevalidate\n    ) {\n      return {\n        response: new Response(null, { headers: { 'x-middleware-next': '1' } }),\n      } as FetchEventResult\n    }\n\n    let url: string\n\n    if (this.nextConfig.skipProxyUrlNormalize) {\n      url = getRequestMeta(params.request, 'initURL')!\n    } else {\n      // For middleware to \"fetch\" we must always provide an absolute URL\n      const query = urlQueryToSearchParams(params.parsed.query).toString()\n      const locale = getRequestMeta(params.request, 'locale')\n\n      url = `${getRequestMeta(params.request, 'initProtocol')}://${\n        this.fetchHostname || 'localhost'\n      }:${this.port}${locale ? `/${locale}` : ''}${params.parsed.pathname}${\n        query ? `?${query}` : ''\n      }`\n    }\n\n    if (!url.startsWith('http')) {\n      throw new Error(\n        'To use middleware you must provide a `hostname` and `port` to the Next.js Server'\n      )\n    }\n\n    const page: {\n      name?: string\n      params?: { [key: string]: string | string[] }\n    } = {}\n\n    const middleware = await this.getMiddleware()\n    if (!middleware) {\n      return { finished: false }\n    }\n    if (!(await this.hasMiddleware(middleware.page))) {\n      return { finished: false }\n    }\n\n    await this.ensureMiddleware(params.request.url)\n    const middlewareInfo = this.getEdgeFunctionInfo({\n      page: middleware.page,\n      middleware: true,\n    })\n\n    const method = (params.request.method || 'GET').toUpperCase()\n    const requestData = {\n      headers: params.request.headers,\n      method,\n      nextConfig: {\n        basePath: this.nextConfig.basePath,\n        i18n: this.nextConfig.i18n,\n        trailingSlash: this.nextConfig.trailingSlash,\n        experimental: this.nextConfig.experimental,\n      },\n      url: url,\n      page,\n      body:\n        method !== 'GET' && method !== 'HEAD'\n          ? (getRequestMeta(params.request, 'clonableBody') as any)\n          : undefined,\n\n      signal: signalFromNodeResponse(params.response.originalResponse),\n      waitUntil: this.getWaitUntil(),\n    }\n    let result:\n      | UnwrapPromise<ReturnType<typeof import('./web/sandbox').run>>\n      | undefined\n\n    // if no middleware info check for Node.js middleware\n    // this is not in the middleware-manifest as that historically\n    // has only included edge-functions, we need to do a breaking\n    // version bump for that manifest to write this info there if\n    // we decide we want to\n    if (!middlewareInfo) {\n      let middlewareModule\n      middlewareModule = await this.loadNodeMiddleware()\n\n      if (!middlewareModule) {\n        throw new MiddlewareNotFoundError()\n      }\n      const adapterFn: typeof import('./web/adapter').adapter =\n        middlewareModule.default || middlewareModule\n\n      const hasRequestBody =\n        !['HEAD', 'GET'].includes(params.request.method) &&\n        Boolean(requestData.body)\n\n      try {\n        result = await adapterFn({\n          handler:\n            middlewareModule.proxy ||\n            middlewareModule.middleware ||\n            middlewareModule,\n          request: {\n            ...requestData,\n            body: hasRequestBody\n              ? requestData.body.cloneBodyStream()\n              : undefined,\n          },\n          page: 'middleware',\n        })\n      } finally {\n        if (hasRequestBody) {\n          await requestData.body.finalize()\n        }\n      }\n    } else {\n      const { run } = require('./web/sandbox') as typeof import('./web/sandbox')\n\n      result = await run({\n        distDir: this.distDir,\n        name: middlewareInfo.name,\n        paths: middlewareInfo.paths,\n        edgeFunctionEntry: middlewareInfo,\n        request: requestData,\n        useCache: true,\n        onWarning: params.onWarning,\n        clientAssetToken:\n          this.nextConfig.experimental.immutableAssetToken || this.deploymentId,\n      })\n    }\n\n    if (!this.dev) {\n      result.waitUntil.catch((error) => {\n        console.error(`Uncaught: middleware waitUntil errored`, error)\n      })\n    }\n\n    if (!result) {\n      this.render404(params.request, params.response, params.parsed)\n      return { finished: true }\n    }\n\n    // Split compound (comma-separated) set-cookie headers\n    if (result.response.headers.has('set-cookie')) {\n      const cookies = result.response.headers\n        .getSetCookie()\n        .flatMap((maybeCompoundCookie) =>\n          splitCookiesString(maybeCompoundCookie)\n        )\n\n      // Clear existing header(s)\n      result.response.headers.delete('set-cookie')\n\n      // Append each cookie individually.\n      for (const cookie of cookies) {\n        result.response.headers.append('set-cookie', cookie)\n      }\n\n      // Add cookies to request meta.\n      addRequestMeta(params.request, 'middlewareCookie', cookies)\n    }\n\n    return result\n  }\n\n  protected handleCatchallMiddlewareRequest: NodeRouteHandler = async (\n    req,\n    res,\n    parsed\n  ) => {\n    const isMiddlewareInvoke = getRequestMeta(req, 'middlewareInvoke')\n\n    if (!isMiddlewareInvoke) {\n      return false\n    }\n\n    const handleFinished = () => {\n      addRequestMeta(req, 'middlewareInvoke', true)\n      res.body('').send()\n      return true\n    }\n\n    const middleware = await this.getMiddleware()\n    if (!middleware) {\n      return handleFinished()\n    }\n\n    const initUrl = getRequestMeta(req, 'initURL')!\n    const parsedUrl = parseUrl(initUrl)\n    const pathnameInfo = getNextPathnameInfo(parsedUrl.pathname, {\n      nextConfig: this.nextConfig,\n      i18nProvider: this.i18nProvider,\n    })\n\n    parsedUrl.pathname = pathnameInfo.pathname\n    const normalizedPathname = removeTrailingSlash(parsed.pathname || '')\n    let maybeDecodedPathname = normalizedPathname\n\n    try {\n      maybeDecodedPathname = decodeURIComponent(normalizedPathname)\n    } catch {\n      /* non-fatal we can't decode so can't match it */\n    }\n\n    if (\n      !(\n        middleware.match(normalizedPathname, req, parsedUrl.query) ||\n        middleware.match(maybeDecodedPathname, req, parsedUrl.query)\n      )\n    ) {\n      return handleFinished()\n    }\n\n    let result: Awaited<\n      ReturnType<typeof NextNodeServer.prototype.runMiddleware>\n    >\n    let bubblingResult = false\n\n    try {\n      await this.ensureMiddleware(req.url)\n\n      result = await this.runMiddleware({\n        request: req,\n        response: res,\n        parsedUrl: parsedUrl,\n        parsed: parsed,\n      })\n\n      if ('response' in result) {\n        if (isMiddlewareInvoke) {\n          bubblingResult = true\n          throw new BubbledError(true, result)\n        }\n\n        for (const [key, value] of Object.entries(\n          toNodeOutgoingHttpHeaders(result.response.headers)\n        )) {\n          if (key !== 'content-encoding' && value !== undefined) {\n            res.setHeader(key, value as string | string[])\n          }\n        }\n        res.statusCode = result.response.status\n\n        const { originalResponse } = res\n        if (result.response.body) {\n          await pipeToNodeResponse(result.response.body, originalResponse)\n        } else {\n          originalResponse.end()\n        }\n        return true\n      }\n    } catch (err: unknown) {\n      if (bubblingResult) {\n        throw err\n      }\n\n      if (isError(err) && err.code === 'ENOENT') {\n        await this.render404(req, res, parsed)\n        return true\n      }\n\n      if (err instanceof DecodeError) {\n        res.statusCode = 400\n        await this.renderError(err, req, res, parsed.pathname || '')\n        return true\n      }\n\n      const error = getProperError(err)\n      console.error(error)\n      res.statusCode = 500\n      await this.renderError(error, req, res, parsed.pathname || '')\n      return true\n    }\n\n    return result.finished\n  }\n\n  private _cachedPreviewManifest: PrerenderManifest | undefined\n  protected getPrerenderManifest(): PrerenderManifest {\n    if (this._cachedPreviewManifest) {\n      return this._cachedPreviewManifest\n    }\n\n    this._cachedPreviewManifest = loadManifest(\n      join(/* turbopackIgnore: true */ this.distDir, PRERENDER_MANIFEST)\n    ) as PrerenderManifest\n\n    return this._cachedPreviewManifest\n  }\n\n  private _cachedPrefetchHints: Record<string, PrefetchHints> | undefined\n  protected getPrefetchHints(): Record<string, PrefetchHints> {\n    if (this._cachedPrefetchHints) {\n      return this._cachedPrefetchHints\n    }\n\n    this._cachedPrefetchHints =\n      (loadManifest(\n        join(\n          /* turbopackIgnore: true */ this.distDir,\n          SERVER_DIRECTORY,\n          PREFETCH_HINTS\n        ),\n        true,\n        undefined,\n        false,\n        true // handleMissing: don't crash if the file doesn't exist\n      ) as Record<string, PrefetchHints>) ?? {}\n\n    return this._cachedPrefetchHints\n  }\n\n  protected getRoutesManifest(): NormalizedRouteManifest | undefined {\n    return getTracer().trace(\n      NextNodeServerSpan.getRoutesManifest,\n      () =>\n        loadManifest(\n          join(/* turbopackIgnore: true */ this.distDir, ROUTES_MANIFEST)\n        ) as RoutesManifest\n    )\n  }\n\n  protected attachRequestMeta(\n    req: NodeNextRequest,\n    parsedUrl: NextUrlWithParsedQuery,\n    isUpgradeReq?: boolean\n  ) {\n    // Injected in base-server.ts\n    const protocol = req.headers['x-forwarded-proto']?.includes('https')\n      ? 'https'\n      : 'http'\n\n    // When there are hostname and port we build an absolute URL\n    const initUrl =\n      this.fetchHostname && this.port\n        ? `${protocol}://${this.fetchHostname}:${this.port}${req.url}`\n        : this.nextConfig.experimental.trustHostHeader\n          ? `https://${req.headers.host || 'localhost'}${req.url}`\n          : req.url\n\n    addRequestMeta(req, 'initURL', initUrl)\n    addRequestMeta(req, 'initQuery', { ...parsedUrl.query })\n    addRequestMeta(req, 'initProtocol', protocol)\n\n    if (!isUpgradeReq) {\n      const bodySizeLimit = this.nextConfig.experimental\n        ?.proxyClientMaxBodySize as number | undefined\n      addRequestMeta(\n        req,\n        'clonableBody',\n        getCloneableBody(req.originalRequest, bodySizeLimit)\n      )\n    }\n  }\n\n  protected async runEdgeFunction(params: {\n    req: NodeNextRequest\n    res: NodeNextResponse\n    query: ParsedUrlQuery\n    params: Params | undefined\n    page: string\n    appPaths: string[] | null\n    match?: RouteMatch\n    onError?: (err: unknown) => void\n    onWarning?: (warning: Error) => void\n  }): Promise<FetchEventResult | null> {\n    if (process.env.NEXT_MINIMAL) {\n      throw new Error(\n        'Middleware is not supported in minimal mode. Please remove the `NEXT_MINIMAL` environment variable.'\n      )\n    }\n    let edgeInfo: ReturnType<typeof this.getEdgeFunctionInfo> | undefined\n\n    const { query, page, match } = params\n\n    if (!match)\n      await this.ensureEdgeFunction({\n        page,\n        appPaths: params.appPaths,\n        url: params.req.url,\n      })\n    edgeInfo = this.getEdgeFunctionInfo({\n      page,\n      middleware: false,\n    })\n\n    if (!edgeInfo) {\n      return null\n    }\n\n    // For edge to \"fetch\" we must always provide an absolute URL\n    const isNextDataRequest = getRequestMeta(params.req, 'isNextDataReq')\n    const initialUrl = new URL(\n      getRequestMeta(params.req, 'initURL') || '/',\n      'http://n'\n    )\n    const queryString = urlQueryToSearchParams({\n      ...Object.fromEntries(initialUrl.searchParams),\n      ...query,\n      ...params.params,\n    }).toString()\n\n    if (isNextDataRequest) {\n      params.req.headers['x-nextjs-data'] = '1'\n    }\n    initialUrl.search = queryString\n    const url = initialUrl.toString()\n\n    if (!url.startsWith('http')) {\n      throw new Error(\n        'To use middleware you must provide a `hostname` and `port` to the Next.js Server'\n      )\n    }\n\n    const { run } = require('./web/sandbox') as typeof import('./web/sandbox')\n    const result = await run({\n      distDir: this.distDir,\n      name: edgeInfo.name,\n      paths: edgeInfo.paths,\n      edgeFunctionEntry: edgeInfo,\n      request: {\n        headers: params.req.headers,\n        method: params.req.method,\n        nextConfig: {\n          basePath: this.nextConfig.basePath,\n          i18n: this.nextConfig.i18n,\n          trailingSlash: this.nextConfig.trailingSlash,\n        },\n        url,\n        page: {\n          name: params.page,\n          ...(params.params && { params: params.params }),\n        },\n        body: getRequestMeta(params.req, 'clonableBody'),\n        signal: signalFromNodeResponse(params.res.originalResponse),\n        waitUntil: this.getWaitUntil(),\n      },\n      useCache: true,\n      onError: params.onError,\n      onWarning: params.onWarning,\n      incrementalCache:\n        (globalThis as any).__incrementalCache ||\n        getRequestMeta(params.req, 'incrementalCache'),\n      serverComponentsHmrCache: getRequestMeta(\n        params.req,\n        'serverComponentsHmrCache'\n      ),\n      clientAssetToken:\n        this.nextConfig.experimental.immutableAssetToken || this.deploymentId,\n    })\n\n    if (result.fetchMetrics) {\n      params.req.fetchMetrics = result.fetchMetrics\n    }\n\n    if (!params.res.statusCode || params.res.statusCode < 400) {\n      params.res.statusCode = result.response.status\n      params.res.statusMessage = result.response.statusText\n    }\n\n    // TODO: (wyattjoh) investigate improving this\n\n    result.response.headers.forEach((value, key) => {\n      // The append handling is special cased for `set-cookie`.\n      if (key.toLowerCase() === 'set-cookie') {\n        // TODO: (wyattjoh) replace with native response iteration when we can upgrade undici\n        for (const cookie of splitCookiesString(value)) {\n          params.res.appendHeader(key, cookie)\n        }\n      } else {\n        params.res.appendHeader(key, value)\n      }\n    })\n\n    const { originalResponse } = params.res\n    if (result.response.body) {\n      await pipeToNodeResponse(result.response.body, originalResponse)\n    } else {\n      originalResponse.end()\n    }\n\n    return result\n  }\n\n  protected get serverDistDir(): string {\n    if (this._serverDistDir) {\n      return this._serverDistDir\n    }\n    const serverDistDir = join(\n      /* turbopackIgnore: true */ this.distDir,\n      SERVER_DIRECTORY\n    )\n    this._serverDistDir = serverDistDir\n    return serverDistDir\n  }\n\n  protected async getFallbackErrorComponents(\n    _url?: string\n  ): Promise<LoadComponentsReturnType<ErrorModule> | null> {\n    // Not implemented for production use cases, this is implemented on the\n    // development server.\n    return null\n  }\n\n  protected async instrumentationOnRequestError(\n    ...args: Parameters<ServerOnInstrumentationRequestError>\n  ) {\n    await super.instrumentationOnRequestError(...args)\n\n    // For Node.js runtime production logs, in dev it will be overridden by next-dev-server\n    if (!this.dev) {\n      const [err, , , silenceLog] = args\n      if (!silenceLog) {\n        this.logError(err)\n      }\n    }\n  }\n\n  protected onServerClose(listener: () => Promise<void>) {\n    this.cleanupListeners.add(listener)\n  }\n\n  async close(): Promise<void> {\n    await this.cleanupListeners.runAll()\n  }\n\n  protected getInternalWaitUntil(): WaitUntil {\n    this.internalWaitUntil ??= this.createInternalWaitUntil()\n    return this.internalWaitUntil\n  }\n\n  private createInternalWaitUntil() {\n    if (this.minimalMode) {\n      throw new InvariantError(\n        'createInternalWaitUntil should never be called in minimal mode'\n      )\n    }\n\n    const awaiter = new AwaiterOnce({ onError: console.error })\n\n    // TODO(after): warn if the process exits before these are awaited\n    this.onServerClose(() => awaiter.awaiting())\n\n    return awaiter.waitUntil\n  }\n}\n","import type { RouteMatch } from './route-match'\nimport type { PagesAPIRouteDefinition } from '../route-definitions/pages-api-route-definition'\n\nimport { RouteKind } from '../route-kind'\n\nexport interface PagesAPIRouteMatch\n  extends RouteMatch<PagesAPIRouteDefinition> {}\n\n/**\n * Checks if the given match is a Pages API route match.\n * @param match the match to check\n * @returns true if the match is a Pages API route match, false otherwise\n */\nexport function isPagesAPIRouteMatch(\n  match: RouteMatch\n): match is PagesAPIRouteMatch {\n  return match.definition.kind === RouteKind.PAGES_API\n}\n","/**\n * Unlike most files in the node-environment-extensions folder this one is not\n * an extension itself but it exposes a function to install config based global\n * behaviors that should be loaded whenever a Node Server or Node Worker are created.\n */\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nimport { setAbortedLogsStyle } from './console-dim.external'\n\nexport function installGlobalBehaviors(config: {\n  experimental?: { hideLogsAfterAbort?: boolean }\n}) {\n  if (process.env.NEXT_RUNTIME === 'edge') {\n    throw new InvariantError(\n      'Expected not to install Node.js global behaviors in the edge runtime.'\n    )\n  }\n\n  if (config.experimental?.hideLogsAfterAbort === true) {\n    setAbortedLogsStyle('hidden')\n  } else {\n    setAbortedLogsStyle('dimmed')\n  }\n}\n","import type { NextConfig } from '../types'\nimport { Agent as HttpAgent } from 'http'\nimport { Agent as HttpsAgent } from 'https'\n\nexport function setHttpClientAndAgentOptions(config: {\n  httpAgentOptions?: NextConfig['httpAgentOptions']\n}) {\n  if (globalThis.__NEXT_HTTP_AGENT) {\n    // We only need to assign once because we want\n    // to reuse the same agent for all requests.\n    return\n  }\n\n  if (!config) {\n    throw new Error('Expected config.httpAgentOptions to be an object')\n  }\n\n  globalThis.__NEXT_HTTP_AGENT_OPTIONS = config.httpAgentOptions\n  globalThis.__NEXT_HTTP_AGENT = new HttpAgent(config.httpAgentOptions)\n  globalThis.__NEXT_HTTPS_AGENT = new HttpsAgent(config.httpAgentOptions)\n}\n","import type {\n  NextConfigComplete,\n  NextConfigRuntime,\n} from '../server/config-shared'\n\nfunction errorIfEnvConflicted(\n  config: NextConfigComplete | NextConfigRuntime,\n  key: string\n) {\n  const isPrivateKey = /^(?:NODE_.+)|^(?:__.+)$/i.test(key)\n  const hasNextRuntimeKey = key === 'NEXT_RUNTIME'\n\n  if (isPrivateKey || hasNextRuntimeKey) {\n    throw new Error(\n      `The key \"${key}\" under \"env\" in ${config.configFileName || 'config'} is not allowed. https://nextjs.org/docs/messages/env-key-not-allowed`\n    )\n  }\n}\n\n/**\n * Collects all environment variables that are using the `NEXT_PUBLIC_` prefix.\n */\nexport function getNextPublicEnvironmentVariables() {\n  const defineEnv: [string, string | undefined][] = []\n  for (const key in process.env) {\n    if (key.startsWith('NEXT_PUBLIC_')) {\n      const value = process.env[key]\n      if (value != null) {\n        defineEnv.push([`process.env.${key}`, value])\n      }\n    }\n  }\n  defineEnv.sort((a, b) => a[0].localeCompare(b[0]))\n  return Object.fromEntries(defineEnv)\n}\n\n/**\n * Collects the `env` config value from the Next.js config.\n */\nexport function getNextConfigEnv(\n  config: NextConfigComplete | NextConfigRuntime\n) {\n  // Refactored code below to use for-of\n  const defineEnv: Record<string, string | undefined> = {}\n  const env = config.env\n  for (const key in env) {\n    const value = env[key]\n    if (value != null) {\n      errorIfEnvConflicted(config, key)\n      defineEnv[`process.env.${key}`] = value\n    }\n  }\n  return defineEnv\n}\n\nexport function getStaticEnv(\n  config: NextConfigComplete | NextConfigRuntime,\n  deploymentId: string\n) {\n  const staticEnv: Record<string, string | undefined> = {\n    ...getNextPublicEnvironmentVariables(),\n    ...getNextConfigEnv(config),\n    'process.env.NEXT_DEPLOYMENT_ID': deploymentId,\n  }\n  return staticEnv\n}\n\nexport function populateStaticEnv(\n  config: NextConfigComplete | NextConfigRuntime,\n  deploymentId: string\n) {\n  // since inlining comes after static generation we need\n  // to ensure this value is assigned to process env so it\n  // can still be accessed\n  const staticEnv = getStaticEnv(config, deploymentId)\n  for (const key in staticEnv) {\n    const innerKey = key.split('.').pop() || ''\n    if (!process.env[innerKey]) {\n      process.env[innerKey] = staticEnv[key] || ''\n    }\n  }\n}\n","import type { IncomingMessage } from 'http'\nimport type { Readable } from 'stream'\nimport { PassThrough } from 'stream'\nimport bytes from 'next/dist/compiled/bytes'\n\nconst DEFAULT_BODY_CLONE_SIZE_LIMIT = 10 * 1024 * 1024 // 10MB\n\nexport function requestToBodyStream(\n  context: { ReadableStream: typeof ReadableStream },\n  KUint8Array: typeof Uint8Array,\n  stream: Readable\n) {\n  return new context.ReadableStream({\n    start: async (controller) => {\n      for await (const chunk of stream) {\n        controller.enqueue(new KUint8Array(chunk))\n      }\n      controller.close()\n    },\n  })\n}\n\nfunction replaceRequestBody<T extends IncomingMessage>(\n  base: T,\n  stream: Readable\n): T {\n  for (const key in stream) {\n    let v = stream[key as keyof Readable] as any\n    if (typeof v === 'function') {\n      v = v.bind(base)\n    }\n    base[key as keyof T] = v\n  }\n\n  return base\n}\n\nexport interface CloneableBody {\n  finalize(): Promise<void>\n  cloneBodyStream(): Readable\n}\n\nexport function getCloneableBody<T extends IncomingMessage>(\n  readable: T,\n  sizeLimit?: number\n): CloneableBody {\n  let buffered: Readable | null = null\n\n  const endPromise = new Promise<void | { error?: unknown }>(\n    (resolve, reject) => {\n      readable.on('end', resolve)\n      readable.on('error', reject)\n    }\n  ).catch((error) => {\n    return { error }\n  })\n\n  return {\n    /**\n     * Replaces the original request body if necessary.\n     * This is done because once we read the body from the original request,\n     * we can't read it again.\n     */\n    async finalize(): Promise<void> {\n      if (buffered) {\n        const res = await endPromise\n\n        if (res && typeof res === 'object' && res.error) {\n          throw res.error\n        }\n        replaceRequestBody(readable, buffered)\n        buffered = readable\n      }\n    },\n    /**\n     * Clones the body stream\n     * to pass into a middleware\n     */\n    cloneBodyStream() {\n      const input = buffered ?? readable\n      const p1 = new PassThrough()\n      const p2 = new PassThrough()\n\n      let bytesRead = 0\n      const bodySizeLimit = sizeLimit ?? DEFAULT_BODY_CLONE_SIZE_LIMIT\n      let limitExceeded = false\n\n      input.on('data', (chunk) => {\n        if (limitExceeded) return\n\n        bytesRead += chunk.length\n\n        if (bytesRead > bodySizeLimit) {\n          limitExceeded = true\n          const urlInfo = readable.url ? ` for ${readable.url}` : ''\n          console.warn(\n            // TODO(jiwon): Update this document link\n            `Request body exceeded ${bytes.format(bodySizeLimit)}${urlInfo}. Only the first ${bytes.format(bodySizeLimit)} will be available unless configured. See https://nextjs.org/docs/app/api-reference/config/next-config-js/middlewareClientMaxBodySize for more details.`\n          )\n          p1.push(null)\n          p2.push(null)\n          return\n        }\n\n        p1.push(chunk)\n        p2.push(chunk)\n      })\n      input.on('end', () => {\n        if (!limitExceeded) {\n          p1.push(null)\n          p2.push(null)\n        }\n      })\n      buffered = p2\n      return p1\n    },\n  }\n}\n"],"names":["Symbol","Object","Error","reportError","r","e","t","process","n","Array","s","console","URL","Buffer","RangeError","JSON","__dirname","p","o","Boolean","a","Date","encodeURIComponent","Map","decodeURIComponent","Number","i","Math","isNaN","parseFloat","parseInt","__nccwpck_require__","TypeError","isFinite","NaN","arguments","Promise","setTimeout","clearTimeout","clearInterval","setInterval","u","RegExp","String","invalidServerComponentReactHooks","setMessage","error","message","stack","lines","split","join","getStackWithoutErrorMessage","replace","formatServerError","includes","addedMessage","clientHook","regex","test","globalThis","AsyncLocalStorage","require","WebSocket","defineProperty","configurable","get","set","value","writable","global","crypto","webcrypto","enumerable","module","codeFrameRenderer","webCrypto","inspectSymbol","errorConstructor","RenderStage","originalConstructor","originalNow","BaseServerSpan","LoadComponentsSpan","NextNodeServerSpan","RedirectStatusCode","RouteKind","CachedRouteKind","IncrementalCacheKind","LRUNode","constructor","key","data","size","prev","next","SentinelNode","LRUCache","maxSize","calculateSize","onEvict","cache","totalSize","head","tail","addToHead","node","removeNode","moveToHead","removeTail","lastNode","warn","existing","newNode","delete","has","iterator","current","remove","currentSize","invalidSourceMap","isAnonymousFrameLikelyJSNative","methodName","startsWith","url","length","regexNextStatic","env","stdout","enabled","NO_COLOR","FORCE_COLOR","isTTY","CI","TERM","replaceClose","str","close","index","start","substring","end","nextIndex","indexOf","formatter","open","input","string","bold","dim","italic","red","green","yellow","magenta","white","frameToString","sourceURL","line1","column1","fileLocation","sourceLocation","canParse","path","cwd","computeErrorName","name","shouldIgnoreListGeneratedFrame","file","createUnsourcemappedFrame","frame","ignored","code","for","prepareStackTrace","structuredStackTrace","toString","prototype","depth","inspectOptions","inspect","workUnitAsyncStorage","newError","sourceMapError","options","undefined","cause","AggregateError","errors","parseAndSourceMap","showIgnoreListed","__NEXT_SHOW_IGNORE_LISTED","unparsedStack","errorName","idx","lastIndexOf","slice","unsourcemappedStack","parseStack","distDir","__NEXT_DIST_DIR","map","line","frames","parse","res","exec","pathname","effectiveDistDir","concat","pop","search","lineNumber","column","sourceMapCache","sourceMappedFrames","sourceFrame","push","sourcemappedFrame","getSourcemappedFrameIfPossible","applicableSourceMap","sourceMap","sourceMapConsumer","sourceMapPayload","codeFrame","sourceMapCacheEntry","maybeSourceMapPayload","nativeFindSourceMap","payload","sourceMapURL","devirtualizeReactServerURL","envIdx","suffixIdx","decodeURI","SyncSourceMapConsumer","sourcePosition","originalPositionFor","findApplicableSourceMapPayload","line0","column0","sections","left","right","result","middle","section","offset","ignoreList","sources","source","sourceIndex","originalFrame","getOriginalCodeFrame","colors","sourceContentFor","ignoreListAnonymousStackFramesIfSandwichedGeneric","isAnonymousFrame","isIgnoredFrame","getMethodName","ignoreFrame","currentFrame","previousFrameIsIgnored","ignoreSandwich","j","nextFrame","sourceMappedStack","hasOwnProperty","call","originalCustomInspect","patchConsoleMethod","descriptor","getOwnPropertyDescriptor","originalMethod","originalName","wrapperMethod","args","apply","InvariantError","endsWith","abortOnSynchronousPlatformIOAccess","route","expression","errorWithStack","prerenderStore","dynamicTracking","digest","controller","abort","dynamicAccesses","isDebugDynamicAccesses","syncDynamicErrorWithStack","WeakMap","React","isDynamicPostponeReason","reason","io","type","workUnitStore","workStore","workAsyncStorage","prerenderSignal","signal","aborted","stageController","stagedRendering","shouldTrackSyncInterrupt","currentStage","accessStatement","additionalInfoLink","syncIOError","syncInterruptCurrentStageWithReason","_random","random","bind","properties","construct","newConstructor","getOwnPropertyDescriptors","now","Reflect","defineProperties","getRandomValuesExpression","_getRandomValues","getRandomValues","_randomUUID","randomUUID","nodeCrypto","randomUUIDExpression","randomBytesExpression","_randomBytes","randomBytes","randomFillSyncExpression","_randomFillSync","randomFillSync","_randomInt","randomInt","generatePrimeSyncExpression","_generatePrimeSync","generatePrimeSync","generateKeyPairSyncExpression","_generateKeyPairSync","generateKeyPairSync","generateKeySyncExpression","_generateKeySync","generateKeySync","mod","originalRequire","resolveFilename","_resolveFilename","resolve","__non_webpack_require__","hookPropertyMap","defaultOverrides","assign","dirname","_","addHookAliases","aliases","toResolveMap","resolveMap","entries","originalResolveFilename","requestMap","request","parent","isMain","hookResolved","basename","SP","performance","every","method","DecodeError","NormalizeError","PageNotFoundError","page","MissingStaticPage","PARAM_SEPARATOR","hasAdjacentParameterIssues","normalizeAdjacentParameters","normalized","stripNormalizedSeparators","safePathToRegexp","keys","pathToRegexp","needsNormalization","routeToUse","normalizedRoute","retryError","safeCompile","compiler","compile","params","getRouteMatcher","re","groups","matcherFn","routeMatch","decode","param","group","match","pos","repeat","entry","cleaned","isArray","item","NEXT_REQUEST_META","getRequestMeta","req","meta","addRequestMeta","removeRequestMeta","UNDERSCORE_NOT_FOUND_ROUTE","UNDERSCORE_NOT_FOUND_ROUTE_ENTRY","PAGES_MANIFEST","APP_PATHS_MANIFEST","SERVER_DIRECTORY","features","typescript","BLOCKED_PAGES","STATIC_STATUS_PAGES","findDir","dir","curDir","fs","ReflectAdapter","target","prop","receiver","deleteProperty","ReadonlyHeadersError","callable","HeadersAdapter","Headers","headers","Proxy","lowercased","toLowerCase","original","find","seal","merge","from","append","forEach","callbackfn","thisArg","values","HTML_CONTENT_TYPE_HEADER","NEXT_QUERY_PARAM_PREFIX","NEXT_INTERCEPTION_MARKER_PREFIX","MATCHED_PATH_HEADER","RSC_SEGMENTS_DIR_SUFFIX","RSC_SEGMENT_SUFFIX","RSC_SUFFIX","NEXT_DATA_SUFFIX","NEXT_META_SUFFIX","NEXT_CACHE_TAGS_HEADER","NEXT_CACHE_REVALIDATED_TAGS_HEADER","WEBPACK_LAYERS_NAMES","shared","reactServerComponents","serverSideRendering","actionBrowser","apiNode","apiEdge","middleware","instrument","edgeAsset","appPagesBrowser","pagesDirBrowser","pagesDirEdge","pagesDirNode","GROUP","builtinReact","serverOnly","neutralTarget","clientOnly","bundled","appPages","SYMBOL_CLEARED_COOKIES","getCookieParser","cookie","parseCookieFn","BaseNextRequest","body","cookies","_cookies","BaseNextResponse","destination","redirect","statusCode","setHeader","NodeNextRequest","_req","toUpperCase","fetchMetrics","streaming","originalRequest","stream","ReadableStream","on","chunk","enqueue","Uint8Array","err","NodeNextResponse","originalResponse","_res","textBody","sent","finished","headersSent","statusMessage","removeHeader","getHeaderValues","getHeader","hasHeader","getHeaders","appendHeader","currentValues","send","onClose","callback","sendRenderResult","generateEtags","poweredByHeader","cacheControl","contentType","getCacheControlHeader","revalidate","expire","swrHeader","isDynamic","toUnchunkedString","etag","generateETag","weak","prefix","fnv1a52","len","t0","v0","t1","v1","t2","v2","t3","v3","charCodeAt","fresh","byteLength","pipeToNodeResponse","searchParamsToUrlQuery","searchParams","query","stringifyUrlQueryParam","parseUrl","parseRelativeUrl","base","parseQuery","globalBase","resolvedBase","hash","href","origin","protocol","host","auth","hostname","port","slashes","parsedURL","username","password","prefixes","wait","ready","info","event","trace","LOGGING_METHOD","log","prefixedLog","prefixType","shift","consoleMethod","bootstrap","warnOnceCache","warnOnce","errorOnceCache","errorOnce","parseMaxPostponedStateSize","bytes","freeze","webpack","ignoreBuildErrors","tsconfigPath","typedRoutes","cleanDistDir","assetPrefix","cacheHandler","NEXT_CACHE_HANDLER_PATH","cacheMaxMemorySize","configOrigin","useFileSystemPublicRoutes","generateBuildId","pageExtensions","compress","images","deviceSizes","imageSizes","loader","loaderFile","domains","disableStaticImages","minimumCacheTTL","formats","maximumDiskCacheSize","maximumRedirects","maximumResponseBody","dangerouslyAllowLocalIP","dangerouslyAllowSVG","contentSecurityPolicy","contentDispositionType","localPatterns","remotePatterns","qualities","unoptimized","customCacheHandler","devIndicators","position","onDemandEntries","maxInactiveAge","pagesBufferLength","basePath","sassOptions","trailingSlash","i18n","productionBrowserSourceMaps","excludeDefaultMomentLocales","reactProductionProfiling","reactStrictMode","reactMaxHeadersLength","httpAgentOptions","keepAlive","logging","serverFunctions","expireTime","NEXT_PRIVATE_CDN_CONSUMED_SWR_CACHE_CONTROL","staticPageGenerationTimeout","output","NEXT_PRIVATE_STANDALONE","modularizeImports","outputFileTracingRoot","NEXT_PRIVATE_OUTPUT_TRACE_ROOT","allowedDevOrigins","enablePrerenderSourceMaps","cacheComponents","cacheLife","default","stale","seconds","minutes","hours","days","weeks","max","cacheHandlers","NEXT_DEFAULT_CACHE_HANDLER_PATH","remote","NEXT_REMOTE_CACHE_HANDLER_PATH","static","NEXT_STATIC_CACHE_HANDLER_PATH","adapterPath","NEXT_ADAPTER_PATH","experimental","appNewScrollHandler","useSkewCookie","cssChunking","multiZoneDraftMode","appNavFailHandling","prerenderEarlyExit","serverMinification","linkNoTouchStart","caseSensitiveRoutes","clientParamParsingOrigins","cachedNavigations","partialFallbacks","dynamicOnHover","varyParams","prefetchInlining","preloadEntriesOnStart","clientRouterFilter","clientRouterFilterRedirects","fetchCacheKeyPrefix","proxyPrefetch","optimisticClientCache","manualClientBasePath","cpus","CIRCLE_NODE_TOTAL","os","memoryBasedWorkersCount","imgOptConcurrency","imgOptTimeoutInSeconds","imgOptMaxInputPixels","imgOptSequentialRead","imgOptSkipMetadata","isrFlushToDisk","workerThreads","proxyTimeout","optimizeCss","nextScriptWorkers","scrollRestoration","externalDir","disableOptimizedLoading","gzipSize","craCompat","esmExternals","fullySpecified","swcTraceProfiling","forceSwcTransforms","swcPlugins","largePageDataBytes","disablePostcssPresetEnv","urlImports","typedEnv","clientTraceMetadata","parallelServerCompiles","parallelServerBuildTraces","ppr","authInterrupts","webpackBuildWorker","webpackMemoryOptimizations","optimizeServerReact","strictRouteTypes","viewTransition","removeUncaughtErrorAndRejectionListeners","validateRSCRequestHeaders","__NEXT_TEST_MODE","__NEXT_VERSION","NEXT_PRIVATE_LOCAL_DEV","staleTimes","dynamic","allowDevelopmentBuild","reactDebugChannel","staticGenerationRetryCount","serverComponentsHmrCache","staticGenerationMaxConcurrency","staticGenerationMinPagesPerWorker","transitionIndicator","gestureTransition","inlineCss","useCache","slowModuleDetection","globalNotFound","browserDebugInfoInTerminal","lockDistDir","proxyClientMaxBodySize","hideLogsAfterAbort","mcpServer","turbopackFileSystemCacheForDev","turbopackFileSystemCacheForBuild","turbopackInferModuleSideEffects","turbopackPluginRuntimeStrategy","htmlLimitedBots","bundlePagesRouterDependencies","v4Seg","v4Str","v6Seg","IPv6Reg","ensureLeadingSlash","normalizeAppPath","reduce","segment","segments","normalizeRscURL","INTERCEPTION_ROUTE_MARKERS","isInterceptionRouteAppPath","m","TEST_ROUTE","TEST_STRICT_ROUTE","isDynamicRoute","strict","extractInterceptionRouteInformation","interceptingRoute","marker","interceptedRoute","splitInterceptingRoute","HTML_LIMITED_BOT_UA_RE","HEADLESS_BROWSER_BOT_UA_RE","HTML_LIMITED_BOT_UA_RE_STRING","voidCatch","encoder","TextEncoder","streamFromString","encode","streamFromBuffer","streamToString","decoder","TextDecoder","fatal","splitCookiesString","cookiesString","ch","lastComma","nextStart","cookiesSeparatorFound","cookiesStrings","skipWhitespace","charAt","toNodeOutgoingHttpHeaders","nodeHeaders","validateURL","normalizeNextQueryParam","removeTrailingSlash","parsePath","hashIndex","queryIndex","hasQuery","addPathPrefix","addPathSuffix","suffix","pathHasPrefix","getHostname","parsed","normalizeLocalePath","locales","detectedLocale","lowercasedLocales","locale","removePathPrefix","withoutPrefix","getNextPathnameInfo","nextConfig","pathnameNoDataPrefix","paths","buildId","parseData","i18nProvider","analyze","REGEX_LOCALHOST_HOSTNAME","parseURL","Internal","NextURL","baseOrOpts","opts","__NEXT_NO_MIDDLEWARE_URL_NORMALIZE","domainLocale","detectDomainLocale","domainItems","domain","defaultLocale","some","formatPathname","addLocale","ignorePrefix","lower","forceLocale","formatSearch","toJSON","clone","PageSignatureError","RemovedPageError","RemovedUAError","INTERNALS","NextRequest","Request","init","duplex","nextUrl","RequestCookies","bodyUsed","credentials","fromEntries","integrity","keepalive","mode","referrer","referrerPolicy","ua","ResponseAbortedName","ResponseAborted","DetachedPromise","reject","promise","rej","clientComponentLoadStart","clientComponentLoadTimes","clientComponentLoadCount","isAbortError","readable","waitUntilForEnd","response","errored","destroyed","AbortController","once","writableFinished","writer","createWriterFromResponse","started","drained","onDrain","off","WritableStream","write","NEXT_OTEL_PERFORMANCE_PREFIX","metrics","getClientComponentLoaderMetrics","reset","measure","flushHeaders","getTracer","spanName","ok","flush","destroy","pipeTo","RenderResult","EMPTY","metadata","fromStatic","waitUntil","assignMetadata","isNull","isBuffer","chainStreams","streams","TransformStream","preventClose","nextStream","then","lastStream","catch","coerce","pipeThrough","transform","unshift","normalizePathSep","denormalizePagePath","_page","getPathMatch","regexp","delimiter","sensitive","matcher","regexpToFunction","regexModifier","flags","removeUnnamedParams","reHasRegExp","reReplaceRegExp","escapeStringRegexp","PARAMETER_PATTERN","parseMatchedParameter","optional","getRouteRegex","includeSuffix","includePrefix","excludeOptionalTrailingSlash","parameterizedRoute","getParametrizedRoute","groupIndex","markerMatch","paramMatches","getSafeKeyFromSegment","interceptionMarker","getSafeRouteKey","routeKeys","keyPrefix","backreferenceDuplicateKeys","pattern","cleanedKey","invalidKey","duplicateKey","interceptionPrefix","unescapeSegments","matchHas","missing","hasMatch","hasItem","getSafeParamName","paramName","newParamName","charCode","matches","groupKey","compileNonPath","validate","decodeQueryPathParameter","slashedProtocols","filterInternalQuery","paramKeys","isNextQueryPrefix","isNextInterceptionMarkerPrefix","isError","getProperError","seen","isPlainObject","getObjectClassLabel","getPrototypeOf","WeakSet","stringify","_key","add","ACTION_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","NEXT_URL","FLIGHT_HEADERS","NEXT_RSC_UNION_QUERY","LocaleRouteNormalizer","provider","normalize","UrlNode","insert","urlPath","_insert","filter","smoosh","_smoosh","childrenPaths","children","sort","slugName","splice","restSlugName","optionalRestSlugName","routes","c","curr","placeholder","urlPaths","slugNames","isCatchAll","nextSegment","segmentName","isOptional","handleSlug","previousSlug","nextSlug","slug","RouteMatcher","definition","identity","LocaleRouteMatcher","DefaultRouteMatcherManager","compilationID","providers","waitTillReady","waitTillReadyPromise","reload","root","matchers","providersMatchers","all","duplicates","providerMatchers","duplicated","duplicate","others","previousMatchers","cachedMatcher","reference","pathnames","indexes","sorted","normalizedPages","pagePath","sortedDynamicMatchers","dynamicMatches","lastCompilationID","matchAll","inferredFromDefault","skipDynamic","Normalizers","normalizers","normalizer","PrefixingNormalizer","normalizePagePath","posix","resolvedPage","UnderscoreNormalizer","AppBundlePathNormalizer","AppFilenameNormalizer","manifestFilename","isAppRouteRoute","getExtensionRegexString","staticExtensions","dynamicExtensions","FAVICON_REGEX","ROBOTS_TXT_REGEX","MANIFEST_JSON_REGEX","MANIFEST_WEBMANIFEST_REGEX","SITEMAP_XML_REGEX","compiledRegexCache","wrapNormalizerFn","fn","AppPathnameNormalizer","AppNormalizers","filename","bundlePath","AppPageRouteMatcher","CachedRouteMatcherProvider","cached","load","compare","ManifestRouteMatcherProvider","manifestName","manifestLoader","AppPageRouteMatcherProvider","manifest","pages","allAppPaths","appPaths","kind","AppRouteRouteMatcher","AppRouteRouteMatcherProvider","isAPIRoute","PagesAPIRouteMatcher","PagesAPILocaleRouteMatcher","PagesBundlePathNormalizer","PagesFilenameNormalizer","PagesNormalizers","PagesAPIRouteMatcherProvider","PagesRouteMatcher","PagesLocaleRouteMatcher","PagesRouteMatcherProvider","ServerManifestLoader","getter","I18NProvider","config","lowerCaseLocales","lowerCaseDomains","http","fromRequest","analysis","sendResponse","status","statusText","headersWithMultipleValuesAllowed","isHeaderPresent","SuffixPathnameNormalizer","matched","RSCPathnameNormalizer","PrefixPathnameNormalizer","NextDataPathnameNormalizer","buildID","toRoute","NEXT_REQUEST_CONTEXT_SYMBOL","REDIRECTS","Set","handleMiddlewareField","NextResponse","Response","cookiesProxy","ResponseCookies","newHeaders","getAll","stringifyCookie","redirected","json","initObj","rewrite","createDefaultCacheHandler","refreshTags","getExpiration","updateTags","memoryCache","pendingSets","debug","NEXT_PRIVATE_DEBUG_CACHE","cacheKey","pendingPromise","privateEntry","timeOrigin","timestamp","areTagsExpired","tags","areTagsStale","returnStream","newSaved","tee","pendingEntry","resolvePending","clonedValue","reader","getReader","read","done","isErrored","errorRetryCount","expiration","tag","tagsManifest","expired","durations","round","existingEntry","updates","handlersSymbol","handlersMapSymbol","handlersSetSymbol","NextRequestHint","sourcePage","respondWith","PATTERN","SegmentPrefixRSCPathnameNormalizer","extract","originalPathname","segmentPath","dynamicParamTypes","catchall","readBodyWithSizeLimit","maxBodySizeBytes","chunks","buffer","WrappedBuildError","innerError","Server","getServerComponentsHmrCache","__serverComponentsHmrCache","handleRSCRequest","parsedUrl","segmentPrefetchRSC","rsc","header","segmentPrefetchRSCRequest","formatUrl","handleNextDataRequest","getMiddleware","render404","lastParam","getRouteFromAssetPath","assetPath","ext","localePathResult","handleNextImageRequest","handleCatchallRenderRequest","handleCatchallMiddlewareRequest","normalizeAndAttachMetadata","enabledDirectories","prepared","preparedPromise","customErrorNo404Warn","execOnce","used","Log","quiet","conf","dev","minimalMode","experimentalTestProxy","serverOptions","loadEnvConfig","forceReload","runtimeServerDeploymentId","NEXT_DEPLOYMENT_ID","deploymentId","id","NEXT_CLIENT_ASSET_SUFFIX","immutableAssetToken","fetchHostname","formatHostname","isIPv6","publicDir","getPublicDir","hasStaticDir","getHasStaticDir","localeNormalizer","getBuildId","NEXT_PRIVATE_MINIMAL_MODE","getEnabledDirectories","isAppPPREnabled","app","checkIsAppPPREnabled","nextFontManifest","getNextFontManifest","renderOpts","supportsDynamicResponse","previewProps","getPrerenderManifest","preview","nextConfigOutput","domainLocales","serverComponents","cacheLifeProfiles","enableTainting","taint","crossOrigin","isExperimentalCompile","optimisticRouting","maxPostponedStateSizeBytes","maxPostponedStateSize","onInstrumentationRequestError","instrumentationOnRequestError","prefetchHints","logServerFunctions","pagesManifest","getPagesManifest","appPathsManifest","getAppPathsManifest","appPathRoutes","getAppPathRoutes","interceptionRoutePatterns","getinterceptionRoutePatterns","getRouteMatchers","setAssetPrefix","reloadMatchers","ctx","instrumentation","onRequestError","handlerErr","logError","handleRequest","prepare","tracer","withPropagatedContext","parentSpan","getActiveScopeSpan","SpanKind","attributes","span","handleRequestImpl","finally","isRSCRequest","setAttributes","setStatus","SpanStatusCode","setAttribute","rootSpanAttributes","getRootSpanAttributes","updateName","utils","middlewareValue","urlNoQuery","urlParts","cleanUrl","URLSearchParams","xForwardedProto","isHttps","socket","encrypted","remoteAddress","attachRequestMeta","parseUrlUtil","pathnameInfo","useMatchedPathHeader","matchedPath","fixMojibake","urlPathname","getMaxPostponedStateSize","configuredMaxPostponedStateSize","postponed","normalizedUrlPath","stripNextDataPath","localeAnalysisResult","srcPathname","pageIsDynamic","paramsResult","hasValidParams","getServerUtils","rewrites","caseSensitive","defaultRouteRegex","dynamicRouteMatcher","defaultRouteMatches","namedRegex","prefixRouteKeys","getNamedParametrizedRoute","names","intercepted","routeKey","fromCharCode","floor","inverseParts","structuredClone","hasInterceptionMarker","namedParameterizedRoute","pathToRegexpPattern","handleRewrites","rewrittenParsedUrl","rewriteParams","fsPathname","checkRewrite","hasParams","parsedDestination","destQuery","prepareDestination","destHostnameCompiler","newUrl","parseDestination","escaped","destHostname","destSearch","destPath","destParams","destPathParamKeys","destHostnameParamKeys","destPathCompiler","strOrArray","appendParamsToQuery","nextInternalLocale","dynamicParams","beforeFiles","fsPathnameNoSlash","afterFiles","fallback","normalizeQueryParams","routeParamKeys","normalizedKey","v","getParamsFromRouteMatches","routeMatchesHeader","routeMatches","obj","keyName","normalizeDynamicRouteParams","ignoreMissingOptional","defaultValue","isDefaultValue","defaultVal","val","normalizeCdnUrl","_parsedUrl","parseReqUrl","urlObj","querystring","interpolateDynamicPath","paramValue","builtParam","replaceAll","getRoutesManifest","originQueryParams","pathnameBeforeRewrite","rewriteParamKeys","rewrittenQueryParams","didRewrite","matcherParams","curParamsResult","renderError","webServerConfig","incrementalCache","getIncrementalCache","requestHeaders","resetRequestCache","__incrementalCache","invokePath","invokeStatus","invokeQuery","parsedMatchedPath","invokePathnameInfo","normalizeResult","bubble","run","NoFallbackError","getRequestHandlerWithMetadata","handler","getRequestHandler","loadInstrumentationModule","prepareImpl","normalizedPath","runImpl","pipe","partialContext","pipeImpl","blockingMetadataUARegex","botType","serveStreamingMetadata","userAgent","originalStatus","getStaticHTML","render","internalRender","renderImpl","getWaitUntil","builtinRequestContext","_globalThis","getInternalWaitUntil","customServer","hasPage","getBotType","renderToResponse","getStaticPaths","staticPaths","fallbackMode","parseFallbackField","fallbackField","dynamicRoutes","renderToResponseWithComponents","requestContext","findComponentsResult","renderToResponseWithComponentsImpl","pathCouldBeIntercepted","resolvedPathname","setVaryHeader","isAppPath","baseVaryHeader","addedNextUrlToVary","components","prerenderManifest","pathsResults","routeModule","actionId","isURLEncodedAction","isMultipartAction","isFetchAction","isErrorPathname","is404Page","is500Page","hasServerProps","getServerSideProps","isPossibleServerAction","getServerActionRequestMetadata","isSSG","getStaticProps","resolvedUrlPathname","hasFallback","isNextDataRequest","couldSupportPPR","hasDebugStaticShellQuery","__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING","__nextppronly","exposeTestingApi","exposeTestingApiInProductionBuild","hasInstantTestCookie","NEXT_INSTANT_TEST_COOKIE","minimalPostponed","isRoutePPREnabled","renderingMode","Component","isBotRequest","isDomBotUA","isSupportedDocument","Document","getInitialProps","NEXT_BUILTIN_DOCUMENT","isDev","getStaticPathsStart","hrtime","bigint","prerenderedRoutes","smallestFallbackRouteParams","fallbackRouteParams","createOpaqueFallbackRouteParams","uniqueID","paramType","parsedInitUrl","initPathname","ComponentMod","filePath","stripLocale","splitPath","getOriginalAppPaths","originalAppPath","renderPageComponent","bubbleNoFallback","findPageComponents","sriEnabled","sri","algorithm","shouldEnsure","setRootSpanAttribute","isNoFallbackError","renderToResponseImpl","existingMatch","fastPath","initUrl","rewrittenPathname","renderErrorToResponse","isWrappedError","renderToHTML","renderToHTMLImpl","setHeaders","renderErrorImpl","renderErrorToResponseImpl","is404","hasAppDir","statusPage","maybeFallbackError","renderToHtmlError","fallbackComponents","getFallbackErrorComponents","renderErrorToHTML","pagePathCache","getMaybePagePath","serverBuildPath","loadManifest","checkManifest","curPath","manifestNoLocales","getPagePath","requirePage","promises","interopDefault","ms","MANIFESTS_SINGLETON","globalThisWithManifests","loadManifestWithRetries","manifestPath","attempts","tryLoadManifestWithRetries","evalManifestWithRetries","evalManifest","tryLoadClientReferenceManifest","entryName","context","__RSC_MANIFEST","loadComponentsImpl","needsManifestsForLegacyReasons","DocumentMod","AppMod","reactLoadableManifestPath","manifestLoadAttempts","hasClientManifest","isMetadataRouteFile","appDirRelativePath","strictlyMatchExtensions","fastResult","regexes","getCompiledRegexes","trailingMatcher","suffixMatcher","variantsMatcher","robotsExts","manifestExts","buildManifest","reactLoadableManifest","dynamicCssManifest","clientReferenceManifest","serverActionsManifest","subresourceIntegrityManifest","SERVER_REFERENCE_MANIFEST","SUBRESOURCE_INTEGRITY_MANIFEST","setManifestsSingleton","rawServerActionsManifest","existingSingleton","encryptionKey","create","edge","clientReferenceManifestsPerRoute","mappingProxies","proxiedClientReferenceManifest","currentManifest","proxy","serverModuleMap","getServerActionsManifest","pageName","workerEntry","workers","getManifestsSingleton","manifestSingleton","at","moduleId","async","App","pageConfig","loadComponents","wrap","getMiddlewareRouteMatcher","parsePositiveInt","envValue","NEXT_PRIVATE_RESPONSE_CACHE_TTL","NEXT_PRIVATE_RESPONSE_CACHE_MAX_SIZE","MultiFileWriter","tasks","findOrCreateTask","directory","task","mkdir","writeFile","flatMap","FileSystemCache","flushToDisk","serverDistDir","revalidatedTags","maxMemoryCacheSize","getMemoryCache","revalidateTag","getFilePath","fileData","readFile","mtime","stat","lastModified","getTime","fetchIdx","fetchUrl","parsedData","storedTags","fetchCache","maybeSegmentData","rscData","segmentPaths","segmentData","segmentsDir","segmentDataFilePath","isFallback","html","pageData","tagsHeader","cacheTags","combinedTags","softTags","htmlPath","IncrementalCache","CurCacheHandler","allowedRevalidateHeaderKeys","locks","hasCustomCacheHandler","cacheHandlersSymbol","globalCacheHandler","FetchCache","__NEXT_TEST_MAX_ISR_CACHE","disableForTestmode","NEXT_PRIVATE_TEST_PROXY","cacheControls","SharedCacheControls","previewModeId","isOnDemandRevalidate","getPreviouslyRevalidatedTags","_requestHeaders","calculateRevalidate","fromTime","initialRevalidateSeconds","_getPathname","lock","generateCacheKey","bodyChunks","_ogBody","readableBody","total","arr","arrayBuffer","formData","text","blob","Blob","cacheString","createHash","update","cacheData","isStale","revalidateAfter","resumeDataCache","getRenderResumeDataCache","memoryCacheData","fetch","pendingRevalidatedTags","prerenderResumeDataCache","getPrerenderResumeDataCache","age","notFoundRoutes","itemSize","isImplicitBuildTimeCache","warningText","nodeFs","existsSync","readFileSync","f","d","recursive","MockedRequest","Stream","httpVersion","httpVersionMajor","httpVersionMinor","_target","bodyReadable","emit","headersDistinct","_read","connection","complete","trailers","trailersDistinct","rawTrailers","rawHeaders","MockedResponse","buffers","fromNodeOutgoingHttpHeaders","headPromise","headPromiseResolve","hasStreamed","resWriter","isSent","_implicitHeader","_write","_encoding","writeHead","getHeaderNames","strictContentLength","writeEarlyHints","assignSocket","detachSocket","writeContinue","writeProcessing","upgrading","chunkedEncoding","shouldKeepAlive","useChunkedEncodingByDefault","sendDate","addTrailers","formatDynamicImportPath","absoluteFilePath","pathToFileURL","isInterceptionRouteRewrite","AsyncCallbackSet","callbacks","runAll","allSettled","NodeModuleLoader","RouterServerContextSymbol","routerServerGlobal","REACT_POSTPONE_TYPE","isPostpone","$$typeof","_global","dynamicImportEsmDefault","MiddlewareMatcherCache","NextNodeServer","BaseServer","shouldRemoveUncaughtErrorAndRejectionListeners","cleanupListeners","relativeProjectDir","relative","isWrappedByNextServer","edgeFunctionsPage","getEdgeFunctionsPages","runEdgeFunction","apiError","routePath","routerKind","routeType","revalidateReason","handleApiRequest","logErrorWithOriginalStack","isMiddlewareInvoke","handleFinished","normalizedPathname","maybeDecodedPathname","bubblingResult","ensureMiddleware","runMiddleware","BubbledError","installGlobalBehaviors","setAbortedLogsStyle","getPrefetchHints","__NEXT_OPTIMIZE_CSS","__NEXT_SCRIPT_WORKERS","setHttpClientAndAgentOptions","__NEXT_HTTP_AGENT","__NEXT_HTTP_AGENT_OPTIONS","HttpAgent","__NEXT_HTTPS_AGENT","HttpsAgent","middlewareManifestPath","populateStaticEnv","staticEnv","getNextPublicEnvironmentVariables","defineEnv","b","localeCompare","getNextConfigEnv","errorIfEnvConflicted","isPrivateKey","hasNextRuntimeKey","configFileName","innerKey","nextInitializedProcessErrorHandlers","removeAllListeners","unstable_preloadEntries","loadCustomCacheHandlers","_err","patchFetch","handleUpgrade","getInstrumentationModule","runInstrumentationHookIfAvailable","ensureInstrumentationRegistered","envFilePath","initializeCacheHandlers","DefaultCache","RemoteCache","setCacheHandler","CacheHandler","getCacheFilesystem","routesManifest","buildIdFile","trim","runApi","renderHTML","renderHTMLImpl","imageOptimizer","previousCacheEntry","edgeFunctionsPages","findPageComponentsImpl","_url","pagePaths","NEXT_FONT_MANIFEST","_type","ensurePage","_opts","normalizeReq","normalizeRes","makeRequestHandler","mocked","createRequestResponseMocks","unstable_onlyGenerated","internal","getMiddlewareManifest","middlewareModule","loadNodeMiddleware","originalSource","getMiddlewareMatcher","stored","functions","getEdgeFunctionInfo","foundPage","pageInfo","files","wasm","binding","assets","hasMiddleware","nodeMiddleware","ensureEdgeFunction","_params","_cachedPreviewManifest","_cachedPrefetchHints","isUpgradeReq","trustHostHeader","buffered","endPromise","bodySizeLimit","finalize","replaceRequestBody","cloneBodyStream","p1","PassThrough","p2","bytesRead","sizeLimit","limitExceeded","urlInfo","_serverDistDir","silenceLog","onServerClose","listener","internalWaitUntil","createInternalWaitUntil"],"mappings":"2IAWA,IAAI,EAAqBA,OAAO,GAAG,CAAC,8BAClC,EAAoBA,OAAO,GAAG,CAAC,gBAS/B,GARsBA,OAAO,GAAG,CAAC,kBACRA,OAAO,GAAG,CAAC,qBACdA,OAAO,GAAG,CAAC,kBACXA,OAAO,GAAG,CAAC,kBACZA,OAAO,GAAG,CAAC,iBACPA,OAAO,GAAG,CAAC,qBACdA,OAAO,GAAG,CAAC,kBACfA,OAAO,GAAG,CAAC,cACXA,OAAO,GAAG,CAAC,eAG7B,GAFsBA,OAAO,GAAG,CAAC,kBACJA,OAAO,GAAG,CAAC,yBAChBA,OAAO,QAAQ,EAQrC,EAAuB,CACvB,UAAW,WACT,MAAO,CAAC,CACV,EACA,mBAAoB,WAAa,EACjC,oBAAqB,WAAa,EAClC,gBAAiB,WAAa,CAChC,EACA,EAASC,OAAO,MAAM,CACtB,EAAc,CAAC,EACjB,SAAS,EAAU,CAAK,CAAE,CAAO,CAAE,CAAO,EACxC,IAAI,CAAC,KAAK,CAAG,EACb,IAAI,CAAC,OAAO,CAAG,EACf,IAAI,CAAC,IAAI,CAAG,EACZ,IAAI,CAAC,OAAO,CAAG,GAAW,CAC5B,CAgBA,SAAS,IAAkB,CAE3B,SAAS,EAAc,CAAK,CAAE,CAAO,CAAE,CAAO,EAC5C,IAAI,CAAC,KAAK,CAAG,EACb,IAAI,CAAC,OAAO,CAAG,EACf,IAAI,CAAC,IAAI,CAAG,EACZ,IAAI,CAAC,OAAO,CAAG,GAAW,CAC5B,CAtBA,EAAU,SAAS,CAAC,gBAAgB,CAAG,CAAC,EACxC,EAAU,SAAS,CAAC,QAAQ,CAAG,SAAU,CAAY,CAAE,CAAQ,EAC7D,GACE,UAAa,OAAO,GACpB,YAAe,OAAO,GACtB,MAAQ,EAER,MAAMC,MACJ,0GAEJ,IAAI,CAAC,OAA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aAAA,EAEN,EAiHJ,CAEA,IAAc4oD,eAAwB,CACpC,GAAI,IAAI,CAAC8Q,cAAc,CACrB,OAAO,IAAI,CAACA,cAAc,CAE5B,IAAM9Q,EAAgB3lD,AAAAA,GAAAA,EAAAA,IAAAA,AAAAA,EACQ,IAAI,CAACoJ,OAAO,CACxC2N,IAGF,OADA,IAAI,CAAC0/C,cAAc,CAAG9Q,EACfA,CACT,CAEA,MAAgB5F,2BACd0T,CAAa,CAC0C,CAGvD,OAAO,IACT,CAEA,MAAgBzlB,8BACd,GAAGhgC,CAAqD,CACxD,CAIA,GAHA,MAAM,KAAK,CAACggC,iCAAiChgC,GAGzC,CAAC,IAAI,CAACm9B,GAAG,CAAE,CACb,GAAM,CAAC3uB,IAASk6C,EAAW,CAAG1oD,CAC1B,CAAC0oD,GACH,IAAI,CAACxnB,QAAQ,CAAC1yB,EAElB,CACF,CAEUm6C,cAAcC,CAA6B,CAAE,CACrD,IAAI,CAAC5H,gBAAgB,CAACpzB,GAAG,CAACg7B,EAC5B,CAEA,MAAMtxD,OAAuB,CAC3B,MAAM,IAAI,CAAC0pD,gBAAgB,CAACd,MAAM,EACpC,CAEU3U,sBAAkC,CAE1C,OADA,IAAI,CAACsd,iBAAiB,GAAK,IAAI,CAACC,uBAAuB,GAChD,IAAI,CAACD,iBAAiB,AAC/B,CAEQC,yBAA0B,CAE9B,MAAM,qBAEL,CAFK,IAAI5oD,GACR,kEADI,qB,MAAA,O,WAAA,G,aAAA,EAEN,EASJ,CACF,C","ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198]}