This commit is contained in:
2026-04-12 01:02:14 +08:00
parent 509487f155
commit 9b053e302b
14085 changed files with 2680009 additions and 12 deletions

View File

@@ -0,0 +1,916 @@
import { AppPageRouteModule } from '../../server/route-modules/app-page/module.compiled' with {
'turbopack-transition': 'next-ssr'
};
import { RouteKind } from '../../server/route-kind' with {
'turbopack-transition': 'next-server-utility'
};
import { getRevalidateReason } from '../../server/instrumentation/utils';
import { getTracer, SpanKind } from '../../server/lib/trace/tracer';
import { getRequestMeta } from '../../server/request-meta';
import { BaseServerSpan } from '../../server/lib/trace/constants';
import { interopDefault } from '../../server/app-render/interop-default';
import { stripFlightHeaders } from '../../server/app-render/strip-flight-headers';
import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node';
import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr';
import { getFallbackRouteParams } from '../../server/request/fallback-params';
import { setReferenceManifestsSingleton } from '../../server/app-render/encryption-utils';
import { isHtmlBotRequest, shouldServeStreamingMetadata } from '../../server/lib/streaming-metadata';
import { createServerModuleMap } from '../../server/app-render/action-utils';
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths';
import { getIsPossibleServerAction } from '../../server/lib/server-action-request-meta';
import { RSC_HEADER, NEXT_ROUTER_PREFETCH_HEADER, NEXT_IS_PRERENDER_HEADER, NEXT_DID_POSTPONE_HEADER, RSC_CONTENT_TYPE_HEADER } from '../../client/components/app-router-headers';
import { getBotType, isBot } from '../../shared/lib/router/utils/is-bot';
import { CachedRouteKind } from '../../server/response-cache';
import { FallbackMode, parseFallbackField } from '../../lib/fallback';
import RenderResult from '../../server/render-result';
import { CACHE_ONE_YEAR, HTML_CONTENT_TYPE_HEADER, NEXT_CACHE_TAGS_HEADER } from '../../lib/constants';
import { ENCODED_TAGS } from '../../server/stream-utils/encoded-tags';
import { sendRenderResult } from '../../server/send-payload';
import { NoFallbackError } from '../../shared/lib/no-fallback-error.external';
// We inject the tree and pages here so that we can use them in the route
// module.
// INJECT:tree
// INJECT:pages
export { tree, pages };
import GlobalError from 'VAR_MODULE_GLOBAL_ERROR' with {
'turbopack-transition': 'next-server-utility'
};
export { GlobalError };
// INJECT:__next_app_require__
// INJECT:__next_app_load_chunk__
export const __next_app__ = {
require: __next_app_require__,
loadChunk: __next_app_load_chunk__
};
import * as entryBase from '../../server/app-render/entry-base' with {
'turbopack-transition': 'next-server-utility'
};
import { RedirectStatusCode } from '../../client/components/redirect-status-code';
export * from '../../server/app-render/entry-base' with {
'turbopack-transition': 'next-server-utility'
};
// Create and export the route module that will be consumed.
export const routeModule = new AppPageRouteModule({
definition: {
kind: RouteKind.APP_PAGE,
page: 'VAR_DEFINITION_PAGE',
pathname: 'VAR_DEFINITION_PATHNAME',
// The following aren't used in production.
bundlePath: '',
filename: '',
appPaths: []
},
userland: {
loaderTree: tree
},
distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',
relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || ''
});
export async function handler(req, res, ctx) {
var _this;
let srcPage = 'VAR_DEFINITION_PAGE';
// turbopack doesn't normalize `/index` in the page name
// so we need to to process dynamic routes properly
// TODO: fix turbopack providing differing value from webpack
if (process.env.TURBOPACK) {
srcPage = srcPage.replace(/\/index$/, '') || '/';
} else if (srcPage === '/index') {
// we always normalize /index specifically
srcPage = '/';
}
const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;
const initialPostponed = getRequestMeta(req, 'postponed');
// TODO: replace with more specific flags
const minimalMode = getRequestMeta(req, 'minimalMode');
const prepareResult = await routeModule.prepare(req, res, {
srcPage,
multiZoneDraftMode
});
if (!prepareResult) {
res.statusCode = 400;
res.end('Bad Request');
ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());
return null;
}
const { buildId, query, params, parsedUrl, pageIsDynamic, buildManifest, nextFontManifest, reactLoadableManifest, serverActionsManifest, clientReferenceManifest, subresourceIntegrityManifest, prerenderManifest, isDraftMode, resolvedPathname, revalidateOnlyGenerated, routerServerContext, nextConfig, interceptionRoutePatterns } = prepareResult;
const pathname = parsedUrl.pathname || '/';
const normalizedSrcPage = normalizeAppPath(srcPage);
let { isOnDemandRevalidate } = prepareResult;
const prerenderInfo = routeModule.match(pathname, prerenderManifest);
const isPrerendered = !!prerenderManifest.routes[resolvedPathname];
let isSSG = Boolean(prerenderInfo || isPrerendered || prerenderManifest.routes[normalizedSrcPage]);
const userAgent = req.headers['user-agent'] || '';
const botType = getBotType(userAgent);
const isHtmlBot = isHtmlBotRequest(req);
/**
* If true, this indicates that the request being made is for an app
* prefetch request.
*/ const isPrefetchRSCRequest = getRequestMeta(req, 'isPrefetchRSCRequest') ?? req.headers[NEXT_ROUTER_PREFETCH_HEADER] === '1' // exclude runtime prefetches, which use '2'
;
// NOTE: Don't delete headers[RSC] yet, it still needs to be used in renderToHTML later
const isRSCRequest = getRequestMeta(req, 'isRSCRequest') ?? Boolean(req.headers[RSC_HEADER]);
const isPossibleServerAction = getIsPossibleServerAction(req);
/**
* If the route being rendered is an app page, and the ppr feature has been
* enabled, then the given route _could_ support PPR.
*/ const couldSupportPPR = checkIsAppPPREnabled(nextConfig.experimental.ppr);
// When enabled, this will allow the use of the `?__nextppronly` query to
// enable debugging of the static shell.
const hasDebugStaticShellQuery = process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING === '1' && typeof query.__nextppronly !== 'undefined' && couldSupportPPR;
// When enabled, this will allow the use of the `?__nextppronly` query
// to enable debugging of the fallback shell.
const hasDebugFallbackShellQuery = hasDebugStaticShellQuery && query.__nextppronly === 'fallback';
// This page supports PPR if it is marked as being `PARTIALLY_STATIC` in the
// prerender manifest and this is an app page.
const isRoutePPREnabled = couldSupportPPR && (((_this = prerenderManifest.routes[normalizedSrcPage] ?? prerenderManifest.dynamicRoutes[normalizedSrcPage]) == null ? void 0 : _this.renderingMode) === 'PARTIALLY_STATIC' || // Ideally we'd want to check the appConfig to see if this page has PPR
// enabled or not, but that would require plumbing the appConfig through
// to the server during development. We assume that the page supports it
// but only during development.
hasDebugStaticShellQuery && (routeModule.isDev === true || (routerServerContext == null ? void 0 : routerServerContext.experimentalTestProxy) === true));
const isDebugStaticShell = hasDebugStaticShellQuery && isRoutePPREnabled;
// We should enable debugging dynamic accesses when the static shell
// debugging has been enabled and we're also in development mode.
const isDebugDynamicAccesses = isDebugStaticShell && routeModule.isDev === true;
const isDebugFallbackShell = hasDebugFallbackShellQuery && isRoutePPREnabled;
// If we're in minimal mode, then try to get the postponed information from
// the request metadata. If available, use it for resuming the postponed
// render.
const minimalPostponed = isRoutePPREnabled ? initialPostponed : undefined;
// If PPR is enabled, and this is a RSC request (but not a prefetch), then
// we can use this fact to only generate the flight data for the request
// because we can't cache the HTML (as it's also dynamic).
const isDynamicRSCRequest = isRoutePPREnabled && isRSCRequest && !isPrefetchRSCRequest;
// Need to read this before it's stripped by stripFlightHeaders. We don't
// need to transfer it to the request meta because it's only read
// within this function; the static segment data should have already been
// generated, so we will always either return a static response or a 404.
const segmentPrefetchHeader = getRequestMeta(req, 'segmentPrefetchRSCRequest');
// TODO: investigate existing bug with shouldServeStreamingMetadata always
// being true for a revalidate due to modifying the base-server this.renderOpts
// when fixing this to correct logic it causes hydration issue since we set
// serveStreamingMetadata to true during export
let serveStreamingMetadata = !userAgent ? true : shouldServeStreamingMetadata(userAgent, nextConfig.htmlLimitedBots);
if (isHtmlBot && isRoutePPREnabled) {
isSSG = false;
serveStreamingMetadata = false;
}
// In development, we always want to generate dynamic HTML.
let supportsDynamicResponse = // If we're in development, we always support dynamic HTML, unless it's
// a data request, in which case we only produce static HTML.
routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports
// dynamic HTML.
!isSSG || // If this request has provided postponed data, it supports dynamic
// HTML.
typeof initialPostponed === 'string' || // If this is a dynamic RSC request, then this render supports dynamic
// HTML (it's dynamic).
isDynamicRSCRequest;
// When html bots request PPR page, perform the full dynamic rendering.
const shouldWaitOnAllReady = isHtmlBot && isRoutePPREnabled;
let ssgCacheKey = null;
if (!isDraftMode && isSSG && !supportsDynamicResponse && !isPossibleServerAction && !minimalPostponed && !isDynamicRSCRequest) {
ssgCacheKey = resolvedPathname;
}
// the staticPathKey differs from ssgCacheKey since
// ssgCacheKey is null in dev since we're always in "dynamic"
// mode in dev to bypass the cache, but we still need to honor
// dynamicParams = false in dev mode
let staticPathKey = ssgCacheKey;
if (!staticPathKey && routeModule.isDev) {
staticPathKey = resolvedPathname;
}
// If this is a request for an app path that should be statically generated
// and we aren't in the edge runtime, strip the flight headers so it will
// generate the static response.
if (!routeModule.isDev && !isDraftMode && isSSG && isRSCRequest && !isDynamicRSCRequest) {
stripFlightHeaders(req.headers);
}
const ComponentMod = {
...entryBase,
tree,
pages,
GlobalError,
handler,
routeModule,
__next_app__
};
// Before rendering (which initializes component tree modules), we have to
// set the reference manifests to our global store so Server Action's
// encryption util can access to them at the top level of the page module.
if (serverActionsManifest && clientReferenceManifest) {
setReferenceManifestsSingleton({
page: srcPage,
clientReferenceManifest,
serverActionsManifest,
serverModuleMap: createServerModuleMap({
serverActionsManifest
})
});
}
const method = req.method || 'GET';
const tracer = getTracer();
const activeSpan = tracer.getActiveScopeSpan();
try {
const varyHeader = routeModule.getVaryHeader(resolvedPathname, interceptionRoutePatterns);
res.setHeader('Vary', varyHeader);
const invokeRouteModule = async (span, context)=>{
const nextReq = new NodeNextRequest(req);
const nextRes = new NodeNextResponse(res);
// TODO: adapt for putting the RDC inside the postponed data
// If we're in dev, and this isn't a prefetch or a server action,
// we should seed the resume data cache.
if (process.env.NODE_ENV === 'development') {
if (nextConfig.experimental.cacheComponents && !isPrefetchRSCRequest && !context.renderOpts.isPossibleServerAction) {
const warmup = await routeModule.warmup(nextReq, nextRes, context);
// If the warmup is successful, we should use the resume data
// cache from the warmup.
if (warmup.metadata.renderResumeDataCache) {
context.renderOpts.renderResumeDataCache = warmup.metadata.renderResumeDataCache;
}
}
}
return routeModule.render(nextReq, nextRes, context).finally(()=>{
if (!span) return;
span.setAttributes({
'http.status_code': res.statusCode,
'next.rsc': false
});
const rootSpanAttributes = tracer.getRootSpanAttributes();
// We were unable to get attributes, probably OTEL is not enabled
if (!rootSpanAttributes) {
return;
}
if (rootSpanAttributes.get('next.span_type') !== 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 = `${method} ${route}`;
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': name
});
span.updateName(name);
} else {
span.updateName(`${method} ${req.url}`);
}
});
};
const doRender = async ({ span, postponed, fallbackRouteParams })=>{
const context = {
query,
params,
page: normalizedSrcPage,
sharedContext: {
buildId
},
serverComponentsHmrCache: getRequestMeta(req, 'serverComponentsHmrCache'),
fallbackRouteParams,
renderOpts: {
App: ()=>null,
Document: ()=>null,
pageConfig: {},
ComponentMod,
Component: interopDefault(ComponentMod),
params,
routeModule,
page: srcPage,
postponed,
shouldWaitOnAllReady,
serveStreamingMetadata,
supportsDynamicResponse: typeof postponed === 'string' || supportsDynamicResponse,
buildManifest,
nextFontManifest,
reactLoadableManifest,
subresourceIntegrityManifest,
serverActionsManifest,
clientReferenceManifest,
setIsrStatus: routerServerContext == null ? void 0 : routerServerContext.setIsrStatus,
dir: process.env.NEXT_RUNTIME === 'nodejs' ? require('path').join(/* turbopackIgnore: true */ process.cwd(), routeModule.relativeProjectDir) : `${process.cwd()}/${routeModule.relativeProjectDir}`,
isDraftMode,
isRevalidate: isSSG && !postponed && !isDynamicRSCRequest,
botType,
isOnDemandRevalidate,
isPossibleServerAction,
assetPrefix: nextConfig.assetPrefix,
nextConfigOutput: nextConfig.output,
crossOrigin: nextConfig.crossOrigin,
trailingSlash: nextConfig.trailingSlash,
previewProps: prerenderManifest.preview,
deploymentId: nextConfig.deploymentId,
enableTainting: nextConfig.experimental.taint,
htmlLimitedBots: nextConfig.htmlLimitedBots,
devtoolSegmentExplorer: nextConfig.experimental.devtoolSegmentExplorer,
reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,
multiZoneDraftMode,
incrementalCache: getRequestMeta(req, 'incrementalCache'),
cacheLifeProfiles: nextConfig.experimental.cacheLife,
basePath: nextConfig.basePath,
serverActions: nextConfig.experimental.serverActions,
...isDebugStaticShell || isDebugDynamicAccesses ? {
nextExport: true,
supportsDynamicResponse: false,
isStaticGeneration: true,
isRevalidate: true,
isDebugDynamicAccesses: isDebugDynamicAccesses
} : {},
experimental: {
isRoutePPREnabled,
expireTime: nextConfig.expireTime,
staleTimes: nextConfig.experimental.staleTimes,
cacheComponents: Boolean(nextConfig.experimental.cacheComponents),
clientSegmentCache: Boolean(nextConfig.experimental.clientSegmentCache),
clientParamParsing: Boolean(nextConfig.experimental.clientParamParsing),
dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover),
inlineCss: Boolean(nextConfig.experimental.inlineCss),
authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
clientTraceMetadata: nextConfig.experimental.clientTraceMetadata || []
},
waitUntil: ctx.waitUntil,
onClose: (cb)=>{
res.on('close', cb);
},
onAfterTaskError: ()=>{},
onInstrumentationRequestError: (error, _request, errorContext)=>routeModule.onRequestError(req, error, errorContext, routerServerContext),
err: getRequestMeta(req, 'invokeError'),
dev: routeModule.isDev
}
};
const result = await invokeRouteModule(span, context);
const { metadata } = result;
const { cacheControl, headers = {}, // Add any fetch tags that were on the page to the response headers.
fetchTags: cacheTags } = metadata;
if (cacheTags) {
headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;
}
// Pull any fetch metrics from the render onto the request.
;
req.fetchMetrics = metadata.fetchMetrics;
// we don't throw static to dynamic errors in dev as isSSG
// is a best guess in dev since we don't have the prerender pass
// to know whether the path is actually static or not
if (isSSG && (cacheControl == null ? void 0 : cacheControl.revalidate) === 0 && !routeModule.isDev && !isRoutePPREnabled) {
const staticBailoutInfo = metadata.staticBailoutInfo;
const err = Object.defineProperty(new Error(`Page changed from static to dynamic at runtime ${resolvedPathname}${(staticBailoutInfo == null ? void 0 : staticBailoutInfo.description) ? `, reason: ${staticBailoutInfo.description}` : ``}` + `\nsee more here https://nextjs.org/docs/messages/app-static-to-dynamic-error`), "__NEXT_ERROR_CODE", {
value: "E132",
enumerable: false,
configurable: true
});
if (staticBailoutInfo == null ? void 0 : staticBailoutInfo.stack) {
const stack = staticBailoutInfo.stack;
err.stack = err.message + stack.substring(stack.indexOf('\n'));
}
throw err;
}
return {
value: {
kind: CachedRouteKind.APP_PAGE,
html: result,
headers,
rscData: metadata.flightData,
postponed: metadata.postponed,
status: metadata.statusCode,
segmentData: metadata.segmentData
},
cacheControl
};
};
const responseGenerator = async ({ hasResolved, previousCacheEntry, isRevalidating, span })=>{
const isProduction = routeModule.isDev === false;
const didRespond = hasResolved || res.writableEnded;
// skip on-demand revalidate if cache is not present and
// revalidate-if-generated is set
if (isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry && !minimalMode) {
if (routerServerContext == null ? void 0 : routerServerContext.render404) {
await routerServerContext.render404(req, res);
} else {
res.statusCode = 404;
res.end('This page could not be found');
}
return null;
}
let fallbackMode;
if (prerenderInfo) {
fallbackMode = parseFallbackField(prerenderInfo.fallback);
}
// When serving a HTML bot request, we want to serve a blocking render and
// not the prerendered page. This ensures that the correct content is served
// to the bot in the head.
if (fallbackMode === FallbackMode.PRERENDER && isBot(userAgent)) {
if (!isRoutePPREnabled || isHtmlBot) {
fallbackMode = FallbackMode.BLOCKING_STATIC_RENDER;
}
}
if ((previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) === -1) {
isOnDemandRevalidate = true;
}
// TODO: adapt for PPR
// only allow on-demand revalidate for fallback: true/blocking
// or for prerendered fallback: false paths
if (isOnDemandRevalidate && (fallbackMode !== FallbackMode.NOT_FOUND || previousCacheEntry)) {
fallbackMode = FallbackMode.BLOCKING_STATIC_RENDER;
}
if (!minimalMode && fallbackMode !== FallbackMode.BLOCKING_STATIC_RENDER && staticPathKey && !didRespond && !isDraftMode && pageIsDynamic && (isProduction || !isPrerendered)) {
// if the page has dynamicParams: false and this pathname wasn't
// prerendered trigger the no fallback handling
if (// In development, fall through to render to handle missing
// getStaticPaths.
(isProduction || prerenderInfo) && // When fallback isn't present, abort this render so we 404
fallbackMode === FallbackMode.NOT_FOUND) {
throw new NoFallbackError();
}
let fallbackResponse;
if (isRoutePPREnabled && !isRSCRequest) {
const cacheKey = typeof (prerenderInfo == null ? void 0 : prerenderInfo.fallback) === 'string' ? prerenderInfo.fallback : isProduction ? normalizedSrcPage : null;
// We use the response cache here to handle the revalidation and
// management of the fallback shell.
fallbackResponse = await routeModule.handleResponse({
cacheKey,
req,
nextConfig,
routeKind: RouteKind.APP_PAGE,
isFallback: true,
prerenderManifest,
isRoutePPREnabled,
responseGenerator: async ()=>doRender({
span,
// We pass `undefined` as rendering a fallback isn't resumed
// here.
postponed: undefined,
fallbackRouteParams: // If we're in production or we're debugging the fallback
// shell then we should postpone when dynamic params are
// accessed.
isProduction || isDebugFallbackShell ? getFallbackRouteParams(normalizedSrcPage) : null
}),
waitUntil: ctx.waitUntil
});
// If the fallback response was set to null, then we should return null.
if (fallbackResponse === null) return null;
// Otherwise, if we did get a fallback response, we should return it.
if (fallbackResponse) {
// Remove the cache control from the response to prevent it from being
// used in the surrounding cache.
delete fallbackResponse.cacheControl;
return fallbackResponse;
}
}
}
// Only requests that aren't revalidating can be resumed. If we have the
// minimal postponed data, then we should resume the render with it.
const postponed = !isOnDemandRevalidate && !isRevalidating && minimalPostponed ? minimalPostponed : undefined;
// When we're in minimal mode, if we're trying to debug the static shell,
// we should just return nothing instead of resuming the dynamic render.
if ((isDebugStaticShell || isDebugDynamicAccesses) && typeof postponed !== 'undefined') {
return {
cacheControl: {
revalidate: 1,
expire: undefined
},
value: {
kind: CachedRouteKind.PAGES,
html: RenderResult.EMPTY,
pageData: {},
headers: undefined,
status: undefined
}
};
}
// If this is a dynamic route with PPR enabled and the default route
// matches were set, then we should pass the fallback route params to
// the renderer as this is a fallback revalidation request.
const fallbackRouteParams = pageIsDynamic && isRoutePPREnabled && (getRequestMeta(req, 'renderFallbackShell') || isDebugFallbackShell) ? getFallbackRouteParams(pathname) : null;
// Perform the render.
return doRender({
span,
postponed,
fallbackRouteParams
});
};
const handleResponse = async (span)=>{
var _cacheEntry_value, _cachedData_headers;
const cacheEntry = await routeModule.handleResponse({
cacheKey: ssgCacheKey,
responseGenerator: (c)=>responseGenerator({
span,
...c
}),
routeKind: RouteKind.APP_PAGE,
isOnDemandRevalidate,
isRoutePPREnabled,
req,
nextConfig,
prerenderManifest,
waitUntil: ctx.waitUntil
});
if (isDraftMode) {
res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');
}
// In dev, we should not cache pages for any reason.
if (routeModule.isDev) {
res.setHeader('Cache-Control', 'no-store, must-revalidate');
}
if (!cacheEntry) {
if (ssgCacheKey) {
// A cache entry might not be generated if a response is written
// in `getInitialProps` or `getServerSideProps`, but those shouldn't
// have a cache key. If we do have a cache key but we don't end up
// with a cache entry, then either Next.js or the application has a
// bug that needs fixing.
throw Object.defineProperty(new Error('invariant: cache entry required but not generated'), "__NEXT_ERROR_CODE", {
value: "E62",
enumerable: false,
configurable: true
});
}
return null;
}
if (((_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_PAGE) {
var _cacheEntry_value1;
throw Object.defineProperty(new Error(`Invariant app-page handler received invalid cache entry ${(_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), "__NEXT_ERROR_CODE", {
value: "E707",
enumerable: false,
configurable: true
});
}
const didPostpone = typeof cacheEntry.value.postponed === 'string';
if (isSSG && // We don't want to send a cache header for requests that contain dynamic
// data. If this is a Dynamic RSC request or wasn't a Prefetch RSC
// request, then we should set the cache header.
!isDynamicRSCRequest && (!didPostpone || isPrefetchRSCRequest)) {
if (!minimalMode) {
// set x-nextjs-cache header to match the header
// we set for the image-optimizer
res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');
}
// Set a header used by the client router to signal the response is static
// and should respect the `static` cache staleTime value.
res.setHeader(NEXT_IS_PRERENDER_HEADER, '1');
}
const { value: cachedData } = cacheEntry;
// Coerce the cache control parameter from the render.
let cacheControl;
// If this is a resume request in minimal mode it is streamed with dynamic
// content and should not be cached.
if (minimalPostponed) {
cacheControl = {
revalidate: 0,
expire: undefined
};
} else if (minimalMode && isRSCRequest && !isPrefetchRSCRequest && isRoutePPREnabled) {
cacheControl = {
revalidate: 0,
expire: undefined
};
} else if (!routeModule.isDev) {
// If this is a preview mode request, we shouldn't cache it
if (isDraftMode) {
cacheControl = {
revalidate: 0,
expire: undefined
};
} else if (!isSSG) {
if (!res.getHeader('Cache-Control')) {
cacheControl = {
revalidate: 0,
expire: undefined
};
}
} else if (cacheEntry.cacheControl) {
// If the cache entry has a cache control with a revalidate value that's
// a number, use it.
if (typeof cacheEntry.cacheControl.revalidate === 'number') {
var _cacheEntry_cacheControl;
if (cacheEntry.cacheControl.revalidate < 1) {
throw Object.defineProperty(new Error(`Invalid revalidate configuration provided: ${cacheEntry.cacheControl.revalidate} < 1`), "__NEXT_ERROR_CODE", {
value: "E22",
enumerable: false,
configurable: true
});
}
cacheControl = {
revalidate: cacheEntry.cacheControl.revalidate,
expire: ((_cacheEntry_cacheControl = cacheEntry.cacheControl) == null ? void 0 : _cacheEntry_cacheControl.expire) ?? nextConfig.expireTime
};
} else {
cacheControl = {
revalidate: CACHE_ONE_YEAR,
expire: undefined
};
}
}
}
cacheEntry.cacheControl = cacheControl;
if (typeof segmentPrefetchHeader === 'string' && (cachedData == null ? void 0 : cachedData.kind) === CachedRouteKind.APP_PAGE && cachedData.segmentData) {
var _cachedData_headers1;
// This is a prefetch request issued by the client Segment Cache. These
// should never reach the application layer (lambda). We should either
// respond from the cache (HIT) or respond with 204 No Content (MISS).
// Set a header to indicate that PPR is enabled for this route. This
// lets the client distinguish between a regular cache miss and a cache
// miss due to PPR being disabled. In other contexts this header is used
// to indicate that the response contains dynamic data, but here we're
// only using it to indicate that the feature is enabled — the segment
// response itself contains whether the data is dynamic.
res.setHeader(NEXT_DID_POSTPONE_HEADER, '2');
// Add the cache tags header to the response if it exists and we're in
// minimal mode while rendering a static page.
const tags = (_cachedData_headers1 = cachedData.headers) == null ? void 0 : _cachedData_headers1[NEXT_CACHE_TAGS_HEADER];
if (minimalMode && isSSG && tags && typeof tags === 'string') {
res.setHeader(NEXT_CACHE_TAGS_HEADER, tags);
}
const matchedSegment = cachedData.segmentData.get(segmentPrefetchHeader);
if (matchedSegment !== undefined) {
// Cache hit
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result: RenderResult.fromStatic(matchedSegment, RSC_CONTENT_TYPE_HEADER),
cacheControl: cacheEntry.cacheControl
});
}
// Cache miss. Either a cache entry for this route has not been generated
// (which technically should not be possible when PPR is enabled, because
// at a minimum there should always be a fallback entry) or there's no
// match for the requested segment. Respond with a 204 No Content. We
// don't bother to respond with 404, because these requests are only
// issued as part of a prefetch.
res.statusCode = 204;
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result: RenderResult.EMPTY,
cacheControl: cacheEntry.cacheControl
});
}
// If there's a callback for `onCacheEntry`, call it with the cache entry
// and the revalidate options.
const onCacheEntry = getRequestMeta(req, 'onCacheEntry');
if (onCacheEntry) {
const finished = await onCacheEntry({
...cacheEntry,
// TODO: remove this when upstream doesn't
// always expect this value to be "PAGE"
value: {
...cacheEntry.value,
kind: 'PAGE'
}
}, {
url: getRequestMeta(req, 'initURL')
});
if (finished) {
// TODO: maybe we have to end the request?
return null;
}
}
// If the request has a postponed state and it's a resume request we
// should error.
if (didPostpone && minimalPostponed) {
throw Object.defineProperty(new Error('Invariant: postponed state should not be present on a resume request'), "__NEXT_ERROR_CODE", {
value: "E396",
enumerable: false,
configurable: true
});
}
if (cachedData.headers) {
const headers = {
...cachedData.headers
};
if (!minimalMode || !isSSG) {
delete headers[NEXT_CACHE_TAGS_HEADER];
}
for (let [key, value] of Object.entries(headers)){
if (typeof value === 'undefined') continue;
if (Array.isArray(value)) {
for (const v of value){
res.appendHeader(key, v);
}
} else if (typeof value === 'number') {
value = value.toString();
res.appendHeader(key, value);
} else {
res.appendHeader(key, value);
}
}
}
// Add the cache tags header to the response if it exists and we're in
// minimal mode while rendering a static page.
const tags = (_cachedData_headers = cachedData.headers) == null ? void 0 : _cachedData_headers[NEXT_CACHE_TAGS_HEADER];
if (minimalMode && isSSG && tags && typeof tags === 'string') {
res.setHeader(NEXT_CACHE_TAGS_HEADER, tags);
}
// If the request is a data request, then we shouldn't set the status code
// from the response because it should always be 200. This should be gated
// behind the experimental PPR flag.
if (cachedData.status && (!isRSCRequest || !isRoutePPREnabled)) {
res.statusCode = cachedData.status;
}
// Redirect information is encoded in RSC payload, so we don't need to use redirect status codes
if (!minimalMode && cachedData.status && RedirectStatusCode[cachedData.status] && isRSCRequest) {
res.statusCode = 200;
}
// Mark that the request did postpone.
if (didPostpone) {
res.setHeader(NEXT_DID_POSTPONE_HEADER, '1');
}
// we don't go through this block when preview mode is true
// as preview mode is a dynamic request (bypasses cache) and doesn't
// generate both HTML and payloads in the same request so continue to just
// return the generated payload
if (isRSCRequest && !isDraftMode) {
// If this is a dynamic RSC request, then stream the response.
if (typeof cachedData.rscData === 'undefined') {
if (cachedData.postponed) {
throw Object.defineProperty(new Error('Invariant: Expected postponed to be undefined'), "__NEXT_ERROR_CODE", {
value: "E372",
enumerable: false,
configurable: true
});
}
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result: cachedData.html,
// Dynamic RSC responses cannot be cached, even if they're
// configured with `force-static` because we have no way of
// distinguishing between `force-static` and pages that have no
// postponed state.
// TODO: distinguish `force-static` from pages with no postponed state (static)
cacheControl: isDynamicRSCRequest ? {
revalidate: 0,
expire: undefined
} : cacheEntry.cacheControl
});
}
// As this isn't a prefetch request, we should serve the static flight
// data.
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result: RenderResult.fromStatic(cachedData.rscData, RSC_CONTENT_TYPE_HEADER),
cacheControl: cacheEntry.cacheControl
});
}
// This is a request for HTML data.
let body = cachedData.html;
// If there's no postponed state, we should just serve the HTML. This
// should also be the case for a resume request because it's completed
// as a server render (rather than a static render).
if (!didPostpone || minimalMode || isRSCRequest) {
// If we're in test mode, we should add a sentinel chunk to the response
// that's between the static and dynamic parts so we can compare the
// chunks and add assertions.
if (process.env.__NEXT_TEST_MODE && minimalMode && isRoutePPREnabled && body.contentType === HTML_CONTENT_TYPE_HEADER) {
// As we're in minimal mode, the static part would have already been
// streamed first. The only part that this streams is the dynamic part
// so we should FIRST stream the sentinel and THEN the dynamic part.
body.unshift(createPPRBoundarySentinel());
}
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result: body,
cacheControl: cacheEntry.cacheControl
});
}
// If we're debugging the static shell or the dynamic API accesses, we
// should just serve the HTML without resuming the render. The returned
// HTML will be the static shell so all the Dynamic API's will be used
// during static generation.
if (isDebugStaticShell || isDebugDynamicAccesses) {
// Since we're not resuming the render, we need to at least add the
// closing body and html tags to create valid HTML.
body.push(new ReadableStream({
start (controller) {
controller.enqueue(ENCODED_TAGS.CLOSED.BODY_AND_HTML);
controller.close();
}
}));
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result: body,
cacheControl: {
revalidate: 0,
expire: undefined
}
});
}
// If we're in test mode, we should add a sentinel chunk to the response
// that's between the static and dynamic parts so we can compare the
// chunks and add assertions.
if (process.env.__NEXT_TEST_MODE) {
body.push(createPPRBoundarySentinel());
}
// This request has postponed, so let's create a new transformer that the
// dynamic data can pipe to that will attach the dynamic data to the end
// of the response.
const transformer = new TransformStream();
body.push(transformer.readable);
// Perform the render again, but this time, provide the postponed state.
// We don't await because we want the result to start streaming now, and
// we've already chained the transformer's readable to the render result.
doRender({
span,
postponed: cachedData.postponed,
// This is a resume render, not a fallback render, so we don't need to
// set this.
fallbackRouteParams: null
}).then(async (result)=>{
var _result_value;
if (!result) {
throw Object.defineProperty(new Error('Invariant: expected a result to be returned'), "__NEXT_ERROR_CODE", {
value: "E463",
enumerable: false,
configurable: true
});
}
if (((_result_value = result.value) == null ? void 0 : _result_value.kind) !== CachedRouteKind.APP_PAGE) {
var _result_value1;
throw Object.defineProperty(new Error(`Invariant: expected a page response, got ${(_result_value1 = result.value) == null ? void 0 : _result_value1.kind}`), "__NEXT_ERROR_CODE", {
value: "E305",
enumerable: false,
configurable: true
});
}
// Pipe the resume result to the transformer.
await result.value.html.pipeTo(transformer.writable);
}).catch((err)=>{
// An error occurred during piping or preparing the render, abort
// the transformers writer so we can terminate the stream.
transformer.writable.abort(err).catch((e)=>{
console.error("couldn't abort transformer", e);
});
});
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result: body,
// We don't want to cache the response if it has postponed data because
// the response being sent to the client it's dynamic parts are streamed
// to the client on the same request.
cacheControl: {
revalidate: 0,
expire: undefined
}
});
};
// TODO: activeSpan code path is for when wrapped by
// next-server can be removed when this is no longer used
if (activeSpan) {
await handleResponse(activeSpan);
} else {
return await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {
spanName: `${method} ${req.url}`,
kind: SpanKind.SERVER,
attributes: {
'http.method': method,
'http.target': req.url
}
}, handleResponse));
}
} catch (err) {
if (!(err instanceof NoFallbackError)) {
await routeModule.onRequestError(req, err, {
routerKind: 'App Router',
routePath: srcPage,
routeType: 'render',
revalidateReason: getRevalidateReason({
isRevalidate: isSSG,
isOnDemandRevalidate
})
}, routerServerContext);
}
// rethrow so that we can handle serving error page
throw err;
}
}
// TODO: omit this from production builds, only test builds should include it
/**
* Creates a readable stream that emits a PPR boundary sentinel.
*
* @returns A readable stream that emits a PPR boundary sentinel.
*/ function createPPRBoundarySentinel() {
return new ReadableStream({
start (controller) {
controller.enqueue(new TextEncoder().encode('<!-- PPR_BOUNDARY_SENTINEL -->'));
controller.close();
}
});
}
//# sourceMappingURL=app-page.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,313 @@
import { AppRouteRouteModule } from '../../server/route-modules/app-route/module.compiled';
import { RouteKind } from '../../server/route-kind';
import { patchFetch as _patchFetch } from '../../server/lib/patch-fetch';
import { getRequestMeta } from '../../server/request-meta';
import { getTracer, SpanKind } from '../../server/lib/trace/tracer';
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths';
import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node';
import { NextRequestAdapter, signalFromNodeResponse } from '../../server/web/spec-extension/adapters/next-request';
import { BaseServerSpan } from '../../server/lib/trace/constants';
import { getRevalidateReason } from '../../server/instrumentation/utils';
import { sendResponse } from '../../server/send-response';
import { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from '../../server/web/utils';
import { getCacheControlHeader } from '../../server/lib/cache-control';
import { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from '../../lib/constants';
import { NoFallbackError } from '../../shared/lib/no-fallback-error.external';
import { CachedRouteKind } from '../../server/response-cache';
import * as userland from 'VAR_USERLAND';
// We inject the nextConfigOutput here so that we can use them in the route
// module.
// INJECT:nextConfigOutput
const routeModule = new AppRouteRouteModule({
definition: {
kind: RouteKind.APP_ROUTE,
page: 'VAR_DEFINITION_PAGE',
pathname: 'VAR_DEFINITION_PATHNAME',
filename: 'VAR_DEFINITION_FILENAME',
bundlePath: 'VAR_DEFINITION_BUNDLE_PATH'
},
distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',
relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',
resolvedPagePath: 'VAR_RESOLVED_PAGE_PATH',
nextConfigOutput,
userland
});
// Pull out the exports that we need to expose from the module. This should
// be eliminated when we've moved the other routes to the new format. These
// are used to hook into the route.
const { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;
function patchFetch() {
return _patchFetch({
workAsyncStorage,
workUnitAsyncStorage
});
}
export { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };
export async function handler(req, res, ctx) {
var _nextConfig_experimental;
let srcPage = 'VAR_DEFINITION_PAGE';
// turbopack doesn't normalize `/index` in the page name
// so we need to to process dynamic routes properly
// TODO: fix turbopack providing differing value from webpack
if (process.env.TURBOPACK) {
srcPage = srcPage.replace(/\/index$/, '') || '/';
} else if (srcPage === '/index') {
// we always normalize /index specifically
srcPage = '/';
}
const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;
const prepareResult = await routeModule.prepare(req, res, {
srcPage,
multiZoneDraftMode
});
if (!prepareResult) {
res.statusCode = 400;
res.end('Bad Request');
ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());
return null;
}
const { buildId, params, nextConfig, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname } = prepareResult;
const normalizedSrcPage = normalizeAppPath(srcPage);
let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);
if (isIsr && !isDraftMode) {
const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);
const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];
if (prerenderInfo) {
if (prerenderInfo.fallback === false && !isPrerendered) {
throw new NoFallbackError();
}
}
}
let cacheKey = null;
if (isIsr && !routeModule.isDev && !isDraftMode) {
cacheKey = resolvedPathname;
// ensure /index and / is normalized to one key
cacheKey = cacheKey === '/index' ? '/' : cacheKey;
}
const supportsDynamicResponse = // If we're in development, we always support dynamic HTML
routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports
// dynamic HTML.
!isIsr;
// This is a revalidation request if the request is for a static
// page and it is not being resumed from a postponed render and
// it is not a dynamic RSC request then it is a revalidation
// request.
const isRevalidate = isIsr && !supportsDynamicResponse;
const method = req.method || 'GET';
const tracer = getTracer();
const activeSpan = tracer.getActiveScopeSpan();
const context = {
params,
prerenderManifest,
renderOpts: {
experimental: {
cacheComponents: Boolean(nextConfig.experimental.cacheComponents),
authInterrupts: Boolean(nextConfig.experimental.authInterrupts)
},
supportsDynamicResponse,
incrementalCache: getRequestMeta(req, 'incrementalCache'),
cacheLifeProfiles: (_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : _nextConfig_experimental.cacheLife,
isRevalidate,
waitUntil: ctx.waitUntil,
onClose: (cb)=>{
res.on('close', cb);
},
onAfterTaskError: undefined,
onInstrumentationRequestError: (error, _request, errorContext)=>routeModule.onRequestError(req, error, errorContext, routerServerContext)
},
sharedContext: {
buildId
}
};
const nodeNextReq = new NodeNextRequest(req);
const nodeNextRes = new NodeNextResponse(res);
const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));
try {
const invokeRouteModule = async (span)=>{
return routeModule.handle(nextReq, context).finally(()=>{
if (!span) return;
span.setAttributes({
'http.status_code': res.statusCode,
'next.rsc': false
});
const rootSpanAttributes = tracer.getRootSpanAttributes();
// We were unable to get attributes, probably OTEL is not enabled
if (!rootSpanAttributes) {
return;
}
if (rootSpanAttributes.get('next.span_type') !== 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 = `${method} ${route}`;
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': name
});
span.updateName(name);
} else {
span.updateName(`${method} ${req.url}`);
}
});
};
const handleResponse = async (currentSpan)=>{
var _cacheEntry_value;
const responseGenerator = async ({ previousCacheEntry })=>{
try {
if (!getRequestMeta(req, 'minimalMode') && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {
res.statusCode = 404;
// on-demand revalidate always sets this header
res.setHeader('x-nextjs-cache', 'REVALIDATED');
res.end('This page could not be found');
return null;
}
const response = await invokeRouteModule(currentSpan);
req.fetchMetrics = context.renderOpts.fetchMetrics;
let pendingWaitUntil = context.renderOpts.pendingWaitUntil;
// Attempt using provided waitUntil if available
// if it's not we fallback to sendResponse's handling
if (pendingWaitUntil) {
if (ctx.waitUntil) {
ctx.waitUntil(pendingWaitUntil);
pendingWaitUntil = undefined;
}
}
const cacheTags = context.renderOpts.collectedTags;
// If the request is for a static response, we can cache it so long
// as it's not edge.
if (isIsr) {
const blob = await response.blob();
// Copy the headers from the response.
const headers = toNodeOutgoingHttpHeaders(response.headers);
if (cacheTags) {
headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;
}
if (!headers['content-type'] && blob.type) {
headers['content-type'] = blob.type;
}
const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;
const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;
// Create the cache entry for the response.
const cacheEntry = {
value: {
kind: CachedRouteKind.APP_ROUTE,
status: response.status,
body: Buffer.from(await blob.arrayBuffer()),
headers
},
cacheControl: {
revalidate,
expire
}
};
return cacheEntry;
} else {
// send response without caching if not ISR
await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);
return null;
}
} catch (err) {
// if this is a background revalidate we need to report
// the request error here as it won't be bubbled
if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {
await routeModule.onRequestError(req, err, {
routerKind: 'App Router',
routePath: srcPage,
routeType: 'route',
revalidateReason: getRevalidateReason({
isRevalidate,
isOnDemandRevalidate
})
}, routerServerContext);
}
throw err;
}
};
const cacheEntry = await routeModule.handleResponse({
req,
nextConfig,
cacheKey,
routeKind: RouteKind.APP_ROUTE,
isFallback: false,
prerenderManifest,
isRoutePPREnabled: false,
isOnDemandRevalidate,
revalidateOnlyGenerated,
responseGenerator,
waitUntil: ctx.waitUntil
});
// we don't create a cacheEntry for ISR
if (!isIsr) {
return null;
}
if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {
var _cacheEntry_value1;
throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), "__NEXT_ERROR_CODE", {
value: "E701",
enumerable: false,
configurable: true
});
}
if (!getRequestMeta(req, 'minimalMode')) {
res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');
}
// Draft mode should never be cached
if (isDraftMode) {
res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');
}
const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);
if (!(getRequestMeta(req, 'minimalMode') && isIsr)) {
headers.delete(NEXT_CACHE_TAGS_HEADER);
}
// If cache control is already set on the response we don't
// override it to allow users to customize it via next.config
if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {
headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));
}
await sendResponse(nodeNextReq, nodeNextRes, new Response(cacheEntry.value.body, {
headers,
status: cacheEntry.value.status || 200
}));
return null;
};
// TODO: activeSpan code path is for when wrapped by
// next-server can be removed when this is no longer used
if (activeSpan) {
await handleResponse(activeSpan);
} else {
await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {
spanName: `${method} ${req.url}`,
kind: SpanKind.SERVER,
attributes: {
'http.method': method,
'http.target': req.url
}
}, handleResponse));
}
} catch (err) {
if (!(err instanceof NoFallbackError)) {
await routeModule.onRequestError(req, err, {
routerKind: 'App Router',
routePath: normalizedSrcPage,
routeType: 'route',
revalidateReason: getRevalidateReason({
isRevalidate,
isOnDemandRevalidate
})
});
}
// rethrow so that we can handle serving error page
// If this is during static generation, throw the error again.
if (isIsr) throw err;
// Otherwise, send a 500 response.
await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {
status: 500
}));
return null;
}
}
//# sourceMappingURL=app-route.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,26 @@
var _self___RSC_MANIFEST;
import { createServerModuleMap } from '../../server/app-render/action-utils';
import { setReferenceManifestsSingleton } from '../../server/app-render/encryption-utils';
import { EdgeRouteModuleWrapper } from '../../server/web/edge-route-module-wrapper';
// Import the userland code.
import * as module from 'VAR_USERLAND';
// INJECT:nextConfig
const maybeJSONParse = (str)=>str ? JSON.parse(str) : undefined;
const rscManifest = (_self___RSC_MANIFEST = self.__RSC_MANIFEST) == null ? void 0 : _self___RSC_MANIFEST['VAR_PAGE'];
const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST);
if (rscManifest && rscServerManifest) {
setReferenceManifestsSingleton({
page: 'VAR_PAGE',
clientReferenceManifest: rscManifest,
serverActionsManifest: rscServerManifest,
serverModuleMap: createServerModuleMap({
serverActionsManifest: rscServerManifest
})
});
}
export const ComponentMod = module;
export default EdgeRouteModuleWrapper.wrap(module.routeModule, {
nextConfig
});
//# sourceMappingURL=edge-app-route.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/templates/edge-app-route.ts"],"sourcesContent":["import { createServerModuleMap } from '../../server/app-render/action-utils'\nimport { setReferenceManifestsSingleton } from '../../server/app-render/encryption-utils'\nimport type { NextConfigComplete } from '../../server/config-shared'\nimport { EdgeRouteModuleWrapper } from '../../server/web/edge-route-module-wrapper'\n\n// Import the userland code.\nimport * as module from 'VAR_USERLAND'\n\n// injected by the loader afterwards.\ndeclare const nextConfig: NextConfigComplete\n// INJECT:nextConfig\n\nconst maybeJSONParse = (str?: string) => (str ? JSON.parse(str) : undefined)\n\nconst rscManifest = self.__RSC_MANIFEST?.['VAR_PAGE']\nconst rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST)\n\nif (rscManifest && rscServerManifest) {\n setReferenceManifestsSingleton({\n page: 'VAR_PAGE',\n clientReferenceManifest: rscManifest,\n serverActionsManifest: rscServerManifest,\n serverModuleMap: createServerModuleMap({\n serverActionsManifest: rscServerManifest,\n }),\n })\n}\n\nexport const ComponentMod = module\n\nexport default EdgeRouteModuleWrapper.wrap(module.routeModule, { nextConfig })\n"],"names":["self","createServerModuleMap","setReferenceManifestsSingleton","EdgeRouteModuleWrapper","module","maybeJSONParse","str","JSON","parse","undefined","rscManifest","__RSC_MANIFEST","rscServerManifest","__RSC_SERVER_MANIFEST","page","clientReferenceManifest","serverActionsManifest","serverModuleMap","ComponentMod","wrap","routeModule","nextConfig"],"mappings":"IAcoBA;AAdpB,SAASC,qBAAqB,QAAQ,uCAAsC;AAC5E,SAASC,8BAA8B,QAAQ,2CAA0C;AAEzF,SAASC,sBAAsB,QAAQ,6CAA4C;AAEnF,4BAA4B;AAC5B,YAAYC,YAAY,eAAc;AAItC,oBAAoB;AAEpB,MAAMC,iBAAiB,CAACC,MAAkBA,MAAMC,KAAKC,KAAK,CAACF,OAAOG;AAElE,MAAMC,eAAcV,uBAAAA,KAAKW,cAAc,qBAAnBX,oBAAqB,CAAC,WAAW;AACrD,MAAMY,oBAAoBP,eAAeL,KAAKa,qBAAqB;AAEnE,IAAIH,eAAeE,mBAAmB;IACpCV,+BAA+B;QAC7BY,MAAM;QACNC,yBAAyBL;QACzBM,uBAAuBJ;QACvBK,iBAAiBhB,sBAAsB;YACrCe,uBAAuBJ;QACzB;IACF;AACF;AAEA,OAAO,MAAMM,eAAed,OAAM;AAElC,eAAeD,uBAAuBgB,IAAI,CAACf,OAAOgB,WAAW,EAAE;IAAEC;AAAW,GAAE","ignoreList":[0]}

View File

@@ -0,0 +1,252 @@
var _self___RSC_MANIFEST;
import '../../server/web/globals';
import { adapter } from '../../server/web/adapter';
import { IncrementalCache } from '../../server/lib/incremental-cache';
import * as pageMod from 'VAR_USERLAND';
import { setReferenceManifestsSingleton } from '../../server/app-render/encryption-utils';
import { createServerModuleMap } from '../../server/app-render/action-utils';
import { initializeCacheHandlers } from '../../server/use-cache/handlers';
import { BaseServerSpan } from '../../server/lib/trace/constants';
import { getTracer, SpanKind } from '../../server/lib/trace/tracer';
import { WebNextRequest, WebNextResponse } from '../../server/base-http/web';
import { getIsPossibleServerAction } from '../../server/lib/server-action-request-meta';
import { getBotType } from '../../shared/lib/router/utils/is-bot';
import { interopDefault } from '../../lib/interop-default';
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths';
import { checkIsOnDemandRevalidate } from '../../server/api-utils';
import { CloseController } from '../../server/web/web-on-close';
// OPTIONAL_IMPORT:incrementalCacheHandler
// Initialize the cache handlers interface.
initializeCacheHandlers();
// INJECT:nextConfig
const maybeJSONParse = (str)=>str ? JSON.parse(str) : undefined;
const rscManifest = (_self___RSC_MANIFEST = self.__RSC_MANIFEST) == null ? void 0 : _self___RSC_MANIFEST['VAR_PAGE'];
const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST);
if (rscManifest && rscServerManifest) {
setReferenceManifestsSingleton({
page: 'VAR_PAGE',
clientReferenceManifest: rscManifest,
serverActionsManifest: rscServerManifest,
serverModuleMap: createServerModuleMap({
serverActionsManifest: rscServerManifest
})
});
}
export const ComponentMod = pageMod;
async function requestHandler(req, event) {
let srcPage = 'VAR_PAGE';
const normalizedSrcPage = normalizeAppPath(srcPage);
const relativeUrl = `${req.nextUrl.pathname}${req.nextUrl.search}`;
const baseReq = new WebNextRequest(req);
const baseRes = new WebNextResponse(undefined);
const pageRouteModule = pageMod.routeModule;
const prepareResult = await pageRouteModule.prepare(baseReq, null, {
srcPage,
multiZoneDraftMode: false
});
if (!prepareResult) {
return new Response('Bad Request', {
status: 400
});
}
const { query, params, buildId, buildManifest, prerenderManifest, reactLoadableManifest, clientReferenceManifest, subresourceIntegrityManifest, dynamicCssManifest, nextFontManifest, resolvedPathname, serverActionsManifest, interceptionRoutePatterns, routerServerContext } = prepareResult;
const isPossibleServerAction = getIsPossibleServerAction(req);
const botType = getBotType(req.headers.get('User-Agent') || '');
const { isOnDemandRevalidate } = checkIsOnDemandRevalidate(req, prerenderManifest.preview);
const closeController = new CloseController();
const renderContext = {
page: normalizedSrcPage,
query,
params,
sharedContext: {
buildId
},
fallbackRouteParams: null,
renderOpts: {
App: ()=>null,
Document: ()=>null,
pageConfig: {},
ComponentMod,
Component: interopDefault(ComponentMod),
routeModule: pageRouteModule,
params,
page: srcPage,
postponed: undefined,
shouldWaitOnAllReady: false,
serveStreamingMetadata: true,
supportsDynamicResponse: true,
buildManifest,
nextFontManifest,
reactLoadableManifest,
subresourceIntegrityManifest,
dynamicCssManifest,
serverActionsManifest,
clientReferenceManifest,
setIsrStatus: routerServerContext == null ? void 0 : routerServerContext.setIsrStatus,
dir: pageRouteModule.relativeProjectDir,
botType,
isDraftMode: false,
isRevalidate: false,
isOnDemandRevalidate,
isPossibleServerAction,
assetPrefix: nextConfig.assetPrefix,
nextConfigOutput: nextConfig.output,
crossOrigin: nextConfig.crossOrigin,
trailingSlash: nextConfig.trailingSlash,
previewProps: prerenderManifest.preview,
deploymentId: nextConfig.deploymentId,
enableTainting: nextConfig.experimental.taint,
htmlLimitedBots: nextConfig.htmlLimitedBots,
devtoolSegmentExplorer: nextConfig.experimental.devtoolSegmentExplorer,
reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,
multiZoneDraftMode: false,
cacheLifeProfiles: nextConfig.experimental.cacheLife,
basePath: nextConfig.basePath,
serverActions: nextConfig.experimental.serverActions,
experimental: {
isRoutePPREnabled: false,
expireTime: nextConfig.expireTime,
staleTimes: nextConfig.experimental.staleTimes,
cacheComponents: Boolean(nextConfig.experimental.cacheComponents),
clientSegmentCache: Boolean(nextConfig.experimental.clientSegmentCache),
clientParamParsing: Boolean(nextConfig.experimental.clientParamParsing),
dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover),
inlineCss: Boolean(nextConfig.experimental.inlineCss),
authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
clientTraceMetadata: nextConfig.experimental.clientTraceMetadata || []
},
incrementalCache: await pageRouteModule.getIncrementalCache(baseReq, nextConfig, prerenderManifest),
waitUntil: event.waitUntil.bind(event),
onClose: (cb)=>{
closeController.onClose(cb);
},
onAfterTaskError: ()=>{},
onInstrumentationRequestError: (error, _request, errorContext)=>pageRouteModule.onRequestError(baseReq, error, errorContext, routerServerContext),
dev: pageRouteModule.isDev
}
};
let finalStatus = 200;
const renderResultToResponse = (result)=>{
const varyHeader = pageRouteModule.getVaryHeader(resolvedPathname, interceptionRoutePatterns);
// Handle null responses
if (result.isNull) {
finalStatus = 500;
closeController.dispatchClose();
return new Response(null, {
status: 500
});
}
// Extract metadata
const { metadata } = result;
const headers = new Headers();
finalStatus = metadata.statusCode || baseRes.statusCode || 200;
req.fetchMetrics = metadata.fetchMetrics;
// Set content type
const contentType = result.contentType || 'text/html; charset=utf-8';
headers.set('Content-Type', contentType);
headers.set('x-edge-runtime', '1');
if (varyHeader) {
headers.set('Vary', varyHeader);
}
// Add existing headers
for (const [key, value] of Object.entries({
...baseRes.getHeaders(),
...metadata.headers
})){
if (value !== undefined) {
if (Array.isArray(value)) {
// Handle multiple header values
for (const v of value){
headers.append(key, String(v));
}
} else {
headers.set(key, String(value));
}
}
}
// Handle static response
if (!result.isDynamic) {
const body = result.toUnchunkedString();
headers.set('Content-Length', String(new TextEncoder().encode(body).length));
closeController.dispatchClose();
return new Response(body, {
status: finalStatus,
headers
});
}
// Handle dynamic/streaming response
// For edge runtime, we need to create a readable stream that pipes from the result
const { readable, writable } = new TransformStream();
// Start piping the result to the writable stream
// This is done asynchronously to avoid blocking the response creation
result.pipeTo(writable).catch((err)=>{
console.error('Error piping RenderResult to response:', err);
}).finally(()=>closeController.dispatchClose());
return new Response(readable, {
status: finalStatus,
headers
});
};
const invokeRender = async (span)=>{
try {
const result = await pageRouteModule.render(baseReq, baseRes, renderContext).finally(()=>{
if (!span) return;
span.setAttributes({
'http.status_code': finalStatus,
'next.rsc': false
});
const rootSpanAttributes = tracer.getRootSpanAttributes();
// We were unable to get attributes, probably OTEL is not enabled
if (!rootSpanAttributes) {
return;
}
if (rootSpanAttributes.get('next.span_type') !== 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 = normalizedSrcPage;
if (route) {
const name = `${req.method} ${route}`;
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': name
});
span.updateName(name);
} else {
span.updateName(`${req.method} ${relativeUrl}`);
}
});
return renderResultToResponse(result);
} catch (err) {
await pageRouteModule.onRequestError(baseReq, err, {
routerKind: 'App Router',
routePath: normalizedSrcPage,
routeType: 'render',
revalidateReason: undefined
});
// rethrow so that we can handle serving error page
throw err;
}
};
const tracer = getTracer();
return tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {
spanName: `${req.method} ${relativeUrl}`,
kind: SpanKind.SERVER,
attributes: {
'http.method': req.method,
'http.target': relativeUrl,
'http.route': normalizedSrcPage
}
}, invokeRender));
}
export default function nHandler(opts) {
return adapter({
...opts,
IncrementalCache,
handler: requestHandler,
incrementalCacheHandler
});
}
//# sourceMappingURL=edge-ssr-app.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,268 @@
import '../../server/web/globals';
import { adapter } from '../../server/web/adapter';
import { IncrementalCache } from '../../server/lib/incremental-cache';
import { initializeCacheHandlers } from '../../server/use-cache/handlers';
import Document from 'VAR_MODULE_DOCUMENT';
import * as appMod from 'VAR_MODULE_APP';
import * as userlandPage from 'VAR_USERLAND';
import * as userlandErrorPage from 'VAR_MODULE_GLOBAL_ERROR';
// OPTIONAL_IMPORT:* as userland500Page
// OPTIONAL_IMPORT:incrementalCacheHandler
import RouteModule from '../../server/route-modules/pages/module';
import { WebNextRequest, WebNextResponse } from '../../server/base-http/web';
import { getTracer, SpanKind } from '../../server/lib/trace/tracer';
import { BaseServerSpan } from '../../server/lib/trace/constants';
import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants';
// INJECT:nextConfig
// INJECT:pageRouteModuleOptions
// INJECT:errorRouteModuleOptions
// INJECT:user500RouteModuleOptions
// Initialize the cache handlers interface.
initializeCacheHandlers();
globalThis.nextConfig = nextConfig;
const pageMod = {
...userlandPage,
routeModule: new RouteModule({
...pageRouteModuleOptions,
components: {
App: appMod.default,
Document
},
userland: userlandPage
})
};
const errorMod = {
...userlandErrorPage,
routeModule: new RouteModule({
...errorRouteModuleOptions,
components: {
App: appMod.default,
Document
},
userland: userlandErrorPage
})
};
// FIXME: this needs to be made compatible with the template
const error500Mod = userland500Page ? {
...userland500Page,
routeModule: new RouteModule({
...user500RouteModuleOptions,
components: {
App: appMod.default,
Document
},
userland: userland500Page
})
} : null;
export const ComponentMod = pageMod;
async function requestHandler(req, _event) {
var _nextConfig_experimental_amp, _nextConfig_i18n;
let srcPage = 'VAR_PAGE';
const relativeUrl = `${req.nextUrl.pathname}${req.nextUrl.search}`;
const baseReq = new WebNextRequest(req);
const pageRouteModule = pageMod.routeModule;
const prepareResult = await pageRouteModule.prepare(baseReq, null, {
srcPage,
multiZoneDraftMode: false
});
if (!prepareResult) {
return new Response('Bad Request', {
status: 400
});
}
const { query, params, buildId, isNextDataRequest, buildManifest, prerenderManifest, reactLoadableManifest, clientReferenceManifest, subresourceIntegrityManifest, dynamicCssManifest } = prepareResult;
const renderContext = {
page: srcPage,
query,
params,
sharedContext: {
buildId,
deploymentId: process.env.NEXT_DEPLOYMENT_ID,
customServer: undefined
},
renderContext: {
isFallback: false,
isDraftMode: false,
developmentNotFoundSourcePage: undefined
},
renderOpts: {
params,
page: srcPage,
supportsDynamicResponse: true,
Component: pageMod.Component,
ComponentMod: pageMod,
pageConfig: pageMod.pageConfig,
routeModule: pageMod.routeModule,
canonicalBase: nextConfig.amp.canonicalBase || '',
previewProps: prerenderManifest.preview,
ampOptimizerConfig: (_nextConfig_experimental_amp = nextConfig.experimental.amp) == null ? void 0 : _nextConfig_experimental_amp.optimizer,
basePath: nextConfig.basePath,
assetPrefix: nextConfig.assetPrefix,
images: nextConfig.images,
optimizeCss: nextConfig.experimental.optimizeCss,
nextConfigOutput: nextConfig.output,
nextScriptWorkers: nextConfig.experimental.nextScriptWorkers,
disableOptimizedLoading: nextConfig.experimental.disableOptimizedLoading,
domainLocales: (_nextConfig_i18n = nextConfig.i18n) == null ? void 0 : _nextConfig_i18n.domains,
distDir: '',
crossOrigin: nextConfig.crossOrigin ? nextConfig.crossOrigin : undefined,
largePageDataBytes: nextConfig.experimental.largePageDataBytes,
// Only the `publicRuntimeConfig` key is exposed to the client side
// It'll be rendered as part of __NEXT_DATA__ on the client side
runtimeConfig: Object.keys(nextConfig.publicRuntimeConfig).length > 0 ? nextConfig.publicRuntimeConfig : undefined,
isExperimentalCompile: nextConfig.experimental.isExperimentalCompile,
// `htmlLimitedBots` is passed to server as serialized config in string format
experimental: {
clientTraceMetadata: nextConfig.experimental.clientTraceMetadata
},
buildManifest,
subresourceIntegrityManifest,
reactLoadableManifest,
clientReferenceManifest,
dynamicCssManifest
}
};
let finalStatus = 200;
const renderResultToResponse = (result)=>{
// Handle null responses
if (result.isNull) {
finalStatus = 500;
return new Response(null, {
status: 500
});
}
// Extract metadata
const { metadata } = result;
finalStatus = metadata.statusCode || 200;
const headers = new Headers();
// Set content type
const contentType = result.contentType || HTML_CONTENT_TYPE_HEADER;
headers.set('Content-Type', contentType);
// Add metadata headers
if (metadata.headers) {
for (const [key, value] of Object.entries(metadata.headers)){
if (value !== undefined) {
if (Array.isArray(value)) {
// Handle multiple header values
for (const v of value){
headers.append(key, String(v));
}
} else {
headers.set(key, String(value));
}
}
}
}
// Handle static response
if (!result.isDynamic) {
const body = result.toUnchunkedString();
headers.set('Content-Length', String(new TextEncoder().encode(body).length));
return new Response(body, {
status: finalStatus,
headers
});
}
// Handle dynamic/streaming response
// For edge runtime, we need to create a readable stream that pipes from the result
const { readable, writable } = new TransformStream();
// Start piping the result to the writable stream
// This is done asynchronously to avoid blocking the response creation
result.pipeTo(writable).catch((err)=>{
console.error('Error piping RenderResult to response:', err);
});
return new Response(readable, {
status: finalStatus,
headers
});
};
const invokeRender = async (span)=>{
try {
const result = await pageRouteModule.render(// @ts-expect-error we don't type this for edge
baseReq, new WebNextResponse(undefined), {
...renderContext,
renderOpts: {
...renderContext.renderOpts,
getServerSideProps: pageMod.getServerSideProps,
Component: pageMod.default || pageMod,
ComponentMod: pageMod,
pageConfig: pageMod.config,
isNextDataRequest
}
}).finally(()=>{
if (!span) return;
span.setAttributes({
'http.status_code': finalStatus,
'next.rsc': false
});
const rootSpanAttributes = tracer.getRootSpanAttributes();
// We were unable to get attributes, probably OTEL is not enabled
if (!rootSpanAttributes) {
return;
}
if (rootSpanAttributes.get('next.span_type') !== 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 = `${req.method} ${route}`;
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': name
});
span.updateName(name);
} else {
span.updateName(`${req.method} ${relativeUrl}`);
}
});
return renderResultToResponse(result);
} catch (err) {
const errModule = error500Mod || errorMod;
const errRouteModule = errModule.routeModule;
if (errRouteModule.isDev) {
throw err;
}
await errRouteModule.onRequestError(baseReq, err, {
routerKind: 'Pages Router',
routePath: srcPage,
routeType: 'render',
revalidateReason: undefined
});
const errResult = await errRouteModule.render(// @ts-expect-error we don't type this for edge
baseReq, new WebNextResponse(undefined), {
...renderContext,
page: error500Mod ? '/500' : '/_error',
renderOpts: {
...renderContext.renderOpts,
getServerSideProps: errModule.getServerSideProps,
Component: errModule.default || errModule,
ComponentMod: errModule,
pageConfig: errModule.config
}
});
return renderResultToResponse(errResult);
}
};
const tracer = getTracer();
return tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {
spanName: `${req.method} ${relativeUrl}`,
kind: SpanKind.SERVER,
attributes: {
'http.method': req.method,
'http.target': relativeUrl,
'http.route': srcPage
}
}, invokeRender));
}
export default function nHandler(opts) {
return adapter({
...opts,
IncrementalCache,
handler: requestHandler,
incrementalCacheHandler,
bypassNextUrl: true
});
}
//# sourceMappingURL=edge-ssr.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,26 @@
/**
* Hoists a name from a module or promised module.
*
* @param module the module to hoist the name from
* @param name the name to hoist
* @returns the value on the module (or promised module)
*/ export function hoist(module, name) {
// If the name is available in the module, return it.
if (name in module) {
return module[name];
}
// If a property called `then` exists, assume it's a promise and
// return a promise that resolves to the name.
if ('then' in module && typeof module.then === 'function') {
return module.then((mod)=>hoist(mod, name));
}
// If we're trying to hoise the default export, and the module is a function,
// return the module itself.
if (typeof module === 'function' && name === 'default') {
return module;
}
// Otherwise, return undefined.
return undefined;
}
//# sourceMappingURL=helpers.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/templates/helpers.ts"],"sourcesContent":["/**\n * Hoists a name from a module or promised module.\n *\n * @param module the module to hoist the name from\n * @param name the name to hoist\n * @returns the value on the module (or promised module)\n */\nexport function hoist(module: any, name: string) {\n // If the name is available in the module, return it.\n if (name in module) {\n return module[name]\n }\n\n // If a property called `then` exists, assume it's a promise and\n // return a promise that resolves to the name.\n if ('then' in module && typeof module.then === 'function') {\n return module.then((mod: any) => hoist(mod, name))\n }\n\n // If we're trying to hoise the default export, and the module is a function,\n // return the module itself.\n if (typeof module === 'function' && name === 'default') {\n return module\n }\n\n // Otherwise, return undefined.\n return undefined\n}\n"],"names":["hoist","module","name","then","mod","undefined"],"mappings":"AAAA;;;;;;CAMC,GACD,OAAO,SAASA,MAAMC,MAAW,EAAEC,IAAY;IAC7C,qDAAqD;IACrD,IAAIA,QAAQD,QAAQ;QAClB,OAAOA,MAAM,CAACC,KAAK;IACrB;IAEA,gEAAgE;IAChE,8CAA8C;IAC9C,IAAI,UAAUD,UAAU,OAAOA,OAAOE,IAAI,KAAK,YAAY;QACzD,OAAOF,OAAOE,IAAI,CAAC,CAACC,MAAaJ,MAAMI,KAAKF;IAC9C;IAEA,6EAA6E;IAC7E,4BAA4B;IAC5B,IAAI,OAAOD,WAAW,cAAcC,SAAS,WAAW;QACtD,OAAOD;IACT;IAEA,+BAA+B;IAC/B,OAAOI;AACT","ignoreList":[0]}

View File

@@ -0,0 +1,59 @@
import '../../server/web/globals';
import { adapter } from '../../server/web/adapter';
// Import the userland code.
import * as _mod from 'VAR_USERLAND';
import { edgeInstrumentationOnRequestError } from '../../server/web/globals';
import { isNextRouterError } from '../../client/components/is-next-router-error';
const mod = {
..._mod
};
const handler = mod.middleware || mod.default;
const page = 'VAR_DEFINITION_PAGE';
if (typeof handler !== 'function') {
throw Object.defineProperty(new Error(`The Middleware "${page}" must export a \`middleware\` or a \`default\` function`), "__NEXT_ERROR_CODE", {
value: "E120",
enumerable: false,
configurable: true
});
}
// Middleware will only sent out the FetchEvent to next server,
// so load instrumentation module here and track the error inside middleware module.
function errorHandledHandler(fn) {
return async (...args)=>{
try {
return await fn(...args);
} catch (err) {
// In development, error the navigation API usage in runtime,
// since it's not allowed to be used in middleware as it's outside of react component tree.
if (process.env.NODE_ENV !== 'production') {
if (isNextRouterError(err)) {
err.message = `Next.js navigation API is not allowed to be used in Middleware.`;
throw err;
}
}
const req = args[0];
const url = new URL(req.url);
const resource = url.pathname + url.search;
await edgeInstrumentationOnRequestError(err, {
path: resource,
method: req.method,
headers: Object.fromEntries(req.headers.entries())
}, {
routerKind: 'Pages Router',
routePath: '/middleware',
routeType: 'middleware',
revalidateReason: undefined
});
throw err;
}
};
}
export default function nHandler(opts) {
return adapter({
...opts,
page,
handler: errorHandledHandler(handler)
});
}
//# sourceMappingURL=middleware.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/templates/middleware.ts"],"sourcesContent":["import type { AdapterOptions } from '../../server/web/adapter'\n\nimport '../../server/web/globals'\n\nimport { adapter } from '../../server/web/adapter'\n\n// Import the userland code.\nimport * as _mod from 'VAR_USERLAND'\nimport { edgeInstrumentationOnRequestError } from '../../server/web/globals'\nimport { isNextRouterError } from '../../client/components/is-next-router-error'\n\nconst mod = { ..._mod }\nconst handler = mod.middleware || mod.default\n\nconst page = 'VAR_DEFINITION_PAGE'\n\nif (typeof handler !== 'function') {\n throw new Error(\n `The Middleware \"${page}\" must export a \\`middleware\\` or a \\`default\\` function`\n )\n}\n\n// Middleware will only sent out the FetchEvent to next server,\n// so load instrumentation module here and track the error inside middleware module.\nfunction errorHandledHandler(fn: AdapterOptions['handler']) {\n return async (...args: Parameters<AdapterOptions['handler']>) => {\n try {\n return await fn(...args)\n } catch (err) {\n // In development, error the navigation API usage in runtime,\n // since it's not allowed to be used in middleware as it's outside of react component tree.\n if (process.env.NODE_ENV !== 'production') {\n if (isNextRouterError(err)) {\n err.message = `Next.js navigation API is not allowed to be used in Middleware.`\n throw err\n }\n }\n const req = args[0]\n const url = new URL(req.url)\n const resource = url.pathname + url.search\n await edgeInstrumentationOnRequestError(\n err,\n {\n path: resource,\n method: req.method,\n headers: Object.fromEntries(req.headers.entries()),\n },\n {\n routerKind: 'Pages Router',\n routePath: '/middleware',\n routeType: 'middleware',\n revalidateReason: undefined,\n }\n )\n\n throw err\n }\n }\n}\n\nexport default function nHandler(\n opts: Omit<AdapterOptions, 'IncrementalCache' | 'page' | 'handler'>\n) {\n return adapter({\n ...opts,\n page,\n handler: errorHandledHandler(handler),\n })\n}\n"],"names":["adapter","_mod","edgeInstrumentationOnRequestError","isNextRouterError","mod","handler","middleware","default","page","Error","errorHandledHandler","fn","args","err","process","env","NODE_ENV","message","req","url","URL","resource","pathname","search","path","method","headers","Object","fromEntries","entries","routerKind","routePath","routeType","revalidateReason","undefined","nHandler","opts"],"mappings":"AAEA,OAAO,2BAA0B;AAEjC,SAASA,OAAO,QAAQ,2BAA0B;AAElD,4BAA4B;AAC5B,YAAYC,UAAU,eAAc;AACpC,SAASC,iCAAiC,QAAQ,2BAA0B;AAC5E,SAASC,iBAAiB,QAAQ,+CAA8C;AAEhF,MAAMC,MAAM;IAAE,GAAGH,IAAI;AAAC;AACtB,MAAMI,UAAUD,IAAIE,UAAU,IAAIF,IAAIG,OAAO;AAE7C,MAAMC,OAAO;AAEb,IAAI,OAAOH,YAAY,YAAY;IACjC,MAAM,qBAEL,CAFK,IAAII,MACR,CAAC,gBAAgB,EAAED,KAAK,wDAAwD,CAAC,GAD7E,qBAAA;eAAA;oBAAA;sBAAA;IAEN;AACF;AAEA,+DAA+D;AAC/D,oFAAoF;AACpF,SAASE,oBAAoBC,EAA6B;IACxD,OAAO,OAAO,GAAGC;QACf,IAAI;YACF,OAAO,MAAMD,MAAMC;QACrB,EAAE,OAAOC,KAAK;YACZ,6DAA6D;YAC7D,2FAA2F;YAC3F,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;gBACzC,IAAIb,kBAAkBU,MAAM;oBAC1BA,IAAII,OAAO,GAAG,CAAC,+DAA+D,CAAC;oBAC/E,MAAMJ;gBACR;YACF;YACA,MAAMK,MAAMN,IAAI,CAAC,EAAE;YACnB,MAAMO,MAAM,IAAIC,IAAIF,IAAIC,GAAG;YAC3B,MAAME,WAAWF,IAAIG,QAAQ,GAAGH,IAAII,MAAM;YAC1C,MAAMrB,kCACJW,KACA;gBACEW,MAAMH;gBACNI,QAAQP,IAAIO,MAAM;gBAClBC,SAASC,OAAOC,WAAW,CAACV,IAAIQ,OAAO,CAACG,OAAO;YACjD,GACA;gBACEC,YAAY;gBACZC,WAAW;gBACXC,WAAW;gBACXC,kBAAkBC;YACpB;YAGF,MAAMrB;QACR;IACF;AACF;AAEA,eAAe,SAASsB,SACtBC,IAAmE;IAEnE,OAAOpC,QAAQ;QACb,GAAGoC,IAAI;QACP5B;QACAH,SAASK,oBAAoBL;IAC/B;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,125 @@
import { sendError } from '../../server/api-utils';
import { RouteKind } from '../../server/route-kind';
import { PagesAPIRouteModule } from '../../server/route-modules/pages-api/module.compiled';
import { hoist } from './helpers';
// Import the userland code.
import * as userland from 'VAR_USERLAND';
import { getTracer, SpanKind } from '../../server/lib/trace/tracer';
import { BaseServerSpan } from '../../server/lib/trace/constants';
// Re-export the handler (should be the default export).
export default hoist(userland, 'default');
// Re-export config.
export const config = hoist(userland, 'config');
// Create and export the route module that will be consumed.
const routeModule = new PagesAPIRouteModule({
definition: {
kind: RouteKind.PAGES_API,
page: 'VAR_DEFINITION_PAGE',
pathname: 'VAR_DEFINITION_PATHNAME',
// The following aren't used in production.
bundlePath: '',
filename: ''
},
userland,
distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',
relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || ''
});
export async function handler(req, res, ctx) {
let srcPage = 'VAR_DEFINITION_PAGE';
// turbopack doesn't normalize `/index` in the page name
// so we need to to process dynamic routes properly
// TODO: fix turbopack providing differing value from webpack
if (process.env.TURBOPACK) {
srcPage = srcPage.replace(/\/index$/, '') || '/';
}
const prepareResult = await routeModule.prepare(req, res, {
srcPage
});
if (!prepareResult) {
res.statusCode = 400;
res.end('Bad Request');
ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());
return;
}
const { query, params, prerenderManifest, routerServerContext } = prepareResult;
try {
const method = req.method || 'GET';
const tracer = getTracer();
const activeSpan = tracer.getActiveScopeSpan();
const onRequestError = routeModule.instrumentationOnRequestError.bind(routeModule);
const invokeRouteModule = async (span)=>routeModule.render(req, res, {
query: {
...query,
...params
},
params,
allowedRevalidateHeaderKeys: process.env.__NEXT_ALLOWED_REVALIDATE_HEADERS,
multiZoneDraftMode: Boolean(process.env.__NEXT_MULTI_ZONE_DRAFT_MODE),
trustHostHeader: process.env.__NEXT_TRUST_HOST_HEADER,
// TODO: get this from from runtime env so manifest
// doesn't need to load
previewProps: prerenderManifest.preview,
propagateError: false,
dev: routeModule.isDev,
page: 'VAR_DEFINITION_PAGE',
internalRevalidate: routerServerContext == null ? void 0 : routerServerContext.revalidate,
onError: (...args)=>onRequestError(req, ...args)
}).finally(()=>{
if (!span) return;
span.setAttributes({
'http.status_code': res.statusCode,
'next.rsc': false
});
const rootSpanAttributes = tracer.getRootSpanAttributes();
// We were unable to get attributes, probably OTEL is not enabled
if (!rootSpanAttributes) {
return;
}
if (rootSpanAttributes.get('next.span_type') !== 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 = `${method} ${route}`;
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': name
});
span.updateName(name);
} else {
span.updateName(`${method} ${req.url}`);
}
});
// TODO: activeSpan code path is for when wrapped by
// next-server can be removed when this is no longer used
if (activeSpan) {
await invokeRouteModule(activeSpan);
} else {
await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {
spanName: `${method} ${req.url}`,
kind: SpanKind.SERVER,
attributes: {
'http.method': method,
'http.target': req.url
}
}, invokeRouteModule));
}
} catch (err) {
// we re-throw in dev to show the error overlay
if (routeModule.isDev) {
throw err;
}
// this is technically an invariant as error handling
// should be done inside of api-resolver onError
sendError(res, 500, 'Internal Server Error');
} finally{
// We don't allow any waitUntil work in pages API routes currently
// so if callback is present return with resolved promise since no
// pending work
ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());
}
}
//# sourceMappingURL=pages-api.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,24 @@
import '../../server/web/globals';
import { adapter } from '../../server/web/adapter';
import { IncrementalCache } from '../../server/lib/incremental-cache';
import { wrapApiHandler } from '../../server/api-utils';
// Import the userland code.
import handler from 'VAR_USERLAND';
const page = 'VAR_DEFINITION_PAGE';
if (typeof handler !== 'function') {
throw Object.defineProperty(new Error(`The Edge Function "pages${page}" must export a \`default\` function`), "__NEXT_ERROR_CODE", {
value: "E162",
enumerable: false,
configurable: true
});
}
export default function(opts) {
return adapter({
...opts,
IncrementalCache,
page: 'VAR_DEFINITION_PATHNAME',
handler: wrapApiHandler(page, handler)
});
}
//# sourceMappingURL=pages-edge-api.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/templates/pages-edge-api.ts"],"sourcesContent":["import type { AdapterOptions } from '../../server/web/adapter'\n\nimport '../../server/web/globals'\n\nimport { adapter } from '../../server/web/adapter'\nimport { IncrementalCache } from '../../server/lib/incremental-cache'\nimport { wrapApiHandler } from '../../server/api-utils'\n\n// Import the userland code.\nimport handler from 'VAR_USERLAND'\n\nconst page = 'VAR_DEFINITION_PAGE'\n\nif (typeof handler !== 'function') {\n throw new Error(\n `The Edge Function \"pages${page}\" must export a \\`default\\` function`\n )\n}\n\nexport default function (\n opts: Omit<AdapterOptions, 'IncrementalCache' | 'page' | 'handler'>\n) {\n return adapter({\n ...opts,\n IncrementalCache,\n page: 'VAR_DEFINITION_PATHNAME',\n handler: wrapApiHandler(page, handler),\n })\n}\n"],"names":["adapter","IncrementalCache","wrapApiHandler","handler","page","Error","opts"],"mappings":"AAEA,OAAO,2BAA0B;AAEjC,SAASA,OAAO,QAAQ,2BAA0B;AAClD,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,cAAc,QAAQ,yBAAwB;AAEvD,4BAA4B;AAC5B,OAAOC,aAAa,eAAc;AAElC,MAAMC,OAAO;AAEb,IAAI,OAAOD,YAAY,YAAY;IACjC,MAAM,qBAEL,CAFK,IAAIE,MACR,CAAC,wBAAwB,EAAED,KAAK,oCAAoC,CAAC,GADjE,qBAAA;eAAA;oBAAA;sBAAA;IAEN;AACF;AAEA,eAAe,SACbE,IAAmE;IAEnE,OAAON,QAAQ;QACb,GAAGM,IAAI;QACPL;QACAG,MAAM;QACND,SAASD,eAAeE,MAAMD;IAChC;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,53 @@
import { PagesRouteModule } from '../../server/route-modules/pages/module.compiled';
import { RouteKind } from '../../server/route-kind';
import { hoist } from './helpers';
// Import the app and document modules.
import * as document from 'VAR_MODULE_DOCUMENT';
import * as app from 'VAR_MODULE_APP';
// Import the userland code.
import * as userland from 'VAR_USERLAND';
import { getHandler } from '../../server/route-modules/pages/pages-handler';
// Re-export the component (should be the default export).
export default hoist(userland, 'default');
// Re-export methods.
export const getStaticProps = hoist(userland, 'getStaticProps');
export const getStaticPaths = hoist(userland, 'getStaticPaths');
export const getServerSideProps = hoist(userland, 'getServerSideProps');
export const config = hoist(userland, 'config');
export const reportWebVitals = hoist(userland, 'reportWebVitals');
// Re-export legacy methods.
export const unstable_getStaticProps = hoist(userland, 'unstable_getStaticProps');
export const unstable_getStaticPaths = hoist(userland, 'unstable_getStaticPaths');
export const unstable_getStaticParams = hoist(userland, 'unstable_getStaticParams');
export const unstable_getServerProps = hoist(userland, 'unstable_getServerProps');
export const unstable_getServerSideProps = hoist(userland, 'unstable_getServerSideProps');
// Create and export the route module that will be consumed.
export const routeModule = new PagesRouteModule({
definition: {
kind: RouteKind.PAGES,
page: 'VAR_DEFINITION_PAGE',
pathname: 'VAR_DEFINITION_PATHNAME',
// The following aren't used in production.
bundlePath: '',
filename: ''
},
distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',
relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',
components: {
// default export might not exist when optimized for data only
App: app.default,
Document: document.default
},
userland
});
export const handler = getHandler({
srcPage: 'VAR_DEFINITION_PAGE',
config,
userland,
routeModule,
getStaticPaths,
getStaticProps,
getServerSideProps
});
//# sourceMappingURL=pages.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/templates/pages.ts"],"sourcesContent":["import { PagesRouteModule } from '../../server/route-modules/pages/module.compiled'\nimport { RouteKind } from '../../server/route-kind'\n\nimport { hoist } from './helpers'\n\n// Import the app and document modules.\nimport * as document from 'VAR_MODULE_DOCUMENT'\nimport * as app from 'VAR_MODULE_APP'\n\n// Import the userland code.\nimport * as userland from 'VAR_USERLAND'\nimport { getHandler } from '../../server/route-modules/pages/pages-handler'\n\n// Re-export the component (should be the default export).\nexport default hoist(userland, 'default')\n\n// Re-export methods.\nexport const getStaticProps = hoist(userland, 'getStaticProps')\nexport const getStaticPaths = hoist(userland, 'getStaticPaths')\nexport const getServerSideProps = hoist(userland, 'getServerSideProps')\nexport const config = hoist(userland, 'config')\nexport const reportWebVitals = hoist(userland, 'reportWebVitals')\n\n// Re-export legacy methods.\nexport const unstable_getStaticProps = hoist(\n userland,\n 'unstable_getStaticProps'\n)\nexport const unstable_getStaticPaths = hoist(\n userland,\n 'unstable_getStaticPaths'\n)\nexport const unstable_getStaticParams = hoist(\n userland,\n 'unstable_getStaticParams'\n)\nexport const unstable_getServerProps = hoist(\n userland,\n 'unstable_getServerProps'\n)\nexport const unstable_getServerSideProps = hoist(\n userland,\n 'unstable_getServerSideProps'\n)\n\n// Create and export the route module that will be consumed.\nexport const routeModule = new PagesRouteModule({\n definition: {\n kind: RouteKind.PAGES,\n page: 'VAR_DEFINITION_PAGE',\n pathname: 'VAR_DEFINITION_PATHNAME',\n // The following aren't used in production.\n bundlePath: '',\n filename: '',\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n components: {\n // default export might not exist when optimized for data only\n App: app.default,\n Document: document.default,\n },\n userland,\n})\n\nexport const handler = getHandler({\n srcPage: 'VAR_DEFINITION_PAGE',\n config,\n userland,\n routeModule,\n getStaticPaths,\n getStaticProps,\n getServerSideProps,\n})\n"],"names":["PagesRouteModule","RouteKind","hoist","document","app","userland","getHandler","getStaticProps","getStaticPaths","getServerSideProps","config","reportWebVitals","unstable_getStaticProps","unstable_getStaticPaths","unstable_getStaticParams","unstable_getServerProps","unstable_getServerSideProps","routeModule","definition","kind","PAGES","page","pathname","bundlePath","filename","distDir","process","env","__NEXT_RELATIVE_DIST_DIR","relativeProjectDir","__NEXT_RELATIVE_PROJECT_DIR","components","App","default","Document","handler","srcPage"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,SAAS,QAAQ,0BAAyB;AAEnD,SAASC,KAAK,QAAQ,YAAW;AAEjC,uCAAuC;AACvC,YAAYC,cAAc,sBAAqB;AAC/C,YAAYC,SAAS,iBAAgB;AAErC,4BAA4B;AAC5B,YAAYC,cAAc,eAAc;AACxC,SAASC,UAAU,QAAQ,iDAAgD;AAE3E,0DAA0D;AAC1D,eAAeJ,MAAMG,UAAU,WAAU;AAEzC,qBAAqB;AACrB,OAAO,MAAME,iBAAiBL,MAAMG,UAAU,kBAAiB;AAC/D,OAAO,MAAMG,iBAAiBN,MAAMG,UAAU,kBAAiB;AAC/D,OAAO,MAAMI,qBAAqBP,MAAMG,UAAU,sBAAqB;AACvE,OAAO,MAAMK,SAASR,MAAMG,UAAU,UAAS;AAC/C,OAAO,MAAMM,kBAAkBT,MAAMG,UAAU,mBAAkB;AAEjE,4BAA4B;AAC5B,OAAO,MAAMO,0BAA0BV,MACrCG,UACA,2BACD;AACD,OAAO,MAAMQ,0BAA0BX,MACrCG,UACA,2BACD;AACD,OAAO,MAAMS,2BAA2BZ,MACtCG,UACA,4BACD;AACD,OAAO,MAAMU,0BAA0Bb,MACrCG,UACA,2BACD;AACD,OAAO,MAAMW,8BAA8Bd,MACzCG,UACA,+BACD;AAED,4DAA4D;AAC5D,OAAO,MAAMY,cAAc,IAAIjB,iBAAiB;IAC9CkB,YAAY;QACVC,MAAMlB,UAAUmB,KAAK;QACrBC,MAAM;QACNC,UAAU;QACV,2CAA2C;QAC3CC,YAAY;QACZC,UAAU;IACZ;IACAC,SAASC,QAAQC,GAAG,CAACC,wBAAwB,IAAI;IACjDC,oBAAoBH,QAAQC,GAAG,CAACG,2BAA2B,IAAI;IAC/DC,YAAY;QACV,8DAA8D;QAC9DC,KAAK5B,IAAI6B,OAAO;QAChBC,UAAU/B,SAAS8B,OAAO;IAC5B;IACA5B;AACF,GAAE;AAEF,OAAO,MAAM8B,UAAU7B,WAAW;IAChC8B,SAAS;IACT1B;IACAL;IACAY;IACAT;IACAD;IACAE;AACF,GAAE","ignoreList":[0]}