Unverified Commit 9c5e3da9 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Revert "refactor: consolidate PPR into cacheComponents architecture (#88243)" (#88421)

This reverts commit a85d888a.

PR #88243 introduced deploy test regressions in the following test
suites:

-
`test/e2e/app-dir/segment-cache/prefetch-runtime/prefetch-runtime.test.ts`
- `test/e2e/app-dir/segment-cache/client-params/client-params.test.ts`
parent e99a92bb
...@@ -19,6 +19,7 @@ import { findPagesDir } from '../../lib/find-pages-dir' ...@@ -19,6 +19,7 @@ import { findPagesDir } from '../../lib/find-pages-dir'
import { PAGE_TYPES } from '../../lib/page-types' import { PAGE_TYPES } from '../../lib/page-types'
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'
...@@ -187,7 +188,7 @@ async function collectRoutesForAnalyze( ...@@ -187,7 +188,7 @@ async function collectRoutesForAnalyze(
config.basePath ? `${config.basePath}${pathPrefix}` : pathPrefix config.basePath ? `${config.basePath}${pathPrefix}` : pathPrefix
) )
const isAppPPREnabled = !!config.cacheComponents const isAppPPREnabled = checkIsAppPPREnabled(config.experimental.ppr)
// Generate routes manifest // Generate routes manifest
const { routesManifest } = generateRoutesManifest({ const { routesManifest } = generateRoutesManifest({
......
...@@ -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,
...@@ -114,6 +115,7 @@ export function getDefineEnv({ ...@@ -114,6 +115,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
...@@ -159,6 +161,7 @@ export function getDefineEnv({ ...@@ -159,6 +161,7 @@ export function getDefineEnv({
'process.env.__NEXT_APP_NAV_FAIL_HANDLING': Boolean( 'process.env.__NEXT_APP_NAV_FAIL_HANDLING': Boolean(
config.experimental.appNavFailHandling config.experimental.appNavFailHandling
), ),
'process.env.__NEXT_PPR': isPPREnabled,
'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled, 'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled,
'process.env.__NEXT_USE_CACHE': isUseCacheEnabled, 'process.env.__NEXT_USE_CACHE': isUseCacheEnabled,
......
...@@ -199,6 +199,10 @@ import { traceMemoryUsage } from '../lib/memory/trace' ...@@ -199,6 +199,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'
...@@ -1592,7 +1596,7 @@ export default async function build( ...@@ -1592,7 +1596,7 @@ export default async function build(
const isAuthInterruptsEnabled = Boolean( const isAuthInterruptsEnabled = Boolean(
config.experimental.authInterrupts config.experimental.authInterrupts
) )
const isAppPPREnabled = isAppCacheComponentsEnabled const isAppPPREnabled = checkIsAppPPREnabled(config.experimental.ppr)
const routesManifestPath = path.join(distDir, ROUTES_MANIFEST) const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)
...@@ -2147,6 +2151,7 @@ export default async function build( ...@@ -2147,6 +2151,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,
sriEnabled, sriEnabled,
...@@ -2368,6 +2373,7 @@ export default async function build( ...@@ -2368,6 +2373,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,
sriEnabled, sriEnabled,
...@@ -2942,8 +2948,9 @@ export default async function build( ...@@ -2942,8 +2948,9 @@ export default async function build(
const appConfig = appDefaultConfigs.get(originalAppPath) const appConfig = appDefaultConfigs.get(originalAppPath)
const isDynamicError = appConfig?.dynamic === 'error' const isDynamicError = appConfig?.dynamic === 'error'
const isRoutePPREnabled: boolean = const isRoutePPREnabled: boolean = appConfig
!!appConfig && isAppCacheComponentsEnabled ? 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
...@@ -3132,7 +3139,8 @@ export default async function build( ...@@ -3132,7 +3139,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 && isAppCacheComponentsEnabled !isAppRouteHandler &&
checkIsRoutePPREnabled(config.experimental.ppr)
? true ? true
: undefined : undefined
......
...@@ -20,6 +20,7 @@ import { BaseServerSpan } from '../../server/lib/trace/constants' ...@@ -20,6 +20,7 @@ import { BaseServerSpan } from '../../server/lib/trace/constants'
import { interopDefault } from '../../server/app-render/interop-default' import { interopDefault } from '../../server/app-render/interop-default'
import { stripFlightHeaders } from '../../server/app-render/strip-flight-headers' import { stripFlightHeaders } from '../../server/app-render/strip-flight-headers'
import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node' import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node'
import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr'
import { import {
getFallbackRouteParams, getFallbackRouteParams,
createOpaqueFallbackRouteParams, createOpaqueFallbackRouteParams,
...@@ -221,10 +222,12 @@ export async function handler( ...@@ -221,10 +222,12 @@ export async function handler(
const isPossibleServerAction = getIsPossibleServerAction(req) const isPossibleServerAction = getIsPossibleServerAction(req)
/** /**
* If the route being rendered is an app page, and the cacheComponents feature * If the route being rendered is an app page, and the ppr feature has been
* 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
)
if ( if (
!getRequestMeta(req, 'postponed') && !getRequestMeta(req, 'postponed') &&
......
...@@ -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'
...@@ -749,6 +751,7 @@ export async function isPageStatic({ ...@@ -749,6 +751,7 @@ export async function isPageStatic({
cacheHandler, cacheHandler,
cacheHandlers, cacheHandlers,
cacheLifeProfiles, cacheLifeProfiles,
pprConfig,
buildId, buildId,
sriEnabled, sriEnabled,
}: { }: {
...@@ -774,6 +777,7 @@ export async function isPageStatic({ ...@@ -774,6 +777,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
sriEnabled: boolean sriEnabled: boolean
}): Promise<PageIsStaticResult> { }): Promise<PageIsStaticResult> {
...@@ -898,10 +902,12 @@ export async function isPageStatic({ ...@@ -898,10 +902,12 @@ export async function isPageStatic({
rootParamKeys = collectRootParamKeys(routeModule) rootParamKeys = collectRootParamKeys(routeModule)
// A page supports partial prerendering if it is an app page and // A page supports partial prerendering if it is an app page and either
// cacheComponents is enabled. // 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':
const fallbackParams = workUnitStore.fallbackRouteParams const fallbackParams = workUnitStore.fallbackRouteParams
return fallbackParams ? fallbackParams.size > 0 : false return fallbackParams ? fallbackParams.size > 0 : false
case 'prerender-legacy': case 'prerender-legacy':
......
...@@ -164,11 +164,15 @@ export async function fetchServerResponse( ...@@ -164,11 +164,15 @@ 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.
// 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,
'auto', 'auto',
true shouldImmediatelyDecode
) )
const responseUrl = urlToUrlWithoutFlightMarker(new URL(res.url)) const responseUrl = urlToUrlWithoutFlightMarker(new URL(res.url))
......
...@@ -2,7 +2,10 @@ import { isHangingPromiseRejectionError } from '../../server/dynamic-rendering-u ...@@ -2,7 +2,10 @@ import { isHangingPromiseRejectionError } from '../../server/dynamic-rendering-u
import { isPostpone } from '../../server/lib/router-utils/is-postpone' 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 {
...@@ -10,6 +13,7 @@ export function unstable_rethrow(error: unknown): void { ...@@ -10,6 +13,7 @@ export function unstable_rethrow(error: unknown): void {
isNextRouterError(error) || isNextRouterError(error) ||
isBailoutToCSRError(error) || isBailoutToCSRError(error) ||
isDynamicServerError(error) || isDynamicServerError(error) ||
isDynamicPostpone(error) ||
isPostpone(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)
...@@ -119,6 +119,7 @@ async function createComponentTreeInternal( ...@@ -119,6 +119,7 @@ async function createComponentTreeInternal(
createServerParamsForServerSegment, createServerParamsForServerSegment,
createPrerenderParamsForClientSegment, createPrerenderParamsForClientSegment,
serverHooks: { DynamicServerError }, serverHooks: { DynamicServerError },
Postpone,
}, },
pagePath, pagePath,
getDynamicParamFromSegment, getDynamicParamFromSegment,
...@@ -303,6 +304,7 @@ async function createComponentTreeInternal( ...@@ -303,6 +304,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
} }
...@@ -688,6 +690,42 @@ async function createComponentTreeInternal( ...@@ -688,6 +690,42 @@ 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 (
workStore.isStaticGeneration &&
workStore.forceDynamic &&
experimental.isRoutePPREnabled
) {
return createSeedData(
ctx,
createElement(
Fragment,
{
key: cacheNodeKey,
},
createElement(Postpone, {
reason: 'dynamic = "force-dynamic" was used',
route: workStore.route,
}),
layerAssets
),
parallelRouteCacheNodeSeedData,
loadingData,
true,
hasRuntimePrefetch
)
}
const isClientComponent = isClientReference(layoutOrPageMod) const isClientComponent = isClientReference(layoutOrPageMod)
if ( if (
......
...@@ -50,6 +50,8 @@ import { scheduleOnNextTick } from '../../lib/scheduler' ...@@ -50,6 +50,8 @@ import { scheduleOnNextTick } from '../../lib/scheduler'
import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr' import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
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
...@@ -141,6 +143,7 @@ export function markCurrentScopeAsDynamic( ...@@ -141,6 +143,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':
break break
default: default:
...@@ -161,6 +164,12 @@ export function markCurrentScopeAsDynamic( ...@@ -161,6 +164,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
...@@ -230,6 +239,7 @@ export function trackDynamicDataInDynamicRender(workUnitStore: WorkUnitStore) { ...@@ -230,6 +239,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':
break break
case 'request': case 'request':
...@@ -325,6 +335,78 @@ export function abortAndThrowOnSynchronousRequestDataAccess( ...@@ -325,6 +335,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 {
...@@ -405,6 +487,14 @@ export function formatDynamicAPIAccesses( ...@@ -405,6 +487,14 @@ 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 * 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. * abort semantics slightly.
...@@ -460,6 +550,7 @@ export function createHangingInputAbortSignal( ...@@ -460,6 +550,7 @@ export function createHangingInputAbortSignal(
return controller.signal return controller.signal
case 'prerender-client': case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
...@@ -509,6 +600,17 @@ export function useDynamicRouteParams(expression: string) { ...@@ -509,6 +600,17 @@ export function useDynamicRouteParams(expression: string) {
} }
break break
} }
case 'prerender-ppr': {
const fallbackParams = workUnitStore.fallbackRouteParams
if (fallbackParams && fallbackParams.size > 0) {
return postponeWithTracking(
workStore.route,
expression,
workUnitStore.dynamicTracking
)
}
break
}
case 'prerender-runtime': case 'prerender-runtime':
throw new InvariantError( throw new InvariantError(
`\`${expression}\` was called during a runtime prerender. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.` `\`${expression}\` was called during a runtime prerender. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`
...@@ -552,7 +654,8 @@ export function useDynamicSearchParams(expression: string) { ...@@ -552,7 +654,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
} }
......
...@@ -276,6 +276,7 @@ export async function decryptActionBoundArgs( ...@@ -276,6 +276,7 @@ export async function decryptActionBoundArgs(
} }
break break
case 'prerender-client': case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
......
...@@ -38,6 +38,7 @@ export { createMetadataComponents } from '../../lib/metadata/metadata' ...@@ -38,6 +38,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 { collectSegmentData } from './collect-segment-data' export { collectSegmentData } from './collect-segment-data'
......
/*
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'
...@@ -123,6 +123,7 @@ export function getFlightStream<T>( ...@@ -123,6 +123,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':
......
...@@ -225,6 +225,25 @@ interface StaticPrerenderStoreCommon { ...@@ -225,6 +225,25 @@ interface StaticPrerenderStoreCommon {
readonly allowEmptyStaticShell: boolean readonly allowEmptyStaticShell: boolean
} }
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.
*/
prerenderResumeDataCache: PrerenderResumeDataCache
}
export interface PrerenderStoreLegacy export interface PrerenderStoreLegacy
extends CommonWorkUnitStore, extends CommonWorkUnitStore,
RevalidateStore { RevalidateStore {
...@@ -232,7 +251,10 @@ export interface PrerenderStoreLegacy ...@@ -232,7 +251,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<
...@@ -333,6 +355,7 @@ export function getPrerenderResumeDataCache( ...@@ -333,6 +355,7 @@ export function getPrerenderResumeDataCache(
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'prerender': case 'prerender':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
return workUnitStore.prerenderResumeDataCache return workUnitStore.prerenderResumeDataCache
case 'prerender-client': case 'prerender-client':
// TODO eliminate fetch caching in client scope and stop exposing this data // TODO eliminate fetch caching in client scope and stop exposing this data
...@@ -368,8 +391,10 @@ export function getRenderResumeDataCache( ...@@ -368,8 +391,10 @@ export function getRenderResumeDataCache(
// that is used to read from prefilled caches. // that is used to read from prefilled caches.
return workUnitStore.renderResumeDataCache return workUnitStore.renderResumeDataCache
} }
// Otherwise we return the mutable prerender resume data cache here as an // fallthrough
// immutable version of the cache as it can also be used for reading. case 'prerender-ppr':
// Otherwise we return the mutable resume data cache here as an immutable
// version of the cache as it can also be used for reading.
return workUnitStore.prerenderResumeDataCache ?? null return workUnitStore.prerenderResumeDataCache ?? null
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -395,6 +420,7 @@ export function getHmrRefreshHash( ...@@ -395,6 +420,7 @@ export function getHmrRefreshHash(
case 'request': case 'request':
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 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'unstable-cache': case 'unstable-cache':
break break
...@@ -419,6 +445,7 @@ export function isHmrRefresh( ...@@ -419,6 +445,7 @@ export function isHmrRefresh(
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'unstable-cache': case 'unstable-cache':
break break
...@@ -443,6 +470,7 @@ export function getServerComponentsHmrCache( ...@@ -443,6 +470,7 @@ export function getServerComponentsHmrCache(
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'unstable-cache': case 'unstable-cache':
break break
...@@ -471,6 +499,7 @@ export function getDraftModeProviderForCacheScope( ...@@ -471,6 +499,7 @@ export function getDraftModeProviderForCacheScope(
return workUnitStore.draftMode return workUnitStore.draftMode
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
break break
default: default:
...@@ -496,6 +525,7 @@ export function getCacheSignal( ...@@ -496,6 +525,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':
...@@ -515,6 +545,7 @@ export function getRuntimeStagePromise( ...@@ -515,6 +545,7 @@ export function getRuntimeStagePromise(
return workUnitStore.runtimeStagePromise return workUnitStore.runtimeStagePromise
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
......
...@@ -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,
...@@ -422,7 +423,7 @@ export default abstract class Server< ...@@ -422,7 +423,7 @@ export default abstract class Server<
readonly data: NextDataPathnameNormalizer | undefined readonly data: NextDataPathnameNormalizer | undefined
} }
private readonly isCacheComponentsEnabled: boolean private readonly isAppPPREnabled: boolean
/** /**
* This is used to persist cache scopes across * This is used to persist cache scopes across
...@@ -504,8 +505,9 @@ export default abstract class Server< ...@@ -504,8 +505,9 @@ export default abstract class Server<
this.enabledDirectories = this.getEnabledDirectories(dev) this.enabledDirectories = this.getEnabledDirectories(dev)
this.isCacheComponentsEnabled = this.isAppPPREnabled =
this.enabledDirectories.app && !!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
...@@ -1054,7 +1056,7 @@ export default abstract class Server< ...@@ -1054,7 +1056,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.isCacheComponentsEnabled && this.isAppPPREnabled &&
this.minimalMode && this.minimalMode &&
req.headers[NEXT_RESUME_HEADER] === '1' && req.headers[NEXT_RESUME_HEADER] === '1' &&
req.method === 'POST' req.method === 'POST'
...@@ -2175,7 +2177,7 @@ export default abstract class Server< ...@@ -2175,7 +2177,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.isCacheComponentsEnabled && this.isAppPPREnabled &&
typeof routeModule !== 'undefined' && typeof routeModule !== 'undefined' &&
isAppPageRouteModule(routeModule) isAppPageRouteModule(routeModule)
......
...@@ -11,10 +11,7 @@ import type { WEB_VITALS } from '../shared/lib/utils' ...@@ -11,10 +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'
* @deprecated This type is only kept for backwards compatibility with the deprecated `experimental.ppr` config option.
*/
export type ExperimentalPPRConfig = boolean | 'incremental'
import { INFINITE_CACHE } from '../lib/constants' import { INFINITE_CACHE } from '../lib/constants'
import { isStableBuild } from '../shared/lib/errors/canary-only-config-error' import { isStableBuild } from '../shared/lib/errors/canary-only-config-error'
import type { FallbackRouteParam } from '../build/static-paths/types' import type { FallbackRouteParam } from '../build/static-paths/types'
......
...@@ -1350,6 +1350,9 @@ function assignDefaultsAndValidate( ...@@ -1350,6 +1350,9 @@ function assignDefaultsAndValidate(
} }
if (result.cacheComponents) { if (result.cacheComponents) {
// TODO: remove once we've finished migrating internally to cacheComponents.
result.experimental.ppr = true
// Prerender sourcemaps are enabled by default when using cacheComponents, unless explicitly disabled. // Prerender sourcemaps are enabled by default when using cacheComponents, unless explicitly disabled.
if (result.enablePrerenderSourceMaps === undefined) { if (result.enablePrerenderSourceMaps === undefined) {
result.enablePrerenderSourceMaps = true result.enablePrerenderSourceMaps = true
......
...@@ -778,6 +778,7 @@ export default class DevServer extends Server { ...@@ -778,6 +778,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 { parseAppRoute } from '../../shared/lib/router/routes/app' import { parseAppRoute } from '../../shared/lib/router/routes/app'
type RuntimeConfig = { type RuntimeConfig = {
pprConfig: ExperimentalPPRConfig | undefined
configFileName: string configFileName: string
cacheComponents: boolean cacheComponents: boolean
} }
...@@ -121,7 +126,8 @@ export async function loadStaticPaths({ ...@@ -121,7 +126,8 @@ export async function loadStaticPaths({
} }
const isRoutePPREnabled = const isRoutePPREnabled =
isAppPageRouteModule(routeModule) && config.cacheComponents isAppPageRouteModule(routeModule) &&
checkIsRoutePPREnabled(config.pprConfig)
const rootParamKeys = collectRootParamKeys(routeModule) const rootParamKeys = collectRootParamKeys(routeModule)
......
/**
* 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
}
...@@ -358,6 +358,7 @@ export function createPatchedFetcher( ...@@ -358,6 +358,7 @@ export function createPatchedFetcher(
case 'prerender-runtime': case 'prerender-runtime':
// TODO: Stop accumulating tags in client prerender. (fallthrough) // TODO: Stop accumulating tags in client prerender. (fallthrough)
case 'prerender-client': case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -398,6 +399,7 @@ export function createPatchedFetcher( ...@@ -398,6 +399,7 @@ export function createPatchedFetcher(
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
...@@ -566,6 +568,7 @@ export function createPatchedFetcher( ...@@ -566,6 +568,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':
...@@ -691,6 +694,7 @@ export function createPatchedFetcher( ...@@ -691,6 +694,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':
...@@ -735,6 +739,7 @@ export function createPatchedFetcher( ...@@ -735,6 +739,7 @@ export function createPatchedFetcher(
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'unstable-cache': case 'unstable-cache':
break break
...@@ -880,6 +885,7 @@ export function createPatchedFetcher( ...@@ -880,6 +885,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':
...@@ -960,6 +966,7 @@ export function createPatchedFetcher( ...@@ -960,6 +966,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':
...@@ -1087,6 +1094,7 @@ export function createPatchedFetcher( ...@@ -1087,6 +1094,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':
...@@ -1136,6 +1144,7 @@ export function createPatchedFetcher( ...@@ -1136,6 +1144,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':
break break
default: default:
workUnitStore satisfies never workUnitStore satisfies never
......
...@@ -244,6 +244,7 @@ function patchConsoleMethod(methodName: InterceptableConsoleMethod): void { ...@@ -244,6 +244,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':
......
...@@ -599,6 +599,7 @@ function filteringUnhandledRejectionHandler( ...@@ -599,6 +599,7 @@ function filteringUnhandledRejectionHandler(
} }
break break
} }
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
......
...@@ -142,6 +142,7 @@ export function io(expression: string, type: ApiType) { ...@@ -142,6 +142,7 @@ export function io(expression: string, type: ApiType) {
} }
} }
break break
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
......
...@@ -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'
...@@ -83,6 +84,14 @@ export function connection(): Promise<void> { ...@@ -83,6 +84,14 @@ export function connection(): Promise<void> {
workStore.route, workStore.route,
'`connection()`' '`connection()`'
) )
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 {
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { import {
delayUntilRuntimeStage, delayUntilRuntimeStage,
postponeWithTracking,
throwToInterruptStaticGeneration, throwToInterruptStaticGeneration,
trackDynamicDataInDynamicRender, trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
...@@ -79,6 +80,14 @@ export function cookies(): Promise<ReadonlyRequestCookies> { ...@@ -79,6 +80,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.
......
...@@ -13,6 +13,7 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.exte ...@@ -13,6 +13,7 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.exte
import { import {
abortAndThrowOnSynchronousRequestDataAccess, abortAndThrowOnSynchronousRequestDataAccess,
delayUntilRuntimeStage, delayUntilRuntimeStage,
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'
...@@ -59,6 +60,7 @@ export function draftMode(): Promise<DraftMode> { ...@@ -59,6 +60,7 @@ export function draftMode(): Promise<DraftMode> {
// eslint-disable-next-line no-fallthrough // eslint-disable-next-line no-fallthrough
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
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)
...@@ -219,6 +221,12 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) { ...@@ -219,6 +221,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 {
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { import {
delayUntilRuntimeStage, delayUntilRuntimeStage,
postponeWithTracking,
throwToInterruptStaticGeneration, throwToInterruptStaticGeneration,
trackDynamicDataInDynamicRender, trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
...@@ -77,6 +78,7 @@ export function headers(): Promise<ReadonlyHeaders> { ...@@ -77,6 +78,7 @@ export function headers(): Promise<ReadonlyHeaders> {
case 'prerender-client': case 'prerender-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
...@@ -100,6 +102,16 @@ export function headers(): Promise<ReadonlyHeaders> { ...@@ -100,6 +102,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,10 +5,16 @@ import { ...@@ -5,10 +5,16 @@ import {
import type { OpaqueFallbackRouteParams } from './fallback-params' import type { OpaqueFallbackRouteParams } from './fallback-params'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect' import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import { delayUntilRuntimeStage } from '../app-render/dynamic-rendering' import {
throwToInterruptStaticGeneration,
postponeWithTracking,
delayUntilRuntimeStage,
} from '../app-render/dynamic-rendering'
import { import {
workUnitAsyncStorage, workUnitAsyncStorage,
type PrerenderStorePPR,
type PrerenderStoreLegacy,
type StaticPrerenderStoreModern, type StaticPrerenderStoreModern,
type StaticPrerenderStore, type StaticPrerenderStore,
throwInvariantForMissingStore, throwInvariantForMissingStore,
...@@ -40,6 +46,7 @@ export function createParamsFromClient( ...@@ -40,6 +46,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':
return createStaticPrerenderParams( return createStaticPrerenderParams(
underlyingParams, underlyingParams,
...@@ -92,6 +99,7 @@ export function createServerParamsForRoute( ...@@ -92,6 +99,7 @@ export function createServerParamsForRoute(
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,
...@@ -137,6 +145,7 @@ export function createServerParamsForServerSegment( ...@@ -137,6 +145,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,
...@@ -211,6 +220,7 @@ export function createPrerenderParamsForClientSegment( ...@@ -211,6 +220,7 @@ export function createPrerenderParamsForClientSegment(
throw new InvariantError( throw new InvariantError(
'createPrerenderParamsForClientSegment should not be called in cache contexts.' 'createPrerenderParamsForClientSegment should not be called in cache contexts.'
) )
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-runtime': case 'prerender-runtime':
case 'request': case 'request':
...@@ -251,6 +261,22 @@ function createStaticPrerenderParams( ...@@ -251,6 +261,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:
...@@ -352,6 +378,65 @@ function makeHangingParams( ...@@ -352,6 +378,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) {
......
import type { WorkStore } from '../app-render/work-async-storage.external' import type { WorkStore } from '../app-render/work-async-storage.external'
import { delayUntilRuntimeStage } from '../app-render/dynamic-rendering' import {
delayUntilRuntimeStage,
postponeWithTracking,
type DynamicTrackingState,
} from '../app-render/dynamic-rendering'
import { import {
throwInvariantForMissingStore, throwInvariantForMissingStore,
...@@ -19,6 +23,7 @@ export function createServerPathnameForMetadata( ...@@ -19,6 +23,7 @@ export function createServerPathnameForMetadata(
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 createPrerenderPathname( return createPrerenderPathname(
underlyingPathname, underlyingPathname,
...@@ -68,6 +73,13 @@ function createPrerenderPathname( ...@@ -68,6 +73,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:
...@@ -78,6 +90,41 @@ function createPrerenderPathname( ...@@ -78,6 +90,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,
} from '../app-render/work-async-storage.external' } from '../app-render/work-async-storage.external'
import { import {
workUnitAsyncStorage, workUnitAsyncStorage,
type PrerenderStoreLegacy,
type PrerenderStorePPR,
type StaticPrerenderStore, type StaticPrerenderStore,
} 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'
/** /**
...@@ -58,6 +65,7 @@ export function getRootParam(paramName: string): Promise<ParamValue> { ...@@ -58,6 +65,7 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
} }
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy': { case 'prerender-legacy': {
return createPrerenderRootParamPromise( return createPrerenderRootParamPromise(
paramName, paramName,
...@@ -92,6 +100,7 @@ function createPrerenderRootParamPromise( ...@@ -92,6 +100,7 @@ function createPrerenderRootParamPromise(
} }
case 'prerender': case 'prerender':
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-ppr':
default: default:
} }
...@@ -113,6 +122,22 @@ function createPrerenderRootParamPromise( ...@@ -113,6 +122,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
...@@ -125,3 +150,36 @@ function createPrerenderRootParamPromise( ...@@ -125,3 +150,36 @@ function createPrerenderRootParamPromise(
// If the param is not a fallback param, we just return the statically available value. // If the param is not a fallback param, we just return the statically available value.
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
}
}
}
...@@ -3,6 +3,7 @@ import type { WorkStore } from '../app-render/work-async-storage.external' ...@@ -3,6 +3,7 @@ import type { WorkStore } from '../app-render/work-async-storage.external'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect' import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import { import {
throwToInterruptStaticGeneration, throwToInterruptStaticGeneration,
postponeWithTracking,
annotateDynamicAccess, annotateDynamicAccess,
delayUntilRuntimeStage, delayUntilRuntimeStage,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
...@@ -10,6 +11,7 @@ import { ...@@ -10,6 +11,7 @@ import {
import { import {
workUnitAsyncStorage, workUnitAsyncStorage,
type PrerenderStoreLegacy, type PrerenderStoreLegacy,
type PrerenderStorePPR,
type PrerenderStoreModern, type PrerenderStoreModern,
type PrerenderStoreModernRuntime, type PrerenderStoreModernRuntime,
type StaticPrerenderStore, type StaticPrerenderStore,
...@@ -44,6 +46,7 @@ export function createSearchParamsFromClient( ...@@ -44,6 +46,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 'prerender-runtime': case 'prerender-runtime':
...@@ -82,6 +85,7 @@ export function createServerSearchParamsForServerPage( ...@@ -82,6 +85,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 'cache': case 'cache':
...@@ -139,6 +143,7 @@ export function createPrerenderSearchParamsForClientPage( ...@@ -139,6 +143,7 @@ export function createPrerenderSearchParamsForClientPage(
throw new InvariantError( throw new InvariantError(
'createPrerenderSearchParamsForClientPage should not be called in cache contexts.' 'createPrerenderSearchParamsForClientPage should not be called in cache contexts.'
) )
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
return Promise.resolve({}) return Promise.resolve({})
...@@ -164,6 +169,7 @@ function createStaticPrerenderSearchParams( ...@@ -164,6 +169,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.
...@@ -267,7 +273,7 @@ function makeHangingSearchParams( ...@@ -267,7 +273,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) {
...@@ -297,6 +303,13 @@ function makeErroringSearchParams( ...@@ -297,6 +303,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'
...@@ -1208,6 +1209,12 @@ function trackDynamic( ...@@ -1208,6 +1209,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
......
...@@ -87,6 +87,7 @@ export function cacheLife(profile: CacheLifeProfiles | CacheLife): void { ...@@ -87,6 +87,7 @@ export function cacheLife(profile: CacheLifeProfiles | CacheLife): void {
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-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':
......
...@@ -14,6 +14,7 @@ export function cacheTag(...tags: string[]): void { ...@@ -14,6 +14,7 @@ export function cacheTag(...tags: string[]): void {
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-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':
......
...@@ -58,6 +58,7 @@ import { getCacheHandler } from './handlers' ...@@ -58,6 +58,7 @@ import { getCacheHandler } from './handlers'
import { UseCacheTimeoutError } from './use-cache-errors' import { UseCacheTimeoutError } from './use-cache-errors'
import { import {
createHangingInputAbortSignal, createHangingInputAbortSignal,
postponeWithTracking,
throwToInterruptStaticGeneration, throwToInterruptStaticGeneration,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
import { import {
...@@ -229,6 +230,7 @@ function createUseCacheStore( ...@@ -229,6 +230,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':
break break
...@@ -362,6 +364,7 @@ function propagateCacheLifeAndTags( ...@@ -362,6 +364,7 @@ function propagateCacheLifeAndTags(
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,
...@@ -484,7 +487,8 @@ async function collectResult( ...@@ -484,7 +487,8 @@ async function collectResult(
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': {
propagateCacheLifeAndTags(cacheContext, entry) propagateCacheLifeAndTags(cacheContext, entry)
break break
} }
...@@ -560,6 +564,7 @@ async function generateCacheEntryImpl( ...@@ -560,6 +564,7 @@ async function generateCacheEntryImpl(
} }
}) })
break break
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
...@@ -701,6 +706,7 @@ async function generateCacheEntryImpl( ...@@ -701,6 +706,7 @@ async function generateCacheEntryImpl(
await new Promise((resolve) => setTimeout(resolve)) await new Promise((resolve) => setTimeout(resolve))
} }
// fallthrough // fallthrough
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -881,6 +887,12 @@ export async function cache( ...@@ -881,6 +887,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,
...@@ -940,6 +952,7 @@ export async function cache( ...@@ -940,6 +952,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 'cache': case 'cache':
...@@ -1185,6 +1198,7 @@ export async function cache( ...@@ -1185,6 +1198,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.
...@@ -1287,6 +1301,7 @@ export async function cache( ...@@ -1287,6 +1301,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':
...@@ -1335,6 +1350,7 @@ export async function cache( ...@@ -1335,6 +1350,7 @@ export async function cache(
break break
} }
case 'prerender': case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -1397,6 +1413,7 @@ export async function cache( ...@@ -1397,6 +1413,7 @@ export async function cache(
} }
break break
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
...@@ -1525,6 +1542,7 @@ export async function cache( ...@@ -1525,6 +1542,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':
...@@ -1765,6 +1783,7 @@ function shouldForceRevalidate( ...@@ -1765,6 +1783,7 @@ function shouldForceRevalidate(
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'unstable-cache': case 'unstable-cache':
break break
...@@ -1807,6 +1826,7 @@ function shouldDiscardCacheEntry( ...@@ -1807,6 +1826,7 @@ function shouldDiscardCacheEntry(
return false return false
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-client': case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
......
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,
...@@ -159,6 +162,12 @@ function revalidate( ...@@ -159,6 +162,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
......
...@@ -164,6 +164,7 @@ export function unstable_cache<T extends Callback>( ...@@ -164,6 +164,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.
...@@ -408,6 +409,7 @@ function getFetchUrlPrefix( ...@@ -408,6 +409,7 @@ function getFetchUrlPrefix(
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-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':
......
...@@ -37,6 +37,7 @@ export function unstable_noStore() { ...@@ -37,6 +37,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 { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
describe('static-shell-debugging', () => { // TODO(NAR-423): Migrate to Cache Components.
// TODO: The static shell debugging feature (__nextppronly) needs to be describe.skip('static-shell-debugging', () => {
// reimplemented for the cacheComponents architecture. The feature was const ppr = Boolean(process.env.__NEXT_CACHE_COMPONENTS)
// previously tied to the PPR render path which has been consolidated. const context = {
// For now, this test verifies the basic page rendering works correctly. ppr,
// When the feature is reimplemented, re-enable the static shell assertions. debugging: ppr,
}
const { next, skipped } = nextTestSetup({
const { next, skipped, isNextDev } = nextTestSetup({
files: __dirname, files: __dirname,
// This test skips deployment because env vars that are doubled underscore prefixed
// are not supported. This is also intended to be used in development.
skipDeployment: true, skipDeployment: true,
env: {
__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING: context.debugging
? '1'
: undefined,
},
nextConfig: {
experimental: { ppr: context.ppr },
},
}) })
if (skipped) return if (skipped) return
it('should render the full page', async () => { if (context.debugging && context.ppr) {
const res = await next.fetch('/') it('should only render the static shell', async () => {
expect(res.status).toBe(200) const res = await next.fetch('/?__nextppronly=1')
expect(res.status).toBe(200)
const html = await res.text() const html = await res.text()
expect(html).toContain('Fallback') expect(html).toContain('Fallback')
expect(html).toContain('Dynamic') expect(html).not.toContain('Dynamic')
}) })
// The __nextppronly query param is currently only supported in dev mode.
if (isNextDev) {
it('should skip hydration to avoid blanking out the page', async () => {
const browser = await next.browser('/?__nextppronly=1', {
waitHydration: false,
})
expect(await browser.elementByCss('div').text()).toBe('Fallback')
// Must not log the page error "Error: Connection closed."
expect(await browser.log()).toEqual([])
})
}
} else {
it('should render the full page', async () => {
const res = await next.fetch('/?__nextppronly=1')
expect(res.status).toBe(200)
const html = await res.text()
expect(html).toContain('Fallback')
expect(html).toContain('Dynamic')
})
}
}) })
...@@ -4,6 +4,8 @@ const { version: nextVersion } = require('next/package.json') ...@@ -4,6 +4,8 @@ const { version: nextVersion } = require('next/package.json')
const cacheComponentsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true' const cacheComponentsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true'
const pprEnabled = process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
describe('build-output-prerender', () => { describe('build-output-prerender', () => {
describe('with a next config file', () => { describe('with a next config file', () => {
describe('without --debug-prerender', () => { describe('without --debug-prerender', () => {
...@@ -30,6 +32,20 @@ describe('build-output-prerender', () => { ...@@ -30,6 +32,20 @@ describe('build-output-prerender', () => {
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)" ✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)"
`) `)
} }
} else if (pprEnabled) {
if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (Turbopack, Cache Components)
- Experiments (use with caution):
✓ ppr (enabled by \`__NEXT_EXPERIMENTAL_PPR\`)"
`)
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (webpack, Cache Components)
- Experiments (use with caution):
✓ ppr (enabled by \`__NEXT_EXPERIMENTAL_PPR\`)"
`)
}
} else { } else {
if (isTurbopack) { if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(` expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
...@@ -118,6 +134,28 @@ describe('build-output-prerender', () => { ...@@ -118,6 +134,28 @@ describe('build-output-prerender', () => {
✓ serverSourceMaps (enabled by \`--debug-prerender\`)" ✓ serverSourceMaps (enabled by \`--debug-prerender\`)"
`) `)
} }
} else if (pprEnabled) {
if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z (Turbopack, Cache Components)
- Experiments (use with caution):
✓ ppr (enabled by \`__NEXT_EXPERIMENTAL_PPR\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)
⨯ turbopackMinify (disabled by \`--debug-prerender\`)"
`)
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z (webpack, Cache Components)
- Experiments (use with caution):
✓ ppr (enabled by \`__NEXT_EXPERIMENTAL_PPR\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
⨯ serverMinification (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)"
`)
}
} else { } else {
if (isTurbopack) { if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(` expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
...@@ -240,6 +278,20 @@ describe('build-output-prerender', () => { ...@@ -240,6 +278,20 @@ describe('build-output-prerender', () => {
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)" ✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)"
`) `)
} }
} else if (pprEnabled) {
if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (Turbopack)
- Experiments (use with caution):
✓ ppr (enabled by \`__NEXT_EXPERIMENTAL_PPR\`)"
`)
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (webpack)
- Experiments (use with caution):
✓ ppr (enabled by \`__NEXT_EXPERIMENTAL_PPR\`)"
`)
}
} else { } else {
if (isTurbopack) { if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(` expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
...@@ -295,6 +347,28 @@ describe('build-output-prerender', () => { ...@@ -295,6 +347,28 @@ describe('build-output-prerender', () => {
✓ serverSourceMaps (enabled by \`--debug-prerender\`)" ✓ serverSourceMaps (enabled by \`--debug-prerender\`)"
`) `)
} }
} else if (pprEnabled) {
if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z (Turbopack)
- Experiments (use with caution):
✓ ppr (enabled by \`__NEXT_EXPERIMENTAL_PPR\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)
⨯ turbopackMinify (disabled by \`--debug-prerender\`)"
`)
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z (webpack)
- Experiments (use with caution):
✓ ppr (enabled by \`__NEXT_EXPERIMENTAL_PPR\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
⨯ serverMinification (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)"
`)
}
} else { } else {
if (isTurbopack) { if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(` expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
......
import { Suspense } from 'react'
import { connection } from 'next/server' import { connection } from 'next/server'
async function DynamicContent() { export default async function Page() {
await connection() await connection()
return <p>dynamic</p> return <p>dynamic</p>
} }
export default function Page() {
return (
<Suspense fallback={<p>Loading...</p>}>
<DynamicContent />
</Suspense>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server' import { connection } from 'next/server'
async function DynamicContent() { export default async function Page() {
await connection() await connection()
return <p>ppr</p> return <p>ppr</p>
} }
export default function Page() { export const experimental_ppr = true
return (
<Suspense fallback={<p>Loading...</p>}>
<DynamicContent />
</Suspense>
)
}
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
describe('app-dir - metadata-streaming-config-customized', () => { // TODO: the incremental option has been removed, update to use cacheComponents
describe.skip('app-dir - metadata-streaming-config-customized', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
skipDeployment: true, skipDeployment: true,
...@@ -8,7 +9,9 @@ describe('app-dir - metadata-streaming-config-customized', () => { ...@@ -8,7 +9,9 @@ describe('app-dir - metadata-streaming-config-customized', () => {
'next.config.js': ` 'next.config.js': `
module.exports = { module.exports = {
htmlLimitedBots: /MyBot/i, htmlLimitedBots: /MyBot/i,
cacheComponents: true, experimental: {
ppr: 'incremental',
}
} }
`, `,
}, },
...@@ -30,26 +33,6 @@ describe('app-dir - metadata-streaming-config-customized', () => { ...@@ -30,26 +33,6 @@ describe('app-dir - metadata-streaming-config-customized', () => {
expect(bypassConfigs).toMatchInlineSnapshot(` expect(bypassConfigs).toMatchInlineSnapshot(`
{ {
"/": {
"key": "user-agent",
"type": "header",
"value": "MyBot",
},
"/_global-error": {
"key": "user-agent",
"type": "header",
"value": "MyBot",
},
"/_not-found": {
"key": "user-agent",
"type": "header",
"value": "MyBot",
},
"/dynamic": {
"key": "user-agent",
"type": "header",
"value": "MyBot",
},
"/ppr": { "/ppr": {
"key": "user-agent", "key": "user-agent",
"type": "header", "type": "header",
......
...@@ -2,7 +2,9 @@ ...@@ -2,7 +2,9 @@
* @type {import('next').NextConfig} * @type {import('next').NextConfig}
*/ */
const nextConfig = { const nextConfig = {
cacheComponents: true, experimental: {
ppr: 'incremental',
},
} }
module.exports = nextConfig module.exports = nextConfig
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment