Unverified Commit 85d74bb4 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[Instant] allow non-blocking dynamic holes and errors in shared parents (#89875)

Closes NAR-777
parent 32b1479a
......@@ -1052,5 +1052,11 @@
"1051": "Turbopack trace server is not supported on this platform (%s/%s) because native bindings are not available. Only WebAssembly (WASM) bindings were loaded, and Turbopack requires native bindings.",
"1052": "Turbopack is not supported on this platform (%s/%s) because native bindings are not available. Only WebAssembly (WASM) bindings were loaded, and Turbopack requires native bindings. Use the --webpack flag instead.",
"1053": "Export encountered errors on %s %s:\\n\\t%s",
"1054": "`runInSequentialTasks` should not be called in edge runtime."
"1054": "`runInSequentialTasks` should not be called in edge runtime.",
"1055": "Route \"%s\" failed to render during instant validation and Next.js was unable to determine a reason.",
"1056": "Route \"%s\": Could not validate \\`unstable_instant\\` because the target segment was prevented from rendering for an unknown reason.",
"1057": "Route \"%s\": Could not validate \\`unstable_instant\\` because the target segment was prevented from rendering, likely due to one of the following errors.",
"1058": "InstantValidationBoundary should only be rendered in SSR",
"1059": "Route \"%s\": Could not validate \\`unstable_instant\\` because the target segment was prevented from rendering, likely due to the following error.",
"1060": "Missing boundary tracking state"
}
......@@ -142,6 +142,8 @@ import {
getNavigationDisallowedDynamicReasons,
trackDynamicHoleInNavigation,
DynamicHoleKind,
trackThrownErrorInNavigation,
createInstantValidationState,
} from './dynamic-rendering'
import {
getClientComponentLoaderMetrics,
......@@ -239,6 +241,7 @@ import { createNodeStreamWithLateRelease } from './instant-validation/stream-uti
// NOTE: Only use this for types, access implementations via ComponentMod
import type * as InstantValidation from './instant-validation/instant-validation'
import { createValidationBoundaryTracking } from './instant-validation/boundary-tracking'
export type GetDynamicParamFromSegment = (
// The LoaderTree to extract the dynamic param from
......@@ -4277,6 +4280,9 @@ async function validateInstantConfigNavigation(
const preinitScripts = () => {}
const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
const dynamicValidation = createInstantValidationState()
const boundaryState = createValidationBoundaryTracking()
const finalClientPrerenderStore: PrerenderStore = {
type: 'prerender-client',
phase: 'render',
......@@ -4299,10 +4305,9 @@ async function validateInstantConfigNavigation(
hmrRefreshHash,
// We don't need to track vary params during validation.
varyParamsAccumulator: null,
boundaryState,
}
const dynamicValidation = createDynamicValidationState()
const clientReferenceManifest = getClientReferenceManifest()
const usedSegmentKinds = new Set<InstantValidation.SegmentStage>()
......@@ -4315,6 +4320,7 @@ async function validateInstantConfigNavigation(
routeTree,
navigationParent,
extraChunksReleaseSignal,
boundaryState,
clientReferenceManifest,
stageEndTimes,
useRuntimeStageForPartialSegments,
......@@ -4370,10 +4376,20 @@ async function validateInstantConfigNavigation(
componentStack,
dynamicValidation,
clientDynamicTracking,
dynamicHoleKind
dynamicHoleKind,
boundaryState
)
}
return
} else if (!clientReactController.signal.aborted) {
const componentStack = errorInfo.componentStack
if (typeof componentStack === 'string') {
trackThrownErrorInNavigation(
dynamicValidation,
err,
componentStack
)
}
}
if (isReactLargeShellError(err)) {
......@@ -4408,19 +4424,23 @@ async function validateInstantConfigNavigation(
)
const { preludeIsEmpty } = await processPrelude(unprocessedPrelude)
const reasons = getNavigationDisallowedDynamicReasons(
workStore,
preludeIsEmpty ? PreludeState.Empty : PreludeState.Full,
dynamicValidation
dynamicValidation,
boundaryState
)
return { dynamicHoleKind, errors: reasons } as const
return { dynamicHoleKind, errors: reasons }
} catch (thrownValue) {
// Even if the root errors we still want to report any cache components errors
// that were discovered before the root errored.
let errors: Array<unknown> = getNavigationDisallowedDynamicReasons(
workStore,
PreludeState.Errored,
dynamicValidation
dynamicValidation,
boundaryState
)
if (process.env.NEXT_DEBUG_BUILD || process.env.__NEXT_VERBOSE_LOGGING) {
......
......@@ -50,6 +50,7 @@ import { scheduleOnNextTick } from '../../lib/scheduler'
import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { InvariantError } from '../../shared/lib/invariant-error'
import { INSTANT_VALIDATION_BOUNDARY_NAME } from './instant-validation/boundary-constants'
import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'
const hasPostpone = typeof React.unstable_postpone === 'function'
......@@ -773,12 +774,38 @@ export enum DynamicHoleKind {
Dynamic = 2,
}
/** Stores dynamic reasons used during an SSR render in instant validation. */
export type InstantValidationState = {
hasDynamicMetadata: boolean
hasAllowedClientDynamicAboveBoundary: boolean
dynamicMetadata: null | Error
hasDynamicViewport: boolean
hasAllowedDynamic: boolean
dynamicErrors: Array<Error>
validationPreventingErrors: Array<Error>
thrownErrorsOutsideBoundary: Array<unknown>
}
export function createInstantValidationState(): InstantValidationState {
return {
hasDynamicMetadata: false,
hasAllowedClientDynamicAboveBoundary: false,
dynamicMetadata: null,
hasDynamicViewport: false,
hasAllowedDynamic: false,
dynamicErrors: [],
validationPreventingErrors: [],
thrownErrorsOutsideBoundary: [],
}
}
export function trackDynamicHoleInNavigation(
workStore: WorkStore,
componentStack: string,
dynamicValidation: DynamicValidationState,
dynamicValidation: InstantValidationState,
clientDynamic: DynamicTrackingState,
kind: DynamicHoleKind
kind: DynamicHoleKind,
boundaryState: ValidationBoundaryTracking
) {
if (hasOutletRegex.test(componentStack)) {
// We don't need to track that this is dynamic. It is only so when something else is also dynamic.
......@@ -805,32 +832,62 @@ export function trackDynamicHoleInNavigation(
return
}
// Check if we have a Suspense above the hole, but below the validation boundary.
// If we do, then this dynamic usage wouldn't block a navigation to this subtree.
// Conversely, if the nearest suspense is above the validation boundary, then this subtree would block.
//
// Note that in the component stack, children come before parents.
//
// Valid:
// ...
// at Suspense
// ...
// at __next_prefetch_validation_boundary__
//
// Invalid:
// ...
// at __next_prefetch_validation_boundary__
// ...
// at Suspense
//
const suspenseLocation = hasSuspenseRegex.exec(componentStack)
if (suspenseLocation) {
const boundaryLocation =
hasPrefetchValidationBoundaryRegex.exec(componentStack)
if (boundaryLocation) {
const boundaryLocation =
hasPrefetchValidationBoundaryRegex.exec(componentStack)
if (!boundaryLocation) {
// We don't see the validation boundary in the component stack,
// so this hole must be coming from a shared parent.
// Shared parents are fully resolved and don't have RSC holes,
// but they can still suspend in a client component during SSR.
// If we managed to render all the validation boundaries, that means
// that the client holes aren't blocking validation and we can disregard them.
// Note that we don't even care whether they have suspense or not.
if (boundaryState.expectedIds.size === boundaryState.renderedIds.size) {
dynamicValidation.hasAllowedClientDynamicAboveBoundary = true
dynamicValidation.hasAllowedDynamic = true // Holes outside the boundary contribute to allowing dynamic metadata
return
} else {
// TODO(instant-validation) TODO(NAR-787)
// If shared parents blocked us from validating, we should only log
// the errors from the innermost (segments), i.e. omit layouts whose
// slots managed to render (because clearly they didn't block validation)
const message = `Route "${workStore.route}": Could not validate \`unstable_instant\` because a Client Component in a parent segment prevented the page from rendering.`
const error = createErrorWithComponentOrOwnerStack(
message,
componentStack
)
dynamicValidation.validationPreventingErrors.push(error)
return
}
} else {
// The hole originates inside the validation boundary.
//
// Check if we have a Suspense above the hole, but below the validation boundary.
// If we do, then this dynamic usage wouldn't block a navigation to this subtree.
// Conversely, if the nearest suspense is above the validation boundary, then this subtree would block.
//
// Note that in the component stack, children come before parents.
//
// Valid:
// ...
// at Suspense
// ...
// at __next_prefetch_validation_boundary__
//
// Invalid:
// ...
// at __next_prefetch_validation_boundary__
// ...
// at Suspense
//
const suspenseLocation = hasSuspenseRegex.exec(componentStack)
if (suspenseLocation) {
if (suspenseLocation.index < boundaryLocation.index) {
dynamicValidation.hasAllowedDynamic = true
return
} else {
// invalid - fallthrough
}
}
}
......@@ -853,6 +910,19 @@ export function trackDynamicHoleInNavigation(
return
}
export function trackThrownErrorInNavigation(
dynamicValidation: InstantValidationState,
error: unknown,
componentStack: string
) {
// If we see a validation boundary on the component stack,
// this error couldn't have blocked a validation boundary from rendering.
if (hasPrefetchValidationBoundaryRegex.test(componentStack)) {
return
}
dynamicValidation.thrownErrorsOutsideBoundary.push(error)
}
export function trackDynamicHoleInRuntimeShell(
workStore: WorkStore,
componentStack: string,
......@@ -1110,27 +1180,57 @@ export function getStaticShellDisallowedDynamicReasons(
export function getNavigationDisallowedDynamicReasons(
workStore: WorkStore,
prelude: PreludeState,
dynamicValidation: DynamicValidationState
dynamicValidation: InstantValidationState,
boundaryState: ValidationBoundaryTracking
): Array<Error> {
// NOTE: We don't care about Suspense above body here
// TODO: Need to make sure the logic here actually makes sense
const { validationPreventingErrors } = dynamicValidation
if (validationPreventingErrors.length > 0) {
return validationPreventingErrors
}
if (boundaryState.renderedIds.size < boundaryState.expectedIds.size) {
const { thrownErrorsOutsideBoundary } = dynamicValidation
if (thrownErrorsOutsideBoundary.length === 0) {
return [
new Error(
`Route "${workStore.route}": Could not validate \`unstable_instant\` because the target segment was prevented from rendering for an unknown reason.`
),
]
} else if (thrownErrorsOutsideBoundary.length === 1) {
return [
new Error(
`Route "${workStore.route}": Could not validate \`unstable_instant\` because the target segment was prevented from rendering, likely due to the following error.`
),
thrownErrorsOutsideBoundary[0] as Error,
]
} else {
return [
new Error(
`Route "${workStore.route}": Could not validate \`unstable_instant\` because the target segment was prevented from rendering, likely due to one of the following errors.`
),
...(thrownErrorsOutsideBoundary as Error[]),
]
}
}
// NOTE: We don't care about Suspense above body here,
// we're only concerned with the validation boundary
if (prelude !== PreludeState.Full) {
// We didn't have any sync bailouts but there may be user code which
// blocked the root. We would have captured these during the prerender
// and can log them here and then terminate the build/validating render
const dynamicErrors = dynamicValidation.dynamicErrors
if (dynamicErrors.length > 0) {
return dynamicErrors
}
if (prelude === PreludeState.Empty) {
// If a client component suspended prevented us from rendering a shell
// but didn't block validation, we don't require a prelude.
if (dynamicValidation.hasAllowedClientDynamicAboveBoundary) {
return []
}
// If we ever get this far then we messed up the tracking of invalid dynamic.
// We still adhere to the constraint that you must produce a shell but invite the
// user to report this as a bug in Next.js.
return [
new InvariantError(
`Route "${workStore.route}" did not produce a static shell and Next.js was unable to determine a reason.`
`Route "${workStore.route}" failed to render during instant validation and Next.js was unable to determine a reason.`
),
]
}
......
export type ValidationBoundaryTracking = {
expectedIds: Set<string>
renderedIds: Set<string>
}
export function createValidationBoundaryTracking(): ValidationBoundaryTracking {
return {
expectedIds: new Set(),
renderedIds: new Set(),
}
}
......@@ -2,15 +2,54 @@
import type { ReactNode } from 'react'
import { INSTANT_VALIDATION_BOUNDARY_NAME } from './boundary-constants'
import { InvariantError } from '../../../shared/lib/invariant-error'
import { workUnitAsyncStorage } from '../work-unit-async-storage.external'
import type { ValidationBoundaryTracking } from './boundary-tracking'
function getValidationBoundaryTracking(): ValidationBoundaryTracking | null {
const store = workUnitAsyncStorage.getStore()
if (!store) return null
switch (store.type) {
case 'prerender-client':
return store.boundaryState ?? null
case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':
case 'prerender-runtime':
case 'request':
case 'cache':
case 'private-cache':
case 'unstable-cache':
break
default:
store satisfies never
}
return null
}
// We use a namespace object to allow us to recover the name of the function
// at runtime even when production bundling/minification is used.
const NameSpace = {
[INSTANT_VALIDATION_BOUNDARY_NAME]: function ({
id,
children,
}: {
id: string
children: ReactNode
}) {
if (typeof window !== 'undefined') {
throw new InvariantError(
'InstantValidationBoundary should only be rendered in SSR'
)
}
// Track which boundaries we actually managed to render.
const state = getValidationBoundaryTracking()
if (state === null) {
throw new InvariantError('Missing boundary tracking state')
}
state.renderedIds.add(id)
return children
},
}
......
......@@ -19,7 +19,11 @@ import {
printDebugThrownValueForProspectiveRender,
} from '../prospective-render-utils'
import { getDigestForWellKnownError } from '../create-error-handler'
import { InstantValidationBoundary } from './boundary'
import {
// NOTE: we're in the server layer, so this is a client reference
InstantValidationBoundary,
} from './boundary'
import type { ValidationBoundaryTracking } from './boundary-tracking'
import {
getLayoutOrPageModule,
type LoaderTree,
......@@ -785,6 +789,7 @@ export async function createCombinedPayload(
* */
navigationParent: SegmentPath,
releaseSignal: AbortSignal,
boundaryState: ValidationBoundaryTracking,
clientReferenceManifest: ClientReferenceManifest,
stageEndTimes: StageEndTimes,
/** Only used when retrying a failed validation to see what caused a dynamic hole. */
......@@ -798,6 +803,7 @@ export async function createCombinedPayload(
validationRouteTree,
navigationParent,
releaseSignal,
boundaryState,
clientReferenceManifest,
stageEndTimes,
useRuntimeStageForPartialSegments,
......@@ -838,6 +844,7 @@ function createValidationSeedData(
rootRouteTree: RouteTree,
navigationParent: SegmentPath,
releaseSignal: AbortSignal,
boundaryState: ValidationBoundaryTracking,
clientReferenceManifest: ClientReferenceManifest,
stageEndTimes: StageEndTimes,
useRuntimeStageForPartialSegments: boolean,
......@@ -945,12 +952,17 @@ function createValidationSeedData(
debug?.(
` ['${path}' is in the new subtree, adding validation boundary around it]`
)
const boundaryId = path
boundaryState.expectedIds.add(boundaryId)
segmentData = {
...segmentData,
node: (
// bundled in the server layer
// eslint-disable-next-line @next/internal/no-ambiguous-jsx
<InstantValidationBoundary key="c" /* matching `cacheNodeKey` */>
<InstantValidationBoundary
id={boundaryId}
key="c" /* matching `cacheNodeKey` */
>
{segmentData.node}
</InstantValidationBoundary>
),
......
......@@ -21,6 +21,7 @@ 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 type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'
export type WorkUnitPhase = 'action' | 'render' | 'after'
......@@ -112,6 +113,7 @@ export interface PrerenderStoreModernClient
extends PrerenderStoreModernCommon,
StaticPrerenderStoreCommon {
readonly type: 'prerender-client'
readonly boundaryState?: ValidationBoundaryTracking
}
export interface PrerenderStoreModernServer
......
......@@ -3899,7 +3899,7 @@ describe('Cache Components Errors', () => {
935 | // "use cache: private" is dynamic in prerendering contexts.
936 | case 'prerender':
> 937 | return makeHangingPromise(
| ^
| ^
938 | workUnitStore.renderSignal,
939 | workStore.route,
940 | expression
......
......@@ -81,6 +81,30 @@ export default async function Page() {
<li>
<DebugLinks href="/suspense-in-root/static/missing-suspense-in-parallel-route/bar" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/invalid-client-data-blocks-validation" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/valid-client-api-in-parent/sync-io" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/valid-client-api-in-parent/dynamic-params/123" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/valid-client-api-in-parent/search-params" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/valid-client-data-does-not-block-validation" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/invalid-client-error-in-parent-blocks-children" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/invalid-client-error-in-parent-sibling" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/valid-client-error-in-parent-does-not-block-validation" />
</li>
</ul>
<h2>Disable Validation</h2>
......
'use client'
import { use } from 'react'
import { useDataCache } from '../../../../client-data-fetching-lib/client'
export function FetchesClientData({ children }) {
const dataCache = useDataCache()
const promise = dataCache.getOrLoad('my-key', async () => {
await new Promise<void>((resolve) => setTimeout(resolve, 10))
return 'My client data result'
})
const data = use(promise)
return (
<>
<div>Got client data: "{data}"</div>
<hr />
{children}
</>
)
}
import type { ReactNode } from 'react'
import { FetchesClientData } from './client'
import { DataCacheProvider } from '../../../../client-data-fetching-lib/server'
// Make sure that the holes from this layout aren't factored in for validation
// (otherwise, we'd check a navigation into it from the root layout and fail)
export const unstable_instant = false
export default function Layout({ children }: { children: ReactNode }) {
return (
<DataCacheProvider>
<div>
<p>
This layout renders a client component that suspends in SSR and blocks
the children. This prevents us from validating the page below.
</p>
<FetchesClientData>{children}</FetchesClientData>
</div>
</DataCacheProvider>
)
}
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return (
<main>
<p>
This page is static, so it should pass instant validation, but client
data fetching above will prevent us from validating it.
</p>
</main>
)
}
'use client'
export function ErrorInSSR({ children }) {
if (typeof window === 'undefined') {
throw new Error('No SSR please')
}
return <>{children}</>
}
import { Suspense, type ReactNode } from 'react'
import { ErrorInSSR } from './client'
// Make sure that the holes from this layout aren't factored in for validation
// (otherwise, we'd check a navigation into it from the root layout and fail)
export const unstable_instant = false
export default function Layout({ children }: { children: ReactNode }) {
return (
<>
<div>
<p>
This layout errors in SSR, and the errors is caught by a Suspense
boundary, but it blocks the children slot so it prevents validation.
</p>
<Suspense>
<ErrorInSSR>{children}</ErrorInSSR>
</Suspense>
</div>
</>
)
}
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return (
<main>
<p>This page is static, so it should pass instant validation</p>
</main>
)
}
'use client'
export function ErrorInSSR() {
if (typeof window === 'undefined') {
throw new Error('No SSR please')
}
return <div>Hello, browser!</div>
}
import { type ReactNode } from 'react'
import { ErrorInSSR } from './client'
// Make sure that the holes from this layout aren't factored in for validation
// (otherwise, we'd check a navigation into it from the root layout and fail)
export const unstable_instant = false
export default function Layout({ children }: { children: ReactNode }) {
return (
<>
<div>
<p>
This layout errors in SSR and the error isn't caught by a Suspense
boundary, so it blocks the children slot and prevents validation.
</p>
</div>
<hr />
<ErrorInSSR />
{children}
</>
)
}
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return (
<main>
<p>This page is static, so it should pass instant validation</p>
</main>
)
}
'use client'
import { usePathname } from 'next/navigation'
export function ShouldNotSuspendDuringValidation({ children }) {
const pathname = usePathname()
return (
<>
<div>Hello, browser! Pathname: "{pathname}"</div>
<hr />
{children}
</>
)
}
import type { ReactNode } from 'react'
import { ShouldNotSuspendDuringValidation } from './client'
// Make sure that the holes from this layout aren't factored in for validation
// (otherwise, we'd check a navigation into it from the root layout and fail)
export const unstable_instant = false
export default function Layout({ children }: { children: ReactNode }) {
return (
<>
<div>
<p>
This layout renders a client component that accesses usePathname()
with a dynamic param. This would suspend a prerender, but does not
affect client navigations, so this should be allowed.
</p>
</div>
<ShouldNotSuspendDuringValidation>
{children}
</ShouldNotSuspendDuringValidation>
</>
)
}
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return (
<main>
<p>This page is static, so it should pass instant validation</p>
</main>
)
}
'use client'
import { useSearchParams } from 'next/navigation'
export function ShouldNotSuspendDuringValidation({ children }) {
const search = useSearchParams()
return (
<>
<div>Hello, browser! Search: "{search.toString()}"</div>
<hr />
{children}
</>
)
}
import type { ReactNode } from 'react'
import { ShouldNotSuspendDuringValidation } from './client'
// Make sure that the holes from this layout aren't factored in for validation
// (otherwise, we'd check a navigation into it from the root layout and fail)
export const unstable_instant = false
export default function Layout({ children }: { children: ReactNode }) {
return (
<>
<div>
<p>
This layout renders a client component that accesses
useSearchParams(). This would suspend a prerender, but does not affect
client navigations, so this should be allowed.
</p>
</div>
<hr />
<ShouldNotSuspendDuringValidation>
{children}
</ShouldNotSuspendDuringValidation>
</>
)
}
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return (
<main>
<p>This page is static, so it should pass instant validation</p>
</main>
)
}
'use client'
export function SyncIOInClient({ children }) {
const now = Date.now()
return (
<>
<div>
Hello, browser! Now: "<span suppressHydrationWarning>{now}</span>"
</div>
<hr />
{children}
</>
)
}
import type { ReactNode } from 'react'
import { SyncIOInClient } from './client'
// Make sure that the holes from this layout aren't factored in for validation
// (otherwise, we'd check a navigation into it from the root layout and fail)
export const unstable_instant = false
export default function Layout({ children }: { children: ReactNode }) {
return (
<>
<div>
<p>
This layout renders a client component that uses sync IO. We're
simulating a browser navigation, so sync IO in client components is
fine and should not prevent us from validating.
</p>
<SyncIOInClient>{children}</SyncIOInClient>
</div>
</>
)
}
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return (
<main>
<p>This page is static, so it should pass instant validation</p>
</main>
)
}
'use client'
import { use } from 'react'
import { useDataCache } from '../../../../client-data-fetching-lib/client'
export function FetchesClientData() {
const dataCache = useDataCache()
const promise = dataCache.getOrLoad('my-key', async () => {
await new Promise<void>((resolve) => setTimeout(resolve, 10))
return 'My client data result'
})
const data = use(promise)
return <div>Got client data: "{data}"</div>
}
import type { ReactNode } from 'react'
import { FetchesClientData } from './client'
import { DataCacheProvider } from '../../../../client-data-fetching-lib/server'
// Make sure that the holes from this layout aren't factored in for validation
// (otherwise, we'd check a navigation into it from the root layout and fail)
export const unstable_instant = false
export default function Layout({ children }: { children: ReactNode }) {
return (
<DataCacheProvider>
<div>
<p>
This layout renders a client component that suspends in SSR, but it
doesn't not block the children, so we can still validate them.
</p>
<FetchesClientData />
</div>
<hr />
{children}
</DataCacheProvider>
)
}
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return (
<main>
<p>
This page is static, so it should pass instant validation, but client
data fetching above will prevent us from validating it.
</p>
</main>
)
}
'use client'
export function ErrorInSSR() {
if (typeof window === 'undefined') {
throw new Error('No SSR please')
}
return null
}
import { Suspense, type ReactNode } from 'react'
import { ErrorInSSR } from './client'
// Make sure that the holes from this layout aren't factored in for validation
// (otherwise, we'd check a navigation into it from the root layout and fail)
export const unstable_instant = false
export default function Layout({ children }: { children: ReactNode }) {
return (
<>
<div>
<p>
This layout errors in SSR, but the error is wrapped in Suspense and
does not block the children slot, so it does not prevent us from
validating the page.
</p>
<Suspense>
<ErrorInSSR />
</Suspense>
{children}
</div>
</>
)
}
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return (
<main>
<p>This page is static, so it should pass instant validation</p>
</main>
)
}
import 'client-only'
import { use } from 'react'
import { CacheIdentifierContext } from './internal-context'
export interface CacheIdentifier {}
const cacheById = new WeakMap<CacheIdentifier, DataCache>()
export type DataCache = Map<string, Promise<unknown>>
function createDataCache(): DataCache {
return new Map()
}
export function useDataCache() {
const id = use(CacheIdentifierContext)
if (id === null) {
throw new Error('Missing DataCacheProvider')
}
let cache = cacheById.get(id)
if (!cache) {
cacheById.set(id, (cache = createDataCache()))
}
return {
getOrLoad<T>(key: string, func: () => Promise<T>): Promise<T> {
let promise = cache.get(key) as Promise<T> | undefined
if (!promise) {
console.log('client-data-fetching-lib :: MISS', key)
cache.set(key, (promise = func()))
} else {
console.log('client-data-fetching-lib :: HIT', key)
}
return promise
},
}
}
'use client'
import { createContext } from 'react'
import type { CacheIdentifier } from './client'
export const CacheIdentifierContext = createContext<CacheIdentifier | null>(
null
)
import 'server-only'
import { CacheIdentifierContext } from './internal-context'
export function DataCacheProvider({ children }) {
// This object is used as a key a WeakMap of caches.
// This is a trick to make sure each SSR render gets a separate cache
// without worrying about client state getting reset due to suspense.
//
// It'll be a unique object every time we deserialize this RSC payload,
// so each client render gets a separate id and thus a separate cache.
const id = {}
return <CacheIdentifierContext value={id}>{children}</CacheIdentifierContext>
}
......@@ -72,7 +72,7 @@ interface ErrorSnapshotOptions {
label?: boolean
}
interface ErrorSnapshot {
export interface ErrorSnapshot {
environmentLabel: string | null
label: string | null
description: string | null
......@@ -201,9 +201,9 @@ async function createErrorSnapshot(
return snapshot
}
type RedboxSnapshot = ErrorSnapshot | ErrorSnapshot[]
export type RedboxSnapshot = ErrorSnapshot | ErrorSnapshot[]
async function createRedboxSnapshot(
export async function createRedboxSnapshot(
browser: Playwright,
next: NextInstance | null,
opts?: ErrorSnapshotOptions
......
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