Unverified Commit c85914c1 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

Revert "[dynamicIO] warn for disallowed dynamic in dev" (#71566)

We're going to land this after 15.

Reverts vercel/next.js#71526
parent 0aba53da
...@@ -40,13 +40,27 @@ export function ClientPageRoot({ ...@@ -40,13 +40,27 @@ export function ClientPageRoot({
) )
} }
const { createSearchParamsFromClient } = if (store.isStaticGeneration) {
require('../../server/request/search-params') as typeof import('../../server/request/search-params') // We are in a prerender context
clientSearchParams = createSearchParamsFromClient(searchParams, store) const { createPrerenderSearchParamsFromClient } =
require('../../server/request/search-params') as typeof import('../../server/request/search-params')
clientSearchParams = createPrerenderSearchParamsFromClient(store)
const { createParamsFromClient } = const { createPrerenderParamsFromClient } =
require('../../server/request/params') as typeof import('../../server/request/params') require('../../server/request/params') as typeof import('../../server/request/params')
clientParams = createParamsFromClient(params, store)
clientParams = createPrerenderParamsFromClient(params, store)
} else {
const { createRenderSearchParamsFromClient } =
require('../../server/request/search-params') as typeof import('../../server/request/search-params')
clientSearchParams = createRenderSearchParamsFromClient(
searchParams,
store
)
const { createRenderParamsFromClient } =
require('../../server/request/params') as typeof import('../../server/request/params')
clientParams = createRenderParamsFromClient(params, store)
}
return <Component params={clientParams} searchParams={clientSearchParams} /> return <Component params={clientParams} searchParams={clientSearchParams} />
} else { } else {
......
...@@ -38,10 +38,16 @@ export function ClientSegmentRoot({ ...@@ -38,10 +38,16 @@ export function ClientSegmentRoot({
) )
} }
const { createParamsFromClient } = const { createPrerenderParamsFromClient } =
require('../../server/request/params') as typeof import('../../server/request/params') require('../../server/request/params') as typeof import('../../server/request/params')
clientParams = createParamsFromClient(params, store)
if (store.isStaticGeneration) {
clientParams = createPrerenderParamsFromClient(params, store)
} else {
const { createRenderParamsFromClient } =
require('../../server/request/params') as typeof import('../../server/request/params')
clientParams = createRenderParamsFromClient(params, store)
}
return <Component {...slots} params={clientParams} /> return <Component {...slots} params={clientParams} />
} else { } else {
const { createRenderParamsFromClient } = const { createRenderParamsFromClient } =
......
...@@ -21,19 +21,18 @@ ...@@ -21,19 +21,18 @@
*/ */
import type { WorkStore } from '../app-render/work-async-storage.external' import type { WorkStore } from '../app-render/work-async-storage.external'
import type { import type { WorkUnitStore } from '../app-render/work-unit-async-storage.external'
WorkUnitStore,
RequestStore,
PrerenderStoreLegacy,
PrerenderStoreModern,
} from '../app-render/work-unit-async-storage.external'
// Once postpone is in stable we should switch to importing the postpone export directly // Once postpone is in stable we should switch to importing the postpone export directly
import React from 'react' import React from 'react'
import { DynamicServerError } from '../../client/components/hooks-server-context' import { DynamicServerError } from '../../client/components/hooks-server-context'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { workUnitAsyncStorage } from './work-unit-async-storage.external' import {
workUnitAsyncStorage,
type PrerenderStoreLegacy,
type PrerenderStoreModern,
} from './work-unit-async-storage.external'
import { workAsyncStorage } from '../app-render/work-async-storage.external' import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils' import { makeHangingPromise } from '../dynamic-rendering-utils'
import { import {
...@@ -72,8 +71,6 @@ export type DynamicTrackingState = { ...@@ -72,8 +71,6 @@ export type DynamicTrackingState = {
syncDynamicExpression: undefined | string syncDynamicExpression: undefined | string
syncDynamicErrorWithStack: null | Error syncDynamicErrorWithStack: null | Error
// Dev only
syncDynamicLogged?: boolean
} }
// Stores dynamic reasons used during an SSR render. // Stores dynamic reasons used during an SSR render.
...@@ -81,7 +78,7 @@ export type DynamicValidationState = { ...@@ -81,7 +78,7 @@ export type DynamicValidationState = {
hasSuspendedDynamic: boolean hasSuspendedDynamic: boolean
hasDynamicMetadata: boolean hasDynamicMetadata: boolean
hasDynamicViewport: boolean hasDynamicViewport: boolean
hasSyncDynamicErrors: boolean syncDynamicErrors: Array<Error>
dynamicErrors: Array<Error> dynamicErrors: Array<Error>
} }
...@@ -101,7 +98,7 @@ export function createDynamicValidationState(): DynamicValidationState { ...@@ -101,7 +98,7 @@ export function createDynamicValidationState(): DynamicValidationState {
hasSuspendedDynamic: false, hasSuspendedDynamic: false,
hasDynamicMetadata: false, hasDynamicMetadata: false,
hasDynamicViewport: false, hasDynamicViewport: false,
hasSyncDynamicErrors: false, syncDynamicErrors: [],
dynamicErrors: [], dynamicErrors: [],
} }
} }
...@@ -298,14 +295,6 @@ export function abortOnSynchronousPlatformIOAccess( ...@@ -298,14 +295,6 @@ export function abortOnSynchronousPlatformIOAccess(
return abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore) return abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore)
} }
export function trackSynchronousPlatformIOAccessInDev(
requestStore: RequestStore
): void {
// We don't actually have a controller to abort but we do the semantic equivalent by
// advancing the request store out of prerender mode
requestStore.prerenderPhase = false
}
/** /**
* use this function when prerendering with dynamicIO. If we are doing a * use this function when prerendering with dynamicIO. If we are doing a
* prospective prerender we don't actually abort because we want to discover * prospective prerender we don't actually abort because we want to discover
...@@ -327,11 +316,6 @@ export function abortAndThrowOnSynchronousRequestDataAccess( ...@@ -327,11 +316,6 @@ export function abortAndThrowOnSynchronousRequestDataAccess(
if (dynamicTracking.syncDynamicErrorWithStack === null) { if (dynamicTracking.syncDynamicErrorWithStack === null) {
dynamicTracking.syncDynamicExpression = expression dynamicTracking.syncDynamicExpression = expression
dynamicTracking.syncDynamicErrorWithStack = errorWithStack dynamicTracking.syncDynamicErrorWithStack = errorWithStack
if (prerenderStore.validating === true) {
// We always log Request Access in dev at the point of calling the function
// So we mark the dynamic validation as not requiring it to be printed
dynamicTracking.syncDynamicLogged = true
}
} }
} }
abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore) abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore)
...@@ -340,10 +324,6 @@ export function abortAndThrowOnSynchronousRequestDataAccess( ...@@ -340,10 +324,6 @@ export function abortAndThrowOnSynchronousRequestDataAccess(
) )
} }
// For now these implementations are the same so we just reexport
export const trackSynchronousRequestDataAccessInDev =
trackSynchronousPlatformIOAccessInDev
/** /**
* This component will call `React.postpone` that throws the postponed error. * This component will call `React.postpone` that throws the postponed error.
*/ */
...@@ -598,11 +578,15 @@ export function trackAllowedDynamicAccess( ...@@ -598,11 +578,15 @@ export function trackAllowedDynamicAccess(
} else if (hasSuspenseRegex.test(componentStack)) { } else if (hasSuspenseRegex.test(componentStack)) {
dynamicValidation.hasSuspendedDynamic = true dynamicValidation.hasSuspendedDynamic = true
return return
} else if ( } else if (typeof serverDynamic.syncDynamicExpression === 'string') {
serverDynamic.syncDynamicErrorWithStack || const message = `In Route "${route}" this parent component stack may help you locate where ${serverDynamic.syncDynamicExpression} was used.`
clientDynamic.syncDynamicErrorWithStack const error = createErrorWithComponentStack(message, componentStack)
) { dynamicValidation.syncDynamicErrors.push(error)
dynamicValidation.hasSyncDynamicErrors = true return
} else if (typeof clientDynamic.syncDynamicExpression === 'string') {
const message = `In Route "${route}" this parent component stack may help you locate where ${clientDynamic.syncDynamicExpression} was used.`
const error = createErrorWithComponentStack(message, componentStack)
dynamicValidation.syncDynamicErrors.push(error)
return return
} else { } else {
// The thrownValue must have been the RENDER_COMPLETE abortReason because the only kinds of errors tracked here are // The thrownValue must have been the RENDER_COMPLETE abortReason because the only kinds of errors tracked here are
...@@ -624,37 +608,33 @@ function createErrorWithComponentStack( ...@@ -624,37 +608,33 @@ function createErrorWithComponentStack(
} }
export function throwIfDisallowedDynamic( export function throwIfDisallowedDynamic(
route: string, workStore: WorkStore,
dynamicValidation: DynamicValidationState, dynamicValidation: DynamicValidationState,
serverDynamic: DynamicTrackingState, serverDynamic: DynamicTrackingState,
clientDynamic: DynamicTrackingState clientDynamic: DynamicTrackingState
): void { ): void {
let syncError: null | Error const syncDynamicErrors = dynamicValidation.syncDynamicErrors
let syncExpression: undefined | string let syncError: null | Error, syncExpression: undefined | string
let syncLogged: boolean if (serverDynamic.syncDynamicExpression) {
if (serverDynamic.syncDynamicErrorWithStack) {
syncError = serverDynamic.syncDynamicErrorWithStack syncError = serverDynamic.syncDynamicErrorWithStack
syncExpression = serverDynamic.syncDynamicExpression! syncExpression = serverDynamic.syncDynamicExpression!
syncLogged = serverDynamic.syncDynamicLogged === true } else if (clientDynamic.syncDynamicExpression) {
} else if (clientDynamic.syncDynamicErrorWithStack) {
syncError = clientDynamic.syncDynamicErrorWithStack syncError = clientDynamic.syncDynamicErrorWithStack
syncExpression = clientDynamic.syncDynamicExpression! syncExpression = clientDynamic.syncDynamicExpression!
syncLogged = clientDynamic.syncDynamicLogged === true
} else { } else {
syncError = null syncError = null
syncExpression = undefined syncExpression = undefined
syncLogged = false
} }
if (dynamicValidation.hasSyncDynamicErrors && syncError) { if (syncDynamicErrors.length && syncError) {
if (!syncLogged) { console.error(syncError)
// In dev we already log errors about sync dynamic access. But during builds we need to ensure
// the offending sync error is logged before we exit the build for (let i = 0; i < syncDynamicErrors.length; i++) {
console.error(syncError) console.error(syncDynamicErrors[i])
} }
// The actual error should have been logged when the sync access ocurred
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route "${route}" could not be prerendered.` `Route "${workStore.route}" could not be prerendered.`
) )
} }
...@@ -665,7 +645,7 @@ export function throwIfDisallowedDynamic( ...@@ -665,7 +645,7 @@ export function throwIfDisallowedDynamic(
} }
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route "${route}" could not be prerendered.` `Route "${workStore.route}" could not be prerendered.`
) )
} }
...@@ -674,21 +654,21 @@ export function throwIfDisallowedDynamic( ...@@ -674,21 +654,21 @@ export function throwIfDisallowedDynamic(
if (syncError) { if (syncError) {
console.error(syncError) console.error(syncError)
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route "${route}" has a \`generateMetadata\` that could not finish rendering before ${syncExpression} was used. Follow the instructions in the error for this expression to resolve.` `Route "${workStore.route}" has a \`generateMetadata\` that could not finish rendering before ${syncExpression} was used. Follow the instructions in the error for this expression to resolve.`
) )
} }
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route "${route}" has a \`generateMetadata\` that depends on Request data (\`cookies()\`, etc...) or external data (\`fetch(...)\`, etc...) but the rest of the route was static or only used cached data (\`"use cache"\`). If you expected this route to be prerenderable update your \`generateMetadata\` to not use Request data and only use cached external data. Otherwise, add \`await connection()\` somewhere within this route to indicate explicitly it should not be prerendered.` `Route "${workStore.route}" has a \`generateMetadata\` that depends on Request data (\`cookies()\`, etc...) or external data (\`fetch(...)\`, etc...) but the rest of the route was static or only used cached data (\`"use cache"\`). If you expected this route to be prerenderable update your \`generateMetadata\` to not use Request data and only use cached external data. Otherwise, add \`await connection()\` somewhere within this route to indicate explicitly it should not be prerendered.`
) )
} else if (dynamicValidation.hasDynamicViewport) { } else if (dynamicValidation.hasDynamicViewport) {
if (syncError) { if (syncError) {
console.error(syncError) console.error(syncError)
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route "${route}" has a \`generateViewport\` that could not finish rendering before ${syncExpression} was used. Follow the instructions in the error for this expression to resolve.` `Route "${workStore.route}" has a \`generateViewport\` that could not finish rendering before ${syncExpression} was used. Follow the instructions in the error for this expression to resolve.`
) )
} }
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route "${route}" has a \`generateViewport\` that depends on Request data (\`cookies()\`, etc...) or external data (\`fetch(...)\`, etc...) but the rest of the route was static or only used cached data (\`"use cache"\`). If you expected this route to be prerenderable update your \`generateViewport\` to not use Request data and only use cached external data. Otherwise, add \`await connection()\` somewhere within this route to indicate explicitly it should not be prerendered.` `Route "${workStore.route}" has a \`generateViewport\` that depends on Request data (\`cookies()\`, etc...) or external data (\`fetch(...)\`, etc...) but the rest of the route was static or only used cached data (\`"use cache"\`). If you expected this route to be prerenderable update your \`generateViewport\` to not use Request data and only use cached external data. Otherwise, add \`await connection()\` somewhere within this route to indicate explicitly it should not be prerendered.`
) )
} }
} }
......
...@@ -51,7 +51,7 @@ export type RequestStore = { ...@@ -51,7 +51,7 @@ export type RequestStore = {
// DEV-only // DEV-only
usedDynamic?: boolean usedDynamic?: boolean
prerenderPhase?: boolean environment?: 'Prerender' | 'Server'
} & PhasePartial } & PhasePartial
/** /**
...@@ -94,12 +94,6 @@ export type PrerenderStoreModern = { ...@@ -94,12 +94,6 @@ export type PrerenderStoreModern = {
expire: number // server expiration time expire: number // server expiration time
stale: number // client expiration time stale: number // client expiration time
tags: null | string[] tags: null | string[]
// DEV ONLY
// When used this flag informs certain APIs to skip logging because we're
// not part of the primary render path and are just prerendering to produce
// validation results
validating?: boolean
} & PhasePartial } & PhasePartial
export type PrerenderStorePPR = { export type PrerenderStorePPR = {
......
...@@ -48,7 +48,7 @@ export function createDedupedByCallsiteServerErrorLoggerDev<Args extends any[]>( ...@@ -48,7 +48,7 @@ export function createDedupedByCallsiteServerErrorLoggerDev<Args extends any[]>(
// asyncApiBeingAccessedSynchronously // asyncApiBeingAccessedSynchronously
// <userland callsite> // <userland callsite>
// TODO: This breaks if sourcemaps with ignore lists are enabled. // TODO: This breaks if sourcemaps with ignore lists are enabled.
const key = callStackFrames[4] const key = callStackFrames[3]
errorRef.current = message errorRef.current = message
flushCurrentErrorIfNew(key) flushCurrentErrorIfNew(key)
} }
......
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 } from '../app-render/work-unit-async-storage.external'
import { import { abortOnSynchronousPlatformIOAccess } from '../app-render/dynamic-rendering'
abortOnSynchronousPlatformIOAccess,
trackSynchronousPlatformIOAccessInDev,
} from '../app-render/dynamic-rendering'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
type ApiType = 'time' | 'random' | 'crypto' type ApiType = 'time' | 'random' | 'crypto'
...@@ -39,12 +36,6 @@ export function io(expression: string, type: ApiType) { ...@@ -39,12 +36,6 @@ export function io(expression: string, type: ApiType) {
workUnitStore workUnitStore
) )
} }
} else if (
workUnitStore.type === 'request' &&
workUnitStore.prerenderPhase === true
) {
const requestStore = workUnitStore
trackSynchronousPlatformIOAccessInDev(requestStore)
} }
} }
} }
This diff is collapsed.
...@@ -7,7 +7,6 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.exte ...@@ -7,7 +7,6 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.exte
import { import {
abortAndThrowOnSynchronousRequestDataAccess, abortAndThrowOnSynchronousRequestDataAccess,
postponeWithTracking, postponeWithTracking,
trackSynchronousRequestDataAccessInDev,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-loger' import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-loger'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
...@@ -126,8 +125,8 @@ function createExoticDraftModeWithDevWarnings( ...@@ -126,8 +125,8 @@ function createExoticDraftModeWithDevWarnings(
Object.defineProperty(promise, 'isEnabled', { Object.defineProperty(promise, 'isEnabled', {
get() { get() {
const expression = '`draftMode().isEnabled`' const expression = 'draftMode().isEnabled'
syncIODev(route, expression) warnForSyncAccess(route, expression)
return instance.isEnabled return instance.isEnabled
}, },
set(newValue) { set(newValue) {
...@@ -143,16 +142,16 @@ function createExoticDraftModeWithDevWarnings( ...@@ -143,16 +142,16 @@ function createExoticDraftModeWithDevWarnings(
Object.defineProperty(promise, 'enable', { Object.defineProperty(promise, 'enable', {
value: function get() { value: function get() {
const expression = '`draftMode().enable()`' const expression = 'draftMode().enable()'
syncIODev(route, expression) warnForSyncAccess(route, expression)
return instance.enable.apply(instance, arguments as any) return instance.enable.apply(instance, arguments as any)
}, },
}) })
Object.defineProperty(promise, 'disable', { Object.defineProperty(promise, 'disable', {
value: function get() { value: function get() {
const expression = '`draftMode().disable()`' const expression = 'draftMode().disable()'
syncIODev(route, expression) warnForSyncAccess(route, expression)
return instance.disable.apply(instance, arguments as any) return instance.disable.apply(instance, arguments as any)
}, },
}) })
...@@ -191,39 +190,21 @@ class DraftMode { ...@@ -191,39 +190,21 @@ class DraftMode {
} }
} }
function syncIODev(route: string | undefined, expression: string) {
const workUnitStore = workUnitAsyncStorage.getStore()
if (
workUnitStore &&
workUnitStore.type === 'request' &&
workUnitStore.prerenderPhase === true
) {
// When we're rendering dynamically in dev we need to advance out of the
// Prerender environment when we read Request data synchronously
const requestStore = workUnitStore
trackSynchronousRequestDataAccessInDev(requestStore)
}
// In all cases we warn normally
warnForSyncAccess(route, expression)
}
const noop = () => {} const noop = () => {}
const warnForSyncAccess = process.env.__NEXT_DISABLE_SYNC_DYNAMIC_API_WARNINGS const warnForSyncAccess = process.env.__NEXT_DISABLE_SYNC_DYNAMIC_API_WARNINGS
? noop ? noop
: createDedupedByCallsiteServerErrorLoggerDev(createDraftModeAccessError) : createDedupedByCallsiteServerErrorLoggerDev(function getSyncAccessWarning(
route: undefined | string,
function createDraftModeAccessError( expression: string
route: string | undefined, ) {
expression: string const prefix = route ? ` In route ${route} a ` : 'A '
) { return new Error(
const prefix = route ? `Route "${route}" ` : 'This route ' `${prefix}\`draftMode()\` property was accessed directly with \`${expression}\`. ` +
return new Error( `\`draftMode()\` should be awaited before using its value. ` +
`${prefix}used ${expression}. ` + `Learn more: https://nextjs.org/docs/messages/draft-mode-sync-access`
`\`draftMode()\` should be awaited before using its value. ` + )
`Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis` })
)
}
function trackDynamicDraftMode(expression: string) { function trackDynamicDraftMode(expression: string) {
const store = workAsyncStorage.getStore() const store = workAsyncStorage.getStore()
......
This diff is collapsed.
This diff is collapsed.
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
/**
* React annotates Promises with extra properties to make unwrapping them synchronous
* after they have resolved. We sometimes create promises that are compatible with this
* internal implementation detail when we want to construct a promise that is already resolved.
*
* @internal
*/
export function makeResolvedReactPromise<T>(value: T): Promise<T> {
const promise = Promise.resolve(value)
;(promise as any).status = 'fulfilled'
;(promise as any).value = value
return promise
}
// This regex will have fast negatives meaning valid identifiers may not pass // This regex will have fast negatives meaning valid identifiers may not pass
// this test. However this is only used during static generation to provide hints // this test. However this is only used during static generation to provide hints
// about why a page bailed out of some or all prerendering and we can use bracket notation // about why a page bailed out of some or all prerendering and we can use bracket notation
...@@ -58,9 +72,6 @@ export const wellKnownProperties = new Set([ ...@@ -58,9 +72,6 @@ export const wellKnownProperties = new Set([
// fallthrough // fallthrough
'status', 'status',
// React introspection
'displayName',
// Common tested properties // Common tested properties
// fallthrough // fallthrough
'toJSON', 'toJSON',
......
...@@ -28,14 +28,20 @@ describe('dynamic-data', () => { ...@@ -28,14 +28,20 @@ describe('dynamic-data', () => {
// in dev we expect the entire page to be rendered at runtime // in dev we expect the entire page to be rendered at runtime
expect($('#layout').text()).toBe('at runtime') expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime') expect($('#page').text()).toBe('at runtime')
// we expect there to be no suspense boundary in fallback state
expect($('#boundary').html()).toBeNull()
} else if (process.env.__NEXT_EXPERIMENTAL_PPR) { } else if (process.env.__NEXT_EXPERIMENTAL_PPR) {
// in PPR we expect the shell to be rendered at build and the page to be rendered at runtime // in PPR we expect the shell to be rendered at build and the page to be rendered at runtime
expect($('#layout').text()).toBe('at buildtime') expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime') expect($('#page').text()).toBe('at runtime')
// we expect there to be a suspense boundary in fallback state
expect($('#boundary').html()).not.toBeNull()
} else { } else {
// in static generation we expect the entire page to be rendered at runtime // in static generation we expect the entire page to be rendered at runtime
expect($('#layout').text()).toBe('at runtime') expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime') expect($('#page').text()).toBe('at runtime')
// we expect there to be no suspense boundary in fallback state
expect($('#boundary').html()).toBeNull()
} }
expect($('#headers .fooheader').text()).toBe('foo header value') expect($('#headers .fooheader').text()).toBe('foo header value')
...@@ -58,15 +64,21 @@ describe('dynamic-data', () => { ...@@ -58,15 +64,21 @@ describe('dynamic-data', () => {
// in dev we expect the entire page to be rendered at runtime // in dev we expect the entire page to be rendered at runtime
expect($('#layout').text()).toBe('at runtime') expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime') expect($('#page').text()).toBe('at runtime')
// we expect there to be no suspense boundary in fallback state
expect($('#boundary').html()).toBeNull()
} else if (process.env.__NEXT_EXPERIMENTAL_PPR) { } else if (process.env.__NEXT_EXPERIMENTAL_PPR) {
// @TODO this should actually be build but there is a bug in how we do segment level dynamic in PPR at the moment // @TODO this should actually be build but there is a bug in how we do segment level dynamic in PPR at the moment
// see note in create-component-tree // see note in create-component-tree
expect($('#layout').text()).toBe('at runtime') expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime') expect($('#page').text()).toBe('at runtime')
// we expect there to be a suspense boundary in fallback state
expect($('#boundary').html()).toBeNull()
} else { } else {
// in static generation we expect the entire page to be rendered at runtime // in static generation we expect the entire page to be rendered at runtime
expect($('#layout').text()).toBe('at runtime') expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime') expect($('#page').text()).toBe('at runtime')
// we expect there to be no suspense boundary in fallback state
expect($('#boundary').html()).toBeNull()
} }
expect($('#headers .fooheader').text()).toBe('foo header value') expect($('#headers .fooheader').text()).toBe('foo header value')
......
...@@ -39,6 +39,7 @@ function createExpectError(cliOutput: string) { ...@@ -39,6 +39,7 @@ function createExpectError(cliOutput: string) {
} }
function runTests(options: { withMinification: boolean }) { function runTests(options: { withMinification: boolean }) {
const isTurbopack = !!process.env.TURBOPACK
const { withMinification } = options const { withMinification } = options
describe(`Dynamic IO Errors - ${withMinification ? 'With Minification' : 'Without Minification'}`, () => { describe(`Dynamic IO Errors - ${withMinification ? 'With Minification' : 'Without Minification'}`, () => {
describe('Sync Dynamic - With Fallback - Math.random()', () => { describe('Sync Dynamic - With Fallback - Math.random()', () => {
...@@ -125,6 +126,11 @@ function runTests(options: { withMinification: boolean }) { ...@@ -125,6 +126,11 @@ function runTests(options: { withMinification: boolean }) {
expectError( expectError(
'Error: Route "/" used `Math.random()` outside of `"use cache"` and without explicitly calling `await connection()` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random' 'Error: Route "/" used `Math.random()` outside of `"use cache"` and without explicitly calling `await connection()` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random'
) )
expectError(
'Error: In Route "/" this parent component stack may help you locate where `Math.random()` was used.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
expectError('Error occurred prerendering page "/"') expectError('Error occurred prerendering page "/"')
expectError('Error: Route "/" could not be prerendered.') expectError('Error: Route "/" could not be prerendered.')
expectError('exiting the build.') expectError('exiting the build.')
......
...@@ -39,6 +39,7 @@ function createExpectError(cliOutput: string) { ...@@ -39,6 +39,7 @@ function createExpectError(cliOutput: string) {
} }
function runTests(options: { withMinification: boolean }) { function runTests(options: { withMinification: boolean }) {
const isTurbopack = !!process.env.TURBOPACK
const { withMinification } = options const { withMinification } = options
describe(`Dynamic IO Errors - ${withMinification ? 'With Minification' : 'Without Minification'}`, () => { describe(`Dynamic IO Errors - ${withMinification ? 'With Minification' : 'Without Minification'}`, () => {
describe('Sync Dynamic - With Fallback - client searchParams', () => { describe('Sync Dynamic - With Fallback - client searchParams', () => {
...@@ -122,7 +123,14 @@ function runTests(options: { withMinification: boolean }) { ...@@ -122,7 +123,14 @@ function runTests(options: { withMinification: boolean }) {
} }
const expectError = createExpectError(next.cliOutput) const expectError = createExpectError(next.cliOutput)
expectError('Route "/" used `searchParams.foo`') expectError(
'Error: Route "/" used `searchParams.foo`. `searchParams` is now a Promise and should be `awaited` before accessing search param values. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-params'
)
expectError(
'Error: In Route "/" this parent component stack may help you locate where `searchParams.foo` was used.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
expectError('Error occurred prerendering page "/"') expectError('Error occurred prerendering page "/"')
expectError('Error: Route "/" could not be prerendered.') expectError('Error: Route "/" could not be prerendered.')
expectError('exiting the build.') expectError('exiting the build.')
...@@ -210,7 +218,14 @@ function runTests(options: { withMinification: boolean }) { ...@@ -210,7 +218,14 @@ function runTests(options: { withMinification: boolean }) {
} }
const expectError = createExpectError(next.cliOutput) const expectError = createExpectError(next.cliOutput)
expectError('Route "/" used `searchParams.foo`') expectError(
'Error: Route "/" used `searchParams.foo`. `searchParams` is now a Promise and should be `awaited` before accessing search param values. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-params'
)
expectError(
'Error: In Route "/" this parent component stack may help you locate where `searchParams.foo` was used.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
expectError('Error occurred prerendering page "/"') expectError('Error occurred prerendering page "/"')
expectError('Error: Route "/" could not be prerendered.') expectError('Error: Route "/" could not be prerendered.')
expectError('exiting the build.') expectError('exiting the build.')
...@@ -298,7 +313,14 @@ function runTests(options: { withMinification: boolean }) { ...@@ -298,7 +313,14 @@ function runTests(options: { withMinification: boolean }) {
} }
const expectError = createExpectError(next.cliOutput) const expectError = createExpectError(next.cliOutput)
expectError('Route "/" used `cookies().get(\'token\')`') expectError(
"Error: Route \"/\" used cookies().get('token'). `cookies()` now returns a Promise and should be `awaited` before using it's value. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers"
)
expectError(
'Error: In Route "/" this parent component stack may help you locate where cookies().get(\'token\') was used.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
expectError('Error occurred prerendering page "/"') expectError('Error occurred prerendering page "/"')
expectError('Route "/" could not be prerendered.') expectError('Route "/" could not be prerendered.')
expectError('exiting the build.') expectError('exiting the build.')
......
export async function BuildID() {
const buildID = require('./lazy-id').buildID
await 1
return (
<dl>
<dt>Build ID</dt>
<dd id="id">{buildID}</dd>
</dl>
)
}
import { BuildID } from './build-id'
export default async function Page() {
return (
<>
<p>
This page requires a module lazily during rendering. The Module computes
a "static" id using the current time and a random number. If these APIs
are used while prerendering they would normally trigger a synchronous
dynamic bailout. However since these APIs are used in module scope they
are not semantically part of the render and should be usable like other
"static" values. We demonstrate this with this fixture by asserting that
this page still produces a static result and it does not warn for
reading current time and random in a prerender.
</p>
<BuildID />
</>
)
}
export function BuildID() {
const buildID = require('./lazy-id').buildID
return (
<dl>
<dt>Build ID</dt>
<dd id="id" suppressHydrationWarning={true}>
{buildID}
</dd>
</dl>
)
}
'use client'
import { BuildID } from './build-id'
export default function Page() {
return (
<>
<p>
This page requires a module lazily during rendering. The Module computes
a "static" id using the current time and a random number. If these APIs
are used while prerendering they would normally trigger a synchronous
dynamic bailout. However since these APIs are used in module scope they
are not semantically part of the render and should be usable like other
"static" values. We demonstrate this with this fixture by asserting that
this page still produces a static result and it does not warn for
reading current time and random in a prerender.
</p>
<BuildID />
</>
)
}
...@@ -5,9 +5,7 @@ export function BuildID() { ...@@ -5,9 +5,7 @@ export function BuildID() {
return ( return (
<dl> <dl>
<dt>Build ID</dt> <dt>Build ID</dt>
<dd id="id" suppressHydrationWarning={true}> <dd id="id">{buildID}</dd>
{buildID}
</dd>
</dl> </dl>
) )
} }
...@@ -6,13 +6,15 @@ import { type UnsafeUnwrappedSearchParams } from 'next/server' ...@@ -6,13 +6,15 @@ import { type UnsafeUnwrappedSearchParams } from 'next/server'
import { IndirectionOne, IndirectionTwo, IndirectionThree } from './indirection' import { IndirectionOne, IndirectionTwo, IndirectionThree } from './indirection'
type SearchParams = { foo: string | string[] | undefined } type SearchParams = { foo: string | string[] | undefined }
export default function Page(props: { searchParams: Promise<SearchParams> }) { export default async function Page(props: {
searchParams: Promise<SearchParams>
}) {
return ( return (
<> <>
<p> <p>
This page accesses searchParams synchronously and it does it early This page accesses searchParams synchronously but it does so late enough
enough that some sibling component trees are not finished and they do in the render that all unfinished sub-trees have a defined Suspense
not have a parent Suspense boundary above them. boundary. This is fine and doesn't need to error the build.
</p> </p>
<Suspense fallback={<Fallback />}> <Suspense fallback={<Fallback />}>
<IndirectionOne> <IndirectionOne>
......
...@@ -83,7 +83,7 @@ describe('dynamic-io', () => { ...@@ -83,7 +83,7 @@ describe('dynamic-io', () => {
let $ = await next.render$('/cookies/exercise/async', {}) let $ = await next.render$('/cookies/exercise/async', {})
let cookieWarnings = next.cliOutput let cookieWarnings = next.cliOutput
.split('\n') .split('\n')
.filter((l) => l.includes('Route "/cookies/exercise')) .filter((l) => l.includes('In route /cookies/exercise'))
expect(cookieWarnings).toHaveLength(0) expect(cookieWarnings).toHaveLength(0)
...@@ -143,7 +143,7 @@ describe('dynamic-io', () => { ...@@ -143,7 +143,7 @@ describe('dynamic-io', () => {
let $ = await next.render$('/cookies/exercise/sync', {}) let $ = await next.render$('/cookies/exercise/sync', {})
let cookieWarnings = next.cliOutput let cookieWarnings = next.cliOutput
.split('\n') .split('\n')
.filter((l) => l.includes('Route "/cookies/exercise')) .filter((l) => l.includes('In route /cookies/exercise'))
if (!isNextDev) { if (!isNextDev) {
expect(cookieWarnings).toHaveLength(0) expect(cookieWarnings).toHaveLength(0)
...@@ -157,9 +157,7 @@ describe('dynamic-io', () => { ...@@ -157,9 +157,7 @@ describe('dynamic-io', () => {
) )
expect($('#for-of-x-sentinel-rand').text()).toContain('x-sentinel-rand') expect($('#for-of-x-sentinel-rand').text()).toContain('x-sentinel-rand')
if (isNextDev) { if (isNextDev) {
expect(cookieWarnings[i++]).toContain( expect(cookieWarnings[i++]).toContain('cookies were iterated over')
'`...cookies()` or similar iteration.'
)
} }
// ...spread iteration // ...spread iteration
...@@ -169,15 +167,13 @@ describe('dynamic-io', () => { ...@@ -169,15 +167,13 @@ describe('dynamic-io', () => {
) )
expect($('#spread-x-sentinel-rand').text()).toContain('x-sentinel-rand') expect($('#spread-x-sentinel-rand').text()).toContain('x-sentinel-rand')
if (isNextDev) { if (isNextDev) {
expect(cookieWarnings[i++]).toContain( expect(cookieWarnings[i++]).toContain('cookies were iterated over')
'`...cookies()` or similar iteration.'
)
} }
// cookies().size // cookies().size
expect(parseInt($('#size-cookies').text())).toBeGreaterThanOrEqual(3) expect(parseInt($('#size-cookies').text())).toBeGreaterThanOrEqual(3)
if (isNextDev) { if (isNextDev) {
expect(cookieWarnings[i++]).toContain('`cookies().size`') expect(cookieWarnings[i++]).toContain('cookies().size')
} }
// cookies().get('...') && cookies().getAll('...') // cookies().get('...') && cookies().getAll('...')
...@@ -185,12 +181,10 @@ describe('dynamic-io', () => { ...@@ -185,12 +181,10 @@ describe('dynamic-io', () => {
expect($('#get-x-sentinel-path').text()).toContain('/cookies/exercise/sync') expect($('#get-x-sentinel-path').text()).toContain('/cookies/exercise/sync')
expect($('#get-x-sentinel-rand').text()).toContain('x-sentinel-rand') expect($('#get-x-sentinel-rand').text()).toContain('x-sentinel-rand')
if (isNextDev) { if (isNextDev) {
expect(cookieWarnings[i++]).toContain("`cookies().get('x-sentinel')`") expect(cookieWarnings[i++]).toContain("cookies().get('x-sentinel')")
expect(cookieWarnings[i++]).toContain( expect(cookieWarnings[i++]).toContain("cookies().get('x-sentinel-path')")
"`cookies().get('x-sentinel-path')`"
)
expect(cookieWarnings[i++]).toContain( expect(cookieWarnings[i++]).toContain(
"`cookies().getAll('x-sentinel-rand')`" "cookies().getAll('x-sentinel-rand')"
) )
} }
...@@ -198,9 +192,9 @@ describe('dynamic-io', () => { ...@@ -198,9 +192,9 @@ describe('dynamic-io', () => {
expect($('#has-x-sentinel').text()).toContain('true') expect($('#has-x-sentinel').text()).toContain('true')
expect($('#has-x-sentinel-foobar').text()).toContain('false') expect($('#has-x-sentinel-foobar').text()).toContain('false')
if (isNextDev) { if (isNextDev) {
expect(cookieWarnings[i++]).toContain("`cookies().has('x-sentinel')`") expect(cookieWarnings[i++]).toContain("cookies().has('x-sentinel')")
expect(cookieWarnings[i++]).toContain( expect(cookieWarnings[i++]).toContain(
"`cookies().has('x-sentinel-foobar')`" "cookies().has('x-sentinel-foobar')"
) )
} }
...@@ -210,10 +204,8 @@ describe('dynamic-io', () => { ...@@ -210,10 +204,8 @@ describe('dynamic-io', () => {
) )
expect($('#set-value-x-sentinel').text()).toContain('hello') expect($('#set-value-x-sentinel').text()).toContain('hello')
if (isNextDev) { if (isNextDev) {
expect(cookieWarnings[i++]).toContain( expect(cookieWarnings[i++]).toContain("cookies().set('x-sentinel', ...)")
"`cookies().set('x-sentinel', ...)`" expect(cookieWarnings[i++]).toContain("cookies().get('x-sentinel')")
)
expect(cookieWarnings[i++]).toContain("`cookies().get('x-sentinel')`")
} }
// cookies().delete('...', '...') // cookies().delete('...', '...')
...@@ -222,8 +214,8 @@ describe('dynamic-io', () => { ...@@ -222,8 +214,8 @@ describe('dynamic-io', () => {
) )
expect($('#delete-value-x-sentinel').text()).toContain('hello') expect($('#delete-value-x-sentinel').text()).toContain('hello')
if (isNextDev) { if (isNextDev) {
expect(cookieWarnings[i++]).toContain("`cookies().delete('x-sentinel')`") expect(cookieWarnings[i++]).toContain("cookies().delete('x-sentinel')")
expect(cookieWarnings[i++]).toContain("`cookies().get('x-sentinel')`") expect(cookieWarnings[i++]).toContain("cookies().get('x-sentinel')")
} }
// cookies().clear() // cookies().clear()
...@@ -232,8 +224,8 @@ describe('dynamic-io', () => { ...@@ -232,8 +224,8 @@ describe('dynamic-io', () => {
) )
expect($('#clear-value-x-sentinel').text()).toContain('hello') expect($('#clear-value-x-sentinel').text()).toContain('hello')
if (isNextDev) { if (isNextDev) {
expect(cookieWarnings[i++]).toContain('`cookies().clear()`') expect(cookieWarnings[i++]).toContain('cookies().clear()')
expect(cookieWarnings[i++]).toContain("`cookies().get('x-sentinel')`") expect(cookieWarnings[i++]).toContain("cookies().get('x-sentinel')")
} }
// cookies().toString() // cookies().toString()
...@@ -241,9 +233,7 @@ describe('dynamic-io', () => { ...@@ -241,9 +233,7 @@ describe('dynamic-io', () => {
expect($('#toString').text()).toContain('x-sentinel-path') expect($('#toString').text()).toContain('x-sentinel-path')
expect($('#toString').text()).toContain('x-sentinel-rand=') expect($('#toString').text()).toContain('x-sentinel-rand=')
if (isNextDev) { if (isNextDev) {
expect(cookieWarnings[i++]).toContain( expect(cookieWarnings[i++]).toContain('cookies().toString()')
'`cookies().toString()` or implicit casting'
)
} }
if (isNextDev) { if (isNextDev) {
......
...@@ -13,7 +13,7 @@ describe('dynamic-io', () => { ...@@ -13,7 +13,7 @@ describe('dynamic-io', () => {
} }
it('should not have route specific errors', async () => { it('should not have route specific errors', async () => {
expect(next.cliOutput).not.toMatch('Error: Route "/') expect(next.cliOutput).not.toMatch('Error: Route /')
expect(next.cliOutput).not.toMatch('Error occurred prerendering page') expect(next.cliOutput).not.toMatch('Error occurred prerendering page')
}) })
......
...@@ -25,18 +25,18 @@ describe('dynamic-io', () => { ...@@ -25,18 +25,18 @@ describe('dynamic-io', () => {
} }
it('should fully prerender pages that use draftMode', async () => { it('should fully prerender pages that use draftMode', async () => {
expect(getLines('Route "/draftmode')).toEqual([]) expect(getLines('In route /draftmode')).toEqual([])
let $ = await next.render$('/draftmode/async', {}) let $ = await next.render$('/draftmode/async', {})
if (isNextDev) { if (isNextDev) {
expect($('#layout').text()).toBe('at runtime') expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime') expect($('#page').text()).toBe('at runtime')
expect($('#draft-mode').text()).toBe('false') expect($('#draft-mode').text()).toBe('false')
expect(getLines('Route "/draftmode')).toEqual([]) expect(getLines('In route /draftmode')).toEqual([])
} else { } else {
expect($('#layout').text()).toBe('at buildtime') expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at buildtime') expect($('#page').text()).toBe('at buildtime')
expect($('#draft-mode').text()).toBe('false') expect($('#draft-mode').text()).toBe('false')
expect(getLines('Route "/draftmode')).toEqual([]) expect(getLines('In route /draftmode')).toEqual([])
} }
$ = await next.render$('/draftmode/sync', {}) $ = await next.render$('/draftmode/sync', {})
...@@ -44,16 +44,16 @@ describe('dynamic-io', () => { ...@@ -44,16 +44,16 @@ describe('dynamic-io', () => {
expect($('#layout').text()).toBe('at runtime') expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime') expect($('#page').text()).toBe('at runtime')
expect($('#draft-mode').text()).toBe('false') expect($('#draft-mode').text()).toBe('false')
expect(getLines('Route "/draftmode')).toEqual([ expect(getLines('In route /draftmode')).toEqual([
expect.stringContaining('`draftMode().isEnabled`'), expect.stringContaining(
// TODO need to figure out why deduping isn't working here 'a `draftMode()` property was accessed directly with `draftMode().isEnabled`.'
expect.stringContaining('`draftMode().isEnabled`'), ),
]) ])
} else { } else {
expect($('#layout').text()).toBe('at buildtime') expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at buildtime') expect($('#page').text()).toBe('at buildtime')
expect($('#draft-mode').text()).toBe('false') expect($('#draft-mode').text()).toBe('false')
expect(getLines('Route "/draftmode')).toEqual([]) expect(getLines('In route /draftmode')).toEqual([])
} }
}) })
}) })
...@@ -83,7 +83,7 @@ describe('dynamic-io', () => { ...@@ -83,7 +83,7 @@ describe('dynamic-io', () => {
let $ = await next.render$('/headers/exercise/async', {}) let $ = await next.render$('/headers/exercise/async', {})
let cookieWarnings = next.cliOutput let cookieWarnings = next.cliOutput
.split('\n') .split('\n')
.filter((l) => l.includes('Route "/headers/exercise')) .filter((l) => l.includes('In route /headers/exercise'))
expect(cookieWarnings).toHaveLength(0) expect(cookieWarnings).toHaveLength(0)
...@@ -162,7 +162,7 @@ describe('dynamic-io', () => { ...@@ -162,7 +162,7 @@ describe('dynamic-io', () => {
let $ = await next.render$('/headers/exercise/sync', {}) let $ = await next.render$('/headers/exercise/sync', {})
let headerWarnings = next.cliOutput let headerWarnings = next.cliOutput
.split('\n') .split('\n')
.filter((l) => l.includes('Route "/headers/exercise')) .filter((l) => l.includes('In route /headers/exercise'))
if (!isNextDev) { if (!isNextDev) {
expect(headerWarnings).toHaveLength(0) expect(headerWarnings).toHaveLength(0)
...@@ -176,9 +176,9 @@ describe('dynamic-io', () => { ...@@ -176,9 +176,9 @@ describe('dynamic-io', () => {
expect($('#append-value-x-sentinel').text()).toContain('hello') expect($('#append-value-x-sentinel').text()).toContain('hello')
if (isNextDev) { if (isNextDev) {
expect(headerWarnings[i++]).toContain( expect(headerWarnings[i++]).toContain(
"`headers().append('x-sentinel', ...)`" "headers().append('x-sentinel', ...)"
) )
expect(headerWarnings[i++]).toContain("`headers().get('x-sentinel')`") expect(headerWarnings[i++]).toContain("headers().get('x-sentinel')")
} }
// headers().delete('...') // headers().delete('...')
...@@ -187,23 +187,23 @@ describe('dynamic-io', () => { ...@@ -187,23 +187,23 @@ describe('dynamic-io', () => {
) )
expect($('#delete-value-x-sentinel').text()).toContain('hello') expect($('#delete-value-x-sentinel').text()).toContain('hello')
if (isNextDev) { if (isNextDev) {
expect(headerWarnings[i++]).toContain("`headers().delete('x-sentinel')`") expect(headerWarnings[i++]).toContain("headers().delete('x-sentinel')")
expect(headerWarnings[i++]).toContain("`headers().get('x-sentinel')`") expect(headerWarnings[i++]).toContain("headers().get('x-sentinel')")
} }
// headers().get('...') // headers().get('...')
expect($('#get-x-sentinel').text()).toContain('hello') expect($('#get-x-sentinel').text()).toContain('hello')
if (isNextDev) { if (isNextDev) {
expect(headerWarnings[i++]).toContain("`headers().get('x-sentinel')`") expect(headerWarnings[i++]).toContain("headers().get('x-sentinel')")
} }
// cookies().has('...') // cookies().has('...')
expect($('#has-x-sentinel').text()).toContain('true') expect($('#has-x-sentinel').text()).toContain('true')
expect($('#has-x-sentinel-foobar').text()).toContain('false') expect($('#has-x-sentinel-foobar').text()).toContain('false')
if (isNextDev) { if (isNextDev) {
expect(headerWarnings[i++]).toContain("`headers().has('x-sentinel')`") expect(headerWarnings[i++]).toContain("headers().has('x-sentinel')")
expect(headerWarnings[i++]).toContain( expect(headerWarnings[i++]).toContain(
"`headers().has('x-sentinel-foobar')`" "headers().has('x-sentinel-foobar')"
) )
} }
...@@ -213,10 +213,8 @@ describe('dynamic-io', () => { ...@@ -213,10 +213,8 @@ describe('dynamic-io', () => {
) )
expect($('#set-value-x-sentinel').text()).toContain('hello') expect($('#set-value-x-sentinel').text()).toContain('hello')
if (isNextDev) { if (isNextDev) {
expect(headerWarnings[i++]).toContain( expect(headerWarnings[i++]).toContain("headers().set('x-sentinel', ...)")
"`headers().set('x-sentinel', ...)`" expect(headerWarnings[i++]).toContain("headers().get('x-sentinel')")
)
expect(headerWarnings[i++]).toContain("`headers().get('x-sentinel')`")
} }
// headers().getSetCookie() // headers().getSetCookie()
...@@ -224,7 +222,7 @@ describe('dynamic-io', () => { ...@@ -224,7 +222,7 @@ describe('dynamic-io', () => {
// not response headers and is not mutable. // not response headers and is not mutable.
expect($('#get-set-cookie').text()).toEqual('[]') expect($('#get-set-cookie').text()).toEqual('[]')
if (isNextDev) { if (isNextDev) {
expect(headerWarnings[i++]).toContain('`headers().getSetCookie()`') expect(headerWarnings[i++]).toContain('headers().getSetCookie()')
} }
// headers().forEach(...) // headers().forEach(...)
...@@ -234,7 +232,7 @@ describe('dynamic-io', () => { ...@@ -234,7 +232,7 @@ describe('dynamic-io', () => {
) )
expect($('#for-each-x-sentinel-rand').length).toBe(1) expect($('#for-each-x-sentinel-rand').length).toBe(1)
if (isNextDev) { if (isNextDev) {
expect(headerWarnings[i++]).toContain('`headers().forEach(...)`') expect(headerWarnings[i++]).toContain('headers().forEach(...)')
} }
// headers().keys(...) // headers().keys(...)
...@@ -242,7 +240,7 @@ describe('dynamic-io', () => { ...@@ -242,7 +240,7 @@ describe('dynamic-io', () => {
expect($('#keys-x-sentinel-path').text()).toContain('x-sentinel-path') expect($('#keys-x-sentinel-path').text()).toContain('x-sentinel-path')
expect($('#keys-x-sentinel-rand').text()).toContain('x-sentinel-rand') expect($('#keys-x-sentinel-rand').text()).toContain('x-sentinel-rand')
if (isNextDev) { if (isNextDev) {
expect(headerWarnings[i++]).toContain('`headers().keys()`') expect(headerWarnings[i++]).toContain('headers().keys()')
} }
// headers().values(...) // headers().values(...)
...@@ -252,7 +250,7 @@ describe('dynamic-io', () => { ...@@ -252,7 +250,7 @@ describe('dynamic-io', () => {
) )
expect($('[data-class="values"]').length).toBe(3) expect($('[data-class="values"]').length).toBe(3)
if (isNextDev) { if (isNextDev) {
expect(headerWarnings[i++]).toContain('`headers().values()`') expect(headerWarnings[i++]).toContain('headers().values()')
} }
// headers().entries(...) // headers().entries(...)
...@@ -262,7 +260,7 @@ describe('dynamic-io', () => { ...@@ -262,7 +260,7 @@ describe('dynamic-io', () => {
) )
expect($('#entries-x-sentinel-rand').length).toBe(1) expect($('#entries-x-sentinel-rand').length).toBe(1)
if (isNextDev) { if (isNextDev) {
expect(headerWarnings[i++]).toContain('`headers().entries()`') expect(headerWarnings[i++]).toContain('headers().entries()')
} }
// for...of headers() // for...of headers()
...@@ -272,9 +270,7 @@ describe('dynamic-io', () => { ...@@ -272,9 +270,7 @@ describe('dynamic-io', () => {
) )
expect($('#for-of-x-sentinel-rand').length).toBe(1) expect($('#for-of-x-sentinel-rand').length).toBe(1)
if (isNextDev) { if (isNextDev) {
expect(headerWarnings[i++]).toContain( expect(headerWarnings[i++]).toContain('headers were iterated over.')
'`...headers()` or similar iteration'
)
} }
// ...headers() // ...headers()
...@@ -284,9 +280,7 @@ describe('dynamic-io', () => { ...@@ -284,9 +280,7 @@ describe('dynamic-io', () => {
) )
expect($('#spread-x-sentinel-rand').length).toBe(1) expect($('#spread-x-sentinel-rand').length).toBe(1)
if (isNextDev) { if (isNextDev) {
expect(headerWarnings[i++]).toContain( expect(headerWarnings[i++]).toContain('headers were iterated over.')
'`...headers()` or similar iteration'
)
} }
if (isNextDev) { if (isNextDev) {
......
...@@ -13,7 +13,7 @@ describe('dynamic-io', () => { ...@@ -13,7 +13,7 @@ describe('dynamic-io', () => {
} }
it('should not have route specific errors', async () => { it('should not have route specific errors', async () => {
expect(next.cliOutput).not.toMatch('Error: Route "/') expect(next.cliOutput).not.toMatch('Error: Route /')
expect(next.cliOutput).not.toMatch('Error occurred prerendering page') expect(next.cliOutput).not.toMatch('Error occurred prerendering page')
}) })
......
...@@ -13,7 +13,7 @@ describe('dynamic-io', () => { ...@@ -13,7 +13,7 @@ describe('dynamic-io', () => {
} }
it('should not have route specific errors', async () => { it('should not have route specific errors', async () => {
expect(next.cliOutput).not.toMatch('Error: Route "/') expect(next.cliOutput).not.toMatch('Error: Route /')
expect(next.cliOutput).not.toMatch('Error occurred prerendering page') expect(next.cliOutput).not.toMatch('Error occurred prerendering page')
}) })
......
...@@ -247,7 +247,7 @@ describe('dynamic-io', () => { ...@@ -247,7 +247,7 @@ describe('dynamic-io', () => {
}) })
it('should prerender GET route handlers when accessing awaited params', async () => { it('should prerender GET route handlers when accessing awaited params', async () => {
expect(getLines('Route "/routes/[dyn]')).toEqual([]) expect(getLines('In route /routes/[dyn]')).toEqual([])
let str = await next.render('/routes/1/async', {}) let str = await next.render('/routes/1/async', {})
let json = JSON.parse(str) let json = JSON.parse(str)
...@@ -255,12 +255,12 @@ describe('dynamic-io', () => { ...@@ -255,12 +255,12 @@ describe('dynamic-io', () => {
expect(json.value).toEqual('at runtime') expect(json.value).toEqual('at runtime')
expect(json.type).toBe('dynamic params') expect(json.type).toBe('dynamic params')
expect(json.param).toBe('1') expect(json.param).toBe('1')
expect(getLines('Route "/routes/[dyn]')).toEqual([]) expect(getLines('In route /routes/[dyn]')).toEqual([])
} else { } else {
expect(json.value).toEqual('at buildtime') expect(json.value).toEqual('at buildtime')
expect(json.type).toBe('dynamic params') expect(json.type).toBe('dynamic params')
expect(json.param).toBe('1') expect(json.param).toBe('1')
expect(getLines('Route "/routes/[dyn]')).toEqual([]) expect(getLines('In route /routes/[dyn]')).toEqual([])
} }
str = await next.render('/routes/2/async', {}) str = await next.render('/routes/2/async', {})
...@@ -270,17 +270,17 @@ describe('dynamic-io', () => { ...@@ -270,17 +270,17 @@ describe('dynamic-io', () => {
expect(json.value).toEqual('at runtime') expect(json.value).toEqual('at runtime')
expect(json.type).toBe('dynamic params') expect(json.type).toBe('dynamic params')
expect(json.param).toBe('2') expect(json.param).toBe('2')
expect(getLines('Route "/routes/[dyn]')).toEqual([]) expect(getLines('In route /routes/[dyn]')).toEqual([])
} else { } else {
expect(json.value).toEqual('at runtime') expect(json.value).toEqual('at runtime')
expect(json.type).toBe('dynamic params') expect(json.type).toBe('dynamic params')
expect(json.param).toBe('2') expect(json.param).toBe('2')
expect(getLines('Route "/routes/[dyn]')).toEqual([]) expect(getLines('In route /routes/[dyn]')).toEqual([])
} }
}) })
it('should prerender GET route handlers when accessing params without awaiting first', async () => { it('should prerender GET route handlers when accessing params without awaiting first', async () => {
expect(getLines('Route "/routes/[dyn]')).toEqual([]) expect(getLines('In route /routes/[dyn]')).toEqual([])
let str = await next.render('/routes/1/sync', {}) let str = await next.render('/routes/1/sync', {})
let json = JSON.parse(str) let json = JSON.parse(str)
...@@ -288,14 +288,16 @@ describe('dynamic-io', () => { ...@@ -288,14 +288,16 @@ describe('dynamic-io', () => {
expect(json.value).toEqual('at runtime') expect(json.value).toEqual('at runtime')
expect(json.type).toBe('dynamic params') expect(json.type).toBe('dynamic params')
expect(json.param).toBe('1') expect(json.param).toBe('1')
expect(getLines('Route "/routes/[dyn]')).toEqual([ expect(getLines('In route /routes/[dyn]')).toEqual([
expect.stringContaining('`params.dyn`.'), expect.stringContaining(
'a param property was accessed directly with `params.dyn`.'
),
]) ])
} else { } else {
expect(json.value).toEqual('at buildtime') expect(json.value).toEqual('at buildtime')
expect(json.type).toBe('dynamic params') expect(json.type).toBe('dynamic params')
expect(json.param).toBe('1') expect(json.param).toBe('1')
expect(getLines('Route "/routes/[dyn]')).toEqual([]) expect(getLines('In route /routes/[dyn]')).toEqual([])
} }
str = await next.render('/routes/2/sync', {}) str = await next.render('/routes/2/sync', {})
...@@ -305,14 +307,16 @@ describe('dynamic-io', () => { ...@@ -305,14 +307,16 @@ describe('dynamic-io', () => {
expect(json.value).toEqual('at runtime') expect(json.value).toEqual('at runtime')
expect(json.type).toBe('dynamic params') expect(json.type).toBe('dynamic params')
expect(json.param).toBe('2') expect(json.param).toBe('2')
expect(getLines('Route "/routes/[dyn]')).toEqual([ expect(getLines('In route /routes/[dyn]')).toEqual([
expect.stringContaining('`params.dyn`.'), expect.stringContaining(
'a param property was accessed directly with `params.dyn`.'
),
]) ])
} else { } else {
expect(json.value).toEqual('at runtime') expect(json.value).toEqual('at runtime')
expect(json.type).toBe('dynamic params') expect(json.type).toBe('dynamic params')
expect(json.param).toBe('2') expect(json.param).toBe('2')
expect(getLines('Route "/routes/[dyn]')).toEqual([]) expect(getLines('In route /routes/[dyn]')).toEqual([])
} }
}) })
}) })
...@@ -16,7 +16,7 @@ describe('dynamic-io', () => { ...@@ -16,7 +16,7 @@ describe('dynamic-io', () => {
const itSkipTurbopack = isTurbopack ? it.skip : it const itSkipTurbopack = isTurbopack ? it.skip : it
it('should not have route specific errors', async () => { it('should not have route specific errors', async () => {
expect(next.cliOutput).not.toMatch('Error: Route "/') expect(next.cliOutput).not.toMatch('Error: Route /')
expect(next.cliOutput).not.toMatch('Error occurred prerendering page') expect(next.cliOutput).not.toMatch('Error occurred prerendering page')
}) })
......
...@@ -13,7 +13,7 @@ describe('dynamic-io', () => { ...@@ -13,7 +13,7 @@ describe('dynamic-io', () => {
} }
it('should not have route specific errors', async () => { it('should not have route specific errors', async () => {
expect(next.cliOutput).not.toMatch('Error: Route "/') expect(next.cliOutput).not.toMatch('Error: Route /')
expect(next.cliOutput).not.toMatch('Error occurred prerendering page') expect(next.cliOutput).not.toMatch('Error occurred prerendering page')
}) })
......
...@@ -59,10 +59,7 @@ describe('ppr', () => { ...@@ -59,10 +59,7 @@ describe('ppr', () => {
if (isNextDev) { if (isNextDev) {
it('should have the dynamic part', async () => { it('should have the dynamic part', async () => {
let $ = await next.render$(pathname) let $ = await next.render$(pathname)
// asserting this flushes in a single pass in dev is not reliable let dynamic = $('#container > #dynamic > #state')
// so we just assert that the nodes are somewhere in the document
// even if they aren't in position
let dynamic = $('#dynamic > #state')
expect(dynamic.length).toBe(1) expect(dynamic.length).toBe(1)
expect(dynamic.text()).toBe('Not Signed In') expect(dynamic.text()).toBe('Not Signed In')
...@@ -76,7 +73,7 @@ describe('ppr', () => { ...@@ -76,7 +73,7 @@ describe('ppr', () => {
}, },
} }
) )
dynamic = $('#dynamic > #state') dynamic = $('#container > #dynamic > #state')
expect(dynamic.length).toBe(1) expect(dynamic.length).toBe(1)
expect(dynamic.text()).toBe('Signed In') expect(dynamic.text()).toBe('Signed In')
}) })
......
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