Unverified Commit 46681d90 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[PPF] Sync IO is only allowed in the dynamic stage (#95384)

This PR makes Sync IO behavior more restrictive when
`partialPrefetching` is on (either globally or for a page).

- Previously, we allowed `await cookies(); Date.now()` in in segments
that won't ever be runtime prefetched. This was achieved by separating
segments into "early" and "late" stages and only erroring in the "early"
ones.
- After this PR, it will always be an error to do sync IO anywhere other
than after `io()`/`connection()`/uncached IO (i.e. outside the Dynamic
stage).

We're doing this mainly because with `partialPrefetching`, `cookies()`
resolves in App Shells, and sync IO causes a severe deopt in any
prerender. `allow-runtime` also opts a route into `partialPrefetching`,
which means that even the segments above the runtime prefetch boundary
will need an App Shell and can't tolerate Sync IO.

This PR removes all early/late stage separation, because we no longer
need to vary the Sync IO behavior on the segment. Instead, we now pick
whether a stageController should use
- `SyncIOMode.AllowedInRuntimeOrDynamic` (legacy)
- `SyncIOMode.AllowedInDynamic` (`partialPrefetching`)
- `SyncIOMode.Untracked` if it needs to opt out

I've removed the existing tests that asserted that sync IO is allowed in
segments above the `allow-runtime` boundary. Instead, we check that sync
io either errors (if partialPrefetching is on) or is allowed (if
partialPrefetching is off)

Closes NAR-855
parent 3c995a87
......@@ -17,10 +17,6 @@ import type { MetadataContext } from './types/resolvers'
import { createServerSearchParamsForMetadata } from '../../server/request/search-params'
import { createServerPathnameForMetadata } from '../../server/request/pathname'
import { isPostpone } from '../../server/lib/router-utils/is-postpone'
import {
workUnitAsyncStorage,
getStagedRenderingController,
} from '../../server/app-render/work-unit-async-storage.external'
import {
MetadataBoundary,
......@@ -30,7 +26,6 @@ import {
import { getOrigin } from './generate/utils'
import { IconMark } from './generate/icon-mark'
import { FIRST_LATE_RENDER_STAGE } from '../../server/app-render/staged-rendering'
// Use a promise to share the status of the metadata resolving,
// returning two components `MetadataTree` and `MetadataOutlet`
......@@ -46,7 +41,6 @@ export function createMetadataComponents({
interpolatedParams,
errorType,
serveStreamingMetadata,
isRuntimePrefetchable,
}: {
tree: LoaderTree
pathname: string
......@@ -55,40 +49,19 @@ export function createMetadataComponents({
interpolatedParams: Params
errorType?: MetadataErrorType | 'redirect'
serveStreamingMetadata: boolean
isRuntimePrefetchable: boolean
}): {
Viewport: React.ComponentType
Metadata: React.ComponentType
MetadataOutlet: React.ComponentType
} {
const searchParams = createServerSearchParamsForMetadata(
parsedQuery,
isRuntimePrefetchable
)
const pathnameForMetadata = createServerPathnameForMetadata(
pathname,
isRuntimePrefetchable
)
const searchParams = createServerSearchParamsForMetadata(parsedQuery)
const pathnameForMetadata = createServerPathnameForMetadata(pathname)
async function Viewport() {
// Gate metadata to the correct render stage. If the page is not
// runtime-prefetchable, defer until the ShellStatic stage so that
// prefetchable segments get a head start.
if (!isRuntimePrefetchable) {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
const stagedRendering = getStagedRenderingController(workUnitStore)
if (stagedRendering) {
await stagedRendering.waitForStage(FIRST_LATE_RENDER_STAGE)
}
}
}
const tags = await getResolvedViewport(
tree,
searchParams,
interpolatedParams,
isRuntimePrefetchable,
errorType
).catch((viewportErr) => {
// When Legacy PPR is enabled viewport can reject with a Postpone type
......@@ -101,8 +74,7 @@ export function createMetadataComponents({
return getNotFoundViewport(
tree,
searchParams,
interpolatedParams,
isRuntimePrefetchable
interpolatedParams
).catch(() => null)
}
// We're going to throw the error from the metadata outlet so we just render null here instead
......@@ -122,26 +94,12 @@ export function createMetadataComponents({
}
async function Metadata() {
// Gate metadata to the correct render stage. If the page is not
// runtime-prefetchable, defer until the ShellStatic stage so that
// prefetchable segments get a head start.
if (!isRuntimePrefetchable) {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
const stagedRendering = getStagedRenderingController(workUnitStore)
if (stagedRendering) {
await stagedRendering.waitForStage(FIRST_LATE_RENDER_STAGE)
}
}
}
const tags = await getResolvedMetadata(
tree,
pathnameForMetadata,
searchParams,
interpolatedParams,
metadataContext,
isRuntimePrefetchable,
errorType
).catch((metadataErr) => {
// When Legacy PPR is enabled metadata can reject with a Postpone type
......@@ -156,8 +114,7 @@ export function createMetadataComponents({
pathnameForMetadata,
searchParams,
interpolatedParams,
metadataContext,
isRuntimePrefetchable
metadataContext
).catch(() => null)
}
// We're going to throw the error from the metadata outlet so we just render null here instead
......@@ -198,16 +155,9 @@ export function createMetadataComponents({
searchParams,
interpolatedParams,
metadataContext,
isRuntimePrefetchable,
errorType
),
getResolvedViewport(
tree,
searchParams,
interpolatedParams,
isRuntimePrefetchable,
errorType
),
getResolvedViewport(tree, searchParams, interpolatedParams, errorType),
]).then(() => null)
// TODO: We shouldn't change what we render based on whether we are streaming or not.
......@@ -238,7 +188,6 @@ async function getResolvedMetadataImpl(
searchParams: Promise<ParsedUrlQuery>,
interpolatedParams: Params,
metadataContext: MetadataContext,
isRuntimePrefetchable: boolean,
errorType?: MetadataErrorType | 'redirect'
): Promise<React.ReactNode> {
const errorConvention = errorType === 'redirect' ? undefined : errorType
......@@ -248,7 +197,6 @@ async function getResolvedMetadataImpl(
searchParams,
interpolatedParams,
metadataContext,
isRuntimePrefetchable,
errorConvention
)
}
......@@ -259,8 +207,7 @@ async function getNotFoundMetadataImpl(
pathname: Promise<string>,
searchParams: Promise<ParsedUrlQuery>,
interpolatedParams: Params,
metadataContext: MetadataContext,
isRuntimePrefetchable: boolean
metadataContext: MetadataContext
): Promise<React.ReactNode> {
const notFoundErrorConvention = 'not-found'
return renderMetadata(
......@@ -269,7 +216,6 @@ async function getNotFoundMetadataImpl(
searchParams,
interpolatedParams,
metadataContext,
isRuntimePrefetchable,
notFoundErrorConvention
)
}
......@@ -279,32 +225,23 @@ async function getResolvedViewportImpl(
tree: LoaderTree,
searchParams: Promise<ParsedUrlQuery>,
interpolatedParams: Params,
isRuntimePrefetchable: boolean,
errorType?: MetadataErrorType | 'redirect'
): Promise<React.ReactNode> {
const errorConvention = errorType === 'redirect' ? undefined : errorType
return renderViewport(
tree,
searchParams,
interpolatedParams,
isRuntimePrefetchable,
errorConvention
)
return renderViewport(tree, searchParams, interpolatedParams, errorConvention)
}
const getNotFoundViewport = cache(getNotFoundViewportImpl)
async function getNotFoundViewportImpl(
tree: LoaderTree,
searchParams: Promise<ParsedUrlQuery>,
interpolatedParams: Params,
isRuntimePrefetchable: boolean
interpolatedParams: Params
): Promise<React.ReactNode> {
const notFoundErrorConvention = 'not-found'
return renderViewport(
tree,
searchParams,
interpolatedParams,
isRuntimePrefetchable,
notFoundErrorConvention
)
}
......@@ -315,7 +252,6 @@ async function renderMetadata(
searchParams: Promise<ParsedUrlQuery>,
interpolatedParams: Params,
metadataContext: MetadataContext,
isRuntimePrefetchable: boolean,
errorConvention?: MetadataErrorType
) {
const resolvedMetadata = await resolveMetadata(
......@@ -324,8 +260,7 @@ async function renderMetadata(
searchParams,
errorConvention,
interpolatedParams,
metadataContext,
isRuntimePrefetchable
metadataContext
)
return <>{createMetadataElements(resolvedMetadata)}</>
}
......@@ -334,15 +269,13 @@ async function renderViewport(
tree: LoaderTree,
searchParams: Promise<ParsedUrlQuery>,
interpolatedParams: Params,
isRuntimePrefetchable: boolean,
errorConvention?: MetadataErrorType
) {
const resolvedViewport = await resolveViewport(
tree,
searchParams,
errorConvention,
interpolatedParams,
isRuntimePrefetchable
interpolatedParams
)
return <>{createViewportElements(resolvedViewport)}</>
}
......
......@@ -708,8 +708,7 @@ const resolveMetadataItems = cache(async function (
tree: LoaderTree,
searchParams: Promise<ParsedUrlQuery>,
errorConvention: MetadataErrorType | undefined,
interpolatedParams: Params,
isRuntimePrefetchable: boolean
interpolatedParams: Params
) {
const parentParams = {}
const metadataItems: MetadataItems = []
......@@ -724,8 +723,7 @@ const resolveMetadataItems = cache(async function (
searchParams,
errorConvention,
errorMetadataItem,
interpolatedParams,
isRuntimePrefetchable
interpolatedParams
)
})
......@@ -739,8 +737,7 @@ async function resolveMetadataItemsImpl(
searchParams: Promise<ParsedUrlQuery>,
errorConvention: MetadataErrorType | undefined,
errorMetadataItem: MetadataItems[number],
interpolatedParams: Params,
isRuntimePrefetchable: boolean
interpolatedParams: Params
): Promise<MetadataItems> {
const [segment, parallelRoutes, { page }] = tree
const currentTreePrefix =
......@@ -771,8 +768,7 @@ async function resolveMetadataItemsImpl(
const params = createServerParamsForMetadata(
currentParams,
optionalCatchAllParamName,
isRuntimePrefetchable
optionalCatchAllParamName
)
const props: SegmentProps = isPage ? { params, searchParams } : { params }
......@@ -799,8 +795,7 @@ async function resolveMetadataItemsImpl(
searchParams,
errorConvention,
errorMetadataItem,
interpolatedParams,
isRuntimePrefetchable
interpolatedParams
)
}
......@@ -818,8 +813,7 @@ const resolveViewportItems = cache(async function (
tree: LoaderTree,
searchParams: Promise<ParsedUrlQuery>,
errorConvention: MetadataErrorType | undefined,
interpolatedParams: Params,
isRuntimePrefetchable: boolean
interpolatedParams: Params
) {
const parentParams = {}
const viewportItems: ViewportItems = []
......@@ -836,8 +830,7 @@ const resolveViewportItems = cache(async function (
searchParams,
errorConvention,
errorViewportItemRef,
interpolatedParams,
isRuntimePrefetchable
interpolatedParams
)
})
......@@ -851,8 +844,7 @@ async function resolveViewportItemsImpl(
searchParams: Promise<ParsedUrlQuery>,
errorConvention: MetadataErrorType | undefined,
errorViewportItemRef: ErrorViewportItemRef,
interpolatedParams: Params,
isRuntimePrefetchable: boolean
interpolatedParams: Params
): Promise<ViewportItems> {
const [segment, parallelRoutes, { page }] = tree
const currentTreePrefix =
......@@ -883,8 +875,7 @@ async function resolveViewportItemsImpl(
const params = createServerParamsForMetadata(
currentParams,
optionalCatchAllParamName,
isRuntimePrefetchable
optionalCatchAllParamName
)
let layerProps: LayoutProps | PageProps
......@@ -922,8 +913,7 @@ async function resolveViewportItemsImpl(
searchParams,
errorConvention,
errorViewportItemRef,
interpolatedParams,
isRuntimePrefetchable
interpolatedParams
)
}
......@@ -1292,15 +1282,13 @@ export async function resolveMetadata(
searchParams: Promise<ParsedUrlQuery>,
errorConvention: MetadataErrorType | undefined,
interpolatedParams: Params,
metadataContext: MetadataContext,
isRuntimePrefetchable: boolean
metadataContext: MetadataContext
): Promise<ResolvedMetadata> {
const metadataItems = await resolveMetadataItems(
tree,
searchParams,
errorConvention,
interpolatedParams,
isRuntimePrefetchable
interpolatedParams
)
const workStore = workAsyncStorage.getStore()
if (!workStore) {
......@@ -1319,15 +1307,13 @@ export async function resolveViewport(
tree: LoaderTree,
searchParams: Promise<ParsedUrlQuery>,
errorConvention: MetadataErrorType | undefined,
interpolatedParams: Params,
isRuntimePrefetchable: boolean
interpolatedParams: Params
): Promise<ResolvedViewport> {
const viewportItems = await resolveViewportItems(
tree,
searchParams,
errorConvention,
interpolatedParams,
isRuntimePrefetchable
interpolatedParams
)
return accumulateViewport(viewportItems)
}
......
......@@ -40,11 +40,6 @@ import {
getConventionPathByType,
isNextjsBuiltinFilePath,
} from './segment-explorer-path'
import type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config'
import {
FIRST_LATE_RENDER_STAGE,
type StagedRenderingController,
} from './staged-rendering'
/**
* Use the provided loader tree to create the React Component tree.
......@@ -91,7 +86,6 @@ async function createComponentTreeInternal(
loaderTree: tree,
parentParams,
parentOptionalCatchAllParamName,
parentRuntimePrefetchable,
rootLayoutIncluded,
injectedCSS,
injectedJS,
......@@ -105,7 +99,6 @@ async function createComponentTreeInternal(
loaderTree: LoaderTree
parentParams: Params
parentOptionalCatchAllParamName: string | null
parentRuntimePrefetchable: boolean
rootLayoutIncluded: boolean
injectedCSS: Set<string>
injectedJS: Set<string>
......@@ -235,12 +228,6 @@ async function createComponentTreeInternal(
})
: []
const prefetchConfig = layoutOrPageMod
? (layoutOrPageMod as AppSegmentConfig).prefetch
: undefined
const hasRuntimePrefetch = prefetchConfig === 'allow-runtime'
const isRuntimePrefetchable = hasRuntimePrefetch || parentRuntimePrefetchable
const [Forbidden, forbiddenStyles] =
authInterrupts && forbidden
? await createComponentStylesAndScripts({
......@@ -600,7 +587,6 @@ async function createComponentTreeInternal(
loaderTree: parallelRoute,
parentParams: currentParams,
parentOptionalCatchAllParamName: optionalCatchAllParamName,
parentRuntimePrefetchable: isRuntimePrefetchable,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
......@@ -762,7 +748,6 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData,
loadingData,
isPossiblyPartialResponse,
isRuntimePrefetchable,
// No user-provided component, so no params will be accessed. Use the
// pre-resolved empty tracker.
......@@ -803,7 +788,6 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData,
loadingData,
true,
isRuntimePrefetchable,
// force-dynamic postpones without rendering the component, so no params
// are accessed. The vary params are empty.
......@@ -870,8 +854,7 @@ async function createComponentTreeInternal(
const params = createServerParamsForServerSegment(
currentParams,
optionalCatchAllParamName,
varyParamsAccumulator,
isRuntimePrefetchable
varyParamsAccumulator
)
// If we are passing searchParams to a server component Page we need to
......@@ -879,8 +862,7 @@ async function createComponentTreeInternal(
// usage.
let searchParams = createServerSearchParamsForServerPage(
query,
varyParamsAccumulator,
isRuntimePrefetchable
varyParamsAccumulator
)
if (isUseCacheFunction(PageComponent)) {
......@@ -932,7 +914,6 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData,
loadingData,
isPossiblyPartialResponse,
isRuntimePrefetchable,
varyParamsAccumulator
)
......@@ -1053,8 +1034,7 @@ async function createComponentTreeInternal(
const params = createServerParamsForServerSegment(
currentParams,
optionalCatchAllParamName,
varyParamsAccumulator,
isRuntimePrefetchable
varyParamsAccumulator
)
let serverSegment: React.ReactNode
......@@ -1149,8 +1129,6 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData,
loadingData,
isPossiblyPartialResponse,
isRuntimePrefetchable,
varyParamsAccumulator
)
}
......@@ -1302,48 +1280,9 @@ function createSeedData(
parallelRoutes: Record<string, CacheNodeSeedData | null>,
loading: LoadingModuleData | null,
isPossiblyPartialResponse: boolean,
isRuntimePrefetchable: boolean,
varyParamsAccumulator: VaryParamsAccumulator | null
): CacheNodeSeedData {
const createElement = ctx.componentMod.createElement
// When this segment is NOT runtime-prefetchable, delay it until the ShellStatic
// stage (i.e. the first late stage) by wrapping the node in a promise.
// This allows runtime-prefetchable segments (the lower tree) to render first
// during ShellEarlyStatic, so their runtime data resolves in ShellEarlyRuntime
// where sync IO can be checked. React will suspend on the thenable and resume
// when the stage advances.
if (!isRuntimePrefetchable) {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
let stagedRendering: StagedRenderingController | null | undefined
switch (workUnitStore.type) {
case 'request':
case 'prerender-runtime':
stagedRendering = workUnitStore.stagedRendering
if (stagedRendering) {
const deferredRsc = rsc
rsc = stagedRendering
.waitForStage(FIRST_LATE_RENDER_STAGE)
.then(() => deferredRsc)
}
break
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
}
}
}
if (loading !== null) {
// If a loading.tsx boundary is present, wrap the component data in an
// additional context provider to pass the loading data to the next
......
......@@ -228,7 +228,6 @@ export async function collectStagedSegmentData(
fullPageChunks: StageChunks,
fullPageDebugChunks: Uint8Array[] | null,
startTime: number,
hasRuntimePrefetch: boolean,
clientReferenceManifest: ClientReferenceManifest,
createDebugChannel: () => DebugChannelPair | undefined
) {
......@@ -256,7 +255,7 @@ export async function collectStagedSegmentData(
return 'Prerender'
case RenderStage.ShellRuntime: // TODO(app-shells) - proper environmentName
case RenderStage.Runtime:
return hasRuntimePrefetch ? 'Prefetch' : 'Prefetchable'
return 'Prefetch'
case RenderStage.Dynamic:
return 'Server'
default:
......
......@@ -4,14 +4,10 @@ import { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolv
export enum RenderStage {
Before = 1,
//
ShellEarlyStatic = 10,
ShellStatic = 11,
EarlyStatic = 12,
Static = 13,
//
ShellEarlyRuntime = 20,
ShellRuntime = 21,
EarlyRuntime = 22,
Runtime = 23,
//
Dynamic = 30,
......@@ -25,21 +21,15 @@ export type AdvanceableRenderStage = Exclude<
>
export const RENDER_STAGE_ADVANCE_ORDER: AdvanceableRenderStage[] = [
RenderStage.ShellEarlyStatic,
RenderStage.ShellStatic,
RenderStage.EarlyStatic,
RenderStage.Static,
//
RenderStage.ShellEarlyRuntime,
RenderStage.ShellRuntime,
RenderStage.EarlyRuntime,
RenderStage.Runtime,
//
RenderStage.Dynamic,
]
export const FIRST_LATE_RENDER_STAGE = RenderStage.ShellStatic
export function getNextStage(
stage: Exclude<AdvanceableRenderStage, RenderStage.Dynamic>
) {
......@@ -54,37 +44,19 @@ export function isAdvanceableRenderStage(
return RenderStage.Before < stage && stage <= RenderStage.Dynamic
}
export function isEarlyRenderStage(
stage: Exclude<RenderStage, RenderStage.Before>
): boolean {
switch (stage) {
case RenderStage.ShellEarlyStatic:
case RenderStage.EarlyStatic:
case RenderStage.ShellEarlyRuntime:
case RenderStage.EarlyRuntime: {
return true
}
case RenderStage.ShellStatic:
case RenderStage.Static:
case RenderStage.ShellRuntime:
case RenderStage.Runtime: {
return false
}
case RenderStage.Dynamic:
case RenderStage.Abandoned: {
return false
}
default: {
stage satisfies never
throw new InvariantError(`Invalid render stage: ${stage}`)
}
}
export enum SyncIOMode {
/** Sync IO does not error in any stage. */
Untracked = 1,
/** Before `partialPrefetching`: Sync IO errors in static stages, and is allowed otherwise. */
AllowedInRuntimeOrDynamic = 2,
/** After `partialPrefetching`: Sync IO errors in all stages other than dynamic. */
AllowedInDynamic = 3,
}
export class StagedRenderingController {
private abortSignal: AbortSignal | null
private abandonController: AbortController | null
private shouldTrackSyncIO: boolean
private syncIOMode: SyncIOMode
public readonly finalStage: AdvanceableRenderStage | null
currentStage: RenderStage = RenderStage.Before
......@@ -92,14 +64,10 @@ export class StagedRenderingController {
syncInterruptReason: Error | null = null
triggers: Record<AdvanceableRenderStage, StageTrigger> = {
[RenderStage.ShellEarlyStatic]: createStageTrigger(),
[RenderStage.ShellStatic]: createStageTrigger(),
[RenderStage.EarlyStatic]: createStageTrigger(),
[RenderStage.Static]: createStageTrigger(),
//
[RenderStage.ShellEarlyRuntime]: createStageTrigger(),
[RenderStage.ShellRuntime]: createStageTrigger(),
[RenderStage.EarlyRuntime]: createStageTrigger(),
[RenderStage.Runtime]: createStageTrigger(),
//
[RenderStage.Dynamic]: createStageTrigger(),
......@@ -108,17 +76,17 @@ export class StagedRenderingController {
constructor({
abortSignal,
abandonController,
shouldTrackSyncIO,
syncIO,
finalStage,
}: {
abortSignal: AbortSignal | null
abandonController: AbortController | null
shouldTrackSyncIO: boolean
syncIO: SyncIOMode
finalStage: AdvanceableRenderStage | null
}) {
this.abortSignal = abortSignal
this.abandonController = abandonController
this.shouldTrackSyncIO = shouldTrackSyncIO
this.syncIOMode = syncIO
this.finalStage = finalStage
if (abortSignal) {
......@@ -152,7 +120,7 @@ export class StagedRenderingController {
}
shouldTrackSyncInterrupt(): boolean {
if (!this.shouldTrackSyncIO) {
if (this.syncIOMode === SyncIOMode.Untracked) {
return false
}
......@@ -160,21 +128,22 @@ export class StagedRenderingController {
case RenderStage.Before:
// If we haven't started the render yet, it can't be interrupted.
return false
case RenderStage.ShellEarlyStatic:
case RenderStage.ShellStatic:
case RenderStage.EarlyStatic:
case RenderStage.Static:
return true
case RenderStage.ShellEarlyRuntime:
case RenderStage.EarlyRuntime:
// EarlyRuntime is for runtime-prefetchable segments. Sync IO
// should error because it would abort a runtime prefetch.
return true
case RenderStage.ShellRuntime:
case RenderStage.Runtime:
// Runtime is for non-prefetchable segments. Sync IO is fine there
// because in practice this segment will never be runtime prefetched
return false
case RenderStage.Runtime: {
switch (this.syncIOMode) {
case SyncIOMode.AllowedInRuntimeOrDynamic: {
// Before `partialPrefetching`: Sync IO only errors in static stages.
return false
}
case SyncIOMode.AllowedInDynamic: {
return true
}
}
// NOT a fallthrough, but eslint doesn't understand that
}
case RenderStage.Dynamic:
case RenderStage.Abandoned:
return false
......
......@@ -21,7 +21,6 @@ import type { WorkStore } from './work-async-storage.external'
import { NEXT_HMR_REFRESH_HASH_COOKIE } from '../../client/components/app-router-headers'
import { InvariantError } from '../../shared/lib/invariant-error'
import type { StagedRenderingController } from './staged-rendering'
import { isEarlyRenderStage, RenderStage } from './staged-rendering'
import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'
import type { InstantValidationSampleTracking } from './instant-validation/instant-samples'
......@@ -103,49 +102,14 @@ export type InstantValidationSamples = {
export type AsyncApiPromises = {
cookies: Promise<ReadonlyRequestCookies>
earlyCookies: Promise<ReadonlyRequestCookies>
mutableCookies: Promise<ReadonlyRequestCookies>
earlyMutableCookies: Promise<ReadonlyRequestCookies>
headers: Promise<ReadonlyHeaders>
earlyHeaders: Promise<ReadonlyHeaders>
sharedParamsParent: Promise<string>
earlySharedParamsParent: Promise<string>
sharedSearchParamsParent: Promise<string>
earlySharedSearchParamsParent: Promise<string>
// Connection is not a runtime promise and doesn't
// need to distinguish between early and late
connection: Promise<undefined>
// IO is not a runtime promise and doesn't
// need to distinguish between early and late
io: Promise<undefined>
}
/**
* Returns true if the current render stage is an early stage (EarlyStatic or
* EarlyRuntime). The early stages are for runtime-prefetchable segments. When
* true, runtime APIs should use the early promise variant that resolves at
* EarlyRuntime rather than Runtime.
*/
export function isInEarlyRenderStage(requestStore: RequestStore): boolean {
const stagedRendering = requestStore.stagedRendering
if (stagedRendering) {
const { currentStage } = stagedRendering
if (currentStage === RenderStage.Before) {
throw new InvariantError(
'Cannot determine late/early stage before starting the render'
)
}
return isEarlyRenderStage(currentStage)
}
return false
}
/**
* The Prerender store is for tracking information related to prerenders.
*
......
import { InvariantError } from '../shared/lib/invariant-error'
import {
isEarlyRenderStage,
RenderStage,
type AdvanceableRenderStage,
type StagedRenderingController,
} from './app-render/staged-rendering'
import type { RequestStore } from './app-render/work-unit-async-storage.external'
import { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'
......@@ -165,66 +162,9 @@ export function makeDevtoolsIOAwarePromise<T>(
}
export const RENDER_STAGES_BY_DATA_KIND = {
// NOTE: keep in sync with getSessionDataStage
sessionData: {
early: RenderStage.ShellEarlyRuntime as const,
late: RenderStage.ShellRuntime as const,
},
// NOTE: keep in sync with getStaticLinkDataStage
staticLinkData: {
early: RenderStage.EarlyStatic as const,
late: RenderStage.Static as const,
},
// NOTE: keep in sync with getRuntimeLinkDataStage
runtimeLinkData: {
early: RenderStage.EarlyRuntime as const,
late: RenderStage.Runtime as const,
},
}
export function getSessionDataStage(
stagedRendering: StagedRenderingController
) {
const { currentStage } = stagedRendering
if (currentStage === RenderStage.Before) {
throw new InvariantError(
'Cannot determine late/early stage before starting the render'
)
}
// NOTE: keep in sync with RENDER_STAGES_BY_DATA_KIND
return isEarlyRenderStage(currentStage)
? RenderStage.ShellEarlyRuntime
: RenderStage.ShellRuntime
}
export function getStaticLinkDataStage(
stagedRendering: StagedRenderingController
) {
const { currentStage } = stagedRendering
if (currentStage === RenderStage.Before) {
throw new InvariantError(
'Cannot determine late/early stage before starting the render'
)
}
// NOTE: keep in sync with RENDER_STAGES_BY_DATA_KIND
return isEarlyRenderStage(currentStage)
? RenderStage.EarlyStatic
: RenderStage.Static
}
export function getRuntimeLinkDataStage(
stagedRendering: StagedRenderingController
) {
const { currentStage } = stagedRendering
if (currentStage === RenderStage.Before) {
throw new InvariantError(
'Cannot determine late/early stage before starting the render'
)
}
// NOTE: keep in sync with RENDER_STAGES_BY_DATA_KIND
return isEarlyRenderStage(currentStage)
? RenderStage.EarlyRuntime
: RenderStage.Runtime
sessionData: RenderStage.ShellRuntime as const,
staticLinkData: RenderStage.Static as const,
runtimeLinkData: RenderStage.Runtime as const,
}
export function applyOwnerStack(error: Error): Error {
......
......@@ -60,17 +60,15 @@ export function io(expression: string, type: SyncIOApiType) {
// NOTE: keep stages where we can interrupt in sync with
// `shouldTrackSyncInterrupt`/`syncInterruptCurrentStageWithReason`
switch (stageController.currentStage) {
case RenderStage.ShellEarlyStatic:
case RenderStage.ShellStatic:
case RenderStage.EarlyStatic:
case RenderStage.Static: {
syncIOError = createSyncIOError(workStore.route, expression, type)
break
}
case RenderStage.ShellEarlyRuntime:
case RenderStage.EarlyRuntime: {
// We only error for Sync IO in the Runtime stage if the segment has a runtime prefetch config.
// Only Runtime prefetchable segments are rendered in the "early" runtime stages.
case RenderStage.ShellRuntime:
case RenderStage.Runtime: {
// We're in the Runtime stage.
// We only error for Sync IO in the Runtime stage if the route has partialPrefetching enabled.
syncIOError = createSyncIORuntimeError(
workStore.route,
expression,
......@@ -79,8 +77,6 @@ export function io(expression: string, type: SyncIOApiType) {
break
}
case RenderStage.Before:
case RenderStage.ShellRuntime:
case RenderStage.Runtime:
case RenderStage.Dynamic:
case RenderStage.Abandoned: {
throw new InvariantError(
......
......@@ -13,7 +13,6 @@ import {
workUnitAsyncStorage,
type PrerenderStoreModern,
type RequestStore,
isInEarlyRenderStage,
} from '../app-render/work-unit-async-storage.external'
import {
postponeWithTracking,
......@@ -24,13 +23,12 @@ import { StaticGenBailoutError } from '../../client/components/static-generation
import {
makeDevtoolsIOAwarePromise,
makeHangingPromise,
getSessionDataStage,
RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import { isRequestApiAllowedInCurrentPhase } from './utils'
import { applyOwnerStack } from '../dynamic-rendering-utils'
import { InvariantError } from '../../shared/lib/invariant-error'
import { RenderStage } from '../app-render/staged-rendering'
export function cookies(): Promise<ReadonlyRequestCookies> {
const callingExpression = 'cookies'
......@@ -103,7 +101,7 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
const { stagedRendering } = workUnitStore
if (stagedRendering) {
return stagedRendering.delayUntilStage(
getSessionDataStage(stagedRendering),
RENDER_STAGES_BY_DATA_KIND.sessionData,
'cookies',
workUnitStore.cookies
)
......@@ -139,15 +137,10 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
workStore?.route
)
} else if (workUnitStore.asyncApiPromises) {
const early = isInEarlyRenderStage(workUnitStore)
if (underlyingCookies === workUnitStore.mutableCookies) {
return early
? workUnitStore.asyncApiPromises.earlyMutableCookies
: workUnitStore.asyncApiPromises.mutableCookies
return workUnitStore.asyncApiPromises.mutableCookies
} else {
return early
? workUnitStore.asyncApiPromises.earlyCookies
: workUnitStore.asyncApiPromises.cookies
return workUnitStore.asyncApiPromises.cookies
}
} else {
return makeUntrackedCookies(underlyingCookies)
......@@ -211,16 +204,11 @@ function makeUntrackedCookiesWithDevWarnings(
route?: string
): Promise<ReadonlyRequestCookies> {
if (requestStore.asyncApiPromises) {
const early = isInEarlyRenderStage(requestStore)
let promise: Promise<ReadonlyRequestCookies>
if (underlyingCookies === requestStore.mutableCookies) {
promise = early
? requestStore.asyncApiPromises.earlyMutableCookies
: requestStore.asyncApiPromises.mutableCookies
promise = requestStore.asyncApiPromises.mutableCookies
} else if (underlyingCookies === requestStore.cookies) {
promise = early
? requestStore.asyncApiPromises.earlyCookies
: requestStore.asyncApiPromises.cookies
promise = requestStore.asyncApiPromises.cookies
} else {
throw new InvariantError(
'Received an underlying cookies object that does not match either `cookies` or `mutableCookies`'
......@@ -237,7 +225,7 @@ function makeUntrackedCookiesWithDevWarnings(
const promise = makeDevtoolsIOAwarePromise(
underlyingCookies,
requestStore,
RenderStage.ShellRuntime
RENDER_STAGES_BY_DATA_KIND.sessionData
)
const proxiedPromise = instrumentCookiesPromiseWithDevWarnings(promise, route)
......
......@@ -22,7 +22,7 @@ import { InvariantError } from '../../shared/lib/invariant-error'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import {
applyOwnerStack,
getSessionDataStage,
RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils'
export function draftMode(): Promise<DraftMode> {
......@@ -40,7 +40,7 @@ export function draftMode(): Promise<DraftMode> {
const { stagedRendering } = workUnitStore
if (stagedRendering) {
return stagedRendering.delayUntilStage(
getSessionDataStage(stagedRendering),
RENDER_STAGES_BY_DATA_KIND.sessionData,
'draftMode',
new DraftMode(workUnitStore.draftMode)
)
......
......@@ -11,7 +11,6 @@ import {
workUnitAsyncStorage,
type PrerenderStoreModern,
type RequestStore,
isInEarlyRenderStage,
} from '../app-render/work-unit-async-storage.external'
import {
postponeWithTracking,
......@@ -22,13 +21,12 @@ import { StaticGenBailoutError } from '../../client/components/static-generation
import {
makeDevtoolsIOAwarePromise,
makeHangingPromise,
getSessionDataStage,
RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import { isRequestApiAllowedInCurrentPhase } from './utils'
import { applyOwnerStack } from '../dynamic-rendering-utils'
import { InvariantError } from '../../shared/lib/invariant-error'
import { RenderStage } from '../app-render/staged-rendering'
/**
* This function allows you to read the HTTP incoming request headers in
......@@ -131,7 +129,7 @@ export function headers(): Promise<ReadonlyHeaders> {
const { stagedRendering } = workUnitStore
if (stagedRendering) {
return stagedRendering.delayUntilStage(
getSessionDataStage(stagedRendering),
RENDER_STAGES_BY_DATA_KIND.sessionData,
'headers',
workUnitStore.headers
)
......@@ -156,9 +154,7 @@ export function headers(): Promise<ReadonlyHeaders> {
workUnitStore
)
} else if (workUnitStore.asyncApiPromises) {
return isInEarlyRenderStage(workUnitStore)
? workUnitStore.asyncApiPromises.earlyHeaders
: workUnitStore.asyncApiPromises.headers
return workUnitStore.asyncApiPromises.headers
} else {
return makeUntrackedHeaders(workUnitStore.headers)
}
......@@ -215,10 +211,10 @@ function makeUntrackedHeadersWithDevWarnings(
requestStore: RequestStore
): Promise<ReadonlyHeaders> {
if (requestStore.asyncApiPromises) {
const promise = isInEarlyRenderStage(requestStore)
? requestStore.asyncApiPromises.earlyHeaders
: requestStore.asyncApiPromises.headers
return instrumentHeadersPromiseWithDevWarnings(promise, route)
return instrumentHeadersPromiseWithDevWarnings(
requestStore.asyncApiPromises.headers,
route
)
}
const cachedHeaders = CachedHeaders.get(underlyingHeaders)
......@@ -229,7 +225,7 @@ function makeUntrackedHeadersWithDevWarnings(
const promise = makeDevtoolsIOAwarePromise(
underlyingHeaders,
requestStore,
RenderStage.Runtime
RENDER_STAGES_BY_DATA_KIND.sessionData
)
const proxiedPromise = instrumentHeadersPromiseWithDevWarnings(promise, route)
......
......@@ -39,7 +39,6 @@ import {
} from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'
import { RenderStage } from '../app-render/staged-rendering'
import {
isEmptyParams,
hasFallbackRouteParams,
......@@ -131,15 +130,13 @@ export function createParamsFromClient(
export type CreateServerParamsForMetadata = typeof createServerParamsForMetadata
export function createServerParamsForMetadata(
underlyingParams: Params,
optionalCatchAllParamName: string | null,
isRuntimePrefetchable: boolean
optionalCatchAllParamName: string | null
): Promise<Params> {
const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()
return createServerParamsForServerSegment(
underlyingParams,
optionalCatchAllParamName,
metadataVaryParamsAccumulator,
isRuntimePrefetchable
metadataVaryParamsAccumulator
)
}
......@@ -209,8 +206,7 @@ export function createServerParamsForRoute(
export function createServerParamsForServerSegment(
underlyingParams: Params,
optionalCatchAllParamName: string | null,
varyParamsAccumulator: VaryParamsAccumulator | null,
isRuntimePrefetchable: boolean
varyParamsAccumulator: VaryParamsAccumulator | null
): Promise<Params> {
const workStore = workAsyncStorage.getStore()
if (!workStore) {
......@@ -249,8 +245,7 @@ export function createServerParamsForServerSegment(
underlyingParams,
optionalCatchAllParamName,
workUnitStore,
varyParamsAccumulator,
isRuntimePrefetchable
varyParamsAccumulator
)
case 'request': {
return createRenderParamsForPage(
......@@ -258,8 +253,7 @@ export function createServerParamsForServerSegment(
workUnitStore,
underlyingParams,
optionalCatchAllParamName,
varyParamsAccumulator,
isRuntimePrefetchable
varyParamsAccumulator
)
}
default:
......@@ -371,9 +365,9 @@ function createStaticPrerenderParams(
if (
!allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)
) {
const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.staticLinkData
return stagedRendering.delayUntilStage(
// static prerenders don't distinguish early/late, this is just for consistency.
RENDER_STAGES_BY_DATA_KIND.staticLinkData.late,
staticParamsStage,
'params',
userspaceParams
)
......@@ -438,8 +432,7 @@ function createRuntimePrerenderParams(
underlyingParams: Params,
optionalCatchAllParamName: string | null,
workUnitStore: PrerenderStoreModernRuntime,
varyParamsAccumulator: VaryParamsAccumulator | null,
isRuntimePrefetchable: boolean
varyParamsAccumulator: VaryParamsAccumulator | null
): Promise<Params> {
let userspaceParams = underlyingParams
if (varyParamsAccumulator !== null) {
......@@ -474,9 +467,12 @@ function createRuntimePrerenderParams(
// Semantically, we should resolve static params in the static stage.
// But params are link data, and we need to recover a param-less session shell,
// so we delay all params until the runtime stage instead.
const paramsStages = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
const stage = isRuntimePrefetchable ? paramsStages.early : paramsStages.late
return stagedRendering.delayUntilStage(stage, 'params', userspaceParams)
const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
return stagedRendering.delayUntilStage(
staticParamsStage,
'params',
userspaceParams
)
}
function createRenderParamsForPage(
......@@ -484,8 +480,7 @@ function createRenderParamsForPage(
workUnitStore: RequestStore,
underlyingParams: Params,
optionalCatchAllParamName: string | null,
varyParamsAccumulator: VaryParamsAccumulator | null,
isRuntimePrefetchable: boolean
varyParamsAccumulator: VaryParamsAccumulator | null
) {
const { stagedRendering, asyncApiPromises, validationSamples } = workUnitStore
......@@ -516,8 +511,7 @@ function createRenderParamsForPage(
stagedRendering,
asyncApiPromises,
underlyingParams,
userspaceParams,
isRuntimePrefetchable
userspaceParams
)
}
......@@ -542,16 +536,14 @@ function createStagedRenderParams(
stagedRendering: NonNullable<RequestStore['stagedRendering']>,
asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,
underlyingParams: Params,
userspaceParams: Params,
isRuntimePrefetchable: boolean
userspaceParams: Params
) {
const promise = createStagedRenderParamsImpl(
workUnitStore,
stagedRendering,
asyncApiPromises,
underlyingParams,
userspaceParams,
isRuntimePrefetchable
userspaceParams
)
if (process.env.NODE_ENV === 'development') {
return instrumentParamsPromiseWithDevWarnings(
......@@ -571,8 +563,7 @@ function createStagedRenderParamsImpl(
/** The actual param values, without any instrumentation */
underlyingParams: Params,
/** The params object to return to userspace, possibly wrapped in a proxy */
userspaceParams: Params,
isRuntimePrefetchable: boolean
userspaceParams: Params
) {
// If the route has no params, they should resolve immediately.
if (isEmptyParams(underlyingParams)) {
......@@ -583,9 +574,7 @@ function createStagedRenderParamsImpl(
// We do this indirectly via the shared params parent for better debug info.
if (hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)) {
return createParamsPromiseFromTrigger(
isRuntimePrefetchable
? asyncApiPromises.earlySharedParamsParent
: asyncApiPromises.sharedParamsParent,
asyncApiPromises.sharedParamsParent,
userspaceParams
)
}
......@@ -603,13 +592,14 @@ function createStagedRenderParamsImpl(
// shells are handled with a separate render.
// However, in dev we might need to recover a session shell for instant validation.
// This is indicated by `needsSessionShell`.
const staticParamsStages = workUnitStore.needsSessionShell
const staticParamsStage = workUnitStore.needsSessionShell
? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
: RENDER_STAGES_BY_DATA_KIND.staticLinkData
const stage = isRuntimePrefetchable
? staticParamsStages.early
: staticParamsStages.late
return stagedRendering.delayUntilStage(stage, 'params', userspaceParams)
return stagedRendering.delayUntilStage(
staticParamsStage,
'params',
userspaceParams
)
}
return makeUntrackedParams(userspaceParams)
......@@ -833,7 +823,7 @@ function makeDynamicallyTrackedParamsWithDevWarnings(
? makeDevtoolsIOAwarePromise(
userspaceParams,
requestStore,
RenderStage.Runtime
RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
)
: // We don't want to force an environment transition when this params is not part of the fallback params set
Promise.resolve(userspaceParams)
......
......@@ -22,8 +22,7 @@ import {
import { InvariantError } from '../../shared/lib/invariant-error'
export function createServerPathnameForMetadata(
underlyingPathname: string,
isRuntimePrefetchable: boolean
underlyingPathname: string
): Promise<string> {
const workStore = workAsyncStorage.getStore()
if (!workStore) {
......@@ -65,12 +64,9 @@ export function createServerPathnameForMetadata(
// (i.e. assuming that we have non-static params in the pathname)
const { stagedRendering } = workUnitStore
if (stagedRendering) {
const pathnameStages = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
const stage = isRuntimePrefetchable
? pathnameStages.early
: pathnameStages.late
const pathnameStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
return stagedRendering.delayUntilStage(
stage,
pathnameStage,
undefined,
underlyingPathname
)
......
......@@ -43,7 +43,6 @@ import {
throwWithStaticGenerationBailoutErrorWithDynamicError,
throwForSearchParamsAccessInUseCache,
} from './utils'
import { RenderStage } from '../app-render/staged-rendering'
export type SearchParams = { [key: string]: string | string[] | undefined }
......@@ -87,13 +86,10 @@ export function createSearchParamsFromClient(
return makeUntrackedSearchParams(underlyingSearchParams)
}
case 'request':
// Client searchParams are not runtime prefetchable
const isRuntimePrefetchable = false
return createRenderSearchParams(
underlyingSearchParams,
workStore,
workUnitStore,
isRuntimePrefetchable
workUnitStore
)
default:
workUnitStore satisfies never
......@@ -104,21 +100,18 @@ export function createSearchParamsFromClient(
// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component
export function createServerSearchParamsForMetadata(
underlyingSearchParams: SearchParams,
isRuntimePrefetchable: boolean
underlyingSearchParams: SearchParams
): Promise<SearchParams> {
const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()
return createServerSearchParamsForServerPage(
underlyingSearchParams,
metadataVaryParamsAccumulator,
isRuntimePrefetchable
metadataVaryParamsAccumulator
)
}
export function createServerSearchParamsForServerPage(
underlyingSearchParams: SearchParams,
varyParamsAccumulator: VaryParamsAccumulator | null,
isRuntimePrefetchable: boolean
varyParamsAccumulator: VaryParamsAccumulator | null
): Promise<SearchParams> {
const workStore = workAsyncStorage.getStore()
if (!workStore) {
......@@ -150,15 +143,13 @@ export function createServerSearchParamsForServerPage(
return createRuntimePrerenderSearchParams(
underlyingSearchParams,
workUnitStore,
varyParamsAccumulator,
isRuntimePrefetchable
varyParamsAccumulator
)
case 'request':
return createRenderSearchParams(
underlyingSearchParams,
workStore,
workUnitStore,
isRuntimePrefetchable
workUnitStore
)
default:
workUnitStore satisfies never
......@@ -247,8 +238,7 @@ function createStaticPrerenderSearchParams(
function createRuntimePrerenderSearchParams(
underlyingSearchParams: SearchParams,
workUnitStore: PrerenderStoreModernRuntime,
varyParamsAccumulator: VaryParamsAccumulator | null,
isRuntimePrefetchable: boolean
varyParamsAccumulator: VaryParamsAccumulator | null
): Promise<SearchParams> {
const underlyingSearchParamsWithVarying =
varyParamsAccumulator !== null
......@@ -260,18 +250,14 @@ function createRuntimePrerenderSearchParams(
if (!stagedRendering) {
return result
}
const searchParamsStages = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
const stage = isRuntimePrefetchable
? searchParamsStages.early
: searchParamsStages.late
return stagedRendering.waitForStage(stage).then(() => result)
const searchParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
return stagedRendering.waitForStage(searchParamsStage).then(() => result)
}
function createRenderSearchParams(
underlyingSearchParams: SearchParams,
workStore: WorkStore,
requestStore: RequestStore,
isRuntimePrefetchable: boolean
requestStore: RequestStore
): Promise<SearchParams> {
const { asyncApiPromises, validationSamples } = requestStore
......@@ -288,7 +274,6 @@ function createRenderSearchParams(
return createStagedRenderSearchParams(
workStore,
asyncApiPromises,
isRuntimePrefetchable,
underlyingSearchParams,
userspaceSearchParams
)
......@@ -319,13 +304,10 @@ function createRenderSearchParams(
function createStagedRenderSearchParams(
workStore: WorkStore,
asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,
isRuntimePrefetchable: boolean,
underlyingSearchParams: SearchParams,
userspaceSearchParams: SearchParams
): Promise<SearchParams> {
const trigger = isRuntimePrefetchable
? asyncApiPromises.earlySharedSearchParamsParent
: asyncApiPromises.sharedSearchParamsParent
const trigger = asyncApiPromises.sharedSearchParamsParent
if (process.env.NODE_ENV === 'development') {
// We wrap each instance of searchParams in a `new Promise()`.
......@@ -567,7 +549,7 @@ function makeUntrackedSearchParamsWithDevWarningsImpl(
const promise = makeDevtoolsIOAwarePromise(
proxiedUnderlying,
requestStore,
RenderStage.Runtime
RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
)
promise.then(
......
......@@ -40,7 +40,7 @@ import {
applyOwnerStack,
makeDevtoolsIOAwarePromise,
makeHangingPromise,
getSessionDataStage,
RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils'
import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
......@@ -1853,14 +1853,12 @@ export async function cache(
switch (outerWorkUnitStore.type) {
case 'prerender-runtime': {
// In a runtime prerender, we have to make sure that APIs that would hang during a static prerender
// are resolved with a delay, in the appropriate runtime stage. Private caches read from
// Segments not using runtime prefetch resolve at EarlyRuntime,
// while runtime-prefetchable segments resolve at Runtime.
// are resolved with a delay, in the appropriate runtime stage. Private caches resolve in EarlyRuntime,
const stagedRendering = outerWorkUnitStore.stagedRendering
if (stagedRendering) {
await stagedRendering.waitForStage(
// TODO(app-shells): exclude private caches with a short staletime from shells
getSessionDataStage(stagedRendering)
RENDER_STAGES_BY_DATA_KIND.sessionData
)
}
break
......@@ -1868,14 +1866,13 @@ export async function cache(
case 'request': {
if (process.env.NODE_ENV === 'development') {
// Similar to runtime prerenders, private caches should not resolve in the static stage
// of a dev request, so we delay them. We pick the appropriate runtime stage based on
// whether we're in the early or late stages.
const stagedRendering = outerWorkUnitStore.stagedRendering
const stage = stagedRendering
? // TODO(app-shells): exclude private caches with a short staletime
getSessionDataStage(stagedRendering)
: RenderStage.Runtime
await makeDevtoolsIOAwarePromise(undefined, outerWorkUnitStore, stage)
// of a dev request, so we delay them.
await makeDevtoolsIOAwarePromise(
undefined,
outerWorkUnitStore,
// TODO(app-shells): exclude private caches with a short staletime
RENDER_STAGES_BY_DATA_KIND.sessionData
)
}
break
}
......@@ -2317,7 +2314,7 @@ export async function cache(
if (stagedRendering) {
await stagedRendering.waitForStage(
// TODO(app-shells): exclude caches with a short staletime
getSessionDataStage(stagedRendering)
RENDER_STAGES_BY_DATA_KIND.sessionData
)
}
break
......@@ -2361,14 +2358,10 @@ export async function cache(
cacheSignalReadEnded = true
}
const stagedRendering = workUnitStore.stagedRendering
const stage = stagedRendering
? getSessionDataStage(stagedRendering)
: RenderStage.Runtime
await makeDevtoolsIOAwarePromise(
undefined,
workUnitStore,
stage
RENDER_STAGES_BY_DATA_KIND.sessionData
)
}
break
......@@ -2885,14 +2878,10 @@ export async function cache(
cacheSignalReadEnded = true
}
const stagedRendering = workUnitStore.stagedRendering
const stage = stagedRendering
? getSessionDataStage(stagedRendering)
: RenderStage.Runtime
await makeDevtoolsIOAwarePromise(
undefined,
workUnitStore,
stage
RENDER_STAGES_BY_DATA_KIND.sessionData
)
}
break
......
......@@ -51,7 +51,7 @@ export function runDevWarmupTests({
) {
// Match logs that contain the message, with any environment.
const logPattern = new RegExp(
`^(?=.*\\b${message}\\b)(?=.*\\b(Cache|Prerender|Prefetch|Prefetchable|Server)\\b).*`
`^(?=.*\\b${message}\\b)(?=.*\\b(Cache|Prerender|Prefetch|Server)\\b).*`
)
const logMessages = logs.map((log) => log.message)
const messages = logMessages.filter((message) => logPattern.test(message))
......@@ -223,17 +223,15 @@ export function runDevWarmupTests({
}
}
const RUNTIME_ENV = hasRuntimePrefetch ? 'Prefetch' : 'Prefetchable'
describe(isInitialLoad ? 'initial load' : 'navigation', () => {
// Static
const STATIC_LINK_DATA = isInitialLoad
? 'Prerender'
: // If we're rendering an App Shell, static params are deferred until the runtime stage.
partialPrefetching || hasRuntimePrefetch
? RUNTIME_ENV
? 'Prefetch'
: 'Prerender'
const RUNTIME_LINK_DATA = RUNTIME_ENV
const RUNTIME_LINK_DATA = 'Prefetch'
describe('cached data resolves in the correct phase', () => {
it('cached data + cached fetch', async () => {
......@@ -267,12 +265,12 @@ export function runDevWarmupTests({
// Private caches are dynamic holes in static prerenders,
// so they shouldn't resolve in the static stage.
assertLog(logs, 'after private cache read - page', RUNTIME_ENV)
assertLog(logs, 'after private cache read - layout', RUNTIME_ENV)
assertLog(logs, 'after private cache read - page', 'Prefetch')
assertLog(logs, 'after private cache read - layout', 'Prefetch')
assertLog(
logs,
'after successive private cache reads - page',
RUNTIME_ENV
'Prefetch'
)
assertLog(logs, 'after uncached fetch - layout', 'Server')
......@@ -296,12 +294,8 @@ export function runDevWarmupTests({
// Short lived caches are dynamic holes in static prerenders,
// so they shouldn't resolve in the static stage.
assertLog(logs, 'after short-lived cache read - page', RUNTIME_ENV)
assertLog(
logs,
'after short-lived cache read - layout',
RUNTIME_ENV
)
assertLog(logs, 'after short-lived cache read - page', 'Prefetch')
assertLog(logs, 'after short-lived cache read - layout', 'Prefetch')
assertLog(logs, 'after uncached fetch - layout', 'Server')
assertLog(logs, 'after uncached fetch - page', 'Server')
......@@ -368,10 +362,10 @@ export function runDevWarmupTests({
assertLog(logs, 'after cache read - page', 'Prerender')
// TODO: we should only label this as "Prefetch" if there's a prefetch config.
assertLog(logs, `after cookies`, RUNTIME_ENV)
assertLog(logs, `after headers`, RUNTIME_ENV)
assertLog(logs, `after params`, RUNTIME_ENV)
assertLog(logs, `after searchParams`, RUNTIME_ENV)
assertLog(logs, `after cookies`, 'Prefetch')
assertLog(logs, `after headers`, 'Prefetch')
assertLog(logs, `after params`, 'Prefetch')
assertLog(logs, `after searchParams`, 'Prefetch')
assertLog(logs, 'after connection', 'Server')
}
......@@ -481,15 +475,16 @@ export function runDevWarmupTests({
const logs = await browser.log()
assertLog(logs, 'after first cache', 'Prerender')
assertLog(logs, 'after cookies', RUNTIME_ENV)
if (hasRuntimePrefetch) {
// if runtime prefetching is on, sync IO in the runtime stage errors and advances to Server.
assertLog(logs, 'after cookies', 'Prefetch')
if (hasRuntimePrefetch || partialPrefetching) {
// in partialPrefetching (either via allow-runtime or global flag),
// sync IO in the runtime stage errors and advances to Server.
assertLog(logs, 'after sync io', 'Server')
assertLog(logs, 'after cache read - page', 'Server')
} else {
// if runtime prefetching is not on, sync IO in the runtime stage does nothing.
assertLog(logs, 'after sync io', RUNTIME_ENV)
assertLog(logs, 'after cache read - page', RUNTIME_ENV)
assertLog(logs, 'after sync io', 'Prefetch')
assertLog(logs, 'after cache read - page', 'Prefetch')
}
}
......
......@@ -27,7 +27,7 @@ describe.each([
) {
// Match logs that contain the message, with any environment.
const logPattern = new RegExp(
`^(?=.*\\b${message}\\b)(?=.*\\b(Cache|Prerender|Prefetch|Prefetchable|Server)\\b).*`
`^(?=.*\\b${message}\\b)(?=.*\\b(Cache|Prerender|Prefetch|Server)\\b).*`
)
const logMessages = logs.map((log) => log.message)
const messages = logMessages.filter((message) => logPattern.test(message))
......@@ -154,8 +154,6 @@ describe.each([
}
}
const RUNTIME_ENV = hasRuntimePrefetch ? 'Prefetch' : 'Prefetchable'
describe.each([
{ description: 'initial load', isInitialLoad: true },
{ description: 'navigation', isInitialLoad: false },
......@@ -167,10 +165,10 @@ describe.each([
assertLog(logs, 'after immediate - static - layout', 'Prerender')
assertLog(logs, 'after immediate - static - page', 'Prerender')
assertLog(logs, 'after cookies - layout', RUNTIME_ENV)
assertLog(logs, 'after cookies - page', RUNTIME_ENV)
assertLog(logs, 'after immediate - runtime - layout', RUNTIME_ENV)
assertLog(logs, 'after immediate - runtime - page', RUNTIME_ENV)
assertLog(logs, 'after cookies - layout', 'Prefetch')
assertLog(logs, 'after cookies - page', 'Prefetch')
assertLog(logs, 'after immediate - runtime - layout', 'Prefetch')
assertLog(logs, 'after immediate - runtime - page', 'Prefetch')
assertLog(logs, 'after connection - layout', 'Server')
assertLog(logs, 'after connection - page', 'Server')
......
......@@ -60,7 +60,7 @@ describe('react-performance-track', () => {
expect(track).toEqual(
expect.arrayContaining([
{
name: '\u200bparams [Prefetchable]',
name: '\u200bparams [Prefetch]',
properties: [],
},
])
......@@ -79,7 +79,7 @@ describe('react-performance-track', () => {
expect(track).toEqual(
expect.arrayContaining([
{
name: '\u200bsearchParams [Prefetchable]',
name: '\u200bsearchParams [Prefetch]',
properties: [],
},
])
......@@ -96,7 +96,7 @@ describe('react-performance-track', () => {
expect(track).toEqual(
expect.arrayContaining([
{
name: '\u200bcookies [Prefetchable]',
name: '\u200bcookies [Prefetch]',
properties: [],
},
])
......@@ -110,26 +110,7 @@ describe('react-performance-track', () => {
})
const track = await browser.eval('window.reactServerRequests.getSnapshot()')
// TODO the addition of a promise to delay some Segments from rendering until the later Static
// stage has caused the draftMode snapshot to include an empty-named entry. This is probably
// a bug in React and should be fixed there but
// expect(track).toEqual([])
expect(track).toEqual(
expect.arrayContaining([
{
name: '\u200b [Prerender]',
properties: [],
},
])
)
let didThrow = false
try {
// including this anti-assertion here so we can restore the test when the bug in React is fixed
expect(track).toEqual([])
} catch (e) {
didThrow = true
}
expect(didThrow).toBe(true)
expect(track).toEqual([])
})
it('should show headers', async () => {
......@@ -142,7 +123,7 @@ describe('react-performance-track', () => {
expect(track).toEqual(
expect.arrayContaining([
{
name: '\u200bheaders [Prefetchable]',
name: '\u200bheaders [Prefetch]',
properties: [],
},
])
......
......@@ -116,7 +116,7 @@ describe('cache-components OTEL spans', () => {
{
"code": "E394",
"description": "A Cache Function (\`use cache\`) was passed to startActiveSpan which means it will receive a Span argument with a possibly random ID on every invocation leading to cache misses. Provide a wrapping function around the Cache Function that does not forward the Span argument to avoid this issue.",
"environmentLabel": "Prefetchable",
"environmentLabel": "Prefetch",
"label": "Console Error",
"source": "app/traced-work.tsx (26:19) @ <anonymous>
> 26 | return tracer.startActiveSpan('span-active-span', fn)
......@@ -134,7 +134,7 @@ describe('cache-components OTEL spans', () => {
{
"code": "E394",
"description": "A Cache Function (\`use cache\`) was passed to startActiveSpan which means it will receive a Span argument with a possibly random ID on every invocation leading to cache misses. Provide a wrapping function around the Cache Function that does not forward the Span argument to avoid this issue.",
"environmentLabel": "Prefetchable",
"environmentLabel": "Prefetch",
"label": "Console Error",
"source": "app/traced-work.tsx (26:19) @ eval
> 26 | return tracer.startActiveSpan('span-active-span', fn)
......
......@@ -38,35 +38,27 @@ export default async function Page() {
<li>
<DebugLinks href="/suspense-in-root/runtime/invalid-blocking-inside-runtime" />
</li>
<li>
<DebugLinks href="/suspense-in-root/runtime/invalid-sync-io" />
</li>
<li>
<DebugLinks href="/suspense-in-root/runtime/valid-blocking-inside-runtime" />
</li>
<li>
<DebugLinks href="/suspense-in-root/runtime/valid-sync-io-in-static-parent" />
</li>
<li>
<DebugLinks href="/suspense-in-root/runtime/invalid-sync-io-in-runtime-with-valid-static-parent" />
</li>
<li>
<DebugLinks href="/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input" />
</li>
<li>
<DebugLinks href="/suspense-in-root/runtime/invalid-sync-io-in-generate-metadata" />
<DebugLinks href="/suspense-in-root/runtime/static-layout-above-runtime-config/inner" />
</li>
</ul>
<h2>Sync IO</h2>
<ul>
<li>
<DebugLinks href="/suspense-in-root/runtime/static-layout-above-runtime-config/inner" />
<DebugLinks href="/suspense-in-root/sync-io/sync-io-after-cookies" />
</li>
<li>
<DebugLinks href="/suspense-in-root/runtime/valid-sync-io-in-generate-metadata-static-page" />
<DebugLinks href="/suspense-in-root/sync-io/sync-io-after-cookies-in-generate-metadata" />
</li>
<li>
<DebugLinks href="/suspense-in-root/runtime/invalid-sync-io-in-layout-generate-metadata" />
<DebugLinks href="/suspense-in-root/sync-io/sync-io-after-cache-with-cookie-input" />
</li>
<li>
<DebugLinks href="/suspense-in-root/runtime/valid-sync-io-in-layout-generate-metadata-static-page" />
<DebugLinks href="/suspense-in-root/sync-io/sync-io-after-io" />
</li>
</ul>
......
// Avoid static shell validation -- we only want to test the validation of `prefetch: 'runtime'` here.
export const instant = false
export const prefetch = 'allow-runtime'
export default function DisableStaticShell({ children }) {
return <>{children}</>
}
import { cookies } from 'next/headers'
// This layout does NOT have runtime prefetch itself, but the child page
// does. Since metadata belongs to the Page, the sync IO heuristic for
// generateMetadata uses the Page's prefetchability. Because the child
// page has runtime prefetch enabled, sync IO in this layout's
// generateMetadata should error.
export async function generateMetadata() {
await cookies()
const now = Date.now()
return {
title: `Layout metadata with sync IO: ${now}`,
}
}
export default function Layout({ children }: { children: React.ReactNode }) {
return <div>{children}</div>
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
export const instant = { level: 'experimental-error' }
export const prefetch = 'allow-runtime'
async function Runtime() {
await cookies()
return <p>Runtime content</p>
}
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<Runtime />
</Suspense>
</main>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
// This layout does NOT have runtime prefetch — it's a static segment.
// The sync IO after cookies() is valid here because this segment won't
// be runtime prefetched.
async function RuntimeContent() {
await cookies()
const now = Date.now()
return <p>Static layout with sync IO after cookies: {now}</p>
}
export default function StaticLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<div>
<Suspense fallback={<p>Loading...</p>}>
<RuntimeContent />
</Suspense>
<hr />
{children}
</div>
)
}
import { cookies } from 'next/headers'
export const instant = { level: 'experimental-error' }
export const prefetch = 'allow-runtime'
// This page HAS runtime prefetch enabled. The sync IO (Date.now()) after
// cookies() is invalid here because during a runtime prefetch, cookies()
// resolves and then Date.now() would abort the prerender too early.
export default async function Page() {
await cookies()
const now = Date.now()
return (
<main>
<p>Runtime page with sync IO after cookies: {now}</p>
</main>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
// this page is NOT runtime-prefetchable,
// so Sync IO in generateMetadata should be allowed.
export const instant = { level: 'experimental-error' }
export async function generateMetadata() {
await cookies()
const now = Date.now()
return {
title: `Sync IO in metadata: ${now}`,
}
}
async function Runtime() {
await cookies()
return <p>Runtime content</p>
}
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<Runtime />
</Suspense>
</main>
)
}
import { cookies } from 'next/headers'
// This layout does NOT have runtime prefetch and neither does the child
// page. Since no segment has runtime prefetch enabled, sync IO in
// generateMetadata should be allowed.
export const instant = { level: 'experimental-error' }
export async function generateMetadata() {
await cookies()
const now = Date.now()
return {
title: `Layout metadata with sync IO: ${now}`,
}
}
export default function Layout({ children }: { children: React.ReactNode }) {
return <div>{children}</div>
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
// No instant — this page is NOT runtime-prefetchable.
async function Runtime() {
await cookies()
return <p>Runtime content</p>
}
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<Runtime />
</Suspense>
</main>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
// This layout does NOT have runtime prefetch — it's a static segment.
// The RuntimeContent component accesses cookies() then Date.now().
// In a static prefetch the render would never get past cookies() so the
// sync IO is unreachable. In a runtime prefetch, cookies() would resolve
// but this layout is not runtime-prefetchable — only the child page is.
// So the sync IO here should not error.
async function RuntimeContent() {
await cookies()
const now = Date.now()
return <p>Static layout with sync IO after cookies: {now}</p>
}
export default function StaticLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<div>
<Suspense fallback={<p>Loading...</p>}>
<RuntimeContent />
</Suspense>
<hr />
{children}
</div>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
export const instant = { level: 'experimental-error' }
export const prefetch = 'allow-runtime'
async function Runtime() {
await cookies()
return <p>Runtime content</p>
}
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<Runtime />
</Suspense>
</main>
)
}
import { Instant } from 'next'
import { cookies } from 'next/headers'
import { Fragment, Suspense } from 'react'
export const instant = { level: 'experimental-error' }
export const prefetch = 'allow-runtime'
export const instant: Instant = {
level: 'experimental-error',
unstable_samples: [{ cookies: [{ name: 'testCookie', value: 'testValue' }] }],
}
// This page HAS runtime prefetch enabled. cookies() is passed as a promise
// input to a public "use cache" function. The cache doesn't read the cookies
// in its body — they're only part of the cache key. After the cache resolves,
// Date.now() is sync IO that should error because we're in a
// runtime-prefetchable segment where cookies() has resolved at EarlyRuntime.
// cookies() is passed as a promise input to a public "use cache" function.
// The cache doesn't read the cookies in its body — they're only part of the cache key.
// After the cache resolves, Date.now() is sync IO that should error.
//
// This test validates that the cache input encoding resolves in the correct
// runtime stage (EarlyRuntime for prefetchable segments). If the cache input
// abort signal incorrectly waited for the Runtime stage, the cache would
// resolve later, and Date.now() would happen at the Runtime stage where
// canSyncInterrupt returns false — missing the error.
// This test validates that the cache input encoding resolves in the
// Runtime stage. Date.now() should either error or be allowed
// depending on if partialPrefetching is enabled or not.
async function cachedFn(cookiePromise: Promise<string>) {
'use cache'
......@@ -23,12 +23,28 @@ async function cachedFn(cookiePromise: Promise<string>) {
}
export default async function Page() {
const cookiePromise = cookies().then((c) => c.get('testCookie')?.value ?? '')
await cachedFn(cookiePromise)
const now = Date.now()
return (
<main>
<p>Runtime page with sync IO after cache with cookie input: {now}</p>
<p>
Page with sync IO after cache with cookie input:{' '}
<SuspenseIfNotPartialPrefetching>
<SyncIOAfterCache />
</SuspenseIfNotPartialPrefetching>
</p>
</main>
)
}
// Before partialPrefetching, cookies() is not allowed in shells,
// so it would fail instant validation unless wrapped in suspense.
// We're not interested in checking if cookies blocks,
// only in wheter the Sync IO after triggers an error.
const SuspenseIfNotPartialPrefetching = process.env.__NEXT_PARTIAL_PREFETCHING
? Fragment
: Suspense
async function SyncIOAfterCache() {
const cookiePromise = cookies().then((c) => c.get('testCookie')?.value ?? '')
await cachedFn(cookiePromise)
return Date.now()
}
......@@ -2,7 +2,6 @@ import { cookies } from 'next/headers'
import { Suspense } from 'react'
export const instant = { level: 'experimental-error' }
export const prefetch = 'allow-runtime'
export async function generateMetadata() {
await cookies()
......@@ -12,16 +11,16 @@ export async function generateMetadata() {
}
}
async function Runtime() {
async function SessionData() {
await cookies()
return <p>Runtime content</p>
return <p>Session data</p>
}
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<Runtime />
<SessionData />
</Suspense>
</main>
)
......
import { cookies } from 'next/headers'
import { Fragment, Suspense } from 'react'
export const instant = { level: 'experimental-error' }
export default async function Page() {
return (
<main>
<p>
This page uses sync IO after awaiting cookies():
<SuspenseIfNotPartialPrefetching>
<SyncIOAfterCookies />
</SuspenseIfNotPartialPrefetching>
</p>
</main>
)
}
// Before partialPrefetching, cookies() is not allowed in shells,
// so it would fail instant validation unless wrapped in suspense.
// We're not interested in checking if cookies blocks,
// only in wheter the Sync IO after triggers an error.
const SuspenseIfNotPartialPrefetching = process.env.__NEXT_PARTIAL_PREFETCHING
? Fragment
: Suspense
async function SyncIOAfterCookies() {
await cookies()
return Date.now()
}
import { cookies } from 'next/headers'
import { io } from 'next/cache'
import { Suspense } from 'react'
export const instant = { level: 'experimental-error' }
export const prefetch = 'allow-runtime'
export default async function Page() {
await cookies()
const now = Date.now()
return (
<main>
<p>This page uses sync IO after awaiting cookies(): {now}</p>
<p>
This page uses sync IO after awaiting io():
<Suspense>
<SyncIOAfterIO />
</Suspense>
</p>
</main>
)
}
async function SyncIOAfterIO() {
await io()
return Date.now()
}
......@@ -217,31 +217,31 @@ export function registerHeadAndReportingTests(
)
// TODO(instant-validation): why aren't we pointing to `await connection()` here?
await expect(browser).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Instant Validation",
"source": "app/suspense-in-root/head/invalid-dynamic-viewport-in-blocking-inside-static/layout.tsx (3:24) @ instant
> 3 | export const instant = { level: 'experimental-error' }
| ^",
"stack": [
"instant app/suspense-in-root/head/invalid-dynamic-viewport-in-blocking-inside-static/layout.tsx (3:24)",
"Set.forEach <anonymous>",
],
},
],
"code": "E1395",
"description": "Next.js encountered uncached data in generateViewport().",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/suspense-in-root/head/invalid-dynamic-viewport-in-blocking-inside-static/page.tsx (6:23) @ Module.generateViewport
> 6 | export async function generateViewport(): Promise<Viewport> {
| ^",
"stack": [
"Module.generateViewport app/suspense-in-root/head/invalid-dynamic-viewport-in-blocking-inside-static/page.tsx (6:23)",
],
}
`)
{
"cause": [
{
"label": "Caused by: Instant Validation",
"source": "app/suspense-in-root/head/invalid-dynamic-viewport-in-blocking-inside-static/layout.tsx (3:24) @ instant
> 3 | export const instant = { level: 'experimental-error' }
| ^",
"stack": [
"instant app/suspense-in-root/head/invalid-dynamic-viewport-in-blocking-inside-static/layout.tsx (3:24)",
"Set.forEach <anonymous>",
],
},
],
"code": "E1395",
"description": "Next.js encountered uncached data in generateViewport().",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/suspense-in-root/head/invalid-dynamic-viewport-in-blocking-inside-static/page.tsx (7:19) @ Module.generateViewport
> 7 | await connection()
| ^",
"stack": [
"Module.generateViewport app/suspense-in-root/head/invalid-dynamic-viewport-in-blocking-inside-static/page.tsx (7:19)",
],
}
`)
} else {
const result = await prerender(
'/suspense-in-root/head/invalid-dynamic-viewport-in-blocking-inside-static'
......@@ -780,33 +780,31 @@ export function registerHeadAndReportingTests(
)
await expect(browser).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Instant Validation",
"source": "app/shells/(default)/invalid-static-with-gsp-metadata/[slug]/page.tsx (3:33) @ instant
> 3 | export const instant: Instant = {
| ^",
"stack": [
"instant app/shells/(default)/invalid-static-with-gsp-metadata/[slug]/page.tsx (3:33)",
"Set.forEach <anonymous>",
],
},
],
"code": "E1407",
"description": "Next.js encountered URL data in generateMetadata().",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/shells/(default)/invalid-static-with-gsp-metadata/[slug]/page.tsx (3:33) @ instant
> 3 | export const instant: Instant = {
| ^",
"stack": [
"Suspense <anonymous>",
"div <anonymous>",
"MetadataWrapper [Prerender] <anonymous>",
],
}
`)
{
"cause": [
{
"label": "Caused by: Instant Validation",
"source": "app/shells/(default)/invalid-static-with-gsp-metadata/[slug]/page.tsx (3:33) @ instant
> 3 | export const instant: Instant = {
| ^",
"stack": [
"instant app/shells/(default)/invalid-static-with-gsp-metadata/[slug]/page.tsx (3:33)",
"Set.forEach <anonymous>",
],
},
],
"code": "E1407",
"description": "Next.js encountered URL data in generateMetadata().",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/shells/(default)/invalid-static-with-gsp-metadata/[slug]/page.tsx (19:3) @ Module.generateMetadata
> 19 | await params
| ^",
"stack": [
"Module.generateMetadata app/shells/(default)/invalid-static-with-gsp-metadata/[slug]/page.tsx (19:3)",
],
}
`)
} else {
const result = await prerender(
'/shells/(default)/invalid-static-with-gsp-metadata/[slug]'
......
......@@ -115,8 +115,29 @@ describe('Link with legacyBehavior', () => {
await expectHrefToBeForwardedInSSR('/passHref/default')
})
it('navigates correctly', async () => {
await expectLinkClickToNavigate('/passHref/default')
it('navigates correctly (failing)', async () => {
if (isNextDev) {
// FIXME(NAR-876): false positive due to debug info blocking the child
// await expectLinkClickToNavigate('/passHref/default')
const browser = await next.browser('/passHref/default')
await expect(browser).toDisplayRedbox(`
{
"code": "E863",
"description": "\`<Link legacyBehavior>\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \`<a>\` tag.",
"environmentLabel": null,
"label": "Runtime Error",
"source": "app/passHref/default/page.tsx (7:7) @ Page
> 7 | <Link href="/about" legacyBehavior passHref>
| ^",
"stack": [
"Page app/passHref/default/page.tsx (7:7)",
],
}
`)
} else {
await expectLinkClickToNavigate('/passHref/default')
}
})
})
......
......@@ -133,7 +133,23 @@ describe('Validations for <Link legacyBehavior>', () => {
'/validations/rsc-that-renders-link/client/default'
)
if (isNextDev) {
await waitForNoRedbox(browser)
// FIXME(NAR-876): false positive due to debug info blocking the child
// await waitForNoRedbox(browser)
await expect(browser).toDisplayRedbox(`
{
"code": "E863",
"description": "\`<Link legacyBehavior>\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \`<a>\` tag.",
"environmentLabel": null,
"label": "Runtime Error",
"source": "app/validations/rsc-that-renders-link/client/default/page.tsx (7:7) @ Page
> 7 | <Link href="/about" legacyBehavior passHref>
| ^",
"stack": [
"Page app/validations/rsc-that-renders-link/client/default/page.tsx (7:7)",
],
}
`)
} else {
expect(newConsoleOutput()).toEqual('')
}
......@@ -290,7 +306,24 @@ describe('Validations for <Link legacyBehavior>', () => {
'/validations/rsc-that-renders-client/client/default'
)
if (isNextDev) {
await waitForNoRedbox(browser)
// FIXME(NAR-876): false positive due to debug info blocking the child
// await waitForNoRedbox(browser)
await expect(browser).toDisplayRedbox(`
{
"code": "E863",
"description": "\`<Link legacyBehavior>\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \`<a>\` tag.",
"environmentLabel": null,
"label": "Runtime Error",
"source": "app/validations/rsc-that-renders-client/client-link.tsx (7:10) @ ClientLink
> 7 | return <Link legacyBehavior passHref {...props} />
| ^",
"stack": [
"ClientLink app/validations/rsc-that-renders-client/client-link.tsx (7:10)",
"Page app/validations/rsc-that-renders-client/client/default/page.tsx (7:7)",
],
}
`)
} else {
expect(newConsoleOutput()).toEqual('')
}
......@@ -344,7 +377,24 @@ describe('Validations for <Link legacyBehavior>', () => {
)
if (isNextDev) {
await waitForNoRedbox(browser)
// FIXME(NAR-876): false positive due to debug info blocking the child
// await waitForNoRedbox(browser)
await expect(browser).toDisplayRedbox(`
{
"code": "E863",
"description": "\`<Link legacyBehavior>\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \`<a>\` tag.",
"environmentLabel": null,
"label": "Runtime Error",
"source": "app/validations/rsc-that-renders-client/client-link.tsx (7:10) @ ClientLink
> 7 | return <Link legacyBehavior passHref {...props} />
| ^",
"stack": [
"ClientLink app/validations/rsc-that-renders-client/client-link.tsx (7:10)",
"Page app/validations/rsc-that-renders-client/client-with-rsc-child/default/page.tsx (7:7)",
],
}
`)
} else {
expect(newConsoleOutput()).toEqual('')
}
......
......@@ -476,7 +476,6 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/server/app-render/async-local-storage.js",
"/node_modules/next/dist/server/app-render/console-async-storage-instance.js",
"/node_modules/next/dist/server/app-render/console-async-storage.external.js",
"/node_modules/next/dist/server/app-render/staged-rendering.js",
"/node_modules/next/dist/server/app-render/work-async-storage-instance.js",
"/node_modules/next/dist/server/app-render/work-async-storage.external.js",
"/node_modules/next/dist/server/app-render/work-unit-async-storage-instance.js",
......@@ -519,7 +518,6 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/shared/lib/is-plain-object.js",
"/node_modules/next/dist/shared/lib/is-thenable.js",
"/node_modules/next/dist/shared/lib/no-fallback-error.external.js",
"/node_modules/next/dist/shared/lib/promise-with-resolvers.js",
"/node_modules/next/dist/shared/lib/server-reference-info.js",
"/node_modules/react/cjs/react.production.js",
"/node_modules/react/index.js",
......
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