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'
import { generatePreviewKeys } from './preview-key-utils'
import { handleBuildComplete } from './adapter/build-complete'
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 {
sortPageObjects,
......@@ -421,13 +421,13 @@ export type PrerenderManifest = {
/** @deprecated only kept for the builder, use PreviewPropsManifest within Next.js itself */
preview: __ApiPreviewProps
/**
* The static variant combinations each page declared, grouped by which
* variants they assign, and keyed by page. A request is matched against these
* groups to find the combination it was prerendered against.
* The static variant combinations that produced a prefixed prerender output,
* grouped by which variants they assign, and keyed by page. A request uses
* 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
* 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 }
}
......@@ -2184,13 +2184,14 @@ export default async function build(
const serverPropsPages = new Set<string>()
const additionalPaths = new Map<string, PrerenderedRoute[]>()
const staticPaths = new Map<string, PrerenderedRoute[]>()
// The build gathers page data before the prerender manifest exists, so
// the variant combination groups are collected here and moved into the
// manifest once it does.
// Static generation needs every declaration to produce its candidate
// outputs. The final manifests receive only the combinations whose
// candidates succeeded.
const variantCombinationGroupsByPage = new Map<
string,
VariantCombinationGroups
>()
const variantOutputHashesByPage = new Map<string, Set<string>>()
const prerenderRouteMatchers = new Map<string, PrerenderRouteMatcher[]>()
const appNormalizedPaths = new Map<string, string>()
const fallbackModes = new Map<string, FallbackMode>()
......@@ -3051,26 +3052,13 @@ export default async function build(
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 = {
version: 4,
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: previewProps,
variantCombinationGroups: Object.fromEntries(
variantCombinationGroupsByPage
),
variantCombinationGroups: {},
}
// Accumulate per-route segment inlining decisions for
......@@ -3669,6 +3657,12 @@ export default async function build(
prefetchDataRoute,
allowHeader: ALLOWED_HEADERS,
}
recordVariantOutput(
variantOutputHashesByPage,
page,
route.variantValues
)
} else {
hasRevalidateZero = true
......@@ -4012,6 +4006,12 @@ export default async function build(
),
allowHeader: ALLOWED_HEADERS,
}
recordVariantOutput(
variantOutputHashesByPage,
page,
prerenderCandidate?.variantValues
)
}
}
})
......@@ -4492,7 +4492,6 @@ export default async function build(
}
}
await writePrerenderManifest(distDir, prerenderManifest)
await writeManifest(
path.join(distDir, SERVER_DIRECTORY, PREFETCH_HINTS),
prefetchHints
......@@ -4502,17 +4501,28 @@ export default async function build(
buildId,
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(
path.join(distDir, 'server', PREVIEW_PROPS_MANIFEST),
previewProps
......
import type { VariantCombinationGroups } from '../../server/variants/combinations'
import type { VariantsManifest } from '../../server/variants/manifest'
import { hashVariants } from '../../server/variants/encoding'
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'
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.
* 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.
* The proxy projection keeps a page with empty groups when none of its
* combinations produced an output. It then blocks a less specific dynamic route
* from supplying combinations that belong to another page.
*/
export function buildVariantsManifest(
groupsByPage: ReadonlyMap<string, VariantCombinationGroups>
): VariantsManifest {
groupsByPage: ReadonlyMap<string, VariantCombinationGroups>,
outputHashesByPage: ReadonlyMap<string, ReadonlySet<string>>
): {
variantCombinationGroups: Record<string, VariantCombinationGroups>
variantsManifest: VariantsManifest
} {
const variantCombinationGroups: Record<string, VariantCombinationGroups> = {}
const staticRoutes: Record<string, VariantCombinationGroups> = {}
const dynamicGroupsByPage: Record<string, VariantCombinationGroups> = {}
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)) {
dynamicGroupsByPage[page] = groups
dynamicGroupsByPage[page] = filteredGroups
} else {
staticRoutes[page] = groups
staticRoutes[page] = filteredGroups
}
}
......@@ -33,5 +82,8 @@ export function buildVariantsManifest(
groups,
}))
return { version: 1, staticRoutes, dynamicRoutes }
return {
variantCombinationGroups,
variantsManifest: { version: 1, staticRoutes, dynamicRoutes },
}
}
import type { VariantCombinationGroups } from './combinations'
/**
* The static variant combinations of every page that declared any, in the form
* a proxy needs.
* The static variant combinations with a prefixed prerender output, in the form
* 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.
* It matches a pathname first, which is why this holds route regexes where the
......@@ -57,8 +58,8 @@ function getDynamicMatchers(
}
/**
* Finds the variant combination groups declared for the route that serves a
* pathname, and returns null for a pathname no declaring route serves.
* Finds the variant combination groups with an available output for the route
* 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
* concrete route wins over a dynamic one that would also match it.
......
......@@ -2,10 +2,9 @@ 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.
// Cache Components can place the `searchParams` read behind the boundary and
// produce an output for each combination. A legacy prerender cannot, so the
// route renders dynamically without a variants prefix in that mode.
export async function unstable_generateStaticVariants() {
return [[[theme, 'dark']], [[theme, 'light']]]
}
......
......@@ -22,8 +22,10 @@ export async function unstable_generateStaticVariants() {
]
}
// Both variants sit behind a boundary, so the prerender of the smaller group
// has a shell to serve while `locale` resolves.
// With Cache Components, both variants sit behind a boundary, so the prerender
// 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
// assertion reads either. A prerender that bakes a variant renders its value,
......
......@@ -620,10 +620,10 @@ describe('variants', () => {
// tests belong together.
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
// is the one channel both a routed request and one a platform rebuilt from
// an artifact arrive on. It names no param and is not the page's to see, so
// it must not reach `searchParams` the way a real query value does.
// A combination with an output reaches the origin as a query parameter. A
// route without one receives every value at runtime and needs no internal
// query. In either case the internal parameter must not reach
// `searchParams` the way a real query value does.
const browser = await next.browser(url('/search-params?q=1'), {
async beforePageLoad(page: Playwright.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