Unverified Commit 85861db7 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[strict-route-types] Add `experimental.strictRouteTypes` config (#87378)

parent 77ac1cfa
......@@ -249,6 +249,7 @@ jobs:
export TURBOPACK_DEV=1
export NEXT_TEST_MODE=dev
export NEXT_TEST_REACT_VERSION="${{ matrix.react }}"
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
node run-tests.js \
--test-pattern '^(test\/(development|e2e))/.*\.test\.(js|jsx|ts|tsx)$' \
......@@ -279,6 +280,7 @@ jobs:
export IS_TURBOPACK_TEST=1
export TURBOPACK_DEV=1
export NEXT_TEST_REACT_VERSION="${{ matrix.react }}"
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
node run-tests.js \
--timings \
......@@ -309,6 +311,7 @@ jobs:
export TURBOPACK_BUILD=1
export NEXT_TEST_MODE=start
export NEXT_TEST_REACT_VERSION="${{ matrix.react }}"
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
node run-tests.js --timings -g ${{ matrix.group }} --type production
stepName: 'test-turbopack-production-react-${{ matrix.react }}-${{ matrix.group }}'
......@@ -336,6 +339,7 @@ jobs:
export IS_TURBOPACK_TEST=1
export TURBOPACK_BUILD=1
export NEXT_TEST_REACT_VERSION="${{ matrix.react }}"
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
node run-tests.js \
--timings \
......@@ -363,6 +367,7 @@ jobs:
export NEXT_EXTERNAL_TESTS_FILTERS="$(pwd)/test/rspack-dev-tests-manifest.json"
export NEXT_TEST_MODE=dev
export NEXT_TEST_REACT_VERSION="${{ matrix.react }}"
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
# rspack flags
export NEXT_RSPACK=1
......@@ -399,6 +404,7 @@ jobs:
afterBuild: |
export NEXT_EXTERNAL_TESTS_FILTERS="$(pwd)/test/rspack-dev-tests-manifest.json"
export NEXT_TEST_REACT_VERSION="${{ matrix.react }}"
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
# rspack flags
export NEXT_RSPACK=1
......@@ -435,6 +441,7 @@ jobs:
export NEXT_EXTERNAL_TESTS_FILTERS="$(pwd)/test/rspack-build-tests-manifest.json"
export NEXT_TEST_MODE=start
export NEXT_TEST_REACT_VERSION="${{ matrix.react }}"
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
# rspack flags
export NEXT_RSPACK=1
......@@ -468,6 +475,7 @@ jobs:
afterBuild: |
export NEXT_EXTERNAL_TESTS_FILTERS="$(pwd)/test/rspack-build-tests-manifest.json"
export NEXT_TEST_REACT_VERSION="${{ matrix.react }}"
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
# rspack flags
export NEXT_RSPACK=1
......@@ -562,6 +570,7 @@ jobs:
nodeVersion: ${{ matrix.node }}
afterBuild: |
export __NEXT_NODE_NATIVE_TS_LOADER_ENABLED=true
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
NEXT_TEST_MODE=dev NODE_OPTIONS=--experimental-transform-types node run-tests.js test/e2e/app-dir/next-config-ts-native-ts/**/*.test.ts test/e2e/app-dir/next-config-ts-native-mts/**/*.test.ts
stepName: 'test-next-config-ts-native-ts-dev-${{ matrix.node }}'
......@@ -583,6 +592,7 @@ jobs:
nodeVersion: ${{ matrix.node }}
afterBuild: |
export __NEXT_NODE_NATIVE_TS_LOADER_ENABLED=true
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
NEXT_TEST_MODE=start NODE_OPTIONS=--experimental-transform-types node run-tests.js test/e2e/app-dir/next-config-ts-native-ts/**/*.test.ts test/e2e/app-dir/next-config-ts-native-mts/**/*.test.ts
stepName: 'test-next-config-ts-native-ts-prod-${{ matrix.node }}'
......@@ -623,6 +633,7 @@ jobs:
uses: ./.github/workflows/build_reusable.yml
with:
afterBuild: |
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
node scripts/test-new-tests.mjs \
--flake-detection \
--mode dev \
......@@ -647,6 +658,7 @@ jobs:
uses: ./.github/workflows/build_reusable.yml
with:
afterBuild: |
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
node scripts/test-new-tests.mjs \
--flake-detection \
--mode start \
......@@ -672,6 +684,7 @@ jobs:
with:
afterBuild: |
export NEXT_E2E_TEST_TIMEOUT=240000
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
export GH_PR_NUMBER=${{ github.event.pull_request && github.event.pull_request.number || '' }}
node scripts/test-new-tests.mjs \
--mode deploy \
......@@ -733,6 +746,7 @@ jobs:
export IS_WEBPACK_TEST=1
export NEXT_TEST_MODE=dev
export NEXT_TEST_REACT_VERSION="${{ matrix.react }}"
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
node run-tests.js \
--timings \
......@@ -759,6 +773,7 @@ jobs:
afterBuild: |
export NEXT_TEST_MODE=dev
export IS_WEBPACK_TEST=1
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
node run-tests.js \
test/e2e/app-dir/app/index.test.ts \
......@@ -787,6 +802,7 @@ jobs:
nodeVersion: 20.9.0
afterBuild: |
export IS_WEBPACK_TEST=1
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
node run-tests.js \
--concurrency 4 \
test/production/pages-dir/production/test/index.test.ts \
......@@ -816,6 +832,7 @@ jobs:
afterBuild: |
export NEXT_TEST_MODE=start
export IS_WEBPACK_TEST=1
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
node run-tests.js --type production \
test/e2e/app-dir/app/index.test.ts \
......@@ -848,6 +865,7 @@ jobs:
export IS_WEBPACK_TEST=1
export NEXT_TEST_MODE=start
export NEXT_TEST_REACT_VERSION="${{ matrix.react }}"
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
node run-tests.js --timings -g ${{ matrix.group }} --type production
stepName: 'test-prod-react-${{ matrix.react }}-${{ matrix.group }}'
......@@ -887,6 +905,7 @@ jobs:
afterBuild: |
export IS_WEBPACK_TEST=1
export NEXT_TEST_REACT_VERSION="${{ matrix.react }}"
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
node run-tests.js \
--timings \
......
......@@ -1483,7 +1483,11 @@ export default async function build(
routeTypesFilePath,
config
)
await writeValidatorFile(routeTypesManifest, validatorFilePath)
await writeValidatorFile(
routeTypesManifest,
validatorFilePath,
Boolean(config.experimental.strictRouteTypes)
)
})
// Turbopack already handles conflicting app and page routes.
......
......@@ -169,7 +169,11 @@ const nextTypegen = async (
nextConfig
)
await writeValidatorFile(routeTypesManifest, validatorFilePath)
await writeValidatorFile(
routeTypesManifest,
validatorFilePath,
Boolean(nextConfig.experimental.strictRouteTypes)
)
// Generate cache-life types if cacheLife config exists
const cacheLifeFilePath = join(distDir, 'types', 'cache-life.d.ts')
......
......@@ -313,6 +313,7 @@ export const experimentalSchema = {
turbopackInferModuleSideEffects: z.boolean().optional(),
optimizePackageImports: z.array(z.string()).optional(),
optimizeServerReact: z.boolean().optional(),
strictRouteTypes: z.boolean().optional(),
clientTraceMetadata: z.array(z.string()).optional(),
serverMinification: z.boolean().optional(),
serverSourceMaps: z.boolean().optional(),
......
......@@ -387,6 +387,12 @@ export interface ExperimentalConfig {
*/
optimizeServerReact?: boolean
/**
* Type-checks props and return values of pages.
* Requires literal values for segment config (e.g. `export const dynamic = 'force-static' as const`).
*/
strictRouteTypes?: boolean
/**
* Displays an indicator when a React Transition has no other indicator rendered.
* This includes displaying an indicator on client-side navigations.
......@@ -1548,6 +1554,7 @@ export const defaultConfig = Object.freeze({
webpackBuildWorker: undefined,
webpackMemoryOptimizations: false,
optimizeServerReact: true,
strictRouteTypes: false,
viewTransition: false,
removeUncaughtErrorAndRejectionListeners: false,
validateRSCRequestHeaders: !!(
......
......@@ -1888,6 +1888,25 @@ function enforceExperimentalFeatures(
}
}
// TODO: Remove this once strictRouteTypes is the default.
if (
process.env.__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES === 'true' &&
// We do respect an explicit value in the user config.
(config.experimental.strictRouteTypes === undefined ||
(isDefaultConfig && !config.experimental.strictRouteTypes))
) {
config.experimental.strictRouteTypes = true
if (configuredExperimentalFeatures) {
addConfiguredExperimentalFeature(
configuredExperimentalFeatures,
'strictRouteTypes',
true,
'enabled by `__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES`'
)
}
}
if (
process.env.__NEXT_EXPERIMENTAL_TRANSITION_INDICATOR === 'true' &&
// We do respect an explicit value in the user config.
......
......@@ -10,6 +10,8 @@ import {
generateRouteTypesFile,
generateLinkTypesFile,
generateValidatorFile,
generateValidatorFileStrict,
generateRouteTypesFileStrict,
} from './typegen'
import { tryToParsePath } from '../../../lib/try-to-parse-path'
import {
......@@ -361,7 +363,12 @@ export async function writeRouteTypesManifest(
}
// Write the main routes.d.ts file
await fs.promises.writeFile(filePath, generateRouteTypesFile(manifest))
await fs.promises.writeFile(
filePath,
config.experimental.strictRouteTypes
? generateRouteTypesFileStrict(manifest)
: generateRouteTypesFile(manifest)
)
// Write the link.d.ts file if typedRoutes is enabled
if (config.typedRoutes === true) {
......@@ -372,7 +379,8 @@ export async function writeRouteTypesManifest(
export async function writeValidatorFile(
manifest: RouteTypesManifest,
filePath: string
filePath: string,
strict: boolean
) {
const dirname = path.dirname(filePath)
......@@ -380,5 +388,10 @@ export async function writeValidatorFile(
await fs.promises.mkdir(dirname, { recursive: true })
}
await fs.promises.writeFile(filePath, generateValidatorFile(manifest))
await fs.promises.writeFile(
filePath,
strict
? generateValidatorFileStrict(manifest)
: generateValidatorFile(manifest)
)
}
......@@ -1179,7 +1179,11 @@ async function startWatcher(
routeTypesFilePath,
opts.nextConfig
)
await writeValidatorFile(routeTypesManifest, validatorFilePath)
await writeValidatorFile(
routeTypesManifest,
validatorFilePath,
Boolean(nextConfig.experimental.strictRouteTypes)
)
// Generate cache-life types if cacheLife config exists
const cacheLifeFilePath = path.join(distTypesDir, 'cache-life.d.ts')
......
......@@ -54,6 +54,11 @@ describe('Config Experimental Warning', () => {
module.exports = (phase, { defaultConfig }) => {
return {
...defaultConfig,
experimental: {
...defaultConfig.experimental,
// We enable this by default in CI
strictRouteTypes: false,
}
}
}
`)
......@@ -66,6 +71,10 @@ describe('Config Experimental Warning', () => {
configFile.write(`
module.exports = {
images: {},
experimental: {
// We enable this by default in CI
strictRouteTypes: false,
}
}
`)
......@@ -106,6 +115,8 @@ describe('Config Experimental Warning', () => {
module.exports = (phase) => ({
experimental: {
workerThreads: false
// We enable this by default in CI
strictRouteTypes: false,
}
})
`)
......
......@@ -47,17 +47,21 @@ describe('build-output-prerender', () => {
}
} else {
if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(
`"▲ Next.js x.y.z (Turbopack, Cache Components)"`
)
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (Turbopack, Cache Components)
- Experiments (use with caution):
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)"
`)
} else if (isRspack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (Rspack, Cache Components)"
`)
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(
`"▲ Next.js x.y.z (webpack, Cache Components)"`
)
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (webpack, Cache Components)
- Experiments (use with caution):
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)"
`)
}
}
})
......@@ -156,6 +160,7 @@ describe('build-output-prerender', () => {
- Experiments (use with caution):
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)
⨯ turbopackMinify (disabled by \`--debug-prerender\`)"
`)
} else if (isRspack) {
......@@ -174,7 +179,8 @@ describe('build-output-prerender', () => {
- Experiments (use with caution):
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
⨯ serverMinification (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)"
✓ serverSourceMaps (enabled by \`--debug-prerender\`)
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)"
`)
}
}
......@@ -281,17 +287,21 @@ describe('build-output-prerender', () => {
}
} else {
if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(
`"▲ Next.js x.y.z (Turbopack)"`
)
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (Turbopack)
- Experiments (use with caution):
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)"
`)
} else if (isRspack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(
`"▲ Next.js x.y.z (Rspack)"`
)
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(
`"▲ Next.js x.y.z (webpack)"`
)
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (webpack)
- Experiments (use with caution):
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)"
`)
}
}
})
......@@ -359,6 +369,7 @@ describe('build-output-prerender', () => {
- Experiments (use with caution):
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)
⨯ turbopackMinify (disabled by \`--debug-prerender\`)"
`)
} else if (isRspack) {
......@@ -377,7 +388,8 @@ describe('build-output-prerender', () => {
- Experiments (use with caution):
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
⨯ serverMinification (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)"
✓ serverSourceMaps (enabled by \`--debug-prerender\`)
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)"
`)
}
}
......
......@@ -2,6 +2,9 @@ import fsp from 'fs/promises'
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
const strictRouteTypes =
process.env.__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES === 'true'
describe('types-gen-nounuselocal', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
......@@ -27,65 +30,128 @@ describe('types-gen-nounuselocal', () => {
expect(routeTypes).not.toContain('PagesPageConfig')
expect(routeTypes).not.toContain('ApiRouteConfig')
expect(routeTypes).toMatchInlineSnapshot(`
"// This file is generated automatically by Next.js
// Do not edit this file manually
if (strictRouteTypes) {
expect(routeTypes).toMatchInlineSnapshot(`
"// This file is generated automatically by Next.js with experimental.strictRouteTypes
// Do not edit this file manually
type AppRoutes = "/"
type PageRoutes = never
type LayoutRoutes = "/"
type RedirectRoutes = never
type RewriteRoutes = never
type Routes = AppRoutes | PageRoutes | LayoutRoutes | RedirectRoutes | RewriteRoutes
type AppRoutes = "/"
type PageRoutes = never
type LayoutRoutes = "/"
type RedirectRoutes = never
type RewriteRoutes = never
type Routes = AppRoutes | PageRoutes | LayoutRoutes | RedirectRoutes | RewriteRoutes
interface ParamMap {
"/": {}
}
interface ParamMap {
"/": {}
}
export type ParamsOf<Route extends Routes> = ParamMap[Route]
interface LayoutSlotMap {
"/": never
}
export type ParamsOf<Route extends Routes> = ParamMap[Route]
interface LayoutSlotMap {
"/": never
}
export type { AppRoutes, PageRoutes, LayoutRoutes, RedirectRoutes, RewriteRoutes, ParamMap }
declare global {
/**
* Props for Next.js App Router page components
* @example
* \`\`\`tsx
* export default function Page(props: PageProps<'/blog/[slug]'>) {
* const { slug } = await props.params
* return <div>Blog post: {slug}</div>
* }
* \`\`\`
*/
interface PageProps<AppRoute extends AppRoutes> {
params: Promise<ParamMap[AppRoute]>
searchParams: Promise<Record<string, string | string[] | undefined>>
}
/**
* Props for Next.js App Router layout components
* @example
* \`\`\`tsx
* export default function Layout(props: LayoutProps<'/dashboard'>) {
* return <div>{props.children}</div>
* }
* \`\`\`
*/
type LayoutProps<LayoutRoute extends LayoutRoutes> = {
params: Promise<ParamMap[LayoutRoute]>
children: React.ReactNode
} & {
[K in LayoutSlotMap[LayoutRoute]]: React.ReactNode
}
}
"
`)
} else {
expect(routeTypes).toMatchInlineSnapshot(`
"// This file is generated automatically by Next.js
// Do not edit this file manually
type AppRoutes = "/"
type PageRoutes = never
type LayoutRoutes = "/"
type RedirectRoutes = never
type RewriteRoutes = never
type Routes = AppRoutes | PageRoutes | LayoutRoutes | RedirectRoutes | RewriteRoutes
interface ParamMap {
"/": {}
}
export type { AppRoutes, PageRoutes, LayoutRoutes, RedirectRoutes, RewriteRoutes, ParamMap }
export type ParamsOf<Route extends Routes> = ParamMap[Route]
declare global {
/**
* Props for Next.js App Router page components
* @example
* \`\`\`tsx
* export default function Page(props: PageProps<'/blog/[slug]'>) {
* const { slug } = await props.params
* return <div>Blog post: {slug}</div>
* }
* \`\`\`
*/
interface PageProps<AppRoute extends AppRoutes> {
params: Promise<ParamMap[AppRoute]>
searchParams: Promise<Record<string, string | string[] | undefined>>
interface LayoutSlotMap {
"/": never
}
/**
* Props for Next.js App Router layout components
* @example
* \`\`\`tsx
* export default function Layout(props: LayoutProps<'/dashboard'>) {
* return <div>{props.children}</div>
* }
* \`\`\`
*/
type LayoutProps<LayoutRoute extends LayoutRoutes> = {
params: Promise<ParamMap[LayoutRoute]>
children: React.ReactNode
} & {
[K in LayoutSlotMap[LayoutRoute]]: React.ReactNode
export type { AppRoutes, PageRoutes, LayoutRoutes, RedirectRoutes, RewriteRoutes, ParamMap }
declare global {
/**
* Props for Next.js App Router page components
* @example
* \`\`\`tsx
* export default function Page(props: PageProps<'/blog/[slug]'>) {
* const { slug } = await props.params
* return <div>Blog post: {slug}</div>
* }
* \`\`\`
*/
interface PageProps<AppRoute extends AppRoutes> {
params: Promise<ParamMap[AppRoute]>
searchParams: Promise<Record<string, string | string[] | undefined>>
}
/**
* Props for Next.js App Router layout components
* @example
* \`\`\`tsx
* export default function Layout(props: LayoutProps<'/dashboard'>) {
* return <div>{props.children}</div>
* }
* \`\`\`
*/
type LayoutProps<LayoutRoute extends LayoutRoutes> = {
params: Promise<ParamMap[LayoutRoute]>
children: React.ReactNode
} & {
[K in LayoutSlotMap[LayoutRoute]]: React.ReactNode
}
}
}
"
`)
"
`)
}
})
})
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