Prerender each declared static variant combination

A page that exports `unstable_generateStaticVariants` declares the
static variant combinations it wants prerendered. Until now the build
read those declarations, validated them, and then discarded them. This
change prerenders the route once per combination, and serves a request
the prerender of the combination it resolved.

The build prerenders every route a page produces once per combination.
For a dynamic page that is each row of `generateStaticParams` and each
fallback shell. For a page with no dynamic segments it is the page
itself. The build writes each artifact under a path that carries the
hash of the combination, for example `/__variants/1u0zqp3/blog/my-post`.

The hash sits in the path because that is how a platform addresses a
cached artifact today. It serves such a path straight from its
filesystem before any function runs, and rebuilds the same path to
revalidate the artifact, with no proxy in the loop. A platform that
could pick a variant-specific prerender from request headers alone would
need no prefix, so this shape is the one the current constraints leave
rather than the one to keep.

A proxy resolves the variants of a request, finds the combination they
match, and rewrites to the prefixed path. Routing removes the prefix
again before it matches a route, and puts the hash in `nxtV`, because
route matching runs on route patterns and no prefixed path matches one.
The origin recovers the combination from that hash rather than from the
resolved values, because a request does not always arrive with them. A
platform rebuilds the request from the artifact when it fills or
revalidates a prerender, and the path is all it has to work from.

The render then divides the values into two tiers. The matched
combination assigns the static tier, and the artifact is keyed on those
values, so a render may put them in its output. Everything else the
request resolved is the runtime tier, which no artifact key mentions, so
a read of one waits until request time. A request whose combination no
page declared is served the one prerender that omits every variant. Such
a prerender exists where the route is partially prerendered, and it
keeps that request from taking a cache entry of its own, however many
values it happens to carry.

Two manifests hold the combinations, because two layers look them up
differently. A proxy has a pathname and nothing else, so
`variants-manifest.json` is keyed by pathname for a static route and
holds a route regex for a dynamic one. The origin knows which route it
renders, so the prerender manifest keys the same groups by page.

