Commit f22f75d4 authored by Janka Uryga's avatar Janka Uryga

[Instant] generateSamples

parent 5903c030
...@@ -1116,5 +1116,8 @@ ...@@ -1116,5 +1116,8 @@
"1115": "Route \"%s\" accessed cookie \"%s\" which is not defined in the \\`samples\\` of \\`unstable_instant\\`. Add it to the sample's \\`cookies\\` array, or \\`{ name: \"%s\", value: null }\\` if it should be absent.", "1115": "Route \"%s\" accessed cookie \"%s\" which is not defined in the \\`samples\\` of \\`unstable_instant\\`. Add it to the sample's \\`cookies\\` array, or \\`{ name: \"%s\", value: null }\\` if it should be absent.",
"1116": "Route \"%s\" accessed header \"%s\" which is not defined in the \\`samples\\` of \\`unstable_instant\\`. Add it to the sample's \\`headers\\` array, or \\`[\"%s\", null]\\` if it should be absent.", "1116": "Route \"%s\" accessed header \"%s\" which is not defined in the \\`samples\\` of \\`unstable_instant\\`. Add it to the sample's \\`headers\\` array, or \\`[\"%s\", null]\\` if it should be absent.",
"1117": "Instant validation boundaries should never appear in browser bundles.", "1117": "Instant validation boundaries should never appear in browser bundles.",
"1118": "An error occurred while attempting to validate instant UI. This error may be preventing the validation from completing." "1118": "An error occurred while attempting to validate instant UI. This error may be preventing the validation from completing.",
"1119": "This function is a placeholder that should not be called. Functions cannot be statically extracted.",
"1120": "Route \"%s\" expected \\`unstable_instant.generateSamples\\` to resolve to a non-empty array of valid samples.",
"1121": "Route \"%s\" encountered an error while executing \\`unstable_instant.generateSamples\\`."
} }
import type { import type {
ArrowFunctionExpression,
ArrayExpression, ArrayExpression,
BooleanLiteral, BooleanLiteral,
ExportDeclaration, ExportDeclaration,
FunctionExpression,
Identifier, Identifier,
KeyValueProperty, KeyValueProperty,
Module, Module,
...@@ -48,6 +50,16 @@ function isArrayExpression(node: Node): node is ArrayExpression { ...@@ -48,6 +50,16 @@ function isArrayExpression(node: Node): node is ArrayExpression {
return node.type === 'ArrayExpression' return node.type === 'ArrayExpression'
} }
function isFunctionExpression(node: Node): node is FunctionExpression {
return node.type === 'FunctionExpression'
}
function isArrowFunctionExpression(
node: Node
): node is ArrowFunctionExpression {
return node.type === 'ArrowFunctionExpression'
}
function isObjectExpression(node: Node): node is ObjectExpression { function isObjectExpression(node: Node): node is ObjectExpression {
return node.type === 'ObjectExpression' return node.type === 'ObjectExpression'
} }
...@@ -142,6 +154,16 @@ function extractValue(node: Node, path?: string[]): ExtractValueResult { ...@@ -142,6 +154,16 @@ function extractValue(node: Node, path?: string[]): ExtractValueResult {
} }
} }
return { value: arr } return { value: arr }
} else if (isFunctionExpression(node) || isArrowFunctionExpression(node)) {
// TODO(instant-validation-build): `unstable_instant.generateSamples` needs this, but this feels really hacky.
// We should figure out how to factor this differently
return {
value: () => {
throw new Error(
'This function is a placeholder that should not be called. Functions cannot be statically extracted.'
)
},
}
} else if (isObjectExpression(node)) { } else if (isObjectExpression(node)) {
// e.g. { a: 1, b: 2 } // e.g. { a: 1, b: 2 }
const obj: any = {} const obj: any = {}
......
...@@ -8,7 +8,7 @@ const CookieSchema = z ...@@ -8,7 +8,7 @@ const CookieSchema = z
}) })
.strict() .strict()
const RuntimeSampleSchema = z const InstantSampleSchema = z
.object({ .object({
cookies: z.array(CookieSchema).optional(), cookies: z.array(CookieSchema).optional(),
headers: z.array(z.tuple([z.string(), z.string().or(z.null())])).optional(), headers: z.array(z.tuple([z.string(), z.string().or(z.null())])).optional(),
...@@ -19,10 +19,18 @@ const RuntimeSampleSchema = z ...@@ -19,10 +19,18 @@ const RuntimeSampleSchema = z
}) })
.strict() .strict()
export const InstantSamplesSchema = z.array(InstantSampleSchema).min(1)
const InstantGenerateSamplesSchema = z
.function()
.args()
.returns(z.promise(InstantSamplesSchema))
const InstantConfigStaticSchema = z const InstantConfigStaticSchema = z
.object({ .object({
prefetch: z.literal('static'), prefetch: z.literal('static'),
samples: z.array(RuntimeSampleSchema).min(1).optional(), samples: InstantSamplesSchema.optional(),
generateSamples: InstantGenerateSamplesSchema.optional(),
from: z.array(z.string()).optional(), from: z.array(z.string()).optional(),
unstable_disableValidation: z.literal(true).optional(), unstable_disableValidation: z.literal(true).optional(),
unstable_disableDevValidation: z.literal(true).optional(), unstable_disableDevValidation: z.literal(true).optional(),
...@@ -33,7 +41,8 @@ const InstantConfigStaticSchema = z ...@@ -33,7 +41,8 @@ const InstantConfigStaticSchema = z
const InstantConfigRuntimeSchema = z const InstantConfigRuntimeSchema = z
.object({ .object({
prefetch: z.literal('runtime'), prefetch: z.literal('runtime'),
samples: z.array(RuntimeSampleSchema).min(1), samples: InstantSamplesSchema.optional(),
generateSamples: InstantGenerateSamplesSchema.optional(),
from: z.array(z.string()).optional(), from: z.array(z.string()).optional(),
unstable_disableValidation: z.literal(true).optional(), unstable_disableValidation: z.literal(true).optional(),
unstable_disableDevValidation: z.literal(true).optional(), unstable_disableDevValidation: z.literal(true).optional(),
...@@ -41,14 +50,39 @@ const InstantConfigRuntimeSchema = z ...@@ -41,14 +50,39 @@ const InstantConfigRuntimeSchema = z
}) })
.strict() .strict()
const InstantConfigSchema = z.union([ const InstantConfigObjectSchema = z.discriminatedUnion('prefetch', [
z.discriminatedUnion('prefetch', [
InstantConfigStaticSchema, InstantConfigStaticSchema,
InstantConfigRuntimeSchema, InstantConfigRuntimeSchema,
]),
z.literal(false),
]) ])
const InstantConfigSchema = z
.union([InstantConfigObjectSchema, z.literal(false)])
.superRefine((value, ctx) => {
if (value === false) {
return
}
if (value.samples && value.generateSamples) {
ctx.addIssue({
code: 'custom',
message:
'Instant config cannot provide both `samples` and `generateSamples`.',
path: ['generateSamples'],
})
}
if (
value.prefetch === 'runtime' &&
!value.samples &&
!value.generateSamples
) {
ctx.addIssue({
code: 'custom',
message:
'Instant config with `prefetch: "runtime"` must define `samples` or `generateSamples`.',
path: ['samples'],
})
}
}) as z.ZodType<Instant | false>
export type Instant = InstantConfigStatic | InstantConfigRuntime | false export type Instant = InstantConfigStatic | InstantConfigRuntime | false
export type InstantConfigForTypeCheckInternal = __GenericInstantConfig | Instant export type InstantConfigForTypeCheckInternal = __GenericInstantConfig | Instant
...@@ -61,29 +95,47 @@ export type InstantConfigForTypeCheckInternal = __GenericInstantConfig | Instant ...@@ -61,29 +95,47 @@ export type InstantConfigForTypeCheckInternal = __GenericInstantConfig | Instant
interface __GenericInstantConfig { interface __GenericInstantConfig {
prefetch: string prefetch: string
samples?: Array<WideInstantSample> samples?: Array<WideInstantSample>
generateSamples?: () => Promise<Array<WideInstantSample>>
from?: string[] from?: string[]
unstable_disableValidation?: boolean unstable_disableValidation?: boolean
unstable_disableDevValidation?: boolean unstable_disableDevValidation?: boolean
unstable_disableBuildValidation?: boolean unstable_disableBuildValidation?: boolean
} }
interface InstantConfigStatic { type InstantSamplesGenerator = () => Promise<Array<InstantSample>>
prefetch: 'static'
samples?: Array<InstantSample> interface InstantConfigShared {
from?: string[] from?: string[]
unstable_disableValidation?: true unstable_disableValidation?: true
unstable_disableDevValidation?: true unstable_disableDevValidation?: true
unstable_disableBuildValidation?: true unstable_disableBuildValidation?: true
} }
interface InstantConfigRuntime { type InstantConfigStatic = InstantConfigShared & {
prefetch: 'static'
} & (
| {
samples?: Array<InstantSample>
generateSamples?: never
}
| {
samples?: never
generateSamples: InstantSamplesGenerator
}
)
type InstantConfigRuntime = InstantConfigShared & {
prefetch: 'runtime' prefetch: 'runtime'
} & (
| {
samples: Array<InstantSample> samples: Array<InstantSample>
from?: string[] generateSamples?: never
unstable_disableValidation?: true }
unstable_disableDevValidation?: true | {
unstable_disableBuildValidation?: true samples?: never
} generateSamples: InstantSamplesGenerator
}
)
type WideInstantSample = { type WideInstantSample = {
cookies?: InstantSample['cookies'] cookies?: InstantSample['cookies']
......
...@@ -5183,7 +5183,8 @@ async function validateInstantConfigsInBuild( ...@@ -5183,7 +5183,8 @@ async function validateInstantConfigsInBuild(
} }
/** /**
* Runs instant validation at build time using the `samples` from `unstable_instant`. * Runs instant validation at build time using the samples declared (static or generated)
* in `unstable_instant`.
* *
* For each sample, this creates a staged RSC render with a synthetic `RequestStore` * For each sample, this creates a staged RSC render with a synthetic `RequestStore`
* populated from sample data, then feeds the accumulated chunks to * populated from sample data, then feeds the accumulated chunks to
...@@ -5200,7 +5201,23 @@ async function validateInstantConfigsInBuildImpl( ...@@ -5200,7 +5201,23 @@ async function validateInstantConfigsInBuildImpl(
const route = outerWorkStore.route const route = outerWorkStore.route
const loaderTree = ctx.componentMod.routeModule.userland.loaderTree const loaderTree = ctx.componentMod.routeModule.userland.loaderTree
let samples = await resolveInstantConfigSamplesForPage(loaderTree) let samples: InstantSample[] | null
try {
samples = await resolveInstantConfigSamplesForPage(loaderTree, route)
} catch (err) {
if (isInstantValidationError(err)) {
console.error(err)
const cause = (err as Error & { cause?: unknown }).cause
if (cause) {
console.error(cause)
}
console.error(
`Build-time instant validation failed for route "${route}".`
)
return false
}
throw err
}
if (!samples || samples.length === 0) { if (!samples || samples.length === 0) {
// No samples defined; use a single empty sample to still run validation // No samples defined; use a single empty sample to still run validation
samples = [{}] samples = [{}]
......
import { getLayoutOrPageModule } from '../../lib/app-dir-module' import { getLayoutOrPageModule } from '../../lib/app-dir-module'
import type { LoaderTree } from '../../lib/app-dir-module' import type { LoaderTree } from '../../lib/app-dir-module'
import { parseLoaderTree } from '../../../shared/lib/router/utils/parse-loader-tree' import { parseLoaderTree } from '../../../shared/lib/router/utils/parse-loader-tree'
import type { import {
AppSegmentConfig, InstantSamplesSchema,
InstantSample, type AppSegmentConfig,
type InstantSample,
} from '../../../build/segment-config/app/app-segment-config' } from '../../../build/segment-config/app/app-segment-config'
import { import {
workAsyncStorage, workAsyncStorage,
type WorkStore, type WorkStore,
} from '../work-async-storage.external' } from '../work-async-storage.external'
import { InstantValidationError } from './instant-validation-error'
export async function anySegmentHasRuntimePrefetchEnabled( export async function anySegmentHasRuntimePrefetchEnabled(
tree: LoaderTree tree: LoaderTree
...@@ -149,7 +151,8 @@ export const findSegmentsWithInstantConfig = cacheScopedToWorkStore( ...@@ -149,7 +151,8 @@ export const findSegmentsWithInstantConfig = cacheScopedToWorkStore(
) )
export const resolveInstantConfigSamplesForPage = async ( export const resolveInstantConfigSamplesForPage = async (
tree: LoaderTree tree: LoaderTree,
route: string
): Promise<InstantSample[] | null> => { ): Promise<InstantSample[] | null> => {
const { mod: layoutOrPageMod } = await getLayoutOrPageModule(tree) const { mod: layoutOrPageMod } = await getLayoutOrPageModule(tree)
...@@ -157,15 +160,6 @@ export const resolveInstantConfigSamplesForPage = async ( ...@@ -157,15 +160,6 @@ export const resolveInstantConfigSamplesForPage = async (
? (layoutOrPageMod as AppSegmentConfig).unstable_instant ? (layoutOrPageMod as AppSegmentConfig).unstable_instant
: undefined : undefined
let samples: InstantSample[] | null = null
if (
instantConfig !== undefined &&
typeof instantConfig === 'object' &&
instantConfig.samples
) {
samples = instantConfig.samples
}
// The samples from inner segments override samples from outer segments, // The samples from inner segments override samples from outer segments,
// i.e. a page overrides the samples from a layout. // i.e. a page overrides the samples from a layout.
// We do not perform any merging logic. // We do not perform any merging logic.
...@@ -176,13 +170,41 @@ export const resolveInstantConfigSamplesForPage = async ( ...@@ -176,13 +170,41 @@ export const resolveInstantConfigSamplesForPage = async (
continue continue
} }
const childTree = parallelRoutes[parallelRouteKey] const childTree = parallelRoutes[parallelRouteKey]
const childSamples = await resolveInstantConfigSamplesForPage(childTree) const childSamples = await resolveInstantConfigSamplesForPage(
childTree,
route
)
if (childSamples !== null) { if (childSamples !== null) {
samples = childSamples return childSamples
}
}
if (instantConfig !== undefined && typeof instantConfig === 'object') {
if (instantConfig.samples) {
return instantConfig.samples
}
if (instantConfig.generateSamples) {
let generatedSamples: unknown
try {
generatedSamples = await instantConfig.generateSamples()
} catch (err) {
throw new InstantValidationError(
`Route "${route}" encountered an error while executing \`unstable_instant.generateSamples\`.`,
{ cause: err }
)
}
const parsedSamples = InstantSamplesSchema.safeParse(generatedSamples)
if (!parsedSamples.success) {
throw new InstantValidationError(
`Route "${route}" expected \`unstable_instant.generateSamples\` to resolve to a non-empty array of valid samples.`,
{ cause: parsedSamples.error }
)
}
return parsedSamples.data
} }
} }
return samples return null
} }
/** /**
......
...@@ -212,7 +212,7 @@ export interface RenderOptsPartial { ...@@ -212,7 +212,7 @@ export interface RenderOptsPartial {
/** /**
* When true, attempt to run build-time instant validation for this prerender. * When true, attempt to run build-time instant validation for this prerender.
* Only the first prerender per page sets this, since validation uses * Only the first prerender per page sets this, since validation uses
* unstable_instant.samples and is independent of actual route params. * the samples defined in unstable_instant and is independent of actual route params.
*/ */
runInstantValidation?: boolean runInstantValidation?: boolean
} }
......
...@@ -1118,7 +1118,7 @@ export type ExportPathMap = { ...@@ -1118,7 +1118,7 @@ export type ExportPathMap = {
/** /**
* When true, run build-time instant validation for this export path. * When true, run build-time instant validation for this export path.
* Only set on the first export entry per page, since validation uses * Only set on the first export entry per page, since validation uses
* unstable_instant.samples (not actual params from generateStaticParams), * the samples defined in unstable_instant (not actual params from generateStaticParams),
* so the result is the same for all param combinations. * so the result is the same for all param combinations.
* *
* @internal * @internal
......
import type { Instant } from 'next'
export const unstable_instant: Instant = {
prefetch: 'runtime',
generateSamples: async () => [
{
params: {
slug: 'from-generate-samples',
},
},
],
}
export default function Page({ params }: { params: { slug: string } }) {
return <p>slug: {params.slug}</p>
}
import type { Instant } from 'next'
export const unstable_instant: Instant = {
prefetch: 'runtime',
generateSamples: async () => [],
}
export default function Page() {
return <p>generateSamples returned an empty array</p>
}
import type { Instant } from 'next'
import type { ReactNode } from 'react'
export const unstable_instant: Instant = {
prefetch: 'runtime',
generateSamples: async () => {
throw new Error(
'parent generateSamples should not run when a child defines its own samples'
)
},
}
export default function Layout({ children }: { children: ReactNode }) {
return <>{children}</>
}
import type { Instant } from 'next'
import { cookies } from 'next/headers'
export const unstable_instant: Instant = {
prefetch: 'runtime',
generateSamples: async () => [
{
cookies: [
{
name: 'override',
value: 'child',
},
],
},
],
}
export default async function Page() {
const cookieStore = await cookies()
return <p>cookie: {cookieStore.get('override')?.value}</p>
}
import type { Instant } from 'next'
export const unstable_instant: Instant = {
prefetch: 'runtime',
generateSamples: async () => {
throw new Error('generateSamples exploded')
},
}
export default function Page() {
return <p>generateSamples throws</p>
}
...@@ -832,6 +832,114 @@ describe('instant-validation-build', () => { ...@@ -832,6 +832,114 @@ describe('instant-validation-build', () => {
}) })
}) })
describe('generateSamples', () => {
it('uses samples returned from generateSamples', async () => {
const result = await prerender('/(default)/generate-samples/happy/[slug]')
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
it('reports a helpful error when generateSamples throws', async () => {
const result = await prerender('/(default)/generate-samples/throws')
const validationOutput = extractBuildValidationError(
result.cliOutput
).trim()
expect(validationOutput).toMatchInlineSnapshot(`
"Error: This route encountered an error while executing \`unstable_instant.generateSamples\`.
at ignore-listed frames {
digest: 'INSTANT_VALIDATION_ERROR',
[cause]: Error: generateSamples exploded
at Object.generateSamples (app/(default)/generate-samples/throws/page.tsx:6:11)
4 | prefetch: 'runtime',
5 | generateSamples: async () => {
> 6 | throw new Error('generateSamples exploded')
| ^
7 | },
8 | }
9 |
}
Error: generateSamples exploded
at Object.generateSamples (app/(default)/generate-samples/throws/page.tsx:6:11)
4 | prefetch: 'runtime',
5 | generateSamples: async () => {
> 6 | throw new Error('generateSamples exploded')
| ^
7 | },
8 | }
9 |
Build-time instant validation failed for route "/generate-samples/throws".
Stopping prerender due to instant validation errors."
`)
expect(result.exitCode).toBe(1)
})
it('reports a helpful error when generateSamples returns invalid samples', async () => {
const result = await prerender(
'/(default)/generate-samples/invalid-empty'
)
const validationOutput = extractBuildValidationError(
result.cliOutput
).trim()
expect(validationOutput).toMatchInlineSnapshot(`
"Error: This route expected \`unstable_instant.generateSamples\` to resolve to a non-empty array of valid samples.
at ignore-listed frames {
digest: 'INSTANT_VALIDATION_ERROR',
[cause]: Error [ZodError]: [
{
"code": "too_small",
"minimum": 1,
"type": "array",
"inclusive": true,
"exact": false,
"message": "Array must contain at least 1 element(s)",
"path": []
}
]
at ignore-listed frames {
issues: [ [Object] ],
addIssue: [Function (anonymous)],
addIssues: [Function (anonymous)]
}
}
Error [ZodError]: [
{
"code": "too_small",
"minimum": 1,
"type": "array",
"inclusive": true,
"exact": false,
"message": "Array must contain at least 1 element(s)",
"path": []
}
]
at ignore-listed frames {
issues: [
{
code: 'too_small',
minimum: 1,
type: 'array',
inclusive: true,
exact: false,
message: 'Array must contain at least 1 element(s)',
path: []
}
],
addIssue: [Function (anonymous)],
addIssues: [Function (anonymous)]
}
Build-time instant validation failed for route "/generate-samples/invalid-empty".
Stopping prerender due to instant validation errors."
`)
expect(result.exitCode).toBe(1)
})
it('prefers page generateSamples over the parent layout', async () => {
const result = await prerender('/(default)/generate-samples/override')
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
})
describe('generateStaticParams', () => { describe('generateStaticParams', () => {
it('valid - page with generateStaticParams and samples only runs validation once', async () => { it('valid - page with generateStaticParams and samples only runs validation once', async () => {
const result = await prerender('/(default)/gsp/[slug]') const result = await prerender('/(default)/gsp/[slug]')
......
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