| "use strict"; |
| Object.defineProperty(exports, "__esModule", { |
| value: true |
| }); |
| 0 && (module.exports = { |
| WrappedBuildError: null, |
| default: null |
| }); |
| function _export(target, all) { |
| for(var name in all)Object.defineProperty(target, name, { |
| enumerable: true, |
| get: all[name] |
| }); |
| } |
| _export(exports, { |
| WrappedBuildError: function() { |
| return WrappedBuildError; |
| }, |
| default: function() { |
| return Server; |
| } |
| }); |
| const _utils = require("../shared/lib/utils"); |
| const _url = require("url"); |
| const _formathostname = require("./lib/format-hostname"); |
| const _constants = require("../shared/lib/constants"); |
| const _utils1 = require("../shared/lib/router/utils"); |
| const _runtimeconfigexternal = require("../shared/lib/runtime-config.external"); |
| const _utils2 = require("./utils"); |
| const _isbot = require("../shared/lib/router/utils/is-bot"); |
| const _renderresult = _interop_require_default(require("./render-result")); |
| const _removetrailingslash = require("../shared/lib/router/utils/remove-trailing-slash"); |
| const _denormalizepagepath = require("../shared/lib/page-path/denormalize-page-path"); |
| const _log = _interop_require_wildcard(require("../build/output/log")); |
| const _serverutils = require("./server-utils"); |
| const _iserror = _interop_require_wildcard(require("../lib/is-error")); |
| const _requestmeta = require("./request-meta"); |
| const _removepathprefix = require("../shared/lib/router/utils/remove-path-prefix"); |
| const _apppaths = require("../shared/lib/router/utils/app-paths"); |
| const _gethostname = require("../shared/lib/get-hostname"); |
| const _parseurl = require("../shared/lib/router/utils/parse-url"); |
| const _getnextpathnameinfo = require("../shared/lib/router/utils/get-next-pathname-info"); |
| const _approuterheaders = require("../client/components/app-router-headers"); |
| const _localeroutenormalizer = require("./normalizers/locale-route-normalizer"); |
| const _defaultroutematchermanager = require("./route-matcher-managers/default-route-matcher-manager"); |
| const _apppageroutematcherprovider = require("./route-matcher-providers/app-page-route-matcher-provider"); |
| const _approuteroutematcherprovider = require("./route-matcher-providers/app-route-route-matcher-provider"); |
| const _pagesapiroutematcherprovider = require("./route-matcher-providers/pages-api-route-matcher-provider"); |
| const _pagesroutematcherprovider = require("./route-matcher-providers/pages-route-matcher-provider"); |
| const _servermanifestloader = require("./route-matcher-providers/helpers/manifest-loaders/server-manifest-loader"); |
| const _tracer = require("./lib/trace/tracer"); |
| const _constants1 = require("./lib/trace/constants"); |
| const _i18nprovider = require("./lib/i18n-provider"); |
| const _sendresponse = require("./send-response"); |
| const _utils3 = require("./web/utils"); |
| const _constants2 = require("../lib/constants"); |
| const _normalizelocalepath = require("../shared/lib/i18n/normalize-locale-path"); |
| const _matchnextdatapathname = require("./lib/match-next-data-pathname"); |
| const _getroutefromassetpath = _interop_require_default(require("../shared/lib/router/utils/get-route-from-asset-path")); |
| const _rsc = require("./normalizers/request/rsc"); |
| const _stripflightheaders = require("./app-render/strip-flight-headers"); |
| const _checks = require("./route-modules/checks"); |
| const _prefetchrsc = require("./normalizers/request/prefetch-rsc"); |
| const _nextdata = require("./normalizers/request/next-data"); |
| const _serveractionrequestmeta = require("./lib/server-action-request-meta"); |
| const _interceptionroutes = require("../shared/lib/router/utils/interception-routes"); |
| const _toroute = require("./lib/to-route"); |
| const _helpers = require("./base-http/helpers"); |
| const _patchsetheader = require("./lib/patch-set-header"); |
| const _ppr = require("./lib/experimental/ppr"); |
| const _builtinrequestcontext = require("./after/builtin-request-context"); |
| const _adapter = require("./web/adapter"); |
| const _fallback = require("../lib/fallback"); |
| const _segmentprefixrsc = require("./normalizers/request/segment-prefix-rsc"); |
| const _streamingmetadata = require("./lib/streaming-metadata"); |
| const _decodequerypathparameter = require("./lib/decode-query-path-parameter"); |
| const _nofallbackerrorexternal = require("../shared/lib/no-fallback-error.external"); |
| const _handlers = require("./use-cache/handlers"); |
| const _fixmojibake = require("./lib/fix-mojibake"); |
| const _cachebustingsearchparam = require("../shared/lib/router/utils/cache-busting-search-param"); |
| const _setcachebustingsearchparam = require("../client/components/router-reducer/set-cache-busting-search-param"); |
| function _interop_require_default(obj) { |
| return obj && obj.__esModule ? obj : { |
| default: obj |
| }; |
| } |
| function _getRequireWildcardCache(nodeInterop) { |
| if (typeof WeakMap !== "function") return null; |
| var cacheBabelInterop = new WeakMap(); |
| var cacheNodeInterop = new WeakMap(); |
| return (_getRequireWildcardCache = function(nodeInterop) { |
| return nodeInterop ? cacheNodeInterop : cacheBabelInterop; |
| })(nodeInterop); |
| } |
| function _interop_require_wildcard(obj, nodeInterop) { |
| if (!nodeInterop && obj && obj.__esModule) { |
| return obj; |
| } |
| if (obj === null || typeof obj !== "object" && typeof obj !== "function") { |
| return { |
| default: obj |
| }; |
| } |
| var cache = _getRequireWildcardCache(nodeInterop); |
| if (cache && cache.has(obj)) { |
| return cache.get(obj); |
| } |
| var newObj = { |
| __proto__: null |
| }; |
| var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; |
| for(var key in obj){ |
| if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { |
| var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; |
| if (desc && (desc.get || desc.set)) { |
| Object.defineProperty(newObj, key, desc); |
| } else { |
| newObj[key] = obj[key]; |
| } |
| } |
| } |
| newObj.default = obj; |
| if (cache) { |
| cache.set(obj, newObj); |
| } |
| return newObj; |
| } |
| class WrappedBuildError extends Error { |
| constructor(innerError){ |
| super(); |
| this.innerError = innerError; |
| } |
| } |
| class Server { |
| getServerComponentsHmrCache() { |
| return this.nextConfig.experimental.serverComponentsHmrCache ? globalThis.__serverComponentsHmrCache : undefined; |
| } |
| |
| |
| |
| |
| constructor(options){ |
| var _this_nextConfig_i18n, _this_nextConfig_experimental_amp, _this_nextConfig_i18n1; |
| this.handleRSCRequest = (req, _res, parsedUrl)=>{ |
| var _this_normalizers_segmentPrefetchRSC, _this_normalizers_prefetchRSC, _this_normalizers_rsc; |
| if (!parsedUrl.pathname) return false; |
| if ((_this_normalizers_segmentPrefetchRSC = this.normalizers.segmentPrefetchRSC) == null ? void 0 : _this_normalizers_segmentPrefetchRSC.match(parsedUrl.pathname)) { |
| const result = this.normalizers.segmentPrefetchRSC.extract(parsedUrl.pathname); |
| if (!result) return false; |
| const { originalPathname, segmentPath } = result; |
| parsedUrl.pathname = originalPathname; |
| |
| req.headers[_approuterheaders.RSC_HEADER] = '1'; |
| req.headers[_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER] = '1'; |
| req.headers[_approuterheaders.NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] = segmentPath; |
| (0, _requestmeta.addRequestMeta)(req, 'isRSCRequest', true); |
| (0, _requestmeta.addRequestMeta)(req, 'isPrefetchRSCRequest', true); |
| (0, _requestmeta.addRequestMeta)(req, 'segmentPrefetchRSCRequest', segmentPath); |
| } else if ((_this_normalizers_prefetchRSC = this.normalizers.prefetchRSC) == null ? void 0 : _this_normalizers_prefetchRSC.match(parsedUrl.pathname)) { |
| parsedUrl.pathname = this.normalizers.prefetchRSC.normalize(parsedUrl.pathname, true); |
| |
| req.headers[_approuterheaders.RSC_HEADER] = '1'; |
| req.headers[_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER] = '1'; |
| (0, _requestmeta.addRequestMeta)(req, 'isRSCRequest', true); |
| (0, _requestmeta.addRequestMeta)(req, 'isPrefetchRSCRequest', true); |
| } else if ((_this_normalizers_rsc = this.normalizers.rsc) == null ? void 0 : _this_normalizers_rsc.match(parsedUrl.pathname)) { |
| parsedUrl.pathname = this.normalizers.rsc.normalize(parsedUrl.pathname, true); |
| |
| req.headers[_approuterheaders.RSC_HEADER] = '1'; |
| (0, _requestmeta.addRequestMeta)(req, 'isRSCRequest', true); |
| } else if (req.headers['x-now-route-matches']) { |
| |
| |
| |
| |
| |
| (0, _stripflightheaders.stripFlightHeaders)(req.headers); |
| return false; |
| } else if (req.headers[_approuterheaders.RSC_HEADER] === '1') { |
| (0, _requestmeta.addRequestMeta)(req, 'isRSCRequest', true); |
| if (req.headers[_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER] === '1') { |
| (0, _requestmeta.addRequestMeta)(req, 'isPrefetchRSCRequest', true); |
| const segmentPrefetchRSCRequest = req.headers[_approuterheaders.NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]; |
| if (typeof segmentPrefetchRSCRequest === 'string') { |
| (0, _requestmeta.addRequestMeta)(req, 'segmentPrefetchRSCRequest', segmentPrefetchRSCRequest); |
| } |
| } |
| } else { |
| |
| return false; |
| } |
| if (req.url) { |
| const parsed = (0, _url.parse)(req.url); |
| parsed.pathname = parsedUrl.pathname; |
| req.url = (0, _url.format)(parsed); |
| } |
| return false; |
| }; |
| this.handleNextDataRequest = async (req, res, parsedUrl)=>{ |
| const middleware = await this.getMiddleware(); |
| const params = (0, _matchnextdatapathname.matchNextDataPathname)(parsedUrl.pathname); |
| |
| if (!params || !params.path) { |
| return false; |
| } |
| if (params.path[0] !== this.buildId) { |
| |
| if ((0, _requestmeta.getRequestMeta)(req, 'middlewareInvoke')) { |
| return false; |
| } |
| |
| await this.render404(req, res, parsedUrl); |
| return true; |
| } |
| |
| params.path.shift(); |
| const lastParam = params.path[params.path.length - 1]; |
| |
| if (typeof lastParam !== 'string' || !lastParam.endsWith('.json')) { |
| await this.render404(req, res, parsedUrl); |
| return true; |
| } |
| |
| let pathname = `/${params.path.join('/')}`; |
| pathname = (0, _getroutefromassetpath.default)(pathname, '.json'); |
| |
| if (middleware) { |
| if (this.nextConfig.trailingSlash && !pathname.endsWith('/')) { |
| pathname += '/'; |
| } |
| if (!this.nextConfig.trailingSlash && pathname.length > 1 && pathname.endsWith('/')) { |
| pathname = pathname.substring(0, pathname.length - 1); |
| } |
| } |
| if (this.i18nProvider) { |
| var _req_headers_host; |
| |
| const hostname = req == null ? void 0 : (_req_headers_host = req.headers.host) == null ? void 0 : _req_headers_host.split(':', 1)[0].toLowerCase(); |
| const domainLocale = this.i18nProvider.detectDomainLocale(hostname); |
| const defaultLocale = (domainLocale == null ? void 0 : domainLocale.defaultLocale) ?? this.i18nProvider.config.defaultLocale; |
| const localePathResult = this.i18nProvider.analyze(pathname); |
| |
| |
| if (localePathResult.detectedLocale) { |
| pathname = localePathResult.pathname; |
| } |
| |
| (0, _requestmeta.addRequestMeta)(req, 'locale', localePathResult.detectedLocale); |
| (0, _requestmeta.addRequestMeta)(req, 'defaultLocale', defaultLocale); |
| |
| |
| if (!localePathResult.detectedLocale) { |
| (0, _requestmeta.removeRequestMeta)(req, 'localeInferredFromDefault'); |
| } |
| |
| |
| if (!localePathResult.detectedLocale && !middleware) { |
| (0, _requestmeta.addRequestMeta)(req, 'locale', defaultLocale); |
| await this.render404(req, res, parsedUrl); |
| return true; |
| } |
| } |
| parsedUrl.pathname = pathname; |
| (0, _requestmeta.addRequestMeta)(req, 'isNextDataReq', true); |
| return false; |
| }; |
| this.handleNextImageRequest = ()=>false; |
| this.handleCatchallRenderRequest = ()=>false; |
| this.handleCatchallMiddlewareRequest = ()=>false; |
| |
| |
| |
| |
| |
| |
| this.normalize = (pathname)=>{ |
| const normalizers = []; |
| if (this.normalizers.data) { |
| normalizers.push(this.normalizers.data); |
| } |
| |
| |
| if (this.normalizers.segmentPrefetchRSC) { |
| normalizers.push(this.normalizers.segmentPrefetchRSC); |
| } |
| |
| |
| if (this.normalizers.prefetchRSC) { |
| normalizers.push(this.normalizers.prefetchRSC); |
| } |
| if (this.normalizers.rsc) { |
| normalizers.push(this.normalizers.rsc); |
| } |
| for (const normalizer of normalizers){ |
| if (!normalizer.match(pathname)) continue; |
| return normalizer.normalize(pathname, true); |
| } |
| return pathname; |
| }; |
| this.normalizeAndAttachMetadata = async (req, res, url)=>{ |
| let finished = await this.handleNextImageRequest(req, res, url); |
| if (finished) return true; |
| if (this.enabledDirectories.pages) { |
| finished = await this.handleNextDataRequest(req, res, url); |
| if (finished) return true; |
| } |
| return false; |
| }; |
| this.prepared = false; |
| this.preparedPromise = null; |
| this.customErrorNo404Warn = (0, _utils.execOnce)(()=>{ |
| _log.warn(`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`); |
| }); |
| const { dir = '.', quiet = false, conf, dev = false, minimalMode = false, hostname, port, experimentalTestProxy } = options; |
| this.experimentalTestProxy = experimentalTestProxy; |
| this.serverOptions = options; |
| this.dir = require('path').resolve(dir); |
| this.quiet = quiet; |
| this.loadEnvConfig({ |
| dev |
| }); |
| |
| |
| this.nextConfig = conf; |
| this.hostname = hostname; |
| if (this.hostname) { |
| |
| this.fetchHostname = (0, _formathostname.formatHostname)(this.hostname); |
| } |
| this.port = port; |
| this.distDir = require('path').join(this.dir, this.nextConfig.distDir); |
| this.publicDir = this.getPublicDir(); |
| this.hasStaticDir = !minimalMode && this.getHasStaticDir(); |
| this.i18nProvider = ((_this_nextConfig_i18n = this.nextConfig.i18n) == null ? void 0 : _this_nextConfig_i18n.locales) ? new _i18nprovider.I18NProvider(this.nextConfig.i18n) : undefined; |
| |
| this.localeNormalizer = this.i18nProvider ? new _localeroutenormalizer.LocaleRouteNormalizer(this.i18nProvider) : undefined; |
| |
| |
| const { serverRuntimeConfig = {}, publicRuntimeConfig, assetPrefix, generateEtags } = this.nextConfig; |
| this.buildId = this.getBuildId(); |
| |
| |
| const minimalModeKey = 'minimalMode'; |
| this[minimalModeKey] = minimalMode || !!process.env.NEXT_PRIVATE_MINIMAL_MODE; |
| this.enabledDirectories = this.getEnabledDirectories(dev); |
| this.isAppPPREnabled = this.enabledDirectories.app && (0, _ppr.checkIsAppPPREnabled)(this.nextConfig.experimental.ppr); |
| this.isAppSegmentPrefetchEnabled = this.enabledDirectories.app && this.nextConfig.experimental.clientSegmentCache === true; |
| this.normalizers = { |
| |
| |
| |
| rsc: this.enabledDirectories.app && this.minimalMode ? new _rsc.RSCPathnameNormalizer() : undefined, |
| prefetchRSC: this.isAppPPREnabled && this.minimalMode ? new _prefetchrsc.PrefetchRSCPathnameNormalizer() : undefined, |
| segmentPrefetchRSC: this.isAppSegmentPrefetchEnabled && this.minimalMode ? new _segmentprefixrsc.SegmentPrefixRSCPathnameNormalizer() : undefined, |
| data: this.enabledDirectories.pages ? new _nextdata.NextDataPathnameNormalizer(this.buildId) : undefined |
| }; |
| this.nextFontManifest = this.getNextFontManifest(); |
| process.env.NEXT_DEPLOYMENT_ID = this.nextConfig.deploymentId || ''; |
| this.renderOpts = { |
| dir: this.dir, |
| supportsDynamicResponse: true, |
| trailingSlash: this.nextConfig.trailingSlash, |
| deploymentId: this.nextConfig.deploymentId, |
| poweredByHeader: this.nextConfig.poweredByHeader, |
| canonicalBase: this.nextConfig.amp.canonicalBase || '', |
| generateEtags, |
| previewProps: this.getPrerenderManifest().preview, |
| ampOptimizerConfig: (_this_nextConfig_experimental_amp = this.nextConfig.experimental.amp) == null ? void 0 : _this_nextConfig_experimental_amp.optimizer, |
| basePath: this.nextConfig.basePath, |
| images: this.nextConfig.images, |
| optimizeCss: this.nextConfig.experimental.optimizeCss, |
| nextConfigOutput: this.nextConfig.output, |
| nextScriptWorkers: this.nextConfig.experimental.nextScriptWorkers, |
| disableOptimizedLoading: this.nextConfig.experimental.disableOptimizedLoading, |
| domainLocales: (_this_nextConfig_i18n1 = this.nextConfig.i18n) == null ? void 0 : _this_nextConfig_i18n1.domains, |
| distDir: this.distDir, |
| serverComponents: this.enabledDirectories.app, |
| cacheLifeProfiles: this.nextConfig.experimental.cacheLife, |
| enableTainting: this.nextConfig.experimental.taint, |
| crossOrigin: this.nextConfig.crossOrigin ? this.nextConfig.crossOrigin : undefined, |
| largePageDataBytes: this.nextConfig.experimental.largePageDataBytes, |
| |
| |
| runtimeConfig: Object.keys(publicRuntimeConfig).length > 0 ? publicRuntimeConfig : undefined, |
| isExperimentalCompile: this.nextConfig.experimental.isExperimentalCompile, |
| |
| htmlLimitedBots: this.nextConfig.htmlLimitedBots, |
| experimental: { |
| expireTime: this.nextConfig.expireTime, |
| staleTimes: this.nextConfig.experimental.staleTimes, |
| clientTraceMetadata: this.nextConfig.experimental.clientTraceMetadata, |
| cacheComponents: this.nextConfig.experimental.cacheComponents ?? false, |
| clientSegmentCache: this.nextConfig.experimental.clientSegmentCache === 'client-only' ? 'client-only' : Boolean(this.nextConfig.experimental.clientSegmentCache), |
| clientParamParsing: this.nextConfig.experimental.clientParamParsing ?? false, |
| dynamicOnHover: this.nextConfig.experimental.dynamicOnHover ?? false, |
| inlineCss: this.nextConfig.experimental.inlineCss ?? false, |
| authInterrupts: !!this.nextConfig.experimental.authInterrupts |
| }, |
| onInstrumentationRequestError: this.instrumentationOnRequestError.bind(this), |
| reactMaxHeadersLength: this.nextConfig.reactMaxHeadersLength, |
| devtoolSegmentExplorer: this.nextConfig.experimental.devtoolSegmentExplorer |
| }; |
| |
| (0, _runtimeconfigexternal.setConfig)({ |
| serverRuntimeConfig, |
| publicRuntimeConfig |
| }); |
| this.pagesManifest = this.getPagesManifest(); |
| this.appPathsManifest = this.getAppPathsManifest(); |
| this.appPathRoutes = this.getAppPathRoutes(); |
| this.interceptionRoutePatterns = this.getinterceptionRoutePatterns(); |
| |
| this.matchers = this.getRouteMatchers(); |
| |
| |
| |
| void this.matchers.reload(); |
| this.setAssetPrefix(assetPrefix); |
| this.responseCache = this.getResponseCache({ |
| dev |
| }); |
| } |
| getRouteMatchers() { |
| |
| const manifestLoader = new _servermanifestloader.ServerManifestLoader((name)=>{ |
| switch(name){ |
| case _constants.PAGES_MANIFEST: |
| return this.getPagesManifest() ?? null; |
| case _constants.APP_PATHS_MANIFEST: |
| return this.getAppPathsManifest() ?? null; |
| default: |
| return null; |
| } |
| }); |
| |
| const matchers = new _defaultroutematchermanager.DefaultRouteMatcherManager(); |
| |
| matchers.push(new _pagesroutematcherprovider.PagesRouteMatcherProvider(this.distDir, manifestLoader, this.i18nProvider)); |
| |
| matchers.push(new _pagesapiroutematcherprovider.PagesAPIRouteMatcherProvider(this.distDir, manifestLoader, this.i18nProvider)); |
| |
| if (this.enabledDirectories.app) { |
| |
| matchers.push(new _apppageroutematcherprovider.AppPageRouteMatcherProvider(this.distDir, manifestLoader)); |
| matchers.push(new _approuteroutematcherprovider.AppRouteRouteMatcherProvider(this.distDir, manifestLoader)); |
| } |
| return matchers; |
| } |
| async instrumentationOnRequestError(...args) { |
| const [err, req, ctx] = args; |
| if (this.instrumentation) { |
| try { |
| await (this.instrumentation.onRequestError == null ? void 0 : this.instrumentation.onRequestError.call(this.instrumentation, err, { |
| path: req.url || '', |
| method: req.method || 'GET', |
| |
| headers: req instanceof _adapter.NextRequestHint ? Object.fromEntries(req.headers.entries()) : req.headers |
| }, ctx)); |
| } catch (handlerErr) { |
| |
| console.error('Error in instrumentation.onRequestError:', handlerErr); |
| } |
| } |
| } |
| logError(err) { |
| if (this.quiet) return; |
| _log.error(err); |
| } |
| async handleRequest(req, res, parsedUrl) { |
| await this.prepare(); |
| const method = req.method.toUpperCase(); |
| const tracer = (0, _tracer.getTracer)(); |
| return tracer.withPropagatedContext(req.headers, ()=>{ |
| return tracer.trace(_constants1.BaseServerSpan.handleRequest, { |
| spanName: `${method} ${req.url}`, |
| kind: _tracer.SpanKind.SERVER, |
| attributes: { |
| 'http.method': method, |
| 'http.target': req.url |
| } |
| }, async (span)=>this.handleRequestImpl(req, res, parsedUrl).finally(()=>{ |
| if (!span) return; |
| const isRSCRequest = (0, _requestmeta.getRequestMeta)(req, 'isRSCRequest') ?? false; |
| span.setAttributes({ |
| 'http.status_code': res.statusCode, |
| 'next.rsc': isRSCRequest |
| }); |
| if (res.statusCode && res.statusCode >= 500) { |
| |
| |
| span.setStatus({ |
| code: _tracer.SpanStatusCode.ERROR |
| }); |
| |
| span.setAttribute('error.type', res.statusCode.toString()); |
| } |
| const rootSpanAttributes = tracer.getRootSpanAttributes(); |
| |
| if (!rootSpanAttributes) return; |
| if (rootSpanAttributes.get('next.span_type') !== _constants1.BaseServerSpan.handleRequest) { |
| console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`); |
| return; |
| } |
| const route = rootSpanAttributes.get('next.route'); |
| if (route) { |
| const name = isRSCRequest ? `RSC ${method} ${route}` : `${method} ${route}`; |
| span.setAttributes({ |
| 'next.route': route, |
| 'http.route': route, |
| 'next.span_name': name |
| }); |
| span.updateName(name); |
| } else { |
| span.updateName(isRSCRequest ? `RSC ${method} ${req.url}` : `${method} ${req.url}`); |
| } |
| })); |
| }); |
| } |
| async handleRequestImpl(req, res, parsedUrl) { |
| try { |
| var _originalRequest_socket, _originalRequest_socket1, _this_i18nProvider, _this_nextConfig_i18n; |
| |
| await this.matchers.waitTillReady(); |
| |
| |
| (0, _patchsetheader.patchSetHeaderWithCookieSupport)(req, (0, _helpers.isNodeNextResponse)(res) ? res.originalResponse : res); |
| const urlParts = (req.url || '').split('?', 1); |
| const urlNoQuery = urlParts[0]; |
| |
| |
| |
| |
| if (urlNoQuery == null ? void 0 : urlNoQuery.match(/(\\|\/\/)/)) { |
| const cleanUrl = (0, _utils.normalizeRepeatedSlashes)(req.url); |
| res.redirect(cleanUrl, 308).body(cleanUrl).send(); |
| return; |
| } |
| |
| if (!parsedUrl || typeof parsedUrl !== 'object') { |
| if (!req.url) { |
| throw Object.defineProperty(new Error('Invariant: url can not be undefined'), "__NEXT_ERROR_CODE", { |
| value: "E123", |
| enumerable: false, |
| configurable: true |
| }); |
| } |
| parsedUrl = (0, _url.parse)(req.url, true); |
| } |
| if (!parsedUrl.pathname) { |
| throw Object.defineProperty(new Error("Invariant: pathname can't be empty"), "__NEXT_ERROR_CODE", { |
| value: "E412", |
| enumerable: false, |
| configurable: true |
| }); |
| } |
| |
| if (typeof parsedUrl.query === 'string') { |
| parsedUrl.query = Object.fromEntries(new URLSearchParams(parsedUrl.query)); |
| } |
| |
| const { originalRequest = null } = (0, _helpers.isNodeNextRequest)(req) ? req : {}; |
| const xForwardedProto = originalRequest == null ? void 0 : originalRequest.headers['x-forwarded-proto']; |
| const isHttps = xForwardedProto ? xForwardedProto === 'https' : !!(originalRequest == null ? void 0 : (_originalRequest_socket = originalRequest.socket) == null ? void 0 : _originalRequest_socket.encrypted); |
| req.headers['x-forwarded-host'] ??= req.headers['host'] ?? this.hostname; |
| req.headers['x-forwarded-port'] ??= this.port ? this.port.toString() : isHttps ? '443' : '80'; |
| req.headers['x-forwarded-proto'] ??= isHttps ? 'https' : 'http'; |
| req.headers['x-forwarded-for'] ??= originalRequest == null ? void 0 : (_originalRequest_socket1 = originalRequest.socket) == null ? void 0 : _originalRequest_socket1.remoteAddress; |
| |
| |
| this.attachRequestMeta(req, parsedUrl); |
| let finished = await this.handleRSCRequest(req, res, parsedUrl); |
| if (finished) return; |
| const domainLocale = (_this_i18nProvider = this.i18nProvider) == null ? void 0 : _this_i18nProvider.detectDomainLocale((0, _gethostname.getHostname)(parsedUrl, req.headers)); |
| const defaultLocale = (domainLocale == null ? void 0 : domainLocale.defaultLocale) || ((_this_nextConfig_i18n = this.nextConfig.i18n) == null ? void 0 : _this_nextConfig_i18n.defaultLocale); |
| (0, _requestmeta.addRequestMeta)(req, 'defaultLocale', defaultLocale); |
| const url = (0, _parseurl.parseUrl)(req.url.replace(/^\/+/, '/')); |
| const pathnameInfo = (0, _getnextpathnameinfo.getNextPathnameInfo)(url.pathname, { |
| nextConfig: this.nextConfig, |
| i18nProvider: this.i18nProvider |
| }); |
| url.pathname = pathnameInfo.pathname; |
| if (pathnameInfo.basePath) { |
| req.url = (0, _removepathprefix.removePathPrefix)(req.url, this.nextConfig.basePath); |
| } |
| const useMatchedPathHeader = this.minimalMode && typeof req.headers[_constants2.MATCHED_PATH_HEADER] === 'string'; |
| |
| if (useMatchedPathHeader) { |
| try { |
| var _this_normalizers_data, _this_i18nProvider1, _this_getRoutesManifest; |
| if (this.enabledDirectories.app) { |
| |
| |
| if (req.url.match(/^\/index($|\?)/)) { |
| req.url = req.url.replace(/^\/index/, '/'); |
| } |
| parsedUrl.pathname = parsedUrl.pathname === '/index' ? '/' : parsedUrl.pathname; |
| } |
| |
| |
| let { pathname: matchedPath } = new URL((0, _fixmojibake.fixMojibake)(req.headers[_constants2.MATCHED_PATH_HEADER]), 'http://localhost'); |
| let { pathname: urlPathname } = new URL(req.url, 'http://localhost'); |
| |
| |
| |
| if ((_this_normalizers_data = this.normalizers.data) == null ? void 0 : _this_normalizers_data.match(urlPathname)) { |
| (0, _requestmeta.addRequestMeta)(req, 'isNextDataReq', true); |
| } else if (this.isAppPPREnabled && this.minimalMode && req.headers[_constants2.NEXT_RESUME_HEADER] === '1' && req.method === 'POST') { |
| |
| |
| |
| const body = []; |
| for await (const chunk of req.body){ |
| body.push(chunk); |
| } |
| const postponed = Buffer.concat(body).toString('utf8'); |
| (0, _requestmeta.addRequestMeta)(req, 'postponed', postponed); |
| } |
| matchedPath = this.normalize(matchedPath); |
| const normalizedUrlPath = this.stripNextDataPath(urlPathname); |
| matchedPath = (0, _denormalizepagepath.denormalizePagePath)(matchedPath); |
| |
| const localeAnalysisResult = (_this_i18nProvider1 = this.i18nProvider) == null ? void 0 : _this_i18nProvider1.analyze(matchedPath, { |
| defaultLocale |
| }); |
| |
| |
| |
| if (localeAnalysisResult) { |
| (0, _requestmeta.addRequestMeta)(req, 'locale', localeAnalysisResult.detectedLocale); |
| |
| |
| if (localeAnalysisResult.inferredFromDefault) { |
| (0, _requestmeta.addRequestMeta)(req, 'localeInferredFromDefault', true); |
| } else { |
| (0, _requestmeta.removeRequestMeta)(req, 'localeInferredFromDefault'); |
| } |
| } |
| let srcPathname = matchedPath; |
| let pageIsDynamic = (0, _utils1.isDynamicRoute)(srcPathname); |
| let paramsResult = { |
| params: false, |
| hasValidParams: false |
| }; |
| if (!pageIsDynamic) { |
| const match = await this.matchers.match(srcPathname, { |
| i18n: localeAnalysisResult |
| }); |
| |
| if (match) { |
| srcPathname = match.definition.pathname; |
| |
| |
| |
| if (typeof match.params !== 'undefined') { |
| pageIsDynamic = true; |
| paramsResult.params = match.params; |
| paramsResult.hasValidParams = true; |
| } |
| } |
| } |
| |
| |
| |
| if (localeAnalysisResult) { |
| matchedPath = localeAnalysisResult.pathname; |
| } |
| const utils = (0, _serverutils.getServerUtils)({ |
| pageIsDynamic, |
| page: srcPathname, |
| i18n: this.nextConfig.i18n, |
| basePath: this.nextConfig.basePath, |
| rewrites: ((_this_getRoutesManifest = this.getRoutesManifest()) == null ? void 0 : _this_getRoutesManifest.rewrites) || { |
| beforeFiles: [], |
| afterFiles: [], |
| fallback: [] |
| }, |
| caseSensitive: !!this.nextConfig.experimental.caseSensitiveRoutes |
| }); |
| |
| |
| if (defaultLocale && !pathnameInfo.locale) { |
| parsedUrl.pathname = `/${defaultLocale}${parsedUrl.pathname}`; |
| } |
| |
| |
| const originQueryParams = { |
| ...parsedUrl.query |
| }; |
| const pathnameBeforeRewrite = parsedUrl.pathname; |
| const rewriteParamKeys = Object.keys(utils.handleRewrites(req, parsedUrl)); |
| |
| |
| |
| const queryParams = { |
| ...parsedUrl.query |
| }; |
| const didRewrite = pathnameBeforeRewrite !== parsedUrl.pathname; |
| if (didRewrite && parsedUrl.pathname) { |
| (0, _requestmeta.addRequestMeta)(req, 'rewroteURL', parsedUrl.pathname); |
| } |
| const routeParamKeys = new Set(); |
| for (const [key, value] of Object.entries(parsedUrl.query)){ |
| const normalizedKey = (0, _utils3.normalizeNextQueryParam)(key); |
| if (!normalizedKey) continue; |
| |
| |
| delete parsedUrl.query[key]; |
| routeParamKeys.add(normalizedKey); |
| if (typeof value === 'undefined') continue; |
| queryParams[normalizedKey] = Array.isArray(value) ? value.map((v)=>(0, _decodequerypathparameter.decodeQueryPathParameter)(v)) : (0, _decodequerypathparameter.decodeQueryPathParameter)(value); |
| } |
| |
| if (pageIsDynamic) { |
| let params = {}; |
| |
| |
| if (!paramsResult.hasValidParams) { |
| paramsResult = utils.normalizeDynamicRouteParams(queryParams, false); |
| } |
| |
| |
| |
| |
| if (!paramsResult.hasValidParams && !(0, _utils1.isDynamicRoute)(normalizedUrlPath)) { |
| let matcherParams = utils.dynamicRouteMatcher == null ? void 0 : utils.dynamicRouteMatcher.call(utils, normalizedUrlPath); |
| if (matcherParams) { |
| utils.normalizeDynamicRouteParams(matcherParams, false); |
| Object.assign(paramsResult.params, matcherParams); |
| paramsResult.hasValidParams = true; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| if ( |
| matchedPath !== '/index' && !paramsResult.hasValidParams && !(0, _utils1.isDynamicRoute)(matchedPath)) { |
| let matcherParams = utils.dynamicRouteMatcher == null ? void 0 : utils.dynamicRouteMatcher.call(utils, matchedPath); |
| if (matcherParams) { |
| const curParamsResult = utils.normalizeDynamicRouteParams(matcherParams, false); |
| if (curParamsResult.hasValidParams) { |
| Object.assign(params, matcherParams); |
| paramsResult = curParamsResult; |
| } |
| } |
| } |
| if (paramsResult.hasValidParams) { |
| params = paramsResult.params; |
| } |
| const routeMatchesHeader = req.headers['x-now-route-matches']; |
| if (typeof routeMatchesHeader === 'string' && routeMatchesHeader && (0, _utils1.isDynamicRoute)(matchedPath) && !paramsResult.hasValidParams) { |
| const routeMatches = utils.getParamsFromRouteMatches(routeMatchesHeader); |
| if (routeMatches) { |
| paramsResult = utils.normalizeDynamicRouteParams(routeMatches, true); |
| if (paramsResult.hasValidParams) { |
| params = paramsResult.params; |
| } |
| } |
| } |
| |
| |
| if (!paramsResult.hasValidParams) { |
| paramsResult = utils.normalizeDynamicRouteParams(queryParams, true); |
| if (paramsResult.hasValidParams) { |
| params = paramsResult.params; |
| } |
| } |
| |
| |
| |
| if (utils.defaultRouteMatches && normalizedUrlPath === srcPathname && !paramsResult.hasValidParams) { |
| params = utils.defaultRouteMatches; |
| |
| |
| |
| |
| |
| if (routeMatchesHeader === '') { |
| (0, _requestmeta.addRequestMeta)(req, 'renderFallbackShell', true); |
| } |
| } |
| if (params) { |
| matchedPath = utils.interpolateDynamicPath(srcPathname, params); |
| req.url = utils.interpolateDynamicPath(req.url, params); |
| |
| |
| |
| let segmentPrefetchRSCRequest = (0, _requestmeta.getRequestMeta)(req, 'segmentPrefetchRSCRequest'); |
| if (segmentPrefetchRSCRequest && (0, _utils1.isDynamicRoute)(segmentPrefetchRSCRequest, false)) { |
| segmentPrefetchRSCRequest = utils.interpolateDynamicPath(segmentPrefetchRSCRequest, params); |
| req.headers[_approuterheaders.NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] = segmentPrefetchRSCRequest; |
| (0, _requestmeta.addRequestMeta)(req, 'segmentPrefetchRSCRequest', segmentPrefetchRSCRequest); |
| } |
| } |
| } |
| if (pageIsDynamic || didRewrite) { |
| var _utils_defaultRouteRegex; |
| utils.normalizeCdnUrl(req, [ |
| ...rewriteParamKeys, |
| ...Object.keys(((_utils_defaultRouteRegex = utils.defaultRouteRegex) == null ? void 0 : _utils_defaultRouteRegex.groups) || {}) |
| ]); |
| } |
| |
| |
| |
| for (const key of routeParamKeys){ |
| if (!(key in originQueryParams)) { |
| delete parsedUrl.query[key]; |
| } |
| } |
| parsedUrl.pathname = matchedPath; |
| url.pathname = parsedUrl.pathname; |
| finished = await this.normalizeAndAttachMetadata(req, res, parsedUrl); |
| if (finished) return; |
| } catch (err) { |
| if (err instanceof _utils.DecodeError || err instanceof _utils.NormalizeError) { |
| res.statusCode = 400; |
| return this.renderError(null, req, res, '/_error', {}); |
| } |
| throw err; |
| } |
| } |
| (0, _requestmeta.addRequestMeta)(req, 'isLocaleDomain', Boolean(domainLocale)); |
| if (pathnameInfo.locale) { |
| req.url = (0, _url.format)(url); |
| (0, _requestmeta.addRequestMeta)(req, 'didStripLocale', true); |
| } |
| |
| |
| if (!this.minimalMode || !(0, _requestmeta.getRequestMeta)(req, 'locale')) { |
| |
| if (pathnameInfo.locale) { |
| (0, _requestmeta.addRequestMeta)(req, 'locale', pathnameInfo.locale); |
| } else if (defaultLocale) { |
| (0, _requestmeta.addRequestMeta)(req, 'locale', defaultLocale); |
| (0, _requestmeta.addRequestMeta)(req, 'localeInferredFromDefault', true); |
| } |
| } |
| |
| |
| |
| if (!this.serverOptions.webServerConfig && !(0, _requestmeta.getRequestMeta)(req, 'incrementalCache')) { |
| const incrementalCache = await this.getIncrementalCache({ |
| requestHeaders: Object.assign({}, req.headers) |
| }); |
| incrementalCache.resetRequestCache(); |
| (0, _requestmeta.addRequestMeta)(req, 'incrementalCache', incrementalCache); |
| globalThis.__incrementalCache = incrementalCache; |
| } |
| const cacheHandlers = (0, _handlers.getCacheHandlers)(); |
| if (cacheHandlers) { |
| await Promise.all([ |
| ...cacheHandlers |
| ].map(async (cacheHandler)=>{ |
| if ('refreshTags' in cacheHandler) { |
| |
| |
| |
| } else { |
| const previouslyRevalidatedTags = (0, _serverutils.getPreviouslyRevalidatedTags)(req.headers, this.getPrerenderManifest().preview.previewModeId); |
| await cacheHandler.receiveExpiredTags(...previouslyRevalidatedTags); |
| } |
| })); |
| } |
| |
| |
| if (!(0, _requestmeta.getRequestMeta)(req, 'serverComponentsHmrCache')) { |
| (0, _requestmeta.addRequestMeta)(req, 'serverComponentsHmrCache', this.getServerComponentsHmrCache()); |
| } |
| |
| |
| |
| const invokePath = (0, _requestmeta.getRequestMeta)(req, 'invokePath'); |
| const useInvokePath = !useMatchedPathHeader && invokePath; |
| if (useInvokePath) { |
| var _this_nextConfig_i18n1; |
| const invokeStatus = (0, _requestmeta.getRequestMeta)(req, 'invokeStatus'); |
| if (invokeStatus) { |
| const invokeQuery = (0, _requestmeta.getRequestMeta)(req, 'invokeQuery'); |
| if (invokeQuery) { |
| Object.assign(parsedUrl.query, invokeQuery); |
| } |
| res.statusCode = invokeStatus; |
| let err = (0, _requestmeta.getRequestMeta)(req, 'invokeError') || null; |
| return this.renderError(err, req, res, '/_error', parsedUrl.query); |
| } |
| const parsedMatchedPath = new URL(invokePath || '/', 'http://n'); |
| const invokePathnameInfo = (0, _getnextpathnameinfo.getNextPathnameInfo)(parsedMatchedPath.pathname, { |
| nextConfig: this.nextConfig, |
| parseData: false |
| }); |
| if (invokePathnameInfo.locale) { |
| (0, _requestmeta.addRequestMeta)(req, 'locale', invokePathnameInfo.locale); |
| } |
| if (parsedUrl.pathname !== parsedMatchedPath.pathname) { |
| parsedUrl.pathname = parsedMatchedPath.pathname; |
| (0, _requestmeta.addRequestMeta)(req, 'rewroteURL', invokePathnameInfo.pathname); |
| } |
| const normalizeResult = (0, _normalizelocalepath.normalizeLocalePath)((0, _removepathprefix.removePathPrefix)(parsedUrl.pathname, this.nextConfig.basePath || ''), (_this_nextConfig_i18n1 = this.nextConfig.i18n) == null ? void 0 : _this_nextConfig_i18n1.locales); |
| if (normalizeResult.detectedLocale) { |
| (0, _requestmeta.addRequestMeta)(req, 'locale', normalizeResult.detectedLocale); |
| } |
| parsedUrl.pathname = normalizeResult.pathname; |
| for (const key of Object.keys(parsedUrl.query)){ |
| delete parsedUrl.query[key]; |
| } |
| const invokeQuery = (0, _requestmeta.getRequestMeta)(req, 'invokeQuery'); |
| if (invokeQuery) { |
| Object.assign(parsedUrl.query, invokeQuery); |
| } |
| finished = await this.normalizeAndAttachMetadata(req, res, parsedUrl); |
| if (finished) return; |
| await this.handleCatchallRenderRequest(req, res, parsedUrl); |
| return; |
| } |
| if ((0, _requestmeta.getRequestMeta)(req, 'middlewareInvoke')) { |
| finished = await this.normalizeAndAttachMetadata(req, res, parsedUrl); |
| if (finished) return; |
| finished = await this.handleCatchallMiddlewareRequest(req, res, parsedUrl); |
| if (finished) return; |
| const err = new Error(); |
| err.result = { |
| response: new Response(null, { |
| headers: { |
| 'x-middleware-next': '1' |
| } |
| }) |
| }; |
| err.bubble = true; |
| throw err; |
| } |
| |
| |
| |
| if (!useMatchedPathHeader && pathnameInfo.basePath) { |
| parsedUrl.pathname = (0, _removepathprefix.removePathPrefix)(parsedUrl.pathname, pathnameInfo.basePath); |
| } |
| res.statusCode = 200; |
| return await this.run(req, res, parsedUrl); |
| } catch (err) { |
| if (err instanceof _nofallbackerrorexternal.NoFallbackError) { |
| throw err; |
| } |
| if (err && typeof err === 'object' && err.code === 'ERR_INVALID_URL' || err instanceof _utils.DecodeError || err instanceof _utils.NormalizeError) { |
| res.statusCode = 400; |
| return this.renderError(null, req, res, '/_error', {}); |
| } |
| if (this.minimalMode || this.renderOpts.dev || (0, _tracer.isBubbledError)(err) && err.bubble) { |
| throw err; |
| } |
| this.logError((0, _iserror.getProperError)(err)); |
| res.statusCode = 500; |
| res.body('Internal Server Error').send(); |
| } |
| } |
| |
| |
| getRequestHandlerWithMetadata(meta) { |
| const handler = this.getRequestHandler(); |
| return (req, res, parsedUrl)=>{ |
| (0, _requestmeta.setRequestMeta)(req, meta); |
| return handler(req, res, parsedUrl); |
| }; |
| } |
| getRequestHandler() { |
| return this.handleRequest.bind(this); |
| } |
| setAssetPrefix(prefix) { |
| this.nextConfig.assetPrefix = prefix ? prefix.replace(/\/$/, '') : ''; |
| } |
| |
| |
| |
| async prepare() { |
| if (this.prepared) return; |
| |
| if (!this.instrumentation) { |
| this.instrumentation = await this.loadInstrumentationModule(); |
| } |
| if (this.preparedPromise === null) { |
| this.preparedPromise = this.prepareImpl().then(()=>{ |
| this.prepared = true; |
| this.preparedPromise = null; |
| }); |
| } |
| return this.preparedPromise; |
| } |
| async prepareImpl() {} |
| async loadInstrumentationModule() {} |
| async close() {} |
| getAppPathRoutes() { |
| const appPathRoutes = {}; |
| Object.keys(this.appPathsManifest || {}).forEach((entry)=>{ |
| const normalizedPath = (0, _apppaths.normalizeAppPath)(entry); |
| if (!appPathRoutes[normalizedPath]) { |
| appPathRoutes[normalizedPath] = []; |
| } |
| appPathRoutes[normalizedPath].push(entry); |
| }); |
| return appPathRoutes; |
| } |
| async run(req, res, parsedUrl) { |
| return (0, _tracer.getTracer)().trace(_constants1.BaseServerSpan.run, async ()=>this.runImpl(req, res, parsedUrl)); |
| } |
| async runImpl(req, res, parsedUrl) { |
| await this.handleCatchallRenderRequest(req, res, parsedUrl); |
| } |
| async pipe(fn, partialContext) { |
| return (0, _tracer.getTracer)().trace(_constants1.BaseServerSpan.pipe, async ()=>this.pipeImpl(fn, partialContext)); |
| } |
| async pipeImpl(fn, partialContext) { |
| const ua = partialContext.req.headers['user-agent'] || ''; |
| const ctx = { |
| ...partialContext, |
| renderOpts: { |
| ...this.renderOpts, |
| |
| supportsDynamicResponse: !this.renderOpts.botType, |
| serveStreamingMetadata: (0, _streamingmetadata.shouldServeStreamingMetadata)(ua, this.nextConfig.htmlLimitedBots) |
| } |
| }; |
| const payload = await fn(ctx); |
| if (payload === null) { |
| return; |
| } |
| const { req, res } = ctx; |
| const originalStatus = res.statusCode; |
| const { body } = payload; |
| let { cacheControl } = payload; |
| if (!res.sent) { |
| const { generateEtags, poweredByHeader, dev } = this.renderOpts; |
| |
| if (dev) { |
| res.setHeader('Cache-Control', 'no-store, must-revalidate'); |
| cacheControl = undefined; |
| } |
| if (cacheControl && cacheControl.expire === undefined) { |
| cacheControl.expire = this.nextConfig.expireTime; |
| } |
| await this.sendRenderResult(req, res, { |
| result: body, |
| generateEtags, |
| poweredByHeader, |
| cacheControl |
| }); |
| res.statusCode = originalStatus; |
| } |
| } |
| async getStaticHTML(fn, partialContext) { |
| const ctx = { |
| ...partialContext, |
| renderOpts: { |
| ...this.renderOpts, |
| supportsDynamicResponse: false |
| } |
| }; |
| const payload = await fn(ctx); |
| if (payload === null) { |
| return null; |
| } |
| return payload.body.toUnchunkedString(); |
| } |
| async render(req, res, pathname, query = {}, parsedUrl, internalRender = false) { |
| return (0, _tracer.getTracer)().trace(_constants1.BaseServerSpan.render, async ()=>this.renderImpl(req, res, pathname, query, parsedUrl, internalRender)); |
| } |
| getWaitUntil() { |
| const builtinRequestContext = (0, _builtinrequestcontext.getBuiltinRequestContext)(); |
| if (builtinRequestContext) { |
| |
| |
| |
| |
| return builtinRequestContext.waitUntil; |
| } |
| if (this.minimalMode) { |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| return undefined; |
| } |
| return this.getInternalWaitUntil(); |
| } |
| getInternalWaitUntil() { |
| return undefined; |
| } |
| async renderImpl(req, res, pathname, query = {}, parsedUrl, internalRender = false) { |
| var _req_url; |
| if (!pathname.startsWith('/')) { |
| console.warn(`Cannot render page with path "${pathname}", did you mean "/${pathname}"?. See more info here: https://nextjs.org/docs/messages/render-no-starting-slash`); |
| } |
| if (this.serverOptions.customServer && pathname === '/index' && !await this.hasPage('/index')) { |
| |
| |
| pathname = '/'; |
| } |
| const ua = req.headers['user-agent'] || ''; |
| this.renderOpts.botType = (0, _isbot.getBotType)(ua); |
| |
| |
| |
| |
| if (!internalRender && !this.minimalMode && !(0, _requestmeta.getRequestMeta)(req, 'isNextDataReq') && (((_req_url = req.url) == null ? void 0 : _req_url.match(/^\/_next\//)) || this.hasStaticDir && req.url.match(/^\/static\//))) { |
| return this.handleRequest(req, res, parsedUrl); |
| } |
| if ((0, _utils2.isBlockedPage)(pathname)) { |
| return this.render404(req, res, parsedUrl); |
| } |
| return this.pipe((ctx)=>this.renderToResponse(ctx), { |
| req, |
| res, |
| pathname, |
| query |
| }); |
| } |
| async getStaticPaths({ pathname }) { |
| var _this_getPrerenderManifest_dynamicRoutes_pathname; |
| |
| const fallbackField = (_this_getPrerenderManifest_dynamicRoutes_pathname = this.getPrerenderManifest().dynamicRoutes[pathname]) == null ? void 0 : _this_getPrerenderManifest_dynamicRoutes_pathname.fallback; |
| return { |
| |
| |
| staticPaths: undefined, |
| fallbackMode: (0, _fallback.parseFallbackField)(fallbackField) |
| }; |
| } |
| async renderToResponseWithComponents(requestContext, findComponentsResult) { |
| return (0, _tracer.getTracer)().trace(_constants1.BaseServerSpan.renderToResponseWithComponents, async ()=>this.renderToResponseWithComponentsImpl(requestContext, findComponentsResult)); |
| } |
| pathCouldBeIntercepted(resolvedPathname) { |
| return (0, _interceptionroutes.isInterceptionRouteAppPath)(resolvedPathname) || this.interceptionRoutePatterns.some((regexp)=>{ |
| return regexp.test(resolvedPathname); |
| }); |
| } |
| setVaryHeader(req, res, isAppPath, resolvedPathname) { |
| const baseVaryHeader = `${_approuterheaders.RSC_HEADER}, ${_approuterheaders.NEXT_ROUTER_STATE_TREE_HEADER}, ${_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER}, ${_approuterheaders.NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}`; |
| const isRSCRequest = (0, _requestmeta.getRequestMeta)(req, 'isRSCRequest') ?? false; |
| let addedNextUrlToVary = false; |
| if (isAppPath && this.pathCouldBeIntercepted(resolvedPathname)) { |
| |
| |
| res.appendHeader('vary', `${baseVaryHeader}, ${_approuterheaders.NEXT_URL}`); |
| addedNextUrlToVary = true; |
| } else if (isAppPath || isRSCRequest) { |
| |
| |
| res.appendHeader('vary', baseVaryHeader); |
| } |
| if (!addedNextUrlToVary) { |
| |
| |
| delete req.headers[_approuterheaders.NEXT_URL]; |
| } |
| } |
| async renderToResponseWithComponentsImpl({ req, res, pathname, renderOpts: opts }, { components, query }) { |
| var _this; |
| if (pathname === _constants.UNDERSCORE_NOT_FOUND_ROUTE) { |
| pathname = '/404'; |
| } |
| const isErrorPathname = pathname === '/_error'; |
| const is404Page = pathname === '/404' || isErrorPathname && res.statusCode === 404; |
| const is500Page = pathname === '/500' || isErrorPathname && res.statusCode === 500; |
| const isAppPath = components.isAppPath === true; |
| const hasServerProps = !!components.getServerSideProps; |
| const isPossibleServerAction = (0, _serveractionrequestmeta.getIsPossibleServerAction)(req); |
| let isSSG = !!components.getStaticProps; |
| |
| const isRSCRequest = (0, _requestmeta.getRequestMeta)(req, 'isRSCRequest') ?? false; |
| |
| |
| |
| |
| |
| |
| if (!this.minimalMode && this.nextConfig.experimental.validateRSCRequestHeaders && isRSCRequest) { |
| const headers = req.headers; |
| const prefetchHeaderValue = headers[_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER]; |
| const routerPrefetch = prefetchHeaderValue !== undefined ? prefetchHeaderValue === '1' || prefetchHeaderValue === '2' ? prefetchHeaderValue : undefined : |
| |
| (0, _requestmeta.getRequestMeta)(req, 'isPrefetchRSCRequest') ? '1' : undefined; |
| const segmentPrefetchRSCRequest = headers[_approuterheaders.NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] || (0, _requestmeta.getRequestMeta)(req, 'segmentPrefetchRSCRequest'); |
| const expectedHash = (0, _cachebustingsearchparam.computeCacheBustingSearchParam)(routerPrefetch, segmentPrefetchRSCRequest, headers[_approuterheaders.NEXT_ROUTER_STATE_TREE_HEADER], headers[_approuterheaders.NEXT_URL]); |
| const actualHash = (0, _requestmeta.getRequestMeta)(req, 'cacheBustingSearchParam') ?? new URL(req.url || '', 'http://localhost').searchParams.get(_approuterheaders.NEXT_RSC_UNION_QUERY); |
| if (expectedHash !== actualHash) { |
| |
| |
| |
| |
| |
| const url = new URL(req.url || '', 'http://localhost'); |
| (0, _setcachebustingsearchparam.setCacheBustingSearchParamWithHash)(url, expectedHash); |
| res.statusCode = 307; |
| res.setHeader('location', `${url.pathname}${url.search}`); |
| res.body('').send(); |
| return null; |
| } |
| } |
| |
| |
| |
| let urlPathname = (0, _url.parse)(req.url || '').pathname || '/'; |
| let resolvedUrlPathname = (0, _requestmeta.getRequestMeta)(req, 'rewroteURL') || urlPathname; |
| this.setVaryHeader(req, res, isAppPath, resolvedUrlPathname); |
| let staticPaths; |
| let hasFallback = false; |
| const prerenderManifest = this.getPrerenderManifest(); |
| if (hasFallback || (staticPaths == null ? void 0 : staticPaths.includes(resolvedUrlPathname)) || |
| |
| req.headers['x-now-route-matches']) { |
| isSSG = true; |
| } else if (!this.renderOpts.dev) { |
| isSSG ||= !!prerenderManifest.routes[(0, _toroute.toRoute)(pathname)]; |
| } |
| |
| const isNextDataRequest = !!((0, _requestmeta.getRequestMeta)(req, 'isNextDataReq') || req.headers['x-nextjs-data'] && this.serverOptions.webServerConfig) && (isSSG || hasServerProps); |
| |
| |
| |
| if (!isSSG && req.headers['x-middleware-prefetch'] && !(is404Page || pathname === '/_error')) { |
| res.setHeader(_constants2.MATCHED_PATH_HEADER, pathname); |
| res.setHeader('x-middleware-skip', '1'); |
| res.setHeader('cache-control', 'private, no-cache, no-store, max-age=0, must-revalidate'); |
| res.body('{}').send(); |
| return null; |
| } |
| |
| |
| if (isSSG && this.minimalMode && req.headers[_constants2.MATCHED_PATH_HEADER] && req.url.startsWith('/_next/data')) { |
| req.url = this.stripNextDataPath(req.url); |
| } |
| const locale = (0, _requestmeta.getRequestMeta)(req, 'locale'); |
| if (!!req.headers['x-nextjs-data'] && (!res.statusCode || res.statusCode === 200)) { |
| res.setHeader('x-nextjs-matched-path', `${locale ? `/${locale}` : ''}${pathname}`); |
| } |
| let routeModule; |
| if (components.routeModule) { |
| routeModule = components.routeModule; |
| } |
| |
| |
| |
| const couldSupportPPR = this.isAppPPREnabled && typeof routeModule !== 'undefined' && (0, _checks.isAppPageRouteModule)(routeModule); |
| |
| |
| const hasDebugStaticShellQuery = process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING === '1' && typeof query.__nextppronly !== 'undefined' && couldSupportPPR; |
| |
| |
| const isRoutePPREnabled = couldSupportPPR && (((_this = prerenderManifest.routes[pathname] ?? prerenderManifest.dynamicRoutes[pathname]) == null ? void 0 : _this.renderingMode) === 'PARTIALLY_STATIC' || |
| |
| |
| |
| hasDebugStaticShellQuery && (this.renderOpts.dev === true || this.experimentalTestProxy === true)); |
| |
| |
| |
| const minimalPostponed = isRoutePPREnabled ? (0, _requestmeta.getRequestMeta)(req, 'postponed') : undefined; |
| |
| if (is404Page && !isNextDataRequest && !isRSCRequest) { |
| res.statusCode = 404; |
| } |
| |
| |
| if (_constants.STATIC_STATUS_PAGES.includes(pathname)) { |
| res.statusCode = parseInt(pathname.slice(1), 10); |
| } |
| if ( |
| !isPossibleServerAction && |
| !minimalPostponed && !is404Page && !is500Page && pathname !== '/_error' && req.method !== 'HEAD' && req.method !== 'GET' && (typeof components.Component === 'string' || isSSG)) { |
| res.statusCode = 405; |
| res.setHeader('Allow', [ |
| 'GET', |
| 'HEAD' |
| ]); |
| res.body('Method Not Allowed').send(); |
| return null; |
| } |
| |
| if (typeof components.Component === 'string') { |
| return { |
| body: _renderresult.default.fromStatic(components.Component, _constants2.HTML_CONTENT_TYPE_HEADER) |
| }; |
| } |
| |
| |
| if ('amp' in query && !query.amp) delete query.amp; |
| if (opts.supportsDynamicResponse === true) { |
| var _components_Document; |
| const ua = req.headers['user-agent'] || ''; |
| const isBotRequest = (0, _isbot.isBot)(ua); |
| const isSupportedDocument = typeof ((_components_Document = components.Document) == null ? void 0 : _components_Document.getInitialProps) !== 'function' || |
| _constants.NEXT_BUILTIN_DOCUMENT in components.Document; |
| |
| |
| |
| |
| |
| opts.supportsDynamicResponse = !isSSG && !isBotRequest && !query.amp && isSupportedDocument; |
| } |
| |
| if (!isNextDataRequest && isAppPath && opts.dev) { |
| opts.supportsDynamicResponse = true; |
| } |
| if (isSSG && this.minimalMode && req.headers[_constants2.MATCHED_PATH_HEADER]) { |
| |
| resolvedUrlPathname = urlPathname; |
| } |
| urlPathname = (0, _removetrailingslash.removeTrailingSlash)(urlPathname); |
| resolvedUrlPathname = (0, _removetrailingslash.removeTrailingSlash)(resolvedUrlPathname); |
| if (this.localeNormalizer) { |
| resolvedUrlPathname = this.localeNormalizer.normalize(resolvedUrlPathname); |
| } |
| |
| |
| if (isNextDataRequest) { |
| resolvedUrlPathname = this.stripNextDataPath(resolvedUrlPathname); |
| urlPathname = this.stripNextDataPath(urlPathname); |
| } |
| |
| const incrementalCache = await this.getIncrementalCache({ |
| requestHeaders: Object.assign({}, req.headers) |
| }); |
| |
| incrementalCache.resetRequestCache(); |
| if ((routeModule == null ? void 0 : routeModule.isDev) && (0, _utils1.isDynamicRoute)(pathname) && (components.getStaticPaths || isAppPath)) { |
| const pathsResults = await this.getStaticPaths({ |
| pathname, |
| urlPathname, |
| requestHeaders: req.headers, |
| page: components.page, |
| isAppPath |
| }); |
| if (isAppPath && this.nextConfig.experimental.cacheComponents) { |
| var _pathsResults_prerenderedRoutes; |
| if ((_pathsResults_prerenderedRoutes = pathsResults.prerenderedRoutes) == null ? void 0 : _pathsResults_prerenderedRoutes.length) { |
| let smallestFallbackRouteParams = null; |
| for (const route of pathsResults.prerenderedRoutes){ |
| const fallbackRouteParams = route.fallbackRouteParams; |
| if (!fallbackRouteParams || fallbackRouteParams.length === 0) { |
| |
| smallestFallbackRouteParams = null; |
| break; |
| } |
| if (smallestFallbackRouteParams === null || fallbackRouteParams.length < smallestFallbackRouteParams.length) { |
| smallestFallbackRouteParams = fallbackRouteParams; |
| } |
| } |
| if (smallestFallbackRouteParams) { |
| const devValidatingFallbackParams = new Map(smallestFallbackRouteParams.map((v)=>[ |
| v, |
| '' |
| ])); |
| (0, _requestmeta.addRequestMeta)(req, 'devValidatingFallbackParams', devValidatingFallbackParams); |
| } |
| } |
| } |
| } |
| |
| if (req.method === 'OPTIONS' && !is404Page && (!routeModule || !(0, _checks.isAppRouteRouteModule)(routeModule))) { |
| await (0, _sendresponse.sendResponse)(req, res, new Response(null, { |
| status: 400 |
| })); |
| return null; |
| } |
| const request = (0, _helpers.isNodeNextRequest)(req) ? req.originalRequest : req; |
| const response = (0, _helpers.isNodeNextResponse)(res) ? res.originalResponse : res; |
| const parsedInitUrl = (0, _url.parse)((0, _requestmeta.getRequestMeta)(req, 'initURL') || req.url); |
| let initPathname = parsedInitUrl.pathname || '/'; |
| for (const normalizer of [ |
| this.normalizers.segmentPrefetchRSC, |
| this.normalizers.prefetchRSC, |
| this.normalizers.rsc |
| ]){ |
| if (normalizer == null ? void 0 : normalizer.match(initPathname)) { |
| initPathname = normalizer.normalize(initPathname); |
| } |
| } |
| |
| |
| |
| if (!(this.minimalMode && isErrorPathname)) { |
| request.url = `${initPathname}${parsedInitUrl.search || ''}`; |
| } |
| |
| (0, _requestmeta.setRequestMeta)(request, (0, _requestmeta.getRequestMeta)(req)); |
| (0, _requestmeta.addRequestMeta)(request, 'distDir', this.distDir); |
| (0, _requestmeta.addRequestMeta)(request, 'query', query); |
| (0, _requestmeta.addRequestMeta)(request, 'params', opts.params); |
| (0, _requestmeta.addRequestMeta)(request, 'ampValidator', this.renderOpts.ampValidator); |
| (0, _requestmeta.addRequestMeta)(request, 'minimalMode', this.minimalMode); |
| if (opts.err) { |
| (0, _requestmeta.addRequestMeta)(request, 'invokeError', opts.err); |
| } |
| const handler = components.ComponentMod.handler; |
| const maybeDevRequest = |
| |
| |
| |
| process.env.NODE_ENV === 'development' ? new Proxy(request, { |
| get (target, prop) { |
| if (typeof target[prop] === 'function') { |
| return target[prop].bind(target); |
| } |
| return target[prop]; |
| }, |
| set (target, prop, value) { |
| if (prop === 'fetchMetrics') { |
| ; |
| req.fetchMetrics = value; |
| } |
| target[prop] = value; |
| return true; |
| } |
| }) : request; |
| await handler(maybeDevRequest, response, { |
| waitUntil: this.getWaitUntil() |
| }); |
| |
| return null; |
| } |
| stripNextDataPath(path, stripLocale = true) { |
| if (path.includes(this.buildId)) { |
| const splitPath = path.substring(path.indexOf(this.buildId) + this.buildId.length); |
| path = (0, _denormalizepagepath.denormalizePagePath)(splitPath.replace(/\.json$/, '')); |
| } |
| if (this.localeNormalizer && stripLocale) { |
| return this.localeNormalizer.normalize(path); |
| } |
| return path; |
| } |
| |
| getOriginalAppPaths(route) { |
| if (this.enabledDirectories.app) { |
| var _this_appPathRoutes; |
| const originalAppPath = (_this_appPathRoutes = this.appPathRoutes) == null ? void 0 : _this_appPathRoutes[route]; |
| if (!originalAppPath) { |
| return null; |
| } |
| return originalAppPath; |
| } |
| return null; |
| } |
| async renderPageComponent(ctx, bubbleNoFallback) { |
| var _this_nextConfig_experimental_sri; |
| const { query, pathname } = ctx; |
| const appPaths = this.getOriginalAppPaths(pathname); |
| const isAppPath = Array.isArray(appPaths); |
| let page = pathname; |
| if (isAppPath) { |
| |
| page = appPaths[appPaths.length - 1]; |
| } |
| const result = await this.findPageComponents({ |
| locale: (0, _requestmeta.getRequestMeta)(ctx.req, 'locale'), |
| page, |
| query, |
| params: ctx.renderOpts.params || {}, |
| isAppPath, |
| sriEnabled: !!((_this_nextConfig_experimental_sri = this.nextConfig.experimental.sri) == null ? void 0 : _this_nextConfig_experimental_sri.algorithm), |
| appPaths, |
| |
| shouldEnsure: false |
| }); |
| if (result) { |
| (0, _tracer.getTracer)().setRootSpanAttribute('next.route', pathname); |
| try { |
| return await this.renderToResponseWithComponents(ctx, result); |
| } catch (err) { |
| const isNoFallbackError = err instanceof _nofallbackerrorexternal.NoFallbackError; |
| if (!isNoFallbackError || isNoFallbackError && bubbleNoFallback) { |
| throw err; |
| } |
| } |
| } |
| return false; |
| } |
| async renderToResponse(ctx) { |
| return (0, _tracer.getTracer)().trace(_constants1.BaseServerSpan.renderToResponse, { |
| spanName: `rendering page`, |
| attributes: { |
| 'next.route': ctx.pathname |
| } |
| }, async ()=>{ |
| return this.renderToResponseImpl(ctx); |
| }); |
| } |
| async renderToResponseImpl(ctx) { |
| var _this_i18nProvider; |
| const { req, res, query, pathname } = ctx; |
| let page = pathname; |
| const bubbleNoFallback = (0, _requestmeta.getRequestMeta)(ctx.req, 'bubbleNoFallback') ?? false; |
| if (!this.minimalMode && this.nextConfig.experimental.validateRSCRequestHeaders) { |
| (0, _requestmeta.addRequestMeta)(ctx.req, 'cacheBustingSearchParam', query[_approuterheaders.NEXT_RSC_UNION_QUERY]); |
| } |
| delete query[_approuterheaders.NEXT_RSC_UNION_QUERY]; |
| const options = { |
| i18n: (_this_i18nProvider = this.i18nProvider) == null ? void 0 : _this_i18nProvider.fromRequest(req, pathname) |
| }; |
| try { |
| for await (const match of this.matchers.matchAll(pathname, options)){ |
| |
| |
| const invokeOutput = (0, _requestmeta.getRequestMeta)(ctx.req, 'invokeOutput'); |
| if (!this.minimalMode && typeof invokeOutput === 'string' && (0, _utils1.isDynamicRoute)(invokeOutput || '') && invokeOutput !== match.definition.pathname) { |
| continue; |
| } |
| const result = await this.renderPageComponent({ |
| ...ctx, |
| pathname: match.definition.pathname, |
| renderOpts: { |
| ...ctx.renderOpts, |
| params: match.params |
| } |
| }, bubbleNoFallback); |
| if (result !== false) return result; |
| } |
| |
| |
| |
| |
| |
| if (this.serverOptions.webServerConfig) { |
| |
| ctx.pathname = this.serverOptions.webServerConfig.page; |
| const result = await this.renderPageComponent(ctx, bubbleNoFallback); |
| if (result !== false) return result; |
| } |
| } catch (error) { |
| const err = (0, _iserror.getProperError)(error); |
| if (error instanceof _utils.MissingStaticPage) { |
| console.error('Invariant: failed to load static page', JSON.stringify({ |
| page, |
| url: ctx.req.url, |
| matchedPath: ctx.req.headers[_constants2.MATCHED_PATH_HEADER], |
| initUrl: (0, _requestmeta.getRequestMeta)(ctx.req, 'initURL'), |
| didRewrite: !!(0, _requestmeta.getRequestMeta)(ctx.req, 'rewroteURL'), |
| rewroteUrl: (0, _requestmeta.getRequestMeta)(ctx.req, 'rewroteURL') |
| }, null, 2)); |
| throw err; |
| } |
| if (err instanceof _nofallbackerrorexternal.NoFallbackError && bubbleNoFallback) { |
| throw err; |
| } |
| if (err instanceof _utils.DecodeError || err instanceof _utils.NormalizeError) { |
| res.statusCode = 400; |
| return await this.renderErrorToResponse(ctx, err); |
| } |
| res.statusCode = 500; |
| |
| |
| if (await this.hasPage('/500')) { |
| (0, _requestmeta.addRequestMeta)(ctx.req, 'customErrorRender', true); |
| await this.renderErrorToResponse(ctx, err); |
| (0, _requestmeta.removeRequestMeta)(ctx.req, 'customErrorRender'); |
| } |
| const isWrappedError = err instanceof WrappedBuildError; |
| if (!isWrappedError) { |
| if (this.minimalMode || this.renderOpts.dev) { |
| if ((0, _iserror.default)(err)) err.page = page; |
| throw err; |
| } |
| this.logError((0, _iserror.getProperError)(err)); |
| } |
| const response = await this.renderErrorToResponse(ctx, isWrappedError ? err.innerError : err); |
| return response; |
| } |
| const middleware = await this.getMiddleware(); |
| if (middleware && !!ctx.req.headers['x-nextjs-data'] && (!res.statusCode || res.statusCode === 200 || res.statusCode === 404)) { |
| const locale = (0, _requestmeta.getRequestMeta)(req, 'locale'); |
| res.setHeader('x-nextjs-matched-path', `${locale ? `/${locale}` : ''}${pathname}`); |
| res.statusCode = 200; |
| res.setHeader('Content-Type', _constants2.JSON_CONTENT_TYPE_HEADER); |
| res.body('{}'); |
| res.send(); |
| return null; |
| } |
| res.statusCode = 404; |
| return this.renderErrorToResponse(ctx, null); |
| } |
| async renderToHTML(req, res, pathname, query = {}) { |
| return (0, _tracer.getTracer)().trace(_constants1.BaseServerSpan.renderToHTML, async ()=>{ |
| return this.renderToHTMLImpl(req, res, pathname, query); |
| }); |
| } |
| async renderToHTMLImpl(req, res, pathname, query = {}) { |
| return this.getStaticHTML((ctx)=>this.renderToResponse(ctx), { |
| req, |
| res, |
| pathname, |
| query |
| }); |
| } |
| async renderError(err, req, res, pathname, query = {}, setHeaders = true) { |
| return (0, _tracer.getTracer)().trace(_constants1.BaseServerSpan.renderError, async ()=>{ |
| return this.renderErrorImpl(err, req, res, pathname, query, setHeaders); |
| }); |
| } |
| async renderErrorImpl(err, req, res, pathname, query = {}, setHeaders = true) { |
| if (setHeaders) { |
| res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate'); |
| } |
| return this.pipe(async (ctx)=>{ |
| const response = await this.renderErrorToResponse(ctx, err); |
| if (this.minimalMode && res.statusCode === 500) { |
| throw err; |
| } |
| return response; |
| }, { |
| req, |
| res, |
| pathname, |
| query |
| }); |
| } |
| async renderErrorToResponse(ctx, err) { |
| return (0, _tracer.getTracer)().trace(_constants1.BaseServerSpan.renderErrorToResponse, async ()=>{ |
| return this.renderErrorToResponseImpl(ctx, err); |
| }); |
| } |
| async renderErrorToResponseImpl(ctx, err) { |
| |
| |
| if (this.renderOpts.dev && ctx.pathname === '/favicon.ico') { |
| return { |
| body: _renderresult.default.EMPTY |
| }; |
| } |
| const { res, query } = ctx; |
| try { |
| let result = null; |
| const is404 = res.statusCode === 404; |
| let using404Page = false; |
| if (is404) { |
| if (this.enabledDirectories.app) { |
| |
| result = await this.findPageComponents({ |
| locale: (0, _requestmeta.getRequestMeta)(ctx.req, 'locale'), |
| page: _constants.UNDERSCORE_NOT_FOUND_ROUTE_ENTRY, |
| query, |
| params: {}, |
| isAppPath: true, |
| shouldEnsure: true, |
| url: ctx.req.url |
| }); |
| using404Page = result !== null; |
| } |
| if (!result && await this.hasPage('/404')) { |
| result = await this.findPageComponents({ |
| locale: (0, _requestmeta.getRequestMeta)(ctx.req, 'locale'), |
| page: '/404', |
| query, |
| params: {}, |
| isAppPath: false, |
| |
| shouldEnsure: true, |
| url: ctx.req.url |
| }); |
| using404Page = result !== null; |
| } |
| } |
| let statusPage = `/${res.statusCode}`; |
| if (!(0, _requestmeta.getRequestMeta)(ctx.req, 'customErrorRender') && !result && _constants.STATIC_STATUS_PAGES.includes(statusPage)) { |
| |
| |
| if (statusPage !== '/500' || !this.renderOpts.dev) { |
| result = await this.findPageComponents({ |
| locale: (0, _requestmeta.getRequestMeta)(ctx.req, 'locale'), |
| page: statusPage, |
| query, |
| params: {}, |
| isAppPath: false, |
| |
| |
| shouldEnsure: true, |
| url: ctx.req.url |
| }); |
| } |
| } |
| if (!result) { |
| result = await this.findPageComponents({ |
| locale: (0, _requestmeta.getRequestMeta)(ctx.req, 'locale'), |
| page: '/_error', |
| query, |
| params: {}, |
| isAppPath: false, |
| |
| |
| shouldEnsure: true, |
| url: ctx.req.url |
| }); |
| statusPage = '/_error'; |
| } |
| if (process.env.NODE_ENV !== 'production' && !using404Page && await this.hasPage('/_error') && !await this.hasPage('/404')) { |
| this.customErrorNo404Warn(); |
| } |
| if (!result) { |
| |
| |
| if (this.renderOpts.dev) { |
| return { |
| |
| body: _renderresult.default.fromStatic(` |
| <pre>missing required error components, refreshing...</pre> |
| <script> |
| async function check() { |
| const res = await fetch(location.href).catch(() => ({})) |
| |
| if (res.status === 200) { |
| location.reload() |
| } else { |
| setTimeout(check, 1000) |
| } |
| } |
| check() |
| </script>`, _constants2.HTML_CONTENT_TYPE_HEADER) |
| }; |
| } |
| throw new WrappedBuildError(Object.defineProperty(new Error('missing required error components'), "__NEXT_ERROR_CODE", { |
| value: "E60", |
| enumerable: false, |
| configurable: true |
| })); |
| } |
| |
| |
| if (result.components.routeModule) { |
| (0, _requestmeta.addRequestMeta)(ctx.req, 'match', { |
| definition: result.components.routeModule.definition, |
| params: undefined |
| }); |
| } else { |
| (0, _requestmeta.removeRequestMeta)(ctx.req, 'match'); |
| } |
| try { |
| return await this.renderToResponseWithComponents({ |
| ...ctx, |
| pathname: statusPage, |
| renderOpts: { |
| ...ctx.renderOpts, |
| err |
| } |
| }, result); |
| } catch (maybeFallbackError) { |
| if (maybeFallbackError instanceof _nofallbackerrorexternal.NoFallbackError) { |
| throw Object.defineProperty(new Error('invariant: failed to render error page'), "__NEXT_ERROR_CODE", { |
| value: "E55", |
| enumerable: false, |
| configurable: true |
| }); |
| } |
| throw maybeFallbackError; |
| } |
| } catch (error) { |
| const renderToHtmlError = (0, _iserror.getProperError)(error); |
| const isWrappedError = renderToHtmlError instanceof WrappedBuildError; |
| if (!isWrappedError) { |
| this.logError(renderToHtmlError); |
| } |
| res.statusCode = 500; |
| const fallbackComponents = await this.getFallbackErrorComponents(ctx.req.url); |
| if (fallbackComponents) { |
| |
| |
| (0, _requestmeta.addRequestMeta)(ctx.req, 'match', { |
| definition: fallbackComponents.routeModule.definition, |
| params: undefined |
| }); |
| return this.renderToResponseWithComponents({ |
| ...ctx, |
| pathname: '/_error', |
| renderOpts: { |
| ...ctx.renderOpts, |
| |
| |
| err: isWrappedError ? renderToHtmlError.innerError : renderToHtmlError |
| } |
| }, { |
| query, |
| components: fallbackComponents |
| }); |
| } |
| return { |
| body: _renderresult.default.fromStatic('Internal Server Error', 'text/plain') |
| }; |
| } |
| } |
| async renderErrorToHTML(err, req, res, pathname, query = {}) { |
| return this.getStaticHTML((ctx)=>this.renderErrorToResponse(ctx, err), { |
| req, |
| res, |
| pathname, |
| query |
| }); |
| } |
| async render404(req, res, parsedUrl, setHeaders = true) { |
| const { pathname, query } = parsedUrl ? parsedUrl : (0, _url.parse)(req.url, true); |
| |
| if (this.nextConfig.i18n) { |
| if (!(0, _requestmeta.getRequestMeta)(req, 'locale')) { |
| (0, _requestmeta.addRequestMeta)(req, 'locale', this.nextConfig.i18n.defaultLocale); |
| } |
| (0, _requestmeta.addRequestMeta)(req, 'defaultLocale', this.nextConfig.i18n.defaultLocale); |
| } |
| res.statusCode = 404; |
| return this.renderError(null, req, res, pathname, query, setHeaders); |
| } |
| } |
|
|
| |