Match variants only to available prerender outputs

The build records a combination only when it adds its static or dynamic
prerender entry. The final manifests omit combinations with no output,
while empty proxy route entries preserve route precedence.
parent 2900d616
...@@ -218,7 +218,7 @@ import { runAfterProductionCompile } from './after-production-compile' ...@@ -218,7 +218,7 @@ import { runAfterProductionCompile } from './after-production-compile'
import { generatePreviewKeys } from './preview-key-utils' import { generatePreviewKeys } from './preview-key-utils'
import { handleBuildComplete } from './adapter/build-complete' import { handleBuildComplete } from './adapter/build-complete'
import type { VariantCombinationGroups } from '../server/variants/combinations' import type { VariantCombinationGroups } from '../server/variants/combinations'
import { buildVariantsManifest } from './variants/manifest' import { buildVariantsManifest, recordVariantOutput } from './variants/manifest'
import { getVariantOutputPath } from '../server/variants/prefix' import { getVariantOutputPath } from '../server/variants/prefix'
import { import {
sortPageObjects, sortPageObjects,
...@@ -421,13 +421,13 @@ export type PrerenderManifest = { ...@@ -421,13 +421,13 @@ export type PrerenderManifest = {
/** @deprecated only kept for the builder, use PreviewPropsManifest within Next.js itself */ /** @deprecated only kept for the builder, use PreviewPropsManifest within Next.js itself */
preview: __ApiPreviewProps preview: __ApiPreviewProps
/** /**
* The static variant combinations each page declared, grouped by which * The static variant combinations that produced a prefixed prerender output,
* variants they assign, and keyed by page. A request is matched against these * grouped by which variants they assign, and keyed by page. A request uses
* groups to find the combination it was prerendered against. * these groups to recover the combination it was prerendered against.
* *
* This is keyed by page rather than carried on a route entry, because a page * This is keyed by page rather than carried on a route entry, because a page
* that declares combinations and has no fallback shell has no `dynamicRoutes` * that declares combinations and has no fallback shell has no `dynamicRoutes`
* entry to hold them. The map is empty unless some page declared any. * entry to hold them.
*/ */
variantCombinationGroups: { [page: string]: VariantCombinationGroups } variantCombinationGroups: { [page: string]: VariantCombinationGroups }
} }
...@@ -2184,13 +2184,14 @@ export default async function build( ...@@ -2184,13 +2184,14 @@ export default async function build(
const serverPropsPages = new Set<string>() const serverPropsPages = new Set<string>()
const additionalPaths = new Map<string, PrerenderedRoute[]>() const additionalPaths = new Map<string, PrerenderedRoute[]>()
const staticPaths = new Map<string, PrerenderedRoute[]>() const staticPaths = new Map<string, PrerenderedRoute[]>()
// The build gathers page data before the prerender manifest exists, so // Static generation needs every declaration to produce its candidate
// the variant combination groups are collected here and moved into the // outputs. The final manifests receive only the combinations whose
// manifest once it does. // candidates succeeded.
const variantCombinationGroupsByPage = new Map< const variantCombinationGroupsByPage = new Map<
string, string,
VariantCombinationGroups VariantCombinationGroups
>() >()
const variantOutputHashesByPage = new Map<string, Set<string>>()
const prerenderRouteMatchers = new Map<string, PrerenderRouteMatcher[]>() const prerenderRouteMatchers = new Map<string, PrerenderRouteMatcher[]>()
const appNormalizedPaths = new Map<string, string>() const appNormalizedPaths = new Map<string, string>()
const fallbackModes = new Map<string, FallbackMode>() const fallbackModes = new Map<string, FallbackMode>()
...@@ -3051,26 +3052,13 @@ export default async function build( ...@@ -3051,26 +3052,13 @@ export default async function build(
path.join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST) path.join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST)
) )
// This file is written whenever the flag is on, even when no page
// declared anything. A proxy then reads a file that is either present and
// current, or absent because the feature is off, and never has to tell a
// stale file from a missing one.
if (config.experimental.variants) {
await writeManifest(
path.join(distDir, SERVER_DIRECTORY, VARIANTS_MANIFEST),
buildVariantsManifest(variantCombinationGroupsByPage)
)
}
const prerenderManifest: PrerenderManifest = { const prerenderManifest: PrerenderManifest = {
version: 4, version: 4,
routes: {}, routes: {},
dynamicRoutes: {}, dynamicRoutes: {},
notFoundRoutes: [], notFoundRoutes: [],
preview: previewProps, preview: previewProps,
variantCombinationGroups: Object.fromEntries( variantCombinationGroups: {},
variantCombinationGroupsByPage
),
} }
// Accumulate per-route segment inlining decisions for // Accumulate per-route segment inlining decisions for
...@@ -3669,6 +3657,12 @@ export default async function build( ...@@ -3669,6 +3657,12 @@ export default async function build(
prefetchDataRoute, prefetchDataRoute,
allowHeader: ALLOWED_HEADERS, allowHeader: ALLOWED_HEADERS,
} }
recordVariantOutput(
variantOutputHashesByPage,
page,
route.variantValues
)
} else { } else {
hasRevalidateZero = true hasRevalidateZero = true
...@@ -4012,6 +4006,12 @@ export default async function build( ...@@ -4012,6 +4006,12 @@ export default async function build(
), ),
allowHeader: ALLOWED_HEADERS, allowHeader: ALLOWED_HEADERS,
} }
recordVariantOutput(
variantOutputHashesByPage,
page,
prerenderCandidate?.variantValues
)
} }
} }
}) })
...@@ -4492,7 +4492,6 @@ export default async function build( ...@@ -4492,7 +4492,6 @@ export default async function build(
} }
} }
await writePrerenderManifest(distDir, prerenderManifest)
await writeManifest( await writeManifest(
path.join(distDir, SERVER_DIRECTORY, PREFETCH_HINTS), path.join(distDir, SERVER_DIRECTORY, PREFETCH_HINTS),
prefetchHints prefetchHints
...@@ -4502,17 +4501,28 @@ export default async function build( ...@@ -4502,17 +4501,28 @@ export default async function build(
buildId, buildId,
locales: config.i18n?.locales, locales: config.i18n?.locales,
}) })
} else {
await writePrerenderManifest(distDir, {
version: 4,
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
variantCombinationGroups: {},
preview: previewProps,
})
} }
// Build the variant groups and manifest after the prerender outputs are
// known. A declared static variant combination that produced no prerender
// output is omitted from both manifests.
if (config.experimental.variants) {
const { variantCombinationGroups, variantsManifest } =
buildVariantsManifest(
variantCombinationGroupsByPage,
variantOutputHashesByPage
)
prerenderManifest.variantCombinationGroups = variantCombinationGroups
await writeManifest(
path.join(distDir, SERVER_DIRECTORY, VARIANTS_MANIFEST),
variantsManifest
)
}
await writePrerenderManifest(distDir, prerenderManifest)
await writeManifest( await writeManifest(
path.join(distDir, 'server', PREVIEW_PROPS_MANIFEST), path.join(distDir, 'server', PREVIEW_PROPS_MANIFEST),
previewProps previewProps
......
import type { VariantCombinationGroups } from '../../server/variants/combinations' import type { VariantCombinationGroups } from '../../server/variants/combinations'
import type { VariantsManifest } from '../../server/variants/manifest' import type { VariantsManifest } from '../../server/variants/manifest'
import { hashVariants } from '../../server/variants/encoding'
import { isDynamicRoute } from '../../shared/lib/router/utils/is-dynamic' import { isDynamicRoute } from '../../shared/lib/router/utils/is-dynamic'
import { getRouteRegex } from '../../shared/lib/router/utils/route-regex' import { getRouteRegex } from '../../shared/lib/router/utils/route-regex'
import { sortPagesObject } from '../../shared/lib/router/utils/sortable-routes' import { sortPagesObject } from '../../shared/lib/router/utils/sortable-routes'
export function recordVariantOutput(
outputHashesByPage: Map<string, Set<string>>,
page: string,
variantValues: Readonly<Record<string, string>> | undefined
): void {
if (!variantValues) {
return
}
let outputHashes = outputHashesByPage.get(page)
if (!outputHashes) {
outputHashes = new Set()
outputHashesByPage.set(page, outputHashes)
}
outputHashes.add(hashVariants(variantValues))
}
/** /**
* Builds the variants manifest from the groups the build collected per page. * Builds the variant groups consumed by the origin and their proxy projection.
*
* Only combinations that produced an output reach the origin. Output
* availability belongs to the page rather than to one params row: a combination
* applies to the whole route, so one concrete output establishes that the same
* combination can partition an on-demand prerender for another param.
* *
* A static route is keyed by its pathname, which a proxy can look up directly. * The proxy projection keeps a page with empty groups when none of its
* A dynamic route carries the source of its route regex instead, and the routes * combinations produced an output. It then blocks a less specific dynamic route
* are sorted so that a more specific one is tested first. * from supplying combinations that belong to another page.
*/ */
export function buildVariantsManifest( export function buildVariantsManifest(
groupsByPage: ReadonlyMap<string, VariantCombinationGroups> groupsByPage: ReadonlyMap<string, VariantCombinationGroups>,
): VariantsManifest { outputHashesByPage: ReadonlyMap<string, ReadonlySet<string>>
): {
variantCombinationGroups: Record<string, VariantCombinationGroups>
variantsManifest: VariantsManifest
} {
const variantCombinationGroups: Record<string, VariantCombinationGroups> = {}
const staticRoutes: Record<string, VariantCombinationGroups> = {} const staticRoutes: Record<string, VariantCombinationGroups> = {}
const dynamicGroupsByPage: Record<string, VariantCombinationGroups> = {} const dynamicGroupsByPage: Record<string, VariantCombinationGroups> = {}
for (const [page, groups] of groupsByPage) { for (const [page, groups] of groupsByPage) {
const outputHashes = outputHashesByPage.get(page)
const filteredGroups: VariantCombinationGroups = []
if (outputHashes) {
for (const group of groups) {
const combinations = group.combinations.filter((combination) =>
outputHashes.has(combination.hash)
)
if (combinations.length > 0) {
filteredGroups.push({ ...group, combinations })
}
}
}
if (filteredGroups.length > 0) {
variantCombinationGroups[page] = filteredGroups
}
if (isDynamicRoute(page)) { if (isDynamicRoute(page)) {
dynamicGroupsByPage[page] = groups dynamicGroupsByPage[page] = filteredGroups
} else { } else {
staticRoutes[page] = groups staticRoutes[page] = filteredGroups
} }
} }
...@@ -33,5 +82,8 @@ export function buildVariantsManifest( ...@@ -33,5 +82,8 @@ export function buildVariantsManifest(
groups, groups,
})) }))
return { version: 1, staticRoutes, dynamicRoutes } return {
variantCombinationGroups,
variantsManifest: { version: 1, staticRoutes, dynamicRoutes },
}
} }
import type { VariantCombinationGroups } from './combinations' import type { VariantCombinationGroups } from './combinations'
/** /**
* The static variant combinations of every page that declared any, in the form * The static variant combinations with a prefixed prerender output, in the form
* a proxy needs. * a proxy needs. A page that declared combinations remains present with empty
* groups when none produced an output.
* *
* A proxy runs before any routing of ours, so it cannot look a page up by name. * 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 * It matches a pathname first, which is why this holds route regexes where the
...@@ -57,8 +58,8 @@ function getDynamicMatchers( ...@@ -57,8 +58,8 @@ function getDynamicMatchers(
} }
/** /**
* Finds the variant combination groups declared for the route that serves a * Finds the variant combination groups with an available output for the route
* pathname, and returns null for a pathname no declaring route serves. * that serves a pathname. It returns null when no manifest route matches.
* *
* A static route is looked up by pathname before any regex is tested, so a * 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. * concrete route wins over a dynamic one that would also match it.
......
...@@ -2,10 +2,9 @@ import { Suspense } from 'react' ...@@ -2,10 +2,9 @@ import { Suspense } from 'react'
import { theme } from '../../variants' import { theme } from '../../variants'
// Declared so that a request to this route is prefixed with its combination, // Cache Components can place the `searchParams` read behind the boundary and
// which is what puts the internal query parameter carrying the combination on // produce an output for each combination. A legacy prerender cannot, so the
// the path the origin sees. The page reads `searchParams` so that anything left // route renders dynamically without a variants prefix in that mode.
// in that query becomes visible to user code.
export async function unstable_generateStaticVariants() { export async function unstable_generateStaticVariants() {
return [[[theme, 'dark']], [[theme, 'light']]] return [[[theme, 'dark']], [[theme, 'light']]]
} }
......
...@@ -22,8 +22,10 @@ export async function unstable_generateStaticVariants() { ...@@ -22,8 +22,10 @@ export async function unstable_generateStaticVariants() {
] ]
} }
// Both variants sit behind a boundary, so the prerender of the smaller group // With Cache Components, both variants sit behind a boundary, so the prerender
// has a shell to serve while `locale` resolves. // of the smaller group has a shell to serve while `locale` resolves. A legacy
// prerender cannot leave that hole and produces no output for the smaller
// group.
// //
// A fallback carries the same id as the value it stands in for, so one // 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, // assertion reads either. A prerender that bakes a variant renders its value,
......
...@@ -620,10 +620,10 @@ describe('variants', () => { ...@@ -620,10 +620,10 @@ describe('variants', () => {
// tests belong together. // tests belong together.
it('should not expose the internal combination query parameter to the page', async () => { it('should not expose the internal combination query parameter to the page', async () => {
// The combination travels to the origin as a query parameter, because that // A combination with an output reaches the origin as a query parameter. A
// is the one channel both a routed request and one a platform rebuilt from // route without one receives every value at runtime and needs no internal
// an artifact arrive on. It names no param and is not the page's to see, so // query. In either case the internal parameter must not reach
// it must not reach `searchParams` the way a real query value does. // `searchParams` the way a real query value does.
const browser = await next.browser(url('/search-params?q=1'), { const browser = await next.browser(url('/search-params?q=1'), {
async beforePageLoad(page: Playwright.Page) { async beforePageLoad(page: Playwright.Page) {
await page await page
......
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