Unverified Commit 6cc1049d authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Revert "Remove legacy PPR codepaths" (#95113)

parent 727e5453
...@@ -20,7 +20,7 @@ All flags need: `config-shared.ts` (type) → `config-schema.ts` (zod). If the f ...@@ -20,7 +20,7 @@ All flags need: `config-shared.ts` (type) → `config-schema.ts` (zod). If the f
## Where the Flag Is Consumed ## Where the Flag Is Consumed
**Client/bundled code only** (e.g. `__NEXT_CACHE_COMPONENTS` in client components): `define-env.ts` is sufficient. Webpack/Turbopack replaces `process.env.X` at the user's build time. **Client/bundled code only** (e.g. `__NEXT_PPR` in client components): `define-env.ts` is sufficient. Webpack/Turbopack replaces `process.env.X` at the user's build time.
**Pre-compiled runtime bundles** (e.g. code in `app-render.tsx`): The flag must also be set as a real `process.env` var at runtime, because `app-render.tsx` runs from pre-compiled bundles where `define-env.ts` doesn't reach. Two approaches: **Pre-compiled runtime bundles** (e.g. code in `app-render.tsx`): The flag must also be set as a real `process.env` var at runtime, because `app-render.tsx` runs from pre-compiled bundles where `define-env.ts` doesn't reach. Two approaches:
......
...@@ -2109,6 +2109,7 @@ export async function handleBuildComplete({ ...@@ -2109,6 +2109,7 @@ export async function handleBuildComplete({
onMatchHeaders: [], onMatchHeaders: [],
rewrites, rewrites,
restrictedRedirectPaths: [], restrictedRedirectPaths: [],
isAppPPREnabled: config.cacheComponents,
}).routesManifest.rsc, }).routesManifest.rsc,
}, },
outputs, outputs,
......
...@@ -13,6 +13,7 @@ import { discoverRoutes } from '../route-discovery' ...@@ -13,6 +13,7 @@ import { discoverRoutes } from '../route-discovery'
import { findPagesDir } from '../../lib/find-pages-dir' import { findPagesDir } from '../../lib/find-pages-dir'
import loadCustomRoutes from '../../lib/load-custom-routes' import loadCustomRoutes from '../../lib/load-custom-routes'
import { generateRoutesManifest } from '../generate-routes-manifest' import { generateRoutesManifest } from '../generate-routes-manifest'
import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import http from 'node:http' import http from 'node:http'
...@@ -166,6 +167,8 @@ async function collectRoutesForAnalyze( ...@@ -166,6 +167,8 @@ async function collectRoutesForAnalyze(
config.basePath ? `${config.basePath}${pathPrefix}` : pathPrefix config.basePath ? `${config.basePath}${pathPrefix}` : pathPrefix
) )
const isAppPPREnabled = checkIsAppPPREnabled(config.experimental.ppr)
// Generate routes manifest // Generate routes manifest
const { routesManifest } = generateRoutesManifest({ const { routesManifest } = generateRoutesManifest({
appType, appType,
...@@ -176,6 +179,7 @@ async function collectRoutesForAnalyze( ...@@ -176,6 +179,7 @@ async function collectRoutesForAnalyze(
onMatchHeaders, onMatchHeaders,
rewrites, rewrites,
restrictedRedirectPaths, restrictedRedirectPaths,
isAppPPREnabled,
}) })
return routesManifest.dynamicRoutes return routesManifest.dynamicRoutes
......
...@@ -7,6 +7,7 @@ import type { ProxyMatcher } from './analysis/get-page-static-info' ...@@ -7,6 +7,7 @@ import type { ProxyMatcher } from './analysis/get-page-static-info'
import type { Rewrite } from '../lib/load-custom-routes' import type { Rewrite } from '../lib/load-custom-routes'
import path from 'node:path' import path from 'node:path'
import { needsExperimentalReact } from '../lib/needs-experimental-react' import { needsExperimentalReact } from '../lib/needs-experimental-react'
import { checkIsAppPPREnabled } from '../server/lib/experimental/ppr'
import { import {
getNextConfigEnv, getNextConfigEnv,
getNextPublicEnvironmentVariables, getNextPublicEnvironmentVariables,
...@@ -120,6 +121,7 @@ export function getDefineEnv({ ...@@ -120,6 +121,7 @@ export function getDefineEnv({
const nextPublicEnv = getNextPublicEnvironmentVariables() const nextPublicEnv = getNextPublicEnvironmentVariables()
const nextConfigEnv = getNextConfigEnv(config) const nextConfigEnv = getNextConfigEnv(config)
const isPPREnabled = checkIsAppPPREnabled(config.experimental.ppr)
const isCacheComponentsEnabled = !!config.cacheComponents const isCacheComponentsEnabled = !!config.cacheComponents
const isUseCacheEnabled = !!config.experimental.useCache const isUseCacheEnabled = !!config.experimental.useCache
...@@ -171,6 +173,7 @@ export function getDefineEnv({ ...@@ -171,6 +173,7 @@ export function getDefineEnv({
'process.env.__NEXT_APP_NEW_SCROLL_HANDLER': Boolean( 'process.env.__NEXT_APP_NEW_SCROLL_HANDLER': Boolean(
config.experimental.appNewScrollHandler config.experimental.appNewScrollHandler
), ),
'process.env.__NEXT_PPR': isPPREnabled,
'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled, 'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled,
'process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS': Boolean( 'process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS': Boolean(
config.experimental.cachedNavigations config.experimental.cachedNavigations
......
...@@ -34,6 +34,7 @@ export interface GenerateRoutesManifestOptions { ...@@ -34,6 +34,7 @@ export interface GenerateRoutesManifestOptions {
onMatchHeaders: CustomRoutes['headers'] onMatchHeaders: CustomRoutes['headers']
rewrites: CustomRoutes['rewrites'] rewrites: CustomRoutes['rewrites']
restrictedRedirectPaths: string[] restrictedRedirectPaths: string[]
isAppPPREnabled: boolean
appType: 'pages' | 'app' | 'hybrid' appType: 'pages' | 'app' | 'hybrid'
deploymentId?: string deploymentId?: string
} }
...@@ -60,6 +61,7 @@ export function generateRoutesManifest( ...@@ -60,6 +61,7 @@ export function generateRoutesManifest(
onMatchHeaders, onMatchHeaders,
rewrites, rewrites,
restrictedRedirectPaths, restrictedRedirectPaths,
isAppPPREnabled,
appType, appType,
deploymentId, deploymentId,
} = options } = options
...@@ -92,8 +94,6 @@ export function generateRoutesManifest( ...@@ -92,8 +94,6 @@ export function generateRoutesManifest(
} }
} }
const enableCacheComponents = Boolean(config.cacheComponents)
const routesManifest: RoutesManifest = { const routesManifest: RoutesManifest = {
version: 3, version: 3,
pages404: true, pages404: true,
...@@ -130,9 +130,9 @@ export function generateRoutesManifest( ...@@ -130,9 +130,9 @@ export function generateRoutesManifest(
prefetchSegmentHeader: NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, prefetchSegmentHeader: NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
prefetchSegmentSuffix: RSC_SEGMENT_SUFFIX, prefetchSegmentSuffix: RSC_SEGMENT_SUFFIX,
prefetchSegmentDirSuffix: RSC_SEGMENTS_DIR_SUFFIX, prefetchSegmentDirSuffix: RSC_SEGMENTS_DIR_SUFFIX,
clientParamParsing: enableCacheComponents, clientParamParsing: config.cacheComponents ?? false,
clientParamParsingOrigins: config.experimental.clientParamParsingOrigins, clientParamParsingOrigins: config.experimental.clientParamParsingOrigins,
dynamicRSCPrerender: enableCacheComponents, dynamicRSCPrerender: isAppPPREnabled && config.cacheComponents === true,
}, },
rewriteHeaders: { rewriteHeaders: {
pathHeader: NEXT_REWRITTEN_PATH_HEADER, pathHeader: NEXT_REWRITTEN_PATH_HEADER,
...@@ -140,7 +140,7 @@ export function generateRoutesManifest( ...@@ -140,7 +140,7 @@ export function generateRoutesManifest(
}, },
skipProxyUrlNormalize: config.skipProxyUrlNormalize, skipProxyUrlNormalize: config.skipProxyUrlNormalize,
deploymentId: deploymentId || undefined, deploymentId: deploymentId || undefined,
ppr: enableCacheComponents ppr: isAppPPREnabled
? { ? {
chain: { chain: {
headers: { headers: {
......
...@@ -191,6 +191,10 @@ import { traceMemoryUsage } from '../lib/memory/trace' ...@@ -191,6 +191,10 @@ import { traceMemoryUsage } from '../lib/memory/trace'
import { generateEncryptionKeyBase64 } from '../server/app-render/encryption-utils-server' import { generateEncryptionKeyBase64 } from '../server/app-render/encryption-utils-server'
import type { DeepReadonly } from '../shared/lib/deep-readonly' import type { DeepReadonly } from '../shared/lib/deep-readonly'
import uploadTrace from '../trace/upload-trace' import uploadTrace from '../trace/upload-trace'
import {
checkIsAppPPREnabled,
checkIsRoutePPREnabled,
} from '../server/lib/experimental/ppr'
import { FallbackMode, fallbackModeToFallbackField } from '../lib/fallback' import { FallbackMode, fallbackModeToFallbackField } from '../lib/fallback'
import { RenderingMode } from './rendering-mode' import { RenderingMode } from './rendering-mode'
import { InvariantError } from '../shared/lib/invariant-error' import { InvariantError } from '../shared/lib/invariant-error'
...@@ -1520,6 +1524,7 @@ export default async function build( ...@@ -1520,6 +1524,7 @@ export default async function build(
const isAuthInterruptsEnabled = Boolean( const isAuthInterruptsEnabled = Boolean(
config.experimental.authInterrupts config.experimental.authInterrupts
) )
const isAppPPREnabled = checkIsAppPPREnabled(config.experimental.ppr)
const routesManifestPath = path.join(distDir, ROUTES_MANIFEST) const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)
...@@ -1536,6 +1541,7 @@ export default async function build( ...@@ -1536,6 +1541,7 @@ export default async function build(
onMatchHeaders, onMatchHeaders,
rewrites, rewrites,
restrictedRedirectPaths, restrictedRedirectPaths,
isAppPPREnabled,
deploymentId: config.deploymentId, deploymentId: config.deploymentId,
}) })
) )
...@@ -2105,6 +2111,7 @@ export default async function build( ...@@ -2105,6 +2111,7 @@ export default async function build(
locales: config.i18n?.locales, locales: config.i18n?.locales,
defaultLocale: config.i18n?.defaultLocale, defaultLocale: config.i18n?.defaultLocale,
nextConfigOutput: config.output, nextConfigOutput: config.output,
pprConfig: config.experimental.ppr,
cacheLifeProfiles: config.cacheLife, cacheLifeProfiles: config.cacheLife,
buildId, buildId,
deploymentId: config.deploymentId, deploymentId: config.deploymentId,
...@@ -2337,6 +2344,7 @@ export default async function build( ...@@ -2337,6 +2344,7 @@ export default async function build(
: config.experimental.isrFlushToDisk, : config.experimental.isrFlushToDisk,
cacheMaxMemorySize: config.cacheMaxMemorySize, cacheMaxMemorySize: config.cacheMaxMemorySize,
nextConfigOutput: config.output, nextConfigOutput: config.output,
pprConfig: config.experimental.ppr,
cacheLifeProfiles: config.cacheLife, cacheLifeProfiles: config.cacheLife,
buildId, buildId,
deploymentId: config.deploymentId, deploymentId: config.deploymentId,
...@@ -2741,6 +2749,10 @@ export default async function build( ...@@ -2741,6 +2749,10 @@ export default async function build(
featureName: 'experimental/nextScriptWorkers', featureName: 'experimental/nextScriptWorkers',
invocationCount: config.experimental.nextScriptWorkers ? 1 : 0, invocationCount: config.experimental.nextScriptWorkers ? 1 : 0,
}, },
{
featureName: 'experimental/ppr',
invocationCount: config.experimental.ppr ? 1 : 0,
},
{ {
featureName: 'turbopackFileSystemCache', featureName: 'turbopackFileSystemCache',
invocationCount: config.experimental?.turbopackFileSystemCacheForBuild invocationCount: config.experimental?.turbopackFileSystemCacheForBuild
...@@ -2930,6 +2942,10 @@ export default async function build( ...@@ -2930,6 +2942,10 @@ 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: boolean = appConfig
? checkIsRoutePPREnabled(config.experimental.ppr)
: 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
// rendering the route. This is because we don't support // rendering the route. This is because we don't support
...@@ -2954,6 +2970,7 @@ export default async function build( ...@@ -2954,6 +2970,7 @@ export default async function build(
_fallbackRouteParams: route.fallbackRouteParams, _fallbackRouteParams: route.fallbackRouteParams,
_isDynamicError: isDynamicError, _isDynamicError: isDynamicError,
_isAppDir: true, _isAppDir: true,
_isRoutePPREnabled: isRoutePPREnabled,
_allowEmptyStaticShell: !route.throwOnEmptyStaticShell, _allowEmptyStaticShell: !route.throwOnEmptyStaticShell,
// A fallback shell can only be upgraded if at least one of // A fallback shell can only be upgraded if at least one of
// its fallback params is a `generateStaticParams` candidate. // its fallback params is a `generateStaticParams` candidate.
...@@ -3124,7 +3141,8 @@ export default async function build( ...@@ -3124,7 +3141,8 @@ export default async function build(
// When this is an app page and PPR is enabled, the route supports // When this is an app page and PPR is enabled, the route supports
// partial pre-rendering. // partial pre-rendering.
const isRoutePPREnabled: true | undefined = const isRoutePPREnabled: true | undefined =
!isAppRouteHandler && Boolean(config.cacheComponents) !isAppRouteHandler &&
checkIsRoutePPREnabled(config.experimental.ppr)
? true ? true
: undefined : undefined
...@@ -3306,7 +3324,7 @@ export default async function build( ...@@ -3306,7 +3324,7 @@ export default async function build(
prerenderManifest.routes[route.pathname] = { prerenderManifest.routes[route.pathname] = {
initialStatus: status, initialStatus: status,
initialHeaders: meta.headers, initialHeaders: meta.headers,
renderingMode: isAppCacheComponentsEnabled renderingMode: isAppPPREnabled
? isRoutePPREnabled ? isRoutePPREnabled
? RenderingMode.PARTIALLY_STATIC ? RenderingMode.PARTIALLY_STATIC
: RenderingMode.STATIC : RenderingMode.STATIC
...@@ -3404,7 +3422,7 @@ export default async function build( ...@@ -3404,7 +3422,7 @@ export default async function build(
let dynamicRoute = routesManifest.dynamicRoutes.find( let dynamicRoute = routesManifest.dynamicRoutes.find(
(r) => r.page === route.pathname (r) => r.page === route.pathname
) )
if (!isAppRouteHandler && isAppCacheComponentsEnabled) { if (!isAppRouteHandler && isAppPPREnabled) {
// If the dynamic route wasn't found, then we need to create // If the dynamic route wasn't found, then we need to create
// it. This ensures that for each fallback shell there's an // it. This ensures that for each fallback shell there's an
// entry in the app routes manifest which enables routing for // entry in the app routes manifest which enables routing for
...@@ -3539,7 +3557,7 @@ export default async function build( ...@@ -3539,7 +3557,7 @@ export default async function build(
experimentalPPR: isRoutePPREnabled, experimentalPPR: isRoutePPREnabled,
remainingPrerenderableParams: remainingPrerenderableParams:
route.remainingPrerenderableParams, route.remainingPrerenderableParams,
renderingMode: isAppCacheComponentsEnabled renderingMode: isAppPPREnabled
? isRoutePPREnabled ? isRoutePPREnabled
? RenderingMode.PARTIALLY_STATIC ? RenderingMode.PARTIALLY_STATIC
: RenderingMode.STATIC : RenderingMode.STATIC
......
...@@ -789,7 +789,7 @@ export async function buildAppStaticPaths({ ...@@ -789,7 +789,7 @@ export async function buildAppStaticPaths({
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
nextConfigOutput, nextConfigOutput,
ComponentMod, ComponentMod,
isRoutePPREnabled, isRoutePPREnabled = false,
buildId, buildId,
deploymentId, deploymentId,
rootParamKeys, rootParamKeys,
......
...@@ -29,6 +29,7 @@ import { ...@@ -29,6 +29,7 @@ import {
NodeNextRequest, NodeNextRequest,
NodeNextResponse, NodeNextResponse,
} from '../../server/base-http/node' with { 'turbopack-transition': 'next-server-utility' } } from '../../server/base-http/node' with { 'turbopack-transition': 'next-server-utility' }
import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr' with { 'turbopack-transition': 'next-server-utility' }
import { isRSCRequestHeader } from '../../server/lib/is-rsc-request' with { 'turbopack-transition': 'next-server-utility' } import { isRSCRequestHeader } from '../../server/lib/is-rsc-request' with { 'turbopack-transition': 'next-server-utility' }
import { import {
getFallbackRouteParams, getFallbackRouteParams,
...@@ -118,6 +119,7 @@ import * as entryBase from '../../server/app-render/entry-base' with { 'turbopac ...@@ -118,6 +119,7 @@ import * as entryBase from '../../server/app-render/entry-base' with { 'turbopac
import { RedirectStatusCode } from '../../client/components/redirect-status-code' with { 'turbopack-transition': 'next-server-utility' } import { RedirectStatusCode } from '../../client/components/redirect-status-code' with { 'turbopack-transition': 'next-server-utility' }
import { InvariantError } from '../../shared/lib/invariant-error' with { 'turbopack-transition': 'next-server-utility' } import { InvariantError } from '../../shared/lib/invariant-error' with { 'turbopack-transition': 'next-server-utility' }
import { scheduleOnNextTick } from '../../lib/scheduler' with { 'turbopack-transition': 'next-server-utility' } import { scheduleOnNextTick } from '../../lib/scheduler' with { 'turbopack-transition': 'next-server-utility' }
import { isInterceptionRouteAppPath } from '../../shared/lib/router/utils/interception-routes' with { 'turbopack-transition': 'next-server-utility' }
import { getSegmentParam } from '../../shared/lib/router/utils/get-segment-param' with { 'turbopack-transition': 'next-server-utility' } import { getSegmentParam } from '../../shared/lib/router/utils/get-segment-param' with { 'turbopack-transition': 'next-server-utility' }
export * from '../../server/app-render/entry-base' with { 'turbopack-transition': 'next-server-utility' } export * from '../../server/app-render/entry-base' with { 'turbopack-transition': 'next-server-utility' }
...@@ -270,8 +272,16 @@ export async function handler( ...@@ -270,8 +272,16 @@ export async function handler(
// We use the resolvedPathname instead of the parsedUrl.pathname because it // We use the resolvedPathname instead of the parsedUrl.pathname because it
// is not rewritten as resolvedPathname is. This will ensure that the correct // is not rewritten as resolvedPathname is. This will ensure that the correct
// prerender info is used instead of using the original pathname as the // prerender info is used instead of using the original pathname as the
// source. // source. If however PPR is enabled and cacheComponents is disabled, we
const prerenderMatch = routeModule.match(resolvedPathname, prerenderManifest) // treat the pathname as dynamic. Currently, there's a bug in the PPR
// implementation that incorrectly leaves %%drp placeholders in the output of
// parallel routes. This is addressed with cacheComponents.
const prerenderMatch =
nextConfig.experimental.ppr &&
!nextConfig.cacheComponents &&
isInterceptionRouteAppPath(resolvedPathname)
? null
: routeModule.match(resolvedPathname, prerenderManifest)
const prerenderInfo = prerenderMatch?.route ?? null const prerenderInfo = prerenderMatch?.route ?? null
const isPrerendered = !!prerenderManifest.routes[resolvedPathname] const isPrerendered = !!prerenderManifest.routes[resolvedPathname]
...@@ -300,7 +310,9 @@ export async function handler( ...@@ -300,7 +310,9 @@ export async function handler(
* If the route being rendered is an app page, and the ppr feature has been * If the route being rendered is an app page, and the ppr feature has been
* enabled, then the given route _could_ support PPR. * enabled, then the given route _could_ support PPR.
*/ */
const couldSupportPPR = Boolean(nextConfig.cacheComponents) const couldSupportPPR: boolean = checkIsAppPPREnabled(
nextConfig.experimental.ppr
)
// Stash postponed state for server actions when in minimal mode. // Stash postponed state for server actions when in minimal mode.
// We extract it here so the RDC is available for the re-render after the action completes. // We extract it here so the RDC is available for the re-render after the action completes.
...@@ -899,6 +911,7 @@ export async function handler( ...@@ -899,6 +911,7 @@ export async function handler(
validationLevel: validationLevel:
nextConfig.experimental.instantInsights.validationLevel, nextConfig.experimental.instantInsights.validationLevel,
experimental: { experimental: {
isRoutePPREnabled,
expireTime: nextConfig.expireTime, expireTime: nextConfig.expireTime,
staleTimes: nextConfig.experimental.staleTimes, staleTimes: nextConfig.experimental.staleTimes,
dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover), dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover),
......
...@@ -166,6 +166,7 @@ async function requestHandler( ...@@ -166,6 +166,7 @@ async function requestHandler(
cacheComponents: Boolean(nextConfig.cacheComponents), cacheComponents: Boolean(nextConfig.cacheComponents),
validationLevel: nextConfig.experimental.instantInsights.validationLevel, validationLevel: nextConfig.experimental.instantInsights.validationLevel,
experimental: { experimental: {
isRoutePPREnabled: false,
expireTime: nextConfig.expireTime, expireTime: nextConfig.expireTime,
staleTimes: nextConfig.experimental.staleTimes, staleTimes: nextConfig.experimental.staleTimes,
dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover), dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover),
......
...@@ -2,6 +2,8 @@ import type { ...@@ -2,6 +2,8 @@ import type {
NextConfigComplete, NextConfigComplete,
NextConfigRuntime, NextConfigRuntime,
} from '../server/config-shared' } from '../server/config-shared'
import type { ExperimentalPPRConfig } from '../server/lib/experimental/ppr'
import { checkIsRoutePPREnabled } from '../server/lib/experimental/ppr'
import type { AssetBinding } from './webpack/loaders/get-module-build-info' import type { AssetBinding } from './webpack/loaders/get-module-build-info'
import type { ServerRuntime } from '../types' import type { ServerRuntime } from '../types'
import type { BuildManifest } from '../server/get-page-files' import type { BuildManifest } from '../server/get-page-files'
...@@ -703,6 +705,7 @@ export async function isPageStatic({ ...@@ -703,6 +705,7 @@ export async function isPageStatic({
cacheHandler, cacheHandler,
cacheHandlers, cacheHandlers,
cacheLifeProfiles, cacheLifeProfiles,
pprConfig,
buildId, buildId,
deploymentId, deploymentId,
clientAssetToken, clientAssetToken,
...@@ -732,6 +735,7 @@ export async function isPageStatic({ ...@@ -732,6 +735,7 @@ export async function isPageStatic({
[profile: string]: import('../server/use-cache/cache-life').CacheLife [profile: string]: import('../server/use-cache/cache-life').CacheLife
} }
nextConfigOutput: 'standalone' | 'export' | undefined nextConfigOutput: 'standalone' | 'export' | undefined
pprConfig: ExperimentalPPRConfig | undefined
buildId: string buildId: string
deploymentId: string deploymentId: string
clientAssetToken: string clientAssetToken: string
...@@ -859,8 +863,12 @@ export async function isPageStatic({ ...@@ -859,8 +863,12 @@ export async function isPageStatic({
rootParamKeys = collectRootParamKeys(routeModule) rootParamKeys = collectRootParamKeys(routeModule)
// A page supports partial prerendering if it is an app page and either
// the whole app has PPR enabled or this page has PPR enabled when we're
// in incremental mode.
isRoutePPREnabled = isRoutePPREnabled =
routeModule.definition.kind === RouteKind.APP_PAGE && cacheComponents routeModule.definition.kind === RouteKind.APP_PAGE &&
checkIsRoutePPREnabled(pprConfig)
// If force dynamic was set and we don't have PPR enabled, then set the // If force dynamic was set and we don't have PPR enabled, then set the
// revalidate to 0. // revalidate to 0.
......
...@@ -20,6 +20,7 @@ function hasFallbackRouteParams(): boolean { ...@@ -20,6 +20,7 @@ function hasFallbackRouteParams(): boolean {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'prerender-ppr':
case 'validation-client': case 'validation-client':
const fallbackParams = workUnitStore.fallbackRouteParams const fallbackParams = workUnitStore.fallbackRouteParams
return fallbackParams ? fallbackParams.size > 0 : false return fallbackParams ? fallbackParams.size > 0 : false
......
...@@ -190,7 +190,10 @@ export async function fetchServerResponse( ...@@ -190,7 +190,10 @@ export async function fetchServerResponse(
// Typically, during a navigation, we decode the response using Flight's // Typically, during a navigation, we decode the response using Flight's
// `createFromFetch` API, which accepts a `fetch` promise. // `createFromFetch` API, which accepts a `fetch` promise.
const shouldImmediatelyDecode = true // TODO: Remove this check once the old PPR flag is removed
const isLegacyPPR =
process.env.__NEXT_PPR && !process.env.__NEXT_CACHE_COMPONENTS
const shouldImmediatelyDecode = !isLegacyPPR
const res = await createFetch<NavigationFlightResponse>( const res = await createFetch<NavigationFlightResponse>(
url, url,
headers, headers,
......
import { isHangingPromiseRejectionError } from '../../server/dynamic-rendering-utils' import { isHangingPromiseRejectionError } from '../../server/dynamic-rendering-utils'
import { isPostpone } from '../../server/lib/router-utils/is-postpone'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr' import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { isNextRouterError } from './is-next-router-error' import { isNextRouterError } from './is-next-router-error'
import { isPrerenderInterruptedError } from '../../server/app-render/dynamic-rendering' import {
isDynamicPostpone,
isPrerenderInterruptedError,
} from '../../server/app-render/dynamic-rendering'
import { isDynamicServerError } from './hooks-server-context' import { isDynamicServerError } from './hooks-server-context'
export function unstable_rethrow(error: unknown): void { export function unstable_rethrow(error: unknown): void {
...@@ -9,6 +13,8 @@ export function unstable_rethrow(error: unknown): void { ...@@ -9,6 +13,8 @@ export function unstable_rethrow(error: unknown): void {
isNextRouterError(error) || isNextRouterError(error) ||
isBailoutToCSRError(error) || isBailoutToCSRError(error) ||
isDynamicServerError(error) || isDynamicServerError(error) ||
isDynamicPostpone(error) ||
isPostpone(error) ||
isHangingPromiseRejectionError(error) || isHangingPromiseRejectionError(error) ||
isPrerenderInterruptedError(error) isPrerenderInterruptedError(error)
) { ) {
......
import { isDynamicServerError } from '../../client/components/hooks-server-context' import { isDynamicServerError } from '../../client/components/hooks-server-context'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr' import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { isNextRouterError } from '../../client/components/is-next-router-error' import { isNextRouterError } from '../../client/components/is-next-router-error'
import { isDynamicPostpone } from '../../server/app-render/dynamic-rendering'
export const isDynamicUsageError = (err: unknown) => export const isDynamicUsageError = (err: unknown) =>
isDynamicServerError(err) || isDynamicServerError(err) ||
isBailoutToCSRError(err) || isBailoutToCSRError(err) ||
isNextRouterError(err) isNextRouterError(err) ||
isDynamicPostpone(err)
...@@ -880,11 +880,9 @@ async function exportAppImpl( ...@@ -880,11 +880,9 @@ async function exportAppImpl(
} }
// Export mode provide static outputs that are not compatible with PPR mode. // Export mode provide static outputs that are not compatible with PPR mode.
if (!options.buildExport && nextConfig.cacheComponents) { if (!options.buildExport && nextConfig.experimental.ppr) {
// TODO: add message // TODO: add message
throw new Error( throw new Error('Invariant: PPR cannot be enabled in export mode')
'Invariant: Cache Components cannot be enabled in export mode'
)
} }
// copy prerendered routes to outDir // copy prerendered routes to outDir
......
...@@ -105,7 +105,7 @@ export async function exportAppPage( ...@@ -105,7 +105,7 @@ export async function exportAppPage(
} = metadata } = metadata
// Ensure we don't postpone without having PPR enabled. // Ensure we don't postpone without having PPR enabled.
if (postponed && !renderOpts.cacheComponents) { if (postponed && !renderOpts.experimental.isRoutePPREnabled) {
throw new Error('Invariant: page postponed without PPR being enabled') throw new Error('Invariant: page postponed without PPR being enabled')
} }
...@@ -145,7 +145,8 @@ export async function exportAppPage( ...@@ -145,7 +145,8 @@ export async function exportAppPage(
const hasFallbackParams = const hasFallbackParams =
fallbackRouteParams != null && fallbackRouteParams.size > 0 fallbackRouteParams != null && fallbackRouteParams.size > 0
const shouldWriteRsc = const shouldWriteRsc =
!renderOpts.cacheComponents || (!postponed && !hasFallbackParams) !renderOpts.experimental.isRoutePPREnabled ||
(!postponed && !hasFallbackParams)
hasStaticRsc = shouldWriteRsc hasStaticRsc = shouldWriteRsc
// With PPR enabled, we normally skip writing .rsc because it may contain // With PPR enabled, we normally skip writing .rsc because it may contain
...@@ -197,7 +198,7 @@ export async function exportAppPage( ...@@ -197,7 +198,7 @@ export async function exportAppPage(
// When PPR is enabled, we don't always send 200 for routes that have been // When PPR is enabled, we don't always send 200 for routes that have been
// pregenerated, so we should grab the status code from the mocked // pregenerated, so we should grab the status code from the mocked
// response. // response.
let status: number | undefined = renderOpts.cacheComponents let status: number | undefined = renderOpts.experimental.isRoutePPREnabled
? res.statusCode ? res.statusCode
: undefined : undefined
......
...@@ -36,6 +36,7 @@ import { exportAppPage } from './routes/app-page' ...@@ -36,6 +36,7 @@ import { exportAppPage } from './routes/app-page'
import { exportPagesPage } from './routes/pages' import { exportPagesPage } from './routes/pages'
import { getParams } from './helpers/get-params' import { getParams } from './helpers/get-params'
import { createIncrementalCache } from './helpers/create-incremental-cache' import { createIncrementalCache } from './helpers/create-incremental-cache'
import { isPostpone } from '../server/lib/router-utils/is-postpone'
import { isDynamicUsageError } from './helpers/is-dynamic-usage-error' import { isDynamicUsageError } from './helpers/is-dynamic-usage-error'
import { isBailoutToCSRError } from '../shared/lib/lazy-dynamic/bailout-to-csr' import { isBailoutToCSRError } from '../shared/lib/lazy-dynamic/bailout-to-csr'
import { import {
...@@ -108,6 +109,10 @@ async function exportPageImpl( ...@@ -108,6 +109,10 @@ async function exportPageImpl(
// Check if this should error when dynamic usage is detected. // Check if this should error when dynamic usage is detected.
_isDynamicError: isDynamicError = false, _isDynamicError: isDynamicError = false,
// If this page supports partial prerendering, then we need to pass that to
// the renderOpts.
_isRoutePPREnabled: isRoutePPREnabled,
// Configure the rendering of the page to allow that an empty static shell // Configure the rendering of the page to allow that an empty static shell
// is generated while rendering using PPR and Cache Components. // is generated while rendering using PPR and Cache Components.
_allowEmptyStaticShell: allowEmptyStaticShell = false, _allowEmptyStaticShell: allowEmptyStaticShell = false,
...@@ -275,6 +280,10 @@ async function exportPageImpl( ...@@ -275,6 +280,10 @@ async function exportPageImpl(
allowEmptyStaticShell, allowEmptyStaticShell,
runInstantValidation, runInstantValidation,
isFallbackUpgradeable, isFallbackUpgradeable,
experimental: {
...commonRenderOpts.experimental,
isRoutePPREnabled,
},
renderResumeDataCache, renderResumeDataCache,
} }
...@@ -610,6 +619,12 @@ async function exportPage( ...@@ -610,6 +619,12 @@ async function exportPage(
} }
process.on('unhandledRejection', (err: unknown) => { process.on('unhandledRejection', (err: unknown) => {
// if it's a postpone error, it'll be handled later
// when the postponed promise is actually awaited.
if (isPostpone(err)) {
return
}
// we don't want to log these errors // we don't want to log these errors
if (isDynamicUsageError(err)) { if (isDynamicUsageError(err)) {
return return
......
...@@ -16,6 +16,7 @@ import { isHTTPAccessFallbackError } from '../../client/components/http-access-f ...@@ -16,6 +16,7 @@ import { isHTTPAccessFallbackError } from '../../client/components/http-access-f
import type { MetadataContext } from './types/resolvers' import type { MetadataContext } from './types/resolvers'
import { createServerSearchParamsForMetadata } from '../../server/request/search-params' import { createServerSearchParamsForMetadata } from '../../server/request/search-params'
import { createServerPathnameForMetadata } from '../../server/request/pathname' import { createServerPathnameForMetadata } from '../../server/request/pathname'
import { isPostpone } from '../../server/lib/router-utils/is-postpone'
import { import {
workUnitAsyncStorage, workUnitAsyncStorage,
getStagedRenderingController, getStagedRenderingController,
...@@ -90,6 +91,12 @@ export function createMetadataComponents({ ...@@ -90,6 +91,12 @@ export function createMetadataComponents({
isRuntimePrefetchable, isRuntimePrefetchable,
errorType errorType
).catch((viewportErr) => { ).catch((viewportErr) => {
// When Legacy PPR is enabled viewport can reject with a Postpone type
// This will go away once Legacy PPR is removed and dynamic metadata will
// stay pending until after the prerender is complete when it is dynamic
if (isPostpone(viewportErr)) {
throw viewportErr
}
if (!errorType && isHTTPAccessFallbackError(viewportErr)) { if (!errorType && isHTTPAccessFallbackError(viewportErr)) {
return getNotFoundViewport( return getNotFoundViewport(
tree, tree,
...@@ -137,6 +144,12 @@ export function createMetadataComponents({ ...@@ -137,6 +144,12 @@ export function createMetadataComponents({
isRuntimePrefetchable, isRuntimePrefetchable,
errorType errorType
).catch((metadataErr) => { ).catch((metadataErr) => {
// When Legacy PPR is enabled metadata can reject with a Postpone type
// This will go away once Legacy PPR is removed and dynamic metadata will
// stay pending until after the prerender is complete when it is dynamic
if (isPostpone(metadataErr)) {
throw metadataErr
}
if (!errorType && isHTTPAccessFallbackError(metadataErr)) { if (!errorType && isHTTPAccessFallbackError(metadataErr)) {
return getNotFoundMetadata( return getNotFoundMetadata(
tree, tree,
......
...@@ -119,7 +119,7 @@ async function createComponentTreeInternal( ...@@ -119,7 +119,7 @@ async function createComponentTreeInternal(
isRoot: boolean isRoot: boolean
): Promise<CacheNodeSeedData> { ): Promise<CacheNodeSeedData> {
const { const {
renderOpts: { nextConfigOutput, cacheComponents }, renderOpts: { nextConfigOutput, experimental, cacheComponents },
workStore, workStore,
componentMod: { componentMod: {
createElement, createElement,
...@@ -135,6 +135,7 @@ async function createComponentTreeInternal( ...@@ -135,6 +135,7 @@ async function createComponentTreeInternal(
createServerParamsForServerSegment, createServerParamsForServerSegment,
createPrerenderParamsForClientSegment, createPrerenderParamsForClientSegment,
serverHooks: { DynamicServerError }, serverHooks: { DynamicServerError },
Postpone,
}, },
pagePath, pagePath,
getDynamicParamFromSegment, getDynamicParamFromSegment,
...@@ -263,15 +264,6 @@ async function createComponentTreeInternal( ...@@ -263,15 +264,6 @@ async function createComponentTreeInternal(
: [] : []
let dynamic = layoutOrPageMod?.dynamic let dynamic = layoutOrPageMod?.dynamic
if (typeof dynamic === 'string') {
if (cacheComponents) {
// TODO: Remove this since this should be caught during compilation.
// Left as a guard in case usage of Postpone was attempted
throw new Error(
`Route segment config "dynamic" is not compatible with \`nextConfig.cacheComponents\`. Please remove it.`
)
}
}
if (nextConfigOutput === 'export') { if (nextConfigOutput === 'export') {
if (!dynamic || dynamic === 'auto') { if (!dynamic || dynamic === 'auto') {
...@@ -293,7 +285,10 @@ async function createComponentTreeInternal( ...@@ -293,7 +285,10 @@ async function createComponentTreeInternal(
} else if (dynamic === 'force-dynamic') { } else if (dynamic === 'force-dynamic') {
workStore.forceDynamic = true workStore.forceDynamic = true
if (workStore.isStaticGeneration) { // TODO: (PPR) remove this bailout once PPR is the default
if (workStore.isStaticGeneration && !experimental.isRoutePPREnabled) {
// If the postpone API isn't available, we can't postpone the render and
// therefore we can't use the dynamic API.
const err = new DynamicServerError( const err = new DynamicServerError(
`Page with \`dynamic = "force-dynamic"\` won't be rendered statically.` `Page with \`dynamic = "force-dynamic"\` won't be rendered statically.`
) )
...@@ -325,6 +320,7 @@ async function createComponentTreeInternal( ...@@ -325,6 +320,7 @@ async function createComponentTreeInternal(
case 'prerender': case 'prerender':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-ppr':
if (workUnitStore.revalidate > defaultRevalidate) { if (workUnitStore.revalidate > defaultRevalidate) {
workUnitStore.revalidate = defaultRevalidate workUnitStore.revalidate = defaultRevalidate
} }
...@@ -351,7 +347,7 @@ async function createComponentTreeInternal( ...@@ -351,7 +347,7 @@ async function createComponentTreeInternal(
defaultRevalidate === 0 && defaultRevalidate === 0 &&
// If the postpone API isn't available, we can't postpone the render and // If the postpone API isn't available, we can't postpone the render and
// therefore we can't use the dynamic API. // therefore we can't use the dynamic API.
!cacheComponents !experimental.isRoutePPREnabled
) { ) {
const dynamicUsageDescription = `revalidate: 0 configured ${segment}` const dynamicUsageDescription = `revalidate: 0 configured ${segment}`
workStore.dynamicUsageDescription = dynamicUsageDescription workStore.dynamicUsageDescription = dynamicUsageDescription
...@@ -375,6 +371,7 @@ async function createComponentTreeInternal( ...@@ -375,6 +371,7 @@ async function createComponentTreeInternal(
case 'prerender': case 'prerender':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-ppr':
if (workUnitStore.stale > pageStaleTime) { if (workUnitStore.stale > pageStaleTime) {
workUnitStore.stale = pageStaleTime workUnitStore.stale = pageStaleTime
} }
...@@ -417,7 +414,7 @@ async function createComponentTreeInternal( ...@@ -417,7 +414,7 @@ async function createComponentTreeInternal(
// For dynamic requests, this must always be `false` because dynamic responses // For dynamic requests, this must always be `false` because dynamic responses
// are never partial. // are never partial.
const isPossiblyPartialResponse = const isPossiblyPartialResponse =
isStaticGeneration && cacheComponents === true isStaticGeneration && experimental.isRoutePPREnabled === true
const LayoutOrPage: ComponentType<any> | undefined = layoutOrPageMod const LayoutOrPage: ComponentType<any> | undefined = layoutOrPageMod
? interopDefault(layoutOrPageMod) ? interopDefault(layoutOrPageMod)
...@@ -579,7 +576,7 @@ async function createComponentTreeInternal( ...@@ -579,7 +576,7 @@ async function createComponentTreeInternal(
// possible during both prefetches and dynamic navigations. But during // possible during both prefetches and dynamic navigations. But during
// the beta period, we should be clear about this trade off in our // the beta period, we should be clear about this trade off in our
// communications. // communications.
!cacheComponents !experimental.isRoutePPREnabled
) { ) {
// Don't prefetch this child. This will trigger a lazy fetch by the // Don't prefetch this child. This will trigger a lazy fetch by the
// client router. // client router.
...@@ -774,15 +771,43 @@ async function createComponentTreeInternal( ...@@ -774,15 +771,43 @@ async function createComponentTreeInternal(
} }
const Component = MaybeComponent const Component = MaybeComponent
// If force-dynamic is used and the current render supports postponing, we
// replace it with a node that will postpone the render. This ensures that the
// postpone is invoked during the react render phase and not during the next
// render phase.
// @TODO this does not actually do what it seems like it would or should do. The idea is that
// if we are rendering in a force-dynamic mode and we can postpone we should only make the segments
// that ask for force-dynamic to be dynamic, allowing other segments to still prerender. However
// because this comes after the children traversal and the static generation store is mutated every segment
// along the parent path of a force-dynamic segment will hit this condition effectively making the entire
// render force-dynamic. We should refactor this function so that we can correctly track which segments
// need to be dynamic
if ( if (
workStore.isStaticGeneration && workStore.isStaticGeneration &&
workStore.forceDynamic && workStore.forceDynamic &&
cacheComponents experimental.isRoutePPREnabled
) { ) {
// TODO: Remove this since this should be caught during compilation. return createSeedData(
// Left as a guard in case usage of Postpone was attempted ctx,
throw new Error( createElement(
`Route segment config "dynamic" is not compatible with \`nextConfig.cacheComponents\`. Please remove it.` Fragment,
{
key: cacheNodeKey,
},
createElement(Postpone, {
reason: 'dynamic = "force-dynamic" was used',
route: workStore.route,
}),
layerAssets
),
parallelRouteCacheNodeSeedData,
loadingData,
true,
isRuntimePrefetchable,
// force-dynamic postpones without rendering the component, so no params
// are accessed. The vary params are empty.
emptyVaryParamsAccumulator
) )
} }
...@@ -1306,6 +1331,7 @@ function createSeedData( ...@@ -1306,6 +1331,7 @@ function createSeedData(
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
......
...@@ -29,6 +29,7 @@ import type { ...@@ -29,6 +29,7 @@ import type {
PrerenderStoreModernServer, PrerenderStoreModernServer,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
// Once postpone is in stable we should switch to importing the postpone export directly
import React from 'react' import React from 'react'
import { DynamicServerError } from '../../client/components/hooks-server-context' import { DynamicServerError } from '../../client/components/hooks-server-context'
...@@ -78,6 +79,8 @@ import { ...@@ -78,6 +79,8 @@ import {
} from './instant-validation/boundary-tracking' } from './instant-validation/boundary-tracking'
import type { InstantValidationSampleTracking } from './instant-validation/instant-samples' import type { InstantValidationSampleTracking } from './instant-validation/instant-samples'
const hasPostpone = typeof React.unstable_postpone === 'function'
export type DynamicAccess = { export type DynamicAccess = {
/** /**
* If debugging, this will contain the stack trace of where the dynamic access * If debugging, this will contain the stack trace of where the dynamic access
...@@ -179,6 +182,7 @@ export function markCurrentScopeAsDynamic( ...@@ -179,6 +182,7 @@ export function markCurrentScopeAsDynamic(
// A private cache scope is already dynamic by definition. // A private cache scope is already dynamic by definition.
return return
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-ppr':
case 'request': case 'request':
case 'generate-static-params': case 'generate-static-params':
break break
...@@ -200,6 +204,12 @@ export function markCurrentScopeAsDynamic( ...@@ -200,6 +204,12 @@ export function markCurrentScopeAsDynamic(
if (workUnitStore) { if (workUnitStore) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'prerender-ppr':
return postponeWithTracking(
store.route,
expression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy': case 'prerender-legacy':
workUnitStore.revalidate = 0 workUnitStore.revalidate = 0
...@@ -271,6 +281,7 @@ export function trackDynamicDataInDynamicRender(workUnitStore: WorkUnitStore) { ...@@ -271,6 +281,7 @@ export function trackDynamicDataInDynamicRender(workUnitStore: WorkUnitStore) {
case 'prerender': case 'prerender':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'generate-static-params': case 'generate-static-params':
...@@ -368,6 +379,78 @@ export function abortAndThrowOnSynchronousRequestDataAccess( ...@@ -368,6 +379,78 @@ export function abortAndThrowOnSynchronousRequestDataAccess(
) )
} }
/**
* This component will call `React.postpone` that throws the postponed error.
*/
type PostponeProps = {
reason: string
route: string
}
export function Postpone({ reason, route }: PostponeProps): never {
const prerenderStore = workUnitAsyncStorage.getStore()
const dynamicTracking =
prerenderStore && prerenderStore.type === 'prerender-ppr'
? prerenderStore.dynamicTracking
: null
postponeWithTracking(route, reason, dynamicTracking)
}
export function postponeWithTracking(
route: string,
expression: string,
dynamicTracking: null | DynamicTrackingState
): never {
assertPostpone()
if (dynamicTracking) {
dynamicTracking.dynamicAccesses.push({
// When we aren't debugging, we don't need to create another error for the
// stack trace.
stack: dynamicTracking.isDebugDynamicAccesses
? new Error().stack
: undefined,
expression,
})
}
React.unstable_postpone(createPostponeReason(route, expression))
}
function createPostponeReason(route: string, expression: string) {
return (
`Route ${route} needs to bail out of prerendering at this point because it used ${expression}. ` +
`React throws this special object to indicate where. It should not be caught by ` +
`your own try/catch. Learn more: https://nextjs.org/docs/messages/ppr-caught-error`
)
}
export function isDynamicPostpone(err: unknown) {
if (
typeof err === 'object' &&
err !== null &&
typeof (err as any).message === 'string'
) {
return isDynamicPostponeReason((err as any).message)
}
return false
}
function isDynamicPostponeReason(reason: string) {
return (
reason.includes(
'needs to bail out of prerendering at this point because it used'
) &&
reason.includes(
'Learn more: https://nextjs.org/docs/messages/ppr-caught-error'
)
)
}
if (isDynamicPostponeReason(createPostponeReason('%%%', '^^^')) === false) {
throw new Error(
'Invariant: isDynamicPostpone misidentified a postpone reason. This is a bug in Next.js'
)
}
const NEXT_PRERENDER_INTERRUPTED = 'NEXT_PRERENDER_INTERRUPTED' const NEXT_PRERENDER_INTERRUPTED = 'NEXT_PRERENDER_INTERRUPTED'
function createPrerenderInterruptedError(message: string): Error { function createPrerenderInterruptedError(message: string): Error {
...@@ -448,6 +531,18 @@ export function formatDynamicAPIAccesses( ...@@ -448,6 +531,18 @@ export function formatDynamicAPIAccesses(
}) })
} }
function assertPostpone() {
if (!hasPostpone) {
throw new Error(
`Invariant: React.unstable_postpone is not defined. This suggests the wrong version of React was loaded. This is a bug in Next.js`
)
}
}
/**
* This is a bit of a hack to allow us to abort a render using a Postpone instance instead of an Error which changes React's
* abort semantics slightly.
*/
export function createRenderInBrowserAbortSignal(): AbortSignal { export function createRenderInBrowserAbortSignal(): AbortSignal {
const controller = new AbortController() const controller = new AbortController()
controller.abort(new BailoutToCSRError('Render in Browser')) controller.abort(new BailoutToCSRError('Render in Browser'))
...@@ -505,6 +600,7 @@ export function createHangingInputAbortSignal( ...@@ -505,6 +600,7 @@ export function createHangingInputAbortSignal(
return controller.signal return controller.signal
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
...@@ -559,6 +655,17 @@ export function useDynamicRouteParams(expression: string) { ...@@ -559,6 +655,17 @@ export function useDynamicRouteParams(expression: string) {
throw new InvariantError( throw new InvariantError(
`\`${expression}\` was called from a Server Component. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.` `\`${expression}\` was called from a Server Component. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`
) )
case 'prerender-ppr': {
const fallbackParams = workUnitStore.fallbackRouteParams
if (fallbackParams && fallbackParams.size > 0) {
return postponeWithTracking(
workStore.route,
expression,
workUnitStore.dynamicTracking
)
}
break
}
case 'validation-client': { case 'validation-client': {
// Don't check fallbackRouteParams here. We handle params that weren't // Don't check fallbackRouteParams here. We handle params that weren't
// provided in the samples using a proxy that throws when accessed. // provided in the samples using a proxy that throws when accessed.
...@@ -614,7 +721,8 @@ export function useDynamicSearchParams(expression: string) { ...@@ -614,7 +721,8 @@ export function useDynamicSearchParams(expression: string) {
) )
break break
} }
case 'prerender-legacy': { case 'prerender-legacy':
case 'prerender-ppr': {
if (workStore.forceStatic) { if (workStore.forceStatic) {
return return
} }
......
...@@ -293,6 +293,7 @@ export async function decryptActionBoundArgs( ...@@ -293,6 +293,7 @@ export async function decryptActionBoundArgs(
break break
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
......
...@@ -62,6 +62,7 @@ export { createMetadataComponents } from '../../lib/metadata/metadata' ...@@ -62,6 +62,7 @@ export { createMetadataComponents } from '../../lib/metadata/metadata'
export { RootLayoutBoundary } from '../../lib/framework/boundary-components' export { RootLayoutBoundary } from '../../lib/framework/boundary-components'
export { preloadStyle, preloadFont, preconnect } from './rsc/preloads' export { preloadStyle, preloadFont, preconnect } from './rsc/preloads'
export { Postpone } from './rsc/postpone'
export { taintObjectReference } from './rsc/taint' export { taintObjectReference } from './rsc/taint'
export { export {
collectSegmentData, collectSegmentData,
......
...@@ -24,6 +24,7 @@ function getValidationBoundaryTracking(): ValidationBoundaryTracking | null { ...@@ -24,6 +24,7 @@ function getValidationBoundaryTracking(): ValidationBoundaryTracking | null {
return store.boundaryState return store.boundaryState
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-runtime': case 'prerender-runtime':
case 'request': case 'request':
......
...@@ -32,6 +32,7 @@ export function instrumentParamsForClientValidation<TPArams extends Params>( ...@@ -32,6 +32,7 @@ export function instrumentParamsForClientValidation<TPArams extends Params>(
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-client': case 'prerender-client':
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender': case 'prerender':
case 'cache': case 'cache':
case 'request': case 'request':
...@@ -71,6 +72,7 @@ export function expectCompleteParamsInClientValidation( ...@@ -71,6 +72,7 @@ export function expectCompleteParamsInClientValidation(
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-client': case 'prerender-client':
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender': case 'prerender':
case 'cache': case 'cache':
case 'request': case 'request':
...@@ -107,6 +109,7 @@ export function instrumentSearchParamsForClientValidation( ...@@ -107,6 +109,7 @@ export function instrumentSearchParamsForClientValidation(
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-client': case 'prerender-client':
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender': case 'prerender':
case 'cache': case 'cache':
case 'request': case 'request':
......
...@@ -42,6 +42,7 @@ function getExpectedSampleTracking(): InstantValidationSampleTracking { ...@@ -42,6 +42,7 @@ function getExpectedSampleTracking(): InstantValidationSampleTracking {
case 'private-cache': case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender-client': case 'prerender-client':
case 'prerender': case 'prerender':
case 'prerender-runtime': case 'prerender-runtime':
......
/*
Files in the rsc directory are meant to be packaged as part of the RSC graph using next-app-loader.
*/
// When postpone is available in canary React we can switch to importing it directly
export { Postpone } from '../dynamic-rendering'
...@@ -149,6 +149,11 @@ export interface RenderOptsPartial { ...@@ -149,6 +149,11 @@ export interface RenderOptsPartial {
isPrefetch?: boolean isPrefetch?: boolean
htmlLimitedBots: string | undefined htmlLimitedBots: string | undefined
experimental: { experimental: {
/**
* When true, it indicates that the current page supports partial
* prerendering.
*/
isRoutePPREnabled?: boolean
expireTime: number | undefined expireTime: number | undefined
staleTimes: ExperimentalConfig['staleTimes'] | undefined staleTimes: ExperimentalConfig['staleTimes'] | undefined
clientTraceMetadata: string[] | undefined clientTraceMetadata: string[] | undefined
......
...@@ -135,6 +135,7 @@ export function getFlightStream<T>( ...@@ -135,6 +135,7 @@ export function getFlightStream<T>(
return responseOnNextTick return responseOnNextTick
case 'prerender': case 'prerender':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
......
...@@ -134,7 +134,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -134,7 +134,7 @@ export async function walkTreeWithFlightRouterState({
if ( if (
isInsideSharedLayout && isInsideSharedLayout &&
!cacheComponents && !experimental.isRoutePPREnabled &&
// If PPR is disabled, and this is a request for the route tree, then we // If PPR is disabled, and this is a request for the route tree, then we
// never render any components. Only send the router state. // never render any components. Only send the router state.
(parsedRequestHeaders.isRouteTreePrefetchRequest || (parsedRequestHeaders.isRouteTreePrefetchRequest ||
......
...@@ -11,7 +11,10 @@ import type { OpaqueFallbackRouteParams } from '../request/fallback-params' ...@@ -11,7 +11,10 @@ import type { OpaqueFallbackRouteParams } from '../request/fallback-params'
// Share the instance module in the next-shared layer // Share the instance module in the next-shared layer
import { workUnitAsyncStorageInstance } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' } import { workUnitAsyncStorageInstance } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' }
import type { ServerComponentsHmrCache } from '../response-cache' import type { ServerComponentsHmrCache } from '../response-cache'
import type { ResumeDataCache } from '../resume-data-cache/resume-data-cache' import type {
PrerenderResumeDataCache,
ResumeDataCache,
} from '../resume-data-cache/resume-data-cache'
import type { Params } from '../request/params' import type { Params } from '../request/params'
import type { ImplicitTags } from '../lib/implicit-tags' import type { ImplicitTags } from '../lib/implicit-tags'
import type { WorkStore } from './work-async-storage.external' import type { WorkStore } from './work-async-storage.external'
...@@ -280,6 +283,25 @@ interface StaticPrerenderStoreCommon { ...@@ -280,6 +283,25 @@ interface StaticPrerenderStoreCommon {
readonly fallbackRouteParams: OpaqueFallbackRouteParams | null readonly fallbackRouteParams: OpaqueFallbackRouteParams | null
} }
export interface PrerenderStorePPR
extends CommonWorkUnitStore,
RevalidateStore {
readonly type: 'prerender-ppr'
readonly rootParams: Params
readonly dynamicTracking: null | DynamicTrackingState
/**
* The set of unknown route parameters. Accessing these will be tracked as
* a dynamic access.
*/
readonly fallbackRouteParams: OpaqueFallbackRouteParams | null
/**
* The resume data cache for this prerender. Always mutable in PPR mode.
*/
resumeDataCache: PrerenderResumeDataCache
}
export interface PrerenderStoreLegacy export interface PrerenderStoreLegacy
extends CommonWorkUnitStore, extends CommonWorkUnitStore,
RevalidateStore { RevalidateStore {
...@@ -287,7 +309,10 @@ export interface PrerenderStoreLegacy ...@@ -287,7 +309,10 @@ export interface PrerenderStoreLegacy
readonly rootParams: Params readonly rootParams: Params
} }
export type PrerenderStore = PrerenderStoreLegacy | PrerenderStoreModern export type PrerenderStore =
| PrerenderStoreLegacy
| PrerenderStorePPR
| PrerenderStoreModern
// /** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */ // /** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */
export type StaticPrerenderStore = Exclude< export type StaticPrerenderStore = Exclude<
...@@ -423,6 +448,7 @@ export function getResumeDataCache( ...@@ -423,6 +448,7 @@ export function getResumeDataCache(
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-ppr':
return workUnitStore.resumeDataCache return workUnitStore.resumeDataCache
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -449,6 +475,7 @@ export function getHmrRefreshHash( ...@@ -449,6 +475,7 @@ export function getHmrRefreshHash(
return workUnitStore.cookies.get(NEXT_HMR_REFRESH_HASH_COOKIE)?.value return workUnitStore.cookies.get(NEXT_HMR_REFRESH_HASH_COOKIE)?.value
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'unstable-cache': case 'unstable-cache':
case 'generate-static-params': case 'generate-static-params':
...@@ -472,6 +499,7 @@ export function isHmrRefresh(workUnitStore: WorkUnitStore): boolean { ...@@ -472,6 +499,7 @@ export function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'unstable-cache': case 'unstable-cache':
case 'generate-static-params': case 'generate-static-params':
...@@ -497,6 +525,7 @@ export function getServerComponentsHmrCache( ...@@ -497,6 +525,7 @@ export function getServerComponentsHmrCache(
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'unstable-cache': case 'unstable-cache':
case 'generate-static-params': case 'generate-static-params':
...@@ -527,6 +556,7 @@ export function getDraftModeProviderForCacheScope( ...@@ -527,6 +556,7 @@ export function getDraftModeProviderForCacheScope(
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'generate-static-params': case 'generate-static-params':
break break
...@@ -548,6 +578,7 @@ export function getStagedRenderingController( ...@@ -548,6 +578,7 @@ export function getStagedRenderingController(
return workUnitStore.stagedRendering ?? null return workUnitStore.stagedRendering ?? null
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -575,6 +606,7 @@ export function getCacheSignal( ...@@ -575,6 +606,7 @@ export function getCacheSignal(
} }
// fallthrough // fallthrough
} }
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -595,6 +627,7 @@ export function getVaryParamsAccumulator( ...@@ -595,6 +627,7 @@ export function getVaryParamsAccumulator(
case 'request': { case 'request': {
return workUnitStore.varyParamsAccumulator ?? null return workUnitStore.varyParamsAccumulator ?? null
} }
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
......
...@@ -34,7 +34,7 @@ export type WorkStoreContext = { ...@@ -34,7 +34,7 @@ export type WorkStoreContext = {
pendingWaitUntil?: Promise<any> pendingWaitUntil?: Promise<any>
experimental: Pick< experimental: Pick<
RenderOpts['experimental'], RenderOpts['experimental'],
'authInterrupts' | 'useCacheTimeout' 'isRoutePPREnabled' | 'authInterrupts' | 'useCacheTimeout'
> >
/** /**
......
...@@ -134,6 +134,7 @@ import { toRoute } from './lib/to-route' ...@@ -134,6 +134,7 @@ import { toRoute } from './lib/to-route'
import type { DeepReadonly } from '../shared/lib/deep-readonly' import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { isNodeNextRequest, isNodeNextResponse } from './base-http/helpers' import { isNodeNextRequest, isNodeNextResponse } from './base-http/helpers'
import { patchSetHeaderWithCookieSupport } from './lib/patch-set-header' import { patchSetHeaderWithCookieSupport } from './lib/patch-set-header'
import { checkIsAppPPREnabled } from './lib/experimental/ppr'
import { import {
getBuiltinRequestContext, getBuiltinRequestContext,
type WaitUntil, type WaitUntil,
...@@ -431,7 +432,7 @@ export default abstract class Server< ...@@ -431,7 +432,7 @@ export default abstract class Server<
readonly data: NextDataPathnameNormalizer | undefined readonly data: NextDataPathnameNormalizer | undefined
} }
private readonly isAppCacheComponentsEnabled: boolean private readonly isAppPPREnabled: boolean
/** /**
* This is used to persist cache scopes across * This is used to persist cache scopes across
...@@ -517,8 +518,9 @@ export default abstract class Server< ...@@ -517,8 +518,9 @@ export default abstract class Server<
this.enabledDirectories = this.getEnabledDirectories(dev) this.enabledDirectories = this.getEnabledDirectories(dev)
this.isAppCacheComponentsEnabled = this.isAppPPREnabled =
this.enabledDirectories.app && Boolean(this.nextConfig.cacheComponents) this.enabledDirectories.app &&
checkIsAppPPREnabled(this.nextConfig.experimental.ppr)
this.normalizers = { this.normalizers = {
// We should normalize the pathname from the RSC prefix only in minimal // We should normalize the pathname from the RSC prefix only in minimal
...@@ -1095,7 +1097,7 @@ export default abstract class Server< ...@@ -1095,7 +1097,7 @@ export default abstract class Server<
// It's important to execute the following block even it the request // It's important to execute the following block even it the request
// matches a pages data route from above. // matches a pages data route from above.
if ( if (
this.isAppCacheComponentsEnabled && this.isAppPPREnabled &&
this.minimalMode && this.minimalMode &&
req.headers[NEXT_RESUME_HEADER] === '1' && req.headers[NEXT_RESUME_HEADER] === '1' &&
req.method === 'POST' req.method === 'POST'
...@@ -2217,7 +2219,7 @@ export default abstract class Server< ...@@ -2217,7 +2219,7 @@ export default abstract class Server<
* enabled, then the given route _could_ support PPR. * enabled, then the given route _could_ support PPR.
*/ */
const couldSupportPPR: boolean = const couldSupportPPR: boolean =
this.isAppCacheComponentsEnabled && this.isAppPPREnabled &&
typeof routeModule !== 'undefined' && typeof routeModule !== 'undefined' &&
isAppPageRouteModule(routeModule) isAppPageRouteModule(routeModule)
......
...@@ -41,6 +41,7 @@ const zExportMap: zod.ZodType<ExportPathMap> = z.record( ...@@ -41,6 +41,7 @@ const zExportMap: zod.ZodType<ExportPathMap> = z.record(
_fallbackRouteParams: z.array(z.any()).optional(), _fallbackRouteParams: z.array(z.any()).optional(),
_isAppDir: z.boolean().optional(), _isAppDir: z.boolean().optional(),
_isDynamicError: z.boolean().optional(), _isDynamicError: z.boolean().optional(),
_isRoutePPREnabled: z.boolean().optional(),
_allowEmptyStaticShell: z.boolean().optional(), _allowEmptyStaticShell: z.boolean().optional(),
_isFallbackUpgradeable: z.boolean().optional(), _isFallbackUpgradeable: z.boolean().optional(),
}) })
......
...@@ -11,6 +11,7 @@ import type { WEB_VITALS } from '../shared/lib/utils' ...@@ -11,6 +11,7 @@ import type { WEB_VITALS } from '../shared/lib/utils'
import type { NextParsedUrlQuery } from './request-meta' import type { NextParsedUrlQuery } from './request-meta'
import type { SizeLimit } from '../types' import type { SizeLimit } from '../types'
import type { SupportedTestRunners } from '../cli/next-test' import type { SupportedTestRunners } from '../cli/next-test'
import type { ExperimentalPPRConfig } from './lib/experimental/ppr'
import { INFINITE_CACHE } from '../lib/constants' import { INFINITE_CACHE } from '../lib/constants'
import type { FallbackRouteParam } from '../build/static-paths/types' import type { FallbackRouteParam } from '../build/static-paths/types'
import type { MemoryEvictionMode } from '../build/swc/types' import type { MemoryEvictionMode } from '../build/swc/types'
...@@ -972,6 +973,12 @@ export interface ExperimentalConfig { ...@@ -972,6 +973,12 @@ export interface ExperimentalConfig {
*/ */
clientTraceMetadata?: string[] clientTraceMetadata?: string[]
/**
* @deprecated This configuration option has been merged into `cacheComponents`.
* The Partial Prerendering feature is still available via `cacheComponents`.
*/
ppr?: ExperimentalPPRConfig
/** /**
* Enables experimental taint APIs in React. * Enables experimental taint APIs in React.
* Using this feature will enable the `react@experimental` for the `app` directory. * Using this feature will enable the `react@experimental` for the `app` directory.
...@@ -1356,6 +1363,11 @@ export type ExportPathMap = { ...@@ -1356,6 +1363,11 @@ export type ExportPathMap = {
*/ */
_isDynamicError?: boolean _isDynamicError?: boolean
/**
* @internal
*/
_isRoutePPREnabled?: boolean
/** /**
* When true, the page is prerendered as a fallback shell, while allowing * When true, the page is prerendered as a fallback shell, while allowing
* any dynamic accesses to result in an empty shell. This is the case when * any dynamic accesses to result in an empty shell. This is the case when
...@@ -2076,6 +2088,7 @@ export const defaultConfig = Object.freeze({ ...@@ -2076,6 +2088,7 @@ export const defaultConfig = Object.freeze({
clientTraceMetadata: undefined, clientTraceMetadata: undefined,
parallelServerCompiles: false, parallelServerCompiles: false,
parallelServerBuildTraces: false, parallelServerBuildTraces: false,
ppr: false,
authInterrupts: false, authInterrupts: false,
webpackBuildWorker: undefined, webpackBuildWorker: undefined,
webpackMemoryOptimizations: false, webpackMemoryOptimizations: false,
...@@ -2140,6 +2153,7 @@ export async function normalizeConfig(phase: string, config: any) { ...@@ -2140,6 +2153,7 @@ export async function normalizeConfig(phase: string, config: any) {
// cacheComponents?: boolean; // cacheComponents?: boolean;
// clientParamParsingOrigins?: string[]; // clientParamParsingOrigins?: string[];
// clientSegmentCache?: boolean; // clientSegmentCache?: boolean;
// ppr?: boolean | 'incremental';
// serverActions?: Record<string, never>; // serverActions?: Record<string, never>;
// }; // };
// }; // };
...@@ -2182,6 +2196,7 @@ export interface NextConfigRuntime { ...@@ -2182,6 +2196,7 @@ export interface NextConfigRuntime {
experimental: Pick< experimental: Pick<
NextConfigComplete['experimental'], NextConfigComplete['experimental'],
| 'ppr'
| 'taint' | 'taint'
| 'serverActions' | 'serverActions'
| 'staleTimes' | 'staleTimes'
...@@ -2249,6 +2264,7 @@ export function getNextConfigRuntime( ...@@ -2249,6 +2264,7 @@ export function getNextConfigRuntime(
} }
const experimental = { const experimental = {
ppr: ex.ppr,
taint: ex.taint, taint: ex.taint,
serverActions: ex.serverActions, serverActions: ex.serverActions,
staleTimes: ex.staleTimes, staleTimes: ex.staleTimes,
......
...@@ -575,7 +575,7 @@ function assignDefaultsAndValidate( ...@@ -575,7 +575,7 @@ function assignDefaultsAndValidate(
} }
} }
if ((result.experimental as any).ppr) { if (result.experimental.ppr) {
throw new HardDeprecatedConfigError( throw new HardDeprecatedConfigError(
`\`experimental.ppr\` has been merged into \`cacheComponents\`. The Partial Prerendering feature is still available, but is now enabled via \`cacheComponents\`. Please update your ${configFileName} accordingly.` `\`experimental.ppr\` has been merged into \`cacheComponents\`. The Partial Prerendering feature is still available, but is now enabled via \`cacheComponents\`. Please update your ${configFileName} accordingly.`
) )
...@@ -1570,6 +1570,11 @@ function assignDefaultsAndValidate( ...@@ -1570,6 +1570,11 @@ function assignDefaultsAndValidate(
result.experimental.mcpServer = true result.experimental.mcpServer = true
} }
if (result.cacheComponents) {
// TODO: remove once we've finished migrating internally to cacheComponents.
result.experimental.ppr = true
}
// "use cache" was originally implicitly enabled with the cacheComponents flag, so // "use cache" was originally implicitly enabled with the cacheComponents flag, so
// we transfer the value for cacheComponents to the explicit useCache flag to ensure // we transfer the value for cacheComponents to the explicit useCache flag to ensure
// backwards compatibility. // backwards compatibility.
......
...@@ -72,6 +72,7 @@ import { DefaultFileReader } from '../route-matcher-providers/dev/helpers/file-r ...@@ -72,6 +72,7 @@ import { DefaultFileReader } from '../route-matcher-providers/dev/helpers/file-r
import { LRUCache } from '../lib/lru-cache' import { LRUCache } from '../lib/lru-cache'
import { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher' import { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'
import { DetachedPromise } from '../../lib/detached-promise' import { DetachedPromise } from '../../lib/detached-promise'
import { isPostpone } from '../lib/router-utils/is-postpone'
import { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites' import { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites'
import { buildCustomRoute } from '../../lib/build-custom-route' import { buildCustomRoute } from '../../lib/build-custom-route'
import { decorateServerError } from '../../shared/lib/error-source' import { decorateServerError } from '../../shared/lib/error-source'
...@@ -344,6 +345,11 @@ export default class DevServer extends Server { ...@@ -344,6 +345,11 @@ export default class DevServer extends Server {
} }
process.on('unhandledRejection', (reason) => { process.on('unhandledRejection', (reason) => {
if (isPostpone(reason)) {
// React postpones that are unhandled might end up logged here but they're
// not really errors. They're just part of rendering.
return
}
this.logErrorWithOriginalStack(reason, 'unhandledRejection') this.logErrorWithOriginalStack(reason, 'unhandledRejection')
}) })
process.on('uncaughtException', (err) => { process.on('uncaughtException', (err) => {
...@@ -800,6 +806,7 @@ export default class DevServer extends Server { ...@@ -800,6 +806,7 @@ export default class DevServer extends Server {
distDir: this.distDir, distDir: this.distDir,
pathname, pathname,
config: { config: {
pprConfig: this.nextConfig.experimental.ppr,
configFileName, configFileName,
cacheComponents: Boolean(this.nextConfig.cacheComponents), cacheComponents: Boolean(this.nextConfig.cacheComponents),
}, },
......
...@@ -17,6 +17,10 @@ import { loadComponents } from '../load-components' ...@@ -17,6 +17,10 @@ import { loadComponents } from '../load-components'
import { setHttpClientAndAgentOptions } from '../setup-http-agent-env' import { setHttpClientAndAgentOptions } from '../setup-http-agent-env'
import type { IncrementalCache } from '../lib/incremental-cache' import type { IncrementalCache } from '../lib/incremental-cache'
import { isAppPageRouteModule } from '../route-modules/checks' import { isAppPageRouteModule } from '../route-modules/checks'
import {
checkIsRoutePPREnabled,
type ExperimentalPPRConfig,
} from '../lib/experimental/ppr'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { collectRootParamKeys } from '../../build/segment-config/app/collect-root-param-keys' import { collectRootParamKeys } from '../../build/segment-config/app/collect-root-param-keys'
import { buildAppStaticPaths } from '../../build/static-paths/app' import { buildAppStaticPaths } from '../../build/static-paths/app'
...@@ -25,6 +29,7 @@ import { createIncrementalCache } from '../../export/helpers/create-incremental- ...@@ -25,6 +29,7 @@ import { createIncrementalCache } from '../../export/helpers/create-incremental-
import { parseNormalizedAppRoute } from '../../shared/lib/router/routes/app' import { parseNormalizedAppRoute } from '../../shared/lib/router/routes/app'
type RuntimeConfig = { type RuntimeConfig = {
pprConfig: ExperimentalPPRConfig | undefined
configFileName: string configFileName: string
cacheComponents: boolean cacheComponents: boolean
} }
...@@ -127,7 +132,8 @@ export async function loadStaticPaths({ ...@@ -127,7 +132,8 @@ export async function loadStaticPaths({
} }
const isRoutePPREnabled = const isRoutePPREnabled =
isAppPageRouteModule(routeModule) && Boolean(config.cacheComponents) isAppPageRouteModule(routeModule) &&
checkIsRoutePPREnabled(config.pprConfig)
const rootParamKeys = collectRootParamKeys(routeModule) const rootParamKeys = collectRootParamKeys(routeModule)
......
...@@ -251,6 +251,7 @@ export function applyOwnerStack(error: Error): Error { ...@@ -251,6 +251,7 @@ export function applyOwnerStack(error: Error): Error {
case 'unstable-cache': case 'unstable-cache':
case 'request': case 'request':
case 'prerender': case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-client': case 'prerender-client':
......
/**
* If set to `incremental`, only those leaf pages that export
* `experimental_ppr = true` will have partial prerendering enabled. If any
* page exports this value as `false` or does not export it at all will not
* have partial prerendering enabled. If set to a boolean, the options for
* `experimental_ppr` will be ignored.
*/
export type ExperimentalPPRConfig = boolean | 'incremental'
/**
* Returns true if partial prerendering is enabled for the application. It does
* not tell you if a given route has PPR enabled, as that requires analysis of
* the route's configuration.
*
* @see {@link checkIsRoutePPREnabled} - for checking if a specific route has PPR enabled.
*/
export function checkIsAppPPREnabled(
config: ExperimentalPPRConfig | undefined
): boolean {
// If the config is undefined, partial prerendering is disabled.
if (typeof config === 'undefined') return false
// If the config is a boolean, use it directly.
if (typeof config === 'boolean') return config
// If the config is a string, it must be 'incremental' to enable partial
// prerendering.
if (config === 'incremental') return true
return false
}
/**
* Returns true if partial prerendering is supported for the current page with
* the provided app configuration. If the application doesn't have partial
* prerendering enabled, this function will always return false. If you want to
* check if the application has partial prerendering enabled
*
* @see {@link checkIsAppPPREnabled} for checking if the application has PPR enabled.
*/
export function checkIsRoutePPREnabled(
config: ExperimentalPPRConfig | undefined
): boolean {
// If the config is undefined, partial prerendering is disabled.
if (typeof config === 'undefined') return false
// If the config is a boolean, use it directly.
if (typeof config === 'boolean') return config
return false
}
...@@ -369,6 +369,7 @@ export function createPatchedFetcher( ...@@ -369,6 +369,7 @@ export function createPatchedFetcher(
// TODO: Stop accumulating tags in client prerender. (fallthrough) // TODO: Stop accumulating tags in client prerender. (fallthrough)
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -411,6 +412,7 @@ export function createPatchedFetcher( ...@@ -411,6 +412,7 @@ export function createPatchedFetcher(
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
...@@ -582,6 +584,7 @@ export function createPatchedFetcher( ...@@ -582,6 +584,7 @@ export function createPatchedFetcher(
) )
} }
break break
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -714,6 +717,7 @@ export function createPatchedFetcher( ...@@ -714,6 +717,7 @@ export function createPatchedFetcher(
) )
} }
break break
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -760,6 +764,7 @@ export function createPatchedFetcher( ...@@ -760,6 +764,7 @@ export function createPatchedFetcher(
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'unstable-cache': case 'unstable-cache':
case 'generate-static-params': case 'generate-static-params':
...@@ -912,6 +917,7 @@ export function createPatchedFetcher( ...@@ -912,6 +917,7 @@ export function createPatchedFetcher(
) )
} }
// fallthrough // fallthrough
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -995,6 +1001,7 @@ export function createPatchedFetcher( ...@@ -995,6 +1001,7 @@ export function createPatchedFetcher(
) )
} }
break break
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -1124,6 +1131,7 @@ export function createPatchedFetcher( ...@@ -1124,6 +1131,7 @@ export function createPatchedFetcher(
) )
} }
break break
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -1175,6 +1183,7 @@ export function createPatchedFetcher( ...@@ -1175,6 +1183,7 @@ export function createPatchedFetcher(
case 'private-cache': case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-ppr':
case 'generate-static-params': case 'generate-static-params':
break break
default: default:
......
...@@ -24,6 +24,7 @@ import { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix' ...@@ -24,6 +24,7 @@ import { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'
import { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix' import { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'
import setupCompression from 'next/dist/compiled/compression' import setupCompression from 'next/dist/compiled/compression'
import { signalFromNodeResponse } from '../web/spec-extension/adapters/next-request' import { signalFromNodeResponse } from '../web/spec-extension/adapters/next-request'
import { isPostpone } from './router-utils/is-postpone'
import { parseUrl as parseUrlUtil } from '../../shared/lib/router/utils/parse-url' import { parseUrl as parseUrlUtil } from '../../shared/lib/router/utils/parse-url'
import { import {
...@@ -794,6 +795,11 @@ export async function initialize(opts: { ...@@ -794,6 +795,11 @@ export async function initialize(opts: {
type: 'uncaughtException' | 'unhandledRejection', type: 'uncaughtException' | 'unhandledRejection',
err: Error | undefined err: Error | undefined
) => { ) => {
if (isPostpone(err)) {
// React postpones that are unhandled might end up logged here but they're
// not really errors. They're just part of rendering.
return
}
if (type === 'unhandledRejection') { if (type === 'unhandledRejection') {
Log.error('unhandledRejection: ', err) Log.error('unhandledRejection: ', err)
} else if (type === 'uncaughtException') { } else if (type === 'uncaughtException') {
......
const REACT_POSTPONE_TYPE: symbol = Symbol.for('react.postpone')
export function isPostpone(error: any): boolean {
return (
typeof error === 'object' &&
error !== null &&
error.$$typeof === REACT_POSTPONE_TYPE
)
}
...@@ -257,6 +257,7 @@ function patchConsoleMethod(methodName: InterceptableConsoleMethod): void { ...@@ -257,6 +257,7 @@ function patchConsoleMethod(methodName: InterceptableConsoleMethod): void {
} }
// intentional fallthrough // intentional fallthrough
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-ppr':
case 'cache': case 'cache':
case 'unstable-cache': case 'unstable-cache':
case 'private-cache': case 'private-cache':
......
...@@ -90,6 +90,7 @@ export function io(expression: string, type: SyncIOApiType) { ...@@ -90,6 +90,7 @@ export function io(expression: string, type: SyncIOApiType) {
break break
} }
case 'validation-client': case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
......
import { isPostpone } from '../lib/router-utils/is-postpone'
let _global = globalThis as typeof globalThis & { let _global = globalThis as typeof globalThis & {
nextInitializedProcessErrorHandlers?: boolean nextInitializedProcessErrorHandlers?: boolean
} }
...@@ -54,6 +56,11 @@ export function installProcessErrorHandlers( ...@@ -54,6 +56,11 @@ export function installProcessErrorHandlers(
// Install a new handler to prevent the process from crashing. // Install a new handler to prevent the process from crashing.
process.on('unhandledRejection', (reason: unknown) => { process.on('unhandledRejection', (reason: unknown) => {
if (isPostpone(reason)) {
// React postpones that are unhandled might end up logged here but they're
// not really errors. They're just part of rendering.
return
}
// Immediately log the error. // Immediately log the error.
// TODO: Ideally, if we knew that this error was triggered by application // TODO: Ideally, if we knew that this error was triggered by application
// code, we would suppress it entirely without logging. We can't reliably // code, we would suppress it entirely without logging. We can't reliably
...@@ -74,6 +81,9 @@ export function installProcessErrorHandlers( ...@@ -74,6 +81,9 @@ export function installProcessErrorHandlers(
// is unrelated to the late-awaiting pattern. However, for similar reasons, // is unrelated to the late-awaiting pattern. However, for similar reasons,
// we still shouldn't crash the process. Just log it. // we still shouldn't crash the process. Just log it.
process.on('uncaughtException', (reason: unknown) => { process.on('uncaughtException', (reason: unknown) => {
if (isPostpone(reason)) {
return
}
console.error(reason) console.error(reason)
}) })
} }
...@@ -615,6 +615,7 @@ function filteringUnhandledRejectionHandler( ...@@ -615,6 +615,7 @@ function filteringUnhandledRejectionHandler(
} }
break break
} }
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
......
...@@ -76,6 +76,7 @@ async function getCachedImageResponseArrayBuffer( ...@@ -76,6 +76,7 @@ async function getCachedImageResponseArrayBuffer(
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'generate-static-params': case 'generate-static-params':
return renderImageResponseArrayBuffer(args) return renderImageResponseArrayBuffer(args)
......
...@@ -4,6 +4,7 @@ import { ...@@ -4,6 +4,7 @@ import {
workUnitAsyncStorage, workUnitAsyncStorage,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { import {
postponeWithTracking,
throwToInterruptStaticGeneration, throwToInterruptStaticGeneration,
trackDynamicDataInDynamicRender, trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
...@@ -95,6 +96,14 @@ export function connection(): Promise<void> { ...@@ -95,6 +96,14 @@ export function connection(): Promise<void> {
`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.` `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`
) )
} }
case 'prerender-ppr':
// We use React's postpone API to interrupt rendering here to create a
// dynamic hole
return postponeWithTracking(
workStore.route,
'connection',
workUnitStore.dynamicTracking
)
case 'prerender-legacy': case 'prerender-legacy':
// We throw an error here to interrupt prerendering to mark the route // We throw an error here to interrupt prerendering to mark the route
// as dynamic // as dynamic
......
...@@ -16,6 +16,7 @@ import { ...@@ -16,6 +16,7 @@ import {
isInEarlyRenderStage, isInEarlyRenderStage,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { import {
postponeWithTracking,
throwToInterruptStaticGeneration, throwToInterruptStaticGeneration,
trackDynamicDataInDynamicRender, trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
...@@ -82,6 +83,14 @@ export function cookies(): Promise<ReadonlyRequestCookies> { ...@@ -82,6 +83,14 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
throw new InvariantError( throw new InvariantError(
`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.` `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`
) )
case 'prerender-ppr':
// We need track dynamic access here eagerly to keep continuity with
// how cookies has worked in PPR without cacheComponents.
return postponeWithTracking(
workStore.route,
callingExpression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy': case 'prerender-legacy':
// We track dynamic access here so we don't need to wrap the cookies // We track dynamic access here so we don't need to wrap the cookies
// in individual property access tracking. // in individual property access tracking.
......
...@@ -12,6 +12,7 @@ import { ...@@ -12,6 +12,7 @@ import {
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external' import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import { import {
abortAndThrowOnSynchronousRequestDataAccess, abortAndThrowOnSynchronousRequestDataAccess,
postponeWithTracking,
trackDynamicDataInDynamicRender, trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger' import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
...@@ -68,6 +69,7 @@ export function draftMode(): Promise<DraftMode> { ...@@ -68,6 +69,7 @@ export function draftMode(): Promise<DraftMode> {
// Otherwise, we fall through to providing an empty draft mode. // Otherwise, we fall through to providing an empty draft mode.
// eslint-disable-next-line no-fallthrough // eslint-disable-next-line no-fallthrough
case 'prerender': case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
// Return empty draft mode // Return empty draft mode
return createOrGetCachedDraftMode(null, workStore) return createOrGetCachedDraftMode(null, workStore)
...@@ -241,6 +243,12 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) { ...@@ -241,6 +243,12 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) {
throw new InvariantError( throw new InvariantError(
`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.` `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`
) )
case 'prerender-ppr':
return postponeWithTracking(
workStore.route,
expression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy': case 'prerender-legacy':
workUnitStore.revalidate = 0 workUnitStore.revalidate = 0
......
...@@ -14,6 +14,7 @@ import { ...@@ -14,6 +14,7 @@ import {
isInEarlyRenderStage, isInEarlyRenderStage,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { import {
postponeWithTracking,
throwToInterruptStaticGeneration, throwToInterruptStaticGeneration,
trackDynamicDataInDynamicRender, trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
...@@ -81,6 +82,7 @@ export function headers(): Promise<ReadonlyHeaders> { ...@@ -81,6 +82,7 @@ export function headers(): Promise<ReadonlyHeaders> {
case 'validation-client': case 'validation-client':
case 'private-cache': case 'private-cache':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
break break
...@@ -105,6 +107,16 @@ export function headers(): Promise<ReadonlyHeaders> { ...@@ -105,6 +107,16 @@ export function headers(): Promise<ReadonlyHeaders> {
throw new InvariantError( throw new InvariantError(
`${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.` `${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`
) )
case 'prerender-ppr':
// PPR Prerender (no cacheComponents)
// We are prerendering with PPR. We need track dynamic access here eagerly
// to keep continuity with how headers has worked in PPR without cacheComponents.
// TODO consider switching the semantic to throw on property access instead
return postponeWithTracking(
workStore.route,
callingExpression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy': case 'prerender-legacy':
// Legacy Prerender // Legacy Prerender
// We are in a legacy static generation mode while prerendering // We are in a legacy static generation mode while prerendering
......
...@@ -5,6 +5,7 @@ import { ...@@ -5,6 +5,7 @@ import {
makeDevtoolsIOAwarePromise, makeDevtoolsIOAwarePromise,
} from '../dynamic-rendering-utils' } from '../dynamic-rendering-utils'
import { RenderStage } from '../app-render/staged-rendering' import { RenderStage } from '../app-render/staged-rendering'
import { throwPrerenderPPRRemovedError } from '../../shared/lib/ppr-removed-error'
import { isRequestApiAllowedInCurrentPhase } from './utils' import { isRequestApiAllowedInCurrentPhase } from './utils'
// A fulfilled thenable that React can unwrap synchronously via `use()` without // A fulfilled thenable that React can unwrap synchronously via `use()` without
...@@ -66,6 +67,10 @@ export function io(): Promise<void> { ...@@ -66,6 +67,10 @@ export function io(): Promise<void> {
workStore.route, workStore.route,
'`io()`' '`io()`'
) )
case 'prerender-ppr':
// Dead code to be removed when we eliminate legacy ppr code
throwPrerenderPPRRemovedError()
break
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
......
...@@ -10,8 +10,15 @@ import { ...@@ -10,8 +10,15 @@ import {
} from '../app-render/vary-params' } from '../app-render/vary-params'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect' import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import {
throwToInterruptStaticGeneration,
postponeWithTracking,
} from '../app-render/dynamic-rendering'
import { import {
workUnitAsyncStorage, workUnitAsyncStorage,
type PrerenderStorePPR,
type PrerenderStoreLegacy,
type StaticPrerenderStoreModern, type StaticPrerenderStoreModern,
type StaticPrerenderStore, type StaticPrerenderStore,
throwInvariantForMissingStore, throwInvariantForMissingStore,
...@@ -49,6 +56,7 @@ export function createParamsFromClient( ...@@ -49,6 +56,7 @@ export function createParamsFromClient(
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
// Client params don't need additional vary tracking because by the // Client params don't need additional vary tracking because by the
// time they reach the client, the access would have already been // time they reach the client, the access would have already been
...@@ -139,6 +147,7 @@ export function createServerParamsForRoute( ...@@ -139,6 +147,7 @@ export function createServerParamsForRoute(
if (workUnitStore) { if (workUnitStore) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'prerender': case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
return createStaticPrerenderParams( return createStaticPrerenderParams(
underlyingParams, underlyingParams,
...@@ -203,6 +212,7 @@ export function createServerParamsForServerSegment( ...@@ -203,6 +212,7 @@ export function createServerParamsForServerSegment(
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
return createStaticPrerenderParams( return createStaticPrerenderParams(
underlyingParams, underlyingParams,
...@@ -298,6 +308,7 @@ export function createPrerenderParamsForClientSegment( ...@@ -298,6 +308,7 @@ export function createPrerenderParamsForClientSegment(
'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.' 'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'
) )
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
break break
...@@ -381,6 +392,22 @@ function createStaticPrerenderParams( ...@@ -381,6 +392,22 @@ function createStaticPrerenderParams(
} }
break break
} }
case 'prerender-ppr': {
const fallbackParams = prerenderStore.fallbackRouteParams
if (fallbackParams) {
for (const key in underlyingParams) {
if (fallbackParams.has(key)) {
return makeErroringParams(
underlyingParams,
fallbackParams,
workStore,
prerenderStore
)
}
}
}
break
}
case 'prerender-legacy': case 'prerender-legacy':
break break
default: default:
...@@ -733,6 +760,65 @@ function makeHangingParams( ...@@ -733,6 +760,65 @@ function makeHangingParams(
return promise return promise
} }
function makeErroringParams(
underlyingParams: Params,
fallbackParams: OpaqueFallbackRouteParams,
workStore: WorkStore,
prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy
): Promise<Params> {
const cachedParams = CachedParams.get(underlyingParams)
if (cachedParams) {
return cachedParams
}
const augmentedUnderlying = { ...underlyingParams }
// We don't use makeResolvedReactPromise here because params
// supports copying with spread and we don't want to unnecessarily
// instrument the promise with spreadable properties of ReactPromise.
const promise = Promise.resolve(augmentedUnderlying)
CachedParams.set(underlyingParams, promise)
Object.keys(underlyingParams).forEach((prop) => {
if (wellKnownProperties.has(prop)) {
// These properties cannot be shadowed because they need to be the
// true underlying value for Promises to work correctly at runtime
} else {
if (fallbackParams.has(prop)) {
Object.defineProperty(augmentedUnderlying, prop, {
get() {
const expression = describeStringPropertyAccess('params', prop)
// In most dynamic APIs we also throw if `dynamic = "error"` however
// for params is only dynamic when we're generating a fallback shell
// and even when `dynamic = "error"` we still support generating dynamic
// fallback shells
// TODO remove this comment when cacheComponents is the default since there
// will be no `dynamic = "error"`
if (prerenderStore.type === 'prerender-ppr') {
// PPR Prerender (no cacheComponents)
postponeWithTracking(
workStore.route,
expression,
prerenderStore.dynamicTracking
)
} else {
// Legacy Prerender
throwToInterruptStaticGeneration(
expression,
workStore,
prerenderStore
)
}
},
enumerable: true,
})
}
}
})
return promise
}
function makeUntrackedParams(underlyingParams: Params): Promise<Params> { function makeUntrackedParams(underlyingParams: Params): Promise<Params> {
const cachedParams = CachedParams.get(underlyingParams) const cachedParams = CachedParams.get(underlyingParams)
if (cachedParams) { if (cachedParams) {
......
...@@ -3,11 +3,17 @@ import { ...@@ -3,11 +3,17 @@ import {
type WorkStore, type WorkStore,
} from '../app-render/work-async-storage.external' } from '../app-render/work-async-storage.external'
import {
postponeWithTracking,
type DynamicTrackingState,
} from '../app-render/dynamic-rendering'
import { import {
throwInvariantForMissingStore, throwInvariantForMissingStore,
workUnitAsyncStorage, workUnitAsyncStorage,
type PrerenderStoreLegacy, type PrerenderStoreLegacy,
type PrerenderStoreModernServer, type PrerenderStoreModernServer,
type PrerenderStorePPR,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { import {
makeHangingPromise, makeHangingPromise,
...@@ -27,6 +33,7 @@ export function createServerPathnameForMetadata( ...@@ -27,6 +33,7 @@ export function createServerPathnameForMetadata(
if (workUnitStore) { if (workUnitStore) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'prerender': case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy': { case 'prerender-legacy': {
return createPrerenderPathname( return createPrerenderPathname(
underlyingPathname, underlyingPathname,
...@@ -84,7 +91,10 @@ export function createServerPathnameForMetadata( ...@@ -84,7 +91,10 @@ export function createServerPathnameForMetadata(
function createPrerenderPathname( function createPrerenderPathname(
underlyingPathname: string, underlyingPathname: string,
workStore: WorkStore, workStore: WorkStore,
prerenderStore: PrerenderStoreLegacy | PrerenderStoreModernServer prerenderStore:
| PrerenderStoreLegacy
| PrerenderStorePPR
| PrerenderStoreModernServer
): Promise<string> { ): Promise<string> {
switch (prerenderStore.type) { switch (prerenderStore.type) {
case 'prerender': { case 'prerender': {
...@@ -98,6 +108,13 @@ function createPrerenderPathname( ...@@ -98,6 +108,13 @@ function createPrerenderPathname(
} }
break break
} }
case 'prerender-ppr': {
const fallbackParams = prerenderStore.fallbackRouteParams
if (fallbackParams && fallbackParams.size > 0) {
return makeErroringPathname(workStore, prerenderStore.dynamicTracking)
}
break
}
case 'prerender-legacy': case 'prerender-legacy':
break break
default: default:
...@@ -108,6 +125,41 @@ function createPrerenderPathname( ...@@ -108,6 +125,41 @@ function createPrerenderPathname(
return Promise.resolve(underlyingPathname) return Promise.resolve(underlyingPathname)
} }
function makeErroringPathname<T>(
workStore: WorkStore,
dynamicTracking: null | DynamicTrackingState
): Promise<T> {
let reject: null | ((reason: unknown) => void) = null
const promise = new Promise<T>((_, re) => {
reject = re
})
const originalThen = promise.then.bind(promise)
// We instrument .then so that we can generate a tracking event only if you actually
// await this promise, not just that it is created.
promise.then = (onfulfilled, onrejected) => {
if (reject) {
try {
postponeWithTracking(
workStore.route,
'metadata relative url resolving',
dynamicTracking
)
} catch (error) {
reject(error)
reject = null
}
}
return originalThen(onfulfilled, onrejected)
}
// We wrap in a noop proxy to trick the runtime into thinking it
// isn't a native promise (it's not really). This is so that awaiting
// the promise will call the `then` property triggering the lazy postpone
return new Proxy(promise, {})
}
function createRenderPathname(underlyingPathname: string): Promise<string> { function createRenderPathname(underlyingPathname: string): Promise<string> {
return Promise.resolve(underlyingPathname) return Promise.resolve(underlyingPathname)
} }
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import {
postponeWithTracking,
throwToInterruptStaticGeneration,
} from '../app-render/dynamic-rendering'
import { import {
workAsyncStorage, workAsyncStorage,
type WorkStore, type WorkStore,
...@@ -7,9 +11,11 @@ import { ...@@ -7,9 +11,11 @@ import {
workUnitAsyncStorage, workUnitAsyncStorage,
type PrerenderStoreLegacy, type PrerenderStoreLegacy,
type PrerenderStoreModernServer, type PrerenderStoreModernServer,
type PrerenderStorePPR,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils' import { makeHangingPromise } from '../dynamic-rendering-utils'
import type { ParamValue } from './params' import type { ParamValue } from './params'
import { describeStringPropertyAccess } from '../../shared/lib/utils/reflect-utils'
import { actionAsyncStorage } from '../app-render/action-async-storage.external' import { actionAsyncStorage } from '../app-render/action-async-storage.external'
import { accumulateRootVaryParam } from '../app-render/vary-params' import { accumulateRootVaryParam } from '../app-render/vary-params'
...@@ -67,6 +73,7 @@ export function getRootParam(paramName: string): Promise<ParamValue> { ...@@ -67,6 +73,7 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
return Promise.resolve(workUnitStore.rootParams[paramName]) return Promise.resolve(workUnitStore.rootParams[paramName])
} }
case 'prerender': case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy': { case 'prerender-legacy': {
return createPrerenderRootParamPromise( return createPrerenderRootParamPromise(
paramName, paramName,
...@@ -132,12 +139,16 @@ export function getRootParam(paramName: string): Promise<ParamValue> { ...@@ -132,12 +139,16 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
function createPrerenderRootParamPromise( function createPrerenderRootParamPromise(
paramName: string, paramName: string,
workStore: WorkStore, workStore: WorkStore,
prerenderStore: PrerenderStoreLegacy | PrerenderStoreModernServer, prerenderStore:
| PrerenderStorePPR
| PrerenderStoreLegacy
| PrerenderStoreModernServer,
apiName: string apiName: string
): Promise<ParamValue> { ): Promise<ParamValue> {
switch (prerenderStore.type) { switch (prerenderStore.type) {
case 'prerender': case 'prerender':
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-ppr':
default: default:
} }
...@@ -159,6 +170,22 @@ function createPrerenderRootParamPromise( ...@@ -159,6 +170,22 @@ function createPrerenderRootParamPromise(
} }
break break
} }
case 'prerender-ppr': {
// We aren't in a cacheComponents prerender, but the param is a fallback,
// so we need to make an erroring params object which will postpone/error if you access it
if (
prerenderStore.fallbackRouteParams &&
prerenderStore.fallbackRouteParams.has(paramName)
) {
return makeErroringRootParamPromise(
paramName,
workStore,
prerenderStore,
apiName
)
}
break
}
case 'prerender-legacy': { case 'prerender-legacy': {
// legacy prerenders can't have fallback params // legacy prerenders can't have fallback params
break break
...@@ -172,3 +199,36 @@ function createPrerenderRootParamPromise( ...@@ -172,3 +199,36 @@ function createPrerenderRootParamPromise(
accumulateRootVaryParam(paramName) accumulateRootVaryParam(paramName)
return Promise.resolve(underlyingParams[paramName]) return Promise.resolve(underlyingParams[paramName])
} }
/** Deliberately async -- we want to create a rejected promise, not error synchronously. */
async function makeErroringRootParamPromise(
paramName: string,
workStore: WorkStore,
prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy,
apiName: string
): Promise<ParamValue> {
const expression = describeStringPropertyAccess(apiName, paramName)
// In most dynamic APIs, we also throw if `dynamic = "error"`.
// However, root params are only dynamic when we're generating a fallback shell,
// and even with `dynamic = "error"` we still support generating dynamic fallback shells.
// TODO: remove this comment when cacheComponents is the default since there will be no `dynamic = "error"`
switch (prerenderStore.type) {
case 'prerender-ppr': {
return postponeWithTracking(
workStore.route,
expression,
prerenderStore.dynamicTracking
)
}
case 'prerender-legacy': {
return throwToInterruptStaticGeneration(
expression,
workStore,
prerenderStore
)
}
default: {
prerenderStore satisfies never
}
}
}
...@@ -11,12 +11,14 @@ import { ...@@ -11,12 +11,14 @@ import {
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect' import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import { import {
throwToInterruptStaticGeneration, throwToInterruptStaticGeneration,
postponeWithTracking,
annotateDynamicAccess, annotateDynamicAccess,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
import { import {
workUnitAsyncStorage, workUnitAsyncStorage,
type PrerenderStoreLegacy, type PrerenderStoreLegacy,
type PrerenderStorePPR,
type PrerenderStoreModern, type PrerenderStoreModern,
type PrerenderStoreModernRuntime, type PrerenderStoreModernRuntime,
type StaticPrerenderStore, type StaticPrerenderStore,
...@@ -57,6 +59,7 @@ export function createSearchParamsFromClient( ...@@ -57,6 +59,7 @@ export function createSearchParamsFromClient(
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
return createStaticPrerenderSearchParams(workStore, workUnitStore) return createStaticPrerenderSearchParams(workStore, workUnitStore)
case 'validation-client': { case 'validation-client': {
...@@ -123,6 +126,7 @@ export function createServerSearchParamsForServerPage( ...@@ -123,6 +126,7 @@ export function createServerSearchParamsForServerPage(
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
return createStaticPrerenderSearchParams(workStore, workUnitStore) return createStaticPrerenderSearchParams(workStore, workUnitStore)
case 'validation-client': case 'validation-client':
...@@ -201,6 +205,7 @@ export function createPrerenderSearchParamsForClientPage(): Promise<SearchParams ...@@ -201,6 +205,7 @@ export function createPrerenderSearchParamsForClientPage(): Promise<SearchParams
throw new InvariantError( throw new InvariantError(
'createPrerenderSearchParamsForClientPage should not be called inside generateStaticParams.' 'createPrerenderSearchParamsForClientPage should not be called inside generateStaticParams.'
) )
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
return Promise.resolve({}) return Promise.resolve({})
...@@ -226,6 +231,7 @@ function createStaticPrerenderSearchParams( ...@@ -226,6 +231,7 @@ function createStaticPrerenderSearchParams(
case 'prerender-client': case 'prerender-client':
// We are in a cacheComponents (PPR or otherwise) prerender // We are in a cacheComponents (PPR or otherwise) prerender
return makeHangingSearchParams(workStore, prerenderStore) return makeHangingSearchParams(workStore, prerenderStore)
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
// We are in a legacy static generation and need to interrupt the // We are in a legacy static generation and need to interrupt the
// prerender when search params are accessed. // prerender when search params are accessed.
...@@ -415,7 +421,7 @@ function makeHangingSearchParams( ...@@ -415,7 +421,7 @@ function makeHangingSearchParams(
function makeErroringSearchParams( function makeErroringSearchParams(
workStore: WorkStore, workStore: WorkStore,
prerenderStore: PrerenderStoreLegacy prerenderStore: PrerenderStoreLegacy | PrerenderStorePPR
): Promise<SearchParams> { ): Promise<SearchParams> {
const cachedSearchParams = CachedSearchParams.get(workStore) const cachedSearchParams = CachedSearchParams.get(workStore)
if (cachedSearchParams) { if (cachedSearchParams) {
...@@ -445,6 +451,13 @@ function makeErroringSearchParams( ...@@ -445,6 +451,13 @@ function makeErroringSearchParams(
workStore.route, workStore.route,
expression expression
) )
} else if (prerenderStore.type === 'prerender-ppr') {
// PPR Prerender (no cacheComponents)
postponeWithTracking(
workStore.route,
expression,
prerenderStore.dynamicTracking
)
} else { } else {
// Legacy Prerender // Legacy Prerender
throwToInterruptStaticGeneration( throwToInterruptStaticGeneration(
......
...@@ -60,6 +60,7 @@ import { StaticGenBailoutError } from '../../../client/components/static-generat ...@@ -60,6 +60,7 @@ import { StaticGenBailoutError } from '../../../client/components/static-generat
import { isStaticGenEnabled } from './helpers/is-static-gen-enabled' import { isStaticGenEnabled } from './helpers/is-static-gen-enabled'
import { import {
abortAndThrowOnSynchronousRequestDataAccess, abortAndThrowOnSynchronousRequestDataAccess,
postponeWithTracking,
createDynamicTrackingState, createDynamicTrackingState,
getFirstDynamicReason, getFirstDynamicReason,
} from '../../app-render/dynamic-rendering' } from '../../app-render/dynamic-rendering'
...@@ -1351,6 +1352,12 @@ function trackDynamic( ...@@ -1351,6 +1352,12 @@ function trackDynamic(
throw new InvariantError( throw new InvariantError(
'A runtime prerender store should not be used for a route handler.' 'A runtime prerender store should not be used for a route handler.'
) )
case 'prerender-ppr':
return postponeWithTracking(
store.route,
expression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy': case 'prerender-legacy':
workUnitStore.revalidate = 0 workUnitStore.revalidate = 0
......
...@@ -88,6 +88,7 @@ export function cacheLife(profile: CacheLifeProfiles | CacheLife): void { ...@@ -88,6 +88,7 @@ export function cacheLife(profile: CacheLifeProfiles | CacheLife): void {
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'unstable-cache': case 'unstable-cache':
......
...@@ -15,6 +15,7 @@ export function cacheTag(...tags: string[]): void { ...@@ -15,6 +15,7 @@ export function cacheTag(...tags: string[]): void {
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'unstable-cache': case 'unstable-cache':
......
...@@ -83,6 +83,7 @@ import { ...@@ -83,6 +83,7 @@ import {
} from './use-cache-errors' } from './use-cache-errors'
import { import {
createHangingInputAbortSignal, createHangingInputAbortSignal,
postponeWithTracking,
throwToInterruptStaticGeneration, throwToInterruptStaticGeneration,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
import { import {
...@@ -685,6 +686,7 @@ function createUseCacheStore( ...@@ -685,6 +686,7 @@ function createUseCacheStore(
break break
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender': case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'unstable-cache': case 'unstable-cache':
case 'generate-static-params': case 'generate-static-params':
...@@ -744,6 +746,7 @@ function captureOuterOwnerStack( ...@@ -744,6 +746,7 @@ function captureOuterOwnerStack(
case 'unstable-cache': case 'unstable-cache':
case 'request': case 'request':
case 'prerender': case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-client': case 'prerender-client':
...@@ -913,6 +916,7 @@ function propagateCacheEntryMetadata( ...@@ -913,6 +916,7 @@ function propagateCacheEntryMetadata(
case 'private-cache': case 'private-cache':
case 'prerender': case 'prerender':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
propagateCacheLifeAndTagsToRevalidateStore( propagateCacheLifeAndTagsToRevalidateStore(
cacheContext.outerWorkUnitStore, cacheContext.outerWorkUnitStore,
...@@ -977,7 +981,8 @@ function maybePropagateCacheEntryMetadata( ...@@ -977,7 +981,8 @@ function maybePropagateCacheEntryMetadata(
case 'private-cache': case 'private-cache':
case 'cache': case 'cache':
case 'unstable-cache': case 'unstable-cache':
case 'prerender-legacy': { case 'prerender-legacy':
case 'prerender-ppr': {
propagateCacheEntryMetadata(cacheContext, metadata) propagateCacheEntryMetadata(cacheContext, metadata)
break break
} }
...@@ -1216,6 +1221,7 @@ async function generateCacheEntryImpl( ...@@ -1216,6 +1221,7 @@ async function generateCacheEntryImpl(
} }
}) })
break break
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
...@@ -1471,6 +1477,7 @@ async function generateCacheEntryImpl( ...@@ -1471,6 +1477,7 @@ async function generateCacheEntryImpl(
} }
} }
// fallthrough // fallthrough
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -1716,6 +1723,12 @@ export async function cache( ...@@ -1716,6 +1723,12 @@ export async function cache(
workStore.route, workStore.route,
expression expression
) )
case 'prerender-ppr':
return postponeWithTracking(
workStore.route,
expression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy': case 'prerender-legacy':
return throwToInterruptStaticGeneration( return throwToInterruptStaticGeneration(
expression, expression,
...@@ -1803,6 +1816,7 @@ export async function cache( ...@@ -1803,6 +1816,7 @@ export async function cache(
} }
case 'prerender': case 'prerender':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'private-cache': case 'private-cache':
...@@ -2058,6 +2072,7 @@ export async function cache( ...@@ -2058,6 +2072,7 @@ export async function cache(
break break
} }
// fallthrough // fallthrough
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
// TODO(restart-on-cache-miss): We need to handle params/searchParams on page components. // TODO(restart-on-cache-miss): We need to handle params/searchParams on page components.
...@@ -2196,6 +2211,7 @@ export async function cache( ...@@ -2196,6 +2211,7 @@ export async function cache(
workStore.route, workStore.route,
'dynamic "use cache"' 'dynamic "use cache"'
) )
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
...@@ -2350,6 +2366,7 @@ export async function cache( ...@@ -2350,6 +2366,7 @@ export async function cache(
} }
break break
} }
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -2403,6 +2420,7 @@ export async function cache( ...@@ -2403,6 +2420,7 @@ export async function cache(
} }
break break
} }
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -2510,6 +2528,7 @@ export async function cache( ...@@ -2510,6 +2528,7 @@ export async function cache(
) )
} }
break break
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
...@@ -2872,6 +2891,7 @@ export async function cache( ...@@ -2872,6 +2891,7 @@ export async function cache(
break break
} }
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -2907,6 +2927,7 @@ export async function cache( ...@@ -2907,6 +2927,7 @@ export async function cache(
} }
case 'prerender': case 'prerender':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -3282,6 +3303,7 @@ function shouldForceRevalidate( ...@@ -3282,6 +3303,7 @@ function shouldForceRevalidate(
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'unstable-cache': case 'unstable-cache':
case 'generate-static-params': case 'generate-static-params':
...@@ -3325,6 +3347,7 @@ function shouldDiscardCacheEntry( ...@@ -3325,6 +3347,7 @@ function shouldDiscardCacheEntry(
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
......
...@@ -315,6 +315,7 @@ export async function adapter( ...@@ -315,6 +315,7 @@ export async function adapter(
// TODO: remove validationLevel and other global config from renderOpts // TODO: remove validationLevel and other global config from renderOpts
validationLevel: 'warning', validationLevel: 'warning',
experimental: { experimental: {
isRoutePPREnabled: false,
authInterrupts: authInterrupts:
!!params.request.nextConfig?.experimental?.authInterrupts, !!params.request.nextConfig?.experimental?.authInterrupts,
// Proxy doesn't fill Cache Components entries, so this value // Proxy doesn't fill Cache Components entries, so this value
......
import { abortAndThrowOnSynchronousRequestDataAccess } from '../../app-render/dynamic-rendering' import {
abortAndThrowOnSynchronousRequestDataAccess,
postponeWithTracking,
} from '../../app-render/dynamic-rendering'
import { isDynamicRoute } from '../../../shared/lib/router/utils' import { isDynamicRoute } from '../../../shared/lib/router/utils'
import { import {
NEXT_CACHE_IMPLICIT_TAG_ID, NEXT_CACHE_IMPLICIT_TAG_ID,
...@@ -170,6 +173,12 @@ function revalidate( ...@@ -170,6 +173,12 @@ function revalidate(
throw new InvariantError( throw new InvariantError(
`${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.` `${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.`
) )
case 'prerender-ppr':
return postponeWithTracking(
store.route,
expression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy': case 'prerender-legacy':
workUnitStore.revalidate = 0 workUnitStore.revalidate = 0
......
...@@ -166,6 +166,7 @@ export function unstable_cache<T extends Callback>( ...@@ -166,6 +166,7 @@ export function unstable_cache<T extends Callback>(
case 'private-cache': case 'private-cache':
case 'prerender': case 'prerender':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
// We update the store's revalidate property if the option.revalidate is a higher precedence // We update the store's revalidate property if the option.revalidate is a higher precedence
// options.revalidate === undefined doesn't affect timing. // options.revalidate === undefined doesn't affect timing.
...@@ -417,6 +418,7 @@ function getFetchUrlPrefix( ...@@ -417,6 +418,7 @@ function getFetchUrlPrefix(
case 'prerender-client': case 'prerender-client':
case 'validation-client': case 'validation-client':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
......
...@@ -38,6 +38,7 @@ export function unstable_noStore() { ...@@ -38,6 +38,7 @@ export function unstable_noStore() {
case 'prerender-runtime': case 'prerender-runtime':
// unstable_noStore() is a noop in Dynamic I/O. // unstable_noStore() is a noop in Dynamic I/O.
return return
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
......
import { InvariantError } from './invariant-error'
/**
* Throws an InvariantError indicating that a prerender-ppr code path was
* reached. The prerender-ppr work unit type has been removed and all code
* handling it is dead. Use this in exhaustive switch cases while the
* prerender-ppr type is being cleaned up.
*/
export function throwPrerenderPPRRemovedError(): never {
throw new InvariantError(
'The prerender-ppr work unit type has been removed. This code path should be unreachable.'
)
}
import React from 'react'
export default function Root({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
import { cookies } from 'next/headers'
export default async function Page() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Foobar />
</Suspense>
)
}
async function Foobar() {
try {
await cookies()
} catch (err) {
console.log('User land logged error: ' + err.message)
}
await cookies() // still postpones so doesn't fail build
return null
}
import React from 'react'
import { cookies } from 'next/headers'
export default async function Page() {
try {
await cookies()
} catch (err) {
throw new Error(
"Throwing a new error from 'no-suspense-boundary-re-throwing-error'"
)
}
return <div>Hello World</div>
}
import React from 'react'
import { cookies } from 'next/headers'
export default async function Page() {
try {
await cookies()
} catch (err) {}
return <div>Hello World</div>
}
import React, { Suspense } from 'react'
import { cookies } from 'next/headers'
export default async function Page() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Foobar />
</Suspense>
)
}
async function Foobar() {
try {
await cookies()
} catch (err) {}
return null
}
import React, { Suspense } from 'react'
import { cookies } from 'next/headers'
export default async function Page() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Foobar />
</Suspense>
)
}
async function Foobar() {
try {
await cookies()
} catch (err) {
throw new Error('The original error was caught and rethrown.')
}
return null
}
import React, { Suspense } from 'react'
export default async function Page() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Foobar />
</Suspense>
)
}
async function Foobar() {
throw new Error('Kaboom')
}
export default async function Page() {
throw new Error('Regular Prerender Error')
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
experimental: { prerenderEarlyExit: false },
}
module.exports = nextConfig
import { isNextStart, nextTestSetup } from 'e2e-utils'
// TODO(NAR-423): Migrate to Cache Components.
describe.skip('ppr build errors', () => {
;(isNextStart ? describe : describe.skip)('production only', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
let cliOutput: string
beforeAll(async () => {
const output = await next.build()
cliOutput = output.cliOutput
})
describe('within a suspense boundary', () => {
it('should fail the build for uncaught prerender errors', async () => {
expect(cliOutput).toContain(
'Error occurred prerendering page "/regular-error-suspense-boundary".'
)
expect(cliOutput).toContain(
'Error occurred prerendering page "/re-throwing-error".'
)
})
})
describe('outside of a suspense boundary', () => {
it('should fail the build for uncaught errors', async () => {
expect(cliOutput).toContain(
'Error occurred prerendering page "/regular-error".'
)
expect(cliOutput).toContain(
'Error occurred prerendering page "/no-suspense-boundary-re-throwing-error".'
)
})
})
describe('when a postpone call is caught and logged it should', () => {
it('should include a message telling why', async () => {
expect(cliOutput).toContain(
'User land logged error: Route /logging-error needs to bail out of prerendering at this point because it used cookies.'
)
})
})
})
})
...@@ -2,10 +2,10 @@ import { nextTestSetup } from 'e2e-utils' ...@@ -2,10 +2,10 @@ import { nextTestSetup } from 'e2e-utils'
// TODO(NAR-423): Migrate to Cache Components. // TODO(NAR-423): Migrate to Cache Components.
describe.skip('static-shell-debugging', () => { describe.skip('static-shell-debugging', () => {
const cacheComponents = Boolean(process.env.__NEXT_CACHE_COMPONENTS) const ppr = Boolean(process.env.__NEXT_CACHE_COMPONENTS)
const context = { const context = {
cacheComponents, ppr,
debugging: cacheComponents, debugging: ppr,
} }
const { next, skipped, isNextDev } = nextTestSetup({ const { next, skipped, isNextDev } = nextTestSetup({
...@@ -19,13 +19,13 @@ describe.skip('static-shell-debugging', () => { ...@@ -19,13 +19,13 @@ describe.skip('static-shell-debugging', () => {
: undefined, : undefined,
}, },
nextConfig: { nextConfig: {
cacheComponents: context.cacheComponents, experimental: { ppr: context.ppr },
}, },
}) })
if (skipped) return if (skipped) return
if (context.debugging && context.cacheComponents) { if (context.debugging && context.ppr) {
it('should only render the static shell', async () => { it('should only render the static shell', async () => {
const res = await next.fetch('/?__nextppronly=1') const res = await next.fetch('/?__nextppronly=1')
expect(res.status).toBe(200) expect(res.status).toBe(200)
......
...@@ -159,7 +159,7 @@ describe('Config Experimental Warning', () => { ...@@ -159,7 +159,7 @@ describe('Config Experimental Warning', () => {
nextConfig: { nextConfig: {
experimental: { experimental: {
ppr: 'incremental', ppr: 'incremental',
} as any, },
}, },
}) })
......
...@@ -2,7 +2,7 @@ import React from 'react'; ...@@ -2,7 +2,7 @@ import React from 'react';
import { DynamicServerError } from '../../client/components/hooks-server-context'; import { DynamicServerError } from '../../client/components/hooks-server-context';
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'; import { StaticGenBailoutError } from '../../client/components/static-generation-bailout';
import { getPathname } from '../../lib/url'; import { getPathname } from '../../lib/url';
const hasUnnamed = typeof React.unstable_unnamed === 'function'; const hasPostpone = typeof React.unstable_postpone === 'function';
export function createPrerenderState(isDebugSkeleton) { export function createPrerenderState(isDebugSkeleton) {
return { return {
isDebugSkeleton, isDebugSkeleton,
...@@ -16,7 +16,7 @@ export function markCurrentScopeAsDynamic(store, expression) { ...@@ -16,7 +16,7 @@ export function markCurrentScopeAsDynamic(store, expression) {
} else if (store.dynamicShouldError) { } else if (store.dynamicShouldError) {
throw new StaticGenBailoutError(`Route ${pathname} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`); throw new StaticGenBailoutError(`Route ${pathname} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`);
} else if (store.prerenderState) { } else if (store.prerenderState) {
markPrerenderState(store.prerenderState, expression, pathname); postponeWithTracking(store.prerenderState, expression, pathname);
} else { } else {
store.revalidate = 0; store.revalidate = 0;
if (store.isStaticGeneration) { if (store.isStaticGeneration) {
...@@ -34,7 +34,7 @@ export function trackDynamicDataAccessed(store, expression) { ...@@ -34,7 +34,7 @@ export function trackDynamicDataAccessed(store, expression) {
} else if (store.dynamicShouldError) { } else if (store.dynamicShouldError) {
throw new StaticGenBailoutError(`Route ${pathname} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`); throw new StaticGenBailoutError(`Route ${pathname} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`);
} else if (store.prerenderState) { } else if (store.prerenderState) {
markPrerenderState(store.prerenderState, expression, pathname); postponeWithTracking(store.prerenderState, expression, pathname);
} else { } else {
store.revalidate = 0; store.revalidate = 0;
if (store.isStaticGeneration) { if (store.isStaticGeneration) {
...@@ -45,21 +45,21 @@ export function trackDynamicDataAccessed(store, expression) { ...@@ -45,21 +45,21 @@ export function trackDynamicDataAccessed(store, expression) {
} }
} }
} }
export function ApiThatShallNotBeNamed({ reason, prerenderState, pathname }) { export function Postpone({ reason, prerenderState, pathname }) {
markPrerenderState(prerenderState, reason, pathname); postponeWithTracking(prerenderState, reason, pathname);
} }
export function trackDynamicFetch(store, expression) { export function trackDynamicFetch(store, expression) {
if (!store.prerenderState || store.isUnstableCacheCallback) return; if (!store.prerenderState || store.isUnstableCacheCallback) return;
markPrerenderState(store.prerenderState, expression, store.urlPathname); postponeWithTracking(store.prerenderState, expression, store.urlPathname);
} }
function markPrerenderState(prerenderState, expression, pathname) { function postponeWithTracking(prerenderState, expression, pathname) {
assertUnnamed(); assertPostpone();
const reason = `Route ${pathname} needs to bail out of prerendering at this point because it used ${expression}. ` + `React throws this special object to indicate where. It should not be caught by ` + `your own try/catch. Learn more: https://nextjs.org/docs/messages/ppr-caught-error`; const reason = `Route ${pathname} needs to bail out of prerendering at this point because it used ${expression}. ` + `React throws this special object to indicate where. It should not be caught by ` + `your own try/catch. Learn more: https://nextjs.org/docs/messages/ppr-caught-error`;
prerenderState.dynamicAccesses.push({ prerenderState.dynamicAccesses.push({
stack: prerenderState.isDebugSkeleton ? new Error().stack : undefined, stack: prerenderState.isDebugSkeleton ? new Error().stack : undefined,
expression expression
}); });
React.unstable_unnamed(reason); React.unstable_postpone(reason);
} }
export function usedDynamicAPIs(prerenderState) { export function usedDynamicAPIs(prerenderState) {
return prerenderState.dynamicAccesses.length > 0; return prerenderState.dynamicAccesses.length > 0;
...@@ -81,16 +81,16 @@ export function formatDynamicAPIAccesses(prerenderState) { ...@@ -81,16 +81,16 @@ export function formatDynamicAPIAccesses(prerenderState) {
return `Dynamic API Usage Debug - ${expression}:\n${stack}`; return `Dynamic API Usage Debug - ${expression}:\n${stack}`;
}); });
} }
function assertUnnamed() { function assertPostpone() {
if (!hasUnnamed) { if (!hasPostpone) {
throw new Error(`Invariant: React.unstable_unnamed is not defined. This suggests the wrong version of React was loaded. This is a bug in Next.js`); throw new Error(`Invariant: React.unstable_postpone is not defined. This suggests the wrong version of React was loaded. This is a bug in Next.js`);
} }
} }
export function createUnnamedAbortSignal(reason) { export function createPostponedAbortSignal(reason) {
assertUnnamed(); assertPostpone();
const controller = new AbortController(); const controller = new AbortController();
try { try {
React.unstable_unnamed(reason); React.unstable_postpone(reason);
} catch (x) { } catch (x) {
controller.abort(x); controller.abort(x);
} }
......
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