/opt/canhelp/node_modules/next/dist/compiled/next-server
NameSizeModeActions
app-page-experimental.runtime.dev.js13441550644editdlrm
app-page-experimental.runtime.dev.js.map37938060644editdlrm
app-page-experimental.runtime.prod.js5416350644editdlrm
app-page-experimental.runtime.prod.js.map27867110644editdlrm
app-page-turbo-experimental.runtime.dev.js13470080644editdlrm
app-page-turbo-experimental.runtime.dev.js.map37989910644editdlrm
app-page-turbo-experimental.runtime.prod.js5416440644editdlrm
app-page-turbo-experimental.runtime.prod.js.map27861310644editdlrm
app-page-turbo.runtime.dev.js12810780644editdlrm
app-page-turbo.runtime.dev.js.map36309660644editdlrm
app-page-turbo.runtime.prod.js5166400644editdlrm
app-page-turbo.runtime.prod.js.map27001080644editdlrm
app-page.runtime.dev.js12782250644editdlrm
app-page.runtime.dev.js.map36257820644editdlrm
app-page.runtime.prod.js5166310644editdlrm
app-page.runtime.prod.js.map27006920644editdlrm
app-route-experimental.runtime.dev.js2797490644editdlrm
app-route-experimental.runtime.dev.js.map10033500644editdlrm
app-route-experimental.runtime.prod.js1615880644editdlrm
app-route-experimental.runtime.prod.js.map9413880644editdlrm
app-route-turbo-experimental.runtime.dev.js2798330644editdlrm
app-route-turbo-experimental.runtime.dev.js.map10034220644editdlrm
app-route-turbo-experimental.runtime.prod.js1616380644editdlrm
app-route-turbo-experimental.runtime.prod.js.map9414580644editdlrm
app-route-turbo.runtime.dev.js2770350644editdlrm
app-route-turbo.runtime.dev.js.map9980710644editdlrm
app-route-turbo.runtime.prod.js1605890644editdlrm
app-route-turbo.runtime.prod.js.map9378110644editdlrm
app-route.runtime.dev.js2769510644editdlrm
app-route.runtime.dev.js.map9979980644editdlrm
app-route.runtime.prod.js1605390644editdlrm
app-route.runtime.prod.js.map9377410644editdlrm
dist_client_dev_noop-turbopack-hmr_js-experimental.runtime.dev.js6860644editdlrm
dist_client_dev_noop-turbopack-hmr_js-experimental.runtime.dev.js.map4430644editdlrm
dist_client_dev_noop-turbopack-hmr_js-turbo-experimental.runtime.dev.js6920644editdlrm
dist_client_dev_noop-turbopack-hmr_js-turbo-experimental.runtime.dev.js.map4490644editdlrm
dist_client_dev_noop-turbopack-hmr_js-turbo.runtime.dev.js6790644editdlrm
dist_client_dev_noop-turbopack-hmr_js-turbo.runtime.dev.js.map4360644editdlrm
dist_client_dev_noop-turbopack-hmr_js.runtime.dev.js6730644editdlrm
dist_client_dev_noop-turbopack-hmr_js.runtime.dev.js.map4300644editdlrm
pages-api-turbo.runtime.dev.js1697810644editdlrm
pages-api-turbo.runtime.dev.js.map6285840644editdlrm
pages-api-turbo.runtime.prod.js1070200644editdlrm
pages-api-turbo.runtime.prod.js.map6214500644editdlrm
pages-api.runtime.dev.js1697000644editdlrm
pages-api.runtime.dev.js.map6285120644editdlrm
pages-api.runtime.prod.js1069730644editdlrm
pages-api.runtime.prod.js.map6213800644editdlrm
pages-turbo.runtime.dev.js2099970644editdlrm
pages-turbo.runtime.dev.js.map7398840644editdlrm
pages-turbo.runtime.prod.js1284240644editdlrm
pages-turbo.runtime.prod.js.map7292920644editdlrm
pages.runtime.dev.js2108140644editdlrm
pages.runtime.dev.js.map7408800644editdlrm
pages.runtime.prod.js1289210644editdlrm
pages.runtime.prod.js.map7302610644editdlrm
server.runtime.prod.js2022010644editdlrm
server.runtime.prod.js.map11748790644editdlrm
Edit: /opt/canhelp/node_modules/next/dist/compiled/next-server/server.runtime.prod.js.map (1174879B)
{"version":3,"file":"server.runtime.prod.js","sources":["webpack://next/../../node_modules/.pnpm/react@19.2.0-canary-0bdb9206-20250818/node_modules/react/cjs/react.production.js","webpack://next/../../node_modules/.pnpm/react@19.2.0-canary-0bdb9206-20250818/node_modules/react/index.js","webpack://next/../next-env/dist/index.js","webpack://next/./dist/compiled/@edge-runtime/cookies/index.js","webpack://next/./dist/compiled/bytes/index.js","webpack://next/./dist/compiled/cookie/index.js","webpack://next/./dist/compiled/fresh/index.js","webpack://next/./dist/compiled/p-queue/index.js","webpack://next/./dist/compiled/path-to-regexp/index.js","webpack://next/./dist/src/server/node-environment-baseline.ts","webpack://next/./dist/src/server/node-polyfill-crypto.ts","webpack://next/./dist/src/shared/lib/isomorphic/path.js","webpack://next/./dist/src/shared/lib/modern-browserslist-target.js","webpack://next/./dist/compiled/superstruct/index.cjs","webpack://next/webpack/runtime/compat_get_default_export","webpack://next/webpack/runtime/define_property_getters","webpack://next/webpack/runtime/has_own_property","webpack://next/webpack/runtime/make_namespace_object","webpack://next/./dist/src/server/node-environment-extensions/web-crypto.tsx","webpack://next/./dist/src/server/lib/source-maps.ts","webpack://next/./dist/src/lib/picocolors.ts","webpack://next/./dist/src/server/lib/lru-cache.ts","webpack://next/./dist/src/server/lib/parse-stack.ts","webpack://next/./dist/src/shared/lib/is-internal.ts","webpack://next/./dist/src/server/patch-error-inspect.ts","webpack://next/./dist/src/server/node-environment-extensions/error-inspect.tsx","webpack://next/./dist/src/next-devtools/server/shared.ts","webpack://next/./dist/src/server/dynamic-rendering-utils.ts","webpack://next/./dist/src/shared/lib/invariant-error.ts","webpack://next/./dist/src/server/app-render/dynamic-rendering.ts","webpack://next/./dist/src/server/node-environment-extensions/utils.tsx","webpack://next/./dist/src/server/node-environment-extensions/random.tsx","webpack://next/./dist/src/server/node-environment-extensions/date.tsx","webpack://next/./dist/src/server/node-environment-extensions/node-crypto.tsx","webpack://next/./dist/src/server/require-hook.ts","webpack://next/./dist/src/shared/lib/utils.ts","webpack://next/./dist/src/lib/route-pattern-normalizer.ts","webpack://next/./dist/src/shared/lib/router/utils/route-match-utils.ts","webpack://next/./dist/src/shared/lib/router/utils/route-matcher.ts","webpack://next/./dist/src/server/request-meta.ts","webpack://next/./dist/src/shared/lib/constants.ts","webpack://next/./dist/src/lib/find-pages-dir.ts","webpack://next/./dist/src/server/web/spec-extension/adapters/reflect.ts","webpack://next/./dist/src/server/web/spec-extension/adapters/headers.ts","webpack://next/./dist/src/lib/constants.ts","webpack://next/./dist/src/server/lib/trace/constants.ts","webpack://next/./dist/src/server/api-utils/index.ts","webpack://next/./dist/src/client/components/redirect-status-code.ts","webpack://next/./dist/src/server/api-utils/get-cookie-parser.ts","webpack://next/./dist/src/server/base-http/index.ts","webpack://next/./dist/src/server/base-http/node.ts","webpack://next/./dist/src/server/send-payload.ts","webpack://next/./dist/src/server/lib/cache-control.ts","webpack://next/./dist/src/server/lib/etag.ts","webpack://next/./dist/src/shared/lib/router/utils/querystring.ts","webpack://next/./dist/src/shared/lib/router/utils/parse-url.ts","webpack://next/./dist/src/shared/lib/router/utils/parse-relative-url.ts","webpack://next/./dist/src/build/output/log.ts","webpack://next/./dist/src/server/lib/is-ipv6.ts","webpack://next/./dist/src/shared/lib/page-path/ensure-leading-slash.ts","webpack://next/./dist/src/shared/lib/router/utils/app-paths.ts","webpack://next/./dist/src/shared/lib/segment.ts","webpack://next/./dist/src/shared/lib/router/utils/interception-routes.ts","webpack://next/./dist/src/shared/lib/router/utils/is-dynamic.ts","webpack://next/./dist/src/shared/lib/router/utils/html-bots.ts","webpack://next/./dist/src/shared/lib/router/utils/is-bot.ts","webpack://next/./dist/src/server/stream-utils/node-web-streams-helper.ts","webpack://next/./dist/src/server/stream-utils/encoded-tags.ts","webpack://next/./dist/src/server/web/utils.ts","webpack://next/./dist/src/shared/lib/router/utils/remove-trailing-slash.ts","webpack://next/./dist/src/shared/lib/router/utils/parse-path.ts","webpack://next/./dist/src/shared/lib/router/utils/add-path-prefix.ts","webpack://next/./dist/src/shared/lib/router/utils/add-path-suffix.ts","webpack://next/./dist/src/shared/lib/router/utils/path-has-prefix.ts","webpack://next/./dist/src/shared/lib/get-hostname.ts","webpack://next/./dist/src/shared/lib/i18n/normalize-locale-path.ts","webpack://next/./dist/src/shared/lib/router/utils/remove-path-prefix.ts","webpack://next/./dist/src/shared/lib/router/utils/get-next-pathname-info.ts","webpack://next/./dist/src/server/web/next-url.ts","webpack://next/./dist/src/shared/lib/i18n/detect-domain-locale.ts","webpack://next/./dist/src/shared/lib/router/utils/format-next-pathname-info.ts","webpack://next/./dist/src/shared/lib/router/utils/add-locale.ts","webpack://next/./dist/src/server/web/error.ts","webpack://next/./dist/src/server/web/spec-extension/request.ts","webpack://next/./dist/src/server/web/spec-extension/adapters/next-request.ts","webpack://next/./dist/src/lib/detached-promise.ts","webpack://next/./dist/src/server/client-component-renderer-logger.ts","webpack://next/./dist/src/server/pipe-readable.ts","webpack://next/./dist/src/server/render-result.ts","webpack://next/./dist/src/shared/lib/page-path/normalize-path-sep.ts","webpack://next/./dist/src/shared/lib/page-path/denormalize-page-path.ts","webpack://next/./dist/src/shared/lib/router/utils/path-match.ts","webpack://next/./dist/src/shared/lib/escape-regexp.ts","webpack://next/./dist/src/shared/lib/router/utils/get-dynamic-param.ts","webpack://next/./dist/src/shared/lib/router/utils/route-regex.ts","webpack://next/./dist/src/shared/lib/router/utils/prepare-destination.ts","webpack://next/./dist/src/server/lib/decode-query-path-parameter.ts","webpack://next/./dist/src/shared/lib/router/utils/format-url.ts","webpack://next/./dist/src/server/app-render/types.ts","webpack://next/./dist/src/client/components/app-router-headers.ts","webpack://next/./dist/src/lib/generate-interception-routes-rewrites.ts","webpack://next/./dist/src/server/server-utils.ts","webpack://next/./dist/src/lib/is-error.ts","webpack://next/./dist/src/shared/lib/is-plain-object.ts","webpack://next/./dist/src/server/normalizers/locale-route-normalizer.ts","webpack://next/./dist/src/shared/lib/router/utils/sorted-routes.ts","webpack://next/./dist/src/server/route-matchers/route-matcher.ts","webpack://next/./dist/src/server/route-matchers/locale-route-matcher.ts","webpack://next/./dist/src/server/route-matcher-managers/default-route-matcher-manager.ts","webpack://next/./dist/src/server/normalizers/normalizers.ts","webpack://next/./dist/src/server/normalizers/prefixing-normalizer.ts","webpack://next/./dist/src/shared/lib/page-path/normalize-page-path.ts","webpack://next/./dist/src/server/normalizers/underscore-normalizer.ts","webpack://next/./dist/src/server/normalizers/built/app/app-bundle-path-normalizer.ts","webpack://next/./dist/src/server/normalizers/built/app/app-filename-normalizer.ts","webpack://next/./dist/src/lib/is-app-route-route.ts","webpack://next/./dist/src/lib/metadata/is-metadata-route.ts","webpack://next/./dist/src/server/normalizers/wrap-normalizer-fn.ts","webpack://next/./dist/src/server/normalizers/built/app/app-pathname-normalizer.ts","webpack://next/./dist/src/server/normalizers/built/app/index.ts","webpack://next/./dist/src/server/route-kind.ts","webpack://next/./dist/src/server/route-matchers/app-page-route-matcher.ts","webpack://next/./dist/src/server/route-matcher-providers/helpers/cached-route-matcher-provider.ts","webpack://next/./dist/src/server/route-matcher-providers/manifest-route-matcher-provider.ts","webpack://next/./dist/src/server/route-matcher-providers/app-page-route-matcher-provider.ts","webpack://next/./dist/src/lib/is-app-page-route.ts","webpack://next/./dist/src/server/route-matchers/app-route-route-matcher.ts","webpack://next/./dist/src/server/route-matcher-providers/app-route-route-matcher-provider.ts","webpack://next/./dist/src/lib/is-api-route.ts","webpack://next/./dist/src/server/route-matchers/pages-api-route-matcher.ts","webpack://next/./dist/src/server/normalizers/built/pages/pages-bundle-path-normalizer.ts","webpack://next/./dist/src/server/normalizers/built/pages/pages-filename-normalizer.ts","webpack://next/./dist/src/server/normalizers/built/pages/index.ts","webpack://next/./dist/src/server/route-matcher-providers/pages-api-route-matcher-provider.ts","webpack://next/./dist/src/server/route-matchers/pages-route-matcher.ts","webpack://next/./dist/src/server/route-matcher-providers/pages-route-matcher-provider.ts","webpack://next/./dist/src/server/route-matcher-providers/helpers/manifest-loaders/server-manifest-loader.ts","webpack://next/./dist/src/server/lib/i18n-provider.ts","webpack://next/./dist/src/server/send-response.ts","webpack://next/./dist/src/server/lib/match-next-data-pathname.ts","webpack://next/./dist/src/server/normalizers/request/suffix.ts","webpack://next/./dist/src/server/normalizers/request/rsc.ts","webpack://next/./dist/src/server/normalizers/request/prefetch-rsc.ts","webpack://next/./dist/src/server/normalizers/request/prefix.ts","webpack://next/./dist/src/server/normalizers/request/next-data.ts","webpack://next/./dist/src/server/lib/to-route.ts","webpack://next/./dist/src/server/app-render/async-local-storage.ts","webpack://next/./dist/src/server/after/builtin-request-context.ts","webpack://next/./dist/src/server/web/spec-extension/fetch-event.ts","webpack://next/./dist/src/server/web/spec-extension/response.ts","webpack://next/./dist/src/server/web/spec-extension/adapters/request-cookies.ts","webpack://next/./dist/src/server/use-cache/handlers.ts","webpack://next/./dist/src/server/web/adapter.ts","webpack://next/./dist/src/server/normalizers/request/segment-prefix-rsc.ts","webpack://next/./dist/src/server/base-server.ts","webpack://next/./dist/src/server/app-render/strip-flight-headers.ts","webpack://next/./dist/src/shared/lib/router/utils/get-route-from-asset-path.ts","webpack://next/./dist/src/server/lib/format-hostname.ts","webpack://next/./dist/src/server/lib/experimental/ppr.ts","webpack://next/./dist/src/server/lib/patch-set-header.ts","webpack://next/./dist/src/server/lib/fix-mojibake.ts","webpack://next/./dist/src/client/components/router-reducer/compute-changed-path.ts","webpack://next/./dist/src/server/app-render/parse-and-validate-flight-router-state.tsx","webpack://next/./dist/src/lib/url.ts","webpack://next/./dist/src/server/lib/streaming-metadata.ts","webpack://next/./dist/src/server/utils.ts","webpack://next/./dist/src/lib/fallback.ts","webpack://next/./dist/src/server/lib/server-action-request-meta.ts","webpack://next/./dist/src/server/route-modules/checks.ts","webpack://next/./dist/src/server/require.ts","webpack://next/./dist/src/lib/interop-default.ts","webpack://next/./dist/src/lib/wait.ts","webpack://next/./dist/src/server/app-render/encryption-utils.ts","webpack://next/./dist/src/server/load-components.ts","webpack://next/./dist/src/server/app-render/action-utils.ts","webpack://next/./dist/src/shared/lib/router/utils/middleware-route-matcher.ts","webpack://next/./dist/src/lib/batcher.ts","webpack://next/./dist/src/lib/scheduler.ts","webpack://next/./dist/src/server/response-cache/types.ts","webpack://next/./dist/src/server/response-cache/utils.ts","webpack://next/./dist/src/server/response-cache/index.ts","webpack://next/./dist/src/lib/multi-file-writer.ts","webpack://next/./dist/src/server/lib/incremental-cache/file-system-cache.ts","webpack://next/./dist/src/server/lib/incremental-cache/index.ts","webpack://next/./dist/src/server/lib/node-fs-methods.ts","webpack://next/./dist/src/server/lib/mock-request.ts","webpack://next/./dist/src/lib/format-dynamic-import-path.ts","webpack://next/./dist/src/server/lib/async-callback-set.ts","webpack://next/./dist/src/server/lib/router-utils/is-postpone.ts","webpack://next/./dist/src/server/lib/module-loader/node-module-loader.ts","webpack://next/./dist/src/server/lib/router-utils/router-server-context.ts","webpack://next/./dist/src/server/next-server.ts","webpack://next/./dist/src/server/route-matches/pages-api-route-match.ts","webpack://next/./dist/src/server/setup-http-agent-env.ts","webpack://next/./dist/src/lib/static-env.ts","webpack://next/./dist/src/server/body-streams.ts"],"sourcesContent":["/**\n * @license React\n * react.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_PORTAL_TYPE = Symbol.for(\"react.portal\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\"),\n REACT_STRICT_MODE_TYPE = Symbol.for(\"react.strict_mode\"),\n REACT_PROFILER_TYPE = Symbol.for(\"react.profiler\"),\n REACT_CONSUMER_TYPE = Symbol.for(\"react.consumer\"),\n REACT_CONTEXT_TYPE = Symbol.for(\"react.context\"),\n REACT_FORWARD_REF_TYPE = Symbol.for(\"react.forward_ref\"),\n REACT_SUSPENSE_TYPE = Symbol.for(\"react.suspense\"),\n REACT_MEMO_TYPE = Symbol.for(\"react.memo\"),\n REACT_LAZY_TYPE = Symbol.for(\"react.lazy\"),\n 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 ctor = ctor();\n ctor.then(\n function (moduleObject) {\n if (0 === payload._status || -1 === payload._status)\n (payload._status = 1), (payload._result = moduleObject);\n },\n function (error) {\n if (0 === payload._status || -1 === payload._status)\n (payload._status = 2), (payload._result = error);\n }\n );\n -1 === payload._status && ((payload._status = 0), (payload._result = ctor));\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 };\nexports.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.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.__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.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 = function (scope) {\n var prevTransition = ReactSharedInternals.T,\n currentTransition = {};\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};\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.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.2.0-canary-0bdb9206-20250818\";\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react.production.js');\n} else {\n module.exports = require('./cjs/react.development.js');\n}\n","(()=>{var e={383:e=>{\"use strict\";function _searchLast(e,t){const n=Array.from(e.matchAll(t));return n.length>0?n.slice(-1)[0].index:-1}function _interpolate(e,t,n){const r=_searchLast(e,/(?!(?<=\\\\))\\$/g);if(r===-1)return e;const o=e.slice(r);const s=/((?!(?<=\\\\))\\${?([\\w]+)(?::-([^}\\\\]*))?}?)/;const i=o.match(s);if(i!=null){const[,r,o,s]=i;return _interpolate(e.replace(r,t[o]||s||n.parsed[o]||\"\"),t,n)}return e}function _resolveEscapeSequences(e){return e.replace(/\\\\\\$/g,\"$\")}function expand(e){const t=e.ignoreProcessEnv?{}:process.env;for(const n in e.parsed){const r=Object.prototype.hasOwnProperty.call(t,n)?t[n]:e.parsed[n];e.parsed[n]=_resolveEscapeSequences(_interpolate(r,t,e))}for(const n in e.parsed){t[n]=e.parsed[n]}return e}e.exports.j=expand},234:(e,t,n)=>{const r=n(147);const o=n(17);const s=n(37);const i=n(113);const c=n(803);const a=c.version;const p=/(?:^|^)\\s*(?:export\\s+)?([\\w.-]+)(?:\\s*=\\s*?|:\\s+?)(\\s*'(?:\\\\'|[^'])*'|\\s*\"(?:\\\\\"|[^\"])*\"|\\s*`(?:\\\\`|[^`])*`|[^#\\r\\n]+)?\\s*(?:#.*)?(?:$|$)/gm;function parse(e){const t={};let n=e.toString();n=n.replace(/\\r\\n?/gm,\"\\n\");let r;while((r=p.exec(n))!=null){const e=r[1];let n=r[2]||\"\";n=n.trim();const o=n[0];n=n.replace(/^(['\"`])([\\s\\S]*)\\1$/gm,\"$2\");if(o==='\"'){n=n.replace(/\\\\n/g,\"\\n\");n=n.replace(/\\\\r/g,\"\\r\")}t[e]=n}return t}function _parseVault(e){const t=_vaultPath(e);const n=l.configDotenv({path:t});if(!n.parsed){throw new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`)}const r=_dotenvKey(e).split(\",\");const o=r.length;let s;for(let e=0;e=o){throw t}}}return l.parse(s)}function _log(e){console.log(`[dotenv@${a}][INFO] ${e}`)}function _warn(e){console.log(`[dotenv@${a}][WARN] ${e}`)}function _debug(e){console.log(`[dotenv@${a}][DEBUG] ${e}`)}function _dotenvKey(e){if(e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0){return e.DOTENV_KEY}if(process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0){return process.env.DOTENV_KEY}return\"\"}function _instructions(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===\"ERR_INVALID_URL\"){throw new Error(\"INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenv.org/vault/.env.vault?environment=development\")}throw e}const r=n.password;if(!r){throw new Error(\"INVALID_DOTENV_KEY: Missing key part\")}const o=n.searchParams.get(\"environment\");if(!o){throw new Error(\"INVALID_DOTENV_KEY: Missing environment part\")}const s=`DOTENV_VAULT_${o.toUpperCase()}`;const i=e.parsed[s];if(!i){throw new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${s} in your .env.vault file.`)}return{ciphertext:i,key:r}}function _vaultPath(e){let t=o.resolve(process.cwd(),\".env\");if(e&&e.path&&e.path.length>0){t=e.path}return t.endsWith(\".vault\")?t:`${t}.vault`}function _resolveHome(e){return e[0]===\"~\"?o.join(s.homedir(),e.slice(1)):e}function _configVault(e){_log(\"Loading env from encrypted .env.vault\");const t=l._parseVault(e);let n=process.env;if(e&&e.processEnv!=null){n=e.processEnv}l.populate(n,t,e);return{parsed:t}}function configDotenv(e){let t=o.resolve(process.cwd(),\".env\");let n=\"utf8\";const s=Boolean(e&&e.debug);if(e){if(e.path!=null){t=_resolveHome(e.path)}if(e.encoding!=null){n=e.encoding}}try{const o=l.parse(r.readFileSync(t,{encoding:n}));let s=process.env;if(e&&e.processEnv!=null){s=e.processEnv}l.populate(s,o,e);return{parsed:o}}catch(e){if(s){_debug(`Failed to load ${t} ${e.message}`)}return{error:e}}}function config(e){const t=_vaultPath(e);if(_dotenvKey(e).length===0){return l.configDotenv(e)}if(!r.existsSync(t)){_warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`);return l.configDotenv(e)}return l._configVault(e)}function decrypt(e,t){const n=Buffer.from(t.slice(-64),\"hex\");let r=Buffer.from(e,\"base64\");const o=r.slice(0,12);const s=r.slice(-16);r=r.slice(12,-16);try{const e=i.createDecipheriv(\"aes-256-gcm\",n,o);e.setAuthTag(s);return`${e.update(r)}${e.final()}`}catch(e){const t=e instanceof RangeError;const n=e.message===\"Invalid key length\";const r=e.message===\"Unsupported state or unable to authenticate data\";if(t||n){const e=\"INVALID_DOTENV_KEY: It must be 64 characters long (or more)\";throw new Error(e)}else if(r){const e=\"DECRYPTION_FAILED: Please check your DOTENV_KEY\";throw new Error(e)}else{console.error(\"Error: \",e.code);console.error(\"Error: \",e.message);throw e}}}function populate(e,t,n={}){const r=Boolean(n&&n.debug);const o=Boolean(n&&n.override);if(typeof t!==\"object\"){throw new Error(\"OBJECT_REQUIRED: Please check the processEnv argument being passed to populate\")}for(const n of Object.keys(t)){if(Object.prototype.hasOwnProperty.call(e,n)){if(o===true){e[n]=t[n]}if(r){if(o===true){_debug(`\"${n}\" is already defined and WAS overwritten`)}else{_debug(`\"${n}\" is already defined and was NOT overwritten`)}}}else{e[n]=t[n]}}}const l={configDotenv:configDotenv,_configVault:_configVault,_parseVault:_parseVault,config:config,decrypt:decrypt,parse:parse,populate:populate};e.exports.configDotenv=l.configDotenv;e.exports._configVault=l._configVault;e.exports._parseVault=l._parseVault;e.exports.config=l.config;e.exports.decrypt=l.decrypt;e.exports.parse=l.parse;e.exports.populate=l.populate;e.exports=l},113:e=>{\"use strict\";e.exports=require(\"crypto\")},147:e=>{\"use strict\";e.exports=require(\"fs\")},37:e=>{\"use strict\";e.exports=require(\"os\")},17:e=>{\"use strict\";e.exports=require(\"path\")},803:e=>{\"use strict\";e.exports=JSON.parse('{\"name\":\"dotenv\",\"version\":\"16.3.1\",\"description\":\"Loads environment variables from .env file\",\"main\":\"lib/main.js\",\"types\":\"lib/main.d.ts\",\"exports\":{\".\":{\"types\":\"./lib/main.d.ts\",\"require\":\"./lib/main.js\",\"default\":\"./lib/main.js\"},\"./config\":\"./config.js\",\"./config.js\":\"./config.js\",\"./lib/env-options\":\"./lib/env-options.js\",\"./lib/env-options.js\":\"./lib/env-options.js\",\"./lib/cli-options\":\"./lib/cli-options.js\",\"./lib/cli-options.js\":\"./lib/cli-options.js\",\"./package.json\":\"./package.json\"},\"scripts\":{\"dts-check\":\"tsc --project tests/types/tsconfig.json\",\"lint\":\"standard\",\"lint-readme\":\"standard-markdown\",\"pretest\":\"npm run lint && npm run dts-check\",\"test\":\"tap tests/*.js --100 -Rspec\",\"prerelease\":\"npm test\",\"release\":\"standard-version\"},\"repository\":{\"type\":\"git\",\"url\":\"git://github.com/motdotla/dotenv.git\"},\"funding\":\"https://github.com/motdotla/dotenv?sponsor=1\",\"keywords\":[\"dotenv\",\"env\",\".env\",\"environment\",\"variables\",\"config\",\"settings\"],\"readmeFilename\":\"README.md\",\"license\":\"BSD-2-Clause\",\"devDependencies\":{\"@definitelytyped/dtslint\":\"^0.0.133\",\"@types/node\":\"^18.11.3\",\"decache\":\"^4.6.1\",\"sinon\":\"^14.0.1\",\"standard\":\"^17.0.0\",\"standard-markdown\":\"^7.1.0\",\"standard-version\":\"^9.5.0\",\"tap\":\"^16.3.0\",\"tar\":\"^6.1.11\",\"typescript\":\"^4.8.4\"},\"engines\":{\"node\":\">=12\"},\"browser\":{\"fs\":false}}')}};var t={};function __nccwpck_require__(n){var r=t[n];if(r!==undefined){return r.exports}var o=t[n]={exports:{}};var s=true;try{e[n](o,o.exports,__nccwpck_require__);s=false}finally{if(s)delete t[n]}return o.exports}(()=>{__nccwpck_require__.n=e=>{var t=e&&e.__esModule?()=>e[\"default\"]:()=>e;__nccwpck_require__.d(t,{a:t});return t}})();(()=>{__nccwpck_require__.d=(e,t)=>{for(var n in t){if(__nccwpck_require__.o(t,n)&&!__nccwpck_require__.o(e,n)){Object.defineProperty(e,n,{enumerable:true,get:t[n]})}}}})();(()=>{__nccwpck_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)})();(()=>{__nccwpck_require__.r=e=>{if(typeof Symbol!==\"undefined\"&&Symbol.toStringTag){Object.defineProperty(e,Symbol.toStringTag,{value:\"Module\"})}Object.defineProperty(e,\"__esModule\",{value:true})}})();if(typeof __nccwpck_require__!==\"undefined\")__nccwpck_require__.ab=__dirname+\"/\";var n={};(()=>{\"use strict\";__nccwpck_require__.r(n);__nccwpck_require__.d(n,{initialEnv:()=>a,updateInitialEnv:()=>updateInitialEnv,processEnv:()=>processEnv,resetEnv:()=>resetEnv,loadEnvConfig:()=>loadEnvConfig});var e=__nccwpck_require__(147);var t=__nccwpck_require__.n(e);var r=__nccwpck_require__(17);var o=__nccwpck_require__.n(r);var s=__nccwpck_require__(234);var i=__nccwpck_require__.n(s);var c=__nccwpck_require__(383);let a=undefined;let p=undefined;let l=undefined;let u=[];let _=[];function updateInitialEnv(e){Object.assign(a||{},e)}function replaceProcessEnv(e){Object.keys(process.env).forEach((t=>{if(!t.startsWith(\"__NEXT_PRIVATE\")){if(e[t]===undefined||e[t]===\"\"){delete process.env[t]}}}));Object.entries(e).forEach((([e,t])=>{process.env[e]=t}))}function processEnv(e,t,n=console,o=false,i){var p;if(!a){a=Object.assign({},process.env)}if(!o&&(process.env.__NEXT_PROCESSED_ENV||e.length===0)){return[process.env]}process.env.__NEXT_PROCESSED_ENV=\"true\";const l=Object.assign({},a);const u={};for(const o of e){try{let e={};e.parsed=s.parse(o.contents);e=(0,c.j)(e);if(e.parsed&&!_.some((e=>e.contents===o.contents&&e.path===o.path))){i===null||i===void 0?void 0:i(o.path)}for(const t of Object.keys(e.parsed||{})){if(typeof u[t]===\"undefined\"&&typeof l[t]===\"undefined\"){u[t]=(p=e.parsed)===null||p===void 0?void 0:p[t]}}o.env=e.parsed||{}}catch(e){n.error(`Failed to load env from ${r.join(t||\"\",o.path)}`,e)}}return[Object.assign(process.env,u),u]}function resetEnv(){if(a){replaceProcessEnv(a)}}function loadEnvConfig(t,n,o=console,s=false,i){if(!a){a=Object.assign({},process.env)}if(p&&!s){return{combinedEnv:p,parsedEnv:l,loadedEnvFiles:u}}replaceProcessEnv(a);_=u;u=[];const c=process.env.NODE_ENV===\"test\";const d=c?\"test\":n?\"development\":\"production\";const f=[`.env.${d}.local`,d!==\"test\"&&`.env.local`,`.env.${d}`,\".env\"].filter(Boolean);for(const n of f){const s=r.join(t,n);try{const t=e.statSync(s);if(!t.isFile()&&!t.isFIFO()){continue}const r=e.readFileSync(s,\"utf8\");u.push({path:n,contents:r,env:{}})}catch(e){if(e.code!==\"ENOENT\"){o.error(`Failed to load env from ${n}`,e)}}}[p,l]=processEnv(u,t,o,s,i);return{combinedEnv:p,parsedEnv:l,loadedEnvFiles:u}}})();module.exports=n})();","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// src/index.ts\nvar src_exports = {};\n__export(src_exports, {\n RequestCookies: () => RequestCookies,\n ResponseCookies: () => ResponseCookies,\n parseCookie: () => parseCookie,\n parseSetCookie: () => parseSetCookie,\n stringifyCookie: () => stringifyCookie\n});\nmodule.exports = __toCommonJS(src_exports);\n\n// src/serialize.ts\nfunction stringifyCookie(c) {\n var _a;\n const attrs = [\n \"path\" in c && c.path && `Path=${c.path}`,\n \"expires\" in c && (c.expires || c.expires === 0) && `Expires=${(typeof c.expires === \"number\" ? new Date(c.expires) : c.expires).toUTCString()}`,\n \"maxAge\" in c && typeof c.maxAge === \"number\" && `Max-Age=${c.maxAge}`,\n \"domain\" in c && c.domain && `Domain=${c.domain}`,\n \"secure\" in c && c.secure && \"Secure\",\n \"httpOnly\" in c && c.httpOnly && \"HttpOnly\",\n \"sameSite\" in c && c.sameSite && `SameSite=${c.sameSite}`,\n \"partitioned\" in c && c.partitioned && \"Partitioned\",\n \"priority\" in c && c.priority && `Priority=${c.priority}`\n ].filter(Boolean);\n const stringified = `${c.name}=${encodeURIComponent((_a = c.value) != null ? _a : \"\")}`;\n return attrs.length === 0 ? stringified : `${stringified}; ${attrs.join(\"; \")}`;\n}\nfunction parseCookie(cookie) {\n const map = /* @__PURE__ */ new Map();\n for (const pair of cookie.split(/; */)) {\n if (!pair)\n continue;\n const splitAt = pair.indexOf(\"=\");\n if (splitAt === -1) {\n map.set(pair, \"true\");\n continue;\n }\n const [key, value] = [pair.slice(0, splitAt), pair.slice(splitAt + 1)];\n try {\n map.set(key, decodeURIComponent(value != null ? value : \"true\"));\n } catch {\n }\n }\n return map;\n}\nfunction parseSetCookie(setCookie) {\n if (!setCookie) {\n return void 0;\n }\n const [[name, value], ...attributes] = parseCookie(setCookie);\n const {\n domain,\n expires,\n httponly,\n maxage,\n path,\n samesite,\n secure,\n partitioned,\n priority\n } = Object.fromEntries(\n attributes.map(([key, value2]) => [\n key.toLowerCase().replace(/-/g, \"\"),\n value2\n ])\n );\n const cookie = {\n name,\n value: decodeURIComponent(value),\n domain,\n ...expires && { expires: new Date(expires) },\n ...httponly && { httpOnly: true },\n ...typeof maxage === \"string\" && { maxAge: Number(maxage) },\n path,\n ...samesite && { sameSite: parseSameSite(samesite) },\n ...secure && { secure: true },\n ...priority && { priority: parsePriority(priority) },\n ...partitioned && { partitioned: true }\n };\n return compact(cookie);\n}\nfunction compact(t) {\n const newT = {};\n for (const key in t) {\n if (t[key]) {\n newT[key] = t[key];\n }\n }\n return newT;\n}\nvar SAME_SITE = [\"strict\", \"lax\", \"none\"];\nfunction parseSameSite(string) {\n string = string.toLowerCase();\n return SAME_SITE.includes(string) ? string : void 0;\n}\nvar PRIORITY = [\"low\", \"medium\", \"high\"];\nfunction parsePriority(string) {\n string = string.toLowerCase();\n return PRIORITY.includes(string) ? string : void 0;\n}\nfunction splitCookiesString(cookiesString) {\n if (!cookiesString)\n return [];\n var cookiesStrings = [];\n var pos = 0;\n var start;\n var ch;\n var lastComma;\n var nextStart;\n var cookiesSeparatorFound;\n function skipWhitespace() {\n while (pos < cookiesString.length && /\\s/.test(cookiesString.charAt(pos))) {\n pos += 1;\n }\n return pos < cookiesString.length;\n }\n function notSpecialChar() {\n ch = cookiesString.charAt(pos);\n return ch !== \"=\" && ch !== \";\" && ch !== \",\";\n }\n while (pos < cookiesString.length) {\n start = pos;\n cookiesSeparatorFound = false;\n while (skipWhitespace()) {\n ch = cookiesString.charAt(pos);\n if (ch === \",\") {\n lastComma = pos;\n pos += 1;\n skipWhitespace();\n nextStart = pos;\n while (pos < cookiesString.length && notSpecialChar()) {\n pos += 1;\n }\n if (pos < cookiesString.length && cookiesString.charAt(pos) === \"=\") {\n cookiesSeparatorFound = true;\n pos = nextStart;\n cookiesStrings.push(cookiesString.substring(start, lastComma));\n start = pos;\n } else {\n pos = lastComma + 1;\n }\n } else {\n pos += 1;\n }\n }\n if (!cookiesSeparatorFound || pos >= cookiesString.length) {\n cookiesStrings.push(cookiesString.substring(start, cookiesString.length));\n }\n }\n return cookiesStrings;\n}\n\n// src/request-cookies.ts\nvar RequestCookies = class {\n constructor(requestHeaders) {\n /** @internal */\n this._parsed = /* @__PURE__ */ new Map();\n this._headers = requestHeaders;\n const header = requestHeaders.get(\"cookie\");\n if (header) {\n const parsed = parseCookie(header);\n for (const [name, value] of parsed) {\n this._parsed.set(name, { name, value });\n }\n }\n }\n [Symbol.iterator]() {\n return this._parsed[Symbol.iterator]();\n }\n /**\n * The amount of cookies received from the client\n */\n get size() {\n return this._parsed.size;\n }\n get(...args) {\n const name = typeof args[0] === \"string\" ? args[0] : args[0].name;\n return this._parsed.get(name);\n }\n getAll(...args) {\n var _a;\n const all = Array.from(this._parsed);\n if (!args.length) {\n return all.map(([_, value]) => value);\n }\n const name = typeof args[0] === \"string\" ? args[0] : (_a = args[0]) == null ? void 0 : _a.name;\n return all.filter(([n]) => n === name).map(([_, value]) => value);\n }\n has(name) {\n return this._parsed.has(name);\n }\n set(...args) {\n const [name, value] = args.length === 1 ? [args[0].name, args[0].value] : args;\n const map = this._parsed;\n map.set(name, { name, value });\n this._headers.set(\n \"cookie\",\n Array.from(map).map(([_, value2]) => stringifyCookie(value2)).join(\"; \")\n );\n return this;\n }\n /**\n * Delete the cookies matching the passed name or names in the request.\n */\n delete(names) {\n const map = this._parsed;\n const result = !Array.isArray(names) ? map.delete(names) : names.map((name) => map.delete(name));\n this._headers.set(\n \"cookie\",\n Array.from(map).map(([_, value]) => stringifyCookie(value)).join(\"; \")\n );\n return result;\n }\n /**\n * Delete all the cookies in the cookies in the request.\n */\n clear() {\n this.delete(Array.from(this._parsed.keys()));\n return this;\n }\n /**\n * Format the cookies in the request as a string for logging\n */\n [Symbol.for(\"edge-runtime.inspect.custom\")]() {\n return `RequestCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`;\n }\n toString() {\n return [...this._parsed.values()].map((v) => `${v.name}=${encodeURIComponent(v.value)}`).join(\"; \");\n }\n};\n\n// src/response-cookies.ts\nvar ResponseCookies = class {\n constructor(responseHeaders) {\n /** @internal */\n this._parsed = /* @__PURE__ */ new Map();\n var _a, _b, _c;\n this._headers = responseHeaders;\n const setCookie = (_c = (_b = (_a = responseHeaders.getSetCookie) == null ? void 0 : _a.call(responseHeaders)) != null ? _b : responseHeaders.get(\"set-cookie\")) != null ? _c : [];\n const cookieStrings = Array.isArray(setCookie) ? setCookie : splitCookiesString(setCookie);\n for (const cookieString of cookieStrings) {\n const parsed = parseSetCookie(cookieString);\n if (parsed)\n this._parsed.set(parsed.name, parsed);\n }\n }\n /**\n * {@link https://wicg.github.io/cookie-store/#CookieStore-get CookieStore#get} without the Promise.\n */\n get(...args) {\n const key = typeof args[0] === \"string\" ? args[0] : args[0].name;\n return this._parsed.get(key);\n }\n /**\n * {@link https://wicg.github.io/cookie-store/#CookieStore-getAll CookieStore#getAll} without the Promise.\n */\n getAll(...args) {\n var _a;\n const all = Array.from(this._parsed.values());\n if (!args.length) {\n return all;\n }\n const key = typeof args[0] === \"string\" ? args[0] : (_a = args[0]) == null ? void 0 : _a.name;\n return all.filter((c) => c.name === key);\n }\n has(name) {\n return this._parsed.has(name);\n }\n /**\n * {@link https://wicg.github.io/cookie-store/#CookieStore-set CookieStore#set} without the Promise.\n */\n set(...args) {\n const [name, value, cookie] = args.length === 1 ? [args[0].name, args[0].value, args[0]] : args;\n const map = this._parsed;\n map.set(name, normalizeCookie({ name, value, ...cookie }));\n replace(map, this._headers);\n return this;\n }\n /**\n * {@link https://wicg.github.io/cookie-store/#CookieStore-delete CookieStore#delete} without the Promise.\n */\n delete(...args) {\n const [name, options] = typeof args[0] === \"string\" ? [args[0]] : [args[0].name, args[0]];\n return this.set({ ...options, name, value: \"\", expires: /* @__PURE__ */ new Date(0) });\n }\n [Symbol.for(\"edge-runtime.inspect.custom\")]() {\n return `ResponseCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`;\n }\n toString() {\n return [...this._parsed.values()].map(stringifyCookie).join(\"; \");\n }\n};\nfunction replace(bag, headers) {\n headers.delete(\"set-cookie\");\n for (const [, value] of bag) {\n const serialized = stringifyCookie(value);\n headers.append(\"set-cookie\", serialized);\n }\n}\nfunction normalizeCookie(cookie = { name: \"\", value: \"\" }) {\n if (typeof cookie.expires === \"number\") {\n cookie.expires = new Date(cookie.expires);\n }\n if (cookie.maxAge) {\n cookie.expires = new Date(Date.now() + cookie.maxAge * 1e3);\n }\n if (cookie.path === null || cookie.path === void 0) {\n cookie.path = \"/\";\n }\n return cookie;\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n RequestCookies,\n ResponseCookies,\n parseCookie,\n parseSetCookie,\n stringifyCookie\n});\n","(()=>{\"use strict\";var e={56:e=>{\n/*!\n * bytes\n * Copyright(c) 2012-2014 TJ Holowaychuk\n * Copyright(c) 2015 Jed Watson\n * MIT Licensed\n */\ne.exports=bytes;e.exports.format=format;e.exports.parse=parse;var r=/\\B(?=(\\d{3})+(?!\\d))/g;var a=/(?:\\.0*|(\\.[^0]+)0+)$/;var t={b:1,kb:1<<10,mb:1<<20,gb:1<<30,tb:Math.pow(1024,4),pb:Math.pow(1024,5)};var i=/^((-|\\+)?(\\d+(?:\\.\\d+)?)) *(kb|mb|gb|tb|pb)$/i;function bytes(e,r){if(typeof e===\"string\"){return parse(e)}if(typeof e===\"number\"){return format(e,r)}return null}function format(e,i){if(!Number.isFinite(e)){return null}var n=Math.abs(e);var o=i&&i.thousandsSeparator||\"\";var s=i&&i.unitSeparator||\"\";var f=i&&i.decimalPlaces!==undefined?i.decimalPlaces:2;var u=Boolean(i&&i.fixedDecimals);var p=i&&i.unit||\"\";if(!p||!t[p.toLowerCase()]){if(n>=t.pb){p=\"PB\"}else if(n>=t.tb){p=\"TB\"}else if(n>=t.gb){p=\"GB\"}else if(n>=t.mb){p=\"MB\"}else if(n>=t.kb){p=\"KB\"}else{p=\"B\"}}var b=e/t[p.toLowerCase()];var l=b.toFixed(f);if(!u){l=l.replace(a,\"$1\")}if(o){l=l.split(\".\").map((function(e,a){return a===0?e.replace(r,o):e})).join(\".\")}return l+s+p}function parse(e){if(typeof e===\"number\"&&!isNaN(e)){return e}if(typeof e!==\"string\"){return null}var r=i.exec(e);var a;var n=\"b\";if(!r){a=parseInt(e,10);n=\"b\"}else{a=parseFloat(r[1]);n=r[4].toLowerCase()}return Math.floor(t[n]*a)}}};var r={};function __nccwpck_require__(a){var t=r[a];if(t!==undefined){return t.exports}var i=r[a]={exports:{}};var n=true;try{e[a](i,i.exports,__nccwpck_require__);n=false}finally{if(n)delete r[a]}return i.exports}if(typeof __nccwpck_require__!==\"undefined\")__nccwpck_require__.ab=__dirname+\"/\";var a=__nccwpck_require__(56);module.exports=a})();","(()=>{\"use strict\";if(typeof __nccwpck_require__!==\"undefined\")__nccwpck_require__.ab=__dirname+\"/\";var e={};(()=>{var r=e;\n/*!\n * cookie\n * Copyright(c) 2012-2014 Roman Shtylman\n * Copyright(c) 2015 Douglas Christopher Wilson\n * MIT Licensed\n */r.parse=parse;r.serialize=serialize;var i=decodeURIComponent;var t=encodeURIComponent;var a=/; */;var n=/^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;function parse(e,r){if(typeof e!==\"string\"){throw new TypeError(\"argument str must be a string\")}var t={};var n=r||{};var o=e.split(a);var s=n.decode||i;for(var p=0;p{\"use strict\";var e={695:e=>{\n/*!\n * fresh\n * Copyright(c) 2012 TJ Holowaychuk\n * Copyright(c) 2016-2017 Douglas Christopher Wilson\n * MIT Licensed\n */\nvar r=/(?:^|,)\\s*?no-cache\\s*?(?:,|$)/;e.exports=fresh;function fresh(e,a){var t=e[\"if-modified-since\"];var s=e[\"if-none-match\"];if(!t&&!s){return false}var i=e[\"cache-control\"];if(i&&r.test(i)){return false}if(s&&s!==\"*\"){var f=a[\"etag\"];if(!f){return false}var n=true;var u=parseTokenList(s);for(var _=0;_{\"use strict\";var e={993:e=>{var t=Object.prototype.hasOwnProperty,n=\"~\";function Events(){}if(Object.create){Events.prototype=Object.create(null);if(!(new Events).__proto__)n=false}function EE(e,t,n){this.fn=e;this.context=t;this.once=n||false}function addListener(e,t,r,i,s){if(typeof r!==\"function\"){throw new TypeError(\"The listener must be a function\")}var o=new EE(r,i||e,s),u=n?n+t:t;if(!e._events[u])e._events[u]=o,e._eventsCount++;else if(!e._events[u].fn)e._events[u].push(o);else e._events[u]=[e._events[u],o];return e}function clearEvent(e,t){if(--e._eventsCount===0)e._events=new Events;else delete e._events[t]}function EventEmitter(){this._events=new Events;this._eventsCount=0}EventEmitter.prototype.eventNames=function eventNames(){var e=[],r,i;if(this._eventsCount===0)return e;for(i in r=this._events){if(t.call(r,i))e.push(n?i.slice(1):i)}if(Object.getOwnPropertySymbols){return e.concat(Object.getOwnPropertySymbols(r))}return e};EventEmitter.prototype.listeners=function listeners(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,s=r.length,o=new Array(s);i{e.exports=(e,t)=>{t=t||(()=>{});return e.then((e=>new Promise((e=>{e(t())})).then((()=>e))),(e=>new Promise((e=>{e(t())})).then((()=>{throw e}))))}},574:(e,t)=>{Object.defineProperty(t,\"__esModule\",{value:true});function lowerBound(e,t,n){let r=0;let i=e.length;while(i>0){const s=i/2|0;let o=r+s;if(n(e[o],t)<=0){r=++o;i-=s+1}else{i=s}}return r}t[\"default\"]=lowerBound},821:(e,t,n)=>{Object.defineProperty(t,\"__esModule\",{value:true});const r=n(574);class PriorityQueue{constructor(){this._queue=[]}enqueue(e,t){t=Object.assign({priority:0},t);const n={priority:t.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority){this._queue.push(n);return}const i=r.default(this._queue,n,((e,t)=>t.priority-e.priority));this._queue.splice(i,0,n)}dequeue(){const e=this._queue.shift();return e===null||e===void 0?void 0:e.run}filter(e){return this._queue.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this._queue.length}}t[\"default\"]=PriorityQueue},816:(e,t,n)=>{const r=n(213);class TimeoutError extends Error{constructor(e){super(e);this.name=\"TimeoutError\"}}const pTimeout=(e,t,n)=>new Promise(((i,s)=>{if(typeof t!==\"number\"||t<0){throw new TypeError(\"Expected `milliseconds` to be a positive number\")}if(t===Infinity){i(e);return}const o=setTimeout((()=>{if(typeof n===\"function\"){try{i(n())}catch(e){s(e)}return}const r=typeof n===\"string\"?n:`Promise timed out after ${t} milliseconds`;const o=n instanceof Error?n:new TimeoutError(r);if(typeof e.cancel===\"function\"){e.cancel()}s(o)}),t);r(e.then(i,s),(()=>{clearTimeout(o)}))}));e.exports=pTimeout;e.exports[\"default\"]=pTimeout;e.exports.TimeoutError=TimeoutError}};var t={};function __nccwpck_require__(n){var r=t[n];if(r!==undefined){return r.exports}var i=t[n]={exports:{}};var s=true;try{e[n](i,i.exports,__nccwpck_require__);s=false}finally{if(s)delete t[n]}return i.exports}if(typeof __nccwpck_require__!==\"undefined\")__nccwpck_require__.ab=__dirname+\"/\";var n={};(()=>{var e=n;Object.defineProperty(e,\"__esModule\",{value:true});const t=__nccwpck_require__(993);const r=__nccwpck_require__(816);const i=__nccwpck_require__(821);const empty=()=>{};const s=new r.TimeoutError;class PQueue extends t{constructor(e){var t,n,r,s;super();this._intervalCount=0;this._intervalEnd=0;this._pendingCount=0;this._resolveEmpty=empty;this._resolveIdle=empty;e=Object.assign({carryoverConcurrencyCount:false,intervalCap:Infinity,interval:0,concurrency:Infinity,autoStart:true,queueClass:i.default},e);if(!(typeof e.intervalCap===\"number\"&&e.intervalCap>=1)){throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:\"\"}\\` (${typeof e.intervalCap})`)}if(e.interval===undefined||!(Number.isFinite(e.interval)&&e.interval>=0)){throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${(s=(r=e.interval)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:\"\"}\\` (${typeof e.interval})`)}this._carryoverConcurrencyCount=e.carryoverConcurrencyCount;this._isIntervalIgnored=e.intervalCap===Infinity||e.interval===0;this._intervalCap=e.intervalCap;this._interval=e.interval;this._queue=new e.queueClass;this._queueClass=e.queueClass;this.concurrency=e.concurrency;this._timeout=e.timeout;this._throwOnTimeout=e.throwOnTimeout===true;this._isPaused=e.autoStart===false}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount{this._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=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-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)?(?!\\?)/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-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})();","// This file should be imported before any others. It sets up the environment\n// for later imports to work properly.\n\n// expose AsyncLocalStorage on global for react usage if it isn't already provided by the environment\nif (typeof (globalThis as any).AsyncLocalStorage !== 'function') {\n const { AsyncLocalStorage } =\n require('async_hooks') as typeof import('async_hooks')\n ;(globalThis as any).AsyncLocalStorage = AsyncLocalStorage\n}\n\nif (typeof (globalThis as any).WebSocket !== 'function') {\n Object.defineProperty(globalThis, 'WebSocket', {\n configurable: true,\n get() {\n return (\n require('next/dist/compiled/ws') as typeof import('next/dist/compiled/ws')\n ).WebSocket\n },\n set(value) {\n Object.defineProperty(globalThis, 'WebSocket', {\n configurable: true,\n writable: true,\n value,\n })\n },\n })\n}\n","// Polyfill crypto() in the Node.js environment\n\nif (!global.crypto) {\n let webcrypto: Crypto | undefined\n\n Object.defineProperty(global, 'crypto', {\n enumerable: false,\n configurable: true,\n get() {\n if (!webcrypto) {\n // @ts-expect-error -- TODO: Is this actually safe?\n webcrypto = (require('node:crypto') as typeof import('node:crypto'))\n .webcrypto\n }\n return webcrypto\n },\n set(value: Crypto) {\n webcrypto = value\n },\n })\n}\n","/**\n * This module is for next.js server internal usage of path module.\n * It will use native path module for nodejs runtime.\n * It will use path-browserify polyfill for edge runtime.\n */\nlet path\n\nif (process.env.NEXT_RUNTIME === 'edge') {\n path = require('next/dist/compiled/path-browserify')\n} else {\n path = require('path')\n}\n\nmodule.exports = path\n","// Note: This file is JS because it's used by the taskfile-swc.js file, which is JS.\n// Keep file changes in sync with the corresponding `.d.ts` files.\n/**\n * These are the browser versions that support all of the following:\n * static import: https://caniuse.com/es6-module\n * dynamic import: https://caniuse.com/es6-module-dynamic-import\n * import.meta: https://caniuse.com/mdn-javascript_operators_import_meta\n */\nconst MODERN_BROWSERSLIST_TARGET = [\n 'chrome 64',\n 'edge 79',\n 'firefox 67',\n 'opera 51',\n 'safari 12',\n]\n\nmodule.exports = MODERN_BROWSERSLIST_TARGET\n","(()=>{var e={318:function(e,t){(function(e,n){true?n(t):0})(this,(function(e){\"use strict\";class StructError extends TypeError{constructor(e,t){let n;const{message:r,explanation:i,...c}=e;const{path:o}=e;const a=o.length===0?r:`At path: ${o.join(\".\")} -- ${r}`;super(i??a);if(i!=null)this.cause=a;Object.assign(this,c);this.name=this.constructor.name;this.failures=()=>n??(n=[e,...t()])}}function isIterable(e){return isObject(e)&&typeof e[Symbol.iterator]===\"function\"}function isObject(e){return typeof e===\"object\"&&e!=null}function isPlainObject(e){if(Object.prototype.toString.call(e)!==\"[object Object]\"){return false}const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function print(e){if(typeof e===\"symbol\"){return e.toString()}return typeof e===\"string\"?JSON.stringify(e):`${e}`}function shiftIterator(e){const{done:t,value:n}=e.next();return t?undefined:n}function toFailure(e,t,n,r){if(e===true){return}else if(e===false){e={}}else if(typeof e===\"string\"){e={message:e}}const{path:i,branch:c}=t;const{type:o}=n;const{refinement:a,message:s=`Expected a value of type \\`${o}\\`${a?` with refinement \\`${a}\\``:\"\"}, but received: \\`${print(r)}\\``}=e;return{value:r,type:o,refinement:a,key:i[i.length-1],path:i,branch:c,...e,message:s}}function*toFailures(e,t,n,r){if(!isIterable(e)){e=[e]}for(const i of e){const e=toFailure(i,t,n,r);if(e){yield e}}}function*run(e,t,n={}){const{path:r=[],branch:i=[e],coerce:c=false,mask:o=false}=n;const a={path:r,branch:i};if(c){e=t.coercer(e,a);if(o&&t.type!==\"type\"&&isObject(t.schema)&&isObject(e)&&!Array.isArray(e)){for(const n in e){if(t.schema[n]===undefined){delete e[n]}}}}let s=\"valid\";for(const r of t.validator(e,a)){r.explanation=n.message;s=\"not_valid\";yield[r,undefined]}for(let[u,f,l]of t.entries(e,a)){const t=run(f,l,{path:u===undefined?r:[...r,u],branch:u===undefined?i:[...i,f],coerce:c,mask:o,message:n.message});for(const n of t){if(n[0]){s=n[0].refinement!=null?\"not_refined\":\"not_valid\";yield[n[0],undefined]}else if(c){f=n[1];if(u===undefined){e=f}else if(e instanceof Map){e.set(u,f)}else if(e instanceof Set){e.add(f)}else if(isObject(e)){if(f!==undefined||u in e)e[u]=f}}}}if(s!==\"not_valid\"){for(const r of t.refiner(e,a)){r.explanation=n.message;s=\"not_refined\";yield[r,undefined]}}if(s===\"valid\"){yield[undefined,e]}}class Struct{constructor(e){const{type:t,schema:n,validator:r,refiner:i,coercer:c=(e=>e),entries:o=function*(){}}=e;this.type=t;this.schema=n;this.entries=o;this.coercer=c;if(r){this.validator=(e,t)=>{const n=r(e,t);return toFailures(n,t,this,e)}}else{this.validator=()=>[]}if(i){this.refiner=(e,t)=>{const n=i(e,t);return toFailures(n,t,this,e)}}else{this.refiner=()=>[]}}assert(e,t){return assert(e,this,t)}create(e,t){return create(e,this,t)}is(e){return is(e,this)}mask(e,t){return mask(e,this,t)}validate(e,t={}){return validate(e,this,t)}}function assert(e,t,n){const r=validate(e,t,{message:n});if(r[0]){throw r[0]}}function create(e,t,n){const r=validate(e,t,{coerce:true,message:n});if(r[0]){throw r[0]}else{return r[1]}}function mask(e,t,n){const r=validate(e,t,{coerce:true,mask:true,message:n});if(r[0]){throw r[0]}else{return r[1]}}function is(e,t){const n=validate(e,t);return!n[0]}function validate(e,t,n={}){const r=run(e,t,n);const i=shiftIterator(r);if(i[0]){const e=new StructError(i[0],(function*(){for(const e of r){if(e[0]){yield e[0]}}}));return[e,undefined]}else{const e=i[1];return[undefined,e]}}function assign(...e){const t=e[0].type===\"type\";const n=e.map((e=>e.schema));const r=Object.assign({},...n);return t?type(r):object(r)}function define(e,t){return new Struct({type:e,schema:null,validator:t})}function deprecated(e,t){return new Struct({...e,refiner:(t,n)=>t===undefined||e.refiner(t,n),validator(n,r){if(n===undefined){return true}else{t(n,r);return e.validator(n,r)}}})}function dynamic(e){return new Struct({type:\"dynamic\",schema:null,*entries(t,n){const r=e(t,n);yield*r.entries(t,n)},validator(t,n){const r=e(t,n);return r.validator(t,n)},coercer(t,n){const r=e(t,n);return r.coercer(t,n)},refiner(t,n){const r=e(t,n);return r.refiner(t,n)}})}function lazy(e){let t;return new Struct({type:\"lazy\",schema:null,*entries(n,r){t??(t=e());yield*t.entries(n,r)},validator(n,r){t??(t=e());return t.validator(n,r)},coercer(n,r){t??(t=e());return t.coercer(n,r)},refiner(n,r){t??(t=e());return t.refiner(n,r)}})}function omit(e,t){const{schema:n}=e;const r={...n};for(const e of t){delete r[e]}switch(e.type){case\"type\":return type(r);default:return object(r)}}function partial(e){const t=e instanceof Struct?{...e.schema}:{...e};for(const e in t){t[e]=optional(t[e])}return object(t)}function pick(e,t){const{schema:n}=e;const r={};for(const e of t){r[e]=n[e]}return object(r)}function struct(e,t){console.warn(\"superstruct@0.11 - The `struct` helper has been renamed to `define`.\");return define(e,t)}function any(){return define(\"any\",(()=>true))}function array(e){return new Struct({type:\"array\",schema:e,*entries(t){if(e&&Array.isArray(t)){for(const[n,r]of t.entries()){yield[n,r,e]}}},coercer(e){return Array.isArray(e)?e.slice():e},validator(e){return Array.isArray(e)||`Expected an array value, but received: ${print(e)}`}})}function bigint(){return define(\"bigint\",(e=>typeof e===\"bigint\"))}function boolean(){return define(\"boolean\",(e=>typeof e===\"boolean\"))}function date(){return define(\"date\",(e=>e instanceof Date&&!isNaN(e.getTime())||`Expected a valid \\`Date\\` object, but received: ${print(e)}`))}function enums(e){const t={};const n=e.map((e=>print(e))).join();for(const n of e){t[n]=n}return new Struct({type:\"enums\",schema:t,validator(t){return e.includes(t)||`Expected one of \\`${n}\\`, but received: ${print(t)}`}})}function func(){return define(\"func\",(e=>typeof e===\"function\"||`Expected a function, but received: ${print(e)}`))}function instance(e){return define(\"instance\",(t=>t instanceof e||`Expected a \\`${e.name}\\` instance, but received: ${print(t)}`))}function integer(){return define(\"integer\",(e=>typeof e===\"number\"&&!isNaN(e)&&Number.isInteger(e)||`Expected an integer, but received: ${print(e)}`))}function intersection(e){return new Struct({type:\"intersection\",schema:null,*entries(t,n){for(const r of e){yield*r.entries(t,n)}},*validator(t,n){for(const r of e){yield*r.validator(t,n)}},*refiner(t,n){for(const r of e){yield*r.refiner(t,n)}}})}function literal(e){const t=print(e);const n=typeof e;return new Struct({type:\"literal\",schema:n===\"string\"||n===\"number\"||n===\"boolean\"?e:null,validator(n){return n===e||`Expected the literal \\`${t}\\`, but received: ${print(n)}`}})}function map(e,t){return new Struct({type:\"map\",schema:null,*entries(n){if(e&&t&&n instanceof Map){for(const[r,i]of n.entries()){yield[r,r,e];yield[r,i,t]}}},coercer(e){return e instanceof Map?new Map(e):e},validator(e){return e instanceof Map||`Expected a \\`Map\\` object, but received: ${print(e)}`}})}function never(){return define(\"never\",(()=>false))}function nullable(e){return new Struct({...e,validator:(t,n)=>t===null||e.validator(t,n),refiner:(t,n)=>t===null||e.refiner(t,n)})}function number(){return define(\"number\",(e=>typeof e===\"number\"&&!isNaN(e)||`Expected a number, but received: ${print(e)}`))}function object(e){const t=e?Object.keys(e):[];const n=never();return new Struct({type:\"object\",schema:e?e:null,*entries(r){if(e&&isObject(r)){const i=new Set(Object.keys(r));for(const n of t){i.delete(n);yield[n,r[n],e[n]]}for(const e of i){yield[e,r[e],n]}}},validator(e){return isObject(e)||`Expected an object, but received: ${print(e)}`},coercer(e){return isObject(e)?{...e}:e}})}function optional(e){return new Struct({...e,validator:(t,n)=>t===undefined||e.validator(t,n),refiner:(t,n)=>t===undefined||e.refiner(t,n)})}function record(e,t){return new Struct({type:\"record\",schema:null,*entries(n){if(isObject(n)){for(const r in n){const i=n[r];yield[r,r,e];yield[r,i,t]}}},validator(e){return isObject(e)||`Expected an object, but received: ${print(e)}`}})}function regexp(){return define(\"regexp\",(e=>e instanceof RegExp))}function set(e){return new Struct({type:\"set\",schema:null,*entries(t){if(e&&t instanceof Set){for(const n of t){yield[n,n,e]}}},coercer(e){return e instanceof Set?new Set(e):e},validator(e){return e instanceof Set||`Expected a \\`Set\\` object, but received: ${print(e)}`}})}function string(){return define(\"string\",(e=>typeof e===\"string\"||`Expected a string, but received: ${print(e)}`))}function tuple(e){const t=never();return new Struct({type:\"tuple\",schema:null,*entries(n){if(Array.isArray(n)){const r=Math.max(e.length,n.length);for(let i=0;ie.type)).join(\" | \");return new Struct({type:\"union\",schema:null,coercer(t){for(const n of e){const[e,r]=n.validate(t,{coerce:true});if(!e){return r}}return t},validator(n,r){const i=[];for(const t of e){const[...e]=run(n,t,r);const[c]=e;if(!c[0]){return[]}else{for(const[t]of e){if(t){i.push(t)}}}}return[`Expected the value to satisfy a union of \\`${t}\\`, but received: ${print(n)}`,...i]}})}function unknown(){return define(\"unknown\",(()=>true))}function coerce(e,t,n){return new Struct({...e,coercer:(r,i)=>is(r,t)?e.coercer(n(r,i),i):e.coercer(r,i)})}function defaulted(e,t,n={}){return coerce(e,unknown(),(e=>{const r=typeof t===\"function\"?t():t;if(e===undefined){return r}if(!n.strict&&isPlainObject(e)&&isPlainObject(r)){const t={...e};let n=false;for(const e in r){if(t[e]===undefined){t[e]=r[e];n=true}}if(n){return t}}return e}))}function trimmed(e){return coerce(e,string(),(e=>e.trim()))}function empty(e){return refine(e,\"empty\",(t=>{const n=getSize(t);return n===0||`Expected an empty ${e.type} but received one with a size of \\`${n}\\``}))}function getSize(e){if(e instanceof Map||e instanceof Set){return e.size}else{return e.length}}function max(e,t,n={}){const{exclusive:r}=n;return refine(e,\"max\",(n=>r?nr?n>t:n>=t||`Expected a ${e.type} greater than ${r?\"\":\"or equal to \"}${t} but received \\`${n}\\``))}function nonempty(e){return refine(e,\"nonempty\",(t=>{const n=getSize(t);return n>0||`Expected a nonempty ${e.type} but received an empty one`}))}function pattern(e,t){return refine(e,\"pattern\",(n=>t.test(n)||`Expected a ${e.type} matching \\`/${t.source}/\\` but received \"${n}\"`))}function size(e,t,n=t){const r=`Expected a ${e.type}`;const i=t===n?`of \\`${t}\\``:`between \\`${t}\\` and \\`${n}\\``;return refine(e,\"size\",(e=>{if(typeof e===\"number\"||e instanceof Date){return t<=e&&e<=n||`${r} ${i} but received \\`${e}\\``}else if(e instanceof Map||e instanceof Set){const{size:c}=e;return t<=c&&c<=n||`${r} with a size ${i} but received one with a size of \\`${c}\\``}else{const{length:c}=e;return t<=c&&c<=n||`${r} with a length ${i} but received one with a length of \\`${c}\\``}}))}function refine(e,t,n){return new Struct({...e,*refiner(r,i){yield*e.refiner(r,i);const c=n(r,i);const o=toFailures(c,i,e,r);for(const e of o){yield{...e,refinement:t}}}})}e.Struct=Struct;e.StructError=StructError;e.any=any;e.array=array;e.assert=assert;e.assign=assign;e.bigint=bigint;e.boolean=boolean;e.coerce=coerce;e.create=create;e.date=date;e.defaulted=defaulted;e.define=define;e.deprecated=deprecated;e.dynamic=dynamic;e.empty=empty;e.enums=enums;e.func=func;e.instance=instance;e.integer=integer;e.intersection=intersection;e.is=is;e.lazy=lazy;e.literal=literal;e.map=map;e.mask=mask;e.max=max;e.min=min;e.never=never;e.nonempty=nonempty;e.nullable=nullable;e.number=number;e.object=object;e.omit=omit;e.optional=optional;e.partial=partial;e.pattern=pattern;e.pick=pick;e.record=record;e.refine=refine;e.regexp=regexp;e.set=set;e.size=size;e.string=string;e.struct=struct;e.trimmed=trimmed;e.tuple=tuple;e.type=type;e.union=union;e.unknown=unknown;e.validate=validate}))}};if(typeof __nccwpck_require__!==\"undefined\")__nccwpck_require__.ab=__dirname+\"/\";var t={};e[318](0,t);module.exports=t})();","// getDefaultExport function for compatibility with non-ESM modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};\n","__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * We extend Web Crypto APIs during builds and revalidates to ensure that prerenders don't observe random bytes\n * When cacheComponents is enabled. Random bytes are a form of IO even if they resolve synchronously. When cacheComponents is\n * enabled we need to ensure that random bytes are excluded from prerenders unless they are cached.\n *\n *\n * The extensions here never error nor alter the underlying return values and thus should be transparent to callers.\n */\n\nimport { io } from './utils'\n\nlet webCrypto: typeof crypto\nif (process.env.NEXT_RUNTIME === 'edge') {\n webCrypto = crypto\n} else {\n if (typeof crypto === 'undefined') {\n // @ts-expect-error -- TODO: Is this actually safe?\n webCrypto = (require('node:crypto') as typeof import('node:crypto'))\n .webcrypto\n } else {\n webCrypto = crypto\n }\n}\n\nconst getRandomValuesExpression = '`crypto.getRandomValues()`'\ntry {\n const _getRandomValues = webCrypto.getRandomValues\n webCrypto.getRandomValues = function getRandomValues() {\n io(getRandomValuesExpression, 'crypto')\n return _getRandomValues.apply(webCrypto, arguments as any)\n }\n} catch {\n console.error(\n `Failed to install ${getRandomValuesExpression} extension. When using \\`experimental.cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n )\n}\n\nconst randomUUIDExpression = '`crypto.randomUUID()`'\ntry {\n const _randomUUID = webCrypto.randomUUID\n webCrypto.randomUUID = function randomUUID() {\n io(randomUUIDExpression, 'crypto')\n return _randomUUID.apply(webCrypto, arguments as any)\n } as typeof _randomUUID\n} catch {\n console.error(\n `Failed to install ${getRandomValuesExpression} extension. When using \\`experimental.cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n )\n}\n","import type { SourceMap } from 'module'\nimport { LRUCache } from './lru-cache'\n\nfunction noSourceMap(): SourceMap | undefined {\n return undefined\n}\n\n// Edge runtime does not implement `module`\nconst nativeFindSourceMap =\n process.env.NEXT_RUNTIME === 'edge'\n ? noSourceMap\n : (require('module') as typeof import('module')).findSourceMap\n\n/**\n * https://tc39.es/source-map/#index-map\n */\ninterface IndexSourceMapSection {\n offset: {\n line: number\n column: number\n }\n map: BasicSourceMapPayload\n}\n\n// TODO(veil): Upstream types\n/** https://tc39.es/ecma426/#sec-index-source-map */\ninterface IndexSourceMap {\n version: number\n file: string\n sections: IndexSourceMapSection[]\n}\n\n/** https://tc39.es/ecma426/#sec-source-map-format */\nexport interface BasicSourceMapPayload {\n version: number\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `file` is optional. */\n file: string\n sourceRoot?: string\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `sources[number]` can be `null`. */\n sources: Array\n names: Array\n mappings: string\n ignoreList?: number[]\n}\n\nexport type ModernSourceMapPayload = BasicSourceMapPayload | IndexSourceMap\n\nexport function sourceMapIgnoreListsEverything(\n sourceMap: BasicSourceMapPayload\n): boolean {\n return (\n sourceMap.ignoreList !== undefined &&\n sourceMap.sources.length === sourceMap.ignoreList.length\n )\n}\n\n/**\n * Finds the sourcemap payload applicable to a given frame.\n * Equal to the input unless an Index Source Map is used.\n * @param line0 - The line number of the frame, 0-based.\n * @param column0 - The column number of the frame, 0-based.\n */\nexport function findApplicableSourceMapPayload(\n line0: number,\n column0: number,\n payload: ModernSourceMapPayload\n): BasicSourceMapPayload | undefined {\n if ('sections' in payload) {\n if (payload.sections.length === 0) {\n return undefined\n }\n\n // Sections must not overlap and must be sorted: https://tc39.es/source-map/#section-object\n // Therefore the last section that has an offset less than or equal to the frame is the applicable one.\n const sections = payload.sections\n let left = 0\n let right = sections.length - 1\n let result: IndexSourceMapSection | null = null\n\n while (left <= right) {\n // fast Math.floor\n const middle = ~~((left + right) / 2)\n const section = sections[middle]\n const offset = section.offset\n\n if (\n offset.line < line0 ||\n (offset.line === line0 && offset.column <= column0)\n ) {\n result = section\n left = middle + 1\n } else {\n right = middle - 1\n }\n }\n\n return result === null ? undefined : result.map\n } else {\n return payload\n }\n}\n\nconst didWarnAboutInvalidSourceMapDEV = new Set()\n\nconst findSourceMap: (scriptNameOrSourceURL: string) => SourceMap | undefined =\n process.env.NEXT_RUNTIME === 'nodejs' &&\n process.versions.node?.startsWith('18')\n ? // Node.js 18 has a horribly slow `findSourceMap` implementation\n noSourceMap\n : nativeFindSourceMap\n\nexport function filterStackFrameDEV(\n sourceURL: string,\n functionName: string,\n line1: number,\n column1: number\n): boolean {\n if (sourceURL === '') {\n // The default implementation filters out stack frames\n // but we want to retain them because current Server Components and\n // built-in Components in parent stacks don't have source location.\n // Filter out frames that show up in Promises to get good names in React's\n // Server Request track until we come up with a better heuristic.\n return functionName !== 'new Promise'\n }\n if (sourceURL.startsWith('node:') || sourceURL.includes('node_modules')) {\n return false\n }\n try {\n // Node.js loads source maps eagerly so this call is cheap.\n // TODO: ESM sourcemaps are O(1) but CommonJS sourcemaps are O(Number of CJS modules).\n // Make sure this doesn't adversely affect performance when CJS is used by Next.js.\n const sourceMap = findSourceMap(sourceURL)\n if (sourceMap === undefined) {\n // No source map assoicated.\n // TODO: Node.js types should reflect that `findSourceMap` can return `undefined`.\n return true\n }\n const sourceMapPayload = findApplicableSourceMapPayload(\n line1 - 1,\n column1 - 1,\n sourceMap.payload\n )\n if (sourceMapPayload === undefined) {\n // No source map section applicable to the frame.\n return true\n }\n return !sourceMapIgnoreListsEverything(sourceMapPayload)\n } catch (cause) {\n if (process.env.NODE_ENV !== 'production') {\n // TODO: Share cache with patch-error-inspect\n if (!didWarnAboutInvalidSourceMapDEV.has(sourceURL)) {\n didWarnAboutInvalidSourceMapDEV.add(sourceURL)\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to filter stack frames. Cause: ${cause}`\n )\n }\n }\n\n return true\n }\n}\n\nconst invalidSourceMap = Symbol('invalid-source-map')\nconst sourceMapURLs = new LRUCache(\n 512 * 1024 * 1024,\n (url) =>\n url === invalidSourceMap\n ? // Ideally we'd account for key length. So we just guestimate a small source map\n // so that we don't create a huge cache with empty source maps.\n 8 * 1024\n : // these URLs contain only ASCII characters so .length is equal to Buffer.byteLength\n url.length\n)\nexport function findSourceMapURLDEV(\n scriptNameOrSourceURL: string\n): string | null {\n let sourceMapURL = sourceMapURLs.get(scriptNameOrSourceURL)\n if (sourceMapURL === undefined) {\n let sourceMapPayload: ModernSourceMapPayload | undefined\n try {\n sourceMapPayload = findSourceMap(scriptNameOrSourceURL)?.payload\n } catch (cause) {\n console.error(\n `${scriptNameOrSourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n }\n\n if (sourceMapPayload === undefined) {\n sourceMapURL = invalidSourceMap\n } else {\n // TODO: Might be more efficient to extract the relevant section from Index Maps.\n // Unclear if that search is worth the smaller payload we have to stringify.\n const sourceMapJSON = JSON.stringify(sourceMapPayload)\n const sourceMapURLData = Buffer.from(sourceMapJSON, 'utf8').toString(\n 'base64'\n )\n sourceMapURL = `data:application/json;base64,${sourceMapURLData}`\n }\n\n sourceMapURLs.set(scriptNameOrSourceURL, sourceMapURL)\n }\n\n return sourceMapURL === invalidSourceMap ? null : sourceMapURL\n}\n\nexport function devirtualizeReactServerURL(sourceURL: string): string {\n if (sourceURL.startsWith('about://React/')) {\n // about://React/Server/file://?42 => file://\n const envIdx = sourceURL.indexOf('/', 'about://React/'.length)\n const suffixIdx = sourceURL.lastIndexOf('?')\n if (envIdx > -1 && suffixIdx > -1) {\n return decodeURI(sourceURL.slice(envIdx + 1, suffixIdx))\n }\n }\n return sourceURL\n}\n\nfunction isAnonymousFrameLikelyJSNative(methodName: string): boolean {\n // Anonymous frames can also be produced in React parent stacks either from\n // host components or Server Components. We don't want to ignore those.\n // This could hide user-space methods that are named like native JS methods but\n // should you really do that?\n return (\n // e.g. JSON.parse\n methodName.startsWith('JSON.') ||\n // E.g. Promise.withResolves\n methodName.startsWith('Function.') ||\n // various JS built-ins\n methodName.startsWith('Promise.') ||\n methodName.startsWith('Array.') ||\n methodName.startsWith('Set.') ||\n methodName.startsWith('Map.')\n )\n}\n\nexport function ignoreListAnonymousStackFramesIfSandwiched(\n frames: Frame[],\n isAnonymousFrame: (frame: Frame) => boolean,\n isIgnoredFrame: (frame: Frame) => boolean,\n getMethodName: (frame: Frame) => string,\n /** only passes frames for which `isAnonymousFrame` and their method is a native JS method or `isIgnoredFrame` return true */\n ignoreFrame: (frame: Frame) => void\n): void {\n for (let i = 1; i < frames.length; i++) {\n const currentFrame = frames[i]\n if (\n !(\n isAnonymousFrame(currentFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(currentFrame))\n )\n ) {\n continue\n }\n\n const previousFrameIsIgnored = isIgnoredFrame(frames[i - 1])\n if (previousFrameIsIgnored && i < frames.length - 1) {\n let ignoreSandwich = false\n let j = i + 1\n for (j; j < frames.length; j++) {\n const nextFrame = frames[j]\n const nextFrameIsAnonymous =\n isAnonymousFrame(nextFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(nextFrame))\n if (nextFrameIsAnonymous) {\n continue\n }\n\n const nextFrameIsIgnored = isIgnoredFrame(nextFrame)\n if (nextFrameIsIgnored) {\n ignoreSandwich = true\n break\n }\n }\n\n if (ignoreSandwich) {\n for (i; i < j; i++) {\n ignoreFrame(frames[i])\n }\n }\n }\n }\n}\n","// ISC License\n\n// Copyright (c) 2021 Alexey Raspopov, Kostiantyn Denysov, Anton Verinov\n\n// Permission to use, copy, modify, and/or distribute this software for any\n// purpose with or without fee is hereby granted, provided that the above\n// copyright notice and this permission notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n//\n// https://github.com/alexeyraspopov/picocolors/blob/b6261487e7b81aaab2440e397a356732cad9e342/picocolors.js#L1\n\nconst { env, stdout } = globalThis?.process ?? {}\n\nconst enabled =\n env &&\n !env.NO_COLOR &&\n (env.FORCE_COLOR || (stdout?.isTTY && !env.CI && env.TERM !== 'dumb'))\n\nconst replaceClose = (\n str: string,\n close: string,\n replace: string,\n index: number\n): string => {\n const start = str.substring(0, index) + replace\n const end = str.substring(index + close.length)\n const nextIndex = end.indexOf(close)\n return ~nextIndex\n ? start + replaceClose(end, close, replace, nextIndex)\n : start + end\n}\n\nconst formatter = (open: string, close: string, replace = open) => {\n if (!enabled) return String\n return (input: string) => {\n const string = '' + input\n const index = string.indexOf(close, open.length)\n return ~index\n ? open + replaceClose(string, close, replace, index) + close\n : open + string + close\n }\n}\n\nexport const reset = enabled ? (s: string) => `\\x1b[0m${s}\\x1b[0m` : String\nexport const bold = formatter('\\x1b[1m', '\\x1b[22m', '\\x1b[22m\\x1b[1m')\nexport const dim = formatter('\\x1b[2m', '\\x1b[22m', '\\x1b[22m\\x1b[2m')\nexport const italic = formatter('\\x1b[3m', '\\x1b[23m')\nexport const underline = formatter('\\x1b[4m', '\\x1b[24m')\nexport const inverse = formatter('\\x1b[7m', '\\x1b[27m')\nexport const hidden = formatter('\\x1b[8m', '\\x1b[28m')\nexport const strikethrough = formatter('\\x1b[9m', '\\x1b[29m')\nexport const black = formatter('\\x1b[30m', '\\x1b[39m')\nexport const red = formatter('\\x1b[31m', '\\x1b[39m')\nexport const green = formatter('\\x1b[32m', '\\x1b[39m')\nexport const yellow = formatter('\\x1b[33m', '\\x1b[39m')\nexport const blue = formatter('\\x1b[34m', '\\x1b[39m')\nexport const magenta = formatter('\\x1b[35m', '\\x1b[39m')\nexport const purple = formatter('\\x1b[38;2;173;127;168m', '\\x1b[39m')\nexport const cyan = formatter('\\x1b[36m', '\\x1b[39m')\nexport const white = formatter('\\x1b[37m', '\\x1b[39m')\nexport const gray = formatter('\\x1b[90m', '\\x1b[39m')\nexport const bgBlack = formatter('\\x1b[40m', '\\x1b[49m')\nexport const bgRed = formatter('\\x1b[41m', '\\x1b[49m')\nexport const bgGreen = formatter('\\x1b[42m', '\\x1b[49m')\nexport const bgYellow = formatter('\\x1b[43m', '\\x1b[49m')\nexport const bgBlue = formatter('\\x1b[44m', '\\x1b[49m')\nexport const bgMagenta = formatter('\\x1b[45m', '\\x1b[49m')\nexport const bgCyan = formatter('\\x1b[46m', '\\x1b[49m')\nexport const bgWhite = formatter('\\x1b[47m', '\\x1b[49m')\n","/**\n * Node in the doubly-linked list used for LRU tracking.\n * Each node represents a cache entry with bidirectional pointers.\n */\nclass LRUNode {\n public readonly key: string\n public data: T\n public size: number\n public prev: LRUNode | SentinelNode | null = null\n public next: LRUNode | SentinelNode | 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 {\n public prev: LRUNode | SentinelNode | null = null\n public next: LRUNode | SentinelNode | 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 {\n private readonly cache: Map> = new Map()\n private readonly head: SentinelNode\n private readonly tail: SentinelNode\n private totalSize: number = 0\n private readonly maxSize: number\n private readonly calculateSize: ((value: T) => number) | undefined\n private readonly onEvict: ((key: string, value: T) => void) | undefined\n\n constructor(\n maxSize: number,\n calculateSize?: (value: T) => number,\n onEvict?: (key: string, value: T) => void\n ) {\n this.maxSize = maxSize\n this.calculateSize = calculateSize\n this.onEvict = onEvict\n\n // Create sentinel nodes to simplify doubly-linked list operations\n // HEAD <-> TAIL (empty list)\n this.head = new SentinelNode()\n this.tail = new SentinelNode()\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): 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): 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): 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 {\n const lastNode = this.tail.prev as LRUNode\n // tail.prev is always non-null and always LRUNode when cache is not empty\n this.removeNode(lastNode)\n return lastNode\n }\n\n /**\n * Sets a key-value pair in the cache.\n * If the key exists, updates the value and moves to head.\n * If new, adds at head and evicts from tail if necessary.\n *\n * Time Complexity:\n * - O(1) for uniform item sizes\n * - O(k) where k is the number of items evicted (can be O(N) for variable sizes)\n */\n public set(key: string, value: T): boolean {\n const size = this.calculateSize?.(value) ?? 1\n if (size <= 0) {\n throw new Error(\n `LRUCache: calculateSize returned ${size}, but size must be > 0. ` +\n `Items with size 0 would never be evicted, causing unbounded cache growth.`\n )\n }\n if (size > this.maxSize) {\n console.warn('Single item size exceeds maxSize')\n return false\n }\n\n const existing = this.cache.get(key)\n if (existing) {\n // Update existing node: adjust size and move to head (most recent)\n existing.data = value\n this.totalSize = this.totalSize - existing.size + size\n existing.size = size\n this.moveToHead(existing)\n } else {\n // Add new node at head (most recent position)\n const newNode = new LRUNode(key, value, size)\n this.cache.set(key, newNode)\n this.addToHead(newNode)\n this.totalSize += size\n }\n\n // Evict least recently used items until under capacity\n while (this.totalSize > this.maxSize && this.cache.size > 0) {\n const tail = this.removeTail()\n this.cache.delete(tail.key)\n this.totalSize -= tail.size\n this.onEvict?.(tail.key, tail.data)\n }\n\n return true\n }\n\n /**\n * Checks if a key exists in the cache.\n * This is a pure query operation - does NOT update LRU order.\n *\n * Time Complexity: O(1)\n */\n public has(key: string): boolean {\n return this.cache.has(key)\n }\n\n /**\n * Retrieves a value by key and marks it as most recently used.\n * Moving to head maintains the LRU property for future evictions.\n *\n * Time Complexity: O(1)\n */\n public get(key: string): T | undefined {\n const node = this.cache.get(key)\n if (!node) return undefined\n\n // Mark as most recently used by moving to head\n this.moveToHead(node)\n\n return node.data\n }\n\n /**\n * Returns an iterator over the cache entries. The order is outputted in the\n * order of most recently used to least recently used.\n */\n public *[Symbol.iterator](): IterableIterator<[string, T]> {\n let current = this.head.next\n while (current && current !== this.tail) {\n // Between head and tail, current is always LRUNode\n const node = current as LRUNode\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 { parse } from 'next/dist/compiled/stacktrace-parser'\n\nconst regexNextStatic = /\\/_next(\\/static\\/.+)/\n\nexport interface StackFrame {\n file: string | null\n methodName: string\n arguments: string[]\n /** 1-based */\n line1: number | null\n /** 1-based */\n column1: number | null\n}\n\nexport function parseStack(\n stack: string,\n distDir = process.env.__NEXT_DIST_DIR\n): StackFrame[] {\n if (!stack) return []\n\n // throw away eval information that stacktrace-parser doesn't support\n // adapted from https://github.com/stacktracejs/error-stack-parser/blob/9f33c224b5d7b607755eb277f9d51fcdb7287e24/error-stack-parser.js#L59C33-L59C62\n stack = stack\n .split('\\n')\n .map((line) => {\n if (line.includes('(eval ')) {\n line = line\n .replace(/eval code/g, 'eval')\n .replace(/\\(eval at [^()]* \\(/, '(file://')\n .replace(/\\),.*$/g, ')')\n }\n\n return line\n })\n .join('\\n')\n\n const frames = parse(stack)\n return frames.map((frame) => {\n try {\n const url = new URL(frame.file!)\n const res = regexNextStatic.exec(url.pathname)\n if (res) {\n const effectiveDistDir = distDir\n ?.replace(/\\\\/g, '/')\n ?.replace(/\\/$/, '')\n if (effectiveDistDir) {\n frame.file =\n 'file://' + effectiveDistDir.concat(res.pop()!) + url.search\n }\n }\n } catch {}\n return {\n file: frame.file,\n line1: frame.lineNumber,\n column1: frame.column,\n methodName: frame.methodName,\n arguments: frame.arguments,\n }\n })\n}\n","/** React that's compiled with `next`. Used by App Router. */\nexport const reactVendoredRe =\n /[\\\\/]next[\\\\/]dist[\\\\/]compiled[\\\\/](react|react-dom|react-server-dom-(webpack|turbopack)|scheduler)[\\\\/]/\n\n/** React the user installed. Used by Pages Router, or user imports in App Router. */\nexport const reactNodeModulesRe =\n /node_modules[\\\\/](react|react-dom|scheduler)[\\\\/]/\n\nexport const nextInternalsRe =\n /(node_modules[\\\\/]next[\\\\/]|[\\\\/].next[\\\\/]static[\\\\/]chunks[\\\\/]webpack\\.js$|(edge-runtime-webpack|webpack-runtime)\\.js$)/\n\nexport default function isInternal(file: string | null) {\n if (!file) return false\n\n return (\n nextInternalsRe.test(file) ||\n reactVendoredRe.test(file) ||\n reactNodeModulesRe.test(file)\n )\n}\n","import { findSourceMap as nativeFindSourceMap } from 'module'\nimport * as path from 'path'\nimport * as url from 'url'\nimport type * as util from 'util'\nimport { SourceMapConsumer as SyncSourceMapConsumer } from 'next/dist/compiled/source-map'\nimport {\n type ModernSourceMapPayload,\n findApplicableSourceMapPayload,\n ignoreListAnonymousStackFramesIfSandwiched as ignoreListAnonymousStackFramesIfSandwichedGeneric,\n sourceMapIgnoreListsEverything,\n} from './lib/source-maps'\nimport { parseStack, type StackFrame } from './lib/parse-stack'\nimport { getOriginalCodeFrame } from '../next-devtools/server/shared'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { dim } from '../lib/picocolors'\n\ntype FindSourceMapPayload = (\n sourceURL: string\n) => ModernSourceMapPayload | undefined\n// Find a source map using the bundler's API.\n// This is only a fallback for when Node.js fails to due to bugs e.g. https://github.com/nodejs/node/issues/52102\n// TODO: Remove once all supported Node.js versions are fixed.\n// TODO(veil): Set from Webpack as well\nlet bundlerFindSourceMapPayload: FindSourceMapPayload = () => undefined\n\nexport function setBundlerFindSourceMapImplementation(\n findSourceMapImplementation: FindSourceMapPayload\n): void {\n bundlerFindSourceMapPayload = findSourceMapImplementation\n}\n\ninterface IgnorableStackFrame extends StackFrame {\n ignored: boolean\n}\n\ntype SourceMapCache = Map<\n string,\n null | { map: SyncSourceMapConsumer; payload: ModernSourceMapPayload }\n>\n\nfunction frameToString(\n methodName: string | null,\n sourceURL: string | null,\n line1: number | null,\n column1: number | null\n): string {\n let sourceLocation = line1 !== null ? `:${line1}` : ''\n if (column1 !== null && sourceLocation !== '') {\n sourceLocation += `:${column1}`\n }\n\n let fileLocation: string | null\n if (\n sourceURL !== null &&\n sourceURL.startsWith('file://') &&\n URL.canParse(sourceURL)\n ) {\n // If not relative to CWD, the path is ambiguous to IDEs and clicking will prompt to select the file first.\n // In a multi-app repo, this leads to potentially larger file names but will make clicking snappy.\n // There's no tradeoff for the cases where `dir` in `next dev [dir]` is omitted\n // since relative to cwd is both the shortest and snappiest.\n fileLocation = path.relative(process.cwd(), url.fileURLToPath(sourceURL))\n } else if (sourceURL !== null && sourceURL.startsWith('/')) {\n fileLocation = path.relative(process.cwd(), sourceURL)\n } else {\n fileLocation = sourceURL\n }\n\n return methodName\n ? ` at ${methodName} (${fileLocation}${sourceLocation})`\n : ` at ${fileLocation}${sourceLocation}`\n}\n\nfunction computeErrorName(error: Error): string {\n // TODO: Node.js seems to use a different algorithm\n // class ReadonlyRequestCookiesError extends Error {}` would read `ReadonlyRequestCookiesError: [...]`\n // in the stack i.e. seems like under certain conditions it favors the constructor name.\n return error.name || 'Error'\n}\n\nfunction prepareUnsourcemappedStackTrace(\n error: Error,\n structuredStackTrace: any[]\n): string {\n const name = computeErrorName(error)\n const message = error.message || ''\n let stack = name + ': ' + message\n for (let i = 0; i < structuredStackTrace.length; i++) {\n stack += '\\n at ' + structuredStackTrace[i].toString()\n }\n return stack\n}\n\nfunction shouldIgnoreListGeneratedFrame(file: string): boolean {\n return file.startsWith('node:') || file.includes('node_modules')\n}\n\nfunction shouldIgnoreListOriginalFrame(file: string): boolean {\n return file.includes('node_modules')\n}\n\ninterface SourcemappableStackFrame extends StackFrame {\n file: NonNullable\n}\n\ninterface SourceMappedFrame {\n stack: IgnorableStackFrame\n // DEV only\n code: string | null\n}\n\nfunction createUnsourcemappedFrame(\n frame: SourcemappableStackFrame\n): SourceMappedFrame {\n return {\n stack: {\n file: frame.file,\n line1: frame.line1,\n column1: frame.column1,\n methodName: frame.methodName,\n arguments: frame.arguments,\n ignored: shouldIgnoreListGeneratedFrame(frame.file),\n },\n code: null,\n }\n}\n\nfunction ignoreListAnonymousStackFramesIfSandwiched(\n sourceMappedFrames: Array<{\n stack: IgnorableStackFrame\n code: string | null\n }>\n) {\n return ignoreListAnonymousStackFramesIfSandwichedGeneric(\n sourceMappedFrames,\n (frame) => frame.stack.file === '',\n (frame) => frame.stack.ignored,\n (frame) => frame.stack.methodName,\n (frame) => {\n frame.stack.ignored = true\n }\n )\n}\n\n/**\n * @param frame\n * @param sourceMapCache\n * @returns The original frame if not sourcemapped.\n */\nfunction getSourcemappedFrameIfPossible(\n frame: SourcemappableStackFrame,\n sourceMapCache: SourceMapCache,\n inspectOptions: util.InspectOptions\n): {\n stack: IgnorableStackFrame\n code: string | null\n} {\n const sourceMapCacheEntry = sourceMapCache.get(frame.file)\n let sourceMapConsumer: SyncSourceMapConsumer\n let sourceMapPayload: ModernSourceMapPayload\n if (sourceMapCacheEntry === undefined) {\n let sourceURL = frame.file\n // e.g. \"/APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js\"\n // will be keyed by Node.js as \"file:///APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js\".\n // This is likely caused by `callsite.toString()` in `Error.prepareStackTrace converting file URLs to paths.\n if (sourceURL.startsWith('/')) {\n sourceURL = url.pathToFileURL(frame.file).toString()\n }\n let maybeSourceMapPayload: ModernSourceMapPayload | undefined\n try {\n const sourceMap = nativeFindSourceMap(sourceURL)\n maybeSourceMapPayload = sourceMap?.payload\n } catch (cause) {\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n // If loading fails once, it'll fail every time.\n // So set the cache to avoid duplicate errors.\n sourceMapCache.set(frame.file, null)\n // Don't even fall back to the bundler because it might be not as strict\n // with regards to parsing and then we fail later once we consume the\n // source map payload.\n // This essentially avoids a redundant error where we fail here and then\n // later on consumption because the bundler just handed back an invalid\n // source map.\n return createUnsourcemappedFrame(frame)\n }\n if (maybeSourceMapPayload === undefined) {\n maybeSourceMapPayload = bundlerFindSourceMapPayload(sourceURL)\n }\n\n if (maybeSourceMapPayload === undefined) {\n return createUnsourcemappedFrame(frame)\n }\n sourceMapPayload = maybeSourceMapPayload\n try {\n sourceMapConsumer = new SyncSourceMapConsumer(\n // @ts-expect-error -- Module.SourceMap['version'] is number but SyncSourceMapConsumer wants a string\n sourceMapPayload\n )\n } catch (cause) {\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n // If creating the consumer fails once, it'll fail every time.\n // So set the cache to avoid duplicate errors.\n sourceMapCache.set(frame.file, null)\n return createUnsourcemappedFrame(frame)\n }\n sourceMapCache.set(frame.file, {\n map: sourceMapConsumer,\n payload: sourceMapPayload,\n })\n } else if (sourceMapCacheEntry === null) {\n // We failed earlier getting the payload or consumer.\n // Just return an unsourcemapped frame.\n // Errors will already be logged.\n return createUnsourcemappedFrame(frame)\n } else {\n sourceMapConsumer = sourceMapCacheEntry.map\n sourceMapPayload = sourceMapCacheEntry.payload\n }\n\n const sourcePosition = sourceMapConsumer.originalPositionFor({\n column: (frame.column1 ?? 1) - 1,\n line: frame.line1 ?? 1,\n })\n\n const applicableSourceMap = findApplicableSourceMapPayload(\n (frame.line1 ?? 1) - 1,\n (frame.column1 ?? 1) - 1,\n sourceMapPayload\n )\n let ignored =\n applicableSourceMap !== undefined &&\n sourceMapIgnoreListsEverything(applicableSourceMap)\n if (sourcePosition.source === null) {\n return {\n stack: {\n arguments: frame.arguments,\n file: frame.file,\n line1: frame.line1,\n column1: frame.column1,\n methodName: frame.methodName,\n ignored: ignored || shouldIgnoreListGeneratedFrame(frame.file),\n },\n code: null,\n }\n }\n\n // TODO(veil): Upstream a method to sourcemap consumer that immediately says if a frame is ignored or not.\n if (applicableSourceMap === undefined) {\n console.error('No applicable source map found in sections for frame', frame)\n } else if (!ignored && shouldIgnoreListOriginalFrame(sourcePosition.source)) {\n // Externals may be libraries that don't ship ignoreLists.\n // This is really taking control away from libraries.\n // They should still ship `ignoreList` so that attached debuggers ignore-list their frames.\n // TODO: Maybe only ignore library sourcemaps if `ignoreList` is absent?\n // Though keep in mind that Turbopack omits empty `ignoreList`.\n // So if we establish this convention, we should communicate it to the ecosystem.\n ignored = true\n } else if (!ignored) {\n // TODO: O(n^2). Consider moving `ignoreList` into a Set\n const sourceIndex = applicableSourceMap.sources.indexOf(\n sourcePosition.source\n )\n ignored = applicableSourceMap.ignoreList?.includes(sourceIndex) ?? false\n }\n\n const originalFrame: IgnorableStackFrame = {\n // We ignore the sourcemapped name since it won't be the correct name.\n // The callsite will point to the column of the variable name instead of the\n // name of the enclosing function.\n // TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.\n methodName: frame.methodName\n ?.replace('__WEBPACK_DEFAULT_EXPORT__', 'default')\n ?.replace('__webpack_exports__.', ''),\n file: sourcePosition.source,\n line1: sourcePosition.line,\n column1: sourcePosition.column + 1,\n // TODO: c&p from async createOriginalStackFrame but why not frame.arguments?\n arguments: [],\n ignored,\n }\n\n /** undefined = not yet computed*/\n let codeFrame: string | null | undefined\n\n return Object.defineProperty(\n {\n stack: originalFrame,\n code: null,\n },\n 'code',\n {\n get: () => {\n if (codeFrame === undefined) {\n const sourceContent: string | null =\n sourceMapConsumer.sourceContentFor(\n sourcePosition.source,\n /* returnNullOnMissing */ true\n ) ?? null\n codeFrame = getOriginalCodeFrame(\n originalFrame,\n sourceContent,\n inspectOptions.colors\n )\n }\n return codeFrame\n },\n }\n )\n}\n\nfunction parseAndSourceMap(\n error: Error,\n inspectOptions: util.InspectOptions\n): string {\n // TODO(veil): Expose as CLI arg or config option. Useful for local debugging.\n const showIgnoreListed = false\n // We overwrote Error.prepareStackTrace earlier so error.stack is not sourcemapped.\n let unparsedStack = String(error.stack)\n // We could just read it from `error.stack`.\n // This works around cases where a 3rd party `Error.prepareStackTrace` implementation\n // doesn't implement the name computation correctly.\n const errorName = computeErrorName(error)\n\n let idx = unparsedStack.indexOf('react_stack_bottom_frame')\n if (idx !== -1) {\n idx = unparsedStack.lastIndexOf('\\n', idx)\n } else {\n idx = unparsedStack.indexOf('react-stack-bottom-frame')\n if (idx !== -1) {\n idx = unparsedStack.lastIndexOf('\\n', idx)\n }\n }\n if (idx !== -1 && !showIgnoreListed) {\n // Cut off everything after the bottom frame since it'll be React internals.\n unparsedStack = unparsedStack.slice(0, idx)\n }\n\n const unsourcemappedStack = parseStack(unparsedStack)\n const sourceMapCache: SourceMapCache = new Map()\n\n const sourceMappedFrames: Array<{\n stack: IgnorableStackFrame\n code: string | null\n }> = []\n let sourceFrame: null | string = null\n for (const frame of unsourcemappedStack) {\n if (frame.file === null) {\n sourceMappedFrames.push({\n code: null,\n stack: {\n file: frame.file,\n line1: frame.line1,\n column1: frame.column1,\n methodName: frame.methodName,\n arguments: frame.arguments,\n ignored: false,\n },\n })\n } else {\n const sourcemappedFrame = getSourcemappedFrameIfPossible(\n // We narrowed this earlier by bailing if `frame.file` is null.\n frame as SourcemappableStackFrame,\n sourceMapCache,\n inspectOptions\n )\n sourceMappedFrames.push(sourcemappedFrame)\n\n // We can determine the sourceframe here.\n // anonymous frames won't have a sourceframe so we don't need to scan\n // all stacks again to check if they are sandwiched between ignored frames.\n if (\n sourceFrame === null &&\n // TODO: Is this the right choice?\n !sourcemappedFrame.stack.ignored &&\n sourcemappedFrame.code !== null\n ) {\n sourceFrame = sourcemappedFrame.code\n }\n }\n }\n\n ignoreListAnonymousStackFramesIfSandwiched(sourceMappedFrames)\n\n let sourceMappedStack = ''\n for (let i = 0; i < sourceMappedFrames.length; i++) {\n const frame = sourceMappedFrames[i]\n\n if (!frame.stack.ignored) {\n sourceMappedStack +=\n '\\n' +\n frameToString(\n frame.stack.methodName,\n frame.stack.file,\n frame.stack.line1,\n frame.stack.column1\n )\n } else if (showIgnoreListed) {\n sourceMappedStack +=\n '\\n' +\n dim(\n frameToString(\n frame.stack.methodName,\n frame.stack.file,\n frame.stack.line1,\n frame.stack.column1\n )\n )\n }\n }\n\n return (\n errorName +\n ': ' +\n error.message +\n sourceMappedStack +\n (sourceFrame !== null ? '\\n' + sourceFrame : '')\n )\n}\n\nfunction sourceMapError(\n this: void,\n error: Error,\n inspectOptions: util.InspectOptions\n): Error {\n // Create a new Error object with the source mapping applied and then use native\n // Node.js formatting on the result.\n const newError =\n error.cause !== undefined\n ? // Setting an undefined `cause` would print `[cause]: undefined`\n new Error(error.message, { cause: error.cause })\n : new Error(error.message)\n\n // TODO: Ensure `class MyError extends Error {}` prints `MyError` as the name\n newError.stack = parseAndSourceMap(error, inspectOptions)\n\n for (const key in error) {\n if (!Object.prototype.hasOwnProperty.call(newError, key)) {\n // @ts-expect-error -- We're copying all enumerable properties.\n // So they definitely exist on `this` and obviously have no type on `newError` (yet)\n newError[key] = error[key]\n }\n }\n\n return newError\n}\n\nexport function patchErrorInspectNodeJS(\n errorConstructor: ErrorConstructor\n): void {\n const inspectSymbol = Symbol.for('nodejs.util.inspect.custom')\n\n errorConstructor.prepareStackTrace = prepareUnsourcemappedStackTrace\n\n // @ts-expect-error -- TODO upstream types\n // eslint-disable-next-line no-extend-native -- We're not extending but overriding.\n errorConstructor.prototype[inspectSymbol] = function (\n depth: number,\n inspectOptions: util.InspectOptions,\n inspect: typeof util.inspect\n ): string {\n // avoid false-positive dynamic i/o warnings e.g. due to usage of `Math.random` in `source-map`.\n return workUnitAsyncStorage.exit(() => {\n const newError = sourceMapError(this, inspectOptions)\n\n const originalCustomInspect = (newError as any)[inspectSymbol]\n // Prevent infinite recursion.\n // { customInspect: false } would result in `error.cause` not using our inspect.\n Object.defineProperty(newError, inspectSymbol, {\n value: undefined,\n enumerable: false,\n writable: true,\n })\n try {\n return inspect(newError, {\n ...inspectOptions,\n depth:\n (inspectOptions.depth ??\n // Default in Node.js\n 2) - depth,\n })\n } finally {\n ;(newError as any)[inspectSymbol] = originalCustomInspect\n }\n })\n }\n}\n\nexport function patchErrorInspectEdgeLite(\n errorConstructor: ErrorConstructor\n): void {\n const inspectSymbol = Symbol.for('edge-runtime.inspect.custom')\n\n errorConstructor.prepareStackTrace = prepareUnsourcemappedStackTrace\n\n // @ts-expect-error -- TODO upstream types\n // eslint-disable-next-line no-extend-native -- We're not extending but overriding.\n errorConstructor.prototype[inspectSymbol] = function ({\n format,\n }: {\n format: (...args: unknown[]) => string\n }): string {\n // avoid false-positive dynamic i/o warnings e.g. due to usage of `Math.random` in `source-map`.\n return workUnitAsyncStorage.exit(() => {\n const newError = sourceMapError(this, {})\n\n const originalCustomInspect = (newError as any)[inspectSymbol]\n // Prevent infinite recursion.\n Object.defineProperty(newError, inspectSymbol, {\n value: undefined,\n enumerable: false,\n writable: true,\n })\n try {\n return format(newError)\n } finally {\n ;(newError as any)[inspectSymbol] = originalCustomInspect\n }\n })\n }\n}\n","import { patchErrorInspectNodeJS } from '../patch-error-inspect'\n\npatchErrorInspectNodeJS(globalThis.Error)\n","import { codeFrameColumns } from 'next/dist/compiled/babel/code-frame'\nimport isInternal from '../../shared/lib/is-internal'\nimport type { StackFrame } from '../../server/lib/parse-stack'\nimport { ignoreListAnonymousStackFramesIfSandwiched as ignoreListAnonymousStackFramesIfSandwichedGeneric } from '../../server/lib/source-maps'\n\nexport type { StackFrame }\n\nexport interface IgnorableStackFrame extends StackFrame {\n ignored: boolean\n}\n\nexport interface OriginalStackFramesRequest {\n frames: readonly StackFrame[]\n isServer: boolean\n isEdgeServer: boolean\n isAppDirectory: boolean\n}\n\nexport type OriginalStackFramesResponse = OriginalStackFrameResponseResult[]\n\nexport type OriginalStackFrameResponseResult =\n PromiseSettledResult\n\nexport interface OriginalStackFrameResponse {\n originalStackFrame: (StackFrame & { ignored: boolean }) | null\n originalCodeFrame: string | null\n}\n\nexport function ignoreListAnonymousStackFramesIfSandwiched(\n responses: OriginalStackFramesResponse\n): void {\n ignoreListAnonymousStackFramesIfSandwichedGeneric(\n responses,\n (response) => {\n return (\n response.status === 'fulfilled' &&\n response.value.originalStackFrame !== null &&\n response.value.originalStackFrame.file === ''\n )\n },\n (response) => {\n return (\n response.status === 'fulfilled' &&\n response.value.originalStackFrame !== null &&\n response.value.originalStackFrame.ignored === true\n )\n },\n (response) => {\n return response.status === 'fulfilled' &&\n response.value.originalStackFrame !== null\n ? response.value.originalStackFrame.methodName\n : ''\n },\n (response) => {\n ;(\n response as PromiseFulfilledResult\n ).value.originalStackFrame!.ignored = true\n }\n )\n}\n\n/**\n * It looks up the code frame of the traced source.\n * @note It ignores Next.js/React internals, as these can often be huge bundled files.\n */\nexport function getOriginalCodeFrame(\n frame: IgnorableStackFrame,\n source: string | null,\n colors: boolean = process.stdout.isTTY\n): string | null {\n if (!source || isInternal(frame.file)) {\n return null\n }\n\n return codeFrameColumns(\n source,\n {\n start: {\n // 1-based, but -1 means start line without highlighting\n line: frame.line1 ?? -1,\n // 1-based, but 0 means whole line without column highlighting\n column: frame.column1 ?? 0,\n },\n },\n { forceColor: colors }\n )\n}\n","export function isHangingPromiseRejectionError(\n err: unknown\n): err is HangingPromiseRejectionError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === HANGING_PROMISE_REJECTION\n}\n\nconst HANGING_PROMISE_REJECTION = 'HANGING_PROMISE_REJECTION'\n\nclass HangingPromiseRejectionError extends Error {\n public readonly digest = HANGING_PROMISE_REJECTION\n\n constructor(\n public readonly route: string,\n public readonly expression: string\n ) {\n super(\n `During prerendering, ${expression} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${expression} to a different context by using \\`setTimeout\\`, \\`after\\`, or similar functions you may observe this error and you should handle it in that context. This occurred at route \"${route}\".`\n )\n }\n}\n\ntype AbortListeners = Array<(err: unknown) => void>\nconst abortListenersBySignal = new WeakMap()\n\n/**\n * This function constructs a promise that will never resolve. This is primarily\n * useful for cacheComponents where we use promise resolution timing to determine which\n * parts of a render can be included in a prerender.\n *\n * @internal\n */\nexport function makeHangingPromise(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise {\n if (signal.aborted) {\n return Promise.reject(new HangingPromiseRejectionError(route, expression))\n } else {\n const hangingPromise = new Promise((_, reject) => {\n const boundRejection = reject.bind(\n null,\n new HangingPromiseRejectionError(route, expression)\n )\n let currentListeners = abortListenersBySignal.get(signal)\n if (currentListeners) {\n currentListeners.push(boundRejection)\n } else {\n const listeners = [boundRejection]\n abortListenersBySignal.set(signal, listeners)\n signal.addEventListener(\n 'abort',\n () => {\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n },\n { once: true }\n )\n }\n })\n // We are fine if no one actually awaits this promise. We shouldn't consider this an unhandled rejection so\n // we attach a noop catch handler here to suppress this warning. If you actually await somewhere or construct\n // your own promise out of it you'll need to ensure you handle the error when it rejects.\n hangingPromise.catch(ignoreReject)\n return hangingPromise\n }\n}\n\nfunction ignoreReject() {}\n\nexport function makeDevtoolsIOAwarePromise(underlying: T): Promise {\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((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","export class InvariantError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(\n `Invariant: ${message.endsWith('.') ? message : message + '.'} This is a bug in Next.js.`,\n options\n )\n this.name = 'InvariantError'\n }\n}\n","/**\n * The functions provided by this module are used to communicate certain properties\n * about the currently running code so that Next.js can make decisions on how to handle\n * the current execution in different rendering modes such as pre-rendering, resuming, and SSR.\n *\n * Today Next.js treats all code as potentially static. Certain APIs may only make sense when dynamically rendering.\n * Traditionally this meant deopting the entire render to dynamic however with PPR we can now deopt parts\n * of a React tree as dynamic while still keeping other parts static. There are really two different kinds of\n * Dynamic indications.\n *\n * The first is simply an intention to be dynamic. unstable_noStore is an example of this where\n * the currently executing code simply declares that the current scope is dynamic but if you use it\n * inside unstable_cache it can still be cached. This type of indication can be removed if we ever\n * make the default dynamic to begin with because the only way you would ever be static is inside\n * a cache scope which this indication does not affect.\n *\n * The second is an indication that a dynamic data source was read. This is a stronger form of dynamic\n * because it means that it is inappropriate to cache this at all. using a dynamic data source inside\n * unstable_cache should error. If you want to use some dynamic data inside unstable_cache you should\n * read that data outside the cache and pass it in as an argument to the cached function.\n */\n\nimport type { WorkStore } from '../app-render/work-async-storage.external'\nimport type {\n WorkUnitStore,\n RequestStore,\n PrerenderStoreLegacy,\n PrerenderStoreModern,\n PrerenderStoreModernRuntime,\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 getRuntimeStagePromise,\n workUnitAsyncStorage,\n} from './work-unit-async-storage.external'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { makeHangingPromise } from '../dynamic-rendering-utils'\nimport {\n METADATA_BOUNDARY_NAME,\n VIEWPORT_BOUNDARY_NAME,\n OUTLET_BOUNDARY_NAME,\n ROOT_LAYOUT_BOUNDARY_NAME,\n} from '../../lib/framework/boundary-constants'\nimport { scheduleOnNextTick } from '../../lib/scheduler'\nimport { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { InvariantError } from '../../shared/lib/invariant-error'\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\n\n syncDynamicErrorWithStack: null | Error\n}\n\n// Stores dynamic reasons used during an SSR render.\nexport type DynamicValidationState = {\n hasSuspenseAboveBody: boolean\n hasDynamicMetadata: boolean\n hasDynamicViewport: boolean\n hasAllowedDynamic: boolean\n dynamicErrors: Array\n}\n\nexport function createDynamicTrackingState(\n isDebugDynamicAccesses: boolean | undefined\n): DynamicTrackingState {\n return {\n isDebugDynamicAccesses,\n dynamicAccesses: [],\n syncDynamicErrorWithStack: null,\n }\n}\n\nexport function createDynamicValidationState(): DynamicValidationState {\n return {\n hasSuspenseAboveBody: false,\n hasDynamicMetadata: false,\n hasDynamicViewport: false,\n hasAllowedDynamic: false,\n dynamicErrors: [],\n }\n}\n\nexport function getFirstDynamicReason(\n trackingState: DynamicTrackingState\n): undefined | string {\n return trackingState.dynamicAccesses[0]?.expression\n}\n\n/**\n * This function communicates that the current scope should be treated as dynamic.\n *\n * In most cases this function is a no-op but if called during\n * a PPR prerender it will postpone the current sub-tree and calling\n * it during a normal prerender will cause the entire prerender to abort\n */\nexport function markCurrentScopeAsDynamic(\n store: WorkStore,\n workUnitStore: undefined | Exclude,\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 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 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 break\n case 'request':\n if (process.env.NODE_ENV !== 'production') {\n workUnitStore.usedDynamic = true\n }\n break\n default:\n workUnitStore satisfies never\n }\n}\n\nfunction abortOnSynchronousDynamicDataAccess(\n route: string,\n expression: string,\n prerenderStore: PrerenderStoreModern\n): void {\n const reason = `Route ${route} needs to bail out of prerendering at this point because it used ${expression}.`\n\n const error = createPrerenderInterruptedError(reason)\n\n prerenderStore.controller.abort(error)\n\n const dynamicTracking = prerenderStore.dynamicTracking\n if (dynamicTracking) {\n dynamicTracking.dynamicAccesses.push({\n // When we aren't debugging, we don't need to create another error for the\n // stack trace.\n stack: dynamicTracking.isDebugDynamicAccesses\n ? new Error().stack\n : undefined,\n expression,\n })\n }\n}\n\nexport function abortOnSynchronousPlatformIOAccess(\n route: string,\n expression: string,\n errorWithStack: Error,\n prerenderStore: PrerenderStoreModern\n): void {\n const dynamicTracking = prerenderStore.dynamicTracking\n abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore)\n // It is important that we set this tracking value after aborting. Aborts are executed\n // synchronously except for the case where you abort during render itself. By setting this\n // value late we can use it to determine if any of the aborted tasks are the task that\n // called the sync IO expression in the first place.\n if (dynamicTracking) {\n if (dynamicTracking.syncDynamicErrorWithStack === null) {\n dynamicTracking.syncDynamicErrorWithStack = errorWithStack\n }\n }\n}\n\nexport function trackSynchronousPlatformIOAccessInDev(\n requestStore: RequestStore\n): void {\n // We don't actually have a controller to abort but we do the semantic equivalent by\n // advancing the request store out of prerender mode\n requestStore.prerenderPhase = false\n}\n\n/**\n * use this function when prerendering with cacheComponents. If we are doing a\n * prospective prerender we don't actually abort because we want to discover\n * all caches for the shell. If this is the actual prerender we do abort.\n *\n * This function accepts a prerenderStore but the caller should ensure we're\n * actually running in cacheComponents mode.\n *\n * @internal\n */\nexport function abortAndThrowOnSynchronousRequestDataAccess(\n route: string,\n expression: string,\n errorWithStack: Error,\n prerenderStore: PrerenderStoreModern\n): never {\n const prerenderSignal = prerenderStore.controller.signal\n if (prerenderSignal.aborted === false) {\n // TODO it would be better to move this aborted check into the callsite so we can avoid making\n // the error object when it isn't relevant to the aborting of the prerender however\n // since we need the throw semantics regardless of whether we abort it is easier to land\n // this way. See how this was handled with `abortOnSynchronousPlatformIOAccess` for a closer\n // to ideal implementation\n abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore)\n // It is important that we set this tracking value after aborting. Aborts are executed\n // synchronously except for the case where you abort during render itself. By setting this\n // value late we can use it to determine if any of the aborted tasks are the task that\n // called the sync IO expression in the first place.\n const dynamicTracking = prerenderStore.dynamicTracking\n if (dynamicTracking) {\n if (dynamicTracking.syncDynamicErrorWithStack === null) {\n dynamicTracking.syncDynamicErrorWithStack = errorWithStack\n }\n }\n }\n throw createPrerenderInterruptedError(\n `Route ${route} needs to bail out of prerendering at this point because it used ${expression}.`\n )\n}\n\n/**\n * Use this function when dynamically prerendering with dynamicIO.\n * We don't want to error, because it's better to return something\n * (and we've already aborted the render at the point where the sync dynamic error occured),\n * but we should log an error server-side.\n * @internal\n */\nexport function warnOnSyncDynamicError(dynamicTracking: DynamicTrackingState) {\n if (dynamicTracking.syncDynamicErrorWithStack) {\n // the server did something sync dynamic, likely\n // leading to an early termination of the prerender.\n console.error(dynamicTracking.syncDynamicErrorWithStack)\n }\n}\n\n// For now these implementations are the same so we just reexport\nexport const trackSynchronousRequestDataAccessInDev =\n trackSynchronousPlatformIOAccessInDev\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\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\n): string[] {\n return dynamicAccesses\n .filter(\n (access): access is Required =>\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(' ()')) {\n return false\n }\n\n // Exclude Node.js internals from the stack trace.\n if (line.includes(' (node:')) {\n return false\n }\n\n return true\n })\n .join('\\n')\n return `Dynamic API Usage Debug - ${expression}:\\n${stack}`\n })\n}\n\nfunction assertPostpone() {\n if (!hasPostpone) {\n throw new Error(\n `Invariant: React.unstable_postpone is not defined. This suggests the wrong version of React was loaded. This is a bug in Next.js`\n )\n }\n}\n\n/**\n * This is a bit of a hack to allow us to abort a render using a Postpone instance instead of an Error which changes React's\n * abort semantics slightly.\n */\nexport function createRenderInBrowserAbortSignal(): AbortSignal {\n const controller = new AbortController()\n controller.abort(new BailoutToCSRError('Render in Browser'))\n return controller.signal\n}\n\n/**\n * In a prerender, we may end up with hanging Promises as inputs due them\n * stalling on connection() or because they're loading dynamic data. In that\n * case we need to abort the encoding of arguments since they'll never complete.\n */\nexport function createHangingInputAbortSignal(\n workUnitStore: WorkUnitStore\n): AbortSignal | undefined {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime':\n const controller = new AbortController()\n\n if (workUnitStore.cacheSignal) {\n // If we have a cacheSignal it means we're in a prospective render. If\n // the input we're waiting on is coming from another cache, we do want\n // to wait for it so that we can resolve this cache entry too.\n workUnitStore.cacheSignal.inputReady().then(() => {\n controller.abort()\n })\n } else {\n // Otherwise we're in the final render and we should already have all\n // our caches filled.\n // If the prerender uses stages, we have wait until the runtime stage,\n // at which point all runtime inputs will be resolved.\n // (otherwise, a runtime prerender might consider `cookies()` hanging\n // even though they'd resolve in the next task.)\n //\n // We might still be waiting on some microtasks so we\n // wait one tick before giving up. When we give up, we still want to\n // render the content of this cache as deeply as we can so that we can\n // suspend as deeply as possible in the tree or not at all if we don't\n // end up waiting for the input.\n const runtimeStagePromise = getRuntimeStagePromise(workUnitStore)\n if (runtimeStagePromise) {\n runtimeStagePromise.then(() =>\n scheduleOnNextTick(() => controller.abort())\n )\n } else {\n scheduleOnNextTick(() => controller.abort())\n }\n }\n\n return controller.signal\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n return undefined\n default:\n workUnitStore satisfies never\n }\n}\n\nexport function annotateDynamicAccess(\n expression: string,\n prerenderStore: PrerenderStoreModern\n) {\n const dynamicTracking = prerenderStore.dynamicTracking\n if (dynamicTracking) {\n dynamicTracking.dynamicAccesses.push({\n stack: dynamicTracking.isDebugDynamicAccesses\n ? new Error().stack\n : undefined,\n expression,\n })\n }\n}\n\nexport function useDynamicRouteParams(expression: string) {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workStore && workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender-client':\n case 'prerender': {\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n // We are in a prerender with cacheComponents semantics. We are going to\n // hang here and never resolve. This will cause the currently\n // rendering component to effectively be a dynamic hole.\n React.use(\n makeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n expression\n )\n )\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n return postponeWithTracking(\n workStore.route,\n expression,\n workUnitStore.dynamicTracking\n )\n }\n break\n }\n case '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 'prerender-legacy':\n case 'request':\n case 'unstable-cache':\n break\n default:\n workUnitStore satisfies never\n }\n }\n}\n\nconst hasSuspenseRegex = /\\n\\s+at Suspense \\(\\)/\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 ()\n// at __next_root_layout_boundary__ ()\n//\n// Or with other components in between (but not body/html/implicit-body):\n// at Suspense ()\n// at SomeComponent ()\n// at __next_root_layout_boundary__ ()\nconst hasSuspenseBeforeRootLayoutWithoutBodyOrImplicitBodyRegex = new RegExp(\n `\\\\n\\\\s+at Suspense \\\\(\\\\)(?:(?!\\\\n\\\\s+at (?:${bodyAndImplicitTags}) \\\\(\\\\))[\\\\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\nexport function trackAllowedDynamicAccess(\n workStore: WorkStore,\n componentStack: string,\n dynamicValidation: DynamicValidationState,\n clientDynamic: DynamicTrackingState\n) {\n if (hasOutletRegex.test(componentStack)) {\n // We don't need to track that this is dynamic. It is only so when something else is also dynamic.\n return\n } else if (hasMetadataRegex.test(componentStack)) {\n dynamicValidation.hasDynamicMetadata = true\n return\n } else if (hasViewportRegex.test(componentStack)) {\n dynamicValidation.hasDynamicViewport = true\n return\n } else if (\n hasSuspenseBeforeRootLayoutWithoutBodyOrImplicitBodyRegex.test(\n componentStack\n )\n ) {\n // For Suspense within body, the prelude wouldn't be empty so it wouldn't violate the empty static shells rule.\n // But if you have Suspense above body, the prelude is empty but we allow that because having Suspense\n // is an explicit signal from the user that they acknowledge the empty shell and want dynamic rendering.\n dynamicValidation.hasAllowedDynamic = true\n dynamicValidation.hasSuspenseAboveBody = true\n return\n } else if (hasSuspenseRegex.test(componentStack)) {\n // this error had a Suspense boundary above it so we don't need to report it as a source\n // of disallowed\n dynamicValidation.hasAllowedDynamic = true\n return\n } else if (clientDynamic.syncDynamicErrorWithStack) {\n // This task was the task that called the sync error.\n dynamicValidation.dynamicErrors.push(\n clientDynamic.syncDynamicErrorWithStack\n )\n return\n } else {\n const message = `Route \"${workStore.route}\": A component accessed data, headers, params, searchParams, or a short-lived cache without a Suspense boundary nor a \"use cache\" above it. See more info: https://nextjs.org/docs/messages/next-prerender-missing-suspense`\n const error = createErrorWithComponentOrOwnerStack(message, componentStack)\n dynamicValidation.dynamicErrors.push(error)\n return\n }\n}\n\n/**\n * In dev mode, we prefer using the owner stack, otherwise the provided\n * component stack is used.\n */\nfunction createErrorWithComponentOrOwnerStack(\n message: string,\n componentStack: string\n) {\n const ownerStack =\n process.env.NODE_ENV !== 'production' && React.captureOwnerStack\n ? React.captureOwnerStack()\n : null\n\n const error = new Error(message)\n error.stack = error.name + ': ' + message + (ownerStack ?? componentStack)\n return error\n}\n\nexport enum PreludeState {\n Full = 0,\n Empty = 1,\n Errored = 2,\n}\n\nexport function logDisallowedDynamicError(\n workStore: WorkStore,\n error: Error\n): void {\n console.error(error)\n\n if (!workStore.dev) {\n if (workStore.hasReadableErrorStacks) {\n console.error(\n `To get a more detailed stack trace and pinpoint the issue, start the app in development mode by running \\`next dev\\`, then open \"${workStore.route}\" in your browser to investigate the error.`\n )\n } else {\n console.error(`To get a more detailed stack trace and pinpoint the issue, try one of the following:\n - Start the app in development mode by running \\`next dev\\`, then open \"${workStore.route}\" in your browser to investigate the error.\n - Rerun the production build with \\`next build --debug-prerender\\` to generate better stack traces.`)\n }\n }\n}\n\nexport function throwIfDisallowedDynamic(\n workStore: WorkStore,\n prelude: PreludeState,\n dynamicValidation: DynamicValidationState,\n serverDynamic: DynamicTrackingState\n): void {\n if (prelude !== PreludeState.Full) {\n if (dynamicValidation.hasSuspenseAboveBody) {\n // This route has opted into allowing fully dynamic rendering\n // by including a Suspense boundary above the body. In this case\n // a lack of a shell is not considered disallowed so we simply return\n return\n }\n\n if (serverDynamic.syncDynamicErrorWithStack) {\n // There is no shell and the server did something sync dynamic likely\n // leading to an early termination of the prerender before the shell\n // could be completed. We terminate the build/validating render.\n logDisallowedDynamicError(\n workStore,\n serverDynamic.syncDynamicErrorWithStack\n )\n throw new StaticGenBailoutError()\n }\n\n // We didn't have any sync bailouts but there may be user code which\n // blocked the root. We would have captured these during the prerender\n // and can log them here and then terminate the build/validating render\n const dynamicErrors = dynamicValidation.dynamicErrors\n if (dynamicErrors.length > 0) {\n for (let i = 0; i < dynamicErrors.length; i++) {\n logDisallowedDynamicError(workStore, dynamicErrors[i])\n }\n\n throw new StaticGenBailoutError()\n }\n\n // If we got this far then the only other thing that could be blocking\n // the root is dynamic Viewport. If this is dynamic then\n // you need to opt into that by adding a Suspense boundary above the body\n // to indicate your are ok with fully dynamic rendering.\n if (dynamicValidation.hasDynamicViewport) {\n console.error(\n `Route \"${workStore.route}\" has a \\`generateViewport\\` that depends on Request data (\\`cookies()\\`, etc...) or uncached external data (\\`fetch(...)\\`, etc...) without explicitly allowing fully dynamic rendering. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`\n )\n throw new StaticGenBailoutError()\n }\n\n if (prelude === PreludeState.Empty) {\n // If we ever get this far then we messed up the tracking of invalid dynamic.\n // We still adhere to the constraint that you must produce a shell but invite the\n // user to report this as a bug in Next.js.\n console.error(\n `Route \"${workStore.route}\" did not produce a static shell and Next.js was unable to determine a reason. This is a bug in Next.js.`\n )\n throw new StaticGenBailoutError()\n }\n } else {\n if (\n dynamicValidation.hasAllowedDynamic === false &&\n dynamicValidation.hasDynamicMetadata\n ) {\n console.error(\n `Route \"${workStore.route}\" has a \\`generateMetadata\\` that depends on Request data (\\`cookies()\\`, etc...) or uncached external data (\\`fetch(...)\\`, etc...) when the rest of the route does not. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`\n )\n throw new StaticGenBailoutError()\n }\n }\n}\n\nexport function delayUntilRuntimeStage(\n prerenderStore: PrerenderStoreModernRuntime,\n result: Promise\n): Promise {\n if (prerenderStore.runtimeStagePromise) {\n return prerenderStore.runtimeStagePromise.then(() => result)\n }\n return result\n}\n","import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n abortOnSynchronousPlatformIOAccess,\n trackSynchronousPlatformIOAccessInDev,\n} from '../app-render/dynamic-rendering'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\ntype ApiType = 'time' | 'random' | 'crypto'\n\nexport function io(expression: string, type: ApiType) {\n const workUnitStore = workUnitAsyncStorage.getStore()\n const workStore = workAsyncStorage.getStore()\n\n if (!workUnitStore || !workStore) {\n return\n }\n\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime': {\n const prerenderSignal = workUnitStore.controller.signal\n\n if (prerenderSignal.aborted === false) {\n // If the prerender signal is already aborted we don't need to construct\n // any stacks because something else actually terminated the prerender.\n let message: string\n switch (type) {\n case 'time':\n message = `Route \"${workStore.route}\" used ${expression} instead of using \\`performance\\` or without explicitly calling \\`await connection()\\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time`\n break\n case 'random':\n message = `Route \"${workStore.route}\" used ${expression} outside of \\`\"use cache\"\\` and without explicitly calling \\`await connection()\\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random`\n break\n case 'crypto':\n message = `Route \"${workStore.route}\" used ${expression} outside of \\`\"use cache\"\\` and without explicitly calling \\`await connection()\\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto`\n break\n default:\n throw new InvariantError(\n 'Unknown expression type in abortOnSynchronousPlatformIOAccess.'\n )\n }\n\n abortOnSynchronousPlatformIOAccess(\n workStore.route,\n expression,\n applyOwnerStack(new Error(message), workUnitStore),\n workUnitStore\n )\n }\n break\n }\n case 'prerender-client': {\n const prerenderSignal = workUnitStore.controller.signal\n\n if (prerenderSignal.aborted === false) {\n // If the prerender signal is already aborted we don't need to construct\n // any stacks because something else actually terminated the prerender.\n let message: string\n switch (type) {\n case 'time':\n message = `Route \"${workStore.route}\" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time-client`\n break\n case 'random':\n message = `Route \"${workStore.route}\" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-random-client`\n break\n case 'crypto':\n message = `Route \"${workStore.route}\" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto-client`\n break\n default:\n throw new InvariantError(\n 'Unknown expression type in abortOnSynchronousPlatformIOAccess.'\n )\n }\n\n abortOnSynchronousPlatformIOAccess(\n workStore.route,\n expression,\n applyOwnerStack(new Error(message), workUnitStore),\n workUnitStore\n )\n }\n break\n }\n case 'request':\n if (workUnitStore.prerenderPhase === true) {\n trackSynchronousPlatformIOAccessInDev(workUnitStore)\n }\n break\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n break\n default:\n workUnitStore satisfies never\n }\n}\n\nfunction applyOwnerStack(error: Error, workUnitStore: PrerenderStoreModern) {\n // TODO: Instead of stitching the stacks here, we should log the original\n // error as-is when it occurs, and let `patchErrorInspect` handle adding the\n // owner stack, instead of logging it deferred in the `LogSafely` component\n // via `throwIfDisallowedDynamic`.\n if (\n process.env.NODE_ENV !== 'production' &&\n workUnitStore.captureOwnerStack\n ) {\n const ownerStack = workUnitStore.captureOwnerStack()\n\n if (ownerStack) {\n let stack = ownerStack\n\n if (error.stack) {\n const frames: string[] = []\n\n for (const frame of error.stack.split('\\n').slice(1)) {\n if (frame.includes('react_stack_bottom_frame')) {\n break\n }\n\n frames.push(frame)\n }\n\n stack = '\\n' + frames.join('\\n') + stack\n }\n\n error.stack = error.name + ': ' + error.message + stack\n }\n }\n\n return error\n}\n","/**\n * We extend Math.random() during builds and revalidates to ensure that prerenders don't observe randomness\n * When cacheComponents is enabled. randomness is a form of IO even though it resolves synchronously. When cacheComponents is\n * enabled we need to ensure that randomness is excluded from prerenders.\n *\n * The extensions here never error nor alter the random generation itself and thus should be transparent to callers.\n */\n\nimport { io } from './utils'\n\nconst expression = '`Math.random()`'\ntry {\n const _random = Math.random\n Math.random = function random() {\n io(expression, 'random')\n return _random.apply(null, arguments as any)\n\n // We bind here to alter the `toString` printing to match `Math.random`'s native `toString`.\n // eslint-disable-next-line no-extra-bind\n }.bind(null)\n Object.defineProperty(Math.random, 'name', { value: 'random' })\n} catch {\n console.error(\n `Failed to install ${expression} extension. When using \\`experimental.cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n )\n}\n","/**\n * We extend `Date` during builds and revalidates to ensure that prerenders don't observe the clock as a source of IO\n * When cacheComponents is enabled. The current time is a form of IO even though it resolves synchronously. When cacheComponents is\n * enabled we need to ensure that clock time is excluded from prerenders unless it is cached.\n *\n * There is tension here because time is used for both output and introspection. While arbitrary we intend to reserve\n * `Date` for output use cases and `performance` for introspection use cases. If you want to measure\n * how long something takes use `performance.timeOrigin` and `performance.now()` rather than `Date.now()` for instance.\n *\n * The extensions here never error nor alter the underlying Date objects, strings, and numbers created and thus should be transparent to callers.\n */\nimport { io } from './utils'\n\nfunction createNow(originalNow: typeof Date.now) {\n return {\n now: function now() {\n io('`Date.now()`', 'time')\n return originalNow()\n },\n }['now'.slice() as 'now'].bind(null)\n}\n\nfunction createDate(originalConstructor: typeof Date): typeof Date {\n const properties = Object.getOwnPropertyDescriptors(originalConstructor)\n properties.now.value = createNow(originalConstructor.now)\n\n const apply = Reflect.apply\n const construct = Reflect.construct\n\n const newConstructor = Object.defineProperties(\n // Ideally this should not minify the name.\n function Date() {\n if (new.target === undefined) {\n io('`Date()`', 'time')\n return apply(originalConstructor, undefined, arguments)\n }\n if (arguments.length === 0) {\n io('`new Date()`', 'time')\n }\n return construct(originalConstructor, arguments, new.target)\n },\n properties\n )\n Object.defineProperty(originalConstructor.prototype, 'constructor', {\n value: newConstructor,\n })\n return newConstructor as typeof Date\n}\n\ntry {\n // eslint-disable-next-line no-native-reassign\n Date = createDate(Date)\n} catch {\n console.error(\n 'Failed to install `Date` class extension. When using `experimental.cacheComponents`, APIs that read the current time will not correctly trigger dynamic behavior.'\n )\n}\n","/**\n * We extend node:crypto APIs during builds and revalidates to ensure that prerenders don't observe random bytes\n * When cacheComponents is enabled. Random bytes are a form of IO even if they resolve synchronously. When cacheComponents is\n * enabled we need to ensure that random bytes are excluded from prerenders unless they are cached.\n *\n *\n * The extensions here never error nor alter the underlying return values and thus should be transparent to callers.\n */\n\nimport { io } from './utils'\n\nif (process.env.NEXT_RUNTIME === 'edge') {\n // nothing to patch\n} else {\n const nodeCrypto = require('node:crypto') as typeof import('node:crypto')\n\n // require('node:crypto').getRandomValues is an alias for\n // crypto.getRandomValues which is extended in web-crypto.tsx\n\n // require('node:crypto').randomUUID is not an alias for crypto.randomUUID\n\n const randomUUIDExpression = \"`require('node:crypto').randomUUID()`\"\n try {\n const _randomUUID = nodeCrypto.randomUUID\n nodeCrypto.randomUUID = function randomUUID() {\n io(randomUUIDExpression, 'random')\n return _randomUUID.apply(this, arguments as any)\n }\n } catch {\n console.error(\n `Failed to install ${randomUUIDExpression} extension. When using \\`experimental.cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n )\n }\n\n const randomBytesExpression = \"`require('node:crypto').randomBytes(size)`\"\n try {\n const _randomBytes = nodeCrypto.randomBytes\n // @ts-expect-error -- TODO: tell TS the overloads are preserved\n nodeCrypto.randomBytes = function randomBytes() {\n if (typeof arguments[1] !== 'function') {\n // randomBytes is sync if the second arg is undefined\n io(randomBytesExpression, 'random')\n }\n return _randomBytes.apply(this, arguments as any)\n }\n } catch {\n console.error(\n `Failed to install ${randomBytesExpression} extension. When using \\`experimental.cacheComponents\\` calling this function without a callback argument will not correctly trigger dynamic behavior.`\n )\n }\n\n const randomFillSyncExpression =\n \"`require('node:crypto').randomFillSync(...)`\"\n try {\n const _randomFillSync = nodeCrypto.randomFillSync\n // @ts-expect-error -- TODO: tell TS the overloads are preserved\n nodeCrypto.randomFillSync = function randomFillSync() {\n io(randomFillSyncExpression, 'random')\n return _randomFillSync.apply(this, arguments as any)\n }\n } catch {\n console.error(\n `Failed to install ${randomFillSyncExpression} extension. When using \\`experimental.cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n )\n }\n\n const randomIntExpression = \"`require('node:crypto').randomInt(min, max)`\"\n try {\n const _randomInt = nodeCrypto.randomInt\n // @ts-expect-error -- TODO: tell TS the overloads are preserved\n nodeCrypto.randomInt = function randomInt() {\n if (typeof arguments[2] !== 'function') {\n // randomInt is sync if the third arg is undefined\n io(randomIntExpression, 'random')\n }\n return _randomInt.apply(this, arguments as any)\n }\n } catch {\n console.error(\n `Failed to install ${randomBytesExpression} extension. When using \\`experimental.cacheComponents\\` calling this function without a callback argument will not correctly trigger dynamic behavior.`\n )\n }\n\n const generatePrimeSyncExpression =\n \"`require('node:crypto').generatePrimeSync(...)`\"\n try {\n const _generatePrimeSync = nodeCrypto.generatePrimeSync\n // @ts-expect-error -- TODO: tell TS the overloads are preserved\n nodeCrypto.generatePrimeSync = function generatePrimeSync() {\n io(generatePrimeSyncExpression, 'random')\n return _generatePrimeSync.apply(this, arguments as any)\n }\n } catch {\n console.error(\n `Failed to install ${generatePrimeSyncExpression} extension. When using \\`experimental.cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n )\n }\n\n const generateKeyPairSyncExpression =\n \"`require('node:crypto').generateKeyPairSync(...)`\"\n try {\n const _generateKeyPairSync = nodeCrypto.generateKeyPairSync\n // @ts-expect-error -- TODO: tell TS the overloads are preserved\n nodeCrypto.generateKeyPairSync = function generateKeyPairSync() {\n io(generateKeyPairSyncExpression, 'random')\n return _generateKeyPairSync.apply(this, arguments as any)\n }\n } catch {\n console.error(\n `Failed to install ${generateKeyPairSyncExpression} extension. When using \\`experimental.cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n )\n }\n\n const generateKeySyncExpression =\n \"`require('node:crypto').generateKeySync(...)`\"\n try {\n const _generateKeySync = nodeCrypto.generateKeySync\n nodeCrypto.generateKeySync = function generateKeySync() {\n io(generateKeySyncExpression, 'random')\n return _generateKeySync.apply(this, arguments as any)\n }\n } catch {\n console.error(\n `Failed to install ${generateKeySyncExpression} extension. When using \\`experimental.cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n )\n }\n}\n","// Synchronously inject a require hook for webpack and webpack/. It's required to use the internal ncc webpack version.\n// This is needed for userland plugins to attach to the same webpack instance as Next.js'.\n// Individually compiled modules are as defined for the compilation in bundles/webpack/packages/*.\n\n// This module will only be loaded once per process.\nconst path = require('path') as typeof import('path')\nconst mod = require('module') as typeof import('module')\nconst originalRequire = mod.prototype.require\nconst resolveFilename =\n // @ts-expect-error\n mod._resolveFilename\n\nlet resolve: typeof require.resolve = process.env.NEXT_MINIMAL\n ? // @ts-ignore\n __non_webpack_require__.resolve\n : require.resolve\n\nexport const hookPropertyMap = new Map()\n\nexport const defaultOverrides = {\n 'styled-jsx': path.dirname(resolve('styled-jsx/package.json')),\n 'styled-jsx/style': resolve('styled-jsx/style'),\n 'styled-jsx/style.js': resolve('styled-jsx/style'),\n}\n\nconst toResolveMap = (map: Record): [string, string][] =>\n Object.entries(map).map(([key, value]) => [key, resolve(value)])\n\nexport function addHookAliases(aliases: [string, string][] = []) {\n for (const [key, value] of aliases) {\n hookPropertyMap.set(key, value)\n }\n}\n\naddHookAliases(toResolveMap(defaultOverrides))\n\n// @ts-expect-error\nmod._resolveFilename = function (\n originalResolveFilename: (\n request: string,\n parent: string,\n isMain: boolean,\n opts: any\n ) => string,\n requestMap: Map,\n request: string,\n parent: string,\n isMain: boolean,\n options: any\n) {\n const hookResolved = requestMap.get(request)\n if (hookResolved) request = hookResolved\n\n return originalResolveFilename.call(mod, request, parent, isMain, options)\n\n // We use `bind` here to avoid referencing outside variables to create potential memory leaks.\n}.bind(null, resolveFilename, hookPropertyMap)\n\n// @ts-expect-error\n// This is a hack to make sure that if a user requires a Next.js module that wasn't bundled\n// that needs to point to the rendering runtime version, it will point to the correct one.\n// This can happen on `pages` when a user requires a dependency that uses next/image for example.\nmod.prototype.require = function (request: string) {\n if (request.endsWith('.shared-runtime')) {\n return originalRequire.call(\n this,\n `next/dist/server/route-modules/pages/vendored/contexts/${path.basename(\n request,\n '.shared-runtime'\n )}`\n )\n }\n\n return originalRequire.call(this, request)\n}\n","import type { HtmlProps } from './html-context.shared-runtime'\nimport type { ComponentType, JSX } from 'react'\nimport type { DomainLocale } from '../../server/config'\nimport type { Env } from '@next/env'\nimport type { IncomingMessage, ServerResponse } from 'http'\nimport type { NextRouter } from './router/router'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { PreviewData } from '../../types'\nimport type { COMPILER_NAMES } from './constants'\nimport type fs from 'fs'\n\nexport type NextComponentType<\n Context extends BaseContext = NextPageContext,\n InitialProps = {},\n Props = {},\n> = ComponentType & {\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\n}\n\nexport type DocumentType = NextComponentType<\n DocumentContext,\n DocumentInitialProps,\n DocumentProps\n>\n\nexport type AppType

= NextComponentType<\n AppContextType,\n P,\n AppPropsType\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 = (Component: C) => C\n\nexport type ComponentsEnhancer =\n | {\n enhanceApp?: Enhancer\n enhanceComponent?: Enhancer\n }\n | Enhancer\n\nexport type RenderPageResult = {\n html: string\n head?: Array\n}\n\nexport type RenderPage = (\n options?: ComponentsEnhancer\n) => DocumentInitialProps | Promise\n\nexport type BaseContext = {\n res?: ServerResponse\n [k: string]: any\n}\n\nexport type NEXT_DATA = {\n props: Record\n page: string\n query: ParsedUrlQuery\n buildId: string\n assetPrefix?: string\n runtimeConfig?: { [key: string]: any }\n nextExport?: boolean\n autoExport?: boolean\n isFallback?: boolean\n isExperimentalCompile?: boolean\n dynamicIds?: (string | number)[]\n err?: Error & {\n statusCode?: number\n source?: typeof COMPILER_NAMES.server | typeof COMPILER_NAMES.edgeServer\n }\n gsp?: boolean\n gssp?: boolean\n customServer?: boolean\n gip?: boolean\n appGip?: boolean\n locale?: string\n locales?: readonly string[]\n defaultLocale?: string\n domainLocales?: readonly DomainLocale[]\n scriptLoader?: any[]\n isPreview?: boolean\n notFoundSrcPage?: string\n}\n\n/**\n * `Next` context\n */\nexport interface NextPageContext {\n /**\n * Error object if encountered during rendering\n */\n err?: (Error & { statusCode?: number }) | null\n /**\n * `HTTP` request object.\n */\n req?: IncomingMessage\n /**\n * `HTTP` response object.\n */\n res?: ServerResponse\n /**\n * Path section of `URL`.\n */\n pathname: string\n /**\n * Query string section of `URL` parsed as an object.\n */\n query: ParsedUrlQuery\n /**\n * `String` of the actual path including query.\n */\n asPath?: string\n /**\n * The currently active locale\n */\n locale?: string\n /**\n * All configured locales\n */\n locales?: readonly string[]\n /**\n * The configured default locale\n */\n defaultLocale?: string\n /**\n * `Component` the tree of the App to use if needing to render separately\n */\n AppTree: AppTreeType\n}\n\nexport type AppContextType = {\n Component: NextComponentType\n AppTree: AppTreeType\n ctx: NextPageContext\n router: Router\n}\n\nexport type AppInitialProps = {\n pageProps: PageProps\n}\n\nexport type AppPropsType<\n Router extends NextRouter = NextRouter,\n PageProps = {},\n> = AppInitialProps & {\n Component: NextComponentType\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\n}\n\nexport type DocumentInitialProps = RenderPageResult & {\n styles?: React.ReactElement[] | Iterable | 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 = (body: T) => void\n\n/**\n * Next `API` route response\n */\nexport type NextApiResponse = ServerResponse & {\n /**\n * Send data `any` data in response\n */\n send: Send\n /**\n * Send data `json` data in response\n */\n json: Send\n status: (statusCode: number) => NextApiResponse\n redirect(url: string): NextApiResponse\n redirect(status: number, url: string): NextApiResponse\n\n /**\n * Set draft mode\n */\n setDraftMode: (options: { enable: boolean }) => NextApiResponse\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\n\n /**\n * Clear preview data for Next.js' prerender mode\n */\n clearPreviewData: (options?: { path?: string }) => NextApiResponse\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\n}\n\n/**\n * Next `API` route handler\n */\nexport type NextApiHandler = (\n req: NextApiRequest,\n res: NextApiResponse\n) => unknown | Promise\n\n/**\n * Utils\n */\nexport function execOnce ReturnType>(\n fn: T\n): T {\n let used = false\n let result: ReturnType\n\n return ((...args: any[]) => {\n if (!used) {\n used = true\n result = fn(...args)\n }\n return result\n }) as T\n}\n\n// Scheme: https://tools.ietf.org/html/rfc3986#section-3.1\n// Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3\nconst ABSOLUTE_URL_REGEX = /^[a-zA-Z][a-zA-Z\\d+\\-.]*?:/\nexport const isAbsoluteUrl = (url: string) => ABSOLUTE_URL_REGEX.test(url)\n\nexport function getLocationOrigin() {\n const { protocol, hostname, port } = window.location\n return `${protocol}//${hostname}${port ? ':' + port : ''}`\n}\n\nexport function getURL() {\n const { href } = window.location\n const origin = getLocationOrigin()\n return href.substring(origin.length)\n}\n\nexport function getDisplayName

(Component: ComponentType

) {\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, ctx: C): Promise {\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\n mkdir(dir: string): Promise\n stat(f: string): Promise<{ mtime: Date }>\n}\n\nexport function stringifyError(error: Error) {\n return JSON.stringify({ message: error.message, stack: error.stack })\n}\n","import type { Token } from 'next/dist/compiled/path-to-regexp'\n\n/**\n * Route pattern normalization utilities for path-to-regexp compatibility.\n *\n * path-to-regexp 6.3.0+ introduced stricter validation that rejects certain\n * patterns commonly used in Next.js interception routes. This module provides\n * normalization functions to make Next.js route patterns compatible with the\n * updated library while preserving all functionality.\n */\n\n/**\n * Internal separator used to normalize adjacent parameter patterns.\n * This unique marker is inserted between adjacent parameters and stripped out\n * during parameter extraction to avoid conflicts with real URL content.\n */\nconst 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 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\n): Record {\n const cleaned: Record = {}\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} 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,\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 */\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 return compile(routeToUse, 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 compile(normalizedRoute, 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 regexpToFunction that automatically cleans parameters.\n */\nexport function safeRegexpToFunction<\n T extends Record = Record,\n>(regexp: RegExp, keys?: Key[]): (pathname: string) => { params: T } | false {\n const originalMatcher = regexpToFunction(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>(\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\n groups: Record\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","/* eslint-disable no-redeclare */\nimport type { IncomingMessage } 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 { ServerComponentsHmrCache } from './response-cache'\nimport type { PagesDevOverlayBridgeType } from '../next-devtools/userspace/pages/pages-dev-overlay-setup'\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 = (BaseNextRequest | IncomingMessage) & {\n [NEXT_REQUEST_META]?: RequestMeta\n}\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 it's URL rewritten, this is the URL it was rewritten to.\n */\n rewroteURL?: 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?: any\n\n /**\n * The server components HMR cache, only for dev.\n */\n serverComponentsHmrCache?: ServerComponentsHmrCache\n\n /**\n * Equals the segment path that was used for the prefetch RSC request.\n */\n segmentPrefetchRSCRequest?: string\n\n /**\n * True when the request is for the prefetch flight data.\n */\n isPrefetchRSCRequest?: true\n\n /**\n * True when the request is for the flight data.\n */\n isRSCRequest?: true\n\n /**\n * A search param set by the Next.js client when performing RSC requests.\n * Because some CDNs do not vary their cache entries on our custom headers,\n * this search param represents a hash of the header values. For any cached\n * RSC request, we should verify that the hash matches before responding.\n * Otherwise this can lead to cache poisoning.\n * TODO: Consider not using custom request headers at all, and instead encode\n * everything into the search param.\n */\n cacheBustingSearchParam?: string\n\n /**\n * True when the request is for the `/_next/data` route using the pages\n * router.\n */\n isNextDataReq?: true\n\n /**\n * Postponed state to use for resumption. If present it's assumed that the\n * request is for a page that has postponed (there are no guarantees that the\n * page actually has postponed though as it would incur an additional cache\n * lookup).\n */\n postponed?: string\n\n /**\n * If provided, this will be called when a response cache entry was generated\n * or looked up in the cache.\n */\n onCacheEntry?: (\n cacheEntry: any,\n requestMeta: any\n ) => Promise | boolean | void\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\n\n /**\n * Whether the request is a middleware invocation\n */\n middlewareInvoke?: boolean\n\n /**\n * Whether the request should render the fallback shell or not.\n */\n renderFallbackShell?: boolean\n\n /**\n * Whether the request is for the custom error page.\n */\n customErrorRender?: true\n\n /**\n * Whether to bubble up the NoFallbackError to the caller when a 404 is\n * returned.\n */\n bubbleNoFallback?: true\n\n /**\n * True when the request had locale information inferred from the default\n * locale.\n */\n localeInferredFromDefault?: true\n\n /**\n * The locale that was inferred or explicitly set for the request.\n */\n locale?: string\n\n /**\n * The default locale that was inferred or explicitly set for the request.\n */\n defaultLocale?: string\n\n /**\n * The relative project dir the server is running in from project root\n */\n relativeProjectDir?: string\n\n /**\n * The dist directory the server is currently using\n */\n distDir?: string\n\n /**\n * The query after resolving routes\n */\n query?: ParsedUrlQuery\n\n /**\n * The params after resolving routes\n */\n params?: ParsedUrlQuery\n\n /**\n * The AMP validator to use in development\n */\n ampValidator?: (html: string, pathname: string) => Promise\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 * DEV only: The fallback params that should be used when validating prerenders during dev\n */\n devValidatingFallbackParams?: Map\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(\n req: NextIncomingMessage,\n key: K\n): RequestMeta[K]\nexport function getRequestMeta(\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(\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(\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 &\n NextQueryMetadata & {\n amp?: '1'\n }\n\nexport interface NextUrlWithParsedQuery extends UrlWithParsedQuery {\n query: NextParsedUrlQuery\n}\n","import MODERN_BROWSERSLIST_TARGET from './modern-browserslist-target'\n\nexport { MODERN_BROWSERSLIST_TARGET }\n\nexport type ValueOf = Required[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\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 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\nexport const UNDERSCORE_NOT_FOUND_ROUTE = '/_not-found'\nexport const UNDERSCORE_NOT_FOUND_ROUTE_ENTRY = `${UNDERSCORE_NOT_FOUND_ROUTE}/page`\nexport const PHASE_EXPORT = 'phase-export'\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'\nexport const PAGES_MANIFEST = 'pages-manifest.json'\nexport const WEBPACK_STATS = 'webpack-stats.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 APP_BUILD_MANIFEST = 'app-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 ROUTES_MANIFEST = 'routes-manifest.json'\nexport const IMAGES_MANIFEST = 'images-manifest.json'\nexport const SERVER_FILES_MANIFEST = 'required-server-files.json'\nexport const DEV_CLIENT_PAGES_MANIFEST = '_devPagesManifest.json'\nexport const MIDDLEWARE_MANIFEST = 'middleware-manifest.json'\nexport const TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST =\n '_clientMiddlewareManifest.json'\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]\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/amp.js\nexport const CLIENT_STATIC_FILES_RUNTIME_AMP = `amp`\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([\n CLIENT_STATIC_FILES_RUNTIME_MAIN,\n CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,\n CLIENT_STATIC_FILES_RUNTIME_AMP,\n CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,\n])\n","import fs from 'fs'\nimport path from 'path'\n\nexport function findDir(dir: string, name: 'pages' | 'app'): string | null {\n // prioritize ./${name} over ./src/${name}\n let curDir = path.join(dir, name)\n if (fs.existsSync(curDir)) return curDir\n\n curDir = path.join(dir, 'src', name)\n if (fs.existsSync(curDir)) return curDir\n\n return null\n}\n\nexport function findPagesDir(dir: string): {\n pagesDir: string | undefined\n appDir: string | undefined\n} {\n const pagesDir = findDir(dir, 'pages') || undefined\n const appDir = findDir(dir, 'app') || undefined\n\n if (appDir == null && pagesDir == null) {\n throw new Error(\n \"> Couldn't find any `pages` or `app` directory. Please create one under the project root\"\n )\n }\n\n return {\n pagesDir,\n appDir,\n }\n}\n","export class ReflectAdapter {\n static get(\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(\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(target: T, prop: string | symbol): boolean {\n return Reflect.has(target, prop)\n }\n\n static deleteProperty(\n target: T,\n prop: string | symbol\n ): boolean {\n return Reflect.deleteProperty(target, prop)\n }\n}\n","import type { IncomingHttpHeaders } from 'http'\n\nimport { ReflectAdapter } from './reflect'\n\n/**\n * @internal\n */\nexport class ReadonlyHeadersError extends Error {\n constructor() {\n super(\n 'Headers cannot be modified. Read more: https://nextjs.org/docs/app/api-reference/functions/headers'\n )\n }\n\n public static callable() {\n throw new ReadonlyHeadersError()\n }\n}\n\nexport type ReadonlyHeaders = Headers & {\n /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */\n append(...args: any[]): void\n /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */\n set(...args: any[]): void\n /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */\n delete(...args: any[]): void\n}\nexport class HeadersAdapter extends Headers {\n private readonly headers: IncomingHttpHeaders\n\n constructor(headers: IncomingHttpHeaders) {\n // We've already overridden the methods that would be called, so we're just\n // calling the super constructor to ensure that the instanceof check works.\n super()\n\n this.headers = new Proxy(headers, {\n get(target, prop, receiver) {\n // Because this is just an object, we expect that all \"get\" operations\n // are for properties. If it's a \"get\" for a symbol, we'll just return\n // the symbol.\n if (typeof prop === 'symbol') {\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n const lowercased = prop.toLowerCase()\n\n // Let's find the original casing of the key. This assumes that there is\n // no mixed case keys (e.g. \"Content-Type\" and \"content-type\") in the\n // headers object.\n const original = Object.keys(headers).find(\n (o) => o.toLowerCase() === lowercased\n )\n\n // If the original casing doesn't exist, return undefined.\n if (typeof original === 'undefined') return\n\n // If the original casing exists, return the value.\n return ReflectAdapter.get(target, original, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'symbol') {\n return ReflectAdapter.set(target, prop, value, receiver)\n }\n\n const lowercased = prop.toLowerCase()\n\n // Let's find the original casing of the key. This assumes that there is\n // no mixed case keys (e.g. \"Content-Type\" and \"content-type\") in the\n // headers object.\n const original = Object.keys(headers).find(\n (o) => o.toLowerCase() === lowercased\n )\n\n // If the original casing doesn't exist, use the prop as the key.\n return ReflectAdapter.set(target, original ?? prop, value, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'symbol') return ReflectAdapter.has(target, prop)\n\n const lowercased = prop.toLowerCase()\n\n // Let's find the original casing of the key. This assumes that there is\n // no mixed case keys (e.g. \"Content-Type\" and \"content-type\") in the\n // headers object.\n const original = Object.keys(headers).find(\n (o) => o.toLowerCase() === lowercased\n )\n\n // If the original casing doesn't exist, return false.\n if (typeof original === 'undefined') return false\n\n // If the original casing exists, return true.\n return ReflectAdapter.has(target, original)\n },\n deleteProperty(target, prop) {\n if (typeof prop === 'symbol')\n return ReflectAdapter.deleteProperty(target, prop)\n\n const lowercased = prop.toLowerCase()\n\n // Let's find the original casing of the key. This assumes that there is\n // no mixed case keys (e.g. \"Content-Type\" and \"content-type\") in the\n // headers object.\n const original = Object.keys(headers).find(\n (o) => o.toLowerCase() === lowercased\n )\n\n // If the original casing doesn't exist, return true.\n if (typeof original === 'undefined') return true\n\n // If the original casing exists, delete the property.\n return ReflectAdapter.deleteProperty(target, original)\n },\n })\n }\n\n /**\n * Seals a Headers instance to prevent modification by throwing an error when\n * any mutating method is called.\n */\n public static seal(headers: Headers): ReadonlyHeaders {\n return new Proxy(headers, {\n get(target, prop, receiver) {\n switch (prop) {\n case 'append':\n case 'delete':\n case 'set':\n return ReadonlyHeadersError.callable\n default:\n return ReflectAdapter.get(target, prop, receiver)\n }\n },\n })\n }\n\n /**\n * Merges a header value into a string. This stores multiple values as an\n * array, so we need to merge them into a string.\n *\n * @param value a header value\n * @returns a merged header value (a string)\n */\n private merge(value: string | string[]): string {\n if (Array.isArray(value)) return value.join(', ')\n\n return value\n }\n\n /**\n * Creates a Headers instance from a plain object or a Headers instance.\n *\n * @param headers a plain object or a Headers instance\n * @returns a headers instance\n */\n public static from(headers: IncomingHttpHeaders | Headers): Headers {\n if (headers instanceof Headers) return headers\n\n return new HeadersAdapter(headers)\n }\n\n public append(name: string, value: string): void {\n const existing = this.headers[name]\n if (typeof existing === 'string') {\n this.headers[name] = [existing, value]\n } else if (Array.isArray(existing)) {\n existing.push(value)\n } else {\n this.headers[name] = value\n }\n }\n\n public delete(name: string): void {\n delete this.headers[name]\n }\n\n public get(name: string): string | null {\n const value = this.headers[name]\n if (typeof value !== 'undefined') return this.merge(value)\n\n return null\n }\n\n public has(name: string): boolean {\n return typeof this.headers[name] !== 'undefined'\n }\n\n public set(name: string, value: string): void {\n this.headers[name] = value\n }\n\n public forEach(\n callbackfn: (value: string, name: string, parent: Headers) => void,\n thisArg?: any\n ): void {\n for (const [name, value] of this.entries()) {\n callbackfn.call(thisArg, value, name, this)\n }\n }\n\n public *entries(): HeadersIterator<[string, string]> {\n for (const key of Object.keys(this.headers)) {\n const name = key.toLowerCase()\n // We assert here that this is a string because we got it from the\n // Object.keys() call above.\n const value = this.get(name) as string\n\n yield [name, value] as [string, string]\n }\n }\n\n public *keys(): HeadersIterator {\n for (const key of Object.keys(this.headers)) {\n const name = key.toLowerCase()\n yield name\n }\n }\n\n public *values(): HeadersIterator {\n for (const key of Object.keys(this.headers)) {\n // We assert here that this is a string because we got it from the\n // Object.keys() call above.\n const value = this.get(key) as string\n\n yield value\n }\n }\n\n public [Symbol.iterator](): HeadersIterator<[string, string]> {\n return this.entries()\n }\n}\n","import type { ServerRuntime } from '../types'\n\nexport const TEXT_PLAIN_CONTENT_TYPE_HEADER = 'text/plain'\nexport const HTML_CONTENT_TYPE_HEADER = 'text/html; charset=utf-8'\nexport const JSON_CONTENT_TYPE_HEADER = 'application/json; charset=utf-8'\nexport const NEXT_QUERY_PARAM_PREFIX = 'nxtP'\nexport const NEXT_INTERCEPTION_MARKER_PREFIX = 'nxtI'\n\nexport const MATCHED_PATH_HEADER = 'x-matched-path'\nexport const PRERENDER_REVALIDATE_HEADER = 'x-prerender-revalidate'\nexport const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER =\n 'x-prerender-revalidate-if-generated'\n\nexport const RSC_PREFETCH_SUFFIX = '.prefetch.rsc'\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_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'\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_'\n\n// in seconds\nexport const CACHE_ONE_YEAR = 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// 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 = {\n edge: 'edge',\n experimentalEdge: 'experimental-edge',\n nodejs: 'nodejs',\n}\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","/**\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/* eslint-disable no-shadow */\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 getServer = 'NextServer.getServer',\n getServerRequestHandler = 'NextServer.getServerRequestHandler',\n createServer = 'createServer.createServer',\n}\n\nenum NextNodeServerSpan {\n compression = 'NextNodeServer.compression',\n getBuildId = 'NextNodeServer.getBuildId',\n createComponentTree = 'NextNodeServer.createComponentTree',\n clientComponentLoading = 'NextNodeServer.clientComponentLoading',\n getLayoutOrPageModule = 'NextNodeServer.getLayoutOrPageModule',\n generateStaticRoutes = 'NextNodeServer.generateStaticRoutes',\n generateFsStaticRoutes = 'NextNodeServer.generateFsStaticRoutes',\n generatePublicRoutes = 'NextNodeServer.generatePublicRoutes',\n generateImageRoutes = 'NextNodeServer.generateImageRoutes.route',\n sendRenderResult = 'NextNodeServer.sendRenderResult',\n proxyRequest = 'NextNodeServer.proxyRequest',\n runApi = 'NextNodeServer.runApi',\n render = 'NextNodeServer.render',\n renderHTML = 'NextNodeServer.renderHTML',\n imageOptimizer = 'NextNodeServer.imageOptimizer',\n getPagePath = 'NextNodeServer.getPagePath',\n getRoutesManifest = 'NextNodeServer.getRoutesManifest',\n findPageComponents = 'NextNodeServer.findPageComponents',\n getFontManifest = 'NextNodeServer.getFontManifest',\n getServerComponentManifest = 'NextNodeServer.getServerComponentManifest',\n getRequestHandler = 'NextNodeServer.getRequestHandler',\n renderToHTML = 'NextNodeServer.renderToHTML',\n renderError = 'NextNodeServer.renderError',\n renderErrorToHTML = 'NextNodeServer.renderErrorToHTML',\n render404 = 'NextNodeServer.render404',\n startResponse = 'NextNodeServer.startResponse',\n\n // nested inner span, does not require parent scope name\n route = 'route',\n onProxyReq = 'onProxyReq',\n apiResolver = 'apiResolver',\n internalFetch = 'internalFetch',\n}\n\nenum StartServerSpan {\n startServer = 'startServer.startServer',\n}\n\nenum RenderSpan {\n getServerSideProps = 'Render.getServerSideProps',\n getStaticProps = 'Render.getStaticProps',\n renderToString = 'Render.renderToString',\n renderDocument = 'Render.renderDocument',\n createBodyResult = 'Render.createBodyResult',\n}\n\nenum AppRenderSpan {\n renderToString = 'AppRender.renderToString',\n renderToReadableStream = 'AppRender.renderToReadableStream',\n getBodyResult = 'AppRender.getBodyResult',\n fetch = 'AppRender.fetch',\n}\n\nenum RouterSpan {\n executeRoute = 'Router.executeRoute',\n}\n\nenum NodeSpan {\n runHandler = 'Node.runHandler',\n}\n\nenum AppRouteRouteHandlersSpan {\n runHandler = 'AppRouteRouteHandlers.runHandler',\n}\n\nenum ResolveMetadataSpan {\n generateMetadata = 'ResolveMetadata.generateMetadata',\n generateViewport = 'ResolveMetadata.generateViewport',\n}\n\nenum MiddlewareSpan {\n execute = 'Middleware.execute',\n}\n\ntype SpanTypes =\n | `${BaseServerSpan}`\n | `${LoadComponentsSpan}`\n | `${NextServerSpan}`\n | `${StartServerSpan}`\n | `${NextNodeServerSpan}`\n | `${RenderSpan}`\n | `${RouterSpan}`\n | `${AppRenderSpan}`\n | `${NodeSpan}`\n | `${AppRouteRouteHandlersSpan}`\n | `${ResolveMetadataSpan}`\n | `${MiddlewareSpan}`\n\n// This list is used to filter out spans that are not relevant to the user\nexport const NextVanillaSpanAllowlist = new Set([\n MiddlewareSpan.execute,\n BaseServerSpan.handleRequest,\n RenderSpan.getServerSideProps,\n RenderSpan.getStaticProps,\n AppRenderSpan.fetch,\n AppRenderSpan.getBodyResult,\n RenderSpan.renderDocument,\n NodeSpan.runHandler,\n AppRouteRouteHandlersSpan.runHandler,\n ResolveMetadataSpan.generateMetadata,\n ResolveMetadataSpan.generateViewport,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.getLayoutOrPageModule,\n NextNodeServerSpan.startResponse,\n NextNodeServerSpan.clientComponentLoading,\n])\n\n// These Spans are allowed to be always logged\n// when the otel log prefix env is set\nexport const LogSpanAllowList = new Set([\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.clientComponentLoading,\n])\n\nexport {\n BaseServerSpan,\n LoadComponentsSpan,\n NextServerSpan,\n NextNodeServerSpan,\n StartServerSpan,\n RenderSpan,\n RouterSpan,\n AppRenderSpan,\n NodeSpan,\n AppRouteRouteHandlersSpan,\n ResolveMetadataSpan,\n MiddlewareSpan,\n}\n\nexport type { SpanTypes }\n","import type { IncomingMessage } from 'http'\nimport type { BaseNextRequest } from '../base-http'\nimport type { CookieSerializeOptions } from 'next/dist/compiled/cookie'\nimport type { NextApiResponse } from '../../shared/lib/utils'\n\nimport { HeadersAdapter } from '../web/spec-extension/adapters/headers'\nimport {\n PRERENDER_REVALIDATE_HEADER,\n PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER,\n} from '../../lib/constants'\nimport { getTracer } from '../lib/trace/tracer'\nimport { NodeSpan } from '../lib/trace/constants'\n\nexport type NextApiRequestCookies = Partial<{ [key: string]: string }>\nexport type NextApiRequestQuery = Partial<{ [key: string]: string | string[] }>\n\nexport type __ApiPreviewProps = {\n previewModeId: string\n previewModeEncryptionKey: string\n previewModeSigningKey: string\n}\n\nexport function wrapApiHandler 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 {\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 {\n if (typeof statusOrUrl === 'string') {\n url = statusOrUrl\n statusOrUrl = 307\n }\n if (typeof statusOrUrl !== 'number' || typeof url !== 'string') {\n throw new Error(\n `Invalid redirect arguments. Please use a single argument URL, e.g. res.redirect('/destination') or use a status code and URL, e.g. res.redirect(307, '/destination').`\n )\n }\n res.writeHead(statusOrUrl, { Location: url })\n res.write(url)\n res.end()\n return res\n}\n\nexport function checkIsOnDemandRevalidate(\n req: Request | IncomingMessage | BaseNextRequest,\n previewProps: __ApiPreviewProps\n): {\n isOnDemandRevalidate: boolean\n revalidateOnlyGenerated: boolean\n} {\n const headers = HeadersAdapter.from(req.headers)\n\n const previewModeId = headers.get(PRERENDER_REVALIDATE_HEADER)\n const isOnDemandRevalidate = previewModeId === previewProps.previewModeId\n\n const revalidateOnlyGenerated = headers.has(\n PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER\n )\n\n return { isOnDemandRevalidate, revalidateOnlyGenerated }\n}\n\nexport const COOKIE_NAME_PRERENDER_BYPASS = `__prerender_bypass`\nexport const COOKIE_NAME_PRERENDER_DATA = `__next_preview_data`\n\nexport const RESPONSE_LIMIT_DEFAULT = 4 * 1024 * 1024\n\nexport const SYMBOL_PREVIEW_DATA = Symbol(COOKIE_NAME_PRERENDER_DATA)\nexport const SYMBOL_CLEARED_COOKIES = Symbol(COOKIE_NAME_PRERENDER_BYPASS)\n\nexport function clearPreviewData(\n res: NextApiResponse,\n options: {\n path?: string\n } = {}\n): NextApiResponse {\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(\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","export enum RedirectStatusCode {\n SeeOther = 303,\n TemporaryRedirect = 307,\n PermanentRedirect = 308,\n}\n","import type { NextApiRequestCookies } from '.'\n\n/**\n * Parse cookies from the `headers` of request\n * @param req request object\n */\n\nexport function getCookieParser(headers: {\n [key: string]: string | string[] | null | undefined\n}): () => NextApiRequestCookies {\n return function parseCookie(): NextApiRequestCookies {\n const { cookie } = headers\n\n if (!cookie) {\n return {}\n }\n\n const { parse: parseCookieFn } =\n require('next/dist/compiled/cookie') as typeof import('next/dist/compiled/cookie')\n return parseCookieFn(Array.isArray(cookie) ? cookie.join('; ') : cookie)\n }\n}\n","import type { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http'\nimport type { I18NConfig } from '../config-shared'\n\nimport { RedirectStatusCode } from '../../client/components/redirect-status-code'\nimport type { NextApiRequestCookies } from '../api-utils'\nimport { getCookieParser } from '../api-utils/get-cookie-parser'\n\nexport interface BaseNextRequestConfig {\n basePath: string | undefined\n i18n?: I18NConfig\n trailingSlash?: boolean | undefined\n}\n\nexport type FetchMetric = {\n url: string\n idx: number\n end: number\n start: number\n method: string\n status: number\n cacheReason: string\n cacheStatus: 'hit' | 'miss' | 'skip' | 'hmr'\n cacheWarning?: string\n}\n\nexport type FetchMetrics = Array\n\nexport abstract class BaseNextRequest {\n protected _cookies: NextApiRequestCookies | undefined\n public abstract headers: IncomingHttpHeaders\n public abstract fetchMetrics: FetchMetric[] | undefined\n\n constructor(\n public method: string,\n public url: string,\n public body: Body\n ) {}\n\n // Utils implemented using the abstract methods above\n\n public get cookies() {\n if (this._cookies) return this._cookies\n return (this._cookies = getCookieParser(this.headers)())\n }\n}\n\nexport abstract class BaseNextResponse {\n abstract statusCode: number | undefined\n abstract statusMessage: string | undefined\n abstract get sent(): boolean\n\n constructor(public destination: Destination) {}\n\n /**\n * Sets a value for the header overwriting existing values\n */\n abstract setHeader(name: string, value: string | string[]): this\n\n /**\n * Removes a header\n */\n abstract removeHeader(name: string): this\n\n /**\n * Appends value for the given header name\n */\n abstract appendHeader(name: string, value: string): this\n\n /**\n * Get all values for a header as an array or undefined if no value is present\n */\n abstract getHeaderValues(name: string): string[] | undefined\n\n abstract hasHeader(name: string): boolean\n\n /**\n * Get values for a header concatenated using `,` or undefined if no value is present\n */\n abstract getHeader(name: string): string | undefined\n\n abstract getHeaders(): OutgoingHttpHeaders\n\n abstract body(value: string): this\n\n abstract send(): void\n\n abstract onClose(callback: () => void): void\n\n // Utils implemented using the abstract methods above\n\n public redirect(destination: string, statusCode: number) {\n this.setHeader('Location', destination)\n this.statusCode = statusCode\n\n // Since IE11 doesn't support the 308 header add backwards\n // compatibility using refresh header\n if (statusCode === RedirectStatusCode.PermanentRedirect) {\n this.setHeader('Refresh', `0;url=${destination}`)\n }\n\n return this\n }\n}\n","import type { ServerResponse, IncomingMessage } from 'http'\nimport type { Writable, Readable } from 'stream'\n\nimport { SYMBOL_CLEARED_COOKIES } from '../api-utils'\nimport type { NextApiRequestCookies } from '../api-utils'\n\nimport { NEXT_REQUEST_META } from '../request-meta'\nimport type { RequestMeta } from '../request-meta'\n\nimport { BaseNextRequest, BaseNextResponse, type FetchMetric } from './index'\nimport type { OutgoingHttpHeaders } from 'node:http'\n\ntype Req = IncomingMessage & {\n [NEXT_REQUEST_META]?: RequestMeta\n cookies?: NextApiRequestCookies\n fetchMetrics?: FetchMetric[]\n}\n\nexport class NodeNextRequest extends BaseNextRequest {\n public headers = this._req.headers\n public fetchMetrics: FetchMetric[] | undefined = this._req?.fetchMetrics;\n\n [NEXT_REQUEST_META]: RequestMeta = this._req[NEXT_REQUEST_META] || {}\n\n constructor(private _req: Req) {\n super(_req.method!.toUpperCase(), _req.url!, _req)\n }\n\n get originalRequest() {\n // Need to mimic these changes to the original req object for places where we use it:\n // render.tsx, api/ssg requests\n this._req[NEXT_REQUEST_META] = this[NEXT_REQUEST_META]\n this._req.url = this.url\n this._req.cookies = this.cookies\n return this._req\n }\n\n set originalRequest(value: Req) {\n this._req = value\n }\n\n private streaming = false\n\n /**\n * Returns the request body as a Web Readable Stream. The body here can only\n * be read once as the body will start flowing as soon as the data handler\n * is attached.\n *\n * @internal\n */\n public stream() {\n if (this.streaming) {\n throw new Error(\n 'Invariant: NodeNextRequest.stream() can only be called once'\n )\n }\n this.streaming = true\n\n return new ReadableStream({\n start: (controller) => {\n this._req.on('data', (chunk) => {\n controller.enqueue(new Uint8Array(chunk))\n })\n this._req.on('end', () => {\n controller.close()\n })\n this._req.on('error', (err) => {\n controller.error(err)\n })\n },\n })\n }\n}\n\nexport class NodeNextResponse extends BaseNextResponse {\n private textBody: string | undefined = undefined\n\n public [SYMBOL_CLEARED_COOKIES]?: boolean\n\n get originalResponse() {\n if (SYMBOL_CLEARED_COOKIES in this) {\n this._res[SYMBOL_CLEARED_COOKIES] = this[SYMBOL_CLEARED_COOKIES]\n }\n\n return this._res\n }\n\n constructor(\n private _res: ServerResponse & { [SYMBOL_CLEARED_COOKIES]?: boolean }\n ) {\n super(_res)\n }\n\n get sent() {\n return this._res.finished || this._res.headersSent\n }\n\n get statusCode() {\n return this._res.statusCode\n }\n\n set statusCode(value: number) {\n this._res.statusCode = value\n }\n\n get statusMessage() {\n return this._res.statusMessage\n }\n\n set statusMessage(value: string) {\n this._res.statusMessage = value\n }\n\n setHeader(name: string, value: string | string[]): this {\n this._res.setHeader(name, value)\n return this\n }\n\n removeHeader(name: string): this {\n this._res.removeHeader(name)\n return this\n }\n\n getHeaderValues(name: string): string[] | undefined {\n const values = this._res.getHeader(name)\n\n if (values === undefined) return undefined\n\n return (Array.isArray(values) ? values : [values]).map((value) =>\n value.toString()\n )\n }\n\n hasHeader(name: string): boolean {\n return this._res.hasHeader(name)\n }\n\n getHeader(name: string): string | undefined {\n const values = this.getHeaderValues(name)\n return Array.isArray(values) ? values.join(',') : undefined\n }\n\n getHeaders(): OutgoingHttpHeaders {\n return this._res.getHeaders()\n }\n\n appendHeader(name: string, value: string): this {\n const currentValues = this.getHeaderValues(name) ?? []\n\n if (!currentValues.includes(value)) {\n this._res.setHeader(name, [...currentValues, value])\n }\n\n return this\n }\n\n body(value: string) {\n this.textBody = value\n return this\n }\n\n send() {\n this._res.end(this.textBody)\n }\n\n public onClose(callback: () => void) {\n this.originalResponse.on('close', callback)\n }\n}\n","import type { IncomingMessage, ServerResponse } from 'http'\nimport type RenderResult from './render-result'\nimport type { CacheControl } from './lib/cache-control'\n\nimport { isResSent } from '../shared/lib/utils'\nimport { generateETag } from './lib/etag'\nimport fresh from 'next/dist/compiled/fresh'\nimport { getCacheControlHeader } from './lib/cache-control'\nimport { HTML_CONTENT_TYPE_HEADER } from '../lib/constants'\n\nexport function sendEtagResponse(\n req: IncomingMessage,\n res: ServerResponse,\n etag: string | undefined\n): boolean {\n if (etag) {\n /**\n * The server generating a 304 response MUST generate any of the\n * following header fields that would have been sent in a 200 (OK)\n * response to the same request: Cache-Control, Content-Location, Date,\n * ETag, Expires, and Vary. https://tools.ietf.org/html/rfc7232#section-4.1\n */\n res.setHeader('ETag', etag)\n }\n\n if (fresh(req.headers, { etag })) {\n res.statusCode = 304\n res.end()\n return true\n }\n\n return false\n}\n\nexport async function sendRenderResult({\n req,\n res,\n result,\n generateEtags,\n poweredByHeader,\n cacheControl,\n}: {\n req: IncomingMessage\n res: ServerResponse\n result: RenderResult\n generateEtags: boolean\n poweredByHeader: boolean\n cacheControl: CacheControl | undefined\n}): Promise {\n if (isResSent(res)) {\n return\n }\n\n if (poweredByHeader && result.contentType === HTML_CONTENT_TYPE_HEADER) {\n res.setHeader('X-Powered-By', 'Next.js')\n }\n\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheControl && !res.getHeader('Cache-Control')) {\n res.setHeader('Cache-Control', getCacheControlHeader(cacheControl))\n }\n\n const payload = result.isDynamic ? null : result.toUnchunkedString()\n\n if (generateEtags && payload !== null) {\n const etag = generateETag(payload)\n if (sendEtagResponse(req, res, etag)) {\n return\n }\n }\n\n if (!res.getHeader('Content-Type') && result.contentType) {\n res.setHeader('Content-Type', result.contentType)\n }\n\n if (payload) {\n res.setHeader('Content-Length', Buffer.byteLength(payload))\n }\n\n if (req.method === 'HEAD') {\n res.end(null)\n return\n }\n\n if (payload !== null) {\n res.end(payload)\n return\n }\n\n // Pipe the render result to the response after we get a writer for it.\n await result.pipeToNodeResponse(res)\n}\n","import { CACHE_ONE_YEAR } from '../../lib/constants'\n\n/**\n * The revalidate option used internally for pages. A value of `false` means\n * that the page should not be revalidated. A number means that the page\n * should be revalidated after the given number of seconds (this also includes\n * `1` which means to revalidate after 1 second). A value of `0` is not a valid\n * value for this option.\n */\nexport type Revalidate = number | false\n\nexport interface CacheControl {\n revalidate: Revalidate\n expire: number | undefined\n}\n\nexport function getCacheControlHeader({\n revalidate,\n expire,\n}: CacheControl): string {\n const swrHeader =\n typeof revalidate === 'number' &&\n expire !== undefined &&\n revalidate < expire\n ? `, stale-while-revalidate=${expire - revalidate}`\n : ''\n\n if (revalidate === 0) {\n return 'private, no-cache, no-store, max-age=0, must-revalidate'\n } else if (typeof revalidate === 'number') {\n return `s-maxage=${revalidate}${swrHeader}`\n }\n\n return `s-maxage=${CACHE_ONE_YEAR}${swrHeader}`\n}\n","/**\n * FNV-1a Hash implementation\n * @author Travis Webb (tjwebb) \n *\n * Ported from https://github.com/tjwebb/fnv-plus/blob/master/index.js\n *\n * Simplified, optimized and add modified for 52 bit, which provides a larger hash space\n * and still making use of Javascript's 53-bit integer space.\n */\nexport const fnv1a52 = (str: string) => {\n const len = str.length\n let i = 0,\n t0 = 0,\n v0 = 0x2325,\n t1 = 0,\n v1 = 0x8422,\n t2 = 0,\n v2 = 0x9ce4,\n t3 = 0,\n v3 = 0xcbf2\n\n while (i < len) {\n v0 ^= str.charCodeAt(i++)\n t0 = v0 * 435\n t1 = v1 * 435\n t2 = v2 * 435\n t3 = v3 * 435\n t2 += v0 << 8\n t3 += v1 << 8\n t1 += t0 >>> 16\n v0 = t0 & 65535\n t2 += t1 >>> 16\n v1 = t1 & 65535\n v3 = (t3 + (t2 >>> 16)) & 65535\n v2 = t2 & 65535\n }\n\n return (\n (v3 & 15) * 281474976710656 +\n v2 * 4294967296 +\n v1 * 65536 +\n (v0 ^ (v3 >> 4))\n )\n}\n\nexport const generateETag = (payload: string, weak = false) => {\n const prefix = weak ? 'W/\"' : '\"'\n return (\n prefix + fnv1a52(payload).toString(36) + payload.length.toString(36) + '\"'\n )\n}\n","import type { ParsedUrlQuery } from 'querystring'\n\nexport function searchParamsToUrlQuery(\n searchParams: URLSearchParams\n): ParsedUrlQuery {\n const query: ParsedUrlQuery = {}\n for (const [key, value] of searchParams.entries()) {\n const existing = query[key]\n if (typeof existing === 'undefined') {\n query[key] = value\n } else if (Array.isArray(existing)) {\n existing.push(value)\n } else {\n query[key] = [existing, value]\n }\n }\n return query\n}\n\nfunction stringifyUrlQueryParam(param: unknown): string {\n if (typeof param === 'string') {\n return param\n }\n\n if (\n (typeof param === 'number' && !isNaN(param)) ||\n typeof param === 'boolean'\n ) {\n return String(param)\n } else {\n return ''\n }\n}\n\nexport function urlQueryToSearchParams(query: ParsedUrlQuery): URLSearchParams {\n const searchParams = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n if (Array.isArray(value)) {\n for (const item of value) {\n searchParams.append(key, stringifyUrlQueryParam(item))\n }\n } else {\n searchParams.set(key, stringifyUrlQueryParam(value))\n }\n }\n return searchParams\n}\n\nexport function assign(\n target: URLSearchParams,\n ...searchParamsList: URLSearchParams[]\n): URLSearchParams {\n for (const searchParams of searchParamsList) {\n for (const key of searchParams.keys()) {\n target.delete(key)\n }\n\n for (const [key, value] of searchParams.entries()) {\n target.append(key, value)\n }\n }\n\n return target\n}\n","import type { ParsedUrlQuery } from 'querystring'\n\nimport { searchParamsToUrlQuery } from './querystring'\nimport { parseRelativeUrl } from './parse-relative-url'\n\nexport interface ParsedUrl {\n hash: string\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: boolean | undefined\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 return {\n hash: parsedURL.hash,\n hostname: parsedURL.hostname,\n href: parsedURL.href,\n pathname: parsedURL.pathname,\n port: parsedURL.port,\n protocol: parsedURL.protocol,\n query: searchParamsToUrlQuery(parsedURL.searchParams),\n search: parsedURL.search,\n slashes:\n parsedURL.href.slice(\n parsedURL.protocol.length,\n parsedURL.protocol.length + 2\n ) === '//',\n }\n}\n","import type { ParsedUrlQuery } from 'querystring'\nimport { getLocationOrigin } from '../../utils'\nimport { searchParamsToUrlQuery } from './querystring'\n\nexport interface ParsedRelativeUrl {\n hash: string\n href: string\n pathname: string\n query: ParsedUrlQuery\n search: string\n slashes: undefined\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\nexport function parseRelativeUrl(\n url: string,\n base?: string,\n parseQuery = true\n): ParsedRelativeUrl | Omit {\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 } = new URL(\n url,\n resolvedBase\n )\n\n if (origin !== globalBase.origin) {\n throw new Error(`invariant: invalid relative URL, router received ${url}`)\n }\n\n return {\n pathname,\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: undefined,\n }\n}\n","import { bold, green, magenta, red, yellow, white } from '../../lib/picocolors'\nimport { LRUCache } from '../../server/lib/lru-cache'\n\nexport const prefixes = {\n wait: white(bold('○')),\n error: red(bold('⨯')),\n warn: yellow(bold('⚠')),\n ready: '▲', // no color\n info: white(bold(' ')),\n event: green(bold('✓')),\n trace: magenta(bold('»')),\n} as const\n\nconst LOGGING_METHOD = {\n log: 'log',\n warn: 'warn',\n error: 'error',\n} as const\n\nfunction prefixedLog(prefixType: keyof typeof prefixes, ...message: any[]) {\n if ((message[0] === '' || message[0] === undefined) && message.length === 1) {\n message.shift()\n }\n\n const consoleMethod: keyof typeof LOGGING_METHOD =\n prefixType in LOGGING_METHOD\n ? LOGGING_METHOD[prefixType as keyof typeof LOGGING_METHOD]\n : 'log'\n\n const prefix = prefixes[prefixType]\n // If there's no message, don't print the prefix but a new line\n if (message.length === 0) {\n console[consoleMethod]('')\n } else {\n // Ensure if there's ANSI escape codes it's concatenated into one string.\n // Chrome DevTool can only handle color if it's in one string.\n if (message.length === 1 && typeof message[0] === 'string') {\n console[consoleMethod](' ' + prefix + ' ' + message[0])\n } else {\n console[consoleMethod](' ' + prefix, ...message)\n }\n }\n}\n\nexport function bootstrap(...message: string[]) {\n // logging format: ' '\n // e.g. ' ✓ Compiled successfully'\n // Add spaces to align with the indent of other logs\n console.log(' ' + message.join(' '))\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(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","// Regex from `node/lib/internal/net.js`: https://github.com/nodejs/node/blob/9fc57006c27564ed7f75eee090eca86786508f51/lib/internal/net.js#L19-L29\n// License included below:\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nconst v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'\nconst v4Str = `(${v4Seg}[.]){3}${v4Seg}`\nconst v6Seg = '(?:[0-9a-fA-F]{1,4})'\nconst IPv6Reg = new RegExp(\n '^(' +\n `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +\n `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +\n `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +\n `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +\n `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +\n `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +\n `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +\n `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +\n ')(%[0-9a-zA-Z-.:]{1,})?$'\n)\n\nexport function isIPv6(s: string) {\n return IPv6Reg.test(s)\n}\n","/**\n * For a given page path, this function ensures that there is a leading slash.\n * If there is not a leading slash, one is added, otherwise it is noop.\n */\nexport function ensureLeadingSlash(path: string) {\n return path.startsWith('/') ? path : `/${path}`\n}\n","import { ensureLeadingSlash } from '../../page-path/ensure-leading-slash'\nimport { isGroupSegment } from '../../segment'\n\n/**\n * Normalizes an app route so it represents the actual request path. Essentially\n * performing the following transformations:\n *\n * - `/(dashboard)/user/[id]/page` to `/user/[id]`\n * - `/(dashboard)/account/page` to `/account`\n * - `/user/[id]/page` to `/user/[id]`\n * - `/account/page` to `/account`\n * - `/page` to `/`\n * - `/(dashboard)/user/[id]/route` to `/user/[id]`\n * - `/(dashboard)/account/route` to `/account`\n * - `/user/[id]/route` to `/user/[id]`\n * - `/account/route` to `/account`\n * - `/route` to `/`\n * - `/` to `/`\n *\n * @param route the app route to normalize\n * @returns the normalized pathname\n */\nexport function normalizeAppPath(route: string) {\n return ensureLeadingSlash(\n route.split('/').reduce((pathname, segment, index, segments) => {\n // Empty segments are ignored.\n if (!segment) {\n return pathname\n }\n\n // Groups are ignored.\n if (isGroupSegment(segment)) {\n return pathname\n }\n\n // Parallel segments are ignored.\n if (segment[0] === '@') {\n return pathname\n }\n\n // The last segment (if it's a leaf) should be ignored.\n if (\n (segment === 'page' || segment === 'route') &&\n index === segments.length - 1\n ) {\n return pathname\n }\n\n return `${pathname}/${segment}`\n }, '')\n )\n}\n\n/**\n * Strips the `.rsc` extension if it's in the pathname.\n * Since this function is used on full urls it checks `?` for searchParams handling.\n */\nexport function normalizeRscURL(url: string) {\n return url.replace(\n /\\.rsc($|\\?)/,\n // $1 ensures `?` is preserved\n '$1'\n )\n}\n","import type { Segment } from '../../server/app-render/types'\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\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 const PAGE_SEGMENT_KEY = '__PAGE__'\nexport const DEFAULT_SEGMENT_KEY = '__DEFAULT__'\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 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\nexport function extractInterceptionRouteInformation(path: string) {\n let interceptingRoute: string | undefined,\n marker: (typeof INTERCEPTION_ROUTE_MARKERS)[number] | undefined,\n 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 //(..|...|..)(..)/`\n )\n }\n\n interceptingRoute = normalizeAppPath(interceptingRoute) // normalize the path, e.g. /(blog)/feed -> /feed\n\n switch (marker) {\n case '(.)':\n // (.) indicates that we should match with sibling routes, so we just need to append the intercepted route to the intercepting route\n if (interceptingRoute === '/') {\n interceptedRoute = `/${interceptedRoute}`\n } else {\n interceptedRoute = interceptingRoute + '/' + interceptedRoute\n }\n break\n case '(..)':\n // (..) indicates that we should match at one level up, so we need to remove the last segment of the intercepting route\n if (interceptingRoute === '/') {\n throw new Error(\n `Invalid interception route: ${path}. Cannot use (..) marker at the root level, use (.) instead.`\n )\n }\n interceptedRoute = interceptingRoute\n .split('/')\n .slice(0, -1)\n .concat(interceptedRoute)\n .join('/')\n break\n case '(...)':\n // (...) will match the route segment in the root directory, so we need to use the root directory to prepend the intercepted route\n interceptedRoute = '/' + interceptedRoute\n break\n case '(..)(..)':\n // (..)(..) indicates that we should match at two levels up, so we need to remove the last two segments of the intercepting route\n\n const splitInterceptingRoute = interceptingRoute.split('/')\n if (splitInterceptingRoute.length <= 2) {\n throw new Error(\n `Invalid interception route: ${path}. Cannot use (..)(..) marker at the root level or one level up.`\n )\n }\n\n interceptedRoute = splitInterceptingRoute\n .slice(0, -2)\n .concat(interceptedRoute)\n .join('/')\n break\n default:\n throw new Error('Invariant: unexpected marker')\n }\n\n return { interceptingRoute, interceptedRoute }\n}\n","import {\n extractInterceptionRouteInformation,\n isInterceptionRouteAppPath,\n} from './interception-routes'\n\n// Identify /.*[param].*/ in route string\nconst TEST_ROUTE = /\\/[^/]*\\[[^/]+\\][^/]*(?=\\/|$)/\n\n// Identify /[param]/ in route string\nconst TEST_STRICT_ROUTE = /\\/\\[[^/]+\\](?=\\/|$)/\n\n/**\n * Check if a route is dynamic.\n *\n * @param route - The route to check.\n * @param strict - Whether to use strict mode which prohibits segments with prefixes/suffixes (default: true).\n * @returns Whether the route is dynamic.\n */\nexport function isDynamicRoute(route: string, strict: boolean = true): boolean {\n if (isInterceptionRouteAppPath(route)) {\n route = extractInterceptionRouteInformation(route).interceptedRoute\n }\n\n if (strict) {\n return TEST_STRICT_ROUTE.test(route)\n }\n\n return TEST_ROUTE.test(route)\n}\n","// This regex contains the bots that we need to do a blocking render for and can't safely stream the response\n// due to how they parse the DOM. For example, they might explicitly check for metadata in the `head` tag, so we can't stream metadata tags after the `head` was sent.\n// Note: The pattern [\\w-]+-Google captures all Google crawlers with \"-Google\" suffix (e.g., Mediapartners-Google, AdsBot-Google, Storebot-Google)\n// as well as crawlers starting with \"Google-\" (e.g., Google-PageRenderer, Google-InspectionTool)\nexport const HTML_LIMITED_BOT_UA_RE =\n /[\\w-]+-Google|Google-[\\w-]+|Chrome-Lighthouse|Slurp|DuckDuckBot|baiduspider|yandex|sogou|bitlybot|tumblr|vkShare|quora link preview|redditbot|ia_archiver|Bingbot|BingPreview|applebot|facebookexternalhit|facebookcatalog|Twitterbot|LinkedInBot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|Yeti|googleweblight/i\n","import { HTML_LIMITED_BOT_UA_RE } from './html-bots'\n\n// Bot crawler that will spin up a headless browser and execute JS.\n// Only the main Googlebot search crawler executes JavaScript, not other Google crawlers.\n// x-ref: https://developers.google.com/search/docs/crawling-indexing/google-common-crawlers\n// This regex specifically matches \"Googlebot\" but NOT \"Mediapartners-Google\", \"AdsBot-Google\", etc.\nconst HEADLESS_BROWSER_BOT_UA_RE = /Googlebot(?!-)|Googlebot$/i\n\nexport const HTML_LIMITED_BOT_UA_RE_STRING = HTML_LIMITED_BOT_UA_RE.source\n\nexport { HTML_LIMITED_BOT_UA_RE }\n\nfunction isDomBotUA(userAgent: string) {\n return HEADLESS_BROWSER_BOT_UA_RE.test(userAgent)\n}\n\nfunction isHtmlLimitedBotUA(userAgent: string) {\n return HTML_LIMITED_BOT_UA_RE.test(userAgent)\n}\n\nexport function isBot(userAgent: string): boolean {\n return isDomBotUA(userAgent) || isHtmlLimitedBotUA(userAgent)\n}\n\nexport function getBotType(userAgent: string): 'dom' | 'html' | undefined {\n if (isDomBotUA(userAgent)) {\n return 'dom'\n }\n if (isHtmlLimitedBotUA(userAgent)) {\n return 'html'\n }\n return undefined\n}\n","import type { ReactDOMServerReadableStream } from 'react-dom/server'\nimport { getTracer } from '../lib/trace/tracer'\nimport { AppRenderSpan } from '../lib/trace/constants'\nimport { DetachedPromise } from '../../lib/detached-promise'\nimport { scheduleImmediate, atLeastOneTask } 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 { insertBuildIdComment } from '../../shared/lib/segment-cache/output-export-prefetch-encoding'\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(\n ...streams: ReadableStream[]\n): ReadableStream {\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({\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 {\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 {\n return new ReadableStream({\n start(controller) {\n controller.enqueue(chunk)\n controller.close()\n },\n })\n}\n\nexport async function streamToBuffer(\n stream: ReadableStream\n): Promise {\n const reader = stream.getReader()\n const chunks: 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 Buffer.concat(chunks)\n}\n\nexport async function streamToString(\n stream: ReadableStream,\n signal?: AbortSignal\n): Promise {\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 function createBufferedTransformStream(): TransformStream<\n Uint8Array,\n Uint8Array\n> {\n let bufferedChunks: Array = []\n let bufferByteLength: number = 0\n let pending: DetachedPromise | undefined\n\n const flush = (controller: TransformStreamDefaultController) => {\n // If we already have a pending flush, then return early.\n if (pending) return\n\n const detached = new DetachedPromise()\n pending = detached\n\n scheduleImmediate(() => {\n try {\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 // 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 // Combine the previous buffer with the new chunk.\n bufferedChunks.push(chunk)\n bufferByteLength += chunk.byteLength\n\n // Flush the buffer to the controller.\n flush(controller)\n },\n flush() {\n if (!pending) return\n\n return pending.promise\n },\n })\n}\n\nfunction createPrefetchCommentStream(\n isBuildTimePrerendering: boolean,\n buildId: string\n): TransformStream {\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[1]\n}): Promise {\n return getTracer().trace(AppRenderSpan.renderToReadableStream, async () =>\n ReactDOMServer.renderToReadableStream(element, streamOptions)\n )\n}\n\nfunction createMetadataTransformStream(\n insert: () => Promise | string\n): TransformStream {\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 `` 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 tag in the first chunk.\n if (chunkIndex === 0) {\n closedHeadIndex = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.HEAD)\n if (iconMarkIndex !== -1) {\n // The mark icon is located in the 1st chunk before the head tag.\n // We do not need to insert the script tag in this case because it's in the head.\n // Just remove the icon mark from the chunk.\n if (iconMarkIndex < closedHeadIndex) {\n const replaced = new Uint8Array(chunk.length - iconMarkLength)\n\n // Remove the icon mark from the chunk.\n replaced.set(chunk.subarray(0, iconMarkIndex))\n replaced.set(\n chunk.subarray(iconMarkIndex + iconMarkLength),\n iconMarkIndex\n )\n chunk = replaced\n } else {\n // The icon mark is after the head tag, replace and insert the script tag at that position.\n const insertion = await insert()\n const encodedInsertion = encoder.encode(insertion)\n const insertionLength = encodedInsertion.length\n const replaced = new Uint8Array(\n chunk.length - iconMarkLength + insertionLength\n )\n replaced.set(chunk.subarray(0, iconMarkIndex))\n replaced.set(encodedInsertion, iconMarkIndex)\n replaced.set(\n chunk.subarray(iconMarkIndex + iconMarkLength),\n iconMarkIndex + insertionLength\n )\n chunk = replaced\n }\n isMarkRemoved = true\n }\n // If there's no icon mark located, it will be handled later when if present in the following chunks.\n } else {\n // When it's appeared in the following chunks, we'll need to\n // remove the mark and then insert the script tag at that position.\n const insertion = await insert()\n const encodedInsertion = encoder.encode(insertion)\n const insertionLength = encodedInsertion.length\n // Replace the icon mark with the hoist script or empty string.\n const replaced = new Uint8Array(\n chunk.length - iconMarkLength + insertionLength\n )\n // Set the first part of the chunk, before the icon mark.\n replaced.set(chunk.subarray(0, iconMarkIndex))\n // Set the insertion after the icon mark.\n replaced.set(encodedInsertion, iconMarkIndex)\n\n // Set the rest of the chunk after the icon mark.\n replaced.set(\n chunk.subarray(iconMarkIndex + iconMarkLength),\n iconMarkIndex + insertionLength\n )\n chunk = replaced\n isMarkRemoved = true\n }\n controller.enqueue(chunk)\n },\n })\n}\n\nfunction createHeadInsertionTransformStream(\n insert: () => Promise\n): TransformStream {\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 = \n // insertion = \n // output = [ ] \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: ... [ resume content ] \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\n// Suffix after main body content - scripts before ,\n// but wait for the major chunks to be enqueued.\nfunction createDeferredSuffixStream(\n suffix: string\n): TransformStream {\n let flushed = false\n let pending: DetachedPromise | undefined\n\n const flush = (controller: TransformStreamDefaultController) => {\n const detached = new DetachedPromise()\n pending = detached\n\n scheduleImmediate(() => {\n try {\n controller.enqueue(encoder.encode(suffix))\n } catch {\n // If an error occurs while enqueuing it can't be due to this\n // transformers fault. It's likely due to the controller being\n // errored due to the stream being cancelled.\n } finally {\n pending = undefined\n detached.resolve()\n }\n })\n }\n\n return new TransformStream({\n transform(chunk, controller) {\n controller.enqueue(chunk)\n\n // If we've already flushed, we're done.\n if (flushed) return\n\n // Schedule the flush to happen.\n flushed = true\n flush(controller)\n },\n flush(controller) {\n if (pending) return pending.promise\n if (flushed) return\n\n // Flush now.\n controller.enqueue(encoder.encode(suffix))\n },\n })\n}\n\nfunction createFlightDataInjectionTransformStream(\n stream: ReadableStream,\n delayDataUntilFirstHtmlChunk: boolean\n): TransformStream {\n let htmlStreamFinished = false\n\n let pull: Promise | null = null\n let donePulling = false\n\n function startOrContinuePulling(\n controller: TransformStreamDefaultController\n ) {\n if (!pull) {\n pull = startPulling(controller)\n }\n return pull\n }\n\n async function startPulling(controller: TransformStreamDefaultController) {\n const reader = stream.getReader()\n\n if (delayDataUntilFirstHtmlChunk) {\n // NOTE: streaming flush\n // We are buffering here for the inlined data stream because the\n // \"shell\" stream might be chunkenized again by the underlying stream\n // implementation, e.g. with a specific high-water mark. To ensure it's\n // the safe timing to pipe the data stream, this extra tick is\n // necessary.\n\n // We don't start reading until we've left the current Task to ensure\n // that it's inserted after flushing the shell. Note that this implementation\n // might get stale if impl details of Fizz change in the future.\n await atLeastOneTask()\n }\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) {\n donePulling = true\n return\n }\n\n // We want to prioritize HTML over RSC data.\n // The SSR render is based on the same RSC stream, so when we get a new RSC chunk,\n // we're likely to produce an HTML chunk as well, so give it a chance to flush first.\n if (!delayDataUntilFirstHtmlChunk && !htmlStreamFinished) {\n await atLeastOneTask()\n }\n controller.enqueue(value)\n }\n } catch (err) {\n controller.error(err)\n }\n }\n\n return new TransformStream({\n start(controller) {\n if (!delayDataUntilFirstHtmlChunk) {\n startOrContinuePulling(controller)\n }\n },\n transform(chunk, controller) {\n controller.enqueue(chunk)\n\n // Start the streaming if it hasn't already been started yet.\n if (delayDataUntilFirstHtmlChunk) {\n startOrContinuePulling(controller)\n }\n },\n flush(controller) {\n htmlStreamFinished = true\n if (donePulling) {\n return\n }\n return startOrContinuePulling(controller)\n },\n })\n}\n\nconst CLOSE_TAG = ''\n\n/**\n * This transform stream moves the suffix to the end of the stream, so results\n * like `` will be transformed to\n * ``.\n */\nfunction createMoveSuffixStream(): TransformStream {\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\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 `\n `<${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 >\n `\n )\n )\n },\n })\n}\n\nfunction chainTransformers(\n readable: ReadableStream,\n transformers: ReadonlyArray | null>\n): ReadableStream {\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 | undefined\n isStaticGeneration: boolean\n isBuildTimePrerendering: boolean\n buildId: string\n getServerInsertedHTML: () => Promise\n getServerInsertedMetadata: () => Promise\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 isBuildTimePrerendering,\n buildId,\n getServerInsertedHTML,\n getServerInsertedMetadata,\n validateRootLayout,\n }: ContinueStreamOptions\n): Promise> {\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 we're generating static HTML we need to wait for it to resolve before continuing.\n if (isStaticGeneration) {\n await renderStream.allReady\n }\n\n return chainTransformers(renderStream, [\n // Buffer everything to avoid flushing too frequently\n createBufferedTransformStream(),\n\n // Add build id comment to start of the HTML document (in export mode)\n createPrefetchCommentStream(isBuildTimePrerendering, buildId),\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\n getServerInsertedMetadata: () => Promise\n}\n\nexport async function continueDynamicPrerender(\n prerenderStream: ReadableStream,\n {\n getServerInsertedHTML,\n getServerInsertedMetadata,\n }: ContinueDynamicPrerenderOptions\n) {\n return (\n prerenderStream\n // Buffer everything to avoid flushing too frequently\n .pipeThrough(createBufferedTransformStream())\n .pipeThrough(createStripDocumentClosingTagsTransform())\n // Insert generated tags to head\n .pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML))\n // Transform metadata\n .pipeThrough(createMetadataTransformStream(getServerInsertedMetadata))\n )\n}\n\ntype ContinueStaticPrerenderOptions = {\n inlinedDataStream: ReadableStream\n getServerInsertedHTML: () => Promise\n getServerInsertedMetadata: () => Promise\n isBuildTimePrerendering: boolean\n buildId: string\n}\n\nexport async function continueStaticPrerender(\n prerenderStream: ReadableStream,\n {\n inlinedDataStream,\n getServerInsertedHTML,\n getServerInsertedMetadata,\n isBuildTimePrerendering,\n buildId,\n }: ContinueStaticPrerenderOptions\n) {\n return (\n prerenderStream\n // Buffer everything to avoid flushing too frequently\n .pipeThrough(createBufferedTransformStream())\n // Add build id comment to start of the HTML document (in export mode)\n .pipeThrough(\n createPrefetchCommentStream(isBuildTimePrerendering, buildId)\n )\n // Insert generated tags to head\n .pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML))\n // Transform metadata\n .pipeThrough(createMetadataTransformStream(getServerInsertedMetadata))\n // Insert the inlined data (Flight data, form state, etc.) stream into the HTML\n .pipeThrough(\n createFlightDataInjectionTransformStream(inlinedDataStream, true)\n )\n // Close tags should always be deferred to the end\n .pipeThrough(createMoveSuffixStream())\n )\n}\n\ntype ContinueResumeOptions = {\n inlinedDataStream: ReadableStream\n getServerInsertedHTML: () => Promise\n getServerInsertedMetadata: () => Promise\n delayDataUntilFirstHtmlChunk: boolean\n}\n\nexport async function continueDynamicHTMLResume(\n renderStream: ReadableStream,\n {\n delayDataUntilFirstHtmlChunk,\n inlinedDataStream,\n getServerInsertedHTML,\n getServerInsertedMetadata,\n }: ContinueResumeOptions\n) {\n return (\n renderStream\n // Buffer everything to avoid flushing too frequently\n .pipeThrough(createBufferedTransformStream())\n // Insert generated tags to head\n .pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML))\n // Transform metadata\n .pipeThrough(createMetadataTransformStream(getServerInsertedMetadata))\n // Insert the inlined data (Flight data, form state, etc.) stream into the HTML\n .pipeThrough(\n createFlightDataInjectionTransformStream(\n inlinedDataStream,\n delayDataUntilFirstHtmlChunk\n )\n )\n // Close tags should always be deferred to the end\n .pipeThrough(createMoveSuffixStream())\n )\n}\n\nexport function createDocumentClosingStream(): ReadableStream {\n return streamFromString(CLOSE_TAG)\n}\n","export const ENCODED_TAGS = {\n // opening tags do not have the closing `>` since they can contain other attributes such as ``\n OPENING: {\n // \n HEAD: new Uint8Array([60, 47, 104, 101, 97, 100, 62]),\n // \n BODY: new Uint8Array([60, 47, 98, 111, 100, 121, 62]),\n // \n HTML: new Uint8Array([60, 47, 104, 116, 109, 108, 62]),\n // \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 // = cookiesString.length) {\n cookiesStrings.push(cookiesString.substring(start, cookiesString.length))\n }\n }\n\n return cookiesStrings\n}\n\n/**\n * Converts a Headers object to a Node.js OutgoingHttpHeaders object. This is\n * required to support the set-cookie header, which may have multiple values.\n *\n * @param headers the headers object to convert\n * @returns the converted headers object\n */\nexport function toNodeOutgoingHttpHeaders(\n headers: Headers\n): OutgoingHttpHeaders {\n const nodeHeaders: OutgoingHttpHeaders = {}\n const cookies: string[] = []\n if (headers) {\n for (const [key, value] of headers.entries()) {\n if (key.toLowerCase() === 'set-cookie') {\n // We may have gotten a comma joined string of cookies, or multiple\n // set-cookie headers. We need to merge them into one header array\n // to represent all the cookies.\n cookies.push(...splitCookiesString(value))\n nodeHeaders[key] = cookies.length === 1 ? cookies[0] : cookies\n } else {\n nodeHeaders[key] = value\n }\n }\n }\n return nodeHeaders\n}\n\n/**\n * Validate the correctness of a user-provided URL.\n */\nexport function validateURL(url: string | URL): string {\n try {\n return String(new URL(String(url)))\n } catch (error: any) {\n throw new Error(\n `URL is malformed \"${String(\n url\n )}\". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`,\n { cause: error }\n )\n }\n}\n\n/**\n * Normalizes `nxtP` and `nxtI` query param values to remove the prefix.\n * This function does not mutate the input key.\n */\nexport function normalizeNextQueryParam(key: string): null | string {\n const prefixes = [NEXT_QUERY_PARAM_PREFIX, NEXT_INTERCEPTION_MARKER_PREFIX]\n for (const prefix of prefixes) {\n if (key !== prefix && key.startsWith(prefix)) {\n return key.substring(prefix.length)\n }\n }\n return null\n}\n","/**\n * Removes the trailing slash for a given route or page path. Preserves the\n * root page. Examples:\n * - `/foo/bar/` -> `/foo/bar`\n * - `/foo/bar` -> `/foo/bar`\n * - `/` -> `/`\n */\nexport function removeTrailingSlash(route: string) {\n return route.replace(/\\/$/, '') || '/'\n}\n","/**\n * Given a path this function will find the pathname, query and hash and return\n * them. This is useful to parse full paths on the client side.\n * @param path A path to parse e.g. /foo/bar?id=1#hash\n */\nexport function parsePath(path: string) {\n const hashIndex = path.indexOf('#')\n const queryIndex = path.indexOf('?')\n const hasQuery = queryIndex > -1 && (hashIndex < 0 || queryIndex < hashIndex)\n\n if (hasQuery || hashIndex > -1) {\n return {\n pathname: path.substring(0, hasQuery ? queryIndex : hashIndex),\n query: hasQuery\n ? path.substring(queryIndex, hashIndex > -1 ? hashIndex : undefined)\n : '',\n hash: hashIndex > -1 ? path.slice(hashIndex) : '',\n }\n }\n\n return { pathname: path, query: '', hash: '' }\n}\n","import { parsePath } from './parse-path'\n\n/**\n * Adds the provided prefix to the given path. It first ensures that the path\n * is indeed starting with a slash.\n */\nexport function addPathPrefix(path: string, prefix?: string) {\n if (!path.startsWith('/') || !prefix) {\n return path\n }\n\n const { pathname, query, hash } = parsePath(path)\n return `${prefix}${pathname}${query}${hash}`\n}\n","import { parsePath } from './parse-path'\n\n/**\n * Similarly to `addPathPrefix`, this function adds a suffix at the end on the\n * provided path. It also works only for paths ensuring the argument starts\n * with a slash.\n */\nexport function addPathSuffix(path: string, suffix?: string) {\n if (!path.startsWith('/') || !suffix) {\n return path\n }\n\n const { pathname, query, hash } = parsePath(path)\n return `${pathname}${suffix}${query}${hash}`\n}\n","import { parsePath } from './parse-path'\n\n/**\n * Checks if a given path starts with a given prefix. It ensures it matches\n * exactly without containing extra chars. e.g. prefix /docs should replace\n * for /docs, /docs/, /docs/a but not /docsss\n * @param path The path to check.\n * @param prefix The prefix to check against.\n */\nexport function pathHasPrefix(path: string, prefix: string) {\n if (typeof path !== 'string') {\n return false\n }\n\n const { pathname } = parsePath(path)\n return pathname === prefix || pathname.startsWith(prefix + '/')\n}\n","import type { OutgoingHttpHeaders } from 'http'\n\n/**\n * Takes an object with a hostname property (like a parsed URL) and some\n * headers that may contain Host and returns the preferred hostname.\n * @param parsed An object containing a hostname property.\n * @param headers A dictionary with headers containing a `host`.\n */\nexport function getHostname(\n parsed: { hostname?: string | null },\n headers?: OutgoingHttpHeaders\n): string | undefined {\n // Get the hostname from the headers if it exists, otherwise use the parsed\n // hostname.\n let hostname: string\n if (headers?.host && !Array.isArray(headers.host)) {\n hostname = headers.host.toString().split(':', 1)[0]\n } else if (parsed.hostname) {\n hostname = parsed.hostname\n } else return\n\n return hostname.toLowerCase()\n}\n","export interface PathLocale {\n detectedLocale?: string\n pathname: string\n}\n\n/**\n * A cache of lowercased locales for each list of locales. This is stored as a\n * WeakMap so if the locales are garbage collected, the cache entry will be\n * removed as well.\n */\nconst cache = new WeakMap()\n\n/**\n * For a pathname that may include a locale from a list of locales, it\n * removes the locale from the pathname returning it alongside with the\n * detected locale.\n *\n * @param pathname A pathname that may include a locale.\n * @param locales A list of locales.\n * @returns The detected locale and pathname without locale\n */\nexport function normalizeLocalePath(\n pathname: string,\n locales?: readonly string[]\n): PathLocale {\n // If locales is undefined, return the pathname as is.\n if (!locales) return { pathname }\n\n // Get the cached lowercased locales or create a new cache entry.\n let lowercasedLocales = cache.get(locales)\n if (!lowercasedLocales) {\n lowercasedLocales = locales.map((locale) => locale.toLowerCase())\n cache.set(locales, lowercasedLocales)\n }\n\n let detectedLocale: string | undefined\n\n // The first segment will be empty, because it has a leading `/`. If\n // there is no further segment, there is no locale (or it's the default).\n const segments = pathname.split('/', 2)\n\n // If there's no second segment (ie, the pathname is just `/`), there's no\n // locale.\n if (!segments[1]) return { pathname }\n\n // The second segment will contain the locale part if any.\n const segment = segments[1].toLowerCase()\n\n // See if the segment matches one of the locales. If it doesn't, there is\n // no locale (or it's the default).\n const index = lowercasedLocales.indexOf(segment)\n if (index < 0) return { pathname }\n\n // Return the case-sensitive locale.\n detectedLocale = locales[index]\n\n // Remove the `/${locale}` part of the pathname.\n pathname = pathname.slice(detectedLocale.length + 1) || '/'\n\n return { pathname, detectedLocale }\n}\n","import { pathHasPrefix } from './path-has-prefix'\n\n/**\n * Given a path and a prefix it will remove the prefix when it exists in the\n * given path. It ensures it matches exactly without containing extra chars\n * and if the prefix is not there it will be noop.\n *\n * @param path The path to remove the prefix from.\n * @param prefix The prefix to be removed.\n */\nexport function removePathPrefix(path: string, prefix: string): string {\n // If the path doesn't start with the prefix we can return it as is. This\n // protects us from situations where the prefix is a substring of the path\n // prefix such as:\n //\n // For prefix: /blog\n //\n // /blog -> true\n // /blog/ -> true\n // /blog/1 -> true\n // /blogging -> false\n // /blogging/ -> false\n // /blogging/1 -> false\n if (!pathHasPrefix(path, prefix)) {\n return path\n }\n\n // Remove the prefix from the path via slicing.\n const withoutPrefix = path.slice(prefix.length)\n\n // If the path without the prefix starts with a `/` we can return it as is.\n if (withoutPrefix.startsWith('/')) {\n return withoutPrefix\n }\n\n // If the path without the prefix doesn't start with a `/` we need to add it\n // back to the path to make sure it's a valid path.\n return `/${withoutPrefix}`\n}\n","import { normalizeLocalePath } from '../../i18n/normalize-locale-path'\nimport { removePathPrefix } from './remove-path-prefix'\nimport { pathHasPrefix } from './path-has-prefix'\nimport type { I18NProvider } from '../../../../server/lib/i18n-provider'\n\nexport interface NextPathnameInfo {\n /**\n * The base path in case the pathname included it.\n */\n basePath?: string\n /**\n * The buildId for when the parsed URL is a data URL. Parsing it can be\n * disabled with the `parseData` option.\n */\n buildId?: string\n /**\n * If there was a locale in the pathname, this will hold its value.\n */\n locale?: string\n /**\n * The processed pathname without a base path, locale, or data URL elements\n * when parsing it is enabled.\n */\n pathname: string\n /**\n * A boolean telling if the pathname had a trailingSlash. This can be only\n * true if trailingSlash is enabled.\n */\n trailingSlash?: boolean\n}\n\ninterface Options {\n /**\n * When passed to true, this function will also parse Nextjs data URLs.\n */\n parseData?: boolean\n /**\n * A partial of the Next.js configuration to parse the URL.\n */\n nextConfig?: {\n basePath?: string\n i18n?: { locales?: readonly string[] } | null\n trailingSlash?: boolean\n }\n\n /**\n * If provided, this normalizer will be used to detect the locale instead of\n * the default locale detection.\n */\n i18nProvider?: I18NProvider\n}\n\nexport function getNextPathnameInfo(\n pathname: string,\n options: Options\n): NextPathnameInfo {\n const { basePath, i18n, trailingSlash } = options.nextConfig ?? {}\n const info: NextPathnameInfo = {\n pathname,\n trailingSlash: pathname !== '/' ? pathname.endsWith('/') : trailingSlash,\n }\n\n if (basePath && pathHasPrefix(info.pathname, basePath)) {\n info.pathname = removePathPrefix(info.pathname, basePath)\n info.basePath = basePath\n }\n let pathnameNoDataPrefix = info.pathname\n\n if (\n info.pathname.startsWith('/_next/data/') &&\n info.pathname.endsWith('.json')\n ) {\n const paths = info.pathname\n .replace(/^\\/_next\\/data\\//, '')\n .replace(/\\.json$/, '')\n .split('/')\n\n const buildId = paths[0]\n info.buildId = buildId\n pathnameNoDataPrefix =\n paths[1] !== 'index' ? `/${paths.slice(1).join('/')}` : '/'\n\n // update pathname with normalized if enabled although\n // we use normalized to populate locale info still\n if (options.parseData === true) {\n info.pathname = pathnameNoDataPrefix\n }\n }\n\n // If provided, use the locale route normalizer to detect the locale instead\n // of the function below.\n if (i18n) {\n let result = options.i18nProvider\n ? options.i18nProvider.analyze(info.pathname)\n : normalizeLocalePath(info.pathname, i18n.locales)\n\n info.locale = result.detectedLocale\n info.pathname = result.pathname ?? info.pathname\n\n if (!result.detectedLocale && info.buildId) {\n result = options.i18nProvider\n ? options.i18nProvider.analyze(pathnameNoDataPrefix)\n : normalizeLocalePath(pathnameNoDataPrefix, i18n.locales)\n\n if (result.detectedLocale) {\n info.locale = result.detectedLocale\n }\n }\n }\n return info\n}\n","import type { OutgoingHttpHeaders } from 'http'\nimport type { DomainLocale, I18NConfig } from '../config-shared'\nimport type { I18NProvider } from '../lib/i18n-provider'\n\nimport { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale'\nimport { formatNextPathnameInfo } from '../../shared/lib/router/utils/format-next-pathname-info'\nimport { getHostname } from '../../shared/lib/get-hostname'\nimport { getNextPathnameInfo } from '../../shared/lib/router/utils/get-next-pathname-info'\n\ninterface Options {\n base?: string | URL\n headers?: OutgoingHttpHeaders\n forceLocale?: boolean\n nextConfig?: {\n basePath?: string\n i18n?: I18NConfig | null\n trailingSlash?: boolean\n }\n i18nProvider?: I18NProvider\n}\n\nconst REGEX_LOCALHOST_HOSTNAME =\n /(?!^https?:\\/\\/)(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 return new URL(\n String(url).replace(REGEX_LOCALHOST_HOSTNAME, 'localhost'),\n base && String(base).replace(REGEX_LOCALHOST_HOSTNAME, 'localhost')\n )\n}\n\nconst Internal = Symbol('NextURLInternal')\n\nexport class NextURL {\n private [Internal]: {\n basePath: string\n buildId?: string\n flightSearchParameters?: Record\n defaultLocale?: string\n domainLocale?: DomainLocale\n locale?: string\n options: Options\n trailingSlash?: boolean\n url: URL\n }\n\n constructor(input: string | URL, base?: string | URL, opts?: Options)\n constructor(input: string | URL, opts?: Options)\n constructor(\n input: string | URL,\n baseOrOpts?: string | URL | Options,\n opts?: Options\n ) {\n let base: undefined | string | URL\n let options: Options\n\n if (\n (typeof baseOrOpts === 'object' && 'pathname' in baseOrOpts) ||\n typeof baseOrOpts === 'string'\n ) {\n base = baseOrOpts\n options = opts || {}\n } else {\n options = opts || baseOrOpts || {}\n }\n\n this[Internal] = {\n url: parseURL(input, base ?? options.base),\n options: options,\n basePath: '',\n }\n\n this.analyze()\n }\n\n private analyze() {\n const info = getNextPathnameInfo(this[Internal].url.pathname, {\n nextConfig: this[Internal].options.nextConfig,\n parseData: !process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE,\n i18nProvider: this[Internal].options.i18nProvider,\n })\n\n const hostname = getHostname(\n this[Internal].url,\n this[Internal].options.headers\n )\n this[Internal].domainLocale = this[Internal].options.i18nProvider\n ? this[Internal].options.i18nProvider.detectDomainLocale(hostname)\n : detectDomainLocale(\n this[Internal].options.nextConfig?.i18n?.domains,\n hostname\n )\n\n const defaultLocale =\n this[Internal].domainLocale?.defaultLocale ||\n this[Internal].options.nextConfig?.i18n?.defaultLocale\n\n this[Internal].url.pathname = info.pathname\n this[Internal].defaultLocale = defaultLocale\n this[Internal].basePath = info.basePath ?? ''\n this[Internal].buildId = info.buildId\n this[Internal].locale = info.locale ?? defaultLocale\n this[Internal].trailingSlash = info.trailingSlash\n }\n\n private formatPathname() {\n return formatNextPathnameInfo({\n basePath: this[Internal].basePath,\n buildId: this[Internal].buildId,\n defaultLocale: !this[Internal].options.forceLocale\n ? this[Internal].defaultLocale\n : undefined,\n locale: this[Internal].locale,\n pathname: this[Internal].url.pathname,\n trailingSlash: this[Internal].trailingSlash,\n })\n }\n\n private formatSearch() {\n return this[Internal].url.search\n }\n\n public get buildId() {\n return this[Internal].buildId\n }\n\n public set buildId(buildId: string | undefined) {\n this[Internal].buildId = buildId\n }\n\n public get locale() {\n return this[Internal].locale ?? ''\n }\n\n public set locale(locale: string) {\n if (\n !this[Internal].locale ||\n !this[Internal].options.nextConfig?.i18n?.locales.includes(locale)\n ) {\n throw new TypeError(\n `The NextURL configuration includes no locale \"${locale}\"`\n )\n }\n\n this[Internal].locale = locale\n }\n\n get defaultLocale() {\n return this[Internal].defaultLocale\n }\n\n get domainLocale() {\n return this[Internal].domainLocale\n }\n\n get searchParams() {\n return this[Internal].url.searchParams\n }\n\n get host() {\n return this[Internal].url.host\n }\n\n set host(value: string) {\n this[Internal].url.host = value\n }\n\n get hostname() {\n return this[Internal].url.hostname\n }\n\n set hostname(value: string) {\n this[Internal].url.hostname = value\n }\n\n get port() {\n return this[Internal].url.port\n }\n\n set port(value: string) {\n this[Internal].url.port = value\n }\n\n get protocol() {\n return this[Internal].url.protocol\n }\n\n set protocol(value: string) {\n this[Internal].url.protocol = value\n }\n\n get href() {\n const pathname = this.formatPathname()\n const search = this.formatSearch()\n return `${this.protocol}//${this.host}${pathname}${search}${this.hash}`\n }\n\n set href(url: string) {\n this[Internal].url = parseURL(url)\n this.analyze()\n }\n\n get origin() {\n return this[Internal].url.origin\n }\n\n get pathname() {\n return this[Internal].url.pathname\n }\n\n set pathname(value: string) {\n this[Internal].url.pathname = value\n }\n\n get hash() {\n return this[Internal].url.hash\n }\n\n set hash(value: string) {\n this[Internal].url.hash = value\n }\n\n get search() {\n return this[Internal].url.search\n }\n\n set search(value: string) {\n this[Internal].url.search = value\n }\n\n get password() {\n return this[Internal].url.password\n }\n\n set password(value: string) {\n this[Internal].url.password = value\n }\n\n get username() {\n return this[Internal].url.username\n }\n\n set username(value: string) {\n this[Internal].url.username = value\n }\n\n get basePath() {\n return this[Internal].basePath\n }\n\n set basePath(value: string) {\n this[Internal].basePath = value.startsWith('/') ? value : `/${value}`\n }\n\n toString() {\n return this.href\n }\n\n toJSON() {\n return this.href\n }\n\n [Symbol.for('edge-runtime.inspect.custom')]() {\n return {\n href: this.href,\n origin: this.origin,\n protocol: this.protocol,\n username: this.username,\n password: this.password,\n host: this.host,\n hostname: this.hostname,\n port: this.port,\n pathname: this.pathname,\n search: this.search,\n searchParams: this.searchParams,\n hash: this.hash,\n }\n }\n\n clone() {\n return new NextURL(String(this), this[Internal].options)\n }\n}\n","import type { DomainLocale } from '../../../server/config-shared'\n\nexport function detectDomainLocale(\n domainItems?: readonly DomainLocale[],\n hostname?: string,\n detectedLocale?: string\n) {\n if (!domainItems) return\n\n if (detectedLocale) {\n detectedLocale = detectedLocale.toLowerCase()\n }\n\n for (const item of domainItems) {\n // remove port if present\n const domainHostname = item.domain?.split(':', 1)[0].toLowerCase()\n if (\n hostname === domainHostname ||\n detectedLocale === item.defaultLocale.toLowerCase() ||\n item.locales?.some((locale) => locale.toLowerCase() === detectedLocale)\n ) {\n return item\n }\n }\n}\n","import type { NextPathnameInfo } from './get-next-pathname-info'\nimport { removeTrailingSlash } from './remove-trailing-slash'\nimport { addPathPrefix } from './add-path-prefix'\nimport { addPathSuffix } from './add-path-suffix'\nimport { addLocale } from './add-locale'\n\ninterface ExtendedInfo extends NextPathnameInfo {\n defaultLocale?: string\n ignorePrefix?: boolean\n}\n\nexport function formatNextPathnameInfo(info: ExtendedInfo) {\n let pathname = addLocale(\n info.pathname,\n info.locale,\n info.buildId ? undefined : info.defaultLocale,\n info.ignorePrefix\n )\n\n if (info.buildId || !info.trailingSlash) {\n pathname = removeTrailingSlash(pathname)\n }\n\n if (info.buildId) {\n pathname = addPathSuffix(\n addPathPrefix(pathname, `/_next/data/${info.buildId}`),\n info.pathname === '/' ? 'index.json' : '.json'\n )\n }\n\n pathname = addPathPrefix(pathname, info.basePath)\n return !info.buildId && info.trailingSlash\n ? !pathname.endsWith('/')\n ? addPathSuffix(pathname, '/')\n : pathname\n : removeTrailingSlash(pathname)\n}\n","import { addPathPrefix } from './add-path-prefix'\nimport { pathHasPrefix } from './path-has-prefix'\n\n/**\n * For a given path and a locale, if the locale is given, it will prefix the\n * locale. The path shouldn't be an API path. If a default locale is given the\n * prefix will be omitted if the locale is already the default locale.\n */\nexport function addLocale(\n path: string,\n locale?: string | false,\n defaultLocale?: string,\n ignorePrefix?: boolean\n) {\n // If no locale was given or the locale is the default locale, we don't need\n // to prefix the path.\n if (!locale || locale === defaultLocale) return path\n\n const lower = path.toLowerCase()\n\n // If the path is an API path or the path already has the locale prefix, we\n // don't need to prefix the path.\n if (!ignorePrefix) {\n if (pathHasPrefix(lower, '/api')) return path\n if (pathHasPrefix(lower, `/${locale.toLowerCase()}`)) return path\n }\n\n // Add the locale prefix to the path.\n return addPathPrefix(path, `/${locale}`)\n}\n","export class PageSignatureError extends Error {\n constructor({ page }: { page: string }) {\n super(`The middleware \"${page}\" accepts an async API directly with the form:\n \n export function middleware(request, event) {\n return NextResponse.redirect('/new-location')\n }\n \n Read more: https://nextjs.org/docs/messages/middleware-new-signature\n `)\n }\n}\n\nexport class RemovedPageError extends Error {\n constructor() {\n super(`The request.page has been deprecated in favour of \\`URLPattern\\`.\n Read more: https://nextjs.org/docs/messages/middleware-request-page\n `)\n }\n}\n\nexport class RemovedUAError extends Error {\n constructor() {\n super(`The request.ua has been removed in favour of \\`userAgent\\` function.\n Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent\n `)\n }\n}\n","import type { I18NConfig } from '../../config-shared'\nimport { NextURL } from '../next-url'\nimport { toNodeOutgoingHttpHeaders, validateURL } from '../utils'\nimport { RemovedUAError, RemovedPageError } from '../error'\nimport { RequestCookies } from './cookies'\n\nexport const INTERNALS = Symbol('internal request')\n\n/**\n * This class extends the [Web `Request` API](https://developer.mozilla.org/docs/Web/API/Request) with additional convenience methods.\n *\n * Read more: [Next.js Docs: `NextRequest`](https://nextjs.org/docs/app/api-reference/functions/next-request)\n */\nexport class NextRequest extends Request {\n /** @internal */\n [INTERNALS]: {\n cookies: RequestCookies\n url: string\n nextUrl: NextURL\n }\n\n constructor(input: URL | RequestInfo, init: RequestInit = {}) {\n const url =\n typeof input !== 'string' && 'url' in input ? input.url : String(input)\n\n validateURL(url)\n\n // node Request instance requires duplex option when a body\n // is present or it errors, we don't handle this for\n // Request being passed in since it would have already\n // errored if this wasn't configured\n if (process.env.NEXT_RUNTIME !== 'edge') {\n if (init.body && init.duplex !== 'half') {\n init.duplex = 'half'\n }\n }\n\n if (input instanceof Request) super(input, init)\n else super(url, init)\n\n const nextUrl = new NextURL(url, {\n headers: toNodeOutgoingHttpHeaders(this.headers),\n nextConfig: init.nextConfig,\n })\n this[INTERNALS] = {\n cookies: new RequestCookies(this.headers),\n nextUrl,\n url: process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE\n ? url\n : nextUrl.toString(),\n }\n }\n\n [Symbol.for('edge-runtime.inspect.custom')]() {\n return {\n cookies: this.cookies,\n nextUrl: this.nextUrl,\n url: this.url,\n // rest of props come from Request\n bodyUsed: this.bodyUsed,\n cache: this.cache,\n credentials: this.credentials,\n destination: this.destination,\n headers: Object.fromEntries(this.headers),\n integrity: this.integrity,\n keepalive: this.keepalive,\n method: this.method,\n mode: this.mode,\n redirect: this.redirect,\n referrer: this.referrer,\n referrerPolicy: this.referrerPolicy,\n signal: this.signal,\n }\n }\n\n public get cookies() {\n return this[INTERNALS].cookies\n }\n\n public get nextUrl() {\n return this[INTERNALS].nextUrl\n }\n\n /**\n * @deprecated\n * `page` has been deprecated in favour of `URLPattern`.\n * Read more: https://nextjs.org/docs/messages/middleware-request-page\n */\n public get page() {\n throw new RemovedPageError()\n }\n\n /**\n * @deprecated\n * `ua` has been removed in favour of \\`userAgent\\` function.\n * Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent\n */\n public get ua() {\n throw new RemovedUAError()\n }\n\n public get url() {\n return this[INTERNALS].url\n }\n}\n\nexport interface RequestInit extends globalThis.RequestInit {\n nextConfig?: {\n basePath?: string\n i18n?: I18NConfig | null\n trailingSlash?: boolean\n }\n signal?: AbortSignal\n // see https://github.com/whatwg/fetch/pull/1457\n duplex?: 'half'\n}\n","import type { BaseNextRequest } from '../../../base-http'\nimport type { NodeNextRequest } from '../../../base-http/node'\nimport type { WebNextRequest } from '../../../base-http/web'\nimport type { Writable } from 'node:stream'\n\nimport { getRequestMeta } from '../../../request-meta'\nimport { fromNodeOutgoingHttpHeaders } from '../../utils'\nimport { NextRequest } from '../request'\nimport { isNodeNextRequest, isWebNextRequest } from '../../../base-http/helpers'\n\nexport const ResponseAbortedName = 'ResponseAborted'\nexport class ResponseAborted extends Error {\n public readonly name = ResponseAbortedName\n}\n\n/**\n * Creates an AbortController tied to the closing of a ServerResponse (or other\n * appropriate Writable).\n *\n * If the `close` event is fired before the `finish` event, then we'll send the\n * `abort` signal.\n */\nexport function createAbortController(response: Writable): AbortController {\n const controller = new AbortController()\n\n // If `finish` fires first, then `res.end()` has been called and the close is\n // just us finishing the stream on our side. If `close` fires first, then we\n // know the client disconnected before we finished.\n response.once('close', () => {\n if (response.writableFinished) return\n\n controller.abort(new ResponseAborted())\n })\n\n return controller\n}\n\n/**\n * Creates an AbortSignal tied to the closing of a ServerResponse (or other\n * appropriate Writable).\n *\n * This cannot be done with the request (IncomingMessage or Readable) because\n * the `abort` event will not fire if to data has been fully read (because that\n * will \"close\" the readable stream and nothing fires after that).\n */\nexport function signalFromNodeResponse(response: Writable): AbortSignal {\n const { errored, destroyed } = response\n if (errored || destroyed) {\n return AbortSignal.abort(errored ?? new ResponseAborted())\n }\n\n const { signal } = createAbortController(response)\n return signal\n}\n\nexport class NextRequestAdapter {\n public static fromBaseNextRequest(\n request: BaseNextRequest,\n signal: AbortSignal\n ): NextRequest {\n if (\n // The type check here ensures that `req` is correctly typed, and the\n // environment variable check provides dead code elimination.\n process.env.NEXT_RUNTIME === 'edge' &&\n isWebNextRequest(request)\n ) {\n return NextRequestAdapter.fromWebNextRequest(request)\n } else if (\n // The type check here ensures that `req` is correctly typed, and the\n // environment variable check provides dead code elimination.\n process.env.NEXT_RUNTIME !== 'edge' &&\n isNodeNextRequest(request)\n ) {\n return NextRequestAdapter.fromNodeNextRequest(request, signal)\n } else {\n throw new Error('Invariant: Unsupported NextRequest type')\n }\n }\n\n public static fromNodeNextRequest(\n request: NodeNextRequest,\n signal: AbortSignal\n ): NextRequest {\n // HEAD and GET requests can not have a body.\n let body: BodyInit | null = null\n if (request.method !== 'GET' && request.method !== 'HEAD' && request.body) {\n // @ts-expect-error - this is handled by undici, when streams/web land use it instead\n body = request.body\n }\n\n let url: URL\n if (request.url.startsWith('http')) {\n url = new URL(request.url)\n } else {\n // Grab the full URL from the request metadata.\n const base = getRequestMeta(request, 'initURL')\n if (!base || !base.startsWith('http')) {\n // Because the URL construction relies on the fact that the URL provided\n // is absolute, we need to provide a base URL. We can't use the request\n // URL because it's relative, so we use a dummy URL instead.\n url = new URL(request.url, 'http://n')\n } else {\n url = new URL(request.url, base)\n }\n }\n\n return new NextRequest(url, {\n method: request.method,\n headers: fromNodeOutgoingHttpHeaders(request.headers),\n duplex: 'half',\n signal,\n // geo\n // ip\n // nextConfig\n\n // body can not be passed if request was aborted\n // or we get a Request body was disturbed error\n ...(signal.aborted\n ? {}\n : {\n body,\n }),\n })\n }\n\n public static fromWebNextRequest(request: WebNextRequest): NextRequest {\n // HEAD and GET requests can not have a body.\n let body: ReadableStream | null = null\n if (request.method !== 'GET' && request.method !== 'HEAD') {\n body = request.body\n }\n\n return new NextRequest(request.url, {\n method: request.method,\n headers: fromNodeOutgoingHttpHeaders(request.headers),\n duplex: 'half',\n signal: request.request.signal,\n // geo\n // ip\n // nextConfig\n\n // body can not be passed if request was aborted\n // or we get a Request body was disturbed error\n ...(request.request.signal.aborted\n ? {}\n : {\n body,\n }),\n })\n }\n}\n","/**\n * A `Promise.withResolvers` implementation that exposes the `resolve` and\n * `reject` functions on a `Promise`.\n *\n * @see https://tc39.es/proposal-promise-with-resolvers/\n */\nexport class DetachedPromise {\n public readonly resolve: (value: T | PromiseLike) => void\n public readonly reject: (reason: any) => void\n public readonly promise: Promise\n\n constructor() {\n let resolve: (value: T | PromiseLike) => void\n let reject: (reason: any) => void\n\n // Create the promise and assign the resolvers to the object.\n this.promise = new Promise((res, rej) => {\n resolve = res\n reject = rej\n })\n\n // We know that resolvers is defined because the Promise constructor runs\n // synchronously.\n this.resolve = resolve!\n this.reject = reject!\n }\n}\n","import type { AppPageModule } from './route-modules/app-page/module'\n\n// Combined load times for loading client components\nlet clientComponentLoadStart = 0\nlet clientComponentLoadTimes = 0\nlet clientComponentLoadCount = 0\n\nexport function wrapClientComponentLoader(\n ComponentMod: AppPageModule\n): AppPageModule['__next_app__'] {\n if (!('performance' in globalThis)) {\n return ComponentMod.__next_app__\n }\n\n return {\n require: (...args) => {\n const startTime = performance.now()\n\n if (clientComponentLoadStart === 0) {\n clientComponentLoadStart = startTime\n }\n\n try {\n clientComponentLoadCount += 1\n return ComponentMod.__next_app__.require(...args)\n } finally {\n clientComponentLoadTimes += performance.now() - startTime\n }\n },\n loadChunk: (...args) => {\n const startTime = performance.now()\n const result = ComponentMod.__next_app__.loadChunk(...args)\n // Avoid wrapping `loadChunk`'s result in an extra promise in case something like React depends on its identity.\n // We only need to know when it's settled.\n result.finally(() => {\n clientComponentLoadTimes += performance.now() - startTime\n })\n return result\n },\n }\n}\n\nexport function getClientComponentLoaderMetrics(\n options: { reset?: boolean } = {}\n) {\n const metrics =\n clientComponentLoadStart === 0\n ? undefined\n : {\n clientComponentLoadStart,\n clientComponentLoadTimes,\n clientComponentLoadCount,\n }\n\n if (options.reset) {\n clientComponentLoadStart = 0\n clientComponentLoadTimes = 0\n clientComponentLoadCount = 0\n }\n\n return metrics\n}\n","import type { ServerResponse } from 'node:http'\n\nimport {\n ResponseAbortedName,\n createAbortController,\n} from './web/spec-extension/adapters/next-request'\nimport { DetachedPromise } from '../lib/detached-promise'\nimport { getTracer } from './lib/trace/tracer'\nimport { NextNodeServerSpan } from './lib/trace/constants'\nimport { getClientComponentLoaderMetrics } from './client-component-renderer-logger'\n\nexport function isAbortError(e: any): e is Error & { name: 'AbortError' } {\n return e?.name === 'AbortError' || e?.name === ResponseAbortedName\n}\n\nfunction createWriterFromResponse(\n res: ServerResponse,\n waitUntilForEnd?: Promise\n): WritableStream {\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()\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()\n res.once('finish', () => {\n finished.resolve()\n })\n\n // Create a writable stream that will write to the response.\n return new WritableStream({\n write: async (chunk) => {\n // You'd think we'd want to use `start` instead of placing this in `write`\n // but this ensures that we don't actually flush the headers until we've\n // started writing chunks.\n if (!started) {\n started = true\n\n if (\n 'performance' in globalThis &&\n process.env.NEXT_OTEL_PERFORMANCE_PREFIX\n ) {\n const metrics = getClientComponentLoaderMetrics()\n if (metrics) {\n performance.measure(\n `${process.env.NEXT_OTEL_PERFORMANCE_PREFIX}:next-client-component-loading`,\n {\n start: metrics.clientComponentLoadStart,\n end:\n metrics.clientComponentLoadStart +\n metrics.clientComponentLoadTimes,\n }\n )\n }\n }\n\n res.flushHeaders()\n getTracer().trace(\n NextNodeServerSpan.startResponse,\n {\n spanName: 'start response',\n },\n () => undefined\n )\n }\n\n try {\n const ok = res.write(chunk)\n\n // Added by the `compression` middleware, this is a function that will\n // flush the partially-compressed response to the client.\n if ('flush' in res && typeof res.flush === 'function') {\n res.flush()\n }\n\n // If the write returns false, it means there's some backpressure, so\n // wait until it's streamed before continuing.\n if (!ok) {\n await drained.promise\n\n // Reset the drained promise so that we can wait for the next drain event.\n drained = new DetachedPromise()\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,\n res: ServerResponse,\n waitUntilForEnd?: Promise\n) {\n try {\n // If the response has already errored, then just return now.\n const { errored, destroyed } = res\n if (errored || destroyed) return\n\n // Create a new AbortController so that we can abort the readable if the\n // client disconnects.\n const controller = createAbortController(res)\n\n const writer = createWriterFromResponse(res, waitUntilForEnd)\n\n await readable.pipeTo(writer, { signal: controller.signal })\n } catch (err: any) {\n // If this isn't related to an abort error, re-throw it.\n if (isAbortError(err)) return\n\n throw new Error('failed to pipe response', { cause: err })\n }\n}\n","import type { OutgoingHttpHeaders, ServerResponse } from 'http'\nimport type { CacheControl } from './lib/cache-control'\nimport type { FetchMetrics } from './base-http'\n\nimport {\n chainStreams,\n streamFromBuffer,\n streamFromString,\n streamToString,\n} from './stream-utils/node-web-streams-helper'\nimport { isAbortError, pipeToNodeResponse } from './pipe-readable'\nimport type { RenderResumeDataCache } from './resume-data-cache/resume-data-cache'\nimport { InvariantError } from '../shared/lib/invariant-error'\nimport type {\n HTML_CONTENT_TYPE_HEADER,\n JSON_CONTENT_TYPE_HEADER,\n TEXT_PLAIN_CONTENT_TYPE_HEADER,\n} from '../lib/constants'\nimport type { RSC_CONTENT_TYPE_HEADER } from '../client/components/app-router-headers'\n\ntype ContentTypeOption =\n | typeof RSC_CONTENT_TYPE_HEADER // For App Page RSC responses\n | typeof HTML_CONTENT_TYPE_HEADER // For App Page, Pages HTML responses\n | typeof JSON_CONTENT_TYPE_HEADER // For API routes, Next.js data requests\n | typeof TEXT_PLAIN_CONTENT_TYPE_HEADER // For simplified errors\n\nexport type AppPageRenderResultMetadata = {\n flightData?: Buffer\n cacheControl?: CacheControl\n staticBailoutInfo?: {\n stack?: string\n description?: string\n }\n\n /**\n * The postponed state if the render had postponed and needs to be resumed.\n */\n postponed?: string\n\n /**\n * The headers to set on the response that were added by the render.\n */\n headers?: OutgoingHttpHeaders\n statusCode?: number\n fetchTags?: string\n fetchMetrics?: FetchMetrics\n\n segmentData?: Map\n\n /**\n * In development, the resume data cache is warmed up before the render. This\n * is attached to the metadata so that it can be used during the render. When\n * prerendering, the filled resume data cache is also attached to the metadata\n * so that it can be used when prerendering matching fallback shells.\n */\n renderResumeDataCache?: RenderResumeDataCache\n}\n\nexport type PagesRenderResultMetadata = {\n pageData?: any\n cacheControl?: CacheControl\n assetQueryString?: string\n 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[]\n | ReadableStream\n | string\n | Buffer\n | null\n\nexport type RenderResultOptions<\n Metadata extends RenderResultMetadata = RenderResultMetadata,\n> = {\n contentType: ContentTypeOption | null\n waitUntil?: Promise\n metadata: Metadata\n}\n\nexport default class RenderResult<\n Metadata extends RenderResultMetadata = RenderResultMetadata,\n> {\n /**\n * The detected content type for the response. This is used to set the\n * `Content-Type` header.\n */\n public readonly contentType: ContentTypeOption | null\n\n /**\n * The metadata for the response. This is used to set the revalidation times\n * and other metadata.\n */\n public readonly metadata: Readonly\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(\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(value, {\n metadata: {},\n contentType,\n })\n }\n\n private readonly waitUntil?: Promise\n\n constructor(\n response: RenderResultResponse,\n { contentType, waitUntil, metadata }: RenderResultOptions\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\n public toUnchunkedString(stream = false): Promise | 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 {\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({\n start(controller) {\n controller.close()\n },\n })\n }\n\n if (typeof this.response === 'string') {\n return streamFromString(this.response)\n }\n\n if (Buffer.isBuffer(this.response)) {\n return streamFromBuffer(this.response)\n }\n\n // If the response is an array of streams, then chain them together.\n if (Array.isArray(this.response)) {\n return chainStreams(...this.response)\n }\n\n return this.response\n }\n\n /**\n * Coerces the response to an array of streams. This will convert the response\n * to an array of streams if it is not already one.\n *\n * @returns An array of streams\n */\n private coerce(): ReadableStream[] {\n if (this.response === null) {\n // If the response is null, return an empty stream. This behavior is\n // intentional as we're now providing the `RenderResult.EMPTY` value.\n return []\n }\n\n if (typeof this.response === 'string') {\n return [streamFromString(this.response)]\n } else if (Array.isArray(this.response)) {\n return this.response\n } else if (Buffer.isBuffer(this.response)) {\n return [streamFromBuffer(this.response)]\n } else {\n return [this.response]\n }\n }\n\n /**\n * 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): 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): 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): Promise {\n try {\n await this.readable.pipeTo(writable, {\n // We want to close the writable stream ourselves so that we can wait\n // for the waitUntil promise to resolve before closing it. If an error\n // is encountered, we'll abort the writable stream if we swallowed the\n // error.\n preventClose: true,\n })\n\n // If there is a waitUntil promise, wait for it to resolve before\n // closing the writable stream.\n if (this.waitUntil) await this.waitUntil\n\n // Close the writable stream.\n await writable.close()\n } catch (err) {\n // If this is an abort error, we should abort the writable stream (as we\n // took ownership of it when we started piping). We don't need to re-throw\n // because we handled the error.\n if (isAbortError(err)) {\n // Abort the writable stream if an error is encountered.\n await writable.abort(err)\n\n return\n }\n\n // We're not aborting the writer here as when this method throws it's not\n // clear as to how so the caller should assume it's their responsibility\n // to clean up the writer.\n throw err\n }\n }\n\n /**\n * Pipes the response to a node response. This will close/cancel the node\n * response if an error is encountered.\n *\n * @param res\n */\n public async pipeToNodeResponse(res: ServerResponse) {\n await pipeToNodeResponse(this.readable, res, this.waitUntil)\n }\n}\n","/**\n * For a given page path, this function ensures that there is no backslash\n * escaping slashes in the path. Example:\n * - `foo\\/bar\\/baz` -> `foo/bar/baz`\n */\nexport function normalizePathSep(path: string): string {\n return path.replace(/\\\\/g, '/')\n}\n","import { isDynamicRoute } from '../router/utils'\nimport { normalizePathSep } from './normalize-path-sep'\n\n/**\n * Performs the opposite transformation of `normalizePagePath`. Note that\n * this function is not idempotent either in cases where there are multiple\n * leading `/index` for the page. Examples:\n * - `/index` -> `/`\n * - `/index/foo` -> `/foo`\n * - `/index/index` -> `/index`\n */\nexport function denormalizePagePath(page: string) {\n let _page = normalizePathSep(page)\n return _page.startsWith('/index/') && !isDynamicRoute(_page)\n ? _page.slice(6)\n : _page !== '/index'\n ? _page\n : '/'\n}\n","import type { Key } from 'next/dist/compiled/path-to-regexp'\nimport { regexpToFunction } from 'next/dist/compiled/path-to-regexp'\nimport { pathToRegexp } from 'next/dist/compiled/path-to-regexp'\n\ninterface Options {\n /**\n * A transformer function that will be applied to the regexp generated\n * from the provided path and path-to-regexp.\n */\n regexModifier?: (regex: string) => string\n /**\n * When true the function will remove all unnamed parameters\n * from the matched parameters.\n */\n removeUnnamedParams?: boolean\n /**\n * When true the regexp won't allow an optional trailing delimiter\n * to match.\n */\n strict?: boolean\n\n /**\n * When true the matcher will be case-sensitive, defaults to false\n */\n sensitive?: boolean\n}\n\nexport type PatchMatcher = (\n pathname: string,\n params?: Record\n) => Record | 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>(\n options?.regexModifier\n ? new RegExp(options.regexModifier(regexp.source), regexp.flags)\n : regexp,\n keys\n )\n\n /**\n * A matcher function that will check if a given pathname matches the path\n * given in the builder function. When the path does not match it will return\n * `false` but if it does it will return an object with the matched params\n * merged with the params provided in the second argument.\n */\n return (pathname, params) => {\n // If no pathname is provided it's not a match.\n if (typeof pathname !== 'string') return false\n\n const match = matcher(pathname)\n\n // If the path did not match `false` will be returned.\n if (!match) return false\n\n /**\n * If unnamed params are not allowed they must be removed from\n * the matched parameters. path-to-regexp uses \"string\" for named and\n * \"number\" for unnamed parameters.\n */\n if (options?.removeUnnamedParams) {\n for (const key of keys) {\n if (typeof key.name === 'number') {\n delete match.params[key.name]\n }\n }\n }\n\n return { ...params, ...match.params }\n }\n}\n","// regexp is based on https://github.com/sindresorhus/escape-string-regexp\nconst reHasRegExp = /[|\\\\{}()[\\]^$+*?.-]/\nconst reReplaceRegExp = /[|\\\\{}()[\\]^$+*?.-]/g\n\nexport function escapeStringRegexp(str: string) {\n // see also: https://github.com/lodash/lodash/blob/2da024c3b4f9947a48517639de7560457cd4ec6c/escapeRegExp.js#L23\n if (reHasRegExp.test(str)) {\n return str.replace(reReplaceRegExp, '\\\\$&')\n }\n return str\n}\n","import type { DynamicParam } from '../../../../server/app-render/app-render'\nimport type { DynamicParamTypesShort } from '../../../../server/app-render/types'\nimport type { FallbackRouteParams } from '../../../../server/request/fallback-params'\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 params: { [key: string]: any },\n segmentKey: string,\n dynamicParamType: DynamicParamTypesShort,\n pagePath: string,\n fallbackRouteParams: FallbackRouteParams | null\n): DynamicParam {\n let value = params[segmentKey]\n\n if (fallbackRouteParams && fallbackRouteParams.has(segmentKey)) {\n value = fallbackRouteParams.get(segmentKey)\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 if (!value) {\n const isCatchall = dynamicParamType === 'c'\n const isOptionalCatchall = dynamicParamType === 'oc'\n\n if (isCatchall || isOptionalCatchall) {\n // handle the case where an optional catchall does not have a value,\n // e.g. `/dashboard/[[...slug]]` when requesting `/dashboard`\n if (isOptionalCatchall) {\n return {\n param: segmentKey,\n value: null,\n type: dynamicParamType,\n treeSegment: [segmentKey, '', dynamicParamType],\n }\n }\n\n // handle the case where a catchall or optional catchall does not have a value,\n // e.g. `/foo/bar/hello` and `@slot/[...catchall]` or `@slot/[[...catchall]]` is matched\n value = pagePath\n .split('/')\n // remove the first empty string\n .slice(1)\n // replace any dynamic params with the actual values\n .flatMap((pathSegment) => {\n const param = parseParameter(pathSegment)\n // if the segment matches a param, return the param value\n // otherwise, it's a static segment, so just return that\n return params[param.key] ?? param.key\n })\n\n return {\n param: segmentKey,\n value,\n type: dynamicParamType,\n // This value always has to be a string.\n treeSegment: [segmentKey, value.join('/'), dynamicParamType],\n }\n }\n }\n\n return {\n param: segmentKey,\n // The value that is passed to user code.\n value: value,\n // The value that is rendered in the router tree.\n treeSegment: [\n segmentKey,\n Array.isArray(value) ? value.join('/') : value,\n dynamicParamType,\n ],\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\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\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\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 optional\n ? `(?:/${interceptionPrefix}${pattern})?`\n : `/${interceptionPrefix}${pattern}`\n}\n\nfunction getNamedParametrizedRoute(\n route: string,\n prefixRouteKeys: boolean,\n includeSuffix: boolean,\n includePrefix: boolean,\n backreferenceDuplicateKeys: boolean\n) {\n const getSafeRouteKey = buildGetSafeRouteKey()\n const routeKeys: { [named: string]: string } = {}\n\n const segments: string[] = []\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 if (hasInterceptionMarker && paramMatches && paramMatches[2]) {\n // If there's an interception marker, add it to the segments.\n segments.push(\n getSafeKeyFromSegment({\n getSafeRouteKey,\n interceptionMarker: paramMatches[1],\n segment: paramMatches[2],\n routeKeys,\n keyPrefix: prefixRouteKeys\n ? NEXT_INTERCEPTION_MARKER_PREFIX\n : undefined,\n backreferenceDuplicateKeys,\n })\n )\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 }\n\n let s = getSafeKeyFromSegment({\n getSafeRouteKey,\n segment: paramMatches[2],\n routeKeys,\n keyPrefix: prefixRouteKeys ? NEXT_QUERY_PARAM_PREFIX : undefined,\n backreferenceDuplicateKeys,\n })\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 namedParameterizedRoute: segments.join(''),\n routeKeys,\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 )\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 }\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 )\n let catchAllGroupedRegex = catchAll ? '(?:(/.*)?)' : ''\n return {\n namedRegex: `^${namedParameterizedRoute}${catchAllGroupedRegex}$`,\n }\n}\n","import type { IncomingMessage } from 'http'\nimport type { Key } from 'next/dist/compiled/path-to-regexp'\nimport type { NextParsedUrlQuery } from '../../../../server/request-meta'\nimport type { RouteHas } from '../../../../lib/load-custom-routes'\nimport type { BaseNextRequest } from '../../../../server/base-http'\n\nimport { escapeStringRegexp } from '../../escape-regexp'\nimport { parseUrl } 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\n query: Readonly\n}) {\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 return {\n ...parsed,\n pathname,\n hostname,\n href,\n hash,\n search,\n }\n}\n\nexport function prepareDestination(args: {\n appendParamsToQuery: boolean\n destination: string\n params: Params\n query: NextParsedUrlQuery\n}) {\n const parsedDestination = parseDestination(args)\n\n const {\n hostname: destHostname,\n query: destQuery,\n search: destSearch,\n } = parsedDestination\n\n // The following code assumes that the pathname here includes the hash if it's\n // present.\n let destPath = parsedDestination.pathname\n if (parsedDestination.hash) {\n destPath = `${destPath}${parsedDestination.hash}`\n }\n\n const destParams: (string | number)[] = []\n\n const destPathParamKeys: Key[] = []\n safePathToRegexp(destPath, destPathParamKeys)\n for (const key of destPathParamKeys) {\n destParams.push(key.name)\n }\n\n if (destHostname) {\n const destHostnameParamKeys: Key[] = []\n safePathToRegexp(destHostname, destHostnameParamKeys)\n for (const key of destHostnameParamKeys) {\n destParams.push(key.name)\n }\n }\n\n const destPathCompiler = safeCompile(\n destPath,\n // we don't validate while compiling the destination since we should\n // have already validated before we got to this point and validating\n // breaks compiling destinations with named pattern params from the source\n // e.g. /something:hello(.*) -> /another/:hello is broken with validation\n // since compile validation is meant for reversing and not for inserting\n // params from a separate path-regex into another\n { validate: false }\n )\n\n let destHostnameCompiler\n if (destHostname) {\n destHostnameCompiler = safeCompile(destHostname, { validate: false })\n }\n\n // update any params in query values\n for (const [key, strOrArray] of Object.entries(destQuery)) {\n // the value needs to start with a forward-slash to be compiled\n // correctly\n if (Array.isArray(strOrArray)) {\n destQuery[key] = strOrArray.map((value) =>\n compileNonPath(unescapeSegments(value), args.params)\n )\n } else if (typeof strOrArray === 'string') {\n destQuery[key] = compileNonPath(unescapeSegments(strOrArray), args.params)\n }\n }\n\n // add path params to query if it's not a redirect and not\n // already defined in destination query or path\n let paramKeys = Object.keys(args.params).filter(\n (name) => name !== 'nextInternalLocale'\n )\n\n if (\n args.appendParamsToQuery &&\n !paramKeys.some((key) => destParams.includes(key))\n ) {\n for (const key of paramKeys) {\n if (!(key in destQuery)) {\n destQuery[key] = args.params[key]\n }\n }\n }\n\n let newUrl\n\n // The compiler also that the interception route marker is an unnamed param, hence '0',\n // so we need to add it to the params object.\n if (isInterceptionRouteAppPath(destPath)) {\n for (const segment of destPath.split('/')) {\n const marker = INTERCEPTION_ROUTE_MARKERS.find((m) =>\n segment.startsWith(m)\n )\n if (marker) {\n if (marker === '(..)(..)') {\n args.params['0'] = '(..)'\n args.params['1'] = '(..)'\n } else {\n args.params['0'] = marker\n }\n break\n }\n }\n }\n\n try {\n newUrl = destPathCompiler(args.params)\n\n const [pathname, hash] = newUrl.split('#', 2)\n if (destHostnameCompiler) {\n parsedDestination.hostname = destHostnameCompiler(args.params)\n }\n parsedDestination.pathname = pathname\n parsedDestination.hash = `${hash ? '#' : ''}${hash || ''}`\n parsedDestination.search = destSearch\n ? compileNonPath(destSearch, args.params)\n : ''\n } catch (err: any) {\n if (err.message.match(/Expected .*? to not repeat, but got an array/)) {\n throw new Error(\n `To use a multi-match in the destination you must add \\`*\\` at the end of the param name to signify it should repeat. https://nextjs.org/docs/messages/invalid-multi-match`\n )\n }\n throw err\n }\n\n // Query merge order lowest priority to highest\n // 1. initial URL query values\n // 2. path segment values\n // 3. destination specified query values\n parsedDestination.query = {\n ...args.query,\n ...parsedDestination.query,\n }\n\n return {\n newUrl,\n destQuery,\n parsedDestination,\n }\n}\n","/**\n * Decodes a query path parameter.\n *\n * @param value - The value to decode.\n * @returns The decoded value.\n */\nexport function decodeQueryPathParameter(value: string) {\n // When deployed to Vercel, the value may be encoded, so this attempts to\n // decode it and returns the original value if it fails.\n try {\n return decodeURIComponent(value)\n } catch {\n return value\n }\n}\n","// Format function modified from nodejs\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { UrlObject } from 'url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport * as querystring from './querystring'\n\nconst slashedProtocols = /https?|ftp|gopher|file/\n\nexport function formatUrl(urlObj: UrlObject) {\n let { auth, hostname } = urlObj\n let protocol = urlObj.protocol || ''\n let pathname = urlObj.pathname || ''\n let hash = urlObj.hash || ''\n let query = urlObj.query || ''\n let host: string | false = false\n\n auth = auth ? encodeURIComponent(auth).replace(/%3A/i, ':') + '@' : ''\n\n if (urlObj.host) {\n host = auth + urlObj.host\n } else if (hostname) {\n host = auth + (~hostname.indexOf(':') ? `[${hostname}]` : hostname)\n if (urlObj.port) {\n host += ':' + urlObj.port\n }\n }\n\n if (query && typeof query === 'object') {\n query = String(querystring.urlQueryToSearchParams(query as ParsedUrlQuery))\n }\n\n let search = urlObj.search || (query && `?${query}`) || ''\n\n if (protocol && !protocol.endsWith(':')) protocol += ':'\n\n if (\n urlObj.slashes ||\n ((!protocol || slashedProtocols.test(protocol)) && host !== false)\n ) {\n host = '//' + (host || '')\n if (pathname && pathname[0] !== '/') pathname = '/' + pathname\n } else if (!host) {\n host = ''\n }\n\n if (hash && hash[0] !== '#') hash = '#' + hash\n if (search && search[0] !== '?') search = '?' + search\n\n pathname = pathname.replace(/[?#]/g, encodeURIComponent)\n search = search.replace('#', '%23')\n\n return `${protocol}${host}${pathname}${search}${hash}`\n}\n\nexport const urlObjectKeys = [\n 'auth',\n 'hash',\n 'host',\n 'hostname',\n 'href',\n 'path',\n 'pathname',\n 'port',\n 'protocol',\n 'query',\n 'search',\n 'slashes',\n]\n\nexport function formatWithValidation(url: UrlObject): string {\n if (process.env.NODE_ENV === 'development') {\n if (url !== null && typeof url === 'object') {\n Object.keys(url).forEach((key) => {\n if (!urlObjectKeys.includes(key)) {\n console.warn(\n `Unknown key passed via urlObject into url.format: ${key}`\n )\n }\n })\n }\n }\n\n return formatUrl(url)\n}\n","import type { LoadComponentsReturnType } from '../load-components'\nimport type { ServerRuntime, SizeLimit } from '../../types'\nimport type {\n ExperimentalConfig,\n NextConfigComplete,\n} from '../../server/config-shared'\nimport type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'\nimport type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { AppPageModule } from '../route-modules/app-page/module'\nimport type {\n HeadData,\n LoadingModuleData,\n} from '../../shared/lib/app-router-context.shared-runtime'\nimport type { DeepReadonly } from '../../shared/lib/deep-readonly'\nimport type { __ApiPreviewProps } from '../api-utils'\n\nimport s from 'next/dist/compiled/superstruct'\nimport type { RequestLifecycleOpts } from '../base-server'\nimport type { InstrumentationOnRequestError } from '../instrumentation/types'\nimport type { NextRequestHint } from '../web/adapter'\nimport type { BaseNextRequest } from '../base-http'\nimport type { IncomingMessage } from 'http'\nimport type { RenderResumeDataCache } from '../resume-data-cache/resume-data-cache'\n\nexport type DynamicParamTypes =\n | 'catchall'\n | 'catchall-intercepted'\n | 'optional-catchall'\n | 'dynamic'\n | 'dynamic-intercepted'\n\nconst dynamicParamTypesSchema = s.enums(['c', 'ci', 'oc', 'd', 'di'])\n\nexport type DynamicParamTypesShort = s.Infer\n\nconst segmentSchema = s.union([\n s.string(),\n\n s.tuple([\n // Param name\n s.string(),\n // Param cache key (almost the same as the value, but arrays are\n // concatenated into strings)\n // TODO: We should change this to just be the value. Currently we convert\n // it back to a value when passing to useParams. It only needs to be\n // a string when converted to a a cache key, but that doesn't mean we\n // need to store it as that representation.\n s.string(),\n // Dynamic param type\n dynamicParamTypesSchema,\n ]),\n])\n\nexport type Segment = s.Infer\n\n// unfortunately the tuple is not understood well by Describe so we have to\n// use any here. This does not have any impact on the runtime type since the validation\n// does work correctly.\nexport const flightRouterStateSchema: s.Describe = s.tuple([\n segmentSchema,\n s.record(\n s.string(),\n s.lazy(() => flightRouterStateSchema)\n ),\n s.optional(s.nullable(s.string())),\n s.optional(\n s.nullable(\n s.union([\n s.literal('refetch'),\n s.literal('refresh'),\n s.literal('inside-shared-layout'),\n s.literal('metadata-only'),\n ])\n )\n ),\n s.optional(s.boolean()),\n])\n\n/**\n * Router state\n */\nexport type FlightRouterState = [\n segment: Segment,\n parallelRoutes: { [parallelRouterKey: string]: FlightRouterState },\n url?: string | null,\n /**\n * \"refresh\" and \"refetch\", despite being similarly named, have different\n * semantics:\n * - \"refetch\" is used during a request to inform the server where rendering\n * should start from.\n *\n * - \"refresh\" is used by the client to mark that a segment should re-fetch the\n * data from the server for the current segment. It uses the \"url\" property\n * above to determine where to fetch from.\n *\n * - \"inside-shared-layout\" is used during a prefetch request to inform the\n * server that even if the segment matches, it should be treated as if it's\n * within the \"new\" part of a navigation — inside the shared layout. If\n * the segment doesn't match, then it has no effect, since it would be\n * treated as new regardless. If it does match, though, the server does not\n * need to render it, because the client already has it.\n *\n * - \"metadata-only\" instructs the server to skip rendering the segments and\n * only send the head data.\n *\n * A bit confusing, but that's because it has only one extremely narrow use\n * case — during a non-PPR prefetch, the server uses it to find the first\n * loading boundary beneath a shared layout.\n *\n * TODO: We should rethink the protocol for dynamic requests. It might not\n * make sense for the client to send a FlightRouterState, since this type is\n * overloaded with concerns.\n */\n refresh?:\n | 'refetch'\n | 'refresh'\n | 'inside-shared-layout'\n | 'metadata-only'\n | null,\n isRootLayout?: boolean,\n /**\n * Only present when responding to a tree prefetch request. Indicates whether\n * there is a loading boundary somewhere in the tree. The client cache uses\n * this to determine if it can skip the data prefetch request.\n */\n hasLoadingBoundary?: HasLoadingBoundary,\n]\n\nexport const enum HasLoadingBoundary {\n // There is a loading boundary in this particular segment\n SegmentHasLoadingBoundary = 1,\n // There is a loading boundary somewhere in the subtree (but not in\n // this segment)\n SubtreeHasLoadingBoundary = 2,\n // There is no loading boundary in this segment or any of its descendants\n SubtreeHasNoLoadingBoundary = 3,\n}\n\n/**\n * Individual Flight response path\n */\nexport type FlightSegmentPath =\n // Uses `any` as repeating pattern can't be typed.\n | any[]\n // Looks somewhat like this\n | [\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n ]\n\n/**\n * Represents a tree of segments and the Flight data (i.e. React nodes) that\n * correspond to each one. The tree is isomorphic to the FlightRouterState;\n * however in the future we want to be able to fetch arbitrary partial segments\n * without having to fetch all its children. So this response format will\n * likely change.\n */\nexport type CacheNodeSeedData = [\n segment: Segment,\n node: React.ReactNode | null,\n parallelRoutes: {\n [parallelRouterKey: string]: CacheNodeSeedData | null\n },\n loading: LoadingModuleData | Promise,\n isPartial: boolean,\n]\n\nexport type FlightDataSegment = [\n /* segment of the rendered slice: */ Segment,\n /* treePatch */ FlightRouterState,\n /* cacheNodeSeedData */ CacheNodeSeedData | null, // Can be null during prefetch if there's no loading component\n /* head: viewport */ HeadData,\n /* isHeadPartial */ boolean,\n]\n\nexport type FlightDataPath =\n // Uses `any` as repeating pattern can't be typed.\n | any[]\n // Looks somewhat like this\n | [\n // Holds full path to the segment.\n ...FlightSegmentPath[],\n ...FlightDataSegment,\n ]\n\n/**\n * The Flight response data\n */\nexport type FlightData = Array | string\n\nexport type ActionResult = Promise\n\nexport type ServerOnInstrumentationRequestError = (\n error: unknown,\n // The request could be middleware, node server or web server request,\n // we normalized them into an aligned format to `onRequestError` API later.\n request: NextRequestHint | BaseNextRequest | IncomingMessage,\n errorContext: Parameters[2]\n) => void | Promise\n\nexport interface RenderOptsPartial {\n dir?: string\n previewProps: __ApiPreviewProps | undefined\n err?: Error | null\n dev?: boolean\n basePath: string\n trailingSlash: boolean\n clientReferenceManifest?: DeepReadonly\n supportsDynamicResponse: boolean\n runtime?: ServerRuntime\n serverComponents?: boolean\n enableTainting?: boolean\n assetPrefix?: string\n crossOrigin?: '' | 'anonymous' | 'use-credentials' | undefined\n nextFontManifest?: DeepReadonly\n botType?: 'dom' | 'html' | undefined\n serveStreamingMetadata?: boolean\n incrementalCache?: import('../lib/incremental-cache').IncrementalCache\n cacheLifeProfiles?: {\n [profile: string]: import('../use-cache/cache-life').CacheLife\n }\n isOnDemandRevalidate?: boolean\n isPossibleServerAction?: boolean\n setIsrStatus?: (key: string, value: boolean | null) => void\n isRevalidate?: boolean\n nextExport?: boolean\n nextConfigOutput?: 'standalone' | 'export'\n onInstrumentationRequestError?: ServerOnInstrumentationRequestError\n isDraftMode?: boolean\n deploymentId?: string\n onUpdateCookies?: (cookies: string[]) => void\n loadConfig?: (\n phase: string,\n dir: string,\n customConfig?: object | null,\n rawConfig?: boolean,\n silent?: boolean\n ) => Promise\n serverActions?: {\n bodySizeLimit?: SizeLimit\n allowedOrigins?: string[]\n }\n params?: ParsedUrlQuery\n isPrefetch?: boolean\n htmlLimitedBots: string | undefined\n experimental: {\n /**\n * When true, it indicates that the current page supports partial\n * prerendering.\n */\n isRoutePPREnabled?: boolean\n expireTime: number | undefined\n staleTimes: ExperimentalConfig['staleTimes'] | undefined\n clientTraceMetadata: string[] | undefined\n cacheComponents: boolean\n clientSegmentCache: boolean | 'client-only'\n clientParamParsing: boolean\n dynamicOnHover: boolean\n inlineCss: boolean\n authInterrupts: boolean\n }\n postponed?: string\n\n /**\n * Should wait for react stream allReady to resolve all suspense boundaries,\n * in order to perform a full page render.\n */\n shouldWaitOnAllReady?: boolean\n\n /**\n * A prefilled resume data cache. This was either generated for this page\n * during dev warmup, or when a page with defined params was previously\n * prerendered, and now its matching optional fallback shell is prerendered.\n */\n renderResumeDataCache?: RenderResumeDataCache\n\n /**\n * When true, the page will be rendered using the static rendering to detect\n * any dynamic API's that would have stopped the page from being fully\n * statically generated.\n */\n isDebugDynamicAccesses?: boolean\n\n /**\n * This is true when:\n * - source maps are generated\n * - source maps are applied\n * - minification is disabled\n */\n hasReadableErrorStacks?: boolean\n\n /**\n * The maximum length of the headers that are emitted by React and added to\n * the response.\n */\n reactMaxHeadersLength: number | undefined\n\n isStaticGeneration?: boolean\n\n /**\n * When true, the page is prerendered as a fallback shell, while allowing any\n * dynamic accesses to result in an empty shell. This is the case when there\n * are also routes prerendered with a more complete set of params.\n * Prerendering those routes would catch any invalid dynamic accesses.\n */\n allowEmptyStaticShell?: boolean\n\n /**\n * next config experimental.devtoolSegmentExplorer\n */\n devtoolSegmentExplorer?: boolean\n}\n\nexport type RenderOpts = LoadComponentsReturnType &\n RenderOptsPartial &\n RequestLifecycleOpts\n\nexport type PreloadCallbacks = (() => void)[]\n\nexport type InitialRSCPayload = {\n /** buildId */\n b: string\n /** assetPrefix */\n p: string\n /** initialCanonicalUrlParts */\n c: string[]\n /** couldBeIntercepted */\n i: boolean\n /** initialFlightData */\n f: FlightDataPath[]\n /** missingSlots */\n m: Set | undefined\n /** GlobalError */\n G: [React.ComponentType, React.ReactNode | undefined]\n /** postponed */\n s: boolean\n /** prerendered */\n S: boolean\n}\n\n// Response from `createFromFetch` for normal rendering\nexport type NavigationFlightResponse = {\n /** buildId */\n b: string\n /** flightData */\n f: FlightData\n /** prerendered */\n S: boolean\n}\n\n// Response from `createFromFetch` for server actions. Action's flight data can be null\nexport type ActionFlightResponse = {\n /** actionResult */\n a: ActionResult\n /** buildId */\n b: string\n /** flightData */\n f: FlightData\n}\n\nexport type RSCPayload =\n | InitialRSCPayload\n | NavigationFlightResponse\n | ActionFlightResponse\n","export const RSC_HEADER = 'rsc' as const\nexport const ACTION_HEADER = 'next-action' as const\n// TODO: Instead of sending the full router state, we only need to send the\n// segment path. Saves bytes. Then we could also use this field for segment\n// prefetches, which also need to specify a particular segment.\nexport const NEXT_ROUTER_STATE_TREE_HEADER = 'next-router-state-tree' as const\nexport const NEXT_ROUTER_PREFETCH_HEADER = 'next-router-prefetch' as const\n// This contains the path to the segment being prefetched.\n// TODO: If we change next-router-state-tree to be a segment path, we can use\n// that instead. Then next-router-prefetch and next-router-segment-prefetch can\n// be merged into a single enum.\nexport const NEXT_ROUTER_SEGMENT_PREFETCH_HEADER =\n 'next-router-segment-prefetch' as const\nexport const NEXT_HMR_REFRESH_HEADER = 'next-hmr-refresh' as const\nexport const NEXT_HMR_REFRESH_HASH_COOKIE = '__next_hmr_refresh_hash__' as const\nexport const NEXT_URL = 'next-url' as const\nexport const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const\n\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\n","import { NEXT_URL } from '../client/components/app-router-headers'\nimport {\n extractInterceptionRouteInformation,\n isInterceptionRouteAppPath,\n} from '../shared/lib/router/utils/interception-routes'\nimport type { Rewrite } from './load-custom-routes'\nimport { safePathToRegexp } from '../shared/lib/router/utils/route-match-utils'\nimport type { DeepReadonly } from '../shared/lib/deep-readonly'\n\n// a function that converts normalised paths (e.g. /foo/[bar]/[baz]) to the format expected by pathToRegexp (e.g. /foo/:bar/:baz)\nfunction toPathToRegexpPath(path: string): string {\n return path.replace(/\\[\\[?([^\\]]+)\\]\\]?/g, (_, capture) => {\n // path-to-regexp only supports word characters, so we replace any non-word characters with underscores\n const paramName = capture.replace(/\\W+/g, '_')\n\n // handle catch-all segments (e.g. /foo/bar/[...baz] or /foo/bar/[[...baz]])\n if (capture.startsWith('...')) {\n return `:${capture.slice(3)}*`\n }\n return ':' + paramName\n })\n}\n\nexport function generateInterceptionRoutesRewrites(\n appPaths: string[],\n basePath = ''\n): Rewrite[] {\n const rewrites: Rewrite[] = []\n\n for (const appPath of appPaths) {\n if (isInterceptionRouteAppPath(appPath)) {\n const { interceptingRoute, interceptedRoute } =\n extractInterceptionRouteInformation(appPath)\n\n const normalizedInterceptingRoute = `${\n interceptingRoute !== '/' ? toPathToRegexpPath(interceptingRoute) : ''\n }/(.*)?`\n\n const normalizedInterceptedRoute = toPathToRegexpPath(interceptedRoute)\n const normalizedAppPath = toPathToRegexpPath(appPath)\n\n // pathToRegexp returns a regex that matches the path, but we need to\n // convert it to a string that can be used in a header value\n // to the format that Next/the proxy expects\n let interceptingRouteRegex = safePathToRegexp(normalizedInterceptingRoute)\n .toString()\n .slice(2, -3)\n\n rewrites.push({\n source: `${basePath}${normalizedInterceptedRoute}`,\n destination: `${basePath}${normalizedAppPath}`,\n has: [\n {\n type: 'header',\n key: NEXT_URL,\n value: interceptingRouteRegex,\n },\n ],\n })\n }\n }\n\n return rewrites\n}\n\nexport function isInterceptionRouteRewrite(route: DeepReadonly) {\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 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 { ParsedUrlQuery } from 'querystring'\nimport type { UrlWithParsedQuery } from 'url'\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'\nimport { parseAndValidateFlightRouterState } from './app-render/parse-and-validate-flight-router-state'\nimport { isInterceptionRouteRewrite } from '../lib/generate-interception-routes-rewrites'\nimport { NEXT_ROUTER_STATE_TREE_HEADER } from '../client/components/app-router-headers'\nimport { getSelectedParams } from '../client/components/router-reducer/compute-changed-path'\n\nfunction filterInternalQuery(\n query: Record,\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 | 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,\n defaultRouteMatches: ParsedUrlQuery,\n ignoreMissingOptional: boolean\n) {\n let hasValidParams = true\n let params: ParsedUrlQuery = {}\n\n for (const key of Object.keys(defaultRouteRegex.groups)) {\n let value: string | string[] | undefined = query[key]\n\n if (typeof value === 'string') {\n value = normalizeRscURL(value)\n } else if (Array.isArray(value)) {\n value = value.map(normalizeRscURL)\n }\n\n // if the value matches the default value we can't rely\n // on the parsed params, this is used to signal if we need\n // to parse x-now-route-matches or not\n const defaultValue = defaultRouteMatches![key]\n const isOptional = defaultRouteRegex!.groups[key].optional\n\n const isDefaultValue = Array.isArray(defaultValue)\n ? defaultValue.some((defaultVal) => {\n return Array.isArray(value)\n ? value.some((val) => val.includes(defaultVal))\n : value?.includes(defaultVal)\n })\n : value?.includes(defaultValue as string)\n\n if (\n isDefaultValue ||\n (typeof value === 'undefined' && !(isOptional && ignoreMissingOptional))\n ) {\n return { params: {}, hasValidParams: false }\n }\n\n // non-provided optional values should be undefined so normalize\n // them to undefined\n if (\n isOptional &&\n (!value ||\n (Array.isArray(value) &&\n value.length === 1 &&\n // fallback optional catch-all SSG pages have\n // [[...paramName]] for the root path on Vercel\n (value[0] === 'index' || value[0] === `[[...${key}]]`)))\n ) {\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\n afterFiles?: ReadonlyArray\n beforeFiles?: ReadonlyArray\n }>\n pageIsDynamic: boolean\n trailingSlash?: boolean\n caseSensitive: boolean\n}) {\n let defaultRouteRegex: ReturnType | 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: UrlWithParsedQuery\n ) {\n const rewriteParams: Record = {}\n let fsPathname = parsedUrl.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): boolean => {\n const matcher = getPathMatch(\n rewrite.source + (trailingSlash ? '(/)?' : ''),\n {\n removeUnnamedParams: true,\n strict: true,\n sensitive: !!caseSensitive,\n }\n )\n\n if (!parsedUrl.pathname) return false\n\n let params = matcher(parsedUrl.pathname)\n\n if ((rewrite.has || rewrite.missing) && params) {\n const hasParams = matchHas(\n req,\n parsedUrl.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 try {\n // An interception rewrite might reference a dynamic param for a route the user\n // is currently on, which wouldn't be extractable from the matched route params.\n // This attempts to extract the dynamic params from the provided router state.\n if (isInterceptionRouteRewrite(rewrite as Rewrite)) {\n const stateHeader = req.headers[NEXT_ROUTER_STATE_TREE_HEADER]\n\n if (stateHeader) {\n params = {\n ...getSelectedParams(\n parseAndValidateFlightRouterState(stateHeader)\n ),\n ...params,\n }\n }\n }\n } catch (err) {\n // this is a no-op -- we couldn't extract dynamic params from the provided router state,\n // so we'll just use the params from the route matcher\n }\n\n const { parsedDestination, destQuery } = prepareDestination({\n appendParamsToQuery: true,\n destination: rewrite.destination,\n params: params,\n query: parsedUrl.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(parsedUrl.query, parsedDestination.query)\n delete (parsedDestination as any).query\n\n // for each property in parsedUrl.query, if the value is parametrized (eg :foo), look up the value\n // in rewriteParams and replace the parametrized value with the actual value\n // this is used when the rewrite destination does not contain the original source param\n // and so the value is still parametrized and needs to be replaced with the actual rewrite param\n Object.entries(parsedUrl.query).forEach(([key, value]) => {\n if (value && typeof value === 'string' && value.startsWith(':')) {\n const paramName = value.slice(1)\n const actualValue = rewriteParams[paramName]\n if (actualValue) {\n parsedUrl.query[key] = actualValue\n }\n }\n })\n\n Object.assign(parsedUrl, parsedDestination)\n\n fsPathname = parsedUrl.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 parsedUrl.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 parsedUrl.query = {\n ...parsedUrl.query,\n ...dynamicParams,\n }\n return true\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 return rewriteParams\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 = 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,\n routeParamKeys: Set\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\n ) => interpolateDynamicPath(pathname, params, defaultRouteRegex),\n\n filterInternalQuery: (query: ParsedUrlQuery, paramKeys: string[]) =>\n filterInternalQuery(query, paramKeys),\n }\n}\n\nexport function getPreviouslyRevalidatedTags(\n headers: IncomingHttpHeaders,\n previewModeId: string | undefined\n): string[] {\n return typeof headers[NEXT_CACHE_REVALIDATED_TAGS_HEADER] === 'string' &&\n headers[NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER] === previewModeId\n ? headers[NEXT_CACHE_REVALIDATED_TAGS_HEADER].split(',')\n : []\n}\n","import { isPlainObject } from '../shared/lib/is-plain-object'\n\n// We allow some additional attached properties for Next.js errors\nexport interface NextError extends Error {\n type?: string\n page?: string\n code?: string | number\n cancelled?: boolean\n digest?: number\n}\n\n/**\n * Checks whether the given value is a NextError.\n * This can be used to print a more detailed error message with properties like `code` & `digest`.\n */\nexport default function isError(err: unknown): err is NextError {\n return (\n typeof err === 'object' && err !== null && 'name' in err && 'message' in err\n )\n}\n\nfunction safeStringify(obj: any) {\n const seen = new WeakSet()\n\n return JSON.stringify(obj, (_key, value) => {\n // If value is an object and already seen, replace with \"[Circular]\"\n if (typeof value === 'object' && value !== null) {\n if (seen.has(value)) {\n return '[Circular]'\n }\n seen.add(value)\n }\n return value\n })\n}\n\nexport function getProperError(err: unknown): Error {\n if (isError(err)) {\n return err\n }\n\n if (process.env.NODE_ENV === 'development') {\n // provide better error for case where `throw undefined`\n // is called in development\n if (typeof err === 'undefined') {\n return new Error(\n 'An undefined error was thrown, ' +\n 'see here for more info: https://nextjs.org/docs/messages/threw-undefined'\n )\n }\n\n if (err === null) {\n return new Error(\n 'A null error was thrown, ' +\n 'see here for more info: https://nextjs.org/docs/messages/threw-undefined'\n )\n }\n }\n\n return new Error(isPlainObject(err) ? safeStringify(err) : err + '')\n}\n","export function getObjectClassLabel(value: any): string {\n return Object.prototype.toString.call(value)\n}\n\nexport function isPlainObject(value: any): boolean {\n if (getObjectClassLabel(value) !== '[object Object]') {\n return false\n }\n\n const prototype = Object.getPrototypeOf(value)\n\n /**\n * this used to be previously:\n *\n * `return prototype === null || prototype === Object.prototype`\n *\n * but Edge Runtime expose Object from vm, being that kind of type-checking wrongly fail.\n *\n * It was changed to the current implementation since it's resilient to serialization.\n */\n return prototype === null || prototype.hasOwnProperty('isPrototypeOf')\n}\n","import type { I18NProvider } from '../lib/i18n-provider'\nimport type { Normalizer } from './normalizer'\n\n/**\n * Normalizes the pathname by removing the locale prefix if any.\n */\nexport class LocaleRouteNormalizer implements Normalizer {\n constructor(private readonly provider: I18NProvider) {}\n\n /**\n * Normalizes the pathname by removing the locale prefix if any.\n *\n * @param pathname The pathname to normalize.\n * @returns The pathname without the locale prefix (if any).\n */\n public normalize(pathname: string): string {\n const match = this.provider.analyze(pathname)\n return match.pathname\n }\n}\n","class UrlNode {\n placeholder: boolean = true\n children: Map = new Map()\n slugName: string | null = null\n restSlugName: string | null = null\n optionalRestSlugName: string | null = null\n\n insert(urlPath: string): void {\n this._insert(urlPath.split('/').filter(Boolean), [], false)\n }\n\n smoosh(): string[] {\n return this._smoosh()\n }\n\n private _smoosh(prefix: string = '/'): string[] {\n const childrenPaths = [...this.children.keys()].sort()\n if (this.slugName !== null) {\n childrenPaths.splice(childrenPaths.indexOf('[]'), 1)\n }\n if (this.restSlugName !== null) {\n childrenPaths.splice(childrenPaths.indexOf('[...]'), 1)\n }\n if (this.optionalRestSlugName !== null) {\n childrenPaths.splice(childrenPaths.indexOf('[[...]]'), 1)\n }\n\n const routes = childrenPaths\n .map((c) => this.children.get(c)!._smoosh(`${prefix}${c}/`))\n .reduce((prev, curr) => [...prev, ...curr], [])\n\n if (this.slugName !== null) {\n routes.push(\n ...this.children.get('[]')!._smoosh(`${prefix}[${this.slugName}]/`)\n )\n }\n\n if (!this.placeholder) {\n const r = prefix === '/' ? '/' : prefix.slice(0, -1)\n if (this.optionalRestSlugName != null) {\n throw new Error(\n `You cannot define a route with the same specificity as a optional catch-all route (\"${r}\" and \"${r}[[...${this.optionalRestSlugName}]]\").`\n )\n }\n\n routes.unshift(r)\n }\n\n if (this.restSlugName !== null) {\n routes.push(\n ...this.children\n .get('[...]')!\n ._smoosh(`${prefix}[...${this.restSlugName}]/`)\n )\n }\n\n if (this.optionalRestSlugName !== null) {\n routes.push(\n ...this.children\n .get('[[...]]')!\n ._smoosh(`${prefix}[[...${this.optionalRestSlugName}]]/`)\n )\n }\n\n return routes\n }\n\n private _insert(\n urlPaths: string[],\n slugNames: string[],\n isCatchAll: boolean\n ): void {\n if (urlPaths.length === 0) {\n this.placeholder = false\n return\n }\n\n if (isCatchAll) {\n throw new Error(`Catch-all must be the last part of the URL.`)\n }\n\n // The next segment in the urlPaths list\n let nextSegment = urlPaths[0]\n\n // Check if the segment matches `[something]`\n if (nextSegment.startsWith('[') && nextSegment.endsWith(']')) {\n // Strip `[` and `]`, leaving only `something`\n let segmentName = nextSegment.slice(1, -1)\n\n let isOptional = false\n if (segmentName.startsWith('[') && segmentName.endsWith(']')) {\n // Strip optional `[` and `]`, leaving only `something`\n segmentName = segmentName.slice(1, -1)\n isOptional = true\n }\n\n if (segmentName.startsWith('…')) {\n throw new Error(\n `Detected a three-dot character ('…') at ('${segmentName}'). Did you mean ('...')?`\n )\n }\n\n if (segmentName.startsWith('...')) {\n // Strip `...`, leaving only `something`\n segmentName = segmentName.substring(3)\n isCatchAll = true\n }\n\n if (segmentName.startsWith('[') || segmentName.endsWith(']')) {\n throw new Error(\n `Segment names may not start or end with extra brackets ('${segmentName}').`\n )\n }\n\n if (segmentName.startsWith('.')) {\n throw new Error(\n `Segment names may not start with erroneous periods ('${segmentName}').`\n )\n }\n\n function handleSlug(previousSlug: string | null, nextSlug: string) {\n if (previousSlug !== null) {\n // If the specific segment already has a slug but the slug is not `something`\n // This prevents collisions like:\n // pages/[post]/index.js\n // pages/[id]/index.js\n // Because currently multiple dynamic params on the same segment level are not supported\n if (previousSlug !== nextSlug) {\n // TODO: This error seems to be confusing for users, needs an error link, the description can be based on above comment.\n throw new Error(\n `You cannot use different slug names for the same dynamic path ('${previousSlug}' !== '${nextSlug}').`\n )\n }\n }\n\n slugNames.forEach((slug) => {\n if (slug === nextSlug) {\n throw new Error(\n `You cannot have the same slug name \"${nextSlug}\" repeat within a single dynamic path`\n )\n }\n\n if (slug.replace(/\\W/g, '') === nextSegment.replace(/\\W/g, '')) {\n throw new Error(\n `You cannot have the slug names \"${slug}\" and \"${nextSlug}\" differ only by non-word symbols within a single dynamic path`\n )\n }\n })\n\n slugNames.push(nextSlug)\n }\n\n if (isCatchAll) {\n if (isOptional) {\n if (this.restSlugName != null) {\n throw new Error(\n `You cannot use both an required and optional catch-all route at the same level (\"[...${this.restSlugName}]\" and \"${urlPaths[0]}\" ).`\n )\n }\n\n handleSlug(this.optionalRestSlugName, segmentName)\n // slugName is kept as it can only be one particular slugName\n this.optionalRestSlugName = segmentName\n // nextSegment is overwritten to [[...]] so that it can later be sorted specifically\n nextSegment = '[[...]]'\n } else {\n if (this.optionalRestSlugName != null) {\n throw new Error(\n `You cannot use both an optional and required catch-all route at the same level (\"[[...${this.optionalRestSlugName}]]\" and \"${urlPaths[0]}\").`\n )\n }\n\n handleSlug(this.restSlugName, segmentName)\n // slugName is kept as it can only be one particular slugName\n this.restSlugName = segmentName\n // nextSegment is overwritten to [...] so that it can later be sorted specifically\n nextSegment = '[...]'\n }\n } else {\n if (isOptional) {\n throw new Error(\n `Optional route parameters are not yet supported (\"${urlPaths[0]}\").`\n )\n }\n handleSlug(this.slugName, segmentName)\n // slugName is kept as it can only be one particular slugName\n this.slugName = segmentName\n // nextSegment is overwritten to [] so that it can later be sorted specifically\n nextSegment = '[]'\n }\n }\n\n // If this UrlNode doesn't have the nextSegment yet we create a new child UrlNode\n if (!this.children.has(nextSegment)) {\n this.children.set(nextSegment, new UrlNode())\n }\n\n this.children\n .get(nextSegment)!\n ._insert(urlPaths.slice(1), slugNames, isCatchAll)\n }\n}\n\n/**\n * @deprecated Use `sortSortableRoutes` or `sortPages` instead.\n */\nexport function getSortedRoutes(\n normalizedPages: ReadonlyArray\n): string[] {\n // First the UrlNode is created, and every UrlNode can have only 1 dynamic segment\n // Eg you can't have pages/[post]/abc.js and pages/[hello]/something-else.js\n // Only 1 dynamic segment per nesting level\n\n // So in the case that is test/integration/dynamic-routing it'll be this:\n // pages/[post]/comments.js\n // pages/blog/[post]/comment/[id].js\n // Both are fine because `pages/[post]` and `pages/blog` are on the same level\n // So in this case `UrlNode` created here has `this.slugName === 'post'`\n // And since your PR passed through `slugName` as an array basically it'd including it in too many possibilities\n // Instead what has to be passed through is the upwards path's dynamic names\n const root = new UrlNode()\n\n // Here the `root` gets injected multiple paths, and insert will break them up into sublevels\n normalizedPages.forEach((pagePath) => root.insert(pagePath))\n // Smoosh will then sort those sublevels up to the point where you get the correct route definition priority\n return root.smoosh()\n}\n\n/**\n * @deprecated Use `sortSortableRouteObjects` or `sortPageObjects` instead.\n */\nexport function getSortedRouteObjects(\n objects: T[],\n getter: (obj: T) => string\n): T[] {\n // We're assuming here that all the pathnames are unique, that way we can\n // sort the list and use the index as the key.\n const indexes: Record = {}\n const pathnames: string[] = []\n for (let i = 0; i < objects.length; i++) {\n const pathname = getter(objects[i])\n indexes[pathname] = i\n pathnames[i] = pathname\n }\n\n // Sort the pathnames.\n const sorted = getSortedRoutes(pathnames)\n\n // Map the sorted pathnames back to the original objects using the new sorted\n // index.\n return sorted.map((pathname) => objects[indexes[pathname]])\n}\n","import type { RouteMatch } from '../route-matches/route-match'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { Params } from '../request/params'\n\nimport { isDynamicRoute } from '../../shared/lib/router/utils'\nimport {\n getRouteMatcher,\n type RouteMatchFn,\n} from '../../shared/lib/router/utils/route-matcher'\nimport { getRouteRegex } from '../../shared/lib/router/utils/route-regex'\n\ntype RouteMatchResult = {\n params?: Params\n}\n\nexport class RouteMatcher {\n private readonly dynamic?: RouteMatchFn\n\n /**\n * When set, this is an array of all the other matchers that are duplicates of\n * this one. This is used by the managers to warn the users about possible\n * duplicate matches on routes.\n */\n public duplicated?: Array\n\n constructor(public readonly definition: D) {\n if (isDynamicRoute(definition.pathname)) {\n this.dynamic = getRouteMatcher(getRouteRegex(definition.pathname))\n }\n }\n\n /**\n * Identity returns the identity part of the matcher. This is used to compare\n * a unique matcher to another. This is also used when sorting dynamic routes,\n * so it must contain the pathname part.\n */\n public get identity(): string {\n return this.definition.pathname\n }\n\n public get isDynamic() {\n return this.dynamic !== undefined\n }\n\n public match(pathname: string): RouteMatch | null {\n const result = this.test(pathname)\n if (!result) return null\n\n return { definition: this.definition, params: result.params }\n }\n\n public test(pathname: string): RouteMatchResult | null {\n if (this.dynamic) {\n const params = this.dynamic(pathname)\n if (!params) return null\n\n return { params }\n }\n\n if (pathname === this.definition.pathname) {\n return {}\n }\n\n return null\n }\n}\n","import type { LocaleAnalysisResult } from '../lib/i18n-provider'\nimport type { LocaleRouteDefinition } from '../route-definitions/locale-route-definition'\nimport type { LocaleRouteMatch } from '../route-matches/locale-route-match'\nimport { RouteMatcher } from './route-matcher'\n\nexport type LocaleMatcherMatchOptions = {\n /**\n * If defined, this indicates to the matcher that the request should be\n * treated as locale-aware. If this is undefined, it means that this\n * application was not configured for additional locales.\n */\n i18n?: LocaleAnalysisResult\n}\n\nexport class LocaleRouteMatcher<\n D extends LocaleRouteDefinition = LocaleRouteDefinition,\n> extends RouteMatcher {\n /**\n * Identity returns the identity part of the matcher. This is used to compare\n * a unique matcher to another. This is also used when sorting dynamic routes,\n * so it must contain the pathname part as well.\n */\n public get identity(): string {\n return `${this.definition.pathname}?__nextLocale=${this.definition.i18n?.locale}`\n }\n\n /**\n * Match will attempt to match the given pathname against this route while\n * also taking into account the locale information.\n *\n * @param pathname The pathname to match against.\n * @param options The options to use when matching.\n * @returns The match result, or `null` if there was no match.\n */\n public match(\n pathname: string,\n options?: LocaleMatcherMatchOptions\n ): LocaleRouteMatch | null {\n // This is like the parent `match` method but instead this injects the\n // additional `options` into the\n const result = this.test(pathname, options)\n if (!result) return null\n\n return {\n definition: this.definition,\n params: result.params,\n detectedLocale:\n // If the options have a detected locale, then use that, otherwise use\n // the route's locale.\n options?.i18n?.detectedLocale ?? this.definition.i18n?.locale,\n }\n }\n\n /**\n * Test will attempt to match the given pathname against this route while\n * also taking into account the locale information.\n *\n * @param pathname The pathname to match against.\n * @param options The options to use when matching.\n * @returns The match result, or `null` if there was no match.\n */\n public test(pathname: string, options?: LocaleMatcherMatchOptions) {\n // If this route has locale information and we have detected a locale, then\n // we need to compare the detected locale to the route's locale.\n if (this.definition.i18n && options?.i18n) {\n // If we have detected a locale and it does not match this route's locale,\n // then this isn't a match!\n if (\n this.definition.i18n.locale &&\n options.i18n.detectedLocale &&\n this.definition.i18n.locale !== options.i18n.detectedLocale\n ) {\n return null\n }\n\n // Perform regular matching against the locale stripped pathname now, the\n // locale information matches!\n return super.test(options.i18n.pathname)\n }\n\n // If we don't have locale information, then we can just perform regular\n // matching.\n return super.test(pathname)\n }\n}\n","import { isDynamicRoute } from '../../shared/lib/router/utils'\nimport type { RouteKind } from '../route-kind'\nimport type { RouteMatch } from '../route-matches/route-match'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { RouteMatcherProvider } from '../route-matcher-providers/route-matcher-provider'\nimport type { RouteMatcher } from '../route-matchers/route-matcher'\nimport type { MatchOptions, RouteMatcherManager } from './route-matcher-manager'\nimport { getSortedRoutes } from '../../shared/lib/router/utils'\nimport { LocaleRouteMatcher } from '../route-matchers/locale-route-matcher'\nimport { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-slash'\nimport { DetachedPromise } from '../../lib/detached-promise'\n\ninterface RouteMatchers {\n static: ReadonlyArray\n dynamic: ReadonlyArray\n duplicates: Record>\n}\n\nexport class DefaultRouteMatcherManager implements RouteMatcherManager {\n private readonly providers: Array = []\n protected readonly matchers: RouteMatchers = {\n static: [],\n dynamic: [],\n duplicates: {},\n }\n private lastCompilationID = this.compilationID\n\n /**\n * When this value changes, it indicates that a change has been introduced\n * that requires recompilation.\n */\n private get compilationID() {\n return this.providers.length\n }\n\n private waitTillReadyPromise?: Promise\n public async waitTillReady(): Promise {\n if (this.waitTillReadyPromise) {\n await this.waitTillReadyPromise\n delete this.waitTillReadyPromise\n }\n }\n\n private previousMatchers: ReadonlyArray = []\n public async reload() {\n const { promise, resolve, reject } = new DetachedPromise()\n this.waitTillReadyPromise = promise\n\n // Grab the compilation ID for this run, we'll verify it at the end to\n // ensure that if any routes were added before reloading is finished that\n // we error out.\n const compilationID = this.compilationID\n\n try {\n // Collect all the matchers from each provider.\n const matchers: Array = []\n\n // Get all the providers matchers.\n const providersMatchers: ReadonlyArray> =\n await Promise.all(this.providers.map((provider) => provider.matchers()))\n\n // Use this to detect duplicate pathnames.\n const all = new Map()\n const duplicates: Record = {}\n for (const providerMatchers of providersMatchers) {\n for (const matcher of providerMatchers) {\n // Reset duplicated matches when reloading from pages conflicting state.\n if (matcher.duplicated) delete matcher.duplicated\n // Test to see if the matcher being added is a duplicate.\n const duplicate = all.get(matcher.definition.pathname)\n if (duplicate) {\n // This looks a little weird, but essentially if the pathname\n // already exists in the duplicates map, then we got that array\n // reference. Otherwise, we create a new array with the original\n // duplicate first. Then we push the new matcher into the duplicate\n // array, and reset it to the duplicates object (which may be a\n // no-op if the pathname already existed in the duplicates object).\n // Then we set the array of duplicates on both the original\n // duplicate object and the new one, so we can keep them in sync.\n // If a new duplicate is found, and it matches an existing pathname,\n // the retrieval of the `other` will actually return the array\n // reference used by all other duplicates. This is why ReadonlyArray\n // is so important! Array's are always references!\n const others = duplicates[matcher.definition.pathname] ?? [\n duplicate,\n ]\n others.push(matcher)\n duplicates[matcher.definition.pathname] = others\n\n // Add duplicated details to each route.\n duplicate.duplicated = others\n matcher.duplicated = others\n\n // TODO: see if we should error for duplicates in production?\n }\n\n matchers.push(matcher)\n\n // Add the matcher's pathname to the set.\n all.set(matcher.definition.pathname, matcher)\n }\n }\n\n // Update the duplicate matchers. This is used in the development manager\n // to warn about duplicates.\n this.matchers.duplicates = duplicates\n\n // If the cache is the same as what we just parsed, we can exit now. We\n // can tell by using the `===` which compares object identity, which for\n // the manifest matchers, will return the same matcher each time.\n if (\n this.previousMatchers.length === matchers.length &&\n this.previousMatchers.every(\n (cachedMatcher, index) => cachedMatcher === matchers[index]\n )\n ) {\n return\n }\n this.previousMatchers = matchers\n\n // For matchers that are for static routes, filter them now.\n this.matchers.static = matchers.filter((matcher) => !matcher.isDynamic)\n\n // For matchers that are for dynamic routes, filter them and sort them now.\n const dynamic = matchers.filter((matcher) => matcher.isDynamic)\n\n // As `getSortedRoutes` only takes an array of strings, we need to create\n // a map of the pathnames (used for sorting) and the matchers. When we\n // have locales, there may be multiple matches for the same pathname. To\n // handle this, we keep a map of all the indexes (in `reference`) and\n // merge them in later.\n\n const reference = new Map()\n const pathnames = new Array()\n for (let index = 0; index < dynamic.length; index++) {\n // Grab the pathname from the definition.\n const pathname = dynamic[index].definition.pathname\n\n // Grab the index in the dynamic array, push it into the reference.\n const indexes = reference.get(pathname) ?? []\n indexes.push(index)\n\n // If this is the first one set it. If it isn't, we don't need to\n // because pushing above on the array will mutate the array already\n // stored there because array's are always a reference!\n if (indexes.length === 1) reference.set(pathname, indexes)\n // Otherwise, continue, we've already added this pathname before.\n else continue\n\n pathnames.push(pathname)\n }\n\n // Sort the array of pathnames.\n const sorted = getSortedRoutes(pathnames)\n\n // For each of the sorted pathnames, iterate over them, grabbing the list\n // of indexes and merging them back into the new `sortedDynamicMatchers`\n // array. The order of the same matching pathname doesn't matter because\n // they will have other matching characteristics (like the locale) that\n // is considered.\n const sortedDynamicMatchers: Array = []\n for (const pathname of sorted) {\n const indexes = reference.get(pathname)\n if (!Array.isArray(indexes)) {\n throw new Error('Invariant: expected to find identity in indexes map')\n }\n\n const dynamicMatches = indexes.map((index) => dynamic[index])\n\n sortedDynamicMatchers.push(...dynamicMatches)\n }\n\n this.matchers.dynamic = sortedDynamicMatchers\n\n // This means that there was a new matcher pushed while we were waiting\n if (this.compilationID !== compilationID) {\n throw new Error(\n 'Invariant: expected compilation to finish before new matchers were added, possible missing await'\n )\n }\n } catch (err) {\n reject(err)\n } finally {\n // The compilation ID matched, so mark the complication as finished.\n this.lastCompilationID = compilationID\n resolve()\n }\n }\n\n public push(provider: RouteMatcherProvider): void {\n this.providers.push(provider)\n }\n\n public async test(pathname: string, options: MatchOptions): Promise {\n // See if there's a match for the pathname...\n const match = await this.match(pathname, options)\n\n // This default implementation only needs to check to see if there _was_ a\n // match. The development matcher actually changes it's behavior by not\n // recompiling the routes.\n return match !== null\n }\n\n public async match(\n pathname: string,\n options: MatchOptions\n ): Promise> | null> {\n // \"Iterate\" over the match options. Once we found a single match, exit with\n // it, otherwise return null below. If no match is found, the inner block\n // won't be called.\n for await (const match of this.matchAll(pathname, options)) {\n return match\n }\n\n return null\n }\n\n /**\n * This is a point for other managers to override to inject other checking\n * behavior like duplicate route checking on a per-request basis.\n *\n * @param pathname the pathname to validate against\n * @param matcher the matcher to validate/test with\n * @returns the match if found\n */\n protected validate(\n pathname: string,\n matcher: RouteMatcher,\n options: MatchOptions\n ): RouteMatch | null {\n if (matcher instanceof LocaleRouteMatcher) {\n return matcher.match(pathname, options)\n }\n\n // If the locale was inferred from the default locale, then it will have\n // already added a locale to the pathname. We need to remove it before\n // matching because this matcher is not locale aware.\n if (options.i18n?.inferredFromDefault) {\n return matcher.match(options.i18n.pathname)\n }\n\n return matcher.match(pathname)\n }\n\n public async *matchAll(\n pathname: string,\n options: MatchOptions\n ): AsyncGenerator>, null, undefined> {\n // Guard against the matcher manager from being run before it needs to be\n // recompiled. This was preferred to re-running the compilation here because\n // it should be re-ran only when it changes. If a match is attempted before\n // this is done, it indicates that there is a case where a provider is added\n // before it was recompiled (an error). We also don't want to affect request\n // times.\n if (this.lastCompilationID !== this.compilationID) {\n throw new Error(\n 'Invariant: expected routes to have been loaded before match'\n )\n }\n\n // Ensure that path matching is done with a leading slash.\n pathname = ensureLeadingSlash(pathname)\n\n // If this pathname doesn't look like a dynamic route, and this pathname is\n // listed in the normalized list of routes, then return it. This ensures\n // that when a route like `/user/[id]` is encountered, it doesn't just match\n // with the list of normalized routes.\n if (!isDynamicRoute(pathname)) {\n for (const matcher of this.matchers.static) {\n const match = this.validate(pathname, matcher, options)\n if (!match) continue\n\n yield match\n }\n }\n\n // If we should skip handling dynamic routes, exit now.\n if (options?.skipDynamic) return null\n\n // Loop over the dynamic matchers, yielding each match.\n for (const matcher of this.matchers.dynamic) {\n const match = this.validate(pathname, matcher, options)\n if (!match) continue\n\n yield match\n }\n\n // We tried direct matching against the pathname and against all the dynamic\n // paths, so there was no match.\n return null\n }\n}\n","import type { Normalizer } from './normalizer'\n\n/**\n * Normalizers combines many normalizers into a single normalizer interface that\n * will normalize the inputted pathname with each normalizer in order.\n */\nexport class Normalizers implements Normalizer {\n constructor(private readonly normalizers: Array = []) {}\n\n public push(normalizer: Normalizer) {\n this.normalizers.push(normalizer)\n }\n\n public normalize(pathname: string): string {\n return this.normalizers.reduce(\n (normalized, normalizer) => normalizer.normalize(normalized),\n pathname\n )\n }\n}\n","import path from '../../shared/lib/isomorphic/path'\nimport type { Normalizer } from './normalizer'\n\nexport class PrefixingNormalizer implements Normalizer {\n private readonly prefix: string\n\n constructor(...prefixes: ReadonlyArray) {\n this.prefix = path.posix.join(...prefixes)\n }\n\n public normalize(pathname: string): string {\n return path.posix.join(this.prefix, pathname)\n }\n}\n","import { ensureLeadingSlash } from './ensure-leading-slash'\nimport { isDynamicRoute } from '../router/utils'\nimport { NormalizeError } from '../utils'\n\n/**\n * Takes a page and transforms it into its file counterpart ensuring that the\n * output is normalized. Note this function is not idempotent because a page\n * `/index` can be referencing `/index/index.js` and `/index/index` could be\n * referencing `/index/index/index.js`. Examples:\n * - `/` -> `/index`\n * - `/index/foo` -> `/index/index/foo`\n * - `/index` -> `/index/index`\n */\nexport function normalizePagePath(page: string): string {\n const normalized =\n /^\\/index(\\/|$)/.test(page) && !isDynamicRoute(page)\n ? `/index${page}`\n : page === '/'\n ? '/index'\n : ensureLeadingSlash(page)\n\n if (process.env.NEXT_RUNTIME !== 'edge') {\n const { posix } = require('path') as typeof import('path')\n const resolvedPage = posix.normalize(normalized)\n if (resolvedPage !== normalized) {\n throw new NormalizeError(\n `Requested and resolved page mismatch: ${normalized} ${resolvedPage}`\n )\n }\n }\n\n return normalized\n}\n","import type { Normalizer } from './normalizer'\n\n/**\n * UnderscoreNormalizer replaces all instances of %5F with _.\n */\nexport class UnderscoreNormalizer implements Normalizer {\n public normalize(pathname: string): string {\n return pathname.replace(/%5F/g, '_')\n }\n}\n","import { Normalizers } from '../../normalizers'\nimport type { Normalizer } from '../../normalizer'\nimport { PrefixingNormalizer } from '../../prefixing-normalizer'\nimport { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path'\nimport { UnderscoreNormalizer } from '../../underscore-normalizer'\n\nexport class AppBundlePathNormalizer extends PrefixingNormalizer {\n constructor() {\n super('app')\n }\n\n public normalize(page: string): string {\n return super.normalize(normalizePagePath(page))\n }\n}\n\nexport class DevAppBundlePathNormalizer extends Normalizers {\n constructor(pageNormalizer: Normalizer, isTurbopack: boolean) {\n const normalizers = [\n // This should normalize the filename to a page.\n pageNormalizer,\n // Normalize the app page to a pathname.\n new AppBundlePathNormalizer(),\n ]\n\n // %5F to _ replacement should only happen with Turbopack.\n if (isTurbopack) {\n normalizers.unshift(new UnderscoreNormalizer())\n }\n super(normalizers)\n }\n\n public normalize(filename: string): string {\n return super.normalize(filename)\n }\n}\n","import { SERVER_DIRECTORY } from '../../../../shared/lib/constants'\nimport { PrefixingNormalizer } from '../../prefixing-normalizer'\n\nexport class AppFilenameNormalizer extends PrefixingNormalizer {\n constructor(distDir: string) {\n super(distDir, SERVER_DIRECTORY)\n }\n\n public normalize(manifestFilename: string): string {\n return super.normalize(manifestFilename)\n }\n}\n","export function isAppRouteRoute(route: string): boolean {\n return route.endsWith('/route')\n}\n","import type { PageExtensions } from '../../build/page-extensions-type'\nimport { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport { isAppRouteRoute } from '../is-app-route-route'\n\nexport const STATIC_METADATA_IMAGES = {\n icon: {\n filename: 'icon',\n extensions: ['ico', 'jpg', 'jpeg', 'png', 'svg'],\n },\n apple: {\n filename: 'apple-icon',\n extensions: ['jpg', 'jpeg', 'png'],\n },\n favicon: {\n filename: 'favicon',\n extensions: ['ico'],\n },\n openGraph: {\n filename: 'opengraph-image',\n extensions: ['jpg', 'jpeg', 'png', 'gif'],\n },\n twitter: {\n filename: 'twitter-image',\n extensions: ['jpg', 'jpeg', 'png', 'gif'],\n },\n} as const\n\n// Match routes that are metadata routes, e.g. /sitemap.xml, /favicon., /., 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 `/opengrapg-image.png`, `/opengraph-image.ts`\nexport const getExtensionRegexString = (\n staticExtensions: readonly string[],\n dynamicExtensions: readonly string[] | null\n) => {\n // If there's no possible multi dynamic routes, will not match any []. files\n if (!dynamicExtensions || dynamicExtensions.length === 0) {\n return `(\\\\.(?:${staticExtensions.join('|')}))`\n }\n return `(?:\\\\.(${staticExtensions.join('|')})|(\\\\.(${dynamicExtensions.join('|')})))`\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) {\n // End with the extension or optional to have the extension\n // When strictlyMatchExtensions is true, it's used for match file path;\n // When strictlyMatchExtensions, the dynamic extension is skipped but\n // static extension is kept, which is usually used for matching route path.\n const trailingMatcher = (strictlyMatchExtensions ? '' : '?') + '$'\n // Match the optional variants like /opengraph-image2, /icon-a102f4.png, etc.\n const variantsMatcher = '\\\\d?'\n // The -\\w{6} is the suffix that normalized from group routes;\n const groupSuffix = strictlyMatchExtensions ? '' : '(-\\\\w{6})?'\n\n const suffixMatcher = `${variantsMatcher}${groupSuffix}`\n\n const metadataRouteFilesRegex = [\n new RegExp(\n `^[\\\\\\\\/]robots${getExtensionRegexString(\n pageExtensions.concat('txt'),\n null\n )}${trailingMatcher}`\n ),\n new RegExp(\n `^[\\\\\\\\/]manifest${getExtensionRegexString(\n pageExtensions.concat('webmanifest', 'json'),\n null\n )}${trailingMatcher}`\n ),\n new RegExp(`^[\\\\\\\\/]favicon\\\\.ico$`),\n new RegExp(\n `[\\\\\\\\/]sitemap${getExtensionRegexString(['xml'], pageExtensions)}${trailingMatcher}`\n ),\n new RegExp(\n `[\\\\\\\\/]${STATIC_METADATA_IMAGES.icon.filename}${suffixMatcher}${getExtensionRegexString(\n STATIC_METADATA_IMAGES.icon.extensions,\n pageExtensions\n )}${trailingMatcher}`\n ),\n new RegExp(\n `[\\\\\\\\/]${STATIC_METADATA_IMAGES.apple.filename}${suffixMatcher}${getExtensionRegexString(\n STATIC_METADATA_IMAGES.apple.extensions,\n pageExtensions\n )}${trailingMatcher}`\n ),\n new RegExp(\n `[\\\\\\\\/]${STATIC_METADATA_IMAGES.openGraph.filename}${suffixMatcher}${getExtensionRegexString(\n STATIC_METADATA_IMAGES.openGraph.extensions,\n pageExtensions\n )}${trailingMatcher}`\n ),\n new RegExp(\n `[\\\\\\\\/]${STATIC_METADATA_IMAGES.twitter.filename}${suffixMatcher}${getExtensionRegexString(\n STATIC_METADATA_IMAGES.twitter.extensions,\n pageExtensions\n )}${trailingMatcher}`\n ),\n ]\n\n const normalizedAppDirRelativePath = normalizePathSep(appDirRelativePath)\n const matched = metadataRouteFilesRegex.some((r) =>\n r.test(normalizedAppDirRelativePath)\n )\n\n return matched\n}\n\n// Check if the route is a static metadata route, with /route suffix\n// e.g. /favicon.ico/route, /icon.png/route, etc.\n// But skip the text routes like robots.txt since they might also be dynamic.\n// Checking route path is not enough to determine if text routes is dynamic.\nexport function isStaticMetadataRoute(route: string) {\n // extract ext with regex\n const pathname = route.replace(/\\/route$/, '')\n\n const matched =\n isAppRouteRoute(route) &&\n isMetadataRouteFile(pathname, [], true) &&\n // These routes can either be built by static or dynamic entrypoints,\n // so we assume they're dynamic\n pathname !== '/robots.txt' &&\n pathname !== '/manifest.webmanifest' &&\n !pathname.endsWith('/sitemap.xml')\n\n return matched\n}\n\n/**\n * Determine if a page or pathname is a metadata page.\n *\n * The input is a page or pathname, which can be with or without page suffix /foo/page or /foo.\n * But it will not contain the /route suffix.\n *\n * .e.g\n * /robots -> true\n * /sitemap -> true\n * /foo -> false\n */\nexport function isMetadataPage(page: string) {\n const matched = !isAppRouteRoute(page) && isMetadataRouteFile(page, [], false)\n\n return matched\n}\n\n/*\n * Determine if a Next.js route is a metadata route.\n * `route` will has a route suffix.\n *\n * e.g.\n * /app/robots/route -> true\n * /robots/route -> true\n * /sitemap/[__metadata_id__]/route -> true\n * /app/sitemap/page -> false\n * /icon-a102f4/route -> true\n */\nexport function isMetadataRoute(route: string): boolean {\n let page = normalizeAppPath(route)\n .replace(/^\\/?app\\//, '')\n // Remove the dynamic route id\n .replace('/[__metadata_id__]', '')\n // Remove the /route suffix\n .replace(/\\/route$/, '')\n\n if (page[0] !== '/') page = '/' + page\n\n const matched = isAppRouteRoute(route) && isMetadataRouteFile(page, [], false)\n\n return matched\n}\n","import type { Normalizer } from './normalizer'\n\nexport function wrapNormalizerFn(fn: (pathname: string) => string): Normalizer {\n return { normalize: fn }\n}\n","import { normalizeAppPath } from '../../../../shared/lib/router/utils/app-paths'\nimport { Normalizers } from '../../normalizers'\nimport { wrapNormalizerFn } from '../../wrap-normalizer-fn'\nimport { UnderscoreNormalizer } from '../../underscore-normalizer'\nimport type { Normalizer } from '../../normalizer'\n\nexport class AppPathnameNormalizer extends Normalizers {\n constructor() {\n super([\n // The pathname to match should have the trailing `/page` and other route\n // group information stripped from it.\n wrapNormalizerFn(normalizeAppPath),\n // The page should have the `%5F` characters replaced with `_` characters.\n new UnderscoreNormalizer(),\n ])\n }\n\n public normalize(page: string): string {\n return super.normalize(page)\n }\n}\n\nexport class DevAppPathnameNormalizer extends Normalizers {\n constructor(pageNormalizer: Normalizer) {\n super([\n // This should normalize the filename to a page.\n pageNormalizer,\n // Normalize the app page to a pathname.\n new AppPathnameNormalizer(),\n ])\n }\n\n public normalize(filename: string): string {\n return super.normalize(filename)\n }\n}\n","import {\n AppBundlePathNormalizer,\n DevAppBundlePathNormalizer,\n} from './app-bundle-path-normalizer'\nimport { AppFilenameNormalizer } from './app-filename-normalizer'\nimport { DevAppPageNormalizer } from './app-page-normalizer'\nimport {\n AppPathnameNormalizer,\n DevAppPathnameNormalizer,\n} from './app-pathname-normalizer'\n\nexport class AppNormalizers {\n public readonly filename: AppFilenameNormalizer\n public readonly pathname: AppPathnameNormalizer\n public readonly bundlePath: AppBundlePathNormalizer\n\n constructor(distDir: string) {\n this.filename = new AppFilenameNormalizer(distDir)\n this.pathname = new AppPathnameNormalizer()\n this.bundlePath = new AppBundlePathNormalizer()\n }\n}\n\nexport class DevAppNormalizers {\n public readonly page: DevAppPageNormalizer\n public readonly pathname: DevAppPathnameNormalizer\n public readonly bundlePath: DevAppBundlePathNormalizer\n\n constructor(\n appDir: string,\n extensions: ReadonlyArray,\n isTurbopack: boolean\n ) {\n this.page = new DevAppPageNormalizer(appDir, extensions, isTurbopack)\n this.pathname = new DevAppPathnameNormalizer(this.page)\n this.bundlePath = new DevAppBundlePathNormalizer(this.page, isTurbopack)\n }\n}\n","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 { RouteMatcher } from './route-matcher'\nimport type { AppPageRouteDefinition } from '../route-definitions/app-page-route-definition'\n\nexport class AppPageRouteMatcher extends RouteMatcher {\n public get identity(): string {\n return `${this.definition.pathname}?__nextPage=${this.definition.page}`\n }\n}\n","import type { RouteMatcherProvider } from '../route-matcher-provider'\nimport type { RouteMatcher } from '../../route-matchers/route-matcher'\n\ninterface LoaderComparable {\n load(): Promise\n compare(left: D, right: D): boolean\n}\n\n/**\n * This will memoize the matchers if the loaded data is comparable.\n */\nexport abstract class CachedRouteMatcherProvider<\n M extends RouteMatcher = RouteMatcher,\n D = any,\n> implements RouteMatcherProvider\n{\n private data?: D\n private cached: ReadonlyArray = []\n\n constructor(private readonly loader: LoaderComparable) {}\n\n protected abstract transform(data: D): Promise>\n\n public async matchers(): Promise {\n const data = await this.loader.load()\n if (!data) return []\n\n // Return the cached matchers if the data has not changed.\n if (this.data && this.loader.compare(this.data, data)) return this.cached\n this.data = data\n\n // Transform the manifest into matchers.\n const matchers = await this.transform(data)\n\n // Cache the matchers.\n this.cached = matchers\n\n return matchers\n }\n}\n","import type { RouteMatcher } from '../route-matchers/route-matcher'\nimport type {\n Manifest,\n ManifestLoader,\n} from './helpers/manifest-loaders/manifest-loader'\nimport { CachedRouteMatcherProvider } from './helpers/cached-route-matcher-provider'\n\nexport abstract class ManifestRouteMatcherProvider<\n M extends RouteMatcher = RouteMatcher,\n> extends CachedRouteMatcherProvider {\n constructor(manifestName: string, manifestLoader: ManifestLoader) {\n super({\n load: async () => manifestLoader.load(manifestName),\n compare: (left, right) => left === right,\n })\n }\n}\n","import { isAppPageRoute } from '../../lib/is-app-page-route'\n\nimport { APP_PATHS_MANIFEST } from '../../shared/lib/constants'\nimport { AppNormalizers } from '../normalizers/built/app'\nimport { RouteKind } from '../route-kind'\nimport { AppPageRouteMatcher } from '../route-matchers/app-page-route-matcher'\nimport type {\n Manifest,\n ManifestLoader,\n} from './helpers/manifest-loaders/manifest-loader'\nimport { ManifestRouteMatcherProvider } from './manifest-route-matcher-provider'\n\nexport class AppPageRouteMatcherProvider extends ManifestRouteMatcherProvider {\n private readonly normalizers: AppNormalizers\n\n constructor(distDir: string, manifestLoader: ManifestLoader) {\n super(APP_PATHS_MANIFEST, manifestLoader)\n\n this.normalizers = new AppNormalizers(distDir)\n }\n\n protected async transform(\n manifest: Manifest\n ): Promise> {\n // This matcher only matches app pages.\n const pages = Object.keys(manifest).filter((page) => isAppPageRoute(page))\n\n // Collect all the app paths for each page. This could include any parallel\n // routes.\n const allAppPaths: Record = {}\n for (const page of pages) {\n const pathname = this.normalizers.pathname.normalize(page)\n if (pathname in allAppPaths) allAppPaths[pathname].push(page)\n else allAppPaths[pathname] = [page]\n }\n\n // Format the routes.\n const matchers: Array = []\n for (const [pathname, appPaths] of Object.entries(allAppPaths)) {\n // TODO-APP: (wyattjoh) this is a hack right now, should be more deterministic\n const page = appPaths[0]\n\n const filename = this.normalizers.filename.normalize(manifest[page])\n const bundlePath = this.normalizers.bundlePath.normalize(page)\n\n matchers.push(\n new AppPageRouteMatcher({\n kind: RouteKind.APP_PAGE,\n pathname,\n page,\n bundlePath,\n filename,\n appPaths,\n })\n )\n }\n\n return matchers\n }\n}\n","export function isAppPageRoute(route: string): boolean {\n return route.endsWith('/page')\n}\n","import { RouteMatcher } from './route-matcher'\nimport type { AppRouteRouteDefinition } from '../route-definitions/app-route-route-definition'\n\nexport class AppRouteRouteMatcher extends RouteMatcher {}\n","import { isAppRouteRoute } from '../../lib/is-app-route-route'\nimport { APP_PATHS_MANIFEST } from '../../shared/lib/constants'\nimport { RouteKind } from '../route-kind'\nimport { AppRouteRouteMatcher } from '../route-matchers/app-route-route-matcher'\nimport type {\n Manifest,\n ManifestLoader,\n} from './helpers/manifest-loaders/manifest-loader'\nimport { ManifestRouteMatcherProvider } from './manifest-route-matcher-provider'\nimport { AppNormalizers } from '../normalizers/built/app'\n\nexport class AppRouteRouteMatcherProvider extends ManifestRouteMatcherProvider {\n private readonly normalizers: AppNormalizers\n\n constructor(distDir: string, manifestLoader: ManifestLoader) {\n super(APP_PATHS_MANIFEST, manifestLoader)\n\n this.normalizers = new AppNormalizers(distDir)\n }\n\n protected async transform(\n manifest: Manifest\n ): Promise> {\n // This matcher only matches app routes.\n const pages = Object.keys(manifest).filter((page) => isAppRouteRoute(page))\n\n // Format the routes.\n const matchers: Array = []\n for (const page of pages) {\n const filename = this.normalizers.filename.normalize(manifest[page])\n const pathname = this.normalizers.pathname.normalize(page)\n const bundlePath = this.normalizers.bundlePath.normalize(page)\n\n matchers.push(\n new AppRouteRouteMatcher({\n kind: RouteKind.APP_ROUTE,\n pathname,\n page,\n bundlePath,\n filename,\n })\n )\n }\n\n return matchers\n }\n}\n","export function isAPIRoute(value?: string) {\n return value === '/api' || Boolean(value?.startsWith('/api/'))\n}\n","import type { PagesAPIRouteDefinition } from '../route-definitions/pages-api-route-definition'\nimport { LocaleRouteMatcher } from './locale-route-matcher'\nimport { RouteMatcher } from './route-matcher'\n\nexport class PagesAPIRouteMatcher extends RouteMatcher {}\n\nexport class PagesAPILocaleRouteMatcher extends LocaleRouteMatcher {}\n","import { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path'\nimport type { Normalizer } from '../../normalizer'\nimport { Normalizers } from '../../normalizers'\nimport { PrefixingNormalizer } from '../../prefixing-normalizer'\nimport { wrapNormalizerFn } from '../../wrap-normalizer-fn'\n\nexport class PagesBundlePathNormalizer extends Normalizers {\n constructor() {\n super([\n // The bundle path should have the trailing `/index` stripped from\n // it.\n wrapNormalizerFn(normalizePagePath),\n // The page should prefixed with `pages/`.\n new PrefixingNormalizer('pages'),\n ])\n }\n\n public normalize(page: string): string {\n return super.normalize(page)\n }\n}\n\nexport class DevPagesBundlePathNormalizer extends Normalizers {\n constructor(pagesNormalizer: Normalizer) {\n super([\n // This should normalize the filename to a page.\n pagesNormalizer,\n // Normalize the app page to a pathname.\n new PagesBundlePathNormalizer(),\n ])\n }\n\n public normalize(filename: string): string {\n return super.normalize(filename)\n }\n}\n","import { SERVER_DIRECTORY } from '../../../../shared/lib/constants'\nimport { PrefixingNormalizer } from '../../prefixing-normalizer'\n\nexport class PagesFilenameNormalizer extends PrefixingNormalizer {\n constructor(distDir: string) {\n super(distDir, SERVER_DIRECTORY)\n }\n\n public normalize(manifestFilename: string): string {\n return super.normalize(manifestFilename)\n }\n}\n","import {\n DevPagesBundlePathNormalizer,\n PagesBundlePathNormalizer,\n} from './pages-bundle-path-normalizer'\nimport { PagesFilenameNormalizer } from './pages-filename-normalizer'\nimport { DevPagesPageNormalizer } from './pages-page-normalizer'\nimport { DevPagesPathnameNormalizer } from './pages-pathname-normalizer'\n\nexport class PagesNormalizers {\n public readonly filename: PagesFilenameNormalizer\n public readonly bundlePath: PagesBundlePathNormalizer\n\n constructor(distDir: string) {\n this.filename = new PagesFilenameNormalizer(distDir)\n this.bundlePath = new PagesBundlePathNormalizer()\n\n // You'd think that we'd require a `pathname` normalizer here, but for\n // `/pages` we have to handle i18n routes, which means that we need to\n // analyze the page path to determine the locale prefix and it's locale.\n }\n}\n\nexport class DevPagesNormalizers {\n public readonly page: DevPagesPageNormalizer\n public readonly pathname: DevPagesPathnameNormalizer\n public readonly bundlePath: DevPagesBundlePathNormalizer\n\n constructor(pagesDir: string, extensions: ReadonlyArray) {\n this.page = new DevPagesPageNormalizer(pagesDir, extensions)\n this.pathname = new DevPagesPathnameNormalizer(pagesDir, extensions)\n this.bundlePath = new DevPagesBundlePathNormalizer(this.page)\n }\n}\n","import { isAPIRoute } from '../../lib/is-api-route'\nimport { PAGES_MANIFEST } from '../../shared/lib/constants'\nimport { RouteKind } from '../route-kind'\nimport {\n PagesAPILocaleRouteMatcher,\n PagesAPIRouteMatcher,\n} from '../route-matchers/pages-api-route-matcher'\nimport type {\n Manifest,\n ManifestLoader,\n} from './helpers/manifest-loaders/manifest-loader'\nimport { ManifestRouteMatcherProvider } from './manifest-route-matcher-provider'\nimport type { I18NProvider } from '../lib/i18n-provider'\nimport { PagesNormalizers } from '../normalizers/built/pages'\n\nexport class PagesAPIRouteMatcherProvider extends ManifestRouteMatcherProvider {\n private readonly normalizers: PagesNormalizers\n\n constructor(\n distDir: string,\n manifestLoader: ManifestLoader,\n private readonly i18nProvider?: I18NProvider\n ) {\n super(PAGES_MANIFEST, manifestLoader)\n\n this.normalizers = new PagesNormalizers(distDir)\n }\n\n protected async transform(\n manifest: Manifest\n ): Promise> {\n // This matcher is only for Pages API routes.\n const pathnames = Object.keys(manifest).filter((pathname) =>\n isAPIRoute(pathname)\n )\n\n const matchers: Array = []\n\n for (const page of pathnames) {\n if (this.i18nProvider) {\n // Match the locale on the page name, or default to the default locale.\n const { detectedLocale, pathname } = this.i18nProvider.analyze(page)\n\n matchers.push(\n new PagesAPILocaleRouteMatcher({\n kind: RouteKind.PAGES_API,\n pathname,\n page,\n bundlePath: this.normalizers.bundlePath.normalize(page),\n filename: this.normalizers.filename.normalize(manifest[page]),\n i18n: {\n locale: detectedLocale,\n },\n })\n )\n } else {\n matchers.push(\n new PagesAPIRouteMatcher({\n kind: RouteKind.PAGES_API,\n // In `pages/`, the page is the same as the pathname.\n pathname: page,\n page,\n bundlePath: this.normalizers.bundlePath.normalize(page),\n filename: this.normalizers.filename.normalize(manifest[page]),\n })\n )\n }\n }\n\n return matchers\n }\n}\n","import type { PagesRouteDefinition } from '../route-definitions/pages-route-definition'\nimport { LocaleRouteMatcher } from './locale-route-matcher'\nimport { RouteMatcher } from './route-matcher'\n\nexport class PagesRouteMatcher extends RouteMatcher {}\n\nexport class PagesLocaleRouteMatcher extends LocaleRouteMatcher {}\n","import { isAPIRoute } from '../../lib/is-api-route'\nimport { BLOCKED_PAGES, PAGES_MANIFEST } from '../../shared/lib/constants'\nimport { RouteKind } from '../route-kind'\nimport {\n PagesLocaleRouteMatcher,\n PagesRouteMatcher,\n} from '../route-matchers/pages-route-matcher'\nimport type {\n Manifest,\n ManifestLoader,\n} from './helpers/manifest-loaders/manifest-loader'\nimport { ManifestRouteMatcherProvider } from './manifest-route-matcher-provider'\nimport type { I18NProvider } from '../lib/i18n-provider'\nimport { PagesNormalizers } from '../normalizers/built/pages'\n\nexport class PagesRouteMatcherProvider extends ManifestRouteMatcherProvider {\n private readonly normalizers: PagesNormalizers\n\n constructor(\n distDir: string,\n manifestLoader: ManifestLoader,\n private readonly i18nProvider?: I18NProvider\n ) {\n super(PAGES_MANIFEST, manifestLoader)\n\n this.normalizers = new PagesNormalizers(distDir)\n }\n\n protected async transform(\n manifest: Manifest\n ): Promise> {\n // This matcher is only for Pages routes, not Pages API routes which are\n // included in this manifest.\n const pathnames = Object.keys(manifest)\n .filter((pathname) => !isAPIRoute(pathname))\n // Remove any blocked pages (page that can't be routed to, like error or\n // internal pages).\n .filter((pathname) => {\n const normalized =\n this.i18nProvider?.analyze(pathname).pathname ?? pathname\n\n // Skip any blocked pages.\n if (BLOCKED_PAGES.includes(normalized)) return false\n\n return true\n })\n\n const matchers: Array = []\n for (const page of pathnames) {\n if (this.i18nProvider) {\n // Match the locale on the page name, or default to the default locale.\n const { detectedLocale, pathname } = this.i18nProvider.analyze(page)\n\n matchers.push(\n new PagesLocaleRouteMatcher({\n kind: RouteKind.PAGES,\n pathname,\n page,\n bundlePath: this.normalizers.bundlePath.normalize(page),\n filename: this.normalizers.filename.normalize(manifest[page]),\n i18n: {\n locale: detectedLocale,\n },\n })\n )\n } else {\n matchers.push(\n new PagesRouteMatcher({\n kind: RouteKind.PAGES,\n // In `pages/`, the page is the same as the pathname.\n pathname: page,\n page,\n bundlePath: this.normalizers.bundlePath.normalize(page),\n filename: this.normalizers.filename.normalize(manifest[page]),\n })\n )\n }\n }\n\n return matchers\n }\n}\n","import type { Manifest, ManifestLoader } from './manifest-loader'\n\nexport class ServerManifestLoader implements ManifestLoader {\n constructor(private readonly getter: (name: string) => Manifest | null) {}\n\n public load(name: string): Manifest | null {\n return this.getter(name)\n }\n}\n","import type { DomainLocale, I18NConfig } from '../config-shared'\nimport { getRequestMeta, type NextIncomingMessage } from '../request-meta'\n\n/**\n * The result of matching a locale aware route.\n */\nexport interface LocaleAnalysisResult {\n /**\n * The pathname without the locale prefix (if any).\n */\n pathname: string\n\n /**\n * The detected locale. If no locale was detected, this will be `undefined`.\n */\n detectedLocale?: string\n\n /**\n * True if the locale was inferred from the default locale.\n */\n inferredFromDefault: boolean\n}\n\ntype LocaleAnalysisOptions = {\n /**\n * When provided, it will be used as the default locale if the locale\n * cannot be inferred from the pathname.\n */\n defaultLocale?: string\n}\n\n/**\n * The I18NProvider is used to match locale aware routes, detect the locale from\n * the pathname and hostname and normalize the pathname by removing the locale\n * prefix.\n */\nexport class I18NProvider {\n private readonly lowerCaseLocales: ReadonlyArray\n private readonly lowerCaseDomains?: ReadonlyArray<\n DomainLocale & {\n // The configuration references a domain with an optional port, but the\n // hostname is always the domain without the port and is used for\n // matching.\n hostname: string\n }\n >\n\n constructor(public readonly config: Readonly) {\n if (!config.locales.length) {\n throw new Error('Invariant: No locales provided')\n }\n\n this.lowerCaseLocales = config.locales.map((locale) => locale.toLowerCase())\n this.lowerCaseDomains = config.domains?.map((domainLocale) => {\n const domain = domainLocale.domain.toLowerCase()\n return {\n defaultLocale: domainLocale.defaultLocale.toLowerCase(),\n hostname: domain.split(':', 1)[0],\n domain,\n locales: domainLocale.locales?.map((locale) => locale.toLowerCase()),\n http: domainLocale.http,\n }\n })\n }\n\n /**\n * Detects the domain locale from the hostname and the detected locale if\n * provided.\n *\n * @param hostname The hostname to detect the domain locale from, this must be lowercased.\n * @param detectedLocale The detected locale to use if the hostname does not match.\n * @returns The domain locale if found, `undefined` otherwise.\n */\n public detectDomainLocale(\n hostname?: string,\n detectedLocale?: string\n ): DomainLocale | undefined {\n if (!hostname || !this.lowerCaseDomains || !this.config.domains) return\n\n if (detectedLocale) detectedLocale = detectedLocale.toLowerCase()\n\n for (let i = 0; i < this.lowerCaseDomains.length; i++) {\n const domainLocale = this.lowerCaseDomains[i]\n if (\n // We assume that the hostname is already lowercased.\n domainLocale.hostname === hostname ||\n // Configuration validation ensures that the locale is not repeated in\n // other domains locales.\n domainLocale.locales?.some((locale) => locale === detectedLocale)\n ) {\n return this.config.domains[i]\n }\n }\n\n return\n }\n\n /**\n * Pulls the pre-computed locale and inference results from the query\n * object.\n *\n * @param req the request object\n * @param pathname the pathname that could contain a locale prefix\n * @returns the locale analysis result\n */\n public fromRequest(\n req: NextIncomingMessage,\n pathname: string\n ): LocaleAnalysisResult {\n const detectedLocale = getRequestMeta(req, 'locale')\n\n // If a locale was detected on the query, analyze the pathname to ensure\n // that the locale matches.\n if (detectedLocale) {\n const analysis = this.analyze(pathname)\n\n // If the analysis contained a locale we should validate it against the\n // query and strip it from the pathname.\n if (analysis.detectedLocale) {\n if (analysis.detectedLocale !== detectedLocale) {\n console.warn(\n `The detected locale does not match the locale in the query. Expected to find '${detectedLocale}' in '${pathname}' but found '${analysis.detectedLocale}'}`\n )\n }\n\n pathname = analysis.pathname\n }\n }\n\n return {\n pathname,\n detectedLocale,\n inferredFromDefault:\n getRequestMeta(req, 'localeInferredFromDefault') ?? false,\n }\n }\n\n /**\n * Analyzes the pathname for a locale and returns the pathname without it.\n *\n * @param pathname The pathname that could contain a locale prefix.\n * @param options The options to use when matching the locale.\n * @returns The matched locale and the pathname without the locale prefix\n * (if any).\n */\n public analyze(\n pathname: string,\n options: LocaleAnalysisOptions = {}\n ): LocaleAnalysisResult {\n let detectedLocale: string | undefined = options.defaultLocale\n\n // By default, we assume that the default locale was inferred if there was\n // no detected locale.\n let inferredFromDefault = typeof detectedLocale === 'string'\n\n // The first segment will be empty, because it has a leading `/`. If\n // there is no further segment, there is no locale (or it's the default).\n const segments = pathname.split('/', 2)\n if (!segments[1])\n return {\n detectedLocale,\n pathname,\n inferredFromDefault,\n }\n\n // The second segment will contain the locale part if any.\n const segment = segments[1].toLowerCase()\n\n // See if the segment matches one of the locales. If it doesn't, there is\n // no locale (or it's the default).\n const index = this.lowerCaseLocales.indexOf(segment)\n if (index < 0)\n return {\n detectedLocale,\n pathname,\n inferredFromDefault,\n }\n\n // Return the case-sensitive locale.\n detectedLocale = this.config.locales[index]\n inferredFromDefault = false\n\n // Remove the `/${locale}` part of the pathname.\n pathname = pathname.slice(detectedLocale.length + 1) || '/'\n\n return {\n detectedLocale,\n pathname,\n inferredFromDefault,\n }\n }\n}\n","import type { BaseNextRequest, BaseNextResponse } from './base-http'\nimport { isNodeNextResponse } from './base-http/helpers'\n\nimport { pipeToNodeResponse } from './pipe-readable'\nimport { splitCookiesString } from './web/utils'\n\n/**\n * Sends the response on the underlying next response object.\n *\n * @param req the underlying request object\n * @param res the underlying response object\n * @param response the response to send\n */\nexport async function sendResponse(\n req: BaseNextRequest,\n res: BaseNextResponse,\n response: Response,\n waitUntil?: Promise\n): Promise {\n if (\n // The type check here ensures that `req` is correctly typed, and the\n // environment variable check provides dead code elimination.\n process.env.NEXT_RUNTIME !== 'edge' &&\n isNodeNextResponse(res)\n ) {\n // Copy over the response status.\n res.statusCode = response.status\n res.statusMessage = response.statusText\n\n // TODO: this is not spec-compliant behavior and we should not restrict\n // headers that are allowed to appear many times.\n //\n // See:\n // https://github.com/vercel/next.js/pull/70127\n const headersWithMultipleValuesAllowed = [\n // can add more headers to this list if needed\n 'set-cookie',\n 'www-authenticate',\n 'proxy-authenticate',\n 'vary',\n ]\n\n // Copy over the response headers.\n response.headers?.forEach((value, name) => {\n // `x-middleware-set-cookie` is an internal header not needed for the response\n if (name.toLowerCase() === 'x-middleware-set-cookie') {\n return\n }\n\n // The append handling is special cased for `set-cookie`.\n if (name.toLowerCase() === 'set-cookie') {\n // TODO: (wyattjoh) replace with native response iteration when we can upgrade undici\n for (const cookie of splitCookiesString(value)) {\n res.appendHeader(name, cookie)\n }\n } else {\n // only append the header if it is either not present in the outbound response\n // or if the header supports multiple values\n const isHeaderPresent = typeof res.getHeader(name) !== 'undefined'\n if (\n headersWithMultipleValuesAllowed.includes(name.toLowerCase()) ||\n !isHeaderPresent\n ) {\n res.appendHeader(name, value)\n }\n }\n })\n\n /**\n * The response can't be directly piped to the underlying response. The\n * following is duplicated from the edge runtime handler.\n *\n * See packages/next/server/next-server.ts\n */\n\n const { originalResponse } = res\n\n // A response body must not be sent for HEAD requests. See https://httpwg.org/specs/rfc9110.html#HEAD\n if (response.body && req.method !== 'HEAD') {\n await pipeToNodeResponse(response.body, originalResponse, waitUntil)\n } else {\n originalResponse.end()\n }\n }\n}\n","import { getPathMatch } from '../../shared/lib/router/utils/path-match'\n\nconst matcher = getPathMatch('/_next/data/:path*')\n\nexport function matchNextDataPathname(pathname: string | null | undefined) {\n if (typeof pathname !== 'string') return false\n\n return matcher(pathname)\n}\n","import type { Normalizer } from '../normalizer'\n\nexport class SuffixPathnameNormalizer implements Normalizer {\n constructor(private readonly suffix: string) {}\n\n public match(pathname: string) {\n // If the pathname doesn't end in the suffix, we don't match.\n if (!pathname.endsWith(this.suffix)) return false\n\n return true\n }\n\n public normalize(pathname: string, matched?: boolean): string {\n // If we're not matched and we don't match, we don't need to normalize.\n if (!matched && !this.match(pathname)) return pathname\n\n return pathname.substring(0, pathname.length - this.suffix.length)\n }\n}\n","import type { PathnameNormalizer } from './pathname-normalizer'\n\nimport { RSC_SUFFIX } from '../../../lib/constants'\nimport { SuffixPathnameNormalizer } from './suffix'\n\nexport class RSCPathnameNormalizer\n extends SuffixPathnameNormalizer\n implements PathnameNormalizer\n{\n constructor() {\n super(RSC_SUFFIX)\n }\n}\n","import type { PathnameNormalizer } from './pathname-normalizer'\n\nimport { RSC_PREFETCH_SUFFIX } from '../../../lib/constants'\nimport { SuffixPathnameNormalizer } from './suffix'\n\nexport class PrefetchRSCPathnameNormalizer\n extends SuffixPathnameNormalizer\n implements PathnameNormalizer\n{\n constructor() {\n super(RSC_PREFETCH_SUFFIX)\n }\n\n public match(pathname: string): boolean {\n if (pathname === '/__index' + RSC_PREFETCH_SUFFIX) {\n return true\n }\n\n return super.match(pathname)\n }\n\n public normalize(pathname: string, matched?: boolean): string {\n if (pathname === '/__index' + RSC_PREFETCH_SUFFIX) {\n return '/'\n }\n\n return super.normalize(pathname, matched)\n }\n}\n","import type { Normalizer } from '../normalizer'\n\nexport class PrefixPathnameNormalizer implements Normalizer {\n constructor(private readonly prefix: string) {\n if (prefix.endsWith('/')) {\n throw new Error(\n `PrefixPathnameNormalizer: prefix \"${prefix}\" should not end with a slash`\n )\n }\n }\n\n public match(pathname: string) {\n // If the pathname doesn't start with the prefix, we don't match.\n if (pathname !== this.prefix && !pathname.startsWith(this.prefix + '/')) {\n return false\n }\n\n return true\n }\n\n public normalize(pathname: string, matched?: boolean): string {\n // If we're not matched and we don't match, we don't need to normalize.\n if (!matched && !this.match(pathname)) return pathname\n\n if (pathname.length === this.prefix.length) {\n return '/'\n }\n\n return pathname.substring(this.prefix.length)\n }\n}\n","import type { PathnameNormalizer } from './pathname-normalizer'\n\nimport { denormalizePagePath } from '../../../shared/lib/page-path/denormalize-page-path'\nimport { PrefixPathnameNormalizer } from './prefix'\nimport { SuffixPathnameNormalizer } from './suffix'\n\nexport class NextDataPathnameNormalizer implements PathnameNormalizer {\n private readonly prefix: PrefixPathnameNormalizer\n private readonly suffix = new SuffixPathnameNormalizer('.json')\n constructor(buildID: string) {\n if (!buildID) {\n throw new Error('Invariant: buildID is required')\n }\n\n this.prefix = new PrefixPathnameNormalizer(`/_next/data/${buildID}`)\n }\n\n public match(pathname: string) {\n return this.prefix.match(pathname) && this.suffix.match(pathname)\n }\n\n public normalize(pathname: string, matched?: boolean): string {\n // If we're not matched and we don't match, we don't need to normalize.\n if (!matched && !this.match(pathname)) return pathname\n\n pathname = this.prefix.normalize(pathname, true)\n pathname = this.suffix.normalize(pathname, true)\n\n return denormalizePagePath(pathname)\n }\n}\n","/**\n * This transforms a URL pathname into a route. It removes any trailing slashes\n * and the `/index` suffix.\n *\n * @param pathname - The URL path that needs to be optimized.\n * @returns - The route\n *\n * @example\n * // returns '/example'\n * toRoute('/example/index/');\n *\n * @example\n * // returns '/example'\n * toRoute('/example/');\n *\n * @example\n * // returns '/'\n * toRoute('/index/');\n *\n * @example\n * // returns '/'\n * toRoute('/');\n */\nexport function toRoute(pathname: string): string {\n return pathname.replace(/(?:\\/index)?\\/?$/, '') || '/'\n}\n","import type { AsyncLocalStorage } from 'async_hooks'\n\nconst sharedAsyncLocalStorageNotAvailableError = new Error(\n 'Invariant: AsyncLocalStorage accessed in runtime where it is not available'\n)\n\nclass FakeAsyncLocalStorage\n implements AsyncLocalStorage\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 {\n throw sharedAsyncLocalStorageNotAvailableError\n }\n\n exit(): R {\n throw sharedAsyncLocalStorageNotAvailableError\n }\n\n enterWith(): void {\n throw sharedAsyncLocalStorageNotAvailableError\n }\n\n static bind(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 {\n if (maybeGlobalAsyncLocalStorage) {\n return new maybeGlobalAsyncLocalStorage()\n }\n return new FakeAsyncLocalStorage()\n}\n\nexport function bindSnapshot(fn: T): T {\n if (maybeGlobalAsyncLocalStorage) {\n return maybeGlobalAsyncLocalStorage.bind(fn)\n }\n return FakeAsyncLocalStorage.bind(fn)\n}\n\nexport function createSnapshot(): (\n fn: (...args: TArgs) => R,\n ...args: TArgs\n) => R {\n if (maybeGlobalAsyncLocalStorage) {\n return maybeGlobalAsyncLocalStorage.snapshot()\n }\n return function (fn: any, ...args: any[]) {\n return fn(...args)\n }\n}\n","import { createAsyncLocalStorage } from '../app-render/async-local-storage'\n\nexport function getBuiltinRequestContext():\n | BuiltinRequestContextValue\n | undefined {\n const _globalThis = globalThis as GlobalThisWithRequestContext\n const ctx = _globalThis[NEXT_REQUEST_CONTEXT_SYMBOL]\n return ctx?.get()\n}\n\nconst NEXT_REQUEST_CONTEXT_SYMBOL = Symbol.for('@next/request-context')\n\ntype GlobalThisWithRequestContext = typeof globalThis & {\n [NEXT_REQUEST_CONTEXT_SYMBOL]?: BuiltinRequestContext\n}\n\n/** A request context provided by the platform. */\nexport type BuiltinRequestContext = {\n get(): BuiltinRequestContextValue | undefined\n}\n\nexport type RunnableBuiltinRequestContext = BuiltinRequestContext & {\n run(value: BuiltinRequestContextValue, callback: () => T): T\n}\n\nexport type BuiltinRequestContextValue = {\n waitUntil?: WaitUntil\n}\nexport type WaitUntil = (promise: Promise) => void\n\n/** \"@next/request-context\" has a different signature from AsyncLocalStorage,\n * matching [AsyncContext.Variable](https://github.com/tc39/proposal-async-context).\n * We don't need a full AsyncContext adapter here, just having `.get()` is enough\n */\nexport function createLocalRequestContext(): RunnableBuiltinRequestContext {\n const storage = createAsyncLocalStorage()\n return {\n get: () => storage.getStore(),\n run: (value, callback) => storage.run(value, callback),\n }\n}\n","import type { WaitUntil } from '../../after/builtin-request-context'\nimport { PageSignatureError } from '../error'\nimport type { NextRequest } from './request'\n\nconst responseSymbol = Symbol('response')\nconst passThroughSymbol = Symbol('passThrough')\nconst waitUntilSymbol = Symbol('waitUntil')\n\nclass FetchEvent {\n // TODO(after): get rid of the 'internal' variant and always use an external waitUntil\n // (this means removing `FetchEventResult.waitUntil` which also requires a builder change)\n readonly [waitUntilSymbol]:\n | { kind: 'internal'; promises: Promise[] }\n | { kind: 'external'; function: WaitUntil };\n\n [responseSymbol]?: Promise;\n [passThroughSymbol] = false\n\n constructor(_request: Request, waitUntil?: WaitUntil) {\n this[waitUntilSymbol] = waitUntil\n ? { kind: 'external', function: waitUntil }\n : { kind: 'internal', promises: [] }\n }\n\n // TODO: is this dead code? NextFetchEvent never lets this get called\n respondWith(response: Response | Promise): void {\n if (!this[responseSymbol]) {\n this[responseSymbol] = Promise.resolve(response)\n }\n }\n\n // TODO: is this dead code? passThroughSymbol is unused\n passThroughOnException(): void {\n this[passThroughSymbol] = true\n }\n\n waitUntil(promise: Promise): void {\n if (this[waitUntilSymbol].kind === 'external') {\n // if we received an external waitUntil, we delegate to it\n // TODO(after): this will make us not go through `getServerError(error, 'edge-server')` in `sandbox`\n const waitUntil = this[waitUntilSymbol].function\n return waitUntil(promise)\n } else {\n // if we didn't receive an external waitUntil, we make it work on our own\n // (and expect the caller to do something with the promises)\n this[waitUntilSymbol].promises.push(promise)\n }\n }\n}\n\nexport function getWaitUntilPromiseFromEvent(\n event: FetchEvent\n): Promise | undefined {\n return event[waitUntilSymbol].kind === 'internal'\n ? Promise.all(event[waitUntilSymbol].promises).then(() => {})\n : undefined\n}\n\nexport class NextFetchEvent extends FetchEvent {\n sourcePage: string\n\n constructor(params: {\n request: NextRequest\n page: string\n context: { waitUntil: WaitUntil } | undefined\n }) {\n super(params.request, params.context?.waitUntil)\n this.sourcePage = params.page\n }\n\n /**\n * @deprecated The `request` is now the first parameter and the API is now async.\n *\n * Read more: https://nextjs.org/docs/messages/middleware-new-signature\n */\n get request() {\n throw new PageSignatureError({\n page: this.sourcePage,\n })\n }\n\n /**\n * @deprecated Using `respondWith` is no longer needed.\n *\n * Read more: https://nextjs.org/docs/messages/middleware-new-signature\n */\n respondWith() {\n throw new PageSignatureError({\n page: this.sourcePage,\n })\n }\n}\n","import { stringifyCookie } from '../../web/spec-extension/cookies'\nimport type { I18NConfig } from '../../config-shared'\nimport { NextURL } from '../next-url'\nimport { toNodeOutgoingHttpHeaders, validateURL } from '../utils'\nimport { ReflectAdapter } from './adapters/reflect'\n\nimport { ResponseCookies } from './cookies'\n\nconst INTERNALS = Symbol('internal response')\nconst REDIRECTS = new Set([301, 302, 303, 307, 308])\n\nfunction handleMiddlewareField(\n init: MiddlewareResponseInit | undefined,\n headers: Headers\n) {\n if (init?.request?.headers) {\n if (!(init.request.headers instanceof Headers)) {\n throw new Error('request.headers must be an instance of Headers')\n }\n\n const keys = []\n for (const [key, value] of init.request.headers) {\n headers.set('x-middleware-request-' + key, value)\n keys.push(key)\n }\n\n headers.set('x-middleware-override-headers', keys.join(','))\n }\n}\n\n/**\n * This class extends the [Web `Response` API](https://developer.mozilla.org/docs/Web/API/Response) with additional convenience methods.\n *\n * Read more: [Next.js Docs: `NextResponse`](https://nextjs.org/docs/app/api-reference/functions/next-response)\n */\nexport class NextResponse extends Response {\n [INTERNALS]: {\n cookies: ResponseCookies\n url?: NextURL\n body?: Body\n }\n\n constructor(body?: BodyInit | null, init: ResponseInit = {}) {\n super(body, init)\n\n const headers = this.headers\n const cookies = new ResponseCookies(headers)\n\n const cookiesProxy = new Proxy(cookies, {\n get(target, prop, receiver) {\n switch (prop) {\n case 'delete':\n case 'set': {\n return (...args: [string, string]) => {\n const result = Reflect.apply(target[prop], target, args)\n const newHeaders = new Headers(headers)\n\n if (result instanceof ResponseCookies) {\n headers.set(\n 'x-middleware-set-cookie',\n result\n .getAll()\n .map((cookie) => stringifyCookie(cookie))\n .join(',')\n )\n }\n\n handleMiddlewareField(init, newHeaders)\n return result\n }\n }\n default:\n return ReflectAdapter.get(target, prop, receiver)\n }\n },\n })\n\n this[INTERNALS] = {\n cookies: cookiesProxy,\n url: init.url\n ? new NextURL(init.url, {\n headers: toNodeOutgoingHttpHeaders(headers),\n nextConfig: init.nextConfig,\n })\n : undefined,\n }\n }\n\n [Symbol.for('edge-runtime.inspect.custom')]() {\n return {\n cookies: this.cookies,\n url: this.url,\n // rest of props come from Response\n body: this.body,\n bodyUsed: this.bodyUsed,\n headers: Object.fromEntries(this.headers),\n ok: this.ok,\n redirected: this.redirected,\n status: this.status,\n statusText: this.statusText,\n type: this.type,\n }\n }\n\n public get cookies() {\n return this[INTERNALS].cookies\n }\n\n static json(\n body: JsonBody,\n init?: ResponseInit\n ): NextResponse {\n const response: Response = Response.json(body, init)\n return new NextResponse(response.body, response)\n }\n\n static redirect(url: string | NextURL | URL, init?: number | ResponseInit) {\n const status = typeof init === 'number' ? init : init?.status ?? 307\n if (!REDIRECTS.has(status)) {\n throw new RangeError(\n 'Failed to execute \"redirect\" on \"response\": Invalid status code'\n )\n }\n const initObj = typeof init === 'object' ? init : {}\n const headers = new Headers(initObj?.headers)\n headers.set('Location', validateURL(url))\n\n return new NextResponse(null, {\n ...initObj,\n headers,\n status,\n })\n }\n\n static rewrite(\n destination: string | NextURL | URL,\n init?: MiddlewareResponseInit\n ) {\n const headers = new Headers(init?.headers)\n headers.set('x-middleware-rewrite', validateURL(destination))\n\n handleMiddlewareField(init, headers)\n return new NextResponse(null, { ...init, headers })\n }\n\n static next(init?: MiddlewareResponseInit) {\n const headers = new Headers(init?.headers)\n headers.set('x-middleware-next', '1')\n\n handleMiddlewareField(init, headers)\n return new NextResponse(null, { ...init, headers })\n }\n}\n\ninterface ResponseInit extends globalThis.ResponseInit {\n nextConfig?: {\n basePath?: string\n i18n?: I18NConfig\n trailingSlash?: boolean\n }\n url?: string\n}\n\ninterface ModifiedRequest {\n /**\n * If this is set, the request headers will be overridden with this value.\n */\n headers?: Headers\n}\n\ninterface MiddlewareResponseInit extends globalThis.ResponseInit {\n /**\n * These fields will override the request from clients.\n */\n request?: ModifiedRequest\n}\n","import { RequestCookies } from '../cookies'\n\nimport { ResponseCookies } from '../cookies'\nimport { ReflectAdapter } from './reflect'\nimport { workAsyncStorage } from '../../../app-render/work-async-storage.external'\nimport type { RequestStore } from '../../../app-render/work-unit-async-storage.external'\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\n\nexport class RequestCookiesAdapter {\n public static seal(cookies: RequestCookies): ReadonlyRequestCookies {\n return new Proxy(cookies as any, {\n get(target, prop, receiver) {\n switch (prop) {\n case 'clear':\n case 'delete':\n case 'set':\n return ReadonlyRequestCookiesError.callable\n default:\n return ReflectAdapter.get(target, prop, receiver)\n }\n },\n })\n }\n}\n\nconst SYMBOL_MODIFY_COOKIE_VALUES = Symbol.for('next.mutated.cookies')\n\nexport function getModifiedCookieValues(\n cookies: ResponseCookies\n): ResponseCookie[] {\n const modified: ResponseCookie[] | undefined = (cookies as unknown as any)[\n SYMBOL_MODIFY_COOKIE_VALUES\n ]\n if (!modified || !Array.isArray(modified) || modified.length === 0) {\n return []\n }\n\n return modified\n}\n\ntype SetCookieArgs =\n | [key: string, value: string, cookie?: Partial]\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['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()\n const updateResponseCookies = () => {\n // TODO-APP: change method of getting workStore\n const workStore = workAsyncStorage.getStore()\n if (workStore) {\n workStore.pathWasRevalidated = true\n }\n\n const allCookies = responseCookies.getAll()\n modifiedValues = allCookies.filter((c) => modifiedCookies.has(c.name))\n if (onUpdateCookies) {\n const serializedCookies: string[] = []\n for (const cookie of modifiedValues) {\n const tempCookies = new ResponseCookies(new Headers())\n tempCookies.set(cookie)\n serializedCookies.push(tempCookies.toString())\n }\n\n onUpdateCookies(serializedCookies)\n }\n }\n\n const wrappedCookies = new Proxy(responseCookies, {\n get(target, prop, receiver) {\n switch (prop) {\n // A special symbol to get the modified cookie values\n case SYMBOL_MODIFY_COOKIE_VALUES:\n return modifiedValues\n\n // TODO: Throw error if trying to set a cookie after the response\n // headers have been set.\n case 'delete':\n return function (...args: [string] | [ResponseCookie]) {\n modifiedCookies.add(\n typeof args[0] === 'string' ? args[0] : args[0].name\n )\n try {\n target.delete(...args)\n return wrappedCookies\n } finally {\n updateResponseCookies()\n }\n }\n case 'set':\n return function (...args: SetCookieArgs) {\n modifiedCookies.add(\n typeof args[0] === 'string' ? args[0] : args[0].name\n )\n try {\n target.set(...args)\n return wrappedCookies\n } finally {\n updateResponseCookies()\n }\n }\n\n default:\n return ReflectAdapter.get(target, prop, receiver)\n }\n },\n })\n\n return wrappedCookies\n }\n}\n\nexport function createCookiesWithMutableAccessCheck(\n requestStore: RequestStore\n): ResponseCookies {\n const wrappedCookies = new Proxy(requestStore.mutableCookies, {\n get(target, prop, receiver) {\n switch (prop) {\n case 'delete':\n return function (...args: [string] | [ResponseCookie]) {\n ensureCookiesAreStillMutable(requestStore, 'cookies().delete')\n target.delete(...args)\n return wrappedCookies\n }\n case 'set':\n return function (...args: SetCookieArgs) {\n ensureCookiesAreStillMutable(requestStore, 'cookies().set')\n target.set(...args)\n return wrappedCookies\n }\n\n default:\n return ReflectAdapter.get(target, prop, receiver)\n }\n },\n })\n return wrappedCookies\n}\n\nexport function areCookiesMutableInCurrentPhase(requestStore: RequestStore) {\n return requestStore.phase === 'action'\n}\n\n/** Ensure that cookies() starts throwing on mutation\n * if we changed phases and can no longer mutate.\n *\n * This can happen when going:\n * 'render' -> 'after'\n * 'action' -> 'render'\n * */\nfunction ensureCookiesAreStillMutable(\n requestStore: RequestStore,\n _callingExpression: string\n) {\n if (!areCookiesMutableInCurrentPhase(requestStore)) {\n // TODO: maybe we can give a more precise error message based on callingExpression?\n throw new ReadonlyRequestCookiesError()\n }\n}\n\nexport function responseCookiesToRequestCookies(\n responseCookies: ResponseCookies\n): RequestCookies {\n const requestCookies = new RequestCookies(new Headers())\n for (const cookie of responseCookies.getAll()) {\n requestCookies.set(cookie)\n }\n return requestCookies\n}\n","import DefaultCacheHandler from '../lib/cache-handlers/default.external'\nimport type { CacheHandlerCompat } from '../lib/cache-handlers/types'\n\nconst debug = process.env.NEXT_PRIVATE_DEBUG_CACHE\n ? (message: string, ...args: any[]) => {\n console.log(`use-cache: ${message}`, ...args)\n }\n : undefined\n\nconst handlersSymbol = Symbol.for('@next/cache-handlers')\nconst handlersMapSymbol = Symbol.for('@next/cache-handlers-map')\nconst handlersSetSymbol = Symbol.for('@next/cache-handlers-set')\n\n/**\n * The reference to the cache handlers. We store the cache handlers on the\n * global object so that we can access the same instance across different\n * boundaries (such as different copies of the same module).\n */\nconst reference: typeof globalThis & {\n [handlersSymbol]?: {\n RemoteCache?: CacheHandlerCompat\n DefaultCache?: CacheHandlerCompat\n }\n [handlersMapSymbol]?: Map\n [handlersSetSymbol]?: Set\n} = globalThis\n\n/**\n * Initialize the cache handlers.\n * @returns `true` if the cache handlers were initialized, `false` if they were already initialized.\n */\nexport function initializeCacheHandlers(): boolean {\n // If the cache handlers have already been initialized, don't do it again.\n if (reference[handlersMapSymbol]) {\n debug?.('cache handlers already initialized')\n return false\n }\n\n debug?.('initializing cache handlers')\n reference[handlersMapSymbol] = new Map()\n\n // Initialize the cache from the symbol contents first.\n if (reference[handlersSymbol]) {\n let fallback: CacheHandlerCompat\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 = DefaultCacheHandler\n }\n\n reference[handlersMapSymbol].set('default', fallback)\n\n if (reference[handlersSymbol].RemoteCache) {\n debug?.('setting \"remote\" cache handler from symbol')\n reference[handlersMapSymbol].set(\n 'remote',\n reference[handlersSymbol].RemoteCache\n )\n } else {\n debug?.('setting \"remote\" cache handler from default')\n reference[handlersMapSymbol].set('remote', fallback)\n }\n } else {\n debug?.('setting \"default\" cache handler from default')\n reference[handlersMapSymbol].set('default', DefaultCacheHandler)\n debug?.('setting \"remote\" cache handler from default')\n reference[handlersMapSymbol].set('remote', DefaultCacheHandler)\n }\n\n // Create a set of the cache handlers.\n reference[handlersSetSymbol] = new Set(reference[handlersMapSymbol].values())\n\n return true\n}\n\n/**\n * Get a cache handler by kind.\n * @param kind - The kind of cache handler to get.\n * @returns The cache handler, or `undefined` if it does not exist.\n * @throws If the cache handlers are not initialized.\n */\nexport function getCacheHandler(kind: string): CacheHandlerCompat | undefined {\n // This should never be called before initializeCacheHandlers.\n if (!reference[handlersMapSymbol]) {\n throw new Error('Cache handlers not initialized')\n }\n\n return reference[handlersMapSymbol].get(kind)\n}\n\n/**\n * Get a set iterator over the cache handlers.\n * @returns An iterator over the cache handlers, or `undefined` if they are not\n * initialized.\n */\nexport function getCacheHandlers():\n | SetIterator\n | undefined {\n if (!reference[handlersSetSymbol]) {\n return undefined\n }\n\n return reference[handlersSetSymbol].values()\n}\n\n/**\n * Get a map iterator over the cache handlers (keyed by kind).\n * @returns An iterator over the cache handler entries, or `undefined` if they\n * are not initialized.\n * @throws If the cache handlers are not initialized.\n */\nexport function getCacheHandlerEntries():\n | MapIterator<[string, CacheHandlerCompat]>\n | undefined {\n if (!reference[handlersMapSymbol]) {\n return undefined\n }\n\n return reference[handlersMapSymbol].entries()\n}\n\n/**\n * Set a cache handler by kind.\n * @param kind - The kind of cache handler to set.\n * @param cacheHandler - The cache handler to set.\n */\nexport function setCacheHandler(\n kind: string,\n cacheHandler: CacheHandlerCompat\n): void {\n // This should never be called before initializeCacheHandlers.\n if (!reference[handlersMapSymbol] || !reference[handlersSetSymbol]) {\n throw new Error('Cache handlers not initialized')\n }\n\n debug?.('setting cache handler for \"%s\"', kind)\n reference[handlersMapSymbol].set(kind, cacheHandler)\n reference[handlersSetSymbol].add(cacheHandler)\n}\n","import type { RequestData, FetchEventResult } from './types'\nimport type { RequestInit } from './spec-extension/request'\nimport { PageSignatureError } from './error'\nimport { fromNodeOutgoingHttpHeaders, normalizeNextQueryParam } from './utils'\nimport {\n NextFetchEvent,\n getWaitUntilPromiseFromEvent,\n} from './spec-extension/fetch-event'\nimport { NextRequest } from './spec-extension/request'\nimport { NextResponse } from './spec-extension/response'\nimport {\n parseRelativeURL,\n getRelativeURL,\n} from '../../shared/lib/router/utils/relativize-url'\nimport { NextURL } from './next-url'\nimport { stripInternalSearchParams } from '../internal-utils'\nimport { normalizeRscURL } from '../../shared/lib/router/utils/app-paths'\nimport {\n FLIGHT_HEADERS,\n NEXT_REWRITTEN_PATH_HEADER,\n NEXT_REWRITTEN_QUERY_HEADER,\n NEXT_RSC_UNION_QUERY,\n RSC_HEADER,\n} from '../../client/components/app-router-headers'\nimport { ensureInstrumentationRegistered } from './globals'\nimport { createRequestStoreForAPI } from '../async-storage/request-store'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { createWorkStore } from '../async-storage/work-store'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { NEXT_ROUTER_PREFETCH_HEADER } from '../../client/components/app-router-headers'\nimport { getTracer } from '../lib/trace/tracer'\nimport type { TextMapGetter } from 'next/dist/compiled/@opentelemetry/api'\nimport { MiddlewareSpan } from '../lib/trace/constants'\nimport { CloseController } from './web-on-close'\nimport { getEdgePreviewProps } from './get-edge-preview-props'\nimport { getBuiltinRequestContext } from '../after/builtin-request-context'\nimport { getImplicitTags } from '../lib/implicit-tags'\n\nexport class NextRequestHint extends NextRequest {\n sourcePage: string\n fetchMetrics: FetchEventResult['fetchMetrics'] | undefined\n\n constructor(params: {\n init: RequestInit\n input: Request | string\n page: string\n }) {\n super(params.input, params.init)\n this.sourcePage = params.page\n }\n\n get request() {\n throw new PageSignatureError({ page: this.sourcePage })\n }\n\n respondWith() {\n throw new PageSignatureError({ page: this.sourcePage })\n }\n\n waitUntil() {\n throw new PageSignatureError({ page: this.sourcePage })\n }\n}\n\nconst headersGetter: TextMapGetter = {\n keys: (headers) => Array.from(headers.keys()),\n get: (headers, key) => headers.get(key) ?? undefined,\n}\n\nexport type AdapterOptions = {\n handler: (req: NextRequestHint, event: NextFetchEvent) => Promise\n page: string\n request: RequestData\n IncrementalCache?: typeof import('../lib/incremental-cache').IncrementalCache\n incrementalCacheHandler?: typeof import('../lib/incremental-cache').CacheHandler\n bypassNextUrl?: boolean\n}\n\nlet propagator: (request: NextRequestHint, fn: () => T) => T = (\n request,\n fn\n) => {\n const tracer = getTracer()\n return tracer.withPropagatedContext(request.headers, fn, headersGetter)\n}\n\nlet testApisIntercepted = false\n\nfunction ensureTestApisIntercepted() {\n if (!testApisIntercepted) {\n testApisIntercepted = true\n if (process.env.NEXT_PRIVATE_TEST_PROXY === 'true') {\n const { interceptTestApis, wrapRequestHandler } =\n // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm\n require('next/dist/experimental/testmode/server-edge') as typeof import('../../experimental/testmode/server-edge')\n interceptTestApis()\n propagator = wrapRequestHandler(propagator)\n }\n }\n}\n\nexport async function adapter(\n params: AdapterOptions\n): Promise {\n ensureTestApisIntercepted()\n await ensureInstrumentationRegistered()\n\n // TODO-APP: use explicit marker for this\n const isEdgeRendering =\n typeof (globalThis as any).__BUILD_MANIFEST !== 'undefined'\n\n params.request.url = normalizeRscURL(params.request.url)\n\n const requestURL = params.bypassNextUrl\n ? new URL(params.request.url)\n : new NextURL(params.request.url, {\n headers: params.request.headers,\n nextConfig: params.request.nextConfig,\n })\n\n // Iterator uses an index to keep track of the current iteration. Because of deleting and appending below we can't just use the iterator.\n // Instead we use the keys before iteration.\n const keys = [...requestURL.searchParams.keys()]\n for (const key of keys) {\n const value = requestURL.searchParams.getAll(key)\n\n const normalizedKey = normalizeNextQueryParam(key)\n if (normalizedKey) {\n requestURL.searchParams.delete(normalizedKey)\n for (const val of value) {\n requestURL.searchParams.append(normalizedKey, val)\n }\n requestURL.searchParams.delete(key)\n }\n }\n\n // Ensure users only see page requests, never data requests.\n let buildId = process.env.__NEXT_BUILD_ID || ''\n if ('buildId' in requestURL) {\n buildId = (requestURL as NextURL).buildId || ''\n requestURL.buildId = ''\n }\n\n const requestHeaders = fromNodeOutgoingHttpHeaders(params.request.headers)\n const isNextDataRequest = requestHeaders.has('x-nextjs-data')\n const isRSCRequest = requestHeaders.get(RSC_HEADER) === '1'\n\n if (isNextDataRequest && requestURL.pathname === '/index') {\n requestURL.pathname = '/'\n }\n\n const flightHeaders = new Map()\n\n // Headers should only be stripped for middleware\n if (!isEdgeRendering) {\n for (const header of FLIGHT_HEADERS) {\n const value = requestHeaders.get(header)\n if (value !== null) {\n flightHeaders.set(header, value)\n requestHeaders.delete(header)\n }\n }\n }\n\n const normalizeURL = process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE\n ? new URL(params.request.url)\n : requestURL\n\n const rscHash = normalizeURL.searchParams.get(NEXT_RSC_UNION_QUERY)\n\n const request = new NextRequestHint({\n page: params.page,\n // Strip internal query parameters off the request.\n input: stripInternalSearchParams(normalizeURL).toString(),\n init: {\n body: params.request.body,\n headers: requestHeaders,\n method: params.request.method,\n nextConfig: params.request.nextConfig,\n signal: params.request.signal,\n },\n })\n\n /**\n * This allows to identify the request as a data request. The user doesn't\n * need to know about this property neither use it. We add it for testing\n * purposes.\n */\n if (isNextDataRequest) {\n Object.defineProperty(request, '__isData', {\n enumerable: false,\n value: true,\n })\n }\n\n if (\n // If we are inside of the next start sandbox\n // leverage the shared instance if not we need\n // to create a fresh cache instance each time\n !(globalThis as any).__incrementalCacheShared &&\n (params as any).IncrementalCache\n ) {\n ;(globalThis as any).__incrementalCache = new (\n params as {\n IncrementalCache: typeof import('../lib/incremental-cache').IncrementalCache\n }\n ).IncrementalCache({\n CurCacheHandler: params.incrementalCacheHandler,\n minimalMode: process.env.NODE_ENV !== 'development',\n fetchCacheKeyPrefix: process.env.__NEXT_FETCH_CACHE_KEY_PREFIX,\n dev: process.env.NODE_ENV === 'development',\n requestHeaders: params.request.headers as any,\n\n getPrerenderManifest: () => {\n return {\n version: -1 as any, // letting us know this doesn't conform to spec\n routes: {},\n dynamicRoutes: {},\n notFoundRoutes: [],\n preview: getEdgePreviewProps(),\n }\n },\n })\n }\n\n // if we're in an edge runtime sandbox, we should use the waitUntil\n // that we receive from the enclosing NextServer\n const outerWaitUntil =\n params.request.waitUntil ?? getBuiltinRequestContext()?.waitUntil\n\n const event = new NextFetchEvent({\n request,\n page: params.page,\n context: outerWaitUntil ? { waitUntil: outerWaitUntil } : undefined,\n })\n let response\n let cookiesFromResponse\n\n response = await propagator(request, () => {\n // we only care to make async storage available for middleware\n const isMiddleware =\n params.page === '/middleware' || params.page === '/src/middleware'\n\n if (isMiddleware) {\n // if we're in an edge function, we only get a subset of `nextConfig` (no `experimental`),\n // so we have to inject it via DefinePlugin.\n // in `next start` this will be passed normally (see `NextNodeServer.runMiddleware`).\n\n const waitUntil = event.waitUntil.bind(event)\n const closeController = new CloseController()\n\n return getTracer().trace(\n MiddlewareSpan.execute,\n {\n spanName: `middleware ${request.method} ${request.nextUrl.pathname}`,\n attributes: {\n 'http.target': request.nextUrl.pathname,\n 'http.method': request.method,\n },\n },\n async () => {\n try {\n const onUpdateCookies = (cookies: Array) => {\n cookiesFromResponse = cookies\n }\n const previewProps = getEdgePreviewProps()\n const page = '/' // Fake Work\n const fallbackRouteParams = null\n\n const implicitTags = await getImplicitTags(\n page,\n request.nextUrl,\n fallbackRouteParams\n )\n\n const requestStore = createRequestStoreForAPI(\n request,\n request.nextUrl,\n implicitTags,\n onUpdateCookies,\n previewProps\n )\n\n const workStore = createWorkStore({\n page,\n renderOpts: {\n cacheLifeProfiles:\n params.request.nextConfig?.experimental?.cacheLife,\n experimental: {\n isRoutePPREnabled: false,\n cacheComponents: false,\n authInterrupts:\n !!params.request.nextConfig?.experimental?.authInterrupts,\n },\n supportsDynamicResponse: true,\n waitUntil,\n onClose: closeController.onClose.bind(closeController),\n onAfterTaskError: undefined,\n },\n isPrefetchRequest:\n request.headers.get(NEXT_ROUTER_PREFETCH_HEADER) === '1',\n buildId: buildId ?? '',\n previouslyRevalidatedTags: [],\n })\n\n return await workAsyncStorage.run(workStore, () =>\n workUnitAsyncStorage.run(\n requestStore,\n params.handler,\n request,\n event\n )\n )\n } finally {\n // middleware cannot stream, so we can consider the response closed\n // as soon as the handler returns.\n // we can delay running it until a bit later --\n // if it's needed, we'll have a `waitUntil` lock anyway.\n setTimeout(() => {\n closeController.dispatchClose()\n }, 0)\n }\n }\n )\n }\n return params.handler(request, event)\n })\n\n // check if response is a Response object\n if (response && !(response instanceof Response)) {\n throw new TypeError('Expected an instance of Response to be returned')\n }\n\n if (response && cookiesFromResponse) {\n response.headers.set('set-cookie', cookiesFromResponse)\n }\n\n /**\n * For rewrites we must always include the locale in the final pathname\n * so we re-create the NextURL forcing it to include it when the it is\n * an internal rewrite. Also we make sure the outgoing rewrite URL is\n * a data URL if the request was a data request.\n */\n const rewrite = response?.headers.get('x-middleware-rewrite')\n if (response && rewrite && (isRSCRequest || !isEdgeRendering)) {\n const destination = new NextURL(rewrite, {\n forceLocale: true,\n headers: params.request.headers,\n nextConfig: params.request.nextConfig,\n })\n\n if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE && !isEdgeRendering) {\n if (destination.host === request.nextUrl.host) {\n destination.buildId = buildId || destination.buildId\n response.headers.set('x-middleware-rewrite', String(destination))\n }\n }\n\n /**\n * When the request is a data request we must show if there was a rewrite\n * with an internal header so the client knows which component to load\n * from the data request.\n */\n const { url: relativeDestination, isRelative } = parseRelativeURL(\n destination.toString(),\n requestURL.toString()\n )\n\n if (\n !isEdgeRendering &&\n isNextDataRequest &&\n // if the rewrite is external and external rewrite\n // resolving config is enabled don't add this header\n // so the upstream app can set it instead\n !(\n process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE &&\n relativeDestination.match(/http(s)?:\\/\\//)\n )\n ) {\n response.headers.set('x-nextjs-rewrite', relativeDestination)\n }\n\n // If this is an RSC request, and the pathname or search has changed, and\n // this isn't an external rewrite, we need to set the rewritten pathname and\n // query headers.\n if (isRSCRequest && isRelative) {\n if (requestURL.pathname !== destination.pathname) {\n response.headers.set(NEXT_REWRITTEN_PATH_HEADER, destination.pathname)\n }\n if (requestURL.search !== destination.search) {\n response.headers.set(\n NEXT_REWRITTEN_QUERY_HEADER,\n // remove the leading ? from the search string\n destination.search.slice(1)\n )\n }\n }\n }\n\n /**\n * Always forward the `_rsc` search parameter to the rewritten URL for RSC requests,\n * unless it's already present. This is necessary to ensure that RSC hash validation\n * works correctly after a rewrite. For internal rewrites, the server can validate the\n * RSC hash using the original URL, so forwarding the `_rsc` parameter is less critical.\n * However, for external rewrites (where the request is proxied to another Next.js server),\n * the external server does not have access to the original URL or its search parameters.\n * In these cases, forwarding the `_rsc` parameter is essential so that the external server\n * can perform the correct RSC hash validation.\n */\n if (response && rewrite && isRSCRequest && rscHash) {\n const rewriteURL = new URL(rewrite)\n if (!rewriteURL.searchParams.has(NEXT_RSC_UNION_QUERY)) {\n rewriteURL.searchParams.set(NEXT_RSC_UNION_QUERY, rscHash)\n response.headers.set('x-middleware-rewrite', rewriteURL.toString())\n }\n }\n\n /**\n * For redirects we will not include the locale in case when it is the\n * default and we must also make sure the outgoing URL is a data one if\n * the incoming request was a data request.\n */\n const redirect = response?.headers.get('Location')\n if (response && redirect && !isEdgeRendering) {\n const redirectURL = new NextURL(redirect, {\n forceLocale: false,\n headers: params.request.headers,\n nextConfig: params.request.nextConfig,\n })\n\n /**\n * Responses created from redirects have immutable headers so we have\n * to clone the response to be able to modify it.\n */\n response = new Response(response.body, response)\n\n if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) {\n if (redirectURL.host === requestURL.host) {\n redirectURL.buildId = buildId || redirectURL.buildId\n response.headers.set('Location', redirectURL.toString())\n }\n }\n\n /**\n * When the request is a data request we can't use the location header as\n * it may end up with CORS error. Instead we map to an internal header so\n * the client knows the destination.\n */\n if (isNextDataRequest) {\n response.headers.delete('Location')\n response.headers.set(\n 'x-nextjs-redirect',\n getRelativeURL(redirectURL.toString(), requestURL.toString())\n )\n }\n }\n\n const finalResponse = response ? response : NextResponse.next()\n\n // Flight headers are not overridable / removable so they are applied at the end.\n const middlewareOverrideHeaders = finalResponse.headers.get(\n 'x-middleware-override-headers'\n )\n const overwrittenHeaders: string[] = []\n if (middlewareOverrideHeaders) {\n for (const [key, value] of flightHeaders) {\n finalResponse.headers.set(`x-middleware-request-${key}`, value)\n overwrittenHeaders.push(key)\n }\n\n if (overwrittenHeaders.length > 0) {\n finalResponse.headers.set(\n 'x-middleware-override-headers',\n middlewareOverrideHeaders + ',' + overwrittenHeaders.join(',')\n )\n }\n }\n\n return {\n response: finalResponse,\n waitUntil: getWaitUntilPromiseFromEvent(event) ?? Promise.resolve(),\n fetchMetrics: request.fetchMetrics,\n }\n}\n","import type { PathnameNormalizer } from './pathname-normalizer'\n\nimport {\n RSC_SEGMENT_SUFFIX,\n RSC_SEGMENTS_DIR_SUFFIX,\n} from '../../../lib/constants'\n\nconst PATTERN = new RegExp(\n `^(/.*)${RSC_SEGMENTS_DIR_SUFFIX}(/.*)${RSC_SEGMENT_SUFFIX}$`\n)\n\nexport class SegmentPrefixRSCPathnameNormalizer implements PathnameNormalizer {\n public match(pathname: string): boolean {\n return PATTERN.test(pathname)\n }\n\n public extract(pathname: string) {\n const match = pathname.match(PATTERN)\n if (!match) return null\n\n return { originalPathname: match[1], segmentPath: match[2] }\n }\n\n public normalize(pathname: string): string {\n const match = this.extract(pathname)\n if (!match) return pathname\n\n return match.originalPathname\n }\n}\n","import type { __ApiPreviewProps } from './api-utils'\nimport type { LoadComponentsReturnType } from './load-components'\nimport type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher'\nimport type { Params } from './request/params'\nimport type { NextConfig, NextConfigComplete } from './config-shared'\nimport type {\n NextParsedUrlQuery,\n NextUrlWithParsedQuery,\n RequestMeta,\n} from './request-meta'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { RenderOptsPartial as PagesRenderOptsPartial } from './render'\nimport type {\n RenderOptsPartial as AppRenderOptsPartial,\n ServerOnInstrumentationRequestError,\n} from './app-render/types'\nimport type {\n ServerComponentsHmrCache,\n ResponseCacheBase,\n} from './response-cache'\nimport type { UrlWithParsedQuery } from 'url'\nimport {\n NormalizeError,\n DecodeError,\n normalizeRepeatedSlashes,\n MissingStaticPage,\n} from '../shared/lib/utils'\nimport type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'\nimport type { BaseNextRequest, BaseNextResponse } from './base-http'\nimport type {\n ManifestRewriteRoute,\n ManifestRoute,\n PrerenderManifest,\n} from '../build'\nimport type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'\nimport type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'\nimport type { PagesAPIRouteMatch } from './route-matches/pages-api-route-match'\nimport type {\n Server as HTTPServer,\n IncomingMessage,\n ServerResponse as HTTPServerResponse,\n} from 'http'\nimport type { MiddlewareMatcher } from '../build/analysis/get-page-static-info'\nimport type { TLSSocket } from 'tls'\nimport type { PathnameNormalizer } from './normalizers/request/pathname-normalizer'\nimport type { InstrumentationModule } from './instrumentation/types'\n\nimport { format as formatUrl, parse as parseUrl } from 'url'\nimport { formatHostname } from './lib/format-hostname'\nimport {\n APP_PATHS_MANIFEST,\n NEXT_BUILTIN_DOCUMENT,\n PAGES_MANIFEST,\n STATIC_STATUS_PAGES,\n UNDERSCORE_NOT_FOUND_ROUTE,\n UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,\n} from '../shared/lib/constants'\nimport { isDynamicRoute } from '../shared/lib/router/utils'\nimport { setConfig } from '../shared/lib/runtime-config.external'\nimport { execOnce } from '../shared/lib/utils'\nimport { isBlockedPage } from './utils'\nimport { getBotType, isBot } from '../shared/lib/router/utils/is-bot'\nimport RenderResult from './render-result'\nimport { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'\nimport { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'\nimport * as Log from '../build/output/log'\nimport { getPreviouslyRevalidatedTags, getServerUtils } from './server-utils'\nimport isError, { getProperError } from '../lib/is-error'\nimport {\n addRequestMeta,\n getRequestMeta,\n removeRequestMeta,\n setRequestMeta,\n} from './request-meta'\nimport { removePathPrefix } from '../shared/lib/router/utils/remove-path-prefix'\nimport { normalizeAppPath } from '../shared/lib/router/utils/app-paths'\nimport { getHostname } from '../shared/lib/get-hostname'\nimport { parseUrl as parseUrlUtil } from '../shared/lib/router/utils/parse-url'\nimport { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'\nimport {\n RSC_HEADER,\n NEXT_RSC_UNION_QUERY,\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_URL,\n NEXT_ROUTER_STATE_TREE_HEADER,\n} from '../client/components/app-router-headers'\nimport type {\n MatchOptions,\n RouteMatcherManager,\n} from './route-matcher-managers/route-matcher-manager'\nimport { LocaleRouteNormalizer } from './normalizers/locale-route-normalizer'\nimport { DefaultRouteMatcherManager } from './route-matcher-managers/default-route-matcher-manager'\nimport { AppPageRouteMatcherProvider } from './route-matcher-providers/app-page-route-matcher-provider'\nimport { AppRouteRouteMatcherProvider } from './route-matcher-providers/app-route-route-matcher-provider'\nimport { PagesAPIRouteMatcherProvider } from './route-matcher-providers/pages-api-route-matcher-provider'\nimport { PagesRouteMatcherProvider } from './route-matcher-providers/pages-route-matcher-provider'\nimport { ServerManifestLoader } from './route-matcher-providers/helpers/manifest-loaders/server-manifest-loader'\nimport {\n getTracer,\n isBubbledError,\n SpanKind,\n SpanStatusCode,\n} from './lib/trace/tracer'\nimport { BaseServerSpan } from './lib/trace/constants'\nimport { I18NProvider } from './lib/i18n-provider'\nimport { sendResponse } from './send-response'\nimport { normalizeNextQueryParam } from './web/utils'\nimport {\n HTML_CONTENT_TYPE_HEADER,\n JSON_CONTENT_TYPE_HEADER,\n MATCHED_PATH_HEADER,\n NEXT_RESUME_HEADER,\n} from '../lib/constants'\nimport { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'\nimport { matchNextDataPathname } from './lib/match-next-data-pathname'\nimport getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-asset-path'\nimport { RSCPathnameNormalizer } from './normalizers/request/rsc'\nimport { stripFlightHeaders } from './app-render/strip-flight-headers'\nimport {\n isAppPageRouteModule,\n isAppRouteRouteModule,\n} from './route-modules/checks'\nimport { PrefetchRSCPathnameNormalizer } from './normalizers/request/prefetch-rsc'\nimport { NextDataPathnameNormalizer } from './normalizers/request/next-data'\nimport { getIsPossibleServerAction } from './lib/server-action-request-meta'\nimport { isInterceptionRouteAppPath } from '../shared/lib/router/utils/interception-routes'\nimport { toRoute } from './lib/to-route'\nimport type { DeepReadonly } from '../shared/lib/deep-readonly'\nimport { isNodeNextRequest, isNodeNextResponse } from './base-http/helpers'\nimport { patchSetHeaderWithCookieSupport } from './lib/patch-set-header'\nimport { checkIsAppPPREnabled } from './lib/experimental/ppr'\nimport {\n getBuiltinRequestContext,\n type WaitUntil,\n} from './after/builtin-request-context'\nimport { NextRequestHint } from './web/adapter'\nimport type { RouteModule } from './route-modules/route-module'\nimport { type FallbackMode, parseFallbackField } from '../lib/fallback'\nimport { SegmentPrefixRSCPathnameNormalizer } from './normalizers/request/segment-prefix-rsc'\nimport { shouldServeStreamingMetadata } from './lib/streaming-metadata'\nimport { decodeQueryPathParameter } from './lib/decode-query-path-parameter'\nimport { NoFallbackError } from '../shared/lib/no-fallback-error.external'\nimport { getCacheHandlers } from './use-cache/handlers'\nimport { fixMojibake } from './lib/fix-mojibake'\nimport { computeCacheBustingSearchParam } from '../shared/lib/router/utils/cache-busting-search-param'\nimport { setCacheBustingSearchParamWithHash } from '../client/components/router-reducer/set-cache-busting-search-param'\nimport type { CacheControl } from './lib/cache-control'\nimport type { PrerenderedRoute } from '../build/static-paths/types'\n\nexport type FindComponentsResult = {\n components: LoadComponentsReturnType\n query: NextParsedUrlQuery\n}\n\nexport interface MiddlewareRoutingItem {\n page: string\n match: MiddlewareRouteMatch\n matchers?: MiddlewareMatcher[]\n}\n\nexport type RouteHandler<\n ServerRequest extends BaseNextRequest = BaseNextRequest,\n ServerResponse extends BaseNextResponse = BaseNextResponse,\n> = (\n req: ServerRequest,\n res: ServerResponse,\n parsedUrl: NextUrlWithParsedQuery\n) => PromiseLike | boolean\n\n/**\n * The normalized route manifest is the same as the route manifest, but with\n * the rewrites normalized to the object shape that the router expects.\n */\nexport type NormalizedRouteManifest = {\n readonly dynamicRoutes: ReadonlyArray\n readonly rewrites: {\n readonly beforeFiles: ReadonlyArray\n readonly afterFiles: ReadonlyArray\n readonly fallback: ReadonlyArray\n }\n}\n\nexport interface Options {\n /**\n * Object containing the configuration next.config.js\n */\n conf: NextConfig\n /**\n * Set to false when the server was created by Next.js\n */\n customServer?: boolean\n /**\n * Tells if Next.js is running in dev mode\n */\n dev?: boolean\n /**\n * Enables the experimental testing mode.\n */\n experimentalTestProxy?: boolean\n\n /**\n * Whether or not the dev server is running in experimental HTTPS mode\n */\n experimentalHttpsServer?: boolean\n /**\n * Where the Next project is located\n */\n dir?: string\n /**\n * Tells if Next.js is at the platform-level\n */\n minimalMode?: boolean\n /**\n * Hide error messages containing server information\n */\n quiet?: boolean\n /**\n * The hostname the server is running behind\n */\n hostname?: string\n /**\n * The port the server is running behind\n */\n port?: number\n /**\n * The HTTP Server that Next.js is running behind\n */\n httpServer?: HTTPServer\n}\n\nexport type RenderOpts = PagesRenderOptsPartial & AppRenderOptsPartial\n\nexport type LoadedRenderOpts = RenderOpts &\n LoadComponentsReturnType &\n RequestLifecycleOpts\n\nexport type RequestLifecycleOpts = {\n waitUntil: ((promise: Promise) => void) | undefined\n onClose: (callback: () => void) => void\n onAfterTaskError: ((error: unknown) => void) | undefined\n}\n\ntype BaseRenderOpts = RenderOpts & {\n poweredByHeader: boolean\n generateEtags: boolean\n previewProps: __ApiPreviewProps\n}\n\n/**\n * The public interface for rendering with the server programmatically. This\n * would typically only allow the base request or response to extend it, but\n * because this can be programmatically accessed, we assume that it could also\n * be the base Node.js request and response types.\n */\nexport interface BaseRequestHandler<\n ServerRequest extends BaseNextRequest | IncomingMessage = BaseNextRequest,\n ServerResponse extends\n | BaseNextResponse\n | HTTPServerResponse = BaseNextResponse,\n> {\n (\n req: ServerRequest,\n res: ServerResponse,\n parsedUrl?: NextUrlWithParsedQuery | undefined\n ): Promise | void\n}\n\nexport type RequestContext<\n ServerRequest extends BaseNextRequest = BaseNextRequest,\n ServerResponse extends BaseNextResponse = BaseNextResponse,\n> = {\n req: ServerRequest\n res: ServerResponse\n pathname: string\n query: NextParsedUrlQuery\n renderOpts: RenderOpts\n}\n\n// Internal wrapper around build errors at development\n// time, to prevent us from propagating or logging them\nexport class WrappedBuildError extends Error {\n innerError: Error\n\n constructor(innerError: Error) {\n super()\n this.innerError = innerError\n }\n}\n\ntype ResponsePayload = {\n body: RenderResult\n cacheControl?: CacheControl\n}\n\nexport type NextEnabledDirectories = {\n readonly pages: boolean\n readonly app: boolean\n}\n\nexport default abstract class Server<\n ServerOptions extends Options = Options,\n ServerRequest extends BaseNextRequest = BaseNextRequest,\n ServerResponse extends BaseNextResponse = BaseNextResponse,\n> {\n public readonly hostname?: string\n public readonly fetchHostname?: string\n public readonly port?: number\n protected readonly dir: string\n protected readonly quiet: boolean\n protected readonly nextConfig: NextConfigComplete\n protected readonly distDir: string\n protected readonly publicDir: string\n protected readonly hasStaticDir: boolean\n protected readonly pagesManifest?: PagesManifest\n protected readonly appPathsManifest?: PagesManifest\n protected readonly buildId: string\n protected readonly minimalMode: boolean\n protected readonly renderOpts: BaseRenderOpts\n protected readonly serverOptions: Readonly\n protected readonly appPathRoutes?: Record\n protected readonly clientReferenceManifest?: DeepReadonly\n protected interceptionRoutePatterns: RegExp[]\n protected nextFontManifest?: DeepReadonly\n protected instrumentation: InstrumentationModule | undefined\n private readonly responseCache: ResponseCacheBase\n\n protected abstract getPublicDir(): string\n protected abstract getHasStaticDir(): boolean\n protected abstract getPagesManifest(): PagesManifest | undefined\n protected abstract getAppPathsManifest(): PagesManifest | undefined\n protected abstract getBuildId(): string\n protected abstract getinterceptionRoutePatterns(): RegExp[]\n\n protected readonly enabledDirectories: NextEnabledDirectories\n protected abstract getEnabledDirectories(dev: boolean): NextEnabledDirectories\n\n protected readonly experimentalTestProxy?: boolean\n\n protected abstract findPageComponents(params: {\n locale: string | undefined\n page: string\n query: NextParsedUrlQuery\n params: Params\n isAppPath: boolean\n // The following parameters are used in the development server's\n // implementation.\n sriEnabled?: boolean\n appPaths?: ReadonlyArray | null\n shouldEnsure?: boolean\n url?: string\n }): Promise\n protected abstract getPrerenderManifest(): DeepReadonly\n protected abstract getNextFontManifest():\n | DeepReadonly\n | undefined\n protected abstract attachRequestMeta(\n req: ServerRequest,\n parsedUrl: NextUrlWithParsedQuery\n ): void\n protected abstract hasPage(pathname: string): Promise\n\n protected abstract sendRenderResult(\n req: ServerRequest,\n res: ServerResponse,\n options: {\n result: RenderResult\n generateEtags: boolean\n poweredByHeader: boolean\n cacheControl: CacheControl | undefined\n }\n ): Promise\n\n protected abstract runApi(\n req: ServerRequest,\n res: ServerResponse,\n query: ParsedUrlQuery,\n match: PagesAPIRouteMatch\n ): Promise\n\n protected abstract renderHTML(\n req: ServerRequest,\n res: ServerResponse,\n pathname: string,\n query: NextParsedUrlQuery,\n renderOpts: LoadedRenderOpts\n ): Promise\n\n protected abstract getIncrementalCache(options: {\n requestHeaders: Record\n }): Promise\n\n protected abstract getResponseCache(options: {\n dev: boolean\n }): ResponseCacheBase\n\n protected getServerComponentsHmrCache():\n | ServerComponentsHmrCache\n | undefined {\n return this.nextConfig.experimental.serverComponentsHmrCache\n ? (globalThis as any).__serverComponentsHmrCache\n : undefined\n }\n\n protected abstract loadEnvConfig(params: {\n dev: boolean\n forceReload?: boolean\n }): void\n\n // TODO-APP: (wyattjoh): Make protected again. Used for turbopack in route-resolver.ts right now.\n public readonly matchers: RouteMatcherManager\n protected readonly i18nProvider?: I18NProvider\n protected readonly localeNormalizer?: LocaleRouteNormalizer\n\n protected readonly normalizers: {\n readonly rsc: RSCPathnameNormalizer | undefined\n readonly prefetchRSC: PrefetchRSCPathnameNormalizer | undefined\n readonly segmentPrefetchRSC: SegmentPrefixRSCPathnameNormalizer | undefined\n readonly data: NextDataPathnameNormalizer | undefined\n }\n\n private readonly isAppPPREnabled: boolean\n private readonly isAppSegmentPrefetchEnabled: boolean\n\n /**\n * This is used to persist cache scopes across\n * prefetch -> full route requests for cache components\n * it's only fully used in dev\n */\n\n public constructor(options: ServerOptions) {\n const {\n dir = '.',\n quiet = false,\n conf,\n dev = false,\n minimalMode = false,\n hostname,\n port,\n experimentalTestProxy,\n } = options\n\n this.experimentalTestProxy = experimentalTestProxy\n this.serverOptions = options\n\n this.dir = (require('path') as typeof import('path')).resolve(dir)\n\n this.quiet = quiet\n this.loadEnvConfig({ dev })\n\n // TODO: should conf be normalized to prevent missing\n // values from causing issues as this can be user provided\n this.nextConfig = conf as NextConfigComplete\n this.hostname = hostname\n if (this.hostname) {\n // we format the hostname so that it can be fetched\n this.fetchHostname = formatHostname(this.hostname)\n }\n this.port = port\n this.distDir = (require('path') as typeof import('path')).join(\n this.dir,\n this.nextConfig.distDir\n )\n this.publicDir = this.getPublicDir()\n this.hasStaticDir = !minimalMode && this.getHasStaticDir()\n\n this.i18nProvider = this.nextConfig.i18n?.locales\n ? new I18NProvider(this.nextConfig.i18n)\n : undefined\n\n // Configure the locale normalizer, it's used for routes inside `pages/`.\n this.localeNormalizer = this.i18nProvider\n ? new LocaleRouteNormalizer(this.i18nProvider)\n : undefined\n\n // Only serverRuntimeConfig needs the default\n // publicRuntimeConfig gets it's default in client/index.js\n const {\n serverRuntimeConfig = {},\n publicRuntimeConfig,\n assetPrefix,\n generateEtags,\n } = this.nextConfig\n\n this.buildId = this.getBuildId()\n // this is a hack to avoid Webpack knowing this is equal to this.minimalMode\n // because we replace this.minimalMode to true in production bundles.\n const minimalModeKey = 'minimalMode'\n this[minimalModeKey] =\n minimalMode || !!process.env.NEXT_PRIVATE_MINIMAL_MODE\n\n this.enabledDirectories = this.getEnabledDirectories(dev)\n\n this.isAppPPREnabled =\n this.enabledDirectories.app &&\n checkIsAppPPREnabled(this.nextConfig.experimental.ppr)\n\n this.isAppSegmentPrefetchEnabled =\n this.enabledDirectories.app &&\n this.nextConfig.experimental.clientSegmentCache === true\n\n this.normalizers = {\n // We should normalize the pathname from the RSC prefix only in minimal\n // mode as otherwise that route is not exposed external to the server as\n // we instead only rely on the headers.\n rsc:\n this.enabledDirectories.app && this.minimalMode\n ? new RSCPathnameNormalizer()\n : undefined,\n prefetchRSC:\n this.isAppPPREnabled && this.minimalMode\n ? new PrefetchRSCPathnameNormalizer()\n : undefined,\n segmentPrefetchRSC:\n this.isAppSegmentPrefetchEnabled && this.minimalMode\n ? new SegmentPrefixRSCPathnameNormalizer()\n : undefined,\n data: this.enabledDirectories.pages\n ? new NextDataPathnameNormalizer(this.buildId)\n : undefined,\n }\n\n this.nextFontManifest = this.getNextFontManifest()\n process.env.NEXT_DEPLOYMENT_ID = this.nextConfig.deploymentId || ''\n\n this.renderOpts = {\n dir: this.dir,\n supportsDynamicResponse: true,\n trailingSlash: this.nextConfig.trailingSlash,\n deploymentId: this.nextConfig.deploymentId,\n poweredByHeader: this.nextConfig.poweredByHeader,\n canonicalBase: this.nextConfig.amp.canonicalBase || '',\n generateEtags,\n previewProps: this.getPrerenderManifest().preview,\n ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,\n basePath: this.nextConfig.basePath,\n images: this.nextConfig.images,\n optimizeCss: this.nextConfig.experimental.optimizeCss,\n nextConfigOutput: this.nextConfig.output,\n nextScriptWorkers: this.nextConfig.experimental.nextScriptWorkers,\n disableOptimizedLoading:\n this.nextConfig.experimental.disableOptimizedLoading,\n domainLocales: this.nextConfig.i18n?.domains,\n distDir: this.distDir,\n serverComponents: this.enabledDirectories.app,\n cacheLifeProfiles: this.nextConfig.experimental.cacheLife,\n enableTainting: this.nextConfig.experimental.taint,\n crossOrigin: this.nextConfig.crossOrigin\n ? this.nextConfig.crossOrigin\n : undefined,\n largePageDataBytes: this.nextConfig.experimental.largePageDataBytes,\n // Only the `publicRuntimeConfig` key is exposed to the client side\n // It'll be rendered as part of __NEXT_DATA__ on the client side\n runtimeConfig:\n Object.keys(publicRuntimeConfig).length > 0\n ? publicRuntimeConfig\n : undefined,\n\n isExperimentalCompile: this.nextConfig.experimental.isExperimentalCompile,\n // `htmlLimitedBots` is passed to server as serialized config in string format\n htmlLimitedBots: this.nextConfig.htmlLimitedBots,\n experimental: {\n expireTime: this.nextConfig.expireTime,\n staleTimes: this.nextConfig.experimental.staleTimes,\n clientTraceMetadata: this.nextConfig.experimental.clientTraceMetadata,\n cacheComponents: this.nextConfig.experimental.cacheComponents ?? false,\n clientSegmentCache:\n this.nextConfig.experimental.clientSegmentCache === 'client-only'\n ? 'client-only'\n : Boolean(this.nextConfig.experimental.clientSegmentCache),\n clientParamParsing:\n this.nextConfig.experimental.clientParamParsing ?? false,\n dynamicOnHover: this.nextConfig.experimental.dynamicOnHover ?? false,\n inlineCss: this.nextConfig.experimental.inlineCss ?? false,\n authInterrupts: !!this.nextConfig.experimental.authInterrupts,\n },\n onInstrumentationRequestError:\n this.instrumentationOnRequestError.bind(this),\n reactMaxHeadersLength: this.nextConfig.reactMaxHeadersLength,\n devtoolSegmentExplorer:\n this.nextConfig.experimental.devtoolSegmentExplorer,\n }\n\n // Initialize next/config with the environment configuration\n setConfig({\n serverRuntimeConfig,\n publicRuntimeConfig,\n })\n\n this.pagesManifest = this.getPagesManifest()\n this.appPathsManifest = this.getAppPathsManifest()\n this.appPathRoutes = this.getAppPathRoutes()\n this.interceptionRoutePatterns = this.getinterceptionRoutePatterns()\n\n // Configure the routes.\n this.matchers = this.getRouteMatchers()\n\n // Start route compilation. We don't wait for the routes to finish loading\n // because we use the `waitTillReady` promise below in `handleRequest` to\n // wait. Also we can't `await` in the constructor.\n void this.matchers.reload()\n\n this.setAssetPrefix(assetPrefix)\n this.responseCache = this.getResponseCache({ dev })\n }\n\n private handleRSCRequest: RouteHandler = (\n req,\n _res,\n parsedUrl\n ) => {\n if (!parsedUrl.pathname) return false\n\n if (this.normalizers.segmentPrefetchRSC?.match(parsedUrl.pathname)) {\n const result = this.normalizers.segmentPrefetchRSC.extract(\n parsedUrl.pathname\n )\n if (!result) return false\n\n const { originalPathname, segmentPath } = result\n parsedUrl.pathname = originalPathname\n\n // Mark the request as a router prefetch request.\n req.headers[RSC_HEADER] = '1'\n req.headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'\n req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] = segmentPath\n\n addRequestMeta(req, 'isRSCRequest', true)\n addRequestMeta(req, 'isPrefetchRSCRequest', true)\n addRequestMeta(req, 'segmentPrefetchRSCRequest', segmentPath)\n } else if (this.normalizers.prefetchRSC?.match(parsedUrl.pathname)) {\n parsedUrl.pathname = this.normalizers.prefetchRSC.normalize(\n parsedUrl.pathname,\n true\n )\n\n // Mark the request as a router prefetch request.\n req.headers[RSC_HEADER] = '1'\n req.headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'\n addRequestMeta(req, 'isRSCRequest', true)\n addRequestMeta(req, 'isPrefetchRSCRequest', true)\n } else if (this.normalizers.rsc?.match(parsedUrl.pathname)) {\n parsedUrl.pathname = this.normalizers.rsc.normalize(\n parsedUrl.pathname,\n true\n )\n\n // Mark the request as a RSC request.\n req.headers[RSC_HEADER] = '1'\n addRequestMeta(req, 'isRSCRequest', true)\n } else if (req.headers['x-now-route-matches']) {\n // If we didn't match, return with the flight headers stripped. If in\n // minimal mode we didn't match based on the path, this can't be a RSC\n // request. This is because Vercel only sends this header during\n // revalidation requests and we want the cache to instead depend on the\n // request path for flight information.\n stripFlightHeaders(req.headers)\n\n return false\n } else if (req.headers[RSC_HEADER] === '1') {\n addRequestMeta(req, 'isRSCRequest', true)\n\n if (req.headers[NEXT_ROUTER_PREFETCH_HEADER] === '1') {\n addRequestMeta(req, 'isPrefetchRSCRequest', true)\n\n const segmentPrefetchRSCRequest =\n req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]\n if (typeof segmentPrefetchRSCRequest === 'string') {\n addRequestMeta(\n req,\n 'segmentPrefetchRSCRequest',\n segmentPrefetchRSCRequest\n )\n }\n }\n } else {\n // Otherwise just return without doing anything.\n return false\n }\n\n if (req.url) {\n const parsed = parseUrl(req.url)\n parsed.pathname = parsedUrl.pathname\n req.url = formatUrl(parsed)\n }\n\n return false\n }\n\n private handleNextDataRequest: RouteHandler =\n async (req, res, parsedUrl) => {\n const middleware = await this.getMiddleware()\n const params = matchNextDataPathname(parsedUrl.pathname)\n\n // ignore for non-next data URLs\n if (!params || !params.path) {\n return false\n }\n\n if (params.path[0] !== this.buildId) {\n // Ignore if its a middleware request when we aren't on edge.\n if (getRequestMeta(req, 'middlewareInvoke')) {\n return false\n }\n\n // Make sure to 404 if the buildId isn't correct\n await this.render404(req, res, parsedUrl)\n return true\n }\n\n // remove buildId from URL\n params.path.shift()\n\n const lastParam = params.path[params.path.length - 1]\n\n // show 404 if it doesn't end with .json\n if (typeof lastParam !== 'string' || !lastParam.endsWith('.json')) {\n await this.render404(req, res, parsedUrl)\n return true\n }\n\n // re-create page's pathname\n let pathname = `/${params.path.join('/')}`\n pathname = getRouteFromAssetPath(pathname, '.json')\n\n // ensure trailing slash is normalized per config\n if (middleware) {\n if (this.nextConfig.trailingSlash && !pathname.endsWith('/')) {\n pathname += '/'\n }\n if (\n !this.nextConfig.trailingSlash &&\n pathname.length > 1 &&\n pathname.endsWith('/')\n ) {\n pathname = pathname.substring(0, pathname.length - 1)\n }\n }\n\n if (this.i18nProvider) {\n // Remove the port from the hostname if present.\n const hostname = req?.headers.host?.split(':', 1)[0].toLowerCase()\n\n const domainLocale = this.i18nProvider.detectDomainLocale(hostname)\n const defaultLocale =\n domainLocale?.defaultLocale ?? this.i18nProvider.config.defaultLocale\n\n const localePathResult = this.i18nProvider.analyze(pathname)\n\n // If the locale is detected from the path, we need to remove it\n // from the pathname.\n if (localePathResult.detectedLocale) {\n pathname = localePathResult.pathname\n }\n\n // Update the query with the detected locale and default locale.\n addRequestMeta(req, 'locale', localePathResult.detectedLocale)\n addRequestMeta(req, 'defaultLocale', defaultLocale)\n\n // If the locale is not detected from the path, we need to mark that\n // it was not inferred from default.\n if (!localePathResult.detectedLocale) {\n removeRequestMeta(req, 'localeInferredFromDefault')\n }\n\n // If no locale was detected and we don't have middleware, we need\n // to render a 404 page.\n if (!localePathResult.detectedLocale && !middleware) {\n addRequestMeta(req, 'locale', defaultLocale)\n await this.render404(req, res, parsedUrl)\n return true\n }\n }\n\n parsedUrl.pathname = pathname\n addRequestMeta(req, 'isNextDataReq', true)\n\n return false\n }\n\n protected handleNextImageRequest: RouteHandler<\n ServerRequest,\n ServerResponse\n > = () => false\n\n protected handleCatchallRenderRequest: RouteHandler<\n ServerRequest,\n ServerResponse\n > = () => false\n\n protected handleCatchallMiddlewareRequest: RouteHandler<\n ServerRequest,\n ServerResponse\n > = () => false\n\n protected getRouteMatchers(): RouteMatcherManager {\n // Create a new manifest loader that get's the manifests from the server.\n const manifestLoader = new ServerManifestLoader((name) => {\n switch (name) {\n case PAGES_MANIFEST:\n return this.getPagesManifest() ?? null\n case APP_PATHS_MANIFEST:\n return this.getAppPathsManifest() ?? null\n default:\n return null\n }\n })\n\n // Configure the matchers and handlers.\n const matchers: RouteMatcherManager = new DefaultRouteMatcherManager()\n\n // Match pages under `pages/`.\n matchers.push(\n new PagesRouteMatcherProvider(\n this.distDir,\n manifestLoader,\n this.i18nProvider\n )\n )\n\n // Match api routes under `pages/api/`.\n matchers.push(\n new PagesAPIRouteMatcherProvider(\n this.distDir,\n manifestLoader,\n this.i18nProvider\n )\n )\n\n // If the app directory is enabled, then add the app matchers and handlers.\n if (this.enabledDirectories.app) {\n // Match app pages under `app/`.\n matchers.push(\n new AppPageRouteMatcherProvider(this.distDir, manifestLoader)\n )\n matchers.push(\n new AppRouteRouteMatcherProvider(this.distDir, manifestLoader)\n )\n }\n\n return matchers\n }\n\n protected async instrumentationOnRequestError(\n ...args: Parameters\n ) {\n const [err, req, ctx] = args\n\n if (this.instrumentation) {\n try {\n await this.instrumentation.onRequestError?.(\n err,\n {\n path: req.url || '',\n method: req.method || 'GET',\n // Normalize middleware headers and other server request headers\n headers:\n req instanceof NextRequestHint\n ? Object.fromEntries(req.headers.entries())\n : req.headers,\n },\n ctx\n )\n } catch (handlerErr) {\n // Log the soft error and continue, since errors can thrown from react stream handler\n console.error('Error in instrumentation.onRequestError:', handlerErr)\n }\n }\n }\n\n public logError(err: Error): void {\n if (this.quiet) return\n Log.error(err)\n }\n\n public async handleRequest(\n req: ServerRequest,\n res: ServerResponse,\n parsedUrl?: NextUrlWithParsedQuery\n ): Promise {\n await this.prepare()\n const method = req.method.toUpperCase()\n\n const tracer = getTracer()\n return tracer.withPropagatedContext(req.headers, () => {\n return tracer.trace(\n BaseServerSpan.handleRequest,\n {\n spanName: `${method} ${req.url}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url,\n },\n },\n async (span) =>\n this.handleRequestImpl(req, res, parsedUrl).finally(() => {\n if (!span) return\n\n const isRSCRequest = getRequestMeta(req, 'isRSCRequest') ?? false\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': isRSCRequest,\n })\n\n if (res.statusCode && res.statusCode >= 500) {\n // For 5xx status codes: SHOULD be set to 'Error' span status.\n // x-ref: https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status\n span.setStatus({\n code: SpanStatusCode.ERROR,\n })\n // For span status 'Error', SHOULD set 'error.type' attribute.\n span.setAttribute('error.type', res.statusCode.toString())\n }\n\n const rootSpanAttributes = tracer.getRootSpanAttributes()\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) return\n\n if (\n rootSpanAttributes.get('next.span_type') !==\n BaseServerSpan.handleRequest\n ) {\n console.warn(\n `Unexpected root span type '${rootSpanAttributes.get(\n 'next.span_type'\n )}'. Please report this Next.js issue https://github.com/vercel/next.js`\n )\n return\n }\n\n const route = rootSpanAttributes.get('next.route')\n if (route) {\n const name = isRSCRequest\n ? `RSC ${method} ${route}`\n : `${method} ${route}`\n\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name,\n })\n span.updateName(name)\n } else {\n span.updateName(\n isRSCRequest\n ? `RSC ${method} ${req.url}`\n : `${method} ${req.url}`\n )\n }\n })\n )\n })\n }\n\n private async handleRequestImpl(\n req: ServerRequest,\n res: ServerResponse,\n parsedUrl?: NextUrlWithParsedQuery\n ): Promise {\n try {\n // Wait for the matchers to be ready.\n await this.matchers.waitTillReady()\n\n // ensure cookies set in middleware are merged and\n // not overridden by API routes/getServerSideProps\n patchSetHeaderWithCookieSupport(\n req,\n isNodeNextResponse(res) ? res.originalResponse : res\n )\n\n const urlParts = (req.url || '').split('?', 1)\n const urlNoQuery = urlParts[0]\n\n // this normalizes repeated slashes in the path e.g. hello//world ->\n // hello/world or backslashes to forward slashes, this does not\n // handle trailing slash as that is handled the same as a next.config.js\n // redirect\n if (urlNoQuery?.match(/(\\\\|\\/\\/)/)) {\n const cleanUrl = normalizeRepeatedSlashes(req.url!)\n res.redirect(cleanUrl, 308).body(cleanUrl).send()\n return\n }\n\n // Parse url if parsedUrl not provided\n if (!parsedUrl || typeof parsedUrl !== 'object') {\n if (!req.url) {\n throw new Error('Invariant: url can not be undefined')\n }\n\n parsedUrl = parseUrl(req.url!, true)\n }\n\n if (!parsedUrl.pathname) {\n throw new Error(\"Invariant: pathname can't be empty\")\n }\n\n // Parse the querystring ourselves if the user doesn't handle querystring parsing\n if (typeof parsedUrl.query === 'string') {\n parsedUrl.query = Object.fromEntries(\n new URLSearchParams(parsedUrl.query)\n )\n }\n\n // Update the `x-forwarded-*` headers.\n const { originalRequest = null } = isNodeNextRequest(req) ? req : {}\n const xForwardedProto = originalRequest?.headers['x-forwarded-proto']\n const isHttps = xForwardedProto\n ? xForwardedProto === 'https'\n : !!(originalRequest?.socket as TLSSocket)?.encrypted\n\n req.headers['x-forwarded-host'] ??= req.headers['host'] ?? this.hostname\n req.headers['x-forwarded-port'] ??= this.port\n ? this.port.toString()\n : isHttps\n ? '443'\n : '80'\n req.headers['x-forwarded-proto'] ??= isHttps ? 'https' : 'http'\n req.headers['x-forwarded-for'] ??= originalRequest?.socket?.remoteAddress\n\n // This should be done before any normalization of the pathname happens as\n // it captures the initial URL.\n this.attachRequestMeta(req, parsedUrl)\n\n let finished = await this.handleRSCRequest(req, res, parsedUrl)\n if (finished) return\n\n const domainLocale = this.i18nProvider?.detectDomainLocale(\n getHostname(parsedUrl, req.headers)\n )\n\n const defaultLocale =\n domainLocale?.defaultLocale || this.nextConfig.i18n?.defaultLocale\n addRequestMeta(req, 'defaultLocale', defaultLocale)\n\n const url = parseUrlUtil(req.url.replace(/^\\/+/, '/'))\n const pathnameInfo = getNextPathnameInfo(url.pathname, {\n nextConfig: this.nextConfig,\n i18nProvider: this.i18nProvider,\n })\n url.pathname = pathnameInfo.pathname\n\n if (pathnameInfo.basePath) {\n req.url = removePathPrefix(req.url!, this.nextConfig.basePath)\n }\n\n const useMatchedPathHeader =\n this.minimalMode && typeof req.headers[MATCHED_PATH_HEADER] === 'string'\n\n // TODO: merge handling with invokePath\n if (useMatchedPathHeader) {\n try {\n if (this.enabledDirectories.app) {\n // ensure /index path is normalized for prerender\n // in minimal mode\n if (req.url.match(/^\\/index($|\\?)/)) {\n req.url = req.url.replace(/^\\/index/, '/')\n }\n parsedUrl.pathname =\n parsedUrl.pathname === '/index' ? '/' : parsedUrl.pathname\n }\n\n // x-matched-path is the source of truth, it tells what page\n // should be rendered because we don't process rewrites in minimalMode\n let { pathname: matchedPath } = new URL(\n fixMojibake(req.headers[MATCHED_PATH_HEADER] as string),\n 'http://localhost'\n )\n\n let { pathname: urlPathname } = new URL(req.url, 'http://localhost')\n\n // For ISR the URL is normalized to the prerenderPath so if\n // it's a data request the URL path will be the data URL,\n // basePath is already stripped by this point\n if (this.normalizers.data?.match(urlPathname)) {\n addRequestMeta(req, 'isNextDataReq', true)\n }\n // In minimal mode, if PPR is enabled, then we should check to see if\n // the request should be a resume request.\n else if (\n this.isAppPPREnabled &&\n this.minimalMode &&\n req.headers[NEXT_RESUME_HEADER] === '1' &&\n req.method === 'POST'\n ) {\n // Decode the postponed state from the request body, it will come as\n // an array of buffers, so collect them and then concat them to form\n // the string.\n const body: Array = []\n for await (const chunk of req.body) {\n body.push(chunk)\n }\n const postponed = Buffer.concat(body).toString('utf8')\n\n addRequestMeta(req, 'postponed', postponed)\n }\n\n matchedPath = this.normalize(matchedPath)\n const normalizedUrlPath = this.stripNextDataPath(urlPathname)\n\n matchedPath = denormalizePagePath(matchedPath)\n\n // Perform locale detection and normalization.\n const localeAnalysisResult = this.i18nProvider?.analyze(matchedPath, {\n defaultLocale,\n })\n\n // The locale result will be defined even if the locale was not\n // detected for the request because it will be inferred from the\n // default locale.\n if (localeAnalysisResult) {\n addRequestMeta(req, 'locale', localeAnalysisResult.detectedLocale)\n\n // If the detected locale was inferred from the default locale, we\n // need to modify the metadata on the request to indicate that.\n if (localeAnalysisResult.inferredFromDefault) {\n addRequestMeta(req, 'localeInferredFromDefault', true)\n } else {\n removeRequestMeta(req, 'localeInferredFromDefault')\n }\n }\n\n let srcPathname = matchedPath\n let pageIsDynamic = isDynamicRoute(srcPathname)\n let paramsResult: {\n params: ParsedUrlQuery | false\n hasValidParams: boolean\n } = {\n params: false,\n hasValidParams: false,\n }\n\n if (!pageIsDynamic) {\n const match = await this.matchers.match(srcPathname, {\n i18n: localeAnalysisResult,\n })\n\n // Update the source pathname to the matched page's pathname.\n if (match) {\n srcPathname = match.definition.pathname\n\n // The page is dynamic if the params are defined. We know at this\n // stage that the matched path is not a static page if the params\n // were parsed from the matched path header.\n if (typeof match.params !== 'undefined') {\n pageIsDynamic = true\n paramsResult.params = match.params\n paramsResult.hasValidParams = true\n }\n }\n }\n\n // The rest of this function can't handle i18n properly, so ensure we\n // restore the pathname with the locale information stripped from it\n // now that we're done matching if we're using i18n.\n if (localeAnalysisResult) {\n matchedPath = localeAnalysisResult.pathname\n }\n\n const utils = getServerUtils({\n pageIsDynamic,\n page: srcPathname,\n i18n: this.nextConfig.i18n,\n basePath: this.nextConfig.basePath,\n rewrites: this.getRoutesManifest()?.rewrites || {\n beforeFiles: [],\n afterFiles: [],\n fallback: [],\n },\n caseSensitive: !!this.nextConfig.experimental.caseSensitiveRoutes,\n })\n\n // Ensure parsedUrl.pathname includes locale before processing\n // rewrites or they won't match correctly.\n if (defaultLocale && !pathnameInfo.locale) {\n parsedUrl.pathname = `/${defaultLocale}${parsedUrl.pathname}`\n }\n\n // Store a copy of `parsedUrl.query` before calling handleRewrites.\n // Since `handleRewrites` might add new queries to `parsedUrl.query`.\n const originQueryParams = { ...parsedUrl.query }\n\n const pathnameBeforeRewrite = parsedUrl.pathname\n const rewriteParamKeys = Object.keys(\n utils.handleRewrites(req, parsedUrl)\n )\n\n // Create a copy of the query params to avoid mutating the original\n // object. This prevents any overlapping query params that have the\n // same normalized key from causing issues.\n const queryParams = { ...parsedUrl.query }\n const didRewrite = pathnameBeforeRewrite !== parsedUrl.pathname\n\n if (didRewrite && parsedUrl.pathname) {\n addRequestMeta(req, 'rewroteURL', parsedUrl.pathname)\n }\n\n const routeParamKeys = new Set()\n for (const [key, value] of Object.entries(parsedUrl.query)) {\n const normalizedKey = normalizeNextQueryParam(key)\n if (!normalizedKey) continue\n\n // Remove the prefixed key from the query params because we want\n // to consume it for the dynamic route matcher.\n delete parsedUrl.query[key]\n routeParamKeys.add(normalizedKey)\n\n if (typeof value === 'undefined') continue\n\n queryParams[normalizedKey] = Array.isArray(value)\n ? value.map((v) => decodeQueryPathParameter(v))\n : decodeQueryPathParameter(value)\n }\n\n // interpolate dynamic params and normalize URL if needed\n if (pageIsDynamic) {\n let params: ParsedUrlQuery | false = {}\n\n // If we don't already have valid params, try to parse them from\n // the query params.\n if (!paramsResult.hasValidParams) {\n paramsResult = utils.normalizeDynamicRouteParams(\n queryParams,\n false\n )\n }\n\n // for prerendered ISR paths we attempt parsing the route\n // params from the URL directly as route-matches may not\n // contain the correct values due to the filesystem path\n // matching before the dynamic route has been matched\n if (\n !paramsResult.hasValidParams &&\n !isDynamicRoute(normalizedUrlPath)\n ) {\n let matcherParams = utils.dynamicRouteMatcher?.(normalizedUrlPath)\n\n if (matcherParams) {\n utils.normalizeDynamicRouteParams(matcherParams, false)\n Object.assign(paramsResult.params, matcherParams)\n paramsResult.hasValidParams = true\n }\n }\n\n // if an action request is bypassing a prerender and we\n // don't have the params in the URL since it was prerendered\n // and matched during handle: 'filesystem' rather than dynamic route\n // resolving we need to parse the params from the matched-path.\n // Note: this is similar to above case but from match-path instead\n // of from the request URL since a rewrite could cause that to not\n // match the src pathname\n if (\n // we can have a collision with /index and a top-level /[slug]\n matchedPath !== '/index' &&\n !paramsResult.hasValidParams &&\n !isDynamicRoute(matchedPath)\n ) {\n let matcherParams = utils.dynamicRouteMatcher?.(matchedPath)\n\n if (matcherParams) {\n const curParamsResult = utils.normalizeDynamicRouteParams(\n matcherParams,\n false\n )\n\n if (curParamsResult.hasValidParams) {\n Object.assign(params, matcherParams)\n paramsResult = curParamsResult\n }\n }\n }\n\n if (paramsResult.hasValidParams) {\n params = paramsResult.params\n }\n\n const routeMatchesHeader = req.headers['x-now-route-matches']\n if (\n typeof routeMatchesHeader === 'string' &&\n routeMatchesHeader &&\n isDynamicRoute(matchedPath) &&\n !paramsResult.hasValidParams\n ) {\n const routeMatches =\n utils.getParamsFromRouteMatches(routeMatchesHeader)\n\n if (routeMatches) {\n paramsResult = utils.normalizeDynamicRouteParams(\n routeMatches,\n true\n )\n\n if (paramsResult.hasValidParams) {\n params = paramsResult.params\n }\n }\n }\n\n // Try to parse the params from the query if we couldn't parse them\n // from the route matches but ignore missing optional params.\n if (!paramsResult.hasValidParams) {\n paramsResult = utils.normalizeDynamicRouteParams(\n queryParams,\n true\n )\n\n if (paramsResult.hasValidParams) {\n params = paramsResult.params\n }\n }\n\n // If the pathname being requested is the same as the source\n // pathname, and we don't have valid params, we want to use the\n // default route matches.\n if (\n utils.defaultRouteMatches &&\n normalizedUrlPath === srcPathname &&\n !paramsResult.hasValidParams\n ) {\n params = utils.defaultRouteMatches\n\n // If the route matches header is an empty string, we want to\n // render a fallback shell. This is because we know this came from\n // a prerender (it has the header) but it's values were filtered\n // out (because the allowQuery was empty). If it was undefined\n // then we know that the request is hitting the lambda directly.\n if (routeMatchesHeader === '') {\n addRequestMeta(req, 'renderFallbackShell', true)\n }\n }\n\n if (params) {\n matchedPath = utils.interpolateDynamicPath(srcPathname, params)\n req.url = utils.interpolateDynamicPath(req.url!, params)\n\n // If the request is for a segment prefetch, we need to update the\n // segment prefetch request path to include the interpolated\n // params.\n let segmentPrefetchRSCRequest = getRequestMeta(\n req,\n 'segmentPrefetchRSCRequest'\n )\n if (\n segmentPrefetchRSCRequest &&\n isDynamicRoute(segmentPrefetchRSCRequest, false)\n ) {\n segmentPrefetchRSCRequest = utils.interpolateDynamicPath(\n segmentPrefetchRSCRequest,\n params\n )\n\n req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] =\n segmentPrefetchRSCRequest\n addRequestMeta(\n req,\n 'segmentPrefetchRSCRequest',\n segmentPrefetchRSCRequest\n )\n }\n }\n }\n\n if (pageIsDynamic || didRewrite) {\n utils.normalizeCdnUrl(req, [\n ...rewriteParamKeys,\n ...Object.keys(utils.defaultRouteRegex?.groups || {}),\n ])\n }\n // Remove the route `params` keys from `parsedUrl.query` if they are\n // not in the original query params.\n // If it's used in both route `params` and query `searchParams`, it should be kept.\n for (const key of routeParamKeys) {\n if (!(key in originQueryParams)) {\n delete parsedUrl.query[key]\n }\n }\n parsedUrl.pathname = matchedPath\n url.pathname = parsedUrl.pathname\n finished = await this.normalizeAndAttachMetadata(req, res, parsedUrl)\n if (finished) return\n } catch (err) {\n if (err instanceof DecodeError || err instanceof NormalizeError) {\n res.statusCode = 400\n return this.renderError(null, req, res, '/_error', {})\n }\n throw err\n }\n }\n\n addRequestMeta(req, 'isLocaleDomain', Boolean(domainLocale))\n\n if (pathnameInfo.locale) {\n req.url = formatUrl(url)\n addRequestMeta(req, 'didStripLocale', true)\n }\n\n // If we aren't in minimal mode or there is no locale in the query\n // string, add the locale to the query string.\n if (!this.minimalMode || !getRequestMeta(req, 'locale')) {\n // If the locale is in the pathname, add it to the query string.\n if (pathnameInfo.locale) {\n addRequestMeta(req, 'locale', pathnameInfo.locale)\n }\n // If the default locale is available, add it to the query string and\n // mark it as inferred rather than implicit.\n else if (defaultLocale) {\n addRequestMeta(req, 'locale', defaultLocale)\n addRequestMeta(req, 'localeInferredFromDefault', true)\n }\n }\n\n // set incremental cache to request meta so it can\n // be passed down for edge functions and the fetch disk\n // cache can be leveraged locally\n if (\n !(this.serverOptions as any).webServerConfig &&\n !getRequestMeta(req, 'incrementalCache')\n ) {\n const incrementalCache = await this.getIncrementalCache({\n requestHeaders: Object.assign({}, req.headers),\n })\n\n incrementalCache.resetRequestCache()\n addRequestMeta(req, 'incrementalCache', incrementalCache)\n // This is needed for pages router to leverage unstable_cache\n // TODO: re-work this handling to not use global and use a AsyncStore\n ;(globalThis as any).__incrementalCache = incrementalCache\n }\n\n const cacheHandlers = getCacheHandlers()\n\n if (cacheHandlers) {\n await Promise.all(\n [...cacheHandlers].map(async (cacheHandler) => {\n if ('refreshTags' in cacheHandler) {\n // Note: cacheHandler.refreshTags() is called lazily before the\n // first cache entry is retrieved. It allows us to skip the\n // refresh request if no caches are read at all.\n } else {\n const previouslyRevalidatedTags = getPreviouslyRevalidatedTags(\n req.headers,\n this.getPrerenderManifest().preview.previewModeId\n )\n\n await cacheHandler.receiveExpiredTags(\n ...previouslyRevalidatedTags\n )\n }\n })\n )\n }\n\n // set server components HMR cache to request meta so it can be passed\n // down for edge functions\n if (!getRequestMeta(req, 'serverComponentsHmrCache')) {\n addRequestMeta(\n req,\n 'serverComponentsHmrCache',\n this.getServerComponentsHmrCache()\n )\n }\n\n // when invokePath is specified we can short short circuit resolving\n // we only honor this header if we are inside of a render worker to\n // prevent external users coercing the routing path\n const invokePath = getRequestMeta(req, 'invokePath')\n const useInvokePath = !useMatchedPathHeader && invokePath\n\n if (useInvokePath) {\n const invokeStatus = getRequestMeta(req, 'invokeStatus')\n if (invokeStatus) {\n const invokeQuery = getRequestMeta(req, 'invokeQuery')\n\n if (invokeQuery) {\n Object.assign(parsedUrl.query, invokeQuery)\n }\n\n res.statusCode = invokeStatus\n let err: Error | null = getRequestMeta(req, 'invokeError') || null\n\n return this.renderError(err, req, res, '/_error', parsedUrl.query)\n }\n\n const parsedMatchedPath = new URL(invokePath || '/', 'http://n')\n const invokePathnameInfo = getNextPathnameInfo(\n parsedMatchedPath.pathname,\n {\n nextConfig: this.nextConfig,\n parseData: false,\n }\n )\n\n if (invokePathnameInfo.locale) {\n addRequestMeta(req, 'locale', invokePathnameInfo.locale)\n }\n\n if (parsedUrl.pathname !== parsedMatchedPath.pathname) {\n parsedUrl.pathname = parsedMatchedPath.pathname\n addRequestMeta(req, 'rewroteURL', invokePathnameInfo.pathname)\n }\n const normalizeResult = normalizeLocalePath(\n removePathPrefix(parsedUrl.pathname, this.nextConfig.basePath || ''),\n this.nextConfig.i18n?.locales\n )\n\n if (normalizeResult.detectedLocale) {\n addRequestMeta(req, 'locale', normalizeResult.detectedLocale)\n }\n parsedUrl.pathname = normalizeResult.pathname\n\n for (const key of Object.keys(parsedUrl.query)) {\n delete parsedUrl.query[key]\n }\n const invokeQuery = getRequestMeta(req, 'invokeQuery')\n\n if (invokeQuery) {\n Object.assign(parsedUrl.query, invokeQuery)\n }\n\n finished = await this.normalizeAndAttachMetadata(req, res, parsedUrl)\n if (finished) return\n\n await this.handleCatchallRenderRequest(req, res, parsedUrl)\n return\n }\n\n if (getRequestMeta(req, 'middlewareInvoke')) {\n finished = await this.normalizeAndAttachMetadata(req, res, parsedUrl)\n if (finished) return\n\n finished = await this.handleCatchallMiddlewareRequest(\n req,\n res,\n parsedUrl\n )\n if (finished) return\n\n const err = new Error()\n ;(err as any).result = {\n response: new Response(null, {\n headers: {\n 'x-middleware-next': '1',\n },\n }),\n }\n ;(err as any).bubble = true\n throw err\n }\n\n // This wasn't a request via the matched path or the invoke path, so\n // prepare for a legacy run by removing the base path.\n\n // ensure we strip the basePath when not using an invoke header\n if (!useMatchedPathHeader && pathnameInfo.basePath) {\n parsedUrl.pathname = removePathPrefix(\n parsedUrl.pathname,\n pathnameInfo.basePath\n )\n }\n\n res.statusCode = 200\n return await this.run(req, res, parsedUrl)\n } catch (err: any) {\n if (err instanceof NoFallbackError) {\n throw err\n }\n\n if (\n (err && typeof err === 'object' && err.code === 'ERR_INVALID_URL') ||\n err instanceof DecodeError ||\n err instanceof NormalizeError\n ) {\n res.statusCode = 400\n return this.renderError(null, req, res, '/_error', {})\n }\n\n if (\n this.minimalMode ||\n this.renderOpts.dev ||\n (isBubbledError(err) && err.bubble)\n ) {\n throw err\n }\n this.logError(getProperError(err))\n res.statusCode = 500\n res.body('Internal Server Error').send()\n }\n }\n\n /**\n * Normalizes a pathname without attaching any metadata from any matched\n * normalizer.\n *\n * @param pathname the pathname to normalize\n * @returns the normalized pathname\n */\n private normalize = (pathname: string) => {\n const normalizers: Array = []\n\n if (this.normalizers.data) {\n normalizers.push(this.normalizers.data)\n }\n\n // We have to put the segment prefetch normalizer before the RSC normalizer\n // because the RSC normalizer will match the prefetch RSC routes too.\n if (this.normalizers.segmentPrefetchRSC) {\n normalizers.push(this.normalizers.segmentPrefetchRSC)\n }\n\n // We have to put the prefetch normalizer before the RSC normalizer\n // because the RSC normalizer will match the prefetch RSC routes too.\n if (this.normalizers.prefetchRSC) {\n normalizers.push(this.normalizers.prefetchRSC)\n }\n\n if (this.normalizers.rsc) {\n normalizers.push(this.normalizers.rsc)\n }\n\n for (const normalizer of normalizers) {\n if (!normalizer.match(pathname)) continue\n\n return normalizer.normalize(pathname, true)\n }\n\n return pathname\n }\n\n private normalizeAndAttachMetadata: RouteHandler<\n ServerRequest,\n ServerResponse\n > = async (req, res, url) => {\n let finished = await this.handleNextImageRequest(req, res, url)\n if (finished) return true\n\n if (this.enabledDirectories.pages) {\n finished = await this.handleNextDataRequest(req, res, url)\n if (finished) return true\n }\n\n return false\n }\n\n /**\n * @internal - this method is internal to Next.js and should not be used directly by end-users\n */\n public getRequestHandlerWithMetadata(\n meta: RequestMeta\n ): BaseRequestHandler {\n const handler = this.getRequestHandler()\n return (req, res, parsedUrl) => {\n setRequestMeta(req, meta)\n return handler(req, res, parsedUrl)\n }\n }\n\n public getRequestHandler(): BaseRequestHandler<\n ServerRequest,\n ServerResponse\n > {\n return this.handleRequest.bind(this)\n }\n\n protected abstract handleUpgrade(\n req: ServerRequest,\n socket: any,\n head?: any\n ): Promise\n\n public setAssetPrefix(prefix?: string): void {\n this.nextConfig.assetPrefix = prefix ? prefix.replace(/\\/$/, '') : ''\n }\n\n protected prepared: boolean = false\n protected preparedPromise: Promise | null = null\n /**\n * Runs async initialization of server.\n * It is idempotent, won't fire underlying initialization more than once.\n */\n public async prepare(): Promise {\n if (this.prepared) return\n\n // Get instrumentation module\n if (!this.instrumentation) {\n this.instrumentation = await this.loadInstrumentationModule()\n }\n if (this.preparedPromise === null) {\n this.preparedPromise = this.prepareImpl().then(() => {\n this.prepared = true\n this.preparedPromise = null\n })\n }\n return this.preparedPromise\n }\n protected async prepareImpl(): Promise {}\n protected async loadInstrumentationModule(): Promise {}\n\n public async close(): Promise {}\n\n protected getAppPathRoutes(): Record {\n const appPathRoutes: Record = {}\n\n Object.keys(this.appPathsManifest || {}).forEach((entry) => {\n const normalizedPath = normalizeAppPath(entry)\n if (!appPathRoutes[normalizedPath]) {\n appPathRoutes[normalizedPath] = []\n }\n appPathRoutes[normalizedPath].push(entry)\n })\n return appPathRoutes\n }\n\n protected async run(\n req: ServerRequest,\n res: ServerResponse,\n parsedUrl: UrlWithParsedQuery\n ): Promise {\n return getTracer().trace(BaseServerSpan.run, async () =>\n this.runImpl(req, res, parsedUrl)\n )\n }\n\n private async runImpl(\n req: ServerRequest,\n res: ServerResponse,\n parsedUrl: UrlWithParsedQuery\n ): Promise {\n await this.handleCatchallRenderRequest(req, res, parsedUrl)\n }\n\n private async pipe(\n fn: (\n ctx: RequestContext\n ) => Promise,\n partialContext: Omit<\n RequestContext,\n 'renderOpts'\n >\n ): Promise {\n return getTracer().trace(BaseServerSpan.pipe, async () =>\n this.pipeImpl(fn, partialContext)\n )\n }\n\n private async pipeImpl(\n fn: (\n ctx: RequestContext\n ) => Promise,\n partialContext: Omit<\n RequestContext,\n 'renderOpts'\n >\n ): Promise {\n const ua = partialContext.req.headers['user-agent'] || ''\n\n const ctx: RequestContext = {\n ...partialContext,\n renderOpts: {\n ...this.renderOpts,\n // `renderOpts.botType` is accumulated in `this.renderImpl()`\n supportsDynamicResponse: !this.renderOpts.botType,\n serveStreamingMetadata: shouldServeStreamingMetadata(\n ua,\n this.nextConfig.htmlLimitedBots\n ),\n },\n }\n\n const payload = await fn(ctx)\n if (payload === null) {\n return\n }\n const { req, res } = ctx\n const originalStatus = res.statusCode\n const { body } = payload\n let { cacheControl } = payload\n if (!res.sent) {\n const { generateEtags, poweredByHeader, dev } = this.renderOpts\n\n // In dev, we should not cache pages for any reason.\n if (dev) {\n res.setHeader('Cache-Control', 'no-store, must-revalidate')\n cacheControl = undefined\n }\n\n if (cacheControl && cacheControl.expire === undefined) {\n cacheControl.expire = this.nextConfig.expireTime\n }\n\n await this.sendRenderResult(req, res, {\n result: body,\n generateEtags,\n poweredByHeader,\n cacheControl,\n })\n res.statusCode = originalStatus\n }\n }\n\n private async getStaticHTML(\n fn: (\n ctx: RequestContext\n ) => Promise,\n partialContext: Omit<\n RequestContext,\n 'renderOpts'\n >\n ): Promise {\n const ctx: RequestContext = {\n ...partialContext,\n renderOpts: {\n ...this.renderOpts,\n supportsDynamicResponse: false,\n },\n }\n const payload = await fn(ctx)\n if (payload === null) {\n return null\n }\n return payload.body.toUnchunkedString()\n }\n\n public async render(\n req: ServerRequest,\n res: ServerResponse,\n pathname: string,\n query: NextParsedUrlQuery = {},\n parsedUrl?: NextUrlWithParsedQuery,\n internalRender = false\n ): Promise {\n return getTracer().trace(BaseServerSpan.render, async () =>\n this.renderImpl(req, res, pathname, query, parsedUrl, internalRender)\n )\n }\n\n protected getWaitUntil(): WaitUntil | undefined {\n const builtinRequestContext = getBuiltinRequestContext()\n if (builtinRequestContext) {\n // the platform provided a request context.\n // use the `waitUntil` from there, whether actually present or not --\n // if not present, `after` will error.\n\n // NOTE: if we're in an edge runtime sandbox, this context will be used to forward the outer waitUntil.\n return builtinRequestContext.waitUntil\n }\n\n if (this.minimalMode) {\n // we're built for a serverless environment, and `waitUntil` is not available,\n // but using a noop would likely lead to incorrect behavior,\n // because we have no way of keeping the invocation alive.\n // return nothing, and `after` will error if used.\n //\n // NOTE: for edge functions, `NextWebServer` always runs in minimal mode.\n //\n // NOTE: if we're in an edge runtime sandbox, waitUntil will be passed in using \"@next/request-context\",\n // so we won't get here.\n return undefined\n }\n\n return this.getInternalWaitUntil()\n }\n\n protected getInternalWaitUntil(): WaitUntil | undefined {\n return undefined\n }\n\n private async renderImpl(\n req: ServerRequest,\n res: ServerResponse,\n pathname: string,\n query: NextParsedUrlQuery = {},\n parsedUrl?: NextUrlWithParsedQuery,\n internalRender = false\n ): Promise {\n if (!pathname.startsWith('/')) {\n console.warn(\n `Cannot render page with path \"${pathname}\", did you mean \"/${pathname}\"?. See more info here: https://nextjs.org/docs/messages/render-no-starting-slash`\n )\n }\n\n if (\n this.serverOptions.customServer &&\n pathname === '/index' &&\n !(await this.hasPage('/index'))\n ) {\n // maintain backwards compatibility for custom server\n // (see custom-server integration tests)\n pathname = '/'\n }\n\n const ua = req.headers['user-agent'] || ''\n this.renderOpts.botType = getBotType(ua)\n\n // we allow custom servers to call render for all URLs\n // so check if we need to serve a static _next file or not.\n // we don't modify the URL for _next/data request but still\n // call render so we special case this to prevent an infinite loop\n if (\n !internalRender &&\n !this.minimalMode &&\n !getRequestMeta(req, 'isNextDataReq') &&\n (req.url?.match(/^\\/_next\\//) ||\n (this.hasStaticDir && req.url!.match(/^\\/static\\//)))\n ) {\n return this.handleRequest(req, res, parsedUrl)\n }\n\n if (isBlockedPage(pathname)) {\n return this.render404(req, res, parsedUrl)\n }\n\n return this.pipe((ctx) => this.renderToResponse(ctx), {\n req,\n res,\n pathname,\n query,\n })\n }\n\n protected async getStaticPaths({\n pathname,\n }: {\n pathname: string\n urlPathname: string\n requestHeaders: import('./lib/incremental-cache').IncrementalCache['requestHeaders']\n page: string\n isAppPath: boolean\n }): Promise<{\n staticPaths?: string[]\n prerenderedRoutes?: PrerenderedRoute[]\n fallbackMode?: FallbackMode\n }> {\n // Read whether or not fallback should exist from the manifest.\n const fallbackField =\n this.getPrerenderManifest().dynamicRoutes[pathname]?.fallback\n\n return {\n // `staticPaths` is intentionally set to `undefined` as it should've\n // been caught when checking disk data.\n staticPaths: undefined,\n fallbackMode: parseFallbackField(fallbackField),\n }\n }\n\n private async renderToResponseWithComponents(\n requestContext: RequestContext,\n findComponentsResult: FindComponentsResult\n ): Promise {\n return getTracer().trace(\n BaseServerSpan.renderToResponseWithComponents,\n async () =>\n this.renderToResponseWithComponentsImpl(\n requestContext,\n findComponentsResult\n )\n )\n }\n\n protected pathCouldBeIntercepted(resolvedPathname: string): boolean {\n return (\n isInterceptionRouteAppPath(resolvedPathname) ||\n this.interceptionRoutePatterns.some((regexp) => {\n return regexp.test(resolvedPathname)\n })\n )\n }\n\n protected setVaryHeader(\n req: ServerRequest,\n res: ServerResponse,\n isAppPath: boolean,\n resolvedPathname: string\n ): void {\n const baseVaryHeader = `${RSC_HEADER}, ${NEXT_ROUTER_STATE_TREE_HEADER}, ${NEXT_ROUTER_PREFETCH_HEADER}, ${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}`\n const isRSCRequest = getRequestMeta(req, 'isRSCRequest') ?? false\n\n let addedNextUrlToVary = false\n\n if (isAppPath && this.pathCouldBeIntercepted(resolvedPathname)) {\n // Interception route responses can vary based on the `Next-URL` header.\n // We use the Vary header to signal this behavior to the client to properly cache the response.\n res.appendHeader('vary', `${baseVaryHeader}, ${NEXT_URL}`)\n addedNextUrlToVary = true\n } else if (isAppPath || isRSCRequest) {\n // We don't need to include `Next-URL` in the Vary header for non-interception routes since it won't affect the response.\n // We also set this header for pages to avoid caching issues when navigating between pages and app.\n res.appendHeader('vary', baseVaryHeader)\n }\n\n if (!addedNextUrlToVary) {\n // Remove `Next-URL` from the request headers we determined it wasn't necessary to include in the Vary header.\n // This is to avoid any dependency on the `Next-URL` header being present when preparing the response.\n delete req.headers[NEXT_URL]\n }\n }\n\n private async renderToResponseWithComponentsImpl(\n {\n req,\n res,\n pathname,\n renderOpts: opts,\n }: RequestContext,\n { components, query }: FindComponentsResult\n ): Promise {\n if (pathname === UNDERSCORE_NOT_FOUND_ROUTE) {\n pathname = '/404'\n }\n const isErrorPathname = pathname === '/_error'\n const is404Page =\n pathname === '/404' || (isErrorPathname && res.statusCode === 404)\n const is500Page =\n pathname === '/500' || (isErrorPathname && res.statusCode === 500)\n const isAppPath = components.isAppPath === true\n\n const hasServerProps = !!components.getServerSideProps\n const isPossibleServerAction = getIsPossibleServerAction(req)\n let isSSG = !!components.getStaticProps\n // NOTE: Don't delete headers[RSC] yet, it still needs to be used in renderToHTML later\n const isRSCRequest = getRequestMeta(req, 'isRSCRequest') ?? false\n\n // Not all CDNs respect the Vary header when caching. We must assume that\n // only the URL is used to vary the responses. The Next client computes a\n // hash of the header values and sends it as a search param. Before\n // responding to a request, we must verify that the hash matches the\n // expected value. Neglecting to do this properly can lead to cache\n // poisoning attacks on certain CDNs.\n if (\n !this.minimalMode &&\n this.nextConfig.experimental.validateRSCRequestHeaders &&\n isRSCRequest\n ) {\n const headers = req.headers\n\n const prefetchHeaderValue = headers[NEXT_ROUTER_PREFETCH_HEADER]\n const routerPrefetch =\n prefetchHeaderValue !== undefined\n ? // We only recognize '1' and '2'. Strip all other values here.\n prefetchHeaderValue === '1' || prefetchHeaderValue === '2'\n ? prefetchHeaderValue\n : undefined\n : // For runtime prefetches, we always perform a dynamic request,\n // so we don't expect the header to be stripped by an intermediate layer.\n // This should only happen for static prefetches, so we only handle those here.\n getRequestMeta(req, 'isPrefetchRSCRequest')\n ? '1'\n : undefined\n\n const segmentPrefetchRSCRequest =\n headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] ||\n getRequestMeta(req, 'segmentPrefetchRSCRequest')\n\n const expectedHash = computeCacheBustingSearchParam(\n routerPrefetch,\n segmentPrefetchRSCRequest,\n headers[NEXT_ROUTER_STATE_TREE_HEADER],\n headers[NEXT_URL]\n )\n const actualHash =\n getRequestMeta(req, 'cacheBustingSearchParam') ??\n new URL(req.url || '', 'http://localhost').searchParams.get(\n NEXT_RSC_UNION_QUERY\n )\n\n if (expectedHash !== actualHash) {\n // The hash sent by the client does not match the expected value.\n // Redirect to the URL with the correct cache-busting search param.\n // This prevents cache poisoning attacks on CDNs that don't respect Vary headers.\n // Note: When no headers are present, expectedHash is empty string and client\n // must send `_rsc` param, otherwise actualHash is null and hash check fails.\n const url = new URL(req.url || '', 'http://localhost')\n setCacheBustingSearchParamWithHash(url, expectedHash)\n res.statusCode = 307\n res.setHeader('location', `${url.pathname}${url.search}`)\n res.body('').send()\n return null\n }\n }\n\n // Compute the iSSG cache key. We use the rewroteUrl since\n // pages with fallback: false are allowed to be rewritten to\n // and we need to look up the path by the rewritten path\n let urlPathname = parseUrl(req.url || '').pathname || '/'\n\n let resolvedUrlPathname = getRequestMeta(req, 'rewroteURL') || urlPathname\n\n this.setVaryHeader(req, res, isAppPath, resolvedUrlPathname)\n\n let staticPaths: string[] | undefined\n let hasFallback = false\n\n const prerenderManifest = this.getPrerenderManifest()\n\n if (\n hasFallback ||\n staticPaths?.includes(resolvedUrlPathname) ||\n // this signals revalidation in deploy environments\n // TODO: make this more generic\n req.headers['x-now-route-matches']\n ) {\n isSSG = true\n } else if (!this.renderOpts.dev) {\n isSSG ||= !!prerenderManifest.routes[toRoute(pathname)]\n }\n\n // Toggle whether or not this is a Data request\n const isNextDataRequest =\n !!(\n getRequestMeta(req, 'isNextDataReq') ||\n (req.headers['x-nextjs-data'] &&\n (this.serverOptions as any).webServerConfig)\n ) &&\n (isSSG || hasServerProps)\n\n // when we are handling a middleware prefetch and it doesn't\n // resolve to a static data route we bail early to avoid\n // unexpected SSR invocations\n if (\n !isSSG &&\n req.headers['x-middleware-prefetch'] &&\n !(is404Page || pathname === '/_error')\n ) {\n res.setHeader(MATCHED_PATH_HEADER, pathname)\n res.setHeader('x-middleware-skip', '1')\n res.setHeader(\n 'cache-control',\n 'private, no-cache, no-store, max-age=0, must-revalidate'\n )\n res.body('{}').send()\n return null\n }\n\n // normalize req.url for SSG paths as it is not exposed\n // to getStaticProps and the asPath should not expose /_next/data\n if (\n isSSG &&\n this.minimalMode &&\n req.headers[MATCHED_PATH_HEADER] &&\n req.url.startsWith('/_next/data')\n ) {\n req.url = this.stripNextDataPath(req.url)\n }\n\n const locale = getRequestMeta(req, 'locale')\n\n if (\n !!req.headers['x-nextjs-data'] &&\n (!res.statusCode || res.statusCode === 200)\n ) {\n res.setHeader(\n 'x-nextjs-matched-path',\n `${locale ? `/${locale}` : ''}${pathname}`\n )\n }\n\n let routeModule: RouteModule | undefined\n if (components.routeModule) {\n routeModule = components.routeModule\n }\n\n /**\n * If the route being rendered is an app page, and the ppr feature has been\n * enabled, then the given route _could_ support PPR.\n */\n const couldSupportPPR: boolean =\n this.isAppPPREnabled &&\n typeof routeModule !== 'undefined' &&\n isAppPageRouteModule(routeModule)\n\n // When enabled, this will allow the use of the `?__nextppronly` query to\n // enable debugging of the static shell.\n const hasDebugStaticShellQuery =\n process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING === '1' &&\n typeof query.__nextppronly !== 'undefined' &&\n couldSupportPPR\n\n // This page supports PPR if it is marked as being `PARTIALLY_STATIC` in the\n // prerender manifest and this is an app page.\n const isRoutePPREnabled: boolean =\n couldSupportPPR &&\n ((\n prerenderManifest.routes[pathname] ??\n prerenderManifest.dynamicRoutes[pathname]\n )?.renderingMode === 'PARTIALLY_STATIC' ||\n // Ideally we'd want to check the appConfig to see if this page has PPR\n // enabled or not, but that would require plumbing the appConfig through\n // to the server during development. We assume that the page supports it\n // but only during development.\n (hasDebugStaticShellQuery &&\n (this.renderOpts.dev === true ||\n this.experimentalTestProxy === true)))\n\n // If we're in minimal mode, then try to get the postponed information from\n // the request metadata. If available, use it for resuming the postponed\n // render.\n const minimalPostponed = isRoutePPREnabled\n ? getRequestMeta(req, 'postponed')\n : undefined\n\n // we need to ensure the status code if /404 is visited directly\n if (is404Page && !isNextDataRequest && !isRSCRequest) {\n res.statusCode = 404\n }\n\n // ensure correct status is set when visiting a status page\n // directly e.g. /500\n if (STATIC_STATUS_PAGES.includes(pathname)) {\n res.statusCode = parseInt(pathname.slice(1), 10)\n }\n\n if (\n // Server actions can use non-GET/HEAD methods.\n !isPossibleServerAction &&\n // Resume can use non-GET/HEAD methods.\n !minimalPostponed &&\n !is404Page &&\n !is500Page &&\n pathname !== '/_error' &&\n req.method !== 'HEAD' &&\n req.method !== 'GET' &&\n (typeof components.Component === 'string' || isSSG)\n ) {\n res.statusCode = 405\n res.setHeader('Allow', ['GET', 'HEAD'])\n res.body('Method Not Allowed').send()\n return null\n }\n\n // handle static page\n if (typeof components.Component === 'string') {\n return {\n body: RenderResult.fromStatic(\n components.Component,\n HTML_CONTENT_TYPE_HEADER\n ),\n }\n }\n\n // Ensure that if the `amp` query parameter is falsy that we remove it from\n // the query object. This ensures it won't be found by the `in` operator.\n if ('amp' in query && !query.amp) delete query.amp\n\n if (opts.supportsDynamicResponse === true) {\n const ua = req.headers['user-agent'] || ''\n const isBotRequest = isBot(ua)\n const isSupportedDocument =\n typeof components.Document?.getInitialProps !== 'function' ||\n // The built-in `Document` component also supports dynamic HTML for concurrent mode.\n NEXT_BUILTIN_DOCUMENT in components.Document\n\n // Disable dynamic HTML in cases that we know it won't be generated,\n // so that we can continue generating a cache key when possible.\n // TODO-APP: should the first render for a dynamic app path\n // be static so we can collect revalidate and populate the\n // cache if there are no dynamic data requirements\n opts.supportsDynamicResponse =\n !isSSG && !isBotRequest && !query.amp && isSupportedDocument\n }\n\n // In development, we always want to generate dynamic HTML.\n if (!isNextDataRequest && isAppPath && opts.dev) {\n opts.supportsDynamicResponse = true\n }\n\n if (isSSG && this.minimalMode && req.headers[MATCHED_PATH_HEADER]) {\n // the url value is already correct when the matched-path header is set\n resolvedUrlPathname = urlPathname\n }\n\n urlPathname = removeTrailingSlash(urlPathname)\n resolvedUrlPathname = removeTrailingSlash(resolvedUrlPathname)\n if (this.localeNormalizer) {\n resolvedUrlPathname = this.localeNormalizer.normalize(resolvedUrlPathname)\n }\n\n // remove /_next/data prefix from urlPathname so it matches\n // for direct page visit and /_next/data visit\n if (isNextDataRequest) {\n resolvedUrlPathname = this.stripNextDataPath(resolvedUrlPathname)\n urlPathname = this.stripNextDataPath(urlPathname)\n }\n\n // use existing incrementalCache instance if available\n const incrementalCache: import('./lib/incremental-cache').IncrementalCache =\n await this.getIncrementalCache({\n requestHeaders: Object.assign({}, req.headers),\n })\n\n // TODO: investigate, this is not safe across multiple concurrent requests\n incrementalCache.resetRequestCache()\n\n if (\n routeModule?.isDev &&\n isDynamicRoute(pathname) &&\n (components.getStaticPaths || isAppPath)\n ) {\n const pathsResults = await this.getStaticPaths({\n pathname,\n urlPathname,\n requestHeaders: req.headers,\n page: components.page,\n isAppPath,\n })\n if (isAppPath && this.nextConfig.experimental.cacheComponents) {\n if (pathsResults.prerenderedRoutes?.length) {\n let smallestFallbackRouteParams = null\n for (const route of pathsResults.prerenderedRoutes) {\n const fallbackRouteParams = route.fallbackRouteParams\n if (!fallbackRouteParams || fallbackRouteParams.length === 0) {\n // There are no fallback route params so we don't need to continue\n smallestFallbackRouteParams = null\n break\n }\n if (\n smallestFallbackRouteParams === null ||\n fallbackRouteParams.length < smallestFallbackRouteParams.length\n ) {\n smallestFallbackRouteParams = fallbackRouteParams\n }\n }\n if (smallestFallbackRouteParams) {\n const devValidatingFallbackParams = new Map(\n smallestFallbackRouteParams.map((v) => [v, ''])\n )\n addRequestMeta(\n req,\n 'devValidatingFallbackParams',\n devValidatingFallbackParams\n )\n }\n }\n }\n }\n\n // An OPTIONS request to a page handler is invalid.\n if (\n req.method === 'OPTIONS' &&\n !is404Page &&\n (!routeModule || !isAppRouteRouteModule(routeModule))\n ) {\n await sendResponse(req, res, new Response(null, { status: 400 }))\n return null\n }\n\n const request = isNodeNextRequest(req) ? req.originalRequest : req\n const response = isNodeNextResponse(res) ? res.originalResponse : res\n\n const parsedInitUrl = parseUrl(getRequestMeta(req, 'initURL') || req.url)\n let initPathname = parsedInitUrl.pathname || '/'\n\n for (const normalizer of [\n this.normalizers.segmentPrefetchRSC,\n this.normalizers.prefetchRSC,\n this.normalizers.rsc,\n ]) {\n if (normalizer?.match(initPathname)) {\n initPathname = normalizer.normalize(initPathname)\n }\n }\n\n // On minimal mode, the request url of dynamic route can be a\n // literal dynamic route ('/[slug]') instead of actual URL, so overwriting to initPathname\n // will transform back the resolved url to the dynamic route pathname.\n if (!(this.minimalMode && isErrorPathname)) {\n request.url = `${initPathname}${parsedInitUrl.search || ''}`\n }\n\n // propagate the request context for dev\n setRequestMeta(request, getRequestMeta(req))\n addRequestMeta(request, 'distDir', this.distDir)\n addRequestMeta(request, 'query', query)\n addRequestMeta(request, 'params', opts.params)\n addRequestMeta(request, 'ampValidator', this.renderOpts.ampValidator)\n addRequestMeta(request, 'minimalMode', this.minimalMode)\n\n if (opts.err) {\n addRequestMeta(request, 'invokeError', opts.err)\n }\n\n const handler: (\n req: ServerRequest | IncomingMessage,\n res: ServerResponse | HTTPServerResponse,\n ctx: {\n waitUntil: ReturnType\n }\n ) => Promise = components.ComponentMod.handler\n\n const maybeDevRequest =\n // we need to capture fetch metrics when they are set\n // and can't wait for handler to resolve as the fetch\n // metrics are logged on response close which happens\n // before handler resolves\n process.env.NODE_ENV === 'development'\n ? new Proxy(request, {\n get(target: any, prop) {\n if (typeof target[prop] === 'function') {\n return target[prop].bind(target)\n }\n return target[prop]\n },\n set(target: any, prop, value) {\n if (prop === 'fetchMetrics') {\n ;(req as any).fetchMetrics = value\n }\n target[prop] = value\n return true\n },\n })\n : request\n\n await handler(maybeDevRequest, response, {\n waitUntil: this.getWaitUntil(),\n })\n\n // response is handled fully in handler\n return null\n }\n\n private stripNextDataPath(path: string, stripLocale = true) {\n if (path.includes(this.buildId)) {\n const splitPath = path.substring(\n path.indexOf(this.buildId) + this.buildId.length\n )\n\n path = denormalizePagePath(splitPath.replace(/\\.json$/, ''))\n }\n\n if (this.localeNormalizer && stripLocale) {\n return this.localeNormalizer.normalize(path)\n }\n return path\n }\n\n // map the route to the actual bundle name\n protected getOriginalAppPaths(route: string) {\n if (this.enabledDirectories.app) {\n const originalAppPath = this.appPathRoutes?.[route]\n\n if (!originalAppPath) {\n return null\n }\n\n return originalAppPath\n }\n return null\n }\n\n protected async renderPageComponent(\n ctx: RequestContext,\n bubbleNoFallback: boolean\n ) {\n const { query, pathname } = ctx\n\n const appPaths = this.getOriginalAppPaths(pathname)\n const isAppPath = Array.isArray(appPaths)\n\n let page = pathname\n if (isAppPath) {\n // the last item in the array is the root page, if there are parallel routes\n page = appPaths[appPaths.length - 1]\n }\n\n const result = await this.findPageComponents({\n locale: getRequestMeta(ctx.req, 'locale'),\n page,\n query,\n params: ctx.renderOpts.params || {},\n isAppPath,\n sriEnabled: !!this.nextConfig.experimental.sri?.algorithm,\n appPaths,\n // Ensuring for loading page component routes is done via the matcher.\n shouldEnsure: false,\n })\n if (result) {\n getTracer().setRootSpanAttribute('next.route', pathname)\n try {\n return await this.renderToResponseWithComponents(ctx, result)\n } catch (err) {\n const isNoFallbackError = err instanceof NoFallbackError\n\n if (!isNoFallbackError || (isNoFallbackError && bubbleNoFallback)) {\n throw err\n }\n }\n }\n return false\n }\n\n private async renderToResponse(\n ctx: RequestContext\n ): Promise {\n return getTracer().trace(\n BaseServerSpan.renderToResponse,\n {\n spanName: `rendering page`,\n attributes: {\n 'next.route': ctx.pathname,\n },\n },\n async () => {\n return this.renderToResponseImpl(ctx)\n }\n )\n }\n\n protected abstract getMiddleware(): Promise\n protected abstract getFallbackErrorComponents(\n url?: string\n ): Promise\n protected abstract getRoutesManifest(): NormalizedRouteManifest | undefined\n\n private async renderToResponseImpl(\n ctx: RequestContext\n ): Promise {\n const { req, res, query, pathname } = ctx\n let page = pathname\n const bubbleNoFallback =\n getRequestMeta(ctx.req, 'bubbleNoFallback') ?? false\n\n if (\n !this.minimalMode &&\n this.nextConfig.experimental.validateRSCRequestHeaders\n ) {\n addRequestMeta(\n ctx.req,\n 'cacheBustingSearchParam',\n query[NEXT_RSC_UNION_QUERY]\n )\n }\n delete query[NEXT_RSC_UNION_QUERY]\n\n const options: MatchOptions = {\n i18n: this.i18nProvider?.fromRequest(req, pathname),\n }\n\n try {\n for await (const match of this.matchers.matchAll(pathname, options)) {\n // when a specific invoke-output is meant to be matched\n // ensure a prior dynamic route/page doesn't take priority\n const invokeOutput = getRequestMeta(ctx.req, 'invokeOutput')\n if (\n !this.minimalMode &&\n typeof invokeOutput === 'string' &&\n isDynamicRoute(invokeOutput || '') &&\n invokeOutput !== match.definition.pathname\n ) {\n continue\n }\n\n const result = await this.renderPageComponent(\n {\n ...ctx,\n pathname: match.definition.pathname,\n renderOpts: {\n ...ctx.renderOpts,\n params: match.params,\n },\n },\n bubbleNoFallback\n )\n if (result !== false) return result\n }\n\n // currently edge functions aren't receiving the x-matched-path\n // header so we need to fallback to matching the current page\n // when we weren't able to match via dynamic route to handle\n // the rewrite case\n // @ts-expect-error extended in child class web-server\n if (this.serverOptions.webServerConfig) {\n // @ts-expect-error extended in child class web-server\n ctx.pathname = this.serverOptions.webServerConfig.page\n const result = await this.renderPageComponent(ctx, bubbleNoFallback)\n if (result !== false) return result\n }\n } catch (error) {\n const err = getProperError(error)\n\n if (error instanceof MissingStaticPage) {\n console.error(\n 'Invariant: failed to load static page',\n JSON.stringify(\n {\n page,\n url: ctx.req.url,\n matchedPath: ctx.req.headers[MATCHED_PATH_HEADER],\n initUrl: getRequestMeta(ctx.req, 'initURL'),\n didRewrite: !!getRequestMeta(ctx.req, 'rewroteURL'),\n rewroteUrl: getRequestMeta(ctx.req, 'rewroteURL'),\n },\n null,\n 2\n )\n )\n throw err\n }\n\n if (err instanceof NoFallbackError && bubbleNoFallback) {\n throw err\n }\n if (err instanceof DecodeError || err instanceof NormalizeError) {\n res.statusCode = 400\n return await this.renderErrorToResponse(ctx, err)\n }\n\n res.statusCode = 500\n\n // if pages/500 is present we still need to trigger\n // /_error `getInitialProps` to allow reporting error\n if (await this.hasPage('/500')) {\n addRequestMeta(ctx.req, 'customErrorRender', true)\n await this.renderErrorToResponse(ctx, err)\n removeRequestMeta(ctx.req, 'customErrorRender')\n }\n\n const isWrappedError = err instanceof WrappedBuildError\n\n if (!isWrappedError) {\n if (this.minimalMode || this.renderOpts.dev) {\n if (isError(err)) err.page = page\n throw err\n }\n this.logError(getProperError(err))\n }\n const response = await this.renderErrorToResponse(\n ctx,\n isWrappedError ? (err as WrappedBuildError).innerError : err\n )\n return response\n }\n\n const middleware = await this.getMiddleware()\n if (\n middleware &&\n !!ctx.req.headers['x-nextjs-data'] &&\n (!res.statusCode || res.statusCode === 200 || res.statusCode === 404)\n ) {\n const locale = getRequestMeta(req, 'locale')\n\n res.setHeader(\n 'x-nextjs-matched-path',\n `${locale ? `/${locale}` : ''}${pathname}`\n )\n res.statusCode = 200\n res.setHeader('Content-Type', JSON_CONTENT_TYPE_HEADER)\n res.body('{}')\n res.send()\n return null\n }\n\n res.statusCode = 404\n return this.renderErrorToResponse(ctx, null)\n }\n\n public async renderToHTML(\n req: ServerRequest,\n res: ServerResponse,\n pathname: string,\n query: ParsedUrlQuery = {}\n ): Promise {\n return getTracer().trace(BaseServerSpan.renderToHTML, async () => {\n return this.renderToHTMLImpl(req, res, pathname, query)\n })\n }\n\n private async renderToHTMLImpl(\n req: ServerRequest,\n res: ServerResponse,\n pathname: string,\n query: ParsedUrlQuery = {}\n ): Promise {\n return this.getStaticHTML((ctx) => this.renderToResponse(ctx), {\n req,\n res,\n pathname,\n query,\n })\n }\n\n public async renderError(\n err: Error | null,\n req: ServerRequest,\n res: ServerResponse,\n pathname: string,\n query: NextParsedUrlQuery = {},\n setHeaders = true\n ): Promise {\n return getTracer().trace(BaseServerSpan.renderError, async () => {\n return this.renderErrorImpl(err, req, res, pathname, query, setHeaders)\n })\n }\n\n private async renderErrorImpl(\n err: Error | null,\n req: ServerRequest,\n res: ServerResponse,\n pathname: string,\n query: NextParsedUrlQuery = {},\n setHeaders = true\n ): Promise {\n if (setHeaders) {\n res.setHeader(\n 'Cache-Control',\n 'private, no-cache, no-store, max-age=0, must-revalidate'\n )\n }\n\n return this.pipe(\n async (ctx) => {\n const response = await this.renderErrorToResponse(ctx, err)\n if (this.minimalMode && res.statusCode === 500) {\n throw err\n }\n return response\n },\n { req, res, pathname, query }\n )\n }\n\n private customErrorNo404Warn = execOnce(() => {\n Log.warn(\n `You have added a custom /_error page without a custom /404 page. This prevents the 404 page from being auto statically optimized.\\nSee here for info: https://nextjs.org/docs/messages/custom-error-no-custom-404`\n )\n })\n\n private async renderErrorToResponse(\n ctx: RequestContext,\n err: Error | null\n ): Promise {\n return getTracer().trace(BaseServerSpan.renderErrorToResponse, async () => {\n return this.renderErrorToResponseImpl(ctx, err)\n })\n }\n\n protected async renderErrorToResponseImpl(\n ctx: RequestContext,\n err: Error | null\n ): Promise {\n // Short-circuit favicon.ico in development to avoid compiling 404 page when the app has no favicon.ico.\n // Since favicon.ico is automatically requested by the browser.\n if (this.renderOpts.dev && ctx.pathname === '/favicon.ico') {\n return {\n body: RenderResult.EMPTY,\n }\n }\n const { res, query } = ctx\n\n try {\n let result: null | FindComponentsResult = null\n\n const is404 = res.statusCode === 404\n let using404Page = false\n\n if (is404) {\n if (this.enabledDirectories.app) {\n // Use the not-found entry in app directory\n result = await this.findPageComponents({\n locale: getRequestMeta(ctx.req, 'locale'),\n page: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,\n query,\n params: {},\n isAppPath: true,\n shouldEnsure: true,\n url: ctx.req.url,\n })\n using404Page = result !== null\n }\n\n if (!result && (await this.hasPage('/404'))) {\n result = await this.findPageComponents({\n locale: getRequestMeta(ctx.req, 'locale'),\n page: '/404',\n query,\n params: {},\n isAppPath: false,\n // Ensuring can't be done here because you never \"match\" a 404 route.\n shouldEnsure: true,\n url: ctx.req.url,\n })\n using404Page = result !== null\n }\n }\n let statusPage = `/${res.statusCode}`\n\n if (\n !getRequestMeta(ctx.req, 'customErrorRender') &&\n !result &&\n STATIC_STATUS_PAGES.includes(statusPage)\n ) {\n // skip ensuring /500 in dev mode as it isn't used and the\n // dev overlay is used instead\n if (statusPage !== '/500' || !this.renderOpts.dev) {\n result = await this.findPageComponents({\n locale: getRequestMeta(ctx.req, 'locale'),\n page: statusPage,\n query,\n params: {},\n isAppPath: false,\n // Ensuring can't be done here because you never \"match\" a 500\n // route.\n shouldEnsure: true,\n url: ctx.req.url,\n })\n }\n }\n\n if (!result) {\n result = await this.findPageComponents({\n locale: getRequestMeta(ctx.req, 'locale'),\n page: '/_error',\n query,\n params: {},\n isAppPath: false,\n // Ensuring can't be done here because you never \"match\" an error\n // route.\n shouldEnsure: true,\n url: ctx.req.url,\n })\n statusPage = '/_error'\n }\n\n if (\n process.env.NODE_ENV !== 'production' &&\n !using404Page &&\n (await this.hasPage('/_error')) &&\n !(await this.hasPage('/404'))\n ) {\n this.customErrorNo404Warn()\n }\n\n if (!result) {\n // this can occur when a project directory has been moved/deleted\n // which is handled in the parent process in development\n if (this.renderOpts.dev) {\n return {\n // wait for dev-server to restart before refreshing\n body: RenderResult.fromStatic(\n `\n

missing required error components, refreshing...
\n `,\n HTML_CONTENT_TYPE_HEADER\n ),\n }\n }\n\n throw new WrappedBuildError(\n new Error('missing required error components')\n )\n }\n\n // If the page has a route module, use it for the new match. If it doesn't\n // have a route module, remove the match.\n if (result.components.routeModule) {\n addRequestMeta(ctx.req, 'match', {\n definition: result.components.routeModule.definition,\n params: undefined,\n })\n } else {\n removeRequestMeta(ctx.req, 'match')\n }\n\n try {\n return await this.renderToResponseWithComponents(\n {\n ...ctx,\n pathname: statusPage,\n renderOpts: {\n ...ctx.renderOpts,\n err,\n },\n },\n result\n )\n } catch (maybeFallbackError) {\n if (maybeFallbackError instanceof NoFallbackError) {\n throw new Error('invariant: failed to render error page')\n }\n throw maybeFallbackError\n }\n } catch (error) {\n const renderToHtmlError = getProperError(error)\n const isWrappedError = renderToHtmlError instanceof WrappedBuildError\n if (!isWrappedError) {\n this.logError(renderToHtmlError)\n }\n res.statusCode = 500\n const fallbackComponents = await this.getFallbackErrorComponents(\n ctx.req.url\n )\n\n if (fallbackComponents) {\n // There was an error, so use it's definition from the route module\n // to add the match to the request.\n addRequestMeta(ctx.req, 'match', {\n definition: fallbackComponents.routeModule!.definition,\n params: undefined,\n })\n\n return this.renderToResponseWithComponents(\n {\n ...ctx,\n pathname: '/_error',\n renderOpts: {\n ...ctx.renderOpts,\n // We render `renderToHtmlError` here because `err` is\n // already captured in the stacktrace.\n err: isWrappedError\n ? renderToHtmlError.innerError\n : renderToHtmlError,\n },\n },\n {\n query,\n components: fallbackComponents,\n }\n )\n }\n return {\n body: RenderResult.fromStatic('Internal Server Error', 'text/plain'),\n }\n }\n }\n\n public async renderErrorToHTML(\n err: Error | null,\n req: ServerRequest,\n res: ServerResponse,\n pathname: string,\n query: ParsedUrlQuery = {}\n ): Promise {\n return this.getStaticHTML((ctx) => this.renderErrorToResponse(ctx, err), {\n req,\n res,\n pathname,\n query,\n })\n }\n\n public async render404(\n req: ServerRequest,\n res: ServerResponse,\n parsedUrl?: Pick,\n setHeaders = true\n ): Promise {\n const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(req.url!, true)\n\n // Ensure the locales are provided on the request meta.\n if (this.nextConfig.i18n) {\n if (!getRequestMeta(req, 'locale')) {\n addRequestMeta(req, 'locale', this.nextConfig.i18n.defaultLocale)\n }\n addRequestMeta(req, 'defaultLocale', this.nextConfig.i18n.defaultLocale)\n }\n\n res.statusCode = 404\n return this.renderError(null, req, res, pathname!, query, setHeaders)\n }\n}\n","import type { IncomingHttpHeaders } from 'node:http'\n\nimport { FLIGHT_HEADERS } from '../../client/components/app-router-headers'\n\n/**\n * Removes the flight headers from the request.\n *\n * @param req the request to strip the headers from\n */\nexport function stripFlightHeaders(headers: IncomingHttpHeaders) {\n for (const header of FLIGHT_HEADERS) {\n delete headers[header]\n }\n}\n","// Translate a pages asset path (relative from a common prefix) back into its logical route\n\nimport { isDynamicRoute } from './is-dynamic'\n\n// \"asset path\" being its javascript file, data file, prerendered html,...\nexport default function getRouteFromAssetPath(\n assetPath: string,\n ext: string = ''\n): string {\n assetPath = assetPath.replace(/\\\\/g, '/')\n assetPath =\n ext && assetPath.endsWith(ext) ? assetPath.slice(0, -ext.length) : assetPath\n if (assetPath.startsWith('/index/') && !isDynamicRoute(assetPath)) {\n assetPath = assetPath.slice(6)\n } else if (assetPath === '/index') {\n assetPath = '/'\n }\n return assetPath\n}\n","import { isIPv6 } from './is-ipv6'\n\n/**\n * Formats a hostname so that it is a valid host that can be fetched by wrapping\n * IPv6 hosts with brackets.\n * @param hostname\n * @returns\n */\nexport function formatHostname(hostname: string): string {\n return isIPv6(hostname) ? `[${hostname}]` : hostname\n}\n","/**\n * If set to `incremental`, only those leaf pages that export\n * `experimental_ppr = true` will have partial prerendering enabled. If any\n * page exports this value as `false` or does not export it at all will not\n * have partial prerendering enabled. If set to a boolean, the options for\n * `experimental_ppr` will be ignored.\n */\n\nexport type ExperimentalPPRConfig = boolean | 'incremental'\n\n/**\n * Returns true if partial prerendering is enabled for the application. It does\n * not tell you if a given route has PPR enabled, as that requires analysis of\n * the route's configuration.\n *\n * @see {@link checkIsRoutePPREnabled} - for checking if a specific route has PPR enabled.\n */\nexport function checkIsAppPPREnabled(\n config: ExperimentalPPRConfig | undefined\n): boolean {\n // If the config is undefined, partial prerendering is disabled.\n if (typeof config === 'undefined') return false\n\n // If the config is a boolean, use it directly.\n if (typeof config === 'boolean') return config\n\n // If the config is a string, it must be 'incremental' to enable partial\n // prerendering.\n if (config === 'incremental') return true\n\n return false\n}\n\n/**\n * Returns true if partial prerendering is supported for the current page with\n * the provided app configuration. If the application doesn't have partial\n * prerendering enabled, this function will always return false. If you want to\n * check if the application has partial prerendering enabled\n *\n * @see {@link checkIsAppPPREnabled} for checking if the application has PPR enabled.\n */\nexport function checkIsRoutePPREnabled(\n config: ExperimentalPPRConfig | undefined,\n appConfig: {\n experimental_ppr?: boolean\n }\n): boolean {\n // If the config is undefined, partial prerendering is disabled.\n if (typeof config === 'undefined') return false\n\n // If the config is a boolean, use it directly.\n if (typeof config === 'boolean') return config\n\n // If the config is a string, it must be 'incremental' to enable partial\n // prerendering.\n if (config === 'incremental' && appConfig.experimental_ppr === true) {\n return true\n }\n\n return false\n}\n","import { getRequestMeta, type NextIncomingMessage } from '../request-meta'\n\ntype PatchableResponse = {\n setHeader(key: string, value: string | string[]): PatchableResponse\n}\n\n/**\n * Ensure cookies set in middleware are merged and not overridden by API\n * routes/getServerSideProps.\n *\n * @param req Incoming request\n * @param res Outgoing response\n */\nexport function patchSetHeaderWithCookieSupport(\n req: NextIncomingMessage,\n res: PatchableResponse\n) {\n const setHeader = res.setHeader.bind(res)\n res.setHeader = (\n name: string,\n value: string | string[]\n ): PatchableResponse => {\n // When renders /_error after page is failed, it could attempt to set\n // headers after headers.\n if ('headersSent' in res && res.headersSent) {\n return res\n }\n\n if (name.toLowerCase() === 'set-cookie') {\n const middlewareValue = getRequestMeta(req, 'middlewareCookie')\n\n if (\n !middlewareValue ||\n !Array.isArray(value) ||\n !value.every((item, idx) => item === middlewareValue[idx])\n ) {\n value = [\n // TODO: (wyattjoh) find out why this is called multiple times resulting in duplicate cookies being added\n ...new Set([\n ...(middlewareValue || []),\n ...(typeof value === 'string'\n ? [value]\n : Array.isArray(value)\n ? value\n : []),\n ]),\n ]\n }\n }\n\n return setHeader(name, value)\n }\n}\n","// x-matched-path header can be decoded incorrectly\n// and should only be utf8 characters so this fixes\n// incorrectly encoded values\nexport function fixMojibake(input: string): string {\n // Convert each character's char code to a byte\n const bytes = new Uint8Array(input.length)\n for (let i = 0; i < input.length; i++) {\n bytes[i] = input.charCodeAt(i)\n }\n\n // Decode the bytes as proper UTF-8\n const decoder = new TextDecoder('utf-8')\n return decoder.decode(bytes)\n}\n","import type {\n FlightRouterState,\n Segment,\n} from '../../../server/app-render/types'\nimport { INTERCEPTION_ROUTE_MARKERS } from '../../../shared/lib/router/utils/interception-routes'\nimport type { Params } from '../../../server/request/params'\nimport {\n isGroupSegment,\n DEFAULT_SEGMENT_KEY,\n PAGE_SEGMENT_KEY,\n} from '../../../shared/lib/segment'\nimport { matchSegment } from '../match-segments'\n\nconst removeLeadingSlash = (segment: string): string => {\n return segment[0] === '/' ? segment.slice(1) : segment\n}\n\nconst segmentToPathname = (segment: Segment): string => {\n if (typeof segment === 'string') {\n // 'children' is not a valid path -- it's technically a parallel route that corresponds with the current segment's page\n // if we don't skip it, then the computed pathname might be something like `/children` which doesn't make sense.\n if (segment === 'children') return ''\n\n return segment\n }\n\n return segment[1]\n}\n\nfunction normalizeSegments(segments: string[]): string {\n return (\n segments.reduce((acc, segment) => {\n segment = removeLeadingSlash(segment)\n if (segment === '' || isGroupSegment(segment)) {\n return acc\n }\n\n return `${acc}/${segment}`\n }, '') || '/'\n )\n}\n\nexport function extractPathFromFlightRouterState(\n flightRouterState: FlightRouterState\n): string | undefined {\n const segment = Array.isArray(flightRouterState[0])\n ? flightRouterState[0][1]\n : flightRouterState[0]\n\n if (\n segment === DEFAULT_SEGMENT_KEY ||\n INTERCEPTION_ROUTE_MARKERS.some((m) => segment.startsWith(m))\n )\n return undefined\n\n if (segment.startsWith(PAGE_SEGMENT_KEY)) return ''\n\n const segments = [segmentToPathname(segment)]\n const parallelRoutes = flightRouterState[1] ?? {}\n\n const childrenPath = parallelRoutes.children\n ? extractPathFromFlightRouterState(parallelRoutes.children)\n : undefined\n\n if (childrenPath !== undefined) {\n segments.push(childrenPath)\n } else {\n for (const [key, value] of Object.entries(parallelRoutes)) {\n if (key === 'children') continue\n\n const childPath = extractPathFromFlightRouterState(value)\n\n if (childPath !== undefined) {\n segments.push(childPath)\n }\n }\n }\n\n return normalizeSegments(segments)\n}\n\nfunction computeChangedPathImpl(\n treeA: FlightRouterState,\n treeB: FlightRouterState\n): string | null {\n const [segmentA, parallelRoutesA] = treeA\n const [segmentB, parallelRoutesB] = treeB\n\n const normalizedSegmentA = segmentToPathname(segmentA)\n const normalizedSegmentB = segmentToPathname(segmentB)\n\n if (\n INTERCEPTION_ROUTE_MARKERS.some(\n (m) =>\n normalizedSegmentA.startsWith(m) || normalizedSegmentB.startsWith(m)\n )\n ) {\n return ''\n }\n\n if (!matchSegment(segmentA, segmentB)) {\n // once we find where the tree changed, we compute the rest of the path by traversing the tree\n return extractPathFromFlightRouterState(treeB) ?? ''\n }\n\n for (const parallelRouterKey in parallelRoutesA) {\n if (parallelRoutesB[parallelRouterKey]) {\n const changedPath = computeChangedPathImpl(\n parallelRoutesA[parallelRouterKey],\n parallelRoutesB[parallelRouterKey]\n )\n if (changedPath !== null) {\n return `${segmentToPathname(segmentB)}/${changedPath}`\n }\n }\n }\n\n return null\n}\n\nexport function computeChangedPath(\n treeA: FlightRouterState,\n treeB: FlightRouterState\n): string | null {\n const changedPath = computeChangedPathImpl(treeA, treeB)\n\n if (changedPath == null || changedPath === '/') {\n return changedPath\n }\n\n // lightweight normalization to remove route groups\n return normalizeSegments(changedPath.split('/'))\n}\n\n/**\n * Recursively extracts dynamic parameters from FlightRouterState.\n */\nexport function getSelectedParams(\n currentTree: FlightRouterState,\n params: Params = {}\n): Params {\n const parallelRoutes = currentTree[1]\n\n for (const parallelRoute of Object.values(parallelRoutes)) {\n const segment = parallelRoute[0]\n const isDynamicParameter = Array.isArray(segment)\n const segmentValue = isDynamicParameter ? segment[1] : segment\n if (!segmentValue || segmentValue.startsWith(PAGE_SEGMENT_KEY)) continue\n\n // Ensure catchAll and optional catchall are turned into an array\n const isCatchAll =\n isDynamicParameter && (segment[2] === 'c' || segment[2] === 'oc')\n\n if (isCatchAll) {\n params[segment[0]] = segment[1].split('/')\n } else if (isDynamicParameter) {\n params[segment[0]] = segment[1]\n }\n\n params = getSelectedParams(parallelRoute, params)\n }\n\n return params\n}\n","import type { FlightRouterState } from './types'\nimport { flightRouterStateSchema } from './types'\nimport { assert } from 'next/dist/compiled/superstruct'\n\nexport function parseAndValidateFlightRouterState(\n stateHeader: string | string[]\n): FlightRouterState\nexport function parseAndValidateFlightRouterState(\n stateHeader: undefined\n): undefined\nexport function parseAndValidateFlightRouterState(\n stateHeader: string | string[] | undefined\n): FlightRouterState | undefined\nexport function parseAndValidateFlightRouterState(\n stateHeader: string | string[] | undefined\n): FlightRouterState | undefined {\n if (typeof stateHeader === 'undefined') {\n return undefined\n }\n if (Array.isArray(stateHeader)) {\n throw new Error(\n 'Multiple router state headers were sent. This is not allowed.'\n )\n }\n\n // We limit the size of the router state header to ~40kb. This is to prevent\n // a malicious user from sending a very large header and slowing down the\n // resolving of the router state.\n // This is around 2,000 nested or parallel route segment states:\n // '{\"children\":[\"\",{}]}'.length === 20.\n if (stateHeader.length > 20 * 2000) {\n throw new Error('The router state header was too large.')\n }\n\n try {\n const state = JSON.parse(decodeURIComponent(stateHeader))\n assert(state, flightRouterStateSchema)\n return state\n } catch {\n throw new Error('The router state header was sent but could not be parsed.')\n }\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 = {}\n\n for (const key of parsedUrl.searchParams.keys()) {\n const values = parsedUrl.searchParams.getAll(key)\n query[key] = values.length > 1 ? values : values[0]\n }\n\n const legacyUrl: UrlWithParsedQuery = {\n query,\n hash: parsedUrl.hash,\n search: parsedUrl.search,\n path: parsedUrl.pathname,\n pathname: parsedUrl.pathname,\n href: `${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`,\n host: '',\n hostname: '',\n auth: '',\n protocol: '',\n slashes: null,\n port: '',\n }\n return legacyUrl\n}\n\nexport function stripNextRscUnionQuery(relativeUrl: string): string {\n const urlInstance = new URL(relativeUrl, DUMMY_ORIGIN)\n urlInstance.searchParams.delete(NEXT_RSC_UNION_QUERY)\n\n return urlInstance.pathname + urlInstance.search\n}\n","import {\n getBotType,\n HTML_LIMITED_BOT_UA_RE_STRING,\n} from '../../shared/lib/router/utils/is-bot'\nimport type { BaseNextRequest } from '../base-http'\n\nexport function shouldServeStreamingMetadata(\n userAgent: string,\n htmlLimitedBots: string | undefined\n): boolean {\n const blockingMetadataUARegex = new RegExp(\n htmlLimitedBots || HTML_LIMITED_BOT_UA_RE_STRING,\n 'i'\n )\n // Only block metadata for HTML-limited bots\n if (userAgent && blockingMetadataUARegex.test(userAgent)) {\n return false\n }\n return true\n}\n\n// When the request UA is a html-limited bot, we should do a dynamic render.\n// In this case, postpone state is not sent.\nexport function isHtmlBotRequest(req: {\n headers: BaseNextRequest['headers']\n}): boolean {\n const ua = req.headers['user-agent'] || ''\n const botType = getBotType(ua)\n\n return botType === 'html'\n}\n","import { BLOCKED_PAGES } from '../shared/lib/constants'\n\nexport function isBlockedPage(page: string): boolean {\n return BLOCKED_PAGES.includes(page)\n}\n\nexport function cleanAmpPath(pathname: string): string {\n if (pathname.match(/\\?amp=(y|yes|true|1)/)) {\n pathname = pathname.replace(/\\?amp=(y|yes|true|1)&?/, '?')\n }\n if (pathname.match(/&=(y|yes|true|1)/)) {\n pathname = pathname.replace(/&=(y|yes|true|1)/, '')\n }\n pathname = pathname.replace(/\\?$/, '')\n return pathname\n}\n\ntype AnyFunc = (this: T, ...args: any) => any\nexport function debounce>(\n fn: F,\n ms: number,\n maxWait = Infinity\n) {\n let timeoutId: undefined | NodeJS.Timeout\n\n // The time the debouncing function was first called during this debounce queue.\n let startTime = 0\n // The time the debouncing function was last called.\n let lastCall = 0\n\n // The arguments and this context of the last call to the debouncing function.\n let args: Parameters, context: T\n\n // A helper used to that either invokes the debounced function, or\n // reschedules the timer if a more recent call was made.\n function run() {\n const now = Date.now()\n const diff = lastCall + ms - now\n\n // If the diff is non-positive, then we've waited at least `ms`\n // milliseconds since the last call. Or if we've waited for longer than the\n // max wait time, we must call the debounced function.\n if (diff <= 0 || startTime + maxWait >= now) {\n // It's important to clear the timeout id before invoking the debounced\n // function, in case the function calls the debouncing function again.\n timeoutId = undefined\n fn.apply(context, args)\n } else {\n // Else, a new call was made after the original timer was scheduled. We\n // didn't clear the timeout (doing so is very slow), so now we need to\n // reschedule the timer for the time difference.\n timeoutId = setTimeout(run, diff)\n }\n }\n\n return function (this: T, ...passedArgs: Parameters) {\n // The arguments and this context of the most recent call are saved so the\n // debounced function can be invoked with them later.\n args = passedArgs\n context = this\n\n // Instead of constantly clearing and scheduling a timer, we record the\n // time of the last call. If a second call comes in before the timer fires,\n // then we'll reschedule in the run function. Doing this is considerably\n // faster.\n lastCall = Date.now()\n\n // Only schedule a new timer if we're not currently waiting.\n if (timeoutId === undefined) {\n startTime = lastCall\n timeoutId = setTimeout(run, ms)\n }\n }\n}\n","/**\n * Describes the different fallback modes that a given page can have.\n */\nexport const enum FallbackMode {\n /**\n * A BLOCKING_STATIC_RENDER fallback will block the request until the page is\n * generated. No fallback page will be rendered, and users will have to wait\n * to render the page.\n */\n BLOCKING_STATIC_RENDER = 'BLOCKING_STATIC_RENDER',\n\n /**\n * When set to PRERENDER, a fallback page will be sent to users in place of\n * forcing them to wait for the page to be generated. This allows the user to\n * see a rendered page earlier.\n */\n PRERENDER = 'PRERENDER',\n\n /**\n * When set to NOT_FOUND, pages that are not already prerendered will result\n * in a not found response.\n */\n NOT_FOUND = 'NOT_FOUND',\n}\n\n/**\n * The fallback value returned from the `getStaticPaths` function.\n */\nexport type GetStaticPathsFallback = boolean | 'blocking'\n\n/**\n * Parses the fallback field from the prerender manifest.\n *\n * @param fallbackField The fallback field from the prerender manifest.\n * @returns The fallback mode.\n */\nexport function parseFallbackField(\n fallbackField: string | boolean | null | undefined\n): FallbackMode | undefined {\n if (typeof fallbackField === 'string') {\n return FallbackMode.PRERENDER\n } else if (fallbackField === null) {\n return FallbackMode.BLOCKING_STATIC_RENDER\n } else if (fallbackField === false) {\n return FallbackMode.NOT_FOUND\n } else if (fallbackField === undefined) {\n return undefined\n } else {\n throw new Error(\n `Invalid fallback option: ${fallbackField}. Fallback option must be a string, null, undefined, or false.`\n )\n }\n}\n\nexport function fallbackModeToFallbackField(\n fallback: FallbackMode,\n page: string | undefined\n): string | false | null {\n switch (fallback) {\n case FallbackMode.BLOCKING_STATIC_RENDER:\n return null\n case FallbackMode.NOT_FOUND:\n return false\n case FallbackMode.PRERENDER:\n if (!page) {\n throw new Error(\n `Invariant: expected a page to be provided when fallback mode is \"${fallback}\"`\n )\n }\n\n return page\n default:\n throw new Error(`Invalid fallback mode: ${fallback}`)\n }\n}\n\n/**\n * Parses the fallback from the static paths result.\n *\n * @param result The result from the static paths function.\n * @returns The fallback mode.\n */\nexport function parseStaticPathsResult(\n result: GetStaticPathsFallback\n): FallbackMode {\n if (result === true) {\n return FallbackMode.PRERENDER\n } else if (result === 'blocking') {\n return FallbackMode.BLOCKING_STATIC_RENDER\n } else {\n return FallbackMode.NOT_FOUND\n }\n}\n","import type { IncomingMessage } from 'http'\nimport type { BaseNextRequest } from '../base-http'\nimport type { NextRequest } from '../web/exports'\nimport { ACTION_HEADER } from '../../client/components/app-router-headers'\n\nexport function getServerActionRequestMetadata(\n req: IncomingMessage | BaseNextRequest | NextRequest\n): {\n actionId: string | null\n isURLEncodedAction: boolean\n isMultipartAction: boolean\n isFetchAction: boolean\n isPossibleServerAction: boolean\n} {\n let actionId: string | null\n let contentType: string | null\n\n if (req.headers instanceof Headers) {\n actionId = req.headers.get(ACTION_HEADER) ?? null\n contentType = req.headers.get('content-type')\n } else {\n actionId = (req.headers[ACTION_HEADER] as string) ?? null\n contentType = req.headers['content-type'] ?? null\n }\n\n // We don't actually support URL encoded actions, and the action handler will bail out if it sees one.\n // But we still want it to flow through to the action handler, to prevent changes in behavior when a regular\n // page component tries to handle a POST.\n const isURLEncodedAction = Boolean(\n req.method === 'POST' && contentType === 'application/x-www-form-urlencoded'\n )\n const isMultipartAction = Boolean(\n req.method === 'POST' && contentType?.startsWith('multipart/form-data')\n )\n const isFetchAction = Boolean(\n actionId !== undefined &&\n typeof actionId === 'string' &&\n req.method === 'POST'\n )\n\n const isPossibleServerAction = Boolean(\n isFetchAction || isURLEncodedAction || isMultipartAction\n )\n\n return {\n actionId,\n isURLEncodedAction,\n isMultipartAction,\n isFetchAction,\n isPossibleServerAction,\n }\n}\n\nexport function getIsPossibleServerAction(\n req: IncomingMessage | BaseNextRequest | NextRequest\n): boolean {\n return getServerActionRequestMetadata(req).isPossibleServerAction\n}\n","import type { AppRouteRouteModule } from './app-route/module'\nimport type { AppPageRouteModule } from './app-page/module'\nimport type { PagesRouteModule } from './pages/module'\nimport type { PagesAPIRouteModule } from './pages-api/module'\n\nimport type { RouteModule } from './route-module'\n\nimport { RouteKind } from '../route-kind'\n\nexport function isAppRouteRouteModule(\n routeModule: RouteModule\n): routeModule is AppRouteRouteModule {\n return routeModule.definition.kind === RouteKind.APP_ROUTE\n}\n\nexport function isAppPageRouteModule(\n routeModule: RouteModule\n): routeModule is AppPageRouteModule {\n return routeModule.definition.kind === RouteKind.APP_PAGE\n}\n\nexport function isPagesRouteModule(\n routeModule: RouteModule\n): routeModule is PagesRouteModule {\n return routeModule.definition.kind === RouteKind.PAGES\n}\n\nexport function isPagesAPIRouteModule(\n routeModule: RouteModule\n): routeModule is PagesAPIRouteModule {\n return routeModule.definition.kind === RouteKind.PAGES_API\n}\n","import path from 'path'\nimport {\n PAGES_MANIFEST,\n SERVER_DIRECTORY,\n APP_PATHS_MANIFEST,\n} from '../shared/lib/constants'\nimport { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'\nimport type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'\nimport { PageNotFoundError, MissingStaticPage } from '../shared/lib/utils'\nimport { LRUCache } from '../server/lib/lru-cache'\nimport { loadManifest } from './load-manifest.external'\nimport { promises } from 'fs'\n\nconst isDev = process.env.NODE_ENV === 'development'\nconst pagePathCache = !isDev ? new LRUCache(1000) : null\n\nexport function getMaybePagePath(\n page: string,\n distDir: string,\n locales: readonly string[] | undefined,\n isAppPath: boolean\n): string | null {\n const cacheKey = `${page}:${distDir}:${locales}:${isAppPath}`\n\n let pagePath = pagePathCache?.get(cacheKey)\n\n // If we have a cached path, we can return it directly.\n if (pagePath) return pagePath\n\n const serverBuildPath = path.join(distDir, SERVER_DIRECTORY)\n let appPathsManifest: undefined | PagesManifest\n\n if (isAppPath) {\n appPathsManifest = loadManifest(\n path.join(serverBuildPath, APP_PATHS_MANIFEST),\n !isDev\n ) as PagesManifest\n }\n const pagesManifest = loadManifest(\n path.join(serverBuildPath, PAGES_MANIFEST),\n !isDev\n ) as PagesManifest\n\n try {\n page = denormalizePagePath(normalizePagePath(page))\n } catch (err) {\n console.error(err)\n throw new PageNotFoundError(page)\n }\n\n const checkManifest = (manifest: PagesManifest) => {\n let curPath = manifest[page]\n\n if (!manifest[curPath] && locales) {\n const manifestNoLocales: typeof pagesManifest = {}\n\n for (const key of Object.keys(manifest)) {\n manifestNoLocales[normalizeLocalePath(key, locales).pathname] =\n pagesManifest[key]\n }\n curPath = manifestNoLocales[page]\n }\n return curPath\n }\n\n if (appPathsManifest) {\n pagePath = checkManifest(appPathsManifest)\n }\n\n if (!pagePath) {\n pagePath = checkManifest(pagesManifest)\n }\n\n if (!pagePath) {\n pagePathCache?.set(cacheKey, null)\n return null\n }\n\n pagePath = path.join(serverBuildPath, pagePath)\n\n pagePathCache?.set(cacheKey, pagePath)\n return pagePath\n}\n\nexport function getPagePath(\n page: string,\n distDir: string,\n locales: string[] | undefined,\n isAppPath: boolean\n): string {\n const pagePath = getMaybePagePath(page, distDir, locales, isAppPath)\n\n if (!pagePath) {\n throw new PageNotFoundError(page)\n }\n\n return pagePath\n}\n\nexport async function requirePage(\n page: string,\n distDir: string,\n isAppPath: boolean\n): Promise {\n const pagePath = getPagePath(page, distDir, undefined, isAppPath)\n if (pagePath.endsWith('.html')) {\n return promises.readFile(pagePath, 'utf8').catch((err) => {\n throw new MissingStaticPage(page, err.message)\n })\n }\n\n const mod = process.env.NEXT_MINIMAL\n ? // @ts-ignore\n __non_webpack_require__(pagePath)\n : require(pagePath)\n return mod\n}\n","export function interopDefault(mod: any) {\n return mod.default || mod\n}\n","/**\n * Wait for a given number of milliseconds and then resolve.\n *\n * @param ms the number of milliseconds to wait\n */\nexport async function wait(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n","import type { ActionManifest } from '../../build/webpack/plugins/flight-client-entry-plugin'\nimport type {\n ClientReferenceManifest,\n ClientReferenceManifestForRsc,\n} 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 { workAsyncStorage } from './work-async-storage.external'\n\nlet __next_loaded_action_key: CryptoKey\n\nexport function arrayBufferToString(\n buffer: ArrayBuffer | Uint8Array\n) {\n const bytes = new Uint8Array(buffer)\n const len = bytes.byteLength\n\n // @anonrig: V8 has a limit of 65535 arguments in a function.\n // For len < 65535, this is faster.\n // https://github.com/vercel/next.js/pull/56377#pullrequestreview-1656181623\n if (len < 65535) {\n return String.fromCharCode.apply(null, bytes as unknown as number[])\n }\n\n let binary = ''\n for (let i = 0; i < len; i++) {\n binary += String.fromCharCode(bytes[i])\n }\n return binary\n}\n\nexport function stringToUint8Array(binary: string) {\n const len = binary.length\n const arr = new Uint8Array(len)\n\n for (let i = 0; i < len; i++) {\n arr[i] = binary.charCodeAt(i)\n }\n\n return arr\n}\n\nexport function encrypt(key: CryptoKey, iv: Uint8Array, data: Uint8Array) {\n return crypto.subtle.encrypt(\n {\n name: 'AES-GCM',\n iv,\n },\n key,\n data\n )\n}\n\nexport function decrypt(key: CryptoKey, iv: Uint8Array, data: Uint8Array) {\n return crypto.subtle.decrypt(\n {\n name: 'AES-GCM',\n iv,\n },\n key,\n data\n )\n}\n\n// This is a global singleton that is used to encode/decode the action bound args from\n// the closure. This can't be using a AsyncLocalStorage as it might happen on the module\n// level. Since the client reference manifest won't be mutated, let's use a global singleton\n// to keep it.\nconst SERVER_ACTION_MANIFESTS_SINGLETON = Symbol.for(\n 'next.server.action-manifests'\n)\n\nexport function setReferenceManifestsSingleton({\n page,\n clientReferenceManifest,\n serverActionsManifest,\n serverModuleMap,\n}: {\n page: string\n clientReferenceManifest: DeepReadonly\n serverActionsManifest: DeepReadonly\n serverModuleMap: {\n [id: string]: {\n id: string\n chunks: string[]\n name: string\n }\n }\n}) {\n // @ts-expect-error\n const clientReferenceManifestsPerPage = globalThis[\n SERVER_ACTION_MANIFESTS_SINGLETON\n ]?.clientReferenceManifestsPerPage as\n | undefined\n | DeepReadonly>\n\n // @ts-expect-error\n globalThis[SERVER_ACTION_MANIFESTS_SINGLETON] = {\n clientReferenceManifestsPerPage: {\n ...clientReferenceManifestsPerPage,\n [normalizeAppPath(page)]: clientReferenceManifest,\n },\n serverActionsManifest,\n serverModuleMap,\n }\n}\n\nexport function getServerModuleMap() {\n const serverActionsManifestSingleton = (globalThis as any)[\n SERVER_ACTION_MANIFESTS_SINGLETON\n ] as {\n serverModuleMap: {\n [id: string]: {\n id: string\n chunks: string[]\n name: string\n }\n }\n }\n\n if (!serverActionsManifestSingleton) {\n throw new InvariantError('Missing manifest for Server Actions.')\n }\n\n return serverActionsManifestSingleton.serverModuleMap\n}\n\nexport function getClientReferenceManifestForRsc(): DeepReadonly {\n const serverActionsManifestSingleton = (globalThis as any)[\n SERVER_ACTION_MANIFESTS_SINGLETON\n ] as {\n clientReferenceManifestsPerPage: DeepReadonly<\n Record\n >\n }\n\n if (!serverActionsManifestSingleton) {\n throw new InvariantError('Missing manifest for Server Actions.')\n }\n\n const { clientReferenceManifestsPerPage } = serverActionsManifestSingleton\n const workStore = workAsyncStorage.getStore()\n\n if (!workStore) {\n // If there's no work store defined, we can assume that a client reference\n // manifest is needed during module evaluation, e.g. to create a server\n // action using a higher-order function. This might also use client\n // components which need to be serialized by Flight, and therefore client\n // references need to be resolvable. To make this work, we're returning a\n // merged manifest across all pages. This is fine as long as the module IDs\n // are not page specific, which they are not for Webpack. TODO: Fix this in\n // Turbopack.\n return mergeClientReferenceManifests(clientReferenceManifestsPerPage)\n }\n\n const clientReferenceManifest =\n clientReferenceManifestsPerPage[workStore.route]\n\n if (!clientReferenceManifest) {\n throw new InvariantError(\n `Missing Client Reference Manifest for ${workStore.route}.`\n )\n }\n\n return clientReferenceManifest\n}\n\nexport async function getActionEncryptionKey() {\n if (__next_loaded_action_key) {\n return __next_loaded_action_key\n }\n\n const serverActionsManifestSingleton = (globalThis as any)[\n SERVER_ACTION_MANIFESTS_SINGLETON\n ] as {\n serverActionsManifest: DeepReadonly\n }\n\n if (!serverActionsManifestSingleton) {\n throw new InvariantError('Missing manifest for Server Actions.')\n }\n\n const rawKey =\n process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY ||\n serverActionsManifestSingleton.serverActionsManifest.encryptionKey\n\n if (rawKey === undefined) {\n throw new InvariantError('Missing encryption key for Server Actions')\n }\n\n __next_loaded_action_key = await crypto.subtle.importKey(\n 'raw',\n stringToUint8Array(atob(rawKey)),\n 'AES-GCM',\n true,\n ['encrypt', 'decrypt']\n )\n\n return __next_loaded_action_key\n}\n\nfunction mergeClientReferenceManifests(\n clientReferenceManifestsPerPage: DeepReadonly<\n Record\n >\n): ClientReferenceManifestForRsc {\n const clientReferenceManifests = Object.values(\n clientReferenceManifestsPerPage as Record\n )\n\n const mergedClientReferenceManifest: ClientReferenceManifestForRsc = {\n clientModules: {},\n edgeRscModuleMapping: {},\n rscModuleMapping: {},\n }\n\n for (const clientReferenceManifest of clientReferenceManifests) {\n mergedClientReferenceManifest.clientModules = {\n ...mergedClientReferenceManifest.clientModules,\n ...clientReferenceManifest.clientModules,\n }\n mergedClientReferenceManifest.edgeRscModuleMapping = {\n ...mergedClientReferenceManifest.edgeRscModuleMapping,\n ...clientReferenceManifest.edgeRscModuleMapping,\n }\n mergedClientReferenceManifest.rscModuleMapping = {\n ...mergedClientReferenceManifest.rscModuleMapping,\n ...clientReferenceManifest.rscModuleMapping,\n }\n }\n\n return mergedClientReferenceManifest\n}\n","import type {\n AppType,\n DocumentType,\n NextComponentType,\n} from '../shared/lib/utils'\nimport type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'\nimport type {\n PageConfig,\n GetStaticPaths,\n GetServerSideProps,\n GetStaticProps,\n} from '../types'\nimport type { RouteModule } from './route-modules/route-module'\nimport type { BuildManifest } from './get-page-files'\nimport type { ActionManifest } from '../build/webpack/plugins/flight-client-entry-plugin'\n\nimport {\n BUILD_MANIFEST,\n REACT_LOADABLE_MANIFEST,\n CLIENT_REFERENCE_MANIFEST,\n SERVER_REFERENCE_MANIFEST,\n DYNAMIC_CSS_MANIFEST,\n SUBRESOURCE_INTEGRITY_MANIFEST,\n} from '../shared/lib/constants'\nimport { join } from 'path'\nimport { requirePage } from './require'\nimport { interopDefault } from '../lib/interop-default'\nimport { getTracer } from './lib/trace/tracer'\nimport { LoadComponentsSpan } from './lib/trace/constants'\nimport { evalManifest, loadManifest } from './load-manifest.external'\nimport { wait } from '../lib/wait'\nimport { setReferenceManifestsSingleton } from './app-render/encryption-utils'\nimport { createServerModuleMap } from './app-render/action-utils'\nimport type { DeepReadonly } from '../shared/lib/deep-readonly'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { isStaticMetadataRoute } from '../lib/metadata/is-metadata-route'\n\nexport type ManifestItem = {\n id: number | string\n files: string[]\n}\n\nexport type ReactLoadableManifest = { [moduleId: string]: ManifestItem }\n/**\n * This manifest prevents removing server rendered tags after client\n * navigation. This is only needed under `Pages dir && Production && Webpack`.\n * @see https://github.com/vercel/next.js/pull/72959\n */\nexport type DynamicCssManifest = string[]\n\n/**\n * A manifest entry type for the react-loadable-manifest.json.\n *\n * The whole manifest.json is a type of `Record`\n * where pathname is a string-based key points to the path of the page contains\n * each dynamic imports.\n */\nexport interface LoadableManifest {\n [k: string]: { id: string | number; files: string[] }\n}\n\nexport type LoadComponentsReturnType = {\n Component: NextComponentType\n pageConfig: PageConfig\n buildManifest: DeepReadonly\n subresourceIntegrityManifest?: DeepReadonly>\n reactLoadableManifest: DeepReadonly\n dynamicCssManifest?: DeepReadonly\n clientReferenceManifest?: DeepReadonly\n serverActionsManifest?: any\n Document: DocumentType\n App: AppType\n getStaticProps?: GetStaticProps\n getStaticPaths?: GetStaticPaths\n getServerSideProps?: GetServerSideProps\n ComponentMod: NextModule\n routeModule: RouteModule\n isAppPath?: boolean\n page: string\n multiZoneDraftMode?: boolean\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts.\n */\nexport async function loadManifestWithRetries(\n manifestPath: string,\n attempts = 3\n) {\n while (true) {\n try {\n return loadManifest(manifestPath)\n } catch (err) {\n attempts--\n if (attempts <= 0) throw err\n\n await wait(100)\n }\n }\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts, or return undefined.\n */\nexport async function tryLoadManifestWithRetries(\n manifestPath: string,\n attempts = 3\n) {\n try {\n return await loadManifestWithRetries(manifestPath, attempts)\n } catch (err) {\n return undefined\n }\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts.\n */\nexport async function evalManifestWithRetries(\n manifestPath: string,\n attempts = 3\n) {\n while (true) {\n try {\n return evalManifest(manifestPath)\n } catch (err) {\n attempts--\n if (attempts <= 0) throw err\n\n await wait(100)\n }\n }\n}\n\nasync function tryLoadClientReferenceManifest(\n manifestPath: string,\n entryName: string,\n attempts?: number\n) {\n try {\n const context = await evalManifestWithRetries<{\n __RSC_MANIFEST: { [key: string]: ClientReferenceManifest }\n }>(manifestPath, attempts)\n return context.__RSC_MANIFEST[entryName]\n } catch (err) {\n return undefined\n }\n}\n\nasync function loadComponentsImpl({\n distDir,\n page,\n isAppPath,\n isDev,\n sriEnabled,\n}: {\n distDir: string\n page: string\n isAppPath: boolean\n isDev: boolean\n sriEnabled: boolean\n}): Promise> {\n let DocumentMod = {}\n let AppMod = {}\n if (!isAppPath) {\n ;[DocumentMod, AppMod] = await Promise.all([\n requirePage('/_document', distDir, false),\n requirePage('/_app', distDir, false),\n ])\n }\n\n // In dev mode we retry loading a manifest file to handle a race condition\n // that can occur while app and pages are compiling at the same time, and the\n // build-manifest is still being written to disk while an app path is\n // attempting to load.\n const manifestLoadAttempts = isDev ? 3 : 1\n\n let reactLoadableManifestPath\n if (!process.env.TURBOPACK) {\n reactLoadableManifestPath = join(distDir, REACT_LOADABLE_MANIFEST)\n } else if (isAppPath) {\n reactLoadableManifestPath = join(\n distDir,\n 'server',\n 'app',\n page,\n REACT_LOADABLE_MANIFEST\n )\n } else {\n reactLoadableManifestPath = join(\n distDir,\n 'server',\n 'pages',\n normalizePagePath(page),\n REACT_LOADABLE_MANIFEST\n )\n }\n\n // Make sure to avoid loading the manifest for static metadata routes for better performance.\n const hasClientManifest = !isStaticMetadataRoute(page)\n\n // Load the manifest files first\n //\n // Loading page-specific manifests shouldn't throw an error if the manifest couldn't be found, so\n // that the `requirePage` call below will throw the correct error in that case\n // (a `PageNotFoundError`).\n const [\n buildManifest,\n reactLoadableManifest,\n dynamicCssManifest,\n clientReferenceManifest,\n serverActionsManifest,\n subresourceIntegrityManifest,\n ] = await Promise.all([\n loadManifestWithRetries(\n join(distDir, BUILD_MANIFEST),\n manifestLoadAttempts\n ),\n tryLoadManifestWithRetries(\n reactLoadableManifestPath,\n manifestLoadAttempts\n ),\n // This manifest will only exist in Pages dir && Production && Webpack.\n isAppPath || process.env.TURBOPACK\n ? undefined\n : loadManifestWithRetries(\n join(distDir, `${DYNAMIC_CSS_MANIFEST}.json`),\n manifestLoadAttempts\n ).catch(() => undefined),\n isAppPath && hasClientManifest\n ? tryLoadClientReferenceManifest(\n join(\n distDir,\n 'server',\n 'app',\n page.replace(/%5F/g, '_') + '_' + CLIENT_REFERENCE_MANIFEST + '.js'\n ),\n page.replace(/%5F/g, '_'),\n manifestLoadAttempts\n )\n : undefined,\n isAppPath\n ? loadManifestWithRetries(\n join(distDir, 'server', SERVER_REFERENCE_MANIFEST + '.json'),\n manifestLoadAttempts\n ).catch(() => null)\n : null,\n sriEnabled\n ? loadManifestWithRetries>>(\n join(distDir, 'server', SUBRESOURCE_INTEGRITY_MANIFEST + '.json')\n ).catch(() => undefined)\n : undefined,\n ])\n\n // Before requiring the actual page module, we have to set the reference\n // manifests to our global store so Server Action's encryption util can access\n // to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setReferenceManifestsSingleton({\n page,\n clientReferenceManifest,\n serverActionsManifest,\n serverModuleMap: createServerModuleMap({\n serverActionsManifest,\n }),\n })\n }\n\n const ComponentMod = await requirePage(page, distDir, isAppPath)\n\n const Component = interopDefault(ComponentMod)\n const Document = interopDefault(DocumentMod)\n const App = interopDefault(AppMod)\n\n const { getServerSideProps, getStaticProps, getStaticPaths, routeModule } =\n ComponentMod\n\n return {\n App,\n Document,\n Component,\n buildManifest,\n subresourceIntegrityManifest,\n reactLoadableManifest: reactLoadableManifest || {},\n dynamicCssManifest,\n pageConfig: ComponentMod.config || {},\n ComponentMod,\n getServerSideProps,\n getStaticProps,\n getStaticPaths,\n clientReferenceManifest,\n serverActionsManifest,\n isAppPath,\n page,\n routeModule,\n }\n}\n\nexport const loadComponents = getTracer().wrap(\n LoadComponentsSpan.loadComponents,\n loadComponentsImpl\n)\n","import type { ActionManifest } from '../../build/webpack/plugins/flight-client-entry-plugin'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { workAsyncStorage } from './work-async-storage.external'\n\n// This function creates a Flight-acceptable server module map proxy from our\n// Server Reference Manifest similar to our client module map.\n// This is because our manifest contains a lot of internal Next.js data that\n// are relevant to the runtime, workers, etc. that React doesn't need to know.\nexport function createServerModuleMap({\n serverActionsManifest,\n}: {\n serverActionsManifest: ActionManifest\n}) {\n return new Proxy(\n {},\n {\n get: (_, id: string) => {\n const workers =\n serverActionsManifest[\n process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'\n ]?.[id]?.workers\n\n if (!workers) {\n return undefined\n }\n\n const workStore = workAsyncStorage.getStore()\n\n let workerEntry:\n | { moduleId: string | number; async: boolean }\n | undefined\n\n if (workStore) {\n workerEntry = workers[normalizeWorkerPageName(workStore.page)]\n } else {\n // If there's no work store defined, we can assume that a server\n // module map is needed during module evaluation, e.g. to create a\n // server action using a higher-order function. Therefore it should be\n // safe to return any entry from the manifest that matches the action\n // ID. They all refer to the same module ID, which must also exist in\n // the current page bundle. TODO: This is currently not guaranteed in\n // Turbopack, and needs to be fixed.\n workerEntry = Object.values(workers).at(0)\n }\n\n if (!workerEntry) {\n return undefined\n }\n\n const { moduleId, async } = workerEntry\n\n return { id: moduleId, name: id, chunks: [], async }\n },\n }\n )\n}\n\n/**\n * 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 serverActionsManifest: ActionManifest\n) {\n const workers =\n serverActionsManifest[\n process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'\n ][actionId]?.workers\n const workerName = normalizeWorkerPageName(pageName)\n\n // no workers, nothing to forward to\n if (!workers) return\n\n // if there is a worker for this page, no need to forward it.\n if (workers[workerName]) {\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\n/**\n * The flight entry loader keys actions by bundlePath.\n * bundlePath corresponds 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 name\n */\nfunction denormalizeWorkerPageName(bundlePath: string) {\n return normalizeAppPath(removePathPrefix(bundlePath, 'app'))\n}\n","import type { BaseNextRequest } from '../../../../server/base-http'\nimport type { MiddlewareMatcher } from '../../../../build/analysis/get-page-static-info'\nimport type { Params } from '../../../../server/request/params'\nimport { matchHas } from './prepare-destination'\n\nexport interface MiddlewareRouteMatch {\n (\n pathname: string | null | undefined,\n request: BaseNextRequest,\n query: Params\n ): boolean\n}\n\nexport function getMiddlewareRouteMatcher(\n matchers: MiddlewareMatcher[]\n): MiddlewareRouteMatch {\n return (\n pathname: string | null | undefined,\n req: BaseNextRequest,\n query: Params\n ) => {\n for (const matcher of matchers) {\n const routeMatch = new RegExp(matcher.regexp).exec(pathname!)\n if (!routeMatch) {\n continue\n }\n\n if (matcher.has || matcher.missing) {\n const hasParams = matchHas(req, query, matcher.has, matcher.missing)\n if (!hasParams) {\n continue\n }\n }\n\n return true\n }\n\n return false\n }\n}\n","import type { SchedulerFn } from './scheduler'\n\nimport { DetachedPromise } from './detached-promise'\n\ntype CacheKeyFn = (\n key: K\n) => PromiseLike | C\n\ntype BatcherOptions = {\n cacheKeyFn?: CacheKeyFn\n schedulerFn?: SchedulerFn\n}\n\ntype WorkFn = (\n key: C,\n resolve: (value: V | PromiseLike) => void\n) => Promise\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 {\n private readonly pending = new Map>()\n\n protected constructor(\n private readonly cacheKeyFn?: CacheKeyFn,\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 = (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(\n options?: BatcherOptions\n ): Batcher\n public static create(\n options: BatcherOptions &\n Required, 'cacheKeyFn'>>\n ): Batcher\n public static create(\n options?: BatcherOptions\n ): Batcher {\n return new Batcher(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): Promise {\n const cacheKey = (this.cacheKeyFn ? await this.cacheKeyFn(key) : key) as C\n if (cacheKey === null) {\n return fn(cacheKey, Promise.resolve)\n }\n\n const pending = this.pending.get(cacheKey)\n if (pending) return pending\n\n const { promise, resolve, reject } = new DetachedPromise()\n this.pending.set(cacheKey, promise)\n\n this.schedulerFn(async () => {\n try {\n const result = await fn(cacheKey, resolve)\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 | PromiseLike\nexport type SchedulerFn = (cb: ScheduledFn) => 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) => {\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 => {\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((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 {\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 { 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\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\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 | 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 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 | 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 value: Exclude | 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}\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}) => Promise\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\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\n set(\n key: string,\n data: Exclude | null,\n ctx: SetIncrementalResponseCacheContext\n ): Promise\n}\n\nexport interface IncrementalCache extends IncrementalResponseCache {\n get(\n cacheKey: string,\n ctx: GetIncrementalFetchCacheContext\n ): Promise\n get(\n cacheKey: string,\n ctx: GetIncrementalResponseCacheContext\n ): Promise\n set(\n key: string,\n data: CachedFetchValue | null,\n ctx: SetIncrementalFetchCacheContext\n ): Promise\n set(\n key: string,\n data: Exclude | null,\n ctx: SetIncrementalResponseCacheContext\n ): Promise\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 {\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 {\n if (!response) return null\n\n return {\n isMiss: response.isMiss,\n isStale: response.isStale,\n cacheControl: response.cacheControl,\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 {\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 batcher = 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\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 = 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 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) => 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 {\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.batcher.batch(\n { key, isOnDemandRevalidate },\n (_cacheKey, 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\n // passed to waitUntil\n if (waitUntil) {\n waitUntil(promise)\n }\n return promise\n }\n )\n\n return toResponseCacheEntry(response)\n }\n\n /**\n * Handles the get request for the response cache.\n *\n * @param key - The key to get the response cache entry for.\n * @param responseGenerator - The response generator to use to generate the response cache entry.\n * @param context - The context for the get request.\n * @param resolve - The resolve function to use to resolve the response cache entry.\n * @returns The response cache entry.\n */\n private async handleGet(\n key: string,\n responseGenerator: ResponseGenerator,\n context: {\n incrementalCache: IncrementalResponseCache\n isOnDemandRevalidate: boolean\n isFallback: boolean\n isRoutePPREnabled: boolean\n isPrefetch: boolean\n routeKind: RouteKind\n invocationID: string | undefined\n },\n resolve: (value: IncrementalResponseCacheEntry | null) => void\n ): Promise {\n let previousIncrementalCacheEntry: IncrementalResponseCacheEntry | null =\n null\n let resolved = false\n\n try {\n // Get the previous cache entry if not in minimal mode\n previousIncrementalCacheEntry = !this.minimal_mode\n ? await context.incrementalCache.get(key, {\n kind: routeKindToIncrementalCacheKind(context.routeKind),\n isRoutePPREnabled: context.isRoutePPREnabled,\n isFallback: context.isFallback,\n })\n : null\n\n if (previousIncrementalCacheEntry && !context.isOnDemandRevalidate) {\n resolve(previousIncrementalCacheEntry)\n resolved = true\n\n if (!previousIncrementalCacheEntry.isStale || context.isPrefetch) {\n // The cached value is still valid, so we don't need to update it yet.\n return previousIncrementalCacheEntry\n }\n }\n\n // Revalidate the cache entry\n const incrementalResponseCacheEntry = await this.revalidate(\n key,\n context.incrementalCache,\n context.isRoutePPREnabled,\n context.isFallback,\n responseGenerator,\n previousIncrementalCacheEntry,\n previousIncrementalCacheEntry !== null && !context.isOnDemandRevalidate,\n undefined,\n context.invocationID\n )\n\n // Handle null response\n if (!incrementalResponseCacheEntry) {\n // Remove the cache item if it was set so we don't use it again.\n if (this.minimal_mode) {\n const cacheKey = createCacheKey(key, context.invocationID)\n this.cache.remove(cacheKey)\n }\n return null\n }\n\n // Resolve for on-demand revalidation or if not already resolved\n if (context.isOnDemandRevalidate && !resolved) {\n return incrementalResponseCacheEntry\n }\n\n return incrementalResponseCacheEntry\n } catch (err) {\n // If we've already resolved the cache entry, we can't reject as we\n // already resolved the cache entry so log the error here.\n if (resolved) {\n console.error(err)\n return null\n }\n\n throw err\n }\n }\n\n /**\n * Revalidates the cache entry for the given key.\n *\n * @param key - The key to revalidate the cache entry for.\n * @param incrementalCache - The incremental cache to use to revalidate the cache entry.\n * @param isRoutePPREnabled - Whether the route is PPR enabled.\n * @param isFallback - Whether the route is a fallback.\n * @param responseGenerator - The response generator to use to generate the response cache entry.\n * @param previousIncrementalCacheEntry - The previous cache entry to use to revalidate the cache entry.\n * @param hasResolved - Whether the response has been resolved.\n * @param waitUntil - Optional function to register background work.\n * @param invocationID - The invocation ID for cache key scoping.\n * @returns The revalidated cache entry.\n */\n public async revalidate(\n key: string,\n incrementalCache: IncrementalResponseCache,\n isRoutePPREnabled: boolean,\n isFallback: boolean,\n responseGenerator: ResponseGenerator,\n previousIncrementalCacheEntry: IncrementalResponseCacheEntry | null,\n hasResolved: boolean,\n waitUntil?: (prom: Promise) => void,\n invocationID?: string\n ) {\n return this.revalidateBatcher.batch(key, () => {\n const promise = this.handleRevalidate(\n key,\n incrementalCache,\n isRoutePPREnabled,\n isFallback,\n responseGenerator,\n previousIncrementalCacheEntry,\n hasResolved,\n invocationID\n )\n\n // We need to ensure background revalidates are passed to waitUntil.\n if (waitUntil) waitUntil(promise)\n\n return promise\n })\n }\n\n private async handleRevalidate(\n key: string,\n incrementalCache: IncrementalResponseCache,\n isRoutePPREnabled: boolean,\n isFallback: boolean,\n responseGenerator: ResponseGenerator,\n previousIncrementalCacheEntry: IncrementalResponseCacheEntry | null,\n hasResolved: boolean,\n invocationID: string | undefined\n ) {\n try {\n // Generate the response cache entry using the response generator.\n const responseCacheEntry = await responseGenerator({\n hasResolved,\n previousCacheEntry: previousIncrementalCacheEntry,\n isRevalidating: true,\n })\n if (!responseCacheEntry) {\n return null\n }\n\n // Convert the response cache entry to an incremental response cache entry.\n const incrementalResponseCacheEntry = await fromResponseCacheEntry({\n ...responseCacheEntry,\n isMiss: !previousIncrementalCacheEntry,\n })\n\n // We want to persist the result only if it has a cache control value\n // defined.\n if (incrementalResponseCacheEntry.cacheControl) {\n if (this.minimal_mode) {\n // Set TTL expiration for cache hit validation. Entries are validated\n // by invocationID when available, with TTL as a fallback for providers\n // that don't send x-invocation-id. Memory is managed by LRU eviction.\n const cacheKey = createCacheKey(key, invocationID)\n this.cache.set(cacheKey, {\n entry: incrementalResponseCacheEntry,\n expiresAt: Date.now() + this.ttl,\n })\n } else {\n await incrementalCache.set(key, incrementalResponseCacheEntry.value, {\n cacheControl: incrementalResponseCacheEntry.cacheControl,\n isRoutePPREnabled,\n isFallback,\n })\n }\n }\n\n return incrementalResponseCacheEntry\n } catch (err) {\n // When a path is erroring we automatically re-set the existing cache\n // with new revalidate and expire times to prevent non-stop retrying.\n if (previousIncrementalCacheEntry?.cacheControl) {\n const revalidate = Math.min(\n Math.max(\n previousIncrementalCacheEntry.cacheControl.revalidate || 3,\n 3\n ),\n 30\n )\n const expire =\n previousIncrementalCacheEntry.cacheControl.expire === undefined\n ? undefined\n : Math.max(\n revalidate + 3,\n previousIncrementalCacheEntry.cacheControl.expire\n )\n\n await incrementalCache.set(key, previousIncrementalCacheEntry.value, {\n cacheControl: { revalidate: revalidate, expire: expire },\n isRoutePPREnabled,\n isFallback,\n })\n }\n\n // We haven't resolved yet, so let's throw to indicate an error.\n throw err\n }\n }\n}\n","import path from '../shared/lib/isomorphic/path'\nimport type { CacheFs } from '../shared/lib/utils'\n\n/**\n * A task to be written.\n */\ntype Task = [\n /**\n * The directory to create.\n */\n directory: string,\n\n /**\n * The promise to create the directory.\n */\n mkdir: Promise,\n\n /**\n * The promises to write the files that are dependent on the directory being\n * created.\n */\n writeFile: Promise[],\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\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 {\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 {\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_PREFETCH_SUFFIX,\n RSC_SEGMENT_SUFFIX,\n RSC_SEGMENTS_DIR_SUFFIX,\n RSC_SUFFIX,\n} from '../../../lib/constants'\nimport { isStale, 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 | 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('using memory store for fetch cache')\n }\n\n FileSystemCache.memoryCache = getMemoryCache(ctx.maxMemoryCacheSize)\n } else if (FileSystemCache.debug) {\n console.log('memory store already initialized')\n }\n } else if (FileSystemCache.debug) {\n console.log('not using memory store for fetch cache')\n }\n }\n\n public resetRequestCache(): void {}\n\n public async revalidateTag(\n ...args: Parameters\n ) {\n let [tags] = args\n tags = typeof tags === 'string' ? [tags] : tags\n\n if (FileSystemCache.debug) {\n console.log('revalidateTag', tags)\n }\n\n if (tags.length === 0) {\n return\n }\n\n for (const tag of tags) {\n if (!tagsManifest.has(tag)) {\n tagsManifest.set(tag, Date.now())\n }\n }\n }\n\n public async get(...args: Parameters) {\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('get', key, ctx.tags, kind, !!data)\n } else {\n console.log('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('tags vs storedTags mismatch', tags, storedTags)\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 | 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 = 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 (!ctx.isFallback) {\n rscData = await this.fs.readFile(\n this.getFilePath(\n `${key}${ctx.isRoutePPREnabled ? RSC_PREFETCH_SUFFIX : 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 let cacheTags: undefined | string[]\n const tagsHeader = data.value.headers?.[NEXT_CACHE_TAGS_HEADER]\n\n if (typeof tagsHeader === 'string') {\n cacheTags = tagsHeader.split(',')\n }\n\n if (cacheTags?.length) {\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 (isStale(cacheTags, data?.lastModified || Date.now())) {\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 const wasRevalidated = combinedTags.some((tag) => {\n if (this.revalidatedTags.includes(tag)) {\n return true\n }\n\n return isStale([tag], data?.lastModified || Date.now())\n })\n // When revalidate tag is called we don't return\n // stale data so it's updated right away\n if (wasRevalidated) {\n data = undefined\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('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 }\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) {\n writer.append(\n this.getFilePath(\n `${key}${\n isAppPath\n ? ctx.isRoutePPREnabled\n ? RSC_PREFETCH_SUFFIX\n : RSC_SUFFIX\n : NEXT_DATA_SUFFIX\n }`,\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 }\n\n writer.append(\n htmlPath.replace(/\\.html$/, NEXT_META_SUFFIX),\n JSON.stringify(meta)\n )\n }\n } else if (data.kind === CachedRouteKind.FETCH) {\n const filePath = this.getFilePath(key, IncrementalCacheKind.FETCH)\n writer.append(\n filePath,\n JSON.stringify({\n ...data,\n tags: ctx.fetchCache ? ctx.tags : [],\n })\n )\n }\n\n // Wait for all FS operations to complete.\n await writer.wait()\n }\n\n private getFilePath(pathname: string, kind: IncrementalCacheKind): string {\n switch (kind) {\n case IncrementalCacheKind.FETCH:\n // we store in .next/cache/fetch-cache so it can be persisted\n // across deploys\n return path.join(\n this.serverDistDir,\n '..',\n 'cache',\n 'fetch-cache',\n pathname\n )\n case IncrementalCacheKind.PAGES:\n return path.join(this.serverDistDir, 'pages', pathname)\n case IncrementalCacheKind.IMAGE:\n case IncrementalCacheKind.APP_PAGE:\n case IncrementalCacheKind.APP_ROUTE:\n return path.join(this.serverDistDir, 'app', pathname)\n default:\n throw new Error(`Unexpected file path kind: ${kind}`)\n }\n }\n}\n","import type { CacheFs } from '../../../shared/lib/utils'\nimport type { PrerenderManifest } from '../../../build'\nimport {\n type IncrementalCacheValue,\n type IncrementalCacheEntry,\n type IncrementalCache as IncrementalCacheType,\n IncrementalCacheKind,\n CachedRouteKind,\n type IncrementalResponseCacheEntry,\n type IncrementalFetchCacheEntry,\n type GetIncrementalFetchCacheContext,\n type GetIncrementalResponseCacheContext,\n type CachedFetchValue,\n type SetIncrementalFetchCacheContext,\n type SetIncrementalResponseCacheContext,\n} from '../../response-cache'\nimport type { DeepReadonly } from '../../../shared/lib/deep-readonly'\n\nimport FileSystemCache from './file-system-cache'\nimport { normalizePagePath } from '../../../shared/lib/page-path/normalize-page-path'\n\nimport {\n CACHE_ONE_YEAR,\n PRERENDER_REVALIDATE_HEADER,\n} from '../../../lib/constants'\nimport { toRoute } from '../to-route'\nimport { SharedCacheControls } from './shared-cache-controls.external'\nimport {\n getPrerenderResumeDataCache,\n getRenderResumeDataCache,\n workUnitAsyncStorage,\n} from '../../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport type { Revalidate } from '../cache-control'\nimport { getPreviouslyRevalidatedTags } from '../../server-utils'\nimport { workAsyncStorage } from '../../app-render/work-async-storage.external'\nimport { DetachedPromise } from '../../../lib/detached-promise'\n\nexport interface CacheHandlerContext {\n fs?: CacheFs\n dev?: boolean\n flushToDisk?: boolean\n serverDistDir?: string\n maxMemoryCacheSize?: number\n fetchCacheKeyPrefix?: string\n prerenderManifest?: PrerenderManifest\n revalidatedTags: string[]\n _requestHeaders: IncrementalCache['requestHeaders']\n}\n\nexport interface CacheHandlerValue {\n lastModified?: number\n age?: number\n cacheState?: string\n value: IncrementalCacheValue | null\n}\n\nexport class CacheHandler {\n // eslint-disable-next-line\n constructor(_ctx: CacheHandlerContext) {}\n\n public async get(\n _cacheKey: string,\n _ctx: GetIncrementalFetchCacheContext | GetIncrementalResponseCacheContext\n ): Promise {\n return {} as any\n }\n\n public async set(\n _cacheKey: string,\n _data: IncrementalCacheValue | null,\n _ctx: SetIncrementalFetchCacheContext | SetIncrementalResponseCacheContext\n ): Promise {}\n\n public async revalidateTag(\n ..._args: Parameters\n ): Promise {}\n\n public resetRequestCache(): void {}\n}\n\nexport class IncrementalCache implements IncrementalCacheType {\n readonly dev?: boolean\n readonly disableForTestmode?: boolean\n readonly cacheHandler?: CacheHandler\n readonly hasCustomCacheHandler: boolean\n readonly prerenderManifest: DeepReadonly\n readonly requestHeaders: Record\n readonly allowedRevalidateHeaderKeys?: string[]\n readonly minimalMode?: boolean\n readonly fetchCacheKeyPrefix?: string\n readonly revalidatedTags?: string[]\n readonly isOnDemandRevalidate?: boolean\n\n private static readonly debug: boolean =\n !!process.env.NEXT_PRIVATE_DEBUG_CACHE\n private readonly locks = new Map>()\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\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 } else {\n if (fs && serverDistDir) {\n if (IncrementalCache.debug) {\n console.log('using filesystem cache handler')\n }\n CurCacheHandler = FileSystemCache\n }\n }\n } else if (IncrementalCache.debug) {\n console.log('using custom cache handler', CurCacheHandler.name)\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 = 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> {\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('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()\n\n if (IncrementalCache.debug) {\n console.log('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(tags: string | string[]): Promise {\n return this.cacheHandler?.revalidateTag(tags)\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 {\n // this should be bumped anytime a fix is made to cache entries\n // that should bust the cache\n const MAIN_KEY_PREFIX = 'v3'\n\n const bodyChunks: string[] = []\n\n const encoder = new TextEncoder()\n const decoder = new TextDecoder()\n\n if (init.body) {\n // handle Uint8Array body\n if (init.body instanceof Uint8Array) {\n bodyChunks.push(decoder.decode(init.body))\n ;(init as any)._ogBody = init.body\n } // handle ReadableStream body\n else if (typeof (init.body as any).getReader === 'function') {\n const readableBody = init.body as ReadableStream\n\n const chunks: Uint8Array[] = []\n\n try {\n await readableBody.pipeTo(\n new WritableStream({\n write(chunk) {\n if (typeof chunk === 'string') {\n chunks.push(encoder.encode(chunk))\n bodyChunks.push(chunk)\n } else {\n chunks.push(chunk)\n bodyChunks.push(decoder.decode(chunk, { stream: true }))\n }\n },\n })\n )\n\n // Flush the decoder.\n bodyChunks.push(decoder.decode())\n\n // Create a new buffer with all the chunks.\n const length = chunks.reduce((total, arr) => total + arr.length, 0)\n const arrayBuffer = new Uint8Array(length)\n\n // Push each of the chunks into the new array buffer.\n let offset = 0\n for (const chunk of chunks) {\n arrayBuffer.set(chunk, offset)\n offset += chunk.length\n }\n\n ;(init as any)._ogBody = arrayBuffer\n } catch (err) {\n console.error('Problem reading body', err)\n }\n } // handle FormData or URLSearchParams bodies\n else if (typeof (init.body as any).keys === 'function') {\n const formData = init.body as FormData\n ;(init as any)._ogBody = init.body\n for (const key of new Set([...formData.keys()])) {\n const values = formData.getAll(key)\n bodyChunks.push(\n `${key}=${(\n await Promise.all(\n values.map(async (val) => {\n if (typeof val === 'string') {\n return val\n } else {\n return await val.text()\n }\n })\n )\n ).join(',')}`\n )\n }\n // handle blob body\n } else if (typeof (init.body as any).arrayBuffer === 'function') {\n const blob = init.body as Blob\n const arrayBuffer = await blob.arrayBuffer()\n bodyChunks.push(await blob.text())\n ;(init as any)._ogBody = new Blob([arrayBuffer], { type: blob.type })\n } else if (typeof init.body === 'string') {\n bodyChunks.push(init.body)\n ;(init as any)._ogBody = init.body\n }\n }\n\n const headers =\n typeof (init.headers || {}).keys === 'function'\n ? Object.fromEntries(init.headers as Headers)\n : Object.assign({}, init.headers)\n\n // w3c trace context headers can break request caching and deduplication\n // so we remove them from the cache key\n if ('traceparent' in headers) delete headers['traceparent']\n if ('tracestate' in headers) delete headers['tracestate']\n\n const cacheString = JSON.stringify([\n MAIN_KEY_PREFIX,\n this.fetchCacheKeyPrefix || '',\n url,\n init.method,\n headers,\n init.mode,\n init.redirect,\n init.credentials,\n init.referrer,\n init.referrerPolicy,\n init.integrity,\n init.cache,\n bodyChunks,\n ])\n\n if (process.env.NEXT_RUNTIME === 'edge') {\n function bufferToHex(buffer: ArrayBuffer): string {\n return Array.prototype.map\n .call(new Uint8Array(buffer), (b) => b.toString(16).padStart(2, '0'))\n .join('')\n }\n const buffer = encoder.encode(cacheString)\n return bufferToHex(await crypto.subtle.digest('SHA-256', buffer))\n } else {\n const crypto = require('crypto') as typeof import('crypto')\n return crypto.createHash('sha256').update(cacheString).digest('hex')\n }\n }\n\n async get(\n cacheKey: string,\n ctx: GetIncrementalFetchCacheContext\n ): Promise\n async get(\n cacheKey: string,\n ctx: GetIncrementalResponseCacheContext\n ): Promise\n async get(\n cacheKey: string,\n ctx: GetIncrementalFetchCacheContext | GetIncrementalResponseCacheContext\n ): Promise {\n // Unlike other caches if we have a resume data cache, we use it even if\n // testmode would normally disable it or if requestHeaders say 'no-cache'.\n if (ctx.kind === IncrementalCacheKind.FETCH) {\n const workUnitStore = workUnitAsyncStorage.getStore()\n const resumeDataCache = workUnitStore\n ? getRenderResumeDataCache(workUnitStore)\n : null\n if (resumeDataCache) {\n const memoryCacheData = resumeDataCache.fetch.get(cacheKey)\n if (memoryCacheData?.kind === CachedRouteKind.FETCH) {\n return { isStale: false, value: memoryCacheData }\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?.includes(tag)\n )\n ) {\n return null\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 const isStale = age > revalidate\n const data = cacheData.value.data\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 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\n } else {\n revalidateAfter = this.calculateRevalidate(\n cacheKey,\n cacheData?.lastModified || performance.timeOrigin + performance.now(),\n this.dev ?? false,\n ctx.isFallback\n )\n isStale =\n revalidateAfter !== false &&\n revalidateAfter < performance.timeOrigin + performance.now()\n ? true\n : undefined\n }\n\n if (cacheData) {\n entry = {\n isStale,\n cacheControl,\n revalidateAfter,\n value: cacheData.value,\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 }\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\n async set(\n pathname: string,\n data: Exclude | null,\n ctx: SetIncrementalResponseCacheContext\n ): Promise\n async set(\n pathname: string,\n data: IncrementalCacheValue | null,\n ctx: SetIncrementalFetchCacheContext | SetIncrementalResponseCacheContext\n ): Promise {\n // Even if we otherwise disable caching for testMode or if no fetchCache is\n // configured we still always stash results in the resume data cache if one\n // exists. This is because this is a transient in memory cache that\n // populates caches ahead of a dynamic render in dev mode to allow the RSC\n // debug info to have the right environment associated to it.\n if (data?.kind === CachedRouteKind.FETCH) {\n const workUnitStore = workUnitAsyncStorage.getStore()\n const prerenderResumeDataCache = workUnitStore\n ? getPrerenderResumeDataCache(workUnitStore)\n : null\n if (prerenderResumeDataCache) {\n prerenderResumeDataCache.fetch.set(pathname, data)\n }\n }\n\n if (this.disableForTestmode || (this.dev && !ctx.fetchCache)) return\n\n pathname = this._getPathname(pathname, ctx.fetchCache)\n\n // FetchCache has upper limit of 2MB per-entry currently\n const itemSize = JSON.stringify(data).length\n if (\n ctx.fetchCache &&\n itemSize > 2 * 1024 * 1024 &&\n // We ignore the size limit when custom cache handler is being used, as it\n // might not have this limit\n !this.hasCustomCacheHandler &&\n // We also ignore the size limit when it's an implicit build-time-only\n // caching that the user isn't even aware of.\n !ctx.isImplicitBuildTimeCache\n ) {\n const warningText = `Failed to set Next.js data cache for ${ctx.fetchUrl || pathname}, items over 2MB can not be cached (${itemSize} bytes)`\n\n if (this.dev) {\n throw new Error(warningText)\n }\n console.warn(warningText)\n return\n }\n\n try {\n if (!ctx.fetchCache && ctx.cacheControl) {\n this.cacheControls.set(toRoute(pathname), ctx.cacheControl)\n }\n\n await this.cacheHandler?.set(pathname, data, ctx)\n } catch (error) {\n console.warn('Failed to update prerender cache for', pathname, error)\n }\n }\n}\n","import type { CacheFs } from '../../shared/lib/utils'\n\nimport fs from 'fs'\n\nexport const nodeFs: CacheFs = {\n existsSync: fs.existsSync,\n readFile: fs.promises.readFile,\n readFileSync: fs.readFileSync,\n writeFile: (f, d) => fs.promises.writeFile(f, d),\n mkdir: (dir) => fs.promises.mkdir(dir, { recursive: true }),\n stat: (f) => fs.promises.stat(f),\n}\n","import type {\n ServerResponse,\n OutgoingHttpHeaders,\n OutgoingHttpHeader,\n IncomingMessage,\n IncomingHttpHeaders,\n} from 'http'\nimport type { Socket } from 'net'\nimport type { TLSSocket } from 'tls'\n\nimport Stream from 'stream'\nimport {\n fromNodeOutgoingHttpHeaders,\n toNodeOutgoingHttpHeaders,\n} from '../web/utils'\n\ninterface MockedRequestOptions {\n url: string\n headers: IncomingHttpHeaders\n method: string\n readable?: Stream.Readable\n socket?: Socket | null\n}\n\nexport class MockedRequest extends Stream.Readable implements IncomingMessage {\n public url: string\n public readonly statusCode?: number | undefined\n public readonly statusMessage?: string | undefined\n public readonly headers: IncomingHttpHeaders\n public readonly method: string\n\n // This is hardcoded for now, but can be updated to be configurable if needed.\n public readonly httpVersion = '1.0'\n public readonly httpVersionMajor = 1\n public readonly httpVersionMinor = 0\n\n private bodyReadable?: Stream.Readable\n\n // If we don't actually have a socket, we'll just use a mock one that\n // always returns false for the `encrypted` property and undefined for the\n // `remoteAddress` property.\n public socket: Socket = new Proxy({} as TLSSocket, {\n get: (_target, prop) => {\n if (prop !== 'encrypted' && prop !== 'remoteAddress') {\n throw new Error('Method not implemented')\n }\n\n if (prop === 'remoteAddress') return undefined\n // For this mock request, always ensure we just respond with the encrypted\n // set to false to ensure there's no odd leakages.\n return false\n },\n })\n\n constructor({\n url,\n headers,\n method,\n socket = null,\n readable,\n }: MockedRequestOptions) {\n super()\n\n this.url = url\n this.headers = headers\n this.method = method\n\n if (readable) {\n this.bodyReadable = readable\n this.bodyReadable.on('end', () => this.emit('end'))\n this.bodyReadable.on('close', () => this.emit('close'))\n }\n\n if (socket) {\n this.socket = socket\n }\n }\n\n public get headersDistinct(): NodeJS.Dict {\n const headers: NodeJS.Dict = {}\n for (const [key, value] of Object.entries(this.headers)) {\n if (!value) continue\n\n headers[key] = Array.isArray(value) ? value : [value]\n }\n\n return headers\n }\n\n public _read(size: number): void {\n if (this.bodyReadable) {\n return this.bodyReadable._read(size)\n } else {\n this.emit('end')\n this.emit('close')\n }\n }\n\n /**\n * The `connection` property is just an alias for the `socket` property.\n *\n * @deprecated — since v13.0.0 - Use socket instead.\n */\n public get connection(): Socket {\n return this.socket\n }\n\n // The following methods are not implemented as they are not used in the\n // Next.js codebase.\n\n public get aborted(): boolean {\n throw new Error('Method not implemented')\n }\n\n public get complete(): boolean {\n throw new Error('Method not implemented')\n }\n\n public get trailers(): NodeJS.Dict {\n throw new Error('Method not implemented')\n }\n\n public get trailersDistinct(): NodeJS.Dict {\n throw new Error('Method not implemented')\n }\n\n public get rawTrailers(): string[] {\n throw new Error('Method not implemented')\n }\n\n public get rawHeaders(): string[] {\n throw new Error('Method not implemented.')\n }\n\n public setTimeout(): this {\n throw new Error('Method not implemented.')\n }\n}\n\nexport interface MockedResponseOptions {\n statusCode?: number\n socket?: Socket | null\n headers?: OutgoingHttpHeaders\n resWriter?: (chunk: Uint8Array | Buffer | string) => boolean\n}\n\nexport class MockedResponse extends Stream.Writable implements ServerResponse {\n public statusCode: number\n public statusMessage: string = ''\n public finished = false\n public headersSent = false\n public readonly socket: Socket | null\n\n /**\n * A promise that resolves to `true` when the response has been streamed.\n *\n * @internal - used internally by Next.js\n */\n public readonly hasStreamed: Promise\n\n /**\n * A list of buffers that have been written to the response.\n *\n * @internal - used internally by Next.js\n */\n public readonly buffers: Buffer[] = []\n\n /**\n * The headers object that contains the headers that were initialized on the\n * response and any that were added subsequently.\n *\n * @internal - used internally by Next.js\n */\n public readonly headers: Headers\n\n private resWriter: MockedResponseOptions['resWriter']\n\n public readonly headPromise: Promise\n private headPromiseResolve?: () => void\n\n constructor(res: MockedResponseOptions = {}) {\n super()\n\n this.statusCode = res.statusCode ?? 200\n this.socket = res.socket ?? null\n this.headers = res.headers\n ? fromNodeOutgoingHttpHeaders(res.headers)\n : new Headers()\n\n this.headPromise = new Promise((resolve) => {\n this.headPromiseResolve = resolve\n })\n\n // Attach listeners for the `finish`, `end`, and `error` events to the\n // `MockedResponse` instance.\n this.hasStreamed = new Promise((resolve, reject) => {\n this.on('finish', () => resolve(true))\n this.on('end', () => resolve(true))\n this.on('error', (err) => reject(err))\n }).then((val) => {\n this.headPromiseResolve?.()\n return val\n })\n\n if (res.resWriter) {\n this.resWriter = res.resWriter\n }\n }\n\n public appendHeader(name: string, value: string | string[]): this {\n const values = Array.isArray(value) ? value : [value]\n for (const v of values) {\n this.headers.append(name, v)\n }\n\n return this\n }\n\n /**\n * Returns true if the response has been sent, false otherwise.\n *\n * @internal - used internally by Next.js\n */\n public get isSent() {\n return this.finished || this.headersSent\n }\n\n /**\n * The `connection` property is just an alias for the `socket` property.\n *\n * @deprecated — since v13.0.0 - Use socket instead.\n */\n public get connection(): Socket | null {\n return this.socket\n }\n\n public write(chunk: Uint8Array | Buffer | string) {\n if (this.resWriter) {\n return this.resWriter(chunk)\n }\n this.buffers.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))\n\n return true\n }\n\n public end() {\n this.finished = true\n return super.end(...arguments)\n }\n\n /**\n * This method is a no-op because the `MockedResponse` instance is not\n * actually connected to a socket. This method is not specified on the\n * interface type for `ServerResponse` but is called by Node.js.\n *\n * @see https://github.com/nodejs/node/pull/7949\n */\n public _implicitHeader() {}\n\n public _write(\n chunk: Buffer | string,\n _encoding: string,\n callback: () => void\n ) {\n this.write(chunk)\n\n // According to Node.js documentation, the callback MUST be invoked to\n // signal that the write completed successfully. If this callback is not\n // invoked, the 'finish' event will not be emitted.\n //\n // https://nodejs.org/docs/latest-v16.x/api/stream.html#writable_writechunk-encoding-callback\n callback()\n }\n\n public writeHead(\n statusCode: number,\n statusMessage?: string | undefined,\n headers?: OutgoingHttpHeaders | OutgoingHttpHeader[] | undefined\n ): this\n public writeHead(\n statusCode: number,\n headers?: OutgoingHttpHeaders | OutgoingHttpHeader[] | undefined\n ): this\n public writeHead(\n statusCode: number,\n statusMessage?:\n | string\n | OutgoingHttpHeaders\n | OutgoingHttpHeader[]\n | undefined,\n headers?: OutgoingHttpHeaders | OutgoingHttpHeader[] | undefined\n ): this {\n if (!headers && typeof statusMessage !== 'string') {\n headers = statusMessage\n } else if (typeof statusMessage === 'string' && statusMessage.length > 0) {\n this.statusMessage = statusMessage\n }\n\n if (headers) {\n // When headers have been set with response.setHeader(), they will be\n // merged with any headers passed to response.writeHead(), with the\n // headers passed to response.writeHead() given precedence.\n //\n // https://nodejs.org/api/http.html#responsewriteheadstatuscode-statusmessage-headers\n //\n // For this reason, we need to only call `set` to ensure that this will\n // overwrite any existing headers.\n if (Array.isArray(headers)) {\n // headers may be an Array where the keys and values are in the same list.\n // It is not a list of tuples. So, the even-numbered offsets are key\n // values, and the odd-numbered offsets are the associated values. The\n // array is in the same format as request.rawHeaders.\n for (let i = 0; i < headers.length; i += 2) {\n // The header key is always a string according to the spec.\n this.setHeader(headers[i] as string, headers[i + 1])\n }\n } else {\n for (const [key, value] of Object.entries(headers)) {\n // Skip undefined values\n if (typeof value === 'undefined') continue\n\n this.setHeader(key, value)\n }\n }\n }\n\n this.statusCode = statusCode\n this.headersSent = true\n this.headPromiseResolve?.()\n\n return this\n }\n\n public hasHeader(name: string): boolean {\n return this.headers.has(name)\n }\n\n public getHeader(name: string): string | undefined {\n return this.headers.get(name) ?? undefined\n }\n\n public getHeaders(): OutgoingHttpHeaders {\n return toNodeOutgoingHttpHeaders(this.headers)\n }\n\n public getHeaderNames(): string[] {\n return Array.from(this.headers.keys())\n }\n\n public setHeader(name: string, value: OutgoingHttpHeader) {\n if (Array.isArray(value)) {\n // Because `set` here should override any existing values, we need to\n // delete the existing values before setting the new ones via `append`.\n this.headers.delete(name)\n\n for (const v of value) {\n this.headers.append(name, v)\n }\n } else if (typeof value === 'number') {\n this.headers.set(name, value.toString())\n } else {\n this.headers.set(name, value)\n }\n\n return this\n }\n\n public removeHeader(name: string): void {\n this.headers.delete(name)\n }\n\n public flushHeaders(): void {\n // This is a no-op because we don't actually have a socket to flush the\n // headers to.\n }\n\n // The following methods are not implemented as they are not used in the\n // Next.js codebase.\n\n public get strictContentLength(): boolean {\n throw new Error('Method not implemented.')\n }\n\n public writeEarlyHints() {\n throw new Error('Method not implemented.')\n }\n\n public get req(): IncomingMessage {\n throw new Error('Method not implemented.')\n }\n\n public assignSocket() {\n throw new Error('Method not implemented.')\n }\n\n public detachSocket(): void {\n throw new Error('Method not implemented.')\n }\n\n public writeContinue(): void {\n throw new Error('Method not implemented.')\n }\n\n public writeProcessing(): void {\n throw new Error('Method not implemented.')\n }\n\n public get upgrading(): boolean {\n throw new Error('Method not implemented.')\n }\n\n public get chunkedEncoding(): boolean {\n throw new Error('Method not implemented.')\n }\n\n public get shouldKeepAlive(): boolean {\n throw new Error('Method not implemented.')\n }\n\n public get useChunkedEncodingByDefault(): boolean {\n throw new Error('Method not implemented.')\n }\n\n public get sendDate(): boolean {\n throw new Error('Method not implemented.')\n }\n\n public setTimeout(): this {\n throw new Error('Method not implemented.')\n }\n\n public addTrailers(): void {\n throw new Error('Method not implemented.')\n }\n\n public setHeaders(): this {\n throw new Error('Method not implemented.')\n }\n}\n\ninterface RequestResponseMockerOptions {\n url: string\n headers?: IncomingHttpHeaders\n method?: string\n bodyReadable?: Stream.Readable\n resWriter?: (chunk: Uint8Array | Buffer | string) => boolean\n socket?: Socket | null\n}\n\nexport function createRequestResponseMocks({\n url,\n headers = {},\n method = 'GET',\n bodyReadable,\n resWriter,\n socket = null,\n}: RequestResponseMockerOptions) {\n return {\n req: new MockedRequest({\n url,\n headers,\n method,\n socket,\n readable: bodyReadable,\n }),\n res: new MockedResponse({ socket, resWriter }),\n }\n}\n","import path from 'path'\nimport { pathToFileURL } from 'url'\n\n/**\n * The path for a dynamic route must be URLs with a valid scheme.\n *\n * When an absolute Windows path is passed to it, it interprets the beginning of the path as a protocol (`C:`).\n * Therefore, it is important to always construct a complete path.\n * @param dir File directory\n * @param filePath Absolute or relative path\n */\nexport const formatDynamicImportPath = (dir: string, filePath: string) => {\n const absoluteFilePath = path.isAbsolute(filePath)\n ? filePath\n : path.join(dir, filePath)\n const formattedFilePath = pathToFileURL(absoluteFilePath).toString()\n\n return formattedFilePath\n}\n","export class AsyncCallbackSet {\n private callbacks: (() => Promise)[] = []\n\n public add(callback: () => Promise) {\n this.callbacks.push(callback)\n }\n\n public async runAll(): Promise {\n if (!this.callbacks.length) {\n return\n }\n const callbacks = this.callbacks\n this.callbacks = []\n await Promise.allSettled(\n callbacks.map(\n // NOTE: wrapped in an async function to protect against synchronous exceptions\n async (f) => f()\n )\n )\n }\n}\n","const REACT_POSTPONE_TYPE: symbol = Symbol.for('react.postpone')\n\nexport function isPostpone(error: any): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n error.$$typeof === REACT_POSTPONE_TYPE\n )\n}\n","import type { ModuleLoader } from './module-loader'\n\n/**\n * Loads a module using `await require(id)`.\n */\nexport class NodeModuleLoader implements ModuleLoader {\n public async load(id: string): Promise {\n if (process.env.NEXT_RUNTIME !== 'edge') {\n // Need to `await` to cover the case that route is marked ESM modules by ESM escalation.\n return await (process.env.NEXT_MINIMAL\n ? // @ts-ignore\n __non_webpack_require__(id)\n : require(id))\n }\n\n throw new Error('NodeModuleLoader is not supported in edge runtime.')\n }\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { NextConfigComplete } from '../../config-shared'\nimport type { UrlWithParsedQuery } from 'node:url'\n\nexport type RevalidateFn = (config: {\n urlPath: string\n revalidateHeaders: { [key: string]: string | string[] }\n opts: { unstable_onlyGenerated?: boolean }\n}) => Promise\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\n // current loaded public runtime config\n publicRuntimeConfig?: NextConfigComplete['publicRuntimeConfig']\n // exposing nextConfig for dev mode specifically\n nextConfig?: NextConfigComplete\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 | null) => void\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","import './node-environment'\nimport './require-hook'\nimport './node-polyfill-crypto'\n\nimport type { CacheFs } from '../shared/lib/utils'\nimport {\n DecodeError,\n PageNotFoundError,\n MiddlewareNotFoundError,\n} from '../shared/lib/utils'\nimport type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin'\nimport type RenderResult from './render-result'\nimport type { FetchEventResult } from './web/types'\nimport type { PrerenderManifest, RoutesManifest } from '../build'\nimport type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'\nimport type { NextParsedUrlQuery, NextUrlWithParsedQuery } from './request-meta'\nimport type { Params } from './request/params'\nimport type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher'\nimport type { RouteMatch } from './route-matches/route-match'\nimport type { IncomingMessage, ServerResponse } from 'http'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { ParsedUrl } from '../shared/lib/router/utils/parse-url'\nimport type { CacheControl } from './lib/cache-control'\nimport type { WaitUntil } from './after/builtin-request-context'\n\nimport fs from 'fs'\nimport { join, relative } from 'path'\nimport { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'\nimport { addRequestMeta, getRequestMeta } from './request-meta'\nimport {\n PAGES_MANIFEST,\n BUILD_ID_FILE,\n MIDDLEWARE_MANIFEST,\n PRERENDER_MANIFEST,\n ROUTES_MANIFEST,\n CLIENT_PUBLIC_FILES_PATH,\n APP_PATHS_MANIFEST,\n SERVER_DIRECTORY,\n NEXT_FONT_MANIFEST,\n UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,\n FUNCTIONS_CONFIG_MANIFEST,\n} from '../shared/lib/constants'\nimport { findDir } from '../lib/find-pages-dir'\nimport { NodeNextRequest, NodeNextResponse } from './base-http/node'\nimport { sendRenderResult } from './send-payload'\nimport { parseUrl } from '../shared/lib/router/utils/parse-url'\nimport * as Log from '../build/output/log'\n\nimport type {\n Options,\n FindComponentsResult,\n MiddlewareRoutingItem,\n RequestContext,\n NormalizedRouteManifest,\n LoadedRenderOpts,\n RouteHandler,\n NextEnabledDirectories,\n BaseRequestHandler,\n} from './base-server'\nimport BaseServer from './base-server'\nimport { getMaybePagePath, getPagePath } from './require'\nimport { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { loadComponents } from './load-components'\nimport type { LoadComponentsReturnType } from './load-components'\nimport isError, { getProperError } from '../lib/is-error'\nimport { splitCookiesString, toNodeOutgoingHttpHeaders } from './web/utils'\nimport { getMiddlewareRouteMatcher } from '../shared/lib/router/utils/middleware-route-matcher'\nimport { loadEnvConfig } from '@next/env'\nimport { urlQueryToSearchParams } from '../shared/lib/router/utils/querystring'\nimport { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'\nimport { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'\nimport { getCloneableBody } from './body-streams'\nimport { checkIsOnDemandRevalidate } from './api-utils'\nimport ResponseCache, {\n CachedRouteKind,\n type IncrementalResponseCacheEntry,\n} from './response-cache'\nimport { IncrementalCache } from './lib/incremental-cache'\nimport { normalizeAppPath } from '../shared/lib/router/utils/app-paths'\n\nimport { setHttpClientAndAgentOptions } from './setup-http-agent-env'\n\nimport { isPagesAPIRouteMatch } from './route-matches/pages-api-route-match'\nimport type { PagesAPIRouteMatch } from './route-matches/pages-api-route-match'\nimport type { MatchOptions } from './route-matcher-managers/route-matcher-manager'\nimport { BubbledError, getTracer } from './lib/trace/tracer'\nimport { NextNodeServerSpan } from './lib/trace/constants'\nimport { nodeFs } from './lib/node-fs-methods'\nimport { getRouteRegex } from '../shared/lib/router/utils/route-regex'\nimport { pipeToNodeResponse } from './pipe-readable'\nimport { createRequestResponseMocks } from './lib/mock-request'\nimport { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers'\nimport { signalFromNodeResponse } from './web/spec-extension/adapters/next-request'\nimport { loadManifest } from './load-manifest.external'\nimport { lazyRenderAppPage } from './route-modules/app-page/module.render'\nimport { lazyRenderPagesPage } from './route-modules/pages/module.render'\nimport { interopDefault } from '../lib/interop-default'\nimport { formatDynamicImportPath } from '../lib/format-dynamic-import-path'\nimport type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'\nimport { isInterceptionRouteRewrite } from '../lib/generate-interception-routes-rewrites'\nimport type { ServerOnInstrumentationRequestError } from './app-render/types'\nimport { RouteKind } from './route-kind'\nimport { InvariantError } from '../shared/lib/invariant-error'\nimport { AwaiterOnce } from './after/awaiter'\nimport { AsyncCallbackSet } from './lib/async-callback-set'\nimport { initializeCacheHandlers, setCacheHandler } from './use-cache/handlers'\nimport type { UnwrapPromise } from '../lib/coalesced-function'\nimport { populateStaticEnv } from '../lib/static-env'\nimport { isPostpone } from './lib/router-utils/is-postpone'\nimport { NodeModuleLoader } from './lib/module-loader/node-module-loader'\nimport { NoFallbackError } from '../shared/lib/no-fallback-error.external'\nimport {\n ensureInstrumentationRegistered,\n getInstrumentationModule,\n} from './lib/router-utils/instrumentation-globals.external'\nimport {\n RouterServerContextSymbol,\n routerServerGlobal,\n} from './lib/router-utils/router-server-context'\n\nexport * from './base-server'\n\n// For module that can be both CJS or ESM\nconst dynamicImportEsmDefault = process.env.NEXT_MINIMAL\n ? (id: string) =>\n import(/* webpackIgnore: true */ id).then((mod) => mod.default || mod)\n : (id: string) => import(id).then((mod) => mod.default || mod)\n\nexport type NodeRequestHandler = BaseRequestHandler<\n IncomingMessage | NodeNextRequest,\n ServerResponse | NodeNextResponse\n>\n\ntype NodeRouteHandler = RouteHandler\n\nconst MiddlewareMatcherCache = new WeakMap<\n MiddlewareManifest['middleware'][string],\n MiddlewareRouteMatch\n>()\n\nfunction getMiddlewareMatcher(\n info: MiddlewareManifest['middleware'][string]\n): MiddlewareRouteMatch {\n const stored = MiddlewareMatcherCache.get(info)\n if (stored) {\n return stored\n }\n\n if (!Array.isArray(info.matchers)) {\n throw new Error(\n `Invariant: invalid matchers for middleware ${JSON.stringify(info)}`\n )\n }\n\n const matcher = getMiddlewareRouteMatcher(info.matchers)\n MiddlewareMatcherCache.set(info, matcher)\n return matcher\n}\n\nfunction installProcessErrorHandlers(\n shouldRemoveUncaughtErrorAndRejectionListeners: boolean\n) {\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 \n // }\n //\n // In this example, `fetchData` is called immediately to start the request\n // as soon as possible, but if `shouldShow` is false, then it will be\n // discarded without unwrapping its result. If it errors, it will trigger\n // an \"unhandledRejection\" event.\n //\n // Ideally, we would suppress these rejections completely without warning,\n // because we don't consider them real errors. (TODO: Currently we do warn.)\n //\n // But regardless of whether we do or don't warn, we definitely shouldn't\n // crash the entire process.\n //\n // Even a \"legit\" unhandled error unrelated to prefetching shouldn't\n // prevent the rest of the page from rendering.\n //\n // So, we're going to intentionally override the default error handling\n // behavior of the outer JS runtime to be more forgiving\n\n // Remove any existing \"unhandledRejection\" and \"uncaughtException\" handlers.\n // This is gated behind an experimental flag until we've considered the impact\n // in various deployment environments. It's possible this may always need to\n // be configurable.\n if (shouldRemoveUncaughtErrorAndRejectionListeners) {\n process.removeAllListeners('uncaughtException')\n process.removeAllListeners('unhandledRejection')\n }\n\n // Install a new handler to prevent the process from crashing.\n process.on('unhandledRejection', (reason: unknown) => {\n if (isPostpone(reason)) {\n // React postpones that are unhandled might end up logged here but they're\n // not really errors. They're just part of rendering.\n return\n }\n // Immediately log the error.\n // TODO: Ideally, if we knew that this error was triggered by application\n // code, we would suppress it entirely without logging. We can't reliably\n // detect all of these, but when cacheComponents is enabled, we could suppress\n // at least some of them by waiting to log the error until after all in-\n // progress renders have completed. Then, only log errors for which there\n // was not a corresponding \"rejectionHandled\" event.\n console.error(reason)\n })\n\n process.on('rejectionHandled', () => {\n // TODO: See note in the unhandledRejection handler above. In the future,\n // we may use the \"rejectionHandled\" event to de-queue an error from\n // being logged.\n })\n\n // Unhandled exceptions are errors triggered by non-async functions, so this\n // is unrelated to the late-awaiting pattern. However, for similar reasons,\n // we still shouldn't crash the process. Just log it.\n process.on('uncaughtException', (reason: unknown) => {\n if (isPostpone(reason)) {\n return\n }\n console.error(reason)\n })\n}\n\nexport default class NextNodeServer extends BaseServer<\n Options,\n NodeNextRequest,\n NodeNextResponse\n> {\n protected middlewareManifestPath: string\n private _serverDistDir: string | undefined\n private imageResponseCache?: ResponseCache\n protected renderWorkersPromises?: Promise\n protected dynamicRoutes?: {\n match: import('../shared/lib/router/utils/route-matcher').RouteMatchFn\n page: string\n re: RegExp\n }[]\n private routerServerHandler?: (\n req: IncomingMessage,\n res: ServerResponse\n ) => void\n\n protected cleanupListeners = new AsyncCallbackSet()\n protected internalWaitUntil: WaitUntil | undefined\n private isDev: boolean\n private sriEnabled: boolean\n\n constructor(options: Options) {\n // Initialize super class\n super(options)\n\n const isDev = options.dev ?? false\n this.isDev = isDev\n this.sriEnabled = Boolean(options.conf.experimental?.sri?.algorithm)\n\n /**\n * This sets environment variable to be used at the time of SSR by head.tsx.\n * Using this from process.env allows targeting SSR by calling\n * `process.env.__NEXT_OPTIMIZE_CSS`.\n */\n if (this.renderOpts.optimizeCss) {\n process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)\n }\n if (this.renderOpts.nextScriptWorkers) {\n process.env.__NEXT_SCRIPT_WORKERS = JSON.stringify(true)\n }\n process.env.NEXT_DEPLOYMENT_ID = this.nextConfig.experimental.useSkewCookie\n ? ''\n : this.nextConfig.deploymentId || ''\n\n if (!this.minimalMode) {\n this.imageResponseCache = new ResponseCache(this.minimalMode)\n }\n\n const { appDocumentPreloading } = this.nextConfig.experimental\n const isDefaultEnabled = typeof appDocumentPreloading === 'undefined'\n\n if (\n !options.dev &&\n (appDocumentPreloading === true ||\n !(this.minimalMode && isDefaultEnabled))\n ) {\n // pre-warm _document and _app as these will be\n // needed for most requests\n loadComponents({\n distDir: this.distDir,\n page: '/_document',\n isAppPath: false,\n isDev: this.isDev,\n sriEnabled: this.sriEnabled,\n }).catch(() => {})\n loadComponents({\n distDir: this.distDir,\n page: '/_app',\n isAppPath: false,\n isDev: this.isDev,\n sriEnabled: this.sriEnabled,\n }).catch(() => {})\n }\n\n if (\n !options.dev &&\n !this.minimalMode &&\n this.nextConfig.experimental.preloadEntriesOnStart\n ) {\n this.unstable_preloadEntries()\n }\n\n if (!options.dev) {\n const { dynamicRoutes = [] } = this.getRoutesManifest() ?? {}\n this.dynamicRoutes = dynamicRoutes.map((r) => {\n // TODO: can we just re-use the regex from the manifest?\n const regex = getRouteRegex(r.page)\n const match = getRouteMatcher(regex)\n\n return {\n match,\n page: r.page,\n re: regex.re,\n }\n })\n }\n\n // ensure options are set when loadConfig isn't called\n setHttpClientAndAgentOptions(this.nextConfig)\n\n // Intercept fetch and other testmode apis.\n if (this.serverOptions.experimentalTestProxy) {\n process.env.NEXT_PRIVATE_TEST_PROXY = 'true'\n const { interceptTestApis } =\n // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm\n require('next/dist/experimental/testmode/server') as typeof import('../experimental/testmode/server')\n interceptTestApis()\n }\n\n this.middlewareManifestPath = join(this.serverDistDir, MIDDLEWARE_MANIFEST)\n\n // This is just optimization to fire prepare as soon as possible. It will be\n // properly awaited later. We add the catch here to ensure that it does not\n // cause a unhandled promise rejection. The promise rejection will be\n // handled later on via the `await` when the request handler is called.\n if (!options.dev) {\n this.prepare().catch((err) => {\n console.error('Failed to prepare server', err)\n })\n }\n\n // when using compile mode static env isn't inlined so we\n // need to populate in normal runtime env\n if (this.renderOpts.isExperimentalCompile) {\n populateStaticEnv(this.nextConfig)\n }\n\n const shouldRemoveUncaughtErrorAndRejectionListeners = Boolean(\n options.conf.experimental?.removeUncaughtErrorAndRejectionListeners\n )\n installProcessErrorHandlers(shouldRemoveUncaughtErrorAndRejectionListeners)\n }\n\n public async unstable_preloadEntries(): Promise {\n // Ensure prepare process will be finished before preloading entries.\n await this.prepare()\n\n const appPathsManifest = this.getAppPathsManifest()\n const pagesManifest = this.getPagesManifest()\n\n await this.loadCustomCacheHandlers()\n\n for (const page of Object.keys(pagesManifest || {})) {\n await loadComponents({\n distDir: this.distDir,\n page,\n isAppPath: false,\n isDev: this.isDev,\n sriEnabled: this.sriEnabled,\n }).catch(() => {})\n }\n\n for (const page of Object.keys(appPathsManifest || {})) {\n await loadComponents({\n distDir: this.distDir,\n page,\n isAppPath: true,\n isDev: this.isDev,\n sriEnabled: this.sriEnabled,\n })\n .then(async ({ ComponentMod }) => {\n // we need to ensure fetch is patched before we require the page,\n // otherwise if the fetch is patched by user code, we will be patching it\n // too late and there won't be any caching behaviors\n ComponentMod.patchFetch()\n\n const webpackRequire = ComponentMod.__next_app__.require\n if (webpackRequire?.m) {\n for (const id of Object.keys(webpackRequire.m)) {\n await webpackRequire(id)\n }\n }\n })\n .catch(() => {})\n }\n }\n\n protected async handleUpgrade(): Promise {\n // The web server does not support web sockets, it's only used for HMR in\n // development.\n }\n\n protected async loadInstrumentationModule() {\n if (!this.serverOptions.dev) {\n try {\n this.instrumentation = await getInstrumentationModule(\n this.dir,\n this.nextConfig.distDir\n )\n } catch (err: any) {\n if (err.code !== 'MODULE_NOT_FOUND') {\n throw new Error(\n 'An error occurred while loading the instrumentation hook',\n { cause: err }\n )\n }\n }\n }\n return this.instrumentation\n }\n\n protected async prepareImpl() {\n await super.prepareImpl()\n await this.runInstrumentationHookIfAvailable()\n }\n\n protected async runInstrumentationHookIfAvailable() {\n await ensureInstrumentationRegistered(this.dir, this.nextConfig.distDir)\n }\n\n protected loadEnvConfig({\n dev,\n forceReload,\n silent,\n }: {\n dev: boolean\n forceReload?: boolean\n silent?: boolean\n }) {\n loadEnvConfig(\n this.dir,\n dev,\n silent ? { info: () => {}, error: () => {} } : Log,\n forceReload\n )\n }\n\n private async loadCustomCacheHandlers() {\n const { cacheHandlers } = this.nextConfig.experimental\n if (!cacheHandlers) return\n\n // If we've already initialized the cache handlers interface, don't do it\n // again.\n if (!initializeCacheHandlers()) return\n\n for (const [kind, handler] of Object.entries(cacheHandlers)) {\n if (!handler) continue\n\n setCacheHandler(\n kind,\n interopDefault(\n await dynamicImportEsmDefault(\n formatDynamicImportPath(this.distDir, handler)\n )\n )\n )\n }\n }\n\n protected async getIncrementalCache({\n requestHeaders,\n }: {\n requestHeaders: IncrementalCache['requestHeaders']\n }) {\n const dev = !!this.renderOpts.dev\n let CacheHandler: any\n const { cacheHandler } = this.nextConfig\n\n if (cacheHandler) {\n CacheHandler = interopDefault(\n await dynamicImportEsmDefault(\n formatDynamicImportPath(this.distDir, cacheHandler)\n )\n )\n }\n\n await this.loadCustomCacheHandlers()\n\n // incremental-cache is request specific\n // although can have shared caches in module scope\n // per-cache handler\n return new IncrementalCache({\n fs: this.getCacheFilesystem(),\n dev,\n requestHeaders,\n allowedRevalidateHeaderKeys:\n this.nextConfig.experimental.allowedRevalidateHeaderKeys,\n minimalMode: this.minimalMode,\n serverDistDir: this.serverDistDir,\n fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,\n maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize,\n flushToDisk:\n !this.minimalMode && this.nextConfig.experimental.isrFlushToDisk,\n getPrerenderManifest: () => this.getPrerenderManifest(),\n CurCacheHandler: CacheHandler,\n })\n }\n\n protected getResponseCache() {\n return new ResponseCache(this.minimalMode)\n }\n\n protected getPublicDir(): string {\n return join(this.dir, CLIENT_PUBLIC_FILES_PATH)\n }\n\n protected getHasStaticDir(): boolean {\n return fs.existsSync(join(this.dir, 'static'))\n }\n\n protected getPagesManifest(): PagesManifest | undefined {\n return loadManifest(\n join(this.serverDistDir, PAGES_MANIFEST)\n ) as PagesManifest\n }\n\n protected getAppPathsManifest(): PagesManifest | undefined {\n if (!this.enabledDirectories.app) return undefined\n\n return loadManifest(\n join(this.serverDistDir, APP_PATHS_MANIFEST)\n ) as PagesManifest\n }\n\n protected getinterceptionRoutePatterns(): RegExp[] {\n if (!this.enabledDirectories.app) return []\n\n const routesManifest = this.getRoutesManifest()\n return (\n routesManifest?.rewrites.beforeFiles\n .filter(isInterceptionRouteRewrite)\n .map((rewrite) => new RegExp(rewrite.regex)) ?? []\n )\n }\n\n protected async hasPage(pathname: string): Promise {\n return !!getMaybePagePath(\n pathname,\n this.distDir,\n this.nextConfig.i18n?.locales,\n this.enabledDirectories.app\n )\n }\n\n protected getBuildId(): string {\n const buildIdFile = join(this.distDir, BUILD_ID_FILE)\n try {\n return fs.readFileSync(buildIdFile, 'utf8').trim()\n } catch (err: any) {\n if (err.code === 'ENOENT') {\n throw new Error(\n `Could not find a production build in the '${this.distDir}' directory. Try building your app with 'next build' before starting the production server. https://nextjs.org/docs/messages/production-start-no-build-id`\n )\n }\n\n throw err\n }\n }\n\n protected getEnabledDirectories(dev: boolean): NextEnabledDirectories {\n const dir = dev ? this.dir : this.serverDistDir\n\n return {\n app: findDir(dir, 'app') ? true : false,\n pages: findDir(dir, 'pages') ? true : false,\n }\n }\n\n protected sendRenderResult(\n req: NodeNextRequest,\n res: NodeNextResponse,\n options: {\n result: RenderResult\n generateEtags: boolean\n poweredByHeader: boolean\n cacheControl: CacheControl | undefined\n }\n ): Promise {\n return sendRenderResult({\n req: req.originalRequest,\n res: res.originalResponse,\n result: options.result,\n generateEtags: options.generateEtags,\n poweredByHeader: options.poweredByHeader,\n cacheControl: options.cacheControl,\n })\n }\n\n protected async runApi(\n req: NodeNextRequest,\n res: NodeNextResponse,\n query: ParsedUrlQuery,\n match: PagesAPIRouteMatch\n ): Promise {\n const edgeFunctionsPages = this.getEdgeFunctionsPages()\n\n for (const edgeFunctionsPage of edgeFunctionsPages) {\n if (edgeFunctionsPage === match.definition.pathname) {\n const handledAsEdgeFunction = await this.runEdgeFunction({\n req,\n res,\n query,\n params: match.params,\n page: match.definition.pathname,\n appPaths: null,\n })\n\n if (handledAsEdgeFunction) {\n return true\n }\n }\n }\n // The module supports minimal mode, load the minimal module.\n // Restore original URL as the handler handles it's own parsing\n const parsedInitUrl = parseUrl(getRequestMeta(req, 'initURL') || req.url)\n req.url = `${parsedInitUrl.pathname}${parsedInitUrl.search || ''}`\n\n const loader = new NodeModuleLoader()\n const module = (await loader.load(match.definition.filename)) as {\n handler: (\n req: IncomingMessage,\n res: ServerResponse,\n ctx: {\n waitUntil: ReturnType\n }\n ) => Promise\n }\n addRequestMeta(\n req.originalRequest,\n 'relativeProjectDir',\n relative(process.cwd(), this.dir)\n )\n addRequestMeta(req.originalRequest, 'distDir', this.distDir)\n await module.handler(req.originalRequest, res.originalResponse, {\n waitUntil: this.getWaitUntil(),\n })\n return true\n }\n\n protected async renderHTML(\n req: NodeNextRequest,\n res: NodeNextResponse,\n pathname: string,\n query: NextParsedUrlQuery,\n renderOpts: LoadedRenderOpts\n ): Promise {\n return getTracer().trace(NextNodeServerSpan.renderHTML, async () =>\n this.renderHTMLImpl(req, res, pathname, query, renderOpts)\n )\n }\n\n private async renderHTMLImpl(\n req: NodeNextRequest,\n res: NodeNextResponse,\n pathname: string,\n query: NextParsedUrlQuery,\n renderOpts: LoadedRenderOpts\n ): Promise {\n if (process.env.NEXT_MINIMAL) {\n throw new Error(\n 'Invariant: renderHTML should not be called in minimal mode'\n )\n // the `else` branch is needed for tree-shaking\n } else {\n // Due to the way we pass data by mutating `renderOpts`, we can't extend the\n // object here but only updating its `nextFontManifest` field.\n // https://github.com/vercel/next.js/blob/df7cbd904c3bd85f399d1ce90680c0ecf92d2752/packages/next/server/render.tsx#L947-L952\n renderOpts.nextFontManifest = this.nextFontManifest\n\n if (this.enabledDirectories.app && renderOpts.isAppPath) {\n return lazyRenderAppPage(\n req,\n res,\n pathname,\n query,\n // This code path does not service revalidations for unknown param\n // shells. As a result, we don't need to pass in the unknown params.\n null,\n renderOpts,\n this.getServerComponentsHmrCache(),\n false,\n {\n buildId: this.buildId,\n }\n )\n }\n\n // TODO: re-enable this once we've refactored to use implicit matches\n // throw new Error('Invariant: render should have used routeModule')\n\n return lazyRenderPagesPage(\n req.originalRequest,\n res.originalResponse,\n pathname,\n query,\n renderOpts,\n {\n buildId: this.buildId,\n deploymentId: this.nextConfig.deploymentId,\n customServer: this.serverOptions.customServer || undefined,\n },\n {\n isFallback: false,\n isDraftMode: renderOpts.isDraftMode,\n developmentNotFoundSourcePage: getRequestMeta(\n req,\n 'developmentNotFoundSourcePage'\n ),\n }\n )\n }\n }\n\n protected async imageOptimizer(\n req: NodeNextRequest,\n res: NodeNextResponse,\n paramsResult: import('./image-optimizer').ImageParamsResult,\n previousCacheEntry?: IncrementalResponseCacheEntry | null\n ): Promise<{\n buffer: Buffer\n contentType: string\n maxAge: number\n upstreamEtag: string\n etag: string\n }> {\n if (process.env.NEXT_MINIMAL) {\n throw new Error(\n 'invariant: imageOptimizer should not be called in minimal mode'\n )\n } else {\n const { imageOptimizer, fetchExternalImage, fetchInternalImage } =\n require('./image-optimizer') as typeof import('./image-optimizer')\n\n const handleInternalReq = async (\n newReq: IncomingMessage,\n newRes: ServerResponse\n ) => {\n if (newReq.url === req.url) {\n throw new Error(`Invariant attempted to optimize _next/image itself`)\n }\n\n if (!this.routerServerHandler) {\n throw new Error(`Invariant missing routerServerHandler`)\n }\n\n await this.routerServerHandler(newReq, newRes)\n return\n }\n\n const { isAbsolute, href } = paramsResult\n\n const imageUpstream = isAbsolute\n ? await fetchExternalImage(\n href,\n this.nextConfig.images.maximumResponseBody\n )\n : await fetchInternalImage(\n href,\n req.originalRequest,\n res.originalResponse,\n handleInternalReq\n )\n\n return imageOptimizer(imageUpstream, paramsResult, this.nextConfig, {\n isDev: this.renderOpts.dev,\n previousCacheEntry,\n })\n }\n }\n\n protected getPagePath(pathname: string, locales?: string[]): string {\n return getPagePath(\n pathname,\n this.distDir,\n locales,\n this.enabledDirectories.app\n )\n }\n\n protected async renderPageComponent(\n ctx: RequestContext,\n bubbleNoFallback: boolean\n ) {\n const edgeFunctionsPages = this.getEdgeFunctionsPages() || []\n if (edgeFunctionsPages.length) {\n const appPaths = this.getOriginalAppPaths(ctx.pathname)\n const isAppPath = Array.isArray(appPaths)\n\n let page = ctx.pathname\n if (isAppPath) {\n // When it's an array, we need to pass all parallel routes to the loader.\n page = appPaths[0]\n }\n\n for (const edgeFunctionsPage of edgeFunctionsPages) {\n if (edgeFunctionsPage === page) {\n await this.runEdgeFunction({\n req: ctx.req,\n res: ctx.res,\n query: ctx.query,\n params: ctx.renderOpts.params,\n page,\n appPaths,\n })\n return null\n }\n }\n }\n\n return super.renderPageComponent(ctx, bubbleNoFallback)\n }\n\n protected async findPageComponents({\n locale,\n page,\n query,\n params,\n isAppPath,\n url,\n }: {\n locale: string | undefined\n page: string\n query: NextParsedUrlQuery\n params: Params\n isAppPath: boolean\n // The following parameters are used in the development server's\n // implementation.\n sriEnabled?: boolean\n appPaths?: ReadonlyArray | null\n shouldEnsure: boolean\n url?: string\n }): Promise {\n return getTracer().trace(\n NextNodeServerSpan.findPageComponents,\n {\n spanName: 'resolve page components',\n attributes: {\n 'next.route': isAppPath ? normalizeAppPath(page) : page,\n },\n },\n () =>\n this.findPageComponentsImpl({\n locale,\n page,\n query,\n params,\n isAppPath,\n url,\n })\n )\n }\n\n private async findPageComponentsImpl({\n locale,\n page,\n query,\n params,\n isAppPath,\n url: _url,\n }: {\n locale: string | undefined\n page: string\n query: NextParsedUrlQuery\n params: Params\n isAppPath: boolean\n url?: string\n }): Promise {\n const pagePaths: string[] = [page]\n if (query.amp) {\n // try serving a static AMP version first\n pagePaths.unshift(\n (isAppPath ? normalizeAppPath(page) : normalizePagePath(page)) + '.amp'\n )\n }\n\n if (locale) {\n pagePaths.unshift(\n ...pagePaths.map((path) => `/${locale}${path === '/' ? '' : path}`)\n )\n }\n\n for (const pagePath of pagePaths) {\n try {\n const components = await loadComponents({\n distDir: this.distDir,\n page: pagePath,\n isAppPath,\n isDev: this.isDev,\n sriEnabled: this.sriEnabled,\n })\n\n if (\n locale &&\n typeof components.Component === 'string' &&\n !pagePath.startsWith(`/${locale}/`) &&\n pagePath !== `/${locale}`\n ) {\n // if loading an static HTML file the locale is required\n // to be present since all HTML files are output under their locale\n continue\n }\n\n return {\n components,\n query: {\n ...(!this.renderOpts.isExperimentalCompile &&\n components.getStaticProps\n ? ({\n amp: query.amp,\n } as NextParsedUrlQuery)\n : query),\n // For appDir params is excluded.\n ...((isAppPath ? {} : params) || {}),\n },\n }\n } catch (err) {\n // we should only not throw if we failed to find the page\n // in the pages-manifest\n if (!(err instanceof PageNotFoundError)) {\n throw err\n }\n }\n }\n return null\n }\n\n protected getNextFontManifest(): NextFontManifest | undefined {\n return loadManifest(\n join(this.distDir, 'server', NEXT_FONT_MANIFEST + '.json')\n ) as NextFontManifest\n }\n\n protected handleNextImageRequest: NodeRouteHandler = async (\n req,\n res,\n parsedUrl\n ) => {\n if (!parsedUrl.pathname || !parsedUrl.pathname.startsWith('/_next/image')) {\n return false\n }\n // Ignore if its a middleware request\n if (getRequestMeta(req, 'middlewareInvoke')) {\n return false\n }\n\n if (\n this.minimalMode ||\n this.nextConfig.output === 'export' ||\n process.env.NEXT_MINIMAL\n ) {\n res.statusCode = 400\n res.body('Bad Request').send()\n return true\n // the `else` branch is needed for tree-shaking\n } else {\n const { ImageOptimizerCache } =\n require('./image-optimizer') as typeof import('./image-optimizer')\n\n const imageOptimizerCache = new ImageOptimizerCache({\n distDir: this.distDir,\n nextConfig: this.nextConfig,\n })\n\n const { sendResponse, ImageError } =\n require('./image-optimizer') as typeof import('./image-optimizer')\n\n if (!this.imageResponseCache) {\n throw new Error('invariant image optimizer cache was not initialized')\n }\n const imagesConfig = this.nextConfig.images\n\n if (imagesConfig.loader !== 'default' || imagesConfig.unoptimized) {\n await this.render404(req, res)\n return true\n }\n\n const paramsResult = ImageOptimizerCache.validateParams(\n req.originalRequest,\n parsedUrl.query,\n this.nextConfig,\n !!this.renderOpts.dev\n )\n\n if ('errorMessage' in paramsResult) {\n res.statusCode = 400\n res.body(paramsResult.errorMessage).send()\n return true\n }\n\n const cacheKey = ImageOptimizerCache.getCacheKey(paramsResult)\n\n try {\n const { getExtension } =\n require('./serve-static') as typeof import('./serve-static')\n const cacheEntry = await this.imageResponseCache.get(\n cacheKey,\n async ({ previousCacheEntry }) => {\n const { buffer, contentType, maxAge, upstreamEtag, etag } =\n await this.imageOptimizer(\n req,\n res,\n paramsResult,\n previousCacheEntry\n )\n\n return {\n value: {\n kind: CachedRouteKind.IMAGE,\n buffer,\n etag,\n extension: getExtension(contentType) as string,\n upstreamEtag,\n },\n cacheControl: { revalidate: maxAge, expire: undefined },\n }\n },\n {\n routeKind: RouteKind.IMAGE,\n incrementalCache: imageOptimizerCache,\n isFallback: false,\n }\n )\n\n if (cacheEntry?.value?.kind !== CachedRouteKind.IMAGE) {\n throw new Error(\n 'invariant did not get entry from image response cache'\n )\n }\n\n sendResponse(\n req.originalRequest,\n res.originalResponse,\n paramsResult.href,\n cacheEntry.value.extension,\n cacheEntry.value.buffer,\n cacheEntry.value.etag,\n paramsResult.isStatic,\n cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT',\n imagesConfig,\n cacheEntry.cacheControl?.revalidate || 0,\n Boolean(this.renderOpts.dev)\n )\n return true\n } catch (err) {\n if (err instanceof ImageError) {\n res.statusCode = err.statusCode\n res.body(err.message).send()\n return true\n }\n throw err\n }\n }\n }\n\n protected handleCatchallRenderRequest: NodeRouteHandler = async (\n req,\n res,\n parsedUrl\n ) => {\n let { pathname, query } = parsedUrl\n if (!pathname) {\n throw new Error('Invariant: pathname is undefined')\n }\n\n // When in minimal mode we do not bubble the fallback as the\n // router-server is not present to handle the error\n addRequestMeta(req, 'bubbleNoFallback', this.minimalMode ? undefined : true)\n\n // This is needed to expose render404 and nextConfig\n // for environments without router-server\n if (!routerServerGlobal[RouterServerContextSymbol]) {\n routerServerGlobal[RouterServerContextSymbol] = {}\n }\n const relativeProjectDir = relative(process.cwd(), this.dir)\n const existingServerContext =\n routerServerGlobal[RouterServerContextSymbol][relativeProjectDir]\n\n if (!existingServerContext) {\n routerServerGlobal[RouterServerContextSymbol][relativeProjectDir] = {\n render404: this.render404.bind(this),\n }\n }\n routerServerGlobal[RouterServerContextSymbol][\n relativeProjectDir\n ].nextConfig = this.nextConfig\n\n try {\n // next.js core assumes page path without trailing slash\n pathname = removeTrailingSlash(pathname)\n\n const options: MatchOptions = {\n i18n: this.i18nProvider?.fromRequest(req, pathname),\n }\n const match = await this.matchers.match(pathname, options)\n\n // If we don't have a match, try to render it anyways.\n if (!match) {\n await this.render(req, res, pathname, query, parsedUrl, true)\n\n return true\n }\n\n // Add the match to the request so we don't have to re-run the matcher\n // for the same request.\n addRequestMeta(req, 'match', match)\n\n // TODO-APP: move this to a route handler\n const edgeFunctionsPages = this.getEdgeFunctionsPages()\n for (const edgeFunctionsPage of edgeFunctionsPages) {\n // If the page doesn't match the edge function page, skip it.\n if (edgeFunctionsPage !== match.definition.page) continue\n\n if (this.nextConfig.output === 'export') {\n await this.render404(req, res, parsedUrl)\n return true\n }\n delete query[NEXT_RSC_UNION_QUERY]\n\n // If we handled the request, we can return early.\n // For api routes edge runtime\n try {\n const handled = await this.runEdgeFunction({\n req,\n res,\n query,\n params: match.params,\n page: match.definition.page,\n match,\n appPaths: null,\n })\n if (handled) return true\n } catch (apiError) {\n await this.instrumentationOnRequestError(apiError, req, {\n routePath: match.definition.page,\n routerKind: 'Pages Router',\n routeType: 'route',\n // Edge runtime does not support ISR\n revalidateReason: undefined,\n })\n throw apiError\n }\n }\n\n // If the route was detected as being a Pages API route, then handle\n // it.\n // TODO: move this behavior into a route handler.\n if (isPagesAPIRouteMatch(match)) {\n if (this.nextConfig.output === 'export') {\n await this.render404(req, res, parsedUrl)\n return true\n }\n\n const handled = await this.handleApiRequest(req, res, query, match)\n if (handled) return true\n }\n\n await this.render(req, res, pathname, query, parsedUrl, true)\n\n return true\n } catch (err: any) {\n if (err instanceof NoFallbackError) {\n throw err\n }\n\n try {\n if (this.renderOpts.dev) {\n const { formatServerError } =\n require('../lib/format-server-error') as typeof import('../lib/format-server-error')\n formatServerError(err)\n this.logErrorWithOriginalStack(err)\n } else {\n this.logError(err)\n }\n res.statusCode = 500\n await this.renderError(err, req, res, pathname, query)\n return true\n } catch {}\n\n throw err\n }\n }\n\n // Used in development only, overloaded in next-dev-server\n protected logErrorWithOriginalStack(\n _err?: unknown,\n _type?: 'unhandledRejection' | 'uncaughtException' | 'warning' | 'app-dir'\n ): void {\n throw new Error(\n 'Invariant: logErrorWithOriginalStack can only be called on the development server'\n )\n }\n\n // Used in development only, overloaded in next-dev-server\n protected async ensurePage(_opts: {\n page: string\n clientOnly: boolean\n appPaths?: ReadonlyArray | null\n match?: RouteMatch\n url?: string\n }): Promise {\n throw new Error(\n 'Invariant: ensurePage can only be called on the development server'\n )\n }\n\n /**\n * Resolves `API` request, in development builds on demand\n * @param req http request\n * @param res http response\n * @param pathname path of request\n */\n protected async handleApiRequest(\n req: NodeNextRequest,\n res: NodeNextResponse,\n query: ParsedUrlQuery,\n match: PagesAPIRouteMatch\n ): Promise {\n return this.runApi(req, res, query, match)\n }\n\n protected getCacheFilesystem(): CacheFs {\n return nodeFs\n }\n\n protected normalizeReq(\n req: NodeNextRequest | IncomingMessage\n ): NodeNextRequest {\n return !(req instanceof NodeNextRequest) ? new NodeNextRequest(req) : req\n }\n\n protected normalizeRes(\n res: NodeNextResponse | ServerResponse\n ): NodeNextResponse {\n return !(res instanceof NodeNextResponse) ? new NodeNextResponse(res) : res\n }\n\n public getRequestHandler(): NodeRequestHandler {\n const handler = this.makeRequestHandler()\n if (this.serverOptions.experimentalTestProxy) {\n const { wrapRequestHandlerNode } =\n // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm\n require('next/dist/experimental/testmode/server') as typeof import('../experimental/testmode/server')\n return wrapRequestHandlerNode(handler)\n }\n return handler\n }\n\n private makeRequestHandler(): NodeRequestHandler {\n // This is just optimization to fire prepare as soon as possible. It will be\n // properly awaited later. We add the catch here to ensure that it does not\n // cause an unhandled promise rejection. The promise rejection will be\n // handled later on via the `await` when the request handler is called.\n this.prepare().catch((err) => {\n console.error('Failed to prepare server', err)\n })\n\n const handler = super.getRequestHandler()\n\n return (req, res, parsedUrl) =>\n handler(this.normalizeReq(req), this.normalizeRes(res), parsedUrl)\n }\n\n public async revalidate({\n urlPath,\n revalidateHeaders,\n opts,\n }: {\n urlPath: string\n revalidateHeaders: { [key: string]: string | string[] }\n opts: { unstable_onlyGenerated?: boolean }\n }) {\n const mocked = createRequestResponseMocks({\n url: urlPath,\n headers: revalidateHeaders,\n })\n\n const handler = this.getRequestHandler()\n await handler(\n new NodeNextRequest(mocked.req),\n new NodeNextResponse(mocked.res)\n )\n await mocked.res.hasStreamed\n\n if (\n mocked.res.getHeader('x-nextjs-cache') !== 'REVALIDATED' &&\n mocked.res.statusCode !== 200 &&\n !(mocked.res.statusCode === 404 && opts.unstable_onlyGenerated)\n ) {\n throw new Error(`Invalid response ${mocked.res.statusCode}`)\n }\n }\n\n public async render(\n req: NodeNextRequest | IncomingMessage,\n res: NodeNextResponse | ServerResponse,\n pathname: string,\n query?: NextParsedUrlQuery,\n parsedUrl?: NextUrlWithParsedQuery,\n internal = false\n ): Promise {\n return super.render(\n this.normalizeReq(req),\n this.normalizeRes(res),\n pathname,\n query,\n parsedUrl,\n internal\n )\n }\n\n public async renderToHTML(\n req: NodeNextRequest | IncomingMessage,\n res: NodeNextResponse | ServerResponse,\n pathname: string,\n query?: ParsedUrlQuery\n ): Promise {\n return super.renderToHTML(\n this.normalizeReq(req),\n this.normalizeRes(res),\n pathname,\n query\n )\n }\n\n protected async renderErrorToResponseImpl(\n ctx: RequestContext,\n err: Error | null\n ) {\n const { req, res, query } = ctx\n const is404 = res.statusCode === 404\n\n if (is404 && this.enabledDirectories.app) {\n if (this.renderOpts.dev) {\n await this.ensurePage({\n page: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,\n clientOnly: false,\n url: req.url,\n }).catch(() => {})\n }\n\n if (\n this.getEdgeFunctionsPages().includes(UNDERSCORE_NOT_FOUND_ROUTE_ENTRY)\n ) {\n await this.runEdgeFunction({\n req,\n res,\n query: query || {},\n params: {},\n page: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,\n appPaths: null,\n })\n return null\n }\n }\n return super.renderErrorToResponseImpl(ctx, err)\n }\n\n public async renderError(\n err: Error | null,\n req: NodeNextRequest | IncomingMessage,\n res: NodeNextResponse | ServerResponse,\n pathname: string,\n query?: NextParsedUrlQuery,\n setHeaders?: boolean\n ): Promise {\n return super.renderError(\n err,\n this.normalizeReq(req),\n this.normalizeRes(res),\n pathname,\n query,\n setHeaders\n )\n }\n\n public async renderErrorToHTML(\n err: Error | null,\n req: NodeNextRequest | IncomingMessage,\n res: NodeNextResponse | ServerResponse,\n pathname: string,\n query?: ParsedUrlQuery\n ): Promise {\n return super.renderErrorToHTML(\n err,\n this.normalizeReq(req),\n this.normalizeRes(res),\n pathname,\n query\n )\n }\n\n public async render404(\n req: NodeNextRequest | IncomingMessage,\n res: NodeNextResponse | ServerResponse,\n parsedUrl?: NextUrlWithParsedQuery,\n setHeaders?: boolean\n ): Promise {\n return super.render404(\n this.normalizeReq(req),\n this.normalizeRes(res),\n parsedUrl,\n setHeaders\n )\n }\n\n protected getMiddlewareManifest(): MiddlewareManifest | null {\n if (this.minimalMode) {\n return null\n } else {\n const manifest: MiddlewareManifest = require(this.middlewareManifestPath)\n return manifest\n }\n }\n\n /** Returns the middleware routing item if there is one. */\n protected async getMiddleware(): Promise {\n const manifest = this.getMiddlewareManifest()\n const middleware = manifest?.middleware?.['/']\n if (!middleware) {\n const middlewareModule = await this.loadNodeMiddleware()\n\n if (middlewareModule) {\n return {\n match: getMiddlewareRouteMatcher(\n middlewareModule.config?.matchers || [\n { regexp: '.*', originalSource: '/:path*' },\n ]\n ),\n page: '/',\n }\n }\n\n return\n }\n\n return {\n match: getMiddlewareMatcher(middleware),\n page: '/',\n }\n }\n\n protected getEdgeFunctionsPages(): string[] {\n const manifest = this.getMiddlewareManifest()\n if (!manifest) {\n return []\n }\n\n return Object.keys(manifest.functions)\n }\n\n /**\n * Get information for the edge function located in the provided page\n * folder. If the edge function info can't be found it will throw\n * an error.\n */\n protected getEdgeFunctionInfo(params: {\n page: string\n /** Whether we should look for a middleware or not */\n middleware: boolean\n }): {\n name: string\n paths: string[]\n wasm: { filePath: string; name: string }[]\n env: { [key: string]: string }\n assets?: { filePath: string; name: string }[]\n } | null {\n const manifest = this.getMiddlewareManifest()\n if (!manifest) {\n return null\n }\n\n let foundPage: string\n\n try {\n foundPage = denormalizePagePath(normalizePagePath(params.page))\n } catch (err) {\n return null\n }\n\n let pageInfo = params.middleware\n ? manifest.middleware[foundPage]\n : manifest.functions[foundPage]\n\n if (!pageInfo) {\n if (!params.middleware) {\n throw new PageNotFoundError(foundPage)\n }\n return null\n }\n\n return {\n name: pageInfo.name,\n paths: pageInfo.files.map((file) => join(this.distDir, file)),\n wasm: (pageInfo.wasm ?? []).map((binding) => ({\n ...binding,\n filePath: join(this.distDir, binding.filePath),\n })),\n assets:\n pageInfo.assets &&\n pageInfo.assets.map((binding) => {\n return {\n ...binding,\n filePath: join(this.distDir, binding.filePath),\n }\n }),\n env: pageInfo.env,\n }\n }\n\n private async loadNodeMiddleware() {\n if (!process.env.NEXT_MINIMAL) {\n try {\n const functionsConfig = this.renderOpts.dev\n ? {}\n : require(join(this.distDir, 'server', FUNCTIONS_CONFIG_MANIFEST))\n\n if (\n this.renderOpts.dev ||\n functionsConfig?.functions?.['/_middleware']\n ) {\n // if used with top level await, this will be a promise\n return require(join(this.distDir, 'server', 'middleware.js'))\n }\n } catch (err) {\n if (\n isError(err) &&\n err.code !== 'ENOENT' &&\n err.code !== 'MODULE_NOT_FOUND'\n ) {\n throw err\n }\n }\n }\n }\n\n /**\n * Checks if a middleware exists. This method is useful for the development\n * server where we need to check the filesystem. Here we just check the\n * middleware manifest.\n */\n protected async hasMiddleware(pathname: string): Promise {\n const info = this.getEdgeFunctionInfo({ page: pathname, middleware: true })\n const nodeMiddleware = await this.loadNodeMiddleware()\n\n if (!info && nodeMiddleware) {\n return true\n }\n return Boolean(info && info.paths.length > 0)\n }\n\n /**\n * A placeholder for a function to be defined in the development server.\n * It will make sure that the root middleware or an edge function has been compiled\n * so that we can run it.\n */\n protected async ensureMiddleware(_url?: string) {}\n protected async ensureEdgeFunction(_params: {\n page: string\n appPaths: string[] | null\n url?: string\n }) {}\n\n /**\n * This method gets all middleware matchers and execute them when the request\n * matches. It will make sure that each middleware exists and is compiled and\n * ready to be invoked. The development server will decorate it to add warns\n * and errors with rich traces.\n */\n protected async runMiddleware(params: {\n request: NodeNextRequest\n response: NodeNextResponse\n parsedUrl: ParsedUrl\n parsed: UrlWithParsedQuery\n onWarning?: (warning: Error) => void\n }) {\n if (process.env.NEXT_MINIMAL) {\n throw new Error(\n 'invariant: runMiddleware should not be called in minimal mode'\n )\n }\n\n // Middleware is skipped for on-demand revalidate requests\n if (\n checkIsOnDemandRevalidate(params.request, this.renderOpts.previewProps)\n .isOnDemandRevalidate\n ) {\n return {\n response: new Response(null, { headers: { 'x-middleware-next': '1' } }),\n } as FetchEventResult\n }\n\n let url: string\n\n if (this.nextConfig.skipMiddlewareUrlNormalize) {\n url = getRequestMeta(params.request, 'initURL')!\n } else {\n // For middleware to \"fetch\" we must always provide an absolute URL\n const query = urlQueryToSearchParams(params.parsed.query).toString()\n const locale = getRequestMeta(params.request, 'locale')\n\n url = `${getRequestMeta(params.request, 'initProtocol')}://${\n this.fetchHostname || 'localhost'\n }:${this.port}${locale ? `/${locale}` : ''}${params.parsed.pathname}${\n query ? `?${query}` : ''\n }`\n }\n\n if (!url.startsWith('http')) {\n throw new Error(\n 'To use middleware you must provide a `hostname` and `port` to the Next.js Server'\n )\n }\n\n const page: {\n name?: string\n params?: { [key: string]: string | string[] }\n } = {}\n\n const middleware = await this.getMiddleware()\n if (!middleware) {\n return { finished: false }\n }\n if (!(await this.hasMiddleware(middleware.page))) {\n return { finished: false }\n }\n\n await this.ensureMiddleware(params.request.url)\n const middlewareInfo = this.getEdgeFunctionInfo({\n page: middleware.page,\n middleware: true,\n })\n\n const method = (params.request.method || 'GET').toUpperCase()\n const requestData = {\n headers: params.request.headers,\n method,\n nextConfig: {\n basePath: this.nextConfig.basePath,\n i18n: this.nextConfig.i18n,\n trailingSlash: this.nextConfig.trailingSlash,\n experimental: this.nextConfig.experimental,\n },\n url: url,\n page,\n body:\n method !== 'GET' && method !== 'HEAD'\n ? (getRequestMeta(params.request, 'clonableBody') as any)\n : undefined,\n\n signal: signalFromNodeResponse(params.response.originalResponse),\n waitUntil: this.getWaitUntil(),\n }\n let result:\n | UnwrapPromise>\n | undefined\n\n // if no middleware info check for Node.js middleware\n // this is not in the middleware-manifest as that historically\n // has only included edge-functions, we need to do a breaking\n // version bump for that manifest to write this info there if\n // we decide we want to\n if (!middlewareInfo) {\n let middlewareModule\n middlewareModule = await this.loadNodeMiddleware()\n\n if (!middlewareModule) {\n throw new MiddlewareNotFoundError()\n }\n const adapterFn: typeof import('./web/adapter').adapter =\n middlewareModule.default || middlewareModule\n\n const hasRequestBody =\n !['HEAD', 'GET'].includes(params.request.method) &&\n Boolean(requestData.body)\n\n try {\n result = await adapterFn({\n handler: middlewareModule.middleware || middlewareModule,\n request: {\n ...requestData,\n body: hasRequestBody\n ? requestData.body.cloneBodyStream()\n : undefined,\n },\n page: 'middleware',\n })\n } finally {\n if (hasRequestBody) {\n requestData.body.finalize()\n }\n }\n } else {\n const { run } = require('./web/sandbox') as typeof import('./web/sandbox')\n\n result = await run({\n distDir: this.distDir,\n name: middlewareInfo.name,\n paths: middlewareInfo.paths,\n edgeFunctionEntry: middlewareInfo,\n request: requestData,\n useCache: true,\n onWarning: params.onWarning,\n })\n }\n\n if (!this.renderOpts.dev) {\n result.waitUntil.catch((error) => {\n console.error(`Uncaught: middleware waitUntil errored`, error)\n })\n }\n\n if (!result) {\n this.render404(params.request, params.response, params.parsed)\n return { finished: true }\n }\n\n // Split compound (comma-separated) set-cookie headers\n if (result.response.headers.has('set-cookie')) {\n const cookies = result.response.headers\n .getSetCookie()\n .flatMap((maybeCompoundCookie) =>\n splitCookiesString(maybeCompoundCookie)\n )\n\n // Clear existing header(s)\n result.response.headers.delete('set-cookie')\n\n // Append each cookie individually.\n for (const cookie of cookies) {\n result.response.headers.append('set-cookie', cookie)\n }\n\n // Add cookies to request meta.\n addRequestMeta(params.request, 'middlewareCookie', cookies)\n }\n\n return result\n }\n\n protected handleCatchallMiddlewareRequest: NodeRouteHandler = async (\n req,\n res,\n parsed\n ) => {\n const isMiddlewareInvoke = getRequestMeta(req, 'middlewareInvoke')\n\n if (!isMiddlewareInvoke) {\n return false\n }\n\n const handleFinished = () => {\n addRequestMeta(req, 'middlewareInvoke', true)\n res.body('').send()\n return true\n }\n\n const middleware = await this.getMiddleware()\n if (!middleware) {\n return handleFinished()\n }\n\n const initUrl = getRequestMeta(req, 'initURL')!\n const parsedUrl = parseUrl(initUrl)\n const pathnameInfo = getNextPathnameInfo(parsedUrl.pathname, {\n nextConfig: this.nextConfig,\n i18nProvider: this.i18nProvider,\n })\n\n parsedUrl.pathname = pathnameInfo.pathname\n const normalizedPathname = removeTrailingSlash(parsed.pathname || '')\n let maybeDecodedPathname = normalizedPathname\n\n try {\n maybeDecodedPathname = decodeURIComponent(normalizedPathname)\n } catch {\n /* non-fatal we can't decode so can't match it */\n }\n\n if (\n !(\n middleware.match(normalizedPathname, req, parsedUrl.query) ||\n middleware.match(maybeDecodedPathname, req, parsedUrl.query)\n )\n ) {\n return handleFinished()\n }\n\n let result: Awaited<\n ReturnType\n >\n let bubblingResult = false\n\n try {\n await this.ensureMiddleware(req.url)\n\n result = await this.runMiddleware({\n request: req,\n response: res,\n parsedUrl: parsedUrl,\n parsed: parsed,\n })\n\n if ('response' in result) {\n if (isMiddlewareInvoke) {\n bubblingResult = true\n throw new BubbledError(true, result)\n }\n\n for (const [key, value] of Object.entries(\n toNodeOutgoingHttpHeaders(result.response.headers)\n )) {\n if (key !== 'content-encoding' && value !== undefined) {\n res.setHeader(key, value as string | string[])\n }\n }\n res.statusCode = result.response.status\n\n const { originalResponse } = res\n if (result.response.body) {\n await pipeToNodeResponse(result.response.body, originalResponse)\n } else {\n originalResponse.end()\n }\n return true\n }\n } catch (err: unknown) {\n if (bubblingResult) {\n throw err\n }\n\n if (isError(err) && err.code === 'ENOENT') {\n await this.render404(req, res, parsed)\n return true\n }\n\n if (err instanceof DecodeError) {\n res.statusCode = 400\n await this.renderError(err, req, res, parsed.pathname || '')\n return true\n }\n\n const error = getProperError(err)\n console.error(error)\n res.statusCode = 500\n await this.renderError(error, req, res, parsed.pathname || '')\n return true\n }\n\n return result.finished\n }\n\n private _cachedPreviewManifest: PrerenderManifest | undefined\n protected getPrerenderManifest(): PrerenderManifest {\n if (this._cachedPreviewManifest) {\n return this._cachedPreviewManifest\n }\n\n this._cachedPreviewManifest = loadManifest(\n join(this.distDir, PRERENDER_MANIFEST)\n ) as PrerenderManifest\n\n return this._cachedPreviewManifest\n }\n\n protected getRoutesManifest(): NormalizedRouteManifest | undefined {\n return getTracer().trace(\n NextNodeServerSpan.getRoutesManifest,\n () => loadManifest(join(this.distDir, ROUTES_MANIFEST)) as RoutesManifest\n )\n }\n\n protected attachRequestMeta(\n req: NodeNextRequest,\n parsedUrl: NextUrlWithParsedQuery,\n isUpgradeReq?: boolean\n ) {\n // Injected in base-server.ts\n const protocol = req.headers['x-forwarded-proto']?.includes('https')\n ? 'https'\n : 'http'\n\n // When there are hostname and port we build an absolute URL\n const initUrl =\n this.fetchHostname && this.port\n ? `${protocol}://${this.fetchHostname}:${this.port}${req.url}`\n : this.nextConfig.experimental.trustHostHeader\n ? `https://${req.headers.host || 'localhost'}${req.url}`\n : req.url\n\n addRequestMeta(req, 'initURL', initUrl)\n addRequestMeta(req, 'initQuery', { ...parsedUrl.query })\n addRequestMeta(req, 'initProtocol', protocol)\n\n if (!isUpgradeReq) {\n const bodySizeLimit = this.nextConfig.experimental\n ?.middlewareClientMaxBodySize as number | undefined\n addRequestMeta(\n req,\n 'clonableBody',\n getCloneableBody(req.originalRequest, bodySizeLimit)\n )\n }\n }\n\n protected async runEdgeFunction(params: {\n req: NodeNextRequest\n res: NodeNextResponse\n query: ParsedUrlQuery\n params: Params | undefined\n page: string\n appPaths: string[] | null\n match?: RouteMatch\n onError?: (err: unknown) => void\n onWarning?: (warning: Error) => void\n }): Promise {\n if (process.env.NEXT_MINIMAL) {\n throw new Error(\n 'Middleware is not supported in minimal mode. Please remove the `NEXT_MINIMAL` environment variable.'\n )\n }\n let edgeInfo: ReturnType | undefined\n\n const { query, page, match } = params\n\n if (!match)\n await this.ensureEdgeFunction({\n page,\n appPaths: params.appPaths,\n url: params.req.url,\n })\n edgeInfo = this.getEdgeFunctionInfo({\n page,\n middleware: false,\n })\n\n if (!edgeInfo) {\n return null\n }\n\n // For edge to \"fetch\" we must always provide an absolute URL\n const isNextDataRequest = getRequestMeta(params.req, 'isNextDataReq')\n const initialUrl = new URL(\n getRequestMeta(params.req, 'initURL') || '/',\n 'http://n'\n )\n const queryString = urlQueryToSearchParams({\n ...Object.fromEntries(initialUrl.searchParams),\n ...query,\n ...params.params,\n }).toString()\n\n if (isNextDataRequest) {\n params.req.headers['x-nextjs-data'] = '1'\n }\n initialUrl.search = queryString\n const url = initialUrl.toString()\n\n if (!url.startsWith('http')) {\n throw new Error(\n 'To use middleware you must provide a `hostname` and `port` to the Next.js Server'\n )\n }\n\n const { run } = require('./web/sandbox') as typeof import('./web/sandbox')\n const result = await run({\n distDir: this.distDir,\n name: edgeInfo.name,\n paths: edgeInfo.paths,\n edgeFunctionEntry: edgeInfo,\n request: {\n headers: params.req.headers,\n method: params.req.method,\n nextConfig: {\n basePath: this.nextConfig.basePath,\n i18n: this.nextConfig.i18n,\n trailingSlash: this.nextConfig.trailingSlash,\n },\n url,\n page: {\n name: params.page,\n ...(params.params && { params: params.params }),\n },\n body: getRequestMeta(params.req, 'clonableBody'),\n signal: signalFromNodeResponse(params.res.originalResponse),\n waitUntil: this.getWaitUntil(),\n },\n useCache: true,\n onError: params.onError,\n onWarning: params.onWarning,\n incrementalCache:\n (globalThis as any).__incrementalCache ||\n getRequestMeta(params.req, 'incrementalCache'),\n serverComponentsHmrCache: getRequestMeta(\n params.req,\n 'serverComponentsHmrCache'\n ),\n })\n\n if (result.fetchMetrics) {\n params.req.fetchMetrics = result.fetchMetrics\n }\n\n if (!params.res.statusCode || params.res.statusCode < 400) {\n params.res.statusCode = result.response.status\n params.res.statusMessage = result.response.statusText\n }\n\n // TODO: (wyattjoh) investigate improving this\n\n result.response.headers.forEach((value, key) => {\n // The append handling is special cased for `set-cookie`.\n if (key.toLowerCase() === 'set-cookie') {\n // TODO: (wyattjoh) replace with native response iteration when we can upgrade undici\n for (const cookie of splitCookiesString(value)) {\n params.res.appendHeader(key, cookie)\n }\n } else {\n params.res.appendHeader(key, value)\n }\n })\n\n const { originalResponse } = params.res\n if (result.response.body) {\n await pipeToNodeResponse(result.response.body, originalResponse)\n } else {\n originalResponse.end()\n }\n\n return result\n }\n\n protected get serverDistDir(): string {\n if (this._serverDistDir) {\n return this._serverDistDir\n }\n const serverDistDir = join(this.distDir, SERVER_DIRECTORY)\n this._serverDistDir = serverDistDir\n return serverDistDir\n }\n\n protected async getFallbackErrorComponents(\n _url?: string\n ): Promise {\n // Not implemented for production use cases, this is implemented on the\n // development server.\n return null\n }\n\n protected async instrumentationOnRequestError(\n ...args: Parameters\n ) {\n await super.instrumentationOnRequestError(...args)\n\n // For Node.js runtime production logs, in dev it will be overridden by next-dev-server\n if (!this.renderOpts.dev) {\n this.logError(args[0] as Error)\n }\n }\n\n protected onServerClose(listener: () => Promise) {\n this.cleanupListeners.add(listener)\n }\n\n async close(): Promise {\n await this.cleanupListeners.runAll()\n }\n\n protected getInternalWaitUntil(): WaitUntil {\n this.internalWaitUntil ??= this.createInternalWaitUntil()\n return this.internalWaitUntil\n }\n\n private createInternalWaitUntil() {\n if (this.minimalMode) {\n throw new InvariantError(\n 'createInternalWaitUntil should never be called in minimal mode'\n )\n }\n\n const awaiter = new AwaiterOnce({ onError: console.error })\n\n // TODO(after): warn if the process exits before these are awaited\n this.onServerClose(() => awaiter.awaiting())\n\n return awaiter.waitUntil\n }\n}\n","import type { RouteMatch } from './route-match'\nimport type { PagesAPIRouteDefinition } from '../route-definitions/pages-api-route-definition'\n\nimport { RouteKind } from '../route-kind'\n\nexport interface PagesAPIRouteMatch\n extends RouteMatch {}\n\n/**\n * Checks if the given match is a Pages API route match.\n * @param match the match to check\n * @returns true if the match is a Pages API route match, false otherwise\n */\nexport function isPagesAPIRouteMatch(\n match: RouteMatch\n): match is PagesAPIRouteMatch {\n return match.definition.kind === RouteKind.PAGES_API\n}\n","import type { NextConfig } from '../types'\nimport { Agent as HttpAgent } from 'http'\nimport { Agent as HttpsAgent } from 'https'\n\nexport function setHttpClientAndAgentOptions(config: {\n httpAgentOptions?: NextConfig['httpAgentOptions']\n}) {\n if (globalThis.__NEXT_HTTP_AGENT) {\n // We only need to assign once because we want\n // to reuse the same agent for all requests.\n return\n }\n\n if (!config) {\n throw new Error('Expected config.httpAgentOptions to be an object')\n }\n\n globalThis.__NEXT_HTTP_AGENT_OPTIONS = config.httpAgentOptions\n globalThis.__NEXT_HTTP_AGENT = new HttpAgent(config.httpAgentOptions)\n globalThis.__NEXT_HTTPS_AGENT = new HttpsAgent(config.httpAgentOptions)\n}\n","import type { NextConfigComplete } from '../server/config-shared'\n\nfunction errorIfEnvConflicted(config: NextConfigComplete, key: string) {\n const isPrivateKey = /^(?:NODE_.+)|^(?:__.+)$/i.test(key)\n const hasNextRuntimeKey = key === 'NEXT_RUNTIME'\n\n if (isPrivateKey || hasNextRuntimeKey) {\n throw new Error(\n `The key \"${key}\" under \"env\" in ${config.configFileName} is not allowed. https://nextjs.org/docs/messages/env-key-not-allowed`\n )\n }\n}\n\n/**\n * Collects all environment variables that are using the `NEXT_PUBLIC_` prefix.\n */\nexport function getNextPublicEnvironmentVariables() {\n const defineEnv: Record = {}\n for (const key in process.env) {\n if (key.startsWith('NEXT_PUBLIC_')) {\n const value = process.env[key]\n if (value != null) {\n defineEnv[`process.env.${key}`] = value\n }\n }\n }\n return defineEnv\n}\n\n/**\n * Collects the `env` config value from the Next.js config.\n */\nexport function getNextConfigEnv(config: NextConfigComplete) {\n // Refactored code below to use for-of\n const defineEnv: Record = {}\n const env = config.env\n for (const key in env) {\n const value = env[key]\n if (value != null) {\n errorIfEnvConflicted(config, key)\n defineEnv[`process.env.${key}`] = value\n }\n }\n return defineEnv\n}\n\nexport function getStaticEnv(config: NextConfigComplete) {\n const staticEnv: Record = {\n ...getNextPublicEnvironmentVariables(),\n ...getNextConfigEnv(config),\n 'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || '',\n }\n return staticEnv\n}\n\nexport function populateStaticEnv(config: NextConfigComplete) {\n // since inlining comes after static generation we need\n // to ensure this value is assigned to process env so it\n // can still be accessed\n const staticEnv = getStaticEnv(config)\n for (const key in staticEnv) {\n const innerKey = key.split('.').pop() || ''\n if (!process.env[innerKey]) {\n process.env[innerKey] = staticEnv[key] || ''\n }\n }\n}\n","import type { IncomingMessage } from 'http'\nimport type { Readable } from 'stream'\nimport { PassThrough } from 'stream'\nimport bytes from 'next/dist/compiled/bytes'\n\nconst DEFAULT_BODY_CLONE_SIZE_LIMIT = 10 * 1024 * 1024 // 10MB\n\nexport function requestToBodyStream(\n context: { ReadableStream: typeof ReadableStream },\n KUint8Array: typeof Uint8Array,\n stream: Readable\n) {\n return new context.ReadableStream({\n start: async (controller) => {\n for await (const chunk of stream) {\n controller.enqueue(new KUint8Array(chunk))\n }\n controller.close()\n },\n })\n}\n\nfunction replaceRequestBody(\n base: T,\n stream: Readable\n): T {\n for (const key in stream) {\n let v = stream[key as keyof Readable] as any\n if (typeof v === 'function') {\n v = v.bind(base)\n }\n base[key as keyof T] = v\n }\n\n return base\n}\n\nexport interface CloneableBody {\n finalize(): Promise\n cloneBodyStream(): Readable\n}\n\nexport function getCloneableBody(\n readable: T,\n sizeLimit?: number\n): CloneableBody {\n let buffered: Readable | null = null\n\n const endPromise = new Promise(\n (resolve, reject) => {\n readable.on('end', resolve)\n readable.on('error', reject)\n }\n ).catch((error) => {\n return { error }\n })\n\n return {\n /**\n * Replaces the original request body if necessary.\n * This is done because once we read the body from the original request,\n * we can't read it again.\n */\n async finalize(): Promise {\n if (buffered) {\n const res = await endPromise\n\n if (res && typeof res === 'object' && res.error) {\n throw res.error\n }\n replaceRequestBody(readable, buffered)\n buffered = readable\n }\n },\n /**\n * Clones the body stream\n * to pass into a middleware\n */\n cloneBodyStream() {\n const input = buffered ?? readable\n const p1 = new PassThrough()\n const p2 = new PassThrough()\n\n let bytesRead = 0\n const bodySizeLimit = sizeLimit ?? DEFAULT_BODY_CLONE_SIZE_LIMIT\n let limitExceeded = false\n\n input.on('data', (chunk) => {\n if (limitExceeded) return\n\n bytesRead += chunk.length\n\n if (bytesRead > bodySizeLimit) {\n limitExceeded = true\n const urlInfo = readable.url ? ` for ${readable.url}` : ''\n console.warn(\n `Request body exceeded ${bytes.format(bodySizeLimit)}${urlInfo}. Only the first ${bytes.format(bodySizeLimit)} will be available unless configured. See https://nextjs.org/docs/app/api-reference/config/next-config-js/middlewareClientMaxBodySize for more details.`\n )\n p1.push(null)\n p2.push(null)\n return\n }\n\n p1.push(chunk)\n p2.push(chunk)\n })\n input.on('end', () => {\n if (!limitExceeded) {\n p1.push(null)\n p2.push(null)\n }\n })\n buffered = p2\n return p1\n },\n }\n}\n"],"names":["Symbol","Object","Error","reportError","r","e","t","process","n","Array","console","s","URL","Buffer","RangeError","JSON","__dirname","p","o","Boolean","Date","encodeURIComponent","Map","decodeURIComponent","Number","i","Math","isNaN","parseFloat","parseInt","__nccwpck_require__","TypeError","a","isFinite","NaN","arguments","Promise","setTimeout","clearTimeout","clearInterval","setInterval","u","v","RegExp","String","globalThis","AsyncLocalStorage","require","WebSocket","defineProperty","configurable","get","set","value","writable","global","crypto","webcrypto","enumerable","module","Set","c","webCrypto","LRUNode","constructor","key","data","size","prev","next","SentinelNode","LRUCache","maxSize","calculateSize","onEvict","cache","totalSize","head","tail","addToHead","node","removeNode","moveToHead","removeTail","lastNode","warn","existing","newNode","delete","has","iterator","current","remove","currentSize","versions","startsWith","invalidSourceMap","isAnonymousFrameLikelyJSNative","methodName","url","length","regexNextStatic","reactVendoredRe","reactNodeModulesRe","nextInternalsRe","env","stdout","enabled","NO_COLOR","FORCE_COLOR","isTTY","CI","TERM","replaceClose","str","close","replace","index","start","substring","end","nextIndex","indexOf","formatter","open","input","string","bold","red","green","yellow","magenta","white","frameToString","sourceURL","line1","column1","fileLocation","sourceLocation","canParse","path","cwd","computeErrorName","error","name","prepareUnsourcemappedStackTrace","structuredStackTrace","stack","message","toString","shouldIgnoreListGeneratedFrame","file","includes","createUnsourcemappedFrame","frame","ignored","code","patchErrorInspectNodeJS","errorConstructor","inspectSymbol","for","prepareStackTrace","prototype","depth","inspectOptions","inspect","workUnitAsyncStorage","newError","sourceMapError","undefined","cause","parseAndSourceMap","unparsedStack","errorName","idx","lastIndexOf","slice","unsourcemappedStack","parseStack","distDir","__NEXT_DIST_DIR","split","map","line","join","frames","parse","res","exec","pathname","effectiveDistDir","concat","pop","search","lineNumber","column","sourceMapCache","sourceMappedFrames","sourceFrame","push","sourcemappedFrame","getSourcemappedFrameIfPossible","applicableSourceMap","sourceMap","sourceMapConsumer","sourceMapPayload","codeFrame","sourceMapCacheEntry","maybeSourceMapPayload","nativeFindSourceMap","payload","SyncSourceMapConsumer","sourcePosition","originalPositionFor","findApplicableSourceMapPayload","line0","column0","sections","left","right","result","middle","section","offset","ignoreList","sources","source","sourceIndex","originalFrame","colors","sourceContent","sourceContentFor","test","codeFrameColumns","forceColor","ignoreListAnonymousStackFramesIfSandwichedGeneric","isAnonymousFrame","isIgnoredFrame","getMethodName","ignoreFrame","currentFrame","previousFrameIsIgnored","ignoreSandwich","j","nextFrame","sourceMappedStack","hasOwnProperty","call","originalCustomInspect","WeakMap","InvariantError","options","endsWith","abortOnSynchronousPlatformIOAccess","route","expression","errorWithStack","prerenderStore","dynamicTracking","createPrerenderInterruptedError","digest","controller","abort","dynamicAccesses","isDebugDynamicAccesses","syncDynamicErrorWithStack","React","isDynamicPostponeReason","reason","io","type","workUnitStore","workStore","workAsyncStorage","prerenderSignal","signal","aborted","prerenderPhase","requestStore","_random","random","apply","bind","createDate","originalConstructor","originalNow","properties","getOwnPropertyDescriptors","now","Reflect","construct","newConstructor","defineProperties","getRandomValuesExpression","_getRandomValues","getRandomValues","_randomUUID","randomUUID","nodeCrypto","randomUUIDExpression","randomBytesExpression","_randomBytes","randomBytes","randomFillSyncExpression","_randomFillSync","randomFillSync","_randomInt","randomInt","generatePrimeSyncExpression","_generatePrimeSync","generatePrimeSync","generateKeyPairSyncExpression","_generateKeyPairSync","generateKeyPairSync","generateKeySyncExpression","_generateKeySync","generateKeySync","mod","originalRequire","resolveFilename","_resolveFilename","resolve","__non_webpack_require__","hookPropertyMap","addHookAliases","aliases","entries","dirname","originalResolveFilename","requestMap","request","parent","isMain","hookResolved","basename","SP","performance","every","method","DecodeError","NormalizeError","PageNotFoundError","page","MissingStaticPage","PARAM_SEPARATOR","hasAdjacentParameterIssues","normalizeAdjacentParameters","normalized","safePathToRegexp","keys","pathToRegexp","needsNormalization","routeToUse","normalizedRoute","retryError","safeCompile","compile","getRouteMatcher","matcherFn","re","groups","routeMatch","decode","param","params","group","match","pos","repeat","entry","cleaned","isArray","item","NEXT_REQUEST_META","getRequestMeta","req","meta","addRequestMeta","removeRequestMeta","COMPILER_NAMES","client","server","edgeServer","UNDERSCORE_NOT_FOUND_ROUTE","UNDERSCORE_NOT_FOUND_ROUTE_ENTRY","PAGES_MANIFEST","APP_PATHS_MANIFEST","SERVER_DIRECTORY","BLOCKED_PAGES","STATIC_STATUS_PAGES","findDir","dir","curDir","fs","ReflectAdapter","target","prop","receiver","deleteProperty","ReadonlyHeadersError","callable","HeadersAdapter","Headers","headers","Proxy","lowercased","toLowerCase","original","find","seal","merge","from","append","forEach","callbackfn","thisArg","values","HTML_CONTENT_TYPE_HEADER","NEXT_QUERY_PARAM_PREFIX","NEXT_INTERCEPTION_MARKER_PREFIX","MATCHED_PATH_HEADER","RSC_PREFETCH_SUFFIX","RSC_SEGMENTS_DIR_SUFFIX","RSC_SEGMENT_SUFFIX","RSC_SUFFIX","NEXT_DATA_SUFFIX","NEXT_META_SUFFIX","NEXT_CACHE_REVALIDATED_TAGS_HEADER","WEBPACK_LAYERS_NAMES","shared","reactServerComponents","serverSideRendering","actionBrowser","apiNode","apiEdge","middleware","instrument","edgeAsset","appPagesBrowser","pagesDirBrowser","pagesDirEdge","pagesDirNode","GROUP","builtinReact","serverOnly","neutralTarget","clientOnly","bundled","appPages","BaseServerSpan","LoadComponentsSpan","NextNodeServerSpan","SYMBOL_CLEARED_COOKIES","RedirectStatusCode","getCookieParser","cookie","parseCookieFn","BaseNextRequest","body","cookies","_cookies","BaseNextResponse","destination","redirect","statusCode","setHeader","NodeNextRequest","_req","toUpperCase","fetchMetrics","streaming","originalRequest","stream","ReadableStream","on","chunk","enqueue","Uint8Array","err","NodeNextResponse","originalResponse","_res","textBody","sent","finished","headersSent","statusMessage","removeHeader","getHeaderValues","getHeader","hasHeader","getHeaders","appendHeader","currentValues","send","onClose","callback","sendRenderResult","generateEtags","poweredByHeader","cacheControl","contentType","getCacheControlHeader","revalidate","expire","swrHeader","isDynamic","toUnchunkedString","etag","generateETag","weak","prefix","fnv1a52","len","t0","v0","t1","v1","t2","v2","t3","v3","charCodeAt","fresh","byteLength","pipeToNodeResponse","searchParamsToUrlQuery","searchParams","query","stringifyUrlQueryParam","parseUrl","parseRelativeUrl","base","parseQuery","globalBase","resolvedBase","hash","href","origin","slashes","parsedURL","hostname","port","protocol","prefixes","wait","ready","info","event","trace","LOGGING_METHOD","log","prefixedLog","prefixType","shift","consoleMethod","bootstrap","warnOnceCache","warnOnce","v4Seg","v4Str","v6Seg","IPv6Reg","ensureLeadingSlash","normalizeAppPath","reduce","segment","segments","normalizeRscURL","INTERCEPTION_ROUTE_MARKERS","isInterceptionRouteAppPath","m","TEST_ROUTE","TEST_STRICT_ROUTE","isDynamicRoute","strict","extractInterceptionRouteInformation","interceptingRoute","marker","interceptedRoute","splitInterceptingRoute","HTML_LIMITED_BOT_UA_RE","HEADLESS_BROWSER_BOT_UA_RE","HTML_LIMITED_BOT_UA_RE_STRING","voidCatch","encoder","TextEncoder","streamFromString","encode","streamFromBuffer","streamToString","decoder","TextDecoder","fatal","splitCookiesString","cookiesString","ch","lastComma","nextStart","cookiesSeparatorFound","cookiesStrings","skipWhitespace","charAt","toNodeOutgoingHttpHeaders","nodeHeaders","validateURL","normalizeNextQueryParam","removeTrailingSlash","parsePath","hashIndex","queryIndex","hasQuery","addPathPrefix","addPathSuffix","suffix","pathHasPrefix","getHostname","parsed","host","normalizeLocalePath","locales","detectedLocale","lowercasedLocales","locale","removePathPrefix","withoutPrefix","getNextPathnameInfo","basePath","i18n","trailingSlash","nextConfig","pathnameNoDataPrefix","paths","buildId","parseData","i18nProvider","analyze","REGEX_LOCALHOST_HOSTNAME","parseURL","Internal","NextURL","baseOrOpts","opts","__NEXT_NO_MIDDLEWARE_URL_NORMALIZE","domainLocale","detectDomainLocale","domainItems","domain","defaultLocale","some","domains","formatPathname","addLocale","ignorePrefix","lower","forceLocale","formatSearch","password","username","toJSON","clone","PageSignatureError","RemovedPageError","RemovedUAError","INTERNALS","NextRequest","Request","init","duplex","nextUrl","RequestCookies","bodyUsed","credentials","fromEntries","integrity","keepalive","mode","referrer","referrerPolicy","ua","ResponseAbortedName","ResponseAborted","DetachedPromise","reject","promise","rej","clientComponentLoadStart","clientComponentLoadTimes","clientComponentLoadCount","isAbortError","readable","waitUntilForEnd","errored","destroyed","createAbortController","response","AbortController","once","writableFinished","writer","createWriterFromResponse","started","drained","onDrain","off","WritableStream","write","NEXT_OTEL_PERFORMANCE_PREFIX","metrics","getClientComponentLoaderMetrics","reset","measure","flushHeaders","getTracer","spanName","ok","flush","destroy","pipeTo","RenderResult","EMPTY","metadata","fromStatic","waitUntil","assignMetadata","assign","isNull","isBuffer","chainStreams","streams","TransformStream","preventClose","nextStream","then","lastStream","catch","coerce","unshift","normalizePathSep","denormalizePagePath","_page","getPathMatch","regexp","delimiter","sensitive","matcher","regexpToFunction","regexModifier","flags","removeUnnamedParams","reHasRegExp","reReplaceRegExp","escapeStringRegexp","PARAMETER_PATTERN","parseMatchedParameter","optional","getRouteRegex","includeSuffix","includePrefix","excludeOptionalTrailingSlash","parameterizedRoute","getParametrizedRoute","groupIndex","markerMatch","paramMatches","getSafeKeyFromSegment","pattern","interceptionMarker","getSafeRouteKey","routeKeys","keyPrefix","backreferenceDuplicateKeys","cleanedKey","invalidKey","duplicateKey","interceptionPrefix","unescapeSegments","matchHas","missing","hasMatch","hasItem","getSafeParamName","paramName","newParamName","charCode","matches","groupKey","compileNonPath","validate","decodeQueryPathParameter","slashedProtocols","dynamicParamTypesSchema","segmentSchema","flightRouterStateSchema","ACTION_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","NEXT_URL","FLIGHT_HEADERS","NEXT_RSC_UNION_QUERY","isInterceptionRouteRewrite","filterInternalQuery","paramKeys","isNextQueryPrefix","isNextInterceptionMarkerPrefix","getPreviouslyRevalidatedTags","previewModeId","isError","getProperError","isPlainObject","getObjectClassLabel","getPrototypeOf","safeStringify","obj","seen","WeakSet","stringify","_key","add","LocaleRouteNormalizer","provider","normalize","UrlNode","insert","urlPath","_insert","filter","smoosh","_smoosh","childrenPaths","children","sort","slugName","splice","restSlugName","optionalRestSlugName","routes","curr","placeholder","urlPaths","slugNames","isCatchAll","nextSegment","segmentName","isOptional","handleSlug","previousSlug","nextSlug","slug","RouteMatcher","definition","dynamic","identity","LocaleRouteMatcher","DefaultRouteMatcherManager","compilationID","providers","waitTillReady","waitTillReadyPromise","reload","matchers","providersMatchers","all","duplicates","providerMatchers","duplicated","duplicate","others","previousMatchers","cachedMatcher","static","reference","pathnames","indexes","sorted","getSortedRoutes","normalizedPages","root","pagePath","sortedDynamicMatchers","dynamicMatches","lastCompilationID","matchAll","inferredFromDefault","skipDynamic","Normalizers","normalizers","normalizer","PrefixingNormalizer","normalizePagePath","posix","resolvedPage","UnderscoreNormalizer","AppBundlePathNormalizer","AppFilenameNormalizer","manifestFilename","isAppRouteRoute","STATIC_METADATA_IMAGES","icon","filename","extensions","apple","openGraph","twitter","getExtensionRegexString","staticExtensions","dynamicExtensions","wrapNormalizerFn","fn","AppPathnameNormalizer","AppNormalizers","bundlePath","RouteKind","AppPageRouteMatcher","CachedRouteMatcherProvider","loader","cached","load","compare","transform","ManifestRouteMatcherProvider","manifestName","manifestLoader","AppPageRouteMatcherProvider","manifest","pages","allAppPaths","appPaths","kind","AppRouteRouteMatcher","AppRouteRouteMatcherProvider","isAPIRoute","PagesAPIRouteMatcher","PagesAPILocaleRouteMatcher","PagesBundlePathNormalizer","PagesFilenameNormalizer","PagesNormalizers","PagesAPIRouteMatcherProvider","PagesRouteMatcher","PagesLocaleRouteMatcher","PagesRouteMatcherProvider","ServerManifestLoader","getter","I18NProvider","config","lowerCaseLocales","lowerCaseDomains","http","fromRequest","analysis","sendResponse","status","statusText","headersWithMultipleValuesAllowed","isHeaderPresent","SuffixPathnameNormalizer","matched","RSCPathnameNormalizer","PrefetchRSCPathnameNormalizer","PrefixPathnameNormalizer","NextDataPathnameNormalizer","buildID","toRoute","NEXT_REQUEST_CONTEXT_SYMBOL","REDIRECTS","handleMiddlewareField","NextResponse","Response","cookiesProxy","ResponseCookies","args","newHeaders","getAll","stringifyCookie","redirected","json","initObj","rewrite","debug","NEXT_PRIVATE_DEBUG_CACHE","handlersSymbol","handlersMapSymbol","handlersSetSymbol","NextRequestHint","sourcePage","respondWith","PATTERN","SegmentPrefixRSCPathnameNormalizer","extract","originalPathname","segmentPath","WrappedBuildError","innerError","Server","getServerComponentsHmrCache","experimental","serverComponentsHmrCache","__serverComponentsHmrCache","handleRSCRequest","parsedUrl","segmentPrefetchRSC","prefetchRSC","rsc","header","segmentPrefetchRSCRequest","formatUrl","handleNextDataRequest","getMiddleware","matchNextDataPathname","render404","lastParam","getRouteFromAssetPath","assetPath","ext","localePathResult","handleNextImageRequest","handleCatchallRenderRequest","handleCatchallMiddlewareRequest","normalizeAndAttachMetadata","enabledDirectories","prepared","preparedPromise","customErrorNo404Warn","execOnce","used","Log","quiet","conf","dev","minimalMode","experimentalTestProxy","serverOptions","loadEnvConfig","fetchHostname","formatHostname","isIPv6","publicDir","getPublicDir","hasStaticDir","getHasStaticDir","localeNormalizer","serverRuntimeConfig","publicRuntimeConfig","assetPrefix","getBuildId","NEXT_PRIVATE_MINIMAL_MODE","getEnabledDirectories","isAppPPREnabled","app","checkIsAppPPREnabled","ppr","isAppSegmentPrefetchEnabled","clientSegmentCache","nextFontManifest","getNextFontManifest","NEXT_DEPLOYMENT_ID","deploymentId","renderOpts","supportsDynamicResponse","canonicalBase","amp","previewProps","getPrerenderManifest","preview","ampOptimizerConfig","optimizer","images","optimizeCss","nextConfigOutput","output","nextScriptWorkers","disableOptimizedLoading","domainLocales","serverComponents","cacheLifeProfiles","cacheLife","enableTainting","taint","crossOrigin","largePageDataBytes","runtimeConfig","isExperimentalCompile","htmlLimitedBots","expireTime","staleTimes","clientTraceMetadata","cacheComponents","clientParamParsing","dynamicOnHover","inlineCss","authInterrupts","onInstrumentationRequestError","instrumentationOnRequestError","reactMaxHeadersLength","devtoolSegmentExplorer","setConfig","pagesManifest","getPagesManifest","appPathsManifest","getAppPathsManifest","appPathRoutes","getAppPathRoutes","interceptionRoutePatterns","getinterceptionRoutePatterns","getRouteMatchers","setAssetPrefix","responseCache","getResponseCache","ctx","instrumentation","onRequestError","handlerErr","logError","handleRequest","prepare","tracer","withPropagatedContext","SpanKind","attributes","span","handleRequestImpl","finally","isRSCRequest","setAttributes","setStatus","SpanStatusCode","setAttribute","rootSpanAttributes","getRootSpanAttributes","updateName","utils","middlewareValue","urlNoQuery","urlParts","cleanUrl","normalizeRepeatedSlashes","URLSearchParams","xForwardedProto","isHttps","socket","encrypted","remoteAddress","attachRequestMeta","parseUrlUtil","pathnameInfo","useMatchedPathHeader","matchedPath","fixMojibake","bytes","urlPathname","postponed","normalizedUrlPath","stripNextDataPath","localeAnalysisResult","srcPathname","pageIsDynamic","paramsResult","hasValidParams","getServerUtils","rewrites","caseSensitive","defaultRouteRegex","dynamicRouteMatcher","defaultRouteMatches","getNamedRouteRegex","getNamedParametrizedRoute","prefixRouteKeys","routeKey","fromCharCode","floor","hasInterceptionMarker","namedParameterizedRoute","namedRegex","handleRewrites","rewriteParams","fsPathname","checkRewrite","hasParams","stateHeader","getSelectedParams","currentTree","parallelRoute","isDynamicParameter","segmentValue","parseAndValidateFlightRouterState","state","assert","parsedDestination","destQuery","prepareDestination","destHostnameCompiler","newUrl","parseDestination","escaped","destHostname","destSearch","destPath","destParams","destPathParamKeys","destHostnameParamKeys","destPathCompiler","strOrArray","appendParamsToQuery","actualValue","nextInternalLocale","dynamicParams","beforeFiles","afterFiles","matchesPage","fsPathnameNoSlash","fallback","normalizeQueryParams","routeParamKeys","normalizedKey","getParamsFromRouteMatches","routeMatchesHeader","routeMatches","keyName","normalizeDynamicRouteParams","ignoreMissingOptional","defaultValue","isDefaultValue","defaultVal","val","normalizeCdnUrl","_parsedUrl","parseReqUrl","auth","urlObj","querystring","interpolateDynamicPath","paramValue","builtParam","replaceAll","getRoutesManifest","caseSensitiveRoutes","originQueryParams","pathnameBeforeRewrite","rewriteParamKeys","queryParams","didRewrite","matcherParams","curParamsResult","renderError","webServerConfig","incrementalCache","getIncrementalCache","requestHeaders","resetRequestCache","__incrementalCache","cacheHandlers","getCacheHandlers","cacheHandler","previouslyRevalidatedTags","receiveExpiredTags","invokePath","invokeStatus","invokeQuery","parsedMatchedPath","invokePathnameInfo","normalizeResult","bubble","run","NoFallbackError","getRequestHandlerWithMetadata","handler","getRequestHandler","loadInstrumentationModule","prepareImpl","normalizedPath","runImpl","pipe","partialContext","pipeImpl","botType","serveStreamingMetadata","shouldServeStreamingMetadata","userAgent","blockingMetadataUARegex","originalStatus","getStaticHTML","render","internalRender","renderImpl","getWaitUntil","builtinRequestContext","getBuiltinRequestContext","_globalThis","getInternalWaitUntil","customServer","hasPage","getBotType","renderToResponse","getStaticPaths","staticPaths","fallbackMode","parseFallbackField","fallbackField","dynamicRoutes","renderToResponseWithComponents","requestContext","findComponentsResult","renderToResponseWithComponentsImpl","pathCouldBeIntercepted","resolvedPathname","setVaryHeader","isAppPath","baseVaryHeader","addedNextUrlToVary","components","prerenderManifest","pathsResults","routeModule","isErrorPathname","is404Page","is500Page","hasServerProps","getServerSideProps","isPossibleServerAction","getServerActionRequestMetadata","actionId","isURLEncodedAction","isMultipartAction","isFetchAction","isSSG","getStaticProps","resolvedUrlPathname","hasFallback","isNextDataRequest","couldSupportPPR","hasDebugStaticShellQuery","__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING","__nextppronly","minimalPostponed","isRoutePPREnabled","renderingMode","Component","isBotRequest","isDomBotUA","isSupportedDocument","Document","getInitialProps","NEXT_BUILTIN_DOCUMENT","isDev","prerenderedRoutes","smallestFallbackRouteParams","fallbackRouteParams","parsedInitUrl","initPathname","ampValidator","ComponentMod","stripLocale","splitPath","getOriginalAppPaths","originalAppPath","renderPageComponent","bubbleNoFallback","findPageComponents","sriEnabled","sri","algorithm","shouldEnsure","setRootSpanAttribute","isNoFallbackError","renderToResponseImpl","initUrl","rewroteUrl","renderErrorToResponse","isWrappedError","renderToHTML","renderToHTMLImpl","setHeaders","renderErrorImpl","renderErrorToResponseImpl","statusPage","maybeFallbackError","renderToHtmlError","fallbackComponents","getFallbackErrorComponents","renderErrorToHTML","pagePathCache","getMaybePagePath","cacheKey","serverBuildPath","loadManifest","checkManifest","curPath","manifestNoLocales","getPagePath","requirePage","promises","interopDefault","default","ms","SERVER_ACTION_MANIFESTS_SINGLETON","loadManifestWithRetries","manifestPath","attempts","tryLoadManifestWithRetries","evalManifestWithRetries","evalManifest","tryLoadClientReferenceManifest","entryName","context","__RSC_MANIFEST","loadComponentsImpl","reactLoadableManifestPath","DocumentMod","AppMod","manifestLoadAttempts","hasClientManifest","isStaticMetadataRoute","isMetadataRouteFile","appDirRelativePath","pageExtensions","strictlyMatchExtensions","trailingMatcher","suffixMatcher","metadataRouteFilesRegex","normalizedAppDirRelativePath","buildManifest","reactLoadableManifest","dynamicCssManifest","clientReferenceManifest","serverActionsManifest","subresourceIntegrityManifest","SERVER_REFERENCE_MANIFEST","SUBRESOURCE_INTEGRITY_MANIFEST","setReferenceManifestsSingleton","serverModuleMap","clientReferenceManifestsPerPage","createServerModuleMap","_","id","pageName","workerEntry","workers","at","moduleId","async","chunks","App","pageConfig","loadComponents","wrap","getMiddlewareRouteMatcher","Batcher","cacheKeyFn","schedulerFn","pending","create","batch","scheduleOnNextTick","cb","nextTick","CachedRouteKind","IncrementalCacheKind","fromResponseCacheEntry","cacheEntry","html","pageData","rscData","segmentData","toResponseCacheEntry","isMiss","isStale","parsePositiveInt","envValue","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","batcher","isOnDemandRevalidate","revalidateBatcher","evictedInvocationIDs","compoundKey","extractInvocationID","separatorIndex","first","responseGenerator","hasResolved","previousCacheEntry","cachedItem","expiresAt","isFallback","isPrefetch","routeKind","_cacheKey","handleGet","previousIncrementalCacheEntry","resolved","routeKindToIncrementalCacheKind","incrementalResponseCacheEntry","handleRevalidate","responseCacheEntry","isRevalidating","min","max","MultiFileWriter","tasks","findOrCreateTask","directory","task","mkdir","filePath","writeFile","flatMap","FileSystemCache","flushToDisk","serverDistDir","revalidatedTags","maxMemoryCacheSize","memoryCache","getMemoryCache","revalidateTag","tags","tag","tagsManifest","getFilePath","fileData","readFile","mtime","stat","lastModified","getTime","fetchIdx","fetchUrl","parsedData","storedTags","fetchCache","maybeSegmentData","segmentPaths","segmentsDir","segmentDataFilePath","cacheTags","tagsHeader","combinedTags","softTags","htmlPath","buffer","IncrementalCache","fetchCacheKeyPrefix","CurCacheHandler","allowedRevalidateHeaderKeys","locks","hasCustomCacheHandler","cacheHandlersSymbol","globalCacheHandler","FetchCache","__NEXT_TEST_MAX_ISR_CACHE","disableForTestmode","NEXT_PRIVATE_TEST_PROXY","cacheControls","SharedCacheControls","_requestHeaders","calculateRevalidate","fromTime","timeOrigin","initialRevalidateSeconds","_getPathname","lock","generateCacheKey","bodyChunks","_ogBody","getReader","readableBody","total","arr","arrayBuffer","formData","text","blob","Blob","cacheString","createHash","update","cacheData","revalidateAfter","resumeDataCache","getRenderResumeDataCache","memoryCacheData","fetch","pendingRevalidatedTags","age","notFoundRoutes","prerenderResumeDataCache","getPrerenderResumeDataCache","itemSize","isImplicitBuildTimeCache","warningText","nodeFs","existsSync","readFileSync","f","d","recursive","MockedRequest","Stream","httpVersion","httpVersionMajor","httpVersionMinor","_target","bodyReadable","emit","headersDistinct","_read","connection","complete","trailers","trailersDistinct","rawTrailers","rawHeaders","MockedResponse","buffers","fromNodeOutgoingHttpHeaders","headPromise","headPromiseResolve","hasStreamed","resWriter","isSent","_implicitHeader","_write","_encoding","writeHead","getHeaderNames","strictContentLength","writeEarlyHints","assignSocket","detachSocket","writeContinue","writeProcessing","upgrading","chunkedEncoding","shouldKeepAlive","useChunkedEncodingByDefault","sendDate","addTrailers","formatDynamicImportPath","absoluteFilePath","pathToFileURL","AsyncCallbackSet","callbacks","runAll","allSettled","REACT_POSTPONE_TYPE","isPostpone","$$typeof","NodeModuleLoader","RouterServerContextSymbol","routerServerGlobal","dynamicImportEsmDefault","MiddlewareMatcherCache","NextNodeServer","BaseServer","cleanupListeners","relativeProjectDir","relative","edgeFunctionsPage","getEdgeFunctionsPages","runEdgeFunction","apiError","routePath","routerKind","routeType","revalidateReason","handleApiRequest","isMiddlewareInvoke","handleFinished","normalizedPathname","maybeDecodedPathname","bubblingResult","ensureMiddleware","runMiddleware","BubbledError","__NEXT_OPTIMIZE_CSS","__NEXT_SCRIPT_WORKERS","useSkewCookie","appDocumentPreloading","regex","setHttpClientAndAgentOptions","__NEXT_HTTP_AGENT","__NEXT_HTTP_AGENT_OPTIONS","httpAgentOptions","HttpAgent","__NEXT_HTTPS_AGENT","HttpsAgent","middlewareManifestPath","populateStaticEnv","staticEnv","getNextPublicEnvironmentVariables","defineEnv","getNextConfigEnv","isPrivateKey","hasNextRuntimeKey","configFileName","innerKey","removeUncaughtErrorAndRejectionListeners","removeAllListeners","unstable_preloadEntries","loadCustomCacheHandlers","patchFetch","webpackRequire","__next_app__","handleUpgrade","getInstrumentationModule","runInstrumentationHookIfAvailable","ensureInstrumentationRegistered","forceReload","silent","initializeCacheHandlers","DefaultCache","DefaultCacheHandler","RemoteCache","setCacheHandler","CacheHandler","getCacheFilesystem","cacheMaxMemorySize","routesManifest","buildIdFile","trim","runApi","renderHTML","renderHTMLImpl","imageOptimizer","edgeFunctionsPages","findPageComponentsImpl","_url","pagePaths","NEXT_FONT_MANIFEST","logErrorWithOriginalStack","_err","_type","ensurePage","_opts","normalizeReq","normalizeRes","makeRequestHandler","revalidateHeaders","mocked","createRequestResponseMocks","unstable_onlyGenerated","internal","is404","getMiddlewareManifest","middlewareModule","loadNodeMiddleware","originalSource","getMiddlewareMatcher","stored","functions","getEdgeFunctionInfo","foundPage","pageInfo","files","wasm","binding","assets","hasMiddleware","nodeMiddleware","ensureEdgeFunction","_params","_cachedPreviewManifest","isUpgradeReq","trustHostHeader","bodySizeLimit","middlewareClientMaxBodySize","getCloneableBody","sizeLimit","buffered","endPromise","finalize","replaceRequestBody","cloneBodyStream","p1","PassThrough","p2","bytesRead","limitExceeded","urlInfo","_serverDistDir","onServerClose","listener","internalWaitUntil","createInternalWaitUntil"],"mappings":"oJAWA,IAAI,EAAqBA,OAAO,GAAG,CAAC,8BAClC,EAAoBA,OAAO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,OAAuB,CAC3B,MAAM,IAAI,CAAC2gD,gBAAgB,CAACZ,MAAM,EACpC,CAEUzW,sBAAkC,CAE1C,OADA,IAAI,CAACqf,iBAAiB,GAAK,IAAI,CAACC,uBAAuB,GAChD,IAAI,CAACD,iBAAiB,AAC/B,CAEQC,yBAA0B,CAE9B,MAAM,qBAEL,CAFK,IAAIrgD,EACR,kEADI,qB,MAAA,O,WAAA,G,aAAA,EAEN,EASJ,CACF,C","ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195]}