Unverified Commit 35a566b3 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[strict-route-types] Ensure cache profiles and routes are type-checked even if…

[strict-route-types] Ensure cache profiles and routes are type-checked even if .next is excluded (#87768)

Flagged behind `experimental.strictRouteTypes`

This fixes issues where cache profiles where not included or routes not validated if `.next` was excluded to squeeze out every bit of TypeScript performance.

It also fixes a redundant type-check since we have separate dev and prod dist folders.  If you run `next dev` and (`next build` or `next typegen`), you'd type-check routes and links twice. Now `next-env.d.ts` only exists once where we decide which dist folder to type-check.

Going forward, new Next.js type-checking should be added to `next-env.d.ts`. That file is fully controlled by Next.js and churning it, does not churn users since it's not in version control.

`next-env.d.ts` will be moved into `.next` in a follow-up. Ideally independent of the dist folder i.e.  independent of `next dev` vs `next build`.

Closes https://linear.app/vercel/issue/NXT-124/

https://github.com/vercel/next.js/pull/87319 but flagged.
parent b983ce47
...@@ -52,6 +52,8 @@ test/e2e/app-dir/server-source-maps/fixtures/default/internal-pkg/ignored.js ...@@ -52,6 +52,8 @@ test/e2e/app-dir/server-source-maps/fixtures/default/internal-pkg/ignored.js
test/e2e/app-dir/server-source-maps/fixtures/default/internal-pkg/sourcemapped.js test/e2e/app-dir/server-source-maps/fixtures/default/internal-pkg/sourcemapped.js
test/e2e/app-dir/server-source-maps/fixtures/default/external-pkg/sourcemapped.js test/e2e/app-dir/server-source-maps/fixtures/default/external-pkg/sourcemapped.js
test/development/mcp-server/fixtures/default-template/app/build-error/page.tsx test/development/mcp-server/fixtures/default-template/app/build-error/page.tsx
# Tested against auto-generated content that isn't formatted
test/integration/typescript-app-type-declarations/next-env.strictRouteTypes.d.ts
# turbopack crates, disable for some tests and precompiled dependencies. # turbopack crates, disable for some tests and precompiled dependencies.
/turbopack/crates/*/js/src/compiled /turbopack/crates/*/js/src/compiled
......
...@@ -23,6 +23,7 @@ function verifyTypeScriptSetup( ...@@ -23,6 +23,7 @@ function verifyTypeScriptSetup(
strictRouteTypes: boolean, strictRouteTypes: boolean,
typeCheckPreflight: boolean, typeCheckPreflight: boolean,
tsconfigPath: string | undefined, tsconfigPath: string | undefined,
typedRoutes: boolean,
disableStaticImages: boolean, disableStaticImages: boolean,
cacheDir: string | undefined, cacheDir: string | undefined,
enableWorkerThreads: boolean | undefined, enableWorkerThreads: boolean | undefined,
...@@ -54,6 +55,7 @@ function verifyTypeScriptSetup( ...@@ -54,6 +55,7 @@ function verifyTypeScriptSetup(
strictRouteTypes, strictRouteTypes,
typeCheckPreflight, typeCheckPreflight,
tsconfigPath, tsconfigPath,
typedRoutes,
disableStaticImages, disableStaticImages,
cacheDir, cacheDir,
hasAppDir, hasAppDir,
...@@ -122,6 +124,7 @@ export async function startTypeChecking({ ...@@ -122,6 +124,7 @@ export async function startTypeChecking({
Boolean(config.experimental.strictRouteTypes), Boolean(config.experimental.strictRouteTypes),
!ignoreTypeScriptErrors, !ignoreTypeScriptErrors,
config.typescript.tsconfigPath, config.typescript.tsconfigPath,
Boolean(config.typedRoutes),
config.images.disableStaticImages, config.images.disableStaticImages,
cacheDir, cacheDir,
config.experimental.workerThreads, config.experimental.workerThreads,
......
...@@ -143,6 +143,7 @@ async function runPlaywright( ...@@ -143,6 +143,7 @@ async function runPlaywright(
strictRouteTypes: Boolean(nextConfig.experimental.strictRouteTypes), strictRouteTypes: Boolean(nextConfig.experimental.strictRouteTypes),
typeCheckPreflight: false, typeCheckPreflight: false,
tsconfigPath: nextConfig.typescript.tsconfigPath, tsconfigPath: nextConfig.typescript.tsconfigPath,
typedRoutes: Boolean(nextConfig.typedRoutes),
disableStaticImages: nextConfig.images.disableStaticImages, disableStaticImages: nextConfig.images.disableStaticImages,
hasAppDir: !!appDir, hasAppDir: !!appDir,
hasPagesDir: !!pagesDir, hasPagesDir: !!pagesDir,
......
...@@ -62,6 +62,7 @@ const nextTypegen = async ( ...@@ -62,6 +62,7 @@ const nextTypegen = async (
strictRouteTypes, strictRouteTypes,
typeCheckPreflight: false, typeCheckPreflight: false,
tsconfigPath: nextConfig.typescript.tsconfigPath, tsconfigPath: nextConfig.typescript.tsconfigPath,
typedRoutes: Boolean(nextConfig.typedRoutes),
disableStaticImages: nextConfig.images.disableStaticImages, disableStaticImages: nextConfig.images.disableStaticImages,
hasAppDir: !!appDir, hasAppDir: !!appDir,
hasPagesDir: !!pagesDir, hasPagesDir: !!pagesDir,
......
...@@ -8,12 +8,16 @@ export async function writeAppTypeDeclarations({ ...@@ -8,12 +8,16 @@ export async function writeAppTypeDeclarations({
imageImportsEnabled, imageImportsEnabled,
hasPagesDir, hasPagesDir,
hasAppDir, hasAppDir,
strictRouteTypes,
typedRoutes,
}: { }: {
baseDir: string baseDir: string
distDir: string distDir: string
imageImportsEnabled: boolean imageImportsEnabled: boolean
hasPagesDir: boolean hasPagesDir: boolean
hasAppDir: boolean hasAppDir: boolean
strictRouteTypes: boolean
typedRoutes: boolean
}): Promise<void> { }): Promise<void> {
// Reference `next` types // Reference `next` types
const appTypeDeclarations = path.join(baseDir, 'next-env.d.ts') const appTypeDeclarations = path.join(baseDir, 'next-env.d.ts')
...@@ -42,17 +46,17 @@ export async function writeAppTypeDeclarations({ ...@@ -42,17 +46,17 @@ export async function writeAppTypeDeclarations({
* *
* @see https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html * @see https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html
*/ */
const directives: string[] = [ const lines: string[] = [
// Include the core Next.js typings. // Include the core Next.js typings.
'/// <reference types="next" />', '/// <reference types="next" />',
] ]
if (imageImportsEnabled) { if (imageImportsEnabled) {
directives.push('/// <reference types="next/image-types/global" />') lines.push('/// <reference types="next/image-types/global" />')
} }
if (hasAppDir && hasPagesDir) { if (hasAppDir && hasPagesDir) {
directives.push( lines.push(
'/// <reference types="next/navigation-types/compat/navigation" />' '/// <reference types="next/navigation-types/compat/navigation" />'
) )
} }
...@@ -63,16 +67,38 @@ export async function writeAppTypeDeclarations({ ...@@ -63,16 +67,38 @@ export async function writeAppTypeDeclarations({
) )
// Use ESM import instead of triple-slash reference for better ESLint compatibility // Use ESM import instead of triple-slash reference for better ESLint compatibility
directives.push(`import "./${routeTypesPath}";`) lines.push(`import "./${routeTypesPath}";`)
if (strictRouteTypes) {
const cacheLifePath = path.posix.join(
distDir.replaceAll(path.win32.sep, path.posix.sep),
'types/cache-life.d.ts'
)
lines.push(`import "./${cacheLifePath}";`)
const routeValidatorPath = path.posix.join(
distDir.replaceAll(path.win32.sep, path.posix.sep),
'types/validator.ts'
)
lines.push(`import "./${routeValidatorPath}";`)
if (typedRoutes === true) {
const linkTypesPath = path.posix.join(
distDir.replaceAll(path.win32.sep, path.posix.sep),
'types/link.d.ts'
)
lines.push(`import "./${linkTypesPath}";`)
}
}
// Push the notice in. // Push the notice in.
directives.push( lines.push(
'', '',
'// NOTE: This file should not be edited', '// NOTE: This file should not be edited',
`// see https://nextjs.org/docs/${hasAppDir ? 'app' : 'pages'}/api-reference/config/typescript for more information.` `// see https://nextjs.org/docs/${hasAppDir ? 'app' : 'pages'}/api-reference/config/typescript for more information.`
) )
const content = directives.join(eol) + eol const content = lines.join(eol) + eol
// Avoids an un-necessary write on read-only fs // Avoids an un-necessary write on read-only fs
if (currentContent === content) { if (currentContent === content) {
......
...@@ -87,8 +87,6 @@ describe('writeConfigurationDefaults()', () => { ...@@ -87,8 +87,6 @@ describe('writeConfigurationDefaults()', () => {
], ],
"include": [ "include": [
"next-env.d.ts", "next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts", "**/*.mts",
"**/*.ts", "**/*.ts",
"**/*.tsx", "**/*.tsx",
...@@ -109,7 +107,7 @@ describe('writeConfigurationDefaults()', () => { ...@@ -109,7 +107,7 @@ describe('writeConfigurationDefaults()', () => {
- strict was set to false - strict was set to false
- noEmit was set to true - noEmit was set to true
- incremental was set to true - incremental was set to true
- include was set to ['next-env.d.ts', '.next/types/**/*.ts', '.next/dev/types/**/*.ts', '**/*.mts', '**/*.ts', '**/*.tsx'] - include was set to ['next-env.d.ts', '**/*.mts', '**/*.ts', '**/*.tsx']
- plugins was updated to add { name: 'next' } - plugins was updated to add { name: 'next' }
- exclude was set to ['node_modules'] - exclude was set to ['node_modules']
......
...@@ -284,7 +284,7 @@ export async function writeConfigurationDefaults( ...@@ -284,7 +284,7 @@ export async function writeConfigurationDefaults(
if (!('include' in userTsConfig)) { if (!('include' in userTsConfig)) {
const defaultInclude = const defaultInclude =
hasAppDir || strictRouteTypes hasAppDir && !strictRouteTypes
? ['next-env.d.ts', ...nextTypes, '**/*.mts', '**/*.ts', '**/*.tsx'] ? ['next-env.d.ts', ...nextTypes, '**/*.mts', '**/*.ts', '**/*.tsx']
: ['next-env.d.ts', '**/*.mts', '**/*.ts', '**/*.tsx'] : ['next-env.d.ts', '**/*.mts', '**/*.ts', '**/*.tsx']
...@@ -295,7 +295,7 @@ export async function writeConfigurationDefaults( ...@@ -295,7 +295,7 @@ export async function writeConfigurationDefaults(
bold(defaultInclude.map((type) => `'${type}'`).join(', ')) + bold(defaultInclude.map((type) => `'${type}'`).join(', ')) +
']' ']'
) )
} else if (hasAppDir || strictRouteTypes) { } else if (hasAppDir && !strictRouteTypes) {
const missingFromResolved = [] const missingFromResolved = []
for (const type of nextTypes) { for (const type of nextTypes) {
if (!userTsConfig.include.includes(type)) { if (!userTsConfig.include.includes(type)) {
......
...@@ -40,6 +40,7 @@ export async function verifyTypeScriptSetup({ ...@@ -40,6 +40,7 @@ export async function verifyTypeScriptSetup({
strictRouteTypes, strictRouteTypes,
tsconfigPath, tsconfigPath,
typeCheckPreflight, typeCheckPreflight,
typedRoutes,
disableStaticImages, disableStaticImages,
hasAppDir, hasAppDir,
hasPagesDir, hasPagesDir,
...@@ -54,6 +55,7 @@ export async function verifyTypeScriptSetup({ ...@@ -54,6 +55,7 @@ export async function verifyTypeScriptSetup({
strictRouteTypes: boolean strictRouteTypes: boolean
tsconfigPath: string | undefined tsconfigPath: string | undefined
typeCheckPreflight: boolean typeCheckPreflight: boolean
typedRoutes: boolean
disableStaticImages: boolean disableStaticImages: boolean
hasAppDir: boolean hasAppDir: boolean
hasPagesDir: boolean hasPagesDir: boolean
...@@ -149,6 +151,8 @@ export async function verifyTypeScriptSetup({ ...@@ -149,6 +151,8 @@ export async function verifyTypeScriptSetup({
imageImportsEnabled: !disableStaticImages, imageImportsEnabled: !disableStaticImages,
hasPagesDir, hasPagesDir,
hasAppDir, hasAppDir,
strictRouteTypes,
typedRoutes,
}) })
let result let result
......
...@@ -146,6 +146,7 @@ async function verifyTypeScript(opts: SetupOpts) { ...@@ -146,6 +146,7 @@ async function verifyTypeScript(opts: SetupOpts) {
strictRouteTypes: Boolean(opts.nextConfig.experimental.strictRouteTypes), strictRouteTypes: Boolean(opts.nextConfig.experimental.strictRouteTypes),
typeCheckPreflight: false, typeCheckPreflight: false,
tsconfigPath: opts.nextConfig.typescript.tsconfigPath, tsconfigPath: opts.nextConfig.typescript.tsconfigPath,
typedRoutes: Boolean(opts.nextConfig.typedRoutes),
disableStaticImages: opts.nextConfig.images.disableStaticImages, disableStaticImages: opts.nextConfig.images.disableStaticImages,
hasAppDir: !!opts.appDir, hasAppDir: !!opts.appDir,
hasPagesDir: !!opts.pagesDir, hasPagesDir: !!opts.pagesDir,
......
...@@ -61,8 +61,6 @@ describe('tsconfig module: preserve', () => { ...@@ -61,8 +61,6 @@ describe('tsconfig module: preserve', () => {
}, },
"include": [ "include": [
"next-env.d.ts", "next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts", "**/*.mts",
"**/*.ts", "**/*.ts",
"**/*.tsx" "**/*.tsx"
......
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts";
import "./.next/dev/types/cache-life.d.ts";
import "./.next/dev/types/validator.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
...@@ -6,8 +6,34 @@ import { promises as fs } from 'fs' ...@@ -6,8 +6,34 @@ import { promises as fs } from 'fs'
const appDir = join(__dirname, '..') const appDir = join(__dirname, '..')
const appTypeDeclarations = join(appDir, 'next-env.d.ts') const appTypeDeclarations = join(appDir, 'next-env.d.ts')
const appTypeDeclarationsStrictRouteTypes = join(
appDir,
'next-env.strictRouteTypes.d.ts'
)
const strictRouteTypes =
process.env.__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES === 'true'
describe('TypeScript App Type Declarations', () => { describe('TypeScript App Type Declarations', () => {
beforeAll(async () => {
if (strictRouteTypes) {
await fs.rename(appTypeDeclarations, appTypeDeclarations + '.bak')
await fs.copyFile(
appTypeDeclarationsStrictRouteTypes,
appTypeDeclarations
)
}
})
afterAll(async () => {
if (strictRouteTypes) {
await fs.rename(
join(appDir, 'next-env.d.ts') + '.bak',
join(appDir, 'next-env.d.ts')
)
}
})
it('should write a new next-env.d.ts if none exist', async () => { it('should write a new next-env.d.ts if none exist', async () => {
const prevContent = await fs.readFile(appTypeDeclarations, 'utf8') const prevContent = await fs.readFile(appTypeDeclarations, 'utf8')
try { try {
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
const strictRouteTypes =
process.env.__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES === 'true'
// This next-types-plugin feature only works in webpack // This next-types-plugin feature only works in webpack
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)( ;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'app-dir - sync-params-type-check', 'app-dir - sync-params-type-check',
...@@ -28,7 +31,9 @@ import { nextTestSetup } from 'e2e-utils' ...@@ -28,7 +31,9 @@ import { nextTestSetup } from 'e2e-utils'
const { exitCode, cliOutput } = await next.build() const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1) expect(exitCode).toBe(1)
expect(cliOutput).toMatch( expect(cliOutput).toMatch(
/Type error: Type '{ params: Params; }' does not satisfy the constraint 'PageProps'/ strictRouteTypes
? /Property 'slug' is missing in type 'Promise<{ slug: string; }>'/
: /Type error: Type '{ params: Params; }' does not satisfy the constraint 'PageProps'/
) )
}) })
} }
......
...@@ -38,6 +38,8 @@ describe('find config', () => { ...@@ -38,6 +38,8 @@ describe('find config', () => {
imageImportsEnabled, imageImportsEnabled,
hasPagesDir: false, hasPagesDir: false,
hasAppDir: false, hasAppDir: false,
strictRouteTypes: false,
typedRoutes: true,
}) })
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content) expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
}) })
...@@ -66,6 +68,8 @@ describe('find config', () => { ...@@ -66,6 +68,8 @@ describe('find config', () => {
imageImportsEnabled, imageImportsEnabled,
hasPagesDir: false, hasPagesDir: false,
hasAppDir: false, hasAppDir: false,
strictRouteTypes: false,
typedRoutes: true,
}) })
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content) expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
}) })
...@@ -92,6 +96,8 @@ describe('find config', () => { ...@@ -92,6 +96,8 @@ describe('find config', () => {
imageImportsEnabled, imageImportsEnabled,
hasPagesDir: false, hasPagesDir: false,
hasAppDir: false, hasAppDir: false,
strictRouteTypes: false,
typedRoutes: true,
}) })
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content) expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
}) })
...@@ -103,6 +109,8 @@ describe('find config', () => { ...@@ -103,6 +109,8 @@ describe('find config', () => {
imageImportsEnabled, imageImportsEnabled,
hasPagesDir: false, hasPagesDir: false,
hasAppDir: true, hasAppDir: true,
strictRouteTypes: false,
typedRoutes: true,
}) })
await expect(fs.readFile(declarationFile, 'utf8')).resolves.not.toContain( await expect(fs.readFile(declarationFile, 'utf8')).resolves.not.toContain(
...@@ -115,6 +123,8 @@ describe('find config', () => { ...@@ -115,6 +123,8 @@ describe('find config', () => {
imageImportsEnabled, imageImportsEnabled,
hasPagesDir: true, hasPagesDir: true,
hasAppDir: true, hasAppDir: true,
strictRouteTypes: false,
typedRoutes: true,
}) })
await expect(fs.readFile(declarationFile, 'utf8')).resolves.toContain( 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