Unverified Commit f0d81f14 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

[ppr] Route Cardinality Updates (#78476)

This enables a new set of cardinality changes for pages with PPR and
Dynamic IO enabled on it. When a set of more specific routes are
generated, we no longer error when the static shell is empty and instead
infer that as a sign that the user doesn't want to provide a route
fallback. If the user does in fact place suspense boundaries above
params access, the fallback shell will not be empty and will be used.

Given the following application structure:
```
/[lang]/layout.tsx
/[lang]/[teamSlug]/page.tsx
```

Where we have the following returned for `generateStaticProps`: `[{
lang: "en", teamSlug: "nextjs"}]`, we'd have the following rendered:

```
/[lang]/[teamSlug] <- empty shell won't cause error
/en/[teamSlug] <- empty shell won't cause error
/en/nextjs <- empty shell will cause error
```

If `/[lang]/[teamSlug]` generated an empty shell, then a request to
`/fr/nextjs` wouldn't use the `/[lang]/[teamSlug]` fallback shell and
would instead generate a new blocking route shell. Otherwise if it
didn't generate an empty shell, it would use the fallback shell that's
outputted.

If `/en/[teamSlug]` generated an empty shell, then a request to
`/en/react` wouldn't use the `/en/[teamSlug]` fallback shell and would
instead generate a new blocking route shell. Otherwise if it didn't
generate an empty shell, it would use the fallback shell that's
outputted.
parent bf2ad52d
...@@ -444,7 +444,7 @@ export type RoutesManifest = { ...@@ -444,7 +444,7 @@ export type RoutesManifest = {
} }
} }
function pageToRoute(page: string) { function pageToRoute(page: string): ManifestRoute {
const routeRegex = getNamedRouteRegex(page, { const routeRegex = getNamedRouteRegex(page, {
prefixRouteKeys: true, prefixRouteKeys: true,
}) })
...@@ -1303,8 +1303,8 @@ export default async function build( ...@@ -1303,8 +1303,8 @@ export default async function build(
...pageKeys.pages, ...pageKeys.pages,
...(pageKeys.app ?? []), ...(pageKeys.app ?? []),
]) ])
const dynamicRoutes: Array<ReturnType<typeof pageToRoute>> = [] const dynamicRoutes: Array<ManifestRoute> = []
const staticRoutes: typeof dynamicRoutes = [] const staticRoutes: Array<ManifestRoute> = []
for (const route of sortedRoutes) { for (const route of sortedRoutes) {
if (isDynamicRoute(route)) { if (isDynamicRoute(route)) {
...@@ -2025,12 +2025,14 @@ export default async function build( ...@@ -2025,12 +2025,14 @@ export default async function build(
if (!isDynamic) { if (!isDynamic) {
staticPaths.set(originalAppPath, [ staticPaths.set(originalAppPath, [
{ {
params: {},
pathname: page, pathname: page,
encodedPathname: page, encodedPathname: page,
fallbackRouteParams: undefined, fallbackRouteParams: [],
fallbackMode: fallbackMode:
workerResult.prerenderFallbackMode, workerResult.prerenderFallbackMode,
fallbackRootParams: undefined, fallbackRootParams: [],
throwOnEmptyStaticShell: true,
}, },
]) ])
isStatic = true isStatic = true
...@@ -2061,8 +2063,6 @@ export default async function build( ...@@ -2061,8 +2063,6 @@ export default async function build(
`"getStaticProps" is not yet supported fully with "experimental-edge", detected on ${page}` `"getStaticProps" is not yet supported fully with "experimental-edge", detected on ${page}`
) )
} }
// TODO: add handling for statically rendering edge
// pages and allow edge with Prerender outputs
workerResult.isStatic = false workerResult.isStatic = false
workerResult.hasStaticProps = false workerResult.hasStaticProps = false
} }
...@@ -2188,7 +2188,7 @@ export default async function build( ...@@ -2188,7 +2188,7 @@ export default async function build(
runtime: pageRuntime, runtime: pageRuntime,
pageDuration: undefined, pageDuration: undefined,
ssgPageDurations: undefined, ssgPageDurations: undefined,
hasEmptyPrelude: undefined, hasEmptyStaticShell: undefined,
}) })
}) })
}) })
...@@ -2607,6 +2607,7 @@ export default async function build( ...@@ -2607,6 +2607,7 @@ export default async function build(
) )
) )
) )
const exportApp = require('../export') const exportApp = require('../export')
.default as typeof import('../export').default .default as typeof import('../export').default
...@@ -2678,9 +2679,9 @@ export default async function build( ...@@ -2678,9 +2679,9 @@ export default async function build(
const appConfig = appDefaultConfigs.get(originalAppPath) const appConfig = appDefaultConfigs.get(originalAppPath)
const isDynamicError = appConfig?.dynamic === 'error' const isDynamicError = appConfig?.dynamic === 'error'
const isRoutePPREnabled = appConfig const isRoutePPREnabled: boolean = appConfig
? checkIsRoutePPREnabled(config.experimental.ppr, appConfig) ? checkIsRoutePPREnabled(config.experimental.ppr, appConfig)
: undefined : false
routes.forEach((route) => { routes.forEach((route) => {
// If the route has any dynamic root segments, we need to skip // If the route has any dynamic root segments, we need to skip
...@@ -2700,6 +2701,8 @@ export default async function build( ...@@ -2700,6 +2701,8 @@ export default async function build(
_isDynamicError: isDynamicError, _isDynamicError: isDynamicError,
_isAppDir: true, _isAppDir: true,
_isRoutePPREnabled: isRoutePPREnabled, _isRoutePPREnabled: isRoutePPREnabled,
_doNotThrowOnEmptyStaticShell:
!route.throwOnEmptyStaticShell,
} }
}) })
}) })
...@@ -2780,6 +2783,31 @@ export default async function build( ...@@ -2780,6 +2783,31 @@ export default async function build(
// If there was no result, there's nothing more to do. // If there was no result, there's nothing more to do.
if (!exportResult) return if (!exportResult) return
const getFallbackMode = (route: PrerenderedRoute) => {
const hasEmptyStaticShell = exportResult.byPath.get(
route.pathname
)?.hasEmptyStaticShell
// If the route has an empty static shell and is not configured to
// throw on empty static shell, then we should use the blocking
// static render mode.
if (
hasEmptyStaticShell &&
!route.throwOnEmptyStaticShell &&
route.fallbackMode === FallbackMode.PRERENDER
) {
return FallbackMode.BLOCKING_STATIC_RENDER
}
// If the route has no fallback mode, then we should use the
// `NOT_FOUND` fallback mode.
if (!route.fallbackMode) {
return FallbackMode.NOT_FOUND
}
return route.fallbackMode
}
const getCacheControl = ( const getCacheControl = (
exportPath: string, exportPath: string,
defaultRevalidate: Revalidate = false defaultRevalidate: Revalidate = false
...@@ -2953,7 +2981,7 @@ export default async function build( ...@@ -2953,7 +2981,7 @@ export default async function build(
const { const {
metadata = {}, metadata = {},
hasEmptyPrelude, hasEmptyStaticShell,
hasPostponed, hasPostponed,
} = exportResult.byPath.get(route.pathname) ?? {} } = exportResult.byPath.get(route.pathname) ?? {}
...@@ -2965,7 +2993,7 @@ export default async function build( ...@@ -2965,7 +2993,7 @@ export default async function build(
pageInfos.set(route.pathname, { pageInfos.set(route.pathname, {
...(pageInfos.get(route.pathname) as PageInfo), ...(pageInfos.get(route.pathname) as PageInfo),
hasPostponed, hasPostponed,
hasEmptyPrelude, hasEmptyStaticShell,
initialCacheControl: cacheControl, initialCacheControl: cacheControl,
}) })
...@@ -2973,7 +3001,7 @@ export default async function build( ...@@ -2973,7 +3001,7 @@ export default async function build(
pageInfos.set(page, { pageInfos.set(page, {
...(pageInfos.get(page) as PageInfo), ...(pageInfos.get(page) as PageInfo),
hasPostponed, hasPostponed,
hasEmptyPrelude, hasEmptyStaticShell,
initialCacheControl: cacheControl, initialCacheControl: cacheControl,
}) })
...@@ -3035,13 +3063,15 @@ export default async function build( ...@@ -3035,13 +3063,15 @@ export default async function build(
// prerendered routes. // prerendered routes.
if (!isRoutePPREnabled) { if (!isRoutePPREnabled) {
dynamicRoutes.push({ dynamicRoutes.push({
params: {},
pathname: page, pathname: page,
encodedPathname: page, encodedPathname: page,
fallbackRouteParams: undefined, fallbackRouteParams: [],
fallbackMode: fallbackMode:
fallbackModes.get(originalAppPath) ?? fallbackModes.get(originalAppPath) ??
FallbackMode.NOT_FOUND, FallbackMode.NOT_FOUND,
fallbackRootParams: undefined, fallbackRootParams: [],
throwOnEmptyStaticShell: true,
}) })
} }
...@@ -3090,8 +3120,7 @@ export default async function build( ...@@ -3090,8 +3120,7 @@ export default async function build(
hasPostponed: isRoutePPREnabled, hasPostponed: isRoutePPREnabled,
}) })
const fallbackMode = const fallbackMode = getFallbackMode(route)
route.fallbackMode ?? FallbackMode.NOT_FOUND
// When the route is configured to serve a prerender, we should // When the route is configured to serve a prerender, we should
// use the cache control from the export result. If it can't be // use the cache control from the export result. If it can't be
...@@ -3133,7 +3162,9 @@ export default async function build( ...@@ -3133,7 +3162,9 @@ export default async function build(
fallbackExpire: fallbackCacheControl?.expire, fallbackExpire: fallbackCacheControl?.expire,
fallbackStatus: meta.status, fallbackStatus: meta.status,
fallbackHeaders: meta.headers, fallbackHeaders: meta.headers,
fallbackRootParams: route.fallbackRootParams, fallbackRootParams: fallback
? route.fallbackRootParams
: undefined,
fallbackSourceRoute: route.fallbackRouteParams?.length fallbackSourceRoute: route.fallbackRouteParams?.length
? page ? page
: undefined, : undefined,
......
import { FallbackMode } from '../../lib/fallback'
import {
assignErrorIfEmpty,
filterUniqueRootParamsCombinations,
filterUniqueParams,
} from './app'
import type { PrerenderedRoute } from './types'
describe('assignErrorIfEmpty', () => {
it('should assign throwOnEmptyStaticShell false for a static route', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: {},
pathname: '/',
encodedPathname: '/',
fallbackRouteParams: [],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
]
assignErrorIfEmpty(prerenderedRoutes, [])
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(true)
})
it('should assign throwOnEmptyStaticShell to the prerendered routes', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: {},
pathname: '/[id]',
encodedPathname: '/[id]',
fallbackRouteParams: ['id'],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { id: '1' },
pathname: '/1',
encodedPathname: '/1',
fallbackRouteParams: [],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
]
assignErrorIfEmpty(prerenderedRoutes, ['id'])
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(true)
})
it('should handle more complex routes', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: {},
pathname: '/[id]/[name]',
encodedPathname: '/[id]/[name]',
fallbackRouteParams: ['id', 'name'],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { id: '1' },
pathname: '/1/[name]',
encodedPathname: '/1/[name]',
fallbackRouteParams: ['name'],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { id: '1', name: 'test' },
pathname: '/1/test',
encodedPathname: '/1/test',
fallbackRouteParams: [],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { id: '2', name: 'test' },
pathname: '/2/test',
encodedPathname: '/2/test',
fallbackRouteParams: [],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { id: '2' },
pathname: '/2/[name]',
encodedPathname: '/2/[name]',
fallbackRouteParams: ['name'],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
]
assignErrorIfEmpty(prerenderedRoutes, ['id', 'name'])
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[2].throwOnEmptyStaticShell).toBe(true)
expect(prerenderedRoutes[3].throwOnEmptyStaticShell).toBe(true)
expect(prerenderedRoutes[4].throwOnEmptyStaticShell).toBe(false)
})
})
describe('filterUniqueParams', () => {
it('should filter out duplicate parameters', () => {
const params = [
{ id: '1', name: 'test' },
{ id: '1', name: 'test' },
{ id: '2' },
]
const unique = filterUniqueParams(['id', 'name'], params)
expect(unique).toEqual([{ id: '1', name: 'test' }, { id: '2' }])
})
it('should handle more complex routes', () => {
const params = [
{ id: '1', name: 'test', age: '10' },
{ id: '1', name: 'test', age: '20' },
{ id: '2', name: 'test', age: '10' },
]
const unique = filterUniqueParams(['id', 'name', 'age'], params)
expect(unique).toEqual([
{ id: '1', name: 'test', age: '10' },
{ id: '1', name: 'test', age: '20' },
{ id: '2', name: 'test', age: '10' },
])
})
})
describe('filterUniqueRootParamsCombinations', () => {
it('should return only the root parameters', () => {
const params = [
{ id: '1', name: 'test' },
{ id: '1', name: 'test' },
{ id: '2', name: 'test' },
]
const unique = filterUniqueRootParamsCombinations(['id'], params)
expect(unique).toEqual([{ id: '1' }, { id: '2' }])
})
})
import type { ParamValue, Params } from '../../server/request/params' import type { ParamValue, Params } from '../../server/request/params'
import type { AppPageModule } from '../../server/route-modules/app-page/module' import type { AppPageModule } from '../../server/route-modules/app-page/module'
import type { AppSegment } from '../segment-config/app/app-segments' import type { AppSegment } from '../segment-config/app/app-segments'
import type { StaticPathsResult } from './types' import type { PrerenderedRoute, StaticPathsResult } from './types'
import path from 'path' import path from 'node:path'
import { AfterRunner } from '../../server/after/run-with-after' import { AfterRunner } from '../../server/after/run-with-after'
import { createWorkStore } from '../../server/async-storage/work-store' import { createWorkStore } from '../../server/async-storage/work-store'
import { FallbackMode } from '../../lib/fallback' import { FallbackMode } from '../../lib/fallback'
...@@ -52,39 +52,26 @@ function areParamValuesEqual(a: ParamValue, b: ParamValue) { ...@@ -52,39 +52,26 @@ function areParamValuesEqual(a: ParamValue, b: ParamValue) {
* @param routeParams - The list of parameters to filter. * @param routeParams - The list of parameters to filter.
* @returns The list of unique parameters. * @returns The list of unique parameters.
*/ */
function filterUniqueParams( export function filterUniqueParams(
routeParamKeys: readonly string[], routeParamKeys: readonly string[],
routeParams: readonly Params[] routeParams: readonly Params[]
): Params[] { ): Params[] {
const unique: Params[] = [] const unique: Params[] = []
for (const params of routeParams) { paramsLoop: for (const params of routeParams) {
let i = 0 uniqueLoop: for (const item of unique) {
for (; i < unique.length; i++) { for (const key of routeParamKeys) {
const item = unique[i] // If the param is not the same, then we need to check the next item
let j = 0
for (; j < routeParamKeys.length; j++) {
const key = routeParamKeys[j]
// If the param is not the same, then we need to break out of the loop.
if (!areParamValuesEqual(item[key], params[key])) { if (!areParamValuesEqual(item[key], params[key])) {
break continue uniqueLoop
} }
} }
// If we got to the end of the paramKeys array, then it means that we // If we got here, then all params matched and we found a duplicate
// found a duplicate. Skip it. continue paramsLoop
if (j === routeParamKeys.length) {
break
}
}
// If we didn't get to the end of the unique array, then it means that we
// found a duplicate. Skip it.
if (i < unique.length) {
continue
} }
// If we got here, then we checked all items and found no duplicates
unique.push(params) unique.push(params)
} }
...@@ -117,36 +104,29 @@ function filterUniqueParams( ...@@ -117,36 +104,29 @@ function filterUniqueParams(
* @param routeParams - The list of parameters to filter. * @param routeParams - The list of parameters to filter.
* @returns The list of combinations of root params. * @returns The list of combinations of root params.
*/ */
function filterRootParamsCombinations( export function filterUniqueRootParamsCombinations(
rootParamKeys: readonly string[], rootParamKeys: readonly string[],
routeParams: readonly Params[] routeParams: readonly Params[]
): Params[] { ): Params[] {
const combinations: Params[] = [] const combinations: Params[] = []
for (const params of routeParams) { paramsLoop: for (const params of routeParams) {
const combination: Params = {} const combination: Params = {}
// Collect all root params. As soon as we don't find a root param, break. // Collect all root params. As soon as we don't find a root param, break.
let i = 0 for (const key of rootParamKeys) {
for (; i < rootParamKeys.length; i++) {
const key = rootParamKeys[i]
if (params[key]) { if (params[key]) {
combination[key] = params[key] combination[key] = params[key]
} else { } else {
break // Skip this combination if we don't have all root params
continue paramsLoop
} }
} }
// If we didn't find all root params, skip this combination. We only want to
// generate combinations that have all root params.
if (i < rootParamKeys.length) {
continue
}
combinations.push(combination) combinations.push(combination)
} }
return combinations return filterUniqueParams(rootParamKeys, combinations)
} }
/** /**
...@@ -243,6 +223,50 @@ function validateParams( ...@@ -243,6 +223,50 @@ function validateParams(
return valid return valid
} }
/**
* Assigns the throwOnEmptyStaticShell property to each of the prerendered routes.
*
* @param prerenderedRoutes - The prerendered routes.
* @param routeParamKeys - The keys of the route parameters.
*/
export function assignErrorIfEmpty(
prerenderedRoutes: readonly PrerenderedRoute[],
routeParamKeys: readonly string[]
) {
// If we're rendering a more specific route, then we don't need to error
// if the route is empty.
for (const prerenderedRoute of prerenderedRoutes) {
let throwOnEmptyStaticShell: boolean = true
// If the route has fallbackRouteParams, then we need to check if the
// route is a more specific route.
const { fallbackRouteParams, params } = prerenderedRoute
if (fallbackRouteParams && fallbackRouteParams.length > 0) {
siblingLoop: for (const other of prerenderedRoutes) {
// Skip the current route.
if (other === prerenderedRoute) continue
for (const key of routeParamKeys) {
// If the key is a fallback route param, then we can skip it, because
// it always matches.
if (fallbackRouteParams.includes(key)) {
throwOnEmptyStaticShell = false
break siblingLoop
}
// If the param value is not equal, then we can break out of the loop
// because the route is not a more specific route.
if (!areParamValuesEqual(params[key], other.params[key])) {
continue siblingLoop
}
}
}
}
prerenderedRoute.throwOnEmptyStaticShell = throwOnEmptyStaticShell
}
}
/** /**
* Builds the static paths for an app using `generateStaticParams`. * Builds the static paths for an app using `generateStaticParams`.
* *
...@@ -396,6 +420,8 @@ export async function buildAppStaticPaths({ ...@@ -396,6 +420,8 @@ export async function buildAppStaticPaths({
} }
) )
await afterRunner.executeAfter()
let lastDynamicSegmentHadGenerateStaticParams = false let lastDynamicSegmentHadGenerateStaticParams = false
for (const segment of segments) { for (const segment of segments) {
// Check to see if there are any missing params for segments that have // Check to see if there are any missing params for segments that have
...@@ -470,11 +496,12 @@ export async function buildAppStaticPaths({ ...@@ -470,11 +496,12 @@ export async function buildAppStaticPaths({
// Discover all unique combinations of the rootParams so we can generate // Discover all unique combinations of the rootParams so we can generate
// shells for each of them if they're available. // shells for each of them if they're available.
routeParams.unshift( routeParams.unshift(
...filterRootParamsCombinations(rootParamKeys, routeParams) ...filterUniqueRootParamsCombinations(rootParamKeys, routeParams)
) )
result.prerenderedRoutes ??= [] result.prerenderedRoutes ??= []
result.prerenderedRoutes.push({ result.prerenderedRoutes.push({
params: {},
pathname: page, pathname: page,
encodedPathname: page, encodedPathname: page,
fallbackRouteParams: routeParamKeys, fallbackRouteParams: routeParamKeys,
...@@ -486,6 +513,8 @@ export async function buildAppStaticPaths({ ...@@ -486,6 +513,8 @@ export async function buildAppStaticPaths({
: fallbackMode : fallbackMode
: FallbackMode.NOT_FOUND, : FallbackMode.NOT_FOUND,
fallbackRootParams: rootParamKeys, fallbackRootParams: rootParamKeys,
// This is set later after all the routes have been processed.
throwOnEmptyStaticShell: true,
}) })
} }
...@@ -503,7 +532,7 @@ export async function buildAppStaticPaths({ ...@@ -503,7 +532,7 @@ export async function buildAppStaticPaths({
let pathname: string = page let pathname: string = page
let encodedPathname: string = page let encodedPathname: string = page
const fallbackRouteParams: string[] = [] let fallbackRouteParams: string[] = []
for (const key of routeParamKeys) { for (const key of routeParamKeys) {
if (fallbackRouteParams.length > 0) { if (fallbackRouteParams.length > 0) {
...@@ -550,6 +579,7 @@ export async function buildAppStaticPaths({ ...@@ -550,6 +579,7 @@ export async function buildAppStaticPaths({
result.prerenderedRoutes ??= [] result.prerenderedRoutes ??= []
result.prerenderedRoutes.push({ result.prerenderedRoutes.push({
params,
pathname: normalizePathname(pathname), pathname: normalizePathname(pathname),
encodedPathname: normalizePathname(encodedPathname), encodedPathname: normalizePathname(encodedPathname),
fallbackRouteParams, fallbackRouteParams,
...@@ -561,11 +591,16 @@ export async function buildAppStaticPaths({ ...@@ -561,11 +591,16 @@ export async function buildAppStaticPaths({
: fallbackMode : fallbackMode
: FallbackMode.NOT_FOUND, : FallbackMode.NOT_FOUND,
fallbackRootParams, fallbackRootParams,
// This is set later after all the routes have been processed.
throwOnEmptyStaticShell: true,
}) })
}) })
} }
await afterRunner.executeAfter() // Now we have to set the throwOnEmptyStaticShell for each of the routes.
if (result.prerenderedRoutes && dynamicIO) {
assignErrorIfEmpty(result.prerenderedRoutes, routeParamKeys)
}
return result return result
} }
...@@ -98,8 +98,8 @@ export async function buildPagesStaticPaths({ ...@@ -98,8 +98,8 @@ export async function buildPagesStaticPaths({
entry = `/${defaultLocale}${entry}` entry = `/${defaultLocale}${entry}`
} }
const result = _routeMatcher(cleanedEntry) const params = _routeMatcher(cleanedEntry)
if (!result) { if (!params) {
throw new Error( throw new Error(
`The provided path \`${cleanedEntry}\` does not match the page: \`${page}\`.` `The provided path \`${cleanedEntry}\` does not match the page: \`${page}\`.`
) )
...@@ -109,6 +109,7 @@ export async function buildPagesStaticPaths({ ...@@ -109,6 +109,7 @@ export async function buildPagesStaticPaths({
// encoded so we decode the segments ensuring we only escape path // encoded so we decode the segments ensuring we only escape path
// delimiters // delimiters
prerenderedRoutes.push({ prerenderedRoutes.push({
params,
pathname: entry pathname: entry
.split('/') .split('/')
.map((segment) => .map((segment) =>
...@@ -119,6 +120,7 @@ export async function buildPagesStaticPaths({ ...@@ -119,6 +120,7 @@ export async function buildPagesStaticPaths({
fallbackRouteParams: undefined, fallbackRouteParams: undefined,
fallbackMode: parseStaticPathsResult(staticPathsResult.fallback), fallbackMode: parseStaticPathsResult(staticPathsResult.fallback),
fallbackRootParams: undefined, fallbackRootParams: undefined,
throwOnEmptyStaticShell: undefined,
}) })
} }
// For the object-provided path, we must make sure it specifies all // For the object-provided path, we must make sure it specifies all
...@@ -196,6 +198,7 @@ export async function buildPagesStaticPaths({ ...@@ -196,6 +198,7 @@ export async function buildPagesStaticPaths({
const curLocale = entry.locale || defaultLocale || '' const curLocale = entry.locale || defaultLocale || ''
prerenderedRoutes.push({ prerenderedRoutes.push({
params,
pathname: normalizePathname( pathname: normalizePathname(
`${curLocale ? `/${curLocale}` : ''}${ `${curLocale ? `/${curLocale}` : ''}${
curLocale && builtPage === '/' ? '' : builtPage curLocale && builtPage === '/' ? '' : builtPage
...@@ -209,6 +212,7 @@ export async function buildPagesStaticPaths({ ...@@ -209,6 +212,7 @@ export async function buildPagesStaticPaths({
fallbackRouteParams: undefined, fallbackRouteParams: undefined,
fallbackMode: parseStaticPathsResult(staticPathsResult.fallback), fallbackMode: parseStaticPathsResult(staticPathsResult.fallback),
fallbackRootParams: undefined, fallbackRootParams: undefined,
throwOnEmptyStaticShell: undefined,
}) })
} }
}) })
......
import type { FallbackMode } from '../../lib/fallback' import type { FallbackMode } from '../../lib/fallback'
import type { Params } from '../../server/request/params'
type StaticPrerenderedRoute = { type StaticPrerenderedRoute = {
pathname: string readonly params: Params
encodedPathname: string readonly pathname: string
fallbackRouteParams: undefined readonly encodedPathname: string
fallbackMode: FallbackMode | undefined readonly fallbackRouteParams: undefined
fallbackRootParams: undefined readonly fallbackMode: FallbackMode | undefined
readonly fallbackRootParams: undefined
/**
* When enabled, the route will be rendered with diagnostics enabled which
* will error the build if the route that is generated is empty.
*/
throwOnEmptyStaticShell: undefined
} }
type FallbackPrerenderedRoute = { type FallbackPrerenderedRoute = {
pathname: string readonly params: Params
encodedPathname: string readonly pathname: string
fallbackRouteParams: readonly string[] readonly encodedPathname: string
fallbackMode: FallbackMode | undefined readonly fallbackRouteParams: readonly string[]
fallbackRootParams: readonly string[] readonly fallbackMode: FallbackMode | undefined
readonly fallbackRootParams: readonly string[]
/**
* When enabled, the route will be rendered with diagnostics enabled which
* will error the build if the route that is generated is empty.
*/
throwOnEmptyStaticShell: boolean
} }
export type PrerenderedRoute = StaticPrerenderedRoute | FallbackPrerenderedRoute export type PrerenderedRoute = StaticPrerenderedRoute | FallbackPrerenderedRoute
......
...@@ -353,7 +353,7 @@ export interface PageInfo { ...@@ -353,7 +353,7 @@ export interface PageInfo {
pageDuration: number | undefined pageDuration: number | undefined
ssgPageDurations: number[] | undefined ssgPageDurations: number[] | undefined
runtime: ServerRuntime runtime: ServerRuntime
hasEmptyPrelude?: boolean hasEmptyStaticShell?: boolean
hasPostponed?: boolean hasPostponed?: boolean
isDynamicAppRoute?: boolean isDynamicAppRoute?: boolean
} }
...@@ -528,8 +528,9 @@ export async function printTreeView( ...@@ -528,8 +528,9 @@ export async function printTreeView(
symbol = 'ƒ' symbol = 'ƒ'
} else if (pageInfo?.isRoutePPREnabled) { } else if (pageInfo?.isRoutePPREnabled) {
if ( if (
// If the page has an empty prelude, then it's equivalent to a dynamic page // If the page has an empty static shell, then it's equivalent to a
pageInfo?.hasEmptyPrelude || // dynamic page
pageInfo?.hasEmptyStaticShell ||
// ensure we don't mark dynamic paths that postponed as being dynamic // ensure we don't mark dynamic paths that postponed as being dynamic
// since in this case we're able to partially prerender it // since in this case we're able to partially prerender it
(pageInfo.isDynamicAppRoute && !pageInfo.hasPostponed) (pageInfo.isDynamicAppRoute && !pageInfo.hasPostponed)
......
...@@ -652,8 +652,8 @@ async function exportAppImpl( ...@@ -652,8 +652,8 @@ async function exportAppImpl(
info.metadata = result.metadata info.metadata = result.metadata
} }
if (typeof result.hasEmptyPrelude !== 'undefined') { if (typeof result.hasEmptyStaticShell !== 'undefined') {
info.hasEmptyPrelude = result.hasEmptyPrelude info.hasEmptyStaticShell = result.hasEmptyStaticShell
} }
if (typeof result.hasPostponed !== 'undefined') { if (typeof result.hasPostponed !== 'undefined') {
......
...@@ -232,7 +232,7 @@ export async function exportAppPage( ...@@ -232,7 +232,7 @@ export async function exportAppPage(
} }
// Writing static HTML to a file. // Writing static HTML to a file.
fileWriter.append(htmlFilepath, html ?? '') fileWriter.append(htmlFilepath, html)
const isParallelRoute = /\/@\w+/.test(page) const isParallelRoute = /\/@\w+/.test(page)
const isNonSuccessfulStatusCode = res.statusCode > 300 const isNonSuccessfulStatusCode = res.statusCode > 300
...@@ -268,7 +268,7 @@ export async function exportAppPage( ...@@ -268,7 +268,7 @@ export async function exportAppPage(
return { return {
// Only include the metadata if the environment has next support. // Only include the metadata if the environment has next support.
metadata: hasNextSupport ? meta : undefined, metadata: hasNextSupport ? meta : undefined,
hasEmptyPrelude: Boolean(postponed) && html === '', hasEmptyStaticShell: Boolean(postponed) && html === '',
hasPostponed: Boolean(postponed), hasPostponed: Boolean(postponed),
cacheControl, cacheControl,
fetchMetrics, fetchMetrics,
......
...@@ -70,7 +70,7 @@ export type ExportRouteResult = ...@@ -70,7 +70,7 @@ export type ExportRouteResult =
cacheControl: CacheControl cacheControl: CacheControl
metadata?: Partial<RouteMetadata> metadata?: Partial<RouteMetadata>
ssgNotFound?: boolean ssgNotFound?: boolean
hasEmptyPrelude?: boolean hasEmptyStaticShell?: boolean
hasPostponed?: boolean hasPostponed?: boolean
fetchMetrics?: FetchMetrics fetchMetrics?: FetchMetrics
} }
...@@ -135,9 +135,9 @@ export type ExportAppResult = { ...@@ -135,9 +135,9 @@ export type ExportAppResult = {
*/ */
metadata?: Partial<RouteMetadata> metadata?: Partial<RouteMetadata>
/** /**
* If the page has an empty prelude when using PPR. * If the page has an empty static shell when using PPR.
*/ */
hasEmptyPrelude?: boolean hasEmptyStaticShell?: boolean
/** /**
* If the page has postponed when using PPR. * If the page has postponed when using PPR.
*/ */
......
...@@ -109,6 +109,10 @@ async function exportPageImpl( ...@@ -109,6 +109,10 @@ async function exportPageImpl(
// result, we just want to use it to error the build if there's a problem. // result, we just want to use it to error the build if there's a problem.
_isProspectiveRender: isProspectiveRender = false, _isProspectiveRender: isProspectiveRender = false,
// Configure the rendering of the page not to throw if an empty static shell
// is generated while rendering using PPR.
_doNotThrowOnEmptyStaticShell: doNotThrowOnEmptyStaticShell = false,
// Pull the original query out. // Pull the original query out.
query: originalQuery = {}, query: originalQuery = {},
} = pathMap } = pathMap
...@@ -267,6 +271,7 @@ async function exportPageImpl( ...@@ -267,6 +271,7 @@ async function exportPageImpl(
// If it's static, then it won't affect anything. // If it's static, then it won't affect anything.
// 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,
doNotThrowOnEmptyStaticShell,
experimental: { experimental: {
...input.renderOpts.experimental, ...input.renderOpts.experimental,
isRoutePPREnabled, isRoutePPREnabled,
...@@ -590,7 +595,7 @@ async function exportPage( ...@@ -590,7 +595,7 @@ async function exportPage(
cacheControl: result.cacheControl, cacheControl: result.cacheControl,
metadata: result.metadata, metadata: result.metadata,
ssgNotFound: result.ssgNotFound, ssgNotFound: result.ssgNotFound,
hasEmptyPrelude: result.hasEmptyPrelude, hasEmptyStaticShell: result.hasEmptyStaticShell,
hasPostponed: result.hasPostponed, hasPostponed: result.hasPostponed,
turborepoAccessTraceResult: turborepoAccessTraceResult.serialize(), turborepoAccessTraceResult: turborepoAccessTraceResult.serialize(),
fetchMetrics: result.fetchMetrics, fetchMetrics: result.fetchMetrics,
......
...@@ -132,7 +132,7 @@ import { ...@@ -132,7 +132,7 @@ import {
createDynamicValidationState, createDynamicValidationState,
getFirstDynamicReason, getFirstDynamicReason,
trackAllowedDynamicAccess, trackAllowedDynamicAccess,
throwIfDisallowedEmptyShell, throwIfDisallowedEmptyStaticShell,
consumeDynamicAccess, consumeDynamicAccess,
type DynamicAccess, type DynamicAccess,
} from './dynamic-rendering' } from './dynamic-rendering'
...@@ -2550,8 +2550,11 @@ async function spawnDynamicValidationInDev( ...@@ -2550,8 +2550,11 @@ async function spawnDynamicValidationInDev(
function LogDynamicValidation() { function LogDynamicValidation() {
try { try {
if (preludeIsEmpty) { // If we've disabled throwing on empty static shell, then we don't need to
throwIfDisallowedEmptyShell( // track any dynamic access that occurs above the suspense boundary because
// we'll do so in the route shell.
if (preludeIsEmpty && !ctx.renderOpts.doNotThrowOnEmptyStaticShell) {
throwIfDisallowedEmptyStaticShell(
route, route,
dynamicValidation, dynamicValidation,
serverDynamicTracking, serverDynamicTracking,
...@@ -3085,8 +3088,11 @@ async function prerenderToStream( ...@@ -3085,8 +3088,11 @@ async function prerenderToStream(
const { prelude, preludeIsEmpty } = const { prelude, preludeIsEmpty } =
await processPrelude(unprocessedPrelude) await processPrelude(unprocessedPrelude)
if (preludeIsEmpty) { // If we've disabled throwing on empty static shell, then we don't need to
throwIfDisallowedEmptyShell( // track any dynamic access that occurs above the suspense boundary because
// we'll do so in the route shell.
if (preludeIsEmpty && !ctx.renderOpts.doNotThrowOnEmptyStaticShell) {
throwIfDisallowedEmptyStaticShell(
workStore.route, workStore.route,
dynamicValidation, dynamicValidation,
serverDynamicTracking, serverDynamicTracking,
...@@ -3568,9 +3574,12 @@ async function prerenderToStream( ...@@ -3568,9 +3574,12 @@ async function prerenderToStream(
} }
} }
if (preludeIsEmpty) { // If we've disabled throwing on empty static shell, then we don't need to
// track any dynamic access that occurs above the suspense boundary because
// we'll do so in the route shell.
if (preludeIsEmpty && !ctx.renderOpts.doNotThrowOnEmptyStaticShell) {
// We don't have a shell because the root errored when we aborted. // We don't have a shell because the root errored when we aborted.
throwIfDisallowedEmptyShell( throwIfDisallowedEmptyStaticShell(
workStore.route, workStore.route,
dynamicValidation, dynamicValidation,
serverDynamicTracking, serverDynamicTracking,
......
...@@ -647,7 +647,7 @@ function createErrorWithComponentStack( ...@@ -647,7 +647,7 @@ function createErrorWithComponentStack(
return error return error
} }
export function throwIfDisallowedEmptyShell( export function throwIfDisallowedEmptyStaticShell(
route: string, route: string,
dynamicValidation: DynamicValidationState, dynamicValidation: DynamicValidationState,
serverDynamic: DynamicTrackingState, serverDynamic: DynamicTrackingState,
...@@ -688,7 +688,7 @@ export function throwIfDisallowedEmptyShell( ...@@ -688,7 +688,7 @@ export function throwIfDisallowedEmptyShell(
// blocked the root. We would have captured these during the prerender // blocked the root. We would have captured these during the prerender
// and can log them here and then terminate the build/validating render // and can log them here and then terminate the build/validating render
const dynamicErrors = dynamicValidation.dynamicErrors const dynamicErrors = dynamicValidation.dynamicErrors
if (dynamicErrors.length) { if (dynamicErrors.length > 0) {
for (let i = 0; i < dynamicErrors.length; i++) { for (let i = 0; i < dynamicErrors.length; i++) {
console.error(dynamicErrors[i]) console.error(dynamicErrors[i])
} }
......
...@@ -262,6 +262,13 @@ export interface RenderOptsPartial { ...@@ -262,6 +262,13 @@ export interface RenderOptsPartial {
reactMaxHeadersLength: number | undefined reactMaxHeadersLength: number | undefined
isStaticGeneration?: boolean isStaticGeneration?: boolean
/**
* When true, the page will be rendered using the static rendering to detect
* any dynamic API's that would have stopped the page from being fully
* statically generated.
*/
doNotThrowOnEmptyStaticShell?: boolean
} }
export type RenderOpts = LoadComponentsReturnType<AppPageModule> & export type RenderOpts = LoadComponentsReturnType<AppPageModule> &
......
...@@ -41,6 +41,7 @@ const zExportMap: zod.ZodType<ExportPathMap> = z.record( ...@@ -41,6 +41,7 @@ const zExportMap: zod.ZodType<ExportPathMap> = z.record(
_isDynamicError: z.boolean().optional(), _isDynamicError: z.boolean().optional(),
_isRoutePPREnabled: z.boolean().optional(), _isRoutePPREnabled: z.boolean().optional(),
_isProspectiveRender: z.boolean().optional(), _isProspectiveRender: z.boolean().optional(),
_doNotThrowOnEmptyStaticShell: z.boolean().optional(),
}) })
) )
......
...@@ -719,6 +719,15 @@ export type ExportPathMap = { ...@@ -719,6 +719,15 @@ export type ExportPathMap = {
* @internal * @internal
*/ */
_isProspectiveRender?: boolean _isProspectiveRender?: boolean
/**
* When true, it indicates that the diagnostic render for this page is
* disabled. This is only used when the app has `experimental.ppr` and
* `experimental.dynamicIO` enabled.
*
* @internal
*/
_doNotThrowOnEmptyStaticShell?: boolean
} }
} }
......
export default async function Page({ params }) {
const { slug } = await params
return <div data-testid={`hello-${slug}`}>Hello /{slug}</div>
}
export async function generateStaticParams() {
return [{ slug: 'foo' }]
}
import { Suspense } from 'react'
export default function Layout({ children }) {
return (
<html>
<Suspense>
<body>{children}</body>
</Suspense>
</html>
)
}
import { nextTestSetup } from 'e2e-utils'
describe('empty-fallback-shells', () => {
const { next, isNextDeploy } = nextTestSetup({
files: __dirname,
})
it('should start and not postpone the response', async () => {
const res = await next.fetch('/world')
const html = await res.text()
expect(html).toContain('hello-world')
if (isNextDeploy) {
expect(res.headers.get('x-matched-path')).toBe('/[slug]')
}
// If we didn't use the fallback shell, then we didn't postpone the response
// and therefore shouldn't have sent the postponed header.
expect(res.headers.get('x-nextjs-postponed')).not.toBe('1')
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
dynamicIO: true,
ppr: true,
},
}
module.exports = nextConfig
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