Commit 020cd2a5 authored by Janka Uryga's avatar Janka Uryga

split up spawnDynamicValidationInDev

parent 96c7f240
...@@ -15,8 +15,10 @@ import { ...@@ -15,8 +15,10 @@ import {
type WorkStore, type WorkStore,
} from '../app-render/work-async-storage.external' } from '../app-render/work-async-storage.external'
import type { import type {
PrerenderStoreModernCommon,
PrerenderStoreModernRuntime, PrerenderStoreModernRuntime,
RequestStore, RequestStore,
StaticPrerenderStoreCommon,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import type { NextParsedUrlQuery } from '../request-meta' import type { NextParsedUrlQuery } from '../request-meta'
import type { LoaderTree } from '../lib/app-dir-module' import type { LoaderTree } from '../lib/app-dir-module'
...@@ -137,6 +139,8 @@ import { ...@@ -137,6 +139,8 @@ import {
consumeDynamicAccess, consumeDynamicAccess,
type DynamicAccess, type DynamicAccess,
logDisallowedDynamicError, logDisallowedDynamicError,
type DynamicTrackingState,
type DynamicValidationState,
} from './dynamic-rendering' } from './dynamic-rendering'
import { import {
getClientComponentLoaderMetrics, getClientComponentLoaderMetrics,
...@@ -1067,7 +1071,12 @@ async function getRSCPayload( ...@@ -1067,7 +1071,12 @@ async function getRSCPayload(
tree: LoaderTree, tree: LoaderTree,
ctx: AppRenderContext, ctx: AppRenderContext,
is404: boolean is404: boolean
): Promise<InitialRSCPayload & { P: React.ReactNode }> { ): Promise<
InitialRSCPayload & {
/** preloads */
P: React.ReactNode
}
> {
const injectedCSS = new Set<string>() const injectedCSS = new Set<string>()
const injectedJS = new Set<string>() const injectedJS = new Set<string>()
const injectedFontPreloadTags = new Set<string>() const injectedFontPreloadTags = new Set<string>()
...@@ -2610,19 +2619,9 @@ async function spawnDynamicValidationInDev( ...@@ -2610,19 +2619,9 @@ async function spawnDynamicValidationInDev(
const { const {
componentMod: ComponentMod, componentMod: ComponentMod,
getDynamicParamFromSegment, getDynamicParamFromSegment,
implicitTags,
nonce,
renderOpts,
workStore, workStore,
} = ctx } = ctx
const { allowEmptyStaticShell = false } = renderOpts
// These values are placeholder values for this validating render
// that are provided during the actual prerenderToStream.
const preinitScripts = () => {}
const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
const rootParams = getRootParams( const rootParams = getRootParams(
ComponentMod.routeModule.userland.loaderTree, ComponentMod.routeModule.userland.loaderTree,
getDynamicParamFromSegment getDynamicParamFromSegment
...@@ -2632,6 +2631,164 @@ async function spawnDynamicValidationInDev( ...@@ -2632,6 +2631,164 @@ async function spawnDynamicValidationInDev(
NEXT_HMR_REFRESH_HASH_COOKIE NEXT_HMR_REFRESH_HASH_COOKIE
)?.value )?.value
// The resume data cache here should use a fresh instance as it's
// performing a fresh prerender. If we get to implementing the
// prerendering of an already prerendered page, we should use the passed
// resume data cache instead.
const prerenderResumeDataCache = createPrerenderResumeDataCache()
//==================================
// Prospective prerender
//==================================
const prospectiveServerResult =
await dynamicValidationProspectiveServerPrerender(
tree,
ctx,
isNotFound,
clientReferenceManifest,
///
hmrRefreshHash,
rootParams,
fallbackRouteParams,
prerenderResumeDataCache
)
if (prospectiveServerResult.type === 'error') {
resolveValidation(
<LogSafely
fn={console.error.bind(console, prospectiveServerResult.error)}
/>
)
return
}
// If the prerender errored for other reasons than dynamic usage,
// we might not have a usable result. We'll error for it in the final prerender.
if (prospectiveServerResult.value) {
await dynamicValidationProspectiveClientPrerender(
ctx,
clientReferenceManifest,
///
hmrRefreshHash,
rootParams,
fallbackRouteParams,
prerenderResumeDataCache,
///
prospectiveServerResult.value
)
}
//==================================
// Final prerender
//==================================
const serverDynamicTracking = createDynamicTrackingState(
false // isDebugDynamicAccesses
)
const clientDynamicTracking = createDynamicTrackingState(
false // isDebugDynamicAccesses
)
const reactServerResult = await dynamicValidationFinalServerPrerender(
tree,
ctx,
isNotFound,
clientReferenceManifest,
///
hmrRefreshHash,
rootParams,
fallbackRouteParams,
prerenderResumeDataCache,
///
serverDynamicTracking
)
const dynamicValidation = createDynamicValidationState()
try {
const { prelude: unprocessedPrelude } =
await dynamicValidationFinalClientPrerender(
ctx,
clientReferenceManifest,
///
hmrRefreshHash,
rootParams,
fallbackRouteParams,
prerenderResumeDataCache,
///
reactServerResult,
clientDynamicTracking,
dynamicValidation
)
const { preludeIsEmpty } = await processPrelude(unprocessedPrelude)
resolveValidation(
<LogSafely
fn={throwIfDisallowedDynamic.bind(
null,
workStore,
preludeIsEmpty ? PreludeState.Empty : PreludeState.Full,
dynamicValidation,
serverDynamicTracking
)}
/>
)
} catch (thrownValue) {
// Even if the root errors we still want to report any cache components errors
// that were discovered before the root errored.
let loggingFunction = throwIfDisallowedDynamic.bind(
null,
workStore,
PreludeState.Errored,
dynamicValidation,
serverDynamicTracking
)
if (process.env.NEXT_DEBUG_BUILD || process.env.__NEXT_VERBOSE_LOGGING) {
// We don't normally log these errors because we are going to retry anyway but
// it can be useful for debugging Next.js itself to get visibility here when needed
const originalLoggingFunction = loggingFunction
loggingFunction = () => {
console.error(
'During dynamic validation the root of the page errored. The next logged error is the thrown value. It may be a duplicate of errors reported during the normal development mode render.'
)
console.error(thrownValue)
originalLoggingFunction()
}
}
resolveValidation(<LogSafely fn={loggingFunction} />)
}
}
type Result<T, E = unknown> =
| { type: 'ok'; value: T }
| { type: 'error'; error: E }
async function dynamicValidationProspectiveServerPrerender(
tree: LoaderTree,
ctx: AppRenderContext,
isNotFound: boolean,
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>,
///
hmrRefreshHash: PrerenderStoreModernCommon['hmrRefreshHash'],
rootParams: PrerenderStoreModernCommon['rootParams'],
fallbackRouteParams: StaticPrerenderStoreCommon['fallbackRouteParams'],
prerenderResumeDataCache: PrerenderStoreModernCommon['prerenderResumeDataCache']
): Promise<Result<ReactServerPrerenderResult | null, Error>> {
const {
componentMod: ComponentMod,
implicitTags,
renderOpts,
workStore,
} = ctx
const { allowEmptyStaticShell = false } = renderOpts
const captureOwnerStack = ComponentMod.captureOwnerStack
// The prerender controller represents the lifetime of the prerender. It will // The prerender controller represents the lifetime of the prerender. It will
// be aborted when a task is complete or a synchronously aborting API is // be aborted when a task is complete or a synchronously aborting API is
// called. Notably, during prospective prerenders, this does not actually // called. Notably, during prospective prerenders, this does not actually
...@@ -2658,14 +2815,6 @@ async function spawnDynamicValidationInDev( ...@@ -2658,14 +2815,6 @@ async function spawnDynamicValidationInDev(
// ready to cut the render off. // ready to cut the render off.
const cacheSignal = new CacheSignal() const cacheSignal = new CacheSignal()
const captureOwnerStackClient = React.captureOwnerStack
const captureOwnerStackServer = ComponentMod.captureOwnerStack
// The resume data cache here should use a fresh instance as it's
// performing a fresh prerender. If we get to implementing the
// prerendering of an already prerendered page, we should use the passed
// resume data cache instead.
const prerenderResumeDataCache = createPrerenderResumeDataCache()
const initialServerPayloadPrerenderStore: PrerenderStore = { const initialServerPayloadPrerenderStore: PrerenderStore = {
type: 'prerender', type: 'prerender',
phase: 'render', phase: 'render',
...@@ -2692,7 +2841,7 @@ async function spawnDynamicValidationInDev( ...@@ -2692,7 +2841,7 @@ async function spawnDynamicValidationInDev(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null, renderResumeDataCache: null,
hmrRefreshHash, hmrRefreshHash,
captureOwnerStack: captureOwnerStackServer, captureOwnerStack,
} }
// We're not going to use the result of this render because the only time it could be used // We're not going to use the result of this render because the only time it could be used
...@@ -2726,7 +2875,7 @@ async function spawnDynamicValidationInDev( ...@@ -2726,7 +2875,7 @@ async function spawnDynamicValidationInDev(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null, renderResumeDataCache: null,
hmrRefreshHash, hmrRefreshHash,
captureOwnerStack: captureOwnerStackServer, captureOwnerStack,
} }
const pendingInitialServerResult = workUnitAsyncStorage.run( const pendingInitialServerResult = workUnitAsyncStorage.run(
...@@ -2791,21 +2940,14 @@ async function spawnDynamicValidationInDev( ...@@ -2791,21 +2940,14 @@ async function spawnDynamicValidationInDev(
// detected invalid dynamic usage in the initial prerender phase. // detected invalid dynamic usage in the initial prerender phase.
const { invalidDynamicUsageError } = workStore const { invalidDynamicUsageError } = workStore
if (invalidDynamicUsageError) { if (invalidDynamicUsageError) {
resolveValidation( return { type: 'error', error: invalidDynamicUsageError }
<LogSafely
fn={() => {
console.error(invalidDynamicUsageError)
}}
/>
)
return
} }
let initialServerResult
try { try {
initialServerResult = await createReactServerPrerenderResult( return {
pendingInitialServerResult type: 'ok',
) value: await createReactServerPrerenderResult(pendingInitialServerResult),
}
} catch (err) { } catch (err) {
if ( if (
initialServerReactController.signal.aborted || initialServerReactController.signal.aborted ||
...@@ -2820,113 +2962,156 @@ async function spawnDynamicValidationInDev( ...@@ -2820,113 +2962,156 @@ async function spawnDynamicValidationInDev(
// it can be useful for debugging Next.js itself to get visibility here when needed // it can be useful for debugging Next.js itself to get visibility here when needed
printDebugThrownValueForProspectiveRender(err, workStore.route) printDebugThrownValueForProspectiveRender(err, workStore.route)
} }
return { type: 'ok', value: null }
} }
}
if (initialServerResult) { async function dynamicValidationProspectiveClientPrerender(
const initialClientPrerenderController = new AbortController() ctx: AppRenderContext,
const initialClientReactController = new AbortController() clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>,
const initialClientRenderController = new AbortController() ///
hmrRefreshHash: PrerenderStoreModernCommon['hmrRefreshHash'],
rootParams: PrerenderStoreModernCommon['rootParams'],
fallbackRouteParams: StaticPrerenderStoreCommon['fallbackRouteParams'],
prerenderResumeDataCache: PrerenderStoreModernCommon['prerenderResumeDataCache'],
///
initialServerResult: ReactServerPrerenderResult
): Promise<void> {
const { implicitTags, nonce, renderOpts, workStore } = ctx
const initialClientPrerenderStore: PrerenderStore = { const { allowEmptyStaticShell = false } = renderOpts
type: 'prerender-client',
phase: 'render',
rootParams,
fallbackRouteParams,
implicitTags,
renderSignal: initialClientRenderController.signal,
controller: initialClientPrerenderController,
// For HTML Generation the only cache tracked activity
// is module loading, which has it's own cache signal
cacheSignal: null,
dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
prerenderResumeDataCache,
renderResumeDataCache: null,
hmrRefreshHash: undefined,
captureOwnerStack: captureOwnerStackClient,
}
const prerender = ( // These values are placeholder values for this validating render
require('react-dom/static') as typeof import('react-dom/static') // that are provided during the actual prerenderToStream.
).prerender const preinitScripts = () => {}
const pendingInitialClientResult = workUnitAsyncStorage.run( const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
initialClientPrerenderStore,
prerender,
<App
reactServerStream={initialServerResult.asUnclosingStream()}
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
/>,
{
signal: initialClientReactController.signal,
onError: (err) => {
const digest = getDigestForWellKnownError(err)
if (digest) { const captureOwnerStack = React.captureOwnerStack
return digest
}
if (isReactLargeShellError(err)) { const initialClientPrerenderController = new AbortController()
// TODO: Aggregate const initialClientReactController = new AbortController()
console.error(err) const initialClientRenderController = new AbortController()
return undefined
}
if (initialClientReactController.signal.aborted) { const cacheSignal = new CacheSignal()
// These are expected errors that might error the prerender. we ignore them.
} else if (
process.env.NEXT_DEBUG_BUILD ||
process.env.__NEXT_VERBOSE_LOGGING
) {
// We don't normally log these errors because we are going to retry anyway but
// it can be useful for debugging Next.js itself to get visibility here when needed
printDebugThrownValueForProspectiveRender(err, workStore.route)
}
},
// We don't need bootstrap scripts in this prerender
// bootstrapScripts: [bootstrapScript],
}
)
// The listener to abort our own render controller must be added after React const initialClientPrerenderStore: PrerenderStore = {
// has added its listener, to ensure that pending I/O is not type: 'prerender-client',
// aborted/rejected too early. phase: 'render',
initialClientReactController.signal.addEventListener( rootParams,
'abort', fallbackRouteParams,
() => { implicitTags,
initialClientRenderController.abort() renderSignal: initialClientRenderController.signal,
controller: initialClientPrerenderController,
// For HTML Generation the only cache tracked activity
// is module loading, which has it's own cache signal
cacheSignal: null,
dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
prerenderResumeDataCache,
renderResumeDataCache: null,
hmrRefreshHash,
captureOwnerStack,
}
const prerender = (
require('react-dom/static') as typeof import('react-dom/static')
).prerender
const pendingInitialClientResult = workUnitAsyncStorage.run(
initialClientPrerenderStore,
prerender,
<App
reactServerStream={initialServerResult.asUnclosingStream()}
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
/>,
{
signal: initialClientReactController.signal,
onError: (err) => {
const digest = getDigestForWellKnownError(err)
if (digest) {
return digest
}
if (isReactLargeShellError(err)) {
// TODO: Aggregate
console.error(err)
return undefined
}
if (initialClientReactController.signal.aborted) {
// These are expected errors that might error the prerender. we ignore them.
} else if (
process.env.NEXT_DEBUG_BUILD ||
process.env.__NEXT_VERBOSE_LOGGING
) {
// We don't normally log these errors because we are going to retry anyway but
// it can be useful for debugging Next.js itself to get visibility here when needed
printDebugThrownValueForProspectiveRender(err, workStore.route)
}
}, },
{ once: true } // We don't need bootstrap scripts in this prerender
) // bootstrapScripts: [bootstrapScript],
}
)
pendingInitialClientResult.catch((err) => { // The listener to abort our own render controller must be added after React
if ( // has added its listener, to ensure that pending I/O is not
initialClientReactController.signal.aborted || // aborted/rejected too early.
isPrerenderInterruptedError(err) initialClientReactController.signal.addEventListener(
) { 'abort',
// These are expected errors that might error the prerender. we ignore them. () => {
} else if ( initialClientRenderController.abort()
process.env.NEXT_DEBUG_BUILD || },
process.env.__NEXT_VERBOSE_LOGGING { once: true }
) { )
// We don't normally log these errors because we are going to retry anyway but
// it can be useful for debugging Next.js itself to get visibility here when needed
printDebugThrownValueForProspectiveRender(err, workStore.route)
}
})
// This is mostly needed for dynamic `import()`s in client components. pendingInitialClientResult.catch((err) => {
// Promises passed to client were already awaited above (assuming that they came from cached functions) if (
trackPendingModules(cacheSignal) initialClientReactController.signal.aborted ||
await cacheSignal.cacheReady() isPrerenderInterruptedError(err)
initialClientReactController.abort() ) {
} // These are expected errors that might error the prerender. we ignore them.
} else if (
process.env.NEXT_DEBUG_BUILD ||
process.env.__NEXT_VERBOSE_LOGGING
) {
// We don't normally log these errors because we are going to retry anyway but
// it can be useful for debugging Next.js itself to get visibility here when needed
printDebugThrownValueForProspectiveRender(err, workStore.route)
}
})
// This is mostly needed for dynamic `import()`s in client components.
// Promises passed to client were already awaited above (assuming that they came from cached functions)
trackPendingModules(cacheSignal)
await cacheSignal.cacheReady()
initialClientReactController.abort()
}
async function dynamicValidationFinalServerPrerender(
tree: LoaderTree,
ctx: AppRenderContext,
isNotFound: boolean,
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>,
///
hmrRefreshHash: PrerenderStoreModernCommon['hmrRefreshHash'],
rootParams: PrerenderStoreModernCommon['rootParams'],
fallbackRouteParams: StaticPrerenderStoreCommon['fallbackRouteParams'],
prerenderResumeDataCache: PrerenderStoreModernCommon['prerenderResumeDataCache'],
///
dynamicTracking: DynamicTrackingState
): Promise<ReactServerPrerenderResult> {
const { componentMod: ComponentMod, implicitTags, renderOpts } = ctx
const { allowEmptyStaticShell = false } = renderOpts
const captureOwnerStack = ComponentMod.captureOwnerStack
const finalServerReactController = new AbortController() const finalServerReactController = new AbortController()
const finalServerRenderController = new AbortController() const finalServerRenderController = new AbortController()
...@@ -2955,7 +3140,7 @@ async function spawnDynamicValidationInDev( ...@@ -2955,7 +3140,7 @@ async function spawnDynamicValidationInDev(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null, renderResumeDataCache: null,
hmrRefreshHash, hmrRefreshHash,
captureOwnerStack: captureOwnerStackServer, captureOwnerStack,
} }
const finalAttemptRSCPayload = await workUnitAsyncStorage.run( const finalAttemptRSCPayload = await workUnitAsyncStorage.run(
...@@ -2966,10 +3151,6 @@ async function spawnDynamicValidationInDev( ...@@ -2966,10 +3151,6 @@ async function spawnDynamicValidationInDev(
isNotFound isNotFound
) )
const serverDynamicTracking = createDynamicTrackingState(
false // isDebugDynamicAccesses
)
const finalServerPrerenderStore: PrerenderStore = { const finalServerPrerenderStore: PrerenderStore = {
type: 'prerender', type: 'prerender',
phase: 'render', phase: 'render',
...@@ -2980,7 +3161,7 @@ async function spawnDynamicValidationInDev( ...@@ -2980,7 +3161,7 @@ async function spawnDynamicValidationInDev(
controller: finalServerReactController, controller: finalServerReactController,
// All caches we could read must already be filled so no tracking is necessary // All caches we could read must already be filled so no tracking is necessary
cacheSignal: null, cacheSignal: null,
dynamicTracking: serverDynamicTracking, dynamicTracking,
allowEmptyStaticShell, allowEmptyStaticShell,
revalidate: INFINITE_CACHE, revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE, expire: INFINITE_CACHE,
...@@ -2989,10 +3170,10 @@ async function spawnDynamicValidationInDev( ...@@ -2989,10 +3170,10 @@ async function spawnDynamicValidationInDev(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null, renderResumeDataCache: null,
hmrRefreshHash, hmrRefreshHash,
captureOwnerStack: captureOwnerStackServer, captureOwnerStack,
} }
const reactServerResult = await createReactServerPrerenderResult( return await createReactServerPrerenderResult(
prerenderAndAbortInSequentialTasks( prerenderAndAbortInSequentialTasks(
async () => { async () => {
const pendingPrerenderResult = workUnitAsyncStorage.run( const pendingPrerenderResult = workUnitAsyncStorage.run(
...@@ -3043,10 +3224,31 @@ async function spawnDynamicValidationInDev( ...@@ -3043,10 +3224,31 @@ async function spawnDynamicValidationInDev(
} }
) )
) )
}
async function dynamicValidationFinalClientPrerender(
ctx: AppRenderContext,
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>,
///
hmrRefreshHash: PrerenderStoreModernCommon['hmrRefreshHash'],
rootParams: PrerenderStoreModernCommon['rootParams'],
fallbackRouteParams: StaticPrerenderStoreCommon['fallbackRouteParams'],
prerenderResumeDataCache: PrerenderStoreModernCommon['prerenderResumeDataCache'],
///
reactServerResult: ReactServerPrerenderResult,
dynamicTracking: DynamicTrackingState,
dynamicValidation: DynamicValidationState
): Promise<import('react-dom/static').PrerenderResult> {
const { implicitTags, nonce, renderOpts, workStore } = ctx
const { allowEmptyStaticShell = false } = renderOpts
// These values are placeholder values for this validating render
// that are provided during the actual prerenderToStream.
const preinitScripts = () => {}
const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
const captureOwnerStack = React.captureOwnerStack
const clientDynamicTracking = createDynamicTrackingState(
false //isDebugDynamicAccesses
)
const finalClientReactController = new AbortController() const finalClientReactController = new AbortController()
const finalClientRenderController = new AbortController() const finalClientRenderController = new AbortController()
...@@ -3060,7 +3262,7 @@ async function spawnDynamicValidationInDev( ...@@ -3060,7 +3262,7 @@ async function spawnDynamicValidationInDev(
controller: finalClientReactController, controller: finalClientReactController,
// No APIs require a cacheSignal through the workUnitStore during the HTML prerender // No APIs require a cacheSignal through the workUnitStore during the HTML prerender
cacheSignal: null, cacheSignal: null,
dynamicTracking: clientDynamicTracking, dynamicTracking,
allowEmptyStaticShell, allowEmptyStaticShell,
revalidate: INFINITE_CACHE, revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE, expire: INFINITE_CACHE,
...@@ -3069,117 +3271,74 @@ async function spawnDynamicValidationInDev( ...@@ -3069,117 +3271,74 @@ async function spawnDynamicValidationInDev(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null, renderResumeDataCache: null,
hmrRefreshHash, hmrRefreshHash,
captureOwnerStack: captureOwnerStackClient, captureOwnerStack,
} }
let dynamicValidation = createDynamicValidationState() const prerender = (
require('react-dom/static') as typeof import('react-dom/static')
).prerender
try { return await prerenderAndAbortInSequentialTasks(
const prerender = ( () => {
require('react-dom/static') as typeof import('react-dom/static') const pendingFinalClientResult = workUnitAsyncStorage.run(
).prerender finalClientPrerenderStore,
let { prelude: unprocessedPrelude } = prerender,
await prerenderAndAbortInSequentialTasks( <App
() => { reactServerStream={reactServerResult.asUnclosingStream()}
const pendingFinalClientResult = workUnitAsyncStorage.run( preinitScripts={preinitScripts}
finalClientPrerenderStore, clientReferenceManifest={clientReferenceManifest}
prerender, ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
<App nonce={nonce}
reactServerStream={reactServerResult.asUnclosingStream()} />,
preinitScripts={preinitScripts} {
clientReferenceManifest={clientReferenceManifest} signal: finalClientReactController.signal,
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} onError: (err: unknown, errorInfo: ErrorInfo) => {
nonce={nonce} if (
/>, isPrerenderInterruptedError(err) ||
{ finalClientReactController.signal.aborted
signal: finalClientReactController.signal, ) {
onError: (err: unknown, errorInfo: ErrorInfo) => { const componentStack = errorInfo.componentStack
if ( if (typeof componentStack === 'string') {
isPrerenderInterruptedError(err) || trackAllowedDynamicAccess(
finalClientReactController.signal.aborted workStore,
) { componentStack,
const componentStack = errorInfo.componentStack dynamicValidation,
if (typeof componentStack === 'string') { dynamicTracking
trackAllowedDynamicAccess( )
workStore, }
componentStack, return
dynamicValidation,
clientDynamicTracking
)
}
return
}
if (isReactLargeShellError(err)) {
// TODO: Aggregate
console.error(err)
return undefined
}
return getDigestForWellKnownError(err)
},
// We don't need bootstrap scripts in this prerender
// bootstrapScripts: [bootstrapScript],
} }
)
// The listener to abort our own render controller must be added after if (isReactLargeShellError(err)) {
// React has added its listener, to ensure that pending I/O is not // TODO: Aggregate
// aborted/rejected too early. console.error(err)
finalClientReactController.signal.addEventListener( return undefined
'abort', }
() => {
finalClientRenderController.abort()
},
{ once: true }
)
return pendingFinalClientResult return getDigestForWellKnownError(err)
}, },
() => { // We don't need bootstrap scripts in this prerender
finalClientReactController.abort() // bootstrapScripts: [bootstrapScript],
} }
) )
const { preludeIsEmpty } = await processPrelude(unprocessedPrelude) // The listener to abort our own render controller must be added after
resolveValidation( // React has added its listener, to ensure that pending I/O is not
<LogSafely // aborted/rejected too early.
fn={throwIfDisallowedDynamic.bind( finalClientReactController.signal.addEventListener(
null, 'abort',
workStore, () => {
preludeIsEmpty ? PreludeState.Empty : PreludeState.Full, finalClientRenderController.abort()
dynamicValidation, },
serverDynamicTracking { once: true }
)} )
/>
)
} catch (thrownValue) {
// Even if the root errors we still want to report any cache components errors
// that were discovered before the root errored.
let loggingFunction = throwIfDisallowedDynamic.bind(
null,
workStore,
PreludeState.Errored,
dynamicValidation,
serverDynamicTracking
)
if (process.env.NEXT_DEBUG_BUILD || process.env.__NEXT_VERBOSE_LOGGING) { return pendingFinalClientResult
// We don't normally log these errors because we are going to retry anyway but },
// it can be useful for debugging Next.js itself to get visibility here when needed () => {
const originalLoggingFunction = loggingFunction finalClientReactController.abort()
loggingFunction = () => {
console.error(
'During dynamic validation the root of the page errored. The next logged error is the thrown value. It may be a duplicate of errors reported during the normal development mode render.'
)
console.error(thrownValue)
originalLoggingFunction()
}
} }
)
resolveValidation(<LogSafely fn={loggingFunction} />)
}
} }
async function LogSafely({ fn }: { fn: () => unknown }) { async function LogSafely({ fn }: { fn: () => unknown }) {
......
...@@ -132,7 +132,7 @@ export interface RevalidateStore { ...@@ -132,7 +132,7 @@ export interface RevalidateStore {
tags: null | string[] tags: null | string[]
} }
interface PrerenderStoreModernCommon export interface PrerenderStoreModernCommon
extends CommonWorkUnitStore, extends CommonWorkUnitStore,
RevalidateStore { RevalidateStore {
/** /**
...@@ -198,7 +198,7 @@ interface PrerenderStoreModernCommon ...@@ -198,7 +198,7 @@ interface PrerenderStoreModernCommon
readonly captureOwnerStack: undefined | (() => string | null) readonly captureOwnerStack: undefined | (() => string | null)
} }
interface StaticPrerenderStoreCommon { export interface StaticPrerenderStoreCommon {
/** /**
* The set of unknown route parameters. Accessing these will be tracked as * The set of unknown route parameters. Accessing these will be tracked as
* a dynamic access. * a dynamic access.
......
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