Variants need a `proxy.ts` file, which always runs on the Node.js
runtime, so `experimental.variants` together with a `middleware.ts` is
now a build error. Serving a combination from a deployment needs routing
rules that a later change adds.
parent e6ab62b9
...@@ -45,7 +45,7 @@ import { ...@@ -45,7 +45,7 @@ import {
} from '../segment-config/middleware/middleware-config' } from '../segment-config/middleware/middleware-config'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'
import { isProxyFile } from '../utils' import { isMiddlewareFile, isProxyFile } from '../utils'
const PARSE_PATTERN = const PARSE_PATTERN =
/(?<!(_jsx|jsx-))runtime|preferredRegion|getStaticProps|getServerSideProps|generateStaticParams|export const|generateImageMetadata|generateSitemaps|middleware|proxy/ /(?<!(_jsx|jsx-))runtime|preferredRegion|getStaticProps|getServerSideProps|generateStaticParams|export const|generateImageMetadata|generateSitemaps|middleware|proxy/
...@@ -830,6 +830,26 @@ export async function getPagesPageStaticInfo({ ...@@ -830,6 +830,26 @@ export async function getPagesPageStaticInfo({
} }
} }
if (
isMiddlewareFile(page) &&
!isProxyFile(page) &&
nextConfig.experimental?.variants
) {
const relativePath = relative(process.cwd(), pageFilePath)
const resolvedPath = relativePath.startsWith('.')
? relativePath
: `./${relativePath}`
const message = `\`experimental.variants\` is not supported in the Middleware file at "${resolvedPath}". Rename it to a Proxy file, which always runs on the Node.js runtime. Run \`npx @next/codemod@canary middleware-to-proxy\` to migrate. Learn more: https://nextjs.org/docs/messages/middleware-to-proxy`
if (isDev) {
// errorOnce as proxy/middleware runs per request including multiple
// internal _next/ routes and spams logs.
Log.errorOnce(message)
} else {
throw new Error(message)
}
}
if (resolvedRuntime === SERVER_RUNTIME.experimentalEdge) { if (resolvedRuntime === SERVER_RUNTIME.experimentalEdge) {
warnAboutExperimentalEdge(isAnAPIRoute ? page! : null) warnAboutExperimentalEdge(isAnAPIRoute ? page! : null)
} }
......
This diff is collapsed.
...@@ -39,6 +39,7 @@ import { ...@@ -39,6 +39,7 @@ import {
} from '../../server/app-render/work-unit-async-storage.external' } from '../../server/app-render/work-unit-async-storage.external'
import type { ImplicitTags } from '../../server/lib/implicit-tags' import type { ImplicitTags } from '../../server/lib/implicit-tags'
import { getImplicitTags } from '../../server/lib/implicit-tags' import { getImplicitTags } from '../../server/lib/implicit-tags'
import { expandPrerenderedRoutesByVariants } from '../variants/combinations'
/** /**
* Filters out duplicate parameters from a list of parameters. * Filters out duplicate parameters from a list of parameters.
...@@ -839,6 +840,7 @@ export async function buildAppStaticPaths({ ...@@ -839,6 +840,7 @@ export async function buildAppStaticPaths({
buildId, buildId,
deploymentId, deploymentId,
rootParamKeys, rootParamKeys,
variantCombinations,
}: { }: {
dir: string dir: string
page: string page: string
...@@ -863,6 +865,12 @@ export async function buildAppStaticPaths({ ...@@ -863,6 +865,12 @@ export async function buildAppStaticPaths({
buildId: string buildId: string
deploymentId: string deploymentId: string
rootParamKeys: readonly string[] rootParamKeys: readonly string[]
/**
* The static variant combinations the page declared. The caller collects
* them, because a page with no dynamic segments never reaches this function
* and still needs them applied.
*/
variantCombinations: ReadonlyArray<Record<string, string>>
}): Promise<StaticPathsResult> { }): Promise<StaticPathsResult> {
if ( if (
segments.some((generate) => generate.config?.dynamicParams === true) && segments.some((generate) => generate.config?.dynamicParams === true) &&
...@@ -1168,6 +1176,12 @@ export async function buildAppStaticPaths({ ...@@ -1168,6 +1176,12 @@ export async function buildAppStaticPaths({
}) })
} }
expandPrerenderedRoutesByVariants(
prerenderedRoutesByPathname,
variantCombinations,
isRoutePPREnabled
)
const prerenderedRoutes = const prerenderedRoutes =
prerenderedRoutesByPathname.size > 0 || prerenderedRoutesByPathname.size > 0 ||
lastDynamicSegmentHadGenerateStaticParams lastDynamicSegmentHadGenerateStaticParams
......
...@@ -16,6 +16,18 @@ type StaticPrerenderedRoute = { ...@@ -16,6 +16,18 @@ type StaticPrerenderedRoute = {
* will error the build if the route that is generated is empty. * will error the build if the route that is generated is empty.
*/ */
throwOnEmptyStaticShell: undefined throwOnEmptyStaticShell: undefined
/**
* The static variant combination this route is prerendered against, keyed by
* variant identity. It is undefined for a route prerendered without variants.
*/
readonly variantValues?: Readonly<Record<string, string>>
/**
* True for the one route prerendered with every variant omitted, which serves
* a request whose variant combination no page declared.
*/
readonly omitsVariants?: boolean
} }
export type FallbackRouteParam = { export type FallbackRouteParam = {
...@@ -50,6 +62,18 @@ type FallbackPrerenderedRoute = { ...@@ -50,6 +62,18 @@ type FallbackPrerenderedRoute = {
* will error the build if the route that is generated is empty. * will error the build if the route that is generated is empty.
*/ */
throwOnEmptyStaticShell: boolean throwOnEmptyStaticShell: boolean
/**
* The static variant combination this route is prerendered against, keyed by
* variant identity. It is undefined for a route prerendered without variants.
*/
readonly variantValues?: Readonly<Record<string, string>>
/**
* True for the one route prerendered with every variant omitted, which serves
* a request whose variant combination no page declared.
*/
readonly omitsVariants?: boolean
} }
/** /**
......
...@@ -23,7 +23,12 @@ import { ...@@ -23,7 +23,12 @@ import {
setRequestMeta, setRequestMeta,
} from '../../server/request-meta' with { 'turbopack-transition': 'next-server-utility' } } from '../../server/request-meta' with { 'turbopack-transition': 'next-server-utility' }
import { BaseServerSpan } from '../../server/lib/trace/constants' with { 'turbopack-transition': 'next-server-utility' } import { BaseServerSpan } from '../../server/lib/trace/constants' with { 'turbopack-transition': 'next-server-utility' }
import { NEXT_VARIANTS_HEADER } from '../../lib/constants' with { 'turbopack-transition': 'next-server-utility' } import {
NEXT_VARIANTS_HEADER,
NEXT_VARIANTS_QUERY_PARAM,
} from '../../lib/constants' with { 'turbopack-transition': 'next-server-utility' }
import { findVariantCombinationByHash } from '../../server/variants/combinations' with { 'turbopack-transition': 'next-server-utility' }
import { insertVariantsPrefix } from '../../server/variants/prefix' with { 'turbopack-transition': 'next-server-utility' }
import { decodeVariants } from '../../server/variants/encoding' with { 'turbopack-transition': 'next-server-utility' } import { decodeVariants } from '../../server/variants/encoding' with { 'turbopack-transition': 'next-server-utility' }
import { stripFlightHeaders } from '../../server/app-render/strip-flight-headers' with { 'turbopack-transition': 'next-server-utility' } import { stripFlightHeaders } from '../../server/app-render/strip-flight-headers' with { 'turbopack-transition': 'next-server-utility' }
import { import {
...@@ -272,9 +277,70 @@ export function createAppPageEntrypoint({ ...@@ -272,9 +277,70 @@ export function createAppPageEntrypoint({
resolvedPathname, resolvedPathname,
prerenderManifest prerenderManifest
) )
const prerenderInfo = prerenderMatch?.route ?? null
const isPrerendered = !!prerenderManifest.routes[resolvedPathname] // The static variant combinations this page declared. A request is matched
// against them to find the prerender it belongs to.
const variantCombinationGroups = process.env.__NEXT_VARIANTS
? prerenderManifest.variantCombinationGroups[normalizedSrcPage]
: undefined
// The hash of the combination, which routing took out of the path and put
// here. It is removed again, so that it reaches neither the render nor a
// cache key by any other route.
const variantsHash = process.env.__NEXT_VARIANTS
? query[NEXT_VARIANTS_QUERY_PARAM]
: undefined
if (typeof variantsHash === 'string') {
delete query[NEXT_VARIANTS_QUERY_PARAM]
}
// The combination comes from the hash rather than from matching the
// resolved values, because a request does not always carry them. A platform
// filling or revalidating a prerender rebuilds the request from the
// artifact, where the hash is all that survives.
const matchedVariants =
variantCombinationGroups?.length && typeof variantsHash === 'string'
? findVariantCombinationByHash(variantCombinationGroups, variantsHash)
: null
// Builds the path of the matched variant combination's artifact. Every
// lookup keyed by a path goes through this, so that a request reads the
// prerender of its own combination and not of another.
//
// No base path is passed, because every path handed to this is a route
// pattern with params interpolated, and a route pattern carries none.
const toOutputPathname = (routePathname: string): string =>
matchedVariants
? insertVariantsPrefix(routePathname, matchedVariants.hash, undefined)
: routePathname
const outputPathname = toOutputPathname(resolvedPathname)
const matchedVariantsPrerenderInfo = matchedVariants
? prerenderManifest.dynamicRoutes[toOutputPathname(normalizedSrcPage)]
: undefined
// This reads the entry directly by key. Route matching here runs on the
// pathname with the prefix already removed, while this entry's key and
// `routeRegex` describe the prefixed path, so matching would not find it.
const prerenderInfo =
matchedVariantsPrerenderInfo ?? prerenderMatch?.route ?? null
// The proxy sends on only the values no combination assigned, so this
// header carries the runtime tier. The static tier comes from the hash
// instead. This header is the only channel a self-hosted request and a
// deployed request are certain to share.
const encodedRuntimeVariants = process.env.__NEXT_VARIANTS
? req.headers[NEXT_VARIANTS_HEADER]
: undefined
const runtimeVariants =
typeof encodedRuntimeVariants === 'string'
? (decodeVariants(encodedRuntimeVariants) ?? undefined)
: undefined
const isPrerendered = !!prerenderManifest.routes[outputPathname]
const userAgent = req.headers['user-agent'] || '' const userAgent = req.headers['user-agent'] || ''
const botType = getBotType(userAgent) const botType = getBotType(userAgent)
...@@ -488,7 +554,7 @@ export function createAppPageEntrypoint({ ...@@ -488,7 +554,7 @@ export function createAppPageEntrypoint({
// we can use this fact to only generate the flight data for the request // we can use this fact to only generate the flight data for the request
// because we can't cache the HTML (as it's also dynamic). // because we can't cache the HTML (as it's also dynamic).
const staticPrefetchDataRoute = const staticPrefetchDataRoute =
prerenderManifest.routes[resolvedPathname]?.prefetchDataRoute prerenderManifest.routes[outputPathname]?.prefetchDataRoute
let isDynamicRSCRequest = let isDynamicRSCRequest =
isRoutePPREnabled && isRoutePPREnabled &&
...@@ -547,11 +613,22 @@ export function createAppPageEntrypoint({ ...@@ -547,11 +613,22 @@ export function createAppPageEntrypoint({
const supportsRDCForNavigations = const supportsRDCForNavigations =
isRoutePPREnabled && nextConfig.cacheComponents === true isRoutePPREnabled && nextConfig.cacheComponents === true
// A static variant combination no page declared is served from the
// prerender that omits the variants, and a route that is not partially
// prerendered has none: omitting a variant leaves a hole only a resume can
// fill. Such a request is rendered dynamically instead. Without this it
// would take the static path, where a variant read finds no value and
// interrupts the render.
const requiresDynamicResponseForVariants = Boolean(
!isRoutePPREnabled && variantCombinationGroups?.length && !matchedVariants
)
// In development, we always want to generate dynamic HTML. // In development, we always want to generate dynamic HTML.
const supportsDynamicResponse: boolean = const supportsDynamicResponse: boolean =
// If we're in development, we always support dynamic HTML, unless it's // If we're in development, we always support dynamic HTML, unless it's
// a data request, in which case we only produce static HTML. // a data request, in which case we only produce static HTML.
routeModule.isDev === true || routeModule.isDev === true ||
requiresDynamicResponseForVariants ||
// If this is a draft mode request, it supports dynamic HTML. // If this is a draft mode request, it supports dynamic HTML.
isDraftMode || isDraftMode ||
// If this is not SSG or does not have static paths, then it supports // If this is not SSG or does not have static paths, then it supports
...@@ -642,6 +719,10 @@ export function createAppPageEntrypoint({ ...@@ -642,6 +719,10 @@ export function createAppPageEntrypoint({
} else { } else {
ssgCacheKey = resolvedPathname ssgCacheKey = resolvedPathname
} }
if (ssgCacheKey !== null) {
ssgCacheKey = toOutputPathname(ssgCacheKey)
}
} }
// the staticPathKey differs from ssgCacheKey since // the staticPathKey differs from ssgCacheKey since
...@@ -815,23 +896,6 @@ export function createAppPageEntrypoint({ ...@@ -815,23 +896,6 @@ export function createAppPageEntrypoint({
incrementalCache?.resetRequestCache() incrementalCache?.resetRequestCache()
;(globalThis as any).__incrementalCache = incrementalCache ;(globalThis as any).__incrementalCache = incrementalCache
// The variants that a proxy resolved for this request.
//
// The route module reads the header, and not the router server. The
// router server sees the header when self-hosting. A deployed request
// reaches no Next.js code before the route module runs.
//
// The flag gates the read, so that a project without variants compiles
// none of it.
const encodedVariants = process.env.__NEXT_VARIANTS
? req.headers[NEXT_VARIANTS_HEADER]
: undefined
const resolvedVariants =
typeof encodedVariants === 'string'
? decodeVariants(encodedVariants)
: null
const doRender = async ({ const doRender = async ({
span, span,
postponed, postponed,
...@@ -870,7 +934,8 @@ export function createAppPageEntrypoint({ ...@@ -870,7 +934,8 @@ export function createAppPageEntrypoint({
), ),
fallbackRouteParams, fallbackRouteParams,
renderOpts: { renderOpts: {
variants: resolvedVariants, staticVariants: matchedVariants?.values,
runtimeVariants,
App: () => null, App: () => null,
Document: () => null, Document: () => null,
pageConfig: {}, pageConfig: {},
...@@ -1198,10 +1263,11 @@ export function createAppPageEntrypoint({ ...@@ -1198,10 +1263,11 @@ export function createAppPageEntrypoint({
? !isDynamicRSCRequest ? !isDynamicRSCRequest
: !isRSCRequest) : !isRSCRequest)
) { ) {
const cacheKey = const cacheKey = toOutputPathname(
isProduction && typeof prerenderInfo?.fallback === 'string' isProduction && typeof prerenderInfo?.fallback === 'string'
? prerenderInfo.fallback ? prerenderInfo.fallback
: normalizedSrcPage : normalizedSrcPage
)
let fallbackRouteParams: OpaqueFallbackRouteParams | null let fallbackRouteParams: OpaqueFallbackRouteParams | null
if (isProduction) { if (isProduction) {
...@@ -1395,7 +1461,7 @@ export function createAppPageEntrypoint({ ...@@ -1395,7 +1461,7 @@ export function createAppPageEntrypoint({
!forceStaticRender !forceStaticRender
) { ) {
const incrementalCacheEntry = await incrementalCache.get( const incrementalCacheEntry = await incrementalCache.get(
resolvedPathname, outputPathname,
{ {
kind: IncrementalCacheKind.APP_PAGE, kind: IncrementalCacheKind.APP_PAGE,
isRoutePPREnabled: true, isRoutePPREnabled: true,
......
...@@ -2,7 +2,10 @@ import type { AdapterOptions, EdgeHandler } from '../../server/web/adapter' ...@@ -2,7 +2,10 @@ import type { AdapterOptions, EdgeHandler } from '../../server/web/adapter'
import '../adapter/setup-node-env.external' import '../adapter/setup-node-env.external'
import '../../server/web/globals' import '../../server/web/globals'
import type { VariantsManifest } from '../../server/variants/manifest'
import { adapter } from '../../server/web/adapter' import { adapter } from '../../server/web/adapter'
import { SERVER_DIRECTORY, VARIANTS_MANIFEST } from '../../shared/lib/constants'
import { IncrementalCache } from '../../server/lib/incremental-cache' import { IncrementalCache } from '../../server/lib/incremental-cache'
declare const incrementalCacheHandler: any declare const incrementalCacheHandler: any
// OPTIONAL_IMPORT:incrementalCacheHandler // OPTIONAL_IMPORT:incrementalCacheHandler
...@@ -75,6 +78,8 @@ function errorHandledHandler(fn: AdapterOptions['handler']) { ...@@ -75,6 +78,8 @@ function errorHandledHandler(fn: AdapterOptions['handler']) {
} }
const internalHandler: EdgeHandler = async (opts) => { const internalHandler: EdgeHandler = async (opts) => {
let variantsManifest: VariantsManifest | undefined
if (process.env.NEXT_RUNTIME !== 'edge') { if (process.env.NEXT_RUNTIME !== 'edge') {
// This mirrors what `RouteModule#prepare` does for routes // This mirrors what `RouteModule#prepare` does for routes
// edge runtime handles loading instrumentation at the edge adapter level // edge runtime handles loading instrumentation at the edge adapter level
...@@ -93,6 +98,11 @@ const internalHandler: EdgeHandler = async (opts) => { ...@@ -93,6 +98,11 @@ const internalHandler: EdgeHandler = async (opts) => {
: '.next' : '.next'
await ensureInstrumentationRegistered(absoluteProjectDir, distDir) await ensureInstrumentationRegistered(absoluteProjectDir, distDir)
if (process.env.__NEXT_VARIANTS) {
variantsManifest =
loadVariantsManifest(join(absoluteProjectDir, distDir)) ?? undefined
}
} }
return adapter({ return adapter({
...@@ -100,10 +110,59 @@ const internalHandler: EdgeHandler = async (opts) => { ...@@ -100,10 +110,59 @@ const internalHandler: EdgeHandler = async (opts) => {
IncrementalCache, IncrementalCache,
incrementalCacheHandler, incrementalCacheHandler,
page, page,
variantsManifest,
handler: errorHandledHandler(handlerUserland), handler: errorHandledHandler(handlerUserland),
}) })
} }
// Keyed by `distDir`, because one process can serve more than one application
// and this module is read once per process.
const cachedVariantsManifests = new Map<string, VariantsManifest | null>()
/**
* Reads the variants manifest from disk, and returns null when there is none.
*
* This branches on a compile-time condition with `if`/`else` rather than
* returning early, so that an edge build removes the branch and with it a
* `node:fs` require it could not resolve. An early return leaves the require in
* the bundle.
*
* An absent file is the ordinary case, not an error: the build writes one
* whenever the flag is on, so a missing file means the feature is off.
*
* The edge branch returns null rather than reading anything, and a variants
* project never takes it. Variants need a Proxy file, which `build/entries.ts`
* always compiles for Node, and `experimental.variants` together with a
* `middleware.ts` is rejected by `getPagesPageStaticInfo`.
*/
function loadVariantsManifest(distDir: string): VariantsManifest | null {
if (process.env.NEXT_RUNTIME !== 'edge') {
const cached = cachedVariantsManifests.get(distDir)
if (cached !== undefined) {
return cached
}
const { readFileSync } = require('node:fs') as typeof import('node:fs')
const { join } = require('node:path') as typeof import('node:path')
let manifest: VariantsManifest | null
try {
manifest = JSON.parse(
readFileSync(join(distDir, SERVER_DIRECTORY, VARIANTS_MANIFEST), 'utf8')
)
} catch {
manifest = null
}
cachedVariantsManifests.set(distDir, manifest)
return manifest
} else {
return null
}
}
export async function handler( export async function handler(
request: Request, request: Request,
ctx: { ctx: {
......
...@@ -68,7 +68,12 @@ import { collectSegments } from './segment-config/app/app-segments' ...@@ -68,7 +68,12 @@ import { collectSegments } from './segment-config/app/app-segments'
import { createIncrementalCache } from '../export/helpers/create-incremental-cache' import { createIncrementalCache } from '../export/helpers/create-incremental-cache'
import { collectRootParamKeys } from './segment-config/app/collect-root-param-keys' import { collectRootParamKeys } from './segment-config/app/collect-root-param-keys'
import { buildAppStaticPaths } from './static-paths/app' import { buildAppStaticPaths } from './static-paths/app'
import { collectStaticVariantCombinations } from './variants/combinations' import type { VariantCombinationGroups } from '../server/variants/combinations'
import {
collectStaticVariantCombinations,
expandPrerenderedRoutesByVariants,
groupStaticVariantCombinations,
} from './variants/combinations'
import { buildPagesStaticPaths } from './static-paths/pages' import { buildPagesStaticPaths } from './static-paths/pages'
import type { import type {
PrerenderRouteMatcher, PrerenderRouteMatcher,
...@@ -679,6 +684,13 @@ type PageIsStaticResult = { ...@@ -679,6 +684,13 @@ type PageIsStaticResult = {
prerenderRouteMatchers: PrerenderRouteMatcher[] | undefined prerenderRouteMatchers: PrerenderRouteMatcher[] | undefined
prerenderFallbackMode: FallbackMode | undefined prerenderFallbackMode: FallbackMode | undefined
rootParamKeys: readonly string[] | undefined rootParamKeys: readonly string[] | undefined
/**
* The static variant combinations the page declared, grouped by which
* variants they assign. A request is matched against these groups to find the
* combination it was prerendered against. It is undefined for a page that
* declared none.
*/
variantCombinationGroups: VariantCombinationGroups | undefined
isNextImageImported?: boolean isNextImageImported?: boolean
traceIncludes?: string[] traceIncludes?: string[]
traceExcludes?: string[] traceExcludes?: string[]
...@@ -751,6 +763,7 @@ export async function isPageStatic({ ...@@ -751,6 +763,7 @@ export async function isPageStatic({
prerenderedRoutes: undefined, prerenderedRoutes: undefined,
prerenderRouteMatchers: undefined, prerenderRouteMatchers: undefined,
rootParamKeys: undefined, rootParamKeys: undefined,
variantCombinationGroups: undefined,
hasStaticProps: false, hasStaticProps: false,
hasServerProps: false, hasServerProps: false,
isNextImageImported: false, isNextImageImported: false,
...@@ -780,6 +793,7 @@ export async function isPageStatic({ ...@@ -780,6 +793,7 @@ export async function isPageStatic({
let prerenderFallbackMode: FallbackMode | undefined let prerenderFallbackMode: FallbackMode | undefined
let appConfig: AppSegmentConfig = {} let appConfig: AppSegmentConfig = {}
let rootParamKeys: readonly string[] | undefined let rootParamKeys: readonly string[] | undefined
let variantCombinationGroups: VariantCombinationGroups | undefined
const pathIsEdgeRuntime = isEdgeRuntime(pageRuntime) const pathIsEdgeRuntime = isEdgeRuntime(pageRuntime)
if (pathIsEdgeRuntime) { if (pathIsEdgeRuntime) {
...@@ -881,24 +895,28 @@ export async function isPageStatic({ ...@@ -881,24 +895,28 @@ export async function isPageStatic({
const route = parseNormalizedAppRoute(page) const route = parseNormalizedAppRoute(page)
// The build reads the static variant combinations of every app route // The build reads the static variant combinations of every app route
// here, and rejects what it cannot use. Nothing prerenders against them // here, and rejects what it cannot use. A page with no dynamic segments
// yet, so the result is discarded. A page with no dynamic segments
// builds no static paths, and can still declare combinations, so this // builds no static paths, and can still declare combinations, so this
// call does not belong with the static paths below. // call does not belong with the static paths below.
// const variantCombinations = await collectStaticVariantCombinations(
// TODO(variants): prerender each route against the combinations it segments,
// declared. page
await collectStaticVariantCombinations(segments, page) )
if (variantCombinations.length > 0) {
variantCombinationGroups =
groupStaticVariantCombinations(variantCombinations)
}
let pathname = normalizeAppPath(page)
if (pathname.endsWith('/route')) {
pathname = pathname.slice(0, -'/route'.length)
}
// If the page is dynamic and we're not in edge runtime, then we need to // If the page is dynamic and we're not in edge runtime, then we need to
// build the static paths. The edge runtime doesn't support static // build the static paths. The edge runtime doesn't support static
// paths. // paths.
if (route.dynamicSegments.length > 0 && !pathIsEdgeRuntime) { if (route.dynamicSegments.length > 0 && !pathIsEdgeRuntime) {
let pathname = normalizeAppPath(page)
if (pathname.endsWith('/route')) {
pathname = pathname.slice(0, -'/route'.length)
}
if ( if (
routeModule.definition.kind === RouteKind.APP_ROUTE && routeModule.definition.kind === RouteKind.APP_ROUTE &&
isStaticMetadataFile(pathname) isStaticMetadataFile(pathname)
...@@ -920,6 +938,7 @@ export async function isPageStatic({ ...@@ -920,6 +938,7 @@ export async function isPageStatic({
durableUseCacheEntries, durableUseCacheEntries,
staticPageGenerationTimeout, staticPageGenerationTimeout,
segments, segments,
variantCombinations,
distDir, distDir,
requestHeaders: {}, requestHeaders: {},
isrFlushToDisk, isrFlushToDisk,
...@@ -934,6 +953,38 @@ export async function isPageStatic({ ...@@ -934,6 +953,38 @@ export async function isPageStatic({
rootParamKeys, rootParamKeys,
})) }))
} }
} else if (variantCombinations.length > 0 && !pathIsEdgeRuntime) {
// A page with no dynamic segments builds no static paths, and a
// variant combination it declared still has to be prerendered
// against. Its one route stands in for the params matrix a dynamic
// page would have, and the same expansion applies to it.
//
// The edge runtime disables static generation, so this branch
// skips it, as the one above does.
const prerenderedRoutesByPathname = new Map<string, PrerenderedRoute>(
[
[
pathname,
{
params: {},
pathname,
encodedPathname: pathname,
fallbackRouteParams: [],
fallbackMode: prerenderFallbackMode,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
],
]
)
expandPrerenderedRoutesByVariants(
prerenderedRoutesByPathname,
variantCombinations,
isRoutePPREnabled
)
prerenderedRoutes = [...prerenderedRoutesByPathname.values()]
} }
} else { } else {
if (!Comp || !isValidElementType(Comp) || typeof Comp === 'string') { if (!Comp || !isValidElementType(Comp) || typeof Comp === 'string') {
...@@ -1007,6 +1058,7 @@ export async function isPageStatic({ ...@@ -1007,6 +1058,7 @@ export async function isPageStatic({
prerenderedRoutes, prerenderedRoutes,
prerenderRouteMatchers, prerenderRouteMatchers,
rootParamKeys, rootParamKeys,
variantCombinationGroups,
hasStaticProps, hasStaticProps,
hasServerProps, hasServerProps,
isNextImageImported, isNextImageImported,
......
import type { AppSegment } from '../segment-config/app/app-segments' import type { AppSegment } from '../segment-config/app/app-segments'
import type { PrerenderedRoute } from '../static-paths/types'
import type {
VariantCombinationGroup,
VariantCombinationGroups,
} from '../../server/variants/combinations'
import { import {
assertValidVariantValue, assertValidVariantValue,
getVariantKey, getVariantKey,
isVariant, isVariant,
} from '../../server/request/variants' } from '../../server/request/variants'
import { hashVariants } from '../../server/variants/encoding'
/** /**
* Normalizes one combination that `unstable_generateStaticVariants` returned * Normalizes one combination that `unstable_generateStaticVariants` returned
...@@ -88,6 +94,7 @@ export async function collectStaticVariantCombinations( ...@@ -88,6 +94,7 @@ export async function collectStaticVariantCombinations(
const declared: readonly unknown[] = returned const declared: readonly unknown[] = returned
const combinations: Array<Record<string, string>> = [] const combinations: Array<Record<string, string>> = []
const seen = new Set<string>()
for (const assignments of declared) { for (const assignments of declared) {
const values = normalizeVariantAssignments(assignments, route) const values = normalizeVariantAssignments(assignments, route)
...@@ -98,7 +105,16 @@ export async function collectStaticVariantCombinations( ...@@ -98,7 +105,16 @@ export async function collectStaticVariantCombinations(
) )
} }
combinations.push(values) // The same combination declared twice would prerender the same artifact
// twice, because the hash of the combination is what names it. Two
// declarations of one combination hash alike whatever order they assign the
// variants in.
const hash = hashVariants(values)
if (!seen.has(hash)) {
seen.add(hash)
combinations.push(values)
}
} }
assertUnambiguousVariantCombinations(combinations, route) assertUnambiguousVariantCombinations(combinations, route)
...@@ -107,8 +123,8 @@ export async function collectStaticVariantCombinations( ...@@ -107,8 +123,8 @@ export async function collectStaticVariantCombinations(
} }
/** /**
* Rejects two combinations that one request can match with no order between * Rejects two static variant combinations that one request can match with no
* them. * order between them.
* *
* Two combinations are ordered when one assigns everything the other assigns * Two combinations are ordered when one assigns everything the other assigns
* and more. The larger one is the more specific, and that is how a page covers * and more. The larger one is the more specific, and that is how a page covers
...@@ -150,3 +166,100 @@ function assertUnambiguousVariantCombinations( ...@@ -150,3 +166,100 @@ function assertUnambiguousVariantCombinations(
} }
} }
} }
/**
* Groups the static variant combinations of one page by which variants they
* assign, and orders the groups most specific first.
*
* A request resolves every variant its route reads, while a combination may
* assign only some of them, so the resolved values cannot be hashed as they
* arrive. The `keys` of a group say which values to select before hashing, and
* that projection is what makes a partial combination findable.
*
* Each combination keeps its values positional against the sorted keys of its
* group, which is the form the manifests carry.
*/
export function groupStaticVariantCombinations(
combinations: ReadonlyArray<Record<string, string>>
): VariantCombinationGroups {
const groupsBySignature = new Map<string, VariantCombinationGroup>()
for (const combination of combinations) {
const keys = Object.keys(combination).sort()
const signature = JSON.stringify(keys)
let group = groupsBySignature.get(signature)
if (!group) {
group = { keys, combinations: [] }
groupsBySignature.set(signature, group)
}
group.combinations.push({
hash: hashVariants(combination),
values: group.keys.map((key) => combination[key]),
})
}
// A combination that assigns more variants leaves fewer holes, so it is the
// better prerender to serve when two of them match one request. `sort` is
// stable, so groups of equal size keep the order the page declared them in.
// The rejection of ambiguous pairs above is what stops that order from
// deciding anything.
return [...groupsBySignature.values()].sort(
(a, b) => b.keys.length - a.keys.length
)
}
/**
* Multiplies the routes a page prerenders by the static variant combinations it
* declared, in place.
*
* A combination belongs to the whole route, so it applies to every concrete
* route the params produced and to every fallback shell alike. The copies
* cannot share a map key, because combinations of one route share a pathname: a
* prefix carries the hash of the combination, and routing removes that prefix
* before it matches the route.
*
* Where the route is partially prerendered, this also keeps the route it did
* not multiply, and marks it as the one that omits variants. A request whose
* combination no page declared is served from that one entry, instead of each
* value it happens to carry seeding an entry of its own. Without it a variant
* with many values would grow the cache in proportion to traffic rather than to
* what the page declared.
*
* Where the route is not partially prerendered there is no resume to fill the
* hole a left-out variant leaves, so no such entry is kept. An undeclared
* combination then renders dynamically for each request.
*/
export function expandPrerenderedRoutesByVariants(
prerenderedRoutesByPathname: Map<string, PrerenderedRoute>,
variantCombinations: ReadonlyArray<Record<string, string>>,
isRoutePPREnabled: boolean
): void {
if (variantCombinations.length === 0) {
return
}
// Iterate over a snapshot, so that the copies added below are not expanded
// again.
for (const [key, prerenderedRoute] of [...prerenderedRoutesByPathname]) {
if (isRoutePPREnabled) {
prerenderedRoutesByPathname.set(key, {
...prerenderedRoute,
omitsVariants: true,
})
} else {
prerenderedRoutesByPathname.delete(key)
}
for (const variantValues of variantCombinations) {
// Each copy is a distinct object, because later passes over these routes
// write to them.
prerenderedRoutesByPathname.set(
`${key}\0${hashVariants(variantValues)}`,
{ ...prerenderedRoute, variantValues }
)
}
}
}
import type { VariantCombinationGroups } from '../../server/variants/combinations'
import type { VariantsManifest } from '../../server/variants/manifest'
import { isDynamicRoute } from '../../shared/lib/router/utils/is-dynamic'
import { getRouteRegex } from '../../shared/lib/router/utils/route-regex'
import { sortPagesObject } from '../../shared/lib/router/utils/sortable-routes'
/**
* Builds the variants manifest from the groups the build collected per page.
*
* A static route is keyed by its pathname, which a proxy can look up directly.
* A dynamic route carries the source of its route regex instead, and the routes
* are sorted so that a more specific one is tested first.
*/
export function buildVariantsManifest(
groupsByPage: ReadonlyMap<string, VariantCombinationGroups>
): VariantsManifest {
const staticRoutes: Record<string, VariantCombinationGroups> = {}
const dynamicGroupsByPage: Record<string, VariantCombinationGroups> = {}
for (const [page, groups] of groupsByPage) {
if (isDynamicRoute(page)) {
dynamicGroupsByPage[page] = groups
} else {
staticRoutes[page] = groups
}
}
const dynamicRoutes = Object.entries(
sortPagesObject(dynamicGroupsByPage)
).map(([page, groups]) => ({
regex: getRouteRegex(page).re.source,
groups,
}))
return { version: 1, staticRoutes, dynamicRoutes }
}
...@@ -70,6 +70,7 @@ export async function createIncrementalCache({ ...@@ -70,6 +70,7 @@ export async function createIncrementalCache({
routes: {}, routes: {},
dynamicRoutes: {}, dynamicRoutes: {},
notFoundRoutes: [], notFoundRoutes: [],
variantCombinationGroups: {},
preview: previewProps, preview: previewProps,
}, },
fs: nodeFs, fs: nodeFs,
......
...@@ -102,6 +102,9 @@ async function exportPageImpl( ...@@ -102,6 +102,9 @@ async function exportPageImpl(
// The parameters that are currently unknown. // The parameters that are currently unknown.
_fallbackRouteParams = [], _fallbackRouteParams = [],
// The static variant combination this output is prerendered against.
_variantValues: staticVariants = null,
// Check if this is an `app/` page. // Check if this is an `app/` page.
_isAppDir: isAppDir = false, _isAppDir: isAppDir = false,
...@@ -277,6 +280,7 @@ async function exportPageImpl( ...@@ -277,6 +280,7 @@ async function exportPageImpl(
// If it's dynamic, then it can be handled when request hits the route. // If it's dynamic, then it can be handled when request hits the route.
serveStreamingMetadata: true, serveStreamingMetadata: true,
allowEmptyStaticShell, allowEmptyStaticShell,
staticVariants,
runInstantValidation, runInstantValidation,
isFallbackUpgradeable, isFallbackUpgradeable,
experimental: { experimental: {
......
...@@ -30,7 +30,35 @@ export const NEXT_RESUME_HEADER = 'next-resume' ...@@ -30,7 +30,35 @@ export const NEXT_RESUME_HEADER = 'next-resume'
export const NEXT_RESUME_STATE_LENGTH_HEADER = 'x-next-resume-state-length' export const NEXT_RESUME_STATE_LENGTH_HEADER = 'x-next-resume-state-length'
/** /**
* Carries the variant values that a request resolved, encoded. * The marker segment that introduces the hash of a static variant combination
* in an internal pathname, for example `/__variants/1u0zqp3/blog/my-post`. The
* build writes an artifact under it, and routing removes it again before route
* resolution. A user never sees it.
*
* The hash travels in the path, and not in a header, because an artifact is a
* file and the layers that serve or refresh one address it by path. A platform
* serves `/__variants/<hash>/blog/my-post` straight from its filesystem, before
* any function runs. It rebuilds the same path to revalidate the artifact, with
* no proxy in the loop and nothing else left to say which combination it is.
*
* Routing converts the hash into `NEXT_VARIANTS_QUERY_PARAM` before it matches
* a route, because matching runs on route patterns and no prefixed path matches
* one. It converts inside the branch that handles a rewrite our own proxy
* produced.
*/
export const VARIANTS_PATH_PREFIX = '__variants'
/**
* Carries the hash of a static variant combination from routing to the route
* module, once routing has taken it out of the path.
*/
export const NEXT_VARIANTS_QUERY_PARAM = 'nxtV'
/**
* Carries the variant values a request resolved that no static variant
* combination assigns, encoded. What a combination does assign is recovered
* from the hash in `VARIANTS_PATH_PREFIX` instead. Where no combination
* matched, every resolved value travels here.
* *
* The `x-next-internal-` prefix makes the header safe to trust on arrival. A * The `x-next-internal-` prefix makes the header safe to trust on arrival. A
* deployment reserves that prefix for its routing layer and removes such a * deployment reserves that prefix for its routing layer and removes such a
......
...@@ -1689,6 +1689,8 @@ async function prospectiveRuntimeServerPrerender( ...@@ -1689,6 +1689,8 @@ async function prospectiveRuntimeServerPrerender(
type: 'prerender-runtime', type: 'prerender-runtime',
phase: 'render', phase: 'render',
rootParams, rootParams,
staticVariants: renderOpts.staticVariants ?? null,
runtimeVariants: renderOpts.runtimeVariants ?? null,
implicitTags, implicitTags,
renderSignal: initialServerRenderController.signal, renderSignal: initialServerRenderController.signal,
controller: initialServerPrerenderController, controller: initialServerPrerenderController,
...@@ -1876,6 +1878,8 @@ async function finalRuntimeServerPrerender( ...@@ -1876,6 +1878,8 @@ async function finalRuntimeServerPrerender(
type: 'prerender-runtime', type: 'prerender-runtime',
phase: 'render', phase: 'render',
rootParams, rootParams,
staticVariants: renderOpts.staticVariants ?? null,
runtimeVariants: renderOpts.runtimeVariants ?? null,
implicitTags, implicitTags,
renderSignal: finalServerController.signal, renderSignal: finalServerController.signal,
controller: finalServerController, controller: finalServerController,
...@@ -3018,7 +3022,8 @@ async function renderAppPage( ...@@ -3018,7 +3022,8 @@ async function renderAppPage(
res, res,
url, url,
rootParams, rootParams,
renderOpts.variants ?? null, renderOpts.staticVariants ?? null,
renderOpts.runtimeVariants ?? null,
implicitTags, implicitTags,
renderOpts.onUpdateCookies, renderOpts.onUpdateCookies,
renderOpts.previewProps, renderOpts.previewProps,
...@@ -6734,7 +6739,8 @@ export async function runValidationInDevFromSnapshot( ...@@ -6734,7 +6739,8 @@ export async function runValidationInDevFromSnapshot(
search: message.request.urlSearch, search: message.request.urlSearch,
}, },
rootParams: message.request.rootParams, rootParams: message.request.rootParams,
variants: message.request.variants, staticVariants: message.request.staticVariants,
runtimeVariants: message.request.runtimeVariants,
implicitTags, implicitTags,
resumeDataCache: null, resumeDataCache: null,
previewProps: undefined, previewProps: undefined,
...@@ -8386,7 +8392,8 @@ async function validateInstantConfigInBuildWithSample( ...@@ -8386,7 +8392,8 @@ async function validateInstantConfigInBuildWithSample(
draftMode, draftMode,
rootParams: sampleRootParams, rootParams: sampleRootParams,
// TODO(variants): Define variants for instant validation. // TODO(variants): Define variants for instant validation.
variants: null, staticVariants: null,
runtimeVariants: null,
validationSamples, validationSamples,
validationSampleTracking: createValidationSampleTracking(), validationSampleTracking: createValidationSampleTracking(),
// This will be set when rendering // This will be set when rendering
...@@ -8836,6 +8843,7 @@ async function prerenderToStream( ...@@ -8836,6 +8843,7 @@ async function prerenderToStream(
const initialServerPayloadPrerenderStore: PrerenderStore = { const initialServerPayloadPrerenderStore: PrerenderStore = {
type: 'prerender', type: 'prerender',
staticVariants: renderOpts.staticVariants ?? null,
phase: 'render', phase: 'render',
rootParams, rootParams,
fallbackRouteParams, fallbackRouteParams,
...@@ -8878,6 +8886,7 @@ async function prerenderToStream( ...@@ -8878,6 +8886,7 @@ async function prerenderToStream(
const initialServerPrerenderStore: PrerenderStore = (prerenderStore = { const initialServerPrerenderStore: PrerenderStore = (prerenderStore = {
type: 'prerender', type: 'prerender',
staticVariants: renderOpts.staticVariants ?? null,
phase: 'render', phase: 'render',
rootParams, rootParams,
fallbackRouteParams, fallbackRouteParams,
...@@ -9147,6 +9156,7 @@ async function prerenderToStream( ...@@ -9147,6 +9156,7 @@ async function prerenderToStream(
const finalServerPayloadPrerenderStore: PrerenderStoreModernServer = { const finalServerPayloadPrerenderStore: PrerenderStoreModernServer = {
type: 'prerender', type: 'prerender',
staticVariants: renderOpts.staticVariants ?? null,
phase: 'render', phase: 'render',
rootParams, rootParams,
fallbackRouteParams, fallbackRouteParams,
...@@ -9210,6 +9220,7 @@ async function prerenderToStream( ...@@ -9210,6 +9220,7 @@ async function prerenderToStream(
const finalServerPrerenderStore: PrerenderStore = (prerenderStore = { const finalServerPrerenderStore: PrerenderStore = (prerenderStore = {
type: 'prerender', type: 'prerender',
staticVariants: renderOpts.staticVariants ?? null,
phase: 'render', phase: 'render',
rootParams, rootParams,
fallbackRouteParams, fallbackRouteParams,
...@@ -9687,6 +9698,7 @@ async function prerenderToStream( ...@@ -9687,6 +9698,7 @@ async function prerenderToStream(
} else { } else {
const prerenderLegacyStore: PrerenderStore = (prerenderStore = { const prerenderLegacyStore: PrerenderStore = (prerenderStore = {
type: 'prerender-legacy', type: 'prerender-legacy',
staticVariants: renderOpts.staticVariants ?? null,
phase: 'render', phase: 'render',
rootParams, rootParams,
implicitTags, implicitTags,
...@@ -9921,6 +9933,7 @@ async function prerenderToStream( ...@@ -9921,6 +9933,7 @@ async function prerenderToStream(
) )
const errorPrerenderStore: PrerenderStore = { const errorPrerenderStore: PrerenderStore = {
type: 'prerender', type: 'prerender',
staticVariants: renderOpts.staticVariants ?? null,
phase: 'render', phase: 'render',
rootParams, rootParams,
fallbackRouteParams, fallbackRouteParams,
...@@ -10242,6 +10255,7 @@ async function prerenderToStream( ...@@ -10242,6 +10255,7 @@ async function prerenderToStream(
const prerenderLegacyStore: PrerenderStore = { const prerenderLegacyStore: PrerenderStore = {
type: 'prerender-legacy', type: 'prerender-legacy',
staticVariants: renderOpts.staticVariants ?? null,
phase: 'render', phase: 'render',
rootParams, rootParams,
implicitTags: implicitTags, implicitTags: implicitTags,
......
...@@ -50,7 +50,8 @@ export interface DevValidationRequestSnapshot { ...@@ -50,7 +50,8 @@ export interface DevValidationRequestSnapshot {
urlPathname: string urlPathname: string
urlSearch: string urlSearch: string
rootParams: Params rootParams: Params
variants: Record<string, string> | null staticVariants: Record<string, string> | null
runtimeVariants: Record<string, string> | null
isDraftMode: boolean isDraftMode: boolean
isHmrRefresh: boolean isHmrRefresh: boolean
hmrRefreshHash: string | undefined hmrRefreshHash: string | undefined
......
...@@ -72,7 +72,8 @@ export async function buildDevValidationSnapshot( ...@@ -72,7 +72,8 @@ export async function buildDevValidationSnapshot(
urlPathname: requestStore.url.pathname, urlPathname: requestStore.url.pathname,
urlSearch: requestStore.url.search, urlSearch: requestStore.url.search,
rootParams: requestStore.rootParams, rootParams: requestStore.rootParams,
variants: requestStore.variants, staticVariants: requestStore.staticVariants,
runtimeVariants: requestStore.runtimeVariants,
isDraftMode: requestStore.draftMode.isEnabled, isDraftMode: requestStore.draftMode.isEnabled,
isHmrRefresh: requestStore.isHmrRefresh ?? false, isHmrRefresh: requestStore.isHmrRefresh ?? false,
hmrRefreshHash: requestStore.hmrRefreshHash, hmrRefreshHash: requestStore.hmrRefreshHash,
......
...@@ -93,10 +93,15 @@ export type ServerOnInstrumentationRequestError = ( ...@@ -93,10 +93,15 @@ export type ServerOnInstrumentationRequestError = (
export interface RenderOptsPartial { export interface RenderOptsPartial {
/** /**
* The variants that the request resolved. The render puts them on the * The variants the matched static variant combination assigns.
* request store. Absent for a render that has none.
*/ */
variants?: Record<string, string> | null staticVariants?: Record<string, string> | null
/**
* The variants the request resolved that no static variant combination
* assigns.
*/
runtimeVariants?: Record<string, string> | null
dir?: string dir?: string
previewProps: __ApiPreviewProps | undefined previewProps: __ApiPreviewProps | undefined
......
...@@ -65,10 +65,30 @@ export interface RequestStore extends CommonWorkUnitStore { ...@@ -65,10 +65,30 @@ export interface RequestStore extends CommonWorkUnitStore {
readonly rootParams: Params readonly rootParams: Params
/** /**
* The variants that this request resolved, keyed by variant identity, for * The variants this request matched a declared combination on, keyed by
* example `theme@variants.ts`. It is null when the request resolved none. * variant identity, for example `theme@variants.ts`. It is null when the
* request matched none.
*
* The prerender serving this request is produced for these values, so a
* render may put them in its output.
*
* "Static" here has the sense it has in `generateStaticParams`: constant
* within this output, not the same for every request. `theme=dark` is static
* within the dark prerender, and a request still chooses which prerender it
* gets.
*/ */
readonly variants: Record<string, string> | null readonly staticVariants: Record<string, string> | null
/**
* The variants this request resolved that no declared combination assigns,
* keyed by variant identity. It is null when there are none.
*
* No artifact key mentions these, so nothing a render caches may hold one. A
* read of one waits until request time.
*
* This map is disjoint from `staticVariants`.
*/
readonly runtimeVariants: Record<string, string> | null
/** /**
* The resume data cache for this request. Either a mutable * The resume data cache for this request. Either a mutable
...@@ -177,6 +197,16 @@ export interface PrerenderStoreModernServer ...@@ -177,6 +197,16 @@ export interface PrerenderStoreModernServer
StaticPrerenderStoreCommon { StaticPrerenderStoreCommon {
readonly type: 'prerender' readonly type: 'prerender'
/**
* The variants this prerender's combination assigns, keyed by variant
* identity. It is null for a prerender produced without variants.
*
* This prerender is produced for these values, so a render may put them in
* its output rather than leaving a hole. Every other variant a request
* resolves stays a hole this prerender does not fill.
*/
readonly staticVariants: Record<string, string> | null
readonly stagedRendering: StagedRenderingController | null readonly stagedRendering: StagedRenderingController | null
/** /**
...@@ -234,6 +264,21 @@ export interface PrerenderStoreModernRuntime ...@@ -234,6 +264,21 @@ export interface PrerenderStoreModernRuntime
extends PrerenderStoreModernCommon { extends PrerenderStoreModernCommon {
readonly type: 'prerender-runtime' readonly type: 'prerender-runtime'
/**
* The variants this prerender's combination assigns, keyed by variant
* identity. It is null for a runtime prerender produced without variants.
*/
readonly staticVariants: Record<string, string> | null
/**
* The variants this runtime prerender resolved that no static variant
* combination assigns, keyed by variant identity.
*
* A runtime prerender runs against a real request, so unlike a static
* prerender it may read these.
*/
readonly runtimeVariants: Record<string, string> | null
/** /**
* The staged rendering controller for this prerender. Models stage * The staged rendering controller for this prerender. Models stage
* transitions (Before → Static → Runtime → Dynamic). Null for prospective * transitions (Before → Static → Runtime → Dynamic). Null for prospective
...@@ -333,6 +378,12 @@ export interface PrerenderStoreLegacy ...@@ -333,6 +378,12 @@ export interface PrerenderStoreLegacy
RevalidateStore { RevalidateStore {
readonly type: 'prerender-legacy' readonly type: 'prerender-legacy'
readonly rootParams: Params readonly rootParams: Params
/**
* The variants this prerender's combination assigns, keyed by variant
* identity. It is null for a prerender produced without variants.
*/
readonly staticVariants: Record<string, string> | null
} }
export type PrerenderStore = PrerenderStoreLegacy | PrerenderStoreModern export type PrerenderStore = PrerenderStoreLegacy | PrerenderStoreModern
......
...@@ -138,11 +138,8 @@ export type RequestStoreInputs = { ...@@ -138,11 +138,8 @@ export type RequestStoreInputs = {
url: { pathname: string; search?: string } url: { pathname: string; search?: string }
rootParams: Params rootParams: Params
/** staticVariants: Record<string, string> | null
* The variants that this request resolved. This becomes `variants` on the runtimeVariants: Record<string, string> | null
* store.
*/
variants: Record<string, string> | null
implicitTags: ImplicitTags implicitTags: ImplicitTags
resumeDataCache: ResumeDataCache | null resumeDataCache: ResumeDataCache | null
previewProps: WrapperRenderOpts['previewProps'] previewProps: WrapperRenderOpts['previewProps']
...@@ -195,7 +192,8 @@ export function createRequestStoreForRender( ...@@ -195,7 +192,8 @@ export function createRequestStoreForRender(
res: RequestContext['res'], res: RequestContext['res'],
url: RequestContext['url'], url: RequestContext['url'],
rootParams: Params, rootParams: Params,
variants: Record<string, string> | null, staticVariants: Record<string, string> | null,
runtimeVariants: Record<string, string> | null,
implicitTags: RequestContext['implicitTags'], implicitTags: RequestContext['implicitTags'],
onUpdateCookies: RenderOpts['onUpdateCookies'], onUpdateCookies: RenderOpts['onUpdateCookies'],
previewProps: WrapperRenderOpts['previewProps'], previewProps: WrapperRenderOpts['previewProps'],
...@@ -218,7 +216,8 @@ export function createRequestStoreForRender( ...@@ -218,7 +216,8 @@ export function createRequestStoreForRender(
: undefined), : undefined),
url, url,
rootParams, rootParams,
variants, staticVariants,
runtimeVariants,
implicitTags, implicitTags,
resumeDataCache, resumeDataCache,
previewProps, previewProps,
...@@ -253,7 +252,8 @@ export function createRequestStoreForAPI( ...@@ -253,7 +252,8 @@ export function createRequestStoreForAPI(
// like any other origin request, and the reader needs only a request store. // like any other origin request, and the reader needs only a request store.
// Support means reading the header where the handler runs and passing the // Support means reading the header where the handler runs and passing the
// values through here, so this becomes a parameter rather than a constant. // values through here, so this becomes a parameter rather than a constant.
variants: null, staticVariants: null,
runtimeVariants: null,
implicitTags, implicitTags,
resumeDataCache: null, resumeDataCache: null,
previewProps, previewProps,
...@@ -278,7 +278,8 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore { ...@@ -278,7 +278,8 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore {
onUpdateCookies, onUpdateCookies,
url, url,
rootParams, rootParams,
variants, staticVariants,
runtimeVariants,
implicitTags, implicitTags,
resumeDataCache, resumeDataCache,
previewProps, previewProps,
...@@ -305,7 +306,8 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore { ...@@ -305,7 +306,8 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore {
// lets us avoid requiring an empty string for `search` in the type. // lets us avoid requiring an empty string for `search` in the type.
url: { pathname: url.pathname, search: url.search ?? '' }, url: { pathname: url.pathname, search: url.search ?? '' },
rootParams, rootParams,
variants, staticVariants,
runtimeVariants,
get headers() { get headers() {
if (!cache.headers) { if (!cache.headers) {
// Seal the headers object that'll freeze out any methods that could // Seal the headers object that'll freeze out any methods that could
......
...@@ -1589,6 +1589,15 @@ export type ExportPathMap = { ...@@ -1589,6 +1589,15 @@ export type ExportPathMap = {
*/ */
_ssgPath?: string _ssgPath?: string
/**
* The static variant combination this output is prerendered against, keyed
* by variant identity. It is absent for an output prerendered without
* variants.
*
* @internal
*/
_variantValues?: Readonly<Record<string, string>>
/** /**
* The parameters that are currently unknown. * The parameters that are currently unknown.
* *
...@@ -2504,6 +2513,7 @@ export interface NextConfigRuntime { ...@@ -2504,6 +2513,7 @@ export interface NextConfigRuntime {
| 'exposeTestingApiInProductionBuild' | 'exposeTestingApiInProductionBuild'
| 'instantInsights' | 'instantInsights'
| 'requestInsights' | 'requestInsights'
| 'variants'
> & { > & {
// Pick on @internal fields generates invalid .d.ts files // Pick on @internal fields generates invalid .d.ts files
/** @internal */ /** @internal */
...@@ -2574,6 +2584,7 @@ export function getNextConfigRuntime( ...@@ -2574,6 +2584,7 @@ export function getNextConfigRuntime(
exposeTestingApiInProductionBuild: ex.exposeTestingApiInProductionBuild, exposeTestingApiInProductionBuild: ex.exposeTestingApiInProductionBuild,
instantInsights: ex.instantInsights, instantInsights: ex.instantInsights,
requestInsights: ex.requestInsights, requestInsights: ex.requestInsights,
variants: ex.variants,
trustHostHeader: ex.trustHostHeader, trustHostHeader: ex.trustHostHeader,
isExperimentalCompile: ex.isExperimentalCompile, isExperimentalCompile: ex.isExperimentalCompile,
......
...@@ -121,13 +121,16 @@ export async function loadStaticPaths({ ...@@ -121,13 +121,16 @@ export async function loadStaticPaths({
) )
// The dev server reads the static variant combinations of a route here, and // The dev server reads the static variant combinations of a route here, and
// rejects what it cannot use. Nothing prerenders against them yet, so the // rejects what it cannot use.
// result is discarded.
// //
// The dev server builds static paths only for a dynamic route. A route // It builds static paths only for a dynamic route. A route without dynamic
// without dynamic segments is therefore checked by a production build // segments is therefore checked by a production build alone.
// alone. // TODO(variants): Check static variant combinations in dev also for static
await collectStaticVariantCombinations(segments, pathname) // routes.
const variantCombinations = await collectStaticVariantCombinations(
segments,
pathname
)
const route = parseNormalizedAppRoute(pathname) const route = parseNormalizedAppRoute(pathname)
if (route.dynamicSegments.length === 0) { if (route.dynamicSegments.length === 0) {
...@@ -147,6 +150,7 @@ export async function loadStaticPaths({ ...@@ -147,6 +150,7 @@ export async function loadStaticPaths({
route, route,
cacheComponents: config.cacheComponents, cacheComponents: config.cacheComponents,
segments, segments,
variantCombinations,
distDir, distDir,
requestHeaders, requestHeaders,
cacheHandler, cacheHandler,
......
...@@ -165,7 +165,8 @@ export async function probeUseCache(msg: ProbeMessage): Promise<boolean> { ...@@ -165,7 +165,8 @@ export async function probeUseCache(msg: ProbeMessage): Promise<boolean> {
rootParams: msg.request.rootParams, rootParams: msg.request.rootParams,
// A `'use cache'` scope rejects a read of a variant, and this probe // A `'use cache'` scope rejects a read of a variant, and this probe
// exercises only such scopes, so it needs no values. // exercises only such scopes, so it needs no values.
variants: null, staticVariants: null,
runtimeVariants: null,
implicitTags: { tags: [], expirationsByCacheKind: new Map() }, implicitTags: { tags: [], expirationsByCacheKind: new Map() },
resumeDataCache: null, resumeDataCache: null,
previewProps: undefined, previewProps: undefined,
......
...@@ -30,6 +30,8 @@ import { detectDomainLocale } from '../../../shared/lib/i18n/detect-domain-local ...@@ -30,6 +30,8 @@ import { detectDomainLocale } from '../../../shared/lib/i18n/detect-domain-local
import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path'
import { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix' import { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix'
import { NextDataPathnameNormalizer } from '../../normalizers/request/next-data' import { NextDataPathnameNormalizer } from '../../normalizers/request/next-data'
import { splitVariantsPrefix } from '../../variants/prefix'
import { NEXT_VARIANTS_QUERY_PARAM } from '../../../lib/constants'
import { BasePathPathnameNormalizer } from '../../normalizers/request/base-path' import { BasePathPathnameNormalizer } from '../../normalizers/request/base-path'
import { addRequestMeta } from '../../request-meta' import { addRequestMeta } from '../../request-meta'
...@@ -751,6 +753,42 @@ export function getResolveRoutes( ...@@ -751,6 +753,42 @@ export function getResolveRoutes(
} }
} }
// Routing removes the variants prefix here and carries its hash
// in the query instead, so that the pathname matches a route
// pattern below. It runs before the locale is detected, because
// the prefix sits in front of the whole remaining public path,
// locale included.
//
// This is the only place the prefix is removed, and only a
// destination a proxy rewrote to reaches it. A prefix a client
// wrote therefore stays on the pathname and matches no route, so
// a self-hosted server answers 404.
//
// TODO(variants): reject a prefix and a
// `NEXT_VARIANTS_QUERY_PARAM` that arrive from a client. A
// deployment serves an artifact by path before any function runs,
// so a client reaches one there whatever this code does. The
// query write below overwrites a client's value only where a
// prefix is present, so a request the proxy matched no
// combination for keeps it.
if (config.experimental?.variants) {
const withoutPrefix = splitVariantsPrefix(
parsedUrl.pathname || '',
config.basePath
)
if (withoutPrefix) {
// The query carries the hash the rest of the way. It survives
// routing, and a platform routing rule produces the same
// shape, because such a rule passes data only through the URL
// it rewrites to. The origin therefore reads one channel for
// a self-hosted request and a deployed one alike.
parsedUrl.query[NEXT_VARIANTS_QUERY_PARAM] =
withoutPrefix.hash
parsedUrl.pathname = withoutPrefix.pathname
}
}
if (config.i18n) { if (config.i18n) {
const curLocaleResult = normalizeLocalePath( const curLocaleResult = normalizeLocalePath(
parsedUrl.pathname || '', parsedUrl.pathname || '',
......
...@@ -352,6 +352,7 @@ async function startWatcher( ...@@ -352,6 +352,7 @@ async function startWatcher(
routes: {}, routes: {},
dynamicRoutes: {}, dynamicRoutes: {},
notFoundRoutes: [], notFoundRoutes: [],
variantCombinationGroups: {},
}, },
null, null,
2 2
......
...@@ -201,13 +201,28 @@ function readVariant(key: string): Promise<string> { ...@@ -201,13 +201,28 @@ function readVariant(key: string): Promise<string> {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'request': { case 'request': {
const value = workUnitStore.variants?.[key] const staticValue = workUnitStore.staticVariants?.[key]
if (staticValue !== undefined) {
return resolveInStage(
workUnitStore,
// A variant can be derived from a param, and a shell is shared
// across the params of a route, so a variant value must not appear
// in one. Resolving after the shell keeps it out and still reaches
// the output of this combination. Static params are delayed by the
// same rule.
// TODO(variants): Track if a variant varies on params.
workUnitStore.needsAppShell
? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData // Match the timing of 'prerender-runtime'.
: RENDER_STAGES_BY_DATA_KIND.staticLinkData, // Match the timing of 'prerender'.
variantName,
staticValue
)
}
const value = workUnitStore.runtimeVariants?.[key]
if (value !== undefined) { if (value !== undefined) {
// TODO(variants): a value that a combination declared belongs to an
// earlier stage, because the prerender of that combination can hold it.
// Only a value that no combination declared waits for the runtime
// stage.
return resolveInStage( return resolveInStage(
workUnitStore, workUnitStore,
RENDER_STAGES_BY_DATA_KIND.runtimeLinkData, RENDER_STAGES_BY_DATA_KIND.runtimeLinkData,
...@@ -245,15 +260,21 @@ function readVariant(key: string): Promise<string> { ...@@ -245,15 +260,21 @@ function readVariant(key: string): Promise<string> {
`${variantName} must not be read within a Client Component. Next.js should be preventing variants from being included in Client Components, but did not in this case.` `${variantName} must not be read within a Client Component. Next.js should be preventing variants from being included in Client Components, but did not in this case.`
) )
} }
// A request resolves a variant, so no prerender holds a value for one. Each // A prerender produced for a declared combination holds the values that
// read below interrupts the prerender instead, and the value then arrives // combination assigns, so a read of one of those returns the value. A read
// at request time. Each kind of prerender interrupts in the way that it // of any other variant interrupts the prerender, in the way that kind of
// requires, as the other request APIs do. // prerender requires and as the other request APIs do, and the value then
// // arrives at request time.
// TODO(variants): a prerender produced for a declared combination holds the
// values that the combination fixes, and returns one here. The interrupts
// then cover only the combinations that nothing declared.
case 'prerender': { case 'prerender': {
// The combination this prerender is produced for assigns some variants,
// so a read of one belongs in the output rather than produce a dynamic
// hole.
const staticValue = workUnitStore.staticVariants?.[key]
if (staticValue !== undefined) {
return Promise.resolve(staticValue)
}
// A variant is runtime data, and not dynamic data. A request resolves it // A variant is runtime data, and not dynamic data. A request resolves it
// from cookies and headers, so a runtime prefetch can supply a value // from cookies and headers, so a runtime prefetch can supply a value
// where a static prerender cannot. This helper also records the access, // where a static prerender cannot. This helper also records the access,
...@@ -267,8 +288,33 @@ function readVariant(key: string): Promise<string> { ...@@ -267,8 +288,33 @@ function readVariant(key: string): Promise<string> {
) )
} }
case 'prerender-runtime': { case 'prerender-runtime': {
// A runtime prefetch produces this store. Only a real request resolves a // This prerender runs against a real request, so both tiers are known
// variant, so the read is dynamic here. // here, and each resolves at the stage its tier belongs to.
const staticValue = workUnitStore.staticVariants?.[key]
if (staticValue !== undefined) {
return resolveInStage(
workUnitStore,
RENDER_STAGES_BY_DATA_KIND.staticLinkData,
variantName,
staticValue
)
}
const runtimeValue = workUnitStore.runtimeVariants?.[key]
if (runtimeValue !== undefined) {
return resolveInStage(
workUnitStore,
RENDER_STAGES_BY_DATA_KIND.runtimeLinkData,
variantName,
runtimeValue
)
}
// The variant is in neither tier, so nothing resolved a value for it.
// The read hangs rather than failing the prefetch, which leaves this part
// of the output to the navigation.
return makeDynamicHangingPromise( return makeDynamicHangingPromise(
workUnitStore.renderSignal, workUnitStore.renderSignal,
workStore.route, workStore.route,
...@@ -276,6 +322,14 @@ function readVariant(key: string): Promise<string> { ...@@ -276,6 +322,14 @@ function readVariant(key: string): Promise<string> {
) )
} }
case 'prerender-legacy': { case 'prerender-legacy': {
const staticValue = workUnitStore.staticVariants?.[key]
if (staticValue !== undefined) {
return Promise.resolve(staticValue)
}
// This path cannot postpone, so without a fixed value the read has to
// interrupt static generation and the route renders per request instead.
return throwToInterruptStaticGeneration( return throwToInterruptStaticGeneration(
variantName, variantName,
workStore, workStore,
......
...@@ -14,6 +14,7 @@ function createMockPrerenderManifest( ...@@ -14,6 +14,7 @@ function createMockPrerenderManifest(
routes: {}, routes: {},
dynamicRoutes, dynamicRoutes,
notFoundRoutes: [], notFoundRoutes: [],
variantCombinationGroups: {},
preview: { preview: {
previewModeId: 'test-preview-id', previewModeId: 'test-preview-id',
previewModeEncryptionKey: 'test-encryption-key', previewModeEncryptionKey: 'test-encryption-key',
......
...@@ -577,6 +577,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -577,6 +577,7 @@ export class AppRouteRouteModule extends RouteModule<
const prospectiveRoutePrerenderStore: PrerenderStore = (prerenderStore = const prospectiveRoutePrerenderStore: PrerenderStore = (prerenderStore =
{ {
type: 'prerender', type: 'prerender',
staticVariants: null,
phase: 'action', phase: 'action',
// This replicates prior behavior where rootParams is empty in routes // This replicates prior behavior where rootParams is empty in routes
// TODO we need to make this have the proper rootParams for this route // TODO we need to make this have the proper rootParams for this route
...@@ -680,6 +681,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -680,6 +681,7 @@ export class AppRouteRouteModule extends RouteModule<
const finalRoutePrerenderStore: PrerenderStore = (prerenderStore = { const finalRoutePrerenderStore: PrerenderStore = (prerenderStore = {
type: 'prerender', type: 'prerender',
staticVariants: null,
phase: 'action', phase: 'action',
rootParams: {}, rootParams: {},
fallbackRouteParams: null, fallbackRouteParams: null,
...@@ -767,6 +769,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -767,6 +769,7 @@ export class AppRouteRouteModule extends RouteModule<
} else { } else {
prerenderStore = { prerenderStore = {
type: 'prerender-legacy', type: 'prerender-legacy',
staticVariants: null,
phase: 'action', phase: 'action',
rootParams: {}, rootParams: {},
implicitTags, implicitTags,
......
...@@ -244,6 +244,7 @@ export abstract class RouteModule< ...@@ -244,6 +244,7 @@ export abstract class RouteModule<
routes: {}, routes: {},
dynamicRoutes: {}, dynamicRoutes: {},
notFoundRoutes: [], notFoundRoutes: [],
variantCombinationGroups: {},
version: 4, version: 4,
preview: getEdgePreviewProps(), preview: getEdgePreviewProps(),
} as const, } as const,
......
import type { DeepReadonly } from '../../shared/lib/deep-readonly'
import { hashVariants } from './encoding'
/**
* One static variant combination a page declared.
*/
export interface VariantCombination {
/**
* The hash of this combination. It is the path segment under which the
* prerender for this combination is written.
*/
hash: string
/**
* The values the combination assigns, positional against the `keys` of the
* group that holds it.
*
* The values are carried and not only the hash, because a request does not
* always arrive with them. A platform that fills or revalidates a prerender
* rebuilds the request from the artifact. Only the hash in the path survives
* that.
*/
values: string[]
}
/**
* The static variant combinations a page declared that assign one particular
* set of variants.
*
* A combination does not have to assign every variant a page reads, so one page
* can declare several groups. For example `[[theme, 'dark']]` and `[[theme,
* 'light'], [locale, 'en']]` are two groups. The variants a group leaves out
* stay dynamic holes in the prerenders it produces.
*/
export interface VariantCombinationGroup {
/**
* The variant identities that every combination in this group assigns,
* sorted. The shape of the group therefore identifies it, and the order a
* page declared them in does not.
*/
keys: string[]
/**
* Every combination declared for this shape.
*/
combinations: VariantCombination[]
}
/**
* The variant combination groups of one page, most specific first.
*
* A combination that assigns more variants leaves fewer holes, so when two of
* them match one request, the larger one is the better prerender to serve. The
* build sorts them, so that the runtime does not sort for each request.
*/
export type VariantCombinationGroups = VariantCombinationGroup[]
/**
* Finds the variant combination a request matched, and returns null when no
* declared combination describes it.
*
* The values a request resolved cannot be hashed as they arrive. They hold
* every variant the route reads, while a declared combination assigns only some
* of them, so the two hashes would never agree. The `keys` of each group say
* which values to select first. The hash of that projection is what identifies
* the combination.
*
* The groups arrive sorted most specific first, so the first group that matches
* is the one leaving fewest holes.
*/
export function findMatchingVariantCombination(
groups: DeepReadonly<VariantCombinationGroups>,
resolved: Readonly<Record<string, string>>
): { values: Record<string, string>; hash: string } | null {
for (const group of groups) {
const values: Record<string, string> = {}
let assignsEveryKey = true
for (const key of group.keys) {
const value = resolved[key]
// A group that assigns a variant this request never resolved cannot
// describe it, so there is nothing to select.
if (value === undefined) {
assignsEveryKey = false
break
}
values[key] = value
}
if (!assignsEveryKey) {
continue
}
const hash = hashVariants(values)
for (const combination of group.combinations) {
if (combination.hash === hash) {
return { values, hash }
}
}
}
return null
}
/**
* Recovers a declared combination from its hash, and returns null for a hash
* no group holds.
*
* A request does not always arrive with the resolved values beside it. A
* platform that fills or revalidates a prerender rebuilds the request from the
* artifact, where the hash in the path is all that survives, which is why the
* groups carry values and not hashes alone.
*/
export function findVariantCombinationByHash(
groups: DeepReadonly<VariantCombinationGroups>,
hash: string
): { values: Record<string, string>; hash: string } | null {
for (const group of groups) {
for (const combination of group.combinations) {
if (combination.hash !== hash) {
continue
}
const values: Record<string, string> = {}
group.keys.forEach((key, index) => {
values[key] = combination.values[index]
})
return { values, hash }
}
}
return null
}
import { djb2Hash } from '../../shared/lib/hash'
/** /**
* Serializes the variants resolved for a request to a canonical form. The * Serializes the variants resolved for a request to a canonical form. The
* entries are sorted by variant identity and written as JSON. * entries are sorted by variant identity and written as JSON.
...@@ -20,6 +22,20 @@ export function canonicalizeVariants(variants: Record<string, string>): string { ...@@ -20,6 +22,20 @@ export function canonicalizeVariants(variants: Record<string, string>): string {
) )
} }
/**
* Hashes a variant combination.
*
* The result holds only `[0-9a-z]`, because `djb2Hash` returns an unsigned
* 32-bit integer and base 36 of one carries no sign. Code that recognizes the
* hash inside a pathname relies on that shape.
*
* It uses `djb2Hash` and not `node:crypto`, because a proxy can run on the edge
* runtime, where `node:crypto` is unavailable.
*/
export function hashVariants(variants: Record<string, string>): string {
return djb2Hash(canonicalizeVariants(variants)).toString(36)
}
/** /**
* Encodes the resolved variants for transport in `NEXT_VARIANTS_HEADER`. * Encodes the resolved variants for transport in `NEXT_VARIANTS_HEADER`.
* *
......
import type { VariantCombinationGroups } from './combinations'
/**
* The static variant combinations of every page that declared any, in the form
* a proxy needs.
*
* A proxy runs before any routing of ours, so it cannot look a page up by name.
* It matches a pathname first, which is why this holds route regexes where the
* prerender manifest holds page keys.
*/
export interface VariantsManifest {
version: 1
/**
* Keyed by the exact pathname the route is served at.
*/
staticRoutes: Record<string, VariantCombinationGroups>
/**
* Ordered most specific first, each matched by its route regex.
*/
dynamicRoutes: Array<{
/**
* The source of a `RegExp` matching the pathnames this route serves.
*/
regex: string
groups: VariantCombinationGroups
}>
}
/**
* Compiled dynamic-route matchers for one manifest.
*
* The manifest is JSON read once per process, so its object identity is stable
* enough to key on, and each regex is compiled once rather than per request.
*/
const matchersByManifest = new WeakMap<
VariantsManifest,
Array<{ matcher: RegExp; groups: VariantCombinationGroups }>
>()
function getDynamicMatchers(
manifest: VariantsManifest
): Array<{ matcher: RegExp; groups: VariantCombinationGroups }> {
let matchers = matchersByManifest.get(manifest)
if (!matchers) {
matchers = manifest.dynamicRoutes.map(({ regex, groups }) => ({
matcher: new RegExp(regex),
groups,
}))
matchersByManifest.set(manifest, matchers)
}
return matchers
}
/**
* Finds the variant combination groups declared for the route that serves a
* pathname, and returns null for a pathname no declaring route serves.
*
* A static route is looked up by pathname before any regex is tested, so a
* concrete route wins over a dynamic one that would also match it.
*/
export function findVariantGroupsForPathname(
manifest: VariantsManifest,
pathname: string
): VariantCombinationGroups | null {
// `hasOwn`, because the pathname comes from a request and the manifest is a
// plain object parsed from JSON. Indexing it directly answers a pathname such
// as `__proto__` with a prototype member.
if (Object.hasOwn(manifest.staticRoutes, pathname)) {
return manifest.staticRoutes[pathname]
}
for (const { matcher, groups } of getDynamicMatchers(manifest)) {
if (matcher.test(pathname)) {
return groups
}
}
return null
}
import { VARIANTS_PATH_PREFIX } from '../../lib/constants'
import { hashVariants } from './encoding'
/**
* Matches the prefix at the start of a pathname and captures the hash.
*
* The hash is matched as `[0-9a-z]+`, which is the shape `hashVariants`
* produces.
*/
const VARIANTS_PREFIX_PATTERN = new RegExp(
`^/${VARIANTS_PATH_PREFIX}/([0-9a-z]+)`
)
/**
* Splits a base path off a pathname, and returns the two parts.
*
* A base path belongs to a request, and a route knows nothing about it, so
* every function here works on the remainder. The remainder always starts with
* a slash.
*/
function splitBasePath(
pathname: string,
basePath: string | undefined
): [base: string, rest: string] {
if (
!basePath ||
basePath === '/' ||
(pathname !== basePath && !pathname.startsWith(`${basePath}/`))
) {
return ['', pathname]
}
return [basePath, pathname.slice(basePath.length) || '/']
}
/**
* Splits the variants prefix off a pathname, and returns null when the pathname
* carries none.
*
* The base path stays on the remainder. Only the prefix is transport, and a
* separate normalizer removes the base path afterwards.
*/
export function splitVariantsPrefix(
pathname: string,
basePath: string | undefined
): { hash: string; pathname: string } | null {
const [base, rest] = splitBasePath(pathname, basePath)
const match = VARIANTS_PREFIX_PATTERN.exec(rest)
if (!match) {
return null
}
const withoutPrefix = rest.slice(match[0].length)
return {
hash: match[1],
pathname: withoutPrefix === '' ? base || '/' : `${base}${withoutPrefix}`,
}
}
/**
* Inserts the prefix into a pathname, after any base path.
*/
export function insertVariantsPrefix(
pathname: string,
hash: string,
basePath: string | undefined
): string {
const [base, rest] = splitBasePath(pathname, basePath)
const prefix = `/${VARIANTS_PATH_PREFIX}/${hash}`
return rest === '/' ? `${base}${prefix}` : `${base}${prefix}${rest}`
}
/**
* Names the artifact of one prerendered route, and returns the pathname
* unchanged for a route prerendered without variants.
*
* This takes no base path, because the build names route paths and a route path
* carries none.
*/
export function getVariantOutputPath(
pathname: string,
variantValues: Readonly<Record<string, string>> | undefined
): string {
if (!variantValues) {
return pathname
}
return insertVariantsPrefix(pathname, hashVariants(variantValues), undefined)
}
...@@ -29,7 +29,13 @@ import { createWorkStore } from '../async-storage/work-store' ...@@ -29,7 +29,13 @@ import { createWorkStore } from '../async-storage/work-store'
import { workAsyncStorage } from '../app-render/work-async-storage.external' import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { NEXT_VARIANTS_HEADER } from '../../lib/constants' import { NEXT_VARIANTS_HEADER } from '../../lib/constants'
import { getProxyTarget } from '../variants/target' import type { VariantsManifest } from '../variants/manifest'
import { getProxyTarget, getTargetRoutePathname } from '../variants/target'
import { findVariantGroupsForPathname } from '../variants/manifest'
import { findMatchingVariantCombination } from '../variants/combinations'
import { decodeVariants, encodeVariants } from '../variants/encoding'
import { insertVariantsPrefix } from '../variants/prefix'
import type { ResolvedCacheLifeProfiles } from '../config-shared' import type { ResolvedCacheLifeProfiles } from '../config-shared'
import { NEXT_ROUTER_PREFETCH_HEADER } from '../../client/components/app-router-headers' import { NEXT_ROUTER_PREFETCH_HEADER } from '../../client/components/app-router-headers'
import { getTracer } from '../lib/trace/tracer' import { getTracer } from '../lib/trace/tracer'
...@@ -95,6 +101,11 @@ export type AdapterOptions = { ...@@ -95,6 +101,11 @@ export type AdapterOptions = {
IncrementalCache?: typeof import('../lib/incremental-cache').IncrementalCache IncrementalCache?: typeof import('../lib/incremental-cache').IncrementalCache
incrementalCacheHandler?: typeof import('../lib/incremental-cache').CacheHandler incrementalCacheHandler?: typeof import('../lib/incremental-cache').CacheHandler
bypassNextUrl?: boolean bypassNextUrl?: boolean
/**
* The combinations each route declared. They are absent for an edge
* middleware and for a project without variants.
*/
variantsManifest?: VariantsManifest
} }
// This has to be compatible with what the Vercel builder does as well: // This has to be compatible with what the Vercel builder does as well:
...@@ -155,6 +166,25 @@ function setRequestHeaderOverride( ...@@ -155,6 +166,25 @@ function setRequestHeaderOverride(
response.headers.set(`x-middleware-request-${name}`, value) response.headers.set(`x-middleware-request-${name}`, value)
} }
/**
* Re-encodes the values that no declared combination assigns, and returns null
* when a combination assigns all of them.
*/
function encodeUndeclaredVariants(
resolved: Record<string, string>,
declared: Record<string, string>
): string | null {
const undeclared: Record<string, string> = {}
for (const key in resolved) {
if (!(key in declared)) {
undeclared[key] = resolved[key]
}
}
return Object.keys(undeclared).length > 0 ? encodeVariants(undeclared) : null
}
let testApisIntercepted = false let testApisIntercepted = false
function ensureTestApisIntercepted() { function ensureTestApisIntercepted() {
...@@ -295,6 +325,7 @@ export async function adapter( ...@@ -295,6 +325,7 @@ export async function adapter(
routes: {}, routes: {},
dynamicRoutes: {}, dynamicRoutes: {},
notFoundRoutes: [], notFoundRoutes: [],
variantCombinationGroups: {},
preview: getEdgePreviewProps(), preview: getEdgePreviewProps(),
}, },
}) })
...@@ -517,17 +548,65 @@ export async function adapter( ...@@ -517,17 +548,65 @@ export async function adapter(
response.headers.delete(NEXT_VARIANTS_HEADER) response.headers.delete(NEXT_VARIANTS_HEADER)
const target = getProxyTarget(requestURL, response) const target = getProxyTarget(requestURL, response)
const resolvedVariants = decodeVariants(encodedVariants)
// The target is null when the proxy rewrote the request to another // The target is null when the proxy rewrote the request to another
// origin. That origin renders no route of this application, and it does // origin. That origin renders no route of this application, and it does
// not remove an internal header, so this code drops the values. // not remove an internal header, so this code drops the values.
if (target) { if (target && resolvedVariants) {
setRequestHeaderOverride( const basePath = params.request.nextConfig?.basePath
response,
requestHeaders, // TODO(variants): reject a request whose target already carries
NEXT_VARIANTS_HEADER, // `NEXT_VARIANTS_QUERY_PARAM`. Only this code writes that parameter, so
encodedVariants // one already present came from the client. A deployment has to reject
) // rather than remove it, because a rewrite merges the incoming query
// into the destination.
const groups = params.variantsManifest
? findVariantGroupsForPathname(
params.variantsManifest,
getTargetRoutePathname(target.pathname, basePath)
)
: null
const matchedVariants = groups
? findMatchingVariantCombination(groups, resolvedVariants)
: null
if (matchedVariants) {
// The prefix goes on last, after `NEXT_REWRITTEN_PATH_HEADER` and
// `NEXT_REWRITTEN_QUERY_HEADER` above. The client router reads those,
// and they describe the undecorated destination, so a prefix present
// earlier would show the router a rewrite to a different route
// structure.
target.pathname = insertVariantsPrefix(
target.pathname,
matchedVariants.hash,
basePath
)
response.headers.set('x-middleware-rewrite', target.toString())
// TODO(variants): set a marker header saying this application's own
// proxy wrote the prefix. A deployment needs one, because its routing
// rules read it to tell a prefix of ours from one a client invented.
}
// The runtime tier is what travels on. The prefix carries the hash of
// the matched combination, and the origin resolves that hash back to
// the static tier. Where no combination matched, every resolved value
// is runtime.
const runtimeVariants = matchedVariants
? encodeUndeclaredVariants(resolvedVariants, matchedVariants.values)
: encodedVariants
if (runtimeVariants) {
setRequestHeaderOverride(
response,
requestHeaders,
NEXT_VARIANTS_HEADER,
runtimeVariants
)
}
} }
} }
} }
......
...@@ -94,6 +94,7 @@ export const NEXT_FONT_MANIFEST = 'next-font-manifest' ...@@ -94,6 +94,7 @@ export const NEXT_FONT_MANIFEST = 'next-font-manifest'
export const EXPORT_MARKER = 'export-marker.json' export const EXPORT_MARKER = 'export-marker.json'
export const EXPORT_DETAIL = 'export-detail.json' export const EXPORT_DETAIL = 'export-detail.json'
export const PRERENDER_MANIFEST = 'prerender-manifest.json' export const PRERENDER_MANIFEST = 'prerender-manifest.json'
export const VARIANTS_MANIFEST = 'variants-manifest.json'
export const PREFETCH_HINTS = 'prefetch-hints.json' export const PREFETCH_HINTS = 'prefetch-hints.json'
export const PREVIEW_PROPS_MANIFEST = 'preview-props.json' export const PREVIEW_PROPS_MANIFEST = 'preview-props.json'
export const ROUTES_MANIFEST = 'routes-manifest.json' export const ROUTES_MANIFEST = 'routes-manifest.json'
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
import { cacheLife, cacheTag } from 'next/cache'
import { theme } from '../../../variants'
// `r` exists only so the revalidation test has a prerender of its own to
// expire, leaving the entries the other tests read untouched.
export async function generateStaticParams() {
return [{ slug: 'a' }, { slug: 'r' }]
}
export async function unstable_generateStaticVariants() {
return [[[theme, 'dark']], [[theme, 'light']]]
}
// The variant value is read outside the cache scope and passed in, which is the
// only way to get it in there: reading a variant inside `'use cache'` throws.
// The lifetime it selects differs per combination, so the two prerenders of
// this route should not share a revalidate period.
async function cachedByTheme(currentTheme: string, slug: string) {
'use cache'
// Tagged per param so a test can expire one param's prerenders on demand
// rather than waiting out the route's lifetime, without disturbing the
// entries another test depends on. The tag propagates to the prerender, so
// invalidating it makes the next request revalidate, which is the path that
// rebuilds the request for the origin and so the path a variant value has to
// survive. Only a param that `generateStaticParams` covers is usable for
// that: an on-demand param is still having its shell completed in the
// background when the tag is expired, and that write lands afterwards, so the
// entry ends up holding pre-invalidation content under a post-invalidation
// timestamp.
cacheTag(`lifetime-${slug}`)
if (currentTheme === 'light') {
cacheLife('minutes')
} else {
cacheLife('hours')
}
// Stamped inside the cache scope, so it changes only when this entry is
// regenerated. That is what lets a test tell a revalidated response from a
// stale one, which the variant value cannot do: it is the same either way.
return { currentTheme, renderedAt: new Date().toISOString() }
}
// The variant is read here rather than in the page, so that a boundary sits
// above it. The cached call depends on the value, so it moves with the read.
async function Cached({ params }: { params: Promise<{ slug: string }> }) {
const currentTheme = await theme()
const { slug } = await params
const cached = await cachedByTheme(currentTheme, slug)
return (
<>
<p id="theme">{cached.currentTheme}</p>
<p id="rendered-at">{cached.renderedAt}</p>
</>
)
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
return (
<Suspense fallback={<p id="cached">pending</p>}>
<Cached params={params} />
</Suspense>
)
}
import { revalidateTag } from 'next/cache'
// Expires whichever tag it is given, so the next request for anything carrying
// that tag has to revalidate. `expire: 0` makes it immediate, which is what
// lets a test exercise a revalidating render without waiting out a cache
// lifetime. Taking the tag from the caller is what lets one test expire its own
// entries without disturbing the ones another test reads.
export async function GET(request: Request) {
const tag = new URL(request.url).searchParams.get('tag')
if (!tag) {
return new Response('missing tag', { status: 400 })
}
revalidateTag(tag, { expire: 0 })
return new Response('ok')
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
// Enabled in the config rather than left to the test matrix, because the
// route this fixture exists for selects a `cacheLife` per variant, and `'use
// cache'` does not compile without it.
cacheComponents: true,
experimental: {
variants: true,
},
}
// Set by `variants-cache-lifetime-base-path.test.ts`, which runs the suite a
// second time under a base path. The value arrives through `nextTestSetup`'s
// `env`, so that it reaches a local build and a deployed build alike.
if (process.env.BASE_PATH) {
nextConfig.basePath = process.env.BASE_PATH
}
module.exports = nextConfig
import { wrapProxy } from 'next/dist/server/variants/wrap-proxy'
import { theme } from './variants'
// The variants transform will wrap the proxy automatically, synthesize one when
// the project has none, and derive each route's variants from its module graph,
// layouts included. Wired by hand until then.
export const proxy = wrapProxy({ '/lifetime/[slug]': [theme] })
export const config = {
matcher: ['/lifetime/:slug'],
}
'use variants'
import { unstable_variant } from 'next/variants'
// The second argument is the variant's identity, which the variants transform
// will inject. It is passed explicitly until that transform exists.
export const theme = unstable_variant(
(request) =>
request.cookies.get('theme')?.value === 'dark' ? 'dark' : 'light',
'theme@variants.ts'
)
'use client'
import Link from 'next/link'
import { useState } from 'react'
import type { ReactNode } from 'react'
/**
* Keeps a `Link` out of the DOM until the checkbox is toggled.
*
* A `Link` prefetches when it enters the viewport. A test that asserts on the
* contents of a prefetch has to know when that happens, so the link becomes
* visible only inside an `act` scope.
*/
export function LinkAccordion({
href,
children,
}: {
href: string
children: ReactNode
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href}>{children}</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
import { Suspense } from 'react'
import { country, locale, theme } from '../../variants'
import { VariantValues } from '../variant-values'
// Three combinations that are all accepted. The second assigns everything the
// first does and one variant more, so the two are ordered. The third assigns a
// variant that neither of the others does, and gives `theme` a different value,
// so no request matches it together with either.
export function unstable_generateStaticVariants() {
return [
[[theme, 'dark']],
[
[theme, 'dark'],
[locale, 'en'],
],
[
[theme, 'light'],
[country, 'us'],
],
]
}
export default function Page() {
return (
<Suspense fallback={<p id="pending">pending</p>}>
<VariantValues />
</Suspense>
)
}
import { Suspense } from 'react'
import { locale, theme } from '../../../variants'
export async function generateStaticParams() {
return [{ slug: 'a' }]
}
// Declared for the route rather than per params row, so it applies to `a` here,
// to any param prerendered on demand, and to a fallback shell.
export async function unstable_generateStaticVariants() {
return [
[
[theme, 'light'],
[locale, 'en'],
],
[
[theme, 'dark'],
[locale, 'en'],
],
]
}
// The param is awaited at the top level, with no boundary above it, so a
// fallback shell for this route can contain nothing and comes out empty. That
// is what makes a param nobody enumerated fall through to being prerendered on
// demand, which is the case this route exists to cover. See `shell/[slug]` for
// the opposite arrangement.
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return (
<>
<Suspense fallback={<p id="theme">pending</p>}>
<p id="theme">{theme()}</p>
</Suspense>
<Suspense fallback={<p id="locale">pending</p>}>
<p id="locale">{locale()}</p>
</Suspense>
<p id="slug">{slug}</p>
</>
)
}
import { Suspense } from 'react'
import { banner, theme } from '../../../variants'
export async function generateStaticParams() {
return [{ slug: 'built' }]
}
export async function unstable_generateStaticVariants() {
return [[[theme, 'dark']], [[theme, 'light']]]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return (
<>
<Suspense fallback={<p id="theme">pending</p>}>
<p id="theme">{theme()}</p>
</Suspense>
<p id="slug">{slug}</p>
<Suspense fallback={<p id="banner">pending</p>}>
<p id="banner">{banner()}</p>
</Suspense>
</>
)
}
...@@ -4,7 +4,7 @@ import { VariantValues } from './variant-values' ...@@ -4,7 +4,7 @@ import { VariantValues } from './variant-values'
export default function Page() { export default function Page() {
return ( return (
<Suspense fallback={<p id="pending">pending</p>}> <Suspense fallback={null}>
<VariantValues /> <VariantValues />
</Suspense> </Suspense>
) )
......
import { Suspense } from 'react'
import { locale, theme } from '../../variants'
// No dynamic segments, so this route builds no static paths at all. The
// combinations still have to be prerendered against, which is what makes the
// variants read below possible: without them there is no value to bake and the
// read has no boundary to postpone into.
export async function unstable_generateStaticVariants() {
return [
[
[theme, 'dark'],
[locale, 'en'],
],
[
[theme, 'light'],
[locale, 'en'],
],
]
}
export default async function Page() {
return (
<>
<Suspense fallback={<p id="theme">pending</p>}>
<p id="theme">{theme()}</p>
</Suspense>
<Suspense fallback={<p id="locale">pending</p>}>
<p id="locale">{locale()}</p>
</Suspense>
</>
)
}
// A statically prerendered route that reads no variants, so that variant routes
// can be compared against how an ordinary prerender behaves.
export default function Page() {
return <p id="plain">plain</p>
}
import { LinkAccordion } from '../components/link-accordion'
export default function Page() {
return (
<>
<LinkAccordion href="/enumerated/never-enumerated">
Never enumerated
</LinkAccordion>
<LinkAccordion href="/on-demand/built">Enumerated param</LinkAccordion>
</>
)
}
...@@ -2,11 +2,9 @@ import { Suspense } from 'react' ...@@ -2,11 +2,9 @@ import { Suspense } from 'react'
import { VariantValues } from '../variant-values' import { VariantValues } from '../variant-values'
// The proxy rewrites `/rewrite-source` here. The variants of this route are the
// ones that apply, because a rewrite decides which route renders.
export default function Page() { export default function Page() {
return ( return (
<Suspense fallback={<p id="pending">pending</p>}> <Suspense fallback={null}>
<VariantValues /> <VariantValues />
</Suspense> </Suspense>
) )
......
import { Suspense } from 'react'
import { theme } from '../../variants'
// Declared so that a request to this route is prefixed with its combination,
// which is what puts the internal query parameter carrying the combination on
// the path the origin sees. The page reads `searchParams` so that anything left
// in that query becomes visible to user code.
export async function unstable_generateStaticVariants() {
return [[[theme, 'dark']], [[theme, 'light']]]
}
async function SearchParams({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[] | undefined>>
}) {
const resolved = await searchParams
return <p id="search-params">{Object.keys(resolved).sort().join(',')}</p>
}
export default async function Page({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[] | undefined>>
}) {
return (
<>
<Suspense fallback={<p id="theme">pending</p>}>
<p id="theme">{theme()}</p>
</Suspense>
<Suspense fallback={<p id="search-params">pending</p>}>
<SearchParams searchParams={searchParams} />
</Suspense>
</>
)
}
import { Suspense } from 'react'
import { banner, locale, theme } from '../../../variants'
// Deliberately no `generateStaticParams`: every param is then a fallback param,
// so the fallback shell is the only thing prerendered here and an empty one is
// an error rather than something a concrete prerender makes up for. The
// combinations below are what let the shell be prerendered at all.
export async function unstable_generateStaticVariants() {
return [
[
[theme, 'light'],
[locale, 'en'],
],
[
[theme, 'dark'],
[locale, 'en'],
],
]
}
async function Slug({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
return <p id="slug">{slug}</p>
}
// The param is awaited behind a boundary, so a fallback shell for this route
// keeps everything above it and only leaves a hole where the param goes. It is
// therefore the only artifact this route has, and it must not be empty. See
// `enumerated/[slug]`, whose param is awaited above every boundary, for the
// arrangement whose fallback shell is empty and whose unnamed params are
// prerendered on demand instead.
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
return (
<>
<Suspense fallback={<p id="theme">pending</p>}>
<p id="theme">{theme()}</p>
</Suspense>
<Suspense fallback={<p id="locale">pending</p>}>
<p id="locale">{locale()}</p>
</Suspense>
<Suspense fallback={<p id="slug">pending</p>}>
<Slug params={params} />
</Suspense>
<Suspense fallback={<p id="banner">pending</p>}>
<p id="banner">{banner()}</p>
</Suspense>
</>
)
}
import { Suspense } from 'react'
import { locale, theme } from '../../variants'
// Two combinations whose key sets contain one another, which is the only shape
// that puts a page in more than one group. Every other route of this fixture
// declares one key set and therefore one group.
//
// `[theme]` is a subset of `[theme, locale]`, so the ambiguity check permits
// the pair: the larger combination is the more specific match rather than a
// rival to it. A request that resolves `theme=dark` and `locale=en` matches
// both groups, and the more specific one has to win. A request that resolves
// `theme=dark` with any other locale matches only the smaller group, which
// leaves `locale` a dynamic hole.
export async function unstable_generateStaticVariants() {
return [
[[theme, 'dark']],
[
[theme, 'dark'],
[locale, 'en'],
],
]
}
// Both variants sit behind a boundary, so the prerender of the smaller group
// has a shell to serve while `locale` resolves.
//
// A fallback carries the same id as the value it stands in for, so one
// assertion reads either. A prerender that bakes a variant renders its value,
// and one that leaves the variant a hole renders `pending`, which is what tells
// the prerenders of this route apart.
export default async function Page() {
return (
<>
<Suspense fallback={<p id="theme">pending</p>}>
<p id="theme">{theme()}</p>
</Suspense>
<Suspense fallback={<p id="locale">pending</p>}>
<p id="locale">{locale()}</p>
</Suspense>
</>
)
}
...@@ -3,11 +3,10 @@ import { headers } from 'next/headers' ...@@ -3,11 +3,10 @@ import { headers } from 'next/headers'
import { locale, theme } from '../variants' import { locale, theme } from '../variants'
// `connection()` holds both reads at request time. A prerender cannot yet // Reading a variant while prerendering is not supported yet, so the reads are
// supply a variant value, so a read during one has nothing to return. // kept at request time. `connection()` defers them, and callers wrap this in a
// // `<Suspense>` boundary, which Cache Components requires for a dynamic read.
// A variant is runtime data, and Cache Components requires a Suspense boundary // Remove both once static generation supports variants.
// above a read of one. Every caller of this component provides that boundary.
export async function VariantValues() { export async function VariantValues() {
await connection() await connection()
const requestHeaders = await headers() const requestHeaders = await headers()
......
import { NextResponse, type NextRequest } from 'next/server' import { NextResponse, type NextRequest } from 'next/server'
import { wrapProxy } from 'next/dist/server/variants/wrap-proxy' import { wrapProxy } from 'next/dist/server/variants/wrap-proxy'
import { country, locale, theme } from './variants' import { banner, locale, theme } from './variants'
// This table names the variants of each route by hand. // The variants transform will wrap the proxy automatically, synthesize one when
// the project has none, and derive each route's variants from its module graph,
// layouts included. Wired by hand until then.
// //
// TODO(variants): the variants transform wraps the proxy, synthesizes one for a // A route reads only some of the variants a project declares, and resolving the
// project that has none, and derives each route's variants from its module // rest would send the origin values nothing consumes. `/rewrite-target` is
// graph, layouts included. // listed rather than `/rewrite-source`, because the rewrite below decides which
// // route renders.
// A route reads only some of the variants that a project declares. Resolution
// of the rest would send the origin values that no code reads. The table lists
// `/rewrite-target` and not `/rewrite-source`, because the rewrite below decides
// which route renders.
const variantsByRoute = { const variantsByRoute = {
'/': [locale, theme], '/': [banner, locale, theme],
'/rewrite-target': [locale, theme], '/enumerated/[slug]': [locale, theme],
// This route declares static combinations that assign `country`, so a request '/on-demand/[slug]': [banner, theme],
// to it resolves that variant as well, even though the route reads only the '/paramless': [locale, theme],
// other two. '/rewrite-target': [banner, locale, theme],
'/declared': [country, locale, theme], '/search-params': [theme],
// The `config.matcher` below omits this route on purpose. See the route. '/specificity': [locale, theme],
'/shell/[slug]': [banner, locale, theme],
// Deliberately absent from `config.matcher` below. See the route itself.
'/unmatched-by-proxy': [locale, theme], '/unmatched-by-proxy': [locale, theme],
} }
...@@ -50,5 +50,15 @@ export const proxy = wrapProxy(variantsByRoute, (request: NextRequest) => { ...@@ -50,5 +50,15 @@ export const proxy = wrapProxy(variantsByRoute, (request: NextRequest) => {
}) })
export const config = { export const config = {
matcher: ['/', '/declared', '/rewrite-source', '/external'], matcher: [
'/',
'/rewrite-source',
'/external',
'/enumerated/:slug',
'/shell/:slug',
'/on-demand/:slug',
'/paramless',
'/search-params',
'/specificity',
],
} }
...@@ -2,26 +2,26 @@ ...@@ -2,26 +2,26 @@
import { unstable_variant } from 'next/variants' import { unstable_variant } from 'next/variants'
// The second argument is the identity of the variant. // The second argument is the variant's identity, which the variants transform
// // will inject. It is passed explicitly until that transform exists.
// TODO(variants): the variants transform injects the identity. This fixture
// passes it explicitly until that transform exists.
export const theme = unstable_variant( export const theme = unstable_variant(
(request) => (request) =>
request.cookies.get('theme')?.value === 'dark' ? 'dark' : 'light', request.cookies.get('theme')?.value === 'dark' ? 'dark' : 'light',
'theme@variants.ts' 'theme@variants.ts'
) )
// A second variant. A resolved set then holds more than one pair, which // A second variant, so that a resolved combination holds more than one pair and
// exercises the canonical ordering. // therefore exercises the canonical ordering.
export const locale = unstable_variant( export const locale = unstable_variant(
(request) => (request.cookies.get('locale')?.value === 'de' ? 'de' : 'en'), (request) => (request.cookies.get('locale')?.value === 'de' ? 'de' : 'en'),
'locale@variants.ts' 'locale@variants.ts'
) )
// A third variant, read by no route. It lets `/declared` declare two // Deliberately named by no route's `unstable_generateStaticVariants`, which is
// combinations that each assign a variant the other leaves out. // what makes it Tier 2. Every request resolves it, like the others. No
export const country = unstable_variant( // prerender is produced per value, so it must not partition the cache, and it
(request) => (request.cookies.get('country')?.value === 'de' ? 'de' : 'us'), // stays a dynamic hole in whichever prerender serves the request.
'country@variants.ts' export const banner = unstable_variant(
(request) => request.cookies.get('banner')?.value ?? 'none',
'banner@variants.ts'
) )
import { theme } from '../../variants'
export async function unstable_generateStaticVariants() {
return [[[theme, 'light']], [[theme, 'dark']]]
}
// The variant is read with no boundary above it, so the prerender that omits
// the variants comes out empty. The build has to reject that.
export default async function Page() {
return <p id="theme">{await theme()}</p>
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { cookies } from 'next/headers'
import { theme } from '../../variants'
export async function unstable_generateStaticVariants() {
return [[[theme, 'light']], [[theme, 'dark']]]
}
// The route reads a cookie with no boundary above it, and no combination bakes
// that value, so the prerender of each combination comes out empty as well as
// the one that omits the variants. Declaring combinations must not excuse the
// route from the diagnostic, which is the difference from `above-boundary`:
// there the value read above the boundary is a variant, so a combination bakes
// it and only the prerender omitting the variants is empty.
export default async function Page() {
const store = await cookies()
return <p id="theme">{store.get('theme')?.value ?? 'none'}</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
// The route this fixture exists for reads a variant while prerendering, which
// only happens with Cache Components. Enabled here rather than left to the
// test matrix, so that the build fails for the reason under test in every
// configuration.
cacheComponents: true,
experimental: {
variants: true,
},
}
module.exports = nextConfig
import { type NextRequest } from 'next/server'
import { wrapProxy } from 'next/dist/server/variants/wrap-proxy'
import { theme } from './variants'
// The variants transform will wrap the proxy automatically and derive each
// route's variants from its module graph. Wired by hand until then.
const variantsByRoute = {
'/above-boundary': [theme],
}
export const proxy = wrapProxy(variantsByRoute, (_request: NextRequest) => {
return undefined
})
export const config = {
matcher: ['/above-boundary'],
}
'use variants'
import { unstable_variant } from 'next/variants'
// The second argument is the variant's identity, which the variants transform
// will inject. It is passed explicitly until that transform exists.
export const theme = unstable_variant(
(request) =>
request.cookies.get('theme')?.value === 'dark' ? 'dark' : 'light',
'theme@variants.ts'
)
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
import { theme } from '../../../variants'
// One row, because Cache Components requires at least one and because it makes
// this param prerenderable, which is what allows a shell to be upgraded. The
// test asks for a value the list does not name, so its request is served a
// fallback shell and triggers the upgrade.
export function generateStaticParams() {
return [{ one: 'b' }]
}
export async function unstable_generateStaticVariants() {
return [[[theme, 'dark']], [[theme, 'light']]]
}
// Each read sits behind its own boundary. A declared combination resolves its
// variant at once, so the theme lands in the shell, while the param stays a
// hole until a request supplies it. That is what makes the upgraded shells of
// two combinations differ.
export default async function Page({
params,
}: {
params: Promise<{ one: string }>
}) {
return (
<>
<Suspense fallback={<p id="theme">pending</p>}>
<p id="theme">{theme()}</p>
</Suspense>
<Suspense fallback={<p id="one">pending</p>}>
<One params={params} />
</Suspense>
</>
)
}
async function One({ params }: { params: Promise<{ one: string }> }) {
const { one } = await params
return <p id="one">{one}</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
// An upgraded fallback shell only exists with Partial Prefetching, which
// requires Cache Components. Enabled here rather than left to the test
// matrix, so the route under test takes that path in every configuration.
cacheComponents: true,
partialPrefetching: true,
experimental: {
variants: true,
},
}
module.exports = nextConfig
import { wrapProxy } from 'next/dist/server/variants/wrap-proxy'
import { theme } from './variants'
export const proxy = wrapProxy({
'/prefix/[one]': [theme],
})
export const config = {
matcher: ['/prefix/:one'],
}
'use variants'
import { unstable_variant } from 'next/variants'
// The second argument is the variant's identity, which the variants transform
// will inject. It is passed explicitly until that transform exists.
export const theme = unstable_variant(
(request) =>
request.cookies.get('theme')?.value === 'dark' ? 'dark' : 'light',
'theme@variants.ts'
)
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
// The page reads no variant. The error under test comes from the middleware
// file, and a page that resolved a variant could fail for its own reasons and
// hide it.
export default function Page() {
return <p id="page">page</p>
}
import { wrapProxy } from 'next/dist/server/variants/wrap-proxy'
import { theme } from './variants'
// The legacy `middleware.ts` filename is what this fixture exists for. Next.js
// compiles it for the edge runtime unless it opts out, and the variants
// manifest is not readable there, so the build rejects the pairing.
export const middleware = wrapProxy({
'/': [theme],
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
variants: true,
},
}
module.exports = nextConfig
'use variants'
import { unstable_variant } from 'next/variants'
// The second argument is the variant's identity, which the variants transform
// will inject. It is passed explicitly until that transform exists.
export const theme = unstable_variant(
(request) =>
request.cookies.get('theme')?.value === 'dark' ? 'dark' : 'light',
'theme@variants.ts'
)
import { getCachedSentinelValue } from '../../sentinel'
export async function generateStaticParams() {
return [{ slug: 'built' }]
}
// The shape of `/declared/[slug]` with no variants at all: the param is read
// above every boundary here too, so this fallback shell is empty as well, and
// the route is absent from the proxy.
//
// It exists so that what a param the build never named costs is read off a
// route that declares no combinations, rather than asserted from memory. A
// difference between the two is what makes such a cost specific to variants.
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return (
<>
<p id="slug">{slug}</p>
<p id="cached-sentinel">{await getCachedSentinelValue()}</p>
</>
)
}
import { Suspense } from 'react'
import { getCachedSentinelValue } from '../../sentinel'
import { theme } from '../../../variants'
export async function generateStaticParams() {
return [{ slug: 'built' }]
}
export async function unstable_generateStaticVariants() {
return [[[theme, 'dark']], [[theme, 'light']]]
}
// The param is read above every boundary, so the fallback shell of every
// combination is empty and there is nothing to serve while the param resolves.
// A param the build never named therefore has to be prerendered by the request
// that asks for it, and that prerender belongs to the combination the request
// resolved.
//
// The variant sits behind a boundary, which every route that reads one needs:
// the prerender that omits the variants has to leave a hole somewhere, and a
// read above every boundary leaves it nothing to prerender at all. A
// combination bakes the value, so the boundary is transparent there and the
// value is in the document.
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return (
<>
<p id="slug">{slug}</p>
<Suspense fallback={<p id="theme">pending</p>}>
<p id="theme">{theme()}</p>
</Suspense>
<p id="cached-sentinel">{await getCachedSentinelValue()}</p>
</>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
const { PHASE_PRODUCTION_BUILD } = require('next/constants')
function getSentinelValue() {
return process.env.NEXT_PHASE === PHASE_PRODUCTION_BUILD
? 'buildtime'
: 'runtime'
}
/**
* The phase of the render that filled this cache entry, rather than of the
* render that reads it.
*
* A route whose fallback shell is empty has nothing to serve while its params
* resolve, so a param the build never named has to be prerendered by the
* request that asks for it. This reports whether that happened.
*
* A prerender carries a resume data cache, and an empty shell carries one too.
* A request answered by resuming such a shell therefore replays what the build
* put in this entry and reports `buildtime`, however many times the route is
* rendered around it. A request that prerenders the route for itself fills the
* entry while it runs and reports `runtime`.
*
* The value has to be read through a cache scope for that. Read directly it
* reports the phase of the current render, which is `runtime` either way.
*/
export async function getCachedSentinelValue() {
'use cache'
return getSentinelValue()
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
// Enabled in the config rather than left to the test matrix, because the
// sentinel this fixture reads its result from is cached, and `'use cache'`
// does not compile without it. A route only reaches the state under test with
// Cache Components anyway: without it a combination leaves no hole, so there
// is no shell to resume and no prerender to keep.
cacheComponents: true,
experimental: {
variants: true,
},
}
module.exports = nextConfig
import { wrapProxy } from 'next/dist/server/variants/wrap-proxy'
import { theme } from './variants'
// The variants transform will wrap the proxy automatically and derive each
// route's variants from its module graph. Wired by hand until then.
//
// `/control/[slug]` is deliberately absent, so that nothing resolves a variant
// for it and it keeps the shape of a route in a project without variants.
const variantsByRoute = {
'/declared/[slug]': [theme],
}
export const proxy = wrapProxy(variantsByRoute, () => undefined)
export const config = {
matcher: ['/declared/:slug'],
}
'use variants'
import { unstable_variant } from 'next/variants'
// The second argument is the variant's identity, which the variants transform
// will inject. It is passed explicitly until that transform exists.
export const theme = unstable_variant(
(request) =>
request.cookies.get('theme')?.value === 'dark' ? 'dark' : 'light',
'theme@variants.ts'
)
// Runs the whole variants suite again under a base path. // Runs the whole variants suite again under a base path.
// //
// A base path prefixes every path a client asks for, while a route carries // A base path prefixes every path a client asks for, and variants are almost
// none, so every site that matches a request against a route has to remove it // entirely path work: the proxy matches a route, the adapter writes a prefix,
// first. // routing strips it again, and the build writes artifacts under it. Each of
// those is a place the prefix and the base path can disagree, so the suite is
// run again rather than a few cases being picked out of it.
// //
// The variable is read by `variants.test.ts`, which hands it to the build and // The variable is read by `variants.test.ts`, which hands it to the build and
// prefixes the paths it requests, and by the fixture's `next.config.js`. // prefixes the paths it requests, and by the fixture's `next.config.js`.
......
// Runs the cache lifetime suite again under a base path.
//
// This suite is the only one that revalidates a stale prerender, and a
// revalidation takes a path no other test does: the request the origin sees is
// rebuilt from the artifact rather than routed from a client. That rebuild
// starts from the path the artifact was written under, which is where a base
// path and the variants prefix can disagree.
//
// The variable is read by `variants-cache-lifetime.test.ts`, which hands it to
// the build and prefixes the paths it requests, and by the fixture's
// `next.config.js`.
process.env.BASE_PATH = '/base'
require('./variants-cache-lifetime.test')
import { isNextStart, nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { retry } from 'next-test-utils'
import { basePath, url } from './base-path'
// Variants are supported with Turbopack only, and enabling them rejects a
// webpack build, which `variants-webpack.test.ts` covers.
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'variants with a cache lifetime per combination',
() => {
const { next, skipped } = nextTestSetup({
files: __dirname + '/fixtures/cache-lifetime',
// TODO(variants): enable this for a deployment. A platform serves a
// combination from the routing rules the adapter emits, and those do not
// exist yet, so every assertion here is about a self-hosted server.
skipDeployment: true,
// Handed to the build rather than read from `process.env` there, so that
// a deployed build receives it too: only what goes through here is
// forwarded to the remote build.
env: basePath ? { BASE_PATH: basePath } : undefined,
})
if (skipped) {
return
}
it('should resolve a variant while revalidating a stale prerender', async () => {
// A tag rather than the route's own lifetime, so the entry goes stale at
// once instead of after an hour.
const before = await next.render$(url('/lifetime/r'), undefined, {
headers: { cookie: 'theme=dark' },
})
expect(before('#theme').text()).toBe('dark')
const renderedAt = before('#rendered-at').text()
expect(renderedAt).not.toBe('')
const revalidateRes = await next.fetch(url('/revalidate?tag=lifetime-r'))
expect(revalidateRes.status).toBe(200)
// The stamp is what shows the entry was replaced. The variant reads
// `dark` before and after, so a response carrying the old stamp is the
// stale entry served while the revalidation runs behind it, and asserting
// on the variant alone would pass without that render happening.
await retry(async () => {
const after = await next.render$(url('/lifetime/r'), undefined, {
headers: { cookie: 'theme=dark' },
})
expect(after('#rendered-at').text()).not.toBe(renderedAt)
expect(after('#theme').text()).toBe('dark')
})
})
it('should resolve the variant the cache lifetime is selected from', async () => {
const $ = await next.render$(url('/lifetime/a'), undefined, {
headers: { cookie: 'theme=dark' },
})
expect($('#theme').text()).toBe('dark')
})
if (isNextStart) {
it('should give each combination its own cache lifetime', async () => {
const darkResponse = await next.fetch(url('/lifetime/a'), {
headers: { cookie: 'theme=dark' },
})
expect(darkResponse.headers.get('cache-control')).toContain(
's-maxage=3600'
)
const darkBrowser = await next.browser(url('/lifetime/a'), {
async beforePageLoad(page: Playwright.Page) {
await page
.context()
.addCookies([{ name: 'theme', value: 'dark', url: next.url }])
},
})
await retry(async () => {
expect(await darkBrowser.elementByCss('#theme').text()).toBe('dark')
})
const lightResponse = await next.fetch(url('/lifetime/a'), {
headers: { cookie: 'theme=light' },
})
expect(lightResponse.headers.get('cache-control')).toContain(
's-maxage=60'
)
const lightBrowser = await next.browser(url('/lifetime/a'), {
async beforePageLoad(page: Playwright.Page) {
await page
.context()
.addCookies([{ name: 'theme', value: 'light', url: next.url }])
},
})
await retry(async () => {
expect(await lightBrowser.elementByCss('#theme').text()).toBe('light')
})
})
}
}
)
import { isNextDev, nextTestSetup } from 'e2e-utils'
// Variants are supported with Turbopack only, and enabling them rejects a
// webpack build, which `variants-webpack.test.ts` covers.
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'variants with a variant read above every boundary',
() => {
const { next, skipped } = nextTestSetup({
files: __dirname + '/fixtures/empty-shell',
// Every route of this fixture exists to fail the build, so the harness
// must not build or start it. Both modes below drive Next.js by hand, and
// a deployment cannot run a build that fails.
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
if (isNextDev) {
it('should report the read above a Suspense boundary in the dev overlay', async () => {
await next.start()
const browser = await next.browser('/above-boundary')
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "Next.js encountered runtime data during prerendering.",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/above-boundary/page.tsx (10:36) @ Page
> 10 | return <p id="theme">{await theme()}</p>
| ^",
"stack": [
"Page app/above-boundary/page.tsx (10:36)",
],
}
`)
})
return
}
// Each route is built on its own, because a build of both stops at
// whichever fails first.
it.each([['above-boundary'], ['runtime-above-boundary']])(
'should fail the build for %s',
async (route) => {
const { exitCode, cliOutput } = await next.build({
args: ['--debug-build-paths', `app/${route}/page.tsx`],
})
expect(exitCode).toBe(1)
expect(cliOutput).toContain(
`Error occurred prerendering page "/${route}"`
)
expect(cliOutput).toContain(
'Next.js encountered uncached or runtime data during prerendering'
)
}
)
}
)
import { isNextDev, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
// Variants are supported with Turbopack only, and enabling them rejects a
// webpack build, which `variants-webpack.test.ts` covers.
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'variants on an upgraded fallback shell',
() => {
const { next, skipped } = nextTestSetup({
files: __dirname + '/fixtures/fallback-upgrade',
// TODO(variants): enable this for a deployment. A platform serves a
// combination from the routing rules the adapter emits, and those do not
// exist yet, so every assertion here is about a self-hosted server.
skipDeployment: true,
})
if (skipped) {
return
}
if (isNextDev) {
// Dev prerenders nothing, so it has no fallback shell to upgrade.
it.skip('upgrades the shell of each combination separately', () => {})
return
}
it('should upgrade the shell of each combination separately', async () => {
// `generateStaticParams` names `b` alone, so `/prefix/c` is served a
// fallback shell where the param is a hole. That request triggers an
// upgrade in the background, and a later one is served a shell built for
// `c`. Partial Prefetching is what enables the upgrade, and nothing else
// in this suite turns it on.
//
// The upgraded shell is rendered for one combination and bakes its theme,
// so each combination needs an upgraded shell of its own. That is what
// the prefix on the cache key provides. Without it the second combination
// reads the first one's shell and is answered with its theme.
for (const theme of ['dark', 'light']) {
const fallback = await next.render$('/prefix/c', undefined, {
headers: { cookie: `theme=${theme}` },
})
// `first()`, because a fallback shell emits the placeholder and the
// resume then emits the value, so both elements carry this id.
expect({
theme: fallback('#theme').first().text(),
one: fallback('#one').first().text(),
}).toEqual({ theme, one: 'pending' })
await retry(async () => {
const upgraded = await next.render$('/prefix/c', undefined, {
headers: { cookie: `theme=${theme}` },
})
expect({
theme: upgraded('#theme').first().text(),
one: upgraded('#one').first().text(),
}).toEqual({ theme, one: 'c' })
})
}
})
}
)
import { isNextDev, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
const expectedError =
'`experimental.variants` is not supported in the Middleware file at "./middleware.ts". Rename it to a Proxy file, which always runs on the Node.js runtime.'
// Variants are supported with Turbopack only, so a webpack build rejects the
// config of this fixture before it reads the middleware file.
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'variants in a middleware file',
() => {
const { next, skipped } = nextTestSetup({
files: __dirname + '/fixtures/middleware-file',
// The fixture exists to fail, so the harness must not build or start it.
// Both modes below drive Next.js by hand instead.
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
if (isNextDev) {
beforeAll(async () => {
await next.start()
})
it('should report the middleware file and keep the dev server up', async () => {
// Renaming the file has to recover without a restart, so the dev server
// reports the error and carries on rather than failing the route.
const response = await next.fetch('/')
expect(response.status).toBe(200)
await retry(async () => {
expect(next.cliOutput).toContain(expectedError)
})
})
} else {
it('should fail the build', async () => {
const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1)
expect(cliOutput).toContain(expectedError)
})
}
}
)
import { isNextDev, nextTestSetup } from 'e2e-utils'
const CONTROL = '/control'
const DECLARED = '/declared'
// Variants are supported with Turbopack only, and enabling them rejects a
// webpack build, which `variants-webpack.test.ts` covers.
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'variants with a param the build did not name',
() => {
const { next, skipped } = nextTestSetup({
files: __dirname + '/fixtures/on-demand-param',
// TODO(variants): enable this for a deployment. A platform serves a
// combination from the routing rules the adapter emits, and those do not
// exist yet, so every assertion here is about a self-hosted server.
skipDeployment: true,
})
if (skipped) {
return
}
if (isNextDev) {
// Dev prerenders nothing, so it has no entry to keep and no shell to
// resume. The second test therefore cannot hold here at all. The first
// would pass, but only because a dev render and an on-demand prerender
// report the same sentinel, so it would prove nothing.
it.skip('prerenders a param the build did not name', () => {})
return
}
it('should prerender a param the build did not name for the request that asks', async () => {
// `/control/[slug]` has the same shape and declares no combinations. If
// both routes behave alike, the combinations are not the cause.
//
// The sentinel reports which render filled the entry, not which render
// reads it. A request that resumes the empty shell replays what the build
// wrote, and reports `buildtime`. The markup cannot report this, because
// the page looks the same either way. The cache state cannot either,
// because resuming a shell looks like serving a prerender.
//
// Two params are asked for, because there must be one prerender per
// param. A single entry that ignored the param would answer for both, and
// would serve one param's page under the other's URL. So each response's
// own param is asserted too.
for (const route of [CONTROL, DECLARED]) {
for (const slug of ['unnamed-one', 'unnamed-two']) {
const $ = await next.render$(`${route}/${slug}`, undefined, {
headers: { cookie: 'theme=dark' },
})
expect({
route,
slug: $('#slug').text(),
cachedSentinel: $('#cached-sentinel').text(),
}).toEqual({ route, slug, cachedSentinel: 'runtime' })
}
}
})
it('should serve a param the build named from the prerender of its combination', async () => {
const $ = await next.render$(`${DECLARED}/built`, undefined, {
headers: { cookie: 'theme=dark' },
})
expect({
slug: $('#slug').text(),
theme: $('#theme').text(),
cachedSentinel: $('#cached-sentinel').text(),
}).toEqual({ slug: 'built', theme: 'dark', cachedSentinel: 'buildtime' })
})
}
)
This diff is collapsed.
...@@ -14,6 +14,7 @@ function createCache() { ...@@ -14,6 +14,7 @@ function createCache() {
routes: {}, routes: {},
dynamicRoutes: {}, dynamicRoutes: {},
notFoundRoutes: [], notFoundRoutes: [],
variantCombinationGroups: {},
preview: { preview: {
previewModeId: 'id', previewModeId: 'id',
previewModeSigningKey: 'key', previewModeSigningKey: 'key',
......
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