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
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/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/*/js/src/compiled
......
......@@ -23,6 +23,7 @@ function verifyTypeScriptSetup(
strictRouteTypes: boolean,
typeCheckPreflight: boolean,
tsconfigPath: string | undefined,
typedRoutes: boolean,
disableStaticImages: boolean,
cacheDir: string | undefined,
enableWorkerThreads: boolean | undefined,
......@@ -54,6 +55,7 @@ function verifyTypeScriptSetup(
strictRouteTypes,
typeCheckPreflight,
tsconfigPath,
typedRoutes,
disableStaticImages,
cacheDir,
hasAppDir,
......@@ -122,6 +124,7 @@ export async function startTypeChecking({
Boolean(config.experimental.strictRouteTypes),
!ignoreTypeScriptErrors,
config.typescript.tsconfigPath,
Boolean(config.typedRoutes),
config.images.disableStaticImages,
cacheDir,
config.experimental.workerThreads,
......
......@@ -143,6 +143,7 @@ async function runPlaywright(
strictRouteTypes: Boolean(nextConfig.experimental.strictRouteTypes),
typeCheckPreflight: false,
tsconfigPath: nextConfig.typescript.tsconfigPath,
typedRoutes: Boolean(nextConfig.typedRoutes),
disableStaticImages: nextConfig.images.disableStaticImages,
hasAppDir: !!appDir,
hasPagesDir: !!pagesDir,
......
......@@ -62,6 +62,7 @@ const nextTypegen = async (
strictRouteTypes,
typeCheckPreflight: false,
tsconfigPath: nextConfig.typescript.tsconfigPath,
typedRoutes: Boolean(nextConfig.typedRoutes),
disableStaticImages: nextConfig.images.disableStaticImages,
hasAppDir: !!appDir,
hasPagesDir: !!pagesDir,
......
......@@ -8,12 +8,16 @@ export async function writeAppTypeDeclarations({
imageImportsEnabled,
hasPagesDir,
hasAppDir,
strictRouteTypes,
typedRoutes,
}: {
baseDir: string
distDir: string
imageImportsEnabled: boolean
hasPagesDir: boolean
hasAppDir: boolean
strictRouteTypes: boolean
typedRoutes: boolean
}): Promise<void> {
// Reference `next` types
const appTypeDeclarations = path.join(baseDir, 'next-env.d.ts')
......@@ -42,17 +46,17 @@ export async function writeAppTypeDeclarations({
*
* @see https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html
*/
const directives: string[] = [
const lines: string[] = [
// Include the core Next.js typings.
'/// <reference types="next" />',
]
if (imageImportsEnabled) {
directives.push('/// <reference types="next/image-types/global" />')
lines.push('/// <reference types="next/image-types/global" />')
}
if (hasAppDir && hasPagesDir) {
directives.push(
lines.push(
'/// <reference types="next/navigation-types/compat/navigation" />'
)
}
......@@ -63,16 +67,38 @@ export async function writeAppTypeDeclarations({
)
// 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.
directives.push(
lines.push(
'',
'// NOTE: This file should not be edited',
`// 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
if (currentContent === content) {
......
......@@ -87,8 +87,6 @@ describe('writeConfigurationDefaults()', () => {
],
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts",
"**/*.ts",
"**/*.tsx",
......@@ -109,7 +107,7 @@ describe('writeConfigurationDefaults()', () => {
- strict was set to false
- noEmit 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' }
- exclude was set to ['node_modules']
......
......@@ -284,7 +284,7 @@ export async function writeConfigurationDefaults(
if (!('include' in userTsConfig)) {
const defaultInclude =
hasAppDir || strictRouteTypes
hasAppDir && !strictRouteTypes
? ['next-env.d.ts', ...nextTypes, '**/*.mts', '**/*.ts', '**/*.tsx']
: ['next-env.d.ts', '**/*.mts', '**/*.ts', '**/*.tsx']
......@@ -295,7 +295,7 @@ export async function writeConfigurationDefaults(
bold(defaultInclude.map((type) => `'${type}'`).join(', ')) +
']'
)
} else if (hasAppDir || strictRouteTypes) {
} else if (hasAppDir && !strictRouteTypes) {
const missingFromResolved = []
for (const type of nextTypes) {
if (!userTsConfig.include.includes(type)) {
......
......@@ -40,6 +40,7 @@ export async function verifyTypeScriptSetup({
strictRouteTypes,
tsconfigPath,
typeCheckPreflight,
typedRoutes,
disableStaticImages,
hasAppDir,
hasPagesDir,
......@@ -54,6 +55,7 @@ export async function verifyTypeScriptSetup({
strictRouteTypes: boolean
tsconfigPath: string | undefined
typeCheckPreflight: boolean
typedRoutes: boolean
disableStaticImages: boolean
hasAppDir: boolean
hasPagesDir: boolean
......@@ -149,6 +151,8 @@ export async function verifyTypeScriptSetup({
imageImportsEnabled: !disableStaticImages,
hasPagesDir,
hasAppDir,
strictRouteTypes,
typedRoutes,
})
let result
......
......@@ -146,6 +146,7 @@ async function verifyTypeScript(opts: SetupOpts) {
strictRouteTypes: Boolean(opts.nextConfig.experimental.strictRouteTypes),
typeCheckPreflight: false,
tsconfigPath: opts.nextConfig.typescript.tsconfigPath,
typedRoutes: Boolean(opts.nextConfig.typedRoutes),
disableStaticImages: opts.nextConfig.images.disableStaticImages,
hasAppDir: !!opts.appDir,
hasPagesDir: !!opts.pagesDir,
......
......@@ -61,8 +61,6 @@ describe('tsconfig module: preserve', () => {
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts",
"**/*.ts",
"**/*.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'
const appDir = join(__dirname, '..')
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', () => {
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 () => {
const prevContent = await fs.readFile(appTypeDeclarations, 'utf8')
try {
......
import { nextTestSetup } from 'e2e-utils'
const strictRouteTypes =
process.env.__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES === 'true'
// This next-types-plugin feature only works in webpack
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'app-dir - sync-params-type-check',
......@@ -28,7 +31,9 @@ import { nextTestSetup } from 'e2e-utils'
const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1)
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', () => {
imageImportsEnabled,
hasPagesDir: false,
hasAppDir: false,
strictRouteTypes: false,
typedRoutes: true,
})
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
})
......@@ -66,6 +68,8 @@ describe('find config', () => {
imageImportsEnabled,
hasPagesDir: false,
hasAppDir: false,
strictRouteTypes: false,
typedRoutes: true,
})
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
})
......@@ -92,6 +96,8 @@ describe('find config', () => {
imageImportsEnabled,
hasPagesDir: false,
hasAppDir: false,
strictRouteTypes: false,
typedRoutes: true,
})
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
})
......@@ -103,6 +109,8 @@ describe('find config', () => {
imageImportsEnabled,
hasPagesDir: false,
hasAppDir: true,
strictRouteTypes: false,
typedRoutes: true,
})
await expect(fs.readFile(declarationFile, 'utf8')).resolves.not.toContain(
......@@ -115,6 +123,8 @@ describe('find config', () => {
imageImportsEnabled,
hasPagesDir: true,
hasAppDir: true,
strictRouteTypes: false,
typedRoutes: true,
})
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