{"version":3,"file":"app-route-turbo.runtime.prod.js","sources":["webpack://next/webpack/runtime/create_fake_namespace_object","webpack://next/./dist/compiled/@edge-runtime/cookies/index.js","webpack://next/./dist/compiled/cookie/index.js","webpack://next/./dist/compiled/p-queue/index.js","webpack://next/./dist/compiled/path-to-regexp/index.js","webpack://next/./dist/compiled/react/cjs/react.production.js","webpack://next/./dist/compiled/react/index.js","webpack://next/./dist/compiled/string-hash/index.js","webpack://next/./src/lib/picocolors.ts","webpack://next/./src/build/output/log.ts","webpack://next/./src/lib/constants.ts","webpack://next/./src/lib/format-dynamic-import-path.ts","webpack://next/./src/server/api-utils/index.ts","webpack://next/./src/server/api-utils/node/try-get-preview-data.ts","webpack://next/./src/server/app-render/instant-validation/instant-samples.ts","webpack://next/./src/server/app-render/instant-validation/instant-validation-error.ts","webpack://next/./src/server/crypto-utils.ts","webpack://next/./src/server/lib/lru-cache.ts","webpack://next/./src/server/lib/node-fs-methods.ts","webpack://next/./src/server/lib/router-utils/is-postpone.ts","webpack://next/./src/server/lib/trace/constants.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-extensions/process-error-handlers.ts","webpack://next/./src/server/web/spec-extension/adapters/headers.ts","webpack://next/./src/server/web/spec-extension/adapters/reflect.ts","webpack://next/./src/server/web/spec-extension/adapters/request-cookies.ts","webpack://next/./src/shared/lib/action-revalidation-kind.ts","webpack://next/./src/shared/lib/invariant-error.ts","webpack://next/./src/shared/lib/isomorphic/path.js","webpack://next/./src/shared/lib/modern-browserslist-target.js","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/router/utils/get-segment-param.tsx","webpack://next/./src/shared/lib/router/utils/interception-routes.ts","webpack://next/./src/shared/lib/router/utils/parse-relative-url.ts","webpack://next/./src/shared/lib/router/utils/querystring.ts","webpack://next/./src/shared/lib/segment.ts","webpack://next/./src/shared/lib/utils.ts","webpack://next/./src/shared/lib/utils/reflect-utils.ts","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/lib/clone-response.ts","webpack://next/./src/server/response-cache/types.ts","webpack://next/./src/server/route-kind.ts","webpack://next/./src/server/app-render/staged-rendering.ts","webpack://next/./src/server/app-render/dynamic-rendering.ts","webpack://next/./src/client/components/redirect-status-code.ts","webpack://next/./src/server/app-render/prospective-render-utils.ts","webpack://next/./src/shared/lib/constants.ts","webpack://next/./src/lib/url.ts","webpack://next/./src/shared/lib/i18n/normalize-locale-path.ts","webpack://next/./src/shared/lib/router/utils/is-dynamic.ts","webpack://next/./src/shared/lib/router/utils/parse-path.ts","webpack://next/./src/shared/lib/router/utils/path-has-prefix.ts","webpack://next/./src/shared/lib/router/utils/remove-path-prefix.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/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/shared/lib/router/utils/prepare-destination.ts","webpack://next/./src/server/web/utils.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/shared/lib/i18n/detect-domain-locale.ts","webpack://next/./src/shared/lib/get-hostname.ts","webpack://next/./src/shared/lib/page-path/normalize-data-path.ts","webpack://next/./src/server/request-meta.ts","webpack://next/./src/server/lib/patch-set-header.ts","webpack://next/./src/shared/lib/page-path/normalize-page-path.ts","webpack://next/./src/lib/metadata/is-metadata-route.ts","webpack://next/./src/lib/detached-promise.ts","webpack://next/./src/lib/batcher.ts","webpack://next/./src/lib/scheduler.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/shared/lib/router/utils/add-path-prefix.ts","webpack://next/./src/shared/lib/router/utils/add-path-suffix.ts","webpack://next/./src/server/web/next-url.ts","webpack://next/./src/shared/lib/router/utils/get-next-pathname-info.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/spec-extension/request.ts","webpack://next/./src/server/web/spec-extension/adapters/next-request.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/server/response-cache/utils.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/to-route.ts","webpack://next/./src/server/lib/incremental-cache/index.ts","webpack://next/./src/server/lib/cache-handlers/default.ts","webpack://next/./src/server/use-cache/handlers.ts","webpack://next/./src/server/app-render/interop-default.ts","webpack://next/./src/server/lib/router-utils/router-server-context.ts","webpack://next/./src/client/components/app-router-headers.ts","webpack://next/./src/lib/is-interception-route-rewrite.ts","webpack://next/./src/server/route-modules/route-module.ts","webpack://next/./src/lib/is-app-route-route.ts","webpack://next/./src/shared/lib/page-path/normalize-path-sep.ts","webpack://next/./src/shared/lib/router/utils/path-match.ts","webpack://next/./src/server/api-utils/get-cookie-parser.ts","webpack://next/./src/shared/lib/router/utils/parse-url.ts","webpack://next/./src/server/lib/router-utils/decode-path-params.ts","webpack://next/./src/shared/lib/router/utils/escape-path-delimiters.ts","webpack://next/./src/server/async-storage/draft-mode-provider.ts","webpack://next/./src/server/async-storage/request-store.ts","webpack://next/./src/server/revalidation-utils.ts","webpack://next/./src/server/app-render/async-local-storage.ts","webpack://next/./src/server/after/after-context.ts","webpack://next/./src/shared/lib/is-thenable.ts","webpack://next/./src/server/lib/lazy-result.ts","webpack://next/./src/server/web/http.ts","webpack://next/./src/server/lib/encode-header-safe.ts","webpack://next/./src/server/lib/implicit-tags.ts","webpack://next/./src/server/lib/trace/request-insights-identity.ts","webpack://next/./src/client/components/hooks-server-context.ts","webpack://next/./src/client/components/static-generation-bailout.ts","webpack://next/./src/server/dynamic-rendering-utils.ts","webpack://next/./src/server/lib/dedupe-fetch.ts","webpack://next/./src/server/lib/patch-fetch.ts","webpack://next/./src/server/route-modules/app-route/helpers/auto-implement-methods.ts","webpack://next/./src/client/components/http-access-fallback/http-access-fallback.ts","webpack://next/./src/client/components/redirect-error.ts","webpack://next/./src/server/app-render/create-error-handler.tsx","webpack://next/./src/shared/lib/lazy-dynamic/bailout-to-csr.ts","webpack://next/./src/client/components/is-next-router-error.ts","webpack://next/./src/server/app-render/react-large-shell-error.ts","webpack://next/./src/shared/lib/app-router-context.shared-runtime.ts","webpack://next/./src/server/app-render/cache-signal.ts","webpack://next/./src/server/app-render/vary-params.ts","webpack://next/./src/server/create-deduped-by-callsite-server-error-logger.ts","webpack://next/./src/server/request/params.ts","webpack://next/./src/server/lib/lazy-module.ts","webpack://next/./src/server/app-render/manifests-singleton.ts","webpack://next/./src/server/route-modules/app-route/module.ts","webpack://next/./src/server/route-modules/app-route/helpers/is-static-gen-enabled.ts","webpack://next/./src/server/lib/params-utils.ts","webpack://next/./src/server/route-modules/app-route/helpers/parsed-url-query-to-params.ts","webpack://next/./src/server/resume-data-cache/resume-data-cache.ts","webpack://next/./src/client/components/redirect.ts","webpack://next/./src/server/lib/server-action-request-meta.ts","webpack://next/./src/server/async-storage/work-store.ts","webpack://next/./src/server/route-modules/app-route/helpers/clean-url.ts"],"sourcesContent":["var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n  __webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => { def[key] = () => (value[key]) });\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\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\";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={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})();","/**\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","(()=>{\"use strict\";var e={36:e=>{function hash(e){var r=5381,_=e.length;while(_){r=r*33^e.charCodeAt(--_)}return r>>>0}e.exports=hash}};var r={};function __nccwpck_require__(_){var a=r[_];if(a!==undefined){return a.exports}var t=r[_]={exports:{}};var i=true;try{e[_](t,t.exports,__nccwpck_require__);i=false}finally{if(i)delete r[_]}return t.exports}if(typeof __nccwpck_require__!==\"undefined\")__nccwpck_require__.ab=__dirname+\"/\";var _=__nccwpck_require__(36);module.exports=_})();","// 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","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 { 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 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 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 { IncomingMessage, ServerResponse } from 'http'\nimport type { NextApiResponse } from '../../../shared/lib/utils'\nimport { checkIsOnDemandRevalidate } from '../.'\nimport type { __ApiPreviewProps } from '../.'\nimport type { BaseNextRequest, BaseNextResponse } from '../../base-http'\nimport type { PreviewData } from '../../../types'\n\nimport {\n  clearPreviewData,\n  COOKIE_NAME_PRERENDER_BYPASS,\n  COOKIE_NAME_PRERENDER_DATA,\n  SYMBOL_PREVIEW_DATA,\n} from '../index'\nimport { RequestCookies } from '../../web/spec-extension/cookies'\nimport { HeadersAdapter } from '../../web/spec-extension/adapters/headers'\n\nexport function tryGetPreviewData(\n  req: IncomingMessage | BaseNextRequest | Request,\n  res: ServerResponse | BaseNextResponse,\n  options: __ApiPreviewProps,\n  multiZoneDraftMode: boolean\n): PreviewData {\n  // if an On-Demand revalidation is being done preview mode\n  // is disabled\n  if (\n    options &&\n    checkIsOnDemandRevalidate(req.headers, options).isOnDemandRevalidate\n  ) {\n    return false\n  }\n\n  // Read cached preview data if present\n  // TODO: use request metadata instead of a symbol\n  if (SYMBOL_PREVIEW_DATA in req) {\n    return (req as any)[SYMBOL_PREVIEW_DATA] as any\n  }\n\n  const headers = HeadersAdapter.from(req.headers)\n  const cookies = new RequestCookies(headers)\n\n  const previewModeId = cookies.get(COOKIE_NAME_PRERENDER_BYPASS)?.value\n  const tokenPreviewData = cookies.get(COOKIE_NAME_PRERENDER_DATA)?.value\n  const isValidPreviewModeId =\n    previewModeId === options.previewModeId ||\n    // In dev mode, the cookie can be the actual hash value preview id but the\n    // preview props can still be `development-id`.\n    (process.env.NODE_ENV !== 'production' &&\n      options.previewModeId === 'development-id')\n\n  // Case: preview mode cookie set but data cookie is not set\n  if (previewModeId && !tokenPreviewData && isValidPreviewModeId) {\n    // This is \"Draft Mode\" which doesn't use\n    // previewData, so we return an empty object\n    // for backwards compat with \"Preview Mode\".\n    const data = {}\n    Object.defineProperty(req, SYMBOL_PREVIEW_DATA, {\n      value: data,\n      enumerable: false,\n    })\n    return data\n  }\n\n  // Case: neither cookie is set.\n  if (!previewModeId && !tokenPreviewData) {\n    return false\n  }\n\n  // Case: one cookie is set, but not the other.\n  if (!previewModeId || !tokenPreviewData) {\n    if (!multiZoneDraftMode) {\n      clearPreviewData(res as NextApiResponse)\n    }\n    return false\n  }\n\n  // Case: preview session is for an old build.\n  if (previewModeId !== options.previewModeId) {\n    if (!multiZoneDraftMode) {\n      clearPreviewData(res as NextApiResponse)\n    }\n    return false\n  }\n\n  let encryptedPreviewData: {\n    data: string\n  }\n  try {\n    const jsonwebtoken =\n      require('next/dist/compiled/jsonwebtoken') as typeof import('next/dist/compiled/jsonwebtoken')\n    encryptedPreviewData = jsonwebtoken.verify(\n      tokenPreviewData,\n      options.previewModeSigningKey\n    ) as typeof encryptedPreviewData\n  } catch {\n    // TODO: warn\n    clearPreviewData(res as NextApiResponse)\n    return false\n  }\n\n  const { decryptWithSecret } =\n    require('../../crypto-utils') as typeof import('../../crypto-utils')\n  const decryptedPreviewData = decryptWithSecret(\n    Buffer.from(options.previewModeEncryptionKey),\n    encryptedPreviewData.data\n  )\n\n  try {\n    // TODO: strict runtime type checking\n    const data = JSON.parse(decryptedPreviewData)\n    // Cache lookup\n    Object.defineProperty(req, SYMBOL_PREVIEW_DATA, {\n      value: data,\n      enumerable: false,\n    })\n    return data\n  } catch {\n    return false\n  }\n}\n","import type { InstantSample } from '../../../build/segment-config/app/app-segment-config'\nimport type { ReadonlyRequestCookies } from '../../web/spec-extension/adapters/request-cookies'\nimport type { ReadonlyHeaders } from '../../web/spec-extension/adapters/headers'\nimport type { DraftModeProvider } from '../../async-storage/draft-mode-provider'\nimport type { Params } from '../../request/params'\n\nimport { RequestCookies } from '../../web/spec-extension/cookies'\nimport { RequestCookiesAdapter } from '../../web/spec-extension/adapters/request-cookies'\nimport { HeadersAdapter } from '../../web/spec-extension/adapters/headers'\nimport type { SearchParams } from '../../request/search-params'\nimport { getSegmentParam } from '../../../shared/lib/router/utils/get-segment-param'\nimport { parseRelativeUrl } from '../../../shared/lib/router/utils/parse-relative-url'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport { InstantValidationError } from './instant-validation-error'\nimport { workUnitAsyncStorage } from '../work-unit-async-storage.external'\nimport { wellKnownProperties } from '../../../shared/lib/utils/reflect-utils'\nimport type { WorkStore } from '../work-async-storage.external'\n\nexport type InstantValidationSampleTracking = {\n  // TODO(instant-validation-build): track which samples config we used and attribute errors\n  missingSampleErrors: InstantValidationError[]\n}\n\nexport function createValidationSampleTracking(): InstantValidationSampleTracking {\n  return {\n    missingSampleErrors: [],\n  }\n}\n\nfunction getExpectedSampleTracking(): InstantValidationSampleTracking {\n  let validationSampleTracking: InstantValidationSampleTracking | null = null\n  const workUnitStore = workUnitAsyncStorage.getStore()\n  if (workUnitStore) {\n    switch (workUnitStore.type) {\n      case 'request':\n      case 'validation-client':\n        // TODO(instant-validation-build): do we need any special handling for caches?\n        validationSampleTracking =\n          workUnitStore.validationSampleTracking ?? null\n        break\n      case 'cache':\n      case 'private-cache':\n      case 'unstable-cache':\n      case 'prerender-legacy':\n      case 'prerender-ppr':\n      case 'prerender-client':\n      case 'prerender':\n      case 'prerender-runtime':\n      case 'generate-static-params':\n        break\n      default:\n        workUnitStore satisfies never\n    }\n  }\n  if (!validationSampleTracking) {\n    throw new InvariantError(\n      'Expected to have a workUnitStore that provides validationSampleTracking'\n    )\n  }\n  return validationSampleTracking\n}\n\nexport function trackMissingSampleError(error: InstantValidationError): void {\n  const validationSampleTracking = getExpectedSampleTracking()\n  validationSampleTracking.missingSampleErrors.push(error)\n}\n\nexport function trackMissingSampleErrorAndThrow(\n  error: InstantValidationError\n): never {\n  // TODO(instant-validation-build): this should abort the render\n  trackMissingSampleError(error)\n  throw error\n}\n\n/**\n * Creates ReadonlyRequestCookies from sample cookie data.\n * Accessing a cookie not declared in the sample will throw an error.\n * Cookies with `value: null` are declared (allowed to access) but return no value.\n */\nexport function createCookiesFromSample(\n  sampleCookies: InstantSample['cookies'],\n  route: string\n): ReadonlyRequestCookies {\n  const declaredNames = new Set<string>()\n\n  const cookies = new RequestCookies(new Headers())\n  if (sampleCookies) {\n    for (const cookie of sampleCookies) {\n      declaredNames.add(cookie.name)\n      if (cookie.value !== null) {\n        cookies.set(cookie.name, cookie.value)\n      }\n    }\n  }\n\n  const sealed = RequestCookiesAdapter.seal(cookies)\n\n  return new Proxy(sealed, {\n    get(target, prop, receiver) {\n      if (prop === 'has') {\n        const originalMethod = Reflect.get(target, prop, receiver)\n        const wrappedMethod: typeof originalMethod = function (name) {\n          if (!declaredNames.has(name)) {\n            trackMissingSampleErrorAndThrow(\n              createMissingCookieSampleError(route, name)\n            )\n          }\n          return originalMethod.call(target, name)\n        }\n        return wrappedMethod\n      }\n      if (prop === 'get') {\n        const originalMethod = Reflect.get(target, prop, receiver)\n        const wrappedMethod: typeof originalMethod = function (nameOrCookie) {\n          let name: string\n          if (typeof nameOrCookie === 'string') {\n            name = nameOrCookie\n          } else if (\n            nameOrCookie &&\n            typeof nameOrCookie === 'object' &&\n            typeof nameOrCookie.name === 'string'\n          ) {\n            name = nameOrCookie.name\n          } else {\n            // This is an invalid input. Pass it through to the original method so it can error.\n            return originalMethod.call(target, nameOrCookie)\n          }\n\n          if (!declaredNames.has(name)) {\n            trackMissingSampleErrorAndThrow(\n              createMissingCookieSampleError(route, name)\n            )\n          }\n          return originalMethod.call(target, name)\n        }\n        return wrappedMethod\n      }\n\n      // TODO(instant-validation-build): what should getAll do?\n      // Maybe we should only allow it if there's an array (possibly empty?)\n\n      return Reflect.get(target, prop, receiver)\n    },\n  })\n}\n\nfunction createMissingCookieSampleError(\n  route: string,\n  name: string\n): InstantValidationError {\n  return new InstantValidationError(\n    `Route \"${route}\" accessed cookie \"${name}\" which is not defined in the \\`unstable_samples\\` ` +\n      `of \\`instant\\`. Add it to the sample's \\`cookies\\` array, ` +\n      `or \\`{ name: \"${name}\", value: null }\\` if it should be absent.`\n  )\n}\n\n/**\n * Creates ReadonlyHeaders from sample header data.\n * Accessing a header not declared in the sample will throw an error.\n * Headers with `value: null` are declared (allowed to access) but return null.\n */\nexport function createHeadersFromSample(\n  rawSampleHeaders: InstantSample['headers'],\n  sampleCookies: InstantSample['cookies'],\n  route: string\n): ReadonlyHeaders {\n  // If we have cookie samples, add a `cookie` header to match.\n  // Accessing it will be implicitly allowed by the proxy --\n  // if the user defined some cookies, accessing the \"cookie\" header is also fine.\n  const sampleHeaders = rawSampleHeaders ? [...rawSampleHeaders] : []\n  if (sampleHeaders.find(([name]) => name.toLowerCase() === 'cookie')) {\n    throw new InstantValidationError(\n      'Invalid sample: Defining cookies via a \"cookie\" header is not supported. Use `cookies: [{ name: ..., value: ... }]` instead.'\n    )\n  }\n  if (sampleCookies) {\n    const cookieHeaderValue = sampleCookies.toString()\n    sampleHeaders.push([\n      'cookie',\n      // if the `cookies` samples were empty, or they were all `null`, then we have no cookies,\n      // and the header isn't present, but should remains readable, so we set it to null.\n      cookieHeaderValue !== '' ? cookieHeaderValue : null,\n    ])\n  }\n\n  const declaredNames = new Set<string>()\n  const headersInit: Record<string, string> = {}\n\n  for (const [name, value] of sampleHeaders) {\n    declaredNames.add(name.toLowerCase())\n    if (value !== null) {\n      headersInit[name.toLowerCase()] = value\n    }\n  }\n\n  const sealed = HeadersAdapter.seal(HeadersAdapter.from(headersInit))\n\n  return new Proxy(sealed, {\n    get(target, prop, receiver) {\n      if (prop === 'get' || prop === 'has') {\n        const originalMethod = Reflect.get(target, prop, receiver)\n        const patchedMethod: typeof originalMethod = function (rawName) {\n          const name = rawName.toLowerCase()\n          if (!declaredNames.has(name)) {\n            trackMissingSampleErrorAndThrow(\n              new InstantValidationError(\n                `Route \"${route}\" accessed header \"${name}\" which is not defined in the \\`unstable_samples\\` ` +\n                  `of \\`instant\\`. Add it to the sample's \\`headers\\` array, ` +\n                  `or \\`[\"${name}\", null]\\` if it should be absent.`\n              )\n            )\n          }\n          // typescript can't reconcile a union of functions with a union of return types,\n          // so we have to cast the original return type away\n          return (originalMethod as (...args: any[]) => any).call(target, name)\n        }\n        return patchedMethod\n      }\n      return Reflect.get(target, prop, receiver)\n    },\n  })\n}\n\n/**\n * Creates a DraftModeProvider that always returns isEnabled: false.\n */\nexport function createDraftModeForValidation(): DraftModeProvider {\n  // Create a minimal DraftModeProvider-compatible object\n  // that always reports draft mode as disabled.\n  //\n  // private properties that can't be set from outside the class.\n  return {\n    get isEnabled() {\n      return false\n    },\n    enable() {\n      throw new Error(\n        'Draft mode cannot be enabled during build-time instant validation.'\n      )\n    },\n    disable() {\n      throw new Error(\n        'Draft mode cannot be disabled during build-time instant validation.'\n      )\n    },\n  } as Partial<DraftModeProvider> as DraftModeProvider\n}\n\n/**\n * Creates params wrapped with an exhaustive proxy.\n * Accessing a param not declared in the sample will throw an error.\n */\nexport function createExhaustiveParamsProxy<TParams extends Params>(\n  underlyingParams: TParams,\n  declaredParamNames: Set<string>,\n  route: string\n): TParams {\n  return new Proxy(underlyingParams, {\n    get(target, prop, receiver) {\n      if (\n        typeof prop === 'string' &&\n        !wellKnownProperties.has(prop) &&\n        // Only error when accessing a param that is part of the route but wasn't provided.\n        // accessing properties that aren't expected to be a valid param value is fine.\n        prop in underlyingParams &&\n        !declaredParamNames.has(prop)\n      ) {\n        trackMissingSampleErrorAndThrow(\n          new InstantValidationError(\n            `Route \"${route}\" accessed param \"${prop}\" which is not defined in the \\`unstable_samples\\` ` +\n              `of \\`instant\\`. Add it to the sample's \\`params\\` object.`\n          )\n        )\n      }\n      return Reflect.get(target, prop, receiver)\n    },\n    // We don't need to override `has` or `ownKeys`.\n    // the shape of the params object is determined by the routing structure\n    // and independent of the samples. We only need to instrument accessing the values.\n  })\n}\n\n/**\n * Creates searchParams wrapped with an exhaustive proxy.\n * Accessing a searchParam not declared in the sample will throw an error.\n * A searchParam with `value: undefined` means \"declared but absent\" (allowed to access, returns undefined).\n */\nexport function createExhaustiveSearchParamsProxy(\n  searchParams: SearchParams,\n  declaredSearchParamNames: Set<string>,\n  route: string\n): SearchParams {\n  return new Proxy(searchParams, {\n    get(target, prop, receiver) {\n      if (\n        typeof prop === 'string' &&\n        !wellKnownProperties.has(prop) &&\n        !declaredSearchParamNames.has(prop)\n      ) {\n        trackMissingSampleErrorAndThrow(\n          createMissingSearchParamSampleError(route, prop)\n        )\n      }\n      return Reflect.get(target, prop, receiver)\n    },\n    has(target, prop) {\n      if (\n        typeof prop === 'string' &&\n        !wellKnownProperties.has(prop) &&\n        !declaredSearchParamNames.has(prop)\n      ) {\n        trackMissingSampleErrorAndThrow(\n          createMissingSearchParamSampleError(route, prop)\n        )\n      }\n      return Reflect.has(target, prop)\n    },\n  })\n}\n\n/**\n * Wraps a URLSearchParams (or subclass like ReadonlyURLSearchParams) with an\n * exhaustive proxy. Accessing a search param not declared in the sample via\n * get/getAll/has will throw an error.\n */\nexport function createExhaustiveURLSearchParamsProxy<T extends URLSearchParams>(\n  searchParams: T,\n  declaredSearchParamNames: Set<string>,\n  route: string\n): T {\n  return new Proxy(searchParams, {\n    get(target, prop, receiver) {\n      // Intercept method calls that access specific param names\n      if (prop === 'get' || prop === 'getAll' || prop === 'has') {\n        const originalMathod = Reflect.get(target, prop, receiver)\n        return (name: string) => {\n          if (typeof name === 'string' && !declaredSearchParamNames.has(name)) {\n            trackMissingSampleErrorAndThrow(\n              createMissingSearchParamSampleError(route, name)\n            )\n          }\n          return (originalMathod as (...args: any[]) => any).call(target, name)\n        }\n      }\n      const value = Reflect.get(target, prop, receiver)\n      // Prevent `TypeError: Value of \"this\" must be of type URLSearchParams` for methods\n      if (typeof value === 'function' && !Object.hasOwn(target, prop)) {\n        return value.bind(target)\n      }\n      return value\n    },\n  })\n}\n\nfunction createMissingSearchParamSampleError(\n  route: string,\n  name: string\n): InstantValidationError {\n  return new InstantValidationError(\n    `Route \"${route}\" accessed searchParam \"${name}\" which is not defined in the \\`unstable_samples\\` ` +\n      `of \\`instant\\`. Add it to the sample's \\`searchParams\\` object, ` +\n      `or \\`{ \"${name}\": null }\\` if it should be absent.`\n  )\n}\n\nexport function createRelativeURLFromSamples(\n  route: string,\n  sampleParams: InstantSample['params'],\n  sampleSearchParams: InstantSample['searchParams']\n) {\n  // Build searchParams query object and URL search string from sample\n  const pathname = createPathnameFromRouteAndSampleParams(\n    route,\n    sampleParams ?? {}\n  )\n\n  let search = ''\n  if (sampleSearchParams) {\n    const qs = createURLSearchParamsFromSample(sampleSearchParams).toString()\n    if (qs) {\n      search = '?' + qs\n    }\n  }\n\n  return parseRelativeUrl(pathname + search, undefined, true)\n}\n\nfunction createURLSearchParamsFromSample(\n  sampleSearchParams: InstantSample['searchParams']\n) {\n  const result = new URLSearchParams()\n  if (sampleSearchParams) {\n    for (const [key, value] of Object.entries(sampleSearchParams)) {\n      if (value === null || value === undefined) continue\n      if (Array.isArray(value)) {\n        for (const v of value) {\n          result.append(key, v)\n        }\n      } else {\n        result.set(key, value)\n      }\n    }\n  }\n  return result\n}\n\n/**\n * Substitute sample params into `workStore.route` to create a plausible pathname.\n * TODO(instant-validation-build): this logic is somewhat hacky and likely incomplete,\n * but it should be good enough for some initial testing.\n */\nfunction createPathnameFromRouteAndSampleParams(route: string, params: Params) {\n  let interpolatedSegments: string[] = []\n  const rawSegments = route.split('/')\n  for (const rawSegment of rawSegments) {\n    const param = getSegmentParam(rawSegment)\n    if (param) {\n      switch (param.paramType) {\n        case 'catchall':\n        case 'optional-catchall': {\n          let paramValue = params[param.paramName]\n          if (paramValue === undefined) {\n            // The value for the param was not provided. `usePathname` will detect this and throw\n            // before this can surface to userspace. Use `[...NAME]` as a placeholder for the param value\n            // in case it pops up somewhere unexpectedly.\n            paramValue = [rawSegment]\n          } else if (!Array.isArray(paramValue)) {\n            // NOTE: this happens outside of render, so we don't need `trackMissingSampleErrorAndThrow`\n            throw new InstantValidationError(\n              `Expected sample param value for segment '${rawSegment}' to be an array of strings, got ${typeof paramValue}`\n            )\n          }\n          interpolatedSegments.push(\n            ...paramValue.map((v) => encodeURIComponent(v))\n          )\n          break\n        }\n        case 'dynamic': {\n          let paramValue = params[param.paramName]\n          if (paramValue === undefined) {\n            // The value for the param was not provided. `usePathname` will detect this and throw\n            // before this can surface to userspace. Use `[NAME]` as a placeholder for the param value\n            // in case it pops up somewhere unexpectedly.\n            paramValue = rawSegment\n          } else if (typeof paramValue !== 'string') {\n            // NOTE: this happens outside of render, so we don't need `trackMissingSampleErrorAndThrow`\n            throw new InstantValidationError(\n              `Expected sample param value for segment '${rawSegment}' to be a string, got ${typeof paramValue}`\n            )\n          }\n          interpolatedSegments.push(encodeURIComponent(paramValue))\n          break\n        }\n        case 'catchall-intercepted-(..)(..)':\n        case 'catchall-intercepted-(.)':\n        case 'catchall-intercepted-(..)':\n        case 'catchall-intercepted-(...)':\n        case 'dynamic-intercepted-(..)(..)':\n        case 'dynamic-intercepted-(.)':\n        case 'dynamic-intercepted-(..)':\n        case 'dynamic-intercepted-(...)': {\n          // TODO(instant-validation-build): i don't know how these are supposed to work, or if we can even get them here\n          throw new InvariantError(\n            'Not implemented: Validation of interception routes'\n          )\n        }\n        default: {\n          param.paramType satisfies never\n        }\n      }\n    } else {\n      interpolatedSegments.push(rawSegment)\n    }\n  }\n  return interpolatedSegments.join('/')\n}\n\nexport function assertRootParamInSamples(\n  workStore: WorkStore,\n  sampleParams: Params | undefined,\n  paramName: string\n) {\n  if (sampleParams && paramName in sampleParams) {\n    // The param is defined in the samples.\n  } else {\n    const route = workStore.route\n    trackMissingSampleErrorAndThrow(\n      new InstantValidationError(\n        `Route \"${route}\" accessed root param \"${paramName}\" which is not defined in the \\`unstable_samples\\` ` +\n          `of \\`instant\\`. Add it to the sample's \\`params\\` object.`\n      )\n    )\n  }\n}\n","const INSTANT_VALIDATION_ERROR_DIGEST = 'INSTANT_VALIDATION_ERROR'\n\n/** Check if an error is an exhaustive samples validation error (by digest). */\nexport function isInstantValidationError(\n  err: unknown\n): err is InstantValidationError {\n  return !!(\n    err &&\n    typeof err === 'object' &&\n    err instanceof Error &&\n    (err as any).digest === INSTANT_VALIDATION_ERROR_DIGEST\n  )\n}\n\nexport class InstantValidationError extends Error {\n  digest = INSTANT_VALIDATION_ERROR_DIGEST\n}\n","import crypto from 'crypto'\n\n// Background:\n// https://security.stackexchange.com/questions/184305/why-would-i-ever-use-aes-256-cbc-if-aes-256-gcm-is-more-secure\n\nconst CIPHER_ALGORITHM = `aes-256-gcm`,\n  CIPHER_KEY_LENGTH = 32, // https://stackoverflow.com/a/28307668/4397028\n  CIPHER_IV_LENGTH = 16, // https://stackoverflow.com/a/28307668/4397028\n  CIPHER_TAG_LENGTH = 16,\n  CIPHER_SALT_LENGTH = 64\n\nconst PBKDF2_ITERATIONS = 100_000 // https://support.1password.com/pbkdf2/\n\nexport function encryptWithSecret(secret: Buffer, data: string): string {\n  const iv = crypto.randomBytes(CIPHER_IV_LENGTH)\n  const salt = crypto.randomBytes(CIPHER_SALT_LENGTH)\n\n  // https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest\n  const key = crypto.pbkdf2Sync(\n    secret,\n    salt,\n    PBKDF2_ITERATIONS,\n    CIPHER_KEY_LENGTH,\n    `sha512`\n  )\n\n  const cipher = crypto.createCipheriv(CIPHER_ALGORITHM, key, iv)\n  const encrypted = Buffer.concat([cipher.update(data, `utf8`), cipher.final()])\n\n  // https://nodejs.org/api/crypto.html#crypto_cipher_getauthtag\n  const tag = cipher.getAuthTag()\n\n  return Buffer.concat([\n    // Data as required by:\n    // Salt for Key: https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest\n    // IV: https://nodejs.org/api/crypto.html#crypto_class_decipher\n    // Tag: https://nodejs.org/api/crypto.html#crypto_decipher_setauthtag_buffer\n    salt,\n    iv,\n    tag,\n    encrypted,\n  ]).toString(`hex`)\n}\n\nexport function decryptWithSecret(\n  secret: Buffer,\n  encryptedData: string\n): string {\n  const buffer = Buffer.from(encryptedData, `hex`)\n\n  const salt = buffer.slice(0, CIPHER_SALT_LENGTH)\n  const iv = buffer.slice(\n    CIPHER_SALT_LENGTH,\n    CIPHER_SALT_LENGTH + CIPHER_IV_LENGTH\n  )\n  const tag = buffer.slice(\n    CIPHER_SALT_LENGTH + CIPHER_IV_LENGTH,\n    CIPHER_SALT_LENGTH + CIPHER_IV_LENGTH + CIPHER_TAG_LENGTH\n  )\n  const encrypted = buffer.slice(\n    CIPHER_SALT_LENGTH + CIPHER_IV_LENGTH + CIPHER_TAG_LENGTH\n  )\n\n  // https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest\n  const key = crypto.pbkdf2Sync(\n    secret,\n    salt,\n    PBKDF2_ITERATIONS,\n    CIPHER_KEY_LENGTH,\n    `sha512`\n  )\n\n  const decipher = crypto.createDecipheriv(CIPHER_ALGORITHM, key, iv)\n  decipher.setAuthTag(tag)\n\n  return decipher.update(encrypted) + decipher.final(`utf8`)\n}\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 { 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","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","/**\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 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","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 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","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 { 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","export type ActionRevalidationKind = 0 | 1 | 2\n\nexport const ActionDidNotRevalidate = 0\nexport const ActionDidRevalidateStaticAndDynamic = 1\nexport const ActionDidRevalidateDynamicOnly = 2\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 * 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","/**\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 { INTERCEPTION_ROUTE_MARKERS } from './interception-routes'\nimport type { DynamicParamTypes } from '../../app-router-types'\n\nexport type SegmentParam = {\n  paramName: string\n  paramType: DynamicParamTypes\n}\n\n/**\n * Parse dynamic route segment to type of parameter\n */\nexport function getSegmentParam(segment: string): SegmentParam | null {\n  const interceptionMarker = INTERCEPTION_ROUTE_MARKERS.find((marker) =>\n    segment.startsWith(marker)\n  )\n\n  // if an interception marker is part of the path segment, we need to jump ahead\n  // to the relevant portion for param parsing\n  if (interceptionMarker) {\n    segment = segment.slice(interceptionMarker.length)\n  }\n\n  if (segment.startsWith('[[...') && segment.endsWith(']]')) {\n    return {\n      // TODO-APP: Optional catchall does not currently work with parallel routes,\n      // so for now aren't handling a potential interception marker.\n      paramType: 'optional-catchall',\n      paramName: segment.slice(5, -2),\n    }\n  }\n\n  if (segment.startsWith('[...') && segment.endsWith(']')) {\n    return {\n      paramType: interceptionMarker\n        ? `catchall-intercepted-${interceptionMarker}`\n        : 'catchall',\n      paramName: segment.slice(4, -1),\n    }\n  }\n\n  if (segment.startsWith('[') && segment.endsWith(']')) {\n    return {\n      paramType: interceptionMarker\n        ? `dynamic-intercepted-${interceptionMarker}`\n        : 'dynamic',\n      paramName: segment.slice(1, -1),\n    }\n  }\n\n  return null\n}\n\nexport function isCatchAll(\n  type: DynamicParamTypes\n): type is\n  | 'catchall'\n  | 'catchall-intercepted-(..)(..)'\n  | 'catchall-intercepted-(.)'\n  | 'catchall-intercepted-(..)'\n  | 'catchall-intercepted-(...)'\n  | 'optional-catchall' {\n  return (\n    type === 'catchall' ||\n    type === 'catchall-intercepted-(..)(..)' ||\n    type === 'catchall-intercepted-(.)' ||\n    type === 'catchall-intercepted-(..)' ||\n    type === 'catchall-intercepted-(...)' ||\n    type === 'optional-catchall'\n  )\n}\n\nexport function getParamProperties(paramType: DynamicParamTypes): {\n  repeat: boolean\n  optional: boolean\n} {\n  let repeat = false\n  let optional = false\n\n  switch (paramType) {\n    case 'catchall':\n    case 'catchall-intercepted-(..)(..)':\n    case 'catchall-intercepted-(.)':\n    case 'catchall-intercepted-(..)':\n    case 'catchall-intercepted-(...)':\n      repeat = true\n      break\n    case 'optional-catchall':\n      repeat = true\n      optional = true\n      break\n    case 'dynamic':\n    case 'dynamic-intercepted-(..)(..)':\n    case 'dynamic-intercepted-(.)':\n    case 'dynamic-intercepted-(..)':\n    case 'dynamic-intercepted-(...)':\n      break\n    default:\n      paramType satisfies never\n  }\n\n  return { repeat, optional }\n}\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 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 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 { 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 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","// 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","// 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};","const noop = () => {}\n\nlet registry: FinalizationRegistry<WeakRef<ReadableStream>> | undefined\n\nif (globalThis.FinalizationRegistry) {\n  registry = new FinalizationRegistry((weakRef: WeakRef<ReadableStream>) => {\n    const stream = weakRef.deref()\n    if (stream && !stream.locked) {\n      stream.cancel('Response object has been garbage collected').then(noop)\n    }\n  })\n}\n\n/**\n * Clones a response by teeing the body so we can return two independent\n * ReadableStreams from it. This avoids the bug in the undici library around\n * response cloning.\n *\n * After cloning, the original response's body will be consumed and closed.\n *\n * @see https://github.com/vercel/next.js/pull/73274\n *\n * @param original - The original response to clone.\n * @returns A tuple containing two independent clones of the original response.\n */\nexport function cloneResponse(original: Response): [Response, Response] {\n  // If the response has no body, then we can just return the original response\n  // twice because it's immutable.\n  if (!original.body) {\n    return [original, original]\n  }\n\n  const [body1, body2] = original.body.tee()\n\n  const cloned1 = new Response(body1, {\n    status: original.status,\n    statusText: original.statusText,\n    headers: original.headers,\n  })\n\n  Object.defineProperty(cloned1, 'url', {\n    value: original.url,\n    // How the original response.url behaves\n    configurable: true,\n    enumerable: true,\n    writable: false,\n  })\n\n  const cloned2 = new Response(body2, {\n    status: original.status,\n    statusText: original.statusText,\n    headers: original.headers,\n  })\n\n  Object.defineProperty(cloned2, 'url', {\n    value: original.url,\n    // How the original response.url behaves\n    configurable: true,\n    enumerable: true,\n    writable: false,\n  })\n\n  // The Fetch Standard allows users to skip consuming the response body by\n  // relying on garbage collection to release connection resources.\n  // https://github.com/nodejs/undici?tab=readme-ov-file#garbage-collection\n  //\n  // To cancel the stream you then need to cancel both resulting branches.\n  // Teeing a stream will generally lock it for the duration, preventing other\n  // readers from locking it.\n  // https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/tee\n  if (registry) {\n    if (cloned1.body) {\n      registry.register(cloned1, new WeakRef(cloned1.body))\n    }\n\n    if (cloned2.body) {\n      registry.register(cloned2, new WeakRef(cloned2.body))\n    }\n  }\n\n  return [cloned1, cloned2]\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","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 { 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 * 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","export enum RedirectStatusCode {\n  SeeOther = 303,\n  TemporaryRedirect = 307,\n  PermanentRedirect = 308,\n}\n","import { getDigestForWellKnownError } from './create-error-handler'\nimport { isReactLargeShellError } from './react-large-shell-error'\n\nexport enum Phase {\n  ProspectiveRender = 'the prospective render',\n  SegmentCollection = 'segment collection',\n  InstantValidation = 'instant validation',\n}\n\nexport function printDebugThrownValueForProspectiveRender(\n  thrownValue: unknown,\n  route: string,\n  phase: Phase\n) {\n  // We don't need to print well-known Next.js errors.\n  if (getDigestForWellKnownError(thrownValue)) {\n    return\n  }\n\n  if (isReactLargeShellError(thrownValue)) {\n    // TODO: Aggregate\n    console.error(thrownValue)\n    return undefined\n  }\n\n  let message: undefined | string\n  if (\n    typeof thrownValue === 'object' &&\n    thrownValue !== null &&\n    typeof (thrownValue as any).message === 'string'\n  ) {\n    message = (thrownValue as any).message\n    if (typeof (thrownValue as any).stack === 'string') {\n      const originalErrorStack: string = (thrownValue as any).stack\n      const stackStart = originalErrorStack.indexOf('\\n')\n      if (stackStart > -1) {\n        const error = new Error(\n          `Route ${route} errored during ${phase}. These errors are normally ignored and may not prevent the route from prerendering but are logged here because build debugging is enabled.\n          \nOriginal Error: ${message}`\n        )\n        error.stack =\n          'Error: ' + error.message + originalErrorStack.slice(stackStart)\n        console.error(error)\n        return\n      }\n    }\n  } else if (typeof thrownValue === 'string') {\n    message = thrownValue\n  }\n\n  if (message) {\n    console.error(`Route ${route} errored during ${phase}. These errors are normally ignored and may not prevent the route from prerendering but are logged here because build debugging is enabled. No stack was provided.\n          \nOriginal Message: ${message}`)\n    return\n  }\n\n  console.error(\n    `Route ${route} errored during ${phase}. These errors are normally ignored and may not prevent the route from prerendering but are logged here because build debugging is enabled. The thrown value is logged just following this message`\n  )\n  console.error(thrownValue)\n  return\n}\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 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","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 {\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","/**\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 * 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 { 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","// 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 { 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 } 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","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 * 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 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 { 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","import { pathHasPrefix } from '../router/utils/path-has-prefix'\n\n/**\n * strip _next/data/<build-id>/ prefix and .json suffix\n */\nexport function normalizeDataPath(pathname: string) {\n  if (!pathHasPrefix(pathname || '/', '/_next/data')) {\n    return pathname\n  }\n  pathname = pathname\n    .replace(/\\/_next\\/data\\/[^/]{1,}/, '')\n    .replace(/\\.json$/, '')\n\n  if (pathname === '/index') {\n    return '/'\n  }\n  return pathname\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","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 { 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 { 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","/**\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 { SchedulerFn } from './scheduler'\n\nimport { DetachedPromise } from './detached-promise'\n\ntype CacheKeyFn<K, C extends string | number | null> = (\n  key: K\n) => PromiseLike<C> | C\n\ntype BatcherOptions<K, C extends string | number | null> = {\n  cacheKeyFn?: CacheKeyFn<K, C>\n  schedulerFn?: SchedulerFn<void>\n}\n\ntype WorkFnContext<V, K> = {\n  resolve: (value: V | PromiseLike<V>) => void\n  key: K\n}\n\ntype WorkFn<V, K> = (context: WorkFnContext<V, K>) => Promise<V>\n\n/**\n * A wrapper for a function that will only allow one call to the function to\n * execute at a time.\n */\nexport class Batcher<K, V, C extends string | number | null> {\n  private readonly pending = new Map<C, Promise<V>>()\n\n  protected constructor(\n    private readonly cacheKeyFn?: CacheKeyFn<K, C>,\n    /**\n     * A function that will be called to schedule the wrapped function to be\n     * executed. This defaults to a function that will execute the function\n     * immediately.\n     */\n    private readonly schedulerFn: SchedulerFn<void> = (fn) => fn()\n  ) {}\n\n  /**\n   * Creates a new instance of PendingWrapper. If the key extends a string or\n   * number, the key will be used as the cache key. If the key is an object, a\n   * cache key function must be provided.\n   */\n  public static create<K extends string | number | null, V>(\n    options?: BatcherOptions<K, K>\n  ): Batcher<K, V, K>\n  public static create<K, V, C extends string | number | null>(\n    options: BatcherOptions<K, C> &\n      Required<Pick<BatcherOptions<K, C>, 'cacheKeyFn'>>\n  ): Batcher<K, V, C>\n  public static create<K, V, C extends string | number | null>(\n    options?: BatcherOptions<K, C>\n  ): Batcher<K, V, C> {\n    return new Batcher<K, V, C>(options?.cacheKeyFn, options?.schedulerFn)\n  }\n\n  /**\n   * Wraps a function in a promise that will be resolved or rejected only once\n   * for a given key. This will allow multiple calls to the function to be\n   * made, but only one will be executed at a time. The result of the first\n   * call will be returned to all callers.\n   *\n   * @param key the key to use for the cache\n   * @param fn the function to wrap\n   * @returns a promise that resolves to the result of the function\n   */\n  public async batch(key: K, fn: WorkFn<V, K>): Promise<V> {\n    const cacheKey = (this.cacheKeyFn ? await this.cacheKeyFn(key) : key) as C\n    if (cacheKey === null) {\n      return fn({ resolve: (value) => Promise.resolve(value), key })\n    }\n\n    const pending = this.pending.get(cacheKey)\n    if (pending) return pending\n\n    const { promise, resolve, reject } = new DetachedPromise<V>()\n    this.pending.set(cacheKey, promise)\n\n    this.schedulerFn(async () => {\n      try {\n        const result = await fn({ resolve, key })\n\n        // Resolving a promise multiple times is a no-op, so we can safely\n        // resolve all pending promises with the same result.\n        resolve(result)\n      } catch (err) {\n        reject(err)\n      } finally {\n        this.pending.delete(cacheKey)\n      }\n    })\n\n    return promise\n  }\n}\n","export type ScheduledFn<T = void> = () => T | PromiseLike<T>\nexport type SchedulerFn<T = void> = (cb: ScheduledFn<T>) => void\n\n/**\n * Schedules a function to be called on the next tick after the other promises\n * have been resolved.\n *\n * @param cb the function to schedule\n */\nexport const scheduleOnNextTick = (cb: ScheduledFn<void>) => {\n  // We use Promise.resolve().then() here so that the operation is scheduled at\n  // the end of the promise job queue, we then add it to the next process tick\n  // to ensure it's evaluated afterwards.\n  //\n  // This was inspired by the implementation of the DataLoader interface: https://github.com/graphql/dataloader/blob/d336bd15282664e0be4b4a657cb796f09bafbc6b/src/index.js#L213-L255\n  //\n  Promise.resolve().then(() => {\n    if (process.env.NEXT_RUNTIME === 'edge') {\n      setTimeout(cb, 0)\n    } else {\n      process.nextTick(cb)\n    }\n  })\n}\n\n/**\n * Schedules a function to be called using `setImmediate` or `setTimeout` if\n * `setImmediate` is not available (like in the Edge runtime).\n *\n * @param cb the function to schedule\n */\nexport const scheduleImmediate = (cb: ScheduledFn<void>): void => {\n  if (process.env.NEXT_RUNTIME === 'edge') {\n    setTimeout(cb, 0)\n  } else {\n    setImmediate(cb)\n  }\n}\n\n/**\n * returns a promise than resolves in a future task. There is no guarantee that the task it resolves in\n * will be the next task but if you await it you can at least be sure that the current task is over and\n * most usefully that the entire microtask queue of the current task has been emptied.\n */\nexport function atLeastOneTask() {\n  return new Promise<void>((resolve) => scheduleImmediate(resolve))\n}\n\n/**\n * This utility function is extracted to make it easier to find places where we are doing\n * specific timing tricks to try to schedule work after React has rendered. This is especially\n * important at the moment because Next.js uses the edge builds of React which use setTimeout to\n * schedule work when you might expect that something like setImmediate would do the trick.\n *\n * Long term we should switch to the node versions of React rendering when possible and then\n * update this to use setImmediate rather than setTimeout\n */\nexport function waitAtLeastOneReactRenderTask(): Promise<void> {\n  if (process.env.NEXT_RUNTIME === 'edge') {\n    return new Promise((r) => setTimeout(r, 0))\n  } else {\n    return new Promise((r) => setImmediate(r))\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 { 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 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 { 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 { 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","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","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","import {\n  CachedRouteKind,\n  IncrementalCacheKind,\n  type CachedAppPageValue,\n  type CachedPageValue,\n  type IncrementalResponseCacheEntry,\n  type ResponseCacheEntry,\n} from './types'\n\nimport RenderResult from '../render-result'\nimport { RouteKind } from '../route-kind'\nimport { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants'\n\nexport async function fromResponseCacheEntry(\n  cacheEntry: ResponseCacheEntry\n): Promise<IncrementalResponseCacheEntry> {\n  return {\n    ...cacheEntry,\n    value:\n      cacheEntry.value?.kind === CachedRouteKind.PAGES\n        ? {\n            kind: CachedRouteKind.PAGES,\n            html: await cacheEntry.value.html.toUnchunkedString(true),\n            pageData: cacheEntry.value.pageData,\n            headers: cacheEntry.value.headers,\n            status: cacheEntry.value.status,\n          }\n        : cacheEntry.value?.kind === CachedRouteKind.APP_PAGE\n          ? {\n              kind: CachedRouteKind.APP_PAGE,\n              html: await cacheEntry.value.html.toUnchunkedString(true),\n              postponed: cacheEntry.value.postponed,\n              rscData: cacheEntry.value.rscData,\n              headers: cacheEntry.value.headers,\n              status: cacheEntry.value.status,\n              segmentData: cacheEntry.value.segmentData,\n            }\n          : cacheEntry.value,\n  }\n}\n\nexport async function toResponseCacheEntry(\n  response: IncrementalResponseCacheEntry | null\n): Promise<ResponseCacheEntry | null> {\n  if (!response) return null\n\n  return {\n    isMiss: response.isMiss,\n    isStale: response.isStale,\n    cacheControl: response.cacheControl,\n    isFallback: response.isFallback,\n    value:\n      response.value?.kind === CachedRouteKind.PAGES\n        ? ({\n            kind: CachedRouteKind.PAGES,\n            html: RenderResult.fromStatic(\n              response.value.html,\n              HTML_CONTENT_TYPE_HEADER\n            ),\n            pageData: response.value.pageData,\n            headers: response.value.headers,\n            status: response.value.status,\n          } satisfies CachedPageValue)\n        : response.value?.kind === CachedRouteKind.APP_PAGE\n          ? ({\n              kind: CachedRouteKind.APP_PAGE,\n              html: RenderResult.fromStatic(\n                response.value.html,\n                HTML_CONTENT_TYPE_HEADER\n              ),\n              rscData: response.value.rscData,\n              headers: response.value.headers,\n              status: response.value.status,\n              postponed: response.value.postponed,\n              segmentData: response.value.segmentData,\n            } satisfies CachedAppPageValue)\n          : response.value,\n  }\n}\n\nexport function routeKindToIncrementalCacheKind(\n  routeKind: RouteKind\n): Exclude<IncrementalCacheKind, IncrementalCacheKind.FETCH> {\n  switch (routeKind) {\n    case RouteKind.PAGES:\n      return IncrementalCacheKind.PAGES\n    case RouteKind.APP_PAGE:\n      return IncrementalCacheKind.APP_PAGE\n    case RouteKind.IMAGE:\n      return IncrementalCacheKind.IMAGE\n    case RouteKind.APP_ROUTE:\n      return IncrementalCacheKind.APP_ROUTE\n    case RouteKind.PAGES_API:\n      // Pages Router API routes are not cached in the incremental cache.\n      throw new Error(`Unexpected route kind ${routeKind}`)\n    default:\n      return routeKind satisfies never\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","/**\n * This transforms a URL pathname into a route. It removes any trailing slashes\n * and the `/index` suffix.\n *\n * @param pathname - The URL path that needs to be optimized.\n * @returns - The route\n *\n * @example\n * // returns '/example'\n * toRoute('/example/index/');\n *\n * @example\n * // returns '/example'\n * toRoute('/example/');\n *\n * @example\n * // returns '/'\n * toRoute('/index/');\n *\n * @example\n * // returns '/'\n * toRoute('/');\n */\nexport function toRoute(pathname: string): string {\n  return pathname.replace(/(?:\\/index)?\\/?$/, '') || '/'\n}\n","import type { 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","/**\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","/**\n * Interop between \"export default\" and \"module.exports\".\n */\nexport function interopDefault(mod: any) {\n  return mod.default || mod\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","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 { 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","import '../../build/adapter/setup-node-env.external'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type {\n  InstrumentationOnRequestError,\n  RequestErrorContext,\n} from '../instrumentation/types'\nimport type { ParsedUrlQuery } from 'node:querystring'\nimport type { UrlWithParsedQuery } from 'node:url'\nimport type {\n  PrerenderManifest,\n  RequiredServerFilesManifest,\n} from '../../build'\nimport type { DevRoutesManifest } from '../lib/router-utils/setup-dev-bundler'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { DeepReadonly } from '../../shared/lib/deep-readonly'\nimport {\n  BUILD_ID_FILE,\n  BUILD_MANIFEST,\n  CLIENT_REFERENCE_MANIFEST,\n  DYNAMIC_CSS_MANIFEST,\n  NEXT_FONT_MANIFEST,\n  PREFETCH_HINTS,\n  PRERENDER_MANIFEST,\n  REACT_LOADABLE_MANIFEST,\n  ROUTES_MANIFEST,\n  SERVER_FILES_MANIFEST,\n  SERVER_REFERENCE_MANIFEST,\n  SUBRESOURCE_INTEGRITY_MANIFEST,\n} from '../../shared/lib/constants'\nimport { parseReqUrl } from '../../lib/url'\nimport {\n  normalizeLocalePath,\n  type PathLocale,\n} from '../../shared/lib/i18n/normalize-locale-path'\nimport { isDynamicRoute } from '../../shared/lib/router/utils'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { getServerUtils } from '../server-utils'\nimport { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale'\nimport { getHostname } from '../../shared/lib/get-hostname'\nimport { checkIsOnDemandRevalidate } from '../api-utils'\nimport type { PreviewData } from '../../types'\nimport type { BuildManifest } from '../get-page-files'\nimport type { ReactLoadableManifest } from '../load-components'\nimport type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'\nimport { normalizeDataPath } from '../../shared/lib/page-path/normalize-data-path'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport {\n  addRequestMeta,\n  getRequestMeta,\n  type NextIncomingMessage,\n} from '../request-meta'\nimport { patchSetHeaderWithCookieSupport } from '../lib/patch-set-header'\nimport { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'\nimport { isStaticMetadataRoute } from '../../lib/metadata/is-metadata-route'\nimport { IncrementalCache } from '../lib/incremental-cache'\nimport { initializeCacheHandlers, setCacheHandler } from '../use-cache/handlers'\nimport { interopDefault } from '../app-render/interop-default'\nimport { RouteKind } from '../route-kind'\nimport type { BaseNextRequest } from '../base-http'\nimport type { I18NConfig, NextConfigRuntime } from '../config-shared'\nimport ResponseCache, { type ResponseGenerator } from '../response-cache'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport {\n  RouterServerContextSymbol,\n  routerServerGlobal,\n  type RouterServerContext,\n} from '../lib/router-utils/router-server-context'\nimport { decodePathParams } from '../lib/router-utils/decode-path-params'\nimport { removeTrailingSlash } from '../../shared/lib/router/utils/remove-trailing-slash'\nimport { isInterceptionRouteRewrite } from '../../lib/is-interception-route-rewrite'\n\n/**\n * RouteModuleOptions is the options that are passed to the route module, other\n * route modules should extend this class to add specific options for their\n * route.\n */\nexport interface RouteModuleOptions<\n  D extends RouteDefinition = RouteDefinition,\n  U = unknown,\n> {\n  readonly definition: Readonly<D>\n  readonly userland: Readonly<U>\n  readonly distDir: string\n  readonly relativeProjectDir: string\n}\n\n/**\n * RouteHandlerContext is the base context for a route handler.\n */\nexport interface RouteModuleHandleContext {\n  /**\n   * Any matched parameters for the request. This is only defined for dynamic\n   * routes.\n   */\n  params: Record<string, string | string[] | undefined> | undefined\n}\n\nconst dynamicImportEsmDefault = (id: string) =>\n  import(/* webpackIgnore: true */ /* turbopackIgnore: true */ id).then(\n    (mod) => mod.default || mod\n  )\n\n/**\n * RouteModule is the base class for all route modules. This class should be\n * extended by all route modules.\n */\nexport abstract class RouteModule<\n  D extends RouteDefinition = RouteDefinition,\n  U = unknown,\n> {\n  /**\n   * The userland module. This is the module that is exported from the user's\n   * code. Exposed as a getter so subclasses can override with lazy loading.\n   */\n  protected _userland: Readonly<U>\n\n  get userland(): Readonly<U> {\n    return this._userland\n  }\n\n  /**\n   * The definition of the route.\n   */\n  public readonly definition: Readonly<D>\n\n  /**\n   * The shared modules that are exposed and required for the route module.\n   */\n  public static readonly sharedModules: any\n\n  public isDev: boolean\n  public distDir: string\n  public relativeProjectDir: string\n  public incrementCache?: IncrementalCache\n  public responseCache?: ResponseCache\n\n  constructor({\n    userland,\n    definition,\n    distDir,\n    relativeProjectDir,\n  }: RouteModuleOptions<D, U>) {\n    this._userland = userland\n    this.definition = definition\n    this.isDev = !!process.env.__NEXT_DEV_SERVER\n    this.distDir = distDir\n    this.relativeProjectDir = relativeProjectDir\n  }\n\n  private getRouterServerContext(\n    req: NextIncomingMessage\n  ): RouterServerContext[string] | undefined {\n    const hostname = getRequestMeta(req, 'hostname')\n    const revalidate = getRequestMeta(req, 'revalidate')\n    const render404 = getRequestMeta(req, 'render404')\n    const relativeProjectDir =\n      getRequestMeta(req, 'relativeProjectDir') || this.relativeProjectDir\n    const routerServerContext =\n      routerServerGlobal[RouterServerContextSymbol]?.[relativeProjectDir]\n\n    return {\n      ...routerServerContext,\n      ...(hostname !== undefined ? { hostname } : {}),\n      ...(revalidate !== undefined ? { revalidate } : {}),\n      ...(render404 !== undefined ? { render404 } : {}),\n    }\n  }\n\n  public normalizeUrl(\n    _req: IncomingMessage | BaseNextRequest,\n    _parsedUrl: UrlWithParsedQuery\n  ) {}\n\n  public async instrumentationOnRequestError(\n    req: IncomingMessage | BaseNextRequest,\n    ...args: Parameters<InstrumentationOnRequestError>\n  ) {\n    if (process.env.NEXT_RUNTIME === 'edge') {\n      const { getEdgeInstrumentationModule } = await import('../web/globals')\n      const instrumentation = await getEdgeInstrumentationModule()\n\n      if (instrumentation) {\n        await instrumentation.onRequestError?.(...args)\n      }\n    } else {\n      const { join } = require('node:path') as typeof import('node:path')\n      const absoluteProjectDir = join(\n        /* turbopackIgnore: true */\n        process.cwd(),\n        getRequestMeta(req, 'relativeProjectDir') || this.relativeProjectDir\n      )\n\n      const { instrumentationOnRequestError } = await import(\n        '../lib/router-utils/instrumentation-globals.external.js'\n      )\n\n      return instrumentationOnRequestError(\n        absoluteProjectDir,\n        this.distDir,\n        ...args\n      )\n    }\n  }\n\n  private loadManifests(\n    srcPage: string,\n    projectDir?: string\n  ): {\n    buildId: string\n    buildManifest: BuildManifest\n    fallbackBuildManifest: BuildManifest\n    routesManifest: DeepReadonly<DevRoutesManifest>\n    nextFontManifest: DeepReadonly<NextFontManifest>\n    prerenderManifest: DeepReadonly<PrerenderManifest>\n    serverFilesManifest: DeepReadonly<RequiredServerFilesManifest> | undefined\n    reactLoadableManifest: DeepReadonly<ReactLoadableManifest>\n    subresourceIntegrityManifest: any\n    clientReferenceManifest: any\n    serverActionsManifest: any\n    dynamicCssManifest: any\n    prefetchHintsManifest: Record<string, any> | undefined\n    interceptionRoutePatterns: RegExp[]\n  } {\n    let result\n    if (process.env.NEXT_RUNTIME === 'edge') {\n      const { getEdgePreviewProps } =\n        require('../web/get-edge-preview-props') as typeof import('../web/get-edge-preview-props')\n\n      const maybeJSONParse = (str?: string) =>\n        str ? JSON.parse(str) : undefined\n\n      result = {\n        buildId: process.env.__NEXT_BUILD_ID || '',\n        buildManifest: self.__BUILD_MANIFEST as any,\n        fallbackBuildManifest: {} as any,\n        reactLoadableManifest: maybeJSONParse(self.__REACT_LOADABLE_MANIFEST),\n        nextFontManifest: maybeJSONParse(self.__NEXT_FONT_MANIFEST),\n        prerenderManifest: {\n          routes: {},\n          dynamicRoutes: {},\n          notFoundRoutes: [],\n          version: 4,\n          preview: getEdgePreviewProps(),\n        } as const,\n        routesManifest: {\n          version: 4,\n          caseSensitive: Boolean(process.env.__NEXT_CASE_SENSITIVE_ROUTES),\n          basePath: process.env.__NEXT_BASE_PATH || '',\n          rewrites: (process.env.__NEXT_REWRITES as any) || {\n            beforeFiles: [],\n            afterFiles: [],\n            fallback: [],\n          },\n          redirects: [],\n          headers: [],\n          onMatchHeaders: [],\n          i18n:\n            (process.env.__NEXT_I18N_CONFIG as any as I18NConfig) || undefined,\n          skipProxyUrlNormalize: Boolean(\n            process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE\n          ),\n        },\n        serverFilesManifest: self.__SERVER_FILES_MANIFEST,\n        clientReferenceManifest: self.__RSC_MANIFEST?.[srcPage],\n        serverActionsManifest: maybeJSONParse(self.__RSC_SERVER_MANIFEST),\n        subresourceIntegrityManifest: maybeJSONParse(\n          self.__SUBRESOURCE_INTEGRITY_MANIFEST\n        ),\n        dynamicCssManifest: maybeJSONParse(self.__DYNAMIC_CSS_MANIFEST),\n        // Edge pages are always dynamic so prefetch inlining hints\n        // don't apply. The runtime handles missing hints gracefully.\n        prefetchHintsManifest: undefined,\n        interceptionRoutePatterns: (\n          maybeJSONParse(self.__INTERCEPTION_ROUTE_REWRITE_MANIFEST) ?? []\n        ).map((rewrite: any) => new RegExp(rewrite.regex)),\n      }\n    } else {\n      if (!projectDir) {\n        throw new Error('Invariant: projectDir is required for node runtime')\n      }\n      const { loadManifestFromRelativePath } =\n        require('../load-manifest.external') as typeof import('../load-manifest.external')\n      const normalizedPagePath = normalizePagePath(srcPage)\n\n      const router =\n        this.definition.kind === RouteKind.PAGES ||\n        this.definition.kind === RouteKind.PAGES_API\n          ? 'pages'\n          : 'app'\n\n      const [\n        routesManifest,\n        prerenderManifest,\n        buildManifest,\n        fallbackBuildManifest,\n        reactLoadableManifest,\n        nextFontManifest,\n        clientReferenceManifest,\n        serverActionsManifest,\n        subresourceIntegrityManifest,\n        serverFilesManifest,\n        buildId,\n        dynamicCssManifest,\n        prefetchHintsManifest,\n      ] = [\n        loadManifestFromRelativePath<DevRoutesManifest>({\n          projectDir,\n          distDir: this.distDir,\n          manifest: ROUTES_MANIFEST,\n          shouldCache: !this.isDev,\n        }),\n        loadManifestFromRelativePath<PrerenderManifest>({\n          projectDir,\n          distDir: this.distDir,\n          manifest: PRERENDER_MANIFEST,\n          shouldCache: !this.isDev,\n        }),\n        loadManifestFromRelativePath<BuildManifest>({\n          projectDir,\n          distDir: this.distDir,\n          manifest: BUILD_MANIFEST,\n          shouldCache: !this.isDev,\n        }),\n        srcPage === '/_error'\n          ? loadManifestFromRelativePath<BuildManifest>({\n              projectDir,\n              distDir: this.distDir,\n              manifest: `fallback-${BUILD_MANIFEST}`,\n              shouldCache: !this.isDev,\n              handleMissing: true,\n            })\n          : ({} as BuildManifest),\n        loadManifestFromRelativePath<ReactLoadableManifest>({\n          projectDir,\n          distDir: this.distDir,\n          manifest: process.env.TURBOPACK\n            ? `server/${router === 'app' ? 'app' : 'pages'}${normalizedPagePath}/${REACT_LOADABLE_MANIFEST}`\n            : REACT_LOADABLE_MANIFEST,\n          handleMissing: true,\n          shouldCache: !this.isDev,\n        }),\n        loadManifestFromRelativePath<NextFontManifest>({\n          projectDir,\n          distDir: this.distDir,\n          manifest: `server/${NEXT_FONT_MANIFEST}.json`,\n          shouldCache: !this.isDev,\n        }),\n        router === 'app' && !isStaticMetadataRoute(srcPage)\n          ? loadManifestFromRelativePath({\n              distDir: this.distDir,\n              projectDir,\n              useEval: true,\n              handleMissing: true,\n              manifest: `server/app${srcPage.replace(/%5F/g, '_') + '_' + CLIENT_REFERENCE_MANIFEST}.js`,\n              shouldCache: !this.isDev,\n            })\n          : undefined,\n        router === 'app'\n          ? loadManifestFromRelativePath<any>({\n              distDir: this.distDir,\n              projectDir,\n              manifest: `server/${SERVER_REFERENCE_MANIFEST}.json`,\n              handleMissing: true,\n              shouldCache: !this.isDev,\n            })\n          : {},\n        loadManifestFromRelativePath<Record<string, string>>({\n          projectDir,\n          distDir: this.distDir,\n          manifest: `server/${SUBRESOURCE_INTEGRITY_MANIFEST}.json`,\n          handleMissing: true,\n          shouldCache: !this.isDev,\n        }),\n        this.isDev\n          ? undefined\n          : loadManifestFromRelativePath<RequiredServerFilesManifest>({\n              projectDir,\n              distDir: this.distDir,\n              shouldCache: true,\n              manifest: `${SERVER_FILES_MANIFEST}.json`,\n            }),\n        this.isDev\n          ? 'development'\n          : loadManifestFromRelativePath<any>({\n              projectDir,\n              distDir: this.distDir,\n              manifest: BUILD_ID_FILE,\n              skipParse: true,\n              shouldCache: true,\n            }),\n        loadManifestFromRelativePath<any>({\n          projectDir,\n          distDir: this.distDir,\n          manifest: DYNAMIC_CSS_MANIFEST,\n          shouldCache: !this.isDev,\n          handleMissing: true,\n        }),\n        router === 'app'\n          ? loadManifestFromRelativePath<Record<string, any>>({\n              projectDir,\n              distDir: this.distDir,\n              manifest: `server/${PREFETCH_HINTS}`,\n              shouldCache: !this.isDev,\n              handleMissing: true,\n            })\n          : undefined,\n      ]\n\n      result = {\n        buildId,\n        buildManifest,\n        fallbackBuildManifest,\n        routesManifest,\n        nextFontManifest,\n        prerenderManifest,\n        serverFilesManifest,\n        reactLoadableManifest,\n        clientReferenceManifest: (clientReferenceManifest as any)\n          ?.__RSC_MANIFEST?.[srcPage.replace(/%5F/g, '_')],\n        serverActionsManifest,\n        subresourceIntegrityManifest,\n        dynamicCssManifest,\n        prefetchHintsManifest,\n        interceptionRoutePatterns: routesManifest.rewrites.beforeFiles\n          .filter(isInterceptionRouteRewrite)\n          .map((rewrite) => new RegExp(rewrite.regex)),\n      }\n    }\n\n    return result\n  }\n\n  public async loadCustomCacheHandlers(\n    req: IncomingMessage | BaseNextRequest,\n    nextConfig: NextConfigRuntime\n  ) {\n    if (process.env.NEXT_RUNTIME !== 'edge') {\n      const { cacheMaxMemorySize, cacheHandlers } = 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        const { formatDynamicImportPath } =\n          require('../../lib/format-dynamic-import-path') as typeof import('../../lib/format-dynamic-import-path')\n\n        const { join } = require('node:path') as typeof import('node:path')\n        const absoluteProjectDir = join(\n          /* turbopackIgnore: true */\n          process.cwd(),\n          getRequestMeta(req, 'relativeProjectDir') || this.relativeProjectDir\n        )\n\n        setCacheHandler(\n          kind,\n          interopDefault(\n            await dynamicImportEsmDefault(\n              formatDynamicImportPath(\n                `${absoluteProjectDir}/${this.distDir}`,\n                handler\n              )\n            )\n          )\n        )\n      }\n    }\n  }\n\n  public async getIncrementalCache(\n    req: IncomingMessage | BaseNextRequest,\n    nextConfig: NextConfigRuntime,\n    prerenderManifest: DeepReadonly<PrerenderManifest>,\n    isMinimalMode: boolean\n  ): Promise<IncrementalCache> {\n    if (process.env.NEXT_RUNTIME === 'edge') {\n      return (globalThis as any).__incrementalCache\n    } else {\n      let CacheHandler: any\n      const { cacheHandler } = nextConfig\n\n      if (cacheHandler) {\n        const { formatDynamicImportPath } =\n          require('../../lib/format-dynamic-import-path') as typeof import('../../lib/format-dynamic-import-path')\n\n        CacheHandler = interopDefault(\n          await dynamicImportEsmDefault(\n            formatDynamicImportPath(this.distDir, cacheHandler)\n          )\n        )\n      }\n      const { join } = require('node:path') as typeof import('node:path')\n      const projectDir = join(\n        /* turbopackIgnore: true */\n        process.cwd(),\n        getRequestMeta(req, 'relativeProjectDir') || this.relativeProjectDir\n      )\n\n      await this.loadCustomCacheHandlers(req, nextConfig)\n\n      // incremental-cache is request specific\n      // although can have shared caches in module scope\n      // per-cache handler\n      const incrementalCache = new IncrementalCache({\n        fs: (\n          require('../lib/node-fs-methods') as typeof import('../lib/node-fs-methods')\n        ).nodeFs,\n        dev: this.isDev,\n        requestHeaders: req.headers,\n        allowedRevalidateHeaderKeys:\n          nextConfig.experimental.allowedRevalidateHeaderKeys,\n        minimalMode: isMinimalMode,\n        serverDistDir: `${projectDir}/${this.distDir}/server`,\n        fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix,\n        maxMemoryCacheSize: nextConfig.cacheMaxMemorySize,\n        flushToDisk: !isMinimalMode && nextConfig.experimental.isrFlushToDisk,\n        getPrerenderManifest: () => prerenderManifest,\n        CurCacheHandler: CacheHandler,\n      })\n\n      // we need to expose this on globalThis as the app-render\n      // workStore grabs the incrementalCache from there\n      ;(globalThis as any).__incrementalCache = incrementalCache\n      return incrementalCache\n    }\n  }\n\n  public async onRequestError(\n    req: IncomingMessage | BaseNextRequest,\n    err: unknown,\n    errorContext: RequestErrorContext,\n    silenceLog: boolean,\n    routerServerContext?: RouterServerContext[string]\n  ) {\n    if (!silenceLog) {\n      if (routerServerContext?.logErrorWithOriginalStack) {\n        routerServerContext.logErrorWithOriginalStack(err, 'app-dir')\n      } else {\n        console.error(err)\n      }\n    }\n    await this.instrumentationOnRequestError(\n      req,\n      err,\n      {\n        path: req.url || '/',\n        headers: req.headers,\n        method: req.method || 'GET',\n      },\n      errorContext\n    )\n  }\n\n  /** A more lightweight version of `prepare()` for only retrieving the config on edge */\n  public getNextConfigEdge(req: NextIncomingMessage): {\n    nextConfig: NextConfigRuntime\n    deploymentId: string\n  } {\n    if (process.env.NEXT_RUNTIME !== 'edge') {\n      throw new Error(\n        'Invariant: getNextConfigEdge must only be called in edge runtime'\n      )\n    }\n\n    let serverFilesManifest = self.__SERVER_FILES_MANIFEST as any as\n      | RequiredServerFilesManifest\n      | undefined\n    const routerServerContext = this.getRouterServerContext(req)\n    const nextConfig =\n      routerServerContext?.nextConfig || serverFilesManifest?.config\n\n    if (!nextConfig) {\n      throw new Error(\"Invariant: nextConfig couldn't be loaded\")\n    }\n\n    let deploymentId\n    if (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      deploymentId = process.env.NEXT_DEPLOYMENT_ID\n    } else {\n      deploymentId = nextConfig.deploymentId || ''\n    }\n\n    return { nextConfig, deploymentId }\n  }\n\n  public async prepare(\n    req: IncomingMessage | BaseNextRequest,\n    res: ServerResponse | null,\n    {\n      srcPage,\n      multiZoneDraftMode,\n    }: {\n      srcPage: string\n      multiZoneDraftMode?: boolean\n    }\n  ): Promise<\n    | {\n        buildId: string\n        deploymentId: string\n        clientAssetToken: string\n        locale?: string\n        locales?: readonly string[]\n        defaultLocale?: string\n        query: ParsedUrlQuery\n        originalQuery: ParsedUrlQuery\n        originalPathname: string\n        params?: ParsedUrlQuery\n        parsedUrl: UrlWithParsedQuery\n        previewData: PreviewData\n        pageIsDynamic: boolean\n        isDraftMode: boolean\n        resolvedPathname: string\n        encodedResolvedPathname: string\n        isNextDataRequest: boolean\n        buildManifest: DeepReadonly<BuildManifest>\n        fallbackBuildManifest: DeepReadonly<BuildManifest>\n        nextFontManifest: DeepReadonly<NextFontManifest>\n        serverFilesManifest:\n          | DeepReadonly<RequiredServerFilesManifest>\n          | undefined\n        reactLoadableManifest: DeepReadonly<ReactLoadableManifest>\n        routesManifest: DeepReadonly<DevRoutesManifest>\n        prerenderManifest: DeepReadonly<PrerenderManifest>\n        // we can't pull in the client reference type or it causes issues with\n        // our pre-compiled types\n        clientReferenceManifest?: any\n        serverActionsManifest?: any\n        dynamicCssManifest?: any\n        prefetchHintsManifest?: Record<string, any>\n        subresourceIntegrityManifest?: DeepReadonly<Record<string, string>>\n        isOnDemandRevalidate: boolean\n        revalidateOnlyGenerated: boolean\n        nextConfig: NextConfigRuntime\n        routerServerContext?: RouterServerContext[string]\n        interceptionRoutePatterns?: any\n      }\n    | undefined\n  > {\n    let absoluteProjectDir: string | undefined\n\n    // edge runtime handles loading instrumentation at the edge adapter level\n    if (process.env.NEXT_RUNTIME !== 'edge') {\n      if (res) {\n        patchSetHeaderWithCookieSupport(req, res)\n      }\n\n      const { join, relative } =\n        require('node:path') as typeof import('node:path')\n\n      absoluteProjectDir = join(\n        /* turbopackIgnore: true */\n        process.cwd(),\n        getRequestMeta(req, 'relativeProjectDir') || this.relativeProjectDir\n      )\n\n      const absoluteDistDir = getRequestMeta(req, 'distDir')\n\n      if (absoluteDistDir) {\n        this.distDir = relative(absoluteProjectDir, absoluteDistDir)\n      }\n      const { ensureInstrumentationRegistered } = await import(\n        '../lib/router-utils/instrumentation-globals.external.js'\n      )\n      // ensure instrumentation is registered and pass\n      // onRequestError below. Awaited so any caller of `RouteModule.prepare`\n      // that bypasses `BaseServer.handleRequest` (where this is also awaited\n      // via `prepareImpl`) still observes the instrumentation hook completing\n      // before the userland route handler runs.\n      await ensureInstrumentationRegistered(absoluteProjectDir, this.distDir)\n    }\n    const manifests = this.loadManifests(srcPage, absoluteProjectDir)\n    const { routesManifest, prerenderManifest, serverFilesManifest } = manifests\n\n    const { basePath, i18n, rewrites } = routesManifest\n\n    const routerServerContext = this.getRouterServerContext(req)\n    const nextConfig =\n      routerServerContext?.nextConfig || serverFilesManifest?.config\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    if (!getRequestMeta(req, 'initURL')) {\n      const initUrl = serverFilesManifest?.config.experimental.trustHostHeader\n        ? `${protocol}://${req.headers.host || 'localhost'}${req.url}`\n        : `${protocol}://${routerServerContext?.hostname || 'localhost'}${req.url}`\n\n      addRequestMeta(req, 'initURL', initUrl)\n      addRequestMeta(req, 'initProtocol', protocol)\n    }\n\n    if (basePath) {\n      req.url = removePathPrefix(req.url || '/', basePath)\n    }\n\n    const parsedUrl = parseReqUrl(req.url || '/')\n    addRequestMeta(req, 'initQuery', { ...parsedUrl?.query })\n    // if we couldn't parse the URL we can't continue\n    if (!parsedUrl) {\n      return\n    }\n    let isNextDataRequest = false\n\n    if (pathHasPrefix(parsedUrl.pathname || '/', '/_next/data')) {\n      isNextDataRequest = true\n      parsedUrl.pathname = normalizeDataPath(parsedUrl.pathname || '/')\n    }\n    this.normalizeUrl(req, parsedUrl)\n    let originalPathname = parsedUrl.pathname || '/'\n    const originalQuery = { ...parsedUrl.query }\n    const pageIsDynamic = isDynamicRoute(srcPage)\n\n    let localeResult: PathLocale | undefined\n    let detectedLocale: string | undefined\n\n    if (i18n) {\n      localeResult = normalizeLocalePath(\n        parsedUrl.pathname || '/',\n        i18n.locales\n      )\n\n      if (localeResult.detectedLocale) {\n        req.url = `${localeResult.pathname}${parsedUrl.search}`\n        originalPathname = localeResult.pathname\n\n        if (!detectedLocale) {\n          detectedLocale = localeResult.detectedLocale\n        }\n      }\n    }\n\n    // Normalize the page path for route matching. The srcPage contains the\n    // internal page path (e.g., /app/[slug]/page), but route matchers expect\n    // the pathname format (e.g., /app/[slug]).\n    const normalizedSrcPage = normalizeAppPath(srcPage)\n\n    const serverUtils = getServerUtils({\n      page: normalizedSrcPage,\n      i18n,\n      basePath,\n      rewrites,\n      pageIsDynamic,\n      trailingSlash: process.env.__NEXT_TRAILING_SLASH as any as boolean,\n      caseSensitive: Boolean(routesManifest.caseSensitive),\n    })\n\n    const domainLocale = detectDomainLocale(\n      i18n?.domains,\n      getHostname(parsedUrl, req.headers),\n      detectedLocale\n    )\n\n    if (Boolean(domainLocale)) {\n      addRequestMeta(req, 'isLocaleDomain', Boolean(domainLocale))\n    }\n\n    const defaultLocale =\n      getRequestMeta(req, 'defaultLocale') ||\n      domainLocale?.defaultLocale ||\n      i18n?.defaultLocale\n\n    // Ensure parsedUrl.pathname includes locale before processing\n    // rewrites or they won't match correctly.\n    if (defaultLocale && !detectedLocale) {\n      parsedUrl.pathname = `/${defaultLocale}${parsedUrl.pathname === '/' ? '' : parsedUrl.pathname}`\n    }\n    const locale =\n      getRequestMeta(req, 'locale') || detectedLocale || defaultLocale\n\n    // we apply rewrites against cloned URL so that we don't\n    // modify the original with the rewrite destination\n    const { rewriteParams, rewrittenParsedUrl } = serverUtils.handleRewrites(\n      req,\n      parsedUrl\n    )\n    const rewriteParamKeys = Object.keys(rewriteParams)\n    Object.assign(parsedUrl.query, rewrittenParsedUrl.query)\n\n    // after processing rewrites we want to remove locale\n    // from parsedUrl pathname\n    if (i18n) {\n      parsedUrl.pathname = normalizeLocalePath(\n        parsedUrl.pathname || '/',\n        i18n.locales\n      ).pathname\n\n      rewrittenParsedUrl.pathname = normalizeLocalePath(\n        rewrittenParsedUrl.pathname || '/',\n        i18n.locales\n      ).pathname\n    }\n\n    let params: Record<string, undefined | string | string[]> | undefined =\n      getRequestMeta(req, 'params')\n\n    // attempt parsing from pathname\n    if (!params && serverUtils.dynamicRouteMatcher) {\n      const paramsMatch = serverUtils.dynamicRouteMatcher(\n        normalizeDataPath(\n          rewrittenParsedUrl?.pathname || parsedUrl.pathname || '/'\n        )\n      )\n      const paramsResult = serverUtils.normalizeDynamicRouteParams(\n        paramsMatch || {},\n        true\n      )\n\n      if (paramsResult.hasValidParams) {\n        params = paramsResult.params\n      }\n    }\n\n    // Local \"next start\" expects the routing parsed query values\n    // to not be present in the URL although when deployed proxies\n    // will add query values from resolving the routes to pass to function.\n\n    // TODO: do we want to change expectations for \"next start\"\n    // to include these query values in the URL which affects asPath\n    // but would match deployed behavior, e.g. a rewrite from middleware\n    // that adds a query param would be in asPath as query but locally\n    // it won't be in the asPath but still available in the query object\n    const query = getRequestMeta(req, 'query') || {\n      ...parsedUrl.query,\n    }\n\n    const routeParamKeys = new Set<string>()\n    const combinedParamKeys = []\n\n    // We don't include rewriteParamKeys in the combinedParamKeys\n    // for app router since the searchParams is populated from the\n    // URL so we don't want to strip the rewrite params from the URL\n    // so that searchParams can include them.\n    if (\n      this.definition.kind === RouteKind.PAGES ||\n      this.definition.kind === RouteKind.PAGES_API\n    ) {\n      for (const key of [\n        ...rewriteParamKeys,\n        ...Object.keys(serverUtils.defaultRouteMatches || {}),\n      ]) {\n        // We only want to filter rewrite param keys from the URL\n        // if they are matches from the URL e.g. the key/value matches\n        // before and after applying the rewrites /:path for /hello and\n        // { path: 'hello' } but not for { path: 'another' } and /hello\n        // TODO: we should prefix rewrite param keys the same as we do\n        // for dynamic routes so we can identify them properly\n        const originalValue = Array.isArray(originalQuery[key])\n          ? originalQuery[key].join('')\n          : originalQuery[key]\n\n        const queryValue = Array.isArray(query[key])\n          ? query[key].join('')\n          : query[key]\n\n        if (!(key in originalQuery) || originalValue === queryValue) {\n          combinedParamKeys.push(key)\n        }\n      }\n    }\n\n    serverUtils.normalizeCdnUrl(req, combinedParamKeys)\n    // When Next is not hosted in a single process, upstream proxies will add query values for route params that were used to match the route.\n    // Outside of that environment, there is no reason to do any normalization to honor those query values.\n    if (!routerServerContext?.isWrappedByNextServer) {\n      serverUtils.normalizeQueryParams(query, routeParamKeys)\n    } else {\n      serverUtils.filterInternalQuery(query, [])\n    }\n    serverUtils.filterInternalQuery(originalQuery, combinedParamKeys)\n\n    if (pageIsDynamic) {\n      const queryResult = serverUtils.normalizeDynamicRouteParams(query, true)\n\n      const paramsResult = serverUtils.normalizeDynamicRouteParams(\n        params || {},\n        true\n      )\n\n      let paramsToInterpolate: ParsedUrlQuery\n\n      if (\n        // if both query and params are valid but one\n        // provided more information and the query params\n        // were nxtP prefixed rely on that one\n        query &&\n        params &&\n        paramsResult.hasValidParams &&\n        queryResult.hasValidParams &&\n        routeParamKeys.size > 0 &&\n        Object.keys(paramsResult.params).length <=\n          Object.keys(queryResult.params).length\n      ) {\n        paramsToInterpolate = queryResult.params\n        params = Object.assign(queryResult.params)\n      } else {\n        paramsToInterpolate =\n          paramsResult.hasValidParams && params\n            ? params\n            : queryResult.hasValidParams\n              ? query\n              : {}\n      }\n\n      req.url = serverUtils.interpolateDynamicPath(\n        req.url || '/',\n        paramsToInterpolate\n      )\n      parsedUrl.pathname = serverUtils.interpolateDynamicPath(\n        parsedUrl.pathname || '/',\n        paramsToInterpolate\n      )\n      originalPathname = serverUtils.interpolateDynamicPath(\n        originalPathname,\n        paramsToInterpolate\n      )\n\n      // try pulling from query if valid\n      if (!params) {\n        if (queryResult.hasValidParams) {\n          params = Object.assign({}, queryResult.params)\n\n          // If we pulled from query remove it so it's\n          // only in params\n          for (const key in serverUtils.defaultRouteMatches) {\n            delete query[key]\n          }\n        } else {\n          // use final params from URL matching\n          const paramsMatch = serverUtils.dynamicRouteMatcher?.(\n            normalizeDataPath(\n              localeResult?.pathname || parsedUrl.pathname || '/'\n            )\n          )\n          // we don't normalize these as they are allowed to be\n          // the literal slug matches here e.g. /blog/[slug]\n          // actually being requested\n          if (paramsMatch) {\n            params = Object.assign({}, paramsMatch)\n          }\n        }\n      }\n\n      // When partial nxtP* params are provided (e.g. background\n      // revalidation for intermediate PPR shells), both\n      // normalizeDynamicRouteParams calls above fail because not all\n      // route params are present. Merge the normalized query params\n      // (from nxtP*) into the current params to override placeholders\n      // with concrete values.\n      if (\n        params &&\n        routeParamKeys.size > 0 &&\n        !paramsResult.hasValidParams &&\n        !queryResult.hasValidParams\n      ) {\n        for (const key of routeParamKeys) {\n          if (query[key] !== undefined) {\n            params[key] = query[key]\n          }\n        }\n        addRequestMeta(req, 'resolvedRouteParamKeys', routeParamKeys)\n      }\n    }\n\n    // Remove any normalized params from the query if they\n    // weren't present as non-prefixed query key e.g.\n    // ?search=1&nxtPsearch=hello we don't delete search\n    for (const key of routeParamKeys) {\n      if (!(key in originalQuery)) {\n        delete query[key]\n        // handle the case where there's collision and we\n        // normalized nxtPid=123 -> id=123 but user also\n        // sends id=456 as separate key\n      } else if (\n        originalQuery[key] &&\n        query[key] &&\n        originalQuery[key] !== query[key]\n      ) {\n        query[key] = originalQuery[key]\n      }\n    }\n\n    const { isOnDemandRevalidate, revalidateOnlyGenerated } =\n      checkIsOnDemandRevalidate(req.headers, prerenderManifest.preview)\n\n    let isDraftMode = false\n    let previewData: PreviewData\n\n    // preview data relies on non-edge utils\n    if (process.env.NEXT_RUNTIME !== 'edge' && res) {\n      const { tryGetPreviewData } =\n        require('../api-utils/node/try-get-preview-data') as typeof import('../api-utils/node/try-get-preview-data')\n\n      previewData = tryGetPreviewData(\n        req,\n        res,\n        prerenderManifest.preview,\n        Boolean(multiZoneDraftMode)\n      )\n      isDraftMode = previewData !== false\n    }\n\n    if (!nextConfig) {\n      throw new Error(\"Invariant: nextConfig couldn't be loaded\")\n    }\n\n    if (process.env.NEXT_RUNTIME !== 'edge') {\n      const { installProcessErrorHandlers } =\n        require('../node-environment-extensions/process-error-handlers') as typeof import('../node-environment-extensions/process-error-handlers')\n\n      installProcessErrorHandlers(\n        Boolean(\n          nextConfig.experimental.removeUncaughtErrorAndRejectionListeners\n        )\n      )\n    }\n\n    let resolvedPathname = normalizedSrcPage\n    if (isDynamicRoute(resolvedPathname) && params) {\n      resolvedPathname = serverUtils.interpolateDynamicPath(\n        resolvedPathname,\n        params\n      )\n    }\n\n    if (resolvedPathname === '/index') {\n      resolvedPathname = '/'\n    }\n\n    if (\n      res &&\n      Boolean(req.headers['x-nextjs-data']) &&\n      (!res.statusCode || res.statusCode === 200)\n    ) {\n      res.setHeader(\n        'x-nextjs-matched-path',\n        removeTrailingSlash(`${locale ? `/${locale}` : ''}${normalizedSrcPage}`)\n      )\n    }\n    const encodedResolvedPathname = resolvedPathname\n\n    // we decode for cache key/manifest usage encoded is\n    // for URL building\n    try {\n      resolvedPathname = decodePathParams(resolvedPathname)\n    } catch (_) {}\n\n    resolvedPathname = removeTrailingSlash(resolvedPathname)\n    addRequestMeta(req, 'resolvedPathname', resolvedPathname)\n\n    let deploymentId\n    if (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      deploymentId = process.env.NEXT_DEPLOYMENT_ID\n    } else {\n      deploymentId = nextConfig.deploymentId || ''\n    }\n\n    return {\n      query,\n      originalQuery,\n      originalPathname,\n      params,\n      parsedUrl,\n      locale,\n      isNextDataRequest,\n      locales: i18n?.locales,\n      defaultLocale,\n      isDraftMode,\n      previewData,\n      pageIsDynamic,\n      resolvedPathname,\n      encodedResolvedPathname,\n      isOnDemandRevalidate,\n      revalidateOnlyGenerated,\n      ...manifests,\n      // loadManifest returns a readonly object, but we don't want to propagate that throughout the\n      // whole codebase (for now)\n      nextConfig:\n        nextConfig satisfies DeepReadonly<NextConfigRuntime> as NextConfigRuntime,\n      routerServerContext,\n      deploymentId,\n      clientAssetToken: nextConfig.supportsImmutableAssets ? '' : deploymentId,\n    }\n  }\n\n  public getResponseCache(req: IncomingMessage | BaseNextRequest) {\n    if (!this.responseCache) {\n      const minimalMode = getRequestMeta(req, 'minimalMode') ?? false\n      this.responseCache = new ResponseCache(minimalMode)\n    }\n    return this.responseCache\n  }\n\n  public async handleResponse({\n    req,\n    nextConfig,\n    cacheKey,\n    routeKind,\n    isFallback,\n    prerenderManifest,\n    isRoutePPREnabled,\n    isOnDemandRevalidate,\n    revalidateOnlyGenerated,\n    responseGenerator,\n    waitUntil,\n    isMinimalMode,\n  }: {\n    req: IncomingMessage | BaseNextRequest\n    nextConfig: NextConfigRuntime\n    cacheKey: string | null\n    routeKind: RouteKind\n    isFallback?: boolean\n    prerenderManifest: DeepReadonly<PrerenderManifest>\n    isRoutePPREnabled?: boolean\n    isOnDemandRevalidate?: boolean\n    revalidateOnlyGenerated?: boolean\n    responseGenerator: ResponseGenerator\n    waitUntil?: (prom: Promise<any>) => void\n    isMinimalMode: boolean\n  }) {\n    const responseCache = this.getResponseCache(req)\n    const cacheEntry = await responseCache.get(cacheKey, responseGenerator, {\n      routeKind,\n      isFallback,\n      isRoutePPREnabled,\n      isOnDemandRevalidate,\n      // A Next.js Segment Cache prefetch uses the `Next-Router-Prefetch`\n      // header (surfaced as the `isPrefetchRSCRequest` request meta), not the\n      // standard browser `purpose: prefetch` header. Recognize both so the\n      // response cache treats segment prefetches as prefetches — most\n      // importantly, so a prefetch that misses serves a fallback shell rather\n      // than joining an in-flight background (concrete) revalidation.\n      isPrefetch:\n        req.headers.purpose === 'prefetch' ||\n        getRequestMeta(req, 'isPrefetchRSCRequest') === true,\n      // Use x-invocation-id header to scope the in-memory cache to a single\n      // revalidation request in minimal mode.\n      invocationID: req.headers['x-invocation-id'] as string | undefined,\n      incrementalCache: await this.getIncrementalCache(\n        req,\n        nextConfig,\n        prerenderManifest,\n        isMinimalMode\n      ),\n      waitUntil,\n    })\n\n    if (!cacheEntry) {\n      if (\n        cacheKey &&\n        // revalidate only generated can bail even if cacheKey is provided\n        !(isOnDemandRevalidate && revalidateOnlyGenerated)\n      ) {\n        // A cache entry might not be generated if a response is written\n        // in `getInitialProps` or `getServerSideProps`, but those shouldn't\n        // have a cache key. If we do have a cache key but we don't end up\n        // with a cache entry, then either Next.js or the application has a\n        // bug that needs fixing.\n        throw new Error('invariant: cache entry required but not generated')\n      }\n    }\n    return cacheEntry\n  }\n}\n","export function isAppRouteRoute(route: string): boolean {\n  return route.endsWith('/route')\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 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 { 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 { 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 escapePathDelimiters from '../../../shared/lib/router/utils/escape-path-delimiters'\nimport { DecodeError } from '../../../shared/lib/utils'\n\n/**\n * We only encode path delimiters for path segments from\n * getStaticPaths so we need to attempt decoding the URL\n * to match against and only escape the path delimiters\n * this allows non-ascii values to be handled e.g.\n * Japanese characters.\n * */\nfunction decodePathParams(pathname: string): string {\n  // TODO: investigate adding this handling for non-SSG\n  // pages so non-ascii names also work there.\n  return pathname\n    .split('/')\n    .map((seg) => {\n      try {\n        seg = escapePathDelimiters(decodeURIComponent(seg), true)\n      } catch (_) {\n        // An improperly encoded URL was provided\n        throw new DecodeError('Failed to decode path param(s).')\n      }\n      return seg\n    })\n    .join('/')\n}\n\nexport { decodePathParams }\n","// escape delimiters used by path-to-regexp\nexport default function escapePathDelimiters(\n  segment: string,\n  escapeEncoded?: boolean\n): string {\n  return segment.replace(\n    new RegExp(`([/#?\\\\\\\\]${escapeEncoded ? '|%(2f|23|3f|5c)' : ''})`, 'gi'),\n    (char: string) => encodeURIComponent(char)\n  )\n}\n","import type { IncomingHttpHeaders } from 'http'\nimport type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'\nimport type { ResponseCookies } from '../web/spec-extension/cookies'\n\nimport {\n  COOKIE_NAME_PRERENDER_BYPASS,\n  checkIsOnDemandRevalidate,\n} from '../api-utils'\nimport type { __ApiPreviewProps } from '../api-utils'\n\nexport class DraftModeProvider {\n  /**\n   * @internal - this declaration is stripped via `tsc --stripInternal`\n   */\n  private _isEnabled: boolean\n\n  /**\n   * @internal - this declaration is stripped via `tsc --stripInternal`\n   */\n  private readonly _previewModeId: string | undefined\n\n  /**\n   * @internal - this declaration is stripped via `tsc --stripInternal`\n   */\n  private readonly _mutableCookies: ResponseCookies\n\n  constructor(\n    previewProps: __ApiPreviewProps | undefined,\n    headers: Headers | IncomingHttpHeaders,\n    cookies: ReadonlyRequestCookies,\n    mutableCookies: ResponseCookies\n  ) {\n    // The logic for draftMode() is very similar to tryGetPreviewData()\n    // but Draft Mode does not have any data associated with it.\n    const isOnDemandRevalidate =\n      previewProps &&\n      checkIsOnDemandRevalidate(headers, previewProps).isOnDemandRevalidate\n\n    const cookieValue = cookies.get(COOKIE_NAME_PRERENDER_BYPASS)?.value\n\n    this._isEnabled = Boolean(\n      !isOnDemandRevalidate &&\n        cookieValue &&\n        previewProps &&\n        (cookieValue === previewProps.previewModeId ||\n          // In dev mode, the cookie can be actual hash value preview id but the preview props can still be `development-id`.\n          (process.env.NODE_ENV !== 'production' &&\n            previewProps.previewModeId === 'development-id'))\n    )\n\n    this._previewModeId = previewProps?.previewModeId\n    this._mutableCookies = mutableCookies\n  }\n\n  get isEnabled() {\n    return this._isEnabled\n  }\n\n  enable() {\n    if (!this._previewModeId) {\n      throw new Error(\n        'Invariant: previewProps missing previewModeId this should never happen'\n      )\n    }\n\n    this._mutableCookies.set({\n      name: COOKIE_NAME_PRERENDER_BYPASS,\n      value: this._previewModeId,\n      httpOnly: true,\n      sameSite: process.env.NODE_ENV !== 'development' ? 'none' : 'lax',\n      secure: process.env.NODE_ENV !== 'development',\n      path: '/',\n    })\n\n    this._isEnabled = true\n  }\n\n  disable() {\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    this._mutableCookies.set({\n      name: COOKIE_NAME_PRERENDER_BYPASS,\n      value: '',\n      httpOnly: true,\n      sameSite: process.env.NODE_ENV !== 'development' ? 'none' : 'lax',\n      secure: process.env.NODE_ENV !== 'development',\n      path: '/',\n      expires: new Date(0),\n    })\n\n    this._isEnabled = false\n  }\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","import type { WorkStore } from './app-render/work-async-storage.external'\nimport type { IncrementalCache } from './lib/incremental-cache'\nimport { getCacheHandlers } from './use-cache/handlers'\n\n/** Run a callback, and execute any *new* revalidations added during its runtime. */\nexport async function withExecuteRevalidates<T>(\n  store: WorkStore | undefined,\n  callback: () => Promise<T>\n): Promise<T> {\n  if (!store) {\n    return callback()\n  }\n  // If we executed any revalidates during the request, then we don't want to execute them again.\n  // save the state so we can check if anything changed after we're done running callbacks.\n  const savedRevalidationState = cloneRevalidationState(store)\n  try {\n    return await callback()\n  } finally {\n    // Check if we have any new revalidates, and if so, wait until they are all resolved.\n    const newRevalidates = diffRevalidationState(\n      savedRevalidationState,\n      cloneRevalidationState(store)\n    )\n    await executeRevalidates(store, newRevalidates)\n  }\n}\n\ntype RevalidationState = Required<\n  Pick<\n    WorkStore,\n    'pendingRevalidatedTags' | 'pendingRevalidates' | 'pendingRevalidateWrites'\n  >\n>\n\nfunction cloneRevalidationState(store: WorkStore): RevalidationState {\n  return {\n    pendingRevalidatedTags: store.pendingRevalidatedTags\n      ? [...store.pendingRevalidatedTags]\n      : [],\n    pendingRevalidates: { ...store.pendingRevalidates },\n    pendingRevalidateWrites: store.pendingRevalidateWrites\n      ? [...store.pendingRevalidateWrites]\n      : [],\n  }\n}\n\nfunction diffRevalidationState(\n  prev: RevalidationState,\n  curr: RevalidationState\n): RevalidationState {\n  const prevTagsWithProfile = new Set(\n    prev.pendingRevalidatedTags.map((item) => {\n      const profileKey =\n        typeof item.profile === 'object'\n          ? JSON.stringify(item.profile)\n          : item.profile || ''\n      return `${item.tag}:${profileKey}`\n    })\n  )\n  const prevRevalidateWrites = new Set(prev.pendingRevalidateWrites)\n  return {\n    pendingRevalidatedTags: curr.pendingRevalidatedTags.filter((item) => {\n      const profileKey =\n        typeof item.profile === 'object'\n          ? JSON.stringify(item.profile)\n          : item.profile || ''\n      return !prevTagsWithProfile.has(`${item.tag}:${profileKey}`)\n    }),\n    pendingRevalidates: Object.fromEntries(\n      Object.entries(curr.pendingRevalidates).filter(\n        ([key]) => !(key in prev.pendingRevalidates)\n      )\n    ),\n    pendingRevalidateWrites: curr.pendingRevalidateWrites.filter(\n      (promise) => !prevRevalidateWrites.has(promise)\n    ),\n  }\n}\n\nasync function revalidateTags(\n  tagsWithProfile: Array<{\n    tag: string\n    profile?: string | { expire?: number }\n  }>,\n  incrementalCache: IncrementalCache | undefined,\n  workStore?: WorkStore\n): Promise<void> {\n  if (tagsWithProfile.length === 0) {\n    return\n  }\n\n  const handlers = getCacheHandlers()\n  const promises: Promise<void>[] = []\n\n  // Group tags by profile for batch processing\n  const tagsByProfile = new Map<\n    | string\n    | { stale?: number; revalidate?: number; expire?: number }\n    | undefined,\n    string[]\n  >()\n\n  for (const item of tagsWithProfile) {\n    const profile = item.profile\n    // Find existing profile by comparing values\n    let existingKey = undefined\n    for (const [key] of tagsByProfile) {\n      if (\n        typeof key === 'string' &&\n        typeof profile === 'string' &&\n        key === profile\n      ) {\n        existingKey = key\n        break\n      }\n      if (\n        typeof key === 'object' &&\n        typeof profile === 'object' &&\n        JSON.stringify(key) === JSON.stringify(profile)\n      ) {\n        existingKey = key\n        break\n      }\n      if (key === profile) {\n        existingKey = key\n        break\n      }\n    }\n\n    const profileKey = existingKey || profile\n    if (!tagsByProfile.has(profileKey)) {\n      tagsByProfile.set(profileKey, [])\n    }\n    tagsByProfile.get(profileKey)!.push(item.tag)\n  }\n\n  // Process each profile group\n  for (const [profile, tagsForProfile] of tagsByProfile) {\n    // Look up the cache profile from workStore if available\n    let durations: { expire?: number } | undefined\n\n    if (profile) {\n      let cacheLife:\n        | { stale?: number; revalidate?: number; expire?: number }\n        | undefined\n\n      if (typeof profile === 'object') {\n        // Profile is already a cacheLife configuration object\n        cacheLife = profile\n      } else if (typeof profile === 'string') {\n        // Profile is a string key, look it up in workStore\n        cacheLife = workStore?.cacheLifeProfiles[profile]\n\n        if (!cacheLife) {\n          throw new Error(\n            `Invalid profile provided \"${profile}\" must be configured under cacheLife in next.config or be \"max\"`\n          )\n        }\n      }\n\n      if (cacheLife) {\n        durations = {\n          expire: cacheLife.expire,\n        }\n      }\n    }\n    // If profile is not found and not 'max', durations will be undefined\n    // which will trigger immediate expiration in the cache handler\n\n    for (const handler of handlers || []) {\n      if (profile) {\n        promises.push(handler.updateTags?.(tagsForProfile, durations))\n      } else {\n        promises.push(handler.updateTags?.(tagsForProfile))\n      }\n    }\n\n    if (incrementalCache) {\n      promises.push(incrementalCache.revalidateTag(tagsForProfile, durations))\n    }\n  }\n\n  await Promise.all(promises)\n}\n\nexport function executeRevalidates(\n  workStore: WorkStore,\n  state?: RevalidationState\n): false | Promise<void> {\n  const promises: Promise<unknown>[] = []\n\n  const pendingRevalidatedTags =\n    state?.pendingRevalidatedTags ?? workStore.pendingRevalidatedTags ?? []\n\n  if (pendingRevalidatedTags.length > 0) {\n    promises.push(\n      revalidateTags(\n        pendingRevalidatedTags,\n        workStore.incrementalCache,\n        workStore\n      )\n    )\n  }\n\n  const pendingRevalidates = Object.values(\n    state?.pendingRevalidates ?? workStore.pendingRevalidates ?? {}\n  )\n\n  promises.push(...pendingRevalidates)\n\n  const pendingRevalidateWrites =\n    state?.pendingRevalidateWrites ?? workStore.pendingRevalidateWrites ?? []\n\n  promises.push(...pendingRevalidateWrites)\n\n  if (promises.length === 0) {\n    return false\n  }\n\n  return Promise.all(promises).then(() => undefined)\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 PromiseQueue from 'next/dist/compiled/p-queue'\nimport type { RequestLifecycleOpts } from '../base-server'\nimport type { AfterCallback, AfterTask } from './after'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { isThenable } from '../../shared/lib/is-thenable'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { withExecuteRevalidates } from '../revalidation-utils'\nimport { bindSnapshot } from '../app-render/async-local-storage'\nimport type { WorkUnitStore } from '../app-render/work-unit-async-storage.external'\nimport { afterTaskAsyncStorage } from '../app-render/after-task-async-storage.external'\nimport { scheduleImmediate } from '../../lib/scheduler'\n\nexport type AfterContextOpts = {\n  waitUntil: RequestLifecycleOpts['waitUntil'] | undefined\n  onClose: RequestLifecycleOpts['onClose']\n  onTaskError: RequestLifecycleOpts['onAfterTaskError'] | undefined\n}\n\nexport class AfterContext {\n  private waitUntil: RequestLifecycleOpts['waitUntil'] | undefined\n  private onClose: RequestLifecycleOpts['onClose']\n  private onTaskError: RequestLifecycleOpts['onAfterTaskError'] | undefined\n\n  private isRequestClosed: boolean = false\n  private initialOnCloseError: null | { error: unknown } = null\n\n  private runCallbacksOnClosePromise: Promise<void> | undefined\n  private callbackQueue: PromiseQueue\n  private workUnitStores = new Set<WorkUnitStore>()\n\n  constructor({ waitUntil, onClose, onTaskError }: AfterContextOpts) {\n    this.waitUntil = waitUntil\n    this.onClose = onClose\n    this.onTaskError = onTaskError\n\n    this.callbackQueue = new PromiseQueue()\n    this.callbackQueue.pause()\n\n    try {\n      onClose(() => {\n        this.isRequestClosed = true\n\n        // TODO(after): it's not ideal that we'll only switch the `phase` of a WorkUnitStore\n        // if `after()` was called inside it. We should probably track this whenever a store is created\n        for (const workUnitStore of this.workUnitStores) {\n          workUnitStore.phase = 'after'\n        }\n      })\n    } catch (err) {\n      // If onClose is broken, report errors lazily, when after() is called.\n      this.initialOnCloseError = { error: err }\n    }\n  }\n\n  public after(task: AfterTask, workUnitStore: WorkUnitStore): void {\n    if (this.initialOnCloseError) {\n      throw new InvariantError(\n        `An onClose call failed, which means after() can't work correctly.`,\n        { cause: this.initialOnCloseError.error }\n      )\n    }\n\n    // Save the workUnitStore so we can switch its phase later.\n    this.workUnitStores.add(workUnitStore)\n\n    if (isThenable(task)) {\n      this.addThenable(task)\n    } else if (typeof task === 'function') {\n      // TODO(after): implement tracing\n      this.addCallback(task, workUnitStore)\n    } else {\n      throw new Error('`after()`: Argument must be a promise or a function')\n    }\n  }\n\n  private addThenable(thenable: PromiseLike<any>) {\n    if (!this.waitUntil) {\n      errorWaitUntilNotAvailable()\n    }\n    this.waitUntil(\n      new Promise<void>((resolve) => {\n        thenable.then(\n          () => {\n            resolve()\n          },\n          (error) => {\n            resolve()\n            this.reportTaskError('promise', error)\n          }\n        )\n      })\n    )\n  }\n\n  private addCallback(callback: AfterCallback, workUnitStore: WorkUnitStore) {\n    // if something is wrong, throw synchronously, bubbling up to the `after` callsite.\n    if (!this.waitUntil) {\n      errorWaitUntilNotAvailable()\n    }\n\n    const afterTaskStore = afterTaskAsyncStorage.getStore()\n\n    // This is used for checking if request APIs can be called inside `after`.\n    // Note that we need to check the phase in which the *topmost* `after` was called (which should be \"action\"),\n    // not the current phase (which might be \"after\" if we're in a nested after).\n    // Otherwise, we might allow `after(() => headers())`, but not `after(() => after(() => headers()))`.\n    const rootTaskSpawnPhase = afterTaskStore\n      ? afterTaskStore.rootTaskSpawnPhase // nested after\n      : workUnitStore.phase // topmost after\n\n    // this should only happen once.\n    if (!this.runCallbacksOnClosePromise) {\n      this.runCallbacksOnClosePromise = this.runCallbacksOnClose()\n      this.waitUntil(this.runCallbacksOnClosePromise)\n    }\n\n    // Bind the callback to the current execution context (i.e. preserve all currently available ALS-es).\n    // We do this because we want all of these to be equivalent in every regard except timing:\n    //   after(() => x())\n    //   after(x())\n    //   await x()\n    const wrappedCallback = bindSnapshot(\n      // WARNING: Don't make this a named function. It must be anonymous.\n      // See: https://github.com/facebook/react/pull/34911\n      async () => {\n        try {\n          await afterTaskAsyncStorage.run({ rootTaskSpawnPhase }, () =>\n            callback()\n          )\n        } catch (error) {\n          this.reportTaskError('function', error)\n        }\n      }\n    )\n\n    this.callbackQueue.add(wrappedCallback)\n  }\n\n  private async runCallbacksOnClose() {\n    if (!this.isRequestClosed) {\n      await new Promise<void>((resolve) => this.onClose(resolve))\n    } else {\n      // The request is already closed.\n      // Avoid running the callbacks too quickly to prevent userspace from\n      // e.g. relying on `after` being microtasky somewhere.\n      await new Promise<void>((resolve) => scheduleImmediate(resolve))\n    }\n    return this.runCallbacks()\n  }\n\n  private async runCallbacks(): Promise<void> {\n    if (this.callbackQueue.size === 0) return\n\n    const workStore = workAsyncStorage.getStore()\n    if (!workStore) {\n      throw new InvariantError('Missing workStore in AfterContext.runCallbacks')\n    }\n\n    return withExecuteRevalidates(workStore, () => {\n      this.callbackQueue.start()\n      return this.callbackQueue.onIdle()\n    })\n  }\n\n  private reportTaskError(taskKind: 'promise' | 'function', error: unknown) {\n    // TODO(after): this is fine for now, but will need better intergration with our error reporting.\n    // TODO(after): should we log this if we have a onTaskError callback?\n    console.error(\n      taskKind === 'promise'\n        ? `A promise passed to \\`after()\\` rejected:`\n        : `An error occurred in a function passed to \\`after()\\`:`,\n      error\n    )\n    if (this.onTaskError) {\n      // this is very defensive, but we really don't want anything to blow up in an error handler\n      try {\n        this.onTaskError?.(error)\n      } catch (handlerError) {\n        console.error(\n          new InvariantError(\n            '`onTaskError` threw while handling an error thrown from an `after` task',\n            {\n              cause: handlerError,\n            }\n          )\n        )\n      }\n    }\n  }\n}\n\nfunction errorWaitUntilNotAvailable(): never {\n  throw new Error(\n    '`after()` will not work correctly, because `waitUntil` is not available in the current environment.'\n  )\n}\n","/**\n * Check to see if a value is Thenable.\n *\n * @param promise the maybe-thenable value\n * @returns true if the value is thenable\n */\nexport function isThenable<T = unknown>(\n  promise: Promise<T> | T\n): promise is Promise<T> {\n  return (\n    promise !== null &&\n    typeof promise === 'object' &&\n    'then' in promise &&\n    typeof promise.then === 'function'\n  )\n}\n","export type LazyResult<TValue> = PromiseLike<TValue> & { value?: TValue }\nexport type ResolvedLazyResult<TValue> = PromiseLike<TValue> & { value: TValue }\n\n/**\n * Calls the given function only when the returned promise-like object is\n * awaited. Afterwards, it provides the resolved value synchronously as `value`\n * property.\n */\nexport function createLazyResult<TValue>(\n  fn: () => Promise<TValue> | TValue\n): LazyResult<TValue> {\n  let pendingResult: Promise<TValue> | undefined\n\n  const result: LazyResult<TValue> = {\n    then(onfulfilled, onrejected) {\n      if (!pendingResult) {\n        pendingResult = Promise.resolve(fn())\n      }\n\n      pendingResult\n        .then((value) => {\n          result.value = value\n        })\n        .catch(() => {\n          // The externally awaited result will be rejected via `onrejected`. We\n          // don't need to handle it here. But we do want to avoid an unhandled\n          // rejection.\n        })\n\n      return pendingResult.then(onfulfilled, onrejected)\n    },\n  }\n\n  return result\n}\n\nexport function isResolvedLazyResult<TValue>(\n  result: LazyResult<TValue>\n): result is ResolvedLazyResult<TValue> {\n  return result.hasOwnProperty('value')\n}\n","/**\n * List of valid HTTP methods that can be implemented by Next.js's Custom App\n * Routes.\n */\nexport const HTTP_METHODS = [\n  'GET',\n  'HEAD',\n  'OPTIONS',\n  'POST',\n  'PUT',\n  'DELETE',\n  'PATCH',\n] as const\n\n/**\n * A type representing the valid HTTP methods that can be implemented by\n * Next.js's Custom App Routes.\n */\nexport type HTTP_METHOD = (typeof HTTP_METHODS)[number]\n\n/**\n * Checks to see if the passed string is an HTTP method. Note that this is case\n * sensitive.\n *\n * @param maybeMethod the string that may be an HTTP method\n * @returns true if the string is an HTTP method\n */\nexport function isHTTPMethod(maybeMethod: string): maybeMethod is HTTP_METHOD {\n  return HTTP_METHODS.includes(maybeMethod as HTTP_METHOD)\n}\n","/**\n * Percent-encode every character other than horizontal tab and printable ASCII\n * so a value can be safely serialized into an HTTP header.\n *\n * Node's `validateHeaderValue` and `fetch`'s ByteString conversion accept\n * different character ranges. Restricting values to `\\t\\x20-\\x7e` produces a\n * conservative representation that both can serialize. Characters outside a\n * transport's accepted range (Hebrew, Arabic, Chinese, emoji, …) would\n * otherwise throw `ERR_INVALID_CHAR` or a `TypeError`, which crashes ISR or\n * fails a cache read on every affected request.\n *\n * Cache tags are encoded at the public boundaries — tag construction\n * (`getImplicitTags`, `validateTags`) and invalidation input\n * (`revalidatePath`, `revalidateTag`, `updateTag`) — so storage, comparison,\n * and the wire all see the same canonical form.\n *\n * The class is narrower than either transport accepts. Everything inside it\n * passes through byte-for-byte, including `,`, `/`, `%`, `[`, `]`, `_`, `-` and\n * `\\t`, which preserves the comma-separated header format and the\n * dynamic-segment markers in derived tags (`_N_T_/[slug]/page`).\n *\n * Properties:\n * - Fast-path: input that already fits the class is returned unchanged. This\n *   makes the encoder idempotent on already-encoded `%xx` sequences.\n * - Matches *runs* of out-of-class code units so surrogate pairs (e.g. an\n *   emoji) are handed to `encodeURIComponent` as a complete code point — a\n *   per-code-unit regex would split the pair and throw `URIError`.\n */\nconst OUT_OF_CLASS_CHAR = /[^\\t\\x20-\\x7e]/\nconst OUT_OF_CLASS_RUN = /[^\\t\\x20-\\x7e]+/g\n\nexport function encodeHeaderSafe(value: string): string {\n  return OUT_OF_CLASS_CHAR.test(value)\n    ? value.replace(OUT_OF_CLASS_RUN, (run) => encodeURIComponent(run))\n    : value\n}\n","import { NEXT_CACHE_IMPLICIT_TAG_ID } from '../../lib/constants'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport { getCacheHandlerEntries } from '../use-cache/handlers'\nimport { encodeHeaderSafe } from './encode-header-safe'\nimport { createLazyResult, type LazyResult } from './lazy-result'\n\nexport interface ImplicitTags {\n  /**\n   * For legacy usage, the implicit tags are passed to the incremental cache\n   * handler in `get` calls.\n   */\n  readonly tags: string[]\n\n  /**\n   * Modern cache handlers don't receive implicit tags. Instead, the implicit\n   * tags' expirations are stored in the work unit store, and used to compare\n   * with a cache entry's timestamp.\n   *\n   * Note: This map contains lazy results so that we can evaluate them when the\n   * first cache entry is read. It allows us to skip fetching the expiration\n   * values if no caches are read at all.\n   */\n  readonly expirationsByCacheKind: Map<string, LazyResult<number>>\n}\n\nconst getDerivedTags = (pathname: string): string[] => {\n  const derivedTags: string[] = [`/layout`]\n\n  // we automatically add the current path segments as tags\n  // for revalidatePath handling\n  if (pathname.startsWith('/')) {\n    let end = pathname.indexOf('/', 1)\n\n    while (true) {\n      if (end === -1) {\n        end = pathname.length\n      }\n\n      let curPathname = pathname.slice(0, end)\n      if (curPathname) {\n        // all derived tags other than the page are layout tags\n        if (!curPathname.endsWith('/page') && !curPathname.endsWith('/route')) {\n          curPathname = `${curPathname}${\n            !curPathname.endsWith('/') ? '/' : ''\n          }layout`\n        }\n        derivedTags.push(curPathname)\n      }\n\n      if (end === pathname.length) {\n        break\n      }\n      end = pathname.indexOf('/', end + 1)\n    }\n  }\n  return derivedTags\n}\n\n/**\n * Creates a map with lazy results that fetch the expiration value for the given\n * tags and respective cache kind when they're awaited for the first time.\n */\nfunction createTagsExpirationsByCacheKind(\n  tags: string[]\n): Map<string, LazyResult<number>> {\n  const expirationsByCacheKind = new Map<string, LazyResult<number>>()\n  const cacheHandlers = getCacheHandlerEntries()\n\n  if (cacheHandlers) {\n    for (const [kind, cacheHandler] of cacheHandlers) {\n      if ('getExpiration' in cacheHandler) {\n        expirationsByCacheKind.set(\n          kind,\n          createLazyResult(async () => cacheHandler.getExpiration(tags))\n        )\n      }\n    }\n  }\n\n  return expirationsByCacheKind\n}\n\nexport async function getImplicitTags(\n  page: string,\n  pathname: string,\n  fallbackRouteParams: null | OpaqueFallbackRouteParams\n): Promise<ImplicitTags> {\n  const tags = new Set<string>()\n\n  // Add the derived tags from the page. Encode each tag so a non-ASCII\n  // pathname doesn't trip header validation when written to\n  // `x-next-cache-tags`. Idempotent on already-ASCII input.\n  const derivedTags = getDerivedTags(page)\n  for (let tag of derivedTags) {\n    tag = encodeHeaderSafe(`${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`)\n    tags.add(tag)\n  }\n\n  // Add the tags from the pathname. If the route has unknown params, we don't\n  // want to add the pathname as a tag, as it will be invalid.\n  if (pathname && (!fallbackRouteParams || fallbackRouteParams.size === 0)) {\n    const tag = encodeHeaderSafe(`${NEXT_CACHE_IMPLICIT_TAG_ID}${pathname}`)\n    tags.add(tag)\n  }\n\n  if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)) {\n    tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n  }\n\n  if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)) {\n    tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n  }\n\n  const tagsArray = Array.from(tags)\n  return {\n    tags: tagsArray,\n    expirationsByCacheKind: createTagsExpirationsByCacheKind(tagsArray),\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","const DYNAMIC_ERROR_CODE = 'DYNAMIC_SERVER_USAGE'\n\nexport class DynamicServerError extends Error {\n  digest: typeof DYNAMIC_ERROR_CODE = DYNAMIC_ERROR_CODE\n\n  constructor(public readonly description: string) {\n    super(`Dynamic server usage: ${description}`)\n  }\n}\n\nexport function isDynamicServerError(err: unknown): err is DynamicServerError {\n  if (\n    typeof err !== 'object' ||\n    err === null ||\n    !('digest' in err) ||\n    typeof err.digest !== 'string'\n  ) {\n    return false\n  }\n\n  return err.digest === DYNAMIC_ERROR_CODE\n}\n","const NEXT_STATIC_GEN_BAILOUT = 'NEXT_STATIC_GEN_BAILOUT'\n\nexport class StaticGenBailoutError extends Error {\n  public readonly code = NEXT_STATIC_GEN_BAILOUT\n}\n\nexport function isStaticGenBailoutError(\n  error: unknown\n): error is StaticGenBailoutError {\n  if (typeof error !== 'object' || error === null || !('code' in error)) {\n    return false\n  }\n\n  return error.code === NEXT_STATIC_GEN_BAILOUT\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","/**\n * Based on https://github.com/facebook/react/blob/d4e78c42a94be027b4dc7ed2659a5fddfbf9bd4e/packages/react/src/ReactFetch.js\n */\nimport * as React from 'react'\nimport { cloneResponse } from './clone-response'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nconst simpleCacheKey = '[\"GET\",[],null,\"follow\",null,null,null,null]' // generateCacheKey(new Request('https://blank'));\n\n// Headers that should not affect deduplication\n// traceparent and tracestate are used for distributed tracing and should not affect cache keys\nconst headersToExcludeInCacheKey = new Set(['traceparent', 'tracestate'])\n\nfunction generateCacheKey(request: Request): string {\n  // We pick the fields that goes into the key used to dedupe requests.\n  // We don't include the `cache` field, because we end up using whatever\n  // caching resulted from the first request.\n  // Notably we currently don't consider non-standard (or future) options.\n  // This might not be safe. TODO: warn for non-standard extensions differing.\n  // IF YOU CHANGE THIS UPDATE THE simpleCacheKey ABOVE.\n\n  const filteredHeaders = Array.from(request.headers.entries()).filter(\n    ([key]) => !headersToExcludeInCacheKey.has(key.toLowerCase())\n  )\n\n  return JSON.stringify([\n    request.method,\n    filteredHeaders,\n    request.mode,\n    request.redirect,\n    request.credentials,\n    request.referrer,\n    request.referrerPolicy,\n    request.integrity,\n  ])\n}\n\ntype CacheEntry = [\n  key: string,\n  promise: Promise<Response>,\n  response: Response | null,\n]\n\nexport function createDedupeFetch(originalFetch: typeof fetch) {\n  const getCacheEntries = React.cache(\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars -- url is the cache key\n    (url: string): CacheEntry[] => []\n  )\n\n  return function dedupeFetch(\n    resource: URL | RequestInfo,\n    options?: RequestInit\n  ): Promise<Response> {\n    if (options && options.signal) {\n      // If we're passed a signal, then we assume that\n      // someone else controls the lifetime of this object and opts out of\n      // caching. It's effectively the opt-out mechanism.\n      // Ideally we should be able to check this on the Request but\n      // it always gets initialized with its own signal so we don't\n      // know if it's supposed to override - unless we also override the\n      // Request constructor.\n      return originalFetch(resource, options)\n    }\n    // Normalize the Request\n    let url: string\n    let cacheKey: string\n    if (typeof resource === 'string' && !options) {\n      // Fast path.\n      cacheKey = simpleCacheKey\n      url = resource\n    } else {\n      // Normalize the request.\n      // if resource is not a string or a URL (its an instance of Request)\n      // then do not instantiate a new Request but instead\n      // reuse the request as to not disturb the body in the event it's a ReadableStream.\n      const request =\n        typeof resource === 'string' || resource instanceof URL\n          ? new Request(resource, options)\n          : resource\n      if (\n        (request.method !== 'GET' && request.method !== 'HEAD') ||\n        request.keepalive\n      ) {\n        // We currently don't dedupe requests that might have side-effects. Those\n        // have to be explicitly cached. We assume that the request doesn't have a\n        // body if it's GET or HEAD.\n        // keepalive gets treated the same as if you passed a custom cache signal.\n        return originalFetch(resource, options)\n      }\n      cacheKey = generateCacheKey(request)\n      url = request.url\n    }\n\n    const cacheEntries = getCacheEntries(url)\n    for (let i = 0, j = cacheEntries.length; i < j; i += 1) {\n      const [key, promise] = cacheEntries[i]\n      if (key === cacheKey) {\n        return promise.then(() => {\n          const response = cacheEntries[i][2]\n          if (!response) throw new InvariantError('No cached response')\n\n          // We're cloning the response using this utility because there exists\n          // a bug in the undici library around response cloning. See the\n          // following pull request for more details:\n          // https://github.com/vercel/next.js/pull/73274\n          const [cloned1, cloned2] = cloneResponse(response)\n          cacheEntries[i][2] = cloned2\n          return cloned1\n        })\n      }\n    }\n\n    // We pass the original arguments here in case normalizing the Request\n    // doesn't include all the options in this environment.\n    const promise = originalFetch(resource, options)\n    const entry: CacheEntry = [cacheKey, promise, null]\n    cacheEntries.push(entry)\n\n    return promise.then((response) => {\n      // We're cloning the response using this utility because there exists\n      // a bug in the undici library around response cloning. See the\n      // following pull request for more details:\n      // https://github.com/vercel/next.js/pull/73274\n      const [cloned1, cloned2] = cloneResponse(response)\n      entry[2] = cloned2\n      return cloned1\n    })\n  }\n}\n","import type {\n  WorkAsyncStorage,\n  WorkStore,\n} from '../app-render/work-async-storage.external'\n\nimport { AppRenderSpan, NextNodeServerSpan } from './trace/constants'\nimport {\n  isRequestInsightsEnabled,\n  recordRequestInsightFetch,\n} from './trace/request-insights'\nimport { getRequestInsightsIdentity } from './trace/request-insights-identity'\nimport { getTracer, SpanKind } from './trace/tracer'\nimport {\n  CACHE_ONE_YEAR_SECONDS,\n  INFINITE_CACHE,\n  NEXT_CACHE_TAG_MAX_ITEMS,\n  NEXT_CACHE_TAG_MAX_LENGTH,\n} from '../../lib/constants'\nimport { markCurrentScopeAsDynamic } from '../app-render/dynamic-rendering'\nimport { makeDynamicHangingPromise } from '../dynamic-rendering-utils'\nimport type { FetchMetric } from '../base-http'\nimport { createDedupeFetch } from './dedupe-fetch'\nimport {\n  getCacheSignal,\n  type RevalidateStore,\n  type WorkUnitAsyncStorage,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n  CachedRouteKind,\n  IncrementalCacheKind,\n  type CachedFetchData,\n  type ServerComponentsHmrCache,\n  type SetIncrementalFetchCacheContext,\n} from '../response-cache'\nimport { cloneResponse } from './clone-response'\nimport type { IncrementalCache } from './incremental-cache'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { encodeHeaderSafe } from './encode-header-safe'\nimport type { Span } from './trace/tracer'\n\nconst isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'\n\ntype Fetcher = typeof fetch\n\ntype PatchedFetcher = Fetcher & {\n  readonly __nextPatched: true\n  readonly __nextGetStaticStore: () => WorkAsyncStorage\n  readonly _nextOriginalFetch: Fetcher\n}\n\nexport const NEXT_PATCH_SYMBOL = Symbol.for('next-patch')\n\nfunction isFetchPatched() {\n  return (globalThis as Record<symbol, unknown>)[NEXT_PATCH_SYMBOL] === true\n}\n\nexport function validateRevalidate(\n  revalidateVal: unknown,\n  route: string\n): undefined | number {\n  try {\n    let normalizedRevalidate: number | undefined = undefined\n\n    if (revalidateVal === false || revalidateVal === Infinity) {\n      // Unlike Infinity, INFINITE_CACHE survives JSON serialization (e.g. in\n      // the fetch cache).\n      normalizedRevalidate = INFINITE_CACHE\n    } else if (\n      typeof revalidateVal === 'number' &&\n      !isNaN(revalidateVal) &&\n      revalidateVal > -1\n    ) {\n      normalizedRevalidate = revalidateVal\n    } else if (typeof revalidateVal !== 'undefined') {\n      throw new Error(\n        `Invalid revalidate value \"${revalidateVal}\" on \"${route}\", must be a non-negative number or false`\n      )\n    }\n    return normalizedRevalidate\n  } catch (err: any) {\n    // handle client component error from attempting to check revalidate value\n    if (err instanceof Error && err.message.includes('Invalid revalidate')) {\n      throw err\n    }\n    return undefined\n  }\n}\n\nexport function validateTags(tags: any[], description: string) {\n  const validTags: string[] = []\n  const invalidTags: Array<{\n    tag: any\n    reason: string\n  }> = []\n\n  for (let i = 0; i < tags.length; i++) {\n    const tag = tags[i]\n\n    if (typeof tag !== 'string') {\n      invalidTags.push({ tag, reason: 'invalid type, must be a string' })\n    } else if (tag.length > NEXT_CACHE_TAG_MAX_LENGTH) {\n      invalidTags.push({\n        tag,\n        reason: `exceeded max length of ${NEXT_CACHE_TAG_MAX_LENGTH}`,\n      })\n    } else {\n      // Encode so a non-ASCII tag can be safely serialized into the\n      // `x-next-cache-tags` HTTP header without tripping Node's header\n      // validation. Length is checked on the raw input above.\n      validTags.push(encodeHeaderSafe(tag))\n    }\n\n    if (validTags.length > NEXT_CACHE_TAG_MAX_ITEMS) {\n      console.warn(\n        `Warning: exceeded max tag count for ${description}, dropped tags:`,\n        tags.slice(i).join(', ')\n      )\n      break\n    }\n  }\n\n  if (invalidTags.length > 0) {\n    console.warn(`Warning: invalid tags passed to ${description}: `)\n\n    for (const { tag, reason } of invalidTags) {\n      console.log(`tag: \"${tag}\" ${reason}`)\n    }\n  }\n  return validTags\n}\n\nfunction trackFetchMetric(\n  workStore: WorkStore,\n  span: Span | undefined,\n  ctx: Omit<FetchMetric, 'end' | 'idx'>\n) {\n  const metric = {\n    ...ctx,\n    end: performance.timeOrigin + performance.now(),\n    idx: workStore.nextFetchId || 0,\n  }\n\n  span?.setAttributes({\n    'http.status_code': metric.status,\n    'next.fetch.idx': metric.idx,\n    'next.fetch.cache_status': metric.cacheStatus,\n    'next.fetch.cache_reason': metric.cacheReason,\n  })\n\n  if (isRequestInsightsEnabled()) {\n    const requestInsightsIdentity = getRequestInsightsIdentity()\n    const requestInsightsRequestId =\n      requestInsightsIdentity?.requestId ?? workStore.requestId\n\n    if (requestInsightsRequestId) {\n      recordRequestInsightFetch(\n        {\n          requestId: requestInsightsRequestId,\n          kind: requestInsightsIdentity?.kind,\n          htmlRequestId:\n            requestInsightsIdentity?.htmlRequestId ?? workStore.htmlRequestId,\n          route: workStore.route,\n        },\n        {\n          url: metric.url,\n          method: metric.method,\n          statusCode: metric.status,\n          startTime: metric.start,\n          durationMs: metric.end - metric.start,\n          cacheStatus: metric.cacheStatus,\n          cacheReason: metric.cacheReason,\n          index: metric.idx,\n        }\n      )\n    }\n  }\n\n  if (!workStore.shouldTrackFetchMetrics) {\n    return\n  }\n\n  workStore.fetchMetrics ??= []\n\n  workStore.fetchMetrics.push(metric)\n}\n\nasync function createCachedPrerenderResponse(\n  res: Response,\n  cacheKey: string,\n  incrementalCacheContext: SetIncrementalFetchCacheContext | undefined,\n  incrementalCache: IncrementalCache,\n  revalidate: number,\n  handleUnlock: () => Promise<void> | void\n): Promise<Response> {\n  // We are prerendering at build time or revalidate time with cacheComponents so we\n  // need to buffer the response so we can guarantee it can be read in a\n  // microtask.\n  const bodyBuffer = await res.arrayBuffer()\n\n  const fetchedData = {\n    headers: Object.fromEntries(res.headers.entries()),\n    body: Buffer.from(bodyBuffer).toString('base64'),\n    status: res.status,\n    url: res.url,\n  }\n\n  // We can skip setting the serverComponentsHmrCache because we aren't in dev\n  // mode.\n\n  if (incrementalCacheContext) {\n    await incrementalCache.set(\n      cacheKey,\n      { kind: CachedRouteKind.FETCH, data: fetchedData, revalidate },\n      incrementalCacheContext\n    )\n  }\n\n  await handleUnlock()\n\n  // We return a new Response to the caller.\n  return new Response(bodyBuffer, {\n    headers: res.headers,\n    status: res.status,\n    statusText: res.statusText,\n  })\n}\n\nasync function createCachedDynamicResponse(\n  workStore: WorkStore,\n  res: Response,\n  cacheKey: string,\n  incrementalCacheContext: SetIncrementalFetchCacheContext | undefined,\n  incrementalCache: IncrementalCache,\n  serverComponentsHmrCache: ServerComponentsHmrCache | undefined,\n  revalidate: number,\n  input: RequestInfo | URL,\n  handleUnlock: () => Promise<void> | void,\n  signal: AbortSignal | null\n): Promise<Response> {\n  // We're cloning the response using this utility because there exists a bug in\n  // the undici library around response cloning. See the following pull request\n  // for more details: https://github.com/vercel/next.js/pull/73274\n  const [cloned1, cloned2] = cloneResponse(res)\n\n  // We are dynamically rendering including dev mode. We want to return the\n  // response to the caller as soon as possible because it might stream over a\n  // very long time.\n  const cacheSetPromise = cloned1\n    .arrayBuffer()\n    .then(async (arrayBuffer) => {\n      const bodyBuffer = Buffer.from(arrayBuffer)\n\n      const fetchedData = {\n        headers: Object.fromEntries(cloned1.headers.entries()),\n        body: bodyBuffer.toString('base64'),\n        status: cloned1.status,\n        url: cloned1.url,\n      }\n\n      serverComponentsHmrCache?.set(cacheKey, fetchedData)\n\n      if (incrementalCacheContext) {\n        await incrementalCache.set(\n          cacheKey,\n          { kind: CachedRouteKind.FETCH, data: fetchedData, revalidate },\n          incrementalCacheContext\n        )\n      }\n    })\n    .catch((error) => {\n      // Don't warn if the request was aborted intentionally.\n      if (!signal?.aborted) {\n        console.warn(`Failed to set fetch cache`, input, error)\n      }\n    })\n    .finally(handleUnlock)\n\n  const pendingRevalidateKey = `cache-set-${cacheKey}`\n  const pendingRevalidates = (workStore.pendingRevalidates ??= {})\n\n  let pendingRevalidatePromise = Promise.resolve()\n  if (pendingRevalidateKey in pendingRevalidates) {\n    // There is already a pending revalidate entry that we need to await to\n    // avoid race conditions.\n    pendingRevalidatePromise = pendingRevalidates[pendingRevalidateKey]\n  }\n\n  pendingRevalidates[pendingRevalidateKey] = pendingRevalidatePromise\n    .then(() => cacheSetPromise)\n    .finally(() => {\n      // If the pending revalidate is not present in the store, then we have\n      // nothing to delete.\n      if (!pendingRevalidates?.[pendingRevalidateKey]) {\n        return\n      }\n\n      delete pendingRevalidates[pendingRevalidateKey]\n    })\n\n  return cloned2\n}\n\ninterface PatchableModule {\n  workAsyncStorage: WorkAsyncStorage\n  workUnitAsyncStorage: WorkUnitAsyncStorage\n}\n\nexport function createPatchedFetcher(\n  originFetch: Fetcher,\n  { workAsyncStorage, workUnitAsyncStorage }: PatchableModule\n): PatchedFetcher {\n  // Create the patched fetch function.\n  const patched = async function fetch(\n    input: RequestInfo | URL,\n    init: RequestInit | undefined\n  ): Promise<Response> {\n    let url: URL | undefined\n    try {\n      url = new URL(input instanceof Request ? input.url : input)\n      url.username = ''\n      url.password = ''\n    } catch {\n      // Error caused by malformed URL should be handled by native fetch\n      url = undefined\n    }\n    const fetchUrl = url?.href ?? ''\n    const method = init?.method?.toUpperCase() || 'GET'\n\n    // Do create a new span trace for internal fetches in the\n    // non-verbose mode.\n    const isInternal = (init?.next as any)?.internal === true\n    const hideSpan = process.env.NEXT_OTEL_FETCH_DISABLED === '1'\n    // We don't track fetch metrics for internal fetches\n    // so it's not critical that we have a start time, as it won't be recorded.\n    // This is to workaround a flaky issue where performance APIs might\n    // not be available and will require follow-up investigation.\n    const fetchStart: number | undefined = isInternal\n      ? undefined\n      : performance.timeOrigin + performance.now()\n\n    const workStore = workAsyncStorage.getStore()\n    const workUnitStore = workUnitAsyncStorage.getStore()\n\n    let cacheSignal = workUnitStore ? getCacheSignal(workUnitStore) : null\n    if (cacheSignal) {\n      cacheSignal.beginRead()\n    }\n\n    const result = getTracer().trace(\n      isInternal ? NextNodeServerSpan.internalFetch : AppRenderSpan.fetch,\n      {\n        hideSpan,\n        kind: SpanKind.CLIENT,\n        spanName: ['fetch', method, fetchUrl].filter(Boolean).join(' '),\n        attributes: {\n          'http.url': fetchUrl,\n          'http.method': method,\n          'net.peer.name': url?.hostname,\n          'net.peer.port': url?.port || undefined,\n        },\n      },\n      async (span) => {\n        // If this is an internal fetch, we should not do any special treatment.\n        if (isInternal) {\n          return originFetch(input, init)\n        }\n\n        // If the workStore is not available, we can't do any\n        // special treatment of fetch, therefore fallback to the original\n        // fetch implementation.\n        if (!workStore) {\n          return originFetch(input, init)\n        }\n\n        // We should also fallback to the original fetch implementation if we\n        // are in draft mode, it does not constitute a static generation.\n        if (workStore.isDraftMode) {\n          return originFetch(input, init)\n        }\n\n        const isRequestInput =\n          input &&\n          typeof input === 'object' &&\n          typeof (input as Request).method === 'string'\n\n        // With `fetch(new Request(url), init)`, native fetch lets `init`\n        // override the base Request. Merge them into a single effective Request\n        // so cacheability, the cache key, and the upstream request all describe\n        // the same thing.\n        if (isRequestInput && init) {\n          // `next` (revalidate/tags) is Next-specific and dropped by\n          // `new Request`, so keep it on `init` and move the rest onto input.\n          const { next, ...overrides } = init\n          input = new Request(input as Request, overrides)\n          init = next ? { next } : undefined\n        }\n\n        const getRequestMeta = (field: string) => {\n          // If request input is present but init is not, retrieve from input first.\n          const value = (init as any)?.[field]\n          return value || (isRequestInput ? (input as any)[field] : null)\n        }\n\n        let finalRevalidate: number | undefined = undefined\n        const getNextField = (field: 'revalidate' | 'tags') => {\n          return typeof init?.next?.[field] !== 'undefined'\n            ? init?.next?.[field]\n            : isRequestInput\n              ? (input as any).next?.[field]\n              : undefined\n        }\n        // RequestInit doesn't keep extra fields e.g. next so it's\n        // only available if init is used separate\n        const originalFetchRevalidate = getNextField('revalidate')\n        let currentFetchRevalidate = originalFetchRevalidate\n        const tags: string[] = validateTags(\n          getNextField('tags') || [],\n          `fetch ${input.toString()}`\n        )\n\n        let revalidateStore: RevalidateStore | undefined\n\n        if (workUnitStore) {\n          switch (workUnitStore.type) {\n            case 'prerender':\n            case 'prerender-runtime':\n            // TODO: Stop accumulating tags in client prerender. (fallthrough)\n            case 'prerender-client':\n            case 'validation-client':\n            case 'prerender-ppr':\n            case 'prerender-legacy':\n            case 'cache':\n            case 'private-cache':\n              revalidateStore = workUnitStore\n              break\n            case 'request':\n            case 'unstable-cache':\n            case 'generate-static-params':\n              break\n            default:\n              workUnitStore satisfies never\n          }\n        }\n\n        if (revalidateStore) {\n          if (Array.isArray(tags)) {\n            // Collect tags onto parent caches or parent prerenders.\n            const collectedTags =\n              revalidateStore.tags ?? (revalidateStore.tags = [])\n            for (const tag of tags) {\n              if (!collectedTags.includes(tag)) {\n                collectedTags.push(tag)\n              }\n            }\n          }\n        }\n\n        const implicitTags = workUnitStore?.implicitTags\n\n        let pageFetchCacheMode = workStore.fetchCache\n\n        if (workUnitStore) {\n          switch (workUnitStore.type) {\n            case 'unstable-cache':\n              // Inside unstable-cache we treat it the same as force-no-store on\n              // the page.\n              pageFetchCacheMode = 'force-no-store'\n              break\n            case 'prerender':\n            case 'prerender-client':\n            case 'validation-client':\n            case 'prerender-runtime':\n            case 'prerender-ppr':\n            case 'prerender-legacy':\n            case 'request':\n            case 'cache':\n            case 'private-cache':\n            case 'generate-static-params':\n              break\n            default:\n              workUnitStore satisfies never\n          }\n        }\n\n        const isUsingNoStore = !!workStore.isUnstableNoStore\n\n        let currentFetchCacheConfig = getRequestMeta('cache')\n        let cacheReason = ''\n        let cacheWarning: string | undefined\n\n        if (\n          typeof currentFetchCacheConfig === 'string' &&\n          typeof currentFetchRevalidate !== 'undefined'\n        ) {\n          // If the revalidate value conflicts with the cache value, we should warn the user and unset the conflicting values.\n          const isConflictingRevalidate =\n            // revalidate: 0 and cache: force-cache\n            (currentFetchCacheConfig === 'force-cache' &&\n              currentFetchRevalidate === 0) ||\n            // revalidate: >0 or revalidate: false and cache: no-store\n            (currentFetchCacheConfig === 'no-store' &&\n              (currentFetchRevalidate > 0 || currentFetchRevalidate === false))\n\n          if (isConflictingRevalidate) {\n            cacheWarning = `Specified \"cache: ${currentFetchCacheConfig}\" and \"revalidate: ${currentFetchRevalidate}\", only one should be specified.`\n            currentFetchCacheConfig = undefined\n            currentFetchRevalidate = undefined\n          }\n        }\n\n        const hasExplicitFetchCacheOptOut =\n          // fetch config itself signals not to cache\n          currentFetchCacheConfig === 'no-cache' ||\n          currentFetchCacheConfig === 'no-store' ||\n          // the fetch isn't explicitly caching and the segment level cache config signals not to cache\n          // note: `pageFetchCacheMode` is also set by being in an unstable_cache context.\n          pageFetchCacheMode === 'force-no-store' ||\n          pageFetchCacheMode === 'only-no-store'\n\n        // If no explicit fetch cache mode is set, but dynamic = `force-dynamic` is set,\n        // we shouldn't consider caching the fetch. This is because the `dynamic` cache\n        // is considered a \"top-level\" cache mode, whereas something like `fetchCache` is more\n        // fine-grained. Top-level modes are responsible for setting reasonable defaults for the\n        // other configurations.\n        const noFetchConfigAndForceDynamic =\n          !pageFetchCacheMode &&\n          !currentFetchCacheConfig &&\n          !currentFetchRevalidate &&\n          workStore.forceDynamic\n\n        if (\n          // force-cache was specified without a revalidate value. We set the revalidate value to false\n          // which will signal the cache to not revalidate\n          currentFetchCacheConfig === 'force-cache' &&\n          typeof currentFetchRevalidate === 'undefined'\n        ) {\n          currentFetchRevalidate = false\n        } else if (\n          hasExplicitFetchCacheOptOut ||\n          noFetchConfigAndForceDynamic\n        ) {\n          currentFetchRevalidate = 0\n        }\n\n        if (\n          currentFetchCacheConfig === 'no-cache' ||\n          currentFetchCacheConfig === 'no-store'\n        ) {\n          cacheReason = `cache: ${currentFetchCacheConfig}`\n        }\n\n        finalRevalidate = validateRevalidate(\n          currentFetchRevalidate,\n          workStore.route\n        )\n\n        const _headers = getRequestMeta('headers')\n        const initHeaders: Headers =\n          typeof _headers?.get === 'function'\n            ? _headers\n            : new Headers(_headers || {})\n\n        const hasUnCacheableHeader =\n          initHeaders.get('authorization') || initHeaders.get('cookie')\n\n        const isUnCacheableMethod = !['get', 'head'].includes(\n          getRequestMeta('method')?.toLowerCase() || 'get'\n        )\n\n        /**\n         * We automatically disable fetch caching under the following conditions:\n         * - Fetch cache configs are not set. Specifically:\n         *    - A page fetch cache mode is not set (export const fetchCache=...)\n         *    - A fetch cache mode is not set in the fetch call (fetch(url, { cache: ... }))\n         *      or the fetch cache mode is set to 'default'\n         *    - A fetch revalidate value is not set in the fetch call (fetch(url, { revalidate: ... }))\n         * - OR the fetch comes after a configuration that triggered dynamic rendering (e.g., reading cookies())\n         *   and the fetch was considered uncacheable (e.g., POST method or has authorization headers)\n         */\n        const hasNoExplicitCacheConfig =\n          // eslint-disable-next-line eqeqeq\n          pageFetchCacheMode == undefined &&\n          // eslint-disable-next-line eqeqeq\n          (currentFetchCacheConfig == undefined ||\n            // when considering whether to opt into the default \"no-cache\" fetch semantics,\n            // a \"default\" cache config should be treated the same as no cache config\n            currentFetchCacheConfig === 'default') &&\n          // eslint-disable-next-line eqeqeq\n          currentFetchRevalidate == undefined\n\n        let autoNoCache = Boolean(\n          (hasUnCacheableHeader || isUnCacheableMethod) &&\n            revalidateStore?.revalidate === 0\n        )\n\n        let isImplicitBuildTimeCache = false\n\n        if (!autoNoCache && hasNoExplicitCacheConfig) {\n          // We don't enable automatic no-cache behavior during build-time\n          // prerendering so that we can still leverage the fetch cache between\n          // export workers.\n          if (workStore.isBuildTimePrerendering) {\n            isImplicitBuildTimeCache = true\n          } else {\n            autoNoCache = true\n          }\n        }\n\n        // If we have no cache config, and we're in Dynamic I/O prerendering,\n        // it'll be a dynamic call. We don't have to issue that dynamic call.\n        if (hasNoExplicitCacheConfig && workUnitStore !== undefined) {\n          switch (workUnitStore.type) {\n            case 'prerender':\n            case 'prerender-runtime':\n            // While we don't want to do caching in the client scope we know the\n            // fetch will be dynamic for cacheComponents so we may as well avoid the\n            // call here. (fallthrough)\n            case 'prerender-client':\n              if (cacheSignal) {\n                cacheSignal.endRead()\n                cacheSignal = null\n              }\n\n              return makeDynamicHangingPromise<Response>(\n                workUnitStore.renderSignal,\n                workStore.route,\n                'fetch()'\n              )\n            case 'validation-client':\n              break\n            case 'request':\n              if (\n                process.env.NODE_ENV === 'development' &&\n                workUnitStore.stagedRendering\n              ) {\n                if (cacheSignal) {\n                  cacheSignal.endRead()\n                  cacheSignal = null\n                }\n                await workUnitStore.stagedRendering.waitForStage(\n                  RenderStage.Dynamic\n                )\n              }\n              break\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        switch (pageFetchCacheMode) {\n          case 'force-no-store': {\n            cacheReason = 'fetchCache = force-no-store'\n            break\n          }\n          case 'only-no-store': {\n            if (\n              currentFetchCacheConfig === 'force-cache' ||\n              (typeof finalRevalidate !== 'undefined' && finalRevalidate > 0)\n            ) {\n              throw new Error(\n                `cache: 'force-cache' used on fetch for ${fetchUrl} with 'export const fetchCache = 'only-no-store'`\n              )\n            }\n            cacheReason = 'fetchCache = only-no-store'\n            break\n          }\n          case 'only-cache': {\n            if (currentFetchCacheConfig === 'no-store') {\n              throw new Error(\n                `cache: 'no-store' used on fetch for ${fetchUrl} with 'export const fetchCache = 'only-cache'`\n              )\n            }\n            break\n          }\n          case 'force-cache': {\n            if (\n              typeof currentFetchRevalidate === 'undefined' ||\n              currentFetchRevalidate === 0\n            ) {\n              cacheReason = 'fetchCache = force-cache'\n              finalRevalidate = INFINITE_CACHE\n            }\n            break\n          }\n          case 'default-cache':\n          case 'default-no-store':\n          case 'auto':\n          case undefined:\n            // sometimes we won't match the above cases. the reason we don't move\n            // everything to this switch is the use of autoNoCache which is not a fetchCacheMode\n            // I suspect this could be unified with fetchCacheMode however in which case we could\n            // simplify the switch case and ensure we have an exhaustive switch handling all modes\n            break\n          default:\n            pageFetchCacheMode satisfies never\n        }\n\n        if (typeof finalRevalidate === 'undefined') {\n          if (pageFetchCacheMode === 'default-cache' && !isUsingNoStore) {\n            finalRevalidate = INFINITE_CACHE\n            cacheReason = 'fetchCache = default-cache'\n          } else if (pageFetchCacheMode === 'default-no-store') {\n            finalRevalidate = 0\n            cacheReason = 'fetchCache = default-no-store'\n          } else if (isUsingNoStore) {\n            finalRevalidate = 0\n            cacheReason = 'noStore call'\n          } else if (autoNoCache) {\n            finalRevalidate = 0\n            cacheReason = 'auto no cache'\n          } else {\n            // TODO: should we consider this case an invariant?\n            cacheReason = 'auto cache'\n            finalRevalidate = revalidateStore\n              ? revalidateStore.revalidate\n              : INFINITE_CACHE\n          }\n        } else if (!cacheReason) {\n          cacheReason = `revalidate: ${finalRevalidate}`\n        }\n\n        if (\n          // when force static is configured we don't bail from\n          // `revalidate: 0` values\n          !(workStore.forceStatic && finalRevalidate === 0) &&\n          // we don't consider autoNoCache to switch to dynamic for ISR\n          !autoNoCache &&\n          // If the revalidate value isn't currently set or the value is less\n          // than the current revalidate value, we should update the revalidate\n          // value.\n          revalidateStore &&\n          finalRevalidate < revalidateStore.revalidate\n        ) {\n          // If we were setting the revalidate value to 0, we should try to\n          // postpone instead first.\n          if (finalRevalidate === 0) {\n            if (workUnitStore) {\n              switch (workUnitStore.type) {\n                case 'prerender':\n                case 'prerender-client':\n                case 'prerender-runtime':\n                // If we're in an instant validation, a dynamic fetch won't\n                // have time to resolve during the validation prerender anyway,\n                // so we leave it hanging. This can cause false negatives in shared parents,\n                // but we accept that for now, because client data fetching is non-idiomatic.\n                // eslint-disable-next-line no-fallthrough\n                case 'validation-client':\n                  if (cacheSignal) {\n                    cacheSignal.endRead()\n                    cacheSignal = null\n                  }\n                  return makeDynamicHangingPromise<Response>(\n                    workUnitStore.renderSignal,\n                    workStore.route,\n                    'fetch()'\n                  )\n                case 'request':\n                  if (\n                    process.env.NODE_ENV === 'development' &&\n                    workUnitStore.stagedRendering\n                  ) {\n                    if (cacheSignal) {\n                      cacheSignal.endRead()\n                      cacheSignal = null\n                    }\n                    await workUnitStore.stagedRendering.waitForStage(\n                      RenderStage.Dynamic\n                    )\n                  }\n                  break\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            markCurrentScopeAsDynamic(\n              workStore,\n              workUnitStore,\n              `revalidate: 0 fetch ${input} ${workStore.route}`\n            )\n          }\n\n          // We only want to set the revalidate store's revalidate time if it\n          // was explicitly set for the fetch call, i.e.\n          // originalFetchRevalidate.\n          if (revalidateStore && originalFetchRevalidate === finalRevalidate) {\n            revalidateStore.revalidate = finalRevalidate\n          }\n        }\n\n        const isCacheableRevalidate =\n          typeof finalRevalidate === 'number' && finalRevalidate > 0\n\n        let cacheKey: string | undefined\n        const { incrementalCache } = workStore\n        let isHmrRefresh = false\n        let serverComponentsHmrCache: ServerComponentsHmrCache | undefined\n\n        if (workUnitStore) {\n          switch (workUnitStore.type) {\n            case 'request':\n            case 'cache':\n            case 'private-cache':\n              isHmrRefresh = workUnitStore.isHmrRefresh ?? false\n              serverComponentsHmrCache = workUnitStore.serverComponentsHmrCache\n              break\n            case 'prerender':\n            case 'prerender-client':\n            case 'validation-client':\n            case 'prerender-runtime':\n            case 'prerender-ppr':\n            case 'prerender-legacy':\n            case 'unstable-cache':\n            case 'generate-static-params':\n              break\n            default:\n              workUnitStore satisfies never\n          }\n        }\n\n        if (\n          incrementalCache &&\n          (isCacheableRevalidate || serverComponentsHmrCache)\n        ) {\n          try {\n            cacheKey = await incrementalCache.generateCacheKey(\n              fetchUrl,\n              isRequestInput ? (input as RequestInit) : init\n            )\n          } catch (cause) {\n            console.error(`Failed to generate cache key for`, input, cause)\n          }\n        }\n\n        const fetchIdx = workStore.nextFetchId ?? 1\n        workStore.nextFetchId = fetchIdx + 1\n\n        let handleUnlock: () => Promise<void> | void = () => {}\n\n        const doOriginalFetch = async (\n          isStale?: boolean,\n          cacheReasonOverride?: string\n        ) => {\n          const requestInputFields = [\n            'cache',\n            'credentials',\n            'headers',\n            'integrity',\n            'keepalive',\n            'method',\n            'mode',\n            'redirect',\n            'referrer',\n            'referrerPolicy',\n            'window',\n            'duplex',\n\n            // don't pass through signal when revalidating\n            ...(isStale ? [] : ['signal']),\n          ]\n\n          if (isRequestInput) {\n            const reqInput: Request = input as any\n            const reqOptions: RequestInit = {\n              body: (reqInput as any)._ogBody || reqInput.body,\n            }\n\n            for (const field of requestInputFields) {\n              // @ts-expect-error custom fields\n              reqOptions[field] = reqInput[field]\n            }\n            input = new Request(reqInput.url, reqOptions)\n          } else if (init) {\n            const { _ogBody, body, signal, ...otherInput } =\n              init as RequestInit & { _ogBody?: any }\n            init = {\n              ...otherInput,\n              body: _ogBody || body,\n              signal: isStale ? undefined : signal,\n            }\n          }\n\n          // add metadata to init without editing the original\n          const clonedInit = {\n            ...init,\n            next: { ...init?.next, fetchType: 'origin', fetchIdx },\n          }\n\n          return originFetch(input, clonedInit)\n            .then(async (res) => {\n              if (!isStale && fetchStart) {\n                trackFetchMetric(workStore, span, {\n                  start: fetchStart,\n                  url: fetchUrl,\n                  cacheReason: cacheReasonOverride || cacheReason,\n                  cacheStatus:\n                    finalRevalidate === 0 || cacheReasonOverride\n                      ? 'skip'\n                      : 'miss',\n                  cacheWarning,\n                  status: res.status,\n                  method: clonedInit.method || 'GET',\n                })\n              }\n              if (\n                res.status === 200 &&\n                incrementalCache &&\n                cacheKey &&\n                (isCacheableRevalidate || serverComponentsHmrCache)\n              ) {\n                const normalizedRevalidate =\n                  finalRevalidate >= INFINITE_CACHE\n                    ? CACHE_ONE_YEAR_SECONDS\n                    : finalRevalidate\n\n                const incrementalCacheConfig:\n                  | SetIncrementalFetchCacheContext\n                  | undefined = isCacheableRevalidate\n                  ? {\n                      fetchCache: true,\n                      fetchUrl,\n                      fetchIdx,\n                      tags,\n                      isImplicitBuildTimeCache,\n                    }\n                  : undefined\n\n                switch (workUnitStore?.type) {\n                  case 'prerender':\n                  case 'prerender-client':\n                  case 'validation-client':\n                  case 'prerender-runtime':\n                    return createCachedPrerenderResponse(\n                      res,\n                      cacheKey,\n                      incrementalCacheConfig,\n                      incrementalCache,\n                      normalizedRevalidate,\n                      handleUnlock\n                    )\n                  case 'request':\n                    if (\n                      process.env.NODE_ENV === 'development' &&\n                      workUnitStore.stagedRendering &&\n                      workUnitStore.cacheSignal &&\n                      isCacheableRevalidate\n                    ) {\n                      // We're filling caches for a staged render with an\n                      // explicit cache config, so we need to wait for the\n                      // response to finish instead of streaming. For HMR-only\n                      // caching (no explicit revalidate), we fall through to\n                      // createCachedDynamicResponse which handles streaming\n                      // and abort gracefully.\n                      return createCachedPrerenderResponse(\n                        res,\n                        cacheKey,\n                        incrementalCacheConfig,\n                        incrementalCache,\n                        normalizedRevalidate,\n                        handleUnlock\n                      )\n                    }\n                  // fallthrough\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                  case undefined:\n                    return createCachedDynamicResponse(\n                      workStore,\n                      res,\n                      cacheKey,\n                      incrementalCacheConfig,\n                      incrementalCache,\n                      serverComponentsHmrCache,\n                      normalizedRevalidate,\n                      input,\n                      handleUnlock,\n                      getRequestMeta('signal')\n                    )\n                  default:\n                    workUnitStore satisfies never\n                }\n              }\n\n              // we had response that we determined shouldn't be cached so we return it\n              // and don't cache it. This also needs to unlock the cache lock we acquired.\n              await handleUnlock()\n\n              return res\n            })\n            .catch((error) => {\n              handleUnlock()\n              throw error\n            })\n        }\n\n        let cacheReasonOverride\n        let isForegroundRevalidate = false\n        let isHmrRefreshCache = false\n\n        if (cacheKey && incrementalCache) {\n          let cachedFetchData: CachedFetchData | undefined\n\n          if (isHmrRefresh && serverComponentsHmrCache) {\n            cachedFetchData = serverComponentsHmrCache.get(cacheKey)\n            isHmrRefreshCache = true\n          }\n\n          if (isCacheableRevalidate && !cachedFetchData) {\n            handleUnlock = await incrementalCache.lock(cacheKey)\n            const entry = workStore.isOnDemandRevalidate\n              ? null\n              : await incrementalCache.get(cacheKey, {\n                  kind: IncrementalCacheKind.FETCH,\n                  revalidate: finalRevalidate,\n                  fetchUrl,\n                  fetchIdx,\n                  tags,\n                  softTags: implicitTags?.tags,\n                })\n\n            if (hasNoExplicitCacheConfig && workUnitStore) {\n              switch (workUnitStore.type) {\n                case 'prerender':\n                case 'prerender-client':\n                case 'validation-client':\n                case 'prerender-runtime':\n                  // We sometimes use the cache to dedupe fetches that do not\n                  // specify a cache configuration. In these cases we want to\n                  // make sure we still exclude them from prerenders if\n                  // cacheComponents is on so we introduce an artificial task boundary\n                  // here.\n                  await getTimeoutBoundary()\n                  break\n                case 'request':\n                  if (\n                    process.env.NODE_ENV === 'development' &&\n                    workUnitStore.stagedRendering\n                  ) {\n                    await workUnitStore.stagedRendering.waitForStage(\n                      RenderStage.Dynamic\n                    )\n                  }\n                  break\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            if (entry) {\n              await handleUnlock()\n            } else {\n              // in dev, incremental cache response will be null in case the browser adds `cache-control: no-cache` in the request headers\n              // TODO: it seems like we also hit this after revalidates in dev?\n              cacheReasonOverride = 'cache-control: no-cache (hard refresh)'\n            }\n\n            if (entry?.value && entry.value.kind === CachedRouteKind.FETCH) {\n              // when stale and is revalidating we wait for fresh data\n              // so the revalidated entry has the updated data\n              if (workStore.isStaticGeneration && entry.isStale) {\n                isForegroundRevalidate = true\n              } else {\n                if (entry.isStale) {\n                  workStore.pendingRevalidates ??= {}\n                  if (!workStore.pendingRevalidates[cacheKey]) {\n                    const pendingRevalidate = doOriginalFetch(true)\n                      .then(async (response) => ({\n                        body: await response.arrayBuffer(),\n                        headers: response.headers,\n                        status: response.status,\n                        statusText: response.statusText,\n                      }))\n                      .finally(() => {\n                        workStore.pendingRevalidates ??= {}\n                        delete workStore.pendingRevalidates[cacheKey || '']\n                      })\n\n                    // Attach the empty catch here so we don't get a \"unhandled\n                    // promise rejection\" warning.\n                    pendingRevalidate.catch(console.error)\n\n                    workStore.pendingRevalidates[cacheKey] = pendingRevalidate\n                  }\n                }\n\n                cachedFetchData = entry.value.data\n              }\n            }\n          }\n\n          if (cachedFetchData) {\n            if (fetchStart) {\n              trackFetchMetric(workStore, span, {\n                start: fetchStart,\n                url: fetchUrl,\n                cacheReason,\n                cacheStatus: isHmrRefreshCache ? 'hmr' : 'hit',\n                cacheWarning,\n                status: cachedFetchData.status || 200,\n                method: init?.method || 'GET',\n              })\n            }\n\n            const response = new Response(\n              Buffer.from(cachedFetchData.body, 'base64'),\n              {\n                headers: cachedFetchData.headers,\n                status: cachedFetchData.status,\n              }\n            )\n\n            Object.defineProperty(response, 'url', {\n              value: cachedFetchData.url,\n            })\n\n            return response\n          }\n        }\n\n        if (\n          (workStore.isStaticGeneration ||\n            (process.env.NODE_ENV === 'development' &&\n              process.env.__NEXT_CACHE_COMPONENTS &&\n              workUnitStore &&\n              // eslint-disable-next-line no-restricted-syntax\n              workUnitStore.type === 'request' &&\n              workUnitStore.stagedRendering)) &&\n          init &&\n          typeof init === 'object'\n        ) {\n          const { cache } = init\n\n          // Delete `cache` property as Cloudflare Workers will throw an error\n          if (isEdgeRuntime) delete init.cache\n\n          if (cache === 'no-store') {\n            // If enabled, we should bail out of static generation.\n            if (workUnitStore) {\n              switch (workUnitStore.type) {\n                case 'prerender':\n                case 'prerender-client':\n                case 'prerender-runtime':\n                case 'validation-client':\n                  if (cacheSignal) {\n                    cacheSignal.endRead()\n                    cacheSignal = null\n                  }\n                  return makeDynamicHangingPromise<Response>(\n                    workUnitStore.renderSignal,\n                    workStore.route,\n                    'fetch()'\n                  )\n                case 'request':\n                  if (\n                    process.env.NODE_ENV === 'development' &&\n                    workUnitStore.stagedRendering\n                  ) {\n                    if (cacheSignal) {\n                      cacheSignal.endRead()\n                      cacheSignal = null\n                    }\n                    await workUnitStore.stagedRendering.waitForStage(\n                      RenderStage.Dynamic\n                    )\n                  }\n                  break\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            markCurrentScopeAsDynamic(\n              workStore,\n              workUnitStore,\n              `no-store fetch ${input} ${workStore.route}`\n            )\n          }\n\n          const hasNextConfig = 'next' in init\n          const { next = {} } = init\n          if (\n            typeof next.revalidate === 'number' &&\n            revalidateStore &&\n            next.revalidate < revalidateStore.revalidate\n          ) {\n            if (next.revalidate === 0) {\n              // If enabled, we should bail out of static generation.\n              if (workUnitStore) {\n                switch (workUnitStore.type) {\n                  case 'prerender':\n                  case 'prerender-client':\n                  case 'prerender-runtime':\n                  case 'validation-client':\n                    return makeDynamicHangingPromise<Response>(\n                      workUnitStore.renderSignal,\n                      workStore.route,\n                      'fetch()'\n                    )\n                  case 'request':\n                    if (\n                      process.env.NODE_ENV === 'development' &&\n                      workUnitStore.stagedRendering\n                    ) {\n                      await workUnitStore.stagedRendering.waitForStage(\n                        RenderStage.Dynamic\n                      )\n                    }\n                    break\n                  case 'cache':\n                  case 'private-cache':\n                  case 'unstable-cache':\n                  case 'prerender-legacy':\n                  case 'prerender-ppr':\n                  case 'generate-static-params':\n                    break\n                  default:\n                    workUnitStore satisfies never\n                }\n              }\n              markCurrentScopeAsDynamic(\n                workStore,\n                workUnitStore,\n                `revalidate: 0 fetch ${input} ${workStore.route}`\n              )\n            }\n\n            if (!workStore.forceStatic || next.revalidate !== 0) {\n              revalidateStore.revalidate = next.revalidate\n            }\n          }\n          if (hasNextConfig) delete init.next\n        }\n\n        // if we are revalidating the whole page via time or on-demand and\n        // the fetch cache entry is stale we should still de-dupe the\n        // origin hit if it's a cache-able entry\n        if (cacheKey && isForegroundRevalidate) {\n          const pendingRevalidateKey = cacheKey\n          workStore.pendingRevalidates ??= {}\n          let pendingRevalidate =\n            workStore.pendingRevalidates[pendingRevalidateKey]\n\n          if (pendingRevalidate) {\n            const revalidatedResult: {\n              body: ArrayBuffer\n              headers: Headers\n              status: number\n              statusText: string\n            } = await pendingRevalidate\n            return new Response(revalidatedResult.body, {\n              headers: revalidatedResult.headers,\n              status: revalidatedResult.status,\n              statusText: revalidatedResult.statusText,\n            })\n          }\n\n          // We used to just resolve the Response and clone it however for\n          // static generation with cacheComponents we need the response to be able to\n          // be resolved in a microtask and cloning the response will never have\n          // a body that can resolve in a microtask in node (as observed through\n          // experimentation) So instead we await the body and then when it is\n          // available we construct manually cloned Response objects with the\n          // body as an ArrayBuffer. This will be resolvable in a microtask\n          // making it compatible with cacheComponents.\n          const pendingResponse = doOriginalFetch(true, cacheReasonOverride)\n            // We're cloning the response using this utility because there\n            // exists a bug in the undici library around response cloning.\n            // See the following pull request for more details:\n            // https://github.com/vercel/next.js/pull/73274\n            .then(cloneResponse)\n\n          pendingRevalidate = pendingResponse\n            .then(async (responses) => {\n              const response = responses[0]\n              return {\n                body: await response.arrayBuffer(),\n                headers: response.headers,\n                status: response.status,\n                statusText: response.statusText,\n              }\n            })\n            .finally(() => {\n              // If the pending revalidate is not present in the store, then\n              // we have nothing to delete.\n              if (!workStore.pendingRevalidates?.[pendingRevalidateKey]) {\n                return\n              }\n\n              delete workStore.pendingRevalidates[pendingRevalidateKey]\n            })\n\n          // Attach the empty catch here so we don't get a \"unhandled promise\n          // rejection\" warning\n          pendingRevalidate.catch(() => {})\n\n          workStore.pendingRevalidates[pendingRevalidateKey] = pendingRevalidate\n\n          return pendingResponse.then((responses) => responses[1])\n        } else {\n          return doOriginalFetch(false, cacheReasonOverride)\n        }\n      }\n    )\n\n    if (cacheSignal) {\n      try {\n        return await result\n      } finally {\n        if (cacheSignal) {\n          cacheSignal.endRead()\n        }\n      }\n    }\n    return result\n  }\n\n  // Attach the necessary properties to the patched fetch function.\n  // We don't use this to determine if the fetch function has been patched,\n  // but for external consumers to determine if the fetch function has been\n  // patched.\n  patched.__nextPatched = true as const\n  patched.__nextGetStaticStore = () => workAsyncStorage\n  patched._nextOriginalFetch = originFetch\n  ;(globalThis as Record<symbol, unknown>)[NEXT_PATCH_SYMBOL] = true\n\n  // Assign the function name also as a name property, so that it's preserved\n  // even when mangling is enabled.\n  Object.defineProperty(patched, 'name', { value: 'fetch', writable: false })\n\n  return patched\n}\n\n// we patch fetch to collect cache information used for\n// determining if a page is static or not\nexport function patchFetch(options: PatchableModule) {\n  // If we've already patched fetch, we should not patch it again.\n  if (isFetchPatched()) return\n\n  // Grab the original fetch function. We'll attach this so we can use it in\n  // the patched fetch function.\n  const original = createDedupeFetch(globalThis.fetch)\n\n  // Set the global fetch to the patched fetch.\n  globalThis.fetch = createPatchedFetcher(original, options)\n}\n\nlet currentTimeoutBoundary: null | Promise<void> = null\nfunction getTimeoutBoundary() {\n  if (!currentTimeoutBoundary) {\n    currentTimeoutBoundary = new Promise((r) => {\n      setTimeout(() => {\n        currentTimeoutBoundary = null\n        r()\n      }, 0)\n    })\n  }\n  return currentTimeoutBoundary\n}\n","import type { AppRouteHandlerFn, AppRouteHandlers } from '../module'\n\nimport { HTTP_METHODS, type HTTP_METHOD } from '../../../web/http'\n\nconst AUTOMATIC_ROUTE_METHODS = ['HEAD', 'OPTIONS'] as const\n\nfunction handleMethodNotAllowedResponse(): Response {\n  return new Response(null, { status: 405 })\n}\n\nexport function autoImplementMethods(\n  handlers: AppRouteHandlers\n): Record<HTTP_METHOD, AppRouteHandlerFn> {\n  // Loop through all the HTTP methods to create the initial methods object.\n  // Each of the methods will be set to the 405 response handler.\n  const methods: Record<HTTP_METHOD, AppRouteHandlerFn> = HTTP_METHODS.reduce(\n    (acc, method) => ({\n      ...acc,\n      // If the userland module implements the method, then use it. Otherwise,\n      // use the 405 response handler.\n      [method]: handlers[method] ?? handleMethodNotAllowedResponse,\n    }),\n    {} as Record<HTTP_METHOD, AppRouteHandlerFn>\n  )\n\n  // Get all the methods that could be automatically implemented that were not\n  // implemented by the userland module.\n  const implemented = new Set(HTTP_METHODS.filter((method) => handlers[method]))\n  const missing = AUTOMATIC_ROUTE_METHODS.filter(\n    (method) => !implemented.has(method)\n  )\n\n  // Loop over the missing methods to automatically implement them if we can.\n  for (const method of missing) {\n    // If the userland module doesn't implement the HEAD method, then\n    // we'll automatically implement it by calling the GET method (if it\n    // exists).\n    if (method === 'HEAD') {\n      if (handlers.GET) {\n        // Implement the HEAD method by calling the GET method.\n        methods.HEAD = handlers.GET\n\n        // Mark it as implemented.\n        implemented.add('HEAD')\n      }\n      continue\n    }\n\n    // If OPTIONS is not provided then implement it.\n    if (method === 'OPTIONS') {\n      // TODO: check if HEAD is implemented, if so, use it to add more headers\n\n      // Get all the methods that were implemented by the userland module.\n      const allow: HTTP_METHOD[] = ['OPTIONS', ...implemented]\n\n      // If the list of methods doesn't include HEAD, but it includes GET, then\n      // add HEAD as it's automatically implemented.\n      if (!implemented.has('HEAD') && implemented.has('GET')) {\n        allow.push('HEAD')\n      }\n\n      // Sort and join the list with commas to create the `Allow` header. See:\n      // https://httpwg.org/specs/rfc9110.html#field.allow\n      const headers = { Allow: allow.sort().join(', ') }\n\n      // Implement the OPTIONS method by returning a 204 response with the\n      // `Allow` header.\n      methods.OPTIONS = () => new Response(null, { status: 204, headers })\n\n      // Mark this method as implemented.\n      implemented.add('OPTIONS')\n\n      continue\n    }\n\n    throw new Error(\n      `Invariant: should handle all automatic implementable methods, got method: ${method}`\n    )\n  }\n\n  return methods\n}\n","export const HTTPAccessErrorStatus = {\n  NOT_FOUND: 404,\n  FORBIDDEN: 403,\n  UNAUTHORIZED: 401,\n}\n\nconst ALLOWED_CODES = new Set(Object.values(HTTPAccessErrorStatus))\n\nexport const HTTP_ERROR_FALLBACK_ERROR_CODE = 'NEXT_HTTP_ERROR_FALLBACK'\n\nexport type HTTPAccessFallbackError = Error & {\n  digest: `${typeof HTTP_ERROR_FALLBACK_ERROR_CODE};${string}`\n}\n\n/**\n * Checks an error to determine if it's an error generated by\n * the HTTP navigation APIs `notFound()`, `forbidden()` or `unauthorized()`.\n *\n * @param error the error that may reference a HTTP access error\n * @returns true if the error is a HTTP access error\n */\nexport function isHTTPAccessFallbackError(\n  error: unknown\n): error is HTTPAccessFallbackError {\n  if (\n    typeof error !== 'object' ||\n    error === null ||\n    !('digest' in error) ||\n    typeof error.digest !== 'string'\n  ) {\n    return false\n  }\n  const [prefix, httpStatus] = error.digest.split(';')\n\n  return (\n    prefix === HTTP_ERROR_FALLBACK_ERROR_CODE &&\n    ALLOWED_CODES.has(Number(httpStatus))\n  )\n}\n\nexport function getAccessFallbackHTTPStatus(\n  error: HTTPAccessFallbackError\n): number {\n  const httpStatus = error.digest.split(';')[1]\n  return Number(httpStatus)\n}\n\nexport function getAccessFallbackErrorTypeByStatus(\n  status: number\n): 'not-found' | 'forbidden' | 'unauthorized' | undefined {\n  switch (status) {\n    case 401:\n      return 'unauthorized'\n    case 403:\n      return 'forbidden'\n    case 404:\n      return 'not-found'\n    default:\n      return\n  }\n}\n","import { RedirectStatusCode } from './redirect-status-code'\n\nexport const REDIRECT_ERROR_CODE = 'NEXT_REDIRECT'\n\nexport type RedirectType = 'push' | 'replace'\n\nexport type RedirectError = Error & {\n  digest: `${typeof REDIRECT_ERROR_CODE};${RedirectType};${string};${RedirectStatusCode};`\n}\n\n/**\n * Checks an error to determine if it's an error generated by the\n * `redirect(url)` helper.\n *\n * @param error the error that may reference a redirect error\n * @returns true if the error is a redirect error\n */\nexport function isRedirectError(error: unknown): error is RedirectError {\n  if (\n    typeof error !== 'object' ||\n    error === null ||\n    !('digest' in error) ||\n    typeof error.digest !== 'string'\n  ) {\n    return false\n  }\n\n  const digest = error.digest.split(';')\n  const [errorCode, type] = digest\n  const destination = digest.slice(2, -2).join(';')\n  const status = digest.at(-2)\n\n  const statusCode = Number(status)\n\n  return (\n    errorCode === REDIRECT_ERROR_CODE &&\n    (type === 'replace' || type === 'push') &&\n    typeof destination === 'string' &&\n    !isNaN(statusCode) &&\n    statusCode in RedirectStatusCode\n  )\n}\n","import type { ErrorInfo } from 'react'\nimport stringHash from 'next/dist/compiled/string-hash'\n\nimport { formatServerError } from '../../lib/format-server-error'\nimport { SpanStatusCode, getTracer } from '../lib/trace/tracer'\n\nimport { isAbortError } from '../pipe-readable'\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { isDynamicServerError } from '../../client/components/hooks-server-context'\nimport { isNextRouterError } from '../../client/components/is-next-router-error'\nimport { isPrerenderInterruptedError } from './dynamic-rendering'\nimport { getProperError } from '../../lib/is-error'\nimport { createDigestWithErrorCode } from '../../lib/error-telemetry-utils'\nimport { isReactLargeShellError } from './react-large-shell-error'\nimport { isInstantValidationError } from './instant-validation/instant-validation-error'\n\ndeclare global {\n  var __next_log_error__: undefined | ((err: unknown) => void)\n}\n\ntype RSCErrorHandler = (err: unknown) => string | undefined\ntype SSRErrorHandler = (\n  err: unknown,\n  errorInfo?: ErrorInfo\n) => string | undefined\n\nexport type DigestedError = Error & { digest: string; environmentName?: string }\n\n/**\n * Returns a digest for well-known Next.js errors, otherwise `undefined`. If a\n * digest is returned this also means that the error does not need to be\n * reported.\n */\nexport function getDigestForWellKnownError(error: unknown): string | undefined {\n  // If we're bailing out to CSR, we don't need to log the error.\n  if (isBailoutToCSRError(error)) return error.digest\n\n  // If this is a navigation error, we don't need to log the error.\n  if (isNextRouterError(error)) return error.digest\n\n  // If this error occurs, we know that we should be stopping the static\n  // render. This is only thrown in static generation when PPR is not enabled,\n  // which causes the whole page to be marked as dynamic. We don't need to\n  // tell the user about this error, as it's not actionable.\n  if (isDynamicServerError(error)) return error.digest\n\n  // If this is a prerender interrupted error, we don't need to log the error.\n  if (isPrerenderInterruptedError(error)) return error.digest\n\n  if (isInstantValidationError(error)) return error.digest\n\n  return undefined\n}\n\nexport function createReactServerErrorHandler(\n  shouldFormatError: boolean,\n  isBuildTimePrerendering: boolean,\n  reactServerErrors: Map<string, DigestedError>,\n  onReactServerRenderError: (err: DigestedError, silenceLog: boolean) => void,\n  spanToRecordOn?: any\n): RSCErrorHandler {\n  return (thrownValue: unknown) => {\n    // If the response was closed, we don't need to log the error.\n    if (isAbortError(thrownValue)) return\n\n    const digest = getDigestForWellKnownError(thrownValue)\n\n    if (digest) {\n      return digest\n    }\n\n    if (isReactLargeShellError(thrownValue)) {\n      // TODO: Aggregate\n      console.error(thrownValue)\n      return undefined\n    }\n\n    let err = getProperError(thrownValue) as DigestedError\n    let silenceLog = false\n\n    // If the error already has a digest, respect the original digest,\n    // so it won't get re-generated into another new error.\n    if (err.digest) {\n      const originalError = reactServerErrors.get(err.digest)\n\n      if (originalError) {\n        // This error crossed a react-server boundary (e.g. from a `'use cache'`\n        // render). Reaching the handler means it surfaced (it wasn't caught in\n        // userland), so stamp the digest onto the original to mark it surfaced.\n        // If the original was recorded as `invalidDynamicUsageError` without a\n        // digest (a cache that aborted across the boundary), this is what lets\n        // the dev overlay dedup: the separate forwarding checks for that digest\n        // and skips it.\n        originalError.digest ??= err.digest\n\n        if (process.env.NODE_ENV === 'production') {\n          // In production we use the recovered original (de-obfuscated!) error\n          // for reporting, and don't log it again as it was already logged in\n          // the original environment.\n          err = originalError\n          silenceLog = true\n        }\n      }\n    } else {\n      // TODO-APP: look at using webcrypto instead of string-hash. Requires a promise to be awaited.\n      err.digest =\n        typeof thrownValue === 'string'\n          ? stringHash(thrownValue).toString()\n          : createDigestWithErrorCode(\n              err,\n              stringHash(err.message + (err.stack || '')).toString()\n            )\n    }\n\n    // @TODO by putting this here and not at the top it is possible that\n    // we don't error the build in places we actually expect to\n    if (!reactServerErrors.has(err.digest)) {\n      reactServerErrors.set(err.digest, err)\n    }\n\n    // Format server errors in development to add more helpful error messages\n    if (shouldFormatError) {\n      formatServerError(err)\n    }\n\n    // Don't log the suppressed error during export\n    if (\n      !(\n        isBuildTimePrerendering &&\n        err?.message?.includes(\n          'The specific message is omitted in production builds to avoid leaking sensitive details.'\n        )\n      )\n    ) {\n      // Record exception on the provided span if available, otherwise try active span.\n      const span = spanToRecordOn ?? getTracer().getActiveScopeSpan()\n      if (span) {\n        span.recordException(err)\n        span.setAttribute('error.type', err.name)\n        span.setStatus({\n          code: SpanStatusCode.ERROR,\n          message: err.message,\n        })\n      }\n\n      onReactServerRenderError(err, silenceLog)\n    }\n\n    return err.digest\n  }\n}\n\nexport function createHTMLErrorHandler(\n  shouldFormatError: boolean,\n  isBuildTimePrerendering: boolean,\n  reactServerErrors: Map<string, DigestedError>,\n  allCapturedErrors: Array<unknown>,\n  onHTMLRenderSSRError: (err: DigestedError, errorInfo?: ErrorInfo) => void,\n  spanToRecordOn?: any\n): SSRErrorHandler {\n  return (thrownValue: unknown, errorInfo?: ErrorInfo) => {\n    if (isReactLargeShellError(thrownValue)) {\n      // TODO: Aggregate\n      console.error(thrownValue)\n      return undefined\n    }\n\n    let isSSRError = true\n\n    allCapturedErrors.push(thrownValue)\n\n    // If the response was closed, we don't need to log the error.\n    if (isAbortError(thrownValue)) return\n\n    const digest = getDigestForWellKnownError(thrownValue)\n\n    if (digest) {\n      return digest\n    }\n\n    const err = getProperError(thrownValue) as DigestedError\n\n    // If the error already has a digest, respect the original digest,\n    // so it won't get re-generated into another new error.\n    if (err.digest) {\n      if (reactServerErrors.has(err.digest)) {\n        // This error is likely an obfuscated error from react-server.\n        // We recover the original error here.\n        thrownValue = reactServerErrors.get(err.digest)\n        isSSRError = false\n      } else {\n        // The error is not from react-server but has a digest\n        // from other means so we don't need to produce a new one\n      }\n    } else {\n      err.digest = createDigestWithErrorCode(\n        err,\n        stringHash(\n          err.message + (errorInfo?.componentStack || err.stack || '')\n        ).toString()\n      )\n    }\n\n    // Format server errors in development to add more helpful error messages\n    if (shouldFormatError) {\n      formatServerError(err)\n    }\n\n    // Don't log the suppressed error during export\n    if (\n      !(\n        isBuildTimePrerendering &&\n        err?.message?.includes(\n          'The specific message is omitted in production builds to avoid leaking sensitive details.'\n        )\n      )\n    ) {\n      // HTML errors contain RSC errors as well, filter them out before reporting\n      if (isSSRError) {\n        // Record exception on the provided span if available, otherwise try active span.\n        const span = spanToRecordOn ?? getTracer().getActiveScopeSpan()\n        if (span) {\n          span.recordException(err)\n          span.setAttribute('error.type', err.name)\n          span.setStatus({\n            code: SpanStatusCode.ERROR,\n            message: err.message,\n          })\n        }\n\n        onHTMLRenderSSRError(err, errorInfo)\n      }\n    }\n\n    return err.digest\n  }\n}\n\nexport function isUserLandError(err: any): boolean {\n  return (\n    !isAbortError(err) && !isBailoutToCSRError(err) && !isNextRouterError(err)\n  )\n}\n","// This has to be a shared module which is shared between client component error boundary and dynamic component\nconst BAILOUT_TO_CSR = 'BAILOUT_TO_CLIENT_SIDE_RENDERING'\n\n/** An error that should be thrown when we want to bail out to client-side rendering. */\nexport class BailoutToCSRError extends Error {\n  public readonly digest = BAILOUT_TO_CSR\n\n  constructor(public readonly reason: string) {\n    super(`Bail out to client-side rendering: ${reason}`)\n  }\n}\n\n/** Checks if a passed argument is an error that is thrown if we want to bail out to client-side rendering. */\nexport function isBailoutToCSRError(err: unknown): err is BailoutToCSRError {\n  if (typeof err !== 'object' || err === null || !('digest' in err)) {\n    return false\n  }\n\n  return err.digest === BAILOUT_TO_CSR\n}\n","import {\n  isHTTPAccessFallbackError,\n  type HTTPAccessFallbackError,\n} from './http-access-fallback/http-access-fallback'\nimport { isRedirectError, type RedirectError } from './redirect-error'\n\n/**\n * Returns true if the error is a navigation signal error. These errors are\n * thrown by user code to perform navigation operations and interrupt the React\n * render.\n */\nexport function isNextRouterError(\n  error: unknown\n): error is RedirectError | HTTPAccessFallbackError {\n  return isRedirectError(error) || isHTTPAccessFallbackError(error)\n}\n","// TODO: isWellKnownError -> isNextInternalError\n// isReactLargeShellError -> isWarning\nexport function isReactLargeShellError(\n  error: unknown\n): error is Error & { digest?: string } {\n  return (\n    typeof error === 'object' &&\n    error !== null &&\n    'message' in error &&\n    typeof error.message === 'string' &&\n    error.message.startsWith('This rendered a large document (>')\n  )\n}\n","'use client'\n\nimport type {\n  FocusAndScrollRef,\n  PrefetchKind,\n} from '../../client/components/router-reducer/router-reducer-types'\nimport type { Params } from '../../server/request/params'\nimport type {\n  FlightRouterState,\n  FlightSegmentPath,\n  CacheNode,\n  LoadingModuleData,\n} from './app-router-types'\nimport React from 'react'\n\nexport interface NavigateOptions {\n  scroll?: boolean\n  /**\n   * Transition types to apply when navigating. These types are passed to\n   * [`React.addTransitionType`](https://react.dev/reference/react/addTransitionType)\n   * inside the navigation transition, enabling\n   * [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition) components\n   * to apply different animations based on the type of navigation.\n   */\n  transitionTypes?: string[]\n}\n\nexport interface PrefetchOptions {\n  kind: PrefetchKind\n  onInvalidate?: () => void\n}\n\nexport interface AppRouterInstance {\n  /**\n   * Navigate to the previous history entry.\n   */\n  back(): void\n  /**\n   * Navigate to the next history entry.\n   */\n  forward(): void\n  /**\n   * Refresh the current page.\n   */\n  refresh(): void\n  /**\n   * Refresh the current page. Use in development only.\n   * @internal\n   */\n  hmrRefresh(): void\n  /**\n   * Navigate to the provided href.\n   * Pushes a new history entry.\n   */\n  push(href: string, options?: NavigateOptions): void\n  /**\n   * Navigate to the provided href.\n   * Replaces the current history entry.\n   */\n  replace(href: string, options?: NavigateOptions): void\n  /**\n   * Prefetch the provided href.\n   */\n  prefetch(href: string, options?: PrefetchOptions): void\n  /**\n   * Perform a gesture navigation using prefetched data.\n   * Only available when experimental.gestureTransition is enabled.\n   * @experimental\n   */\n  experimental_gesturePush?(href: string, options?: NavigateOptions): void\n  /**\n   * An opaque string identifier scoped to the current route segment.\n   *\n   * Changes when the surrounding segment is freshly created by a push or\n   * replace navigation. Stays the same for back/forward navigations,\n   * `router.refresh()`, and search-param/hash-only changes.\n   *\n   * Intended to be passed to a React `key` to opt out of state preservation\n   * on fresh navigations:\n   *\n   * ```tsx\n   * <form key={useRouter().bfcacheId}>\n   * ```\n   *\n   * In most cases, prefer resetting state explicitly in an event handler, or\n   * deriving a key from your data (e.g. a draft id from the server). Use\n   * `bfcacheId` only when those patterns aren't a fit.\n   */\n  bfcacheId: string\n}\n\nexport const AppRouterContext = React.createContext<AppRouterInstance | null>(\n  null\n)\nexport const LayoutRouterContext = React.createContext<{\n  parentTree: FlightRouterState\n  parentCacheNode: CacheNode\n  parentSegmentPath: FlightSegmentPath | null\n  parentParams: Params\n  parentLoadingData: LoadingModuleData | null\n  debugNameContext: string\n  url: string\n  isActive: boolean\n} | null>(null)\n\nexport const GlobalLayoutRouterContext = React.createContext<{\n  tree: FlightRouterState\n  focusAndScrollRef: FocusAndScrollRef\n  nextUrl: string | null\n  previousNextUrl: string | null\n}>(null as any)\n\nexport const TemplateContext = React.createContext<React.ReactNode>(null as any)\n\nif (process.env.NODE_ENV !== 'production') {\n  AppRouterContext.displayName = 'AppRouterContext'\n  LayoutRouterContext.displayName = 'LayoutRouterContext'\n  GlobalLayoutRouterContext.displayName = 'GlobalLayoutRouterContext'\n  TemplateContext.displayName = 'TemplateContext'\n}\n\nexport const MissingSlotContext = React.createContext<Set<string>>(new Set())\n","/**\n * This class is used to detect when all cache reads for a given render are settled.\n * We do this to allow for cache warming the prerender without having to continue rendering\n * the remainder of the page. This feature is really only useful when the cacheComponents flag is on\n * and should only be used in codepaths gated with this feature.\n */\n\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport class CacheSignal {\n  private count = 0\n  private earlyListeners: Array<() => void> = []\n  private listeners: Array<() => void> = []\n  private tickPending = false\n  private pendingTimeoutCleanup: (() => void) | null = null\n\n  private subscribedSignals: Set<CacheSignal> | null = null\n\n  constructor() {\n    if (process.env.NEXT_RUNTIME === 'edge') {\n      // we rely on `process.nextTick`, which is not supported in edge\n      throw new InvariantError(\n        'CacheSignal cannot be used in the edge runtime, because `cacheComponents` does not support it.'\n      )\n    }\n  }\n\n  private noMorePendingCaches() {\n    if (!this.tickPending) {\n      this.tickPending = true\n      queueMicrotask(() =>\n        process.nextTick(() => {\n          this.tickPending = false\n          if (this.count === 0) {\n            for (let i = 0; i < this.earlyListeners.length; i++) {\n              this.earlyListeners[i]()\n            }\n            this.earlyListeners.length = 0\n          }\n        })\n      )\n    }\n\n    // After a cache resolves, React will schedule new rendering work:\n    // - in a microtask (when prerendering)\n    // - in setImmediate (when rendering)\n    // To cover both of these, we have to make sure that we let immediates execute at least once after each cache resolved.\n    // We don't know when the pending timeout was scheduled (and if it's about to resolve),\n    // so by scheduling a new one, we can be sure that we'll go around the event loop at least once.\n    if (this.pendingTimeoutCleanup) {\n      // We cancel the timeout in beginRead, so this shouldn't ever be active here,\n      // but we still cancel it defensively.\n      this.pendingTimeoutCleanup()\n    }\n    this.pendingTimeoutCleanup = scheduleImmediateAndTimeoutWithCleanup(\n      this.invokeListenersIfNoPendingReads\n    )\n  }\n\n  private invokeListenersIfNoPendingReads = () => {\n    this.pendingTimeoutCleanup = null\n    if (this.count === 0) {\n      for (let i = 0; i < this.listeners.length; i++) {\n        this.listeners[i]()\n      }\n      this.listeners.length = 0\n    }\n  }\n\n  /**\n   * This promise waits until there are no more in progress cache reads but no later.\n   * This allows for adding more cache reads after to delay cacheReady.\n   */\n  inputReady() {\n    return new Promise<void>((resolve) => {\n      this.earlyListeners.push(resolve)\n      if (this.count === 0) {\n        this.noMorePendingCaches()\n      }\n    })\n  }\n\n  /**\n   * If there are inflight cache reads this Promise can resolve in a microtask however\n   * if there are no inflight cache reads then we wait at least one task to allow initial\n   * cache reads to be initiated.\n   */\n  cacheReady() {\n    return new Promise<void>((resolve) => {\n      this.listeners.push(resolve)\n      if (this.count === 0) {\n        this.noMorePendingCaches()\n      }\n    })\n  }\n\n  beginRead() {\n    this.count++\n\n    // There's a new pending cache, so if there's a `noMorePendingCaches` timeout running,\n    // we should cancel it.\n    if (this.pendingTimeoutCleanup) {\n      this.pendingTimeoutCleanup()\n      this.pendingTimeoutCleanup = null\n    }\n\n    if (this.subscribedSignals !== null) {\n      for (const subscriber of this.subscribedSignals) {\n        subscriber.beginRead()\n      }\n    }\n  }\n\n  endRead() {\n    if (this.count === 0) {\n      throw new InvariantError(\n        'CacheSignal got more endRead() calls than beginRead() calls'\n      )\n    }\n\n    // If this is the last read we need to wait a task before we can claim the cache is settled.\n    // The cache read will likely ping a Server Component which can read from the cache again and this\n    // will play out in a microtask so we need to only resolve pending listeners if we're still at 0\n    // after at least one task.\n    // We only want one task scheduled at a time so when we hit count 1 we don't decrement the counter immediately.\n    // If intervening reads happen before the scheduled task runs they will never observe count 1 preventing reentrency\n    this.count--\n    if (this.count === 0) {\n      this.noMorePendingCaches()\n    }\n\n    if (this.subscribedSignals !== null) {\n      for (const subscriber of this.subscribedSignals) {\n        subscriber.endRead()\n      }\n    }\n  }\n\n  hasPendingReads(): boolean {\n    return this.count > 0\n  }\n\n  trackRead<T>(promise: Promise<T>) {\n    this.beginRead()\n    // `promise.finally()` still rejects, so don't use it here to avoid unhandled rejections\n    const onFinally = this.endRead.bind(this)\n    promise.then(onFinally, onFinally)\n    return promise\n  }\n\n  subscribeToReads(subscriber: CacheSignal): () => void {\n    if (subscriber === this) {\n      throw new InvariantError('A CacheSignal cannot subscribe to itself')\n    }\n    if (this.subscribedSignals === null) {\n      this.subscribedSignals = new Set()\n    }\n    this.subscribedSignals.add(subscriber)\n\n    // we'll notify the subscriber of each endRead() on this signal,\n    // so we need to give it a corresponding beginRead() for each read we have in flight now.\n    for (let i = 0; i < this.count; i++) {\n      subscriber.beginRead()\n    }\n\n    return this.unsubscribeFromReads.bind(this, subscriber)\n  }\n\n  unsubscribeFromReads(subscriber: CacheSignal) {\n    if (!this.subscribedSignals) {\n      return\n    }\n    this.subscribedSignals.delete(subscriber)\n\n    // we don't need to set the set back to `null` if it's empty --\n    // if other signals are subscribing to this one, it'll likely get more subscriptions later,\n    // so we'd have to allocate a fresh set again when that happens.\n  }\n}\n\nfunction scheduleImmediateAndTimeoutWithCleanup(cb: () => void): () => void {\n  // If we decide to clean up the timeout, we want to remove\n  // either the immediate or the timeout, whichever is still pending.\n  let clearPending: () => void\n\n  const immediate = setImmediate(() => {\n    const timeout = setTimeout(cb, 0)\n    clearPending = clearTimeout.bind(null, timeout)\n  })\n  clearPending = clearImmediate.bind(null, immediate)\n\n  return () => clearPending()\n}\n","import type { Params } from '../request/params'\nimport type { SearchParams } from '../request/search-params'\nimport {\n  getVaryParamsAccumulator,\n  workUnitAsyncStorage,\n} from './work-unit-async-storage.external'\n\n/**\n * Accumulates vary params for a single segment (or for metadata/rootParams).\n *\n * A VaryParamsAccumulator is an `AsyncIterable<string>` that can be serialized\n * by React Flight. As params are accessed during render, each newly-seen param\n * name is `add`ed, which yields it into the Flight stream immediately. After\n * rendering, call `close()` (via `finishAccumulatingVaryParams`) to end the\n * iteration.\n *\n * Because each access is flushed into the stream as it happens, the set of\n * accessed params is built up incrementally, with no step at the end of the\n * render that has to run for the client to read anything. If the prerender is\n * aborted by sync I/O, the params yielded before the abort are already in the\n * stream — and they're exactly the params the partial response depends on.\n * This mirrors how `StaleTimeIterable` works (see stale-time.ts).\n *\n * Each name is emitted at most once: `add` dedupes against the set of\n * already-yielded names, so the stream never contains a duplicate.\n *\n * NOTE: like `StaleTimeIterable`, this supports a single concurrent iteration\n * (Flight iterates it exactly once). The shared empty singleton below is the\n * only instance referenced by more than one segment, and it only ever yields\n * \"done\", so concurrent iteration of it is safe.\n */\nexport class VaryParamsAccumulator implements AsyncIterable<string> {\n  private _resolve: ((result: IteratorResult<string>) => void) | null = null\n  private _done = false\n  private _buffer: string[] = []\n  // The set of param names already yielded. Doubles as the dedupe guard so the\n  // same name is never emitted twice.\n  private _seen: Set<string> = new Set()\n\n  /**\n   * Records that a param was accessed. Yields the name into the stream the\n   * first time it's seen; subsequent accesses of the same name are no-ops.\n   */\n  add(paramName: string): void {\n    if (this._done || this._seen.has(paramName)) {\n      return\n    }\n    this._seen.add(paramName)\n    if (this._resolve !== null) {\n      this._resolve({ value: paramName, done: false })\n      this._resolve = null\n    } else {\n      this._buffer.push(paramName)\n    }\n  }\n\n  /** Ends the iteration. Best-effort: if skipped (e.g. on a sync-I/O abort),\n   * the consumer simply reads the params yielded so far. */\n  close(): void {\n    if (this._done) {\n      return\n    }\n    this._done = true\n    if (this._resolve !== null) {\n      this._resolve({ value: undefined, done: true })\n      this._resolve = null\n    }\n  }\n\n  [Symbol.asyncIterator](): AsyncIterator<string> {\n    return {\n      next: () => {\n        if (this._buffer.length > 0) {\n          return Promise.resolve({ value: this._buffer.shift()!, done: false })\n        }\n        if (this._done) {\n          return Promise.resolve({ value: undefined, done: true })\n        }\n        return new Promise<IteratorResult<string>>((resolve) => {\n          this._resolve = resolve\n        })\n      },\n    }\n  }\n}\n\n/**\n * A mutable data structure for accumulating per-segment vary params for an\n * entire server response. It's only used during prerenders. It describes\n * metadata about the response itself.\n */\nexport type ResponseVaryParamsAccumulator = {\n  /** Vary params accumulator for metadata/viewport (the \"head\" segment) */\n  head: VaryParamsAccumulator\n  /** Vary params accumulator for root params access */\n  rootParams: VaryParamsAccumulator\n  /** Vary params accumulators for each route segment */\n  segments: Set<VaryParamsAccumulator>\n}\n\n/**\n * A singleton accumulator that's already closed with no params. Use this for\n * segments where we know upfront that no params will be accessed, such as\n * client components or segments without user code.\n *\n * Benefits:\n * - No need to accumulate or close later\n * - Resilient: reads as an empty set even if other tracking fails\n * - Memory efficient: reuses the same object\n *\n * It's never added to `ResponseVaryParamsAccumulator.segments` (callers pass it\n * directly), so `finishAccumulatingVaryParams` doesn't touch it.\n */\nexport const emptyVaryParamsAccumulator: VaryParamsAccumulator =\n  new VaryParamsAccumulator()\nemptyVaryParamsAccumulator.close()\n\nexport function createResponseVaryParamsAccumulator(): ResponseVaryParamsAccumulator {\n  // Create the head and rootParams accumulators as top-level fields.\n  // Segment accumulators are added to the segments set as they are created.\n  const head = new VaryParamsAccumulator()\n  const rootParams = new VaryParamsAccumulator()\n  const segments = new Set<VaryParamsAccumulator>()\n\n  return {\n    head,\n    rootParams,\n    segments,\n  }\n}\n\n/**\n * Allocates a new VaryParamsAccumulator and adds it to the response accumulator\n * associated with the current WorkUnitStore.\n *\n * Returns an iterable that yields the segment's vary params as they're\n * accessed. The iterable can be passed directly to React Flight for\n * serialization.\n */\nexport function createVaryParamsAccumulator(): VaryParamsAccumulator | null {\n  const workUnitStore = workUnitAsyncStorage.getStore()\n  if (!workUnitStore) {\n    return null\n  }\n  const responseAccumulator = getVaryParamsAccumulator(workUnitStore)\n  if (!responseAccumulator) {\n    return null\n  }\n  const accumulator = new VaryParamsAccumulator()\n  responseAccumulator.segments.add(accumulator)\n  return accumulator\n}\n\nexport function getMetadataVaryParamsAccumulator(): VaryParamsAccumulator | null {\n  const workUnitStore = workUnitAsyncStorage.getStore()\n  if (!workUnitStore) {\n    return null\n  }\n  return getVaryParamsAccumulator(workUnitStore)?.head ?? null\n}\n\n// The metadata and viewport are always delivered in a single payload, so they\n// don't need to be tracked separately. This may change in the future, but for\n// now this is just an alias.\nexport const getViewportVaryParamsAccumulator = getMetadataVaryParamsAccumulator\n\n/**\n * Returns the response-level root params iterable for serialization. Root\n * params are emitted once at the top level (not folded into every segment);\n * the client unions them into each segment's set.\n */\nexport function getRootParamsVaryParamsAccumulator(): VaryParamsAccumulator | null {\n  const workUnitStore = workUnitAsyncStorage.getStore()\n  if (!workUnitStore) {\n    return null\n  }\n  return getVaryParamsAccumulator(workUnitStore)?.rootParams ?? null\n}\n\n/**\n * Records that a param was accessed. Adds the param name to the accumulator.\n */\nexport function accumulateVaryParam(\n  accumulator: VaryParamsAccumulator,\n  paramName: string\n): void {\n  accumulator.add(paramName)\n}\n\n/**\n * Records a root param access.\n */\nexport function accumulateRootVaryParam(paramName: string): void {\n  const rootParamsAccumulator = getRootParamsVaryParamsAccumulator()\n  if (rootParamsAccumulator !== null) {\n    accumulateVaryParam(rootParamsAccumulator, paramName)\n  }\n}\n\nexport function createVaryingParams(\n  accumulator: VaryParamsAccumulator,\n  originalParamsObject: Params,\n  optionalCatchAllParamName: string | null\n): Params {\n  if (optionalCatchAllParamName !== null) {\n    // When there's an optional catch-all param with no value (e.g.,\n    // [[...slug]] at /), the param doesn't exist as a property on the params\n    // object. Use a Proxy to track all param access — both existing params\n    // and the missing optional param — including enumeration patterns like\n    // Object.keys(), spread, for...in, and `in` checks.\n    return new Proxy(originalParamsObject, {\n      get(target, prop, receiver) {\n        if (typeof prop === 'string') {\n          if (\n            prop === optionalCatchAllParamName ||\n            Object.prototype.hasOwnProperty.call(target, prop)\n          ) {\n            accumulateVaryParam(accumulator, prop)\n          }\n        }\n        return Reflect.get(target, prop, receiver)\n      },\n      has(target, prop) {\n        if (prop === optionalCatchAllParamName) {\n          accumulateVaryParam(accumulator, optionalCatchAllParamName)\n        }\n        return Reflect.has(target, prop)\n      },\n      ownKeys(target) {\n        // Enumerating the params object means the user's code may depend on\n        // which params are present, so conservatively track the optional\n        // param as accessed.\n        accumulateVaryParam(accumulator, optionalCatchAllParamName)\n        return Reflect.ownKeys(target)\n      },\n    })\n  }\n\n  // When there's no optional catch-all, all params exist as properties on the\n  // object, so we can use defineProperty getters instead of a Proxy. This is\n  // faster because the engine can optimize property access on regular objects\n  // more aggressively than Proxy trap calls.\n  const underlyingParamsWithVarying: Params = {}\n  for (const paramName in originalParamsObject) {\n    Object.defineProperty(underlyingParamsWithVarying, paramName, {\n      get() {\n        accumulateVaryParam(accumulator, paramName)\n        return originalParamsObject[paramName]\n      },\n      enumerable: true,\n    })\n  }\n  return underlyingParamsWithVarying\n}\n\nexport function createVaryingSearchParams(\n  accumulator: VaryParamsAccumulator,\n  originalSearchParamsObject: SearchParams\n): SearchParams {\n  // Search params have no fixed schema, so any access — missing-key reads, `in`\n  // checks, or enumeration — must register as varying. A Proxy is required\n  // (rather than per-property getters) so that enumeration of an empty\n  // searchParams object still triggers a vary. All accesses bucket into the\n  // single sentinel '?'; the segment is keyed by the whole query string.\n  // TODO: Split into per-param tracking if the cache key evolves.\n  return new Proxy(originalSearchParamsObject, {\n    get(target, prop, receiver) {\n      if (typeof prop === 'string') {\n        accumulateVaryParam(accumulator, '?')\n      }\n      return Reflect.get(target, prop, receiver)\n    },\n    has(target, prop) {\n      if (typeof prop === 'string') {\n        accumulateVaryParam(accumulator, '?')\n      }\n      return Reflect.has(target, prop)\n    },\n    ownKeys(target) {\n      accumulateVaryParam(accumulator, '?')\n      return Reflect.ownKeys(target)\n    },\n  })\n}\n\n/**\n * Closes all accumulators in a ResponseVaryParamsAccumulator, ending their\n * iterables. Call this after rendering is complete.\n *\n * This does NOT merge root params into each segment — root params are\n * serialized separately (at the top level of the response) and unioned in by\n * the client. And it's best-effort: if it's skipped because the render was\n * aborted by sync I/O, the consumer just reads the params each iterable yielded\n * before the abort.\n *\n * If we can't track vary params (e.g., legacy prerender), simply don't call\n * this function - the client treats a missing iterable as \"unknown\" vary\n * params.\n */\nexport function finishAccumulatingVaryParams(\n  responseAccumulator: ResponseVaryParamsAccumulator\n): void {\n  responseAccumulator.head.close()\n  responseAccumulator.rootParams.close()\n  for (const segmentAccumulator of responseAccumulator.segments) {\n    segmentAccumulator.close()\n  }\n}\n","import * as React from 'react'\n\nconst errorRef: { current: null | Error } = { current: null }\n\n// React.cache is currently only available in canary/experimental React channels.\nconst cache =\n  typeof React.cache === 'function'\n    ? React.cache\n    : (fn: (key: unknown) => void) => fn\n\n// When Cache Components is enabled, we record these as errors so that they\n// are captured by the dev overlay as it's more critical to fix these\n// when enabled.\nconst logErrorOrWarn = process.env.__NEXT_CACHE_COMPONENTS\n  ? console.error\n  : console.warn\n\n// We don't want to dedupe across requests.\n// The developer might've just attempted to fix the warning so we should warn again if it still happens.\nconst flushCurrentErrorIfNew = cache(\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars -- cache key\n  (key: unknown) => {\n    try {\n      logErrorOrWarn(errorRef.current)\n    } finally {\n      errorRef.current = null\n    }\n  }\n)\n\n/**\n * Creates a function that logs an error message that is deduped by the userland\n * callsite.\n * This requires no indirection between the call of this function and the userland\n * callsite i.e. there's only a single library frame above this.\n * Do not use on the Client where sourcemaps and ignore listing might be enabled.\n * Only use that for warnings need a fix independent of the callstack.\n *\n * @param getMessage\n * @returns\n */\nexport function createDedupedByCallsiteServerErrorLoggerDev<Args extends any[]>(\n  getMessage: (...args: Args) => Error\n) {\n  return function logDedupedError(...args: Args) {\n    const message = getMessage(...args)\n\n    if (process.env.NODE_ENV !== 'production') {\n      const callStackFrames = new Error().stack?.split('\\n')\n      if (callStackFrames === undefined || callStackFrames.length < 4) {\n        logErrorOrWarn(message)\n      } else {\n        // Error:\n        //   logDedupedError\n        //   asyncApiBeingAccessedSynchronously\n        //   <userland callsite>\n        // TODO: This breaks if sourcemaps with ignore lists are enabled.\n        const key = callStackFrames[4]\n        errorRef.current = message\n        flushCurrentErrorIfNew(key)\n      }\n    } else {\n      logErrorOrWarn(message)\n    }\n  }\n}\n","import {\n  workAsyncStorage,\n  type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { OpaqueFallbackRouteParams } from './fallback-params'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n  createVaryingParams,\n  getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n  throwToInterruptStaticGeneration,\n  postponeWithTracking,\n} from '../app-render/dynamic-rendering'\n\nimport {\n  workUnitAsyncStorage,\n  type PrerenderStorePPR,\n  type PrerenderStoreLegacy,\n  type StaticPrerenderStoreModern,\n  type StaticPrerenderStore,\n  throwInvariantForMissingStore,\n  type PrerenderStoreModernRuntime,\n  type RequestStore,\n  type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n  describeStringPropertyAccess,\n  wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n  makeDevtoolsIOAwarePromise,\n  makeFallbackParamsHangingPromise,\n  makePromiseFromTrigger,\n  trackFallbackParamsAccessed,\n  RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\nimport {\n  isEmptyParams,\n  hasFallbackRouteParams,\n  allParamsAreRootParams,\n} from '../lib/params-utils'\n\nexport type ParamValue = string | Array<string> | undefined\nexport type Params = Record<string, ParamValue>\n\nexport function createParamsFromClient(\n  underlyingParams: Params\n): Promise<Params> {\n  const workStore = workAsyncStorage.getStore()\n  if (!workStore) {\n    throw new InvariantError('Expected workStore to be initialized')\n  }\n  const workUnitStore = workUnitAsyncStorage.getStore()\n  if (workUnitStore) {\n    switch (workUnitStore.type) {\n      case 'prerender':\n      case 'prerender-client':\n      case 'prerender-ppr':\n      case 'prerender-legacy':\n        // Client params don't need additional vary tracking because by the\n        // time they reach the client, the access would have already been\n        // tracked by the server.\n        const varyParamsAccumulator = null\n        return createStaticPrerenderParams(\n          underlyingParams,\n          null,\n          workStore,\n          workUnitStore,\n          varyParamsAccumulator\n        )\n      case 'cache':\n      case 'private-cache':\n      case 'unstable-cache':\n        throw new InvariantError(\n          'createParamsFromClient should not be called in cache contexts.'\n        )\n      case 'prerender-runtime':\n        throw new InvariantError(\n          'createParamsFromClient should not be called in a runtime prerender.'\n        )\n      case 'generate-static-params':\n        throw new InvariantError(\n          'createParamsFromClient should not be called inside generateStaticParams.'\n        )\n      case 'validation-client': {\n        if (workUnitStore.validationSamples) {\n          return createClientParamsInInstantValidation(\n            underlyingParams,\n            workStore,\n            workUnitStore.validationSamples\n          )\n        }\n        return makeUntrackedParams(underlyingParams)\n      }\n      case 'request': {\n        if (workUnitStore.validationSamples) {\n          return createClientParamsInInstantValidation(\n            underlyingParams,\n            workStore,\n            workUnitStore.validationSamples\n          )\n        }\n        if (process.env.NODE_ENV === 'development') {\n          const fallbackParams = workUnitStore.fallbackParams\n          const userspaceParams = underlyingParams\n          return createRenderParamsInDev(\n            underlyingParams,\n            userspaceParams,\n            fallbackParams,\n            workStore,\n            workUnitStore\n          )\n        } else {\n          return createRenderParamsInProd(underlyingParams)\n        }\n      }\n      default:\n        workUnitStore satisfies never\n    }\n  }\n  throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport type CreateServerParamsForMetadata = typeof createServerParamsForMetadata\nexport function createServerParamsForMetadata(\n  underlyingParams: Params,\n  optionalCatchAllParamName: string | null\n): Promise<Params> {\n  const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n  return createServerParamsForServerSegment(\n    underlyingParams,\n    optionalCatchAllParamName,\n    metadataVaryParamsAccumulator\n  )\n}\n\n// routes always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerParamsForRoute(\n  underlyingParams: Params,\n  varyParamsAccumulator: VaryParamsAccumulator | null = null\n): Promise<Params> {\n  const workStore = workAsyncStorage.getStore()\n  if (!workStore) {\n    throw new InvariantError('Expected workStore to be initialized')\n  }\n  const workUnitStore = workUnitAsyncStorage.getStore()\n  if (workUnitStore) {\n    switch (workUnitStore.type) {\n      case 'prerender':\n      case 'prerender-ppr':\n      case 'prerender-legacy':\n        return createStaticPrerenderParams(\n          underlyingParams,\n          null,\n          workStore,\n          workUnitStore,\n          varyParamsAccumulator\n        )\n      case 'prerender-client':\n      case 'validation-client':\n        throw new InvariantError(\n          'createServerParamsForRoute should not be called in client contexts.'\n        )\n      case 'cache':\n      case 'private-cache':\n      case 'unstable-cache':\n        throw new InvariantError(\n          'createServerParamsForRoute should not be called in cache contexts.'\n        )\n      case 'generate-static-params':\n        throw new InvariantError(\n          'createServerParamsForRoute should not be called inside generateStaticParams.'\n        )\n      case 'prerender-runtime': {\n        throw new InvariantError(\n          'createServerParamsForRoute should not be called in runtime prerenders.'\n        )\n      }\n      case 'request':\n        if (process.env.NODE_ENV === 'development') {\n          const fallbackParams = workUnitStore.fallbackParams\n          const userspaceParams = underlyingParams\n          return createRenderParamsInDev(\n            underlyingParams,\n            userspaceParams,\n            fallbackParams,\n            workStore,\n            workUnitStore\n          )\n        } else {\n          return createRenderParamsInProd(underlyingParams)\n        }\n      default:\n        workUnitStore satisfies never\n    }\n  }\n  throwInvariantForMissingStore()\n}\n\nexport function createServerParamsForServerSegment(\n  underlyingParams: Params,\n  optionalCatchAllParamName: string | null,\n  varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n  const workStore = workAsyncStorage.getStore()\n  if (!workStore) {\n    throw new InvariantError('Expected workStore to be initialized')\n  }\n  const workUnitStore = workUnitAsyncStorage.getStore()\n  if (workUnitStore) {\n    switch (workUnitStore.type) {\n      case 'prerender':\n      case 'prerender-client':\n      case 'prerender-ppr':\n      case 'prerender-legacy':\n        return createStaticPrerenderParams(\n          underlyingParams,\n          optionalCatchAllParamName,\n          workStore,\n          workUnitStore,\n          varyParamsAccumulator\n        )\n      case 'validation-client':\n        throw new InvariantError(\n          'createServerParamsForServerSegment should not be called in client contexts.'\n        )\n      case 'cache':\n      case 'private-cache':\n      case 'unstable-cache':\n        throw new InvariantError(\n          'createServerParamsForServerSegment should not be called in cache contexts.'\n        )\n      case 'generate-static-params':\n        throw new InvariantError(\n          'createServerParamsForServerSegment should not be called inside generateStaticParams.'\n        )\n      case 'prerender-runtime':\n        return createRuntimePrerenderParams(\n          underlyingParams,\n          optionalCatchAllParamName,\n          workStore,\n          workUnitStore,\n          varyParamsAccumulator\n        )\n      case 'request': {\n        return createRenderParamsForPage(\n          workStore,\n          workUnitStore,\n          underlyingParams,\n          optionalCatchAllParamName,\n          varyParamsAccumulator\n        )\n      }\n      default:\n        workUnitStore satisfies never\n    }\n  }\n  throwInvariantForMissingStore()\n}\n\nexport function createPrerenderParamsForClientSegment(\n  underlyingParams: Params\n): Promise<Params> {\n  const workStore = workAsyncStorage.getStore()\n  if (!workStore) {\n    throw new InvariantError(\n      'Missing workStore in createPrerenderParamsForClientSegment'\n    )\n  }\n\n  const workUnitStore = workUnitAsyncStorage.getStore()\n  if (workUnitStore) {\n    switch (workUnitStore.type) {\n      case 'prerender':\n      case 'prerender-client':\n        const fallbackParams = workUnitStore.fallbackRouteParams\n        if (fallbackParams) {\n          for (let key in underlyingParams) {\n            if (fallbackParams.has(key)) {\n              // This params object has one or more fallback params, so we need\n              // to consider the awaiting of this params object \"dynamic\". Since\n              // we are in cacheComponents mode we encode this as a promise that never\n              // resolves.\n              return makeFallbackParamsHangingPromise(\n                workUnitStore.renderSignal,\n                workStore.route,\n                '`params`',\n                workUnitStore\n              )\n            }\n          }\n        }\n        break\n      case 'validation-client':\n        throw new InvariantError(\n          'createPrerenderParamsForClientSegment should not be called in validation contexts.'\n        )\n        break\n      case 'cache':\n      case 'private-cache':\n      case 'unstable-cache':\n        throw new InvariantError(\n          'createPrerenderParamsForClientSegment should not be called in cache contexts.'\n        )\n      case 'generate-static-params':\n        throw new InvariantError(\n          'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'\n        )\n      case 'prerender-runtime':\n      case 'prerender-ppr':\n      case 'prerender-legacy':\n      case 'request':\n        break\n      default:\n        workUnitStore satisfies never\n    }\n  }\n  // We're prerendering in a mode that does not abort. We resolve the promise without\n  // any tracking because we're just transporting a value from server to client where the tracking\n  // will be applied.\n  return Promise.resolve(underlyingParams)\n}\n\nfunction createStaticPrerenderParams(\n  underlyingParams: Params,\n  optionalCatchAllParamName: string | null,\n  workStore: WorkStore,\n  prerenderStore: StaticPrerenderStore,\n  varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n  switch (prerenderStore.type) {\n    case 'prerender': {\n      let userspaceParams = underlyingParams\n      if (varyParamsAccumulator !== null) {\n        userspaceParams = createVaryingParams(\n          varyParamsAccumulator,\n          underlyingParams,\n          optionalCatchAllParamName\n        )\n      }\n\n      if (isEmptyParams(underlyingParams)) {\n        // This route has no params.\n        return makeUntrackedParams(userspaceParams)\n      }\n\n      const fallbackParams = prerenderStore.fallbackRouteParams\n      if (hasFallbackRouteParams(underlyingParams, fallbackParams)) {\n        // This params object has one or more fallback params, so we need\n        // to consider the awaiting of this params object dynamic.\n        return makeHangingParams(underlyingParams, workStore, prerenderStore)\n      }\n\n      // All params are static.\n\n      const { stagedRendering } = prerenderStore\n      if (stagedRendering) {\n        // Even if all params are static, we need to exclude them from the app shell\n        // by delaying them to the static stage. However, root params are allowed in shells,\n        // so if all the params are root params, they can be included as well.\n        if (\n          !allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)\n        ) {\n          const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.staticLinkData\n          return stagedRendering.delayUntilStage(\n            staticParamsStage,\n            'params',\n            userspaceParams\n          )\n        }\n      }\n\n      return makeUntrackedParams(userspaceParams)\n    }\n    case 'prerender-client': {\n      const fallbackParams = prerenderStore.fallbackRouteParams\n      if (fallbackParams) {\n        for (const key in underlyingParams) {\n          if (fallbackParams.has(key)) {\n            // This params object has one or more fallback params, so we need\n            // to consider the awaiting of this params object \"dynamic\". Since\n            // we are in cacheComponents mode we encode this as a promise that never\n            // resolves.\n            return makeHangingParams(\n              underlyingParams,\n              workStore,\n              prerenderStore\n            )\n          }\n        }\n      }\n      break\n    }\n    case 'prerender-ppr': {\n      const fallbackParams = prerenderStore.fallbackRouteParams\n      if (fallbackParams) {\n        for (const key in underlyingParams) {\n          if (fallbackParams.has(key)) {\n            return makeErroringParams(\n              underlyingParams,\n              fallbackParams,\n              workStore,\n              prerenderStore\n            )\n          }\n        }\n      }\n      break\n    }\n    case 'prerender-legacy':\n      break\n    default:\n      prerenderStore satisfies never\n  }\n\n  let userspaceParams = underlyingParams\n  if (varyParamsAccumulator !== null) {\n    userspaceParams = createVaryingParams(\n      varyParamsAccumulator,\n      underlyingParams,\n      optionalCatchAllParamName\n    )\n  }\n  return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRuntimePrerenderParams(\n  underlyingParams: Params,\n  optionalCatchAllParamName: string | null,\n  workStore: WorkStore,\n  workUnitStore: PrerenderStoreModernRuntime,\n  varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n  let userspaceParams = underlyingParams\n  if (varyParamsAccumulator !== null) {\n    userspaceParams = createVaryingParams(\n      varyParamsAccumulator,\n      underlyingParams,\n      optionalCatchAllParamName\n    )\n  }\n\n  if (isEmptyParams(underlyingParams)) {\n    // This route has no params.\n    return makeUntrackedParams(userspaceParams)\n  }\n\n  const { stagedRendering } = workUnitStore\n  if (!stagedRendering) {\n    // If there's no staging, we're in a prospective runtime prerender.\n    if (workUnitStore.isSessionShell) {\n      // If we're warming up for a session shell, params should be hanging,\n      // because they'll be a hanging input in the final prerender.\n      return makeHangingParams(underlyingParams, workStore, workUnitStore)\n    } else {\n      return makeUntrackedParams(userspaceParams)\n    }\n  }\n\n  // We don't have fallbackParams in runtime prerenders, so we don't know\n  // when params are static. However, root params are static by definition,\n  // so we can at least check for that.\n  // Note that resolving them without a delay is valid because root params are\n  // allowed in shells.\n  if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n    return makeUntrackedParams(userspaceParams)\n  }\n\n  // Semantically, we should resolve static params in the static stage.\n  // But params are link data, and we need to recover a param-less session shell,\n  // so we delay all params until the runtime stage instead.\n  const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n  return stagedRendering.delayUntilStage(\n    staticParamsStage,\n    'params',\n    userspaceParams\n  )\n}\n\nfunction createRenderParamsForPage(\n  workStore: WorkStore,\n  workUnitStore: RequestStore,\n  underlyingParams: Params,\n  optionalCatchAllParamName: string | null,\n  varyParamsAccumulator: VaryParamsAccumulator | null\n) {\n  const { stagedRendering, asyncApiPromises, validationSamples } = workUnitStore\n\n  // Distinguish the params that we expose to userspace (potentially wrapped in proxies)\n  // and the underlying object containing params values. We do this because wrappers\n  // like `instrumentParamsPromiseWithDevWarnings` need to be able to get the known param names\n  // without triggering other wrapper proxies.\n  let userspaceParams = underlyingParams\n  if (validationSamples) {\n    userspaceParams = createServerParamsProxyForInstantValidation(\n      underlyingParams,\n      workStore,\n      validationSamples\n    )\n  }\n  if (varyParamsAccumulator) {\n    userspaceParams = createVaryingParams(\n      varyParamsAccumulator,\n      userspaceParams,\n      optionalCatchAllParamName\n    )\n  }\n\n  if (stagedRendering && asyncApiPromises) {\n    return createStagedRenderParams(\n      workStore,\n      workUnitStore,\n      stagedRendering,\n      asyncApiPromises,\n      underlyingParams,\n      userspaceParams\n    )\n  }\n\n  // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n  if (process.env.NODE_ENV === 'development') {\n    const fallbackParams = workUnitStore.fallbackParams\n    return createRenderParamsInDev(\n      underlyingParams,\n      userspaceParams,\n      fallbackParams,\n      workStore,\n      workUnitStore\n    )\n  } else {\n    return createRenderParamsInProd(userspaceParams)\n  }\n}\n\nfunction createStagedRenderParams(\n  workStore: WorkStore,\n  workUnitStore: RequestStore,\n  stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n  asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n  underlyingParams: Params,\n  userspaceParams: Params\n) {\n  const promise = createStagedRenderParamsImpl(\n    workUnitStore,\n    stagedRendering,\n    asyncApiPromises,\n    underlyingParams,\n    userspaceParams\n  )\n  if (process.env.NODE_ENV === 'development') {\n    return instrumentParamsPromiseWithDevWarnings(\n      underlyingParams,\n      promise,\n      workStore\n    )\n  } else {\n    return promise\n  }\n}\n\nfunction createStagedRenderParamsImpl(\n  workUnitStore: RequestStore,\n  stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n  asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n  /** The actual param values, without any instrumentation */\n  underlyingParams: Params,\n  /** The params object to return to userspace, possibly wrapped in a proxy */\n  userspaceParams: Params\n) {\n  // If the route has no params, they should resolve immediately.\n  if (isEmptyParams(underlyingParams)) {\n    return makeUntrackedParams(userspaceParams)\n  }\n\n  // If we have fallback params, then they should always resolve in the runtime link data stage.\n  // We do this indirectly via the shared params parent for better debug info.\n  if (hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)) {\n    return createParamsPromiseFromTrigger(\n      asyncApiPromises.sharedParamsParent,\n      userspaceParams\n    )\n  }\n\n  // All params are static.\n\n  // If we're rendering with shells, even static params must be delayed to exclude them from the shell.\n  // However, root params are allowed in shells, so if all the params are root params, they can be included as well.\n  if (!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n    // For a dynamic request we generally want to recover a static shell,\n    // so static params can resolve in the static stage, because session\n    // shells are handled with a separate render.\n    // However, in dev we might need to recover a session shell for instant validation.\n    // This is indicated by `needsSessionShell`.\n    const staticParamsStage = workUnitStore.needsSessionShell\n      ? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n      : RENDER_STAGES_BY_DATA_KIND.staticLinkData\n    return stagedRendering.delayUntilStage(\n      staticParamsStage,\n      'params',\n      userspaceParams\n    )\n  }\n\n  return makeUntrackedParams(userspaceParams)\n}\n\nfunction createParamsPromiseFromTrigger(\n  trigger: Promise<any>,\n  userspaceParams: Params\n) {\n  if (process.env.NODE_ENV === 'development') {\n    // We wrap each instance of params in a `new Promise()`, which lets us show each\n    // await a different set of values. This is important when all awaits\n    // are in third party which would otherwise track all the way to the\n    // internal params.\n    const promise: Promise<Params> = new Promise((resolve, reject) => {\n      trigger.then(() => resolve(userspaceParams), reject)\n    })\n    promise.catch(noop)\n    // @ts-expect-error\n    promise.displayName = 'params'\n    return promise\n  } else {\n    return makePromiseFromTrigger(trigger, userspaceParams)\n  }\n}\n\nfunction noop() {}\n\nfunction createServerParamsProxyForInstantValidation(\n  underlyingParams: Params,\n  workStore: WorkStore,\n  validationSamples: NonNullable<RequestStore['validationSamples']>\n): Params {\n  const { createExhaustiveParamsProxy } =\n    require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n  const declaredParams = new Set(Object.keys(validationSamples.params ?? {}))\n  return createExhaustiveParamsProxy(\n    underlyingParams,\n    declaredParams,\n    workStore.route\n  )\n}\n\nfunction createClientParamsInInstantValidation(\n  underlyingParams: Params,\n  workStore: WorkStore,\n  validationSamples: ValidationStoreClient['validationSamples']\n): Promise<Params> {\n  const { createExhaustiveParamsProxy } =\n    require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n  const declaredParams = new Set(Object.keys(validationSamples?.params ?? {}))\n  const proxiedUnderlying = createExhaustiveParamsProxy(\n    underlyingParams,\n    declaredParams,\n    workStore.route\n  )\n  return Promise.resolve(proxiedUnderlying)\n}\n\nfunction createRenderParamsInProd(userspaceParams: Params): Promise<Params> {\n  return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRenderParamsInDev(\n  underlyingParams: Params,\n  userpaceParams: Params,\n  fallbackParams: OpaqueFallbackRouteParams | null | undefined,\n  workStore: WorkStore,\n  requestStore: RequestStore\n): Promise<Params> {\n  return makeDynamicallyTrackedParamsWithDevWarnings(\n    underlyingParams,\n    userpaceParams,\n    hasFallbackRouteParams(underlyingParams, fallbackParams),\n    workStore,\n    requestStore\n  )\n}\n\ninterface CacheLifetime {}\nconst CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()\n\nconst fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = {\n  get: function get(target, prop, receiver) {\n    if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n      const originalMethod = ReflectAdapter.get(target, prop, receiver)\n\n      return {\n        [prop]: (...args: unknown[]) => {\n          // Record against the store that's active at access time: the\n          // hanging promise is cached by params object across prerender\n          // stores, so the store that created it may not be the one that's\n          // rendering when it's finally awaited.\n          const workUnitStore = workUnitAsyncStorage.getStore()\n          if (workUnitStore !== undefined) {\n            trackFallbackParamsAccessed(workUnitStore)\n          }\n\n          const store = dynamicAccessAsyncStorage.getStore()\n\n          if (store) {\n            store.abortController.abort(\n              new Error(`Accessed fallback \\`params\\` during prerendering.`)\n            )\n          }\n\n          return new Proxy(\n            originalMethod.apply(target, args),\n            fallbackParamsProxyHandler\n          )\n        },\n      }[prop]\n    }\n\n    return ReflectAdapter.get(target, prop, receiver)\n  },\n}\n\nfunction makeHangingParams(\n  underlyingParams: Params,\n  workStore: WorkStore,\n  prerenderStore: StaticPrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<Params> {\n  const cachedParams = CachedParams.get(underlyingParams)\n  if (cachedParams) {\n    return cachedParams\n  }\n\n  const promise = new Proxy(\n    makeFallbackParamsHangingPromise<Params>(\n      prerenderStore.renderSignal,\n      workStore.route,\n      '`params`',\n      // This promise is created for every segment on a fallback route whether\n      // or not it reads params, so recording the access at creation would mark\n      // every render. The access is tracked in the proxy traps instead.\n      null\n    ),\n    fallbackParamsProxyHandler\n  )\n\n  CachedParams.set(underlyingParams, promise)\n\n  return promise\n}\n\nfunction makeErroringParams(\n  underlyingParams: Params,\n  fallbackParams: OpaqueFallbackRouteParams,\n  workStore: WorkStore,\n  prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy\n): Promise<Params> {\n  const cachedParams = CachedParams.get(underlyingParams)\n  if (cachedParams) {\n    return cachedParams\n  }\n\n  const augmentedUnderlying = { ...underlyingParams }\n\n  // We don't use makeResolvedReactPromise here because params\n  // supports copying with spread and we don't want to unnecessarily\n  // instrument the promise with spreadable properties of ReactPromise.\n  const promise = Promise.resolve(augmentedUnderlying)\n  CachedParams.set(underlyingParams, promise)\n\n  Object.keys(underlyingParams).forEach((prop) => {\n    if (wellKnownProperties.has(prop)) {\n      // These properties cannot be shadowed because they need to be the\n      // true underlying value for Promises to work correctly at runtime\n    } else {\n      if (fallbackParams.has(prop)) {\n        Object.defineProperty(augmentedUnderlying, prop, {\n          get() {\n            const expression = describeStringPropertyAccess('params', prop)\n            // In most dynamic APIs we also throw if `dynamic = \"error\"` however\n            // for params is only dynamic when we're generating a fallback shell\n            // and even when `dynamic = \"error\"` we still support generating dynamic\n            // fallback shells\n            // TODO remove this comment when cacheComponents is the default since there\n            // will be no `dynamic = \"error\"`\n            if (prerenderStore.type === 'prerender-ppr') {\n              // PPR Prerender (no cacheComponents)\n              postponeWithTracking(\n                workStore.route,\n                expression,\n                prerenderStore.dynamicTracking\n              )\n            } else {\n              // Legacy Prerender\n              throwToInterruptStaticGeneration(\n                expression,\n                workStore,\n                prerenderStore\n              )\n            }\n          },\n          enumerable: true,\n        })\n      }\n    }\n  })\n\n  return promise\n}\n\nfunction makeUntrackedParams(underlyingParams: Params): Promise<Params> {\n  const cachedParams = CachedParams.get(underlyingParams)\n  if (cachedParams) {\n    return cachedParams\n  }\n\n  const promise = Promise.resolve(underlyingParams)\n  CachedParams.set(underlyingParams, promise)\n\n  return promise\n}\n\nfunction makeDynamicallyTrackedParamsWithDevWarnings(\n  underlyingParams: Params,\n  userspaceParams: Params,\n  hasFallbackParams: boolean,\n  workStore: WorkStore,\n  requestStore: RequestStore\n): Promise<Params> {\n  const cachedParams = CachedParams.get(underlyingParams)\n  if (cachedParams) {\n    return cachedParams\n  }\n\n  // We don't use makeResolvedReactPromise here because params\n  // supports copying with spread and we don't want to unnecessarily\n  // instrument the promise with spreadable properties of ReactPromise.\n  const promise = hasFallbackParams\n    ? makeDevtoolsIOAwarePromise(\n        userspaceParams,\n        requestStore,\n        RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n      )\n    : // We don't want to force an environment transition when this params is not part of the fallback params set\n      Promise.resolve(userspaceParams)\n\n  const proxiedPromise = instrumentParamsPromiseWithDevWarnings(\n    underlyingParams,\n    promise,\n    workStore\n  )\n  CachedParams.set(underlyingParams, proxiedPromise)\n  return proxiedPromise\n}\n\nfunction instrumentParamsPromiseWithDevWarnings(\n  underlyingParams: Params,\n  promise: Promise<Params>,\n  workStore: WorkStore\n): Promise<Params> {\n  // Track which properties we should warn for.\n  const proxiedProperties = new Set<string>()\n\n  Object.keys(underlyingParams).forEach((prop) => {\n    if (wellKnownProperties.has(prop)) {\n      // These properties cannot be shadowed because they need to be the\n      // true underlying value for Promises to work correctly at runtime\n    } else {\n      proxiedProperties.add(prop)\n    }\n  })\n\n  return new Proxy(promise, {\n    get(target, prop, receiver) {\n      if (typeof prop === 'string') {\n        if (\n          // We are accessing a property that was proxied to the promise instance\n          proxiedProperties.has(prop)\n        ) {\n          const expression = describeStringPropertyAccess('params', prop)\n          warnForSyncAccess(workStore.route, expression)\n        }\n      }\n      return ReflectAdapter.get(target, prop, receiver)\n    },\n    set(target, prop, value, receiver) {\n      if (typeof prop === 'string') {\n        proxiedProperties.delete(prop)\n      }\n      return ReflectAdapter.set(target, prop, value, receiver)\n    },\n    ownKeys(target) {\n      const expression = '`...params` or similar expression'\n      warnForSyncAccess(workStore.route, expression)\n      return Reflect.ownKeys(target)\n    },\n  })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n  createParamsAccessError\n)\n\nfunction createParamsAccessError(\n  route: string | undefined,\n  expression: string\n) {\n  const prefix = route ? `Route \"${route}\" ` : 'This route '\n  return new Error(\n    `${prefix}used ${expression}. ` +\n      `\\`params\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n      `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n  )\n}\n","import { InvariantError } from '../../shared/lib/invariant-error'\n\ntype PendingLazyModule<TModule> = {\n  status: 'pending'\n  /** Resolves to the settled state, and never rejects. */\n  promise: Promise<SettledLazyModule<TModule>>\n}\n\ntype SettledLazyModule<TModule> =\n  | { status: 'resolved'; module: TModule }\n  | { status: 'rejected'; reason: unknown }\n\nexport class LazyModule<TModule> {\n  private state:\n    | { status: 'uninitialized' }\n    | PendingLazyModule<TModule>\n    | SettledLazyModule<TModule> = { status: 'uninitialized' }\n\n  constructor(\n    private readonly load: () => TModule | Promise<TModule>,\n    private readonly onLoad: (module: TModule) => void\n  ) {}\n\n  loadIfNeeded(): void {\n    if (this.state.status !== 'uninitialized') {\n      return\n    }\n\n    const result = this.load()\n\n    if (!(result instanceof Promise)) {\n      this.onLoad(result)\n      this.state = { status: 'resolved', module: result }\n      return\n    }\n\n    this.state = {\n      status: 'pending',\n      promise: result\n        .then((module) => {\n          this.onLoad(module)\n          const resolved: SettledLazyModule<TModule> = {\n            status: 'resolved',\n            module,\n          }\n          this.state = resolved\n          return resolved\n        })\n        .catch((reason) => {\n          const rejected: SettledLazyModule<TModule> = {\n            status: 'rejected',\n            reason,\n          }\n          this.state = rejected\n          return rejected\n        }),\n    }\n  }\n\n  async waitUntilLoaded(): Promise<void> {\n    this.loadIfNeeded()\n\n    let state = this.state\n\n    if (state.status === 'pending') {\n      state = await state.promise\n    }\n\n    if (state.status === 'rejected') {\n      throw state.reason\n    }\n  }\n\n  assertLoaded(): TModule {\n    this.loadIfNeeded()\n\n    const state = this.state\n\n    if (state.status === 'resolved') {\n      return state.module\n    }\n\n    if (state.status === 'rejected') {\n      throw state.reason\n    }\n\n    throw new InvariantError(\n      'The lazy module is still loading. It must be awaited with `waitUntilLoaded()` before it can be accessed.'\n    )\n  }\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 { NextConfig } from '../../config-shared'\nimport type { AppRouteRouteDefinition } from '../../route-definitions/app-route-route-definition'\nimport type { AppSegmentConfig } from '../../../build/segment-config/app/app-segment-config'\nimport type { NextRequest } from '../../web/spec-extension/request'\nimport type { NextURL } from '../../web/next-url'\nimport type { DeepReadonly } from '../../../shared/lib/deep-readonly'\nimport type { WorkUnitStore } from '../../app-render/work-unit-async-storage.external'\nimport type { __ApiPreviewProps } from '../../api-utils'\n\nimport {\n  RouteModule,\n  type RouteModuleHandleContext,\n  type RouteModuleOptions,\n} from '../route-module'\nimport { createRequestStoreForAPI } from '../../async-storage/request-store'\nimport {\n  createWorkStore,\n  type WorkStoreContext,\n} from '../../async-storage/work-store'\nimport { type HTTP_METHOD, HTTP_METHODS, isHTTPMethod } from '../../web/http'\nimport { getImplicitTags, type ImplicitTags } from '../../lib/implicit-tags'\nimport { patchFetch } from '../../lib/patch-fetch'\nimport { getTracer } from '../../lib/trace/tracer'\nimport { AppRouteRouteHandlersSpan } from '../../lib/trace/constants'\nimport * as Log from '../../../build/output/log'\nimport { autoImplementMethods } from './helpers/auto-implement-methods'\nimport {\n  appendMutableCookies,\n  type ReadonlyRequestCookies,\n} from '../../web/spec-extension/adapters/request-cookies'\nimport { HeadersAdapter } from '../../web/spec-extension/adapters/headers'\nimport { RequestCookiesAdapter } from '../../web/spec-extension/adapters/request-cookies'\nimport { parsedUrlQueryToParams } from './helpers/parsed-url-query-to-params'\nimport {\n  Phase,\n  printDebugThrownValueForProspectiveRender,\n} from '../../app-render/prospective-render-utils'\n\nimport * as serverHooks from '../../../client/components/hooks-server-context'\nimport { DynamicServerError } from '../../../client/components/hooks-server-context'\n\nimport {\n  workAsyncStorage,\n  type WorkStore,\n} from '../../app-render/work-async-storage.external'\nimport {\n  workUnitAsyncStorage,\n  type RequestStore,\n  type PrerenderStore,\n} from '../../app-render/work-unit-async-storage.external'\nimport {\n  actionAsyncStorage,\n  type ActionStore,\n} from '../../app-render/action-async-storage.external'\nimport * as sharedModules from './shared-modules'\nimport { getIsPossibleServerAction } from '../../lib/server-action-request-meta'\nimport { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies'\nimport { cleanURL } from './helpers/clean-url'\nimport { StaticGenBailoutError } from '../../../client/components/static-generation-bailout'\nimport { isStaticGenEnabled } from './helpers/is-static-gen-enabled'\nimport {\n  abortAndThrowOnSynchronousRequestDataAccess,\n  postponeWithTracking,\n  createDynamicTrackingState,\n  getFirstDynamicReason,\n} from '../../app-render/dynamic-rendering'\nimport { ReflectAdapter } from '../../web/spec-extension/adapters/reflect'\nimport type { RenderOptsPartial } from '../../app-render/types'\nimport { CacheSignal } from '../../app-render/cache-signal'\nimport { scheduleImmediate } from '../../../lib/scheduler'\nimport { createServerParamsForRoute } from '../../request/params'\nimport type { AppSegment } from '../../../build/segment-config/app/app-segments'\nimport {\n  getRedirectStatusCodeFromError,\n  getURLFromRedirectError,\n} from '../../../client/components/redirect'\nimport {\n  isRedirectError,\n  type RedirectError,\n} from '../../../client/components/redirect-error'\nimport {\n  getAccessFallbackHTTPStatus,\n  isHTTPAccessFallbackError,\n} from '../../../client/components/http-access-fallback/http-access-fallback'\nimport { RedirectStatusCode } from '../../../client/components/redirect-status-code'\nimport { INFINITE_CACHE } from '../../../lib/constants'\nimport { executeRevalidates } from '../../revalidation-utils'\nimport { trackPendingModules } from '../../app-render/module-loading/track-module-loading.external'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport { LazyModule } from '../../lib/lazy-module'\nimport { createPrerenderResumeDataCache } from '../../resume-data-cache/resume-data-cache'\n\nexport class WrappedNextRouterError {\n  constructor(\n    public readonly error: RedirectError,\n    public readonly headers?: Headers\n  ) {}\n}\n\n/**\n * The AppRouteModule is the type of the module exported by the bundled App\n * Route module.\n */\nexport type AppRouteModule = typeof import('../../../build/templates/app-route')\n\nexport type AppRouteSharedContext = {\n  buildId: string\n  deploymentId: string\n}\n\n/**\n * AppRouteRouteHandlerContext is the context that is passed to the route\n * handler for app routes.\n */\nexport interface AppRouteRouteHandlerContext extends RouteModuleHandleContext {\n  renderOpts: WorkStoreContext['renderOpts'] &\n    Pick<RenderOptsPartial, 'onInstrumentationRequestError'> &\n    CollectedCacheInfo\n  previewProps: DeepReadonly<__ApiPreviewProps>\n  sharedContext: AppRouteSharedContext\n}\n\ntype CollectedCacheInfo = {\n  collectedTags?: string\n  collectedRevalidate?: number\n  collectedExpire?: number\n  collectedStale?: number\n}\n\n/**\n * AppRouteHandlerFnContext is the context that is passed to the handler as the\n * second argument.\n */\ntype AppRouteHandlerFnContext = {\n  params?: Promise<Record<string, string | string[] | undefined>>\n}\n\n/**\n * Handler function for app routes. If a non-Response value is returned, an error\n * will be thrown.\n */\nexport type AppRouteHandlerFn = (\n  /**\n   * Incoming request object.\n   */\n  req: NextRequest,\n  /**\n   * Context properties on the request (including the parameters if this was a\n   * dynamic route).\n   */\n  ctx: AppRouteHandlerFnContext\n) => unknown\n\n/**\n * AppRouteHandlers describes the handlers for app routes that is provided by\n * the userland module.\n */\nexport type AppRouteHandlers = {\n  [method in HTTP_METHOD]?: AppRouteHandlerFn\n}\n\n/**\n * AppRouteUserlandModule is the userland module that is provided for app\n * routes. This contains all the user generated code.\n */\nexport type AppRouteUserlandModule = AppRouteHandlers &\n  Pick<\n    AppSegmentConfig,\n    'dynamic' | 'revalidate' | 'dynamicParams' | 'fetchCache'\n  > &\n  Pick<AppSegment, 'generateStaticParams'>\n\n/**\n * AppRouteRouteModuleOptions is the options that are passed to the app route\n * module from the bundled code.\n */\nexport interface AppRouteRouteModuleOptions\n  extends Omit<\n    RouteModuleOptions<AppRouteRouteDefinition, AppRouteUserlandModule>,\n    'userland'\n  > {\n  readonly userland: () =>\n    | AppRouteUserlandModule\n    | Promise<AppRouteUserlandModule>\n  readonly resolvedPagePath: string\n  readonly nextConfigOutput: NextConfig['output']\n  /**\n   * Optional synchronous getter that returns the live userland module. When\n   * provided (Turbopack dev mode), it is called on every request so that\n   * server HMR updates are picked up without re-executing the entry chunk.\n   * Using require() instead of import() keeps this synchronous so the time\n   * spent here is not incorrectly attributed to application-code in timing.\n   */\n  readonly getUserland?: () => AppRouteUserlandModule\n}\n\n/**\n * AppRouteRouteHandler is the handler for app routes.\n */\nexport class AppRouteRouteModule extends RouteModule<\n  AppRouteRouteDefinition,\n  AppRouteUserlandModule\n> {\n  /**\n   * A reference to the request async storage.\n   */\n  public readonly workUnitAsyncStorage = workUnitAsyncStorage\n\n  /**\n   * A reference to the static generation async storage.\n   */\n  public readonly workAsyncStorage = workAsyncStorage\n\n  /**\n   * An interface to call server hooks which interact with the underlying\n   * storage.\n   */\n  public readonly serverHooks = serverHooks\n\n  public static readonly sharedModules = sharedModules\n\n  /**\n   * A reference to the mutation related async storage, such as mutations of\n   * cookies.\n   */\n  public readonly actionAsyncStorage = actionAsyncStorage\n\n  public readonly resolvedPagePath: string\n  public readonly nextConfigOutput: NextConfig['output'] | undefined\n\n  // Loaded lazily since the route file may be an async module (top-level\n  // await).\n  private readonly _lazyUserland: LazyModule<AppRouteUserlandModule>\n  // Synchronous per-request userland getter for Turbopack dev mode.\n  // Called on every request to pick up server HMR updates.\n  private readonly _getUserland?: () => AppRouteUserlandModule\n  private _methods!: Record<HTTP_METHOD, AppRouteHandlerFn>\n  private _hasNonStaticMethods!: boolean\n  private _dynamic!: AppRouteUserlandModule['dynamic']\n\n  override get userland(): AppRouteUserlandModule {\n    return this._lazyUserland.assertLoaded()\n  }\n\n  /**\n   * Ensures the userland module is fully loaded before it's accessed via\n   * `userland`. Required for route files that use top-level await, where\n   * require() returns a promise instead of the module directly. Must be called\n   * before accessing `userland` in contexts where the module may not yet be\n   * resolved (e.g. the export/static-generation worker).\n   */\n  async ensureUserland(): Promise<void> {\n    await this._lazyUserland.waitUntilLoaded()\n  }\n\n  constructor({\n    userland,\n    getUserland,\n    definition,\n    distDir,\n    relativeProjectDir,\n    resolvedPagePath,\n    nextConfigOutput,\n  }: AppRouteRouteModuleOptions) {\n    super({\n      userland: undefined! as AppRouteUserlandModule,\n      definition,\n      distDir,\n      relativeProjectDir,\n    })\n\n    this.resolvedPagePath = resolvedPagePath\n    this.nextConfigOutput = nextConfigOutput\n    this._getUserland = getUserland\n    this._lazyUserland = new LazyModule(userland, (module) =>\n      this._onUserlandLoaded(module)\n    )\n\n    // output:export routes load eagerly, so that errors surface at module\n    // load time (as a Redbox in dev) rather than at request time.\n    if (nextConfigOutput === 'export') {\n      this._lazyUserland.loadIfNeeded()\n    }\n  }\n\n  private _onUserlandLoaded(userland: AppRouteUserlandModule): void {\n    // Automatically implement some methods if they aren't implemented by the\n    // userland module.\n    this._methods = autoImplementMethods(userland)\n\n    // Get the non-static methods for this route.\n    this._hasNonStaticMethods = hasNonStaticMethods(userland)\n\n    // Get the dynamic property from the userland module.\n    this._dynamic = userland.dynamic\n    if (this.nextConfigOutput === 'export') {\n      if (this._dynamic === 'force-dynamic') {\n        throw new Error(\n          `export const dynamic = \"force-dynamic\" on page \"${this.definition.pathname}\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export`\n        )\n      } else if (!isStaticGenEnabled(userland) && userland['GET']) {\n        throw new Error(\n          `export const dynamic = \"force-static\"/export const revalidate not configured on route \"${this.definition.pathname}\" with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export`\n        )\n      } else {\n        this._dynamic = 'error'\n      }\n    }\n\n    // We only warn in development after here, so return if we're not in\n    // development.\n    if (process.env.NODE_ENV === 'development') {\n      // Print error in development if the exported handlers are in lowercase, only\n      // uppercase handlers are supported.\n      const lowercased = HTTP_METHODS.map((method) => method.toLowerCase())\n      for (const method of lowercased) {\n        if (method in userland) {\n          Log.error(\n            `Detected lowercase method '${method}' in '${\n              this.resolvedPagePath\n            }'. Export the uppercase '${method.toUpperCase()}' method name to fix this error.`\n          )\n        }\n      }\n\n      // Print error if the module exports a default handler, they must use named\n      // exports for each HTTP method.\n      if ('default' in userland) {\n        Log.error(\n          `Detected default export in '${this.resolvedPagePath}'. Export a named export for each HTTP method instead.`\n        )\n      }\n\n      // If there is no methods exported by this module, then return a not found\n      // response.\n      if (!HTTP_METHODS.some((method) => method in userland)) {\n        Log.error(\n          `No HTTP methods exported in '${this.resolvedPagePath}'. Export a named export for each HTTP method.`\n        )\n      }\n    }\n  }\n\n  /**\n   * Returns the handler function for the given HTTP method.\n   * Must be called after ensureUserland() has resolved so that _methods is\n   * populated.\n   */\n  private resolveHandler(method: string): AppRouteHandlerFn {\n    // Prevent RCE: only allow recognized HTTP methods.\n    if (!isHTTPMethod(method)) return () => new Response(null, { status: 400 })\n\n    return this._methods[method]\n  }\n\n  /**\n   * Returns the handler for the given method using a live userland snapshot.\n   * Used in Turbopack dev mode to pick up server HMR updates. The userland\n   * is fetched synchronously via require() so no async overhead is added.\n   */\n  private resolveHandlerFromUserland(\n    method: string,\n    userland: AppRouteUserlandModule\n  ): AppRouteHandlerFn {\n    if (!isHTTPMethod(method)) return () => new Response(null, { status: 400 })\n    return autoImplementMethods(userland)[method]\n  }\n\n  private async do(\n    handler: AppRouteHandlerFn,\n    actionStore: ActionStore,\n    workStore: WorkStore,\n    // @TODO refactor to not take this argument but instead construct the RequestStore\n    // inside this function. Right now we get passed a RequestStore even when\n    // we're going to do a prerender. We should probably just split do up into prexecute and execute\n    requestStore: RequestStore,\n    implicitTags: ImplicitTags,\n    request: NextRequest,\n    context: AppRouteRouteHandlerContext\n  ) {\n    const isStaticGeneration = workStore.isStaticGeneration\n    const cacheComponentsEnabled = !!context.renderOpts.cacheComponents\n\n    // Patch the global fetch.\n    patchFetch({\n      workAsyncStorage: this.workAsyncStorage,\n      workUnitAsyncStorage: this.workUnitAsyncStorage,\n    })\n\n    const handlerContext: AppRouteHandlerFnContext = {\n      params: context.params\n        ? createServerParamsForRoute(parsedUrlQueryToParams(context.params))\n        : undefined,\n    }\n\n    const resolvePendingRevalidations = () => {\n      const maybeRevalidatesPromise = executeRevalidates(workStore)\n\n      if (maybeRevalidatesPromise !== false) {\n        context.renderOpts.pendingWaitUntil = maybeRevalidatesPromise.finally(\n          () => {\n            if (process.env.NEXT_PRIVATE_DEBUG_CACHE) {\n              console.log(\n                'pending revalidates promise finished for:',\n                requestStore.url.pathname + requestStore.url.search\n              )\n            }\n          }\n        )\n      }\n    }\n\n    let prerenderStore: null | PrerenderStore = null\n\n    let res: unknown\n    try {\n      if (isStaticGeneration) {\n        const userlandRevalidate = this.userland.revalidate\n        const defaultRevalidate: number =\n          // If the static generation store does not have a revalidate value\n          // set, then we should set it the revalidate value from the userland\n          // module or default to false.\n          userlandRevalidate === false || userlandRevalidate === undefined\n            ? INFINITE_CACHE\n            : userlandRevalidate\n\n        if (cacheComponentsEnabled) {\n          /**\n           * When we are attempting to statically prerender the GET handler of a route.ts module\n           * and cacheComponents is on we follow a similar pattern to rendering.\n           *\n           * We first run the handler letting caches fill. If something synchronously dynamic occurs\n           * during this prospective render then we can infer it will happen on every render and we\n           * just bail out of prerendering.\n           *\n           * Next we run the handler again and we check if we get a result back in a microtask.\n           * Next.js expects the return value to be a Response or a Thenable that resolves to a Response.\n           * Unfortunately Response's do not allow for accessing the response body synchronously or in\n           * a microtask so we need to allow one more task to unwrap the response body. This is a slightly\n           * different semantic than what we have when we render and it means that certain tasks can still\n           * execute before a prerender completes such as a carefully timed setImmediate.\n           *\n           * Functionally though IO should still take longer than the time it takes to unwrap the response body\n           * so our heuristic of excluding any IO should be preserved.\n           */\n          const prospectiveController = new AbortController()\n          let prospectiveRenderIsDynamic = false\n          const cacheSignal = new CacheSignal()\n          let dynamicTracking = createDynamicTrackingState(undefined)\n\n          // TODO: Route handlers are never resumed, so it's counter-intuitive\n          // to use an RDC here. However, we need the data cache to store cached\n          // results in memory during the prospective prerender, so that they\n          // can be retrieved during the final prerender within microtasks. This\n          // is crucial when doing revalidations of a deployed route handler,\n          // where the default cache handler does not do any in-memory caching.\n          const prerenderResumeDataCache = createPrerenderResumeDataCache()\n\n          const prospectiveRoutePrerenderStore: PrerenderStore =\n            (prerenderStore = {\n              type: 'prerender',\n              phase: 'action',\n              // This replicates prior behavior where rootParams is empty in routes\n              // TODO we need to make this have the proper rootParams for this route\n              rootParams: {},\n              fallbackRouteParams: null,\n              implicitTags,\n              renderSignal: prospectiveController.signal,\n              controller: prospectiveController,\n              stagedRendering: null,\n              cacheSignal,\n              // During prospective render we don't use a controller\n              // because we need to let all caches fill.\n              dynamicTracking,\n              revalidate: defaultRevalidate,\n              expire: INFINITE_CACHE,\n              stale: INFINITE_CACHE,\n              tags: [...implicitTags.tags],\n              resumeDataCache: prerenderResumeDataCache,\n              hmrRefreshHash: undefined,\n              varyParamsAccumulator: null,\n              runtimeDataAccessed: null,\n              shouldAttemptStaticPrefetch: null,\n              isFallbackUpgradeable: false,\n            })\n\n          let prospectiveResult\n          try {\n            prospectiveResult = this.workUnitAsyncStorage.run(\n              prospectiveRoutePrerenderStore,\n              handler,\n              request,\n              handlerContext\n            )\n          } catch (err) {\n            if (prospectiveController.signal.aborted) {\n              // the route handler called an API which is always dynamic\n              // there is no need to try again\n              prospectiveRenderIsDynamic = true\n            } else if (\n              process.env.NEXT_DEBUG_BUILD ||\n              process.env.__NEXT_VERBOSE_LOGGING\n            ) {\n              printDebugThrownValueForProspectiveRender(\n                err,\n                workStore.route,\n                Phase.ProspectiveRender\n              )\n            }\n          }\n          if (\n            typeof prospectiveResult === 'object' &&\n            prospectiveResult !== null &&\n            typeof (prospectiveResult as any).then === 'function'\n          ) {\n            // The handler returned a Thenable. We'll listen for rejections to determine\n            // if the route is erroring for dynamic reasons.\n            ;(prospectiveResult as any as Promise<unknown>).then(\n              () => {},\n              (err) => {\n                if (prospectiveController.signal.aborted) {\n                  // the route handler called an API which is always dynamic\n                  // there is no need to try again\n                  prospectiveRenderIsDynamic = true\n                } else if (process.env.NEXT_DEBUG_BUILD) {\n                  printDebugThrownValueForProspectiveRender(\n                    err,\n                    workStore.route,\n                    Phase.ProspectiveRender\n                  )\n                }\n              }\n            )\n          }\n\n          trackPendingModules(cacheSignal)\n          await cacheSignal.cacheReady()\n\n          if (prospectiveRenderIsDynamic) {\n            // the route handler called an API which is always dynamic\n            // there is no need to try again\n            const dynamicReason = getFirstDynamicReason(dynamicTracking)\n            if (dynamicReason) {\n              throw new DynamicServerError(\n                `Route ${workStore.route} couldn't be rendered statically because it used \\`${dynamicReason}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n              )\n            } else {\n              console.error(\n                'Expected Next.js to keep track of reason for opting out of static rendering but one was not found. This is a bug in Next.js'\n              )\n              throw new DynamicServerError(\n                `Route ${workStore.route} couldn't be rendered statically because it used a dynamic API. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n              )\n            }\n          }\n\n          // TODO start passing this controller to the route handler. We should expose\n          // it so the handler to abort inflight requests and other operations if we abort\n          // the prerender.\n          const finalController = new AbortController()\n          dynamicTracking = createDynamicTrackingState(undefined)\n\n          const finalRoutePrerenderStore: PrerenderStore = (prerenderStore = {\n            type: 'prerender',\n            phase: 'action',\n            rootParams: {},\n            fallbackRouteParams: null,\n            implicitTags,\n            renderSignal: finalController.signal,\n            controller: finalController,\n            stagedRendering: null,\n            cacheSignal: null,\n            dynamicTracking,\n            revalidate: defaultRevalidate,\n            expire: INFINITE_CACHE,\n            stale: INFINITE_CACHE,\n            tags: [...implicitTags.tags],\n            resumeDataCache: prerenderResumeDataCache,\n            hmrRefreshHash: undefined,\n            varyParamsAccumulator: null,\n            runtimeDataAccessed: null,\n            shouldAttemptStaticPrefetch: null,\n            isFallbackUpgradeable: false,\n          })\n\n          let responseHandled = false\n          res = await new Promise((resolve, reject) => {\n            scheduleImmediate(async () => {\n              try {\n                const result = await (this.workUnitAsyncStorage.run(\n                  finalRoutePrerenderStore,\n                  handler,\n                  request,\n                  handlerContext\n                ) as Promise<Response>)\n                if (responseHandled) {\n                  // we already rejected in the followup task\n                  return\n                } else if (!(result instanceof Response)) {\n                  // This is going to error but we let that happen below\n                  resolve(result)\n                  return\n                }\n\n                responseHandled = true\n\n                let bodyHandled = false\n                result.arrayBuffer().then((body) => {\n                  if (!bodyHandled) {\n                    bodyHandled = true\n\n                    resolve(\n                      new Response(body, {\n                        headers: result.headers,\n                        status: result.status,\n                        statusText: result.statusText,\n                      })\n                    )\n                  }\n                }, reject)\n                scheduleImmediate(() => {\n                  if (!bodyHandled) {\n                    bodyHandled = true\n                    finalController.abort()\n                    reject(createCacheComponentsError(workStore.route))\n                  }\n                })\n              } catch (err) {\n                reject(err)\n              }\n            })\n            scheduleImmediate(() => {\n              if (!responseHandled) {\n                responseHandled = true\n                finalController.abort()\n                reject(createCacheComponentsError(workStore.route))\n              }\n            })\n          })\n          if (finalController.signal.aborted) {\n            // We aborted from within the execution\n            throw createCacheComponentsError(workStore.route)\n          } else {\n            // We didn't abort during the execution. We can abort now as a matter of semantics\n            // though at the moment nothing actually consumes this signal so it won't halt any\n            // inflight work.\n            finalController.abort()\n          }\n        } else {\n          prerenderStore = {\n            type: 'prerender-legacy',\n            phase: 'action',\n            rootParams: {},\n            implicitTags,\n            revalidate: defaultRevalidate,\n            expire: INFINITE_CACHE,\n            stale: INFINITE_CACHE,\n            tags: [...implicitTags.tags],\n          }\n\n          res = await workUnitAsyncStorage.run(\n            prerenderStore,\n            handler,\n            request,\n            handlerContext\n          )\n        }\n      } else {\n        res = await workUnitAsyncStorage.run(\n          requestStore,\n          handler,\n          request,\n          handlerContext\n        )\n      }\n    } catch (err) {\n      if (isRedirectError(err)) {\n        const url = getURLFromRedirectError(err)\n        if (!url) {\n          throw new Error('Invariant: Unexpected redirect url format')\n        }\n\n        // We need to capture any headers that should be sent on\n        // the response.\n        const headers = new Headers({ Location: url })\n\n        // Let's append any cookies that were added by the\n        // cookie API.\n        // TODO leaving the gate here b/c it indicates that we might not actually want to do this\n        // on every `do` call. During prerender there should be no mutableCookies because\n        appendMutableCookies(headers, requestStore.mutableCookies)\n\n        resolvePendingRevalidations()\n\n        // Return the redirect response.\n        return new Response(null, {\n          // If we're in an action, we want to use a 303 redirect as we don't\n          // want the POST request to follow the redirect, as it could result in\n          // erroneous re-submissions.\n          status: actionStore.isAction\n            ? RedirectStatusCode.SeeOther\n            : getRedirectStatusCodeFromError(err),\n          headers,\n        })\n      } else if (isHTTPAccessFallbackError(err)) {\n        const httpStatus = getAccessFallbackHTTPStatus(err)\n        return new Response(null, { status: httpStatus })\n      }\n\n      throw err\n    }\n\n    // Validate that the response is a valid response object.\n    if (!(res instanceof Response)) {\n      const invalidType =\n        res === null\n          ? 'null'\n          : res === undefined\n            ? 'undefined'\n            : typeof res === 'object'\n              ? res.constructor?.name || 'object'\n              : typeof res\n\n      throw new Error(\n        `No response is returned from route handler '${this.resolvedPagePath}'. ` +\n          `Expected a Response object but received '${invalidType}' (method: ${request.method}, url: ${requestStore.url.pathname}). ` +\n          `Ensure you return a \\`Response\\` or a \\`NextResponse\\` in all branches of your handler.`\n      )\n    }\n\n    context.renderOpts.fetchMetrics = workStore.fetchMetrics\n\n    resolvePendingRevalidations()\n\n    if (prerenderStore) {\n      context.renderOpts.collectedTags = prerenderStore.tags?.join(',')\n      context.renderOpts.collectedRevalidate = prerenderStore.revalidate\n      context.renderOpts.collectedExpire = prerenderStore.expire\n      context.renderOpts.collectedStale = prerenderStore.stale\n    }\n\n    // It's possible cookies were set in the handler, so we need\n    // to merge the modified cookies and the returned response\n    // here.\n    const headers = new Headers(res.headers)\n    if (appendMutableCookies(headers, requestStore.mutableCookies)) {\n      return new Response(res.body, {\n        status: res.status,\n        statusText: res.statusText,\n        headers,\n      })\n    }\n\n    return res\n  }\n\n  public async handle(\n    req: NextRequest,\n    context: AppRouteRouteHandlerContext\n  ): Promise<Response> {\n    // Ensure userland is fully loaded (handles async modules with top-level\n    // await, where require() returns a Promise instead of the module).\n    await this.ensureUserland()\n\n    // In Turbopack dev mode, fetch the live userland module on every request\n    // via the synchronous require() getter so server HMR updates are reflected\n    // immediately. This is cheap — it is just a devModuleCache lookup.\n    // For routes with top-level await, require() may still return a Promise\n    // (async module); in that case fall back to the already-resolved\n    // userland module resolved by ensureUserland() above.\n    const rawLiveUserland = this._getUserland?.()\n    const liveUserland =\n      rawLiveUserland instanceof Promise\n        ? undefined\n        : (rawLiveUserland as AppRouteUserlandModule | undefined)\n\n    const handler = liveUserland\n      ? this.resolveHandlerFromUserland(req.method, liveUserland)\n      : this.resolveHandler(req.method)\n\n    // Get the context for the static generation.\n    const staticGenerationContext: WorkStoreContext = {\n      page: this.definition.page,\n      renderOpts: context.renderOpts,\n      buildId: context.sharedContext.buildId,\n      deploymentId: context.sharedContext.deploymentId,\n      previouslyRevalidatedTags: [],\n    }\n\n    // Use the live userland (if available) for per-request values so HMR\n    // changes to fetchCache, dynamic, etc. are also picked up.\n    const userland = liveUserland ?? this.userland\n\n    // Add the fetchCache option to the renderOpts.\n    staticGenerationContext.renderOpts.fetchCache = userland.fetchCache\n\n    const actionStore: ActionStore = {\n      isAppRoute: true,\n      isAction: getIsPossibleServerAction(req),\n    }\n\n    const implicitTags = await getImplicitTags(\n      this.definition.page,\n      req.nextUrl.pathname,\n      // App Routes don't support unknown route params.\n      null\n    )\n\n    const requestStore = createRequestStoreForAPI(\n      req,\n      req.nextUrl,\n      implicitTags,\n      undefined,\n      context.previewProps,\n      context.renderOpts.hmrRefreshHash\n    )\n\n    const workStore = createWorkStore(staticGenerationContext)\n\n    // Run the handler with the request AsyncLocalStorage to inject the helper\n    // support. We set this to `unknown` because the type is not known until\n    // runtime when we do a instanceof check below.\n    const response: unknown = await this.actionAsyncStorage.run(\n      actionStore,\n      () =>\n        this.workUnitAsyncStorage.run(requestStore, () =>\n          this.workAsyncStorage.run(workStore, async () => {\n            // Check to see if we should bail out of static generation based on\n            // having non-static methods. Use live userland when available so\n            // HMR changes to exported HTTP methods are reflected immediately.\n            const hasNonStatic = liveUserland\n              ? hasNonStaticMethods(liveUserland)\n              : this._hasNonStaticMethods\n            if (hasNonStatic) {\n              if (workStore.isStaticGeneration) {\n                const err = new DynamicServerError(\n                  'Route is configured with methods that cannot be statically generated.'\n                )\n                workStore.dynamicUsageDescription = err.message\n                workStore.dynamicUsageStack = err.stack\n                throw err\n              }\n            }\n\n            // We assume we can pass the original request through however we may end up\n            // proxying it in certain circumstances based on execution type and configuration\n            let request = req\n\n            // Use the live dynamic value when available so HMR changes to\n            // `export const dynamic` are reflected immediately.\n            const dynamic = liveUserland?.dynamic ?? this._dynamic\n\n            // Update the static generation store based on the dynamic property.\n            switch (dynamic) {\n              case 'force-dynamic': {\n                // Routes of generated paths should be dynamic\n                workStore.forceDynamic = true\n                if (workStore.isStaticGeneration) {\n                  const err = new DynamicServerError(\n                    'Route is configured with dynamic = error which cannot be statically generated.'\n                  )\n                  workStore.dynamicUsageDescription = err.message\n                  workStore.dynamicUsageStack = err.stack\n                  throw err\n                }\n                break\n              }\n              case 'force-static':\n                // The dynamic property is set to force-static, so we should\n                // force the page to be static.\n                workStore.forceStatic = true\n                // We also Proxy the request to replace dynamic data on the request\n                // with empty stubs to allow for safely executing as static\n                request = new Proxy(req, forceStaticRequestHandlers)\n                break\n              case 'error':\n                // The dynamic property is set to error, so we should throw an\n                // error if the page is being statically generated.\n                workStore.dynamicShouldError = true\n                if (workStore.isStaticGeneration)\n                  request = new Proxy(req, requireStaticRequestHandlers)\n                break\n              case undefined:\n              case 'auto':\n                // We proxy `NextRequest` to track dynamic access, and\n                // potentially bail out of static generation.\n                request = proxyNextRequest(req, workStore)\n                break\n              default:\n                dynamic satisfies never\n            }\n\n            const tracer = getTracer()\n\n            // Update the root span attribute for the route.\n            const { pathname } = this.definition\n            tracer.setRootSpanAttribute('next.route', pathname)\n\n            return tracer.trace(\n              AppRouteRouteHandlersSpan.runHandler,\n              {\n                spanName: `executing api route (app) ${pathname}`,\n                attributes: {\n                  'next.route': pathname,\n                },\n              },\n              async () =>\n                this.do(\n                  handler,\n                  actionStore,\n                  workStore,\n                  requestStore,\n                  implicitTags,\n                  request,\n                  context\n                )\n            )\n          })\n        )\n    )\n\n    // If the handler did't return a valid response, then return the internal\n    // error response.\n    if (!(response instanceof Response)) {\n      // TODO: validate the correct handling behavior, maybe log something?\n      return new Response(null, { status: 500 })\n    }\n\n    if (response.headers.has('x-middleware-rewrite')) {\n      throw new Error(\n        'NextResponse.rewrite() was used in a app route handler, this is not currently supported. Please remove the invocation to continue.'\n      )\n    }\n\n    if (response.headers.get('x-middleware-next') === '1') {\n      // TODO: move this error into the `NextResponse.next()` function.\n      throw new Error(\n        'NextResponse.next() was used in a app route handler, this is not supported. See here for more info: https://nextjs.org/docs/messages/next-response-next-in-app-route-handler'\n      )\n    }\n\n    return response\n  }\n}\n\nexport default AppRouteRouteModule\n\n/**\n * Gets all the method names for handlers that are not considered static.\n *\n * @param handlers the handlers from the userland module\n * @returns the method names that are not considered static or false if all\n *          methods are static\n */\nexport function hasNonStaticMethods(handlers: AppRouteHandlers): boolean {\n  if (\n    // Order these by how common they are to be used\n    handlers.POST ||\n    handlers.PUT ||\n    handlers.DELETE ||\n    handlers.PATCH ||\n    handlers.OPTIONS\n  ) {\n    return true\n  }\n  return false\n}\n\n// These symbols will be used to stash cached values on Proxied requests without requiring\n// additional closures or storage such as WeakMaps.\nconst nextURLSymbol = Symbol('nextUrl')\nconst requestCloneSymbol = Symbol('clone')\nconst urlCloneSymbol = Symbol('clone')\nconst searchParamsSymbol = Symbol('searchParams')\nconst hrefSymbol = Symbol('href')\nconst toStringSymbol = Symbol('toString')\nconst headersSymbol = Symbol('headers')\nconst cookiesSymbol = Symbol('cookies')\n\ntype RequestSymbolTarget = {\n  [headersSymbol]?: Headers\n  [cookiesSymbol]?: RequestCookies | ReadonlyRequestCookies\n  [nextURLSymbol]?: NextURL\n  [requestCloneSymbol]?: () => NextRequest\n}\n\ntype UrlSymbolTarget = {\n  [searchParamsSymbol]?: URLSearchParams\n  [hrefSymbol]?: string\n  [toStringSymbol]?: () => string\n  [urlCloneSymbol]?: () => NextURL\n}\n\n/**\n * The general technique with these proxy handlers is to prioritize keeping them static\n * by stashing computed values on the Proxy itself. This is safe because the Proxy is\n * inaccessible to the consumer since all operations are forwarded\n */\nconst forceStaticRequestHandlers = {\n  get(\n    target: NextRequest & RequestSymbolTarget,\n    prop: string | symbol,\n    receiver: any\n  ): unknown {\n    switch (prop) {\n      case 'headers':\n        return (\n          target[headersSymbol] ||\n          (target[headersSymbol] = HeadersAdapter.seal(new Headers({})))\n        )\n      case 'cookies':\n        return (\n          target[cookiesSymbol] ||\n          (target[cookiesSymbol] = RequestCookiesAdapter.seal(\n            new RequestCookies(new Headers({}))\n          ))\n        )\n      case 'nextUrl':\n        return (\n          target[nextURLSymbol] ||\n          (target[nextURLSymbol] = new Proxy(\n            target.nextUrl,\n            forceStaticNextUrlHandlers\n          ))\n        )\n      case 'url':\n        // we don't need to separately cache this we can just read the nextUrl\n        // and return the href since we know it will have been stripped of any\n        // dynamic parts. We access via the receiver to trigger the get trap\n        return receiver.nextUrl.href\n      case 'geo':\n      case 'ip':\n        return undefined\n      case 'clone':\n        return (\n          target[requestCloneSymbol] ||\n          (target[requestCloneSymbol] = () =>\n            new Proxy(\n              // This is vaguely unsafe but it's required since NextRequest does not implement\n              // clone. The reason we might expect this to work in this context is the Proxy will\n              // respond with static-amenable values anyway somewhat restoring the interface.\n              // @TODO we need to rethink NextRequest and NextURL because they are not sufficientlly\n              // sophisticated to adequately represent themselves in all contexts. A better approach is\n              // to probably embed the static generation logic into the class itself removing the need\n              // for any kind of proxying\n              target.clone() as NextRequest,\n              forceStaticRequestHandlers\n            ))\n        )\n      default:\n        return ReflectAdapter.get(target, prop, receiver)\n    }\n  },\n  // We don't need to proxy set because all the properties we proxy are ready only\n  // and will be ignored\n}\n\nconst forceStaticNextUrlHandlers = {\n  get(\n    target: NextURL & UrlSymbolTarget,\n    prop: string | symbol,\n    receiver: any\n  ): unknown {\n    switch (prop) {\n      // URL properties\n      case 'search':\n        return ''\n      case 'searchParams':\n        return (\n          target[searchParamsSymbol] ||\n          (target[searchParamsSymbol] = new URLSearchParams())\n        )\n      case 'href':\n        return (\n          target[hrefSymbol] ||\n          (target[hrefSymbol] = cleanURL(target.href).href)\n        )\n      case 'toJSON':\n      case 'toString':\n        return (\n          target[toStringSymbol] ||\n          (target[toStringSymbol] = () => receiver.href)\n        )\n\n      // NextUrl properties\n      case 'url':\n        // Currently nextURL does not expose url but our Docs indicate that it is an available property\n        // I am forcing this to undefined here to avoid accidentally exposing a dynamic value later if\n        // the underlying nextURL ends up adding this property\n        return undefined\n      case 'clone':\n        return (\n          target[urlCloneSymbol] ||\n          (target[urlCloneSymbol] = () =>\n            new Proxy(target.clone(), forceStaticNextUrlHandlers))\n        )\n      default:\n        return ReflectAdapter.get(target, prop, receiver)\n    }\n  },\n}\n\nfunction proxyNextRequest(request: NextRequest, workStore: WorkStore) {\n  const nextUrlHandlers = {\n    get(\n      target: NextURL & UrlSymbolTarget,\n      prop: string | symbol,\n      receiver: any\n    ): unknown {\n      switch (prop) {\n        case 'search':\n        case 'searchParams':\n        case 'url':\n        case 'href':\n        case 'toJSON':\n        case 'toString':\n        case 'origin': {\n          const workUnitStore = workUnitAsyncStorage.getStore()\n          trackDynamic(workStore, workUnitStore, `nextUrl.${prop}`)\n          return ReflectAdapter.get(target, prop, receiver)\n        }\n        case 'clone':\n          return (\n            target[urlCloneSymbol] ||\n            (target[urlCloneSymbol] = () =>\n              new Proxy(target.clone(), nextUrlHandlers))\n          )\n        default:\n          return ReflectAdapter.get(target, prop, receiver)\n      }\n    },\n  }\n\n  const nextRequestHandlers = {\n    get(\n      target: NextRequest & RequestSymbolTarget,\n      prop: string | symbol\n    ): unknown {\n      switch (prop) {\n        case 'nextUrl':\n          return (\n            target[nextURLSymbol] ||\n            (target[nextURLSymbol] = new Proxy(target.nextUrl, nextUrlHandlers))\n          )\n        case 'headers':\n        case 'cookies':\n        case 'url':\n        case 'body':\n        case 'blob':\n        case 'json':\n        case 'text':\n        case 'arrayBuffer':\n        case 'formData': {\n          const workUnitStore = workUnitAsyncStorage.getStore()\n          trackDynamic(workStore, workUnitStore, `request.${prop}`)\n          // The receiver arg is intentionally the same as the target to fix an issue with\n          // edge runtime, where attempting to access internal slots with the wrong `this` context\n          // results in an error.\n          return ReflectAdapter.get(target, prop, target)\n        }\n        case 'clone':\n          return (\n            target[requestCloneSymbol] ||\n            (target[requestCloneSymbol] = () =>\n              new Proxy(\n                // This is vaguely unsafe but it's required since NextRequest does not implement\n                // clone. The reason we might expect this to work in this context is the Proxy will\n                // respond with static-amenable values anyway somewhat restoring the interface.\n                // @TODO we need to rethink NextRequest and NextURL because they are not sufficientlly\n                // sophisticated to adequately represent themselves in all contexts. A better approach is\n                // to probably embed the static generation logic into the class itself removing the need\n                // for any kind of proxying\n                target.clone() as NextRequest,\n                nextRequestHandlers\n              ))\n          )\n        default:\n          // The receiver arg is intentionally the same as the target to fix an issue with\n          // edge runtime, where attempting to access internal slots with the wrong `this` context\n          // results in an error.\n          return ReflectAdapter.get(target, prop, target)\n      }\n    },\n    // We don't need to proxy set because all the properties we proxy are ready only\n    // and will be ignored\n  }\n\n  return new Proxy(request, nextRequestHandlers)\n}\n\nconst requireStaticRequestHandlers = {\n  get(\n    target: NextRequest & RequestSymbolTarget,\n    prop: string | symbol,\n    receiver: any\n  ): unknown {\n    switch (prop) {\n      case 'nextUrl':\n        return (\n          target[nextURLSymbol] ||\n          (target[nextURLSymbol] = new Proxy(\n            target.nextUrl,\n            requireStaticNextUrlHandlers\n          ))\n        )\n      case 'headers':\n      case 'cookies':\n      case 'url':\n      case 'body':\n      case 'blob':\n      case 'json':\n      case 'text':\n      case 'arrayBuffer':\n      case 'formData':\n        throw new StaticGenBailoutError(\n          `Route ${target.nextUrl.pathname} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`request.${prop}\\`.`\n        )\n      case 'clone':\n        return (\n          target[requestCloneSymbol] ||\n          (target[requestCloneSymbol] = () =>\n            new Proxy(\n              // This is vaguely unsafe but it's required since NextRequest does not implement\n              // clone. The reason we might expect this to work in this context is the Proxy will\n              // respond with static-amenable values anyway somewhat restoring the interface.\n              // @TODO we need to rethink NextRequest and NextURL because they are not sufficientlly\n              // sophisticated to adequately represent themselves in all contexts. A better approach is\n              // to probably embed the static generation logic into the class itself removing the need\n              // for any kind of proxying\n              target.clone() as NextRequest,\n              requireStaticRequestHandlers\n            ))\n        )\n      default:\n        return ReflectAdapter.get(target, prop, receiver)\n    }\n  },\n  // We don't need to proxy set because all the properties we proxy are ready only\n  // and will be ignored\n}\n\nconst requireStaticNextUrlHandlers = {\n  get(\n    target: NextURL & UrlSymbolTarget,\n    prop: string | symbol,\n    receiver: any\n  ): unknown {\n    switch (prop) {\n      case 'search':\n      case 'searchParams':\n      case 'url':\n      case 'href':\n      case 'toJSON':\n      case 'toString':\n      case 'origin':\n        throw new StaticGenBailoutError(\n          `Route ${target.pathname} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`nextUrl.${prop}\\`.`\n        )\n      case 'clone':\n        return (\n          target[urlCloneSymbol] ||\n          (target[urlCloneSymbol] = () =>\n            new Proxy(target.clone(), requireStaticNextUrlHandlers))\n        )\n      default:\n        return ReflectAdapter.get(target, prop, receiver)\n    }\n  },\n}\n\nfunction createCacheComponentsError(route: string) {\n  return new DynamicServerError(\n    `Route ${route} couldn't be rendered statically because it used IO that was not cached. See more info here: https://nextjs.org/docs/messages/cache-components`\n  )\n}\n\nfunction trackDynamic(\n  store: WorkStore,\n  workUnitStore: undefined | WorkUnitStore,\n  expression: string\n): void {\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 'cache':\n      case 'private-cache':\n        // TODO: Should we allow reading cookies and search params from the\n        // request for private caches in route handlers?\n        throw new Error(\n          `Route ${store.route} used \"${expression}\" inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \"${expression}\" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n        )\n      case 'unstable-cache':\n        throw new Error(\n          `Route ${store.route} used \"${expression}\" inside a function cached with \"unstable_cache(...)\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \"${expression}\" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n        )\n      case 'prerender':\n        const error = new Error(\n          `Route ${store.route} used ${expression} without first calling \\`await connection()\\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-request`\n        )\n        return abortAndThrowOnSynchronousRequestDataAccess(\n          store.route,\n          expression,\n          error,\n          workUnitStore\n        )\n      case 'prerender-client':\n      case 'validation-client':\n        throw new InvariantError(\n          'A client prerender store should not be used for a route handler.'\n        )\n      case 'prerender-runtime':\n        throw new InvariantError(\n          'A runtime prerender store should not be used for a route handler.'\n        )\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        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          // TODO: This is currently not really needed for route handlers, as it\n          // only controls the ISR status that's shown for pages.\n          workUnitStore.usedDynamic = true\n        }\n        break\n      case 'generate-static-params':\n        break\n      default:\n        workUnitStore satisfies never\n    }\n  }\n}\n","import type { AppRouteModule } from '../module.compiled'\n\n// route handlers are only statically optimized if they define\n// one of these top-level configs manually\n//   - dynamic = 'force-static'\n//   - dynamic = 'error'\n//   - revalidate > 0\n//   - revalidate = false\n//   - generateStaticParams\nexport function isStaticGenEnabled(\n  mod: AppRouteModule['routeModule']['userland']\n) {\n  return (\n    mod.dynamic === 'force-static' ||\n    mod.dynamic === 'error' ||\n    mod.revalidate === false ||\n    (mod.revalidate !== undefined && mod.revalidate > 0) ||\n    typeof mod.generateStaticParams == 'function'\n  )\n}\n","import type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport type { Params } from '../request/params'\n\nexport function hasNonRootStaticParams(\n  params: Params,\n  rootParams: Params,\n  fallbackParams: OpaqueFallbackRouteParams | null | undefined\n) {\n  for (const paramName in params) {\n    if (\n      !Object.hasOwn(rootParams, paramName) &&\n      isStaticParam(paramName, fallbackParams)\n    ) {\n      return true\n    }\n  }\n  return false\n}\n\nfunction isStaticParam(\n  paramName: string,\n  fallbackParams: OpaqueFallbackRouteParams | null | undefined\n) {\n  // NOTE: Assume that undefined fallback params mean that all of the params are static.\n  if (!fallbackParams) return true\n  // If the param isn't a fallback param, it must be static.\n  return !fallbackParams.has(paramName)\n}\n\nexport function allParamsAreRootParams(\n  underlyingParams: Params,\n  rootParams: Params\n) {\n  for (const paramName in underlyingParams) {\n    if (!Object.hasOwn(rootParams, paramName)) {\n      return false\n    }\n  }\n  return true\n}\n\nexport function isEmptyParams(params: Params): boolean {\n  for (const _paramKey in params) {\n    return false\n  }\n  return true\n}\n\nexport function hasFallbackRouteParams(\n  underlyingParams: Params,\n  fallbackParams: OpaqueFallbackRouteParams | null | undefined\n): boolean {\n  if (fallbackParams) {\n    for (let key in underlyingParams) {\n      if (fallbackParams.has(key)) {\n        return true\n      }\n    }\n  }\n  return false\n}\n","import type { ParsedUrlQuery } from 'querystring'\n\n/**\n * Converts the query into params.\n *\n * @param query the query to convert to params\n * @returns the params\n */\nexport function parsedUrlQueryToParams(\n  query: ParsedUrlQuery\n): Record<string, string | string[]> {\n  const params: Record<string, string | string[]> = {}\n\n  for (const [key, value] of Object.entries(query)) {\n    if (typeof value === 'undefined') continue\n    params[key] = value\n  }\n\n  return params\n}\n","import { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n  type UseCacheCacheStore,\n  type FetchCacheStore,\n  type EncryptedBoundArgsCacheStore,\n  serializeUseCacheCacheStore,\n  parseUseCacheCacheStore,\n  type DecryptedBoundArgsCacheStore,\n  type ImageResponseCacheStore,\n  type UseCacheCacheStoreSerialized,\n} from './cache-store'\n\n/**\n * An immutable version of the resume data cache used during rendering.\n * This cache is read-only and cannot be modified once created.\n */\nexport interface RenderResumeDataCache {\n  /**\n   * Discriminator. `false` means this cache is read-only and cannot be filled\n   * with new entries. Used by `ResumeDataCache` consumers to narrow the union\n   * via standard discriminated-union narrowing (e.g. `if\n   * (resumeDataCache.mutable)`).\n   */\n  readonly mutable: false\n\n  /**\n   * A read-only Map store for values cached by the 'use cache' React hook.\n   * The 'set' operation is omitted to enforce immutability.\n   */\n  readonly cache: Omit<UseCacheCacheStore, 'set'>\n\n  /**\n   * A read-only Map store for cached fetch responses.\n   * The 'set' operation is omitted to enforce immutability.\n   */\n  readonly fetch: Omit<FetchCacheStore, 'set'>\n\n  /**\n   * A read-only Map store for encrypted bound args of inline server functions.\n   * The 'set' operation is omitted to enforce immutability.\n   */\n  readonly encryptedBoundArgs: Omit<EncryptedBoundArgsCacheStore, 'set'>\n\n  /**\n   * A read-only Map store for decrypted bound args of inline server functions.\n   * This is only intended for in-memory usage during pre-rendering, and must\n   * not be persisted in the resume store. The 'set' operation is omitted to\n   * enforce immutability.\n   */\n  readonly decryptedBoundArgs: Omit<DecryptedBoundArgsCacheStore, 'set'>\n\n  /**\n   * A read-only in-memory Map store for rendered `ImageResponse` array buffers.\n   * This is only intended for in-memory usage during pre-rendering, and must\n   * not be persisted in the resume store. The 'set' operation is omitted to\n   * enforce immutability.\n   */\n  readonly imageResponses: Omit<ImageResponseCacheStore, 'set'>\n\n  /**\n   * Serialized cache keys that were intentionally skipped during the\n   * prospective prerender (e.g. because the cached function accessed fallback\n   * params or other dynamic data). During the final prerender, a key in this\n   * set is returned as a hanging promise early, without attempting to look up\n   * or generate a cache entry. Optional because this field is intentionally not\n   * serialized and won't be present in deserialized caches.\n   */\n  readonly dynamicCacheKeys?: ReadonlySet<string>\n}\n\n/**\n * A mutable version of the resume data cache used during pre-rendering.\n * This cache allows both reading and writing of cached values.\n */\nexport interface PrerenderResumeDataCache {\n  /**\n   * Discriminator. `true` means this cache is mutable and can be filled with\n   * new entries during this prerender. Used by `ResumeDataCache` consumers to\n   * narrow the union via standard discriminated-union narrowing (e.g.\n   * `if (resumeDataCache.mutable)`).\n   */\n  readonly mutable: true\n\n  /**\n   * A mutable Map store for values cached by the 'use cache' React hook.\n   * Supports both 'get' and 'set' operations to build the cache during\n   * pre-rendering.\n   */\n  readonly cache: UseCacheCacheStore\n\n  /**\n   * A mutable Map store for cached fetch responses.\n   * Supports both 'get' and 'set' operations to build the cache during\n   * pre-rendering.\n   */\n  readonly fetch: FetchCacheStore\n\n  /**\n   * A mutable Map store for encrypted bound args of inline server functions.\n   * Supports both 'get' and 'set' operations to build the cache during\n   * pre-rendering.\n   */\n  readonly encryptedBoundArgs: EncryptedBoundArgsCacheStore\n\n  /**\n   * A mutable Map store for decrypted bound args of inline server functions.\n   * This is only intended for in-memory usage during pre-rendering, and must\n   * not be persisted in the resume store. Supports both 'get' and 'set'\n   * operations to build the cache during pre-rendering.\n   */\n  readonly decryptedBoundArgs: DecryptedBoundArgsCacheStore\n\n  /**\n   * A mutable in-memory Map store for rendered `ImageResponse` array buffers.\n   * Filled during the prospective prerender and read during the final\n   * prerender. Never persisted in the resume store.\n   */\n  readonly imageResponses: ImageResponseCacheStore\n\n  /**\n   * Tracks serialized cache keys that were intentionally skipped during the\n   * prospective prerender (e.g. because the cached function accessed fallback\n   * params or other dynamic data). During the final prerender, a key in this\n   * set is returned as a hanging promise early, without attempting to look up\n   * or generate a cache entry.\n   *\n   * This is intentionally not serialized. It is only used in-memory within a\n   * single prerender cycle (prospective to final). During the resume at request\n   * time, a cache miss for a dynamic key should generate a fresh entry rather\n   * than being short-circuited.\n   */\n  readonly dynamicCacheKeys: Set<string>\n}\n\n/**\n * Discriminated union of the two resume data cache flavors. Consumers should\n * narrow via `resumeDataCache.mutable` to access the mutable Map API (only\n * available on `PrerenderResumeDataCache`).\n */\nexport type ResumeDataCache = RenderResumeDataCache | PrerenderResumeDataCache\n\ntype ResumeStoreSerialized = {\n  store: {\n    cache: {\n      [key: string]: any\n    }\n    fetch: {\n      [key: string]: any\n    }\n    encryptedBoundArgs: {\n      [key: string]: string\n    }\n  }\n}\n\n/**\n * Serializes a resume data cache into a JSON string for storage or\n * transmission. Handles 'use cache' values, fetch responses, and encrypted\n * bound args for inline server functions.\n *\n * @param resumeDataCache - The immutable cache to serialize\n * @returns A Promise that resolves to the serialized cache as a JSON string, or\n * 'null' if empty\n */\nexport async function stringifyResumeDataCache(\n  resumeDataCache: ResumeDataCache,\n  isCacheComponentsEnabled: boolean\n): Promise<string> {\n  if (process.env.NEXT_RUNTIME === 'edge') {\n    throw new InvariantError(\n      '`stringifyResumeDataCache` should not be called in edge runtime.'\n    )\n  } else {\n    if (resumeDataCache.fetch.size === 0 && resumeDataCache.cache.size === 0) {\n      return 'null'\n    }\n\n    const json: ResumeStoreSerialized = {\n      store: {\n        fetch: Object.fromEntries(Array.from(resumeDataCache.fetch.entries())),\n        cache: Object.fromEntries(\n          (\n            await serializeUseCacheCacheStore(\n              resumeDataCache.cache.entries(),\n              isCacheComponentsEnabled\n            )\n          ).filter(\n            (entry): entry is [string, UseCacheCacheStoreSerialized] =>\n              entry !== null\n          )\n        ),\n        encryptedBoundArgs: Object.fromEntries(\n          Array.from(resumeDataCache.encryptedBoundArgs.entries())\n        ),\n      },\n    }\n\n    // Compress the JSON string using zlib. As the data we already want to\n    // decompress is in memory, we use the synchronous deflateSync function.\n    const { deflateSync } = require('node:zlib') as typeof import('node:zlib')\n\n    return deflateSync(JSON.stringify(json)).toString('base64')\n  }\n}\n\n/**\n * Creates a new empty mutable resume data cache for pre-rendering.\n * Initializes fresh Map instances for both the 'use cache' and fetch caches.\n * Used at the start of pre-rendering to begin collecting cached values.\n *\n * @returns A new empty PrerenderResumeDataCache instance\n */\nexport function createPrerenderResumeDataCache(\n  source?: ResumeDataCache\n): PrerenderResumeDataCache {\n  if (source) {\n    return {\n      mutable: true,\n      cache: new Map(source.cache),\n      fetch: new Map(source.fetch),\n      encryptedBoundArgs: new Map(source.encryptedBoundArgs),\n      decryptedBoundArgs: new Map(source.decryptedBoundArgs),\n      imageResponses: new Map(source.imageResponses),\n      dynamicCacheKeys: source.dynamicCacheKeys\n        ? new Set(source.dynamicCacheKeys)\n        : new Set(),\n    }\n  } else {\n    return {\n      mutable: true,\n      cache: new Map(),\n      fetch: new Map(),\n      encryptedBoundArgs: new Map(),\n      decryptedBoundArgs: new Map(),\n      imageResponses: new Map(),\n      dynamicCacheKeys: new Set(),\n    }\n  }\n}\n\n/**\n * Creates an immutable render resume data cache from either:\n * 1. An existing prerender cache instance\n * 2. A serialized cache string\n *\n * @param renderResumeDataCache - A RenderResumeDataCache instance to be used directly\n * @param prerenderResumeDataCache - A PrerenderResumeDataCache instance to convert to immutable\n * @param persistedCache - A serialized cache string to parse\n * @param maxPostponedStateSizeBytes - The max compressed size limit in bytes (used to calculate 5x decompression limit)\n * @returns An immutable RenderResumeDataCache instance\n */\nexport function createRenderResumeDataCache(\n  resumeDataCache: ResumeDataCache\n): RenderResumeDataCache\nexport function createRenderResumeDataCache(\n  persistedCache: string,\n  maxPostponedStateSizeBytes: number | undefined\n): RenderResumeDataCache\nexport function createRenderResumeDataCache(\n  resumeDataCacheOrPersistedCache: ResumeDataCache | string,\n  maxPostponedStateSizeBytes?: number | undefined\n): RenderResumeDataCache {\n  if (process.env.NEXT_RUNTIME === 'edge') {\n    throw new InvariantError(\n      '`createRenderResumeDataCache` should not be called in edge runtime.'\n    )\n  } else {\n    if (typeof resumeDataCacheOrPersistedCache !== 'string') {\n      // If the cache is already read-only, return it directly. Otherwise we\n      // perform a type change by overriding the discriminator — the underlying\n      // Map references are still shared, but callers should treat the result\n      // as immutable.\n      if (!resumeDataCacheOrPersistedCache.mutable) {\n        return resumeDataCacheOrPersistedCache\n      }\n      return { ...resumeDataCacheOrPersistedCache, mutable: false }\n    }\n\n    if (resumeDataCacheOrPersistedCache === 'null') {\n      return {\n        mutable: false,\n        cache: new Map(),\n        fetch: new Map(),\n        encryptedBoundArgs: new Map(),\n        decryptedBoundArgs: new Map(),\n        imageResponses: new Map(),\n      }\n    }\n\n    // This should be a compressed string. Let's decompress it using zlib.\n    // As the data we already want to decompress is in memory, we use the\n    // synchronous inflateSync function.\n    const { inflateSync } = require('node:zlib') as typeof import('node:zlib')\n\n    // Limit decompressed size to prevent zipbomb attacks. This is 5x the\n    // configured maxPostponedStateSize, allowing reasonable compression\n    // ratios while preventing extreme decompression bombs.\n    // Default is 500MB (5x the default 100MB compressed limit).\n    const maxDecompressedSize = maxPostponedStateSizeBytes\n      ? maxPostponedStateSizeBytes * 5\n      : 500 * 1024 * 1024\n\n    let json: ResumeStoreSerialized\n    try {\n      json = JSON.parse(\n        inflateSync(Buffer.from(resumeDataCacheOrPersistedCache, 'base64'), {\n          maxOutputLength: maxDecompressedSize,\n        }).toString('utf-8')\n      )\n    } catch (err: unknown) {\n      if (\n        err instanceof RangeError &&\n        (err as NodeJS.ErrnoException).code === 'ERR_BUFFER_TOO_LARGE'\n      ) {\n        throw new Error(\n          `Decompressed resume data cache exceeded ${maxDecompressedSize} byte limit`\n        )\n      }\n      throw err\n    }\n\n    return {\n      mutable: false,\n      cache: parseUseCacheCacheStore(Object.entries(json.store.cache)),\n      fetch: new Map(Object.entries(json.store.fetch)),\n      encryptedBoundArgs: new Map(\n        Object.entries(json.store.encryptedBoundArgs)\n      ),\n      decryptedBoundArgs: new Map(),\n      imageResponses: new Map(),\n    }\n  }\n}\n","import { RedirectStatusCode } from './redirect-status-code'\nimport {\n  type RedirectType,\n  type RedirectError,\n  isRedirectError,\n  REDIRECT_ERROR_CODE,\n} from './redirect-error'\nimport { actionAsyncStorage } from './server-async-storage'\n\nexport function getRedirectError(\n  url: string,\n  type: RedirectType,\n  statusCode: RedirectStatusCode = RedirectStatusCode.TemporaryRedirect\n): RedirectError {\n  const error = new Error(REDIRECT_ERROR_CODE) as RedirectError\n  error.digest = `${REDIRECT_ERROR_CODE};${type};${url};${statusCode};`\n  return error\n}\n\n/**\n * This function allows you to redirect the user to another URL. It can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * - In a Server Component, this will insert a meta tag to redirect the user to the target page.\n * - In a Route Handler, it will serve a 307 to the caller.\n * - In a Server Action, it will perform a client-side navigation when JavaScript is available or serve a 303 for a progressive enhancement form submission.\n * - In a Server Action, type defaults to 'push' and 'replace' elsewhere.\n *\n * Read more: [Next.js Docs: `redirect`](https://nextjs.org/docs/app/api-reference/functions/redirect)\n */\nexport function redirect(\n  /** The URL to redirect to */\n  url: string,\n  type?: RedirectType\n): never {\n  type ??= actionAsyncStorage?.getStore()?.isAction ? 'push' : 'replace'\n\n  throw getRedirectError(url, type, RedirectStatusCode.TemporaryRedirect)\n}\n\n/**\n * This function allows you to redirect the user to another URL. It can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * - In a Server Component, this will insert a meta tag to redirect the user to the target page.\n * - In a Route Handler, it will serve a 308 to the caller.\n * - In a Server Action, it will perform a client-side navigation when JavaScript is available or serve a 303 for a progressive enhancement form submission.\n *\n * Read more: [Next.js Docs: `redirect`](https://nextjs.org/docs/app/api-reference/functions/redirect)\n */\nexport function permanentRedirect(\n  /** The URL to redirect to */\n  url: string,\n  type: RedirectType = 'replace'\n): never {\n  throw getRedirectError(url, type, RedirectStatusCode.PermanentRedirect)\n}\n\n/**\n * Returns the encoded URL from the error if it's a RedirectError, null\n * otherwise. Note that this does not validate the URL returned.\n *\n * @param error the error that may be a redirect error\n * @return the url if the error was a redirect error\n */\nexport function getURLFromRedirectError(error: RedirectError): string\nexport function getURLFromRedirectError(error: unknown): string | null {\n  if (!isRedirectError(error)) return null\n\n  // Slices off the beginning of the digest that contains the code and the\n  // separating ';'.\n  return error.digest.split(';').slice(2, -2).join(';')\n}\n\nexport function getRedirectTypeFromError(error: RedirectError): RedirectType {\n  if (!isRedirectError(error)) {\n    throw new Error('Not a redirect error')\n  }\n\n  return error.digest.split(';', 2)[1] as RedirectType\n}\n\nexport function getRedirectStatusCodeFromError(error: RedirectError): number {\n  if (!isRedirectError(error)) {\n    throw new Error('Not a redirect error')\n  }\n\n  return Number(error.digest.split(';').at(-2))\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 { WorkStore } from '../app-render/work-async-storage.external'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { RenderOpts } from '../app-render/types'\nimport type { FetchMetric } from '../base-http'\nimport type { RequestLifecycleOpts } from '../base-server'\nimport type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config'\nimport type {\n  ValidationLevel,\n  ResolvedCacheLifeProfiles,\n} from '../config-shared'\n\nimport { AfterContext } from '../after/after-context'\n\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport { createLazyResult, type LazyResult } from '../lib/lazy-result'\nimport { getCacheHandlerEntries } from '../use-cache/handlers'\nimport { createSnapshot } from '../app-render/async-local-storage'\n\nexport type WorkStoreContext = {\n  /**\n   * The page that is being rendered. This relates to the path to the page file.\n   */\n  page: string\n\n  isPrefetchRequest?: boolean\n  nonce?: string\n  renderOpts: {\n    cacheLifeProfiles: ResolvedCacheLifeProfiles\n    staticPageGenerationTimeout: number\n    incrementalCache?: IncrementalCache\n    /**\n     * The hash of the most recent server component change (dev only). Included\n     * in `\"use cache\"` cache keys so that cached entries are revalidated after\n     * an edit, for every client, regardless of whether it runs the HMR client.\n     */\n    hmrRefreshHash?: string\n    isOnDemandRevalidate?: boolean\n    cacheComponents: boolean\n    validationLevel: ValidationLevel\n    fetchCache?: AppSegmentConfig['fetchCache']\n    isPossibleServerAction?: boolean\n    pendingWaitUntil?: Promise<any>\n    experimental: Pick<\n      RenderOpts['experimental'],\n      'isRoutePPREnabled' | 'authInterrupts' | 'useCacheTimeout'\n    >\n\n    /**\n     * Fetch metrics attached in patch-fetch.ts\n     **/\n    fetchMetrics?: FetchMetric[]\n\n    /**\n     * A hack around accessing the store value outside the context of the\n     * request.\n     *\n     * @internal\n     * @deprecated should only be used as a temporary workaround\n     */\n    // TODO: remove this when we resolve accessing the store outside the execution context\n    store?: WorkStore\n  } & Pick<\n    // Pull some properties from RenderOpts so that the docs are also\n    // mirrored.\n    RenderOpts,\n    | 'assetPrefix'\n    | 'supportsDynamicResponse'\n    | 'isBuildTimePrerendering'\n    | 'isDraftMode'\n    | 'isDebugDynamicAccesses'\n  > &\n    RequestLifecycleOpts &\n    Partial<Pick<RenderOpts, 'reactLoadableManifest'>>\n\n  /**\n   * The deployment ID of the current build.\n   */\n  deploymentId: string\n\n  /**\n   * The build ID of the current build.\n   */\n  buildId: string\n\n  // Tags that were previously revalidated (e.g. by a redirecting server action)\n  // and have already been sent to cache handlers.\n  previouslyRevalidatedTags: string[]\n}\n\nexport function createWorkStore({\n  page,\n  renderOpts,\n  isPrefetchRequest,\n  buildId,\n  deploymentId,\n  previouslyRevalidatedTags,\n  nonce,\n}: WorkStoreContext): WorkStore {\n  /**\n   * Rules of Static & Dynamic HTML:\n   *\n   *    1.) We must generate static HTML unless the caller explicitly opts\n   *        in to dynamic HTML support.\n   *\n   *    2.) If dynamic HTML support is requested, we must honor that request\n   *        or throw an error. It is the sole responsibility of the caller to\n   *        ensure they aren't e.g. requesting dynamic HTML for a static page.\n   *\n   *    3.) If the request is in draft mode, we must generate dynamic HTML.\n   *\n   *    4.) If the request is a server action, we must generate dynamic HTML.\n   *\n   * These rules help ensure that other existing features like request caching,\n   * coalescing, and ISR continue working as intended.\n   */\n  const isStaticGeneration =\n    !renderOpts.supportsDynamicResponse &&\n    !renderOpts.isDraftMode &&\n    !renderOpts.isPossibleServerAction\n\n  const shouldTrackFetchMetrics =\n    !!process.env.__NEXT_DEV_SERVER ||\n    // The only times we want to track fetch metrics outside of development is\n    // when we are performing a static generation and we either are in debug\n    // mode, or tracking fetch metrics was specifically opted into.\n    (isStaticGeneration &&\n      (!!process.env.NEXT_DEBUG_BUILD ||\n        process.env.NEXT_SSG_FETCH_METRICS === '1'))\n\n  const store: WorkStore = {\n    isStaticGeneration,\n    page,\n    route: normalizeAppPath(page),\n    incrementalCache:\n      // we fallback to a global incremental cache for edge-runtime locally\n      // so that it can access the fs cache without mocks\n      renderOpts.incrementalCache || (globalThis as any).__incrementalCache,\n    cacheLifeProfiles: renderOpts.cacheLifeProfiles,\n    useCacheTimeout: renderOpts.experimental.useCacheTimeout,\n    staticPageGenerationTimeout: renderOpts.staticPageGenerationTimeout,\n    isBuildTimePrerendering: renderOpts.isBuildTimePrerendering,\n    fetchCache: renderOpts.fetchCache,\n    isOnDemandRevalidate: renderOpts.isOnDemandRevalidate,\n    requestId: undefined,\n    htmlRequestId: undefined,\n\n    isDraftMode: renderOpts.isDraftMode,\n\n    isPrefetchRequest,\n    buildId,\n    deploymentId,\n    reactLoadableManifest: renderOpts?.reactLoadableManifest || {},\n    assetPrefix: renderOpts?.assetPrefix || '',\n    nonce,\n\n    afterContext: createAfterContext(renderOpts),\n    cacheComponentsEnabled: renderOpts.cacheComponents,\n    validationLevel: renderOpts.validationLevel,\n    previouslyRevalidatedTags,\n    requestStartTime: performance.timeOrigin + performance.now(),\n    refreshTagsByCacheKind: createRefreshTagsByCacheKind(),\n    runInCleanSnapshot: createSnapshot(),\n    shouldTrackFetchMetrics,\n    reactServerErrorsByDigest: new Map(),\n  }\n\n  // TODO: remove this when we resolve accessing the store outside the execution context\n  renderOpts.store = store\n\n  return store\n}\n\nfunction createAfterContext(renderOpts: RequestLifecycleOpts): AfterContext {\n  const { waitUntil, onClose, onAfterTaskError } = renderOpts\n  return new AfterContext({\n    waitUntil,\n    onClose,\n    onTaskError: onAfterTaskError,\n  })\n}\n\n/**\n * Creates a map with lazy results that refresh tags for the respective cache\n * kind when they're awaited for the first time.\n */\nfunction createRefreshTagsByCacheKind(): Map<string, LazyResult<void>> {\n  const refreshTagsByCacheKind = new Map<string, LazyResult<void>>()\n  const cacheHandlers = getCacheHandlerEntries()\n\n  if (cacheHandlers) {\n    for (const [kind, cacheHandler] of cacheHandlers) {\n      if ('refreshTags' in cacheHandler) {\n        refreshTagsByCacheKind.set(\n          kind,\n          createLazyResult(async () => cacheHandler.refreshTags())\n        )\n      }\n    }\n  }\n\n  return refreshTagsByCacheKind\n}\n","/**\n * Cleans a URL by stripping the protocol, host, and search params.\n *\n * @param urlString the url to clean\n * @returns the cleaned url\n */\n\nexport function cleanURL(url: string | URL): URL {\n  const u = new URL(url)\n  u.host = 'localhost:3000'\n  u.search = ''\n  u.protocol = 'http'\n  return u\n}\n"],"names":["Object","Date","Boolean","encodeURIComponent","Map","decodeURIComponent","p","Number","Symbol","Array","n","r","JSON","s","__nccwpck_require__","__dirname","e","TypeError","a","isNaN","isFinite","Math","t","o","arguments","Promise","Error","setTimeout","clearTimeout","clearInterval","setInterval","i","u","v","RegExp","String","reportError","process","console","env","stdout","globalThis","enabled","NO_COLOR","FORCE_COLOR","isTTY","CI","TERM","replaceClose","str","close","replace","index","start","substring","end","length","nextIndex","indexOf","formatter","open","input","string","bold","red","green","yellow","magenta","white","prefixes","wait","error","warn","ready","info","event","trace","LOGGING_METHOD","log","prefixedLog","prefixType","message","undefined","shift","consoleMethod","prefix","warnOnceCache","LRUCache","value","warnOnce","key","join","has","set","HTML_CONTENT_TYPE_HEADER","NEXT_QUERY_PARAM_PREFIX","NEXT_INTERCEPTION_MARKER_PREFIX","PRERENDER_REVALIDATE_HEADER","PRERENDER_REVALIDATE_ONLY_GENERATED_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","NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER","NEXT_CACHE_TAG_MAX_ITEMS","NEXT_CACHE_TAG_MAX_LENGTH","NEXT_CACHE_IMPLICIT_TAG_ID","CACHE_ONE_YEAR_SECONDS","INFINITE_CACHE","WEBPACK_LAYERS_NAMES","shared","reactServerComponents","serverSideRendering","actionBrowser","apiNode","apiEdge","middleware","instrument","edgeAsset","appPagesBrowser","pagesDirBrowser","pagesDirEdge","pagesDirNode","GROUP","builtinReact","serverOnly","neutralTarget","clientOnly","bundled","appPages","resolveCacheHandlerPathToFilesystem","filePath","startsWith","fileURLToPath","formatDynamicImportPath","dir","resolvedFilePath","absoluteFilePath","path","pathToFileURL","toString","checkIsOnDemandRevalidate","rawHeaders","previewProps","get","headers","HeadersAdapter","isOnDemandRevalidate","previewModeId","revalidateOnlyGenerated","hasOwnProperty","COOKIE_NAME_PRERENDER_BYPASS","COOKIE_NAME_PRERENDER_DATA","SYMBOL_PREVIEW_DATA","SYMBOL_CLEARED_COOKIES","clearPreviewData","res","options","serialize","require","previous","getHeader","setHeader","isArray","expires","httpOnly","sameSite","secure","defineProperty","enumerable","tryGetPreviewData","req","multiZoneDraftMode","cookies","encryptedPreviewData","RequestCookies","tokenPreviewData","isValidPreviewModeId","data","jsonwebtoken","verify","previewModeSigningKey","decryptWithSecret","decryptedPreviewData","Buffer","from","previewModeEncryptionKey","parse","createValidationSampleTracking","missingSampleErrors","trackMissingSampleError","validationSampleTracking","getExpectedSampleTracking","workUnitStore","workUnitAsyncStorage","type","InvariantError","push","trackMissingSampleErrorAndThrow","createCookiesFromSample","sampleCookies","route","declaredNames","Set","Headers","cookie","add","name","Proxy","RequestCookiesAdapter","target","prop","receiver","originalMethod","Reflect","createMissingCookieSampleError","call","nameOrCookie","InstantValidationError","createHeadersFromSample","rawSampleHeaders","sampleHeaders","find","toLowerCase","cookieHeaderValue","headersInit","rawName","createDraftModeForValidation","isEnabled","enable","disable","createExhaustiveParamsProxy","underlyingParams","declaredParamNames","wellKnownProperties","createExhaustiveSearchParamsProxy","searchParams","declaredSearchParamNames","createMissingSearchParamSampleError","createExhaustiveURLSearchParamsProxy","originalMathod","hasOwn","bind","createRelativeURLFromSamples","sampleParams","sampleSearchParams","pathname","createPathnameFromRouteAndSampleParams","params","interpolatedSegments","rawSegment","split","param","getSegmentParam","paramType","paramValue","paramName","map","search","qs","createURLSearchParamsFromSample","result","URLSearchParams","entries","append","parseRelativeUrl","assertRootParamInSamples","workStore","INSTANT_VALIDATION_ERROR_DIGEST","isInstantValidationError","err","digest","CIPHER_ALGORITHM","encryptWithSecret","secret","iv","crypto","salt","cipher","encrypted","concat","update","final","tag","getAuthTag","encryptedData","buffer","slice","CIPHER_SALT_LENGTH","decipher","setAuthTag","LRUNode","constructor","size","prev","next","SentinelNode","maxSize","calculateSize","onEvict","cache","totalSize","head","tail","addToHead","node","removeNode","moveToHead","removeTail","lastNode","existing","newNode","delete","iterator","current","remove","currentSize","nodeFs","existsSync","fs","readFile","readFileSync","writeFile","f","d","mkdir","recursive","stat","REACT_POSTPONE_TYPE","for","isPostpone","$$typeof","NextNodeServerSpan","AppRenderSpan","AppRouteRouteHandlersSpan","getRequestInsightKind","insight","kind","getRequestInsightKey","requestId","REQUEST_INSIGHTS_STORE_KEY","SAFE_SPAN_ATTRIBUTE_KEYS","SENSITIVE_PARAM_NAME_RE","InMemoryRequestInsightsStore","recordSpan","span","links","events","attributes","getOrCreateRequest","requestInsightKind","htmlRequestId","url","startTime","timestamp","spanStartTime","sanitizeUrl","updateTiming","durationMs","status","spans","traceId","spanId","parentSpanId","sanitizeSpanAttributes","link","fetch","getStringAttribute","method","statusCode","getNumberAttribute","cacheStatus","cacheReason","recordFetchForInsight","notify","recordFetch","identity","fetchStartTime","performance","timeOrigin","now","sanitizeFetchInsight","getSnapshot","requests","requestOrder","insightKey","filter","request","subscribe","listener","listeners","clear","requestTimings","isRequestSpan","requestTiming","endTime","requestEndTime","min","max","fetches","trim","some","existingFetch","recordRequestInsightSpan","getRequestInsightsStore","recordRequestInsightFetch","getRequestInsightsSnapshot","subscribeRequestInsights","clearRequestInsightsForTest","globalStore","sanitized","keys","isRelativeUrl","URL","username","password","test","hash","href","isRequestInsightsEnabled","_global","UNHANDLED_REJECTION_LISTENER_KEY","unhandledRejectionListener","reason","Log","isUnhandledRejectionListenerRegistered","includes","registerUnhandledRejectionListener","on","installProcessErrorHandlers","shouldRemoveUncaughtErrorAndRejectionListeners","nextInitializedProcessErrorHandlers","removeAllListeners","ReadonlyHeadersError","callable","ReflectAdapter","lowercased","original","deleteProperty","seal","hidden","methods","isHidden","sealed","createHidingMethods","entry","getSetCookie","values","forEach","callbackfn","thisArg","fresh","merge","ReadonlyRequestCookiesError","SYMBOL_MODIFY_COOKIE_VALUES","appendMutableCookies","mutableCookies","modified","modifiedCookieValues","resCookies","ResponseCookies","returnedCookies","getAll","MutableRequestCookiesAdapter","wrap","onUpdateCookies","responseCookies","modifiedValues","modifiedCookies","updateResponseCookies","workAsyncStorage","pathWasRevalidated","ActionDidRevalidateStaticAndDynamic","allCookies","c","serializedCookies","tempCookies","wrappedCookies","args","createCookiesWithMutableAccessCheck","requestStore","ensureCookiesAreStillMutable","_callingExpression","phase","endsWith","module","ensureLeadingSlash","normalizeAppPath","reduce","segment","segments","isGroupSegment","normalizeRscURL","interceptionMarker","INTERCEPTION_ROUTE_MARKERS","marker","isInterceptionRouteAppPath","m","extractInterceptionRouteInformation","interceptingRoute","interceptedRoute","splitInterceptingRoute","base","parseQuery","globalBase","resolvedBase","origin","protocol","host","auth","hostname","port","query","searchParamsToUrlQuery","slashes","stringifyUrlQueryParam","urlQueryToSearchParams","item","SP","every","DecodeError","NormalizeError","isDefinitelyAValidIdentifier","describeStringPropertyAccess","stringify","registry","CachedRouteKind","IncrementalCacheKind","RouteKind","RenderStage","RedirectStatusCode","Phase","BUILD_MANIFEST","parseReqUrl","parsedUrl","parseUrl","parsed","features","typescript","WeakMap","normalizeLocalePath","locales","detectedLocale","lowercasedLocales","locale","TEST_ROUTE","TEST_STRICT_ROUTE","isDynamicRoute","strict","parsePath","hashIndex","queryIndex","hasQuery","pathHasPrefix","removePathPrefix","withoutPrefix","reHasRegExp","reReplaceRegExp","escapeStringRegexp","removeTrailingSlash","charCodeAt","PARAMETER_PATTERN","parseMatchedParameter","optional","repeat","getSafeKeyFromSegment","getSafeRouteKey","routeKeys","keyPrefix","backreferenceDuplicateKeys","pattern","cleanedKey","invalidKey","parseInt","duplicateKey","interceptionPrefix","PARAM_SEPARATOR","hasAdjacentParameterIssues","normalizeAdjacentParameters","normalized","stripNormalizedSeparators","safePathToRegexp","pathToRegexp","needsNormalization","routeToUse","normalizedRoute","retryError","safeCompile","compiler","compile","getRouteMatcher","re","groups","matcherFn","routeMatch","exec","decode","group","match","pos","cleaned","unescapeSegments","compileNonPath","validate","normalizeNextQueryParam","decodeQueryPathParameter","slashedProtocols","filterInternalQuery","paramKeys","isNextQueryPrefix","isNextInterceptionMarkerPrefix","detectDomainLocale","domainItems","domain","defaultLocale","getHostname","normalizeDataPath","NEXT_REQUEST_META","getRequestMeta","meta","addRequestMeta","PATCHED_SET_HEADER","normalizePagePath","page","posix","resolvedPage","normalize","getExtensionRegexString","staticExtensions","dynamicExtensions","FAVICON_REGEX","ROBOTS_TXT_REGEX","MANIFEST_JSON_REGEX","MANIFEST_WEBMANIFEST_REGEX","SITEMAP_XML_REGEX","compiledRegexCache","DetachedPromise","resolve","reject","promise","rej","Batcher","cacheKeyFn","schedulerFn","fn","pending","create","batch","cacheKey","scheduleOnNextTick","cb","then","nextTick","scheduleImmediate","setImmediate","voidCatch","Uint8Array","TextEncoder","encoder","streamFromString","ReadableStream","controller","enqueue","encode","streamFromBuffer","chunk","streamToString","stream","signal","decoder","TextDecoder","fatal","aborted","addPathPrefix","addPathSuffix","suffix","REGEX_LOCALHOST_HOSTNAME","parseURL","Internal","NextURL","baseOrOpts","opts","basePath","analyze","getNextPathnameInfo","i18n","trailingSlash","nextConfig","pathnameNoDataPrefix","paths","buildId","parseData","i18nProvider","__NEXT_NO_MIDDLEWARE_URL_NORMALIZE","domainLocale","domains","formatPathname","addLocale","ignorePrefix","lower","forceLocale","formatSearch","toJSON","clone","Request","ResponseAbortedName","ResponseAborted","clientComponentLoadStart","clientComponentLoadTimes","clientComponentLoadCount","getClientComponentLoaderMetrics","metrics","reset","isAbortError","HAS_CLIENT_COMPONENT_METRICS_ENABLED","NEXT_OTEL_PERFORMANCE_PREFIX","pipeToNodeResponse","readable","waitUntilForEnd","errored","destroyed","AbortController","response","once","writableFinished","abort","writer","createWriterFromResponse","started","drained","onDrain","off","finished","WritableStream","write","measure","flushHeaders","getTracer","spanName","ok","flush","cause","destroy","pipeTo","pipeNodeReadableToNodeResponse","pause","resume","isNodeReadable","pipe","RenderResult","EMPTY","metadata","contentType","fromStatic","waitUntil","assignMetadata","assign","isNull","isDynamic","toUnchunkedString","isBuffer","chainStreams","streams","writable","TransformStream","preventClose","nextStream","lastStream","catch","Readable","toWeb","coerce","pipeThrough","transform","unshift","fromResponseCacheEntry","cacheEntry","html","pageData","postponed","rscData","segmentData","toResponseCacheEntry","isMiss","isStale","cacheControl","isFallback","parsePositiveInt","envValue","fallback","DEFAULT_TTL_MS","NEXT_PRIVATE_RESPONSE_CACHE_TTL","DEFAULT_MAX_SIZE","NEXT_PRIVATE_RESPONSE_CACHE_MAX_SIZE","TTL_SENTINEL","createCacheKey","invocationID","ResponseCache","minimal_mode","ttl","getBatcher","revalidateBatcher","evictedInvocationIDs","compoundKey","extractInvocationID","separatorIndex","lastIndexOf","first","responseGenerator","context","hasResolved","previousCacheEntry","cachedItem","expiresAt","incrementalCache","isRoutePPREnabled","isPrefetch","routeKind","handleGet","previousIncrementalCacheEntry","resolved","routeKindToIncrementalCacheKind","incrementalResponseCacheEntry","handleRevalidate","revalidate","responseCacheEntry","isRevalidating","expire","MultiFileWriter","tasks","findOrCreateTask","directory","task","all","flatMap","FileSystemCache","debug","NEXT_PRIVATE_DEBUG_CACHE","ctx","flushToDisk","serverDistDir","revalidatedTags","maxMemoryCacheSize","memoryCache","getMemoryCache","resetRequestCache","revalidateTag","tags","durations","existingEntry","tagsManifest","updates","stale","expired","getFilePath","fileData","mtime","lastModified","getTime","body","fetchIdx","fetchUrl","parsedData","storedTags","fetchCache","maybeSegmentData","segmentPaths","segmentsDir","segmentPath","segmentDataFilePath","tagsHeader","cacheTags","areTagsExpired","combinedTags","softTags","prefetchHints","isAppPath","htmlPath","rootDir","toRoute","toHex","bytes","isArrayBuffer","byteOffset","byteLength","hex","byte","padStart","hashString","cacheString","createHash","IncrementalCache","dev","minimalMode","requestHeaders","getPrerenderManifest","fetchCacheKeyPrefix","CurCacheHandler","allowedRevalidateHeaderKeys","locks","hasCustomCacheHandler","cacheHandlersSymbol","_globalThis","globalCacheHandler","FetchCache","__NEXT_TEST_MAX_ISR_CACHE","disableForTestmode","NEXT_PRIVATE_TEST_PROXY","prerenderManifest","cacheControls","SharedCacheControls","preview","getPreviouslyRevalidatedTags","cacheHandler","_requestHeaders","calculateRevalidate","fromTime","floor","initialRevalidateSeconds","_getPathname","lock","generateSimpleCacheKey","generateCacheKey","init","bodyChunks","bodyType","_ogBody","getReader","chunks","readableBody","total","arr","arrayBuffer","offset","val","iterable","blob","Blob","fromEntries","mode","redirect","credentials","referrer","referrerPolicy","integrity","cacheData","revalidateAfter","resumeDataCache","getResumeDataCache","memoryCacheData","pendingRevalidatedTags","mutable","age","areTagsStale","expireAfter","notFoundRoutes","itemSize","isImplicitBuildTimeCache","warningText","createDefaultCacheHandler","refreshTags","getExpiration","updateTags","pendingSets","pendingPromise","privateEntry","maxAgeSeconds","returnStream","newSaved","tee","pendingEntry","resolvePending","clonedValue","reader","read","done","isErrored","errorRetryCount","expiration","round","handlersSymbol","handlersMapSymbol","handlersSetSymbol","builtInHandlersSymbol","reference","getCacheHandlerEntries","handlersMap","interopDefault","mod","default","RouterServerContextSymbol","routerServerGlobal","ACTION_HEADER","isInterceptionRouteRewrite","dynamicImportEsmDefault","id","RouteModule","userland","_userland","definition","distDir","relativeProjectDir","isDev","getRouterServerContext","render404","routerServerContext","normalizeUrl","_req","_parsedUrl","instrumentationOnRequestError","absoluteProjectDir","cwd","loadManifests","srcPage","projectDir","loadManifestFromRelativePath","normalizedPagePath","router","routesManifest","buildManifest","fallbackBuildManifest","reactLoadableManifest","nextFontManifest","clientReferenceManifest","serverActionsManifest","subresourceIntegrityManifest","serverFilesManifest","dynamicCssManifest","prefetchHintsManifest","manifest","shouldCache","handleMissing","isAppRouteRoute","isMetadataRouteFile","appDirRelativePath","pageExtensions","strictlyMatchExtensions","normalizedPath","fastResult","regexes","getCompiledRegexes","cached","trailingMatcher","suffixMatcher","variantsMatcher","robotsExts","manifestExts","useEval","skipParse","__RSC_MANIFEST","interceptionRoutePatterns","rewrites","beforeFiles","rewrite","regex","loadCustomCacheHandlers","cacheMaxMemorySize","cacheHandlers","initializeCacheHandlers","builtInHandlers","DefaultCache","RemoteCache","handler","getIncrementalCache","isMinimalMode","CacheHandler","experimental","isrFlushToDisk","__incrementalCache","onRequestError","errorContext","silenceLog","logErrorWithOriginalStack","getNextConfigEdge","prepare","localeResult","previewData","deploymentId","patchSetHeaderWithCookieSupport","headersSent","middlewareValue","idx","relative","absoluteDistDir","ensureInstrumentationRegistered","manifests","config","initUrl","trustHostHeader","isNextDataRequest","originalPathname","originalQuery","pageIsDynamic","normalizedSrcPage","serverUtils","getServerUtils","caseSensitive","defaultRouteRegex","dynamicRouteMatcher","defaultRouteMatches","namedRegex","getNamedParametrizedRoute","prefixRouteKeys","includeSuffix","includePrefix","names","intercepted","routeKey","j","fromCharCode","inverseParts","structuredClone","hasInterceptionMarker","paramMatches","namedParameterizedRoute","pathToRegexpPattern","excludeOptionalTrailingSlash","getRouteRegex","parameterizedRoute","getParametrizedRoute","groupIndex","markerMatch","handleRewrites","rewrittenParsedUrl","rewriteParams","fsPathname","checkRewrite","regexp","matcher","source","removeUnnamedParams","sensitive","delimiter","regexpToFunction","regexModifier","flags","missing","hasParams","matchHas","hasMatch","hasItem","getCookieParser","parseCookieFn","getSafeParamName","newParamName","charCode","matches","groupKey","parsedDestination","destQuery","prepareDestination","destHostnameCompiler","newUrl","parseDestination","escaped","destination","parsedURL","destHostname","destSearch","destPath","destParams","destPathParamKeys","destHostnameParamKeys","destPathCompiler","strOrArray","appendParamsToQuery","nextInternalLocale","dynamicParams","fsPathnameNoSlash","afterFiles","normalizeQueryParams","routeParamKeys","normalizedKey","getParamsFromRouteMatches","routeMatchesHeader","routeMatches","obj","keyName","normalizeDynamicRouteParams","ignoreMissingOptional","isDefaultValueMatch","candidateValue","defaultValue","normalizedCandidateValue","decodedCandidateValue","isOptional","isDefaultValue","defaultVal","hasValidParams","normalizeCdnUrl","formatUrl","urlObj","querystring","interpolateDynamicPath","builtParam","replaceAll","__NEXT_TRAILING_SLASH","rewriteParamKeys","paramsMatch","paramsResult","combinedParamKeys","originalValue","queryValue","isWrappedByNextServer","paramsToInterpolate","queryResult","isDraftMode","removeUncaughtErrorAndRejectionListeners","resolvedPathname","encodedResolvedPathname","seg","char","_","runtimeServerDeploymentId","NEXT_DEPLOYMENT_ID","clientAssetToken","supportsImmutableAssets","getResponseCache","responseCache","handleResponse","purpose","DraftModeProvider","cookieValue","_isEnabled","_previewModeId","_mutableCookies","HIDDEN_REQUEST_HEADERS","header","mergeMiddlewareCookies","existingCookies","setCookieValue","responseHeaders","splitCookiesString","cookiesString","ch","lastComma","nextStart","cookiesSeparatorFound","cookiesStrings","skipWhitespace","charAt","withExecuteRevalidates","store","callback","savedRevalidationState","cloneRevalidationState","curr","prevTagsWithProfile","prevRevalidateWrites","newRevalidates","profileKey","profile","pendingRevalidateWrites","pendingRevalidates","executeRevalidates","revalidateTags","tagsWithProfile","handlers","getCacheHandlers","handlersSet","promises","tagsByProfile","existingKey","tagsForProfile","cacheLife","cacheLifeProfiles","state","sharedAsyncLocalStorageNotAvailableError","FakeAsyncLocalStorage","getStore","run","exit","enterWith","maybeGlobalAsyncLocalStorage","AsyncLocalStorage","AfterContext","onClose","onTaskError","isRequestClosed","initialOnCloseError","workUnitStores","callbackQueue","PromiseQueue","after","addThenable","addCallback","thenable","errorWaitUntilNotAvailable","reportTaskError","afterTaskStore","afterTaskAsyncStorage","rootTaskSpawnPhase","runCallbacksOnClosePromise","runCallbacksOnClose","wrappedCallback","runCallbacks","onIdle","taskKind","handlerError","createLazyResult","pendingResult","onfulfilled","onrejected","HTTP_METHODS","isHTTPMethod","maybeMethod","OUT_OF_CLASS_CHAR","OUT_OF_CLASS_RUN","encodeHeaderSafe","getImplicitTags","fallbackRouteParams","getDerivedTags","derivedTags","curPathname","tagsArray","expirationsByCacheKind","createTagsExpirationsByCacheKind","REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY","DYNAMIC_ERROR_CODE","DynamicServerError","description","isDynamicServerError","StaticGenBailoutError","code","HangingPromiseRejectionError","expression","abortListenersBySignal","makeDynamicHangingPromise","makeHangingPromiseWithError","trackRuntimeDataAccessedImpl","isFallbackParamAccess","runtimeDataAccessed","hintCell","shouldAttemptStaticPrefetch","isFallbackUpgradeable","hangingPromise","boundRejection","currentListeners","addEventListener","ignoreReject","RENDER_STAGES_BY_DATA_KIND","sessionData","staticLinkData","runtimeLinkData","hasPostpone","React","createDynamicTrackingState","isDebugDynamicAccesses","dynamicAccesses","syncDynamicErrorWithStack","syncDynamicErrorWithStackPostMicrotask","markCurrentScopeAsDynamic","forceDynamic","forceStatic","dynamicShouldError","postponeWithTracking","dynamicTracking","dynamicUsageDescription","dynamicUsageStack","stack","assertPostpone","createPostponeReason","isDynamicPostponeReason","NEXT_PRERENDER_INTERRUPTED","createPrerenderInterruptedError","noop","cloneResponse","body1","body2","cloned1","Response","statusText","configurable","cloned2","register","WeakRef","FinalizationRegistry","weakRef","deref","locked","cancel","headersToExcludeInCacheKey","NEXT_PATCH_SYMBOL","trackFetchMetric","metric","nextFetchId","setAttributes","requestInsightsIdentity","getRequestInsightsIdentityStorage","requestInsightsRequestId","shouldTrackFetchMetrics","fetchMetrics","createCachedPrerenderResponse","incrementalCacheContext","handleUnlock","bodyBuffer","fetchedData","createCachedDynamicResponse","serverComponentsHmrCache","cacheSetPromise","finally","pendingRevalidateKey","pendingRevalidatePromise","currentTimeoutBoundary","AUTOMATIC_ROUTE_METHODS","handleMethodNotAllowedResponse","autoImplementMethods","acc","implemented","GET","HEAD","allow","Allow","sort","OPTIONS","ALLOWED_CODES","NOT_FOUND","FORBIDDEN","UNAUTHORIZED","isHTTPAccessFallbackError","httpStatus","isRedirectError","errorCode","at","printDebugThrownValueForProspectiveRender","thrownValue","getDigestForWellKnownError","originalErrorStack","stackStart","AppRouterContext","LayoutRouterContext","GlobalLayoutRouterContext","TemplateContext","MissingSlotContext","CacheSignal","count","earlyListeners","tickPending","pendingTimeoutCleanup","subscribedSignals","invokeListenersIfNoPendingReads","noMorePendingCaches","clearPending","immediate","queueMicrotask","clearImmediate","inputReady","cacheReady","beginRead","subscriber","endRead","hasPendingReads","trackRead","onFinally","subscribeToReads","unsubscribeFromReads","VaryParamsAccumulator","_done","_seen","_resolve","_buffer","asyncIterator","createVaryingParams","accumulator","originalParamsObject","optionalCatchAllParamName","prototype","ownKeys","underlyingParamsWithVarying","emptyVaryParamsAccumulator","errorRef","logErrorOrWarn","__NEXT_CACHE_COMPONENTS","CachedParams","fallbackParamsProxyHandler","dynamicAccessAsyncStorage","abortController","apply","makeHangingParams","prerenderStore","cachedParams","renderSignal","makeUntrackedParams","LazyModule","load","onLoad","loadIfNeeded","rejected","waitUntilLoaded","assertLoaded","WrappedNextRouterError","AppRouteRouteModule","sharedModules","_lazyUserland","ensureUserland","getUserland","resolvedPagePath","nextConfigOutput","serverHooks","actionAsyncStorage","_getUserland","_onUserlandLoaded","_methods","_hasNonStaticMethods","hasNonStaticMethods","_dynamic","dynamic","generateStaticParams","resolveHandler","resolveHandlerFromUserland","do","actionStore","implicitTags","trackingState","isStaticGeneration","cacheComponentsEnabled","renderOpts","cacheComponents","patchFetch","originalFetch","getCacheEntries","resource","filteredHeaders","keepalive","cacheEntries","createPatchedFetcher","originFetch","patched","toUpperCase","isInternal","internal","hideSpan","NEXT_OTEL_FETCH_DISABLED","fetchStart","cacheSignal","getCacheSignal","SpanKind","revalidateStore","cacheWarning","cacheReasonOverride","finalRevalidate","isRequestInput","overrides","field","getNextField","originalFetchRevalidate","currentFetchRevalidate","validateTags","validTags","invalidTags","collectedTags","pageFetchCacheMode","isUsingNoStore","isUnstableNoStore","currentFetchCacheConfig","hasExplicitFetchCacheOptOut","noFetchConfigAndForceDynamic","validateRevalidate","revalidateVal","normalizedRevalidate","Infinity","_headers","initHeaders","hasUnCacheableHeader","isUnCacheableMethod","hasNoExplicitCacheConfig","autoNoCache","isBuildTimePrerendering","isCacheableRevalidate","isHmrRefresh","doOriginalFetch","requestInputFields","reqInput","reqOptions","otherInput","clonedInit","fetchType","incrementalCacheConfig","isForegroundRevalidate","isHmrRefreshCache","cachedFetchData","pendingRevalidate","hasNextConfig","revalidatedResult","pendingResponse","responses","__nextPatched","__nextGetStaticStore","_nextOriginalFetch","handlerContext","createServerParamsForRoute","varyParamsAccumulator","createStaticPrerenderParams","userspaceParams","isEmptyParams","_paramKey","hasFallbackRouteParams","fallbackParams","stagedRendering","allParamsAreRootParams","rootParams","staticParamsStage","delayUntilStage","makeErroringParams","augmentedUnderlying","throwToInterruptStaticGeneration","throwInvariantForMissingStore","parsedUrlQueryToParams","resolvePendingRevalidations","maybeRevalidatesPromise","pendingWaitUntil","userlandRevalidate","defaultRevalidate","prospectiveResult","prospectiveController","prospectiveRenderIsDynamic","prerenderResumeDataCache","encryptedBoundArgs","decryptedBoundArgs","imageResponses","dynamicCacheKeys","prospectiveRoutePrerenderStore","hmrRefreshHash","NEXT_DEBUG_BUILD","__NEXT_VERBOSE_LOGGING","trackPendingModules","dynamicReason","finalController","finalRoutePrerenderStore","responseHandled","bodyHandled","createCacheComponentsError","Location","isAction","getRedirectStatusCodeFromError","invalidType","collectedRevalidate","collectedExpire","collectedStale","handle","actionId","isURLEncodedAction","isMultipartAction","isFetchAction","rawLiveUserland","liveUserland","staticGenerationContext","sharedContext","previouslyRevalidatedTags","isAppRoute","getServerActionRequestMetadata","isPossibleServerAction","nextUrl","createRequestStore","inputs","requestCookies","userspaceMutableCookies","draftMode","__serverComponentsHmrCache","createWorkStore","isPrefetchRequest","nonce","supportsDynamicResponse","NEXT_SSG_FETCH_METRICS","useCacheTimeout","staticPageGenerationTimeout","assetPrefix","afterContext","createAfterContext","onAfterTaskError","validationLevel","requestStartTime","refreshTagsByCacheKind","createRefreshTagsByCacheKind","runInCleanSnapshot","snapshot","reactServerErrorsByDigest","hasNonStatic","forceStaticRequestHandlers","requireStaticRequestHandlers","nextUrlHandlers","nextRequestHandlers","trackDynamic","urlCloneSymbol","nextURLSymbol","requestCloneSymbol","tracer","setRootSpanAttribute","POST","PUT","DELETE","PATCH","searchParamsSymbol","hrefSymbol","toStringSymbol","headersSymbol","cookiesSymbol","forceStaticNextUrlHandlers","cleanURL","requireStaticNextUrlHandlers","abortAndThrowOnSynchronousRequestDataAccess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,GACLjH,EAAMjhC,KAAK,CACXomC,EACA5mC,EAAc2oC,eAAe,CAEjC,KAAK,mBACH3oC,EAAcunB,UAAU,CAAG,EAE3B,IAAM1iB,EAAM,qBAEX,CAFW,IAAIyhC,GACd,CAAC,MAAM,EAAE7E,EAAMjhC,KAAK,CAAC,mDAAmD,EAAEomC,EAAW,6EAA6E,CAAC,EADzJ,qB,MAAA,O,WAAA,G,aAAA,EAEZ,EAIA,OAHAnF,EAAMmH,uBAAuB,CAAGhC,EAChCnF,EAAMoH,iBAAiB,CAAGhkC,EAAIikC,KAAK,CAE7BjkC,CAYV,CAEJ,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]}