Unverified Commit 46e2114e authored by Ben Gubler's avatar Ben Gubler Committed by GitHub

feat: generate root params types (#91019)

## Summary

Generate type definitions for `next/root-params` from App Router root
layouts.

This adds a `root-params.d.ts` file under `.next/types` during build,
`next dev`, and `next typegen`, so imports from `next/root-params` get
accurate autocomplete and type checking.

## What Changed

- Collect root param metadata from layout routes in the route types
manifest
- Generate `.next/types/root-params.d.ts` for `next/root-params`
- Emit root param types in `next build/dev/typegen`
- Infer `undefined` only when a param is not present in every root
layout
- Model mixed root param shapes correctly as unions
- For example, `string | string[] | undefined` when the same param name
appears with different shapes across roots
- Remove stale `root-params.d.ts` when the feature is disabled or there
are no root params

## Why

`next/root-params` already works at runtime, but its types were not
tailored to the current app.

This change closes that gap by generating declarations from the app's
actual root layouts. Required params stay required for single-root apps,
while multi-root apps correctly expose params that may be missing or
have mixed segment shapes.

## Testing

- Added focused unit tests for root param type generation
- Added a typecheck e2e test for generated `root-params.d.ts`
parent 1d8e326d
// The actual types need to be generated. Avoid type errors for non-existent exports before that happens.
// The actual types are generated into .next/types/root-params.d.ts and wired
// via next-env.d.ts. This bare declaration avoids type errors before generation.
declare module 'next/root-params'
......@@ -221,6 +221,7 @@ import {
writeValidatorFile,
} from '../server/lib/router-utils/route-types-utils'
import { writeCacheLifeTypes } from '../server/lib/router-utils/cache-life-type-utils'
import { writeRootParamsTypes } from '../server/lib/router-utils/root-params-type-utils'
import { Lockfile } from './lockfile'
import {
buildPrefetchSegmentDataRoute,
......@@ -1420,6 +1421,12 @@ export default async function build(
Boolean(config.experimental.strictRouteTypes)
)
writeCacheLifeTypes(config.cacheLife, cacheLifeFilePath)
await writeRootParamsTypes(
routeTypesManifest,
path.join(distDir, 'types', 'root-params.d.ts'),
config
)
})
// Turbopack already handles conflicting app and page routes.
......
......@@ -31,7 +31,8 @@ function verifyAndRunTypeScript(
hasPagesDir: boolean,
appDir: string | undefined,
pagesDir: string | undefined,
debugBuildPaths: { app: string[]; pages: string[] } | undefined
debugBuildPaths: { app: string[]; pages: string[] } | undefined,
rootParams: boolean
) {
let impl: typeof import('../lib/verify-typescript-setup').verifyAndRunTypeScript
let typeCheckWorker:
......@@ -74,6 +75,7 @@ function verifyAndRunTypeScript(
appDir,
pagesDir,
debugBuildPaths,
rootParams,
})
.then((result) => {
typeCheckWorker?.end()
......@@ -142,7 +144,8 @@ export async function startTypeChecking({
!!pagesDir,
appDir,
pagesDir,
debugBuildPaths
debugBuildPaths,
!!config.experimental.rootParams || !!config.cacheComponents
).then((resolved) => {
const checkEnd = process.hrtime(typeCheckAndLintStart)
return [resolved, checkEnd] as const
......
......@@ -149,6 +149,8 @@ async function runPlaywright(
hasPagesDir: !!pagesDir,
appDir: appDir || undefined,
pagesDir: pagesDir || undefined,
rootParams:
!!nextConfig.experimental.rootParams || !!nextConfig.cacheComponents,
})
const isUsingTypeScript = !!typeScriptVersion
......
......@@ -18,6 +18,7 @@ import {
writeValidatorFile,
} from '../server/lib/router-utils/route-types-utils'
import { writeCacheLifeTypes } from '../server/lib/router-utils/cache-life-type-utils'
import { writeRootParamsTypes } from '../server/lib/router-utils/root-params-type-utils'
import { installBindings } from '../build/swc/install-bindings'
export type NextTypegenOptions = {
......@@ -54,6 +55,8 @@ const nextTypegen = async (
hasPagesDir: !!pagesDir,
appDir: appDir || undefined,
pagesDir: pagesDir || undefined,
rootParams:
!!nextConfig.experimental.rootParams || !!nextConfig.cacheComponents,
})
console.log('Generating route types...')
......@@ -112,6 +115,12 @@ const nextTypegen = async (
const cacheLifeFilePath = join(distDir, 'types', 'cache-life.d.ts')
writeCacheLifeTypes(nextConfig.cacheLife, cacheLifeFilePath)
await writeRootParamsTypes(
routeTypesManifest,
join(distDir, 'types', 'root-params.d.ts'),
nextConfig
)
console.log('✓ Types generated successfully')
}
......
......@@ -10,6 +10,7 @@ export async function writeAppTypeDeclarations({
hasAppDir,
strictRouteTypes,
typedRoutes,
rootParams,
}: {
baseDir: string
distDir: string
......@@ -18,6 +19,7 @@ export async function writeAppTypeDeclarations({
hasAppDir: boolean
strictRouteTypes: boolean
typedRoutes: boolean
rootParams: boolean
}): Promise<void> {
// Reference `next` types
const appTypeDeclarations = path.join(baseDir, 'next-env.d.ts')
......@@ -69,6 +71,14 @@ export async function writeAppTypeDeclarations({
// Use ESM import instead of triple-slash reference for better ESLint compatibility
lines.push(`import "./${routeTypesPath}";`)
if (rootParams) {
const rootParamsTypesPath = path.posix.join(
distDir.replaceAll(path.win32.sep, path.posix.sep),
'types/root-params.d.ts'
)
lines.push(`import "./${rootParamsTypesPath}";`)
}
if (strictRouteTypes) {
const cacheLifePath = path.posix.join(
distDir.replaceAll(path.win32.sep, path.posix.sep),
......
......@@ -67,6 +67,7 @@ export async function verifyAndRunTypeScript({
appDir,
pagesDir,
debugBuildPaths,
rootParams,
}: {
dir: string
distDir: string
......@@ -81,6 +82,7 @@ export async function verifyAndRunTypeScript({
appDir?: string
pagesDir?: string
debugBuildPaths?: { app?: string[]; pages?: string[] }
rootParams?: boolean
}): Promise<{ result?: TypeCheckResult; version: string | null }> {
const tsConfigFileName = tsconfigPath || 'tsconfig.json'
const resolvedTsConfigPath = path.join(dir, tsConfigFileName)
......@@ -131,6 +133,7 @@ export async function verifyAndRunTypeScript({
hasAppDir,
strictRouteTypes,
typedRoutes,
rootParams: !!rootParams,
})
return { version: null }
......@@ -214,6 +217,7 @@ export async function verifyAndRunTypeScript({
hasAppDir,
strictRouteTypes,
typedRoutes,
rootParams: !!rootParams,
})
let result
......
import fs from 'fs'
import path from 'path'
import type { RouteTypesManifest } from './route-types-utils'
import type { NextConfigComplete } from '../../config-shared'
export type RootParamValueType = 'string' | 'string[]' | 'undefined'
export type RootParamInfo = Set<RootParamValueType>
const ROOT_PARAM_VALUE_TYPES: RootParamValueType[] = [
'string',
'string[]',
'undefined',
]
/**
* Generates TypeScript type definitions for root params.
* Creates a `declare module 'next/root-params'` block with async getter functions
* for each root parameter.
*/
export function generateRootParamsTypes(
rootParams: Map<string, RootParamInfo>
): string {
const exports = Array.from(rootParams.entries())
.sort(([a], [b]) => a.localeCompare(b))
.map(
([paramName, info]) =>
` export function ${paramName}(): ${getRootParamReturnType(info)}`
)
return `// Type definitions for Next.js root params (next/root-params)
declare module 'next/root-params' {
${exports.join('\n')}
}
`
}
function getRootParamReturnType(valueTypes: RootParamInfo): string {
const orderedValueTypes = ROOT_PARAM_VALUE_TYPES.filter((valueType) =>
valueTypes.has(valueType)
)
return `Promise<${orderedValueTypes.join(' | ')}>`
}
/**
* Writes root-params type definitions to a file if the feature is enabled
* and root params were collected from layouts.
*/
export async function writeRootParamsTypes(
manifest: RouteTypesManifest,
filePath: string,
config: NextConfigComplete
) {
const rootParams = manifest.rootParams
const featureEnabled =
!!config.experimental.rootParams || !!config.cacheComponents
if (!featureEnabled) {
await fs.promises.rm(filePath, { force: true })
return
}
await fs.promises.mkdir(path.dirname(filePath), { recursive: true })
if (!rootParams.size) {
// Write an empty declaration so the import in next-env.d.ts resolves.
await fs.promises.writeFile(
filePath,
`// Type definitions for Next.js root params (next/root-params)\n// No root params detected.\nexport {}\n`
)
return
}
await fs.promises.writeFile(filePath, generateRootParamsTypes(rootParams))
}
......@@ -24,6 +24,10 @@ import {
} from '../../../shared/lib/entry-constants'
import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep'
import type { RouteInfo, SlotInfo } from '../../../build/file-classifier'
import type {
RootParamInfo,
RootParamValueType,
} from './root-params-type-utils'
// Internal route info with extracted params for the manifest
interface ManifestRouteInfo {
......@@ -48,6 +52,8 @@ export interface RouteTypesManifest {
pageApiRoutes: Set<string>
/** Direct mapping from file paths to routes for validation */
filePathToRoute: Map<string, string>
/** Root params collected from root layouts, with their possible runtime value types */
rootParams: Map<string, RootParamInfo>
}
// Convert a custom-route source string (`/blog/:slug`, `/docs/:path*`, ...)
......@@ -144,6 +150,63 @@ function resolveInterceptingRoute(route: string): string {
}
}
/**
* Collects root params from the manifest's layout routes with universality tracking.
* A root layout is the shallowest layout in each branch — no ancestor layout above it.
* A param is "universal" if it appears in ALL root layouts.
*
* Uses the already-extracted `groups` from `manifest.layoutRoutes` (via `getRouteRegex`)
* rather than re-parsing segments.
*/
function collectRootParamsFromLayouts(
layoutRoutes: RouteTypesManifest['layoutRoutes']
): Map<string, RootParamInfo> {
const routes = Object.keys(layoutRoutes)
// Find root layouts: layouts with no ancestor layout above them.
const rootLayoutRoutes = routes.filter(
// If there are no other layouts whose paths are prefixes of this layout,
// then it's a root layout.
(route) =>
!routes.some(
(other) =>
other !== route && (other === '/' || route.startsWith(other + '/'))
)
)
if (rootLayoutRoutes.length === 0) {
return new Map()
}
// The same param name can have different runtime shapes
// across roots, so track both param names and shapes.
const rootParams = new Map<string, RootParamInfo>()
for (const route of rootLayoutRoutes) {
for (const [name, group] of Object.entries(layoutRoutes[route].groups)) {
const info = rootParams.get(name) ?? new Set<RootParamValueType>()
info.add(group.repeat ? 'string[]' : 'string')
if (group.optional) {
info.add('undefined')
}
rootParams.set(name, info)
}
}
// Any param missing from a root layout can be undefined.
for (const [name, info] of rootParams) {
if (
rootLayoutRoutes.some((route) => !(name in layoutRoutes[route].groups))
) {
info.add('undefined')
}
}
return rootParams
}
/**
* Creates a route types manifest from processed route data
* (used for both build and dev)
......@@ -190,6 +253,7 @@ export async function createRouteTypesManifest({
appRouteHandlerRoutes: {},
redirectRoutes: {},
rewriteRoutes: {},
rootParams: new Map(),
appRouteHandlers: new Set(
appRouteHandlers.map(({ filePath }) => getRelativePath(filePath))
),
......@@ -350,6 +414,9 @@ export async function createRouteTypesManifest({
}
}
// Collect root params from layout routes
manifest.rootParams = collectRootParamsFromLayouts(manifest.layoutRoutes)
return manifest
}
......
......@@ -89,6 +89,7 @@ import {
writeValidatorFile,
} from './route-types-utils'
import { writeCacheLifeTypes } from './cache-life-type-utils'
import { writeRootParamsTypes } from './root-params-type-utils'
import {
addSlotIfNew,
type RouteInfo,
......@@ -164,6 +165,9 @@ async function verifyTypeScript(opts: SetupOpts) {
hasPagesDir: !!opts.pagesDir,
appDir: opts.appDir,
pagesDir: opts.pagesDir,
rootParams:
!!opts.nextConfig.experimental.rootParams ||
!!opts.nextConfig.cacheComponents,
})
if (verifyResult.version) {
......@@ -289,6 +293,7 @@ async function startWatcher(
appRouteHandlers: new Set(),
pageApiRoutes: new Set(),
filePathToRoute: new Map(),
rootParams: new Map(),
},
path.join(distTypesDir, 'routes.d.ts'),
opts.nextConfig
......@@ -1191,6 +1196,12 @@ async function startWatcher(
// Generate cache-life types if cacheLife config exists
const cacheLifeFilePath = path.join(distTypesDir, 'cache-life.d.ts')
writeCacheLifeTypes(opts.nextConfig.cacheLife, cacheLifeFilePath)
await writeRootParamsTypes(
routeTypesManifest,
path.join(distTypesDir, 'root-params.d.ts'),
opts.nextConfig
)
}
if (!resolved) {
......
// This file is NOT a React component — it only exists to validate
// the generated root-params.d.ts types via `tsc --noEmit`.
// Lines marked @ts-expect-error must produce a type error; if they
// don't, tsc itself will fail ("Unused '@ts-expect-error' directive").
import { id } from 'next/root-params'
// @ts-expect-error — nonexistent is not a root param
import { nonexistent as _nonexistent } from 'next/root-params'
async function _validate() {
// --- id: Promise<string | undefined> (only in dashboard root, not landing) ---
const _idVal: string | undefined = await id() // ok
// @ts-expect-error — id() does not return a number
const _idBad: number = await id()
}
// This file is NOT a React component — it only exists to validate
// the generated root-params.d.ts types via `tsc --noEmit`.
// Lines marked @ts-expect-error must produce a type error; if they
// don't, tsc itself will fail ("Unused '@ts-expect-error' directive").
import { lang, locale, path } from 'next/root-params'
// @ts-expect-error — nonexistent is not a root param
import { nonexistent as _nonexistent } from 'next/root-params'
async function _validate() {
// --- lang: Promise<string | undefined> ---
const _langVal: string | undefined = await lang() // ok
// @ts-expect-error — lang() does not return a number
const _langBad: number = await lang()
// --- locale: Promise<string | undefined> ---
const _localeVal: string | undefined = await locale() // ok
// @ts-expect-error — locale() does not return a number
const _localeBad: number = await locale()
// --- path: Promise<string[] | undefined> ---
const _pathVal: string[] | undefined = await path() // ok
// @ts-expect-error — path() does not return a plain string
const _pathBad: string = await path()
}
import { nextTestSetup } from 'e2e-utils'
import execa from 'execa'
import { join } from 'path'
import { retry } from 'next-test-utils'
// Each fixture has a typecheck-validation.ts that imports from 'next/root-params'
// and uses @ts-expect-error to assert correct and incorrect type assignments.
// Running `tsc --noEmit` verifies the generated root-params.d.ts is wired in
// and produces the expected types.
describe.each([{ fixture: 'simple' }, { fixture: 'multiple-roots' }])(
'app-root-param-getters - typecheck ($fixture)',
({ fixture }) => {
const { next, skipped } = nextTestSetup({
files: join(__dirname, 'fixtures', fixture),
skipDeployment: true,
})
if (skipped) {
return
}
it('should pass typecheck with generated root-params types', async () => {
await retry(async () => {
await next.readFile(`${next.distDir}/types/root-params.d.ts`)
})
await next.stop()
try {
const { stdout, stderr } = await execa('pnpm', ['tsc', '--noEmit'], {
cwd: next.testDir,
reject: false,
})
expect({ stdout, stderr }).toEqual({
stdout: '',
stderr: '',
})
} finally {
await next.start()
}
})
}
)
......@@ -40,6 +40,7 @@ describe('find config', () => {
hasAppDir: false,
strictRouteTypes: false,
typedRoutes: true,
rootParams: false,
})
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
})
......@@ -70,6 +71,7 @@ describe('find config', () => {
hasAppDir: false,
strictRouteTypes: false,
typedRoutes: true,
rootParams: false,
})
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
})
......@@ -98,6 +100,7 @@ describe('find config', () => {
hasAppDir: false,
strictRouteTypes: false,
typedRoutes: true,
rootParams: false,
})
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
})
......@@ -111,6 +114,7 @@ describe('find config', () => {
hasAppDir: true,
strictRouteTypes: false,
typedRoutes: true,
rootParams: false,
})
await expect(fs.readFile(declarationFile, 'utf8')).resolves.not.toContain(
......@@ -125,6 +129,7 @@ describe('find config', () => {
hasAppDir: true,
strictRouteTypes: false,
typedRoutes: true,
rootParams: false,
})
await expect(fs.readFile(declarationFile, 'utf8')).resolves.toContain(
......
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