Unverified Commit 52c94abd authored by Josh Story's avatar Josh Story Committed by GitHub

[lts-maintenance] Scope response cache keys to their source route (#219)

parent 785f4c23
...@@ -25,6 +25,16 @@ The cache handler can implement the following methods: `get`, `set`, `revalidate ...@@ -25,6 +25,16 @@ The cache handler can implement the following methods: `get`, `set`, `revalidate
| --------- | -------- | ---------------------------- | | --------- | -------- | ---------------------------- |
| `key` | `string` | The key to the cached value. | | `key` | `string` | The key to the cached value. |
Cache keys are opaque identifiers. Preserve the entire key when reading and writing entries; a key is not a request pathname.
Response keys include the response kind and a SHA-256 hash of the source route to keep different routes from sharing entries. Pages Router sources use the route definition's canonical `pathname`, so an index module has the same identity in both bundlers. App Router sources use the full `page` module name, including route groups and parallel slots. For example, a Pages Router response for `/blog/post` generated by `/blog/[slug]` uses `/route-cache/PAGES/<route-hash>/$/blog/post`, where `<route-hash>` is the 64-character hexadecimal SHA-256 digest of the UTF-8 source string `/blog/[slug]`. This bounds the added directory depth and avoids expanding Unicode source names on disk. The request pathname remains readable; the source route cannot be recovered from its hash. Handlers that previously interpreted keys as pathnames must account for this namespace. Fetch cache keys are unchanged.
Without a build adapter, prerendered responses remain at their historical `server/pages` and `server/app` paths. Their metadata identifies the exact scoped key, source owner, and fallback status that produced each immutable build seed. The built-in filesystem cache verifies that metadata before reading a historical seed, then promotes the complete response to `server/route-cache` while retaining the original artifact and its age. When an adapter is configured, build-time response artifacts are written directly to their scoped `server/route-cache` keys so colliding routes cannot overwrite one another before the adapter packages them. Static `output: 'export'` continues to emit normal public export files. Runtime reads and writes use only scoped keys. Custom cache handlers receive the opaque scoped key and are never queried with a historical pathname; an external response cache must preserve that key unchanged.
Runtime packaging must preserve the existing source-route metadata in the prerender manifest. Next.js also uses it to verify the allowed parameters and rendering mode of the selected route.
Integrations that read cached responses before invoking Next.js must also preserve source-route ownership when selecting entries. Removing the route namespace or falling back to pathname-only cache entries defeats that isolation.
Returns the cached value or `null` if not found. Returns the cached value or `null` if not found.
### `set()` ### `set()`
......
...@@ -266,6 +266,7 @@ ...@@ -266,6 +266,7 @@
"find-up": "4.1.0", "find-up": "4.1.0",
"fresh": "0.5.2", "fresh": "0.5.2",
"glob": "7.1.7", "glob": "7.1.7",
"hash.js": "1.1.7",
"gzip-size": "5.1.1", "gzip-size": "5.1.1",
"http-proxy": "1.18.1", "http-proxy": "1.18.1",
"http-proxy-agent": "5.0.0", "http-proxy-agent": "5.0.0",
......
import { getRouteCacheKey } from '../../server/lib/route-cache-key'
import { RouteKind } from '../../server/route-kind'
import path from 'path' import path from 'path'
import fs from 'fs/promises' import fs from 'fs/promises'
import { promisify } from 'util' import { promisify } from 'util'
...@@ -17,7 +19,10 @@ import type { ...@@ -17,7 +19,10 @@ import type {
} from '../webpack/plugins/middleware-plugin' } from '../webpack/plugins/middleware-plugin'
import { isMiddlewareFilename } from '../utils' import { isMiddlewareFilename } from '../utils'
import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import {
normalizeAppPath,
selectAppPageEntry,
} from '../../shared/lib/router/utils/app-paths'
import { AdapterOutputType } from '../../shared/lib/constants' import { AdapterOutputType } from '../../shared/lib/constants'
import { RenderingMode } from '../rendering-mode' import { RenderingMode } from '../rendering-mode'
import { isDynamicRoute } from '../../shared/lib/router/utils' import { isDynamicRoute } from '../../shared/lib/router/utils'
...@@ -262,7 +267,7 @@ export async function handleBuildComplete({ ...@@ -262,7 +267,7 @@ export async function handleBuildComplete({
const appDistDir = path.join(distDir, 'server', 'app') const appDistDir = path.join(distDir, 'server', 'app')
if (appPageKeys) { if (appPageKeys) {
for (const page of appPageKeys) { for (const page of [...appPageKeys].sort().reverse()) {
if (middlewareManifest.functions.hasOwnProperty(page)) { if (middlewareManifest.functions.hasOwnProperty(page)) {
continue continue
} }
...@@ -273,6 +278,15 @@ export async function handleBuildComplete({ ...@@ -273,6 +278,15 @@ export async function handleBuildComplete({
Log.warn(`Failed to copy traced files for ${pageFile}`, err) Log.warn(`Failed to copy traced files for ${pageFile}`, err)
return {} as Record<string, string> return {} as Record<string, string>
}) })
// Parallel entries share one runtime owner but retain every traced asset.
const existingOutput = appOutputMap[normalizedPage]
if (existingOutput) {
existingOutput.assets ??= {}
Object.assign(existingOutput.assets, assets)
existingOutput.assets[path.relative(tracingRoot, pageFile)] =
pageFile
continue
}
const functionConfig = const functionConfig =
functionsConfigManifest.functions[normalizedPage] || {} functionsConfigManifest.functions[normalizedPage] || {}
...@@ -322,6 +336,34 @@ export async function handleBuildComplete({ ...@@ -322,6 +336,34 @@ export async function handleBuildComplete({
contentTypeHeader, contentTypeHeader,
} = routesManifest.rsc } = routesManifest.rsc
const getPrerenderFilePath = (
route: string,
isAppPage: boolean,
extension: string
) => {
const normalizedRoute = route.startsWith('/') ? route : `/${route}`
const prerender = prerenderManifest.routes[normalizedRoute]
const dynamic = prerenderManifest.dynamicRoutes[normalizedRoute]
const source =
prerender?.srcRoute ?? dynamic?.fallbackSourceRoute ?? normalizedRoute
const dataRoute = prerender?.dataRoute ?? dynamic?.dataRoute
const sourceRoute = isAppPage
? selectAppPageEntry(source, appPageKeys ?? [])
: source
return path.join(
distDir,
'server',
`${getRouteCacheKey(normalizedRoute, {
kind: isAppPage
? dataRoute
? RouteKind.APP_PAGE
: RouteKind.APP_ROUTE
: RouteKind.PAGES,
sourceRoute,
})}${extension}`
)
}
const handleAppMeta = async ( const handleAppMeta = async (
route: string, route: string,
initialOutput: AdapterOutputs[0] initialOutput: AdapterOutputs[0]
...@@ -331,7 +373,7 @@ export async function handleBuildComplete({ ...@@ -331,7 +373,7 @@ export async function handleBuildComplete({
postponed?: string postponed?: string
} = JSON.parse( } = JSON.parse(
await fs await fs
.readFile(path.join(appDistDir, `${route}.meta`), 'utf8') .readFile(getPrerenderFilePath(route, true, '.meta'), 'utf8')
.catch(() => '{}') .catch(() => '{}')
) )
...@@ -340,9 +382,10 @@ export async function handleBuildComplete({ ...@@ -340,9 +382,10 @@ export async function handleBuildComplete({
} }
if (meta?.segmentPaths) { if (meta?.segmentPaths) {
const segmentsDir = path.join( const segmentsDir = getPrerenderFilePath(
appDistDir, route,
`${route}${prefetchSegmentDirSuffix}` true,
prefetchSegmentDirSuffix
) )
for (const segmentPath of meta.segmentPaths) { for (const segmentPath of meta.segmentPaths) {
...@@ -422,9 +465,10 @@ export async function handleBuildComplete({ ...@@ -422,9 +465,10 @@ export async function handleBuildComplete({
allowQuery = Object.values(routeKeys) allowQuery = Object.values(routeKeys)
} }
let filePath = path.join( let filePath = getPrerenderFilePath(
isAppPage ? appDistDir : pagesDistDir, route,
`${route}.${isAppPage && !dataRoute ? 'body' : 'html'}` isAppPage,
isAppPage && !dataRoute ? '.body' : '.html'
) )
// we use the static 404 for notFound: true if available // we use the static 404 for notFound: true if available
...@@ -466,7 +510,7 @@ export async function handleBuildComplete({ ...@@ -466,7 +510,7 @@ export async function handleBuildComplete({
outputs.push(initialOutput) outputs.push(initialOutput)
if (dataRoute) { if (dataRoute) {
let dataFilePath = path.join(pagesDistDir, `${route}.json`) let dataFilePath = getPrerenderFilePath(route, false, '.json')
if (isAppPage) { if (isAppPage) {
// When experimental PPR is enabled, we expect that the data // When experimental PPR is enabled, we expect that the data
...@@ -474,12 +518,13 @@ export async function handleBuildComplete({ ...@@ -474,12 +518,13 @@ export async function handleBuildComplete({
// be from the prefetch data route. If this isn't enabled // be from the prefetch data route. If this isn't enabled
// for ppr, the only way to get the data is from the data // for ppr, the only way to get the data is from the data
// route. // route.
dataFilePath = path.join( dataFilePath = getPrerenderFilePath(
appDistDir, route,
true,
prefetchDataRoute && prefetchDataRoute &&
renderingMode === RenderingMode.PARTIALLY_STATIC renderingMode === RenderingMode.PARTIALLY_STATIC
? prefetchDataRoute ? '.prefetch.rsc'
: dataRoute : '.rsc'
) )
} }
...@@ -537,9 +582,10 @@ export async function handleBuildComplete({ ...@@ -537,9 +582,10 @@ export async function handleBuildComplete({
fallback: fallback:
typeof fallback === 'string' typeof fallback === 'string'
? { ? {
filePath: path.join( filePath: getPrerenderFilePath(
isAppPage ? appDistDir : pagesDistDir, fallback.replace(/\.html$/, ''),
fallback isAppPage,
'.html'
), ),
initialStatus: fallbackStatus, initialStatus: fallbackStatus,
initialHeaders: fallbackHeaders, initialHeaders: fallbackHeaders,
......
...@@ -16,7 +16,10 @@ import picomatch from 'next/dist/compiled/picomatch' ...@@ -16,7 +16,10 @@ import picomatch from 'next/dist/compiled/picomatch'
import { defaultOverrides } from '../server/require-hook' import { defaultOverrides } from '../server/require-hook'
import { nodeFileTrace } from 'next/dist/compiled/@vercel/nft' import { nodeFileTrace } from 'next/dist/compiled/@vercel/nft'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import {
normalizeAppPath,
selectAppPageEntry,
} from '../shared/lib/router/utils/app-paths'
import isError from '../lib/is-error' import isError from '../lib/is-error'
import type { NodeFileTraceReasons } from '@vercel/nft' import type { NodeFileTraceReasons } from '@vercel/nft'
import type { RoutesUsingEdgeRuntime } from './utils' import type { RoutesUsingEdgeRuntime } from './utils'
...@@ -479,6 +482,73 @@ export async function collectBuildTraces({ ...@@ -479,6 +482,73 @@ export async function collectBuildTraces({
) )
}) })
) )
// A platform may package any one of the entries for a pathname into
// its route function. The runtime selects the canonical page, so a
// parallel slot trace must also include that page and its dependencies.
const appEntriesByRoute = new Map<string, string[]>()
for (const entryName of Object.keys(entryNameFilesMap || {})) {
if (!entryName.startsWith('app/') || !entryName.endsWith('/page')) {
continue
}
const route = normalizeAppPath(entryName.slice('app'.length))
if (staticPages.includes(route)) continue
const entries = appEntriesByRoute.get(route) || []
entries.push(entryName)
appEntriesByRoute.set(route, entries)
}
await Promise.all(
[...appEntriesByRoute].map(async ([route, entries]) => {
if (entries.length < 2) return
const selectedEntry = `app${selectAppPageEntry(
route,
entries.map((entry) => entry.slice('app'.length)),
normalizeAppPath
)}`
const selectedOutputPath = path.join(
distDir,
'server',
`${selectedEntry}.js`
)
const selectedTracePath = `${selectedOutputPath}.nft.json`
const selectedTrace = JSON.parse(
await fs.readFile(selectedTracePath, 'utf8')
) as { files: string[] }
const selectedTraceDir = path.dirname(selectedTracePath)
const selectedFiles = [
selectedOutputPath,
...selectedTrace.files.map((file) =>
path.resolve(selectedTraceDir, file)
),
]
await Promise.all(
entries
.filter((entry) => entry !== selectedEntry)
.map(async (entry) => {
const tracePath = path.join(
distDir,
'server',
`${entry}.js.nft.json`
)
const traceDir = path.dirname(tracePath)
const trace = JSON.parse(
await fs.readFile(tracePath, 'utf8')
) as { files: string[] }
const files = new Set(trace.files)
for (const file of selectedFiles) {
files.add(path.relative(traceDir, file).replace(/\\/g, '/'))
}
await fs.writeFile(
tracePath,
JSON.stringify({ ...trace, files: [...files].sort() })
)
})
)
})
)
} }
const moduleTypes = ['app-page', 'pages'] const moduleTypes = ['app-page', 'pages']
......
import {
getRouteCacheKey,
ROUTE_CACHE_DIRECTORY,
} from '../server/lib/route-cache-key'
import { RouteKind } from '../server/route-kind'
import type { AppBuildManifest } from './webpack/plugins/app-build-manifest-plugin' import type { AppBuildManifest } from './webpack/plugins/app-build-manifest-plugin'
import type { PagesManifest } from './webpack/plugins/pages-manifest-plugin' import type { PagesManifest } from './webpack/plugins/pages-manifest-plugin'
import type { ExportPathMap, NextConfigComplete } from '../server/config-shared' import type { ExportPathMap, NextConfigComplete } from '../server/config-shared'
...@@ -152,7 +157,10 @@ import { lockfilePatchPromise, teardownTraceSubscriber } from './swc' ...@@ -152,7 +157,10 @@ import { lockfilePatchPromise, teardownTraceSubscriber } from './swc'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex' import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
import { getFilesInDir } from '../lib/get-files-in-dir' import { getFilesInDir } from '../lib/get-files-in-dir'
import { eventSwcPlugins } from '../telemetry/events/swc-plugins' import { eventSwcPlugins } from '../telemetry/events/swc-plugins'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import {
normalizeAppPath,
selectAppPageEntry,
} from '../shared/lib/router/utils/app-paths'
import { import {
ACTION_HEADER, ACTION_HEADER,
NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_PREFETCH_HEADER,
...@@ -754,6 +762,24 @@ async function writeStandaloneDirectory( ...@@ -754,6 +762,24 @@ async function writeStandaloneDirectory(
), ),
{ overwrite: true } { overwrite: true }
) )
const responseCacheDir = path.join(
distDir,
SERVER_DIRECTORY,
ROUTE_CACHE_DIRECTORY
)
if (existsSync(responseCacheDir)) {
await recursiveCopy(
responseCacheDir,
path.join(
distDir,
STANDALONE_DIRECTORY,
path.relative(outputFileTracingRoot, distDir),
SERVER_DIRECTORY,
ROUTE_CACHE_DIRECTORY
),
{ overwrite: true }
)
}
if (appDir) { if (appDir) {
const originalServerApp = path.join(distDir, SERVER_DIRECTORY, 'app') const originalServerApp = path.join(distDir, SERVER_DIRECTORY, 'app')
if (existsSync(originalServerApp)) { if (existsSync(originalServerApp)) {
...@@ -2012,18 +2038,17 @@ export default async function build( ...@@ -2012,18 +2038,17 @@ export default async function build(
let originalAppPath: string | undefined let originalAppPath: string | undefined
if (pageType === 'app' && mappedAppPages) { if (pageType === 'app' && mappedAppPages) {
for (const [originalPath, normalizedPath] of Object.entries( originalAppPath = selectAppPageEntry(
appPathRoutes page,
)) { Object.keys(appPathRoutes).filter(
if (normalizedPath === page) { (entry) => mappedAppPages[entry]
pagePath = mappedAppPages[originalPath].replace( ),
/^private-next-app-dir/, (entry) => appPathRoutes[entry]
'' )
) pagePath = mappedAppPages[originalAppPath].replace(
originalAppPath = originalPath /^private-next-app-dir/,
break ''
} )
}
} }
const pageFilePath = isAppBuiltinNotFoundPage(pagePath) const pageFilePath = isAppBuiltinNotFoundPage(pagePath)
...@@ -3421,14 +3446,36 @@ export default async function build( ...@@ -3421,14 +3446,36 @@ export default async function build(
page: string, page: string,
file: string, file: string,
isSsg: boolean, isSsg: boolean,
ext: 'html' | 'json', ext: 'html' | 'json' | 'meta',
additionalSsgFile = false additionalSsgFile = false
) => { ) => {
if (
isSsg &&
config.experimental.adapterPath &&
config.output !== 'export'
)
return
if (isSsg && ext === 'html') {
await moveExportedPage(
originPage,
page,
file,
isSsg,
'meta',
additionalSsgFile
)
}
return staticGenerationSpan return staticGenerationSpan
.traceChild('move-exported-page') .traceChild('move-exported-page')
.traceAsyncFn(async () => { .traceAsyncFn(async () => {
file = `${file}.${ext}` file = `${file}.${ext}`
const orig = path.join(outdir, file) const orig = path.join(outdir, file)
if (
ext === 'meta' &&
(!i18n || additionalSsgFile) &&
!existsSync(orig)
)
return
const pagePath = getPagePath( const pagePath = getPagePath(
originPage, originPage,
distDir, distDir,
...@@ -3543,8 +3590,12 @@ export default async function build( ...@@ -3543,8 +3590,12 @@ export default async function build(
const orig = path.join( const orig = path.join(
distDir, distDir,
'server', 'server',
'app', config.experimental.adapterPath && config.output !== 'export'
'_not-found.html' ? `${getRouteCacheKey(UNDERSCORE_NOT_FOUND_ROUTE, {
kind: RouteKind.APP_PAGE,
sourceRoute: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
})}.html`
: 'app/_not-found.html'
) )
const updatedRelativeDest = path const updatedRelativeDest = path
.join('pages', '404.html') .join('pages', '404.html')
......
import { isRouteCacheOwner } from '../../server/lib/route-cache-key'
import type { LoaderTree } from '../../server/lib/app-dir-module' import type { LoaderTree } from '../../server/lib/app-dir-module'
import type { IncomingMessage, ServerResponse } from 'node:http' import type { IncomingMessage, ServerResponse } from 'node:http'
...@@ -175,7 +176,14 @@ export async function handler( ...@@ -175,7 +176,14 @@ export async function handler(
let { isOnDemandRevalidate } = prepareResult let { isOnDemandRevalidate } = prepareResult
const prerenderInfo = routeModule.match(pathname, prerenderManifest) const prerenderInfo = routeModule.match(pathname, prerenderManifest)
const isPrerendered = !!prerenderManifest.routes[resolvedPathname] const isPrerendered =
!!prerenderManifest.routes[resolvedPathname] &&
(routeModule.isDev ||
isRouteCacheOwner(
resolvedPathname,
routeModule.cacheOwner,
prerenderManifest.routes[resolvedPathname]
))
let isSSG = Boolean( let isSSG = Boolean(
prerenderInfo || prerenderInfo ||
......
...@@ -24,6 +24,7 @@ import { ...@@ -24,6 +24,7 @@ import {
import { getCacheControlHeader } from '../../server/lib/cache-control' import { getCacheControlHeader } from '../../server/lib/cache-control'
import { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from '../../lib/constants' import { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from '../../lib/constants'
import { NoFallbackError } from '../../shared/lib/no-fallback-error.external' import { NoFallbackError } from '../../shared/lib/no-fallback-error.external'
import { isRouteCacheOwner } from '../../server/lib/route-cache-key'
import { import {
CachedRouteKind, CachedRouteKind,
type ResponseCacheEntry, type ResponseCacheEntry,
...@@ -123,13 +124,21 @@ export async function handler( ...@@ -123,13 +124,21 @@ export async function handler(
const normalizedSrcPage = normalizeAppPath(srcPage) const normalizedSrcPage = normalizeAppPath(srcPage)
// Only this route's prerenders can establish ISR or admit generated params.
const isPrerendered =
Boolean(prerenderManifest.routes[resolvedPathname]) &&
(routeModule.isDev ||
isRouteCacheOwner(
resolvedPathname,
routeModule.cacheOwner,
prerenderManifest.routes[resolvedPathname]
))
let isIsr = Boolean( let isIsr = Boolean(
prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.dynamicRoutes[normalizedSrcPage] || isPrerendered
prerenderManifest.routes[resolvedPathname]
) )
if (isIsr && !isDraftMode) { if (isIsr && !isDraftMode) {
const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname])
const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage] const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage]
if (prerenderInfo) { if (prerenderInfo) {
......
(()=>{var t={330:(t,r,e)=>{"use strict";var n=e(263);var i=e(523);function BlockHash(){this.pending=null;this.pendingTotal=0;this.blockSize=this.constructor.blockSize;this.outSize=this.constructor.outSize;this.hmacStrength=this.constructor.hmacStrength;this.padLength=this.constructor.padLength/8;this.endian="big";this._delta8=this.blockSize/8;this._delta32=this.blockSize/32}r.BlockHash=BlockHash;BlockHash.prototype.update=function update(t,r){t=n.toArray(t,r);if(!this.pending)this.pending=t;else this.pending=this.pending.concat(t);this.pendingTotal+=t.length;if(this.pending.length>=this._delta8){t=this.pending;var e=t.length%this._delta8;this.pending=t.slice(t.length-e,t.length);if(this.pending.length===0)this.pending=null;t=n.join32(t,0,t.length-e,this.endian);for(var i=0;i<t.length;i+=this._delta32)this._update(t,i,i+this._delta32)}return this};BlockHash.prototype.digest=function digest(t){this.update(this._pad());i(this.pending===null);return this._digest(t)};BlockHash.prototype._pad=function pad(){var t=this.pendingTotal;var r=this._delta8;var e=r-(t+this.padLength)%r;var n=new Array(e+this.padLength);n[0]=128;for(var i=1;i<e;i++)n[i]=0;t<<=3;if(this.endian==="big"){for(var s=8;s<this.padLength;s++)n[i++]=0;n[i++]=0;n[i++]=0;n[i++]=0;n[i++]=0;n[i++]=t>>>24&255;n[i++]=t>>>16&255;n[i++]=t>>>8&255;n[i++]=t&255}else{n[i++]=t&255;n[i++]=t>>>8&255;n[i++]=t>>>16&255;n[i++]=t>>>24&255;n[i++]=0;n[i++]=0;n[i++]=0;n[i++]=0;for(s=8;s<this.padLength;s++)n[i++]=0}return n}},525:(t,r,e)=>{"use strict";var n=e(263);var i=e(330);var s=e(975);var o=e(523);var h=n.sum32;var u=n.sum32_4;var a=n.sum32_5;var l=s.ch32;var f=s.maj32;var _=s.s0_256;var c=s.s1_256;var v=s.g0_256;var p=s.g1_256;var g=i.BlockHash;var d=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function SHA256(){if(!(this instanceof SHA256))return new SHA256;g.call(this);this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];this.k=d;this.W=new Array(64)}n.inherits(SHA256,g);t.exports=SHA256;SHA256.blockSize=512;SHA256.outSize=256;SHA256.hmacStrength=192;SHA256.padLength=64;SHA256.prototype._update=function _update(t,r){var e=this.W;for(var n=0;n<16;n++)e[n]=t[r+n];for(;n<e.length;n++)e[n]=u(p(e[n-2]),e[n-7],v(e[n-15]),e[n-16]);var i=this.h[0];var s=this.h[1];var g=this.h[2];var d=this.h[3];var m=this.h[4];var A=this.h[5];var y=this.h[6];var S=this.h[7];o(this.k.length===e.length);for(n=0;n<e.length;n++){var H=a(S,c(m),l(m,A,y),this.k[n],e[n]);var b=h(_(i),f(i,s,g));S=y;y=A;A=m;m=h(d,H);d=g;g=s;s=i;i=h(H,b)}this.h[0]=h(this.h[0],i);this.h[1]=h(this.h[1],s);this.h[2]=h(this.h[2],g);this.h[3]=h(this.h[3],d);this.h[4]=h(this.h[4],m);this.h[5]=h(this.h[5],A);this.h[6]=h(this.h[6],y);this.h[7]=h(this.h[7],S)};SHA256.prototype._digest=function digest(t){if(t==="hex")return n.toHex32(this.h,"big");else return n.split32(this.h,"big")}},975:(t,r,e)=>{"use strict";var n=e(263);var i=n.rotr32;function ft_1(t,r,e,n){if(t===0)return ch32(r,e,n);if(t===1||t===3)return p32(r,e,n);if(t===2)return maj32(r,e,n)}r.ft_1=ft_1;function ch32(t,r,e){return t&r^~t&e}r.ch32=ch32;function maj32(t,r,e){return t&r^t&e^r&e}r.maj32=maj32;function p32(t,r,e){return t^r^e}r.p32=p32;function s0_256(t){return i(t,2)^i(t,13)^i(t,22)}r.s0_256=s0_256;function s1_256(t){return i(t,6)^i(t,11)^i(t,25)}r.s1_256=s1_256;function g0_256(t){return i(t,7)^i(t,18)^t>>>3}r.g0_256=g0_256;function g1_256(t){return i(t,17)^i(t,19)^t>>>10}r.g1_256=g1_256},263:(t,r,e)=>{"use strict";var n=e(523);var i=e(782);r.inherits=i;function isSurrogatePair(t,r){if((t.charCodeAt(r)&64512)!==55296){return false}if(r<0||r+1>=t.length){return false}return(t.charCodeAt(r+1)&64512)===56320}function toArray(t,r){if(Array.isArray(t))return t.slice();if(!t)return[];var e=[];if(typeof t==="string"){if(!r){var n=0;for(var i=0;i<t.length;i++){var s=t.charCodeAt(i);if(s<128){e[n++]=s}else if(s<2048){e[n++]=s>>6|192;e[n++]=s&63|128}else if(isSurrogatePair(t,i)){s=65536+((s&1023)<<10)+(t.charCodeAt(++i)&1023);e[n++]=s>>18|240;e[n++]=s>>12&63|128;e[n++]=s>>6&63|128;e[n++]=s&63|128}else{e[n++]=s>>12|224;e[n++]=s>>6&63|128;e[n++]=s&63|128}}}else if(r==="hex"){t=t.replace(/[^a-z0-9]+/gi,"");if(t.length%2!==0)t="0"+t;for(i=0;i<t.length;i+=2)e.push(parseInt(t[i]+t[i+1],16))}}else{for(i=0;i<t.length;i++)e[i]=t[i]|0}return e}r.toArray=toArray;function toHex(t){var r="";for(var e=0;e<t.length;e++)r+=zero2(t[e].toString(16));return r}r.toHex=toHex;function htonl(t){var r=t>>>24|t>>>8&65280|t<<8&16711680|(t&255)<<24;return r>>>0}r.htonl=htonl;function toHex32(t,r){var e="";for(var n=0;n<t.length;n++){var i=t[n];if(r==="little")i=htonl(i);e+=zero8(i.toString(16))}return e}r.toHex32=toHex32;function zero2(t){if(t.length===1)return"0"+t;else return t}r.zero2=zero2;function zero8(t){if(t.length===7)return"0"+t;else if(t.length===6)return"00"+t;else if(t.length===5)return"000"+t;else if(t.length===4)return"0000"+t;else if(t.length===3)return"00000"+t;else if(t.length===2)return"000000"+t;else if(t.length===1)return"0000000"+t;else return t}r.zero8=zero8;function join32(t,r,e,i){var s=e-r;n(s%4===0);var o=new Array(s/4);for(var h=0,u=r;h<o.length;h++,u+=4){var a;if(i==="big")a=t[u]<<24|t[u+1]<<16|t[u+2]<<8|t[u+3];else a=t[u+3]<<24|t[u+2]<<16|t[u+1]<<8|t[u];o[h]=a>>>0}return o}r.join32=join32;function split32(t,r){var e=new Array(t.length*4);for(var n=0,i=0;n<t.length;n++,i+=4){var s=t[n];if(r==="big"){e[i]=s>>>24;e[i+1]=s>>>16&255;e[i+2]=s>>>8&255;e[i+3]=s&255}else{e[i+3]=s>>>24;e[i+2]=s>>>16&255;e[i+1]=s>>>8&255;e[i]=s&255}}return e}r.split32=split32;function rotr32(t,r){return t>>>r|t<<32-r}r.rotr32=rotr32;function rotl32(t,r){return t<<r|t>>>32-r}r.rotl32=rotl32;function sum32(t,r){return t+r>>>0}r.sum32=sum32;function sum32_3(t,r,e){return t+r+e>>>0}r.sum32_3=sum32_3;function sum32_4(t,r,e,n){return t+r+e+n>>>0}r.sum32_4=sum32_4;function sum32_5(t,r,e,n,i){return t+r+e+n+i>>>0}r.sum32_5=sum32_5;function sum64(t,r,e,n){var i=t[r];var s=t[r+1];var o=n+s>>>0;var h=(o<n?1:0)+e+i;t[r]=h>>>0;t[r+1]=o}r.sum64=sum64;function sum64_hi(t,r,e,n){var i=r+n>>>0;var s=(i<r?1:0)+t+e;return s>>>0}r.sum64_hi=sum64_hi;function sum64_lo(t,r,e,n){var i=r+n;return i>>>0}r.sum64_lo=sum64_lo;function sum64_4_hi(t,r,e,n,i,s,o,h){var u=0;var a=r;a=a+n>>>0;u+=a<r?1:0;a=a+s>>>0;u+=a<s?1:0;a=a+h>>>0;u+=a<h?1:0;var l=t+e+i+o+u;return l>>>0}r.sum64_4_hi=sum64_4_hi;function sum64_4_lo(t,r,e,n,i,s,o,h){var u=r+n+s+h;return u>>>0}r.sum64_4_lo=sum64_4_lo;function sum64_5_hi(t,r,e,n,i,s,o,h,u,a){var l=0;var f=r;f=f+n>>>0;l+=f<r?1:0;f=f+s>>>0;l+=f<s?1:0;f=f+h>>>0;l+=f<h?1:0;f=f+a>>>0;l+=f<a?1:0;var _=t+e+i+o+u+l;return _>>>0}r.sum64_5_hi=sum64_5_hi;function sum64_5_lo(t,r,e,n,i,s,o,h,u,a){var l=r+n+s+h+a;return l>>>0}r.sum64_5_lo=sum64_5_lo;function rotr64_hi(t,r,e){var n=r<<32-e|t>>>e;return n>>>0}r.rotr64_hi=rotr64_hi;function rotr64_lo(t,r,e){var n=t<<32-e|r>>>e;return n>>>0}r.rotr64_lo=rotr64_lo;function shr64_hi(t,r,e){return t>>>e}r.shr64_hi=shr64_hi;function shr64_lo(t,r,e){var n=t<<32-e|r>>>e;return n>>>0}r.shr64_lo=shr64_lo},782:t=>{if(typeof Object.create==="function"){t.exports=function inherits(t,r){if(r){t.super_=r;t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:false,writable:true,configurable:true}})}}}else{t.exports=function inherits(t,r){if(r){t.super_=r;var TempCtor=function(){};TempCtor.prototype=r.prototype;t.prototype=new TempCtor;t.prototype.constructor=t}}}},523:t=>{t.exports=assert;function assert(t,r){if(!t)throw new Error(r||"Assertion failed")}assert.equal=function assertEqual(t,r,e){if(t!=r)throw new Error(e||"Assertion failed: "+t+" != "+r)}}};var r={};function __nccwpck_require__(e){var n=r[e];if(n!==undefined){return n.exports}var i=r[e]={exports:{}};var s=true;try{t[e](i,i.exports,__nccwpck_require__);s=false}finally{if(s)delete r[e]}return i.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var e=__nccwpck_require__(525);module.exports=e})();
\ No newline at end of file
This software is licensed under the MIT License.
Copyright Fedor Indutny, 2014.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
{"name":"hash.js","main":"256.js","author":"Fedor Indutny <fedor@indutny.com>","license":"MIT"}
...@@ -2,7 +2,7 @@ import type { OutgoingHttpHeaders } from 'node:http' ...@@ -2,7 +2,7 @@ import type { OutgoingHttpHeaders } from 'node:http'
import type { ExportRouteResult } from '../types' import type { ExportRouteResult } from '../types'
import type { RenderOpts } from '../../server/app-render/types' import type { RenderOpts } from '../../server/app-render/types'
import type { NextParsedUrlQuery } from '../../server/request-meta' import type { NextParsedUrlQuery } from '../../server/request-meta'
import type { RouteMetadata } from './types' import type { RouteCacheMetadata, RouteMetadata } from './types'
import type { import type {
MockedRequest, MockedRequest,
...@@ -47,7 +47,8 @@ export async function exportAppPage( ...@@ -47,7 +47,8 @@ export async function exportAppPage(
debugOutput: boolean, debugOutput: boolean,
isDynamicError: boolean, isDynamicError: boolean,
fileWriter: MultiFileWriter, fileWriter: MultiFileWriter,
sharedContext: AppSharedContext sharedContext: AppSharedContext,
routeCache?: RouteCacheMetadata
): Promise<ExportRouteResult> { ): Promise<ExportRouteResult> {
const afterRunner = new AfterRunner() const afterRunner = new AfterRunner()
...@@ -208,6 +209,7 @@ export async function exportAppPage( ...@@ -208,6 +209,7 @@ export async function exportAppPage(
headers, headers,
postponed, postponed,
segmentPaths, segmentPaths,
routeCache,
} }
fileWriter.append( fileWriter.append(
......
import type { ExportRouteResult } from '../types' import type { ExportRouteResult } from '../types'
import type { RouteCacheMetadata } from './types'
import type AppRouteRouteModule from '../../server/route-modules/app-route/module' import type AppRouteRouteModule from '../../server/route-modules/app-route/module'
import type { AppRouteRouteHandlerContext } from '../../server/route-modules/app-route/module' import type { AppRouteRouteHandlerContext } from '../../server/route-modules/app-route/module'
import type { IncrementalCache } from '../../server/lib/incremental-cache' import type { IncrementalCache } from '../../server/lib/incremental-cache'
...@@ -51,7 +52,8 @@ export async function exportAppRoute( ...@@ -51,7 +52,8 @@ export async function exportAppRoute(
experimental: Required< experimental: Required<
Pick<ExperimentalConfig, 'cacheComponents' | 'authInterrupts'> Pick<ExperimentalConfig, 'cacheComponents' | 'authInterrupts'>
>, >,
buildId: string buildId: string,
routeCache?: RouteCacheMetadata
): Promise<ExportRouteResult> { ): Promise<ExportRouteResult> {
// Ensure that the URL is absolute. // Ensure that the URL is absolute.
req.url = `http://localhost:3000${req.url}` req.url = `http://localhost:3000${req.url}`
...@@ -158,7 +160,7 @@ export async function exportAppRoute( ...@@ -158,7 +160,7 @@ export async function exportAppRoute(
fileWriter.append(htmlFilepath.replace(/\.html$/, NEXT_BODY_SUFFIX), body) fileWriter.append(htmlFilepath.replace(/\.html$/, NEXT_BODY_SUFFIX), body)
// Write the request metadata to a file. // Write the request metadata to a file.
const meta = { status: response.status, headers } const meta = { status: response.status, headers, routeCache }
fileWriter.append( fileWriter.append(
htmlFilepath.replace(/\.html$/, NEXT_META_SUFFIX), htmlFilepath.replace(/\.html$/, NEXT_META_SUFFIX),
JSON.stringify(meta) JSON.stringify(meta)
......
import type { ExportRouteResult } from '../types' import type { ExportRouteResult } from '../types'
import type { RouteCacheMetadata } from './types'
import type { import type {
PagesRenderContext, PagesRenderContext,
PagesSharedContext, PagesSharedContext,
...@@ -54,7 +55,8 @@ export async function exportPagesPage( ...@@ -54,7 +55,8 @@ export async function exportPagesPage(
hasOrigQueryValues: boolean, hasOrigQueryValues: boolean,
renderOpts: RenderOpts, renderOpts: RenderOpts,
components: LoadComponentsReturnType, components: LoadComponentsReturnType,
fileWriter: MultiFileWriter fileWriter: MultiFileWriter,
routeCache?: RouteCacheMetadata
): Promise<ExportRouteResult | undefined> { ): Promise<ExportRouteResult | undefined> {
const ampState = { const ampState = {
ampFirst: components.pageConfig?.amp === true, ampFirst: components.pageConfig?.amp === true,
...@@ -255,6 +257,12 @@ export async function exportPagesPage( ...@@ -255,6 +257,12 @@ export async function exportPagesPage(
if (!ssgNotFound) { if (!ssgNotFound) {
// don't attempt writing to disk if getStaticProps returned not found // don't attempt writing to disk if getStaticProps returned not found
fileWriter.append(htmlFilepath, html) fileWriter.append(htmlFilepath, html)
if (routeCache) {
fileWriter.append(
htmlFilepath.replace(/\.html$/, '.meta'),
JSON.stringify({ routeCache })
)
}
} }
return { return {
......
import type { OutgoingHttpHeaders } from 'node:http' import type { OutgoingHttpHeaders } from 'node:http'
import type { ResponseCacheOwner } from '../../server/lib/route-cache-key'
export type RouteCacheMetadata = {
key: string
owner: ResponseCacheOwner
isFallback: boolean
}
export type RouteMetadata = { export type RouteMetadata = {
status: number | undefined status: number | undefined
headers: OutgoingHttpHeaders | undefined headers: OutgoingHttpHeaders | undefined
postponed: string | undefined postponed: string | undefined
segmentPaths: Array<string> | undefined segmentPaths: Array<string> | undefined
/** Identifies the response-cache entry represented by this build artifact. */
routeCache?: RouteCacheMetadata
/** Original payload mtime retained when a build seed is promoted. */
routeCacheLastModified?: number
} }
...@@ -62,6 +62,8 @@ export interface ExportPageInput { ...@@ -62,6 +62,8 @@ export interface ExportPageInput {
httpAgentOptions: NextConfigComplete['httpAgentOptions'] httpAgentOptions: NextConfigComplete['httpAgentOptions']
debugOutput?: boolean debugOutput?: boolean
nextConfigOutput?: NextConfigComplete['output'] nextConfigOutput?: NextConfigComplete['output']
/** Write build-time response artifacts to their route-scoped cache keys. */
useScopedBuildArtifacts: boolean
enableExperimentalReact?: boolean enableExperimentalReact?: boolean
sriEnabled: boolean sriEnabled: boolean
renderResumeDataCache: RenderResumeDataCache | undefined renderResumeDataCache: RenderResumeDataCache | undefined
......
import { getRouteCacheKey } from '../server/lib/route-cache-key'
import type { RouteCacheMetadata } from './routes/types'
import type { import type {
ExportPagesInput, ExportPagesInput,
ExportPageInput, ExportPageInput,
...@@ -88,6 +90,7 @@ async function exportPageImpl( ...@@ -88,6 +90,7 @@ async function exportPageImpl(
outDir: commonOutDir, outDir: commonOutDir,
buildId, buildId,
renderResumeDataCache, renderResumeDataCache,
useScopedBuildArtifacts,
} = input } = input
if (enableExperimentalReact) { if (enableExperimentalReact) {
...@@ -229,11 +232,6 @@ async function exportPageImpl( ...@@ -229,11 +232,6 @@ async function exportPageImpl(
htmlFilename = 'index.html' htmlFilename = 'index.html'
} }
const baseDir = join(outDir, dirname(htmlFilename))
let htmlFilepath = join(outDir, htmlFilename)
await fs.mkdir(baseDir, { recursive: true })
const components = await loadComponents({ const components = await loadComponents({
distDir, distDir,
page, page,
...@@ -242,6 +240,30 @@ async function exportPageImpl( ...@@ -242,6 +240,30 @@ async function exportPageImpl(
sriEnabled, sriEnabled,
}) })
const routeCache: RouteCacheMetadata | undefined =
buildExport &&
commonRenderOpts.nextConfigOutput !== 'export' &&
(isAppDir || components.getStaticProps)
? {
key: getRouteCacheKey(path, components.routeModule.cacheOwner),
owner: components.routeModule.cacheOwner,
isFallback: isAppDir
? fallbackRouteParams != null && fallbackRouteParams.size > 0
: exportPath._pagesFallback ?? false,
}
: undefined
const htmlFilepath =
useScopedBuildArtifacts && routeCache
? join(distDir, 'server', `${routeCache.key}.html`)
: join(outDir, htmlFilename)
const routePagesDataDir =
useScopedBuildArtifacts && routeCache
? join(distDir, 'server')
: pagesDataDir
if (useScopedBuildArtifacts && routeCache)
htmlFilename = `${routeCache.key}.html`
await fs.mkdir(dirname(htmlFilepath), { recursive: true })
// Handle App Routes. // Handle App Routes.
if (isAppDir && isAppRouteRoute(page)) { if (isAppDir && isAppRouteRoute(page)) {
return exportAppRoute( return exportAppRoute(
...@@ -255,7 +277,8 @@ async function exportPageImpl( ...@@ -255,7 +277,8 @@ async function exportPageImpl(
htmlFilepath, htmlFilepath,
fileWriter, fileWriter,
commonRenderOpts.experimental, commonRenderOpts.experimental,
buildId buildId,
routeCache
) )
} }
...@@ -302,7 +325,8 @@ async function exportPageImpl( ...@@ -302,7 +325,8 @@ async function exportPageImpl(
debugOutput, debugOutput,
isDynamicError, isDynamicError,
fileWriter, fileWriter,
sharedContext sharedContext,
routeCache
) )
} }
...@@ -331,7 +355,7 @@ async function exportPageImpl( ...@@ -331,7 +355,7 @@ async function exportPageImpl(
subFolders, subFolders,
outDir, outDir,
ampValidatorPath, ampValidatorPath,
pagesDataDir, routePagesDataDir,
buildExport, buildExport,
isDynamic, isDynamic,
sharedContext, sharedContext,
...@@ -339,7 +363,8 @@ async function exportPageImpl( ...@@ -339,7 +363,8 @@ async function exportPageImpl(
hasOrigQueryValues, hasOrigQueryValues,
renderOpts, renderOpts,
components, components,
fileWriter fileWriter,
routeCache
) )
} }
...@@ -432,6 +457,10 @@ export async function exportPages( ...@@ -432,6 +457,10 @@ export async function exportPages(
sriEnabled: Boolean(nextConfig.experimental.sri?.algorithm), sriEnabled: Boolean(nextConfig.experimental.sri?.algorithm),
buildId: input.buildId, buildId: input.buildId,
renderResumeDataCache, renderResumeDataCache,
useScopedBuildArtifacts:
Boolean(nextConfig.experimental.adapterPath) &&
nextConfig.output !== 'export' &&
options.buildExport,
}), }),
hasDebuggerAttached hasDebuggerAttached
? // With a debugger attached, exporting can take infinitely if we paused script execution. ? // With a debugger attached, exporting can take infinitely if we paused script execution.
......
...@@ -14,10 +14,7 @@ import type { ...@@ -14,10 +14,7 @@ import type {
RenderOptsPartial as AppRenderOptsPartial, RenderOptsPartial as AppRenderOptsPartial,
ServerOnInstrumentationRequestError, ServerOnInstrumentationRequestError,
} from './app-render/types' } from './app-render/types'
import type { import type { ServerComponentsHmrCache } from './response-cache'
ServerComponentsHmrCache,
ResponseCacheBase,
} from './response-cache'
import type { UrlWithParsedQuery } from 'url' import type { UrlWithParsedQuery } from 'url'
import { import {
NormalizeError, NormalizeError,
...@@ -74,7 +71,10 @@ import { ...@@ -74,7 +71,10 @@ import {
setRequestMeta, setRequestMeta,
} from './request-meta' } from './request-meta'
import { removePathPrefix } from '../shared/lib/router/utils/remove-path-prefix' import { removePathPrefix } from '../shared/lib/router/utils/remove-path-prefix'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import {
normalizeAppPath,
selectAppPageEntry,
} from '../shared/lib/router/utils/app-paths'
import { getHostname } from '../shared/lib/get-hostname' import { getHostname } from '../shared/lib/get-hostname'
import { parseUrl as parseUrlUtil } from '../shared/lib/router/utils/parse-url' import { parseUrl as parseUrlUtil } from '../shared/lib/router/utils/parse-url'
import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info' import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'
...@@ -327,7 +327,6 @@ export default abstract class Server< ...@@ -327,7 +327,6 @@ export default abstract class Server<
protected interceptionRoutePatterns: RegExp[] protected interceptionRoutePatterns: RegExp[]
protected nextFontManifest?: DeepReadonly<NextFontManifest> protected nextFontManifest?: DeepReadonly<NextFontManifest>
protected instrumentation: InstrumentationModule | undefined protected instrumentation: InstrumentationModule | undefined
private readonly responseCache: ResponseCacheBase
protected abstract getPublicDir(): string protected abstract getPublicDir(): string
protected abstract getHasStaticDir(): boolean protected abstract getHasStaticDir(): boolean
...@@ -394,10 +393,6 @@ export default abstract class Server< ...@@ -394,10 +393,6 @@ export default abstract class Server<
requestHeaders: Record<string, undefined | string | string[]> requestHeaders: Record<string, undefined | string | string[]>
}): Promise<import('./lib/incremental-cache').IncrementalCache> }): Promise<import('./lib/incremental-cache').IncrementalCache>
protected abstract getResponseCache(options: {
dev: boolean
}): ResponseCacheBase
protected getServerComponentsHmrCache(): protected getServerComponentsHmrCache():
| ServerComponentsHmrCache | ServerComponentsHmrCache
| undefined { | undefined {
...@@ -605,7 +600,6 @@ export default abstract class Server< ...@@ -605,7 +600,6 @@ export default abstract class Server<
void this.matchers.reload() void this.matchers.reload()
this.setAssetPrefix(assetPrefix) this.setAssetPrefix(assetPrefix)
this.responseCache = this.getResponseCache({ dev })
} }
private handleRSCRequest: RouteHandler<ServerRequest, ServerResponse> = ( private handleRSCRequest: RouteHandler<ServerRequest, ServerResponse> = (
...@@ -2474,8 +2468,8 @@ export default abstract class Server< ...@@ -2474,8 +2468,8 @@ export default abstract class Server<
let page = pathname let page = pathname
if (isAppPath) { if (isAppPath) {
// the last item in the array is the root page, if there are parallel routes // Use the same direct entry as the build, independent of manifest order.
page = appPaths[appPaths.length - 1] page = selectAppPageEntry(pathname, appPaths)
} }
const result = await this.findPageComponents({ const result = await this.findPageComponents({
......
...@@ -16,16 +16,20 @@ export function getMemoryCache(maxMemoryCacheSize: number) { ...@@ -16,16 +16,20 @@ export function getMemoryCache(maxMemoryCacheSize: number) {
} else if (value.kind === CachedRouteKind.FETCH) { } else if (value.kind === CachedRouteKind.FETCH) {
return JSON.stringify(value.data || '').length return JSON.stringify(value.data || '').length
} else if (value.kind === CachedRouteKind.APP_ROUTE) { } else if (value.kind === CachedRouteKind.APP_ROUTE) {
return value.body.length return Math.max(1, value.body.length)
} }
// rough estimate of size of cache value // rough estimate of size of cache value
return ( return Math.max(
value.html.length + 1,
(JSON.stringify( (value.kind === CachedRouteKind.APP_PAGE
value.kind === CachedRouteKind.APP_PAGE ? value.postponed?.length || 0
? value.rscData : 0) +
: value.pageData value.html.length +
)?.length || 0) (JSON.stringify(
value.kind === CachedRouteKind.APP_PAGE
? value.rscData
: value.pageData
)?.length || 0)
) )
}) })
} }
......
import type { import type {
DynamicPrerenderManifestRoute, DynamicPrerenderManifestRoute,
PrerenderManifestRoute, PrerenderManifestRoute,
PrerenderManifest,
} from '../../../build' } from '../../../build'
import { RenderingMode } from '../../../build/rendering-mode' import { RenderingMode } from '../../../build/rendering-mode'
import { SharedCacheControls } from './shared-cache-controls.external' import { SharedCacheControls } from './shared-cache-controls.external'
import { getRouteCacheKey } from '../route-cache-key'
import { RouteKind } from '../../route-kind'
const owner = { kind: RouteKind.PAGES, sourceRoute: '/[id]' }
const other = { kind: RouteKind.PAGES, sourceRoute: '/[...slug]' }
const appRoute = (sourceRoute: string) => ({
kind: RouteKind.APP_ROUTE,
sourceRoute,
})
describe('SharedCacheControls', () => { describe('SharedCacheControls', () => {
let sharedCacheControls: SharedCacheControls let sharedCacheControls: SharedCacheControls
let prerenderManifest let prerenderManifest: Pick<PrerenderManifest, 'routes' | 'dynamicRoutes'>
beforeEach(() => { beforeEach(() => {
prerenderManifest = { prerenderManifest = {
...@@ -58,37 +68,141 @@ describe('SharedCacheControls', () => { ...@@ -58,37 +68,141 @@ describe('SharedCacheControls', () => {
sharedCacheControls.clear() sharedCacheControls.clear()
}) })
it('rejects cache-control reads without a source route', () => {
expect(() => {
// @ts-expect-error cache-control lookups require a source route
sharedCacheControls.get('/route2')
}).toThrow('Response cache requires a source route')
})
it('should get cache control from in-memory cache', () => { it('should get cache control from in-memory cache', () => {
sharedCacheControls.set('/route1', { revalidate: 15, expire: undefined }) sharedCacheControls.set(getRouteCacheKey('/route1', appRoute('/route1')), {
const cacheControl = sharedCacheControls.get('/route1') revalidate: 15,
expire: undefined,
})
const cacheControl = sharedCacheControls.get('/route1', appRoute('/route1'))
expect(cacheControl).toEqual({ revalidate: 15 }) expect(cacheControl).toEqual({ revalidate: 15 })
}) })
it('should get cache control from prerender manifest if not in cache', () => { it('should get cache control from prerender manifest if not in cache', () => {
const cacheControl = sharedCacheControls.get('/route2') const cacheControl = sharedCacheControls.get('/route2', appRoute('/route2'))
expect(cacheControl).toEqual({ revalidate: 20, expire: 40 }) expect(cacheControl).toEqual({ revalidate: 20, expire: 40 })
}) })
it('should return undefined if cache control not found', () => { it('should return undefined if cache control not found', () => {
const cacheControl = sharedCacheControls.get('/route3') const cacheControl = sharedCacheControls.get('/route3', appRoute('/route3'))
expect(cacheControl).toBeUndefined() expect(cacheControl).toBeUndefined()
}) })
it('should set cache control in cache', () => { it('should set cache control in cache', () => {
sharedCacheControls.set('/route3', { revalidate: 30, expire: undefined }) sharedCacheControls.set(getRouteCacheKey('/route3', appRoute('/route3')), {
const cacheControl = sharedCacheControls.get('/route3') revalidate: 30,
expire: undefined,
})
const cacheControl = sharedCacheControls.get('/route3', appRoute('/route3'))
expect(cacheControl).toEqual({ revalidate: 30 }) expect(cacheControl).toEqual({ revalidate: 30 })
}) })
it('should clear the in-memory cache', () => { it('should clear the in-memory cache', () => {
sharedCacheControls.set('/route3', { revalidate: 30, expire: undefined }) sharedCacheControls.set(getRouteCacheKey('/route3', appRoute('/route3')), {
revalidate: 30,
expire: undefined,
})
sharedCacheControls.clear() sharedCacheControls.clear()
const cacheControl = sharedCacheControls.get('/route3') const cacheControl = sharedCacheControls.get('/route3', appRoute('/route3'))
expect(cacheControl).toBeUndefined() expect(cacheControl).toBeUndefined()
}) })
it('should get cache control from prerender manifest for dynamic route with fallback', () => { it('should get cache control from prerender manifest for dynamic route with fallback', () => {
const cacheControl = sharedCacheControls.get('/route4') const cacheControl = sharedCacheControls.get('/route4', appRoute('/route4'))
expect(cacheControl).toEqual({ revalidate: 30, expire: 50 }) expect(cacheControl).toEqual({ revalidate: 30, expire: 50 })
}) })
it('uses build-time metadata only for its recorded owner', () => {
prerenderManifest.routes['/route2'].srcRoute = owner.sourceRoute
prerenderManifest.routes['/route2'].dataRoute =
'/_next/data/build/route2.json'
expect(sharedCacheControls.get('/route2', owner)).toEqual({
revalidate: 20,
expire: 40,
})
expect(sharedCacheControls.get('/route2', other)).toBeUndefined()
})
it("does not borrow a static route's metadata for a dynamic response", () => {
prerenderManifest.routes['/route2'].dataRoute =
'/_next/data/build/route2.json'
expect(sharedCacheControls.get('/route2', owner)).toBeUndefined()
})
it('keeps runtime lifetime overrides separate from other owners and seeds', () => {
prerenderManifest.routes['/route2'].srcRoute = owner.sourceRoute
prerenderManifest.routes['/route2'].dataRoute =
'/_next/data/build/route2.json'
sharedCacheControls.set(getRouteCacheKey('/route2', other), {
revalidate: 1,
expire: 2,
})
expect(sharedCacheControls.get('/route2', owner)).toEqual({
revalidate: 20,
expire: 40,
})
expect(sharedCacheControls.get('/route2', other)).toEqual({
revalidate: 1,
expire: 2,
})
})
it('uses locale-prefixed static metadata only for its source page', () => {
prerenderManifest.routes['/fr/route2'] = {
...prerenderManifest.routes['/route2'],
dataRoute: '/_next/data/build/fr/route2.json',
}
sharedCacheControls = new SharedCacheControls(prerenderManifest, [
'en',
'fr',
])
expect(
sharedCacheControls.get('/fr/route2', {
kind: RouteKind.PAGES,
sourceRoute: '/route2',
})
).toEqual({ revalidate: 20, expire: 40 })
expect(sharedCacheControls.get('/fr/route2', other)).toBeUndefined()
})
it('uses the source pattern for locale-prefixed fallback metadata', () => {
prerenderManifest.dynamicRoutes['/route4'].dataRoute =
'/_next/data/build/route4.json'
sharedCacheControls = new SharedCacheControls(prerenderManifest, [
'en',
'fr',
])
expect(
sharedCacheControls.get('/fr/route4', {
kind: RouteKind.PAGES,
sourceRoute: '/route4',
})
).toEqual({ revalidate: 30, expire: 50 })
expect(sharedCacheControls.get('/fr/route4', other)).toBeUndefined()
})
it('keeps a partial fallback shell lifetime with its original source', () => {
prerenderManifest.dynamicRoutes['/catalog/a/[item]'] = {
...prerenderManifest.dynamicRoutes['/route4'],
dataRoute: '/catalog/a/[item].rsc',
fallbackSourceRoute: '/catalog/[category]/[item]',
}
expect(
sharedCacheControls.get('/catalog/a/[item]', {
kind: RouteKind.APP_PAGE,
sourceRoute: '/(group)/catalog/[category]/[item]/page',
})
).toEqual({ revalidate: 30, expire: 50 })
expect(
sharedCacheControls.get('/catalog/a/[item]', {
kind: RouteKind.APP_PAGE,
sourceRoute: '/catalog/a/[item]/page',
})
).toBeUndefined()
})
}) })
import type { PrerenderManifest } from '../../../build' import type { PrerenderManifest } from '../../../build'
import type { DeepReadonly } from '../../../shared/lib/deep-readonly' import type { DeepReadonly } from '../../../shared/lib/deep-readonly'
import type { CacheControl } from '../cache-control' import type { CacheControl } from '../cache-control'
import {
getRouteCacheKey,
isRouteCacheOwner,
type ResponseCacheOwner,
} from '../route-cache-key'
import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path'
import { RouteKind } from '../../route-kind'
/** /**
* A shared cache of cache controls for routes. This cache is used so we don't * A shared cache of cache controls for routes. This cache is used so we don't
...@@ -21,7 +28,8 @@ export class SharedCacheControls { ...@@ -21,7 +28,8 @@ export class SharedCacheControls {
*/ */
private readonly prerenderManifest: DeepReadonly< private readonly prerenderManifest: DeepReadonly<
Pick<PrerenderManifest, 'routes' | 'dynamicRoutes'> Pick<PrerenderManifest, 'routes' | 'dynamicRoutes'>
> >,
private readonly locales?: readonly string[]
) {} ) {}
/** /**
...@@ -30,19 +38,28 @@ export class SharedCacheControls { ...@@ -30,19 +38,28 @@ export class SharedCacheControls {
* in-memory cache, it will be sourced from the prerender manifest. * in-memory cache, it will be sourced from the prerender manifest.
* *
* @param route the route to get the cache control for * @param route the route to get the cache control for
* @param owner the source route that owns the response
* @returns the cache control for the route, or undefined if the values * @returns the cache control for the route, or undefined if the values
* are not present in the in-memory cache or the prerender manifest * are not present in the in-memory cache or the prerender manifest
*/ */
public get(route: string): CacheControl | undefined { public get(
route: string,
owner: ResponseCacheOwner
): CacheControl | undefined {
// This is a copy on write cache that is updated when the cache is updated. // This is a copy on write cache that is updated when the cache is updated.
// If the cache is never written to, then the values will be sourced from // If the cache is never written to, then the values will be sourced from
// the prerender manifest. // the prerender manifest.
let cacheControl = SharedCacheControls.cacheControls.get(route) let cacheControl = SharedCacheControls.cacheControls.get(
getRouteCacheKey(route, owner)
)
if (cacheControl) return cacheControl if (cacheControl) return cacheControl
let prerenderData = this.prerenderManifest.routes[route] let prerenderData = this.prerenderManifest.routes[route]
if (prerenderData) { if (
prerenderData &&
isRouteCacheOwner(route, owner, prerenderData, this.locales)
) {
const { initialRevalidateSeconds, initialExpireSeconds } = prerenderData const { initialRevalidateSeconds, initialExpireSeconds } = prerenderData
if (typeof initialRevalidateSeconds !== 'undefined') { if (typeof initialRevalidateSeconds !== 'undefined') {
...@@ -53,9 +70,17 @@ export class SharedCacheControls { ...@@ -53,9 +70,17 @@ export class SharedCacheControls {
} }
} }
const dynamicPrerenderData = this.prerenderManifest.dynamicRoutes[route] const dynamicPathname =
owner.kind === RouteKind.PAGES
? normalizeLocalePath(route, this.locales).pathname
: route
const dynamicPrerenderData =
this.prerenderManifest.dynamicRoutes[dynamicPathname]
if (dynamicPrerenderData) { if (
dynamicPrerenderData &&
isRouteCacheOwner(route, owner, dynamicPrerenderData, this.locales)
) {
const { fallbackRevalidate, fallbackExpire } = dynamicPrerenderData const { fallbackRevalidate, fallbackExpire } = dynamicPrerenderData
if (typeof fallbackRevalidate !== 'undefined') { if (typeof fallbackRevalidate !== 'undefined') {
...@@ -63,6 +88,8 @@ export class SharedCacheControls { ...@@ -63,6 +88,8 @@ export class SharedCacheControls {
} }
} }
// A new runtime pathname has no initial lifetime. Its own render supplies
// one instead of borrowing a sibling route's build-time metadata.
return undefined return undefined
} }
......
import type { CacheFs } from '../../shared/lib/utils' import type { CacheFs } from '../../shared/lib/utils'
import fs from 'fs' import fs from 'fs'
import { randomUUID } from 'node:crypto'
export const nodeFs: CacheFs = { export const nodeFs: CacheFs = {
existsSync: fs.existsSync, existsSync: fs.existsSync,
readFile: fs.promises.readFile, readFile: fs.promises.readFile,
readFileSync: fs.readFileSync, readFileSync: fs.readFileSync,
writeFile: (f, d) => fs.promises.writeFile(f, d), writeFile: (f, d) => fs.promises.writeFile(f, d),
writeFileAtomic: async (f, d) => {
const temporary = `${f}.${randomUUID()}.tmp`
try {
await fs.promises.writeFile(temporary, d)
await fs.promises.link(temporary, f)
return true
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'EEXIST') return false
throw error
} finally {
await fs.promises.unlink(temporary).catch(() => {})
}
},
mkdir: (dir) => fs.promises.mkdir(dir, { recursive: true }), mkdir: (dir) => fs.promises.mkdir(dir, { recursive: true }),
stat: (f) => fs.promises.stat(f), stat: (f) => fs.promises.stat(f),
} }
import type { RouteDefinition } from '../route-definitions/route-definition'
import type {
DynamicPrerenderManifestRoute,
PrerenderManifestRoute,
} from '../../build'
import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'
import { normalizeLocalePath } from '../../shared/lib/i18n/normalize-locale-path'
import { InvariantError } from '../../shared/lib/invariant-error'
import { AppPathnameNormalizer } from '../normalizers/built/app/app-pathname-normalizer'
import { RouteKind } from '../route-kind'
export const ROUTE_CACHE_DIRECTORY = 'route-cache'
export type ResponseCacheOwner = {
readonly kind: RouteKind
/** Canonical Pages pathname or full App module name, including groups and slots. */
readonly sourceRoute: string
}
const appPathnameNormalizer = new AppPathnameNormalizer()
/** Convert a runtime route definition to the identity used by response caches. */
export function getResponseCacheOwner(
definition: Pick<RouteDefinition, 'kind' | 'page' | 'pathname'>
): ResponseCacheOwner {
return {
kind: definition.kind,
// Pages module names can include a trailing /index in Turbopack. Their
// pathname matches the manifest's source in both bundlers. App modules
// retain groups and parallel slots in their cache identity.
sourceRoute:
definition.kind === RouteKind.PAGES
? definition.pathname
: definition.page,
}
}
/**
* Prerender metadata already identifies its source route. Compare that source
* with the selected module before using its metadata, including negative
* entries and partially specialized fallback shells. Cache storage continues
* to use the full module identity, including groups and parallel slots.
*/
export function isRouteCacheOwner(
pathname: string,
owner: ResponseCacheOwner,
prerender:
| Pick<PrerenderManifestRoute, 'srcRoute' | 'dataRoute'>
| Pick<DynamicPrerenderManifestRoute, 'fallbackSourceRoute' | 'dataRoute'>
| undefined,
locales?: readonly string[]
): boolean {
if (!prerender) {
return false
}
// Pages have JSON data routes, App Pages have RSC data routes, and App
// Route Handlers have no separate data route.
const kind =
prerender.dataRoute === null
? RouteKind.APP_ROUTE
: prerender.dataRoute.endsWith('.json')
? RouteKind.PAGES
: prerender.dataRoute.endsWith('.rsc')
? RouteKind.APP_PAGE
: undefined
if (kind !== owner.kind) {
return false
}
const source =
'srcRoute' in prerender ? prerender.srcRoute : prerender.fallbackSourceRoute
const prerenderOwner =
source ??
(kind === RouteKind.PAGES
? normalizeLocalePath(pathname, locales).pathname
: pathname)
return (
prerenderOwner ===
(kind === RouteKind.PAGES
? owner.sourceRoute
: appPathnameNormalizer.normalize(owner.sourceRoute))
)
}
/**
* Response keys are opaque to cache handlers. Hash the source route into one
* fixed-length directory, preserving App groups and slots without expanding
* Unicode names or repeating the source directory hierarchy on disk. The
* pathname stays readable and is normalized exactly once before namespacing.
*/
export function getRouteCacheKey(
pathname: string,
owner: ResponseCacheOwner
): string {
if (!owner) {
throw new InvariantError('Response cache requires a source route')
}
const { sourceRoute } = owner
let source: string
if (process.env.NEXT_RUNTIME === 'edge') {
const sha256 =
require('next/dist/compiled/hash.js/sha256') as typeof import('next/dist/compiled/hash.js/sha256')
source = sha256()
.update(new TextEncoder().encode(sourceRoute))
.digest('hex')
} else {
const { createHash } = require('crypto') as typeof import('crypto')
source = createHash('sha256').update(sourceRoute).digest('hex')
}
return `/${ROUTE_CACHE_DIRECTORY}/${owner.kind}/${source}/$${normalizePagePath(pathname)}`
}
...@@ -78,7 +78,10 @@ import ResponseCache, { ...@@ -78,7 +78,10 @@ import ResponseCache, {
type IncrementalResponseCacheEntry, type IncrementalResponseCacheEntry,
} from './response-cache' } from './response-cache'
import { IncrementalCache } from './lib/incremental-cache' import { IncrementalCache } from './lib/incremental-cache'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import {
normalizeAppPath,
selectAppPageEntry,
} from '../shared/lib/router/utils/app-paths'
import { setHttpClientAndAgentOptions } from './setup-http-agent-env' import { setHttpClientAndAgentOptions } from './setup-http-agent-env'
...@@ -289,7 +292,10 @@ export default class NextNodeServer extends BaseServer< ...@@ -289,7 +292,10 @@ export default class NextNodeServer extends BaseServer<
: this.nextConfig.deploymentId || '' : this.nextConfig.deploymentId || ''
if (!this.minimalMode) { if (!this.minimalMode) {
this.imageResponseCache = new ResponseCache(this.minimalMode) this.imageResponseCache = new ResponseCache({
minimalMode: this.minimalMode,
route: 'image',
})
} }
const { appDocumentPreloading } = this.nextConfig.experimental const { appDocumentPreloading } = this.nextConfig.experimental
...@@ -528,14 +534,11 @@ export default class NextNodeServer extends BaseServer< ...@@ -528,14 +534,11 @@ export default class NextNodeServer extends BaseServer<
flushToDisk: flushToDisk:
!this.minimalMode && this.nextConfig.experimental.isrFlushToDisk, !this.minimalMode && this.nextConfig.experimental.isrFlushToDisk,
getPrerenderManifest: () => this.getPrerenderManifest(), getPrerenderManifest: () => this.getPrerenderManifest(),
locales: this.nextConfig.i18n?.locales,
CurCacheHandler: CacheHandler, CurCacheHandler: CacheHandler,
}) })
} }
protected getResponseCache() {
return new ResponseCache(this.minimalMode)
}
protected getPublicDir(): string { protected getPublicDir(): string {
return join(this.dir, CLIENT_PUBLIC_FILES_PATH) return join(this.dir, CLIENT_PUBLIC_FILES_PATH)
} }
...@@ -825,8 +828,8 @@ export default class NextNodeServer extends BaseServer< ...@@ -825,8 +828,8 @@ export default class NextNodeServer extends BaseServer<
let page = ctx.pathname let page = ctx.pathname
if (isAppPath) { if (isAppPath) {
// When it's an array, we need to pass all parallel routes to the loader. // Match the build owner while passing all parallel paths to the loader.
page = appPaths[0] page = selectAppPageEntry(ctx.pathname, appPaths)
} }
for (const edgeFunctionsPage of edgeFunctionsPages) { for (const edgeFunctionsPage of edgeFunctionsPages) {
......
import ResponseCache from './index'
import {
CachedRouteKind,
IncrementalCacheKind,
type ResponseCacheEntry,
} from './types'
import { RouteKind } from '../route-kind'
import RenderResult from '../render-result'
import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants'
import { fromResponseCacheEntry } from './utils'
function mockIncrementalCache() {
return {
get: jest.fn().mockResolvedValue(null),
set: jest.fn().mockResolvedValue(undefined),
}
}
function makeCacheEntry(html: string): ResponseCacheEntry {
return {
value: {
kind: CachedRouteKind.APP_PAGE,
html: RenderResult.fromStatic(html, HTML_CONTENT_TYPE_HEADER),
rscData: Buffer.from('rsc-payload'),
postponed: undefined,
status: 200,
headers: undefined,
segmentData: undefined,
},
cacheControl: { revalidate: 60, expire: undefined },
}
}
describe('ResponseCache', () => {
const route = { kind: RouteKind.APP_PAGE, sourceRoute: '/test/page' }
it('rejects missing ownership even in minimal mode', () => {
expect(() => {
// @ts-expect-error response caches must explicitly select their owner
new ResponseCache({ minimalMode: true })
}).toThrow('Response cache requires a source route')
})
it('passes the source route to both reads and regeneration writes', async () => {
const cache = new ResponseCache({ minimalMode: false, route })
const incrementalCache = mockIncrementalCache()
await cache.get('/test', async () => makeCacheEntry('generated'), {
routeKind: RouteKind.APP_PAGE,
incrementalCache,
})
expect(incrementalCache.get).toHaveBeenCalledWith('/test', {
kind: IncrementalCacheKind.APP_PAGE,
route,
isFallback: false,
isRoutePPREnabled: false,
})
expect(incrementalCache.set).toHaveBeenCalledWith(
'/test',
expect.any(Object),
expect.objectContaining({ route })
)
})
it('uses an explicit image context without a source route', async () => {
const cache = new ResponseCache({ minimalMode: false, route: 'image' })
const incrementalCache = mockIncrementalCache()
await cache.get(
'image-key',
async () => ({
value: {
kind: CachedRouteKind.IMAGE,
buffer: Buffer.from('image'),
etag: 'etag',
upstreamEtag: 'upstream-etag',
extension: 'png',
},
cacheControl: { revalidate: 60, expire: undefined },
}),
{
routeKind: RouteKind.IMAGE,
incrementalCache,
}
)
expect(incrementalCache.get).toHaveBeenCalledWith('image-key', {
kind: IncrementalCacheKind.IMAGE,
isFallback: false,
})
expect(incrementalCache.set).toHaveBeenCalledWith(
'image-key',
expect.objectContaining({ kind: CachedRouteKind.IMAGE }),
{
kind: IncrementalCacheKind.IMAGE,
isFallback: false,
cacheControl: { revalidate: 60, expire: undefined },
}
)
})
it('keeps ownership when extending a previous entry after regeneration fails', async () => {
const cache = new ResponseCache({ minimalMode: false, route })
const incrementalCache = mockIncrementalCache()
const previous = await fromResponseCacheEntry(makeCacheEntry('cached'))
incrementalCache.get.mockResolvedValue(previous)
await expect(
cache.get(
'/test',
async () => {
throw new Error('regeneration failed')
},
{
routeKind: RouteKind.APP_PAGE,
incrementalCache,
isOnDemandRevalidate: true,
}
)
).rejects.toThrow('regeneration failed')
expect(incrementalCache.set).toHaveBeenCalledWith(
'/test',
previous.value,
expect.objectContaining({
route,
cacheControl: { revalidate: 30, expire: undefined },
})
)
})
})
import type { RouteKind } from '../route-kind'
import type { ResponseCacheOwner } from '../lib/route-cache-key'
import type { import type {
ResponseCacheEntry, ResponseCacheEntry,
ResponseGenerator, ResponseGenerator,
ResponseCacheBase, ResponseCacheBase,
IncrementalResponseCacheEntry, IncrementalResponseCacheEntry,
IncrementalResponseCache, IncrementalResponseCache,
GetIncrementalResponseCacheContext,
GetIncrementalImageCacheContext,
} from './types' } from './types'
import { IncrementalCacheKind } from './types'
import { InvariantError } from '../../shared/lib/invariant-error'
import { Batcher } from '../../lib/batcher' import { Batcher } from '../../lib/batcher'
import { LRUCache } from '../lib/lru-cache' import { LRUCache } from '../lib/lru-cache'
...@@ -15,7 +21,6 @@ import { ...@@ -15,7 +21,6 @@ import {
routeKindToIncrementalCacheKind, routeKindToIncrementalCacheKind,
toResponseCacheEntry, toResponseCacheEntry,
} from './utils' } from './utils'
import type { RouteKind } from '../route-kind'
/** /**
* Parses an environment variable as a positive integer, returning the fallback * Parses an environment variable as a positive integer, returning the fallback
...@@ -159,12 +164,24 @@ export default class ResponseCache implements ResponseCacheBase { ...@@ -159,12 +164,24 @@ export default class ResponseCache implements ResponseCacheBase {
// be dynamic here // be dynamic here
private minimal_mode?: boolean private minimal_mode?: boolean
constructor( private readonly route: ResponseCacheOwner | 'image'
minimal_mode: boolean,
maxSize: number = DEFAULT_MAX_SIZE, constructor({
ttl: number = DEFAULT_TTL_MS minimalMode,
) { route,
this.minimal_mode = minimal_mode maxSize = DEFAULT_MAX_SIZE,
ttl = DEFAULT_TTL_MS,
}: {
minimalMode: boolean
route: ResponseCacheOwner | 'image'
maxSize?: number
ttl?: number
}) {
if (!route) {
throw new InvariantError('Response cache requires a source route')
}
this.route = route
this.minimal_mode = minimalMode
this.maxSize = maxSize this.maxSize = maxSize
this.ttl = ttl this.ttl = ttl
...@@ -258,7 +275,6 @@ export default class ResponseCache implements ResponseCacheBase { ...@@ -258,7 +275,6 @@ export default class ResponseCache implements ResponseCacheBase {
isRoutePPREnabled = false, isRoutePPREnabled = false,
isPrefetch = false, isPrefetch = false,
waitUntil, waitUntil,
routeKind,
invocationID, invocationID,
} = context } = context
...@@ -274,7 +290,6 @@ export default class ResponseCache implements ResponseCacheBase { ...@@ -274,7 +290,6 @@ export default class ResponseCache implements ResponseCacheBase {
isFallback, isFallback,
isRoutePPREnabled, isRoutePPREnabled,
isPrefetch, isPrefetch,
routeKind,
invocationID, invocationID,
}, },
resolve resolve
...@@ -310,7 +325,6 @@ export default class ResponseCache implements ResponseCacheBase { ...@@ -310,7 +325,6 @@ export default class ResponseCache implements ResponseCacheBase {
isFallback: boolean isFallback: boolean
isRoutePPREnabled: boolean isRoutePPREnabled: boolean
isPrefetch: boolean isPrefetch: boolean
routeKind: RouteKind
invocationID: string | undefined invocationID: string | undefined
}, },
resolve: (value: IncrementalResponseCacheEntry | null) => void resolve: (value: IncrementalResponseCacheEntry | null) => void
...@@ -322,11 +336,10 @@ export default class ResponseCache implements ResponseCacheBase { ...@@ -322,11 +336,10 @@ export default class ResponseCache implements ResponseCacheBase {
try { try {
// Get the previous cache entry if not in minimal mode // Get the previous cache entry if not in minimal mode
previousIncrementalCacheEntry = !this.minimal_mode previousIncrementalCacheEntry = !this.minimal_mode
? await context.incrementalCache.get(key, { ? await context.incrementalCache.get(
kind: routeKindToIncrementalCacheKind(context.routeKind), key,
isRoutePPREnabled: context.isRoutePPREnabled, this.getCacheContext(context.isRoutePPREnabled, context.isFallback)
isFallback: context.isFallback, )
})
: null : null
if (previousIncrementalCacheEntry && !context.isOnDemandRevalidate) { if (previousIncrementalCacheEntry && !context.isOnDemandRevalidate) {
...@@ -466,8 +479,7 @@ export default class ResponseCache implements ResponseCacheBase { ...@@ -466,8 +479,7 @@ export default class ResponseCache implements ResponseCacheBase {
} else { } else {
await incrementalCache.set(key, incrementalResponseCacheEntry.value, { await incrementalCache.set(key, incrementalResponseCacheEntry.value, {
cacheControl: incrementalResponseCacheEntry.cacheControl, cacheControl: incrementalResponseCacheEntry.cacheControl,
isRoutePPREnabled, ...this.getCacheContext(isRoutePPREnabled, isFallback),
isFallback,
}) })
} }
} }
...@@ -493,9 +505,8 @@ export default class ResponseCache implements ResponseCacheBase { ...@@ -493,9 +505,8 @@ export default class ResponseCache implements ResponseCacheBase {
) )
await incrementalCache.set(key, previousIncrementalCacheEntry.value, { await incrementalCache.set(key, previousIncrementalCacheEntry.value, {
...this.getCacheContext(isRoutePPREnabled, isFallback),
cacheControl: { revalidate: revalidate, expire: expire }, cacheControl: { revalidate: revalidate, expire: expire },
isRoutePPREnabled,
isFallback,
}) })
} }
...@@ -503,4 +514,18 @@ export default class ResponseCache implements ResponseCacheBase { ...@@ -503,4 +514,18 @@ export default class ResponseCache implements ResponseCacheBase {
throw err throw err
} }
} }
private getCacheContext(
isRoutePPREnabled: boolean,
isFallback: boolean
): GetIncrementalResponseCacheContext | GetIncrementalImageCacheContext {
if (this.route === 'image') {
return { kind: IncrementalCacheKind.IMAGE, isFallback: false }
}
const kind = routeKindToIncrementalCacheKind(this.route.kind)
if (kind === IncrementalCacheKind.IMAGE) {
throw new InvariantError('Images must use the image response cache')
}
return { route: this.route, kind, isRoutePPREnabled, isFallback }
}
} }
import type { ResponseCacheOwner } from '../lib/route-cache-key'
import type { OutgoingHttpHeaders } from 'http' import type { OutgoingHttpHeaders } from 'http'
import type RenderResult from '../render-result' import type RenderResult from '../render-result'
import type { CacheControl, Revalidate } from '../lib/cache-control' import type { CacheControl, Revalidate } from '../lib/cache-control'
...@@ -207,8 +208,11 @@ export interface GetIncrementalFetchCacheContext { ...@@ -207,8 +208,11 @@ export interface GetIncrementalFetchCacheContext {
softTags?: string[] softTags?: string[]
} }
export interface GetIncrementalResponseCacheContext { export interface GetIncrementalResponseCacheHandlerContext {
kind: Exclude<IncrementalCacheKind, IncrementalCacheKind.FETCH> kind: Exclude<
IncrementalCacheKind,
IncrementalCacheKind.FETCH | IncrementalCacheKind.IMAGE
>
/** /**
* True if the route is enabled for PPR. * True if the route is enabled for PPR.
...@@ -221,6 +225,12 @@ export interface GetIncrementalResponseCacheContext { ...@@ -221,6 +225,12 @@ export interface GetIncrementalResponseCacheContext {
isFallback: boolean isFallback: boolean
} }
export interface GetIncrementalResponseCacheContext
extends GetIncrementalResponseCacheHandlerContext {
/** Internal ownership used before invoking the storage handler. */
route: ResponseCacheOwner
}
export interface SetIncrementalFetchCacheContext { export interface SetIncrementalFetchCacheContext {
fetchCache: true fetchCache: true
fetchUrl?: string fetchUrl?: string
...@@ -229,7 +239,7 @@ export interface SetIncrementalFetchCacheContext { ...@@ -229,7 +239,7 @@ export interface SetIncrementalFetchCacheContext {
isImplicitBuildTimeCache?: boolean isImplicitBuildTimeCache?: boolean
} }
export interface SetIncrementalResponseCacheContext { export interface SetIncrementalResponseCacheHandlerContext {
fetchCache?: false fetchCache?: false
cacheControl?: CacheControl cacheControl?: CacheControl
...@@ -244,15 +254,35 @@ export interface SetIncrementalResponseCacheContext { ...@@ -244,15 +254,35 @@ export interface SetIncrementalResponseCacheContext {
isFallback?: boolean isFallback?: boolean
} }
export interface SetIncrementalResponseCacheContext
extends SetIncrementalResponseCacheHandlerContext {
/** Internal ownership used before invoking the storage handler. */
route: ResponseCacheOwner
}
export interface GetIncrementalImageCacheContext {
kind: IncrementalCacheKind.IMAGE
route?: never
isFallback: false
isRoutePPREnabled?: false
}
export interface SetIncrementalImageCacheContext {
kind: IncrementalCacheKind.IMAGE
route?: never
fetchCache?: false
cacheControl?: CacheControl
}
export interface IncrementalResponseCache { export interface IncrementalResponseCache {
get( get(
cacheKey: string, cacheKey: string,
ctx: GetIncrementalResponseCacheContext ctx: GetIncrementalResponseCacheContext | GetIncrementalImageCacheContext
): Promise<IncrementalResponseCacheEntry | null> ): Promise<IncrementalResponseCacheEntry | null>
set( set(
key: string, key: string,
data: Exclude<IncrementalCacheValue, CachedFetchValue> | null, data: Exclude<IncrementalCacheValue, CachedFetchValue> | null,
ctx: SetIncrementalResponseCacheContext ctx: SetIncrementalResponseCacheContext | SetIncrementalImageCacheContext
): Promise<void> ): Promise<void>
} }
...@@ -263,7 +293,7 @@ export interface IncrementalCache extends IncrementalResponseCache { ...@@ -263,7 +293,7 @@ export interface IncrementalCache extends IncrementalResponseCache {
): Promise<IncrementalFetchCacheEntry | null> ): Promise<IncrementalFetchCacheEntry | null>
get( get(
cacheKey: string, cacheKey: string,
ctx: GetIncrementalResponseCacheContext ctx: GetIncrementalResponseCacheContext | GetIncrementalImageCacheContext
): Promise<IncrementalResponseCacheEntry | null> ): Promise<IncrementalResponseCacheEntry | null>
set( set(
key: string, key: string,
...@@ -273,6 +303,6 @@ export interface IncrementalCache extends IncrementalResponseCache { ...@@ -273,6 +303,6 @@ export interface IncrementalCache extends IncrementalResponseCache {
set( set(
key: string, key: string,
data: Exclude<IncrementalCacheValue, CachedFetchValue> | null, data: Exclude<IncrementalCacheValue, CachedFetchValue> | null,
ctx: SetIncrementalResponseCacheContext ctx: SetIncrementalResponseCacheContext | SetIncrementalImageCacheContext
): Promise<void> ): Promise<void>
} }
...@@ -11,6 +11,28 @@ describe('AppPageRouteMatcherProvider', () => { ...@@ -11,6 +11,28 @@ describe('AppPageRouteMatcherProvider', () => {
await expect(matcher.matchers()).resolves.toEqual([]) await expect(matcher.matchers()).resolves.toEqual([])
}) })
it.each([false, true])(
'selects the build owner regardless of manifest insertion order (%s)',
async (reverse) => {
const entries = [
['/stories/@slot/[slug]/page', 'app/stories/@slot/[slug]/page.js'],
['/stories/[slug]/page', 'app/stories/[slug]/page.js'],
]
if (reverse) entries.reverse()
const loader: ManifestLoader = {
load: jest.fn(() => Object.fromEntries(entries)),
}
const provider = new AppPageRouteMatcherProvider('<root>', loader)
const matchers = await provider.matchers()
expect(matchers).toHaveLength(1)
expect(matchers[0].definition).toMatchObject({
page: '/stories/[slug]/page',
filename: `<root>/${SERVER_DIRECTORY}/app/stories/[slug]/page.js`,
appPaths: entries.map(([page]) => page),
})
}
)
describe('manifest matching', () => { describe('manifest matching', () => {
it.each<{ it.each<{
manifest: Record<string, string> manifest: Record<string, string>
......
import { selectAppPageEntry } from '../../shared/lib/router/utils/app-paths'
import { isAppPageRoute } from '../../lib/is-app-page-route' import { isAppPageRoute } from '../../lib/is-app-page-route'
import { APP_PATHS_MANIFEST } from '../../shared/lib/constants' import { APP_PATHS_MANIFEST } from '../../shared/lib/constants'
...@@ -37,8 +38,7 @@ export class AppPageRouteMatcherProvider extends ManifestRouteMatcherProvider<Ap ...@@ -37,8 +38,7 @@ export class AppPageRouteMatcherProvider extends ManifestRouteMatcherProvider<Ap
// Format the routes. // Format the routes.
const matchers: Array<AppPageRouteMatcher> = [] const matchers: Array<AppPageRouteMatcher> = []
for (const [pathname, appPaths] of Object.entries(allAppPaths)) { for (const [pathname, appPaths] of Object.entries(allAppPaths)) {
// TODO-APP: (wyattjoh) this is a hack right now, should be more deterministic const page = selectAppPageEntry(pathname, appPaths)
const page = appPaths[0]
const filename = this.normalizers.filename.normalize(manifest[page]) const filename = this.normalizers.filename.normalize(manifest[page])
const bundlePath = this.normalizers.bundlePath.normalize(page) const bundlePath = this.normalizers.bundlePath.normalize(page)
......
...@@ -36,6 +36,7 @@ import { RedirectStatusCode } from '../../../client/components/redirect-status-c ...@@ -36,6 +36,7 @@ import { RedirectStatusCode } from '../../../client/components/redirect-status-c
import { isBot } from '../../../shared/lib/router/utils/is-bot' import { isBot } from '../../../shared/lib/router/utils/is-bot'
import { addPathPrefix } from '../../../shared/lib/router/utils/add-path-prefix' import { addPathPrefix } from '../../../shared/lib/router/utils/add-path-prefix'
import { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash' import { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash'
import { isRouteCacheOwner } from '../../lib/route-cache-key'
import type { PagesRouteModule } from './module.compiled' import type { PagesRouteModule } from './module.compiled'
import type { import type {
GetServerSideProps, GetServerSideProps,
...@@ -159,8 +160,18 @@ export const getHandler = ({ ...@@ -159,8 +160,18 @@ export const getHandler = ({
: resolvedPathname : resolvedPathname
) )
const isPrerendered = const isPrerendered =
Boolean(prerenderManifest.routes[decodedPathname]) || (Boolean(prerenderManifest.routes[decodedPathname]) ||
prerenderManifest.notFoundRoutes.includes(decodedPathname) prerenderManifest.notFoundRoutes.includes(decodedPathname)) &&
// A sibling's positive or negative prerender cannot admit parameters
// that this route excluded. Development computes static paths on demand
// instead of reading build-time prerender metadata.
(routeModule.isDev ||
isRouteCacheOwner(
decodedPathname,
routeModule.cacheOwner,
prerenderManifest.routes[decodedPathname],
nextConfig.i18n?.locales
))
const prerenderInfo = prerenderManifest.dynamicRoutes[srcPage] const prerenderInfo = prerenderManifest.dynamicRoutes[srcPage]
......
...@@ -49,6 +49,10 @@ import { IncrementalCache } from '../lib/incremental-cache' ...@@ -49,6 +49,10 @@ import { IncrementalCache } from '../lib/incremental-cache'
import { initializeCacheHandlers, setCacheHandler } from '../use-cache/handlers' import { initializeCacheHandlers, setCacheHandler } from '../use-cache/handlers'
import { interopDefault } from '../app-render/interop-default' import { interopDefault } from '../app-render/interop-default'
import type { RouteKind } from '../route-kind' import type { RouteKind } from '../route-kind'
import {
getResponseCacheOwner,
type ResponseCacheOwner,
} from '../lib/route-cache-key'
import type { BaseNextRequest } from '../base-http' import type { BaseNextRequest } from '../base-http'
import type { I18NConfig, NextConfigComplete } from '../config-shared' import type { I18NConfig, NextConfigComplete } from '../config-shared'
import ResponseCache, { type ResponseGenerator } from '../response-cache' import ResponseCache, { type ResponseGenerator } from '../response-cache'
...@@ -113,6 +117,9 @@ export abstract class RouteModule< ...@@ -113,6 +117,9 @@ export abstract class RouteModule<
*/ */
public readonly definition: Readonly<D> public readonly definition: Readonly<D>
/** The canonical source identity shared by cache reads, writes, and metadata. */
public readonly cacheOwner: ResponseCacheOwner
/** /**
* The shared modules that are exposed and required for the route module. * The shared modules that are exposed and required for the route module.
*/ */
...@@ -133,6 +140,7 @@ export abstract class RouteModule< ...@@ -133,6 +140,7 @@ export abstract class RouteModule<
}: RouteModuleOptions<D, U>) { }: RouteModuleOptions<D, U>) {
this.userland = userland this.userland = userland
this.definition = definition this.definition = definition
this.cacheOwner = getResponseCacheOwner(definition)
this.isDev = process.env.NODE_ENV === 'development' this.isDev = process.env.NODE_ENV === 'development'
this.distDir = distDir this.distDir = distDir
this.relativeProjectDir = relativeProjectDir this.relativeProjectDir = relativeProjectDir
...@@ -456,6 +464,7 @@ export abstract class RouteModule< ...@@ -456,6 +464,7 @@ export abstract class RouteModule<
flushToDisk: nextConfig.experimental.isrFlushToDisk, flushToDisk: nextConfig.experimental.isrFlushToDisk,
getPrerenderManifest: () => prerenderManifest, getPrerenderManifest: () => prerenderManifest,
CurCacheHandler: CacheHandler, CurCacheHandler: CacheHandler,
locales: nextConfig.i18n?.locales,
}) })
} }
} }
...@@ -848,7 +857,10 @@ export abstract class RouteModule< ...@@ -848,7 +857,10 @@ export abstract class RouteModule<
public getResponseCache(req: IncomingMessage | BaseNextRequest) { public getResponseCache(req: IncomingMessage | BaseNextRequest) {
if (!this.responseCache) { if (!this.responseCache) {
const minimalMode = getRequestMeta(req, 'minimalMode') ?? false const minimalMode = getRequestMeta(req, 'minimalMode') ?? false
this.responseCache = new ResponseCache(minimalMode) this.responseCache = new ResponseCache({
minimalMode,
route: this.cacheOwner,
})
} }
return this.responseCache return this.responseCache
} }
......
...@@ -51,6 +51,24 @@ export function normalizeAppPath(route: string) { ...@@ -51,6 +51,24 @@ export function normalizeAppPath(route: string) {
) )
} }
/** Select the last direct entry, matching Next 15's sorted appPaths at runtime. */
export function selectAppPageEntry(
pathname: string,
appPaths: readonly string[],
normalizePathname: (appPath: string) => string = (appPath) =>
normalizeAppPath(appPath).replace(/%5F/g, '_')
): string {
let entry: string | undefined
for (const appPath of appPaths) {
if (normalizePathname(appPath) !== pathname) continue
if (entry === undefined || entry < appPath) entry = appPath
}
if (entry === undefined) {
throw new Error(`Invariant: no direct app page entry found for ${pathname}`)
}
return entry
}
/** /**
* Strips the `.rsc` extension if it's in the pathname. * Strips the `.rsc` extension if it's in the pathname.
* Since this function is used on full urls it checks `?` for searchParams handling. * Since this function is used on full urls it checks `?` for searchParams handling.
......
...@@ -452,6 +452,8 @@ export interface CacheFs { ...@@ -452,6 +452,8 @@ export interface CacheFs {
readFile: typeof fs.promises.readFile readFile: typeof fs.promises.readFile
readFileSync: typeof fs.readFileSync readFileSync: typeof fs.readFileSync
writeFile(f: string, d: any): Promise<void> writeFile(f: string, d: any): Promise<void>
/** Publish a complete file without replacing an existing destination. */
writeFileAtomic?(f: string, d: any): Promise<boolean>
mkdir(dir: string): Promise<void | string> mkdir(dir: string): Promise<void | string>
stat(f: string): Promise<{ mtime: Date }> stat(f: string): Promise<{ mtime: Date }>
} }
......
...@@ -1997,7 +1997,29 @@ export async function ncc_string_hash(task, opts) { ...@@ -1997,7 +1997,29 @@ export async function ncc_string_hash(task, opts) {
.ncc({ packageName: 'string-hash', externals }) .ncc({ packageName: 'string-hash', externals })
.target('src/compiled/string-hash') .target('src/compiled/string-hash')
} }
// eslint-disable-next-line camelcase // Bundle only SHA-256, using browser entrypoints so this is safe in Edge.
export async function ncc_hash_sha256(task, opts) {
await task
.source(relative(__dirname, require.resolve('hash.js/lib/hash/sha/256')))
.ncc({
packageName: 'hash.js',
bundleName: 'hash.js/sha256',
externals,
mainFields: ['browser', 'main'],
})
.target('src/compiled/hash.js/sha256')
// hash.js publishes its license in the README rather than a LICENSE file.
const readme = await fs.readFile(require.resolve('hash.js/README.md'), 'utf8')
const license = readme.split('#### LICENSE\n')[1]
if (!license) {
throw new Error('Missing hash.js license')
}
await fs.writeFile(
join(__dirname, 'src/compiled/hash.js/sha256/LICENSE'),
`${license.trim()}\n`
)
}
externals['strip-ansi'] = 'next/dist/compiled/strip-ansi' externals['strip-ansi'] = 'next/dist/compiled/strip-ansi'
externals['next/dist/compiled/strip-ansi'] = 'next/dist/compiled/strip-ansi' externals['next/dist/compiled/strip-ansi'] = 'next/dist/compiled/strip-ansi'
export async function ncc_strip_ansi(task, opts) { export async function ncc_strip_ansi(task, opts) {
...@@ -2404,6 +2426,7 @@ export async function ncc(task, opts) { ...@@ -2404,6 +2426,7 @@ export async function ncc(task, opts) {
'ncc_source_map', 'ncc_source_map',
'ncc_source_map08', 'ncc_source_map08',
'ncc_string_hash', 'ncc_string_hash',
'ncc_hash_sha256',
'ncc_strip_ansi', 'ncc_strip_ansi',
'ncc_superstruct', 'ncc_superstruct',
'ncc_zod', 'ncc_zod',
......
...@@ -684,6 +684,10 @@ declare module 'next/dist/compiled/string-hash' { ...@@ -684,6 +684,10 @@ declare module 'next/dist/compiled/string-hash' {
import m from 'string-hash' import m from 'string-hash'
export = m export = m
} }
declare module 'next/dist/compiled/hash.js/sha256' {
import { sha256 } from 'hash.js'
export = sha256
}
declare module 'next/dist/compiled/ua-parser-js' { declare module 'next/dist/compiled/ua-parser-js' {
import m from 'ua-parser-js' import m from 'ua-parser-js'
export = m export = m
......
...@@ -1360,6 +1360,9 @@ importers: ...@@ -1360,6 +1360,9 @@ importers:
gzip-size: gzip-size:
specifier: 5.1.1 specifier: 5.1.1
version: 5.1.1 version: 5.1.1
hash.js:
specifier: 1.1.7
version: 1.1.7
http-proxy: http-proxy:
specifier: 1.18.1 specifier: 1.18.1
version: 1.18.1(patch_hash=kzqzmw2zuo23hy3avffm6aqice) version: 1.18.1(patch_hash=kzqzmw2zuo23hy3avffm6aqice)
...@@ -176,6 +176,7 @@ async function main() { ...@@ -176,6 +176,7 @@ async function main() {
env: { env: {
...process.env, ...process.env,
NEXT_TEST_MODE: testMode, NEXT_TEST_MODE: testMode,
NEXT_TEST_PREVIEW_BUILDS_BASE_URL: previewBuildsBaseUrl,
NEXT_TEST_VERSION: nextTestVersion, NEXT_TEST_VERSION: nextTestVersion,
NEXT_EXTERNAL_TESTS_FILTERS: NEXT_EXTERNAL_TESTS_FILTERS:
testMode === 'deploy' ? 'test/deploy-tests-manifest.json' : undefined, testMode === 'deploy' ? 'test/deploy-tests-manifest.json' : undefined,
......
import { RouteKind } from 'next/dist/server/route-kind'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { check, waitFor, retry } from 'next-test-utils' import { check, waitFor, retry } from 'next-test-utils'
import { Readable } from 'stream' import { Readable } from 'stream'
...@@ -69,10 +70,26 @@ describe('app-custom-routes', () => { ...@@ -69,10 +70,26 @@ describe('app-custom-routes', () => {
if (isNextStart) { if (isNextStart) {
await check(async () => { await check(async () => {
expect( expect(
await next.readFile(`.next/server/app/${path}.body`) await next.readFile(
next.getPrerenderFilePath(path, '.body', {
router: 'app',
route: {
kind: RouteKind.APP_ROUTE,
sourceRoute: `/${path.split('/')[1]}/[slug]/data.json/route`,
},
})
)
).toBeTruthy() ).toBeTruthy()
expect( expect(
await next.readFile(`.next/server/app/${path}.meta`) await next.readFile(
next.getPrerenderFilePath(path, '.meta', {
router: 'app',
route: {
kind: RouteKind.APP_ROUTE,
sourceRoute: `/${path.split('/')[1]}/[slug]/data.json/route`,
},
})
)
).toBeTruthy() ).toBeTruthy()
return 'success' return 'success'
}, 'success') }, 'success')
...@@ -98,10 +115,26 @@ describe('app-custom-routes', () => { ...@@ -98,10 +115,26 @@ describe('app-custom-routes', () => {
if (isNextStart) { if (isNextStart) {
await check(async () => { await check(async () => {
expect( expect(
await next.readFile(`.next/server/app/${path}.body`) await next.readFile(
next.getPrerenderFilePath(path, '.body', {
router: 'app',
route: {
kind: RouteKind.APP_ROUTE,
sourceRoute: `/${path.split('/')[1]}/[slug]/data.json/route`,
},
})
)
).toBeTruthy() ).toBeTruthy()
expect( expect(
await next.readFile(`.next/server/app/${path}.meta`) await next.readFile(
next.getPrerenderFilePath(path, '.meta', {
router: 'app',
route: {
kind: RouteKind.APP_ROUTE,
sourceRoute: `/${path.split('/')[1]}/[slug]/data.json/route`,
},
})
)
).toBeTruthy() ).toBeTruthy()
return 'success' return 'success'
}, 'success') }, 'success')
......
import path from 'path'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils' import { check } from 'next-test-utils'
describe('catchall-parallel-routes-group', () => { describe('catchall-parallel-routes-group', () => {
const { next } = nextTestSetup({ const { next, isNextStart, isTurbopack } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
if (isNextStart && !isTurbopack) {
it('traces the canonical page and its dependencies from the slot entry', async () => {
const routeDir = path.join(next.testDir, '.next/server/app/[...catchAll]')
const slotDir = path.join(routeDir, '@slot/(group)')
const rootTrace = await next.readJSON(
'.next/server/app/[...catchAll]/page.js.nft.json'
)
const slotTrace = await next.readJSON(
'.next/server/app/[...catchAll]/@slot/(group)/page.js.nft.json'
)
const slotFiles = new Set<string>(
slotTrace.files.map((file: string) => path.resolve(slotDir, file))
)
const requiredFiles = [
path.join(routeDir, 'page.js'),
...rootTrace.files.map((file: string) => path.resolve(routeDir, file)),
]
expect(requiredFiles.filter((file) => !slotFiles.has(file))).toEqual([])
})
}
it('should work without throwing any errors about invalid pages', async () => { it('should work without throwing any errors about invalid pages', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
......
...@@ -22,10 +22,21 @@ describe('ppr-navigations incremental', () => { ...@@ -22,10 +22,21 @@ describe('ppr-navigations incremental', () => {
}) })
it('can navigate between all the links and back without writing to disk', async () => { it('can navigate between all the links and back without writing to disk', async () => {
const before = const checkDisk = !isNextDev && !isTurbopack && !isNextDeploy
!isNextDev && !isTurbopack && !isNextDeploy if (checkDisk) {
? await getDotNextFiles(next) // Promote every route's existing build seed before measuring navigation.
: [] for (const { href } of links) {
if (href === '/') continue
expect((await next.fetch(href)).status).toBe(200)
expect(
(
await next.fetch(href, {
headers: { RSC: '1', 'Next-Router-Prefetch': '1' },
})
).status
).toBe(200)
}
}
const browser = await next.browser('/') const browser = await next.browser('/')
...@@ -33,6 +44,8 @@ describe('ppr-navigations incremental', () => { ...@@ -33,6 +44,8 @@ describe('ppr-navigations incremental', () => {
await waitForHydration(browser) await waitForHydration(browser)
await setTimeout(500) await setTimeout(500)
const before = checkDisk ? await getDotNextFiles(next) : []
// Add a variable to the window so we can tell if it MPA navigated. If this // Add a variable to the window so we can tell if it MPA navigated. If this
// value is still true at the end of the test, then we know that the page // value is still true at the end of the test, then we know that the page
// didn't MPA navigate. // didn't MPA navigate.
...@@ -65,7 +78,7 @@ describe('ppr-navigations incremental', () => { ...@@ -65,7 +78,7 @@ describe('ppr-navigations incremental', () => {
await browser.close() await browser.close()
} }
if (!isNextDev && !isTurbopack && !isNextDeploy) { if (checkDisk) {
const after = await getDotNextFiles(next) const after = await getDotNextFiles(next)
// Ensure that no new files were written to disk. If this test fails, it's // Ensure that no new files were written to disk. If this test fails, it's
......
...@@ -18,6 +18,7 @@ import { ...@@ -18,6 +18,7 @@ import {
} from 'next-test-utils' } from 'next-test-utils'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
import { RouteKind } from 'next/dist/server/route-kind'
const isReact18 = parseInt(process.env.NEXT_TEST_REACT_VERSION) === 18 const isReact18 = parseInt(process.env.NEXT_TEST_REACT_VERSION) === 18
...@@ -57,28 +58,28 @@ describe('Prerender', () => { ...@@ -57,28 +58,28 @@ describe('Prerender', () => {
afterAll(() => next.destroy()) afterAll(() => next.destroy())
async function waitForCacheWrite( async function waitForCacheWrite(
prerenderPath = '', prerenderPath: string,
sourceRoute: string,
timeBeforeRevalidateMilliseconds, timeBeforeRevalidateMilliseconds,
retries = 30 retries = 30
) { ) {
for (let i = 0; i < retries; i++) { for (let i = 0; i < retries; i++) {
const lastRetry = i === retries - 1 const lastRetry = i === retries - 1
const jsonPath = join( const htmlPath = join(
next.testDir, next.testDir,
'.next', next.getPrerenderFilePath(prerenderPath, '.html', {
'server', route: { kind: RouteKind.PAGES, sourceRoute },
'pages', })
`${prerenderPath}.html`
) )
try { try {
const jsonStats = await fs.stat(jsonPath) const htmlStats = await fs.stat(htmlPath)
const jsonLastModified = jsonStats.mtime.getTime() const htmlLastModified = htmlStats.mtime.getTime()
if (timeBeforeRevalidateMilliseconds <= jsonLastModified) { if (timeBeforeRevalidateMilliseconds <= htmlLastModified) {
break break
} }
throw new Error( throw new Error(
`revalidate cache not past ${timeBeforeRevalidateMilliseconds} received time ${jsonLastModified}` `revalidate cache not past ${timeBeforeRevalidateMilliseconds} received time ${htmlLastModified}`
) )
} catch (err) { } catch (err) {
if (lastRetry) { if (lastRetry) {
...@@ -383,7 +384,14 @@ describe('Prerender', () => { ...@@ -383,7 +384,14 @@ describe('Prerender', () => {
await waitFor(2500) await waitFor(2500)
await Promise.all(toBuild.map((pg) => renderViaHTTP(next.url, pg))) if (isDev) {
// Dev requests can concurrently update the prerender manifest.
for (const pg of toBuild) {
await renderViaHTTP(next.url, pg)
}
} else {
await Promise.all(toBuild.map((pg) => renderViaHTTP(next.url, pg)))
}
const browser = await webdriver(next.url, '/') const browser = await webdriver(next.url, '/')
let text = await browser.elementByCss('p').text() let text = await browser.elementByCss('p').text()
...@@ -2445,6 +2453,7 @@ describe('Prerender', () => { ...@@ -2445,6 +2453,7 @@ describe('Prerender', () => {
) )
await waitForCacheWrite( await waitForCacheWrite(
'/blocking-fallback/test-if-generated-2', '/blocking-fallback/test-if-generated-2',
'/blocking-fallback/[slug]',
beforeRevalidate beforeRevalidate
) )
const html = await res.text() const html = await res.text()
......
/* eslint-env jest */ /* eslint-env jest */
import fs from 'fs-extra' import fs from 'fs-extra'
import { getRouteCacheKey } from 'next/dist/server/lib/route-cache-key'
import { RouteKind } from 'next/dist/server/route-kind'
import { join } from 'path' import { join } from 'path'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
...@@ -114,14 +116,26 @@ function runTests(isDev) { ...@@ -114,14 +116,26 @@ function runTests(isDev) {
await check( await check(
() => () =>
fs fs
.exists(join(pagesDir, mode, path + '.html')) .exists(
join(
appDir,
'.next/server',
`${getRouteCacheKey(`/${mode}/${path}`, { kind: RouteKind.PAGES, sourceRoute: `/${mode}/[slug]` })}.html`
)
)
.then((res) => (res ? 'yes' : 'no')), .then((res) => (res ? 'yes' : 'no')),
'yes' 'yes'
) )
await check( await check(
() => () =>
fs fs
.exists(join(pagesDir, mode, path + '.json')) .exists(
join(
appDir,
'.next/server',
`${getRouteCacheKey(`/${mode}/${path}`, { kind: RouteKind.PAGES, sourceRoute: `/${mode}/[slug]` })}.json`
)
)
.then((res) => (res ? 'yes' : 'no')), .then((res) => (res ? 'yes' : 'no')),
'yes' 'yes'
) )
......
/* eslint-env jest */ /* eslint-env jest */
import fs from 'fs-extra' import fs from 'fs-extra'
import { getRouteCacheKey } from 'next/dist/server/lib/route-cache-key'
import { RouteKind } from 'next/dist/server/route-kind'
import { import {
findPort, findPort,
killApp, killApp,
nextBuild, nextBuild,
nextStart, nextStart,
renderViaHTTP, renderViaHTTP,
retry,
waitFor, waitFor,
getPageFileFromPagesManifest,
fetchViaHTTP, fetchViaHTTP,
} from 'next-test-utils' } from 'next-test-utils'
import { join } from 'path' import { join } from 'path'
...@@ -18,15 +20,43 @@ let app ...@@ -18,15 +20,43 @@ let app
let appPort let appPort
let buildId let buildId
function getScopedFile(routePath, extension) {
const cacheKey = getRouteCacheKey(routePath, {
kind: RouteKind.PAGES,
sourceRoute: routePath,
})
return join(appDir, '.next', 'server', `${cacheKey}${extension}`)
}
async function settleScopedResponse(fileName, requestPath, isJson = false) {
const warmStartedAt = Date.now()
await renderViaHTTP(appPort, requestPath)
return retry(
async () => {
const response = await renderViaHTTP(appPort, requestPath)
const file = await fs.readFile(fileName, 'utf8')
const { mtimeMs } = await fs.stat(fileName)
// A promoted build seed keeps its original age. Wait for any stale seed
// regeneration to finish before using the scoped file as the baseline.
expect(mtimeMs).toBeGreaterThanOrEqual(warmStartedAt)
expect(file).not.toBe('')
if (isJson) {
expect(JSON.parse(response)).toEqual(JSON.parse(file))
} else {
expect(response).toBe(file)
}
return file
},
15000,
500
)
}
function runTests(route, routePath) { function runTests(route, routePath) {
it(`[${route}] should regenerate page when revalidate time exceeded`, async () => { it(`[${route}] should regenerate page when revalidate time exceeded`, async () => {
const fileName = join( const fileName = getScopedFile(routePath, '.html')
appDir, const initialHtmlFile = await settleScopedResponse(fileName, route)
'.next',
'server',
getPageFileFromPagesManifest(appDir, routePath).replace('.js', '.html')
)
const initialHtmlFile = await fs.readFile(fileName, 'utf8')
await waitFor(1000) // Wait revalidate duration await waitFor(1000) // Wait revalidate duration
...@@ -40,14 +70,9 @@ function runTests(route, routePath) { ...@@ -40,14 +70,9 @@ function runTests(route, routePath) {
}) })
it(`[${route}] should regenerate /_next/data when revalidate time exceeded`, async () => { it(`[${route}] should regenerate /_next/data when revalidate time exceeded`, async () => {
const fileName = join( const fileName = getScopedFile(routePath, '.json')
appDir,
'.next',
'server',
getPageFileFromPagesManifest(appDir, routePath).replace('.js', '.json')
)
const route = join(`/_next/data/${buildId}`, `${routePath}.json`) const route = join(`/_next/data/${buildId}`, `${routePath}.json`)
const initialFileJson = await fs.readFile(fileName, 'utf8') const initialFileJson = await settleScopedResponse(fileName, route, true)
await waitFor(1000) // Wait revalidate duration await waitFor(1000) // Wait revalidate duration
......
/* eslint-env jest */ /* eslint-env jest */
import cheerio from 'cheerio' import cheerio from 'cheerio'
import { getRouteCacheKey } from 'next/dist/server/lib/route-cache-key'
import { RouteKind } from 'next/dist/server/route-kind'
import cookie from 'cookie' import cookie from 'cookie'
import fs from 'fs-extra' import fs from 'fs-extra'
import { join } from 'path' import { join } from 'path'
...@@ -239,7 +241,13 @@ function runTests(isDev) { ...@@ -239,7 +241,13 @@ function runTests(isDev) {
}) })
if (!isDev) { if (!isDev) {
const fsHtml = await fs.readFile(getCacheFile('fallback/second.html')) const fsHtml = await fs.readFile(
join(
appDir,
'.next/server',
`${getRouteCacheKey('/fallback/second', { kind: RouteKind.PAGES, sourceRoute: '/fallback/[post]' })}.html`
)
)
const fsProps = JSON.parse(cheerio.load(fsHtml)('#props').text()) const fsProps = JSON.parse(cheerio.load(fsHtml)('#props').text())
expect(fsProps).toEqual({ expect(fsProps).toEqual({
......
...@@ -7,6 +7,11 @@ import { FileRef, isNextDeploy } from '../e2e-utils' ...@@ -7,6 +7,11 @@ import { FileRef, isNextDeploy } from '../e2e-utils'
import { ChildProcess } from 'child_process' import { ChildProcess } from 'child_process'
import { createNextInstall } from '../create-next-install' import { createNextInstall } from '../create-next-install'
import { Span } from 'next/dist/trace' import { Span } from 'next/dist/trace'
import { normalizePagePath } from 'next/dist/shared/lib/page-path/normalize-page-path'
import {
getRouteCacheKey,
type ResponseCacheOwner,
} from 'next/dist/server/lib/route-cache-key'
import webdriver from '../next-webdriver' import webdriver from '../next-webdriver'
import { renderViaHTTP, fetchViaHTTP, findPort } from 'next-test-utils' import { renderViaHTTP, fetchViaHTTP, findPort } from 'next-test-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
...@@ -559,6 +564,31 @@ export class NextInstance { ...@@ -559,6 +564,31 @@ export class NextInstance {
return existsSync(path.join(this.testDir, filename)) return existsSync(path.join(this.testDir, filename))
} }
/** Resolve a response artifact without assuming the cache key is its URL. */
public getPrerenderFilePath(
pathname: string,
extension: string,
{
router = 'app',
distDir = '.next',
route,
}: {
router?: 'app' | 'pages'
distDir?: string
/** Supply the source for an entry generated only at runtime. */
route?: ResponseCacheOwner
} = {}
): string {
pathname = `/${pathname.replace(/^\/+/, '')}`
const cacheKey = route ? getRouteCacheKey(pathname, route) : undefined
const filename = normalizePagePath(pathname)
return path.join(
distDir,
'server',
`${cacheKey ?? `/${router}${filename}`}${extension}`
)
}
public async readFile(filename: string) { public async readFile(filename: string) {
return fs.readFile(path.join(this.testDir, filename), 'utf8') return fs.readFile(path.join(this.testDir, filename), 'utf8')
} }
......
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
import type { NextAdapter } from 'next'
import { RouteKind } from 'next/dist/server/route-kind'
describe('adapter config with i18n response artifacts', () => {
const { next } = nextTestSetup({ files: __dirname })
it.each(['en', 'fr'])(
'resolves %s prerenders and fallback shells to scoped files',
async (locale) => {
const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
await next.readJSON('build-complete.json')
for (const [suffix, sourceRoute] of [
['fallback/first', '/fallback/[slug]'],
['fallback/[slug]', '/fallback/[slug]'],
]) {
const pathname = `/${locale}/${suffix}`
const output = outputs.find((item) => item.pathname === pathname)
const artifact = next.getPrerenderFilePath(pathname, '.html', {
router: 'pages',
route: { kind: RouteKind.PAGES, sourceRoute },
})
// Next 15 has no localized fallback outputs in its flat adapter schema.
// Assert the emitted positive route and both localized build shell files.
if (!suffix.includes('[slug]')) {
expect(output?.fallback?.filePath).toBe(
path.join(next.testDir, artifact)
)
}
expect(await next.hasFile(artifact)).toBe(true)
expect(await next.hasFile(artifact.replace(/\.html$/, '.meta'))).toBe(
true
)
if (!suffix.includes('[slug]'))
expect(await next.hasFile(artifact.replace(/\.html$/, '.json'))).toBe(
true
)
for (const extension of ['.html', '.json', '.meta']) {
expect(
await next.hasFile(`.next/server/pages${pathname}${extension}`)
).toBe(false)
}
}
}
)
})
import fs from 'fs/promises'
// @ts-check
/** @type {import('next').NextAdapter} */
const adapter = {
name: 'i18n-test-adapter',
async onBuildComplete(ctx) {
await fs.writeFile('build-complete.json', JSON.stringify(ctx, null, 2))
},
}
export default adapter
import Module from 'module'
const require = Module.createRequire(import.meta.url)
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: { cpus: 2, adapterPath: require.resolve('./my-adapter.mjs') },
i18n: {
locales: ['en', 'fr'],
defaultLocale: 'en',
},
}
export default nextConfig
export function getStaticPaths() {
return {
paths: ['en', 'fr'].map((locale) => ({
params: { slug: 'first' },
locale,
})),
fallback: true,
}
}
export function getStaticProps({ params, locale }) {
return { props: { slug: params.slug, locale } }
}
export default function Page({ slug, locale }) {
return (
<p>
{locale}: {slug}
</p>
)
}
import fs from 'fs' import fs from 'fs'
import path from 'path'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import type { NextAdapter } from 'next' import type { NextAdapter } from 'next'
import { AdapterOutputType } from 'next/constants' import { AdapterOutputType } from 'next/constants'
import { RouteKind } from 'next/dist/server/route-kind'
describe('adapter-config', () => { describe('adapter-config', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -113,4 +115,78 @@ describe('adapter-config', () => { ...@@ -113,4 +115,78 @@ describe('adapter-config', () => {
headers: expect.toBeArray(), headers: expect.toBeArray(),
}) })
}) })
it('uses scoped build files for response artifacts', async () => {
const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
await next.readJSON('build-complete.json')
for (const [pathname, router, extension, route, sidecar] of [
[
'/grouped',
'app',
'.html',
{ kind: RouteKind.APP_PAGE, sourceRoute: '/(group)/grouped/page' },
'.rsc',
],
[
'/isr-app/first',
'app',
'.html',
{ kind: RouteKind.APP_PAGE, sourceRoute: '/isr-app/[slug]/page' },
'.rsc',
],
[
'/isr-route/first',
'app',
'.body',
{ kind: RouteKind.APP_ROUTE, sourceRoute: '/isr-route/[slug]/route' },
undefined,
],
[
'/isr-pages/first',
'pages',
'.html',
{ kind: RouteKind.PAGES, sourceRoute: '/isr-pages/[slug]' },
'.json',
],
[
'/isr-pages-fallback-true/[slug]',
'pages',
'.html',
{
kind: RouteKind.PAGES,
sourceRoute: '/isr-pages-fallback-true/[slug]',
},
undefined,
],
] as const) {
const output = outputs.find(
(item) =>
item.type === AdapterOutputType.PRERENDER &&
item.pathname === pathname
)
const artifact = next.getPrerenderFilePath(pathname, extension, {
router,
route,
})
expect(output?.fallback?.filePath).toBe(path.join(next.testDir, artifact))
expect(await next.hasFile(artifact)).toBe(true)
expect(
await next.hasFile(`.next/server/${router}${pathname}${extension}`)
).toBe(false)
expect(await next.hasFile(`.next/server/${router}${pathname}.meta`)).toBe(
false
)
expect(
await next.hasFile(artifact.replace(/\.(?:html|body)$/, '.meta'))
).toBe(true)
if (sidecar) {
expect(
await next.hasFile(artifact.replace(/\.(?:html|body)$/, sidecar))
).toBe(true)
expect(
await next.hasFile(`.next/server/${router}${pathname}${sidecar}`)
).toBe(false)
}
}
})
}) })
export default function Page() {
return <p>grouped prerender</p>
}
import { RouteKind } from 'next/dist/server/route-kind'
import { nextTestSetup } from 'e2e-utils'
describe.each([false, true])(
'route-scoped-cache parallel closed route (adapter %s)',
(adapter) => {
const { next, skipped } = nextTestSetup({
// Inspects local artifacts and the experimental adapter output.
skipDeployment: true,
files: {
'next.config.js': `module.exports = { cacheMaxMemorySize: 0, experimental: { cpus: 2, cacheComponents: false, ppr: false, ${adapter ? "adapterPath: require.resolve('./adapter.mjs')" : ''} } }`,
'adapter.mjs': `import fs from 'fs'; export default { name: 'test', async onBuildComplete(ctx) { await fs.promises.writeFile('outputs.json', JSON.stringify(ctx.outputs)) } }`,
'app/layout.js':
'export default function Layout({children}) { return <html><body>{children}</body></html> }',
'app/stories/layout.js':
'export default function Layout({children, slot}) { return <>{slot}{children}</> }',
'app/stories/[slug]/page.js': `
export const dynamicParams = false
export function generateStaticParams() { return [{slug: 'known'}] }
export default async function Page({params}) { return <main>story:{(await params).slug}</main> }
`,
'app/stories/@slot/[slug]/page.js': `
export const dynamicParams = false
export function generateStaticParams() { return [{slug: 'known'}] }
export default function Page() { return <aside>slot</aside> }
`,
'app/stories/@slot/default.js':
'export default function Page() { return null }',
},
})
if (skipped) return
it('admits the listed closed route with the runtime root owner', async () => {
const meta = await next.readJSON(
next.getPrerenderFilePath('/stories/known', '.meta', {
route: adapter
? { kind: RouteKind.APP_PAGE, sourceRoute: '/stories/[slug]/page' }
: undefined,
})
)
expect(meta.routeCache.owner).toEqual({
kind: 'APP_PAGE',
sourceRoute: '/stories/[slug]/page',
})
if (adapter) {
const outputs = await next.readJSON('outputs.json')
const entries = outputs.filter(
(output) =>
output.pathname === '/stories/[slug]' && output.type === 'APP_PAGE'
)
expect(entries).toHaveLength(1)
expect(entries[0].filePath).toEndWith('/app/stories/[slug]/page.js')
expect(Object.values(entries[0].assets)).toContainEqual(
expect.stringContaining('/app/stories/@slot/[slug]/page.js')
)
}
for (let i = 0; i < 2; i++) {
const response = await next.fetch('/stories/known')
expect(response.status).toBe(200)
expect(await response.text()).toContain('story:')
}
expect((await next.fetch('/stories/unknown')).status).toBe(404)
})
}
)
import { Suspense } from 'react'
import { Content, Dynamic } from '../../lib/state'
export function generateStaticParams() {
return [{ slug: ['warmup'] }]
}
export default function Page({ params }) {
return (
<>
<h1 id="shell">catchall-shell</h1>
<Suspense fallback="loading">
<Content route="ppr-catchall" params={params} />
</Suspense>
<Suspense fallback="dynamic">
<Dynamic />
</Suspense>
</>
)
}
import { revalidatePath, revalidateTag } from 'next/cache'
export async function POST(request) {
const { item } = await request.json()
if (typeof item !== 'string' || !/^[a-z-]+$/.test(item))
return new Response(null, { status: 400 })
revalidateTag(`state:ppr-catalog:${item}`)
revalidatePath(`/catalog/a/${item}`)
return Response.json({ revalidated: true })
}
import { Suspense } from 'react'
import { Content, Dynamic } from '../../../../lib/state'
export function generateStaticParams() {
return [{ item: 'known' }, { item: 'seed-cold' }, { item: 'seed-warm' }]
}
export default function Page({ params }) {
return (
<>
<h1 id="shell">catalog-shell</h1>
<Suspense fallback="loading">
<Content route="ppr-catalog" params={params} />
</Suspense>
<Suspense fallback="dynamic">
<Dynamic />
</Suspense>
</>
)
}
export function generateStaticParams() {
return [{ category: 'a' }, { category: 'b' }]
}
export default function Layout({ children }) {
return children
}
import { sharedData } from '../../lib/state'
export default async function Page() {
return <p id="shared-data">{await sharedData()}</p>
}
import { sharedData } from '../../lib/state'
export default async function Page() {
return <p id="shared-data">{await sharedData()}</p>
}
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>ppr-home</p>
}
import { Suspense } from 'react'
import { Content, Dynamic } from '../../../../lib/state'
export default function Page({ params }) {
return (
<>
<h1 id="shell">shared-shell</h1>
<Suspense fallback="loading">
<Content route="ppr-shared" params={params} />
</Suspense>
<Suspense fallback="dynamic">
<Dynamic />
</Suspense>
</>
)
}
export function generateStaticParams() {
return [{ category: 'a' }, { category: 'b' }]
}
export default function Layout({ children }) {
return children
}
import { randomUUID } from 'node:crypto'
import {
unstable_cacheLife as cacheLife,
unstable_cacheTag as cacheTag,
} from 'next/cache'
import { connection } from 'next/server'
export async function cachedState(route, params) {
'use cache'
cacheLife({
stale: 30,
revalidate: params.item?.startsWith('fast-') ? 1 : 3600,
expire: 7200,
})
cacheTag(`state:${route}:${params.item || 'shell'}`)
return { route, params, generation: randomUUID() }
}
export async function Content({ route, params }) {
return (
<pre id="route-state">
{JSON.stringify(await cachedState(route, await params))}
</pre>
)
}
export async function Dynamic() {
await connection()
return <pre id="dynamic-state">{randomUUID()}</pre>
}
export async function sharedData() {
'use cache'
cacheLife('max')
return randomUUID()
}
module.exports = {
experimental: { cpus: 2, cacheComponents: true, ppr: true },
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { load } from 'cheerio'
import { RouteKind } from 'next/dist/server/route-kind'
describe('route-scoped-cache with PPR', () => {
const { next, isNextDeploy } = nextTestSetup({ files: __dirname })
async function read(pathname: string) {
const response = await next.fetch(pathname)
expect(response.status).toBe(200)
const $ = load(await response.text())
return {
state: JSON.parse($('#route-state').text()),
shell: $('#shell').text(),
dynamic: $('#dynamic-state').text(),
}
}
async function prefetch(pathname: string) {
const response = await next.fetch(pathname, {
headers: {
RSC: '1',
'Next-Router-Prefetch': '1',
},
})
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toContain('text/x-component')
return response.text()
}
it('normal: emits PPR shells and prefetch payloads as historical build seeds', async () => {
const pathname = '/catalog/a/known'
if (isNextDeploy) {
expect((await read(pathname)).shell).toBe('catalog-shell')
expect(await prefetch(pathname)).toContain('catalog-shell')
return
}
expect(
await next.readJSON('.next/prerender-manifest.json')
).not.toHaveProperty('cacheKeys')
const legacyPath = `.next/server/app${pathname}`
const metadata = await next.readJSON(
next.getPrerenderFilePath(pathname, '.meta')
)
// Next 15 stores a full PPR prefetch payload beside the shell.
const extensions = ['.html', '.meta', '.prefetch.rsc']
expect(metadata.postponed).toBeDefined()
for (const filename of [`${legacyPath}.rsc`]) {
await expect(next.readFile(filename)).rejects.toMatchObject({
code: 'ENOENT',
})
}
for (const extension of extensions) {
expect(
await next.hasFile(next.getPrerenderFilePath(pathname, extension))
).toBe(true)
}
expect(metadata.routeCache).toEqual(
expect.objectContaining({
key: expect.stringMatching(/^\/route-cache\//),
owner: expect.objectContaining({ sourceRoute: expect.any(String) }),
isFallback: false,
})
)
expect((await read(pathname)).shell).toBe('catalog-shell')
for (const extension of extensions) {
expect(
await next.hasFile(
next.getPrerenderFilePath(pathname, extension, {
route: {
kind: RouteKind.APP_PAGE,
sourceRoute: '/catalog/[category]/[item]/page',
},
})
)
).toBe(true)
}
})
it.each(['known', 'normal-runtime'])(
'normal: reuses the %s shell and resumes fresh dynamic content',
async (item) => {
const path = `/catalog/a/${item}`
const first = await read(path)
const hit = await read(path)
expect(first.state.route).toBe('ppr-catalog')
expect(first.state.params).toEqual({ category: 'a', item })
expect(hit.state).toEqual(first.state)
expect(first.shell).toBe('catalog-shell')
expect(hit.shell).toBe('catalog-shell')
expect(first.dynamic).not.toBe('')
expect(hit.dynamic).not.toBe(first.dynamic)
}
)
it('normal: keeps parameter variants distinct', async () => {
const a = await read('/catalog/a/params')
const b = await read('/catalog/b/params')
expect(a.state.params).toEqual({ category: 'a', item: 'params' })
expect(b.state.params).toEqual({ category: 'b', item: 'params' })
expect(a.state.generation).not.toBe(b.state.generation)
})
it('normal: serves a partial shell without mixing its dynamic parameters', async () => {
for (const item of ['one', 'two']) {
const result = await read(`/shared/a/${item}`)
expect(result.shell).toBe('shared-shell')
expect(result.state.route).toBe('ppr-shared')
expect(result.state.params).toEqual({ category: 'a', item })
// Next 15's full prefetch payload embeds the selected parameters. It
// cannot be byte-identical across parameter variants like canary's shell.
const payload = await prefetch(`/shared/a/${item}`)
expect(payload).toContain('shared-shell')
expect(payload).toContain(result.state.generation)
expect(payload).toContain(
JSON.stringify(JSON.stringify({ category: 'a', item })).slice(1, -1)
)
}
})
it('normal: preserves HTML, RSC navigation and PPR prefetch', async () => {
const pathname = '/catalog/a/known'
const html = await read(pathname)
const rsc = await next.fetch(pathname, { headers: { RSC: '1' } })
expect(rsc.status).toBe(200)
expect(rsc.headers.get('content-type')).toContain('text/x-component')
// A dynamic navigation can regenerate use-cache data in this process;
// its UUID need not equal the data embedded during the build.
const navigation = await rsc.text()
expect(navigation).toContain('ppr-catalog')
expect(navigation).toContain('known')
expect(navigation).not.toContain('ppr-catchall')
const shell = await prefetch(pathname)
expect(shell).toContain('catalog-shell')
expect(shell).toContain(html.state.generation)
expect(await prefetch(pathname)).toBe(shell)
})
it('normal: refreshes a runtime-created shell after its cache lifetime', async () => {
const first = await read('/catalog/a/fast-runtime')
await retry(async () => {
const current = await read('/catalog/a/fast-runtime')
expect(current.state.route).toBe('ppr-catalog')
expect(current.state.generation).not.toBe(first.state.generation)
}, 45000)
})
it('normal: revalidates cached data and its route shell through public APIs', async () => {
const path = '/catalog/a/on-demand'
const before = await read(path)
await retry(async () => {
expect(await prefetch(path)).toContain(before.state.generation)
})
const result = await next.fetch('/api/revalidate', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ item: 'on-demand' }),
})
expect(result.status).toBe(200)
await retry(async () => {
const after = await read(path)
expect(after.state.route).toBe('ppr-catalog')
expect(after.state.generation).not.toBe(before.state.generation)
expect(await prefetch(path)).toContain(after.state.generation)
})
})
it('normal: keeps intentionally shared use-cache data shared across routes', async () => {
const a = await next.render$('/data-a')
const b = await next.render$('/data-b')
expect(a('#shared-data').text()).not.toBe('')
expect(b('#shared-data').text()).toBe(a('#shared-data').text())
})
it.each(['cold', 'warm', 'seed-cold', 'seed-warm'])(
'security: isolates a catalog shell from the catch-all (%s)',
async (order) => {
const item = order.startsWith('seed-') ? order : `collision-${order}`
const canonical = `/catalog/a/${item}`
const alias = `/%63atalog/a/${item}`
if (order.endsWith('warm')) {
expect((await read(canonical)).state.route).toBe('ppr-catalog')
}
const encoded = await read(alias)
expect(
isNextDeploy ? ['ppr-catchall', 'ppr-catalog'] : ['ppr-catchall']
).toContain(encoded.state.route)
const ordinary = await read(canonical)
expect(ordinary.state.route).toBe('ppr-catalog')
expect(ordinary.state.params).toEqual({ category: 'a', item })
expect(ordinary.shell).toBe('catalog-shell')
expect((await read(alias)).state.route).toBe(encoded.state.route)
expect((await read(canonical)).state).toEqual(ordinary.state)
// The RSC lookup can bypass the normal response-cache entry point.
expect(await prefetch(canonical)).toContain('catalog-shell')
expect(await prefetch(canonical)).not.toContain('catchall-shell')
expect(await prefetch(alias)).toContain(encoded.shell)
const navigation = await next.fetch(alias, { headers: { RSC: '1' } })
expect(navigation.status).toBe(200)
expect(navigation.headers.get('content-type')).toContain(
'text/x-component'
)
expect(await navigation.text()).toContain(encoded.state.route)
}
)
it('security: keeps a shared partial shell with its source route', async () => {
const alias = await read('/%73hared/a/alias')
expect(
isNextDeploy ? ['ppr-catchall', 'ppr-shared'] : ['ppr-catchall']
).toContain(alias.state.route)
for (const item of ['alias', 'sibling']) {
const result = await read(`/shared/a/${item}`)
expect(result.shell).toBe('shared-shell')
expect(result.state.route).toBe('ppr-shared')
expect(result.state.params).toEqual({ category: 'a', item })
expect(await prefetch(`/shared/a/${item}`)).toContain('shared-shell')
}
})
})
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
}
import { nextTestSetup } from 'e2e-utils'
import {
fetchViaHTTP,
findPort,
initNextServerScript,
killApp,
retry,
} from 'next-test-utils'
import { load } from 'cheerio'
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import type { ChildProcess } from 'node:child_process'
describe('route-scoped-cache standalone', () => {
const { next, skipped } = nextTestSetup({
files: path.join(__dirname, '../route-scoped-cache'),
skipStart: true,
// Tests the self-hosted standalone distribution after moving it outside
// the original build tree; a hosted deployment has no such launcher.
skipDeployment: true,
env: { STANDALONE: '1', CACHE_STORAGE: 'disk' },
})
if (skipped) return
let directory: string
let server: ChildProcess
let port: number
function serverAddress() {
return `http://127.0.0.1:${port}`
}
async function start() {
port = await findPort()
server = await initNextServerScript(
path.join(directory, 'server.js'),
/- Local:/,
{
...process.env,
PORT: String(port),
HOSTNAME: '127.0.0.1',
},
undefined,
{ cwd: directory }
)
}
async function read(pathname: string) {
const response = await fetchViaHTTP(serverAddress(), pathname)
expect(response.status).toBe(200)
const body = await response.text()
return response.headers.get('content-type')?.includes('application/json')
? JSON.parse(body)
: JSON.parse(load(body)('#route-state').text())
}
beforeAll(async () => {
const { exitCode } = await next.build()
if (exitCode !== 0) throw new Error(`Fixture build failed: ${exitCode}`)
directory = await fs.mkdtemp(
path.join(os.tmpdir(), 'route-scoped-standalone-')
)
await fs.copy(path.join(next.testDir, '.next/standalone'), directory)
await fs.copy(
path.join(next.testDir, '.next/static'),
path.join(directory, '.next/static')
)
await fs.copy(
path.join(next.testDir, 'public'),
path.join(directory, 'public')
)
await start()
})
afterAll(async () => {
if (server) await killApp(server)
if (directory) await fs.remove(directory)
})
it.each([
['/pages-victim/known', 'pages-victim'],
['/fr/pages-victim/known', 'pages-victim'],
['/app-victim/known', 'app-victim'],
['/api/victim/known', 'route-victim'],
['/source-hash/known', 'app-long-source'],
])(
'normal: includes the prebuilt response for %s',
async (pathname, route) => {
const response = await read(pathname)
expect(response.route).toBe(route)
expect(response.params.id).toBe('known')
expect(await read(pathname)).toEqual(response)
}
)
it('normal: includes static Pages and public files', async () => {
expect(await (await fetchViaHTTP(serverAddress(), '/')).text()).toContain(
'static-home'
)
expect(
await (await fetchViaHTTP(serverAddress(), '/plain.txt')).text()
).toBe('public-file\n')
})
it('normal: writes runtime cache entries that survive restarting the standalone server', async () => {
const before = await read('/pages-victim/runtime')
expect(before.route).toBe('pages-victim')
await killApp(server)
await start()
expect(await read('/pages-victim/runtime')).toEqual(before)
})
it('normal: revalidates using the public pathname in the standalone server', async () => {
const before = await read('/pages-victim/on-demand')
const response = await fetchViaHTTP(
serverAddress(),
'/api/revalidate',
undefined,
{
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ pathname: '/pages-victim/on-demand' }),
}
)
expect(response.status).toBe(200)
await retry(async () => {
const current = await read('/pages-victim/on-demand')
expect(current.route).toBe('pages-victim')
expect(current.generation).not.toBe(before.generation)
})
})
it.each([
['/%70ages-victim', '/pages-victim', 'pages-catchall', 'pages-victim'],
['/%61pp-victim', '/app-victim', 'pages-catchall', 'app-victim'],
[
'/app-only/%76ictim',
'/app-only/victim',
'app-catchall',
'app-only-victim',
],
['/%61pi/victim', '/api/victim', 'pages-catchall', 'route-victim'],
])(
'security: isolates %s in the standalone distribution',
async (alias, canonical, aliasOwner, owner) => {
const first = await read(`${alias}/standalone`)
expect(first.route).toBe(aliasOwner)
const second = await read(`${canonical}/standalone`)
expect(second.route).toBe(owner)
expect(await read(`${alias}/standalone`)).toEqual(first)
expect(await read(`${canonical}/standalone`)).toEqual(second)
}
)
})
describe('route-scoped-cache minimal-mode handler contract', () => {
const { next, skipped } = nextTestSetup({
files: path.join(__dirname, '../route-scoped-cache'),
// This harness supplies trusted adapter routing metadata locally. Hosted
// platforms perform their own route selection and filter client headers.
skipDeployment: true,
startCommand: 'node minimal-server.js',
serverReadyPattern: /minimal server ready/,
})
if (skipped) return
it.each([
['allowed', 200],
['not-found', 404],
])(
'normal: preserves the App Handler publication allowlist for %s',
async (id, status) => {
const response = await next.fetch(`/api-admission/${id}`, {
headers: { 'x-matched-path': '/api-admission/[...slug]' },
})
expect(response.status).toBe(status)
expect((await response.json()).route).toBe('route-admission-closed')
}
)
it.each(['published', 'not-found'])(
'security: App Handler publication allowlist declines sibling admission for %s',
async (id) => {
const response = await next.fetch(`/api-admission/sibling/${id}`, {
headers: { 'x-matched-path': '/api-admission/[...slug]' },
})
expect(response.status).toBe(500)
expect(await response.text()).toBe('Internal Server Error')
}
)
it.each([
['/pages-victim/minimal', '/[...slug]', 'pages-catchall'],
['/pages-victim/minimal', '/pages-victim/[id]', 'pages-victim'],
['/closed/allowed', '/closed/[...slug]', 'pages-closed-catchall'],
['/fr/closed/allowed', '/closed/[...slug]', 'pages-closed-catchall'],
['/app-victim/minimal', '/[...slug]', 'pages-catchall'],
['/app-victim/minimal', '/app-victim/[id]', 'app-victim'],
['/app-only/victim/minimal', '/app-only/[...slug]', 'app-catchall'],
['/app-only/victim/minimal', '/app-only/victim/[id]', 'app-only-victim'],
])(
'normal: honors the selected route %s → %s',
async (pathname, selected, owner) => {
const states = []
for (let i = 0; i < 2; i++) {
const response = await next.fetch(pathname, {
headers: {
'x-matched-path': selected,
'x-invocation-id': 'shared-invocation',
},
})
expect(response.status).toBe(200)
const state = JSON.parse(
load(await response.text())('#route-state').text()
)
expect(state.route).toBe(owner)
states.push(state)
}
expect(states[1]).toEqual(states[0])
}
)
it.each(['', '/fr'])(
"normal: serves the closed route's own negative entry in locale %s",
async (locale) => {
const response = await next.fetch(`${locale}/closed/not-found`, {
headers: { 'x-matched-path': '/closed/[...slug]' },
})
expect(response.status).toBe(404)
}
)
it.each(
['', '/fr'].flatMap((locale) =>
['published', 'not-found'].map((id) => `${locale}/closed/sibling/${id}`)
)
)(
'security: the selected closed route declines sibling admission for %s',
async (pathname) => {
const response = await next.fetch(pathname, {
headers: { 'x-matched-path': '/closed/[...slug]' },
})
// This minimal harness maps a thrown NoFallbackError to 500. A real
// adapter handles that signal at its route boundary. The closed route
// must decline rather than render the excluded parameters.
expect(response.status).toBe(500)
expect(await response.text()).toBe('Internal Server Error')
}
)
})
This diff is collapsed.
import { state, State } from '../../../../lib/state'
export const revalidate = 3600
export function generateStaticParams() {
return [{ id: 'known' }]
}
export default async function Page({ params }) {
return <State value={state('app-grouped', await params)} />
}
import { state, State } from '../../../../lib/state'
export const revalidate = 3600
export function generateStaticParams() {
return [{ id: 'known' }]
}
export default async function Page({ params }) {
return <State value={state('app-long-source', await params)} />
}
import { state } from '../../../lib/state'
export const dynamic = 'force-static'
export const dynamicParams = false
export const revalidate = false
export function generateStaticParams() {
return ['allowed', 'not-found'].map((slug) => ({ slug: [slug] }))
}
export async function GET(_request, { params }) {
const resolved = await params
return Response.json(state('route-admission-closed', resolved), {
status: resolved.slug[0] === 'not-found' ? 404 : 200,
headers: { 'x-fixture-route': 'route-admission-closed' },
})
}
import { state } from '../../../../lib/state'
export const dynamic = 'force-static'
export const dynamicParams = false
export const revalidate = false
export function generateStaticParams() {
return ['published', 'not-found'].map((id) => ({ id }))
}
export async function GET(_request, { params }) {
const resolved = await params
return Response.json(state('route-admission-sibling', resolved), {
status: resolved.id === 'not-found' ? 404 : 200,
headers: { 'x-fixture-route': 'route-admission-sibling' },
})
}
import { state } from '../../../lib/state'
export const dynamic = 'force-dynamic'
export async function GET(_request, { params }) {
return Response.json(state('route-dynamic-catchall', await params))
}
import { state } from '../../../lib/state'
export const dynamic = 'force-static'
export function GET() {
return Response.json(state('route-dynamic-sibling'))
}
import { revalidatePath } from 'next/cache'
export async function POST(request) {
const { pathname } = await request.json()
if (typeof pathname !== 'string' || !pathname.startsWith('/app-victim/'))
return new Response(null, { status: 400 })
revalidatePath(pathname)
return Response.json({ revalidated: true })
}
import { state } from '../../../../lib/state'
export const dynamic = 'force-static'
export const revalidate = 3600
export function generateStaticParams() {
return ['known', 'seed-cold', 'seed-warm'].map((id) => ({ id }))
}
export async function GET(_request, { params }) {
return Response.json(state('route-victim', await params), {
headers: { 'x-fixture-route': 'route-victim' },
})
}
import { notFound } from 'next/navigation'
import { state, State } from '../../../lib/state'
export const dynamicParams = false
export const revalidate = false
export function generateStaticParams() {
return ['allowed', 'not-found'].map((slug) => ({ slug: [slug] }))
}
export default async function Page({ params }) {
const resolved = await params
if (resolved.slug[0] === 'not-found') notFound()
return <State value={state('app-admission-closed', resolved)} />
}
import { notFound } from 'next/navigation'
import { state, State } from '../../../../lib/state'
export const dynamicParams = false
export const revalidate = false
export function generateStaticParams() {
return ['published', 'not-found'].map((id) => ({ id }))
}
export default async function Page({ params }) {
const resolved = await params
if (resolved.id === 'not-found') notFound()
return <State value={state('app-admission-sibling', resolved)} />
}
import { state, State } from '../../../lib/state'
export const revalidate = 3600
export const dynamicParams = false
export function generateStaticParams() {
return ['known', 'seed-cold', 'seed-warm'].map((id) => ({ id }))
}
export default async function Page({ params }) {
return <State value={state('app-closed', await params)} />
}
import { state, State } from '../../../lib/state'
export const dynamic = 'force-dynamic'
export default async function Page({ params }) {
return <State value={state('app-dynamic-catchall', await params)} />
}
import { state, State } from '../../../lib/state'
export const dynamic = 'force-static'
export default function Page() {
return <State value={state('app-dynamic-sibling')} />
}
import { state, State } from '../../../lib/state'
export const revalidate = 1
export function generateStaticParams() {
return ['known', 'seed-cold', 'seed-warm'].map((id) => ({ id }))
}
export default async function Page({ params }) {
return <State value={state('app-fast', await params)} />
}
import { state, State } from '../../../lib/state'
export const revalidate = 3600
export function generateStaticParams() {
return []
}
export default async function Page({ params }) {
return <State value={state('app-catchall', await params)} />
}
import { state, State } from '../../../../lib/state'
export const revalidate = 3600
export const dynamicParams = false
export function generateStaticParams() {
return ['known', 'seed-cold', 'seed-warm'].map((id) => ({ id }))
}
export default async function Page({ params }) {
return <State value={state('app-only-closed', await params)} />
}
import { state, State } from '../../../../lib/state'
export const revalidate = 3600
export function generateStaticParams() {
return ['known', 'seed-cold', 'seed-warm'].map((id) => ({ id }))
}
export default async function Page({ params }) {
return <State value={state('app-only-victim', await params)} />
}
import { state, State } from '../../../lib/state'
export const revalidate = 3600
export function generateStaticParams() {
return ['known', 'seed-cold', 'seed-warm'].map((id) => ({ id }))
}
export default async function Page({ params }) {
return <State value={state('app-victim', await params)} />
}
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
const fs = require('node:fs')
const path = require('node:path')
const FileSystemCache =
require('next/dist/server/lib/incremental-cache/file-system-cache').default
// Exercise the public handler calls using keys as opaque strings. Delegate value
// formats, expiration and tags to Next's existing handler instead of replicating it.
module.exports = class RecordingCacheHandler extends FileSystemCache {
record(operation, key, value, context) {
if (value?.kind === 'FETCH') return
const body = value?.kind === 'PAGES' ? value.pageData?.pageProps : undefined
fs.appendFileSync(
path.join(process.cwd(), 'cache-operations.jsonl'),
JSON.stringify({
operation,
key,
kind: value?.kind,
hasRouteContext: 'route' in context,
route: body?.route,
params: body?.params,
}) + '\n'
)
}
async get(key, context) {
const value = await super.get(key, context)
if (context.kind !== 'FETCH') this.record('get', key, value?.value, context)
return value
}
async set(key, value, context) {
if (!context.fetchCache) this.record('set', key, value, context)
return super.set(key, value, context)
}
}
export function state(route, params = {}, locale = null) {
return { route, params, locale, generation: crypto.randomUUID() }
}
export function State({ value }) {
return <pre id="route-state">{JSON.stringify(value)}</pre>
}
const http = require('node:http')
require('next/dist/server/node-environment')
require('next/dist/server/require-hook')
require('next/dist/server/node-polyfill-crypto')
const { addRequestMeta } = require('next/dist/server/request-meta')
const {
getRouteRegex,
} = require('next/dist/shared/lib/router/utils/route-regex')
const {
getRouteMatcher,
} = require('next/dist/shared/lib/router/utils/route-matcher')
const routes = {
'/[...slug]': require('./.next/server/pages/[...slug].js'),
'/pages-victim/[id]': require('./.next/server/pages/pages-victim/[id].js'),
'/closed/[...slug]': require('./.next/server/pages/closed/[...slug].js'),
'/api-admission/[...slug]': require('./.next/server/app/api-admission/[...slug]/route.js'),
'/app-victim/[id]': require('./.next/server/app/app-victim/[id]/page.js'),
'/app-only/[...slug]': require('./.next/server/app/app-only/[...slug]/page.js'),
'/app-only/victim/[id]': require('./.next/server/app/app-only/victim/[id]/page.js'),
}
// A test adapter supplies the trusted route selection. This deliberately does
// not rerun next start's router before invoking the selected compiled handler.
const server = http.createServer((req, res) => {
const route = routes[req.headers['x-matched-path']]
if (!route) {
res.statusCode = 404
res.end()
return
}
// Next 15 adapters supply the matched params to App handlers; their full
// module names still include /page or /route at this entrypoint.
const pathname =
new URL(req.url, 'http://localhost').pathname.replace(
/^\/(en|fr)(?=\/|$)/,
''
) || '/'
const params = getRouteMatcher(getRouteRegex(req.headers['x-matched-path']))(
pathname
)
if (params) addRequestMeta(req, 'params', params)
addRequestMeta(req, 'minimalMode', true)
addRequestMeta(req, 'relativeProjectDir', '.')
addRequestMeta(req, 'initURL', `http://localhost${req.url}`)
Promise.resolve(route.handler(req, res, { waitUntil() {} })).catch(
(error) => {
console.error(error)
if (!res.writableEnded) {
res.statusCode = 500
res.end('Internal Server Error')
}
}
)
})
server.listen(Number(process.env.PORT), () => {
console.log(`- Local: http://localhost:${server.address().port}`)
console.log('minimal server ready')
})
module.exports = {
trailingSlash: process.env.TRAILING_SLASH === '1',
skipTrailingSlashRedirect: process.env.SKIP_TRAILING_SLASH_REDIRECT === '1',
output: process.env.STANDALONE === '1' ? 'standalone' : undefined,
cacheHandler:
process.env.CACHE_STORAGE === 'custom'
? require.resolve('./cache-handler.js')
: undefined,
cacheMaxMemorySize: process.env.CACHE_STORAGE === 'disk' ? 0 : undefined,
i18n: { locales: ['en', 'fr'], defaultLocale: 'en' },
experimental: { cpus: 2, cacheComponents: false, ppr: false },
async rewrites() {
return [{ source: '/rewritten/:id', destination: '/pages-victim/:id' }]
},
}
export default function Page() {
return <p id="not-found">fixture-not-found</p>
}
import { state, State } from '../lib/state'
export default function Page(props) {
return <State value={props} />
}
export function getStaticPaths() {
return { paths: [], fallback: 'blocking' }
}
export function getStaticProps({ params, locale }) {
return { props: state('pages-catchall', params, locale), revalidate: 3600 }
}
export default async function handler(req, res) {
const { pathname, onlyGenerated = false } = req.body || {}
if (
req.method !== 'POST' ||
typeof pathname !== 'string' ||
!/^\/(fr\/)?pages-victim\//.test(pathname)
)
return res.status(400).end()
await res.revalidate(pathname, { unstable_onlyGenerated: onlyGenerated })
res.json({ revalidated: true })
}
export default function Page() {
return <p id="static-page">static-unicode</p>
}
import { state, State } from '../../lib/state'
export default function Page(props) {
return <State value={props} />
}
export function getStaticPaths() {
return {
paths: ['en', 'fr'].flatMap((locale) =>
['allowed', 'not-found'].map((slug) => ({
params: { slug: [slug] },
locale,
}))
),
fallback: false,
}
}
export function getStaticProps({ params, locale }) {
if (params.slug[0] === 'not-found') return { notFound: true }
return { props: state('pages-closed-catchall', params, locale) }
}
import { state, State } from '../../../lib/state'
export default function Page(props) {
return <State value={props} />
}
export function getStaticPaths() {
return {
paths: ['en', 'fr'].flatMap((locale) =>
['published', 'not-found'].map((id) => ({ params: { id }, locale }))
),
fallback: false,
}
}
export function getStaticProps({ params, locale }) {
if (params.id === 'not-found') return { notFound: true }
return {
props: state('pages-admission-sibling', params, locale),
revalidate: false,
}
}
export default function Page() {
return <p id="static-page">static-home</p>
}
import { state, State } from '../../lib/state'
export default function Page(props) {
return <State value={props} />
}
export function getStaticPaths() {
return {
paths: ['en', 'fr'].flatMap((locale) =>
['known', 'not-found'].map((id) => ({ params: { id }, locale }))
),
fallback: false,
}
}
export function getStaticProps({ params, locale }) {
if (params.id === 'not-found') return { notFound: true }
return { props: state('pages-closed', params, locale), revalidate: 3600 }
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment