{"version":3,"file":"server.runtime.prod.js","sources":["webpack://next/../../node_modules/.pnpm/react@19.3.0-canary-cbb046ab-20260731/node_modules/react/cjs/react.production.js","webpack://next/../../node_modules/.pnpm/react@19.3.0-canary-cbb046ab-20260731/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/shared/lib/request-insights.ts","webpack://next/./src/server/lib/trace/request-insights.ts","webpack://next/./src/server/lib/trace/span-store.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/./dist/compiled/nanoid/index.cjs","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/node-environment-extensions/web-crypto.tsx","webpack://next/./src/server/lib/streaming-metadata.ts","webpack://next/./src/server/patch-error-inspect.ts","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/app-render/sync-io-messages.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/server/lib/is-ipv6.ts","webpack://next/./src/server/lib/is-non-html-sec-fetch-dest.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/shared/lib/escape-regexp.ts","webpack://next/./src/shared/lib/router/utils/remove-trailing-slash.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/server/stream-utils/node-web-streams-helper.ts","webpack://next/./src/server/stream-utils/encoded-tags.ts","webpack://next/./src/shared/lib/router/utils/cache-busting-search-param.ts","webpack://next/./src/server/web/utils.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/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/app-render/async-local-storage.ts","webpack://next/./src/server/lib/trace/request-insights-identity.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/lib/patch-set-header.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/async-storage/request-store.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/server/lib/is-rsc-request.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/fix-mojibake.ts","webpack://next/./src/lib/url.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/shared/lib/utils/reflect-utils.ts","webpack://next/./src/server/app-render/manifests-singleton.ts","webpack://next/./src/server/load-components.ts","webpack://next/./src/shared/lib/server-reference-info.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-cbb046ab-20260731\";\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={505: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.f=expand},207:(e,t,n)=>{const r=n(896);const o=n(928);const s=n(857);const i=n(982);const c=n(764);const a=c.version;const l=/(?:^|^)\\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=l.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=p.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=p.decrypt(o.ciphertext,o.key);break}catch(t){if(e+1>=o){throw t}}}return p.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=p._parseVault(e);let n=process.env;if(e&&e.processEnv!=null){n=e.processEnv}p.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=p.parse(r.readFileSync(t,{encoding:n}));let s=process.env;if(e&&e.processEnv!=null){s=e.processEnv}p.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 p.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 p.configDotenv(e)}return p._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 p={configDotenv:configDotenv,_configVault:_configVault,_parseVault:_parseVault,config:config,decrypt:decrypt,parse:parse,populate:populate};e.exports.configDotenv=p.configDotenv;e.exports._configVault=p._configVault;e.exports._parseVault=p._parseVault;e.exports.config=p.config;e.exports.decrypt=p.decrypt;e.exports.parse=p.parse;e.exports.populate=p.populate;e.exports=p},982:e=>{\"use strict\";e.exports=require(\"crypto\")},896:e=>{\"use strict\";e.exports=require(\"fs\")},857:e=>{\"use strict\";e.exports=require(\"os\")},928:e=>{\"use strict\";e.exports=require(\"path\")},764: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,loadEnvConfig:()=>loadEnvConfig,processEnv:()=>processEnv,resetEnv:()=>resetEnv,updateInitialEnv:()=>updateInitialEnv});var e=__nccwpck_require__(896);var t=__nccwpck_require__.n(e);var r=__nccwpck_require__(928);var o=__nccwpck_require__.n(r);var s=__nccwpck_require__(207);var i=__nccwpck_require__.n(s);var c=__nccwpck_require__(505);let a=undefined;let l=undefined;let p=undefined;let u=[];let _=[];function updateInitialEnv(e){if(!a){return}for(const[t,n]of Object.entries(e)){if(n===undefined){delete a[t]}else{a[t]=n}}}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 l;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 p=Object.assign({},a);const u={};for(const o of e){try{let e={};e.parsed=s.parse(o.contents);e=(0,c.f)(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 p[t]===\"undefined\"){u[t]=(l=e.parsed)===null||l===void 0?void 0:l[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(l&&!s){return{combinedEnv:l,parsedEnv:p,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)}}}[l,p]=processEnv(u,t,o,s,i);return{combinedEnv:l,parsedEnv:p,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={86: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__(86);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={928: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__(928);module.exports=a})();","(()=>{\"use strict\";var e={234: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}},274: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}))))}},294:(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},838:(e,t,n)=>{Object.defineProperty(t,\"__esModule\",{value:true});const r=n(294);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},138:(e,t,n)=>{const r=n(274);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__(234);const r=__nccwpck_require__(138);const i=__nccwpck_require__(838);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","export type RequestInsightKind = 'request' | 'instant-insights'\n\nexport type RequestInsightIdentity = {\n  requestId: string\n  kind?: RequestInsightKind\n}\n\nexport function getRequestInsightKind(\n  insight: Pick<RequestInsightIdentity, 'kind'>\n): RequestInsightKind {\n  return insight.kind ?? 'request'\n}\n\nexport function getRequestInsightKey(insight: RequestInsightIdentity): string {\n  return `${getRequestInsightKind(insight)}:${insight.requestId}`\n}\n","import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'\nimport type {\n  RequestInsight,\n  RequestInsightFetch,\n  RequestInsightsSnapshot,\n} from '../../../next-devtools/shared/request-insights'\nimport type { RequestInsightKind } from '../../../shared/lib/request-insights'\nimport {\n  getRequestInsightKey,\n  getRequestInsightKind,\n} from '../../../shared/lib/request-insights'\nimport type { SpanStoreRecord } from './span-store'\nexport { isRequestInsightsEnabled } from './span-store'\n\nconst MAX_REQUEST_INSIGHTS = 100\nconst REQUEST_INSIGHTS_STORE_KEY = Symbol.for('@next/request-insights-store')\nconst CLIENT_COMPONENT_LOADING_SPAN_TYPE =\n  'NextNodeServer.clientComponentLoading'\n\ntype RequestInsightsListener = (insight: RequestInsight) => void\ntype RequestInsightIdentity = {\n  requestId?: string\n  kind?: RequestInsightKind\n  htmlRequestId?: string\n  route?: string\n  url?: string\n}\n\nconst REDACTED_VALUE = 'redacted'\nconst SAFE_SPAN_ATTRIBUTE_KEYS = new Set([\n  'http.method',\n  'http.route',\n  'http.status_code',\n  'http.url',\n  'net.peer.name',\n  'net.peer.port',\n  'next.fetch.cache_reason',\n  'next.fetch.cache_status',\n  'next.fetch.idx',\n  'next.route',\n  'next.rsc',\n  'next.segment',\n  'next.span_category',\n  'next.span_name',\n  'next.span_type',\n])\nconst SENSITIVE_PARAM_NAME_RE =\n  /(?:^|[_-])(?:access[_-]?token|api[_-]?key|auth|authorization|code|cookie|credential|id[_-]?token|jwt|key|password|secret|session|signature|sig|token)(?:$|[_-])/i\n\nclass InMemoryRequestInsightsStore {\n  private readonly requests = new Map<string, RequestInsight>()\n  private readonly requestTimings = new Map<\n    string,\n    { startTime: number; durationMs: number }\n  >()\n  private readonly requestOrder: string[] = []\n  private readonly listeners = new Set<RequestInsightsListener>()\n\n  recordSpan(span: SpanStoreRecord): void {\n    if (!span.requestId) {\n      return\n    }\n\n    const insight = this.getOrCreateRequest(\n      {\n        requestId: span.requestId,\n        kind: span.requestInsightKind,\n        htmlRequestId: span.htmlRequestId,\n        route: span.route,\n        url: span.url,\n      },\n      span.startTime ?? span.timestamp\n    )\n\n    const spanStartTime = span.startTime ?? span.timestamp\n    insight.htmlRequestId = span.htmlRequestId ?? insight.htmlRequestId\n    insight.route = insight.route ?? span.route\n    insight.url = insight.url ?? sanitizeUrl(span.url)\n    this.updateTiming(\n      insight,\n      spanStartTime,\n      span.durationMs,\n      span.attributes?.['next.span_type'] === 'BaseServer.handleRequest'\n    )\n    insight.status =\n      insight.status === 'error' || span.status === 'error'\n        ? 'error'\n        : span.status === 'ok'\n          ? 'ok'\n          : insight.status\n\n    insight.spans.push({\n      name: span.name,\n      startTime: spanStartTime,\n      durationMs: span.durationMs,\n      status: span.status,\n      traceId: span.traceId,\n      spanId: span.spanId,\n      parentSpanId: span.parentSpanId,\n      attributes: sanitizeSpanAttributes(span.attributes),\n      links: sanitizeSpanLinks(span.links),\n      events: sanitizeSpanEvents(span.events),\n      error: span.error,\n    })\n\n    const fetch = getFetchInsight(span)\n    if (fetch) {\n      this.recordFetchForInsight(insight, fetch)\n    }\n\n    this.notify(insight)\n  }\n\n  recordFetch(identity: RequestInsightIdentity, fetch: RequestInsightFetch) {\n    if (!identity.requestId) {\n      return\n    }\n\n    const fetchStartTime = fetch.startTime ?? getCurrentTimestamp()\n    const insight = this.getOrCreateRequest(identity, fetchStartTime)\n    this.updateTiming(insight, fetchStartTime, fetch.durationMs, false)\n    this.recordFetchForInsight(insight, sanitizeFetchInsight(fetch))\n    this.notify(insight)\n  }\n\n  getSnapshot(): RequestInsightsSnapshot {\n    return {\n      requests: this.requestOrder\n        .map((insightKey) => this.requests.get(insightKey))\n        .filter((request): request is RequestInsight => request !== undefined),\n    }\n  }\n\n  subscribe(listener: RequestInsightsListener): () => void {\n    this.listeners.add(listener)\n    return () => {\n      this.listeners.delete(listener)\n    }\n  }\n\n  clear(): void {\n    this.requests.clear()\n    this.requestTimings.clear()\n    this.requestOrder.length = 0\n  }\n\n  private updateTiming(\n    insight: RequestInsight,\n    startTime: number,\n    durationMs: number | undefined,\n    isRequestSpan: boolean\n  ): void {\n    const insightKey = getRequestInsightKey(insight)\n    if (isRequestSpan && durationMs !== undefined) {\n      const requestTiming = { startTime, durationMs }\n      this.requestTimings.set(insightKey, requestTiming)\n      insight.startTime = requestTiming.startTime\n      insight.durationMs = requestTiming.durationMs\n      return\n    }\n\n    const requestTiming = this.requestTimings.get(insightKey)\n    if (requestTiming) {\n      insight.startTime = requestTiming.startTime\n      insight.durationMs = requestTiming.durationMs\n      return\n    }\n\n    const endTime = startTime + (durationMs ?? 0)\n    const requestEndTime = insight.startTime + (insight.durationMs ?? 0)\n    insight.startTime = Math.min(insight.startTime, startTime)\n    insight.durationMs = Math.max(requestEndTime, endTime) - insight.startTime\n  }\n\n  private notify(insight: RequestInsight): void {\n    for (const listener of this.listeners) {\n      listener(insight)\n    }\n  }\n\n  private getOrCreateRequest(\n    identity: RequestInsightIdentity,\n    startTime: number\n  ): RequestInsight {\n    const requestId = identity.requestId!\n    const insightKey = getRequestInsightKey({\n      requestId,\n      kind: identity.kind,\n    })\n    let insight = this.requests.get(insightKey)\n\n    if (!insight) {\n      insight = {\n        requestId,\n        kind: getRequestInsightKind(identity),\n        htmlRequestId: identity.htmlRequestId ?? requestId,\n        route: identity.route,\n        url: sanitizeUrl(identity.url),\n        startTime,\n        status: 'pending',\n        spans: [],\n        fetches: [],\n      }\n      this.requests.set(insightKey, insight)\n      this.requestOrder.push(insightKey)\n      this.trim()\n    }\n\n    insight.htmlRequestId = identity.htmlRequestId ?? insight.htmlRequestId\n    insight.route = insight.route ?? identity.route\n    insight.url = insight.url ?? sanitizeUrl(identity.url)\n    insight.startTime = Math.min(insight.startTime, startTime)\n\n    return insight\n  }\n\n  private recordFetchForInsight(\n    insight: RequestInsight,\n    fetch: RequestInsightFetch\n  ): void {\n    if (\n      insight.fetches.some(\n        (existingFetch) =>\n          existingFetch.url === fetch.url &&\n          (existingFetch.index !== undefined && fetch.index !== undefined\n            ? existingFetch.index === fetch.index\n            : existingFetch.startTime === fetch.startTime)\n      )\n    ) {\n      return\n    }\n\n    insight.fetches.push(sanitizeFetchInsight(fetch))\n  }\n\n  private trim(): void {\n    while (this.requestOrder.length > MAX_REQUEST_INSIGHTS) {\n      const insightKey = this.requestOrder.shift()\n      if (insightKey) {\n        this.requests.delete(insightKey)\n        this.requestTimings.delete(insightKey)\n      }\n    }\n  }\n}\n\nexport function recordRequestInsightSpan(span: SpanStoreRecord): void {\n  if (\n    span.attributes?.['next.span_type'] === CLIENT_COMPONENT_LOADING_SPAN_TYPE\n  ) {\n    return\n  }\n\n  getRequestInsightsStore().recordSpan(span)\n}\n\nexport function recordRequestInsightFetch(\n  identity: RequestInsightIdentity,\n  fetch: RequestInsightFetch\n): void {\n  getRequestInsightsStore().recordFetch(identity, fetch)\n}\n\nexport function getRequestInsightsSnapshot(): RequestInsightsSnapshot {\n  return getRequestInsightsStore().getSnapshot()\n}\n\nexport function subscribeRequestInsights(\n  listener: RequestInsightsListener\n): () => void {\n  return getRequestInsightsStore().subscribe(listener)\n}\n\nexport function clearRequestInsightsForTest(): void {\n  getRequestInsightsStore().clear()\n}\n\nfunction getRequestInsightsStore(): InMemoryRequestInsightsStore {\n  const globalStore = globalThis as typeof globalThis & {\n    [REQUEST_INSIGHTS_STORE_KEY]?: InMemoryRequestInsightsStore\n  }\n\n  return (globalStore[REQUEST_INSIGHTS_STORE_KEY] ??=\n    new InMemoryRequestInsightsStore())\n}\n\nfunction getFetchInsight(span: SpanStoreRecord): RequestInsightFetch | null {\n  const attributes = span.attributes\n\n  if (!attributes || attributes['next.span_type'] !== 'AppRender.fetch') {\n    return null\n  }\n\n  return {\n    url: sanitizeUrl(getStringAttribute(attributes['http.url']) ?? span.url),\n    method: getStringAttribute(attributes['http.method']),\n    statusCode: getNumberAttribute(attributes['http.status_code']),\n    startTime: span.startTime ?? span.timestamp,\n    durationMs: span.durationMs,\n    cacheStatus: getStringAttribute(attributes['next.fetch.cache_status']),\n    cacheReason: getStringAttribute(attributes['next.fetch.cache_reason']),\n    index: getNumberAttribute(attributes['next.fetch.idx']),\n  }\n}\n\nfunction sanitizeFetchInsight(fetch: RequestInsightFetch): RequestInsightFetch {\n  return {\n    ...fetch,\n    url: sanitizeUrl(fetch.url),\n  }\n}\n\nfunction getCurrentTimestamp(): number {\n  return performance.timeOrigin + performance.now()\n}\n\nfunction sanitizeSpanAttributes(\n  attributes: SpanStoreRecord['attributes']\n): SpanStoreRecord['attributes'] {\n  if (!attributes) {\n    return undefined\n  }\n\n  const sanitized: NonNullable<SpanStoreRecord['attributes']> = {}\n  for (const [key, value] of Object.entries(attributes)) {\n    if (!SAFE_SPAN_ATTRIBUTE_KEYS.has(key)) {\n      continue\n    }\n\n    sanitized[key] = key === 'http.url' ? sanitizeUrlAttribute(value) : value\n  }\n\n  return Object.keys(sanitized).length > 0 ? sanitized : undefined\n}\n\nfunction sanitizeSpanEvents(\n  events: SpanStoreRecord['events']\n): SpanStoreRecord['events'] {\n  return events?.map((event) => ({\n    ...event,\n    attributes: sanitizeSpanAttributes(event.attributes),\n  }))\n}\n\nfunction sanitizeSpanLinks(\n  links: SpanStoreRecord['links']\n): SpanStoreRecord['links'] {\n  return links?.map((link) => ({\n    ...link,\n    attributes: sanitizeSpanAttributes(link.attributes),\n  }))\n}\n\nfunction sanitizeUrlAttribute(value: AttributeValue): AttributeValue {\n  return typeof value === 'string' ? (sanitizeUrl(value) ?? '') : value\n}\n\nfunction sanitizeUrl(value: string | undefined): string | undefined {\n  if (!value) {\n    return value\n  }\n\n  const isRelativeUrl = value.startsWith('/')\n\n  try {\n    const url = isRelativeUrl ? new URL(value, 'http://n') : new URL(value)\n\n    url.username = ''\n    url.password = ''\n\n    for (const name of Array.from(url.searchParams.keys())) {\n      if (SENSITIVE_PARAM_NAME_RE.test(name)) {\n        url.searchParams.set(name, REDACTED_VALUE)\n      }\n    }\n\n    return isRelativeUrl ? `${url.pathname}${url.search}${url.hash}` : url.href\n  } catch {\n    return value\n  }\n}\n\nfunction getStringAttribute(value: AttributeValue | undefined) {\n  return typeof value === 'string' ? value : undefined\n}\n\nfunction getNumberAttribute(value: AttributeValue | undefined) {\n  return typeof value === 'number' ? value : undefined\n}\n","import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'\nimport type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'\n\nexport type SpanStoreAttributes = Record<string, AttributeValue>\n\nexport type SpanStoreLink = {\n  traceId: string\n  spanId: string\n  attributes?: SpanStoreAttributes\n}\n\nexport type SpanStoreEvent = {\n  name: string\n  timestamp: number\n  attributes?: SpanStoreAttributes\n}\n\nexport type SpanStoreRecord = {\n  name: string\n  timestamp: number\n  startTime?: number\n  durationMs?: number\n  status?: 'ok' | 'error'\n  traceId?: string\n  spanId?: string\n  parentSpanId?: string\n  requestId?: string\n  requestInsightKind?: RequestInsightKind\n  htmlRequestId?: string\n  route?: string\n  url?: string\n  attributes?: SpanStoreAttributes\n  links?: SpanStoreLink[]\n  events?: SpanStoreEvent[]\n  error?: {\n    type?: string\n    message?: string\n  }\n}\n\ntype SpanRecorderForTest = (span: SpanStoreRecord) => void\n\nlet spanRecorderForTest: SpanRecorderForTest | undefined\n\nexport function recordSpan(record: Omit<SpanStoreRecord, 'timestamp'>): void {\n  if (!isLocalSpanRecordingEnabled()) {\n    return\n  }\n\n  const spanRecord: SpanStoreRecord = {\n    timestamp: getCurrentTimestamp(),\n    ...record,\n  }\n\n  spanRecorderForTest?.(spanRecord)\n\n  if (isRequestInsightsEnabled() && spanRecord.requestId) {\n    const { recordRequestInsightSpan } =\n      require('./request-insights') as typeof import('./request-insights')\n    recordRequestInsightSpan(spanRecord)\n  }\n}\n\nexport function setSpanRecorderForTest(\n  recorder: SpanRecorderForTest | undefined\n): void {\n  spanRecorderForTest = recorder\n}\n\nexport function isLocalSpanRecordingEnabled(): boolean {\n  if (!process.env.__NEXT_DEV_SERVER) {\n    return false\n  }\n\n  return spanRecorderForTest !== undefined || isRequestInsightsEnabled()\n}\n\nexport function isRequestInsightsEnabled(): boolean {\n  if (!process.env.__NEXT_DEV_SERVER) {\n    return false\n  }\n\n  const value = process.env.__NEXT_REQUEST_INSIGHTS\n  return isEnabledEnvValue(value)\n}\n\nfunction isEnabledEnvValue(value: string | undefined): boolean {\n  return value === '1' || value === 'true' || (value as unknown) === true\n}\n\nfunction getCurrentTimestamp(): number {\n  return performance.timeOrigin + performance.now()\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","(()=>{var e={982:e=>{\"use strict\";e.exports=require(\"crypto\")},3:(e,r,t)=>{let l=t(982);let{urlAlphabet:a}=t(885);const n=128;let _,u;let fillPool=e=>{if(!_||_.length<e){_=Buffer.allocUnsafe(e*n);l.randomFillSync(_);u=0}else if(u+e>_.length){l.randomFillSync(_);u=0}u+=e};let random=e=>{fillPool(e-=0);return _.subarray(u-e,u)};let customRandom=(e,r,t)=>{let l=(2<<31-Math.clz32(e.length-1|1))-1;let a=Math.ceil(1.6*l*r/e.length);return()=>{let n=\"\";while(true){let _=t(a);let u=a;while(u--){n+=e[_[u]&l]||\"\";if(n.length===r)return n}}}};let customAlphabet=(e,r)=>customRandom(e,r,random);let nanoid=(e=21)=>{fillPool(e-=0);let r=\"\";for(let t=u-e;t<u;t++){r+=a[_[t]&63]}return r};e.exports={nanoid:nanoid,customAlphabet:customAlphabet,customRandom:customRandom,urlAlphabet:a,random:random}},885:e=>{let r=\"useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict\";e.exports={urlAlphabet:r}}};var r={};function __nccwpck_require__(t){var l=r[t];if(l!==undefined){return l.exports}var a=r[t]={exports:{}};var n=true;try{e[t](a,a.exports,__nccwpck_require__);n=false}finally{if(n)delete r[t]}return a.exports}if(typeof __nccwpck_require__!==\"undefined\")__nccwpck_require__.ab=__dirname+\"/\";var t=__nccwpck_require__(3);module.exports=t})();","// 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};","/**\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 { HTML_LIMITED_BOT_UA_RE_STRING } from '../../shared/lib/router/utils/is-bot'\n\nlet cachedPattern: string | undefined\nlet cachedRegex: RegExp | undefined\n\nexport function shouldServeStreamingMetadata(\n  userAgent: string,\n  htmlLimitedBots: string | undefined\n): boolean {\n  const pattern = htmlLimitedBots || HTML_LIMITED_BOT_UA_RE_STRING\n  if (cachedPattern !== pattern) {\n    cachedPattern = pattern\n    cachedRegex = new RegExp(pattern, 'i')\n  }\n  // Only block metadata for HTML-limited bots\n  if (userAgent && cachedRegex!.test(userAgent)) {\n    return false\n  }\n  return true\n}\n","import * 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  findSourceMapPayload,\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\n//\n// Stored on `globalThis` for the same reason as the code frame renderer below:\n// this module is bundled into several runtimes that each get their own copy,\n// and the copy that installs the implementation is not necessarily the one that\n// symbolicates a frame. The dev validation worker depends on that, because it\n// installs its implementation from the worker bundle while the frames are\n// symbolicated by the app-page bundle's copy.\nconst BUNDLER_FIND_SOURCE_MAP = Symbol.for('next.dev.bundlerFindSourceMap')\ntype GlobalWithBundlerFindSourceMap = typeof globalThis & {\n  [BUNDLER_FIND_SOURCE_MAP]?: FindSourceMapPayload\n}\n\nexport function setBundlerFindSourceMapImplementation(\n  findSourceMapImplementation: FindSourceMapPayload\n): void {\n  ;(globalThis as GlobalWithBundlerFindSourceMap)[BUNDLER_FIND_SOURCE_MAP] =\n    findSourceMapImplementation\n}\n\nfunction bundlerFindSourceMapPayload(\n  sourceURL: string\n): ModernSourceMapPayload | undefined {\n  return (globalThis as GlobalWithBundlerFindSourceMap)[\n    BUNDLER_FIND_SOURCE_MAP\n  ]?.(sourceURL)\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\n// The code-frame renderer is stored on `globalThis` rather than in a module\n// variable because this module is bundled into several runtimes (the dev\n// server, the app-page runtime bundle, and the dev worker bundles) that each\n// get their own copy. `Error.prepareStackTrace` is a single process-global, so\n// whichever copy patched it last is the one that renders errors, which may not\n// be the copy `setCodeFrameRenderer` was called on. Sharing the renderer\n// through a `globalThis` symbol lets any copy install it and any copy read it.\nconst CODE_FRAME_RENDERER = Symbol.for('next.dev.codeFrameRenderer')\ntype GlobalWithCodeFrameRenderer = typeof globalThis & {\n  [CODE_FRAME_RENDERER]?: CodeFrameRenderer\n}\n\nexport function setCodeFrameRenderer(renderer: CodeFrameRenderer): void {\n  ;(globalThis as GlobalWithCodeFrameRenderer)[CODE_FRAME_RENDERER] = renderer\n}\n\nfunction getOriginalCodeFrame(\n  frame: IgnorableStackFrame,\n  source: string | null,\n  colors: boolean = process.stdout.isTTY\n): string | null {\n  const codeFrameRenderer = (globalThis as GlobalWithCodeFrameRenderer)[\n    CODE_FRAME_RENDERER\n  ]\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\n// Constructing a consumer indexes the whole payload — expensive for large\n// chunk maps and previously paid per frame — so consumers are shared across\n// all frames and errors whose lookups returned the same payload. The inner\n// key is the URL the consumer resolves relative `sources` against.\nconst sourceMapConsumers = new WeakMap<\n  ModernSourceMapPayload,\n  Map<string, SyncSourceMapConsumer>\n>()\n\nfunction getOrCreateSourceMapConsumer(\n  payload: ModernSourceMapPayload,\n  sourceMapURL: string\n): SyncSourceMapConsumer {\n  let consumersByURL = sourceMapConsumers.get(payload)\n  let consumer = consumersByURL?.get(sourceMapURL)\n  if (consumer === undefined) {\n    consumer = new SyncSourceMapConsumer(\n      payload,\n      // @ts-expect-error: our typings don't include this parameter but it is here.\n      sourceMapURL\n    )\n    if (consumersByURL === undefined) {\n      consumersByURL = new Map()\n      // Throws for payloads that aren't objects; those are invalid source\n      // maps anyway, and the caller reports them.\n      sourceMapConsumers.set(payload, consumersByURL)\n    }\n    consumersByURL.set(sourceMapURL, consumer)\n  }\n  return consumer\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    // Fake frame scripts (`about://React/Server/file:///path/to/chunk.js?42`)\n    // have their positions padded to match the underlying chunk, so they\n    // resolve via the chunk's source map.\n    let sourceURL = devirtualizeReactServerURL(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(sourceURL)) {\n      sourceURL = url.pathToFileURL(sourceURL).toString()\n    }\n    let maybeSourceMapPayload: ModernSourceMapPayload | undefined\n    try {\n      maybeSourceMapPayload = findSourceMapPayload(sourceURL)\n\n      if (\n        maybeSourceMapPayload === undefined &&\n        sourceURL.startsWith('file://')\n      ) {\n        // Devirtualizing React's fake frame URL decodes the path, while Node.js\n        // keys its source map cache by the `pathToFileURL` encoding of the same\n        // path, so a path containing characters that encoding escapes (such as\n        // the brackets in Turbopack's `[root-of-the-server]` chunks) misses\n        // above. Node.js also accepts the plain path, which is unambiguous for\n        // both interpretations, so retry with that before giving up.\n        //\n        // TODO(veil): Making React's fake frame URLs reversible, as proposed in\n        // https://github.com/react/react/pull/37105, would let the first lookup\n        // succeed on its own and retire this retry.\n        maybeSourceMapPayload = findSourceMapPayload(\n          url.fileURLToPath(sourceURL)\n        )\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 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. `sourceURL` is already devirtualized so that relative `sources`\n      // resolve against the real chunk URL, not React's virtual one.\n      const sourceMapURL = sourceURL + '.map'\n      sourceMapConsumer = getOrCreateSourceMapConsumer(\n        sourceMapPayload,\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","import { InvariantError } from '../../shared/lib/invariant-error'\nimport { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'\n\nexport enum RenderStage {\n  Before = 1,\n  //\n  ShellStatic = 11,\n  Static = 13,\n  //\n  ShellRuntime = 21,\n  Runtime = 23,\n  //\n  Dynamic = 30,\n  //\n  Abandoned = 40,\n}\n\nexport type AdvanceableRenderStage = Exclude<\n  RenderStage,\n  RenderStage.Before | RenderStage.Abandoned\n>\n\nexport const RENDER_STAGE_ADVANCE_ORDER: AdvanceableRenderStage[] = [\n  RenderStage.ShellStatic,\n  RenderStage.Static,\n  //\n  RenderStage.ShellRuntime,\n  RenderStage.Runtime,\n  //\n  RenderStage.Dynamic,\n]\n\nexport function getNextStage(\n  stage: Exclude<AdvanceableRenderStage, RenderStage.Dynamic>\n) {\n  return RENDER_STAGE_ADVANCE_ORDER[\n    RENDER_STAGE_ADVANCE_ORDER.indexOf(stage) + 1\n  ]\n}\n\nexport function isAdvanceableRenderStage(\n  stage: RenderStage\n): stage is AdvanceableRenderStage {\n  return RenderStage.Before < stage && stage <= RenderStage.Dynamic\n}\n\nexport enum SyncIOMode {\n  /** Sync IO does not error in any stage. */\n  Untracked = 1,\n  /** Before `partialPrefetching`: Sync IO errors in static stages, and is allowed otherwise. */\n  AllowedInRuntimeOrDynamic = 2,\n  /** After `partialPrefetching`: Sync IO errors in all stages other than dynamic. */\n  AllowedInDynamic = 3,\n}\n\nexport class StagedRenderingController {\n  private abortSignal: AbortSignal | null\n  private abandonController: AbortController | null\n  private syncIOMode: SyncIOMode\n  public readonly finalStage: AdvanceableRenderStage | null\n\n  currentStage: RenderStage = RenderStage.Before\n\n  syncInterruptReason: Error | null = null\n\n  triggers: Record<AdvanceableRenderStage, StageTrigger> = {\n    [RenderStage.ShellStatic]: createStageTrigger(),\n    [RenderStage.Static]: createStageTrigger(),\n    //\n    [RenderStage.ShellRuntime]: createStageTrigger(),\n    [RenderStage.Runtime]: createStageTrigger(),\n    //\n    [RenderStage.Dynamic]: createStageTrigger(),\n  }\n\n  constructor({\n    abortSignal,\n    abandonController,\n    syncIO,\n    finalStage,\n  }: {\n    abortSignal: AbortSignal | null\n    abandonController: AbortController | null\n    syncIO: SyncIOMode\n    finalStage: AdvanceableRenderStage | null\n  }) {\n    this.abortSignal = abortSignal\n    this.abandonController = abandonController\n    this.syncIOMode = syncIO\n    this.finalStage = finalStage\n\n    if (abortSignal) {\n      abortSignal.addEventListener(\n        'abort',\n        () => {\n          // Reject all stage promises that haven't already been resolved.\n          // `cancelStageTrigger` is a noop if the trigger already resolved.\n          const { reason } = abortSignal\n          for (const trigger of Object.values(this.triggers)) {\n            cancelStageTrigger(trigger, reason)\n          }\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    addSyncTriggerListener(this.triggers[stage], callback)\n  }\n\n  shouldTrackSyncInterrupt(): boolean {\n    if (this.syncIOMode === SyncIOMode.Untracked) {\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.ShellStatic:\n      case RenderStage.Static:\n        return true\n      case RenderStage.ShellRuntime:\n      case RenderStage.Runtime: {\n        switch (this.syncIOMode) {\n          case SyncIOMode.AllowedInRuntimeOrDynamic: {\n            // Before `partialPrefetching`: Sync IO only errors in static stages.\n            return false\n          }\n          case SyncIOMode.AllowedInDynamic: {\n            return true\n          }\n        }\n        // NOT a fallthrough, but eslint doesn't understand that\n      }\n      case RenderStage.Dynamic:\n      case RenderStage.Abandoned:\n        return false\n      default:\n        this.currentStage satisfies never\n        return false\n    }\n  }\n\n  /** Note: only call this if `shouldTrackSyncInterrupt()` returned true */\n  syncInterruptCurrentStageWithReason(reason: Error) {\n    const { currentStage } = this\n    if (\n      currentStage === RenderStage.Before ||\n      currentStage === RenderStage.Dynamic ||\n      currentStage === RenderStage.Abandoned\n    ) {\n      // Not interruptible. Defensive noop.\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    this.syncInterruptReason = reason\n    this.advanceStage(RenderStage.Dynamic)\n  }\n\n  getSyncInterruptReason() {\n    return this.syncInterruptReason\n  }\n\n  getStageEndTime(stage: Exclude<AdvanceableRenderStage, RenderStage.Dynamic>) {\n    return this.triggers[getNextStage(stage)].triggeredAt ?? Infinity\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\n    const { currentStage } = this\n\n    if (currentStage === RenderStage.Before) {\n      throw new InvariantError(\n        \"A render that hasn't started yet cannot be abandoned\"\n      )\n    }\n    if (\n      currentStage === RenderStage.Dynamic ||\n      currentStage === RenderStage.Abandoned\n    ) {\n      // We shouldn't ever trigger an abandon in these. Defensive noop.\n      return\n    }\n\n    // Resolve all stages after the current one, up to runtime (excluding dynamic)\n    const nextStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(currentStage) + 1\n    const dynamicStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(\n      RenderStage.Dynamic\n    )\n    for (let i = nextStageIx; i < dynamicStageIx; i++) {\n      this.resolveStage(RENDER_STAGE_ADVANCE_ORDER[i])\n    }\n\n    this.currentStage = RenderStage.Abandoned\n  }\n\n  advanceStage(targetStage: AdvanceableRenderStage) {\n    if (this.finalStage !== null && targetStage > this.finalStage) {\n      throw new InvariantError(\n        `Attempted to advance to stage ${RenderStage[targetStage]} but the render is limited to ${RenderStage[this.finalStage]}`\n      )\n    }\n    const { currentStage } = this\n\n    if (\n      currentStage === RenderStage.Dynamic ||\n      currentStage === RenderStage.Abandoned\n    ) {\n      // Terminal stages, nowhere left to advance.\n      return\n    }\n\n    // If we're already at the target stage or beyond, do nothing.\n    if (targetStage <= currentStage) {\n      return\n    }\n\n    this.currentStage = targetStage\n\n    // Resolve all stages between the current stage and the target.\n    const nextStageIx =\n      currentStage === RenderStage.Before\n        ? 0\n        : RENDER_STAGE_ADVANCE_ORDER.indexOf(currentStage) + 1\n    const targetStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(targetStage)\n    for (let i = nextStageIx; i <= targetStageIx; i++) {\n      this.resolveStage(RENDER_STAGE_ADVANCE_ORDER[i])\n    }\n  }\n\n  private resolveStage(stage: AdvanceableRenderStage) {\n    fireStageTrigger(this.triggers[stage])\n  }\n\n  private getStagePromise(stage: AdvanceableRenderStage): Promise<void> {\n    return this.triggers[stage].promise\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  ): Promise<T> {\n    const stagePromise = this.getStagePromise(stage)\n\n    const promise =\n      process.env.NODE_ENV === 'development'\n        ? makeDevtoolsIOPromiseFromIOTrigger(\n            stagePromise,\n            displayName,\n            resolvedValue\n          )\n        : stagePromise.then(() => resolvedValue)\n\n    // Analogously to `makeDynamicHangingPromise`, 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\ntype StageTrigger = {\n  state: 'pending' | 'triggered' | 'cancelled'\n  triggeredAt: number | null\n  promise: Promise<void>\n  _listeners: Array<() => void>\n  _resolvePromise: () => void\n  _rejectPromise: (reason: unknown) => void\n}\n\nfunction addSyncTriggerListener(trigger: StageTrigger, listener: () => void) {\n  if (trigger.state === 'pending') {\n    trigger._listeners.push(listener)\n  } else {\n    listener()\n  }\n}\n\nfunction createStageTrigger(): StageTrigger {\n  const { promise, resolve, reject } = createPromiseWithResolvers<void>()\n  return {\n    state: 'pending',\n    triggeredAt: null,\n    promise,\n    _listeners: [],\n    _resolvePromise: resolve,\n    _rejectPromise: reject,\n  }\n}\n\nfunction fireStageTrigger(trigger: StageTrigger) {\n  if (trigger.state !== 'pending') {\n    return\n  }\n  trigger.state = 'triggered'\n  trigger.triggeredAt = performance.now() + performance.timeOrigin\n  try {\n    const { _listeners: listeners } = trigger\n    for (let i = 0; i < listeners.length; i++) {\n      listeners[i]()\n    }\n    listeners.length = 0\n  } finally {\n    trigger._resolvePromise()\n  }\n}\n\nfunction cancelStageTrigger(trigger: StageTrigger, reason: unknown) {\n  if (trigger.state !== 'pending') {\n    return\n  }\n  trigger.state = 'cancelled'\n  // we didn't trigger, so don't save `triggeredAt`.\n\n  // We're not gonna fire the listeners, we may as well free them.\n  trigger._listeners.length = 0\n\n  // Suppress unhandled rejection warnings for promises that no one is awaiting.\n  trigger.promise.catch(ignoreReject)\n  trigger._rejectPromise(reason)\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  waitShellReady = 'AppRender.waitShellReady',\n  renderToNodeFizzStream = 'AppRender.renderToNodeFizzStream',\n  instantInsights = 'AppRender.instantInsights',\n  instantInsightsPrepareValidation = 'AppRender.instantInsights.prepareValidation',\n  instantInsightsRunValidation = 'AppRender.instantInsights.runValidation',\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:\n    | ((value: T, key: string) => number)\n    | undefined\n  private readonly onEvict: ((key: string, value: T) => void) | undefined\n\n  constructor(\n    maxSize: number,\n    calculateSize?: (value: T, key: string) => 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, key) ?? 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\n// `SourceMap#payload` deep-clones the payload on every access — expensive\n// for large chunk maps — so the clone is shared per `SourceMap` instance,\n// which Node.js memoizes per script.\nconst sourceMapPayloads = new WeakMap<SourceMap, ModernSourceMapPayload>()\n\n/**\n * Like `module.findSourceMap`, but returns the source map's payload without\n * cloning it on every call. Callers must not mutate the returned payload.\n * Throws like `module.findSourceMap` does on invalid source maps.\n */\nexport function findSourceMapPayload(\n  sourceURL: string\n): ModernSourceMapPayload | undefined {\n  const sourceMap = findSourceMap(sourceURL)\n  if (sourceMap === undefined) {\n    return undefined\n  }\n  let payload = sourceMapPayloads.get(sourceMap)\n  if (payload === undefined) {\n    payload = sourceMap.payload as ModernSourceMapPayload\n    sourceMapPayloads.set(sourceMap, payload)\n  }\n  return payload\n}\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 payload = findSourceMapPayload(sourceURL)\n    if (payload === undefined) {\n      // No source map associated.\n      return true\n    }\n    const sourceMapPayload = findApplicableSourceMapPayload(\n      line1 - 1,\n      column1 - 1,\n      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\n// `scriptNameOrSourceURL` is what React forwards from the stack frame: the\n// script's `getScriptNameOrSourceURL()`, which for the server chunks we can\n// map is an absolute filesystem path, not a URL. The returned value is the\n// source map's URL (`file:` or `data:`).\ntype FindSourceMapURL = (scriptNameOrSourceURL: string) => string | null\n// Find the URL of a source map using the bundler's API.\n// Shared via `globalThis` because this module is compiled both into the server\n// runtime bundles (which call `findSourceMapURLDEV`) and into `next/dist/server`\n// (where the dev server registers the implementation), and each copy has its own\n// module state.\nconst bundlerFindSourceMapURLSymbol = Symbol.for(\n  'next.server.bundlerFindSourceMapURL'\n)\n\nexport function setBundlerFindSourceMapURLImplementation(\n  findSourceMapURLImplementation: FindSourceMapURL\n): void {\n  ;(globalThis as any)[bundlerFindSourceMapURLSymbol] =\n    findSourceMapURLImplementation\n}\n\nfunction bundlerFindSourceMapURL(scriptNameOrSourceURL: string): string | null {\n  const implementation: FindSourceMapURL | undefined = (globalThis as any)[\n    bundlerFindSourceMapURLSymbol\n  ]\n  return implementation === undefined\n    ? null\n    : implementation(scriptNameOrSourceURL)\n}\n\nconst invalidSourceMap = Symbol('invalid-source-map')\nconst sourceMapURLs = new LRUCache<string | typeof invalidSourceMap>(\n  512 * 1024 * 1024,\n  (url, sourceURL) =>\n    sourceURL.length +\n    (url === invalidSourceMap\n      ? // Guestimate a small source map so invalid entries don't fill the cache.\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  try {\n    const bundlerSourceMapURL = bundlerFindSourceMapURL(scriptNameOrSourceURL)\n    if (bundlerSourceMapURL !== null) {\n      return bundlerSourceMapURL\n    }\n  } catch (cause) {\n    console.error(\n      `${scriptNameOrSourceURL}: Failed to find the source map URL. Cause: ${cause}`\n    )\n  }\n\n  // No bundler implementation (e.g. Webpack): inline the source map Node.js\n  // knows as a `data:` URL.\n  let sourceMapURL = sourceMapURLs.get(scriptNameOrSourceURL)\n  if (sourceMapURL === undefined) {\n    let sourceMapPayload: ModernSourceMapPayload | undefined\n    try {\n      sourceMapPayload = findSourceMapPayload(scriptNameOrSourceURL)\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  PrerenderStoreModernServer,\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  getStagedRenderingController,\n  throwForMissingRequestStore,\n  workUnitAsyncStorage,\n} from './work-unit-async-storage.external'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport {\n  ClientHookDynamicError,\n  isClientHookDynamicError,\n  makeClientHookHangingPromise,\n  trackRuntimeDataAccessed,\n} 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 {\n  createRuntimeBodyError,\n  createDynamicBodyError,\n  createRuntimeBodyErrorInNavigation,\n  createDynamicBodyErrorInNavigation,\n  createDynamicOrRuntimeBodyError,\n  createRuntimeMetadataError,\n  createDynamicMetadataError,\n  createRuntimeViewportError,\n  createDynamicViewportError,\n  createDynamicOrRuntimeViewportError,\n  createDynamicOrRuntimeMetadataError,\n  logBuildDebugHint,\n  createLinkBodyErrorInNavigation,\n  createLinkMetadataError,\n  createLinkViewportError,\n} from './blocking-route-messages'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n  INSTANT_VALIDATION_BOUNDARY_NAME,\n  INSTANT_SLOT_MARKER_PREFIX,\n  INSTANT_SLOT_MARKER_SUFFIX,\n} from './instant-validation/boundary-constants'\nimport {\n  type ValidationBoundaryTracking,\n  allRequiredBoundariesRendered,\n} from './instant-validation/boundary-tracking'\nimport type { InstantValidationSampleTracking } from './instant-validation/instant-samples'\nimport { createUnrenderedSegmentError } from '../../shared/lib/instant-messages'\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  syncDynamicErrorWithStackPostMicrotask: boolean\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    syncDynamicErrorWithStackPostMicrotask: false,\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\nfunction getPendingClientSyncDynamicError(\n  clientDynamic: DynamicTrackingState\n): null | Error {\n  return clientDynamic.syncDynamicErrorWithStackPostMicrotask\n    ? null\n    : clientDynamic.syncDynamicErrorWithStack\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\n  if (dynamicTracking && dynamicTracking.syncDynamicErrorWithStack === null) {\n    dynamicTracking.syncDynamicErrorWithStack = errorWithStack\n    // React completes the task that is currently rendering before scheduled\n    // abort cleanup. Client tracking can attribute the sync IO only during\n    // that current task; server tracking keeps the error regardless.\n    queueMicrotask(() => {\n      dynamicTracking.syncDynamicErrorWithStackPostMicrotask = true\n    })\n  }\n\n  abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore)\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  // The synchronously accessed request data would have been available during\n  // a runtime prerender, which would have rendered past this point instead of\n  // aborting — so a runtime prefetch would produce more content than this\n  // render. Record that, same as when request data access creates a hanging\n  // promise (see makeRuntimeHangingPromise). Unlike\n  // `abortOnSynchronousPlatformIOAccess`, which aborts a runtime prerender\n  // all the same and therefore must not record anything.\n  trackRuntimeDataAccessed(prerenderStore)\n\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    // Preserve the exact server-side dynamic access for final validation after\n    // interrupting this render.\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: PrerenderStoreModernServer\n): AbortSignal\nexport function createHangingInputAbortSignal(\n  workUnitStore: WorkUnitStore\n): AbortSignal | undefined\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 final stage.\n        // if an input didn't resolve at that point, then we can assume it never will.\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\n        const stagedRendering = getStagedRenderingController(workUnitStore)\n        if (stagedRendering && stagedRendering.finalStage !== null) {\n          stagedRendering\n            .waitForStage(stagedRendering.finalStage)\n            .then(() => scheduleOnNextTick(() => controller.abort()), noop)\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\nfunction noop() {}\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        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            makeClientHookHangingPromise(\n              workUnitStore.renderSignal,\n              new ClientHookDynamicError(workStore.route, expression)\n            )\n          )\n        }\n        break\n      }\n      case 'prerender':\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 '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        makeClientHookHangingPromise(\n          workUnitStore.renderSignal,\n          new ClientHookDynamicError(workStore.route, 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)\nconst slotMarkerRegex = new RegExp(\n  `\\\\n\\\\s+at ${INSTANT_SLOT_MARKER_PREFIX}(\\\\d+)${INSTANT_SLOT_MARKER_SUFFIX}[\\\\n\\\\s]`\n)\n\n/** Look up the config factory for the slot this error belongs to.\n * Checks the component stack for a slot marker (__next_instant_slot_N__)\n * and returns the config at that index. Falls back to index 0 (root\n * config) when no slot marker is found or the slot has no config. */\nfunction resolveInstantStack(\n  componentStack: string,\n  dynamicValidation: InstantValidationState\n): (() => Error) | null {\n  const { slotStacks } = dynamicValidation\n  if (slotStacks.length > 1) {\n    const match = slotMarkerRegex.exec(componentStack)\n    if (match) {\n      // Slot markers are 0-indexed in the component name but\n      // slotStacks is 1-indexed (index 0 is the root config).\n      const slotIndex = parseInt(match[1], 10) + 1\n      const slotStack = slotStacks[slotIndex]\n      if (slotStack != null) {\n        return slotStack\n      }\n    }\n  }\n  // Fall back to root config (index 0)\n  return slotStacks[0] ?? null\n}\n\n/**\n * Inspects the component stack of an outlet boundary to discover whether the\n * user placed a Suspense boundary above the document body, and records the\n * opt-in on `dynamicValidation.hasSuspenseAboveBody` if so.\n *\n * The outlet itself isn't a meaningful source of dynamic — it only resolves\n * when metadata/viewport are dynamic, which we track via their own boundaries.\n * However, the outlet renders alongside the page content, so its stack passes\n * through the user's layout chain (typically reaching into `<body>` via the\n * root layout). That makes the outlet stack our best opportunity to spot a\n * Suspense boundary above the body, even when no real body content is dynamic.\n * Without this, a route whose only dynamic source is `generateViewport()` would\n * miss the Suspense-above-body opt-in, because the viewport's stack lives in\n * the head and never sees the user's root layout.\n *\n * We deliberately only set `hasSuspenseAboveBody`, not `hasAllowedDynamic`. The\n * latter tracks whether the body has dynamic content that's been wrapped in\n * Suspense (i.e., the page is partially dynamic). The outlet rendering tells us\n * about the structural opt-in for an empty shell, not about the body being\n * partially dynamic. The distinction matters because dynamic metadata is only\n * acceptable when the page is partially dynamic (via real body holes), and we\n * don't want this outlet-based detection to mask that case.\n */\nfunction trackOutletSuspenseAboveBody(\n  componentStack: string,\n  dynamicValidation: DynamicValidationState\n): void {\n  if (\n    hasSuspenseBeforeRootLayoutWithoutBodyOrImplicitBodyRegex.test(\n      componentStack\n    )\n  ) {\n    dynamicValidation.hasSuspenseAboveBody = true\n  }\n}\n\nexport function trackAllowedDynamicAccess(\n  dynamicReason: unknown,\n  workStore: WorkStore,\n  componentStack: string,\n  dynamicValidation: DynamicValidationState,\n  clientDynamic: DynamicTrackingState\n) {\n  const syncDynamicError = getPendingClientSyncDynamicError(clientDynamic)\n\n  if (hasOutletRegex.test(componentStack)) {\n    trackOutletSuspenseAboveBody(componentStack, dynamicValidation)\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 (syncDynamicError) {\n    dynamicValidation.dynamicErrors.push(syncDynamicError)\n    return\n  }\n\n  if (isClientHookDynamicError(dynamicReason)) {\n    dynamicValidation.dynamicErrors.push(\n      addErrorContext(dynamicReason, componentStack, null)\n    )\n    return\n  }\n\n  const error = addErrorContext(\n    createDynamicOrRuntimeBodyError(workStore.route),\n    componentStack,\n    null\n  )\n  dynamicValidation.dynamicErrors.push(error)\n  return\n}\n\nexport enum DynamicHoleKind {\n  /** We know that this hole is caused by link data. */\n  Link = 1,\n  /** We know that this hole is caused by runtime data. */\n  Runtime = 2,\n  /** We know that this hole is caused by dynamic data. */\n  Dynamic = 3,\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  /** Per-slot config factories. Index 0 is the root config (fallback).\n   * Indices 1+ correspond to slot marker components in the tree. */\n  slotStacks: Array<(() => Error) | null>\n}\n\nexport function createInstantValidationState(\n  slotStacks: Array<(() => 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    slotStacks,\n  }\n}\n\nexport function trackDynamicHoleInNavigation(\n  dynamicReason: unknown,\n  workStore: WorkStore,\n  componentStack: string,\n  dynamicValidation: InstantValidationState,\n  clientDynamic: DynamicTrackingState,\n  kind: DynamicHoleKind,\n  boundaryState: ValidationBoundaryTracking\n) {\n  const syncDynamicError = getPendingClientSyncDynamicError(clientDynamic)\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  // Resolve the config stack for this specific error. If the error\n  // is inside a slot marker, use that slot's config. Otherwise fall\n  // back to the default.\n  const effectiveCreateInstantStack = resolveInstantStack(\n    componentStack,\n    dynamicValidation\n  )\n\n  if (hasMetadataRegex.test(componentStack)) {\n    const error = addErrorContext(\n      kind === DynamicHoleKind.Link\n        ? createLinkMetadataError(workStore.route)\n        : kind === DynamicHoleKind.Runtime\n          ? createRuntimeMetadataError(workStore.route)\n          : createDynamicMetadataError(workStore.route),\n      componentStack,\n      effectiveCreateInstantStack\n    )\n    dynamicValidation.dynamicMetadata = error\n    return\n  }\n  if (hasViewportRegex.test(componentStack)) {\n    const error = addErrorContext(\n      kind === DynamicHoleKind.Link\n        ? createLinkViewportError(workStore.route)\n        : kind === DynamicHoleKind.Runtime\n          ? createRuntimeViewportError(workStore.route)\n          : createDynamicViewportError(workStore.route),\n      componentStack,\n      effectiveCreateInstantStack\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 (allRequiredBoundariesRendered(boundaryState)) {\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 \\`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        effectiveCreateInstantStack\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 (syncDynamicError) {\n    if (\n      effectiveCreateInstantStack !== null &&\n      syncDynamicError.cause === undefined\n    ) {\n      syncDynamicError.cause = effectiveCreateInstantStack()\n    }\n    dynamicValidation.dynamicErrors.push(syncDynamicError)\n    return\n  }\n\n  if (isClientHookDynamicError(dynamicReason)) {\n    dynamicValidation.dynamicErrors.push(\n      addErrorContext(\n        dynamicReason,\n        componentStack,\n        effectiveCreateInstantStack\n      )\n    )\n    return\n  }\n\n  const error = addErrorContext(\n    kind === DynamicHoleKind.Link\n      ? createLinkBodyErrorInNavigation(workStore.route)\n      : kind === DynamicHoleKind.Runtime\n        ? createRuntimeBodyErrorInNavigation(workStore.route)\n        : createDynamicBodyErrorInNavigation(workStore.route),\n    componentStack,\n    effectiveCreateInstantStack\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 \\`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  dynamicReason: unknown,\n  workStore: WorkStore,\n  componentStack: string,\n  dynamicValidation: DynamicValidationState,\n  clientDynamic: DynamicTrackingState\n) {\n  const syncDynamicError = getPendingClientSyncDynamicError(clientDynamic)\n\n  if (hasOutletRegex.test(componentStack)) {\n    trackOutletSuspenseAboveBody(componentStack, dynamicValidation)\n    return\n  } else if (hasMetadataRegex.test(componentStack)) {\n    const error = addErrorContext(\n      createDynamicMetadataError(workStore.route),\n      componentStack,\n      null\n    )\n    dynamicValidation.dynamicMetadata = error\n    return\n  } else if (hasViewportRegex.test(componentStack)) {\n    const error = addErrorContext(\n      createDynamicViewportError(workStore.route),\n      componentStack,\n      null\n    )\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 (syncDynamicError) {\n    dynamicValidation.dynamicErrors.push(syncDynamicError)\n    return\n  }\n\n  if (isClientHookDynamicError(dynamicReason)) {\n    dynamicValidation.dynamicErrors.push(\n      addErrorContext(dynamicReason, componentStack, null)\n    )\n    return\n  }\n\n  const error = addErrorContext(\n    createDynamicBodyError(workStore.route),\n    componentStack,\n    null\n  )\n  dynamicValidation.dynamicErrors.push(error)\n  return\n}\n\nexport function trackDynamicHoleInStaticShell(\n  dynamicReason: unknown,\n  workStore: WorkStore,\n  componentStack: string,\n  dynamicValidation: DynamicValidationState,\n  clientDynamic: DynamicTrackingState\n) {\n  const syncDynamicError = getPendingClientSyncDynamicError(clientDynamic)\n\n  if (hasOutletRegex.test(componentStack)) {\n    trackOutletSuspenseAboveBody(componentStack, dynamicValidation)\n    return\n  } else if (hasMetadataRegex.test(componentStack)) {\n    const error = addErrorContext(\n      createRuntimeMetadataError(workStore.route),\n      componentStack,\n      null\n    )\n    dynamicValidation.dynamicMetadata = error\n    return\n  } else if (hasViewportRegex.test(componentStack)) {\n    const error = addErrorContext(\n      createRuntimeViewportError(workStore.route),\n      componentStack,\n      null\n    )\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 (syncDynamicError) {\n    dynamicValidation.dynamicErrors.push(syncDynamicError)\n    return\n  }\n\n  if (isClientHookDynamicError(dynamicReason)) {\n    dynamicValidation.dynamicErrors.push(\n      addErrorContext(dynamicReason, componentStack, null)\n    )\n    return\n  }\n\n  const error = addErrorContext(\n    createRuntimeBodyError(workStore.route),\n    componentStack,\n    null\n  )\n  dynamicValidation.dynamicErrors.push(error)\n  return\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  logBuildDebugHint(workStore.route)\n}\n\nexport function throwIfSyncIOUsed(\n  workStore: WorkStore,\n  serverDynamic: DynamicTrackingState\n) {\n  if (serverDynamic.syncDynamicErrorWithStack) {\n    logDisallowedDynamicError(\n      workStore,\n      serverDynamic.syncDynamicErrorWithStack\n    )\n    throw new StaticGenBailoutError()\n  }\n}\n\nexport function throwIfDisallowedDynamic(\n  workStore: WorkStore,\n  prelude: PreludeState,\n  dynamicValidation: DynamicValidationState,\n  serverDynamic: DynamicTrackingState,\n  allowEmptyStaticShell: boolean\n): void {\n  throwIfSyncIOUsed(workStore, serverDynamic)\n\n  // The dynamic metadata error is a mistake-detection signal. It fires when the\n  // rest of the shell is otherwise fully static apart from metadata, suggesting\n  // the dynamic data access in `generateMetadata` was probably unintentional.\n  // That condition is independent of whether the user or build phase accepted\n  // an empty shell, so we surface it before any opt-in bypass.\n  if (\n    prelude === PreludeState.Full &&\n    dynamicValidation.hasAllowedDynamic === false &&\n    dynamicValidation.hasDynamicMetadata\n  ) {\n    console.error(createDynamicOrRuntimeMetadataError(workStore.route).message)\n    throw new StaticGenBailoutError()\n  }\n\n  // Either flag expresses \"this shell is allowed to be empty/blocking\":\n  //   - `allowEmptyStaticShell` covers `instant = false` (user opt-in)\n  //     and the build-phase fallback-shell case.\n  //   - `hasSuspenseAboveBody` is the structural opt-in inside the user's root\n  //     layout.\n  // Treat them as synonyms for the purpose of bypassing shell-failure errors.\n  if (allowEmptyStaticShell || dynamicValidation.hasSuspenseAboveBody) {\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      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        createDynamicOrRuntimeViewportError(workStore.route).message\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  }\n}\n\nexport function getStaticShellDisallowedDynamicReasons(\n  workStore: WorkStore,\n  prelude: PreludeState,\n  dynamicValidation: DynamicValidationState,\n  allowEmptyStaticShell: boolean\n): Array<Error> {\n  // The dynamic metadata error is a mistake-detection signal. It fires when the\n  // rest of the shell is otherwise fully static apart from metadata, suggesting\n  // the dynamic data access in `generateMetadata` was probably unintentional.\n  // That condition is independent of whether the user or build phase accepted\n  // an empty shell, so we surface it before any opt-in bypass.\n  if (\n    prelude === PreludeState.Full &&\n    dynamicValidation.hasAllowedDynamic === false &&\n    dynamicValidation.dynamicErrors.length === 0 &&\n    dynamicValidation.dynamicMetadata\n  ) {\n    return [dynamicValidation.dynamicMetadata]\n  }\n\n  // Either flag expresses \"this shell is allowed to be empty/blocking\":\n  //   - `allowEmptyStaticShell` covers `instant = false` (user opt-in)\n  //     and the build-phase fallback-shell case.\n  //   - `hasSuspenseAboveBody` is the structural opt-in inside the user's root\n  //     layout.\n  // Treat them as synonyms for the purpose of bypassing shell-failure errors.\n  if (allowEmptyStaticShell || dynamicValidation.hasSuspenseAboveBody) {\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  }\n  // We had a non-empty prelude and there are no dynamic holes\n  return []\n}\n\n/**\n * `errors` are validation failures that should be surfaced immediately.\n * `deferredFallback` carries a missing-boundary explanation that the caller\n * should hold back until *every* validation depth has been tried — a missing\n * boundary often just means a parent layout intentionally omitted a slot, and\n * a different depth's validation may surface a more meaningful error.\n */\nexport type NavigationValidationResult =\n  // instances that block instant navigation\n  | Array<Error>\n  // validation was blocked with zero or more reasons\n  | Error\n  | AggregateError\n\nexport function getNavigationDisallowedDynamicReasons(\n  workStore: WorkStore,\n  prelude: PreludeState,\n  dynamicValidation: InstantValidationState,\n  validationSampleTracking: InstantValidationSampleTracking | null,\n  boundaryState: ValidationBoundaryTracking,\n  devRenderDidError: boolean\n): NavigationValidationResult {\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    if (process.env.__NEXT_DEV_SERVER && devRenderDidError) {\n      // The dev render already surfaced server errors to the user.\n      // The same errors likely caused validation to be inconclusive,\n      // so reporting them again as validation failures would be noisy.\n      return []\n    }\n    return validationPreventingErrors\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 (\n      prelude === PreludeState.Empty &&\n      !dynamicValidation.hasAllowedClientDynamicAboveBoundary &&\n      allRequiredBoundariesRendered(boundaryState)\n    ) {\n      // If we ever get this far then we messed up the tracking of invalid\n      // dynamic. (When boundaries are missing the deferred fallback below\n      // will surface a more useful error.)\n      return new InvariantError(\n        `Route \"${workStore.route}\" failed to render during instant validation and Next.js was unable to determine a reason.`\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\n  // Missing boundaries on their own aren't a strong signal — a parent\n  // layout may legitimately omit a slot. Defer this so the caller can\n  // try shallower validation depths first; if every depth comes up\n  // empty we still want to surface this so the user is made aware that\n  // validation didn't complete. When we add a markers API, the\n  // marker-based variant of this check can become strict again.\n  if (!allRequiredBoundariesRendered(boundaryState)) {\n    const { thrownErrorsOutsideBoundary } = dynamicValidation\n    const rootInstantStack = dynamicValidation.slotStacks[0]\n    if (thrownErrorsOutsideBoundary.length === 0) {\n      const missingFiles: string[] = []\n      for (const [id, filePaths] of boundaryState.requiredIds) {\n        if (!boundaryState.renderedIds.has(id)) {\n          for (const filePath of filePaths) {\n            let normalized = filePath\n              .replace(/^\\[project\\][\\\\/]?/, '')\n              .replace(process.cwd() + '/', '')\n              .replace(process.cwd() + '\\\\', '')\n            missingFiles.push(normalized)\n          }\n        }\n      }\n      missingFiles.sort()\n      return createUnrenderedSegmentError(workStore.route, missingFiles)\n    } else if (process.env.__NEXT_DEV_SERVER && devRenderDidError) {\n      // Errors outside the boundary likely blocked it from rendering,\n      // but they're already being reported to the user via the dev\n      // render. Suppress the validation failure to avoid noise.\n      return []\n    } else if (thrownErrorsOutsideBoundary.length === 1) {\n      const message = `Route \"${workStore.route}\": Could not validate \\`instant\\` because the target segment was prevented from rendering, likely due to the following error.`\n      const error = rootInstantStack !== null ? rootInstantStack() : new Error()\n      error.name = 'Error'\n      error.message = message\n      return new AggregateError([\n        error,\n        thrownErrorsOutsideBoundary[0] as Error,\n      ])\n    } else {\n      const message = `Route \"${workStore.route}\": Could not validate \\`instant\\` because the target segment was prevented from rendering, likely due to one of the following errors.`\n      const error = rootInstantStack !== null ? rootInstantStack() : new Error()\n      error.name = 'Error'\n      error.message = message\n      return new AggregateError([\n        error,\n        ...(thrownErrorsOutsideBoundary as Error[]),\n      ])\n    }\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} from './app-render/staged-rendering'\nimport type {\n  RequestStore,\n  WorkUnitStore,\n} from './app-render/work-unit-async-storage.external'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from './runtime-reacts.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\nconst CLIENT_HOOK_DYNAMIC = 'CLIENT_HOOK_DYNAMIC'\n\nexport class ClientHookDynamicError extends Error {\n  public readonly digest = CLIENT_HOOK_DYNAMIC\n\n  constructor(route: string, expression: string) {\n    super(\n      `Route \"${route}\": Next.js encountered URL data \\`${expression}\\` in a Client Component outside of \\`<Suspense>\\`.\\n\\n` +\n        `This blocks prerendering because the value is only available at runtime.\\n\\n` +\n        `Ways to fix this:\\n` +\n        `  - [stream] Wrap the component in \\`<Suspense fallback={...}>\\` so the hook value streams in after prerendering\\n` +\n        `  - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\n` +\n        `Learn more: https://nextjs.org/docs/messages/blocking-prerender-client-hook`\n    )\n  }\n}\n\nexport function isClientHookDynamicError(\n  err: unknown\n): err is ClientHookDynamicError {\n  if (typeof err !== 'object' || err === null || !('digest' in err)) {\n    return false\n  }\n\n  return err.digest === CLIENT_HOOK_DYNAMIC\n}\n\ntype AbortListeners = Array<() => void>\nconst abortListenersBySignal = new WeakMap<AbortSignal, AbortListeners>()\n\n/**\n * Constructs a promise that never resolves, standing in for *dynamic* data:\n * data that is only available during a real dynamic request and hangs in\n * every kind of prerender — `io()`, `connection()`, uncached `fetch()`.\n *\n * This is primarily useful for cacheComponents where we use promise\n * resolution timing to determine which parts of a render can be included in a\n * prerender.\n *\n * Records nothing on the prerender store: the promise's holes are only ever\n * filled by a real dynamic request, so a runtime prefetch response would have\n * the same holes as the static one. If the data source would resolve during a\n * runtime prerender, use `makeRuntimeHangingPromise` instead.\n *\n * @internal\n */\nexport function makeDynamicHangingPromise<T>(\n  signal: AbortSignal,\n  route: string,\n  expression: string\n): Promise<T> {\n  return makeHangingPromiseWithError(\n    signal,\n    new HangingPromiseRejectionError(route, expression)\n  )\n}\n\nexport function makeUntrackedHangingPromise<T>(\n  signal: AbortSignal,\n  route: string,\n  expression: string\n): Promise<T> {\n  return makeHangingPromiseWithError(\n    signal,\n    new HangingPromiseRejectionError(route, expression)\n  )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for *runtime* data:\n * data that hangs during a static prerender but is available during a runtime\n * prerender (the kind that backs a runtime prefetch request: request data\n * like cookies and headers is available, but the render is still not a real\n * dynamic request). Examples: cookies, headers, fallback params,\n * searchParams, and cache entries that are excluded only from static\n * prerenders.\n *\n * Creating one of these during a static prerender records on the prerender\n * store that a runtime prefetch would produce more content than the static\n * response (`runtimeDataAccessed`), which the segment prefetch encoding uses\n * to tell the client whether a runtime prefetch request could be skipped.\n *\n * When unsure whether data is dynamic or runtime, prefer this method — the\n * cost of over-recording is a redundant runtime prefetch request; the cost of\n * under-recording is a permanently missing one.\n *\n * `workUnitStore` may be null ONLY when the caller tracks the access itself\n * at observation time instead of creation time. This is for promises the\n * framework creates eagerly whether or not anything reads them (e.g. the\n * `searchParams` prop constructed for every page): recording at creation\n * would mark every render. Such a caller MUST call `trackRuntimeDataAccessed`\n * from every path that observes the promise (e.g. the proxy traps for\n * `then`/`status`), against the work unit store active at access time.\n *\n * For fallback-param data — data a concrete (ISR-upgraded) prerender would\n * resolve — use `makeFallbackParamsHangingPromise` instead, so the access\n * is recorded with the right effect on the static-prefetch hint.\n *\n * @internal\n */\nexport function makeRuntimeHangingPromise<T>(\n  signal: AbortSignal,\n  route: string,\n  expression: string,\n  workUnitStore: WorkUnitStore | null\n): Promise<T> {\n  if (workUnitStore !== null) {\n    trackRuntimeDataAccessed(workUnitStore)\n  }\n  return makeHangingPromiseWithError(\n    signal,\n    new HangingPromiseRejectionError(route, expression)\n  )\n}\n\n/**\n * Variant of `makeRuntimeHangingPromise` for *fallback-param* data: fallback\n * route params and values derived solely from them (`params`, `rootParams`,\n * `pathname` during a fallback prerender). Like every runtime data access it\n * records the access on the prerender store's response-level flag, but its\n * effect on the build-time static-prefetch hint differs — on a\n * fallback-upgradeable route the access is transient (a concrete prerender\n * resolves it), so it leaves the hint intact. See\n * `trackFallbackParamsAccessed`.\n *\n * As with `makeRuntimeHangingPromise`, `workUnitStore` may be null ONLY when\n * the caller tracks the access itself at observation time instead of creation\n * time, by calling `trackFallbackParamsAccessed` from every path that\n * observes the promise.\n *\n * @internal\n */\nexport function makeFallbackParamsHangingPromise<T>(\n  signal: AbortSignal,\n  route: string,\n  expression: string,\n  workUnitStore: WorkUnitStore | null\n): Promise<T> {\n  if (workUnitStore !== null) {\n    trackFallbackParamsAccessed(workUnitStore)\n  }\n  return makeHangingPromiseWithError(\n    signal,\n    new HangingPromiseRejectionError(route, expression)\n  )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for data that is only\n * accessible in a later *stage* of rendering than this render reaches — e.g.\n * a prefetchable short-stale cache entry that's excluded from shells when the\n * render ends at the shell stage, or params during a runtime-prefetch render\n * that stops before the stage where params resolve.\n *\n * A render that runs through the later stage would include the data; in\n * particular a runtime prefetch renders through its later stages, so on a\n * static prerender store this records `runtimeDataAccessed`, same as\n * `makeRuntimeHangingPromise`.\n *\n * @internal\n */\nexport function makeStageHangingPromise<T>(\n  signal: AbortSignal,\n  route: string,\n  expression: string,\n  workUnitStore: WorkUnitStore\n): Promise<T> {\n  trackRuntimeDataAccessed(workUnitStore)\n  return makeHangingPromiseWithError(\n    signal,\n    new HangingPromiseRejectionError(route, expression)\n  )\n}\n\n/**\n * Records on a static prerender store that the render accessed a data source\n * which would have resolved during a runtime prerender. No-op for all other\n * store types.\n *\n * `makeRuntimeHangingPromise` and `makeStageHangingPromise` call this\n * automatically; call it directly only where the access is observed\n * separately from the promise's creation (see the null `workUnitStore` case\n * of `makeRuntimeHangingPromise`), or where the prerender is aborted\n * synchronously instead of hanging.\n *\n * For fallback-param data, use `trackFallbackParamsAccessed` instead. When\n * unsure, this is the conservative choice: it unconditionally clears the\n * static-prefetch hint.\n */\nexport function trackRuntimeDataAccessed(workUnitStore: WorkUnitStore): void {\n  trackRuntimeDataAccessedImpl(workUnitStore, false)\n}\n\n/**\n * Fallback-param variant of `trackRuntimeDataAccessed`, for accesses of\n * fallback route params and values derived solely from them. It records the\n * response-level flag all the same, but only clears the build-time\n * static-prefetch hint when the route is not fallback-upgradeable — on an\n * upgradeable route the access is transient, since ISR later produces a\n * concrete prerender that resolves it.\n */\nexport function trackFallbackParamsAccessed(\n  workUnitStore: WorkUnitStore\n): void {\n  trackRuntimeDataAccessedImpl(workUnitStore, true)\n}\n\nfunction trackRuntimeDataAccessedImpl(\n  workUnitStore: WorkUnitStore,\n  isFallbackParamAccess: boolean\n): void {\n  switch (workUnitStore.type) {\n    case 'prerender': {\n      // Response-level flag (the payload's `u`, forwarded to segment\n      // responses as `needsRuntimeRequest`): resolved for every kind of\n      // access — a pre-upgrade fallback response must keep reporting that\n      // a runtime request would return more. The fulfillment row lands at\n      // the current position in the Flight stream, which is what makes the\n      // value rewindable per stage. Promise resolution is idempotent, so\n      // repeated accesses are free.\n      workUnitStore.runtimeDataAccessed?.resolve(true)\n\n      // Hint cell (holds the build-constant\n      // PrefetchHint.ShouldAttemptStaticPrefetch value directly): a\n      // fallback-param access is transient when the route is\n      // fallback-upgradeable — ISR later produces the concrete prerender a\n      // static prefetch attempt would hit — so it leaves the hint intact.\n      // (Until that upgrade, the response-level flag above keeps directing\n      // the client to a runtime fallback; the hint only costs a wasted\n      // static attempt in the interim.) Every other access clears it.\n      const hintCell = workUnitStore.shouldAttemptStaticPrefetch\n      if (\n        hintCell !== null &&\n        (!isFallbackParamAccess || !workUnitStore.isFallbackUpgradeable)\n      ) {\n        hintCell.current = false\n      }\n      break\n    }\n    case 'prerender-client':\n    case 'prerender-ppr':\n    case 'prerender-legacy':\n    case 'prerender-runtime':\n    case 'validation-client':\n    case 'request':\n    case 'cache':\n    case 'private-cache':\n    case 'unstable-cache':\n    case 'generate-static-params':\n      // Only the modern server prerender tracks this; see the field docs on\n      // PrerenderStoreModernServer.\n      break\n    default:\n      workUnitStore satisfies never\n  }\n}\n\nexport function makeClientHookHangingPromise<T>(\n  signal: AbortSignal,\n  error: ClientHookDynamicError\n): Promise<T> {\n  return makeHangingPromiseWithError(signal, error)\n}\n\nfunction makeHangingPromiseWithError<T>(\n  signal: AbortSignal,\n  error: Error\n): Promise<T> {\n  if (signal.aborted) {\n    return Promise.reject(error)\n  } else {\n    const hangingPromise = new Promise<T>((_, reject) => {\n      const boundRejection = reject.bind(null, error)\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\n/**\n * Creates a promise that will be triggered when another promise resolves.\n * It will not emit unhandled rejections, which is important if the trigger\n * is a promise that might itself get rejected (e.g. when a prerender/render\n * are aborted due to sync IO)\n */\nexport function makePromiseFromTrigger<T>(\n  trigger: Promise<any>,\n  value: T\n): Promise<T> {\n  const promise = trigger.then(() => value)\n  promise.catch(ignoreReject)\n  return promise\n}\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\nexport const RENDER_STAGES_BY_DATA_KIND = {\n  sessionData: RenderStage.ShellRuntime as const,\n  staticLinkData: RenderStage.Static as const,\n  runtimeLinkData: RenderStage.Runtime as const,\n}\n\nexport function applyOwnerStack(error: Error): Error {\n  if (process.env.NODE_ENV !== 'production') {\n    let ownerStack: string | undefined | null\n    const workUnitStore = workUnitAsyncStorage.getStore()\n\n    // captureOwnerStack() returns the owner stack for the current React\n    // rendering context. Inside a cache scope this only includes the inner\n    // component tree. The outer owner stack (captured before entering the\n    // cache boundary in use-cache-wrapper.ts) is stored on the cache store.\n    // We concatenate both to get the full component tree.\n    const innerOwnerStack =\n      getClientReact()?.captureOwnerStack?.() ??\n      getServerReact()?.captureOwnerStack?.()\n\n    switch (workUnitStore?.type) {\n      case 'cache':\n      case 'private-cache':\n        ownerStack =\n          (innerOwnerStack || '') + (workUnitStore.outerOwnerStack || '') ||\n          undefined\n        break\n      case 'unstable-cache':\n      case 'request':\n      case 'prerender':\n      case 'prerender-ppr':\n      case 'prerender-legacy':\n      case 'prerender-runtime':\n      case 'prerender-client':\n      case 'validation-client':\n      case 'generate-static-params':\n      case undefined:\n        ownerStack = innerOwnerStack\n        break\n      default:\n        workUnitStore satisfies never\n    }\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","export type SyncIOApiType = 'time' | 'random' | 'crypto'\n\nconst SYNC_IO_DOCS: Record<SyncIOApiType, string> = {\n  time: 'https://nextjs.org/docs/messages/blocking-prerender-current-time',\n  random: 'https://nextjs.org/docs/messages/blocking-prerender-random',\n  crypto: 'https://nextjs.org/docs/messages/blocking-prerender-crypto',\n}\n\nconst SYNC_IO_CLIENT_DOCS: Record<SyncIOApiType, string> = {\n  time: 'https://nextjs.org/docs/messages/blocking-prerender-current-time-client',\n  random: 'https://nextjs.org/docs/messages/blocking-prerender-random-client',\n  crypto: 'https://nextjs.org/docs/messages/blocking-prerender-crypto-client',\n}\n\nconst SYNC_IO_RUNTIME_DOCS: Record<SyncIOApiType, string> = {\n  time: 'https://nextjs.org/docs/messages/blocking-prerender-current-time',\n  random: 'https://nextjs.org/docs/messages/blocking-prerender-random',\n  crypto: 'https://nextjs.org/docs/messages/blocking-prerender-crypto',\n}\n\nfunction elapsedTimeBullet(type: SyncIOApiType): string {\n  return type === 'time'\n    ? `\\n  - [measure] If the value is for telemetry, use a timing API such as \\`performance.now()\\``\n    : ''\n}\n\nfunction createSyncIOErrorImpl(\n  route: string,\n  expression: string,\n  type: SyncIOApiType,\n  docsUrl: string\n): Error {\n  return new Error(\n    `Route \"${route}\": Next.js encountered the unstable value ${expression} while prerendering.\\n\\n` +\n      `This value can change between renders, so it must be either prerendered or computed later.\\n\\n` +\n      `Ways to fix this:\\n` +\n      `  - [dynamic] Render at request time by adding a dynamic data access (e.g. \\`await connection()\\`) before this call\\n` +\n      `  - [cache] Prerender and cache the value with \\`\"use cache\"\\`\\n` +\n      `  - [client] Render the value on the client with \\`\"use client\"\\`` +\n      elapsedTimeBullet(type) +\n      `\\n\\nLearn more: ${docsUrl}`\n  )\n}\n\nexport function createSyncIOError(\n  route: string,\n  expression: string,\n  type: SyncIOApiType\n): Error {\n  return createSyncIOErrorImpl(route, expression, type, SYNC_IO_DOCS[type])\n}\n\nexport function createSyncIORuntimeError(\n  route: string,\n  expression: string,\n  type: SyncIOApiType\n): Error {\n  return createSyncIOErrorImpl(\n    route,\n    expression,\n    type,\n    SYNC_IO_RUNTIME_DOCS[type]\n  )\n}\n\nexport function createSyncIOClientError(\n  route: string,\n  expression: string,\n  type: SyncIOApiType\n): Error {\n  const docsUrl = SYNC_IO_CLIENT_DOCS[type]\n  return new Error(\n    `Route \"${route}\": Next.js encountered the unstable value ${expression} in a Client Component.\\n\\n` +\n      `This value would be evaluated during the prerender, instead of recomputed on each visit.\\n\\n` +\n      `Ways to fix this:\\n` +\n      `  - [stream] Wrap the Client Component in \\`<Suspense fallback={...}>\\`\\n` +\n      `  - [defer] Move the read into a \\`useEffect\\` or event handler` +\n      elapsedTimeBullet(type) +\n      `\\n\\nLearn more: ${docsUrl}`\n  )\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 { RenderStage } from '../app-render/staged-rendering'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport {\n  createSyncIOClientError,\n  createSyncIOError,\n  createSyncIORuntimeError,\n  type SyncIOApiType,\n} from '../app-render/sync-io-messages'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function io(expression: string, type: SyncIOApiType) {\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        abortOnSynchronousPlatformIOAccess(\n          workStore.route,\n          expression,\n          applyOwnerStack(createSyncIOError(workStore.route, expression, type)),\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        abortOnSynchronousPlatformIOAccess(\n          workStore.route,\n          expression,\n          applyOwnerStack(\n            createSyncIOClientError(workStore.route, expression, type)\n          ),\n          workUnitStore\n        )\n      }\n      break\n    }\n    case 'request': {\n      const stageController = workUnitStore.stagedRendering\n      if (stageController && stageController.shouldTrackSyncInterrupt()) {\n        let syncIOError: Error\n        // NOTE: keep stages where we can interrupt in sync with\n        // `shouldTrackSyncInterrupt`/`syncInterruptCurrentStageWithReason`\n        switch (stageController.currentStage) {\n          case RenderStage.ShellStatic:\n          case RenderStage.Static: {\n            syncIOError = createSyncIOError(workStore.route, expression, type)\n            break\n          }\n          case RenderStage.ShellRuntime:\n          case RenderStage.Runtime: {\n            // We're in the Runtime stage.\n            // We only error for Sync IO in the Runtime stage if the route has partialPrefetching enabled.\n            syncIOError = createSyncIORuntimeError(\n              workStore.route,\n              expression,\n              type\n            )\n            break\n          }\n          case RenderStage.Before:\n          case RenderStage.Dynamic:\n          case RenderStage.Abandoned: {\n            throw new InvariantError(\n              `shouldTrackSyncInterrupt allowed a sync IO interrupt in an unexpected stage: ${RenderStage[stageController.currentStage]}`\n            )\n          }\n        }\n\n        syncIOError = applyOwnerStack(syncIOError)\n        stageController.syncInterruptCurrentStageWithReason(syncIOError)\n\n        // A validation render uses a 'request' store type, but may be abortable.\n        // If we're rendering with filled caches, Sync IO is an error and should trigger an abort.\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","/**\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    __NEXT_ERROR_CODE?: string\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) => {\n  // Fast path: an absolute URL must start with a letter (the scheme).\n  // Check for a-z and A-Z without the cost of the regex.\n  const c = url.charCodeAt(0)\n  const isLetter =\n    (c >= 65 /* A */ && c <= 90) /* Z */ ||\n    (c >= 97 /* a */ && c <= 122) /* z */\n  if (!isLetter) {\n    return false\n  }\n\n  return ABSOLUTE_URL_REGEX.test(url)\n}\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   * The hash of the most recent server component change (dev only), set by the\n   * router-server from the hot-reloader. Included in `\"use cache\"` cache keys\n   * so that cached entries are revalidated after an edit, for every client,\n   * regardless of whether it runs the HMR client.\n   */\n  hmrRefreshHash?: string\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. When absent, the request is not a\n   * resume request. A non-empty string contains the state to resume, while an\n   * empty string represents a resume request without postponed state and\n   * signals that the renderer should perform a full dynamic render.\n   *\n   * There are no guarantees that the page actually postponed, as verifying\n   * that would incur an additional cache 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   * Route param keys that were explicitly resolved from partial nxtP*\n   * query params during background revalidation. Used by app-page.ts to\n   * determine which fallback params should remain deferred vs resolved\n   * in intermediate PPR shells.\n   */\n  resolvedRouteParamKeys?: Set<string>\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 REQUEST_INSIGHTS_DEV_ENDPOINT =\n  '/_next/development/request-insights'\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}\n\n/**\n * The read methods that a sealed view provides itself instead of forwarding to\n * the underlying `Headers`. Deriving the type from `Headers` keeps the\n * implementations in step with the platform signatures.\n */\ntype SealedHeaderMethods = Pick<\n  Headers,\n  | 'get'\n  | 'has'\n  | 'getSetCookie'\n  | 'keys'\n  | 'values'\n  | 'entries'\n  | 'forEach'\n  | typeof Symbol.iterator\n>\n\n/**\n * Builds the read methods for a sealed view that exposes all of `target`.\n */\nfunction createPassThroughMethods(\n  target: Headers,\n  sealed: ReadonlyHeaders\n): SealedHeaderMethods {\n  return {\n    get: target.get.bind(target),\n    has: target.has.bind(target),\n    getSetCookie: target.getSetCookie.bind(target),\n    keys: target.keys.bind(target),\n    values: target.values.bind(target),\n    entries: target.entries.bind(target),\n    [Symbol.iterator]: target[Symbol.iterator].bind(target),\n    // The native method passes the unsealed target as the callback's `parent`\n    // argument. That is a mutable handle on the underlying headers. Pass the\n    // sealed view instead.\n    forEach(callbackfn, thisArg) {\n      for (const [name, value] of target.entries()) {\n        callbackfn.call(thisArg, value, name, sealed)\n      }\n    },\n  }\n}\n\n/**\n * Builds the read methods for a sealed view that omits the header names matched\n * by `isHidden`.\n */\nfunction createHidingMethods(\n  target: Headers,\n  sealed: ReadonlyHeaders,\n  isHidden: (name: string) => boolean\n): SealedHeaderMethods {\n  function* entries(): HeadersIterator<[string, string]> {\n    for (const entry of target.entries()) {\n      if (!isHidden(entry[0])) {\n        yield entry\n      }\n    }\n  }\n\n  return {\n    entries,\n    [Symbol.iterator]: entries,\n    get: (name) => (isHidden(name) ? null : target.get(name)),\n    has: (name) => (isHidden(name) ? false : target.has(name)),\n    getSetCookie: () => (isHidden('set-cookie') ? [] : target.getSetCookie()),\n    *keys(): HeadersIterator<string> {\n      for (const name of target.keys()) {\n        if (!isHidden(name)) {\n          yield name\n        }\n      }\n    },\n    *values(): HeadersIterator<string> {\n      for (const [, value] of entries()) {\n        yield value\n      }\n    },\n    // The native method passes the unsealed target as the callback's `parent`\n    // argument. That is a mutable handle on the underlying headers. Pass the\n    // sealed view instead.\n    forEach(callbackfn, thisArg) {\n      for (const [name, value] of entries()) {\n        callbackfn.call(thisArg, value, name, sealed)\n      }\n    },\n  }\n}\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   * The sealed view stays live. Later writes to `headers` remain visible\n   * through it.\n   *\n   * `hidden` omits the given header names from every read operation (`get`,\n   * `has`, `getSetCookie`, `forEach`, and iteration). The names must be\n   * lowercase. The underlying headers are neither copied nor mutated, so hidden\n   * headers remain available to the framework.\n   */\n  public static seal(\n    headers: Headers,\n    hidden?: ReadonlySet<string>\n  ): ReadonlyHeaders {\n    const isHidden =\n      hidden && hidden.size > 0\n        ? (name: string): boolean => hidden.has(name.toLowerCase())\n        : null\n\n    // The methods are built once per sealed view and reused, so repeated access\n    // returns the same function instead of a fresh closure. They are assigned\n    // after the proxy exists because `forEach` hands the proxy to its callback.\n    // Creating the proxy runs no trap, so nothing can read them before then.\n    let methods: SealedHeaderMethods\n\n    const sealed: ReadonlyHeaders = 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          case Symbol.iterator:\n            return methods[Symbol.iterator]\n          case 'get':\n          case 'has':\n          case 'getSetCookie':\n          case 'keys':\n          case 'values':\n          case 'entries':\n          case 'forEach':\n            return methods[prop]\n          default:\n            return ReflectAdapter.get(target, prop, receiver)\n        }\n      },\n    })\n\n    methods = isHidden\n      ? createHidingMethods(headers, sealed, isHidden)\n      : createPassThroughMethods(headers, sealed)\n\n    return sealed\n  }\n\n  /**\n   * @param headers\n   * @returns A fresh object identity backed by the original value\n   */\n  public static fresh(headers: ReadonlyHeaders): ReadonlyHeaders {\n    return new Proxy<ReadonlyHeaders>(headers, {\n      get(target, prop, receiver) {\n        return ReflectAdapter.get(target, prop, receiver)\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 { IncomingHttpHeaders, IncomingMessage } from '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  rawHeaders: Headers | IncomingHttpHeaders,\n  previewProps: __ApiPreviewProps\n): {\n  isOnDemandRevalidate: boolean\n  revalidateOnlyGenerated: boolean\n} {\n  // Headers is a plain object for Node.js, Headers object in Edge runtime\n  if (typeof rawHeaders.get === 'function') {\n    const headers = HeadersAdapter.from(rawHeaders)\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\n  const headers = rawHeaders as IncomingHttpHeaders\n\n  const previewModeId = headers[PRERENDER_REVALIDATE_HEADER]\n  const isOnDemandRevalidate = previewModeId === previewProps.previewModeId\n\n  const revalidateOnlyGenerated = headers.hasOwnProperty(\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 type { FallbackRouteParam } from '../build/static-paths/types'\nimport type { MemoryEvictionMode } from '../build/swc/types'\nimport type { CacheLife } from './use-cache/cache-life'\n\n/**\n * The `cacheLife` profiles after config normalization. `config.ts` always\n * backfills the `default` profile so that its `stale`, `revalidate`, and\n * `expire` are all defined, which is why `default` is `Required<CacheLife>`\n * here while other profiles may still be partial. Runtime `\"use cache\"` code\n * can therefore read `cacheLifeProfiles.default` without re-validating it.\n */\nexport interface ResolvedCacheLifeProfiles {\n  default: Required<CacheLife>\n  [profile: string]: CacheLife\n}\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<\n  Omit<NextConfig, 'configFile' | 'cacheLife'>\n> & {\n  images: Required<ImageConfigComplete>\n  typescript: TypeScriptConfig\n  configFile: string | undefined\n  configFileName: string\n  // Normalized by config.ts: the `default` profile is backfilled to be complete\n  // (see `ResolvedCacheLifeProfiles`), unlike the optional/partial user input.\n  // Omitted from the base so this is a clean replacement, not an intersection.\n  cacheLife: ResolvedCacheLifeProfiles\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    // Normalized by config.ts: defaulted to 90% of staticPageGenerationTimeout\n    useCacheTimeout: number\n    // Normalized by config.ts `finalizeConfig`: defaulted to `'warning'`\n    instantInsights: { validationLevel: ValidationLevel }\n    // Normalized by finalized config with a default and the expected type\n    turbopackMemoryEvictionMode: MemoryEvictionMode\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  // The repository root, regardless of overwritten outputFileTracingRoot or turbopack.root.\n  repoRoot: 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  /**\n   * Override the global variable name used for\n   * chunk loading. Useful when multiple Turbopack-built apps run on the same\n   * page (e.g. horizontal micro-frontends) to avoid `globalThis.TURBOPACK`\n   * conflicts.\n   *\n   * @see https://webpack.js.org/configuration/output/#outputchunkloadingglobal\n   */\n  chunkLoadingGlobal?: string\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\n/**\n * Accepted shapes for `experimental.cssChunking`. See [`ExperimentalConfig.cssChunking`] for the\n * accepted values; use [`resolveCssChunkingMode`] to normalize the value at runtime.\n */\nexport type CssChunkingConfig =\n  | boolean\n  | 'strict'\n  | 'loose'\n  | 'graph'\n  | { type: 'strict' }\n  | { type: 'loose' }\n  | { type: 'graph'; requestCost?: number; weightDistribution?: number }\n\n/**\n * Normalize any [`CssChunkingConfig`] value to one of the four modes the build pipeline cares\n * about:\n *   - `'off'`  — `false`/`undefined`: do not run a CSS chunking plugin.\n *   - `'loose'` — `true` / `'loose'` / `{ type: 'loose' }`: heuristic-based chunking\n *     (the default).\n *   - `'strict'` — `'strict'` / `{ type: 'strict' }`: webpack-only ordered-chunking plugin.\n *   - `'graph'` — `'graph'` / `{ type: 'graph', … }`: Turbopack-only graph algorithm.\n */\nexport function resolveCssChunkingMode(\n  value: CssChunkingConfig | undefined\n): 'off' | 'loose' | 'strict' | 'graph' {\n  if (value === undefined || value === false) return 'off'\n  if (value === true || value === 'loose') return 'loose'\n  if (value === 'strict' || value === 'graph') return value\n  // Object form. `requestCost` and `weightDistribution` are validated by the schema.\n  if (value.type === 'strict') return 'strict'\n  if (value.type === 'graph') return 'graph'\n  return 'loose'\n}\n\nexport interface ExperimentalConfig {\n  /**\n   * @deprecated Use the top-level `outputHashSalt` option instead.\n   */\n  outputHashSalt?: string\n\n  appNewScrollHandler?: boolean\n  /**\n   * Shows a persistent \"Cold cache\" badge in the dev overlay after a load that\n   * filled an empty cache while streaming. Off by default while the badge's\n   * UI/UX is iterated on; the transient \"Rendering (cold cache)\" pill is shown\n   * regardless of this flag.\n   */\n  coldCacheBadge?: 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  /**\n   * Caches subsets of a route, seeded from actual navigations, so subsequent\n   * navigations to the same or similar pages can be served instantly. Requires\n   * Cache Components.\n   */\n  cachedNavigations?: boolean\n  dynamicOnHover?: boolean\n  useOffline?: boolean\n  optimisticRouting?: boolean\n  instrumentationClientRouterTransitionEvents?: 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 Request Insights in the dev tools indicator. Request Insights records\n   * the local framework spans needed to explain App Router request, render,\n   * fetch, and cache behavior without requiring an external OTEL collector.\n   */\n  requestInsights?: boolean\n  extensionAlias?: Record<string, any>\n  allowedRevalidateHeaderKeys?: string[]\n  fetchCacheKeyPrefix?: string\n  imgOptConcurrency?: number | null\n  imgOptOperationCache?: boolean | null\n  imgOptTimeoutInSeconds?: number\n  imgOptMaxInputPixels?: number\n  imgOptSequentialRead?: 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 between\n   * CSS files to keep ordering of them.\n   *\n   * - `true` / `'loose'` / `{ type: 'loose' }` — default heuristic-based chunking.\n   * - `'strict'` / `{ type: 'strict' }` — preserve correct ordering as much as possible, even\n   *   when this leads to many requests. Webpack only.\n   * - `false` — disable chunking; emit one chunk per CSS module. Webpack only.\n   * - `'graph'` / `{ type: 'graph', requestCost?, weightDistribution? }` — Turbopack only.\n   *   Selects a CSS chunking strategy that analyzes the most common style orderings across the\n   *   application and produces shared chunks accordingly. Compared to the default mode it\n   *   intentionally overships some styles in order to reduce the number of CSS requests per\n   *   page. Cost overrides:\n   *     - `requestCost` (bytes, default `100000`) — additional cost charged for every CSS\n   *       request a chunk group makes. Larger values bias the algorithm toward fewer, larger\n   *       shared chunks; smaller values toward more, smaller chunks.\n   *     - `weightDistribution` (default `0.1`) — controls how a chunk's cost is distributed across\n   *       the chunk groups that load it, via a per-group weight of\n   *       `groupSize ^ (-weightDistribution)`. `0` weights every chunk group equally; higher\n   *       values give smaller chunk groups more weight, so small pages ship fewer unrelated\n   *       styles at the expense of more requests overall.\n   */\n  cssChunking?: CssChunkingConfig\n  /**\n   * Controls whether the development server automatically restarts when its\n   * heap usage exceeds the memory threshold. Defaults to `true`.\n   */\n  devMemoryThresholdRestart?: boolean\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\n  /**\n   * Additional options for SWC's preset-env (`env` configuration).\n   * These are merged into the `env` block that Next.js passes to SWC,\n   * alongside the browserslist-derived `targets`.\n   *\n   * See https://swc.rs/docs/configuration/supported-browsers for full details.\n   *\n   * @example\n   * ```js\n   * // next.config.js\n   * module.exports = {\n   *   experimental: {\n   *     swcEnvOptions: {\n   *       mode: 'usage',\n   *       coreJs: '3.38',\n   *     },\n   *   },\n   * }\n   * ```\n   */\n  swcEnvOptions?: {\n    /**\n     * Polyfill injection mode, matching Babel's `useBuiltIns`.\n     * - `'usage'`: Adds specific polyfill imports per file based on actual usage.\n     * - `'entry'`: Replaces a single `import 'core-js'` with only the polyfills\n     *   needed for the target browsers.\n     */\n    mode?: 'usage' | 'entry'\n    /** The core-js version to use (e.g. `'3.38'`). Required when `mode` is set. */\n    coreJs?: string\n    /** Core-js modules or SWC transform passes to skip. */\n    skip?: string[]\n    /** Core-js modules or SWC transform passes to always include. */\n    include?: string[]\n    /** Core-js modules or SWC transform passes to always exclude. */\n    exclude?: string[]\n    /** Enable shipped TC39 proposals. */\n    shippedProposals?: boolean\n    /** Force all transforms regardless of targets. */\n    forceAllTransforms?: boolean\n    /** Enable debug output for preset-env. */\n    debug?: boolean\n    /** Enable loose mode for transforms. */\n    loose?: boolean\n  }\n\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   * Runs the project-local TypeScript CLI instead of using TypeScript's\n   * programmatic API for build-time type checking and config loading.\n   */\n  useTypeScriptCli?: 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   * Controls Turbopack's memory eviction strategy for development sessions\n   *\n   * Only effective in dev sessions where\n   * `experimental.turbopackFileSystemCacheForDev` is enabled (which it is by default).\n   *\n   * - `false`: disable eviction.\n   * - `'full'`: after every snapshot, drop as much memory as possible.\n   * - `'auto'`: evict after a snapshot when we expect to save a lot of memory or the system is under pressure\n   *\n   * Defaults to `'auto'`\n   */\n  turbopackMemoryEviction?: false | 'full' | 'auto'\n\n  /**\n   * Selects the backend used by Turbopack for Node.js evaluation, e.g. webpack\n   * loaders, Babel, or PostCSS.\n   *\n   * This defaults to `'childProcesses'`, which creates a pool of child node.js\n   * processes and communciates with them over sockets.\n   *\n   * `'workerThreads'` runs the same work in worker threads instead, which should\n   * use less memory and CPU. It may become the default in a future version of\n   * Next.js.\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 scope hoisting. Defaults to true in build mode. Always disabled in development mode.\n   */\n  turbopackScopeHoisting?: boolean\n\n  /**\n   * Share the browser runtime across routes in a single `runtime.js` asset and inline the\n   * per-route chunk-group bootstrap into the HTML, dropping the per-route runtime. Defaults to\n   * false. Only applies to production builds; has no effect in development mode.\n   */\n  turbopackSharedRuntime?: boolean\n\n  /**\n   * (`next --turbopack` only) These options change the assumptions Turbopack makes when\n   * making chunk merging decisions and the raw size thresholds it uses.\n   */\n  turbopackChunking?: {\n    /**\n     * This is a number between `0..1`, when higher, we weight the benefits of\n     * merging chunks for a signal page load higher. If you don't know a good\n     * number for this, your bounce rate is a good approximate for this value.\n     */\n    firstPageLoadPriority?: number\n    /**\n     * Regular expressions matching routes that are often the first page\n     * visited and whose client-side bundles should be merged more eagerly to reduce the single-route\n     * request cost (e.g. the homepage). This is at the cost of extra requests on other pages.\n     */\n    priorityRoutes?: RegExp[]\n    /**\n     * How much more eagerly to merge the client-side bundles of\n     * `priorityRoutes` routes, as a multiplier on their single-request probability (default\n     * `1.5`). Higher values merge more aggressively for those routes at the cost of extra requests\n     * elsewhere.\n     */\n    priorityBoost?: number\n    /**\n     * Estimated cost of an additional request, in bytes (uncompressed\n     * and unminfified bytes of code, default is 200 KB), used by the chunker to\n     * trade off request count against preventing double-fetching. Uncompressed and unminfified code\n     * is approximately 5x the size of compressed and minified code.\n     */\n    requestCost?: number\n    /**\n     * Avoid creating more than one chunk smaller than this size, in bytes. Smaller\n     * chunks are merged into bigger ones to avoid that. Defaults to `50000` (50 KB).\n     */\n    minChunkSize?: number\n    /**\n     * Avoid creating more than this number of chunks per chunk group. Chunks are\n     * merged into bigger ones to avoid that. Defaults to `40`.\n     */\n    maxChunkCountPerGroup?: number\n    /**\n     * Never merge chunks bigger than this size, in bytes, with other chunks. This keeps code\n     * in big chunks from being duplicated across multiple chunks. Defaults to `200000` (200 KB).\n     */\n    maxMergeChunkSize?: number\n    /**\n     * Emit each merged production chunk's constituent component chunks alongside it, so the\n     * browser runtime can load only the ones it doesn't already have. Defaults to `false`.\n     */\n    generateComponentChunks?: boolean\n    /**\n     * Minimum size, in bytes, for a component chunk to be emitted on its own when\n     * `generateComponentChunks` is enabled. Component chunks smaller than this are folded into a\n     * single remainder chunk. Defaults to `20000` (20 KB).\n     */\n    minComponentChunkSize?: number\n  }\n\n  /**\n   * (`next --turbopack` only) A custom URL prefix for Web Worker URLs\n   * produced by `new Worker(new URL(..., import.meta.url))` — both the\n   * entrypoint URL and the module chunks loaded inside the worker —\n   * overriding `assetPrefix` for those URLs.\n   *\n   * Use this when `assetPrefix` points to a cross-origin CDN: browsers\n   * reject cross-origin Worker construction, so the entrypoint must stay\n   * same-origin. Module chunks loaded inside the worker are also routed\n   * through this prefix because the worker bootstrap requires them to be\n   * same-origin with the entrypoint. Mirrors webpack's\n   * `output.workerPublicPath`.\n   *\n   * Like `assetPrefix`, the value is a prefix without a trailing slash and\n   * without `/_next` — `/_next/` is appended automatically. An empty\n   * string is treated as a literal empty prefix (resulting in same-origin\n   * `/_next/...` URLs); only `undefined` falls back to `assetPrefix`.\n   *\n   * @example\n   * ```js\n   * // next.config.js\n   * module.exports = {\n   *   assetPrefix: 'https://cdn.example.com',\n   *   experimental: {\n   *     turbopackWorkerAssetPrefix: '',\n   *   },\n   * }\n   * ```\n   */\n  turbopackWorkerAssetPrefix?: string\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 `true`.\n   */\n  turbopackFileSystemCacheForBuild?: boolean\n\n  /**\n   * When running inside a git worktree, warm-start this worktree's Turbopack\n   * filesystem cache by seeding it from the main checkout's cache if the\n   * worktree doesn't have one yet. This is best-effort and never fails a build.\n   *\n   * Defaults to `false`.\n   */\n  turbopackSeedCacheFromWorktree?: 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   * Currently in active development. This splits modules into fragments and\n   * chunks only import the used fragments of the modules.\n   */\n  turbopackModuleFragments?: 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   * Enable tree shaking of unused exports from analyzable CommonJS modules in Turbopack.\n   *\n   * Defaults to `false`\n   */\n  turbopackCjsTreeShaking?: 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   * Enable per-directory PostCSS config resolution for Turbopack. When enabled,\n   * Turbopack searches for `postcss.config.js` starting from the CSS file's\n   * parent directory first, then falls back to the project root. When disabled\n   * (default), the project root is checked first, with the CSS file's directory\n   * as a fallback.\n   */\n  turbopackLocalPostcssConfig?: 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   * Enable server-side Fast Refresh (Hot Module Replacement) during development\n   * with Turbopack. When set to `false`, server-side HMR is disabled and a full\n   * restart is performed on server file changes.\n   *\n   * Can also be controlled via the `--no-server-fast-refresh` CLI flag.\n   * If both are set, the CLI flag takes precedence.\n   *\n   * @default true\n   */\n  turbopackServerFastRefresh?: boolean\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   * Enables blocking server-side rendering for the `app` directory: React emits\n   * a `<link rel=\"expect\">` tag that holds the browser's first paint until the\n   * streamed shell is coherent, avoiding the layout shift / flicker that can\n   * occur while a partially-streamed HTML document is painted. Note that\n   * `rel=\"expect\"` is currently only implemented by Chromium-based browsers.\n   *\n   * This feature is currently only available in React's experimental release\n   * channel, so enabling it opts the `app` directory into `react@experimental`\n   * (the same channel used by `taint`, `transitionIndicator`, and\n   * `gestureTransition`). The name mirrors React's underlying feature flag.\n   *\n   * This is an opt-in only. Setting it to `false` does not disable the\n   * experimental channel when another feature (such as `taint`,\n   * `transitionIndicator`, or `gestureTransition`) requires it.\n   */\n  blockingSSR?: 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 `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   * Configuration for instant navigation validation.\n   */\n  instantInsights?: {\n    /**\n     * Controls the validation behavior of Instant Insights\n     *\n     * - `'warning'` (default): Validates all navigations for Instant UI in development\n     * - `'manual-warning'`: Validates navigations for Instant UI in development only when configured with `instant` in Pages and Layouts\n     * - `'experimental-error'`: Validates all navigations for Instant in development and build. Use with caution.\n     * - `'experimental-manual-error'`: Validates navigations for Instant UI in development and build when configured with `instant` in Pages and Layouts. Use with caution.\n     */\n    validationLevel?: ValidationLevel\n  }\n\n  /**\n   * Runs development Cache Components validation on a worker thread rather than\n   * the main thread, keeping the dev server's event loop responsive during\n   * rapid navigation. This covers static-shell validation (which runs on\n   * initial load and HMR refresh) as well as instant-navigation validation\n   * (when `instant` is configured). Enabled by default; set to `false` to run\n   * validation in-process, as an escape hatch to isolate a problem or fall back\n   * if the worker misbehaves.\n   *\n   * Has no effect with Webpack, where validation always runs in process. The\n   * worker's thread cannot reach Webpack's dev source maps, so validation\n   * errors would be reported without a source location.\n   */\n  devValidationWorker?: 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   * Cancels the render and validation work for a Server Components HMR refresh\n   * once a newer refresh supersedes it. Development only.\n   */\n  serverComponentsHmrCancellation?: 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   * Seconds before a `'use cache'` fill is considered stalled. Defaults to\n   * 90% of `staticPageGenerationTimeout`. In prerender it's clamped to that\n   * ceiling so errors surface before the build worker kills the page.\n   */\n  useCacheTimeout?: number\n\n  /**\n   * Enables the use of the `\"use cache\"` directive.\n   * @deprecated use top-level `cacheComponents` instead\n   */\n  useCache?: boolean\n\n  /**\n   * Enables durable `\"use cache\"` remote cache entries across deployments. Only implemented for\n   * Turbopack.\n   */\n  durableUseCacheEntries?: 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   * @experimental Use the Rust port of the React compiler (Turbopack only).\n   * Requires `reactCompiler` to be enabled.\n   */\n  turbopackRustReactCompiler?: 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   * 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   * @deprecated Use the top-level `supportsImmutableAssets` option instead.\n   */\n  supportsImmutableAssets?: boolean\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     * instant.unstable_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     * When true, a fallback shell produced for this export path could later be\n     * upgraded to a concrete version (at least one fallback param is a\n     * `generateStaticParams` candidate). Threaded into\n     * `renderOpts.isFallbackUpgradeable` so the build-baked shell carries the\n     * gated `isUpgradeableISRFallback` value.\n     *\n     * @internal\n     */\n    _isFallbackUpgradeable?: 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 */\n\nexport type ValidationLevel =\n  | 'warning'\n  | 'manual-warning'\n  | 'experimental-error'\n  | 'experimental-manual-error'\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  /**\n   * Module specifiers that are required for side effects on the client before\n   * hydration, in array order, ahead of the user's `instrumentation-client.{ts,js}`.\n   * Each entry may be a bare npm package name or a path relative to the project root.\n   */\n  instrumentationClientInject?: 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   * Whether the deployment environment supports immutable assets (assets deployed to\n   * `_next/static/immutable` don't need a `?dpl` parameter and can be safely requested across\n   * deployments.)\n   */\n  supportsImmutableAssets?: boolean\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 | number | boolean>\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 | number | boolean>\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   * Defaults to `true`. Set to `false` to disable.\n   */\n  enablePrerenderSourceMaps?: boolean\n\n  /**\n   * When enabled, routes can combine a prerendered shell with dynamic content\n   * streamed into it, rather than being either fully static or fully dynamic. You can mark data and parts of your UI as cacheable using the\n   * `use cache` directive, which includes them in the pre-render pass alongside\n   * static parts of the page. Also enables `cacheLife` and `cacheTag` APIs, and\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  /**\n   * Opts the whole app into Partial Prefetching: `<Link prefetch={true}>`\n   * prefetches only the static parts of a route, never its dynamic data.\n   * When `true`, the default segment-level `prefetch` becomes\n   * `'partial'`; per-segment `prefetch` exports still win. Requires\n   * `cacheComponents: true`.\n   *\n   * When `false` or omitted, this does nothing (the legacy behavior, where\n   * dynamic data is included in the prefetch).\n   *\n   * `'unstable_eager'` is like `true`, except the default becomes\n   * `'unstable_eager'` instead of `'partial'`: every Link has an implied\n   * prefetch={true}. Internal migration aid; not part of the public API.\n   */\n  partialPrefetching?: boolean | 'unstable_eager'\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   * When `next dev` detects an AI coding agent and no managed\n   * agent-rules block is present, Next.js auto-generates `AGENTS.md`\n   * and `CLAUDE.md` at the project root so the agent reads\n   * version-matched docs from `node_modules/next/dist/docs/` instead\n   * of stale training data. Set to `false` to disable this behavior.\n   *\n   * @default true\n   */\n  agentRules?: boolean\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  /**\n   * A string that is incorporated into content-addressed output filenames\n   * (chunks, assets) for both Webpack and Turbopack. Changing this value\n   * forces all output hashes to change, which is useful for invalidating\n   * cached assets across deployments without modifying source files.\n   *\n   * When `NEXT_HASH_SALT` environment variable is also set, the two values are\n   * concatenated (`outputHashSalt + NEXT_HASH_SALT`) to form the effective salt.\n   */\n  outputHashSalt?: 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  instrumentationClientInject: [],\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: '',\n  allowedDevOrigins: undefined,\n  enablePrerenderSourceMaps: true,\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: true,\n    coldCacheBadge: false,\n    devValidationWorker: true,\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    dynamicOnHover: false,\n    useOffline: false,\n    varyParams: true,\n    optimisticRouting: true,\n    instrumentationClientRouterTransitionEvents: false,\n    prefetchInlining: true,\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    imgOptOperationCache: null,\n    imgOptTimeoutInSeconds: 7,\n    imgOptMaxInputPixels: 268_402_689, // https://sharp.pixelplumbing.com/api-constructor#:~:text=%5Boptions.limitInputPixels%5D\n    imgOptSequentialRead: null,\n    isrFlushToDisk: true,\n    workerThreads: false,\n    proxyTimeout: undefined,\n    optimizeCss: false,\n    nextScriptWorkers: false,\n    scrollRestoration: false,\n    externalDir: false,\n    devMemoryThresholdRestart: true,\n    disableOptimizedLoading: false,\n    gzipSize: true,\n    craCompat: false,\n    esmExternals: true,\n    fullySpecified: false,\n    swcTraceProfiling: false,\n    forceSwcTransforms: false,\n    requestInsights: 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    useTypeScriptCli: true,\n    removeUncaughtErrorAndRejectionListeners: false,\n    validateRSCRequestHeaders: true,\n    staleTimes: {\n      dynamic: 0,\n      static: 300,\n    },\n    allowDevelopmentBuild: undefined,\n    reactDebugChannel: true,\n    staticGenerationRetryCount: undefined,\n    serverComponentsHmrCache: true,\n    serverComponentsHmrCancellation: false,\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: true,\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  supportsImmutableAssets?: NextConfigComplete['supportsImmutableAssets']\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  partialPrefetching: NextConfigComplete['partialPrefetching']\n  agentRules: NextConfigComplete['agentRules']\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  staticPageGenerationTimeout: NextConfigComplete['staticPageGenerationTimeout']\n\n  experimental: Pick<\n    NextConfigComplete['experimental'],\n    | 'ppr'\n    | 'taint'\n    | 'serverActions'\n    | 'staleTimes'\n    | 'dynamicOnHover'\n    | 'useOffline'\n    | 'optimisticRouting'\n    | 'inlineCss'\n    | 'prefetchInlining'\n    | 'authInterrupts'\n    | 'useCacheTimeout'\n    | 'clientTraceMetadata'\n    | 'clientParamParsingOrigins'\n    | 'allowedRevalidateHeaderKeys'\n    | 'fetchCacheKeyPrefix'\n    | 'isrFlushToDisk'\n    | 'optimizeCss'\n    | 'nextScriptWorkers'\n    | 'disableOptimizedLoading'\n    | 'largePageDataBytes'\n    | 'serverComponentsHmrCache'\n    | 'serverComponentsHmrCancellation'\n    | 'caseSensitiveRoutes'\n    | 'validateRSCRequestHeaders'\n    | 'sri'\n    | 'useSkewCookie'\n    | 'preloadEntriesOnStart'\n    | 'hideLogsAfterAbort'\n    | 'removeUncaughtErrorAndRejectionListeners'\n    | 'imgOptConcurrency'\n    | 'imgOptOperationCache'\n    | 'imgOptMaxInputPixels'\n    | 'imgOptSequentialRead'\n    | 'imgOptTimeoutInSeconds'\n    | 'proxyClientMaxBodySize'\n    | 'proxyTimeout'\n    | 'testProxy'\n    | 'runtimeServerDeploymentId'\n    | 'maxPostponedStateSize'\n    | 'cachedNavigations'\n    | 'exposeTestingApiInProductionBuild'\n    | 'instantInsights'\n    | 'requestInsights'\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  const ex = config.experimental\n\n  type Requiredish<T> = {\n    [K in keyof Required<T>]: T[K]\n  }\n\n  const experimental = {\n    ppr: ex.ppr,\n    taint: ex.taint,\n    serverActions: ex.serverActions,\n    staleTimes: ex.staleTimes,\n    dynamicOnHover: ex.dynamicOnHover,\n    useOffline: ex.useOffline,\n    optimisticRouting: ex.optimisticRouting,\n    inlineCss: ex.inlineCss,\n    prefetchInlining: ex.prefetchInlining,\n    authInterrupts: ex.authInterrupts,\n    useCacheTimeout: ex.useCacheTimeout,\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    serverComponentsHmrCancellation: ex.serverComponentsHmrCancellation,\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    imgOptOperationCache: ex.imgOptOperationCache,\n    imgOptMaxInputPixels: ex.imgOptMaxInputPixels,\n    imgOptSequentialRead: ex.imgOptSequentialRead,\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    exposeTestingApiInProductionBuild: ex.exposeTestingApiInProductionBuild,\n    instantInsights: ex.instantInsights,\n    requestInsights: ex.requestInsights,\n\n    trustHostHeader: ex.trustHostHeader,\n    isExperimentalCompile: ex.isExperimentalCompile,\n  } satisfies Requiredish<NextConfigRuntime['experimental']>\n\n  const runtimeConfig: Requiredish<NextConfigRuntime> = {\n    deploymentId: config.experimental.runtimeServerDeploymentId\n      ? ''\n      : config.deploymentId,\n    supportsImmutableAssets: config.supportsImmutableAssets,\n\n    configFileName: undefined,\n    env: undefined,\n\n    distDir: config.distDir,\n    cacheComponents: config.cacheComponents,\n    partialPrefetching: config.partialPrefetching,\n    agentRules: config.agentRules,\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    staticPageGenerationTimeout: config.staticPageGenerationTimeout,\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","// 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 * `Sec-Fetch-Dest` values for subresource requests that can never render an\n * HTML response. Excludes destinations that can display HTML (`document`,\n * `iframe`, etc.) and `empty` (`fetch()`/XHR, including RSC requests).\n */\nconst NON_HTML_SEC_FETCH_DESTS = new Set([\n  'audio',\n  'audioworklet',\n  'font',\n  'image',\n  'json',\n  'manifest',\n  'paintworklet',\n  'report',\n  'script',\n  'serviceworker',\n  'sharedworker',\n  'style',\n  'track',\n  'video',\n  'webidentity',\n  'worker',\n  'xslt',\n])\n\nexport function isNonHtmlSecFetchDest(\n  value: string | string[] | null | undefined\n): boolean {\n  return typeof value === 'string' && NON_HTML_SEC_FETCH_DESTS.has(value)\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","// 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","/**\n * Removes the trailing slash for a given route or page path. Examples:\n *   - `/foo/bar/` -> `/foo/bar`\n *   - `/foo/bar` -> `/foo/bar`\n *\n * Uses charCodeAt (47 === '/') instead of regex to avoid the overhead of\n * compiling and executing a RegExp on every call (~3-5x faster).\n */\nexport function removeTrailingSlash(route: string) {\n  return route.charCodeAt(route.length - 1) === 47 && route.length > 1\n    ? route.slice(0, -1)\n    : route\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 { parseNormalizedAppRoute, 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 = parseNormalizedAppRoute(pagePath)\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 { 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} from '../../client/components/app-router-headers'\nimport { computeCacheBustingSearchParam } from '../../shared/lib/router/utils/cache-busting-search-param'\nimport type { AnyStream } from '../app-render/stream-ops'\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 webstreamToUint8Array(\n  stream: ReadableStream<Uint8Array>\n): Promise<Uint8Array> {\n  return concatUint8Arrays(await streamToChunks(stream))\n}\n\nfunction webToReadable(\n  stream: ReadableStream<Uint8Array> | import('node:stream').Readable\n): import('node:stream').Readable {\n  if (process.env.NEXT_RUNTIME === 'edge') {\n    throw new Error('webToReadable cannot be used in the edge runtime')\n  } else {\n    let Readable: typeof import('node:stream').Readable\n    if (process.env.TURBOPACK) {\n      Readable = (require('node:stream') as typeof import('node:stream'))\n        .Readable\n    } else if (\n      process.env.__NEXT_BUNDLER === 'Webpack' ||\n      process.env.__NEXT_BUNDLER === 'Rspack'\n    ) {\n      Readable = (\n        __non_webpack_require__('node:stream') as typeof import('node:stream')\n      ).Readable\n    } else {\n      Readable = (require('node:stream') as typeof import('node:stream'))\n        .Readable\n    }\n    if (stream instanceof Readable) {\n      return stream\n    }\n    return Readable.fromWeb(stream as import('stream/web').ReadableStream)\n  }\n}\n\nexport async function nodestreamToUint8Array(\n  stream: AnyStream\n): Promise<Uint8Array> {\n  const chunks: Buffer[] = []\n  for await (const chunk of webToReadable(stream)) {\n    chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)\n  }\n  return Buffer.concat(chunks)\n}\n\nexport async function streamToUint8Array(stream: AnyStream) {\n  if (process.env.NEXT_RUNTIME === 'edge') {\n    // Edge runtime always uses web streams\n    return webstreamToUint8Array(stream as ReadableStream<Uint8Array>)\n  } else {\n    let Readable: typeof import('node:stream').Readable\n    if (process.env.TURBOPACK) {\n      Readable = (require('node:stream') as typeof import('node:stream'))\n        .Readable\n    } else if (\n      process.env.__NEXT_BUNDLER === 'Webpack' ||\n      process.env.__NEXT_BUNDLER === 'Rspack'\n    ) {\n      Readable = (\n        __non_webpack_require__('node:stream') as typeof import('node:stream')\n      ).Readable\n    } else {\n      Readable = (require('node:stream') as typeof import('node:stream'))\n        .Readable\n    }\n\n    if (stream instanceof Readable) {\n      return nodestreamToUint8Array(stream)\n    }\n\n    return webstreamToUint8Array(stream)\n  }\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\nexport function 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\nexport function 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\nasync function createClientResumeScriptInsertionTransformStream(): Promise<\n  TransformStream<Uint8Array, Uint8Array>\n> {\n  const segmentPath = '/_full'\n  const cacheBustingHeader = await 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// Suffix after main body content - scripts before </body>,\n// but wait for the major chunks to be enqueued.\nexport function 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\nexport function 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\nexport const 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 */\nexport function createMoveSuffixStream(): TransformStream<\n  Uint8Array,\n  Uint8Array\n> {\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\nexport function 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\nexport function 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    await 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 { hexHash } from '../../hash'\n\nconst CACHE_BUSTING_SEARCH_PARAM_DIGEST_BYTES = 12\nconst textEncoder = new TextEncoder()\n\nfunction encodeCacheBustingSearchParam(bytes: Uint8Array): string {\n  let binary = ''\n  for (let i = 0; i < bytes.length; i++) {\n    binary += String.fromCharCode(bytes[i])\n  }\n\n  return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\nfunction normalizeCacheBustingInput(\n  value: string | string[] | undefined\n): string {\n  if (value === undefined) {\n    return '0'\n  }\n  return Array.isArray(value) ? value.join(',') : value\n}\n\nfunction createCacheBustingSearchParamInput(\n  prefetchHeader: '1' | '2' | '3' | '0' | undefined,\n  segmentPrefetchHeader: string | string[] | undefined,\n  stateTreeHeader: string | string[] | undefined,\n  nextUrlHeader: string | string[] | undefined\n): string | null {\n  if (\n    (prefetchHeader === undefined || prefetchHeader === '0') &&\n    segmentPrefetchHeader === undefined &&\n    stateTreeHeader === undefined &&\n    nextUrlHeader === undefined\n  ) {\n    return null\n  }\n\n  return [\n    prefetchHeader ?? '0',\n    normalizeCacheBustingInput(segmentPrefetchHeader),\n    normalizeCacheBustingInput(stateTreeHeader),\n    normalizeCacheBustingInput(nextUrlHeader),\n  ].join(',')\n}\n\nasync function computeCacheBustingSearchParamFromInput(\n  input: string\n): Promise<string> {\n  // Truncate SHA-256 to 96 bits to keep `_rsc` compact\n  const digest = await globalThis.crypto.subtle.digest(\n    'SHA-256',\n    textEncoder.encode(input)\n  )\n  return encodeCacheBustingSearchParam(\n    new Uint8Array(digest).subarray(0, CACHE_BUSTING_SEARCH_PARAM_DIGEST_BYTES)\n  )\n}\n\nexport async function computeCacheBustingSearchParam(\n  prefetchHeader: '1' | '2' | '3' | '0' | undefined,\n  segmentPrefetchHeader: string | string[] | undefined,\n  stateTreeHeader: string | string[] | undefined,\n  nextUrlHeader: string | string[] | undefined\n): Promise<string> {\n  const input = createCacheBustingSearchParamInput(\n    prefetchHeader,\n    segmentPrefetchHeader,\n    stateTreeHeader,\n    nextUrlHeader\n  )\n  if (input === null) {\n    return ''\n  }\n\n  return computeCacheBustingSearchParamFromInput(input)\n}\n\nexport function computeLegacyCacheBustingSearchParam(\n  prefetchHeader: '1' | '2' | '3' | '0' | undefined,\n  segmentPrefetchHeader: string | string[] | undefined,\n  stateTreeHeader: string | string[] | undefined,\n  nextUrlHeader: string | string[] | undefined\n): string {\n  const input = createCacheBustingSearchParamInput(\n    prefetchHeader,\n    segmentPrefetchHeader,\n    stateTreeHeader,\n    nextUrlHeader\n  )\n  if (input === null) {\n    return ''\n  }\n\n  return hexHash(input)\n}\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 * 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  isTracingEnabled: boolean\n): AppPageModule['__next_app__'] {\n  if (\n    !('performance' in globalThis) ||\n    (!process.env.NEXT_OTEL_PERFORMANCE_PREFIX && !isTracingEnabled)\n  ) {\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'\nimport type { Readable } from 'node:stream'\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\nconst HAS_CLIENT_COMPONENT_METRICS_ENABLED =\n  'performance' in globalThis && process.env.NEXT_OTEL_PERFORMANCE_PREFIX\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 (HAS_CLIENT_COMPONENT_METRICS_ENABLED) {\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\nexport async function pipeNodeReadableToNodeResponse(\n  readable: Readable,\n  res: ServerResponse,\n  waitUntilForEnd?: Promise<unknown>\n) {\n  try {\n    const { errored, destroyed } = res\n    if (errored || destroyed) return\n\n    let started = false\n\n    const finished = new DetachedPromise<void>()\n\n    res.once('close', () => {\n      readable.destroy()\n      finished.resolve()\n    })\n\n    readable.on('data', (chunk: Buffer) => {\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      const ok = res.write(chunk)\n\n      if ('flush' in res && typeof res.flush === 'function') {\n        res.flush()\n      }\n\n      if (!ok) {\n        readable.pause()\n        res.once('drain', () => {\n          readable.resume()\n        })\n      }\n    })\n\n    readable.on('end', async () => {\n      if (waitUntilForEnd) {\n        await waitUntilForEnd\n      }\n\n      if (!res.writableFinished) {\n        res.end()\n      }\n\n      finished.resolve()\n    })\n\n    readable.on('error', (err) => {\n      if (isAbortError(err)) {\n        finished.resolve()\n        return\n      }\n\n      res.destroy(err)\n      finished.resolve()\n    })\n\n    await finished.promise\n  } catch (err: any) {\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 { Readable } from 'stream'\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 {\n  isAbortError,\n  pipeToNodeResponse,\n  pipeNodeReadableToNodeResponse,\n} 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   * Whether the prerender left any UI pending in a Suspense boundary. This is\n   * reported directly by React's prerender result before Next.js resumes\n   * client-only boundaries.\n   */\n  hasPendingUi?: boolean\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  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  | Readable\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\nfunction isNodeReadable(value: unknown): value is Readable {\n  return (\n    value !== null &&\n    typeof value === 'object' &&\n    typeof (value as Record<string, unknown>).pipe === 'function' &&\n    typeof (value as Record<string, unknown>).on === 'function' &&\n    !(value instanceof ReadableStream)\n  )\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    if (isNodeReadable(this.response)) {\n      if (process.env.NEXT_RUNTIME === 'edge') {\n        throw new InvariantError(\n          'Node.js Readable cannot be converted to a web stream in the edge runtime'\n        )\n      } else {\n        let Readable: typeof import('node:stream').Readable\n        if (process.env.TURBOPACK) {\n          Readable = (require('node:stream') as typeof import('node:stream'))\n            .Readable\n        } else {\n          Readable = (\n            __non_webpack_require__(\n              'node:stream'\n            ) as typeof import('node:stream')\n          ).Readable\n        }\n        return Readable.toWeb(this.response) as ReadableStream<Uint8Array>\n      }\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 if (isNodeReadable(this.response)) {\n      if (process.env.NEXT_RUNTIME === 'edge') {\n        throw new InvariantError(\n          'Node.js Readable cannot be converted to a web stream in the edge runtime'\n        )\n      } else {\n        let Readable: typeof import('node:stream').Readable\n        if (process.env.TURBOPACK) {\n          Readable = (require('node:stream') as typeof import('node:stream'))\n            .Readable\n        } else {\n          Readable = (\n            __non_webpack_require__(\n              'node:stream'\n            ) as typeof import('node:stream')\n          ).Readable\n        }\n        return [Readable.toWeb(this.response) as ReadableStream<Uint8Array>]\n      }\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    if (\n      this.response !== null &&\n      typeof this.response !== 'string' &&\n      !Buffer.isBuffer(this.response) &&\n      !Array.isArray(this.response) &&\n      isNodeReadable(this.response)\n    ) {\n      await pipeNodeReadableToNodeResponse(this.response, res, this.waitUntil)\n      return\n    }\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","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, {\n      validate: false,\n      encode: encodeURIComponent,\n    })\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  const isDefaultValueMatch = (\n    candidateValue: string | undefined,\n    defaultValue: string\n  ) => {\n    if (!candidateValue) {\n      return false\n    }\n\n    let normalizedCandidateValue = normalizeRscURL(candidateValue)\n    for (let i = 0; i < 3; i++) {\n      if (normalizedCandidateValue === defaultValue) {\n        return true\n      }\n\n      const decodedCandidateValue = decodeQueryPathParameter(\n        normalizedCandidateValue\n      )\n\n      if (decodedCandidateValue === normalizedCandidateValue) {\n        break\n      }\n\n      normalizedCandidateValue = decodedCandidateValue\n    }\n\n    return false\n  }\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) => isDefaultValueMatch(val, defaultVal))\n            : isDefaultValueMatch(value, defaultVal)\n        })\n      : Array.isArray(value)\n        ? value.some((val) => isDefaultValueMatch(val, defaultValue as string))\n        : isDefaultValueMatch(value, 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_URL = 'next-url' as const\nexport const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const\n\n// Cookie for the Instant Navigation Testing API. Sent automatically with all\n// requests while a navigation lock is held; the server uses its presence to\n// render only the shell. Not exposed in production builds 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/e2e/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 { 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 type { AsyncLocalStorage } from 'async_hooks'\nimport type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'\nimport { createAsyncLocalStorage } from '../../app-render/async-local-storage'\n\nexport type RequestInsightsIdentity = {\n  requestId: string\n  kind?: RequestInsightKind\n  htmlRequestId: string\n  url: string | undefined\n}\n\n// This storage covers the part of BaseServer request handling that runs before\n// App Render creates workAsyncStorage. Once available, workStore remains the\n// primary identity source for locally recorded spans.\nconst REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY = Symbol.for(\n  '@next/request-insights-identity-storage'\n)\n\nfunction getRequestInsightsIdentityStorage(): AsyncLocalStorage<RequestInsightsIdentity> {\n  const globalStore = globalThis as typeof globalThis & {\n    [REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY]?: AsyncLocalStorage<RequestInsightsIdentity>\n  }\n\n  return (globalStore[REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY] ??=\n    createAsyncLocalStorage())\n}\n\nexport function runWithRequestInsightsIdentity<T>(\n  identity: RequestInsightsIdentity,\n  fn: () => T\n): T {\n  return getRequestInsightsIdentityStorage().run(identity, fn)\n}\n\nexport function getRequestInsightsIdentity():\n  | RequestInsightsIdentity\n  | undefined {\n  return getRequestInsightsIdentityStorage().getStore()\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 { getRequestMeta, type NextIncomingMessage } from '../request-meta'\n\nconst PATCHED_SET_HEADER = Symbol('next.patchSetHeaderWithCookieSupport')\n\ntype PatchableResponse = {\n  setHeader(key: string, value: string | string[]): PatchableResponse\n  headersSent?: boolean\n  [PATCHED_SET_HEADER]?: true\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  if (res[PATCHED_SET_HEADER]) {\n    return\n  }\n\n  const setHeader = res.setHeader.bind(res)\n\n  Object.defineProperty(res, PATCHED_SET_HEADER, {\n    value: true,\n  })\n\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","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  /**\n   * @param cookies\n   * @returns A fresh object identity backed by the original value\n   */\n  public static fresh(cookies: ReadonlyRequestCookies): ReadonlyRequestCookies {\n    return new Proxy(cookies, {\n      get(target, prop, receiver) {\n        return ReflectAdapter.get(target, prop, receiver)\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","import type { BaseNextRequest, BaseNextResponse } from '../base-http'\nimport type { IncomingHttpHeaders } from 'http'\nimport type { RequestStore } from '../app-render/work-unit-async-storage.external'\nimport type { RenderOpts } from '../app-render/types'\nimport type { NextRequest } from '../web/spec-extension/request'\nimport type { __ApiPreviewProps } from '../api-utils'\n\nimport {\n  FLIGHT_HEADERS,\n  NEXT_HTML_REQUEST_ID_HEADER,\n  NEXT_REQUEST_ID_HEADER,\n} from '../../client/components/app-router-headers'\nimport {\n  HeadersAdapter,\n  type ReadonlyHeaders,\n} from '../web/spec-extension/adapters/headers'\nimport {\n  MutableRequestCookiesAdapter,\n  RequestCookiesAdapter,\n  responseCookiesToRequestCookies,\n  createCookiesWithMutableAccessCheck,\n  type ReadonlyRequestCookies,\n} from '../web/spec-extension/adapters/request-cookies'\nimport { ResponseCookies, RequestCookies } from '../web/spec-extension/cookies'\nimport { DraftModeProvider } from './draft-mode-provider'\nimport { splitCookiesString } from '../web/utils'\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport type { ResumeDataCache } from '../resume-data-cache/resume-data-cache'\nimport type { Params } from '../request/params'\nimport type { ImplicitTags } from '../lib/implicit-tags'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\n\n/**\n * Internal request headers that userland `headers()` must not expose. They stay\n * on the shared request headers for framework plumbing.\n *\n * Every internal header that the client can send must be listed here. The\n * sealed userland view reads through to the shared request headers, so an\n * omission leaks the header to userland.\n *\n * The names are lowercased because `HeadersAdapter.seal` matches them in\n * lowercase.\n */\nconst HIDDEN_REQUEST_HEADERS: ReadonlySet<string> = new Set(\n  [\n    ...FLIGHT_HEADERS,\n    // The client sends these dev-only request IDs so the server can route debug\n    // information back to the originating request. Like the flight headers,\n    // they are internal plumbing.\n    NEXT_REQUEST_ID_HEADER,\n    NEXT_HTML_REQUEST_ID_HEADER,\n  ].map((header) => header.toLowerCase())\n)\n\nfunction getHeaders(headers: Headers | IncomingHttpHeaders): ReadonlyHeaders {\n  // The sealed userland view must not copy the request headers.\n  // `HeadersAdapter.from` returns a `Headers` instance unchanged, so the view\n  // reads through to `NextRequest.headers`. A copy detaches `headers()` from\n  // the writes that Proxy makes to `NextRequest.headers` afterwards.\n  //\n  // The view must also not delete the internal headers. Because\n  // `HeadersAdapter.from` does not copy, a delete removes them from the shared\n  // `req.headers`. The dev server reads the request-id headers from the raw\n  // request again, for example when it renders a redirect target after a server\n  // action. Their removal breaks the dev debug channel routing.\n  return HeadersAdapter.seal(\n    HeadersAdapter.from(headers),\n    HIDDEN_REQUEST_HEADERS\n  )\n}\n\nfunction getMutableCookies(\n  headers: Headers | IncomingHttpHeaders,\n  onUpdateCookies?: (cookies: string[]) => void\n): ResponseCookies {\n  const cookies = new RequestCookies(HeadersAdapter.from(headers))\n  return MutableRequestCookiesAdapter.wrap(cookies, onUpdateCookies)\n}\n\nexport type WrapperRenderOpts = Partial<Pick<RenderOpts, 'onUpdateCookies'>> & {\n  previewProps?: __ApiPreviewProps\n}\n\ntype RequestContext = RequestResponsePair & {\n  /**\n   * The URL of the request. This only specifies the pathname and the search\n   * part of the URL. This is only undefined when generating static paths (ie,\n   * there is no request in progress, nor do we know one).\n   */\n  url: {\n    /**\n     * The pathname of the requested URL.\n     */\n    pathname: string\n\n    /**\n     * The search part of the requested URL. If the request did not provide a\n     * search part, this will be an empty string.\n     */\n    search?: string\n  }\n  phase: RequestStore['phase']\n  renderOpts?: WrapperRenderOpts\n  isHmrRefresh?: boolean\n  serverComponentsHmrCache?: ServerComponentsHmrCache\n  implicitTags: ImplicitTags\n}\n\ntype RequestResponsePair =\n  | { req: BaseNextRequest; res: BaseNextResponse } // for an app page\n  | { req: NextRequest; res: undefined } // in an api route or middleware\n\n/**\n * The fields the request store actually reads from `req` / `res`. Decoupling\n * the store's construction from `IncomingMessage` / `BaseNextRequest` /\n * `NextRequest` lets it be built without a real `req`/`res` (e.g. by the `'use\n * cache'` deadlock probe worker, which only has a serializable snapshot of the\n * outer request).\n */\nexport type RequestStoreInputs = {\n  phase: RequestStore['phase']\n  /**\n   * Raw headers, either as a Web `Headers` instance or Node's\n   * `IncomingHttpHeaders`.\n   */\n  headers: Headers | IncomingHttpHeaders\n  /**\n   * Called whenever userspace mutates cookies (via `cookies().set(...)` etc.).\n   * Real renders wire this to `res.setHeader('Set-Cookie', cookies)`. Pass\n   * `undefined` for callers without a response (e.g. probe workers). Cookie\n   * writes during `'render'` are still gated by\n   * `MutableRequestCookiesAdapter`'s phase guard, so leaving this off doesn't\n   * silently accept writes that would otherwise be rejected.\n   */\n  onUpdateCookies: ((cookies: string[]) => void) | undefined\n  url: { pathname: string; search?: string }\n  rootParams: Params\n  implicitTags: ImplicitTags\n  resumeDataCache: ResumeDataCache | null\n  previewProps: WrapperRenderOpts['previewProps']\n  isHmrRefresh: boolean | undefined\n  serverComponentsHmrCache: ServerComponentsHmrCache | undefined\n  /**\n   * The hash of the most recent server component change (dev only). Included in\n   * `\"use cache\"` cache keys so that cached entries are revalidated after an\n   * edit, for every client, regardless of whether it runs the HMR client.\n   */\n  hmrRefreshHash: string | undefined\n  fallbackParams: OpaqueFallbackRouteParams | null | undefined\n}\n\n/**\n * If middleware set cookies in this request (indicated by `x-middleware-set-cookie`),\n * then merge those into the existing cookie object, so that when `cookies()` is accessed\n * it's able to read the newly set cookies.\n */\nfunction mergeMiddlewareCookies(\n  headers: Headers | IncomingHttpHeaders,\n  existingCookies: RequestCookies | ResponseCookies\n) {\n  // TODO: this only fires for `IncomingHttpHeaders`; `Headers` instances\n  // silently fall through (the `in` check and bracket access don't reach header\n  // values stored in internal slots). Confirm whether edge / Web `Headers`\n  // callers need this merge or already handle it elsewhere.\n  if (\n    'x-middleware-set-cookie' in headers &&\n    typeof headers['x-middleware-set-cookie'] === 'string'\n  ) {\n    const setCookieValue = headers['x-middleware-set-cookie']\n    const responseHeaders = new Headers()\n\n    for (const cookie of splitCookiesString(setCookieValue)) {\n      responseHeaders.append('set-cookie', cookie)\n    }\n\n    const responseCookies = new ResponseCookies(responseHeaders)\n\n    // Transfer cookies from ResponseCookies to RequestCookies\n    for (const cookie of responseCookies.getAll()) {\n      existingCookies.set(cookie)\n    }\n  }\n}\n\nexport function createRequestStoreForRender(\n  req: RequestContext['req'],\n  res: RequestContext['res'],\n  url: RequestContext['url'],\n  rootParams: Params,\n  implicitTags: RequestContext['implicitTags'],\n  onUpdateCookies: RenderOpts['onUpdateCookies'],\n  previewProps: WrapperRenderOpts['previewProps'],\n  isHmrRefresh: RequestContext['isHmrRefresh'],\n  serverComponentsHmrCache: RequestContext['serverComponentsHmrCache'],\n  resumeDataCache: ResumeDataCache | null,\n  fallbackParams: OpaqueFallbackRouteParams | null,\n  hmrRefreshHash: string | undefined\n): RequestStore {\n  return createRequestStore({\n    // Pages start in render phase by default\n    phase: 'render',\n    headers: req.headers,\n    onUpdateCookies:\n      onUpdateCookies ??\n      (res\n        ? (cookies: string[]) => {\n            res.setHeader('Set-Cookie', cookies)\n          }\n        : undefined),\n    url,\n    rootParams,\n    implicitTags,\n    resumeDataCache,\n    previewProps,\n    isHmrRefresh,\n    serverComponentsHmrCache,\n    hmrRefreshHash,\n    fallbackParams,\n  })\n}\n\nexport function createRequestStoreForAPI(\n  req: RequestContext['req'],\n  url: RequestContext['url'],\n  implicitTags: RequestContext['implicitTags'],\n  onUpdateCookies: RenderOpts['onUpdateCookies'],\n  previewProps: WrapperRenderOpts['previewProps'],\n  hmrRefreshHash: string | undefined\n): RequestStore {\n  return createRequestStore({\n    // API routes start in action phase by default\n    phase: 'action',\n    headers: req.headers,\n    onUpdateCookies,\n    url,\n    rootParams: {},\n    implicitTags,\n    resumeDataCache: null,\n    previewProps,\n    isHmrRefresh: false,\n    serverComponentsHmrCache: undefined,\n    hmrRefreshHash,\n    fallbackParams: null,\n  })\n}\n\n/**\n * Build a `RequestStore` from a serializable, request-shaped input. Used\n * directly by the existing `createRequestStoreForRender` /\n * `createRequestStoreForAPI` wrappers, and by side-process consumers like the\n * `'use cache'` deadlock probe worker that don't have a real `req`/`res` pair\n * but do have a forwarded snapshot of the outer request's headers etc.\n */\nexport function createRequestStore(inputs: RequestStoreInputs): RequestStore {\n  const {\n    phase,\n    headers,\n    onUpdateCookies,\n    url,\n    rootParams,\n    implicitTags,\n    resumeDataCache,\n    previewProps,\n    isHmrRefresh,\n    serverComponentsHmrCache,\n    hmrRefreshHash,\n    fallbackParams,\n  } = inputs\n\n  const cache: {\n    headers?: ReadonlyHeaders\n    cookies?: ReadonlyRequestCookies\n    mutableCookies?: ResponseCookies\n    userspaceMutableCookies?: ResponseCookies\n    draftMode?: DraftModeProvider\n  } = {}\n\n  return {\n    type: 'request',\n    phase,\n    implicitTags,\n    // Rather than just using the whole `url` here, we pull the parts we want\n    // to ensure we don't use parts of the URL that we shouldn't. This also\n    // lets us avoid requiring an empty string for `search` in the type.\n    url: { pathname: url.pathname, search: url.search ?? '' },\n    rootParams,\n    get headers() {\n      if (!cache.headers) {\n        // Seal the headers object that'll freeze out any methods that could\n        // mutate the underlying data.\n        cache.headers = getHeaders(headers)\n      }\n\n      return cache.headers\n    },\n    get cookies() {\n      if (!cache.cookies) {\n        // if middleware is setting cookie(s), then include those in\n        // the initial cached cookies so they can be read in render\n        const requestCookies = new RequestCookies(HeadersAdapter.from(headers))\n\n        mergeMiddlewareCookies(headers, requestCookies)\n\n        // Seal the cookies object that'll freeze out any methods that could\n        // mutate the underlying data.\n        cache.cookies = RequestCookiesAdapter.seal(requestCookies)\n      }\n\n      return cache.cookies\n    },\n    set cookies(value: ReadonlyRequestCookies) {\n      cache.cookies = value\n    },\n    get mutableCookies() {\n      if (!cache.mutableCookies) {\n        const mutableCookies = getMutableCookies(headers, onUpdateCookies)\n\n        mergeMiddlewareCookies(headers, mutableCookies)\n\n        cache.mutableCookies = mutableCookies\n      }\n      return cache.mutableCookies\n    },\n    get userspaceMutableCookies() {\n      if (!cache.userspaceMutableCookies) {\n        const userspaceMutableCookies =\n          createCookiesWithMutableAccessCheck(this)\n        cache.userspaceMutableCookies = userspaceMutableCookies\n      }\n      return cache.userspaceMutableCookies\n    },\n    get draftMode() {\n      if (!cache.draftMode) {\n        cache.draftMode = new DraftModeProvider(\n          previewProps,\n          headers,\n          this.cookies,\n          this.mutableCookies\n        )\n      }\n\n      return cache.draftMode\n    },\n    resumeDataCache: resumeDataCache ?? null,\n    isHmrRefresh,\n    serverComponentsHmrCache:\n      serverComponentsHmrCache ||\n      (globalThis as any).__serverComponentsHmrCache,\n    hmrRefreshHash,\n    fallbackParams,\n  }\n}\n\nexport function synchronizeMutableCookies(store: RequestStore) {\n  // TODO: does this need to update headers as well?\n  store.cookies = RequestCookiesAdapter.seal(\n    responseCookiesToRequestCookies(store.mutableCookies)\n  )\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 * The dev server (`next dev`) is the exception: to keep reloads fast it serves\n * stale entries until they expire, relying on the wrapper's\n * stale-while-revalidate path to warm a fresh entry in the background. See\n * `get` for where this branches.\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'\nimport { MIN_PRERENDERABLE_EXPIRE } from '../../use-cache/constants'\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, cacheKey) => entry.size + cacheKey.length\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\n      // A negative `expire` is an eviction sentinel: the tiered cache handler\n      // (dev-only) marks a front entry for deletion by overwriting it with a\n      // negative `expire`, since the cache-handler interface has no per-key\n      // delete. Treat it as missing here, independently of the minimum\n      // retention below (which would otherwise keep it alive). This is distinct\n      // from `revalidate = -1` below, which keeps serving the entry but forces\n      // a revalidation.\n      if (entry.expire < 0) {\n        debug?.('get', cacheKey, 'evicted')\n        return undefined\n      }\n\n      // The dev server serves stale entries until they expire (see the file\n      // overview); production drops them once past the revalidate time. In dev,\n      // an entry is retained for at least `MIN_PRERENDERABLE_EXPIRE` so that\n      // entries with a short `expire` (for example a `cacheLife({ expire: 0 })`\n      // client-only cache) still linger long enough that a reload hits the\n      // cache. That minimum is the same threshold below which the \"use cache\"\n      // wrapper treats an entry as dynamic, so it only extends the retention of\n      // entries that are dynamic anyway. It affects retention only; the\n      // returned entry keeps its real `expire`, so staging decisions are\n      // unchanged.\n      const maxAgeSeconds = process.env.__NEXT_DEV_SERVER\n        ? Math.max(entry.expire, MIN_PRERENDERABLE_EXPIRE)\n        : entry.revalidate\n\n      if (\n        performance.timeOrigin + performance.now() >\n        entry.timestamp + maxAgeSeconds * 1000\n      ) {\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        // In production an `expire: 0` entry is dynamic: the \"use cache\"\n        // wrapper regenerates it on every read instead of serving the stored\n        // copy, so persisting it would be a wasted write of a value that is\n        // never served back. Skip storing it so the next read is a plain miss.\n        // The dev server keeps it, because its minimum retention serves the\n        // previously cached value across reloads. The `finally` below still\n        // resolves the pending set.\n        if (!process.env.__NEXT_DEV_SERVER && entry.expire === 0) {\n          debug?.('set', cacheKey, 'skipped dynamic entry')\n          return\n        }\n\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'\nimport {\n  createTieredCacheHandler,\n  type CacheReadWriteHandler,\n} from './tiered-cache-handler'\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')\nconst privateHandlerSymbol = Symbol.for('@next/cache-handlers-private')\nconst builtInHandlersSymbol = Symbol.for('@next/cache-handlers-built-in')\nconst devFrontHandlersSymbol = Symbol.for('@next/cache-handlers-dev-fronts')\nconst devTieredHandlersSymbol = Symbol.for('@next/cache-handlers-dev-tiered')\nconst memoryCacheDisabledSymbol = Symbol.for(\n  '@next/cache-handlers-memory-disabled'\n)\n\n/**\n * The in-memory size used for the dev-only built-in handlers (the private\n * handler, the size-0 replacement, and the per-kind front handlers for custom\n * kinds). Mirrors the framework default so `cacheMaxMemorySize: 0` does not\n * disable caching in development.\n */\nconst DEV_MEMORY_CACHE_SIZE = 50 * 1024 * 1024\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  [builtInHandlersSymbol]?: Set<CacheHandler>\n  // DEV-only\n  [privateHandlerSymbol]?: CacheHandler\n  [devFrontHandlersSymbol]?: Map<string, CacheHandler>\n  [devTieredHandlersSymbol]?: Map<string, CacheReadWriteHandler>\n  [memoryCacheDisabledSymbol]?: boolean\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  const handlersMap = new Map<string, CacheHandler>()\n  reference[handlersMapSymbol] = handlersMap\n  const builtInHandlers = new Set<CacheHandler>()\n  reference[builtInHandlersSymbol] = builtInHandlers\n\n  // In development, `cacheMaxMemorySize: 0` would make the built-in default\n  // handler a no-op, so every reload would miss. Use a real in-memory size\n  // instead so dev stays fast; the \"use cache\" wrapper forces a dynamic cache\n  // life for this case so it still behaves close to \"no cache\" (serve stale,\n  // regenerate in the background). Production keeps the no-op handler.\n  const builtInSize =\n    process.env.__NEXT_DEV_SERVER && cacheMaxMemorySize === 0\n      ? DEV_MEMORY_CACHE_SIZE\n      : cacheMaxMemorySize\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(builtInSize)\n      builtInHandlers.add(fallback)\n    }\n\n    handlersMap.set('default', fallback)\n\n    if (reference[handlersSymbol].RemoteCache) {\n      debug?.('setting \"remote\" cache handler from symbol')\n      handlersMap.set('remote', reference[handlersSymbol].RemoteCache)\n    } else {\n      debug?.('setting \"remote\" cache handler from default')\n      handlersMap.set('remote', fallback)\n    }\n  } else {\n    const handler = createDefaultCacheHandler(builtInSize)\n    builtInHandlers.add(handler)\n\n    debug?.('setting \"default\" cache handler from default')\n    handlersMap.set('default', handler)\n    debug?.('setting \"remote\" cache handler from default')\n    handlersMap.set('remote', handler)\n  }\n\n  // Create a set of the cache handlers.\n  reference[handlersSetSymbol] = new Set(handlersMap.values())\n\n  // In development we add dedicated built-in in-memory handlers so that reloads\n  // are fast. These are always built-in handlers, never a user-configured one,\n  // and are gated on the dev server so production behaves exactly as\n  // configured.\n  if (process.env.__NEXT_DEV_SERVER) {\n    reference[memoryCacheDisabledSymbol] = cacheMaxMemorySize === 0\n\n    // Private caches are persisted here so reloads are fast. Private entries\n    // can hold data specific to the incoming request (for example, derived from\n    // its cookies or headers), so this is never the user-configured `default`\n    // alias. Sized so it still caches under `cacheMaxMemorySize: 0` (otherwise\n    // it would become the no-op stub and private reloads would miss).\n    reference[privateHandlerSymbol] = createDefaultCacheHandler(\n      DEV_MEMORY_CACHE_SIZE\n    )\n\n    // Built-in front handlers, one per custom kind, and the tiered handlers\n    // that place a front in front of a (possibly slow or remote) backing\n    // handler so cache hits resolve in a microtask, are both created per kind\n    // in `setCacheHandler`.\n    reference[devFrontHandlersSymbol] = new Map()\n    reference[devTieredHandlersSymbol] = new Map()\n  }\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 the dedicated in-memory cache handler that persists private caches in\n * development. Returns `undefined` outside the dev server, where private caches\n * must not be persisted. This is intentionally not part of the kind-keyed\n * handlers map so that it can never be replaced by a user-configured handler.\n */\nexport function getPrivateCacheHandler(): 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[privateHandlerSymbol]\n}\n\n/**\n * Whether the in-memory cache is disabled (`cacheMaxMemorySize: 0`). Dev-only\n * signal used to force a dynamic cache life so that the size-0 case still\n * serves stale and regenerates in the background. Always `false` in production.\n */\nexport function isMemoryCacheDisabled(): boolean {\n  return reference[memoryCacheDisabledSymbol] ?? false\n}\n\n/**\n * Whether `kind` is backed by a real user-configured handler rather than the\n * built-in in-memory default. Such a handler may be slow or remote, so in\n * development a built-in front handler is placed in front of it (see\n * `getDevTieredCacheHandler`) to keep cache hits microtask-fast. The presence\n * of a dev front handler is the signal, since front handlers are created\n * exactly for user-registered kinds. Always `false` in production.\n */\nexport function isCustomCacheHandler(kind: string): boolean {\n  if (!process.env.__NEXT_DEV_SERVER) {\n    return false\n  }\n\n  return reference[devFrontHandlersSymbol]?.has(kind) ?? false\n}\n\n/**\n * Whether `kind` resolves to one of the in-memory handlers that\n * `initializeCacheHandlers` constructs itself, rather than one supplied by the\n * platform through the `@next/cache-handlers` global or by `cacheHandlers`\n * config. Reads from a built-in handler are map lookups, so repeating one\n * within a request costs nothing; reads from a supplied handler may be a\n * network round trip. Unlike `isCustomCacheHandler`, this holds in production.\n *\n * Tracking the instances rather than the kinds is what keeps aliasing correct:\n * self-hosted, `remote` resolves to the same handler as `default` and so\n * reports as built-in, while a platform-supplied `remote` does not.\n */\nexport function isBuiltInCacheHandler(kind: string): boolean {\n  const handler = reference[handlersMapSymbol]?.get(kind)\n\n  return (\n    handler !== undefined &&\n    Boolean(reference[builtInHandlersSymbol]?.has(handler))\n  )\n}\n\n/**\n * Get the dev-only tiered cache handler for a custom `kind`: a fast built-in\n * in-memory front handler in front of the user-configured backing handler, so\n * cache hits resolve in a microtask. Returns `undefined` if there is none (a\n * built-in kind, or production).\n */\nexport function getDevTieredCacheHandler(\n  kind: string\n): CacheReadWriteHandler | undefined {\n  if (!process.env.__NEXT_DEV_SERVER) {\n    return undefined\n  }\n\n  return reference[devTieredHandlersSymbol]?.get(kind)\n}\n\n/**\n * Get an 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(): IterableIterator<CacheHandler> | undefined {\n  const handlersSet = reference[handlersSetSymbol]\n  if (!handlersSet) {\n    return undefined\n  }\n\n  if (process.env.__NEXT_DEV_SERVER) {\n    return iterateCacheHandlersWithDevBuiltIns(handlersSet)\n  }\n\n  return handlersSet.values()\n}\n\n/**\n * Yields the registered handlers plus the dev-only built-in handlers (the\n * private handler and the per-kind front handlers). The built-in handlers are\n * not part of the registered set, but tag operations must still reach them:\n * their `updateTags` writes the shared tags manifest that their `get` consults,\n * so `revalidateTag` can invalidate their entries.\n */\nfunction* iterateCacheHandlersWithDevBuiltIns(\n  handlersSet: Set<CacheHandler>\n): IterableIterator<CacheHandler> {\n  yield* handlersSet\n\n  const privateHandler = reference[privateHandlerSymbol]\n  if (privateHandler) {\n    yield privateHandler\n  }\n\n  const devFrontHandlers = reference[devFrontHandlersSymbol]\n  if (devFrontHandlers) {\n    yield* devFrontHandlers.values()\n  }\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  | IterableIterator<[string, CacheHandler]>\n  | undefined {\n  const handlersMap = reference[handlersMapSymbol]\n  if (!handlersMap) {\n    return undefined\n  }\n\n  if (process.env.__NEXT_DEV_SERVER) {\n    return iterateCacheHandlerEntriesWithDevBuiltIns(handlersMap)\n  }\n\n  return handlersMap.entries()\n}\n\n/**\n * Yields the registered entries plus the dev-only private handler under its\n * kind, so that per-kind tag operations (`refreshTags` / `getExpiration` for\n * implicit tags) apply to private entries. Custom-kind front handlers are\n * intentionally omitted: the backing handler (already in the map) is\n * authoritative for that kind's `getExpiration`, and a front entry is discarded\n * via that same value.\n */\nfunction* iterateCacheHandlerEntriesWithDevBuiltIns(\n  handlersMap: Map<string, CacheHandler>\n): IterableIterator<[string, CacheHandler]> {\n  yield* handlersMap.entries()\n\n  const privateHandler = reference[privateHandlerSymbol]\n  if (privateHandler) {\n    const privateEntry: [string, CacheHandler] = ['private', privateHandler]\n    yield privateEntry\n  }\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  // A user-configured handler may be slow or remote. In development, give it a\n  // dedicated built-in in-memory front handler so cache hits resolve in a\n  // microtask, and pair the two into a tiered handler the wrapper reads\n  // through. Both are created alongside registration so their lifecycle matches\n  // the backing handler's, and the front handler's presence is the signal that\n  // this kind is backed by a real handler (see `isCustomCacheHandler`). Being a\n  // built-in default handler, the front inherits the dev minimum retention, so\n  // a short-`expire` value still hits the front instead of falling through to\n  // the slow backing on every read.\n  if (process.env.__NEXT_DEV_SERVER) {\n    const frontHandler = createDefaultCacheHandler(DEV_MEMORY_CACHE_SIZE)\n    reference[devFrontHandlersSymbol]?.set(kind, frontHandler)\n    reference[devTieredHandlersSymbol]?.set(\n      kind,\n      createTieredCacheHandler(frontHandler, cacheHandler)\n    )\n  }\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 { InvariantError } from '../../shared/lib/invariant-error'\nimport type { ResolvedCacheLifeProfiles } from '../config-shared'\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 { isRSCRequestHeader } from '../lib/is-rsc-request'\nimport { setRequestMeta } from '../request-meta'\n\n// The proxy (middleware) does not support `'use cache'`, so this work store\n// never reaches the code that reads `cacheLife` (and `'use cache'` is\n// disallowed on the edge runtime anyway). This sentinel satisfies the\n// non-optional type while throwing if `default` is ever read, matching the\n// \"never read\" sentinels used for the proxy's other unused renderOpts fields\n// (`staticPageGenerationTimeout: 0`, `useCacheTimeout: 0`). It surfaces loudly\n// rather than silently serving a misleading profile.\nconst proxyCacheLifeProfiles: ResolvedCacheLifeProfiles = {\n  get default(): never {\n    throw new InvariantError(\n      'Proxy does not support `use cache`, so reading its `default` cacheLife profile is unexpected.'\n    )\n  },\n}\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  let deploymentId = process.env.NEXT_DEPLOYMENT_ID\n\n  const requestHeaders = fromNodeOutgoingHttpHeaders(params.request.headers)\n  const isNextDataRequest = requestHeaders.has('x-nextjs-data')\n  const isRSCRequest = isRSCRequestHeader(requestHeaders.get(RSC_HEADER))\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              // Edge route handlers can't use `\"use cache\"`, so there's no HMR\n              // refresh hash to thread through here.\n              undefined\n            )\n\n            const workStore = createWorkStore({\n              page,\n              renderOpts: {\n                cacheLifeProfiles: proxyCacheLifeProfiles,\n                // Proxy doesn't do static generation, so this value does not\n                // apply here. 0 is a sentinel: if something ever reads it,\n                // it'll surface loudly instead of silently using a misleading\n                // default.\n                staticPageGenerationTimeout: 0,\n                cacheComponents: false,\n                // Proxy doesn't run instant validation; the level value is\n                // irrelevant here.\n                // TODO: remove validationLevel and other global config from renderOpts\n                validationLevel: 'warning',\n                experimental: {\n                  isRoutePPREnabled: false,\n                  authInterrupts:\n                    !!params.request.nextConfig?.experimental?.authInterrupts,\n                  // Proxy doesn't fill Cache Components entries, so this value\n                  // is never read. 0 is a sentinel: if something ever reads it,\n                  // the cache fill will time out immediately and surface the\n                  // bug.\n                  useCacheTimeout: 0,\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              deploymentId: deploymentId ?? '',\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 { isRSCRequestHeader } from './lib/is-rsc-request'\nimport { isNonHtmlSecFetchDest } from './lib/is-non-html-sec-fetch-dest'\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 { getRouteRegex } from '../shared/lib/router/utils/route-regex'\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_HTML_REQUEST_ID_HEADER,\n  NEXT_REQUEST_ID_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  NEXT_HMR_REFRESH_HEADER,\n} from '../client/components/app-router-headers'\nimport { nanoid } from 'next/dist/compiled/nanoid'\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 { runWithRequestInsightsIdentity } from './lib/trace/request-insights-identity'\nimport { isRequestInsightsEnabled } from './lib/trace/span-store'\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 { 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'\nimport {\n  computeCacheBustingSearchParam,\n  computeLegacyCacheBustingSearchParam,\n} from '../shared/lib/router/utils/cache-busting-search-param'\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  /**\n   * The hash of the most recent server component change (dev only), used to\n   * revalidate `\"use cache\"` entries after an edit. Overridden by the dev\n   * server; returns `undefined` otherwise.\n   */\n  protected getServerComponentsHmrRefreshHash(): string | undefined {\n    return 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    if (\n      (dev || process.env.__NEXT_DEV_SERVER) &&\n      this.nextConfig.experimental.requestInsights\n    ) {\n      process.env.__NEXT_REQUEST_INSIGHTS = 'true'\n    }\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.supportsImmutableAssets || !this.deploymentId\n        ? ''\n        : `?dpl=${this.deploymentId}`\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      staticPageGenerationTimeout: this.nextConfig.staticPageGenerationTimeout,\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      partialPrefetching: this.nextConfig.partialPrefetching,\n      validationLevel:\n        this.nextConfig.experimental.instantInsights.validationLevel,\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        serverComponentsHmrCancellation:\n          this.nextConfig.experimental.serverComponentsHmrCancellation,\n        useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,\n        cachedNavigations:\n          this.nextConfig.experimental.cachedNavigations ?? false,\n        maxPostponedStateSizeBytes: parseMaxPostponedStateSize(\n          this.nextConfig.experimental.maxPostponedStateSize\n        ),\n        exposeTestingApi:\n          this.dev === true ||\n          this.nextConfig.experimental.exposeTestingApiInProductionBuild ===\n            true,\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 (isRSCRequestHeader(req.headers[RSC_HEADER])) {\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    const handleRequest = () =>\n      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    if (!isRequestInsightsEnabled()) {\n      return handleRequest()\n    }\n\n    const requestIdHeader = req.headers[NEXT_REQUEST_ID_HEADER]\n    const requestId =\n      typeof requestIdHeader === 'string' ? requestIdHeader : nanoid()\n    const htmlRequestIdHeader = req.headers[NEXT_HTML_REQUEST_ID_HEADER]\n\n    // The request root and route-matching spans start before App Render creates\n    // its workStore. Carry their identity in this outer scope; App Render copies\n    // it into the workStore so the complete timeline uses one request ID.\n    return runWithRequestInsightsIdentity(\n      {\n        requestId,\n        htmlRequestId:\n          typeof htmlRequestIdHeader === 'string'\n            ? htmlRequestIdHeader\n            : requestId,\n        url: req.url,\n      },\n      handleRequest\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            typeof getRequestMeta(req, 'postponed') === 'string'\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      // Attach the server components HMR refresh hash here, alongside the HMR\n      // cache, so it reaches every render that passes through this request\n      // handling, including internal renders (e.g. dev validation/warmup) that\n      // don't re-enter the top-level request handler. It's included in `\"use\n      // cache\"` keys so cached entries revalidate after an edit, for every\n      // client.\n      if (!getRequestMeta(req, 'hmrRefreshHash')) {\n        addRequestMeta(\n          req,\n          'hmrRefreshHash',\n          this.getServerComponentsHmrRefreshHash()\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      // Dev responses use `no-cache` so the browser can restore them from the\n      // HTTP cache on back/forward instead of reloading. HMR refresh responses\n      // opt out into `no-store` because a superseded refresh's fetch is aborted\n      // mid-write: under `no-cache` the response is stored, so the abort leaves\n      // the cache entry shared with the superseding refresh (same URL)\n      // half-written; Chromium then discards it and reissues the superseding\n      // refresh on a second connection as a duplicate request. `no-store` keeps\n      // that entry from being created.\n      if (this.dev) {\n        res.setHeader(\n          'Cache-Control',\n          req.headers[NEXT_HMR_REFRESH_HEADER] === '1'\n            ? 'no-store'\n            : 'no-cache, must-revalidate'\n        )\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', '2', and '3'. Strip all other values here.\n            prefetchHeaderValue === '1' ||\n            prefetchHeaderValue === '2' ||\n            prefetchHeaderValue === '3'\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 = await 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      let matchesHash = expectedHash === actualHash\n      if (!matchesHash && actualHash !== null) {\n        // We'll fallback to checking the legacy hash format to support clients that do not have a secure context\n        matchesHash =\n          computeLegacyCacheBustingSearchParam(\n            routerPrefetch,\n            segmentPrefetchRSCRequest,\n            headers[NEXT_ROUTER_STATE_TREE_HEADER],\n            headers[NEXT_URL]\n          ) === actualHash\n      }\n\n      if (!matchesHash) {\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        // We continue to accept the legacy short hash for clients that still\n        // generate the 5-character `_rsc` form.\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        // `req.url` may have had its basePath removed during normalization.\n        // Build the redirect from the original URL so it remains public-facing.\n        const url = new URL(\n          getRequestMeta(req, 'initURL') || req.url || '',\n          'http://localhost'\n        )\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      !isRSCRequestHeader(req.headers[RSC_HEADER]) &&\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    const hasPostponedState = typeof minimalPostponed === 'string'\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      // For subresource requests (e.g. images or fonts), return plain text\n      // 404 instead of rendering the not-found route.\n      if (\n        (req.method === 'GET' || req.method === 'HEAD') &&\n        isNonHtmlSecFetchDest(req.headers['sec-fetch-dest'])\n      ) {\n        res.setHeader(\n          'Cache-Control',\n          'private, no-cache, no-store, max-age=0, must-revalidate'\n        )\n        res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n        res.body('Not Found').send()\n        return null\n      }\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      !hasPostponedState &&\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          // Replicate, on demand, the per-URL fallback set a production build\n          // writes to the prerender manifest. Production matches the requested\n          // URL to the most-specific prerendered route and defers that route's\n          // `fallbackRouteParams` (so `generateStaticParams`-covered params\n          // resolve in the static shell and only the uncovered ones are\n          // deferred). The dev prerender manifest isn't populated for these\n          // ad-hoc routes, but `getStaticPaths` already computed every\n          // prerendered route here, so we do the same match: among the routes\n          // whose canonical regex matches this URL, pick the one with the\n          // fewest fallback params (the most-specific) and thread it via the\n          // `fallbackParams` meta. A fully-covered concrete route (e.g.\n          // `/blog/a`) has zero fallback params and is the most-specific match\n          // for its own URL, so it must be considered alongside the others: it\n          // wins over the base dynamic route (`/blog/[slug]`) and leaves its\n          // statically-known params out of the deferred set.\n          let perUrlFallbackRouteParams: NonNullable<\n            (typeof pathsResults.prerenderedRoutes)[number]['fallbackRouteParams']\n          > | null = null\n          for (const route of pathsResults.prerenderedRoutes) {\n            const fallbackRouteParams = route.fallbackRouteParams ?? []\n            if (!getRouteRegex(route.pathname).re.test(urlPathname)) {\n              continue\n            }\n            if (\n              perUrlFallbackRouteParams === null ||\n              fallbackRouteParams.length < perUrlFallbackRouteParams.length\n            ) {\n              perUrlFallbackRouteParams = fallbackRouteParams\n            }\n          }\n          if (\n            perUrlFallbackRouteParams &&\n            perUrlFallbackRouteParams.length > 0\n          ) {\n            addRequestMeta(\n              req,\n              'fallbackParams',\n              createOpaqueFallbackRouteParams(perUrlFallbackRouteParams)!\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","/**\n * Normalizes the raw RSC header value. Only the literal string \"1\" is treated\n * as a valid RSC request marker; malformed or repeated values are ignored.\n */\nexport function isRSCRequestHeader(\n  value: string | string[] | null | undefined\n): boolean {\n  return value === '1'\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","// 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 { 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 { parseNormalizedAppRoute } from '../../shared/lib/router/routes/app'\nimport { extractPathnameRouteParamSegmentsFromLoaderTree } from '../../build/static-paths/app/extract-pathname-route-param-segments-from-loader-tree'\nimport { getParamProperties } from '../../shared/lib/router/utils/get-segment-param'\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\nexport function buildDynamicSegmentPlaceholder(\n  param: Pick<FallbackRouteParam, 'paramName' | 'paramType'>\n): string {\n  const { repeat, optional } = getParamProperties(param.paramType)\n\n  if (optional) {\n    return `[[...${param.paramName}]]`\n  }\n\n  if (repeat) {\n    return `[...${param.paramName}]`\n  }\n\n  return `[${param.paramName}]`\n}\n\nexport function getPlaceholderFallbackRouteParams(\n  params: Record<string, undefined | string | string[]> | undefined,\n  fallbackRouteParams: readonly FallbackRouteParam[]\n): FallbackRouteParam[] {\n  return fallbackRouteParams.filter((param) => {\n    const placeholder = buildDynamicSegmentPlaceholder(param)\n    const value = params?.[param.paramName]\n\n    return (\n      value === placeholder ||\n      (Array.isArray(value) && value.length === 1 && value[0] === placeholder)\n    )\n  })\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 = parseNormalizedAppRoute(page)\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","// This regex will have fast negatives meaning valid identifiers may not pass\n// this test. However this is only used during static generation to provide hints\n// about why a page bailed out of some or all prerendering and we can use bracket notation\n// for example while `ಠ_ಠ` is a valid identifier it's ok to print `searchParams['ಠ_ಠ']`\n// even if this would have been fine too `searchParams.ಠ_ಠ`\nconst isDefinitelyAValidIdentifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/\n\nexport function describeStringPropertyAccess(target: string, prop: string) {\n  if (isDefinitelyAValidIdentifier.test(prop)) {\n    return `\\`${target}.${prop}\\``\n  }\n  return `\\`${target}[${JSON.stringify(prop)}]\\``\n}\n\nexport function describeHasCheckingStringProperty(\n  target: string,\n  prop: string\n) {\n  const stringifiedProp = JSON.stringify(prop)\n  return `\\`Reflect.has(${target}, ${stringifiedProp})\\`, \\`${stringifiedProp} in ${target}\\`, or similar`\n}\n\nexport const wellKnownProperties = new Set([\n  'hasOwnProperty',\n  'isPrototypeOf',\n  'propertyIsEnumerable',\n  'toString',\n  'valueOf',\n  'toLocaleString',\n\n  // Promise prototype\n  'then',\n  'catch',\n  'finally',\n\n  // React Promise extension\n  'status',\n  // 'value',\n  // 'error',\n\n  // React introspection\n  'displayName',\n  '_debugInfo',\n\n  // Common tested properties\n  'toJSON',\n  '$$typeof',\n  '__esModule',\n\n  // Tested by flight when checking for iterables\n  '@@iterator',\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 { mightBeServerReferenceId } from '../../shared/lib/server-reference-info'\nimport { wellKnownProperties } from '../../shared/lib/utils/reflect-utils'\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\nexport function getActionNotFoundError(actionId: string | null): Error {\n  return new Error(\n    `Failed to find Server Action${actionId ? ` \"${actionId}\"` : ''}. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`\n  )\n}\n\nexport function getInvalidServerReferenceIdError(id: string): Error {\n  // `id` is arbitrary client-provided input. Unlike the not-found case, it has\n  // not passed the length gate and can reach this error via a malformed server\n  // reference in an action payload, so it may be of any length and contain\n  // control characters. `JSON.stringify` escapes newlines and quotes so it\n  // can't forge log lines, and truncating overly long ids prevents log\n  // flooding. Ids at or below the cap are logged in full so that we only add an\n  // ellipsis to ids that are meaningfully longer than the truncated length.\n  const encoded = JSON.stringify(\n    id.length > MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH\n      ? id.slice(0, TRUNCATED_SERVER_REFERENCE_ID_LENGTH) + '…'\n      : id\n  )\n\n  return new Error(\n    `The Server Reference ID did not match the expected format. Received ${encoded}.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`\n  )\n}\n\n// Ids at or below the cap are logged in full. Longer ids are truncated to the\n// shorter length and marked with an ellipsis, so the cap leaves headroom over\n// the truncated length rather than ellipsizing ids that are barely too long.\nconst MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH = 100\nconst TRUNCATED_SERVER_REFERENCE_ID_LENGTH = 90\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 RegisteredClientReferenceManifest {\n  /**\n   * The page the manifest was registered with. Routes are normalized app paths,\n   * which is lossy (route groups, parallel slots and the trailing `/page` are\n   * stripped), so this is kept alongside for consumers that need to address the\n   * manifest on disk again rather than reversing the normalization.\n   */\n  readonly page: string\n  readonly clientReferenceManifest: DeepReadonly<ClientReferenceManifest>\n}\n\ninterface ManifestsSingleton {\n  readonly clientReferenceManifestsPerRoute: Map<\n    string,\n    RegisteredClientReferenceManifest\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    RegisteredClientReferenceManifest\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            )?.clientReferenceManifest\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                { page, clientReferenceManifest },\n              ] of clientReferenceManifestsPerRoute) {\n                if (route === workStore.route) {\n                  continue\n                }\n\n                const entry = clientReferenceManifest[prop][id]\n\n                if (entry !== undefined) {\n                  if (process.env.__NEXT_DEV_SERVER) {\n                    // The dev validation worker rebuilds this registry in its\n                    // own thread, seeded with only the route it validates, so\n                    // it has to be told which other manifests it needs.\n                    workStore.additionalClientReferenceManifestPages ??=\n                      new Set()\n                    workStore.additionalClientReferenceManifestPages.add(page)\n                  }\n\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 {\n              clientReferenceManifest,\n            } of clientReferenceManifestsPerRoute.values()) {\n              const entry = clientReferenceManifest[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 registeredManifest = clientReferenceManifestsPerRoute.get(\n              workStore.route\n            )\n\n            if (!registeredManifest) {\n              throw new InvariantError(\n                `The client reference manifest for route \"${workStore.route}\" does not exist.`\n              )\n            }\n\n            return registeredManifest.clientReferenceManifest[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(Object.create(null) as ServerModuleMap, {\n    get: (target, id: string | symbol, receiver) => {\n      // React's debug serialization can probe the module map like a plain object.\n      // These probes are not server reference lookups.\n      if (typeof id !== 'string') {\n        return Reflect.get(target, id, receiver)\n      }\n\n      if (wellKnownProperties.has(id)) {\n        return Reflect.get(target, id, receiver)\n      }\n\n      if (!mightBeServerReferenceId(id)) {\n        throw getInvalidServerReferenceIdError(id)\n      }\n\n      const workers =\n        getServerActionsManifest()[\n          process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'\n        ]?.[id]?.workers\n\n      if (!workers) {\n        throw getActionNotFoundError(id)\n      }\n\n      const workStore = workAsyncStorage.getStore()\n\n      let workerEntry: { moduleId: string | number; async: boolean } | 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        throw getActionNotFoundError(id)\n      }\n\n      const { moduleId, async } = workerEntry\n\n      return { id: moduleId, name: id, chunks: [], async }\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  const route = normalizeAppPath(page)\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(route, {\n      page,\n      clientReferenceManifest,\n    })\n\n    existingSingleton.serverActionsManifest = serverActionsManifest\n  } else {\n    const clientReferenceManifestsPerRoute = new Map<\n      string,\n      RegisteredClientReferenceManifest\n    >([[route, { 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\n/**\n * Loads the client reference manifest that the bundler emitted for an app page,\n * or returns undefined if there is none. Both the manifest file and the entry\n * inside it are addressed by the page with `%5F` decoded back to `_`, so\n * callers pass the page as-is and this resolves both.\n */\nexport async function loadClientReferenceManifestForPage(\n  distDir: string,\n  page: string,\n  attempts?: number\n): Promise<DeepReadonly<ClientReferenceManifest> | undefined> {\n  const entryName = page.replace(/%5F/g, '_')\n\n  const manifestPath = join(\n    /* turbopackIgnore: true */ distDir,\n    'server',\n    'app',\n    entryName + '_' + CLIENT_REFERENCE_MANIFEST + '.js'\n  )\n\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        ? loadClientReferenceManifestForPage(\n            distDir,\n            page,\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","export interface ServerReferenceInfo {\n  type: 'server-action' | 'use-cache'\n  usedArgs: [boolean, boolean, boolean, boolean, boolean, boolean]\n  hasRestArgs: boolean\n}\n\nexport const SERVER_REFERENCE_ID_LENGTH = 42\n\nexport function mightBeServerReferenceId(id: string): boolean {\n  return id.length === SERVER_REFERENCE_ID_LENGTH\n}\n\n/**\n * Extracts info about the server reference for the given server reference ID by\n * parsing the first byte of the hex-encoded ID.\n *\n * ```\n * Bit positions: [7]      [6] [5] [4] [3] [2] [1]  [0]\n * Bits:          typeBit  argMask                  restArgs\n * ```\n *\n * If the `typeBit` is `1` the server reference represents a `\"use cache\"`\n * function, otherwise a server action.\n *\n * The `argMask` encodes whether the function uses the argument at the\n * respective position.\n *\n * The `restArgs` bit indicates whether the function uses a rest parameter. It's\n * also set to 1 if the function has more than 6 args.\n *\n * @param id hex-encoded server reference ID\n */\nexport function extractInfoFromServerReferenceId(\n  id: string\n): ServerReferenceInfo {\n  const infoByte = parseInt(id.slice(0, 2), 16)\n  const typeBit = (infoByte >> 7) & 0x1\n  const argMask = (infoByte >> 1) & 0x3f\n  const restArgs = infoByte & 0x1\n  const usedArgs = Array(6)\n\n  for (let index = 0; index < 6; index++) {\n    const bitPosition = 5 - index\n    const bit = (argMask >> bitPosition) & 0x1\n    usedArgs[index] = bit === 1\n  }\n\n  return {\n    type: typeBit === 1 ? 'use-cache' : 'server-action',\n    usedArgs: usedArgs as [\n      boolean,\n      boolean,\n      boolean,\n      boolean,\n      boolean,\n      boolean,\n    ],\n    hasRestArgs: restArgs === 1,\n  }\n}\n\n/**\n * Creates a sparse array containing only the used arguments based on the\n * provided action info.\n */\nexport function omitUnusedArgs(\n  args: unknown[],\n  info: ServerReferenceInfo\n): unknown[] {\n  const filteredArgs = new Array(args.length)\n  let length = 0\n\n  for (let index = 0; index < args.length; index++) {\n    if (\n      (index < 6 && info.usedArgs[index]) ||\n      // This assumes that the server reference info byte has the restArgs bit\n      // set to 1 if there are more than 6 args.\n      (index >= 6 && info.hasRestArgs)\n    ) {\n      filteredArgs[index] = args[index]\n      length = index + 1\n    }\n  }\n\n  // Trim trailing unused args from the array.\n  filteredArgs.length = length\n\n  return filteredArgs\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    if (this.minimal_mode && response?.cacheControl) {\n      const cacheKey = createCacheKey(key, invocationID)\n      this.cache.set(cacheKey, {\n        entry: response,\n        expiresAt: Date.now() + this.ttl,\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      // `isStale === -1` signals that the entry is past its `expire` (either\n      // via an expired tag or, with `cacheLife({ expire })`, past the route's\n      // expire time in the prerender manifest). In that case we must NOT\n      // early-resolve with the stale value — instead we fall through to a\n      // blocking revalidation so the response returned to the user is fresh.\n      if (\n        previousIncrementalCacheEntry &&\n        !context.isOnDemandRevalidate &&\n        previousIncrementalCacheEntry.isStale !== -1\n      ) {\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      //\n      // A prefetch request that missed must run its own response generator\n      // rather than joining an in-flight revalidation through the batcher. A\n      // background revalidation may be regenerating the concrete (non-fallback)\n      // entry for this route — e.g. an ISR fallback-shell upgrade scheduled by\n      // an earlier prefetch sub-request. Joining it would serve that concrete\n      // result to the prefetch instead of the fallback shell, and which segment\n      // wins would depend purely on request timing. Running the generator\n      // directly lets every prefetch segment take the same fallback-shell path,\n      // independent of any concurrent background upgrade.\n      const incrementalResponseCacheEntry =\n        context.isPrefetch && previousIncrementalCacheEntry === null\n          ? await this.handleRevalidate(\n              key,\n              context.incrementalCache,\n              context.isRoutePPREnabled,\n              context.isFallback,\n              responseGenerator,\n              previousIncrementalCacheEntry,\n              resolved\n            )\n          : await this.revalidate(\n              key,\n              context.incrementalCache,\n              context.isRoutePPREnabled,\n              context.isFallback,\n              responseGenerator,\n              previousIncrementalCacheEntry,\n              resolved\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  ) {\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      )\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  ) {\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. The minimal mode LRU write is handled in get() so that\n      // every caller — including batched invocations — populates the cache.\n      if (incrementalResponseCacheEntry.cacheControl && !this.minimal_mode) {\n        await incrementalCache.set(key, incrementalResponseCacheEntry.value, {\n          cacheControl: incrementalResponseCacheEntry.cacheControl,\n          isRoutePPREnabled,\n          isFallback,\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(key: string, kind: IncrementalCacheKind): string {\n    let rootDir: 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        rootDir = path.join(this.serverDistDir, '..', 'cache', 'fetch-cache')\n        break\n      case IncrementalCacheKind.PAGES:\n        rootDir = path.join(this.serverDistDir, 'pages')\n        break\n      case IncrementalCacheKind.IMAGE:\n      case IncrementalCacheKind.APP_PAGE:\n      case IncrementalCacheKind.APP_ROUTE:\n        rootDir = path.join(this.serverDistDir, 'app')\n        break\n      default:\n        throw new Error(`Unexpected file path kind: ${kind}`)\n    }\n\n    const filePath = path.join(rootDir, key)\n    if (!(filePath.startsWith(rootDir + path.sep) || filePath === rootDir)) {\n      throw new Error(`Invalid file path: ${filePath}`)\n    }\n\n    return filePath\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  getResumeDataCache,\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\nfunction toHex(buffer: ArrayBufferView | ArrayBuffer): string {\n  // Hex-encode body bytes losslessly: decoding as UTF-8 would collapse\n  // distinct bytes (0xff/0xfe to U+FFFD) and collide; Buffer isn't on edge.\n  const bytes = isArrayBuffer(buffer)\n    ? new Uint8Array(buffer)\n    : new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)\n  let hex = ''\n  for (const byte of bytes) {\n    hex += byte.toString(16).padStart(2, '0')\n  }\n  return hex\n}\n\ntype Body = NonNullable<RequestInit['body'] | Request['body']>\n\n// Duck typing to support Edge runtime\n// TODO: Switch to instanceof checks once Edge runtime is removed.\n\nfunction isArrayBuffer(\n  buffer: ArrayBuffer | ArrayBufferView\n): buffer is ArrayBuffer {\n  return !('buffer' in buffer)\n}\n\nfunction isBodyByteSequence(\n  body: Body\n): body is ArrayBufferView<ArrayBuffer> | ArrayBuffer {\n  return typeof body === 'object' && 'byteLength' in body\n}\n\nfunction isBodyReadableStream(body: Body): body is ReadableStream {\n  return typeof (body as any).getReader === 'function'\n}\n\nfunction isBodyFormDataOrURLSearchParams(\n  body: Body\n): body is FormData | URLSearchParams {\n  return typeof (body as any).keys === 'function'\n}\n\nfunction isBodyBlob(body: Body): body is Blob {\n  return typeof (body as any).arrayBuffer === 'function'\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\nasync function hashString(cacheString: string): Promise<string> {\n  if (process.env.NEXT_RUNTIME === 'edge') {\n    const encoder = new TextEncoder()\n    const buffer = encoder.encode(cacheString)\n    return toHex(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// this should be bumped anytime a fix is made to cache entries\n// that should bust the cache\nconst MAIN_KEY_PREFIX = 'v4'\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  async generateSimpleCacheKey(input: string): Promise<string> {\n    const cacheString = JSON.stringify([\n      MAIN_KEY_PREFIX,\n      this.fetchCacheKeyPrefix || '',\n      input,\n    ])\n\n    return hashString(cacheString)\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    const bodyChunks: string[] = []\n\n    const encoder = new TextEncoder()\n\n    // Will be set implementing https://fetch.spec.whatwg.org/#concept-bodyinit-extract\n    let bodyType: string | null = null\n    const body = init.body\n    if (body) {\n      if (isBodyByteSequence(body)) {\n        bodyChunks.push(`bytes:${toHex(body)}`)\n        ;(init as any)._ogBody = body\n      } else if (isBodyReadableStream(body)) {\n        const readableBody = body\n\n        const chunks: Uint8Array[] = []\n\n        try {\n          await readableBody.pipeTo(\n            new WritableStream({\n              write(chunk) {\n                chunks.push(\n                  typeof chunk === 'string' ? encoder.encode(chunk) : chunk\n                )\n              },\n            })\n          )\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          bodyChunks.push(`bytes:${toHex(arrayBuffer)}`)\n          ;(init as any)._ogBody = arrayBuffer\n        } catch (err) {\n          console.error('Problem reading body', err)\n        }\n      } else if (isBodyFormDataOrURLSearchParams(body)) {\n        bodyType =\n          String(body) === '[object FormData]'\n            ? // We don't need a boundary because we're not actually using this for a Content-Type header\n              'multipart/form-data; boundary='\n            : 'application/x-www-form-urlencoded;charset=UTF-8'\n        const iterable = body\n        ;(init as any)._ogBody = body\n        // Separate, tagged chunks so `[\"a\",\"b\"]` can't collide with `[\"a,b\"]`.\n        for (const [key, val] of iterable.entries()) {\n          bodyChunks.push(`key:${key}`)\n          if (typeof val === 'string') {\n            bodyChunks.push(`str:${val}`)\n          } else {\n            bodyChunks.push(\n              'file',\n              val.name,\n              val.type,\n              `bytes:${toHex(await val.arrayBuffer())}`\n            )\n          }\n        }\n        // handle blob body\n      } else if (isBodyBlob(body)) {\n        const blob = body\n        const arrayBuffer = await blob.arrayBuffer()\n        bodyChunks.push('blob', blob.type, `bytes:${toHex(arrayBuffer)}`)\n        ;(init as any)._ogBody = new Blob([arrayBuffer], { type: blob.type })\n        bodyType = blob.type\n      } else if (typeof body === 'string') {\n        bodyChunks.push(`str:${body}`)\n        ;(init as any)._ogBody = body\n        bodyType = 'text/plain;charset=UTF-8'\n      } else {\n        body satisfies never\n        throw new Error(`Unsupported body type: ${typeof body}`)\n      }\n    }\n\n    const headers =\n      typeof (init.headers || {}).keys === 'function'\n        ? Object.fromEntries(init.headers as Headers)\n        : Object.assign({} as Record<string, string>, 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      // Ensures default Content-Type is part of the cache key\n      // TODO: Only necessary when headers are not used from the Request instance\n      bodyType,\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    return hashString(cacheString)\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        ? getResumeDataCache(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 resumeDataCache = getResumeDataCache(workUnitStore)\n        if (resumeDataCache?.mutable) {\n          if (IncrementalCache.debug) {\n            console.log('IncrementalCache: rdc:set', cacheKey)\n          }\n\n          resumeDataCache.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      // If the route's `expire` time has passed, force a blocking revalidation\n      // by signalling `isStale = -1`. The response cache treats `-1` as \"skip\n      // the early SWR resolve\" and awaits a fresh render before the user sees a\n      // response.\n      const expireAfter =\n        typeof cacheControl?.expire === 'number'\n          ? cacheControl.expire * 1000 + lastModified\n          : undefined\n\n      if (expireAfter !== undefined && expireAfter < now) {\n        isStale = -1\n      } else {\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\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 resumeDataCache = workUnitStore\n        ? getResumeDataCache(workUnitStore)\n        : null\n      if (resumeDataCache?.mutable) {\n        if (IncrementalCache.debug) {\n          console.log('IncrementalCache: rdc:set', pathname)\n        }\n\n        resumeDataCache.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  maximumResponseBody?: number\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  private maximumResponseBody?: number\n  private totalSize: number = 0\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    this.maximumResponseBody = res.maximumResponseBody\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\n    const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n\n    if (this.maximumResponseBody !== undefined) {\n      this.totalSize += buffer.byteLength\n      if (this.totalSize > this.maximumResponseBody) {\n        const error = new Error(\n          `Response body exceeded maximum size of ${this.maximumResponseBody} bytes`\n        ) as NodeJS.ErrnoException\n        error.code = 'ERR_MAX_BODY_SIZE_EXCEEDED'\n        this.destroy(error)\n        return true\n      }\n    }\n\n    this.buffers.push(buffer)\n    return true\n  }\n\n  public end() {\n    if (this.destroyed) {\n      return this\n    }\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: (error?: Error | null) => 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    //\n    // If the stream was destroyed due to an error, we should propagate it\n    if (this.destroyed && this.errored) {\n      callback(this.errored)\n    } else {\n      callback()\n    }\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  maximumResponseBody?: number\n}\n\nexport function createRequestResponseMocks({\n  url,\n  headers = {},\n  method = 'GET',\n  bodyReadable,\n  resWriter,\n  socket = null,\n  maximumResponseBody,\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, maximumResponseBody }),\n  }\n}\n","import path from 'path'\nimport { pathToFileURL, fileURLToPath } from 'url'\n\n/**\n * Converts a cache handler path to a filesystem path.\n * ESM's import.meta.resolve() returns file:// URLs which break when concatenated\n * with .next/ or used with path.join/path.relative.\n * @param filePath - Absolute path, relative path, or file:// URL (e.g. from import.meta.resolve)\n * @returns A filesystem path suitable for path operations\n */\nexport function resolveCacheHandlerPathToFilesystem(filePath: string): string {\n  if (filePath.startsWith('file://')) {\n    return fileURLToPath(filePath)\n  }\n  return filePath\n}\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, or file:// URL (e.g. from import.meta.resolve)\n */\nexport const formatDynamicImportPath = (dir: string, filePath: string) => {\n  const resolvedFilePath = resolveCacheHandlerPathToFilesystem(filePath)\n\n  const absoluteFilePath = path.isAbsolute(resolvedFilePath)\n    ? resolvedFilePath\n    : path.join(dir, resolvedFilePath)\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'\nimport type { AnyStream } from '../../app-render/stream-ops'\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: AnyStream },\n      htmlRequestId: string,\n      requestId: string\n    ) => void\n    setCacheStatus?: (status: ServerCacheStatus, htmlRequestId: string) => void\n    sendErrorsToBrowser?: (\n      errorsRscStream: AnyStream,\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'\nimport * as Log from '../../build/output/log'\n\nlet _global = globalThis as typeof globalThis & {\n  nextInitializedProcessErrorHandlers?: boolean\n  [UNHANDLED_REJECTION_LISTENER_KEY]?: NodeJS.UnhandledRejectionListener\n}\n\n// The listener function is shared via globalThis so that multiple copies of\n// this module (e.g. in the pre-compiled server bundle and in a route module\n// bundle) still register and detect a single listener instance.\nconst UNHANDLED_REJECTION_LISTENER_KEY = Symbol.for(\n  'next.unhandledRejectionListener'\n)\n\nfunction unhandledRejectionListener(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  Log.error('unhandledRejection:', reason)\n}\n\n/**\n * Checks if the Next.js unhandled rejection listener is currently attached.\n * This queries the actual process listeners instead of relying on a module\n * global, so it stays accurate even if the listener was removed externally,\n * e.g. via `process.removeAllListeners('unhandledRejection')`.\n */\nexport function isUnhandledRejectionListenerRegistered(): boolean {\n  const listener = _global[UNHANDLED_REJECTION_LISTENER_KEY]\n\n  return (\n    listener !== undefined &&\n    process.listeners('unhandledRejection').includes(listener)\n  )\n}\n\n/**\n * Registers the Next.js unhandled rejection listener, which logs unhandled\n * rejections (except React postpones) and prevents them from crashing the\n * process. Safe to call unconditionally: if the listener is already attached,\n * this is a no-op, so it never registers a duplicate.\n */\nexport function registerUnhandledRejectionListener(): void {\n  if (isUnhandledRejectionListenerRegistered()) {\n    return\n  }\n\n  const listener = (_global[UNHANDLED_REJECTION_LISTENER_KEY] ??=\n    unhandledRejectionListener)\n\n  process.on('unhandledRejection', listener)\n}\n\nexport function installProcessErrorHandlers(\n  shouldRemoveUncaughtErrorAndRejectionListeners: boolean\n) {\n  if (!_global.nextInitializedProcessErrorHandlers) {\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    process.on('rejectionHandled', () => {\n      // TODO: See note in the unhandledRejection listener above. In the\n      // future, we may use the \"rejectionHandled\" event to de-queue an error\n      // from 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\n  // Register the listener unconditionally, and not only during the guarded\n  // initialization above: a previous registration may have been undone by the\n  // `removeAllListeners` call of a later `installProcessErrorHandlers` call\n  // (or by external code), and registering is a no-op if the listener is\n  // still attached.\n  registerUnhandledRejectionListener()\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    if (\n      (isDev || process.env.__NEXT_DEV_SERVER) &&\n      this.nextConfig.experimental.requestInsights\n    ) {\n      process.env.__NEXT_REQUEST_INSIGHTS = 'true'\n    } else {\n      delete process.env.__NEXT_REQUEST_INSIGHTS\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      // supportsImmutableAssets only works with Turbopack, and `isExperimentalCompile` isn't supported\n      // with that anyway, so we can assign just use 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          requestMeta?: RequestMeta\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      requestMeta: {\n        ...getRequestMeta(req.originalRequest),\n        query,\n        params: match.params,\n      },\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: this.nextConfig.supportsImmutableAssets\n              ? ''\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: this.nextConfig.supportsImmutableAssets\n              ? undefined\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            this.nextConfig.images.maximumResponseBody,\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(\n        params.request.headers,\n        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        // Node.js middleware runs in-process, inside the active\n        // `handleRequest` span. Detach that span so the middleware span\n        // becomes a sibling root (or parents to an incoming traceparent),\n        // matching edge middleware which runs in a detached sandbox.\n        result = await getTracer().runWithDetachedContext(() =>\n          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        )\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: this.nextConfig.supportsImmutableAssets\n          ? ''\n          : 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: this.nextConfig.supportsImmutableAssets\n        ? ''\n        : 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 { PassThrough, Readable } 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      // `p2` becomes the buffered body that replaces the original request stream\n      // in `finalize()` via `replaceRequestBody`. Since it is only ever fed via\n      // `.push()`, it must be a plain Readable: a Duplex (PassThrough) would copy\n      // its writable-side internals (`_writableState`, `write`, `end`, ...) onto the\n      // IncomingMessage, making the request look like an unfinished writable stream\n      // and hanging Node stream APIs such as `Readable.toWeb()`.\n      const p2 = new Readable({ read() {} })\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","e","process","console","r","t","n","Array","s","l","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","getRequestInsightKind","insight","kind","getRequestInsightKey","requestId","REQUEST_INSIGHTS_STORE_KEY","for","SAFE_SPAN_ATTRIBUTE_KEYS","Set","SENSITIVE_PARAM_NAME_RE","InMemoryRequestInsightsStore","recordSpan","span","links","events","attributes","getOrCreateRequest","requestInsightKind","htmlRequestId","route","url","startTime","timestamp","spanStartTime","sanitizeUrl","updateTiming","durationMs","status","spans","push","name","traceId","spanId","parentSpanId","sanitizeSpanAttributes","map","link","event","fetch","getStringAttribute","method","statusCode","getNumberAttribute","cacheStatus","cacheReason","index","recordFetchForInsight","notify","recordFetch","identity","fetchStartTime","performance","timeOrigin","now","sanitizeFetchInsight","getSnapshot","requests","requestOrder","insightKey","get","filter","request","undefined","subscribe","listener","listeners","add","delete","clear","requestTimings","length","isRequestSpan","requestTiming","set","endTime","requestEndTime","min","max","fetches","trim","some","existingFetch","shift","recordRequestInsightSpan","getRequestInsightsStore","recordRequestInsightFetch","getRequestInsightsSnapshot","subscribeRequestInsights","clearRequestInsightsForTest","globalStore","globalThis","sanitized","key","value","entries","has","keys","isRelativeUrl","startsWith","username","password","from","searchParams","pathname","search","hash","href","isRequestInsightsEnabled","AsyncLocalStorage","require","WebSocket","defineProperty","configurable","writable","global","crypto","webcrypto","enumerable","module","c","webCrypto","cachedPattern","cachedRegex","inspectSymbol","errorConstructor","RenderStage","originalConstructor","originalNow","BaseServerSpan","LoadComponentsSpan","NextNodeServerSpan","RedirectStatusCode","RouteKind","CachedRouteKind","IncrementalCacheKind","LRUNode","constructor","data","size","prev","next","SentinelNode","LRUCache","maxSize","calculateSize","onEvict","cache","totalSize","head","tail","addToHead","node","removeNode","moveToHead","removeTail","lastNode","warn","existing","newNode","iterator","current","remove","currentSize","findSourceMap","sourceMapPayloads","WeakMap","findSourceMapPayload","sourceURL","sourceMap","payload","invalidSourceMap","isAnonymousFrameLikelyJSNative","methodName","regexNextStatic","env","stdout","enabled","NO_COLOR","FORCE_COLOR","isTTY","CI","TERM","replaceClose","str","close","start","substring","end","nextIndex","indexOf","formatter","open","input","string","bold","dim","italic","red","green","yellow","magenta","white","BUNDLER_FIND_SOURCE_MAP","CODE_FRAME_RENDERER","sourceMapConsumers","frameToString","line1","column1","fileLocation","sourceLocation","canParse","path","cwd","computeErrorName","shouldIgnoreListGeneratedFrame","file","createUnsourcemappedFrame","frame","ignored","code","prepareStackTrace","structuredStackTrace","toString","prototype","depth","inspectOptions","inspect","workUnitAsyncStorage","newError","sourceMapError","options","cause","AggregateError","errors","parseAndSourceMap","showIgnoreListed","__NEXT_SHOW_IGNORE_LISTED","unparsedStack","errorName","idx","lastIndexOf","slice","unsourcemappedStack","parseStack","distDir","__NEXT_DIST_DIR","line","frames","parse","res","exec","effectiveDistDir","concat","pop","lineNumber","column","sourceMapCache","sourceMappedFrames","sourceFrame","sourcemappedFrame","getSourcemappedFrameIfPossible","applicableSourceMap","sourceMapConsumer","sourceMapPayload","codeFrame","sourceMapCacheEntry","maybeSourceMapPayload","devirtualizeReactServerURL","envIdx","suffixIdx","decodeURI","sourceMapURL","getOrCreateSourceMapConsumer","consumersByURL","consumer","SyncSourceMapConsumer","sourcePosition","originalPositionFor","findApplicableSourceMapPayload","line0","column0","sections","left","right","result","middle","section","offset","ignoreList","sources","source","sourceIndex","originalFrame","getOriginalCodeFrame","colors","codeFrameRenderer","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","expression","errorWithStack","prerenderStore","dynamicTracking","syncDynamicErrorWithStack","queueMicrotask","syncDynamicErrorWithStackPostMicrotask","digest","controller","abort","dynamicAccesses","isDebugDynamicAccesses","React","isDynamicPostponeReason","reason","SYNC_IO_DOCS","time","random","SYNC_IO_CLIENT_DOCS","SYNC_IO_RUNTIME_DOCS","elapsedTimeBullet","type","createSyncIOErrorImpl","docsUrl","io","workUnitStore","workStore","workAsyncStorage","prerenderSignal","signal","aborted","stageController","stagedRendering","shouldTrackSyncInterrupt","syncIOError","currentStage","syncInterruptCurrentStageWithReason","_random","bind","properties","construct","newConstructor","getOwnPropertyDescriptors","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","originalResolveFilename","requestMap","parent","isMain","hookResolved","basename","SP","every","DecodeError","NormalizeError","PageNotFoundError","page","MissingStaticPage","PARAM_SEPARATOR","hasAdjacentParameterIssues","normalizeAdjacentParameters","normalized","stripNormalizedSeparators","safePathToRegexp","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","hidden","methods","isHidden","sealed","createHidingMethods","getSetCookie","values","forEach","callbackfn","thisArg","fresh","merge","append","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","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","byteLength","pipeToNodeResponse","searchParamsToUrlQuery","query","stringifyUrlQueryParam","parseUrl","parseRelativeUrl","base","parseQuery","globalBase","resolvedBase","origin","protocol","host","auth","hostname","port","slashes","parsedURL","prefixes","wait","ready","info","trace","LOGGING_METHOD","log","prefixedLog","prefixType","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","instrumentationClientInject","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","allowedDevOrigins","enablePrerenderSourceMaps","cacheComponents","cacheLife","default","stale","seconds","minutes","hours","days","weeks","cacheHandlers","NEXT_DEFAULT_CACHE_HANDLER_PATH","remote","NEXT_REMOTE_CACHE_HANDLER_PATH","static","NEXT_STATIC_CACHE_HANDLER_PATH","adapterPath","NEXT_ADAPTER_PATH","experimental","appNewScrollHandler","coldCacheBadge","devValidationWorker","useSkewCookie","cssChunking","multiZoneDraftMode","appNavFailHandling","prerenderEarlyExit","serverMinification","linkNoTouchStart","caseSensitiveRoutes","clientParamParsingOrigins","cachedNavigations","dynamicOnHover","useOffline","varyParams","optimisticRouting","instrumentationClientRouterTransitionEvents","prefetchInlining","preloadEntriesOnStart","clientRouterFilter","clientRouterFilterRedirects","fetchCacheKeyPrefix","proxyPrefetch","optimisticClientCache","manualClientBasePath","cpus","CIRCLE_NODE_TOTAL","os","memoryBasedWorkersCount","imgOptConcurrency","imgOptOperationCache","imgOptTimeoutInSeconds","imgOptMaxInputPixels","imgOptSequentialRead","isrFlushToDisk","workerThreads","proxyTimeout","optimizeCss","nextScriptWorkers","scrollRestoration","externalDir","devMemoryThresholdRestart","disableOptimizedLoading","gzipSize","craCompat","esmExternals","fullySpecified","swcTraceProfiling","forceSwcTransforms","requestInsights","swcPlugins","largePageDataBytes","disablePostcssPresetEnv","urlImports","typedEnv","clientTraceMetadata","parallelServerCompiles","parallelServerBuildTraces","ppr","authInterrupts","webpackBuildWorker","webpackMemoryOptimizations","optimizeServerReact","strictRouteTypes","useTypeScriptCli","removeUncaughtErrorAndRejectionListeners","validateRSCRequestHeaders","staleTimes","dynamic","allowDevelopmentBuild","reactDebugChannel","staticGenerationRetryCount","serverComponentsHmrCache","serverComponentsHmrCancellation","staticGenerationMaxConcurrency","staticGenerationMinPagesPerWorker","transitionIndicator","gestureTransition","inlineCss","useCache","slowModuleDetection","globalNotFound","browserDebugInfoInTerminal","lockDistDir","proxyClientMaxBodySize","hideLogsAfterAbort","mcpServer","turbopackFileSystemCacheForDev","turbopackFileSystemCacheForBuild","turbopackInferModuleSideEffects","turbopackPluginRuntimeStrategy","htmlLimitedBots","bundlePagesRouterDependencies","v4Seg","v4Str","v6Seg","IPv6Reg","NON_HTML_SEC_FETCH_DESTS","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","reHasRegExp","reReplaceRegExp","escapeStringRegexp","removeTrailingSlash","PARAMETER_PATTERN","parseMatchedParameter","optional","getRouteRegex","includeSuffix","includePrefix","excludeOptionalTrailingSlash","parameterizedRoute","getParametrizedRoute","groupIndex","markerMatch","paramMatches","getSafeKeyFromSegment","interceptionMarker","getSafeRouteKey","routeKeys","keyPrefix","backreferenceDuplicateKeys","pattern","cleanedKey","invalidKey","duplicateKey","interceptionPrefix","voidCatch","TextEncoder","encoder","streamFromString","encode","streamFromBuffer","streamToString","decoder","TextDecoder","fatal","splitCookiesString","cookiesString","ch","lastComma","nextStart","cookiesSeparatorFound","cookiesStrings","skipWhitespace","charAt","toNodeOutgoingHttpHeaders","nodeHeaders","validateURL","normalizeNextQueryParam","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","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","getClientComponentLoaderMetrics","metrics","reset","isAbortError","HAS_CLIENT_COMPONENT_METRICS_ENABLED","NEXT_OTEL_PERFORMANCE_PREFIX","readable","waitUntilForEnd","response","errored","destroyed","AbortController","once","writableFinished","writer","createWriterFromResponse","started","drained","onDrain","off","WritableStream","write","measure","flushHeaders","getTracer","spanName","ok","flush","destroy","pipeTo","pipeNodeReadableToNodeResponse","pause","resume","isNodeReadable","pipe","RenderResult","EMPTY","metadata","fromStatic","waitUntil","assignMetadata","isNull","isBuffer","chainStreams","streams","TransformStream","preventClose","nextStream","then","lastStream","catch","Readable","toWeb","coerce","pipeThrough","transform","unshift","normalizePathSep","denormalizePagePath","_page","getPathMatch","regexp","delimiter","sensitive","matcher","regexpToFunction","regexModifier","flags","removeUnnamedParams","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","ACTION_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","NEXT_HMR_REFRESH_HEADER","NEXT_URL","FLIGHT_HEADERS","NEXT_RSC_UNION_QUERY","NEXT_REQUEST_ID_HEADER","NEXT_HTML_REQUEST_ID_HEADER","LocaleRouteNormalizer","provider","normalize","UrlNode","insert","urlPath","_insert","smoosh","_smoosh","childrenPaths","children","sort","slugName","splice","restSlugName","optionalRestSlugName","routes","curr","placeholder","urlPaths","slugNames","isCatchAll","nextSegment","segmentName","isOptional","handleSlug","previousSlug","nextSlug","slug","RouteMatcher","definition","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","AppRouteRouteMatcher","AppRouteRouteMatcherProvider","isAPIRoute","PagesAPIRouteMatcher","PagesAPILocaleRouteMatcher","PagesBundlePathNormalizer","PagesFilenameNormalizer","PagesNormalizers","PagesAPIRouteMatcherProvider","PagesRouteMatcher","PagesLocaleRouteMatcher","PagesRouteMatcherProvider","ServerManifestLoader","getter","sharedAsyncLocalStorageNotAvailableError","FakeAsyncLocalStorage","disable","getStore","run","exit","enterWith","maybeGlobalAsyncLocalStorage","REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY","I18NProvider","config","lowerCaseLocales","lowerCaseDomains","http","fromRequest","analysis","sendResponse","statusText","headersWithMultipleValuesAllowed","isHeaderPresent","SuffixPathnameNormalizer","matched","RSCPathnameNormalizer","PrefixPathnameNormalizer","NextDataPathnameNormalizer","buildID","toRoute","PATCHED_SET_HEADER","NEXT_REQUEST_CONTEXT_SYMBOL","REDIRECTS","handleMiddlewareField","NextResponse","Response","cookiesProxy","ResponseCookies","newHeaders","getAll","stringifyCookie","redirected","json","initObj","rewrite","header","createDefaultCacheHandler","refreshTags","getExpiration","updateTags","memoryCache","cacheKey","pendingSets","debug","NEXT_PRIVATE_DEBUG_CACHE","pendingPromise","privateEntry","maxAgeSeconds","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","builtInHandlersSymbol","NextRequestHint","sourcePage","respondWith","PATTERN","SegmentPrefixRSCPathnameNormalizer","extract","originalPathname","segmentPath","dynamicParamTypes","catchall","readBodyWithSizeLimit","maxBodySizeBytes","chunks","buffer","WrappedBuildError","innerError","Server","getServerComponentsHmrCache","__serverComponentsHmrCache","getServerComponentsHmrRefreshHash","handleRSCRequest","parsedUrl","segmentPrefetchRSC","rsc","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","__NEXT_REQUEST_INSIGHTS","runtimeServerDeploymentId","NEXT_DEPLOYMENT_ID","deploymentId","id","NEXT_CLIENT_ASSET_SUFFIX","supportsImmutableAssets","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","partialPrefetching","validationLevel","instantInsights","useCacheTimeout","maxPostponedStateSizeBytes","maxPostponedStateSize","exposeTestingApi","exposeTestingApiInProductionBuild","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","handleRequestImpl","finally","isRSCRequest","setAttributes","setStatus","SpanStatusCode","setAttribute","rootSpanAttributes","getRootSpanAttributes","updateName","requestIdHeader","nanoid","htmlRequestIdHeader","getRequestInsightsIdentityStorage","utils","patchSetHeaderWithCookieSupport","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","isDefaultValueMatch","candidateValue","defaultValue","normalizedCandidateValue","decodedCandidateValue","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","NoFallbackError","getRequestHandlerWithMetadata","handler","getRequestHandler","loadInstrumentationModule","prepareImpl","normalizedPath","runImpl","partialContext","pipeImpl","userAgent","botType","serveStreamingMetadata","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","hasInstantTestCookie","NEXT_INSTANT_TEST_COOKIE","minimalPostponed","isRoutePPREnabled","renderingMode","Component","isBotRequest","isDomBotUA","isSupportedDocument","Document","getInitialProps","NEXT_BUILTIN_DOCUMENT","isDev","getStaticPathsStart","hrtime","bigint","prerenderedRoutes","perUrlFallbackRouteParams","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","wellKnownProperties","getActionNotFoundError","MANIFESTS_SINGLETON","globalThisWithManifests","loadManifestWithRetries","manifestPath","attempts","tryLoadManifestWithRetries","evalManifestWithRetries","evalManifest","loadClientReferenceManifestForPage","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","registeredManifest","proxy","currentManifest","serverModuleMap","getServerActionsManifest","pageName","workerEntry","encoded","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","rootDir","toHex","isArrayBuffer","byteOffset","hex","byte","padStart","hashString","cacheString","createHash","update","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","generateSimpleCacheKey","generateCacheKey","bodyChunks","bodyType","_ogBody","readableBody","total","arr","arrayBuffer","iterable","blob","Blob","cacheData","isStale","revalidateAfter","resumeDataCache","getResumeDataCache","memoryCacheData","pendingRevalidatedTags","mutable","age","expireAfter","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","resolvedFilePath","fileURLToPath","absoluteFilePath","pathToFileURL","isInterceptionRouteRewrite","AsyncCallbackSet","callbacks","runAll","allSettled","NodeModuleLoader","RouterServerContextSymbol","routerServerGlobal","REACT_POSTPONE_TYPE","isPostpone","$$typeof","_global","UNHANDLED_REJECTION_LISTENER_KEY","unhandledRejectionListener","dynamicImportEsmDefault","MiddlewareMatcherCache","NextNodeServer","BaseServer","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","shouldRemoveUncaughtErrorAndRejectionListeners","nextInitializedProcessErrorHandlers","removeAllListeners","registerUnhandledRejectionListener","unstable_preloadEntries","loadCustomCacheHandlers","_err","patchFetch","handleUpgrade","getInstrumentationModule","runInstrumentationHookIfAvailable","ensureInstrumentationRegistered","envFilePath","initializeCacheHandlers","handlersMap","builtInHandlers","DefaultCache","RemoteCache","setCacheHandler","CacheHandler","getCacheFilesystem","routesManifest","buildIdFile","runApi","requestMeta","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","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,CA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ACF,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,199,200,201,202,203,204,205,206,207,208,209]}