From dd75b8f9abfae45166af6a6196c7981602726969 Mon Sep 17 00:00:00 2001 From: JJ Kasper Date: Sun, 19 Oct 2025 19:18:32 -0700 Subject: [PATCH 1/2] Update routes generation for build-complete --- packages/next/package.json | 1 + .../next/src/build/adapter/build-complete.ts | 775 ++++++++++++++++-- .../next/src/build/collect-build-traces.ts | 40 +- packages/next/src/build/define-env.ts | 2 + packages/next/src/build/index.ts | 11 +- packages/next/src/build/templates/app-page.ts | 43 +- .../next/src/build/templates/app-route.ts | 24 +- .../next/src/build/templates/edge-ssr-app.ts | 3 +- .../compiled/@vercel/routing-utils/LICENSE | 202 +++++ .../@vercel/routing-utils/package.json | 1 + .../@vercel/routing-utils/superstatic.js | 1 + packages/next/src/lib/load-custom-routes.ts | 2 +- .../src/server/lib/incremental-cache/index.ts | 3 + .../route-modules/pages/pages-handler.ts | 38 +- .../src/server/route-modules/route-module.ts | 53 +- packages/next/src/server/server-utils.ts | 4 +- packages/next/taskfile.js | 18 + packages/next/types/$$compiled.internal.d.ts | 4 + pnpm-lock.yaml | 227 ++++- .../custom-routes/test/index.test.js | 6 + .../adapter-config/adapter-config.test.ts | 2 + .../production/adapter-config/next.config.mjs | 31 +- 22 files changed, 1334 insertions(+), 157 deletions(-) create mode 100644 packages/next/src/compiled/@vercel/routing-utils/LICENSE create mode 100644 packages/next/src/compiled/@vercel/routing-utils/package.json create mode 100644 packages/next/src/compiled/@vercel/routing-utils/superstatic.js diff --git a/packages/next/package.json b/packages/next/package.json index 6a5b75c04b408..01eee574a2ca6 100644 --- a/packages/next/package.json +++ b/packages/next/package.json @@ -218,6 +218,7 @@ "@types/ws": "8.2.0", "@vercel/ncc": "0.34.0", "@vercel/nft": "0.27.1", + "@vercel/routing-utils": "5.2.0", "@vercel/turbopack-ecmascript-runtime": "*", "acorn": "8.14.0", "anser": "1.4.9", diff --git a/packages/next/src/build/adapter/build-complete.ts b/packages/next/src/build/adapter/build-complete.ts index eb042c4569deb..ce32c1f307b0e 100644 --- a/packages/next/src/build/adapter/build-complete.ts +++ b/packages/next/src/build/adapter/build-complete.ts @@ -10,10 +10,14 @@ import { recursiveReadDir } from '../../lib/recursive-readdir' import { isDynamicRoute } from '../../shared/lib/router/utils' import type { Revalidate } from '../../server/lib/cache-control' import type { NextConfigComplete } from '../../server/config-shared' -import type { ProxyMatcher } from '../analysis/get-page-static-info' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { AdapterOutputType, type PHASE_TYPE } from '../../shared/lib/constants' import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path' +import { + convertRedirects, + convertRewrites, + convertHeaders, +} from 'next/dist/compiled/@vercel/routing-utils' import type { MiddlewareManifest, @@ -21,13 +25,11 @@ import type { } from '../webpack/plugins/middleware-plugin' import type { - ManifestRoute, RoutesManifest, PrerenderManifest, - ManifestHeaderRoute, ManifestRewriteRoute, - ManifestRedirectRoute, FunctionsConfigManifest, + DynamicPrerenderManifestRoute, } from '..' import { @@ -37,6 +39,13 @@ import { } from '../../lib/constants' import { normalizeLocalePath } from '../../shared/lib/i18n/normalize-locale-path' import { addPathPrefix } from '../../shared/lib/router/utils/add-path-prefix' +import { getRedirectStatus, modifyRouteRegex } from '../../lib/redirect-status' +import { getNamedRouteRegex } from '../../shared/lib/router/utils/route-regex' +import { escapeStringRegexp } from '../../shared/lib/escape-regexp' +import { sortSortableRoutes } from '../../shared/lib/router/utils/sortable-routes' +import { nodeFileTrace } from 'next/dist/compiled/@vercel/nft' +import { defaultOverrides } from '../../server/require-hook' +import { makeIgnoreFn } from '../collect-build-traces' interface SharedRouteFields { /** @@ -51,6 +60,12 @@ interface SharedRouteFields { * pathname is the URL pathname the asset should be served at */ pathname: string + + /** + * sourcePage is the original source in the app or pages folder + */ + sourcePage: string + /** * runtime is which runtime the entrypoint is built for */ @@ -149,6 +164,12 @@ export interface AdapterOutput { headers: Record } + /** + * parentFallbackMode signals whether additional routes can be generated + * e.g. fallback: false or 'blocking' in getStaticPaths in pages router + */ + parentFallbackMode?: DynamicPrerenderManifestRoute['fallback'] + /** * fallback is initial cache data generated during build for a prerender */ @@ -209,11 +230,6 @@ export interface AdapterOutput { */ renderingMode?: RenderingMode - /** - * matchers are the configured matchers for middleware - */ - matchers?: ProxyMatcher[] - /** * bypassToken is the generated token that signals a prerender cache * should be bypassed @@ -246,7 +262,12 @@ export interface AdapterOutput { /** * matchers are the configured matchers for middleware */ - matchers?: ProxyMatcher[] + matchers?: Array<{ + source: string + sourceRegex: string + has: RouteHas[] | undefined + missing: RouteHas[] | undefined + }> } } } @@ -261,6 +282,22 @@ export interface AdapterOutputs { staticFiles: Array } +type RewriteItem = { + source: string + sourceRegex: string + destination: string + has: RouteHas[] | undefined + missing: RouteHas[] | undefined +} + +type DynamicRouteItem = { + source: string + sourceRegex: string + destination: string + has: RouteHas[] | undefined + missing: RouteHas[] | undefined +} + export interface NextAdapter { name: string /** @@ -278,14 +315,29 @@ export interface NextAdapter { ) => Promise | NextConfigComplete onBuildComplete?: (ctx: { routes: { - headers: Array - redirects: Array + headers: Array<{ + source: string + sourceRegex: string + headers: Record + has: RouteHas[] | undefined + missing: RouteHas[] | undefined + priority?: boolean + }> + redirects: Array<{ + source: string + sourceRegex: string + destination: string + statusCode: number + has: RouteHas[] | undefined + missing: RouteHas[] | undefined + priority?: boolean + }> rewrites: { - beforeFiles: Array - afterFiles: Array - fallback: Array + beforeFiles: RewriteItem[] + afterFiles: RewriteItem[] + fallback: RewriteItem[] } - dynamicRoutes: ReadonlyArray + dynamicRoutes: Array } outputs: AdapterOutputs /** @@ -308,6 +360,11 @@ export interface NextAdapter { * nextVersion is the current version of Next.js being used */ nextVersion: string + /** + * buildId is the current unique ID for the build, this can be + * influenced by NextConfig.generateBuildId + */ + buildId: string }) => Promise | void } @@ -324,9 +381,10 @@ function normalizePathnames( ...outputs.appRoutes, ...outputs.prerenders, ...outputs.staticFiles, - ...(outputs.middleware ? [outputs.middleware] : []), ]) { - output.pathname = addPathPrefix(output.pathname, config.basePath) + output.pathname = + addPathPrefix(output.pathname, config.basePath).replace(/\/$/, '') || + '/' } } } @@ -334,6 +392,7 @@ function normalizePathnames( export async function handleBuildComplete({ dir, config, + buildId, configOutDir, distDir, pageKeys, @@ -343,7 +402,9 @@ export async function handleBuildComplete({ staticPages, nextVersion, hasStatic404, + hasStatic500, routesManifest, + serverPropsPages, hasNodeMiddleware, prerenderManifest, middlewareManifest, @@ -353,15 +414,18 @@ export async function handleBuildComplete({ }: { dir: string distDir: string + buildId: string configOutDir: string adapterPath: string tracingRoot: string nextVersion: string hasStatic404: boolean + hasStatic500: boolean staticPages: Set hasNodeMiddleware: boolean config: NextConfigComplete pageKeys: readonly string[] + serverPropsPages: Set requiredServerFiles: string[] routesManifest: RoutesManifest hasInstrumentationHook: boolean @@ -375,8 +439,6 @@ export async function handleBuildComplete({ ) as NextAdapter if (typeof adapterMod.onBuildComplete === 'function') { - Log.info(`Running onBuildComplete from ${adapterMod.name}`) - const outputs: AdapterOutputs = { pages: [], pagesApi: [], @@ -419,6 +481,26 @@ export async function handleBuildComplete({ } const sharedNodeAssets: Record = {} + const pagesSharedNodeAssets: Record = {} + const appPagesSharedNodeAssets: Record = {} + + const sharedTraceIgnores = [ + '**/next/dist/compiled/next-server/**/*.dev.js', + '**/next/dist/compiled/webpack/*', + '**/node_modules/webpack5/**/*', + '**/next/dist/server/lib/route-resolver*', + 'next/dist/compiled/semver/semver/**/*.js', + '**/node_modules/react{,-dom,-dom-server-turbopack}/**/*.development.js', + '**/*.d.ts', + '**/*.map', + '**/next/dist/pages/**/*', + '**/node_modules/sharp/**/*', + '**/@img/sharp-libvips*/**/*', + '**/next/dist/compiled/edge-runtime/**/*', + '**/next/dist/server/web/sandbox/**/*', + '**/next/dist/server/post-process.js', + ] + const sharedIgnoreFn = makeIgnoreFn(tracingRoot, sharedTraceIgnores) for (const file of requiredServerFiles) { // add to shared node assets @@ -427,9 +509,77 @@ export async function handleBuildComplete({ sharedNodeAssets[fileOutputPath] = filePath } + const moduleTypes = ['app-page', 'pages'] as const + + for (const type of moduleTypes) { + const currentDependencies: string[] = [] + const modulePath = require.resolve( + `next/dist/server/route-modules/${type}/module.compiled` + ) + const contextDir = path.join( + path.dirname(modulePath), + 'vendored', + 'contexts' + ) + + for (const item of await fs.readdir(contextDir)) { + if (item.match(/\.(mjs|cjs|js)$/)) { + currentDependencies.push(path.join(contextDir, item)) + } + } + + const { fileList, esmFileList } = await nodeFileTrace( + currentDependencies, + { + base: tracingRoot, + ignore: sharedIgnoreFn, + } + ) + esmFileList.forEach((item) => fileList.add(item)) + + for (const rootRelativeFilePath of fileList) { + if (type === 'pages') { + pagesSharedNodeAssets[rootRelativeFilePath] = path.join( + tracingRoot, + rootRelativeFilePath + ) + } else { + appPagesSharedNodeAssets[rootRelativeFilePath] = path.join( + tracingRoot, + rootRelativeFilePath + ) + } + } + } + + // These are modules that are necessary for bootstrapping node env + const necessaryNodeDependencies = [ + require.resolve('next/dist/server/node-environment'), + require.resolve('next/dist/server/require-hook'), + require.resolve('next/dist/server/node-polyfill-crypto'), + ...Object.values(defaultOverrides).filter((item) => path.extname(item)), + ] + + const { fileList, esmFileList } = await nodeFileTrace( + necessaryNodeDependencies, + { + base: tracingRoot, + ignore: sharedIgnoreFn, + } + ) + esmFileList.forEach((item) => fileList.add(item)) + + for (const rootRelativeFilePath of fileList) { + sharedNodeAssets[rootRelativeFilePath] = path.join( + tracingRoot, + rootRelativeFilePath + ) + } + if (hasInstrumentationHook) { const assets = await handleTraceFiles( - path.join(distDir, 'server', 'instrumentation.js.nft.json') + path.join(distDir, 'server', 'instrumentation.js.nft.json'), + 'neutral' ) const fileOutputPath = path.relative( tracingRoot, @@ -444,11 +594,14 @@ export async function handleBuildComplete({ } async function handleTraceFiles( - traceFilePath: string + traceFilePath: string, + type: 'pages' | 'app' | 'neutral' ): Promise> { const assets: Record = Object.assign( {}, - sharedNodeAssets + sharedNodeAssets, + type === 'pages' ? pagesSharedNodeAssets : {}, + type === 'app' ? appPagesSharedNodeAssets : {} ) const traceData = JSON.parse( await fs.readFile(traceFilePath, 'utf8') @@ -470,9 +623,9 @@ export async function handleBuildComplete({ isMiddleware: boolean = false ) { let type: AdapterOutputType = AdapterOutputType.PAGES - const isAppPrefix = page.page.startsWith('app/') - const isAppPage = isAppPrefix && page.page.endsWith('/page') - const isAppRoute = isAppPrefix && page.page.endsWith('/route') + const isAppPrefix = page.name.startsWith('app/') + const isAppPage = isAppPrefix && page.name.endsWith('/page') + const isAppRoute = isAppPrefix && page.name.endsWith('/route') let currentOutputs: Array< | AdapterOutput['PAGES'] | AdapterOutput['PAGES_API'] @@ -493,13 +646,16 @@ export async function handleBuildComplete({ type = AdapterOutputType.PAGES_API } + const route = page.page.replace(/^(app|pages)\//, '') + const output: Omit & { type: any } = { type, id: page.name, runtime: 'edge', - pathname: isAppPrefix ? normalizeAppPath(page.name) : page.name, + sourcePage: route, + pathname: isAppPrefix ? normalizeAppPath(route) : route, filePath: path.join( distDir, page.files.find( @@ -516,11 +672,6 @@ export async function handleBuildComplete({ assets: {}, wasmAssets: {}, config: { - ...(type === AdapterOutputType.MIDDLEWARE - ? { - matchers: page.matchers, - } - : {}), env: page.env, }, } @@ -546,14 +697,44 @@ export async function handleBuildComplete({ if (!output.wasmAssets) { output.wasmAssets = {} } - output.wasmAssets[item.name] = item.filePath + output.wasmAssets[item.name] = path.join(distDir, item.filePath) } if (type === AdapterOutputType.MIDDLEWARE) { + ;(output as AdapterOutput['MIDDLEWARE']).config.matchers = + page.matchers.map((item) => { + return { + source: item.originalSource, + sourceRegex: item.regexp, + has: item.has, + missing: [ + ...(item.missing || []), + // always skip middleware for on-demand revalidate + { + type: 'header', + key: 'x-prerender-revalidate', + value: prerenderManifest.preview.previewModeId, + }, + ], + } + }) + output.pathname = '/_middleware' + output.id = page.name outputs.middleware = output } else { currentOutputs.push(output) } + + // need to add matching .rsc output + if (isAppPage) { + const rscPathname = + (output.pathname === '/' ? '/index' : output.pathname) + '.rsc' + outputs.appPages.push({ + ...output, + pathname: rscPathname, + id: page.name + '.rsc', + }) + } } const edgeFunctionHandlers: Promise[] = [] @@ -573,6 +754,12 @@ export async function handleBuildComplete({ AdapterOutput['PAGES'] | AdapterOutput['PAGES_API'] > = {} + const rscFallbackPath = path.join(distDir, 'server', 'rsc-fallback.json') + + if (appPageKeys && appPageKeys.length > 0 && pageKeys.length > 0) { + await fs.writeFile(rscFallbackPath, '{}') + } + for (const page of pageKeys) { if (page === '/_app' || page === '/_document') { continue @@ -583,10 +770,7 @@ export async function handleBuildComplete({ } const route = normalizePagePath(page) - const pageFile = path.join( - pagesDistDir, - `${normalizePagePath(page)}.js` - ) + const pageFile = path.join(pagesDistDir, `${route}.js`) // if it's an auto static optimized page it's just // a static file @@ -595,7 +779,8 @@ export async function handleBuildComplete({ for (const locale of config.i18n.locales || []) { const localePage = page === '/' ? `/${locale}` : addPathPrefix(page, `/${locale}`) - outputs.staticFiles.push({ + + const localeOutput = { id: localePage, pathname: localePage, type: AdapterOutputType.STATIC_FILE, @@ -603,27 +788,55 @@ export async function handleBuildComplete({ pagesDistDir, `${normalizePagePath(localePage)}.html` ), - } satisfies AdapterOutput['STATIC_FILE']) + } satisfies AdapterOutput['STATIC_FILE'] + + outputs.staticFiles.push(localeOutput) + + if (appPageKeys && appPageKeys.length > 0) { + outputs.staticFiles.push({ + id: `${localePage}.rsc`, + pathname: `${localePage}.rsc`, + type: AdapterOutputType.STATIC_FILE, + filePath: rscFallbackPath, + }) + } } } else { - outputs.staticFiles.push({ + const staticOutput = { id: page, pathname: route, type: AdapterOutputType.STATIC_FILE, filePath: pageFile.replace(/\.js$/, '.html'), - } satisfies AdapterOutput['STATIC_FILE']) + } satisfies AdapterOutput['STATIC_FILE'] + + outputs.staticFiles.push(staticOutput) + + if (appPageKeys && appPageKeys.length > 0) { + outputs.staticFiles.push({ + id: `${page}.rsc`, + pathname: `${route}.rsc`, + type: AdapterOutputType.STATIC_FILE, + filePath: rscFallbackPath, + }) + } } + // if was a static file output don't create page output as well continue } const pageTraceFile = `${pageFile}.nft.json` - const assets = await handleTraceFiles(pageTraceFile).catch((err) => { - if (err.code !== 'ENOENT' || (page !== '/404' && page !== '/500')) { - Log.warn(`Failed to locate traced assets for ${pageFile}`, err) + const assets = await handleTraceFiles(pageTraceFile, 'pages').catch( + (err) => { + if (err.code !== 'ENOENT' || (page !== '/404' && page !== '/500')) { + Log.warn(`Failed to locate traced assets for ${pageFile}`, err) + } + return {} as Record } - return {} as Record - }) + ) const functionConfig = functionsConfigManifest.functions[route] || {} + let sourcePage = route.replace(/^\//, '') + + sourcePage = sourcePage === 'api' ? 'api/index' : sourcePage const output: AdapterOutput['PAGES'] | AdapterOutput['PAGES_API'] = { id: route, @@ -632,6 +845,7 @@ export async function handleBuildComplete({ : AdapterOutputType.PAGES, filePath: pageTraceFile.replace(/\.nft\.json$/, ''), pathname: route, + sourcePage, assets, runtime: 'nodejs', config: { @@ -643,27 +857,92 @@ export async function handleBuildComplete({ if (output.type === AdapterOutputType.PAGES) { outputs.pages.push(output) + + // if page is get server side props we need to create + // the _next/data output as well + if (serverPropsPages.has(page)) { + const dataPathname = path.posix.join( + '/_next/data', + buildId, + page + '.json' + ) + outputs.pages.push({ + ...output, + pathname: dataPathname, + id: dataPathname, + }) + } + + for (const locale of config.i18n?.locales || []) { + const localePage = + page === '/' ? `/${locale}` : addPathPrefix(page, `/${locale}`) + + outputs.pages.push({ + ...output, + id: localePage, + pathname: localePage, + }) + + if (serverPropsPages.has(page)) { + const dataPathname = path.posix.join( + '/_next/data', + buildId, + localePage + '.json' + ) + outputs.pages.push({ + ...output, + pathname: dataPathname, + id: dataPathname, + }) + } + } } else { outputs.pagesApi.push(output) } + + if (appPageKeys && appPageKeys.length > 0) { + outputs.staticFiles.push({ + id: `${output.id}.rsc`, + pathname: `${output.pathname}.rsc`, + type: AdapterOutputType.STATIC_FILE, + filePath: rscFallbackPath, + }) + } } if (hasNodeMiddleware) { const middlewareFile = path.join(distDir, 'server', 'middleware.js') const middlewareTrace = `${middlewareFile}.nft.json` - const assets = await handleTraceFiles(middlewareTrace) + const assets = await handleTraceFiles(middlewareTrace, 'neutral') const functionConfig = functionsConfigManifest.functions['/_middleware'] || {} outputs.middleware = { pathname: '/_middleware', id: '/_middleware', + sourcePage: 'middleware', assets, type: AdapterOutputType.MIDDLEWARE, runtime: 'nodejs', filePath: middlewareFile, config: { - matchers: functionConfig.matchers, + matchers: + functionConfig.matchers?.map((item) => { + return { + source: item.originalSource, + sourceRegex: item.regexp, + has: item.has, + missing: [ + ...(item.missing || []), + // always skip middleware for on-demand revalidate + { + type: 'header', + key: 'x-prerender-revalidate', + value: prerenderManifest.preview.previewModeId, + }, + ], + } + }) || [], }, } satisfies AdapterOutput['MIDDLEWARE'] } @@ -681,10 +960,12 @@ export async function handleBuildComplete({ const normalizedPage = normalizeAppPath(page) const pageFile = path.join(appDistDir, `${page}.js`) const pageTraceFile = `${pageFile}.nft.json` - const assets = await handleTraceFiles(pageTraceFile).catch((err) => { - Log.warn(`Failed to copy traced files for ${pageFile}`, err) - return {} as Record - }) + const assets = await handleTraceFiles(pageTraceFile, 'app').catch( + (err) => { + Log.warn(`Failed to copy traced files for ${pageFile}`, err) + return {} as Record + } + ) const functionConfig = functionsConfigManifest.functions[normalizedPage] || {} @@ -692,6 +973,7 @@ export async function handleBuildComplete({ { pathname: normalizedPage, id: normalizedPage, + sourcePage: page, assets, type: page.endsWith('/route') ? AdapterOutputType.APP_ROUTE @@ -706,6 +988,12 @@ export async function handleBuildComplete({ appOutputMap[normalizedPage] = output if (output.type === AdapterOutputType.APP_PAGE) { + outputs.appPages.push({ + ...output, + pathname: + (output.pathname === '/' ? '/index' : output.pathname) + '.rsc', + id: (output.id === '/' ? '/index' : output.pathname) + '.rsc', + }) outputs.appPages.push(output) } else { outputs.appRoutes.push(output) @@ -765,11 +1053,8 @@ export async function handleBuildComplete({ for (const segmentPath of meta.segmentPaths) { const outputSegmentPath = - path.join( - appDistDir, - route + prefetchSegmentDirSuffix, - segmentPath - ) + prefetchSegmentSuffix + path.join(route + prefetchSegmentDirSuffix, segmentPath) + + prefetchSegmentSuffix const fallbackPathname = path.join( segmentsDir, @@ -840,6 +1125,20 @@ export async function handleBuildComplete({ return meta } + const filePathCache = new Map>() + const cachedFilePathCheck = async (filePath: string) => { + if (filePathCache.has(filePath)) { + return filePathCache.get(filePath) + } + const newCheck = fs + .access(filePath) + .then(() => true) + .catch(() => false) + filePathCache.set(filePath, newCheck) + + return newCheck + } + for (const route in prerenderManifest.routes) { const { initialExpireSeconds: initialExpiration, @@ -854,6 +1153,8 @@ export async function handleBuildComplete({ } = prerenderManifest.routes[route] const srcRoute = prerenderManifest.routes[route].srcRoute || route + const srcRouteInfo = prerenderManifest.dynamicRoutes[srcRoute] + const isAppPage = Boolean(appOutputMap[srcRoute]) || srcRoute === '/_not-found' @@ -885,7 +1186,19 @@ export async function handleBuildComplete({ // we use the static 404 for notFound: true if available // if not we do a blocking invoke on first request if (isNotFoundTrue && hasStatic404) { - filePath = path.join(pagesDistDir, '404.html') + const locale = + config.i18n && + normalizeLocalePath(route, config.i18n?.locales).detectedLocale + + for (const currentFilePath of [ + path.join(pagesDistDir, locale || '', '404.html'), + path.join(pagesDistDir, '404.html'), + ]) { + if (await cachedFilePathCheck(currentFilePath)) { + filePath = currentFilePath + break + } + } } const meta = await getAppRouteMeta(route, isAppPage) @@ -909,11 +1222,14 @@ export async function handleBuildComplete({ } : undefined, + parentFallbackMode: srcRouteInfo?.fallback, + fallback: !isNotFoundTrue || (isNotFoundTrue && hasStatic404) ? { filePath, - initialStatus, + initialStatus: + (initialStatus ?? isNotFoundTrue) ? 404 : undefined, initialHeaders: { ...initialHeaders, vary: varyHeader, @@ -921,7 +1237,10 @@ export async function handleBuildComplete({ ...meta.headers, }, initialExpiration, - initialRevalidate: initialRevalidate || 1, + initialRevalidate: + typeof initialRevalidate === 'undefined' + ? 1 + : initialRevalidate, } : undefined, config: { @@ -1034,38 +1353,344 @@ export async function handleBuildComplete({ } : undefined, } - outputs.prerenders.push(initialOutput) - if (isAppPage) { - await handleAppMeta(dynamicRoute, initialOutput, meta) + if (!config.i18n || isAppPage) { + outputs.prerenders.push(initialOutput) + + if (isAppPage) { + await handleAppMeta(dynamicRoute, initialOutput, meta) + } + + if (dataRoute) { + outputs.prerenders.push({ + ...initialOutput, + id: dataRoute, + pathname: dataRoute, + fallback: undefined, + }) + } + prerenderGroupId += 1 + } else { + for (const locale of config.i18n.locales) { + const currentOutput = { + ...initialOutput, + pathname: path.posix.join(`/${locale}`, initialOutput.pathname), + id: path.posix.join(`/${locale}`, initialOutput.id), + fallback: + typeof fallback === 'string' + ? { + ...initialOutput.fallback, + filePath: path.join( + pagesDistDir, + locale, + // app router dynamic route fallbacks don't have the + // extension so ensure it's added here + fallback.endsWith('.html') + ? fallback + : `${fallback}.html` + ), + } + : undefined, + groupId: prerenderGroupId, + } + outputs.prerenders.push(currentOutput) + + if (dataRoute) { + const dataPathname = path.posix.join( + `/_next/data`, + buildId, + locale, + dynamicRoute + '.json' + ) + outputs.prerenders.push({ + ...initialOutput, + id: dataPathname, + pathname: dataPathname, + // data route doesn't have skeleton fallback + fallback: undefined, + groupId: prerenderGroupId, + }) + } + prerenderGroupId += 1 + } } + } - if (dataRoute) { - outputs.prerenders.push({ - ...initialOutput, - id: dataRoute, - pathname: dataRoute, - fallback: undefined, - }) + // ensure 404 + const staticErrorDocs = [ + ...(hasStatic404 ? ['/404'] : []), + ...(hasStatic500 ? ['/500'] : []), + ] + + for (const errorDoc of staticErrorDocs) { + const errorDocPath = path.posix.join( + '/', + config.i18n?.defaultLocale || '', + errorDoc + ) + + if (!prerenderManifest.routes[errorDocPath]) { + for (const currentDocPath of [ + errorDocPath, + ...(config.i18n?.locales?.map((locale) => + path.posix.join('/', locale, errorDoc) + ) || []), + ]) { + const currentFilePath = path.join( + pagesDistDir, + `${currentDocPath}.html` + ) + if (await cachedFilePathCheck(currentFilePath)) { + outputs.staticFiles.push({ + pathname: currentDocPath, + id: currentDocPath, + type: AdapterOutputType.STATIC_FILE, + filePath: currentFilePath, + }) + } + } } - prerenderGroupId += 1 } } normalizePathnames(config, outputs) + const dynamicRoutes: DynamicRouteItem[] = [] + const dynamicDataRoutes: DynamicRouteItem[] = [] + const dynamicSegmentRoutes: DynamicRouteItem[] = [] + + const getDestinationQuery = (routeKeys: Record) => { + const items = Object.entries(routeKeys ?? {}) + if (items.length === 0) return '' + + return '?' + items.map(([key, value]) => `${value}=$${key}`).join('&') + } + + const fallbackFalseHasCondition: RouteHas[] = [ + { + type: 'cookie', + key: '__prerender_bypass', + value: prerenderManifest.preview.previewModeId, + }, + { + type: 'cookie', + key: '__next_preview_data', + }, + ] + + for (const route of routesManifest.dynamicRoutes) { + const shouldLocalize = config.i18n + + const routeRegex = getNamedRouteRegex(route.page, { + prefixRouteKeys: true, + }) + + const isFallbackFalse = + prerenderManifest.dynamicRoutes[route.page]?.fallback === false + + const { hasFallbackRootParams } = route + + const sourceRegex = routeRegex.namedRegex.replace( + '^', + `^${config.basePath && config.basePath !== '/' ? path.posix.join('/', config.basePath || '') : ''}[/]?${shouldLocalize ? '(?[^/]{1,})?' : ''}` + ) + const destination = + path.posix.join( + '/', + config.basePath, + shouldLocalize ? '/$nextLocale' : '', + route.page + ) + getDestinationQuery(route.routeKeys) + + if ( + appPageKeys && + appPageKeys.length > 0 && + (config.experimental.cacheComponents || + config.experimental.clientSegmentCache) + ) { + // If we have fallback root params (implying we've already + // emitted a rewrite for the /_tree request), or if the route + // has PPR enabled and client param parsing is enabled, then + // we don't need to include any other suffixes. + const shouldSkipSuffixes = hasFallbackRootParams + + dynamicRoutes.push({ + source: route.page + '.rsc', + sourceRegex: sourceRegex.replace( + new RegExp(escapeStringRegexp('(?:/)?$')), + // Now than the upstream issues has been resolved, we can safely + // add the suffix back, this resolves a bug related to segment + // rewrites not capturing the correct suffix values when + // enabled. + shouldSkipSuffixes + ? '(?\\.rsc|\\.segments/.+\\.segment\\.rsc)(?:/)?$' + : '(?\\.rsc|\\.prefetch\\.rsc|\\.segments/.+\\.segment\\.rsc)(?:/)?$' + ), + destination: destination?.replace(/($|\?)/, '$rscSuffix$1'), + has: isFallbackFalse ? fallbackFalseHasCondition : undefined, + missing: undefined, + }) + } + + // needs basePath and locale handling if pages router + dynamicRoutes.push({ + source: route.page, + sourceRegex, + destination, + has: isFallbackFalse ? fallbackFalseHasCondition : undefined, + missing: undefined, + }) + + for (const segmentRoute of route.prefetchSegmentDataRoutes || []) { + dynamicSegmentRoutes.push({ + source: route.page, + sourceRegex: segmentRoute.source.replace( + '^', + `^${config.basePath && config.basePath !== '/' ? path.posix.join('/', config.basePath || '') : ''}[/]?` + ), + destination: path.posix.join( + '/', + config.basePath, + segmentRoute.destination + + getDestinationQuery(segmentRoute.routeKeys) + ), + has: undefined, + missing: undefined, + }) + } + } + + const needsMiddlewareResolveRoutes = + outputs.middleware && outputs.pages.length > 0 + + const dataRoutePages = new Set([ + ...routesManifest.dataRoutes.map((item) => item.page), + ]) + const sortedDataPages = sortSortableRoutes([ + ...(needsMiddlewareResolveRoutes + ? [...staticPages].map((page) => ({ sourcePage: page, page })) + : []), + ...routesManifest.dataRoutes.map((item) => ({ + sourcePage: item.page, + page: item.page, + })), + ]) + + for (const { page } of sortedDataPages) { + if (needsMiddlewareResolveRoutes || isDynamicRoute(page)) { + const shouldLocalize = config.i18n + const isFallbackFalse = + prerenderManifest.dynamicRoutes[page]?.fallback === false + + const routeRegex = getNamedRouteRegex(page + '.json', { + prefixRouteKeys: true, + includeSuffix: true, + }) + const destination = path.posix.join( + '/', + config.basePath, + ...(dataRoutePages.has(page) ? [`_next/data`, buildId] : ''), + ...(page === '/' + ? [shouldLocalize ? '$nextLocale.json' : 'index.json'] + : [ + shouldLocalize ? '$nextLocale' : '', + page + + '.json' + + getDestinationQuery(routeRegex.routeKeys || {}), + ]) + ) + + dynamicDataRoutes.push({ + source: page, + sourceRegex: + shouldLocalize && page === '/' + ? '^' + + path.posix.join( + '/', + config.basePath, + '_next/data', + escapeStringRegexp(buildId), + '(?[^/]{1,}).json' + ) + : routeRegex.namedRegex.replace( + '^', + `^${path.posix.join( + '/', + config.basePath, + `_next/data`, + escapeStringRegexp(buildId) + )}[/]?${shouldLocalize ? '(?[^/]{1,})?' : ''}` + ), + destination, + has: isFallbackFalse ? fallbackFalseHasCondition : undefined, + missing: undefined, + }) + } + } + + const buildRewriteItem = (route: ManifestRewriteRoute): RewriteItem => { + const converted = convertRewrites([route], ['nextInternalLocale'])[0] + const regex = converted.src || route.regex + + return { + source: route.source, + sourceRegex: route.internal ? regex : modifyRouteRegex(regex), + destination: converted.dest || route.destination, + has: route.has, + missing: route.missing, + } + } + try { + Log.info(`Running onBuildComplete from ${adapterMod.name}`) await adapterMod.onBuildComplete({ routes: { - dynamicRoutes: routesManifest.dynamicRoutes, - rewrites: routesManifest.rewrites, - redirects: routesManifest.redirects, - headers: routesManifest.headers, + dynamicRoutes: [ + ...dynamicDataRoutes, + ...dynamicSegmentRoutes, + ...dynamicRoutes, + ], + rewrites: { + beforeFiles: + routesManifest.rewrites.beforeFiles.map(buildRewriteItem), + afterFiles: + routesManifest.rewrites.afterFiles.map(buildRewriteItem), + fallback: routesManifest.rewrites.fallback.map(buildRewriteItem), + }, + redirects: routesManifest.redirects.map((route) => { + const converted = convertRedirects([route], 307)[0] + let dest = 'headers' in converted && converted.headers?.Location + const regex = converted.src || route.regex + + return { + source: route.source, + sourceRegex: route.internal ? regex : modifyRouteRegex(regex), + destination: dest || route.destination, + statusCode: converted.status || getRedirectStatus(route), + has: route.has, + missing: route.missing, + priority: route.internal || undefined, + } + }), + headers: routesManifest.headers.map((route) => { + const converted = convertHeaders([route])[0] + const regex = converted.src || route.regex + + return { + source: route.source, + sourceRegex: route.internal ? regex : modifyRouteRegex(regex), + headers: 'headers' in converted ? converted.headers || {} : {}, + has: route.has, + missing: route.missing, + priority: route.internal || undefined, + } + }), }, outputs, config, distDir, + buildId, nextVersion, projectDir: dir, repoRoot: tracingRoot, diff --git a/packages/next/src/build/collect-build-traces.ts b/packages/next/src/build/collect-build-traces.ts index 4786ff23de691..a70a35f078729 100644 --- a/packages/next/src/build/collect-build-traces.ts +++ b/packages/next/src/build/collect-build-traces.ts @@ -23,6 +23,22 @@ import type { RoutesUsingEdgeRuntime } from './utils' const debug = debugOriginal('next:build:build-traces') +export const makeIgnoreFn = (root: string, ignores: string[]) => { + // pre compile the ignore globs + const isMatch = picomatch(ignores, { + contains: true, + dot: true, + }) + + return (pathname: string) => { + if (path.isAbsolute(pathname) && !pathname.startsWith(root)) { + return true + } + + return isMatch(pathname) + } +} + function shouldIgnore( file: string, serverIgnoreFn: (file: string) => boolean, @@ -199,22 +215,6 @@ export async function collectBuildTraces({ } } - const makeIgnoreFn = (ignores: string[]) => { - // pre compile the ignore globs - const isMatch = picomatch(ignores, { - contains: true, - dot: true, - }) - - return (pathname: string) => { - if (path.isAbsolute(pathname) && !pathname.startsWith(root)) { - return true - } - - return isMatch(pathname) - } - } - const sharedIgnores = [ '**/next/dist/compiled/next-server/**/*.dev.js', ...(isStandalone ? [] : ['**/next/dist/compiled/jest-worker/**/*']), @@ -235,7 +235,7 @@ export async function collectBuildTraces({ ...additionalIgnores, ] - const sharedIgnoresFn = makeIgnoreFn(sharedIgnores) + const sharedIgnoresFn = makeIgnoreFn(root, sharedIgnores) const serverIgnores = [ ...sharedIgnores, @@ -247,7 +247,7 @@ export async function collectBuildTraces({ ? ['**/node_modules/sharp/**/*', '**/@img/sharp-libvips*/**/*'] : []), ].filter(nonNullable) - const serverIgnoreFn = makeIgnoreFn(serverIgnores) + const serverIgnoreFn = makeIgnoreFn(root, serverIgnores) const minimalServerIgnores = [ ...serverIgnores, @@ -255,7 +255,7 @@ export async function collectBuildTraces({ '**/next/dist/server/web/sandbox/**/*', '**/next/dist/server/post-process.js', ] - const minimalServerIgnoreFn = makeIgnoreFn(minimalServerIgnores) + const minimalServerIgnoreFn = makeIgnoreFn(root, minimalServerIgnores) const routesIgnores = [ ...sharedIgnores, @@ -266,7 +266,7 @@ export async function collectBuildTraces({ '**/next/dist/server/post-process.js', ].filter(nonNullable) - const routeIgnoreFn = makeIgnoreFn(routesIgnores) + const routeIgnoreFn = makeIgnoreFn(root, routesIgnores) const serverTracedFiles = new Set() const minimalServerTracedFiles = new Set() diff --git a/packages/next/src/build/define-env.ts b/packages/next/src/build/define-env.ts index ca3d8f7fa8ca1..1d4368881f214 100644 --- a/packages/next/src/build/define-env.ts +++ b/packages/next/src/build/define-env.ts @@ -147,6 +147,8 @@ export function getDefineEnv({ : process.env.NEXT_RSPACK ? 'Rspack' : 'Webpack', + // minimal mode is enforced when an adapter is configured + 'process.env.MINIMAL_MODE': Boolean(config.experimental.adapterPath), // TODO: enforce `NODE_ENV` on `process.env`, and add a test: 'process.env.NODE_ENV': dev || config.experimental.allowDevelopmentBuild diff --git a/packages/next/src/build/index.ts b/packages/next/src/build/index.ts index aa81db30e0b4d..fb9b0756d65ee 100644 --- a/packages/next/src/build/index.ts +++ b/packages/next/src/build/index.ts @@ -1599,7 +1599,11 @@ export default async function build( undefined ) ) - } else if (!isReservedPage(route)) { + } else if ( + !isReservedPage(route) || + // don't consider /api reserved here + route.match(/^\/(api(\/|$))/) + ) { staticRoutes.push(pageToRoute(route)) } } @@ -3186,7 +3190,7 @@ export default async function build( ...(isRoutePPREnabled ? [ { - type: 'header', + type: 'header' as const, key: 'user-agent', value: htmlBotsRegexString, }, @@ -4182,8 +4186,10 @@ export default async function build( dir, distDir, config, + buildId, configOutDir: path.join(dir, configOutDir), staticPages, + serverPropsPages, nextVersion: process.env.__NEXT_VERSION as string, tracingRoot: outputFileTracingRoot, hasNodeMiddleware, @@ -4196,6 +4202,7 @@ export default async function build( middlewareManifest, functionsConfigManifest, hasStatic404: useStaticPages404, + hasStatic500: useDefaultStatic500, requiredServerFiles: requiredServerFilesManifest.files, }) }) diff --git a/packages/next/src/build/templates/app-page.ts b/packages/next/src/build/templates/app-page.ts index c71a6a267e7a8..5455f55f9d70a 100644 --- a/packages/next/src/build/templates/app-page.ts +++ b/packages/next/src/build/templates/app-page.ts @@ -135,8 +135,9 @@ export async function handler( const multiZoneDraftMode = process.env .__NEXT_MULTI_ZONE_DRAFT_MODE as any as boolean - // TODO: replace with more specific flags - const minimalMode = getRequestMeta(req, 'minimalMode') + const isMinimalMode = Boolean( + process.env.MINIMAL_MODE || getRequestMeta(req, 'minimalMode') + ) const prepareResult = await routeModule.prepare(req, res, { srcPage, @@ -167,6 +168,7 @@ export async function handler( revalidateOnlyGenerated, routerServerContext, nextConfig, + parsedUrl, interceptionRoutePatterns, } = prepareResult @@ -317,7 +319,7 @@ export async function handler( // which will generate the RDC for the route. When resuming a Dynamic // RSC request, we'll pass the minimal postponed data to the render // which will trigger the `supportsDynamicResponse` to be true. - isDynamicRSCRequest && !minimalMode + isDynamicRSCRequest && !isMinimalMode : // Otherwise, we can support dynamic responses if it's a dynamic RSC request. isDynamicRSCRequest) @@ -385,6 +387,16 @@ export async function handler( const tracer = getTracer() const activeSpan = tracer.getActiveScopeSpan() + const render404 = async () => { + // TODO: should route-module itself handle rendering the 404 + if (routerServerContext?.render404) { + await routerServerContext.render404(req, res, parsedUrl, false) + } else { + res.end('This page could not be found') + } + return null + } + try { const varyHeader = routeModule.getVaryHeader( resolvedPathname, @@ -670,7 +682,7 @@ export async function handler( isOnDemandRevalidate && revalidateOnlyGenerated && !previousIncrementalCacheEntry && - !minimalMode + !isMinimalMode ) { if (routerServerContext?.render404) { await routerServerContext.render404(req, res) @@ -712,7 +724,7 @@ export async function handler( } if ( - !minimalMode && + !isMinimalMode && fallbackMode !== FallbackMode.BLOCKING_STATIC_RENDER && staticPathKey && !didRespond && @@ -729,6 +741,9 @@ export async function handler( // When fallback isn't present, abort this render so we 404 fallbackMode === FallbackMode.NOT_FOUND ) { + if (nextConfig.experimental.adapterPath) { + return await render404() + } throw new NoFallbackError() } @@ -779,6 +794,7 @@ export async function handler( forceStaticRender: false, }), waitUntil: ctx.waitUntil, + isMinimalMode, }) // If the fallback response was set to null, then we should return null. @@ -810,7 +826,7 @@ export async function handler( // Only enable RDC for Navigations if the feature is enabled. supportsRDCForNavigations && process.env.NEXT_RUNTIME !== 'edge' && - !minimalMode && + !isMinimalMode && incrementalCache && isDynamicRSCRequest && // We don't typically trigger an on-demand revalidation for dynamic RSC @@ -943,6 +959,7 @@ export async function handler( nextConfig, prerenderManifest, waitUntil: ctx.waitUntil, + isMinimalMode, }) if (isDraftMode) { @@ -985,7 +1002,7 @@ export async function handler( !isDynamicRSCRequest && (!didPostpone || isPrefetchRSCRequest) ) { - if (!minimalMode) { + if (!isMinimalMode) { // set x-nextjs-cache header to match the header // we set for the image-optimizer res.setHeader( @@ -1076,7 +1093,7 @@ export async function handler( // 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?.[NEXT_CACHE_TAGS_HEADER] - if (minimalMode && isSSG && tags && typeof tags === 'string') { + if (isMinimalMode && isSSG && tags && typeof tags === 'string') { res.setHeader(NEXT_CACHE_TAGS_HEADER, tags) } @@ -1132,7 +1149,7 @@ export async function handler( if (cachedData.headers) { const headers = { ...cachedData.headers } - if (!minimalMode || !isSSG) { + if (!isMinimalMode || !isSSG) { delete headers[NEXT_CACHE_TAGS_HEADER] } @@ -1155,7 +1172,7 @@ export async function handler( // 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?.[NEXT_CACHE_TAGS_HEADER] - if (minimalMode && isSSG && tags && typeof tags === 'string') { + if (isMinimalMode && isSSG && tags && typeof tags === 'string') { res.setHeader(NEXT_CACHE_TAGS_HEADER, tags) } @@ -1168,7 +1185,7 @@ export async function handler( // Redirect information is encoded in RSC payload, so we don't need to use redirect status codes if ( - !minimalMode && + !isMinimalMode && cachedData.status && RedirectStatusCode[cachedData.status] && isRSCRequest @@ -1239,13 +1256,13 @@ export async function handler( // 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 (!didPostpone || isMinimalMode || 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 && + isMinimalMode && isRoutePPREnabled && body.contentType === HTML_CONTENT_TYPE_HEADER ) { diff --git a/packages/next/src/build/templates/app-route.ts b/packages/next/src/build/templates/app-route.ts index b917f90942224..9770471c002dd 100644 --- a/packages/next/src/build/templates/app-route.ts +++ b/packages/next/src/build/templates/app-route.ts @@ -118,6 +118,7 @@ export async function handler( buildId, params, nextConfig, + parsedUrl, isDraftMode, prerenderManifest, routerServerContext, @@ -135,12 +136,25 @@ export async function handler( prerenderManifest.routes[resolvedPathname] ) + const render404 = async () => { + // TODO: should route-module itself handle rendering the 404 + if (routerServerContext?.render404) { + await routerServerContext.render404(req, res, parsedUrl, false) + } else { + res.end('This page could not be found') + } + return null + } + if (isIsr && !isDraftMode) { const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]) const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage] if (prerenderInfo) { if (prerenderInfo.fallback === false && !isPrerendered) { + if (nextConfig.experimental.adapterPath) { + return await render404() + } throw new NoFallbackError() } } @@ -264,6 +278,9 @@ export async function handler( } }) } + const isMinimalMode = Boolean( + process.env.MINIMAL_MODE || getRequestMeta(req, 'minimalMode') + ) const handleResponse = async (currentSpan?: Span) => { const responseGenerator: ResponseGenerator = async ({ @@ -271,7 +288,7 @@ export async function handler( }) => { try { if ( - !getRequestMeta(req, 'minimalMode') && + !isMinimalMode && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry @@ -383,6 +400,7 @@ export async function handler( revalidateOnlyGenerated, responseGenerator, waitUntil: ctx.waitUntil, + isMinimalMode, }) // we don't create a cacheEntry for ISR @@ -396,7 +414,7 @@ export async function handler( ) } - if (!getRequestMeta(req, 'minimalMode')) { + if (!isMinimalMode) { res.setHeader( 'x-nextjs-cache', isOnDemandRevalidate @@ -419,7 +437,7 @@ export async function handler( const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers) - if (!(getRequestMeta(req, 'minimalMode') && isIsr)) { + if (!(isMinimalMode && isIsr)) { headers.delete(NEXT_CACHE_TAGS_HEADER) } diff --git a/packages/next/src/build/templates/edge-ssr-app.ts b/packages/next/src/build/templates/edge-ssr-app.ts index 566af90348e25..5a02ca5ad3701 100644 --- a/packages/next/src/build/templates/edge-ssr-app.ts +++ b/packages/next/src/build/templates/edge-ssr-app.ts @@ -173,7 +173,8 @@ async function requestHandler( incrementalCache: await pageRouteModule.getIncrementalCache( baseReq, nextConfig, - prerenderManifest + prerenderManifest, + true ), waitUntil: event.waitUntil.bind(event), diff --git a/packages/next/src/compiled/@vercel/routing-utils/LICENSE b/packages/next/src/compiled/@vercel/routing-utils/LICENSE new file mode 100644 index 0000000000000..5454d6d51eb29 --- /dev/null +++ b/packages/next/src/compiled/@vercel/routing-utils/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017 Vercel, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/next/src/compiled/@vercel/routing-utils/package.json b/packages/next/src/compiled/@vercel/routing-utils/package.json new file mode 100644 index 0000000000000..f8accbd7a94ff --- /dev/null +++ b/packages/next/src/compiled/@vercel/routing-utils/package.json @@ -0,0 +1 @@ +{"name":"@vercel/routing-utils","main":"superstatic.js","license":"Apache-2.0"} diff --git a/packages/next/src/compiled/@vercel/routing-utils/superstatic.js b/packages/next/src/compiled/@vercel/routing-utils/superstatic.js new file mode 100644 index 0000000000000..14be9f11f71ff --- /dev/null +++ b/packages/next/src/compiled/@vercel/routing-utils/superstatic.js @@ -0,0 +1 @@ +(function(){"use strict";var e={993:function(e,t,r){var n=Object.defineProperty;var o=Object.getOwnPropertyDescriptor;var a=Object.getOwnPropertyNames;var i=Object.prototype.hasOwnProperty;var __export=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:true})};var __copyProps=(e,t,r,c)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let s of a(t))if(!i.call(e,s)&&s!==r)n(e,s,{get:()=>t[s],enumerable:!(c=o(t,s))||c.enumerable})}return e};var __toCommonJS=e=>__copyProps(n({},"__esModule",{value:true}),e);var c={};__export(c,{collectHasSegments:()=>collectHasSegments,convertCleanUrls:()=>convertCleanUrls,convertHeaders:()=>convertHeaders,convertRedirects:()=>convertRedirects,convertRewrites:()=>convertRewrites,convertTrailingSlash:()=>convertTrailingSlash,getCleanUrls:()=>getCleanUrls,pathToRegexp:()=>pathToRegexp,sourceToRegex:()=>sourceToRegex});e.exports=__toCommonJS(c);var s=r(310);var f=r(671);var u=r(397);function cloneKeys(e){if(typeof e==="undefined"){return void 0}return e.slice(0)}function compareKeys(e,t){const r=typeof e==="undefined"?"undefined":e.toString();const n=typeof t==="undefined"?"undefined":t.toString();return r===n}function pathToRegexp(e,t,r,n){const o=cloneKeys(r);const a=(0,f.pathToRegexp)(t,r,n);try{const i=r;const c=(0,u.pathToRegexp)(t,o,n);const s=a.toString()!==c.toString();if(process.env.FORCE_PATH_TO_REGEXP_LOG||s){const r=JSON.stringify({path:t,currentRegExp:a.toString(),newRegExp:c.toString()});console.error(`[vc] PATH TO REGEXP PATH DIFF @ #${e}: ${r}`)}const f=!compareKeys(r,o);if(process.env.FORCE_PATH_TO_REGEXP_LOG||f){const t=JSON.stringify({isDiffKeys:f,currentKeys:i,newKeys:o});console.error(`[vc] PATH TO REGEXP KEYS DIFF @ #${e}: ${t}`)}}catch(r){const n=r;const o=JSON.stringify({path:t,error:n.message});console.error(`[vc] PATH TO REGEXP ERROR @ #${e}: ${o}`)}return a}const p="__UN_NAMED_SEGMENT__";function getCleanUrls(e){const t=e.map(toRoute).filter((e=>e.endsWith(".html"))).map((e=>({html:e,clean:e.slice(0,-5)})));return t}function convertCleanUrls(e,t,r=308){const n=[];if(e){const e=t?"/$1/":"/$1";n.push({src:"^/(?:(.+)/)?index(?:\\.html)?/?$",headers:{Location:e},status:r});n.push({src:"^/(.*)\\.html/?$",headers:{Location:e},status:r})}return n}function convertRedirects(e,t=308){return e.map((e=>{const{src:r,segments:n}=sourceToRegex(e.source);const o=collectHasSegments(e.has);normalizeHasKeys(e.has);normalizeHasKeys(e.missing);try{const a=replaceSegments(n,o,e.destination,true);let i;if(typeof e.permanent==="boolean"){i=e.permanent?308:307}else if(e.statusCode){i=e.statusCode}else{i=t}const c={src:r,headers:{Location:a},status:i};if(e.has){c.has=e.has}if(e.missing){c.missing=e.missing}return c}catch(t){throw new Error(`Failed to parse redirect: ${JSON.stringify(e)}`)}}))}function convertRewrites(e,t){return e.map((e=>{const{src:r,segments:n}=sourceToRegex(e.source);const o=collectHasSegments(e.has);normalizeHasKeys(e.has);normalizeHasKeys(e.missing);try{const a=replaceSegments(n,o,e.destination,false,t);const i={src:r,dest:a,check:true};if(e.has){i.has=e.has}if(e.missing){i.missing=e.missing}if(e.statusCode){i.status=e.statusCode}return i}catch(t){throw new Error(`Failed to parse rewrite: ${JSON.stringify(e)}`)}}))}function convertHeaders(e){return e.map((e=>{const t={};const{src:r,segments:n}=sourceToRegex(e.source);const o=collectHasSegments(e.has);normalizeHasKeys(e.has);normalizeHasKeys(e.missing);const a=n.filter((e=>e!==p));const i={};n.forEach(((e,t)=>{i[e]=toSegmentDest(t)}));o.forEach((e=>{i[e]="$"+e}));e.headers.forEach((({key:e,value:r})=>{if(a.length>0||o.length>0){if(e.includes(":")){e=safelyCompile(e,i)}if(r.includes(":")){r=safelyCompile(r,i)}}t[e]=r}));const c={src:r,headers:t,continue:true};if(e.has){c.has=e.has}if(e.missing){c.missing=e.missing}return c}))}function convertTrailingSlash(e,t=308){const r=[];if(e){r.push({src:"^/\\.well-known(?:/.*)?$"});r.push({src:"^/((?:[^/]+/)*[^/\\.]+)$",headers:{Location:"/$1/"},status:t});r.push({src:"^/((?:[^/]+/)*[^/]+\\.\\w+)/$",headers:{Location:"/$1"},status:t})}else{r.push({src:"^/(.*)\\/$",headers:{Location:"/$1"},status:t})}return r}function sourceToRegex(e){const t=[];const r=pathToRegexp("632",e,t,{strict:true,sensitive:true,delimiter:"/"});const n=t.map((e=>e.name)).map((e=>{if(typeof e!=="string"){return p}return e}));return{src:r.source,segments:n}}const l=/\(\?<([a-zA-Z][a-zA-Z0-9_]*)>/g;const normalizeHasKeys=(e=[])=>{for(const t of e){if("key"in t&&t.type==="header"){t.key=t.key.toLowerCase()}}return e};function getStringValueForRegex(e){if(typeof e==="string"){return e}if(e&&typeof e==="object"&&e!==null){if("re"in e&&typeof e.re==="string"){return e.re}}return null}function collectHasSegments(e){const t=new Set;for(const r of e||[]){if(!r.value&&"key"in r){t.add(r.key)}const e=getStringValueForRegex(r.value);if(e){for(const r of e.matchAll(l)){if(r[1]){t.add(r[1])}}if(r.type==="host"){t.add("host")}}}return[...t]}const escapeSegment=(e,t)=>e.replace(new RegExp(`:${t}`,"g"),`__ESC_COLON_${t}`);const unescapeSegments=e=>e.replace(/__ESC_COLON_/gi,":");function replaceSegments(e,t,r,n,o){const a=e.filter((e=>e!==p));const i=r.includes(":")&&a.length>0||t.length>0||!n;if(!i){return r}let c=r;const f={};e.forEach(((e,t)=>{f[e]=toSegmentDest(t);c=escapeSegment(c,e)}));t.forEach((e=>{f[e]="$"+e;c=escapeSegment(c,e)}));const u=(0,s.parse)(c,true);delete u.href;delete u.path;delete u.search;delete u.host;let{pathname:l,hash:g,query:h,hostname:v,...d}=u;l=unescapeSegments(l||"");g=unescapeSegments(g||"");v=unescapeSegments(v||"");let m=new Set;const x=[];const y=[];const E=[];try{pathToRegexp("528",l,x);pathToRegexp("834",g||"",y);pathToRegexp("712",v||"",E)}catch(e){}m=new Set([...x,...y,...E].map((e=>e.name)).filter((e=>typeof e==="string")));l=safelyCompile(l,f,true);g=g?safelyCompile(g,f,true):null;v=v?safelyCompile(v,f,true):null;for(const[e,t]of Object.entries(h)){if(Array.isArray(t)){h[e]=t.map((e=>safelyCompile(unescapeSegments(e),f,true)))}else{h[e]=safelyCompile(unescapeSegments(t),f,true)}}const R=Object.keys(f);const T=!n&&!R.some((e=>!(o&&o.includes(e))&&m.has(e)));if(T){for(const e of R){if(!(e in h)&&e!==p){h[e]=f[e]}}}r=(0,s.format)({...d,hostname:v,pathname:l,query:h,hash:g});return r.replace(/%24/g,"$")}function safelyCompile(e,t,r){if(!e){return e}if(r){try{return(0,f.compile)(e,{validate:false})(t)}catch(e){}}for(const r of Object.keys(t)){if(e.includes(`:${r}`)){e=e.replace(new RegExp(`:${r}\\*`,"g"),`:${r}--ESCAPED_PARAM_ASTERISK`).replace(new RegExp(`:${r}\\?`,"g"),`:${r}--ESCAPED_PARAM_QUESTION`).replace(new RegExp(`:${r}\\+`,"g"),`:${r}--ESCAPED_PARAM_PLUS`).replace(new RegExp(`:${r}(?!\\w)`,"g"),`--ESCAPED_PARAM_COLON${r}`)}}e=e.replace(/(:|\*|\?|\+|\(|\)|\{|\})/g,"\\$1").replace(/--ESCAPED_PARAM_PLUS/g,"+").replace(/--ESCAPED_PARAM_COLON/g,":").replace(/--ESCAPED_PARAM_QUESTION/g,"?").replace(/--ESCAPED_PARAM_ASTERISK/g,"*");return(0,f.compile)(`/${e}`,{validate:false})(t).slice(1)}function toSegmentDest(e){const t=e+1;return"$"+t.toString()}function toRoute(e){return e.startsWith("/")?e:"/"+e}0&&0},397:function(e,t){Object.defineProperty(t,"__esModule",{value:true});t.pathToRegexp=t.tokensToRegexp=t.regexpToFunction=t.match=t.tokensToFunction=t.compile=t.parse=void 0;function lexer(e){var t=[];var r=0;while(r=48&&i<=57||i>=65&&i<=90||i>=97&&i<=122||i===95){o+=e[a++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(r));t.push({type:"NAME",index:r,value:o});r=a;continue}if(n==="("){var c=1;var s="";var a=r+1;if(e[a]==="?"){throw new TypeError('Pattern cannot start with "?" at '.concat(a))}while(a-1)return true}return false};var safePattern=function(e){var t=c[c.length-1];var r=e||(t&&typeof t==="string"?t:"");if(t&&!r){throw new TypeError('Must have text between two parameters, missing text after "'.concat(t.name,'"'))}if(!r||isSafe(r))return"[^".concat(escapeString(i),"]+?");return"(?:(?!".concat(escapeString(r),")[^").concat(escapeString(i),"])+?")};while(f)?(?!\?)/g;var n=0;var o=r.exec(e.source);while(o){t.push({name:o[1]||n++,prefix:"",suffix:"",modifier:"",pattern:""});o=r.exec(e.source)}return e}function arrayToRegexp(e,t,r){var n=e.map((function(e){return pathToRegexp(e,t,r).source}));return new RegExp("(?:".concat(n.join("|"),")"),flags(r))}function stringToRegexp(e,t,r){return tokensToRegexp(parse(e,r),t,r)}function tokensToRegexp(e,t,r){if(r===void 0){r={}}var n=r.strict,o=n===void 0?false:n,a=r.start,i=a===void 0?true:a,c=r.end,s=c===void 0?true:c,f=r.encode,u=f===void 0?function(e){return e}:f,p=r.delimiter,l=p===void 0?"/#?":p,g=r.endsWith,h=g===void 0?"":g;var v="[".concat(escapeString(h),"]|$");var d="[".concat(escapeString(l),"]");var m=i?"^":"";for(var x=0,y=e;x-1:w===undefined;if(!o){m+="(?:".concat(d,"(?=").concat(v,"))?")}if(!S){m+="(?=".concat(d,"|").concat(v,")")}}return new RegExp(m,flags(r))}t.tokensToRegexp=tokensToRegexp;function pathToRegexp(e,t,r){if(e instanceof RegExp)return regexpToRegexp(e,t);if(Array.isArray(e))return arrayToRegexp(e,t,r);return stringToRegexp(e,t,r)}t.pathToRegexp=pathToRegexp},671:function(e){e.exports=require("next/dist/compiled/path-to-regexp")},310:function(e){e.exports=require("url")}};var t={};function __nccwpck_require__(r){var n=t[r];if(n!==undefined){return n.exports}var o=t[r]={exports:{}};var a=true;try{e[r](o,o.exports,__nccwpck_require__);a=false}finally{if(a)delete t[r]}return o.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var r=__nccwpck_require__(993);module.exports=r})(); \ No newline at end of file diff --git a/packages/next/src/lib/load-custom-routes.ts b/packages/next/src/lib/load-custom-routes.ts index c13829ba79fdc..3ea01ce13a88c 100644 --- a/packages/next/src/lib/load-custom-routes.ts +++ b/packages/next/src/lib/load-custom-routes.ts @@ -9,7 +9,7 @@ import { isFullStringUrl } from './url' export type RouteHas = | { - type: string + type: 'header' | 'cookie' | 'query' key: string value?: string } diff --git a/packages/next/src/server/lib/incremental-cache/index.ts b/packages/next/src/server/lib/incremental-cache/index.ts index 8840a2d4bf379..c26935d58ac4e 100644 --- a/packages/next/src/server/lib/incremental-cache/index.ts +++ b/packages/next/src/server/lib/incremental-cache/index.ts @@ -144,6 +144,9 @@ export class IncrementalCache implements IncrementalCacheType { if (globalCacheHandler?.FetchCache) { CurCacheHandler = globalCacheHandler.FetchCache + if (IncrementalCache.debug) { + console.log('IncrementalCache: using global FetchCache cache handler') + } } else { if (fs && serverDistDir) { if (IncrementalCache.debug) { diff --git a/packages/next/src/server/route-modules/pages/pages-handler.ts b/packages/next/src/server/route-modules/pages/pages-handler.ts index ce76e27907d67..fad5176cd2539 100644 --- a/packages/next/src/server/route-modules/pages/pages-handler.ts +++ b/packages/next/src/server/route-modules/pages/pages-handler.ts @@ -101,6 +101,19 @@ export const getHandler = ({ return } + const isMinimalMode = Boolean( + process.env.MINIMAL_MODE || getRequestMeta(req, 'minimalMode') + ) + + const render404 = async () => { + // TODO: should route-module itself handle rendering the 404 + if (routerServerContext?.render404) { + await routerServerContext.render404(req, res, parsedUrl, false) + } else { + res.end('This page could not be found') + } + } + const { buildId, query, @@ -173,6 +186,9 @@ export const getHandler = ({ if (prerenderInfo) { if (prerenderInfo.fallback === false && !isPrerendered) { + if (nextConfig.experimental.adapterPath) { + return await render404() + } throw new NoFallbackError() } @@ -191,7 +207,7 @@ export const getHandler = ({ // to the bot in the head. if ( (isIsrFallback && isBot(req.headers['user-agent'] || '')) || - getRequestMeta(req, 'minimalMode') + isMinimalMode ) { isIsrFallback = false } @@ -454,7 +470,8 @@ export const getHandler = ({ incrementalCache: await routeModule.getIncrementalCache( req, nextConfig, - prerenderManifest + prerenderManifest, + isMinimalMode ), waitUntil: ctx.waitUntil, } @@ -469,7 +486,7 @@ export const getHandler = ({ } if ( - !getRequestMeta(req, 'minimalMode') && + !isMinimalMode && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry @@ -518,6 +535,7 @@ export const getHandler = ({ waitUntil: ctx.waitUntil, responseGenerator: responseGenerator, prerenderManifest, + isMinimalMode, }) // if we got a cache hit this wasn't an ISR fallback @@ -532,7 +550,7 @@ export const getHandler = ({ return } - if (hasStaticProps && !getRequestMeta(req, 'minimalMode')) { + if (hasStaticProps && !isMinimalMode) { res.setHeader( 'x-nextjs-cache', isOnDemandRevalidate @@ -609,13 +627,7 @@ export const getHandler = ({ res.end('{"notFound":true}') return } - // TODO: should route-module itself handle rendering the 404 - if (routerServerContext?.render404) { - await routerServerContext.render404(req, res, parsedUrl, false) - } else { - res.end('This page could not be found') - } - return + return await render404() } if (result.value.kind === CachedRouteKind.REDIRECT) { @@ -682,9 +694,7 @@ export const getHandler = ({ // send the _error response if ( getRequestMeta(req, 'customErrorRender') || - (isErrorPage && - getRequestMeta(req, 'minimalMode') && - res.statusCode === 500) + (isErrorPage && isMinimalMode && res.statusCode === 500) ) { return null } diff --git a/packages/next/src/server/route-modules/route-module.ts b/packages/next/src/server/route-modules/route-module.ts index b9684d0f13650..672cb5ba223a9 100644 --- a/packages/next/src/server/route-modules/route-module.ts +++ b/packages/next/src/server/route-modules/route-module.ts @@ -419,7 +419,8 @@ export abstract class RouteModule< public async getIncrementalCache( req: IncomingMessage | BaseNextRequest, nextConfig: NextConfigComplete, - prerenderManifest: DeepReadonly + prerenderManifest: DeepReadonly, + isMinimalMode: boolean ): Promise { if (process.env.NEXT_RUNTIME === 'edge') { return (globalThis as any).__incrementalCache @@ -449,7 +450,7 @@ export abstract class RouteModule< // incremental-cache is request specific // although can have shared caches in module scope // per-cache handler - return new IncrementalCache({ + const incrementalCache = new IncrementalCache({ fs: ( require('../lib/node-fs-methods') as typeof import('../lib/node-fs-methods') ).nodeFs, @@ -457,14 +458,19 @@ export abstract class RouteModule< requestHeaders: req.headers, allowedRevalidateHeaderKeys: nextConfig.experimental.allowedRevalidateHeaderKeys, - minimalMode: getRequestMeta(req, 'minimalMode'), + minimalMode: isMinimalMode, serverDistDir: `${projectDir}/${this.distDir}/server`, fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix, maxMemoryCacheSize: nextConfig.cacheMaxMemorySize, - flushToDisk: nextConfig.experimental.isrFlushToDisk, + flushToDisk: !isMinimalMode && nextConfig.experimental.isrFlushToDisk, getPrerenderManifest: () => prerenderManifest, CurCacheHandler: CacheHandler, }) + + // we need to expose this on globalThis as the app-render + // workStore grabs the incrementalCache from there + ;(globalThis as any).__incrementalCache = incrementalCache + return incrementalCache } } @@ -741,12 +747,29 @@ export abstract class RouteModule< params || {}, true ) - const paramsToInterpolate: ParsedUrlQuery = - paramsResult.hasValidParams && params - ? params - : queryResult.hasValidParams - ? query - : {} + + let paramsToInterpolate: ParsedUrlQuery + + if ( + // if both query and params are valid but one + // provided more information rely on that one + query && + params && + paramsResult.hasValidParams && + queryResult.hasValidParams && + Object.keys(paramsResult.params).length < + Object.keys(queryResult.params).length + ) { + paramsToInterpolate = queryResult.params + params = Object.assign(queryResult.params) + } else { + paramsToInterpolate = + paramsResult.hasValidParams && params + ? params + : queryResult.hasValidParams + ? query + : {} + } req.url = serverUtils.interpolateDynamicPath( req.url || '/', @@ -873,7 +896,10 @@ export abstract class RouteModule< public getResponseCache(req: IncomingMessage | BaseNextRequest) { if (!this.responseCache) { - const minimalMode = getRequestMeta(req, 'minimalMode') ?? false + const minimalMode = + (Boolean(process.env.MINIMAL_MODE) || + getRequestMeta(req, 'minimalMode')) ?? + false this.responseCache = new ResponseCache(minimalMode) } return this.responseCache @@ -891,6 +917,7 @@ export abstract class RouteModule< revalidateOnlyGenerated, responseGenerator, waitUntil, + isMinimalMode, }: { req: IncomingMessage | BaseNextRequest nextConfig: NextConfigComplete @@ -903,6 +930,7 @@ export abstract class RouteModule< revalidateOnlyGenerated?: boolean responseGenerator: ResponseGenerator waitUntil?: (prom: Promise) => void + isMinimalMode: boolean }) { const responseCache = this.getResponseCache(req) const cacheEntry = await responseCache.get(cacheKey, responseGenerator, { @@ -914,7 +942,8 @@ export abstract class RouteModule< incrementalCache: await this.getIncrementalCache( req, nextConfig, - prerenderManifest + prerenderManifest, + isMinimalMode ), waitUntil, }) diff --git a/packages/next/src/server/server-utils.ts b/packages/next/src/server/server-utils.ts index c7c2bbef39014..344b594974302 100644 --- a/packages/next/src/server/server-utils.ts +++ b/packages/next/src/server/server-utils.ts @@ -154,7 +154,9 @@ export function normalizeDynamicRouteParams( value.length === 1 && // fallback optional catch-all SSG pages have // [[...paramName]] for the root path on Vercel - (value[0] === 'index' || value[0] === `[[...${key}]]`))) + (value[0] === 'index' || value[0] === `[[...${key}]]`)) || + value === 'index' || + value === `[[...${key}]]`) ) { value = undefined delete query[key] diff --git a/packages/next/taskfile.js b/packages/next/taskfile.js index 4e1717cb690f9..38d457ce98933 100644 --- a/packages/next/taskfile.js +++ b/packages/next/taskfile.js @@ -86,6 +86,23 @@ export async function ncc_node_html_parser(task, opts) { .target('src/compiled/node-html-parser') } +externals['@vercel/routing-utils'] = 'next/dist/compiled/@vercel/routing-utils' +export async function ncc_vercel_routing_utils(task, opts) { + await task + .source( + relative( + __dirname, + require.resolve('@vercel/routing-utils/dist/superstatic') + ) + ) + .ncc({ + packageName: '@vercel/routing-utils', + externals, + target: 'es5', + }) + .target('src/compiled/@vercel/routing-utils') +} + externals['busboy'] = 'next/dist/compiled/busboy' export async function ncc_busboy(task, opts) { await task @@ -2309,6 +2326,7 @@ export async function ncc(task, opts) { 'ncc_mswjs_interceptors', 'ncc_rsc_poison_packages', 'ncc_modelcontextprotocol_sdk', + 'ncc_vercel_routing_utils', ], opts ) diff --git a/packages/next/types/$$compiled.internal.d.ts b/packages/next/types/$$compiled.internal.d.ts index e7f479b865b2d..0dc85aeef8bef 100644 --- a/packages/next/types/$$compiled.internal.d.ts +++ b/packages/next/types/$$compiled.internal.d.ts @@ -740,6 +740,10 @@ declare module 'next/dist/compiled/ws' { import m from 'ws' export = m } +declare module 'next/dist/compiled/@vercel/routing-utils' { + import m from '@vercel/routing-utils/dist/superstatic' + export = m +} declare module 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp' { export * from '@modelcontextprotocol/sdk/server/mcp' diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 52525f20eee3c..0178d3ad81f3f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -663,7 +663,7 @@ importers: version: 9.37.0(jiti@2.5.1) eslint-config-next: specifier: canary - version: link:../../packages/eslint-config-next + version: 16.0.0-canary.4(eslint-plugin-import-x@4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2) tailwindcss: specifier: 4.1.13 version: 4.1.13 @@ -915,7 +915,7 @@ importers: version: 0.3.9 eslint-import-resolver-typescript: specifier: ^3.5.2 - version: 3.10.1(eslint-plugin-import@2.32.0)(eslint@9.37.0(jiti@2.5.1)) + version: 3.10.1(eslint-plugin-import-x@4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-plugin-import@2.32.0)(eslint@9.37.0(jiti@2.5.1)) eslint-plugin-import: specifier: ^2.32.0 version: 2.32.0(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-typescript@3.10.1)(eslint@9.37.0(jiti@2.5.1)) @@ -1274,6 +1274,9 @@ importers: '@vercel/nft': specifier: 0.27.1 version: 0.27.1(encoding@0.1.13) + '@vercel/routing-utils': + specifier: 5.2.0 + version: 5.2.0 '@vercel/turbopack-ecmascript-runtime': specifier: '*' version: link:../../turbopack/crates/turbopack-ecmascript-runtime/js @@ -4337,6 +4340,9 @@ packages: '@next/env@15.5.3': resolution: {integrity: sha512-RSEDTRqyihYXygx/OJXwvVupfr9m04+0vH8vyy0HfZ7keRto6VX9BbEk0J2PUk0VGy6YhklJUSrgForov5F9pw==} + '@next/eslint-plugin-next@16.0.0-canary.4': + resolution: {integrity: sha512-SOjzRNjH3VOoT76BUijKZYtE8syYqeJrvfZHLyNwBJ/P062lsozZRRGP/saZvJ9PKFsRa+DHi2GbJaCJWtrd7Q==} + '@next/rspack-binding-android-arm-eabi@1.0.0': resolution: {integrity: sha512-goiM4M2ZlT82qtR8e7X3fwYGBBJ4DdaIkMGLa1rgSclyNXvb5mOhiSug+FgzrLsYl0O0UAO7GCMuyiF2hD5nmA==} cpu: [arm] @@ -5337,6 +5343,9 @@ packages: '@rtsao/scc@1.1.0': resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==} + '@rushstack/eslint-patch@1.14.0': + resolution: {integrity: sha512-WJFej426qe4RWOm9MMtP4V3CV4AucXolQty+GRgAWLgQXmpCuwzs7hEpxxhSc/znXUSxum9d/P/32MW0FlAAlA==} + '@shikijs/core@3.12.2': resolution: {integrity: sha512-L1Safnhra3tX/oJK5kYHaWmLEBJi1irASwewzY3taX5ibyXyMkkSDZlq01qigjryOBwrXSdFgTiZ3ryzSNeu7Q==} @@ -6519,6 +6528,9 @@ packages: resolution: {integrity: sha512-yOlbztkWaDtPOrCBsV66SpIZvIwRidAe3DiAYxDOjVj2H7HaJm1PDultH9PQO8J+PeT+mFQaNNSxS9yUTo7i9A==} engines: {node: '>=16'} + '@vercel/routing-utils@5.2.0': + resolution: {integrity: sha512-XBexLmd746XkSFa459tJpHd0NtxYEGswBe1o99BmpC4w4/8hoz6/BhlY+XWJh8jakPTP4hcKiE4w3TjOwuUxfw==} + '@vitest/expect@2.0.5': resolution: {integrity: sha512-yHZtwuP7JZivj65Gxoi8upUN2OzHTi3zVfjwdpu2WrvCZPLwsJ2Ey5ILIPccoW23dd/zQBlJ4/dhi7DWNyXCpA==} @@ -9244,6 +9256,15 @@ packages: engines: {node: '>=6.0'} hasBin: true + eslint-config-next@16.0.0-canary.4: + resolution: {integrity: sha512-lX16Q8gMFh8Hh6PN1BZWwbQfowYtghki/DUykDM6HRbAJv43HuDztIeDFeX3yE86SSjZmbwnBVkwujTRjuVb7w==} + peerDependencies: + eslint: ^7.23.0 || ^8.0.0 || ^9.0.0 + typescript: '>=3.3.1' + peerDependenciesMeta: + typescript: + optional: true + eslint-formatter-codeframe@7.32.1: resolution: {integrity: sha512-DK/3Q3+zVKq/7PdSYiCxPrsDF8H/TRMK5n8Hziwr4IMkMy+XiKSwbpj25AdajS63I/B61Snetq4uVvX9fOLyAg==} engines: {node: ^10.12.0 || >=12.0.0} @@ -9264,12 +9285,46 @@ packages: eslint-plugin-import-x: optional: true + eslint-import-resolver-typescript@3.6.3: + resolution: {integrity: sha512-ud9aw4szY9cCT1EWWdGv1L1XR6hh2PaRWif0j2QjQ0pgTY/69iw+W0Z4qZv5wHahOl8isEr+k/JnyAqNQkLkIA==} + engines: {node: ^14.18.0 || >=16.0.0} + peerDependencies: + eslint: '*' + eslint-plugin-import: '*' + eslint-plugin-import-x: '*' + peerDependenciesMeta: + eslint-plugin-import: + optional: true + eslint-plugin-import-x: + optional: true + eslint-mdx@3.1.5: resolution: {integrity: sha512-ynztX0k7CQ3iDL7fDEIeg3g0O/d6QPv7IBI9fdYLhXp5fAp0fi8X22xF/D3+Pk0f90R27uwqa1clHpay6t0l8Q==} engines: {node: '>=18.0.0'} peerDependencies: eslint: '>=8.0.0' + eslint-module-utils@2.12.0: + resolution: {integrity: sha512-wALZ0HFoytlyh/1+4wuZ9FJCD/leWHQzzrxJ8+rebyReSLk7LApMyd3WJaLVoN+D5+WIdJyDK1c6JnE65V4Zyg==} + engines: {node: '>=4'} + peerDependencies: + '@typescript-eslint/parser': '*' + eslint: '*' + eslint-import-resolver-node: '*' + eslint-import-resolver-typescript: '*' + eslint-import-resolver-webpack: '*' + peerDependenciesMeta: + '@typescript-eslint/parser': + optional: true + eslint: + optional: true + eslint-import-resolver-node: + optional: true + eslint-import-resolver-typescript: + optional: true + eslint-import-resolver-webpack: + optional: true + eslint-module-utils@2.12.1: resolution: {integrity: sha512-L8jSWTze7K2mTg0vos/RuLRS5soomksDPoJLXIslC7c8Wmut3bx7CPpJijDcBZtxQ5lrbUdM+s0OlNbz0DCDNw==} engines: {node: '>=4'} @@ -9297,6 +9352,12 @@ packages: peerDependencies: eslint: '>=7.0.0' + eslint-plugin-import-x@4.3.1: + resolution: {integrity: sha512-5TriWkXulDl486XnYYRgsL+VQoS/7mhN/2ci02iLCuL7gdhbiWxnsuL/NTcaKY9fpMgsMFjWZBtIGW7pb+RX0g==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 + eslint-plugin-import@2.31.0: resolution: {integrity: sha512-ixmkI62Rbc2/w8Vfxyh1jQRTdRTF52VxwRVHl/ykPAmqG+Nb7/kNn+byLP0LxPgI7zWA16Jt82SybJInmMia3A==} engines: {node: '>=4'} @@ -10950,6 +11011,9 @@ packages: resolution: {integrity: sha512-BSLE3HnV2syZ0FK0iMA/yUGplUeMmNz4AW5fnTunbCIqZi4vG3WjJT9FHMy5D69xmAYBHXQhJdALdpwVxV501A==} engines: {node: '>=6'} + is-bun-module@1.3.0: + resolution: {integrity: sha512-DgXeu5UWI0IsMQundYb5UAOzm6G2eVnarJ0byP6Tm55iZNKceD59LNPA2L4VvsScTtHcw0yEkVwSf7PC+QoLSA==} + is-bun-module@2.0.0: resolution: {integrity: sha512-gNCGbnnnnFAUGKeZ9PdbyeGYJqewpmc2aKHUEMO5nQPWU9lOmv7jcmQIv+qHD8fXW6W7qfuCwX4rY9LNRjXrkQ==} @@ -13756,6 +13820,9 @@ packages: path-to-regexp@3.3.0: resolution: {integrity: sha512-qyCH421YQPS2WFDxDjftfc1ZR5WKQzVzqsp4n9M2kQhVOo/ByahFoUNJfl58kOcEGfQ//7weFTDhm+ss8Ecxgw==} + path-to-regexp@6.1.0: + resolution: {integrity: sha512-h9DqehX3zZZDCEm+xbfU0ZmwCGFCAAraPJWMXJ4+v32NjZJilVg3k1TcKsRgIb8IQ/izZSaydDc1OhJCZvs2Dw==} + path-to-regexp@6.3.0: resolution: {integrity: sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==} @@ -14795,7 +14862,6 @@ packages: engines: {node: '>=0.6.0', teleport: '>=0.2.0'} deprecated: |- You or someone you depend on is using Q, the JavaScript Promise library that gave JavaScript developers strong feelings about promises. They can almost certainly migrate to the native JavaScript promise now. Thank you literally everyone for joining me in this bet against the odds. Be excellent to each other. - (For a CapTP with native promises, see @endo/eventual-send and @endo/captp) qs@6.11.0: @@ -16119,6 +16185,9 @@ packages: resolution: {integrity: sha512-97qShzy1AiyxvPNIkLWoGua7xoQzzPjQ0HAH4B0rWKo7SZ6USuPcrUiAFrws0UH8RrbWmgq3LMTObhPIHbbBeQ==} engines: {node: '>= 8'} + stable-hash@0.0.4: + resolution: {integrity: sha512-LjdcbuBeLcdETCrPn9i8AYAZ1eCtu4ECAWtP7UleOiZ9LzVxRzzUZEoZ8zB24nhkQnDWyET0I+3sWokSDS3E7g==} + stable-hash@0.0.5: resolution: {integrity: sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA==} @@ -21083,6 +21152,10 @@ snapshots: '@next/env@15.5.3': {} + '@next/eslint-plugin-next@16.0.0-canary.4': + dependencies: + fast-glob: 3.3.1 + '@next/rspack-binding-android-arm-eabi@1.0.0': optional: true @@ -22115,6 +22188,8 @@ snapshots: '@rtsao/scc@1.1.0': {} + '@rushstack/eslint-patch@1.14.0': {} + '@shikijs/core@3.12.2': dependencies: '@shikijs/types': 3.12.2 @@ -23511,6 +23586,13 @@ snapshots: satori: 0.15.2 yoga-wasm-web: 0.3.3 + '@vercel/routing-utils@5.2.0': + dependencies: + path-to-regexp: 6.1.0 + path-to-regexp-updated: path-to-regexp@6.3.0 + optionalDependencies: + ajv: 6.12.6 + '@vitest/expect@2.0.5': dependencies: '@vitest/spy': 2.0.5 @@ -26767,6 +26849,26 @@ snapshots: optionalDependencies: source-map: 0.6.1 + eslint-config-next@16.0.0-canary.4(eslint-plugin-import-x@4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2): + dependencies: + '@next/eslint-plugin-next': 16.0.0-canary.4 + '@rushstack/eslint-patch': 1.14.0 + '@typescript-eslint/eslint-plugin': 8.46.0(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2) + '@typescript-eslint/parser': 8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2) + eslint: 9.37.0(jiti@2.5.1) + eslint-import-resolver-node: 0.3.9 + eslint-import-resolver-typescript: 3.6.3(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import-x@4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-plugin-import@2.31.0)(eslint@9.37.0(jiti@2.5.1)) + eslint-plugin-import: 2.31.0(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-typescript@3.6.3)(eslint@9.37.0(jiti@2.5.1)) + eslint-plugin-jsx-a11y: 6.10.2(eslint@9.37.0(jiti@2.5.1)) + eslint-plugin-react: 7.37.0(eslint@9.37.0(jiti@2.5.1)) + eslint-plugin-react-hooks: 7.0.0(eslint@9.37.0(jiti@2.5.1)) + optionalDependencies: + typescript: 5.9.2 + transitivePeerDependencies: + - eslint-import-resolver-webpack + - eslint-plugin-import-x + - supports-color + eslint-formatter-codeframe@7.32.1: dependencies: '@babel/code-frame': 7.12.11 @@ -26780,7 +26882,7 @@ snapshots: transitivePeerDependencies: - supports-color - eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0)(eslint@9.37.0(jiti@2.5.1)): + eslint-import-resolver-typescript@3.10.1(eslint-plugin-import-x@4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-plugin-import@2.32.0)(eslint@9.37.0(jiti@2.5.1)): dependencies: '@nolyfill/is-core-module': 1.0.39 debug: 4.4.0 @@ -26792,7 +26894,28 @@ snapshots: unrs-resolver: 1.11.1 optionalDependencies: eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-typescript@3.10.1)(eslint@9.37.0(jiti@2.5.1)) + eslint-plugin-import-x: 4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2) + transitivePeerDependencies: + - supports-color + + eslint-import-resolver-typescript@3.6.3(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import-x@4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-plugin-import@2.31.0)(eslint@9.37.0(jiti@2.5.1)): + dependencies: + '@nolyfill/is-core-module': 1.0.39 + debug: 4.4.0 + enhanced-resolve: 5.17.1 + eslint: 9.37.0(jiti@2.5.1) + eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.6.3(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import-x@4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-plugin-import@2.31.0)(eslint@9.37.0(jiti@2.5.1)))(eslint@9.37.0(jiti@2.5.1)) + fast-glob: 3.3.3 + get-tsconfig: 4.8.1 + is-bun-module: 1.3.0 + is-glob: 4.0.3 + optionalDependencies: + eslint-plugin-import: 2.31.0(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-typescript@3.6.3)(eslint@9.37.0(jiti@2.5.1)) + eslint-plugin-import-x: 4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2) transitivePeerDependencies: + - '@typescript-eslint/parser' + - eslint-import-resolver-node + - eslint-import-resolver-webpack - supports-color eslint-mdx@3.1.5(eslint@9.37.0(jiti@2.5.1)): @@ -26816,14 +26939,36 @@ snapshots: - bluebird - supports-color - eslint-module-utils@2.12.1(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0)(eslint@9.37.0(jiti@2.5.1)))(eslint@9.37.0(jiti@2.5.1)): + eslint-module-utils@2.12.0(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.6.3(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import-x@4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-plugin-import@2.31.0)(eslint@9.37.0(jiti@2.5.1)))(eslint@9.37.0(jiti@2.5.1)): + dependencies: + debug: 3.2.7 + optionalDependencies: + '@typescript-eslint/parser': 8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2) + eslint: 9.37.0(jiti@2.5.1) + eslint-import-resolver-node: 0.3.9 + eslint-import-resolver-typescript: 3.6.3(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import-x@4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-plugin-import@2.31.0)(eslint@9.37.0(jiti@2.5.1)) + transitivePeerDependencies: + - supports-color + + eslint-module-utils@2.12.1(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import-x@4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-plugin-import@2.32.0)(eslint@9.37.0(jiti@2.5.1)))(eslint@9.37.0(jiti@2.5.1)): dependencies: debug: 3.2.7 optionalDependencies: '@typescript-eslint/parser': 8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2) eslint: 9.37.0(jiti@2.5.1) eslint-import-resolver-node: 0.3.9 - eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0)(eslint@9.37.0(jiti@2.5.1)) + eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import-x@4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-plugin-import@2.32.0)(eslint@9.37.0(jiti@2.5.1)) + transitivePeerDependencies: + - supports-color + + eslint-module-utils@2.12.1(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.6.3(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import-x@4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-plugin-import@2.31.0)(eslint@9.37.0(jiti@2.5.1)))(eslint@9.37.0(jiti@2.5.1)): + dependencies: + debug: 3.2.7 + optionalDependencies: + '@typescript-eslint/parser': 8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2) + eslint: 9.37.0(jiti@2.5.1) + eslint-import-resolver-node: 0.3.9 + eslint-import-resolver-typescript: 3.6.3(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import-x@4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-plugin-import@2.31.0)(eslint@9.37.0(jiti@2.5.1)) transitivePeerDependencies: - supports-color @@ -26833,25 +26978,72 @@ snapshots: eslint-utils: 3.0.0(eslint@9.37.0(jiti@2.5.1)) estraverse: 5.3.0 + eslint-plugin-import-x@4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2): + dependencies: + '@typescript-eslint/utils': 8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2) + debug: 4.4.0 + doctrine: 3.0.0 + eslint: 9.37.0(jiti@2.5.1) + eslint-import-resolver-node: 0.3.9 + get-tsconfig: 4.12.0 + is-glob: 4.0.3 + minimatch: 9.0.5 + semver: 7.6.3 + stable-hash: 0.0.4 + tslib: 2.8.1 + transitivePeerDependencies: + - supports-color + - typescript + optional: true + + eslint-plugin-import@2.31.0(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-typescript@3.6.3)(eslint@9.37.0(jiti@2.5.1)): + dependencies: + '@rtsao/scc': 1.1.0 + array-includes: 3.1.8 + array.prototype.findlastindex: 1.2.6 + array.prototype.flat: 1.3.2 + array.prototype.flatmap: 1.3.2 + debug: 3.2.7 + doctrine: 2.1.0 + eslint: 9.37.0(jiti@2.5.1) + eslint-import-resolver-node: 0.3.9 + eslint-module-utils: 2.12.0(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.6.3(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import-x@4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-plugin-import@2.31.0)(eslint@9.37.0(jiti@2.5.1)))(eslint@9.37.0(jiti@2.5.1)) + hasown: 2.0.2 + is-core-module: 2.15.1 + is-glob: 4.0.3 + minimatch: 3.1.2 + object.fromentries: 2.0.8 + object.groupby: 1.0.3 + object.values: 1.2.0 + semver: 6.3.1 + string.prototype.trimend: 1.0.9 + tsconfig-paths: 3.15.0 + optionalDependencies: + '@typescript-eslint/parser': 8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2) + transitivePeerDependencies: + - eslint-import-resolver-typescript + - eslint-import-resolver-webpack + - supports-color + eslint-plugin-import@2.31.0(eslint@9.37.0(jiti@2.5.1)): dependencies: '@rtsao/scc': 1.1.0 - array-includes: 3.1.9 + array-includes: 3.1.8 array.prototype.findlastindex: 1.2.6 - array.prototype.flat: 1.3.3 - array.prototype.flatmap: 1.3.3 + array.prototype.flat: 1.3.2 + array.prototype.flatmap: 1.3.2 debug: 3.2.7 doctrine: 2.1.0 eslint: 9.37.0(jiti@2.5.1) eslint-import-resolver-node: 0.3.9 - eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0)(eslint@9.37.0(jiti@2.5.1)))(eslint@9.37.0(jiti@2.5.1)) + eslint-module-utils: 2.12.0(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.6.3(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import-x@4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-plugin-import@2.31.0)(eslint@9.37.0(jiti@2.5.1)))(eslint@9.37.0(jiti@2.5.1)) hasown: 2.0.2 - is-core-module: 2.16.1 + is-core-module: 2.15.1 is-glob: 4.0.3 minimatch: 3.1.2 object.fromentries: 2.0.8 object.groupby: 1.0.3 - object.values: 1.2.1 + object.values: 1.2.0 semver: 6.3.1 string.prototype.trimend: 1.0.9 tsconfig-paths: 3.15.0 @@ -26871,7 +27063,7 @@ snapshots: doctrine: 2.1.0 eslint: 9.37.0(jiti@2.5.1) eslint-import-resolver-node: 0.3.9 - eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0)(eslint@9.37.0(jiti@2.5.1)))(eslint@9.37.0(jiti@2.5.1)) + eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.46.0(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import-x@4.3.1(eslint@9.37.0(jiti@2.5.1))(typescript@5.9.2))(eslint-plugin-import@2.32.0)(eslint@9.37.0(jiti@2.5.1)))(eslint@9.37.0(jiti@2.5.1)) hasown: 2.0.2 is-core-module: 2.16.1 is-glob: 4.0.3 @@ -29125,6 +29317,10 @@ snapshots: dependencies: builtin-modules: 3.3.0 + is-bun-module@1.3.0: + dependencies: + semver: 7.6.3 + is-bun-module@2.0.0: dependencies: semver: 7.7.2 @@ -32947,6 +33143,8 @@ snapshots: path-to-regexp@3.3.0: {} + path-to-regexp@6.1.0: {} + path-to-regexp@6.3.0: {} path-to-regexp@8.3.0: {} @@ -35770,6 +35968,9 @@ snapshots: dependencies: minipass: 3.1.3 + stable-hash@0.0.4: + optional: true + stable-hash@0.0.5: {} stable@0.1.8: {} diff --git a/test/integration/custom-routes/test/index.test.js b/test/integration/custom-routes/test/index.test.js index fa3261bafc317..8c7dad9a645af 100644 --- a/test/integration/custom-routes/test/index.test.js +++ b/test/integration/custom-routes/test/index.test.js @@ -2443,6 +2443,12 @@ const runTests = (isDev = false) => { "varyHeader": "rsc, next-router-state-tree, next-router-prefetch, next-router-segment-prefetch", }, "staticRoutes": [ + { + "namedRegex": "^/api/hello(?:/)?$", + "page": "/api/hello", + "regex": "^/api/hello(?:/)?$", + "routeKeys": {}, + }, { "namedRegex": "^/auto\\-export/another(?:/)?$", "page": "/auto-export/another", diff --git a/test/production/adapter-config/adapter-config.test.ts b/test/production/adapter-config/adapter-config.test.ts index c017d7123b873..e00c52c66a7af 100644 --- a/test/production/adapter-config/adapter-config.test.ts +++ b/test/production/adapter-config/adapter-config.test.ts @@ -94,6 +94,8 @@ describe('adapter-config', () => { if (output.filePath.endsWith('.html')) { expect(output.pathname.endsWith('.html')).toBe(false) + } else if (output.pathname.endsWith('.rsc')) { + expect(output.filePath.endsWith('rsc-fallback.json')).toBe(true) } else { expect(output.pathname).toStartWith('/docs/_next/static') } diff --git a/test/production/adapter-config/next.config.mjs b/test/production/adapter-config/next.config.mjs index d355c217122e7..6488f152c294f 100644 --- a/test/production/adapter-config/next.config.mjs +++ b/test/production/adapter-config/next.config.mjs @@ -3,8 +3,35 @@ const require = Module.createRequire(import.meta.url) /** @type {import('next').NextConfig} */ const nextConfig = { - cacheComponents: process.env.TEST_CACHE_COMPONENTS === '1', - experimental: { adapterPath: require.resolve('./my-adapter.mjs') }, + experimental: { + adapterPath: require.resolve('./my-adapter.mjs'), + cacheComponents: process.env.TEST_CACHE_COMPONENTS === '1', + }, + rewrites() { + return [ + { + source: '/rewrite-me', + destination: '/isr-pages', + }, + ] + }, + redirects() { + return [ + { + source: '/redirect-me', + destination: '/isr-pages', + permanent: false, + }, + ] + }, + headers() { + return [ + { + source: '/isr-pages', + headers: [{ key: 'x-custom-header', value: 'hello' }], + }, + ] + }, output: process.env.TEST_EXPORT ? 'export' : undefined, } From fd8056749b0258ffc3636a080636e2073966a523 Mon Sep 17 00:00:00 2001 From: JJ Kasper Date: Mon, 20 Oct 2025 15:56:57 -0700 Subject: [PATCH 2/2] update docs --- .../01-next-config-js/adapterPath.mdx | 97 +++++++++++++++++-- 1 file changed, 91 insertions(+), 6 deletions(-) diff --git a/docs/01-app/03-api-reference/05-config/01-next-config-js/adapterPath.mdx b/docs/01-app/03-api-reference/05-config/01-next-config-js/adapterPath.mdx index 36830508304ef..534ceb08f29e5 100644 --- a/docs/01-app/03-api-reference/05-config/01-next-config-js/adapterPath.mdx +++ b/docs/01-app/03-api-reference/05-config/01-next-config-js/adapterPath.mdx @@ -128,12 +128,17 @@ Called after the build process completes with detailed information about routes **Parameters:** - `routes`: Object containing route manifests for headers, redirects, rewrites, and dynamic routes + - `routes.headers`: Array of header route objects with `source`, `sourceRegex`, `headers`, `has`, `missing`, and optional `priority` fields + - `routes.redirects`: Array of redirect route objects with `source`, `sourceRegex`, `destination`, `statusCode`, `has`, `missing`, and optional `priority` fields + - `routes.rewrites`: Object with `beforeFiles`, `afterFiles`, and `fallback` arrays, each containing rewrite route objects with `source`, `sourceRegex`, `destination`, `has`, and `missing` fields + - `routes.dynamicRoutes`: Array of dynamic route objects with `source`, `sourceRegex`, `destination`, `has`, and `missing` fields - `outputs`: Detailed information about all build outputs organized by type - `projectDir`: Absolute path to the Next.js project directory - `repoRoot`: Absolute path to the detected repository root - `distDir`: Absolute path to the build output directory - `config`: The final Next.js configuration (with `modifyConfig` applied) - `nextVersion`: Version of Next.js being used +- `buildId`: Unique identifier for the current build ## Output Types @@ -149,11 +154,14 @@ React pages from the `pages/` directory: id: string // Route identifier filePath: string // Path to the built file pathname: string // URL pathname + sourcePage: string // Original source file path in pages/ directory runtime: 'nodejs' | 'edge' - assets: Record // Traced dependencies + assets: Record // Traced dependencies (key: relative path from repo root, value: absolute path) + wasmAssets?: Record // Bundled wasm files (key: name, value: absolute path) config: { maxDuration?: number preferredRegion?: string | string[] + env?: Record // Environment variables (edge runtime only) } } ``` @@ -168,11 +176,14 @@ API routes from `pages/api/`: id: string filePath: string pathname: string + sourcePage: string // Original relative source file path runtime: 'nodejs' | 'edge' assets: Record + wasmAssets?: Record config: { maxDuration?: number preferredRegion?: string | string[] + env?: Record } } ``` @@ -186,12 +197,15 @@ React pages from the `app/` directory with `page.{js,ts,jsx,tsx}`: type: 'APP_PAGE' id: string filePath: string - pathname: string + pathname: string // Includes .rsc suffix for RSC routes + sourcePage: string // Original relative source file path runtime: 'nodejs' | 'edge' assets: Record + wasmAssets?: Record config: { maxDuration?: number preferredRegion?: string | string[] + env?: Record } } ``` @@ -203,7 +217,18 @@ API and metadata routes from `app/` with `route.{js,ts,jsx,tsx}`: ```typescript { type: 'APP_ROUTE' - // ... same structure as APP_PAGE + id: string + filePath: string + pathname: string + sourcePage: string + runtime: 'nodejs' | 'edge' + assets: Record + wasmAssets?: Record + config: { + maxDuration?: number + preferredRegion?: string | string[] + env?: Record + } } ``` @@ -217,7 +242,11 @@ ISR-enabled routes and static prerenders: id: string pathname: string parentOutputId: string // ID of the source page/route - groupId: number // Revalidation group identifier + groupId: number // Revalidation group identifier (prerenders with same groupId revalidate together) + pprChain?: { + headers: Record // PPR chain headers (e.g., 'x-nextjs-resume': '1') + } + parentFallbackMode?: 'blocking' | false | null // Fallback mode from getStaticPaths fallback?: { filePath: string initialStatus?: number @@ -258,17 +287,72 @@ Middleware function (if present): type: 'MIDDLEWARE' id: string filePath: string - pathname: string + pathname: string // Always '/_middleware' + sourcePage: string // Always 'middleware' runtime: 'nodejs' | 'edge' assets: Record + wasmAssets?: Record config: { maxDuration?: number preferredRegion?: string | string[] - matchers?: ProxyMatcher[] + env?: Record + matchers?: Array<{ + source: string + sourceRegex: string + has: RouteHas[] | undefined + missing: RouteHas[] | undefined + }> } } ``` +## Routes Information + +The `routes` object in `onBuildComplete` provides complete routing information with processed patterns ready for deployment: + +### Headers + +Each header route includes: + +- `source`: Original route pattern (e.g., `/about`) +- `sourceRegex`: Compiled regex for matching requests +- `headers`: Key-value pairs of headers to apply +- `has`: Optional conditions that must be met +- `missing`: Optional conditions that must not be met +- `priority`: Optional flag for internal routes + +### Redirects + +Each redirect route includes: + +- `source`: Original route pattern +- `sourceRegex`: Compiled regex for matching +- `destination`: Target URL (can include captured groups) +- `statusCode`: HTTP status code (301, 302, 307, 308) +- `has`: Optional positive conditions +- `missing`: Optional negative conditions +- `priority`: Optional flag for internal routes + +### Rewrites + +Rewrites are categorized into three phases: + +- `beforeFiles`: Checked before filesystem (including pages and public files) +- `afterFiles`: Checked after pages/public files but before dynamic routes +- `fallback`: Checked after all other routes + +Each rewrite includes `source`, `sourceRegex`, `destination`, `has`, and `missing`. + +### Dynamic Routes + +Generated from dynamic route segments (e.g., `[slug]`, `[...path]`). Each includes: + +- `source`: Route pattern +- `sourceRegex`: Compiled regex with named capture groups +- `destination`: Internal destination with parameter substitution +- `has`: Optional positive conditions +- `missing`: Optional negative conditions + ## Use Cases Common use cases for adapters include: @@ -278,3 +362,4 @@ Common use cases for adapters include: - **Monitoring Integration**: Collect build metrics and route information - **Custom Bundling**: Package outputs in platform-specific formats - **Build Validation**: Ensure outputs meet specific requirements +- **Route Generation**: Use processed route information to generate platform-specific routing configs