Unverified Commit 1c1d9b5f authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Use and enforce exhaustive switch statements for work unit store (#81577)

This allows us to introduce more work unit store types with confidence.

closes NAR-203
parent 079c06d3
...@@ -316,6 +316,16 @@ ...@@ -316,6 +316,16 @@
{ {
"message": "substr() is deprecated, use slice() or substring() instead", "message": "substr() is deprecated, use slice() or substring() instead",
"selector": "MemberExpression > Identifier[name='substr']" "selector": "MemberExpression > Identifier[name='substr']"
},
// ban plain workUnitStore.type if statements and ternaries
{
"selector": "BinaryExpression[left.object.name='workUnitStore'][left.property.name='type'][operator=/^(?:===|!==)$/]",
"message": "Use an exhaustive switch on `workUnitStore.type` (with a `never`-based default) instead of using if statements or ternaries."
},
// ban optional-chained workUnitStore?.type if statements and ternaries
{
"selector": "BinaryExpression[left.type='ChainExpression'][left.expression.object.name='workUnitStore'][left.expression.property.name='type'][operator=/^(?:===|!==)$/]",
"message": "Use an exhaustive switch on `workUnitStore.type` (with a `never`-based default) instead of using if statements or ternaries."
} }
], ],
"no-script-url": "error", "no-script-url": "error",
......
...@@ -717,5 +717,6 @@ ...@@ -717,5 +717,6 @@
"716": "NEXT_DEVTOOLS_SIMULATED_ERROR", "716": "NEXT_DEVTOOLS_SIMULATED_ERROR",
"717": "Unsupported environment condition \"%s\" and react condition \"%s\". This is a bug in Next.js.", "717": "Unsupported environment condition \"%s\" and react condition \"%s\". This is a bug in Next.js.",
"718": "Invariant: projectDir is required for node runtime", "718": "Invariant: projectDir is required for node runtime",
"719": "Failed to get source map for '%s'. This is a bug in Next.js" "719": "Failed to get source map for '%s'. This is a bug in Next.js",
"720": "A client prerender store should not be used for a route handler."
} }
...@@ -16,7 +16,12 @@ export function bailoutToClientRendering(reason: string): void | never { ...@@ -16,7 +16,12 @@ export function bailoutToClientRendering(reason: string): void | never {
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
throw new BailoutToCSRError(reason) throw new BailoutToCSRError(reason)
case 'request':
case 'cache':
case 'unstable-cache':
break
default: default:
workUnitStore satisfies never
} }
} }
} }
...@@ -1233,12 +1233,24 @@ async function renderToHTMLOrFlightImpl( ...@@ -1233,12 +1233,24 @@ async function renderToHTMLOrFlightImpl(
return true return true
} }
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
return !!(
workUnitStore && if (!workUnitStore) {
(workUnitStore.type === 'prerender' || return false
workUnitStore.type === 'prerender-client' || }
workUnitStore.type === 'cache')
) switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'cache':
return true
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'unstable-cache':
return false
default:
workUnitStore satisfies never
}
} }
const __next_require__: typeof instrumented.require = (...args) => { const __next_require__: typeof instrumented.require = (...args) => {
......
...@@ -293,15 +293,21 @@ async function createComponentTreeInternal({ ...@@ -293,15 +293,21 @@ async function createComponentTreeInternal({
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) { if (workUnitStore) {
if ( switch (workUnitStore.type) {
workUnitStore.type === 'prerender' || case 'prerender':
workUnitStore.type === 'prerender-legacy' || case 'prerender-legacy':
workUnitStore.type === 'prerender-ppr' || case 'prerender-ppr':
workUnitStore.type === 'cache' case 'cache':
) { if (workUnitStore.revalidate > defaultRevalidate) {
if (workUnitStore.revalidate > defaultRevalidate) { workUnitStore.revalidate = defaultRevalidate
workUnitStore.revalidate = defaultRevalidate }
} break
case 'prerender-client':
case 'request':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
} }
} }
......
...@@ -122,14 +122,20 @@ export function markCurrentScopeAsDynamic( ...@@ -122,14 +122,20 @@ export function markCurrentScopeAsDynamic(
expression: string expression: string
): void { ): void {
if (workUnitStore) { if (workUnitStore) {
if ( switch (workUnitStore.type) {
workUnitStore.type === 'cache' || case 'cache':
workUnitStore.type === 'unstable-cache' case 'unstable-cache':
) { // Inside cache scopes, marking a scope as dynamic has no effect,
// inside cache scopes marking a scope as dynamic has no effect because the outer cache scope // because the outer cache scope creates a cache boundary. This is
// creates a cache boundary. This is subtly different from reading a dynamic data source which is // subtly different from reading a dynamic data source, which is
// forbidden inside a cache scope. // forbidden inside a cache scope.
return return
case 'prerender-legacy':
case 'prerender-ppr':
case 'request':
break
default:
workUnitStore satisfies never
} }
} }
...@@ -145,51 +151,36 @@ export function markCurrentScopeAsDynamic( ...@@ -145,51 +151,36 @@ export function markCurrentScopeAsDynamic(
} }
if (workUnitStore) { if (workUnitStore) {
if (workUnitStore.type === 'prerender-ppr') { switch (workUnitStore.type) {
postponeWithTracking( case 'prerender-ppr':
store.route, return postponeWithTracking(
expression, store.route,
workUnitStore.dynamicTracking expression,
) workUnitStore.dynamicTracking
} else if (workUnitStore.type === 'prerender-legacy') { )
workUnitStore.revalidate = 0 case 'prerender-legacy':
workUnitStore.revalidate = 0
// We aren't prerendering but we are generating a static page. We need to bail out of static generation // We aren't prerendering, but we are generating a static page. We need
const err = new DynamicServerError( // to bail out of static generation.
`Route ${store.route} couldn't be rendered statically because it used ${expression}. See more info here: https://nextjs.org/docs/messages/dynamic-server-error` const err = new DynamicServerError(
) `Route ${store.route} couldn't be rendered statically because it used ${expression}. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`
store.dynamicUsageDescription = expression )
store.dynamicUsageStack = err.stack store.dynamicUsageDescription = expression
store.dynamicUsageStack = err.stack
throw err
} else if ( throw err
process.env.NODE_ENV === 'development' && case 'request':
workUnitStore && if (process.env.NODE_ENV !== 'production') {
workUnitStore.type === 'request' workUnitStore.usedDynamic = true
) { }
workUnitStore.usedDynamic = true break
default:
workUnitStore satisfies never
} }
} }
} }
/**
* This function communicates that some dynamic path parameter was read. This
* differs from the more general `trackDynamicDataAccessed` in that it is will
* not error when `dynamic = "error"` is set.
*
* @param store The static generation store
* @param expression The expression that was accessed dynamically
*/
export function trackFallbackParamAccessed(
store: WorkStore,
expression: string
): void {
const prerenderStore = workUnitAsyncStorage.getStore()
if (!prerenderStore || prerenderStore.type !== 'prerender-ppr') return
postponeWithTracking(store.route, expression, prerenderStore.dynamicTracking)
}
/** /**
* This function is meant to be used when prerendering without dynamicIO or PPR. * This function is meant to be used when prerendering without dynamicIO or PPR.
* When called during a build it will cause Next.js to consider the route as dynamic. * When called during a build it will cause Next.js to consider the route as dynamic.
...@@ -221,34 +212,27 @@ export function throwToInterruptStaticGeneration( ...@@ -221,34 +212,27 @@ export function throwToInterruptStaticGeneration(
* *
* @internal * @internal
*/ */
export function trackDynamicDataInDynamicRender( export function trackDynamicDataInDynamicRender(workUnitStore: WorkUnitStore) {
_store: WorkStore, switch (workUnitStore.type) {
workUnitStore: void | WorkUnitStore case 'cache':
) { case 'unstable-cache':
if (workUnitStore) { // Inside cache scopes, marking a scope as dynamic has no effect,
if ( // because the outer cache scope creates a cache boundary. This is
workUnitStore.type === 'cache' || // subtly different from reading a dynamic data source, which is
workUnitStore.type === 'unstable-cache'
) {
// inside cache scopes marking a scope as dynamic has no effect because the outer cache scope
// creates a cache boundary. This is subtly different from reading a dynamic data source which is
// forbidden inside a cache scope. // forbidden inside a cache scope.
return return
} case 'prerender':
// TODO: it makes no sense to have these work unit store types during a dev render. case 'prerender-legacy':
if ( case 'prerender-ppr':
workUnitStore.type === 'prerender' || case 'prerender-client':
workUnitStore.type === 'prerender-client' || break
workUnitStore.type === 'prerender-legacy' case 'request':
) { if (process.env.NODE_ENV !== 'production') {
workUnitStore.revalidate = 0 workUnitStore.usedDynamic = true
} }
if ( break
process.env.NODE_ENV === 'development' && default:
workUnitStore.type === 'request' workUnitStore satisfies never
) {
workUnitStore.usedDynamic = true
}
} }
} }
...@@ -529,27 +513,40 @@ export function createPostponedAbortSignal(reason: string): AbortSignal { ...@@ -529,27 +513,40 @@ export function createPostponedAbortSignal(reason: string): AbortSignal {
* case we need to abort the encoding of arguments since they'll never complete. * case we need to abort the encoding of arguments since they'll never complete.
*/ */
export function createHangingInputAbortSignal( export function createHangingInputAbortSignal(
workUnitStore: PrerenderStoreModern workUnitStore: WorkUnitStore
): AbortSignal { ): AbortSignal | undefined {
const controller = new AbortController() switch (workUnitStore.type) {
case 'prerender':
const controller = new AbortController()
if (workUnitStore.cacheSignal) {
// If we have a cacheSignal it means we're in a prospective render. If
// the input we're waiting on is coming from another cache, we do want
// to wait for it so that we can resolve this cache entry too.
workUnitStore.cacheSignal.inputReady().then(() => {
controller.abort()
})
} else {
// Otherwise we're in the final render and we should already have all
// our caches filled. We might still be waiting on some microtasks so we
// wait one tick before giving up. When we give up, we still want to
// render the content of this cache as deeply as we can so that we can
// suspend as deeply as possible in the tree or not at all if we don't
// end up waiting for the input.
scheduleOnNextTick(() => controller.abort())
}
if (workUnitStore.cacheSignal) { return controller.signal
// If we have a cacheSignal it means we're in a prospective render. If the input case 'prerender-client':
// we're waiting on is coming from another cache, we do want to wait for it so that case 'prerender-ppr':
// we can resolve this cache entry too. case 'prerender-legacy':
workUnitStore.cacheSignal.inputReady().then(() => { case 'request':
controller.abort() case 'cache':
}) case 'unstable-cache':
} else { return undefined
// Otherwise we're in the final render and we should already have all our caches default:
// filled. We might still be waiting on some microtasks so we wait one tick before workUnitStore satisfies never
// giving up. When we give up, we still want to render the content of this cache
// as deeply as we can so that we can suspend as deeply as possible in the tree
// or not at all if we don't end up waiting for the input.
scheduleOnNextTick(() => controller.abort())
} }
return controller.signal
} }
export function annotateDynamicAccess( export function annotateDynamicAccess(
...@@ -580,21 +577,32 @@ export function useDynamicRouteParams(expression: string) { ...@@ -580,21 +577,32 @@ export function useDynamicRouteParams(expression: string) {
// accesses. // accesses.
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) { if (workUnitStore) {
// We're prerendering with dynamicIO or PPR or both switch (workUnitStore.type) {
if (workUnitStore.type === 'prerender-client') { case 'prerender-client':
// We are in a prerender with dynamicIO semantics // We are in a prerender with dynamicIO semantics. We are going to
// We are going to hang here and never resolve. This will cause the currently // hang here and never resolve. This will cause the currently
// rendering component to effectively be a dynamic hole // rendering component to effectively be a dynamic hole.
React.use(makeHangingPromise(workUnitStore.renderSignal, expression)) React.use(makeHangingPromise(workUnitStore.renderSignal, expression))
} else if (workUnitStore.type === 'prerender-ppr') { break
// We're prerendering with PPR case 'prerender':
postponeWithTracking( case 'prerender-ppr':
workStore.route, return postponeWithTracking(
expression, workStore.route,
workUnitStore.dynamicTracking expression,
) workUnitStore.dynamicTracking
} else if (workUnitStore.type === 'prerender-legacy') { )
throwToInterruptStaticGeneration(expression, workStore, workUnitStore) case 'prerender-legacy':
return throwToInterruptStaticGeneration(
expression,
workStore,
workUnitStore
)
case 'request':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
} }
} }
} }
......
...@@ -17,6 +17,7 @@ import { ...@@ -17,6 +17,7 @@ import {
stringToUint8Array, stringToUint8Array,
} from './encryption-utils' } from './encryption-utils'
import { import {
getCacheSignal,
getPrerenderResumeDataCache, getPrerenderResumeDataCache,
getRenderResumeDataCache, getRenderResumeDataCache,
workUnitAsyncStorage, workUnitAsyncStorage,
...@@ -95,10 +96,9 @@ enum ReadStatus { ...@@ -95,10 +96,9 @@ enum ReadStatus {
export const encryptActionBoundArgs = React.cache( export const encryptActionBoundArgs = React.cache(
async function encryptActionBoundArgs(actionId: string, ...args: any[]) { async function encryptActionBoundArgs(actionId: string, ...args: any[]) {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
const cacheSignal = const cacheSignal = workUnitStore
workUnitStore?.type === 'prerender' ? getCacheSignal(workUnitStore)
? workUnitStore.cacheSignal : undefined
: undefined
const { clientModules } = getClientReferenceManifestForRsc() const { clientModules } = getClientReferenceManifestForRsc()
...@@ -109,10 +109,9 @@ export const encryptActionBoundArgs = React.cache( ...@@ -109,10 +109,9 @@ export const encryptActionBoundArgs = React.cache(
let didCatchError = false let didCatchError = false
const hangingInputAbortSignal = const hangingInputAbortSignal = workUnitStore
workUnitStore?.type === 'prerender' ? createHangingInputAbortSignal(workUnitStore)
? createHangingInputAbortSignal(workUnitStore) : undefined
: undefined
let readStatus = ReadStatus.Ready let readStatus = ReadStatus.Ready
function startReadOnce() { function startReadOnce() {
...@@ -227,9 +226,7 @@ export async function decryptActionBoundArgs( ...@@ -227,9 +226,7 @@ export async function decryptActionBoundArgs(
let decrypted: string | undefined let decrypted: string | undefined
if (workUnitStore) { if (workUnitStore) {
const cacheSignal = const cacheSignal = getCacheSignal(workUnitStore)
workUnitStore.type === 'prerender' ? workUnitStore.cacheSignal : undefined
const prerenderResumeDataCache = getPrerenderResumeDataCache(workUnitStore) const prerenderResumeDataCache = getPrerenderResumeDataCache(workUnitStore)
const renderResumeDataCache = getRenderResumeDataCache(workUnitStore) const renderResumeDataCache = getRenderResumeDataCache(workUnitStore)
...@@ -256,20 +253,30 @@ export async function decryptActionBoundArgs( ...@@ -256,20 +253,30 @@ export async function decryptActionBoundArgs(
start(controller) { start(controller) {
controller.enqueue(textEncoder.encode(decrypted)) controller.enqueue(textEncoder.encode(decrypted))
if (workUnitStore?.type === 'prerender') { switch (workUnitStore?.type) {
// Explicitly don't close the stream here (until prerendering is case 'prerender':
// complete) so that hanging promises are not rejected. // Explicitly don't close the stream here (until prerendering is
if (workUnitStore.renderSignal.aborted) { // complete) so that hanging promises are not rejected.
controller.close() if (workUnitStore.renderSignal.aborted) {
} else { controller.close()
workUnitStore.renderSignal.addEventListener( } else {
'abort', workUnitStore.renderSignal.addEventListener(
() => controller.close(), 'abort',
{ once: true } () => controller.close(),
) { once: true }
} )
} else { }
controller.close() break
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'unstable-cache':
case undefined:
return controller.close()
default:
workUnitStore satisfies never
} }
}, },
}), }),
......
...@@ -51,17 +51,27 @@ export function useFlightStream<T>( ...@@ -51,17 +51,27 @@ export function useFlightStream<T>(
// that requires the nextTick behavior. This is why it is safe to access a node only API here // that requires the nextTick behavior. This is why it is safe to access a node only API here
if (process.env.NEXT_RUNTIME !== 'edge') { if (process.env.NEXT_RUNTIME !== 'edge') {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (!workUnitStore) { if (!workUnitStore) {
throw new InvariantError('Expected workUnitAsyncStorage to have a store.') throw new InvariantError('Expected workUnitAsyncStorage to have a store.')
} }
if (workUnitStore.type === 'prerender-client') {
const responseOnNextTick = new Promise<T>((r) => { switch (workUnitStore.type) {
process.nextTick(() => { case 'prerender-client':
r(newResponse) const responseOnNextTick = new Promise<T>((resolve) => {
process.nextTick(() => resolve(newResponse))
}) })
}) flightResponses.set(flightStream, responseOnNextTick)
flightResponses.set(flightStream, responseOnNextTick) return responseOnNextTick
return responseOnNextTick case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
} }
} }
......
...@@ -264,8 +264,7 @@ export function getExpectedRequestStore( ...@@ -264,8 +264,7 @@ export function getExpectedRequestStore(
) )
default: default:
const _exhaustiveCheck: never = workUnitStore return workUnitStore satisfies never
return _exhaustiveCheck
} }
} }
...@@ -278,16 +277,22 @@ export function throwForMissingRequestStore(callingExpression: string): never { ...@@ -278,16 +277,22 @@ export function throwForMissingRequestStore(callingExpression: string): never {
export function getPrerenderResumeDataCache( export function getPrerenderResumeDataCache(
workUnitStore: WorkUnitStore workUnitStore: WorkUnitStore
): PrerenderResumeDataCache | null { ): PrerenderResumeDataCache | null {
if ( switch (workUnitStore.type) {
workUnitStore.type === 'prerender' || case 'prerender':
// TODO eliminate fetch caching in client scope and stop exposing this data cache during SSR case 'prerender-ppr':
workUnitStore.type === 'prerender-client' || return workUnitStore.prerenderResumeDataCache
workUnitStore.type === 'prerender-ppr' case 'prerender-client':
) { // TODO eliminate fetch caching in client scope and stop exposing this data
return workUnitStore.prerenderResumeDataCache // cache during SSR.
return workUnitStore.prerenderResumeDataCache
case 'prerender-legacy':
case 'request':
case 'cache':
case 'unstable-cache':
return null
default:
return workUnitStore satisfies never
} }
return null
} }
export function getRenderResumeDataCache( export function getRenderResumeDataCache(
...@@ -308,8 +313,12 @@ export function getRenderResumeDataCache( ...@@ -308,8 +313,12 @@ export function getRenderResumeDataCache(
// Otherwise we return the mutable resume data cache here as an immutable // Otherwise we return the mutable resume data cache here as an immutable
// version of the cache as it can also be used for reading. // version of the cache as it can also be used for reading.
return workUnitStore.prerenderResumeDataCache return workUnitStore.prerenderResumeDataCache
default: case 'cache':
case 'unstable-cache':
case 'prerender-legacy':
return null return null
default:
return workUnitStore satisfies never
} }
} }
...@@ -317,15 +326,24 @@ export function getHmrRefreshHash( ...@@ -317,15 +326,24 @@ export function getHmrRefreshHash(
workStore: WorkStore, workStore: WorkStore,
workUnitStore: WorkUnitStore workUnitStore: WorkUnitStore
): string | undefined { ): string | undefined {
if (!workStore.dev) { if (workStore.dev) {
return undefined switch (workUnitStore.type) {
case 'cache':
case 'prerender':
return workUnitStore.hmrRefreshHash
case 'request':
return workUnitStore.cookies.get(NEXT_HMR_REFRESH_HASH_COOKIE)?.value
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
} }
return workUnitStore.type === 'cache' || workUnitStore.type === 'prerender' return undefined
? workUnitStore.hmrRefreshHash
: workUnitStore.type === 'request'
? workUnitStore.cookies.get(NEXT_HMR_REFRESH_HASH_COOKIE)?.value
: undefined
} }
/** /**
...@@ -341,10 +359,33 @@ export function getDraftModeProviderForCacheScope( ...@@ -341,10 +359,33 @@ export function getDraftModeProviderForCacheScope(
case 'unstable-cache': case 'unstable-cache':
case 'request': case 'request':
return workUnitStore.draftMode return workUnitStore.draftMode
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
break
default: default:
return undefined workUnitStore satisfies never
} }
} }
return undefined return undefined
} }
export function getCacheSignal(
workUnitStore: WorkUnitStore
): CacheSignal | null {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
return workUnitStore.cacheSignal
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'unstable-cache':
return null
default:
return workUnitStore satisfies never
}
}
This diff is collapsed.
...@@ -128,15 +128,22 @@ function patchConsoleMethodDEV(methodName: InterceptableConsoleMethod): void { ...@@ -128,15 +128,22 @@ function patchConsoleMethodDEV(methodName: InterceptableConsoleMethod): void {
const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name') const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name')
const wrapperMethod = function (this: typeof console, ...args: any[]) { const wrapperMethod = function (this: typeof console, ...args: any[]) {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
const isPrerenderValidation =
workUnitStore !== undefined && switch (workUnitStore?.type) {
(workUnitStore.type === 'prerender-client' || case 'prerender':
workUnitStore.type === 'prerender') case 'prerender-client':
originalMethod.apply(this, dimConsoleCall(methodName, args))
if (isPrerenderValidation) { break
originalMethod.apply(this, dimConsoleCall(methodName, args)) case 'prerender-ppr':
} else { case 'prerender-legacy':
originalMethod.apply(this, args) case 'request':
case 'cache':
case 'unstable-cache':
case undefined:
originalMethod.apply(this, args)
break
default:
workUnitStore satisfies never
} }
} }
if (originalName) { if (originalName) {
......
import { workAsyncStorage } from '../app-render/work-async-storage.external' import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external' import {
workUnitAsyncStorage,
type PrerenderStoreModern,
} from '../app-render/work-unit-async-storage.external'
import { import {
abortOnSynchronousPlatformIOAccess, abortOnSynchronousPlatformIOAccess,
trackSynchronousPlatformIOAccessInDev, trackSynchronousPlatformIOAccessInDev,
...@@ -10,93 +13,123 @@ type ApiType = 'time' | 'random' | 'crypto' ...@@ -10,93 +13,123 @@ type ApiType = 'time' | 'random' | 'crypto'
export function io(expression: string, type: ApiType) { export function io(expression: string, type: ApiType) {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) { const workStore = workAsyncStorage.getStore()
let isClient = false
if ( if (!workUnitStore || !workStore) {
workUnitStore.type === 'prerender' || return
(isClient = workUnitStore.type === 'prerender-client') }
) {
switch (workUnitStore.type) {
case 'prerender': {
const prerenderSignal = workUnitStore.controller.signal const prerenderSignal = workUnitStore.controller.signal
if (prerenderSignal.aborted === false) { if (prerenderSignal.aborted === false) {
// If the prerender signal is already aborted we don't need to construct any stacks // If the prerender signal is already aborted we don't need to construct
// because something else actually terminated the prerender. // any stacks because something else actually terminated the prerender.
const workStore = workAsyncStorage.getStore() let message: string
if (workStore) { switch (type) {
let message: string case 'time':
switch (type) { message = `Route "${workStore.route}" used ${expression} instead of using \`performance\` or without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time`
case 'time': break
message = isClient case 'random':
? `Route "${workStore.route}" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time-client` message = `Route "${workStore.route}" used ${expression} outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random`
: `Route "${workStore.route}" used ${expression} instead of using \`performance\` or without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time` break
break case 'crypto':
case 'random': message = `Route "${workStore.route}" used ${expression} outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto`
message = isClient break
? `Route "${workStore.route}" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-random-client` default:
: `Route "${workStore.route}" used ${expression} outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random` throw new InvariantError(
break 'Unknown expression type in abortOnSynchronousPlatformIOAccess.'
case 'crypto': )
message = isClient }
? `Route "${workStore.route}" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto-client`
: `Route "${workStore.route}" used ${expression} outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto`
break
default:
throw new InvariantError(
'Unknown expression type in abortOnSynchronousPlatformIOAccess.'
)
}
const errorWithStack = new Error(message) abortOnSynchronousPlatformIOAccess(
workStore.route,
if ( expression,
process.env.NODE_ENV !== 'production' && applyOwnerStack(new Error(message), workUnitStore),
workUnitStore.captureOwnerStack workUnitStore
) { )
const ownerStack = workUnitStore.captureOwnerStack() }
break
if (ownerStack) { }
// TODO: Instead of stitching the stacks here, we should log the case 'prerender-client': {
// original error as-is when it occurs (i.e. here), and let const prerenderSignal = workUnitStore.controller.signal
// `patchErrorInspect` handle adding the owner stack, instead of
// logging it deferred in the `LogSafely` component via
// `throwIfDisallowedDynamic`.
applyOwnerStack(errorWithStack, ownerStack)
}
}
abortOnSynchronousPlatformIOAccess( if (prerenderSignal.aborted === false) {
workStore.route, // If the prerender signal is already aborted we don't need to construct
expression, // any stacks because something else actually terminated the prerender.
errorWithStack, let message: string
workUnitStore switch (type) {
) case 'time':
message = `Route "${workStore.route}" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time-client`
break
case 'random':
message = `Route "${workStore.route}" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-random-client`
break
case 'crypto':
message = `Route "${workStore.route}" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto-client`
break
default:
throw new InvariantError(
'Unknown expression type in abortOnSynchronousPlatformIOAccess.'
)
} }
abortOnSynchronousPlatformIOAccess(
workStore.route,
expression,
applyOwnerStack(new Error(message), workUnitStore),
workUnitStore
)
} }
} else if ( break
workUnitStore.type === 'request' &&
workUnitStore.prerenderPhase === true
) {
const requestStore = workUnitStore
trackSynchronousPlatformIOAccessInDev(requestStore)
} }
case 'request':
if (workUnitStore.prerenderPhase === true) {
trackSynchronousPlatformIOAccessInDev(workUnitStore)
}
break
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
} }
} }
function applyOwnerStack(error: Error, ownerStack: string) { function applyOwnerStack(error: Error, workUnitStore: PrerenderStoreModern) {
let stack = ownerStack // TODO: Instead of stitching the stacks here, we should log the original
// error as-is when it occurs, and let `patchErrorInspect` handle adding the
// owner stack, instead of logging it deferred in the `LogSafely` component
// via `throwIfDisallowedDynamic`.
if (
process.env.NODE_ENV !== 'production' &&
workUnitStore.captureOwnerStack
) {
const ownerStack = workUnitStore.captureOwnerStack()
if (ownerStack) {
let stack = ownerStack
if (error.stack) { if (error.stack) {
const frames: string[] = [] const frames: string[] = []
for (const frame of error.stack.split('\n').slice(1)) { for (const frame of error.stack.split('\n').slice(1)) {
if (frame.includes('react_stack_bottom_frame')) { if (frame.includes('react_stack_bottom_frame')) {
break break
}
frames.push(frame)
}
stack = '\n' + frames.join('\n') + stack
} }
frames.push(frame) error.stack = error.name + ': ' + error.message + stack
} }
stack = '\n' + frames.join('\n') + stack
} }
error.stack = error.name + ': ' + error.message + stack return error
} }
...@@ -30,22 +30,11 @@ export function connection(): Promise<void> { ...@@ -30,22 +30,11 @@ export function connection(): Promise<void> {
} }
if (workStore.forceStatic) { if (workStore.forceStatic) {
// When using forceStatic we override all other logic and always just return an empty // When using forceStatic, we override all other logic and always just
// headers object without tracking // return a resolving promise without tracking.
return Promise.resolve(undefined) return Promise.resolve(undefined)
} }
if (workUnitStore) {
if (workUnitStore.type === 'cache') {
throw new Error(
`Route ${workStore.route} used "connection" inside "use cache". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
} else if (workUnitStore.type === 'unstable-cache') {
throw new Error(
`Route ${workStore.route} used "connection" inside a function cached with "unstable_cache(...)". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
}
}
if (workStore.dynamicShouldError) { if (workStore.dynamicShouldError) {
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`connection\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering` `Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`connection\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
...@@ -53,30 +42,46 @@ export function connection(): Promise<void> { ...@@ -53,30 +42,46 @@ export function connection(): Promise<void> {
} }
if (workUnitStore) { if (workUnitStore) {
if ( switch (workUnitStore.type) {
workUnitStore.type === 'prerender' || case 'cache':
workUnitStore.type === 'prerender-client' throw new Error(
) { `Route ${workStore.route} used "connection" inside "use cache". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
// dynamicIO Prerender )
// We return a promise that never resolves to allow the prender to stall at this point case 'unstable-cache':
return makeHangingPromise(workUnitStore.renderSignal, '`connection()`') throw new Error(
} else if (workUnitStore.type === 'prerender-ppr') { `Route ${workStore.route} used "connection" inside a function cached with "unstable_cache(...)". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
// PPR Prerender (no dynamicIO) )
// We use React's postpone API to interrupt rendering here to create a dynamic hole case 'prerender':
postponeWithTracking( case 'prerender-client':
workStore.route, // We return a promise that never resolves to allow the prerender to
'connection', // stall at this point.
workUnitStore.dynamicTracking return makeHangingPromise(
) workUnitStore.renderSignal,
} else if (workUnitStore.type === 'prerender-legacy') { '`connection()`'
// Legacy Prerender )
// We throw an error here to interrupt prerendering to mark the route as dynamic case 'prerender-ppr':
throwToInterruptStaticGeneration('connection', workStore, workUnitStore) // We use React's postpone API to interrupt rendering here to create a
// dynamic hole
return postponeWithTracking(
workStore.route,
'connection',
workUnitStore.dynamicTracking
)
case 'prerender-legacy':
// We throw an error here to interrupt prerendering to mark the route
// as dynamic
return throwToInterruptStaticGeneration(
'connection',
workStore,
workUnitStore
)
case 'request':
trackDynamicDataInDynamicRender(workUnitStore)
break
default:
workUnitStore satisfies never
} }
} }
// We fall through to the dynamic context below but we still track dynamic access
// because in dev we can still error for things like using headers inside a cache context
trackDynamicDataInDynamicRender(workStore, workUnitStore)
} }
return Promise.resolve(undefined) return Promise.resolve(undefined)
......
...@@ -72,17 +72,6 @@ export function cookies(): Promise<ReadonlyRequestCookies> { ...@@ -72,17 +72,6 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
return makeUntrackedExoticCookies(underlyingCookies) return makeUntrackedExoticCookies(underlyingCookies)
} }
if (workUnitStore) {
if (workUnitStore.type === 'cache') {
throw new Error(
`Route ${workStore.route} used "cookies" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
} else if (workUnitStore.type === 'unstable-cache') {
throw new Error(
`Route ${workStore.route} used "cookies" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
}
}
if (workStore.dynamicShouldError) { if (workStore.dynamicShouldError) {
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`cookies\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering` `Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`cookies\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
...@@ -91,6 +80,14 @@ export function cookies(): Promise<ReadonlyRequestCookies> { ...@@ -91,6 +80,14 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
if (workUnitStore) { if (workUnitStore) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'cache':
throw new Error(
`Route ${workStore.route} used "cookies" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
case 'unstable-cache':
throw new Error(
`Route ${workStore.route} used "cookies" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
case 'prerender': case 'prerender':
return makeHangingCookies(workUnitStore) return makeHangingCookies(workUnitStore)
case 'prerender-client': case 'prerender-client':
...@@ -99,32 +96,28 @@ export function cookies(): Promise<ReadonlyRequestCookies> { ...@@ -99,32 +96,28 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
`${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.` `${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`
) )
case 'prerender-ppr': case 'prerender-ppr':
// PPR Prerender (no dynamicIO) // We need track dynamic access here eagerly to keep continuity with
// We are prerendering with PPR. We need track dynamic access here eagerly // how cookies has worked in PPR without dynamicIO.
// to keep continuity with how cookies has worked in PPR without dynamicIO. return postponeWithTracking(
postponeWithTracking(
workStore.route, workStore.route,
callingExpression, callingExpression,
workUnitStore.dynamicTracking workUnitStore.dynamicTracking
) )
break
case 'prerender-legacy': case 'prerender-legacy':
// Legacy Prerender // We track dynamic access here so we don't need to wrap the cookies
// We track dynamic access here so we don't need to wrap the cookies in // in individual property access tracking.
// individual property access tracking. return throwToInterruptStaticGeneration(
throwToInterruptStaticGeneration(
callingExpression, callingExpression,
workStore, workStore,
workUnitStore workUnitStore
) )
case 'request':
trackDynamicDataInDynamicRender(workUnitStore)
break break
default: default:
// fallthrough workUnitStore satisfies never
} }
} }
// We fall through to the dynamic context below but we still track dynamic access
// because in dev we can still error for things like using cookies inside a cache context
trackDynamicDataInDynamicRender(workStore, workUnitStore)
} }
// cookies is being called in a dynamic context // cookies is being called in a dynamic context
...@@ -459,16 +452,28 @@ function describeNameArg(arg: unknown) { ...@@ -459,16 +452,28 @@ function describeNameArg(arg: unknown) {
function syncIODev(route: string | undefined, expression: string) { function syncIODev(route: string | undefined, expression: string) {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (
workUnitStore && if (workUnitStore) {
workUnitStore.type === 'request' && switch (workUnitStore.type) {
workUnitStore.prerenderPhase === true case 'request':
) { if (workUnitStore.prerenderPhase === true) {
// When we're rendering dynamically in dev we need to advance out of the // When we're rendering dynamically in dev, we need to advance out of
// Prerender environment when we read Request data synchronously // the Prerender environment when we read Request data synchronously.
const requestStore = workUnitStore trackSynchronousRequestDataAccessInDev(workUnitStore)
trackSynchronousRequestDataAccessInDev(requestStore) }
break
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
} }
// In all cases we warn normally // In all cases we warn normally
warnForSyncAccess(route, expression) warnForSyncAccess(route, expression)
} }
......
...@@ -13,6 +13,7 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.exte ...@@ -13,6 +13,7 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.exte
import { import {
abortAndThrowOnSynchronousRequestDataAccess, abortAndThrowOnSynchronousRequestDataAccess,
postponeWithTracking, postponeWithTracking,
trackDynamicDataInDynamicRender,
trackSynchronousRequestDataAccessInDev, trackSynchronousRequestDataAccessInDev,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger' import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
...@@ -81,8 +82,7 @@ export function draftMode(): Promise<DraftMode> { ...@@ -81,8 +82,7 @@ export function draftMode(): Promise<DraftMode> {
return createOrGetCachedDraftMode(null, workStore) return createOrGetCachedDraftMode(null, workStore)
default: default:
const _exhaustiveCheck: never = workUnitStore return workUnitStore satisfies never
return _exhaustiveCheck
} }
} }
...@@ -244,16 +244,28 @@ class DraftMode { ...@@ -244,16 +244,28 @@ class DraftMode {
function syncIODev(route: string | undefined, expression: string) { function syncIODev(route: string | undefined, expression: string) {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (
workUnitStore && if (workUnitStore) {
workUnitStore.type === 'request' && switch (workUnitStore.type) {
workUnitStore.prerenderPhase === true case 'request':
) { if (workUnitStore.prerenderPhase === true) {
// When we're rendering dynamically in dev we need to advance out of the // When we're rendering dynamically in dev, we need to advance out of
// Prerender environment when we read Request data synchronously // the Prerender environment when we read Request data synchronously.
const requestStore = workUnitStore trackSynchronousRequestDataAccessInDev(workUnitStore)
trackSynchronousRequestDataAccessInDev(requestStore) }
break
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
} }
// In all cases we warn normally // In all cases we warn normally
warnForSyncAccess(route, expression) warnForSyncAccess(route, expression)
} }
...@@ -280,20 +292,10 @@ function trackDynamicDraftMode(expression: string) { ...@@ -280,20 +292,10 @@ function trackDynamicDraftMode(expression: string) {
if (store) { if (store) {
// We have a store we want to track dynamic data access to ensure we // We have a store we want to track dynamic data access to ensure we
// don't statically generate routes that manipulate draft mode. // don't statically generate routes that manipulate draft mode.
if (workUnitStore) { if (workUnitStore?.phase === 'after') {
if (workUnitStore.type === 'cache') { throw new Error(
throw new Error( `Route ${store.route} used "${expression}" inside \`after\`. The enabled status of draftMode can be read inside \`after\` but you cannot enable or disable draftMode. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
`Route ${store.route} used "${expression}" inside "use cache". The enabled status of draftMode can be read in caches but you must not enable or disable draftMode inside a cache. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache` )
)
} else if (workUnitStore.type === 'unstable-cache') {
throw new Error(
`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)". The enabled status of draftMode can be read in caches but you must not enable or disable draftMode inside a cache. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
} else if (workUnitStore.phase === 'after') {
throw new Error(
`Route ${store.route} used "${expression}" inside \`after\`. The enabled status of draftMode can be read inside \`after\` but you cannot enable or disable draftMode. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
)
}
} }
if (store.dynamicShouldError) { if (store.dynamicShouldError) {
...@@ -304,33 +306,36 @@ function trackDynamicDraftMode(expression: string) { ...@@ -304,33 +306,36 @@ function trackDynamicDraftMode(expression: string) {
if (workUnitStore) { if (workUnitStore) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'cache':
throw new Error(
`Route ${store.route} used "${expression}" inside "use cache". The enabled status of draftMode can be read in caches but you must not enable or disable draftMode inside a cache. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
case 'unstable-cache':
throw new Error(
`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)". The enabled status of draftMode can be read in caches but you must not enable or disable draftMode inside a cache. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
case 'prerender': case 'prerender':
// dynamicIO Prerender
const error = new Error( const error = new Error(
`Route ${store.route} used ${expression} without first calling \`await connection()\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers` `Route ${store.route} used ${expression} without first calling \`await connection()\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers`
) )
abortAndThrowOnSynchronousRequestDataAccess( return abortAndThrowOnSynchronousRequestDataAccess(
store.route, store.route,
expression, expression,
error, error,
workUnitStore workUnitStore
) )
break
case 'prerender-client': case 'prerender-client':
const exportName = '`draftMode`' const exportName = '`draftMode`'
throw new InvariantError( throw new InvariantError(
`${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.` `${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`
) )
case 'prerender-ppr': case 'prerender-ppr':
// PPR Prerender return postponeWithTracking(
postponeWithTracking(
store.route, store.route,
expression, expression,
workUnitStore.dynamicTracking workUnitStore.dynamicTracking
) )
break
case 'prerender-legacy': case 'prerender-legacy':
// legacy Prerender
workUnitStore.revalidate = 0 workUnitStore.revalidate = 0
const err = new DynamicServerError( const err = new DynamicServerError(
...@@ -341,12 +346,10 @@ function trackDynamicDraftMode(expression: string) { ...@@ -341,12 +346,10 @@ function trackDynamicDraftMode(expression: string) {
throw err throw err
case 'request': case 'request':
if (process.env.NODE_ENV === 'development') { trackDynamicDataInDynamicRender(workUnitStore)
workUnitStore.usedDynamic = true
}
break break
default: default:
// fallthrough workUnitStore satisfies never
} }
} }
} }
......
...@@ -77,16 +77,26 @@ export function headers(): Promise<ReadonlyHeaders> { ...@@ -77,16 +77,26 @@ export function headers(): Promise<ReadonlyHeaders> {
} }
if (workUnitStore) { if (workUnitStore) {
if (workUnitStore.type === 'cache') { switch (workUnitStore.type) {
throw new Error( case 'cache':
`Route ${workStore.route} used "headers" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "headers" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache` throw new Error(
) `Route ${workStore.route} used "headers" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "headers" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
} else if (workUnitStore.type === 'unstable-cache') { )
throw new Error( case 'unstable-cache':
`Route ${workStore.route} used "headers" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "headers" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache` throw new Error(
) `Route ${workStore.route} used "headers" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "headers" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
break
default:
workUnitStore satisfies never
} }
} }
if (workStore.dynamicShouldError) { if (workStore.dynamicShouldError) {
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`headers\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering` `Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`headers\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
...@@ -107,26 +117,28 @@ export function headers(): Promise<ReadonlyHeaders> { ...@@ -107,26 +117,28 @@ export function headers(): Promise<ReadonlyHeaders> {
// We are prerendering with PPR. We need track dynamic access here eagerly // We are prerendering with PPR. We need track dynamic access here eagerly
// to keep continuity with how headers has worked in PPR without dynamicIO. // to keep continuity with how headers has worked in PPR without dynamicIO.
// TODO consider switching the semantic to throw on property access instead // TODO consider switching the semantic to throw on property access instead
postponeWithTracking( return postponeWithTracking(
workStore.route, workStore.route,
'headers', 'headers',
workUnitStore.dynamicTracking workUnitStore.dynamicTracking
) )
break
case 'prerender-legacy': case 'prerender-legacy':
// Legacy Prerender // Legacy Prerender
// We are in a legacy static generation mode while prerendering // We are in a legacy static generation mode while prerendering
// We track dynamic access here so we don't need to wrap the headers in // We track dynamic access here so we don't need to wrap the headers in
// individual property access tracking. // individual property access tracking.
throwToInterruptStaticGeneration('headers', workStore, workUnitStore) return throwToInterruptStaticGeneration(
'headers',
workStore,
workUnitStore
)
case 'request':
trackDynamicDataInDynamicRender(workUnitStore)
break break
default: default:
// fallthrough workUnitStore satisfies never
} }
} }
// We fall through to the dynamic context below but we still track dynamic access
// because in dev we can still error for things like using headers inside a cache context
trackDynamicDataInDynamicRender(workStore, workUnitStore)
} }
const requestStore = getExpectedRequestStore('headers') const requestStore = getExpectedRequestStore('headers')
...@@ -391,16 +403,28 @@ function describeNameArg(arg: unknown) { ...@@ -391,16 +403,28 @@ function describeNameArg(arg: unknown) {
function syncIODev(route: string | undefined, expression: string) { function syncIODev(route: string | undefined, expression: string) {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (
workUnitStore && if (workUnitStore) {
workUnitStore.type === 'request' && switch (workUnitStore.type) {
workUnitStore.prerenderPhase === true case 'request':
) { if (workUnitStore.prerenderPhase === true) {
// When we're rendering dynamically in dev we need to advance out of the // When we're rendering dynamically in dev, we need to advance out of
// Prerender environment when we read Request data synchronously // the Prerender environment when we read Request data synchronously.
const requestStore = workUnitStore trackSynchronousRequestDataAccessInDev(workUnitStore)
trackSynchronousRequestDataAccessInDev(requestStore) }
break
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
} }
// In all cases we warn normally // In all cases we warn normally
warnForSyncAccess(route, expression) warnForSyncAccess(route, expression)
} }
......
...@@ -68,8 +68,12 @@ export function createParamsFromClient( ...@@ -68,8 +68,12 @@ export function createParamsFromClient(
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
return createPrerenderParams(underlyingParams, workStore, workUnitStore) return createPrerenderParams(underlyingParams, workStore, workUnitStore)
case 'request':
case 'cache':
case 'unstable-cache':
break
default: default:
// fallthrough workUnitStore satisfies never
} }
} }
return createRenderParams(underlyingParams, workStore) return createRenderParams(underlyingParams, workStore)
...@@ -92,8 +96,12 @@ export function createServerParamsForRoute( ...@@ -92,8 +96,12 @@ export function createServerParamsForRoute(
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
return createPrerenderParams(underlyingParams, workStore, workUnitStore) return createPrerenderParams(underlyingParams, workStore, workUnitStore)
case 'request':
case 'cache':
case 'unstable-cache':
break
default: default:
// fallthrough workUnitStore satisfies never
} }
} }
return createRenderParams(underlyingParams, workStore) return createRenderParams(underlyingParams, workStore)
...@@ -111,8 +119,12 @@ export function createServerParamsForServerSegment( ...@@ -111,8 +119,12 @@ export function createServerParamsForServerSegment(
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
return createPrerenderParams(underlyingParams, workStore, workUnitStore) return createPrerenderParams(underlyingParams, workStore, workUnitStore)
case 'request':
case 'cache':
case 'unstable-cache':
break
default: default:
// fallthrough workUnitStore satisfies never
} }
} }
return createRenderParams(underlyingParams, workStore) return createRenderParams(underlyingParams, workStore)
...@@ -122,22 +134,32 @@ export function createPrerenderParamsForClientSegment( ...@@ -122,22 +134,32 @@ export function createPrerenderParamsForClientSegment(
underlyingParams: Params, underlyingParams: Params,
workStore: WorkStore workStore: WorkStore
): Promise<Params> { ): Promise<Params> {
const prerenderStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if ( if (workUnitStore) {
prerenderStore && switch (workUnitStore.type) {
(prerenderStore.type === 'prerender' || case 'prerender':
prerenderStore.type === 'prerender-client') case 'prerender-client':
) { const fallbackParams = workStore.fallbackRouteParams
const fallbackParams = workStore.fallbackRouteParams if (fallbackParams) {
if (fallbackParams) { for (let key in underlyingParams) {
for (let key in underlyingParams) { if (fallbackParams.has(key)) {
if (fallbackParams.has(key)) { // This params object has one or more fallback params, so we need
// This params object has one of more fallback params so we need to consider // to consider the awaiting of this params object "dynamic". Since
// the awaiting of this params object "dynamic". Since we are in dynamicIO mode // we are in dynamicIO mode we encode this as a promise that never
// we encode this as a promise that never resolves // resolves.
return makeHangingPromise(prerenderStore.renderSignal, '`params`') return makeHangingPromise(workUnitStore.renderSignal, '`params`')
}
}
} }
} break
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
} }
} }
// We're prerendering in a mode that does not abort. We resolve the promise without // We're prerendering in a mode that does not abort. We resolve the promise without
...@@ -168,13 +190,16 @@ function createPrerenderParams( ...@@ -168,13 +190,16 @@ function createPrerenderParams(
case 'prerender-client': case 'prerender-client':
// We are in a dynamicIO prerender // We are in a dynamicIO prerender
return makeHangingParams(underlyingParams, prerenderStore) return makeHangingParams(underlyingParams, prerenderStore)
default: case 'prerender-ppr':
case 'prerender-legacy':
return makeErroringExoticParams( return makeErroringExoticParams(
underlyingParams, underlyingParams,
fallbackParams, fallbackParams,
workStore, workStore,
prerenderStore prerenderStore
) )
default:
prerenderStore satisfies never
} }
} }
} }
...@@ -516,15 +541,25 @@ function syncIODev( ...@@ -516,15 +541,25 @@ function syncIODev(
missingProperties?: Array<string> missingProperties?: Array<string>
) { ) {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if ( if (workUnitStore) {
workUnitStore && switch (workUnitStore.type) {
workUnitStore.type === 'request' && case 'request':
workUnitStore.prerenderPhase === true if (workUnitStore.prerenderPhase === true) {
) { // When we're rendering dynamically in dev, we need to advance out of
// When we're rendering dynamically in dev we need to advance out of the // the Prerender environment when we read Request data synchronously.
// Prerender environment when we read Request data synchronously trackSynchronousRequestDataAccessInDev(workUnitStore)
const requestStore = workUnitStore }
trackSynchronousRequestDataAccessInDev(requestStore) break
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
} }
// In all cases we warn normally // In all cases we warn normally
if (missingProperties && missingProperties.length > 0) { if (missingProperties && missingProperties.length > 0) {
......
...@@ -29,8 +29,12 @@ export function createServerPathnameForMetadata( ...@@ -29,8 +29,12 @@ export function createServerPathnameForMetadata(
workUnitStore workUnitStore
) )
} }
case 'request':
case 'cache':
case 'unstable-cache':
break
default: default:
// fallthrough workUnitStore satisfies never
} }
} }
return createRenderPathname(underlyingPathname) return createRenderPathname(underlyingPathname)
...@@ -55,9 +59,10 @@ function createPrerenderPathname( ...@@ -55,9 +59,10 @@ function createPrerenderPathname(
) )
case 'prerender-ppr': case 'prerender-ppr':
return makeErroringPathname(workStore, prerenderStore.dynamicTracking) return makeErroringPathname(workStore, prerenderStore.dynamicTracking)
break case 'prerender-legacy':
default:
return makeErroringPathname(workStore, null) return makeErroringPathname(workStore, null)
default:
prerenderStore satisfies never
} }
} }
......
...@@ -54,8 +54,10 @@ export async function unstable_rootParams(): Promise<Params> { ...@@ -54,8 +54,10 @@ export async function unstable_rootParams(): Promise<Params> {
workStore, workStore,
workUnitStore workUnitStore
) )
default: case 'request':
return Promise.resolve(workUnitStore.rootParams) return Promise.resolve(workUnitStore.rootParams)
default:
return workUnitStore satisfies never
} }
} }
...@@ -96,8 +98,8 @@ function createPrerenderRootParams( ...@@ -96,8 +98,8 @@ function createPrerenderRootParams(
throw new InvariantError( throw new InvariantError(
`${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.` `${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`
) )
default: case 'prerender-ppr':
// remaining cases are prerender-ppr and prerender-legacy case 'prerender-legacy':
// We aren't in a dynamicIO prerender but we do have fallback params at this // We aren't in a dynamicIO prerender but we do have fallback params at this
// level so we need to make an erroring params object which will postpone // level so we need to make an erroring params object which will postpone
// if you access the fallback params // if you access the fallback params
...@@ -107,6 +109,8 @@ function createPrerenderRootParams( ...@@ -107,6 +109,8 @@ function createPrerenderRootParams(
workStore, workStore,
prerenderStore prerenderStore
) )
default:
prerenderStore satisfies never
} }
} }
} }
......
...@@ -72,8 +72,12 @@ export function createSearchParamsFromClient( ...@@ -72,8 +72,12 @@ export function createSearchParamsFromClient(
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
return createPrerenderSearchParams(workStore, workUnitStore) return createPrerenderSearchParams(workStore, workUnitStore)
case 'request':
case 'cache':
case 'unstable-cache':
break
default: default:
// fallthrough workUnitStore satisfies never
} }
} }
return createRenderSearchParams(underlyingSearchParams, workStore) return createRenderSearchParams(underlyingSearchParams, workStore)
...@@ -95,8 +99,12 @@ export function createServerSearchParamsForServerPage( ...@@ -95,8 +99,12 @@ export function createServerSearchParamsForServerPage(
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
return createPrerenderSearchParams(workStore, workUnitStore) return createPrerenderSearchParams(workStore, workUnitStore)
case 'request':
case 'cache':
case 'unstable-cache':
break
default: default:
// fallthrough workUnitStore satisfies never
} }
} }
return createRenderSearchParams(underlyingSearchParams, workStore) return createRenderSearchParams(underlyingSearchParams, workStore)
...@@ -111,20 +119,27 @@ export function createPrerenderSearchParamsForClientPage( ...@@ -111,20 +119,27 @@ export function createPrerenderSearchParamsForClientPage(
return Promise.resolve({}) return Promise.resolve({})
} }
const prerenderStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if ( if (workUnitStore) {
prerenderStore && switch (workUnitStore.type) {
(prerenderStore.type === 'prerender' || case 'prerender':
prerenderStore.type === 'prerender-client') case 'prerender-client':
) { // We're prerendering in a mode that aborts (dynamicIO) and should stall
// dynamicIO Prerender // the promise to ensure the RSC side is considered dynamic
// We're prerendering in a mode that aborts (dynamicIO) and should stall return makeHangingPromise(workUnitStore.renderSignal, '`searchParams`')
// the promise to ensure the RSC side is considered dynamic case 'prerender-ppr':
return makeHangingPromise(prerenderStore.renderSignal, '`searchParams`') case 'prerender-legacy':
case 'request':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
} }
// We're prerendering in a mode that does not aborts. We resolve the promise without // We're prerendering in a mode that does not abort. We resolve the promise
// any tracking because we're just transporting a value from server to client where the tracking // without any tracking because we're just transporting a value from server to
// will be applied. // client where the tracking will be applied.
return Promise.resolve({}) return Promise.resolve({})
} }
...@@ -143,11 +158,13 @@ function createPrerenderSearchParams( ...@@ -143,11 +158,13 @@ function createPrerenderSearchParams(
case 'prerender-client': case 'prerender-client':
// We are in a dynamicIO (PPR or otherwise) prerender // We are in a dynamicIO (PPR or otherwise) prerender
return makeHangingSearchParams(prerenderStore) return makeHangingSearchParams(prerenderStore)
default: case 'prerender-ppr':
// The remaining cases are prerender-ppr and prerender-legacy case 'prerender-legacy':
// We are in a legacy static generation and need to interrupt the prerender // We are in a legacy static generation and need to interrupt the
// when search params are accessed. // prerender when search params are accessed.
return makeErroringExoticSearchParams(workStore, prerenderStore) return makeErroringExoticSearchParams(workStore, prerenderStore)
default:
return prerenderStore satisfies never
} }
} }
...@@ -180,7 +197,7 @@ function createRenderSearchParams( ...@@ -180,7 +197,7 @@ function createRenderSearchParams(
return makeUntrackedSearchParams(underlyingSearchParams) return makeUntrackedSearchParams(underlyingSearchParams)
} }
return makeUntrackedExoticSearchParams(underlyingSearchParams, workStore) return makeUntrackedExoticSearchParams(underlyingSearchParams)
} }
} }
} }
...@@ -464,8 +481,7 @@ export function makeErroringExoticSearchParamsForUseCache( ...@@ -464,8 +481,7 @@ export function makeErroringExoticSearchParamsForUseCache(
} }
function makeUntrackedExoticSearchParams( function makeUntrackedExoticSearchParams(
underlyingSearchParams: SearchParams, underlyingSearchParams: SearchParams
store: WorkStore
): Promise<SearchParams> { ): Promise<SearchParams> {
const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams) const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)
if (cachedSearchParams) { if (cachedSearchParams) {
...@@ -483,7 +499,9 @@ function makeUntrackedExoticSearchParams( ...@@ -483,7 +499,9 @@ function makeUntrackedExoticSearchParams(
Object.defineProperty(promise, prop, { Object.defineProperty(promise, prop, {
get() { get() {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
trackDynamicDataInDynamicRender(store, workUnitStore) if (workUnitStore) {
trackDynamicDataInDynamicRender(workUnitStore)
}
return underlyingSearchParams[prop] return underlyingSearchParams[prop]
}, },
set(value) { set(value) {
...@@ -546,7 +564,9 @@ function makeDynamicallyTrackedExoticSearchParamsWithDevWarnings( ...@@ -546,7 +564,9 @@ function makeDynamicallyTrackedExoticSearchParamsWithDevWarnings(
) )
} }
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
trackDynamicDataInDynamicRender(store, workUnitStore) if (workUnitStore) {
trackDynamicDataInDynamicRender(workUnitStore)
}
} }
return ReflectAdapter.get(target, prop, receiver) return ReflectAdapter.get(target, prop, receiver)
}, },
...@@ -760,15 +780,25 @@ function syncIODev( ...@@ -760,15 +780,25 @@ function syncIODev(
} }
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if ( if (workUnitStore) {
workUnitStore && switch (workUnitStore.type) {
workUnitStore.type === 'request' && case 'request':
workUnitStore.prerenderPhase === true if (workUnitStore.prerenderPhase === true) {
) { // When we're rendering dynamically in dev, we need to advance out of
// When we're rendering dynamically in dev we need to advance out of the // the Prerender environment when we read Request data synchronously.
// Prerender environment when we read Request data synchronously trackSynchronousRequestDataAccessInDev(workUnitStore)
const requestStore = workUnitStore }
trackSynchronousRequestDataAccessInDev(requestStore) break
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
} }
} }
......
...@@ -84,6 +84,7 @@ import { RedirectStatusCode } from '../../../client/components/redirect-status-c ...@@ -84,6 +84,7 @@ import { RedirectStatusCode } from '../../../client/components/redirect-status-c
import { INFINITE_CACHE } from '../../../lib/constants' import { INFINITE_CACHE } from '../../../lib/constants'
import { executeRevalidates } from '../../revalidation-utils' import { executeRevalidates } from '../../revalidation-utils'
import { trackPendingModules } from '../../app-render/module-loading/track-module-loading.external' import { trackPendingModules } from '../../app-render/module-loading/track-module-loading.external'
import { InvariantError } from '../../../shared/lib/invariant-error'
export class WrappedNextRouterError { export class WrappedNextRouterError {
constructor( constructor(
...@@ -601,9 +602,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -601,9 +602,7 @@ export class AppRouteRouteModule extends RouteModule<
// cookie API. // cookie API.
// TODO leaving the gate here b/c it indicates that we might not actually want to do this // TODO leaving the gate here b/c it indicates that we might not actually want to do this
// on every `do` call. During prerender there should be no mutableCookies because // on every `do` call. During prerender there should be no mutableCookies because
if (requestStore.type === 'request') { appendMutableCookies(headers, requestStore.mutableCookies)
appendMutableCookies(headers, requestStore.mutableCookies)
}
resolvePendingRevalidations() resolvePendingRevalidations()
...@@ -647,10 +646,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -647,10 +646,7 @@ export class AppRouteRouteModule extends RouteModule<
// to merge the modified cookies and the returned response // to merge the modified cookies and the returned response
// here. // here.
const headers = new Headers(res.headers) const headers = new Headers(res.headers)
if ( if (appendMutableCookies(headers, requestStore.mutableCookies)) {
requestStore.type === 'request' &&
appendMutableCookies(headers, requestStore.mutableCookies)
) {
return new Response(res.body, { return new Response(res.body, {
status: res.status, status: res.status,
statusText: res.statusText, statusText: res.statusText,
...@@ -1154,18 +1150,6 @@ function trackDynamic( ...@@ -1154,18 +1150,6 @@ function trackDynamic(
workUnitStore: undefined | WorkUnitStore, workUnitStore: undefined | WorkUnitStore,
expression: string expression: string
): void { ): void {
if (workUnitStore) {
if (workUnitStore.type === 'cache') {
throw new Error(
`Route ${store.route} used "${expression}" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
} else if (workUnitStore.type === 'unstable-cache') {
throw new Error(
`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
}
}
if (store.dynamicShouldError) { if (store.dynamicShouldError) {
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route ${store.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering` `Route ${store.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
...@@ -1173,41 +1157,54 @@ function trackDynamic( ...@@ -1173,41 +1157,54 @@ function trackDynamic(
} }
if (workUnitStore) { if (workUnitStore) {
if (workUnitStore.type === 'prerender') { switch (workUnitStore.type) {
// dynamicIO Prerender case 'cache':
const error = new Error( throw new Error(
`Route ${store.route} used ${expression} without first calling \`await connection()\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-request` `Route ${store.route} used "${expression}" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
) )
abortAndThrowOnSynchronousRequestDataAccess( case 'unstable-cache':
store.route, throw new Error(
expression, `Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
error, )
workUnitStore case 'prerender':
) const error = new Error(
} else if (workUnitStore.type === 'prerender-ppr') { `Route ${store.route} used ${expression} without first calling \`await connection()\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-request`
// PPR Prerender )
postponeWithTracking( return abortAndThrowOnSynchronousRequestDataAccess(
store.route, store.route,
expression, expression,
workUnitStore.dynamicTracking error,
) workUnitStore
} else if (workUnitStore.type === 'prerender-legacy') { )
// legacy Prerender case 'prerender-client':
workUnitStore.revalidate = 0 throw new InvariantError(
'A client prerender store should not be used for a route handler.'
const err = new DynamicServerError( )
`Route ${store.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error` case 'prerender-ppr':
) return postponeWithTracking(
store.dynamicUsageDescription = expression store.route,
store.dynamicUsageStack = err.stack expression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy':
workUnitStore.revalidate = 0
throw err const err = new DynamicServerError(
} else if ( `Route ${store.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`
process.env.NODE_ENV === 'development' && )
workUnitStore && store.dynamicUsageDescription = expression
workUnitStore.type === 'request' store.dynamicUsageStack = err.stack
) {
workUnitStore.usedDynamic = true throw err
case 'request':
if (process.env.NODE_ENV !== 'production') {
// TODO: This is currently not really needed for route handlers, as it
// only controls the ISR status that's shown for pages.
workUnitStore.usedDynamic = true
}
break
default:
workUnitStore satisfies never
} }
} }
} }
...@@ -92,10 +92,22 @@ export function cacheLife(profile: CacheLifeProfiles | CacheLife): void { ...@@ -92,10 +92,22 @@ export function cacheLife(profile: CacheLifeProfiles | CacheLife): void {
} }
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (!workUnitStore || workUnitStore.type !== 'cache') {
throw new Error( switch (workUnitStore?.type) {
'cacheLife() can only be called inside a "use cache" function.' case 'prerender':
) case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'unstable-cache':
case undefined:
throw new Error(
'cacheLife() can only be called inside a "use cache" function.'
)
case 'cache':
break
default:
workUnitStore satisfies never
} }
if (typeof profile === 'string') { if (typeof profile === 'string') {
......
...@@ -9,10 +9,22 @@ export function cacheTag(...tags: string[]): void { ...@@ -9,10 +9,22 @@ export function cacheTag(...tags: string[]): void {
} }
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (!workUnitStore || workUnitStore.type !== 'cache') {
throw new Error( switch (workUnitStore?.type) {
'cacheTag() can only be called inside a "use cache" function.' case 'prerender':
) case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'unstable-cache':
case undefined:
throw new Error(
'cacheTag() can only be called inside a "use cache" function.'
)
case 'cache':
break
default:
workUnitStore satisfies never
} }
const validTags = validateTags(tags, 'cacheTag()') const validTags = validateTags(tags, 'cacheTag()')
......
...@@ -93,15 +93,6 @@ function revalidate(tags: string[], expression: string) { ...@@ -93,15 +93,6 @@ function revalidate(tags: string[], expression: string) {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) { if (workUnitStore) {
if (workUnitStore.type === 'cache') {
throw new Error(
`Route ${store.route} used "${expression}" inside a "use cache" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
} else if (workUnitStore.type === 'unstable-cache') {
throw new Error(
`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
}
if (workUnitStore.phase === 'render') { if (workUnitStore.phase === 'render') {
throw new Error( throw new Error(
`Route ${store.route} used "${expression}" during render which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering` `Route ${store.route} used "${expression}" during render which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
...@@ -109,32 +100,35 @@ function revalidate(tags: string[], expression: string) { ...@@ -109,32 +100,35 @@ function revalidate(tags: string[], expression: string) {
} }
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'cache':
throw new Error(
`Route ${store.route} used "${expression}" inside a "use cache" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
case 'unstable-cache':
throw new Error(
`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
case 'prerender': case 'prerender':
// dynamicIO Prerender
const error = new Error( const error = new Error(
`Route ${store.route} used ${expression} without first calling \`await connection()\`.` `Route ${store.route} used ${expression} without first calling \`await connection()\`.`
) )
abortAndThrowOnSynchronousRequestDataAccess( return abortAndThrowOnSynchronousRequestDataAccess(
store.route, store.route,
expression, expression,
error, error,
workUnitStore workUnitStore
) )
break
case 'prerender-client': case 'prerender-client':
throw new InvariantError( throw new InvariantError(
`${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.` `${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.`
) )
case 'prerender-ppr': case 'prerender-ppr':
// PPR Prerender return postponeWithTracking(
postponeWithTracking(
store.route, store.route,
expression, expression,
workUnitStore.dynamicTracking workUnitStore.dynamicTracking
) )
break
case 'prerender-legacy': case 'prerender-legacy':
// legacy Prerender
workUnitStore.revalidate = 0 workUnitStore.revalidate = 0
const err = new DynamicServerError( const err = new DynamicServerError(
...@@ -145,12 +139,15 @@ function revalidate(tags: string[], expression: string) { ...@@ -145,12 +139,15 @@ function revalidate(tags: string[], expression: string) {
throw err throw err
case 'request': case 'request':
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV !== 'production') {
// TODO: This is most likely incorrect. It would lead to the ISR
// status being flipped when revalidating a static page with a server
// action.
workUnitStore.usedDynamic = true workUnitStore.usedDynamic = true
} }
break break
default: default:
// fallthrough workUnitStore satisfies never
} }
} }
......
...@@ -2,8 +2,12 @@ import type { IncrementalCache } from '../../lib/incremental-cache' ...@@ -2,8 +2,12 @@ import type { IncrementalCache } from '../../lib/incremental-cache'
import { CACHE_ONE_YEAR } from '../../../lib/constants' import { CACHE_ONE_YEAR } from '../../../lib/constants'
import { validateRevalidate, validateTags } from '../../lib/patch-fetch' import { validateRevalidate, validateTags } from '../../lib/patch-fetch'
import { workAsyncStorage } from '../../app-render/work-async-storage.external'
import { import {
workAsyncStorage,
type WorkStore,
} from '../../app-render/work-async-storage.external'
import {
getCacheSignal,
getDraftModeProviderForCacheScope, getDraftModeProviderForCacheScope,
workUnitAsyncStorage, workUnitAsyncStorage,
} from '../../app-render/work-unit-async-storage.external' } from '../../app-render/work-unit-async-storage.external'
...@@ -12,7 +16,10 @@ import { ...@@ -12,7 +16,10 @@ import {
IncrementalCacheKind, IncrementalCacheKind,
type CachedFetchData, type CachedFetchData,
} from '../../response-cache' } from '../../response-cache'
import type { UnstableCacheStore } from '../../app-render/work-unit-async-storage.external' import type {
UnstableCacheStore,
WorkUnitStore,
} from '../../app-render/work-unit-async-storage.external'
type Callback = (...args: any[]) => Promise<any> type Callback = (...args: any[]) => Promise<any>
...@@ -106,31 +113,19 @@ export function unstable_cache<T extends Callback>( ...@@ -106,31 +113,19 @@ export function unstable_cache<T extends Callback>(
} }
const incrementalCache = maybeIncrementalCache const incrementalCache = maybeIncrementalCache
const cacheSignal = const cacheSignal = workUnitStore ? getCacheSignal(workUnitStore) : null
workUnitStore && workUnitStore.type === 'prerender'
? workUnitStore.cacheSignal
: null
if (cacheSignal) { if (cacheSignal) {
cacheSignal.beginRead() cacheSignal.beginRead()
} }
try { try {
// If there's no request store, we aren't in a request (or we're not in app // If there's no request store, we aren't in a request (or we're not in
// router) and if there's no static generation store, we aren't in app // app router) and if there's no static generation store, we aren't in app
// router. Default to an empty pathname and search params when there's no // router. Default to an empty pathname and search params when there's no
// request store or static generation store available. // request store or static generation store available.
const requestStore = const fetchUrlPrefix =
workUnitStore && workUnitStore.type === 'request' workStore && workUnitStore
? workUnitStore ? getFetchUrlPrefix(workStore, workUnitStore)
: undefined : ''
const pathname = requestStore?.url.pathname ?? workStore?.route ?? ''
const searchParams = new URLSearchParams(requestStore?.url.search ?? '')
const sortedSearchKeys = [...searchParams.keys()].sort((a, b) => {
return a.localeCompare(b)
})
const sortedSearch = sortedSearchKeys
.map((key) => `${key}=${searchParams.get(key)}`)
.join('&')
// Construct the complete cache key for this function invocation // Construct the complete cache key for this function invocation
// @TODO stringify is likely not safe here. We will coerce undefined to null which will make // @TODO stringify is likely not safe here. We will coerce undefined to null which will make
...@@ -138,7 +133,7 @@ export function unstable_cache<T extends Callback>( ...@@ -138,7 +133,7 @@ export function unstable_cache<T extends Callback>(
const invocationKey = `${fixedKey}-${JSON.stringify(args)}` const invocationKey = `${fixedKey}-${JSON.stringify(args)}`
const cacheKey = await incrementalCache.generateCacheKey(invocationKey) const cacheKey = await incrementalCache.generateCacheKey(invocationKey)
// $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse // $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse
const fetchUrl = `unstable_cache ${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch} ${cb.name ? ` ${cb.name}` : cacheKey}` const fetchUrl = `unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`
const fetchIdx = const fetchIdx =
(workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1 (workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1
...@@ -161,40 +156,49 @@ export function unstable_cache<T extends Callback>( ...@@ -161,40 +156,49 @@ export function unstable_cache<T extends Callback>(
// If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in
// the background. If the entry is missing or invalid we generate a new entry and return it. // the background. If the entry is missing or invalid we generate a new entry and return it.
// We update the store's revalidate property if the option.revalidate is a higher precedence let isNestedUnstableCache = false
if (
workUnitStore && if (workUnitStore) {
(workUnitStore.type === 'cache' || switch (workUnitStore.type) {
workUnitStore.type === 'prerender' || case 'cache':
workUnitStore.type === 'prerender-ppr' || case 'prerender':
workUnitStore.type === 'prerender-legacy') case 'prerender-ppr':
) { case 'prerender-legacy':
// options.revalidate === undefined doesn't affect timing. // We update the store's revalidate property if the option.revalidate is a higher precedence
// options.revalidate === false doesn't shrink timing. it stays at the maximum. // options.revalidate === undefined doesn't affect timing.
if (typeof options.revalidate === 'number') { // options.revalidate === false doesn't shrink timing. it stays at the maximum.
if (workUnitStore.revalidate < options.revalidate) { if (typeof options.revalidate === 'number') {
// The store is already revalidating on a shorter time interval, leave it alone if (workUnitStore.revalidate < options.revalidate) {
} else { // The store is already revalidating on a shorter time interval, leave it alone
workUnitStore.revalidate = options.revalidate } else {
} workUnitStore.revalidate = options.revalidate
} }
}
// We need to accumulate the tags for this invocation within the store // We need to accumulate the tags for this invocation within the store
const collectedTags = workUnitStore.tags const collectedTags = workUnitStore.tags
if (collectedTags === null) { if (collectedTags === null) {
workUnitStore.tags = tags.slice() workUnitStore.tags = tags.slice()
} else { } else {
for (const tag of tags) { for (const tag of tags) {
// @TODO refactor tags to be a set to avoid this O(n) lookup // @TODO refactor tags to be a set to avoid this O(n) lookup
if (!collectedTags.includes(tag)) { if (!collectedTags.includes(tag)) {
collectedTags.push(tag) collectedTags.push(tag)
}
}
} }
} break
case 'unstable-cache':
isNestedUnstableCache = true
break
case 'prerender-client':
case 'request':
break
default:
workUnitStore satisfies never
} }
} }
const isNestedUnstableCache =
workUnitStore && workUnitStore.type === 'unstable-cache'
if ( if (
// when we are nested inside of other unstable_cache's // when we are nested inside of other unstable_cache's
// we should bypass cache similar to fetches // we should bypass cache similar to fetches
...@@ -361,3 +365,30 @@ export function unstable_cache<T extends Callback>( ...@@ -361,3 +365,30 @@ export function unstable_cache<T extends Callback>(
// TODO: once AsyncLocalStorage.run() returns the correct types this override will no longer be necessary // TODO: once AsyncLocalStorage.run() returns the correct types this override will no longer be necessary
return cachedCb as unknown as T return cachedCb as unknown as T
} }
function getFetchUrlPrefix(
workStore: WorkStore,
workUnitStore: WorkUnitStore
): string {
switch (workUnitStore.type) {
case 'request':
const pathname = workUnitStore.url.pathname
const searchParams = new URLSearchParams(workUnitStore.url.search)
const sortedSearch = [...searchParams.keys()]
.sort((a, b) => a.localeCompare(b))
.map((key) => `${key}=${searchParams.get(key)}`)
.join('&')
return `${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch}`
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'unstable-cache':
return workStore.route
default:
return workUnitStore satisfies never
}
}
...@@ -36,8 +36,14 @@ export function unstable_noStore() { ...@@ -36,8 +36,14 @@ export function unstable_noStore() {
case 'prerender-client': case 'prerender-client':
// unstable_noStore() is a noop in Dynamic I/O. // unstable_noStore() is a noop in Dynamic I/O.
return return
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'unstable-cache':
break
default: default:
// fallthrough workUnitStore satisfies never
} }
} }
markCurrentScopeAsDynamic(store, workUnitStore, callingExpression) markCurrentScopeAsDynamic(store, workUnitStore, callingExpression)
......
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