Unverified Commit c6f9d9c8 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[PPF] Scaffold `unstable_ensureStatic` segment config (#98190)

Adds the necessary plumbing and validation for a `unstable_ensureStatic`
segment config, allowing `"auto" | "shell" | "prefetch" | "navigation" |
false`

Also dedupes some checks that we were doing for `instant` and
`prefetch`, because `requireStatic` needs them too:
- is not exported from a client module
- is not used without Cache Components
parent a2470dbd
......@@ -124,6 +124,9 @@ pub struct NextSegmentConfig {
#[turbo_tasks(trace_ignore)]
#[bincode(with_serde)]
pub prefetch: Option<Span>,
#[turbo_tasks(trace_ignore)]
#[bincode(with_serde)]
pub unstable_ensure_static: Option<Span>,
}
#[turbo_tasks::value_impl]
......@@ -548,36 +551,29 @@ pub async fn parse_segment_config_from_source(
.await?;
}
if let Some(span) = config.instant {
invalid_config(
source,
"instant",
span,
rcstr!(
"\"instant\" is a route segment config and can only be used when the segment \
is a Server Component module. Remove the \"use client\" directive to use \
this API."
),
None,
IssueSeverity::Error,
)
.await?;
}
if let Some(span) = config.prefetch {
invalid_config(
source,
"prefetch",
span,
rcstr!(
"\"prefetch\" is a route segment config and can only be used when the segment \
is a Server Component module. Remove the \"use client\" directive to use \
this API."
),
None,
IssueSeverity::Error,
)
.await?;
let server_only_route_configs = [
("instant", config.instant),
("prefetch", config.prefetch),
("unstable_ensureStatic", config.unstable_ensure_static),
];
for (config_name, usage) in server_only_route_configs {
if let Some(span) = usage {
invalid_config(
source,
config_name,
span,
format!(
"\"{}\" is a route segment config and can only be used when the segment \
is a Server Component module. Remove the \"use client\" directive to use \
this API.",
config_name
)
.into(),
None,
IssueSeverity::Error,
)
.await?;
}
}
}
......@@ -1006,6 +1002,9 @@ async fn parse_config_value(
"prefetch" => {
config.prefetch = Some(span);
}
"unstable_ensureStatic" => {
config.unstable_ensure_static = Some(span);
}
_ => {}
}
......
......@@ -692,30 +692,24 @@ export async function getAppPageStaticInfo({
)
}
// Prevent use client and instant in the same file.
if (directives?.has('client') && 'instant' in config) {
throw new Error(
`"instant" is a route segment config and can only be used when the segment is a Server Component module. Remove the "use client" directive from "${pageFilePath}" to use this API.`
)
}
if ('instant' in config && !nextConfig.cacheComponents) {
throw new Error(
`Route "${page}" cannot use \`export const instant = ...\` without enabling \`cacheComponents\`.`
)
}
// Prevent use client and prefetch in the same file.
if (directives?.has('client') && 'prefetch' in config) {
throw new Error(
`"prefetch" is a route segment config and can only be used when the segment is a Server Component module. Remove the "use client" directive from "${pageFilePath}" to use this API.`
)
}
for (const exportName of [
'instant',
'prefetch',
'unstable_ensureStatic',
] as const) {
if (exportName in config) {
if (directives?.has('client')) {
throw new Error(
`"${exportName}" is a route segment config and can only be used when the segment is a Server Component module. Remove the "use client" directive from "${pageFilePath}" to use this API.`
)
}
if ('prefetch' in config && !nextConfig.cacheComponents) {
throw new Error(
`Route "${page}" cannot use \`export const prefetch = ...\` without enabling \`cacheComponents\`.`
)
if (!nextConfig.cacheComponents) {
throw new Error(
`Route "${page}" cannot use \`export const ${exportName} = ...\` without enabling \`cacheComponents\`.`
)
}
}
}
// Prevent unstable_dynamicStaleTime in layouts.
......
......@@ -38,10 +38,17 @@ const InstantConfigSchema = z.union([
const PrefetchSchema = z.enum(['auto', 'partial', 'force-disabled'])
const EnsureStaticSchema = z.union([
z.enum(['auto', 'shell', 'prefetch', 'navigation']),
z.literal(false),
])
export type Instant = InstantConfig | true | false
export type Prefetch = 'auto' | 'partial' | 'force-disabled'
export type EnsureStatic = 'auto' | 'shell' | 'prefetch' | 'navigation' | false
export type InstantConfigForTypeCheckInternal = __GenericInstantConfig | Instant
// the __GenericInstantConfig type is used to avoid type widening issues with
// our choice to make exports the medium for programming a Next.js application
......@@ -137,6 +144,11 @@ const AppSegmentConfigSchema = z.object({
*/
prefetch: PrefetchSchema.optional(),
/**
* Controls which rendering phases require static output for this segment.
*/
unstable_ensureStatic: EnsureStaticSchema.optional(),
/**
* The stale time for dynamic responses in seconds.
* Controls how long the client-side router cache retains dynamic page data.
......@@ -192,6 +204,11 @@ export function parseAppSegmentConfig(
message: `Invalid prefetch value ${JSON.stringify(ctx.data)} on "${route}", must be "auto", "partial", or "force-disabled".`,
}
}
case 'unstable_ensureStatic': {
return {
message: `Invalid unstable_ensureStatic value ${JSON.stringify(ctx.data)} on "${route}", must be "auto", "shell", "prefetch", "navigation", or false.`,
}
}
case 'unstable_dynamicStaleTime': {
return {
message: `Invalid unstable_dynamicStaleTime value ${JSON.stringify(ctx.data)} on "${route}", must be a non-negative number`,
......@@ -261,6 +278,11 @@ export type AppSegmentConfig = {
*/
prefetch?: Prefetch
/**
* Controls which rendering phases require static output for this segment.
*/
unstable_ensureStatic?: EnsureStatic
/**
* The stale time for dynamic responses in seconds.
* Controls how long the client-side router cache retains dynamic page data.
......
......@@ -54,7 +54,7 @@ ${
: `import type { ResolvingMetadata, ResolvingViewport } from 'next/dist/lib/metadata/types/metadata-interface.js'`
}
import type { InstantConfigForTypeCheckInternal, Prefetch } from 'next/dist/build/segment-config/app/app-segment-config.js'
import type { InstantConfigForTypeCheckInternal, Prefetch, EnsureStatic } from 'next/dist/build/segment-config/app/app-segment-config.js'
type TEntry = typeof import('${relativePath}.js')
......@@ -73,6 +73,7 @@ checkFields<Diff<{
generateStaticParams?: Function
instant?: InstantConfigForTypeCheckInternal
prefetch?: Prefetch
unstable_ensureStatic?: EnsureStatic
unstable_dynamicStaleTime?: number
revalidate?: RevalidateRange<TEntry> | false
dynamic?: 'auto' | 'force-dynamic' | 'error' | 'force-static'
......
......@@ -1043,7 +1043,7 @@ export class AppRouteRouteModule extends RouteModule<
break
case 'error':
workStore.dynamicShouldError = true
request = new Proxy(req, requireStaticRequestHandlers)
request = new Proxy(req, ensureStaticRequestHandlers)
break
case undefined:
case 'auto':
......@@ -1361,7 +1361,7 @@ function proxyNextRequest(request: NextRequest, workStore: WorkStore) {
return new Proxy(request, nextRequestHandlers)
}
const requireStaticRequestHandlers = {
const ensureStaticRequestHandlers = {
get(
target: NextRequest & RequestSymbolTarget,
prop: string | symbol,
......@@ -1373,7 +1373,7 @@ const requireStaticRequestHandlers = {
target[nextURLSymbol] ||
(target[nextURLSymbol] = new Proxy(
target.nextUrl,
requireStaticNextUrlHandlers
ensureStaticNextUrlHandlers
))
)
case 'headers':
......@@ -1401,7 +1401,7 @@ const requireStaticRequestHandlers = {
// to probably embed the static generation logic into the class itself removing the need
// for any kind of proxying
target.clone() as NextRequest,
requireStaticRequestHandlers
ensureStaticRequestHandlers
))
)
default:
......@@ -1412,7 +1412,7 @@ const requireStaticRequestHandlers = {
// and will be ignored
}
const requireStaticNextUrlHandlers = {
const ensureStaticNextUrlHandlers = {
get(
target: NextURL & UrlSymbolTarget,
prop: string | symbol,
......@@ -1433,7 +1433,7 @@ const requireStaticNextUrlHandlers = {
return (
target[urlCloneSymbol] ||
(target[urlCloneSymbol] = () =>
new Proxy(target.clone(), requireStaticNextUrlHandlers))
new Proxy(target.clone(), ensureStaticNextUrlHandlers))
)
default:
return ReflectAdapter.get(target, prop, receiver)
......
......@@ -9,7 +9,10 @@ import {
} from '../utils'
import { NEXT_TS_ERRORS, ALLOWED_EXPORTS } from '../constant'
import type tsModule from 'typescript/lib/tsserverlibrary'
import type { AppSegmentConfig } from '../../../build/segment-config/app/app-segment-config'
import type {
AppSegmentConfig,
EnsureStatic,
} from '../../../build/segment-config/app/app-segment-config'
const API_DOCS: Record<
string,
......@@ -168,6 +171,32 @@ const API_DOCS: Record<
},
insertText: `prefetch = 'partial';`,
},
unstable_ensureStatic: {
description: `Controls which rendering phases require static output for this segment. This option is experimental and may change.`,
link: '(docs coming soon)',
type: `"auto" | "shell" | "prefetch" | "navigation" | false`,
options: {
'"auto"':
'Default. The shell, prefetch, or entire page will automatically be prerendered statically if possible.',
'"shell"': 'Force the shell for the route to be prerendered statically.',
'"prefetch"':
'Force both the shell and the prefetch (`<Link prefetch={true}>`) for the route to be prerendered statically.',
'"navigation"': 'Require the route to be fully static.',
false:
'Indicate that this segment must use the default behavior and should not have `ensureStatic = "shell" | "prefetch" | "navigation"` applied to it by another segment. Errors if another segment on the route uses `ensureStatic` with those values.',
} satisfies DocsOptionsObject<
FullAppSegmentConfig['unstable_ensureStatic']
>,
insertText: `unstable_ensureStatic = 'shell';`,
isValid: (value) => {
try {
const parsed: unknown = JSON.parse(value)
return (VALID_ENSURE_STATIC_VALUES as unknown[]).includes(parsed)
} catch {
return false
}
},
},
unstable_dynamicStaleTime: {
description: `Controls how long the client-side router cache retains dynamic page data (in seconds). Pages only — not allowed in layouts. Cannot be combined with \`instant\`.`,
link: '(docs coming soon)',
......@@ -181,6 +210,14 @@ const API_DOCS: Record<
},
}
const VALID_ENSURE_STATIC_VALUES: EnsureStatic[] = [
'auto',
'shell',
'prefetch',
'navigation',
false,
]
type FullAppSegmentConfig = Required<AppSegmentConfig>
/**
......
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