Unverified Commit 25da5f04 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Move next-env.d.ts to dist dir (#86752)

parent aa8a243e
...@@ -224,6 +224,7 @@ import { ...@@ -224,6 +224,7 @@ import {
createRouteTypesManifest, createRouteTypesManifest,
writeRouteTypesManifest, writeRouteTypesManifest,
writeValidatorFile, writeValidatorFile,
writeDynamicTypesFile,
} from '../server/lib/router-utils/route-types-utils' } from '../server/lib/router-utils/route-types-utils'
import { Lockfile } from './lockfile' import { Lockfile } from './lockfile'
import { import {
...@@ -1484,6 +1485,12 @@ export default async function build( ...@@ -1484,6 +1485,12 @@ export default async function build(
config config
) )
await writeValidatorFile(routeTypesManifest, validatorFilePath) await writeValidatorFile(routeTypesManifest, validatorFilePath)
await writeDynamicTypesFile({
distDir,
imageImportsEnabled: !config.images.disableStaticImages,
hasPagesDir: !!pagesDir,
hasAppDir: !!appDir,
})
}) })
// Turbopack already handles conflicting app and page routes. // Turbopack already handles conflicting app and page routes.
......
...@@ -22,7 +22,6 @@ function verifyTypeScriptSetup( ...@@ -22,7 +22,6 @@ function verifyTypeScriptSetup(
distDir: string, distDir: string,
typeCheckPreflight: boolean, typeCheckPreflight: boolean,
tsconfigPath: string | undefined, tsconfigPath: string | undefined,
disableStaticImages: boolean,
cacheDir: string | undefined, cacheDir: string | undefined,
enableWorkerThreads: boolean | undefined, enableWorkerThreads: boolean | undefined,
hasAppDir: boolean, hasAppDir: boolean,
...@@ -52,7 +51,6 @@ function verifyTypeScriptSetup( ...@@ -52,7 +51,6 @@ function verifyTypeScriptSetup(
distDir, distDir,
typeCheckPreflight, typeCheckPreflight,
tsconfigPath, tsconfigPath,
disableStaticImages,
cacheDir, cacheDir,
hasAppDir, hasAppDir,
hasPagesDir, hasPagesDir,
...@@ -119,7 +117,6 @@ export async function startTypeChecking({ ...@@ -119,7 +117,6 @@ export async function startTypeChecking({
config.distDir, config.distDir,
!ignoreTypeScriptErrors, !ignoreTypeScriptErrors,
config.typescript.tsconfigPath, config.typescript.tsconfigPath,
config.images.disableStaticImages,
cacheDir, cacheDir,
config.experimental.workerThreads, config.experimental.workerThreads,
!!appDir, !!appDir,
......
...@@ -142,7 +142,6 @@ async function runPlaywright( ...@@ -142,7 +142,6 @@ async function runPlaywright(
distDir: nextConfig.distDir, distDir: nextConfig.distDir,
typeCheckPreflight: false, typeCheckPreflight: false,
tsconfigPath: nextConfig.typescript.tsconfigPath, tsconfigPath: nextConfig.typescript.tsconfigPath,
disableStaticImages: nextConfig.images.disableStaticImages,
hasAppDir: !!appDir, hasAppDir: !!appDir,
hasPagesDir: !!pagesDir, hasPagesDir: !!pagesDir,
isolatedDevBuild: nextConfig.experimental.isolatedDevBuild, isolatedDevBuild: nextConfig.experimental.isolatedDevBuild,
......
...@@ -29,6 +29,7 @@ import { ...@@ -29,6 +29,7 @@ import {
createRouteTypesManifest, createRouteTypesManifest,
writeRouteTypesManifest, writeRouteTypesManifest,
writeValidatorFile, writeValidatorFile,
writeDynamicTypesFile,
} from '../server/lib/router-utils/route-types-utils' } from '../server/lib/router-utils/route-types-utils'
import { writeCacheLifeTypes } from '../server/lib/router-utils/cache-life-type-utils' import { writeCacheLifeTypes } from '../server/lib/router-utils/cache-life-type-utils'
import { createValidFileMatcher } from '../server/lib/find-page-file' import { createValidFileMatcher } from '../server/lib/find-page-file'
...@@ -59,7 +60,6 @@ const nextTypegen = async ( ...@@ -59,7 +60,6 @@ const nextTypegen = async (
distDir: nextConfig.distDir, distDir: nextConfig.distDir,
typeCheckPreflight: false, typeCheckPreflight: false,
tsconfigPath: nextConfig.typescript.tsconfigPath, tsconfigPath: nextConfig.typescript.tsconfigPath,
disableStaticImages: nextConfig.images.disableStaticImages,
hasAppDir: !!appDir, hasAppDir: !!appDir,
hasPagesDir: !!pagesDir, hasPagesDir: !!pagesDir,
isolatedDevBuild: nextConfig.experimental.isolatedDevBuild, isolatedDevBuild: nextConfig.experimental.isolatedDevBuild,
...@@ -171,6 +171,13 @@ const nextTypegen = async ( ...@@ -171,6 +171,13 @@ const nextTypegen = async (
await writeValidatorFile(routeTypesManifest, validatorFilePath) await writeValidatorFile(routeTypesManifest, validatorFilePath)
await writeDynamicTypesFile({
distDir,
imageImportsEnabled: !nextConfig.images.disableStaticImages,
hasPagesDir: !!pagesDir,
hasAppDir: !!appDir,
})
// Generate cache-life types if cacheLife config exists // Generate cache-life types if cacheLife config exists
const cacheLifeFilePath = join(distDir, 'types', 'cache-life.d.ts') const cacheLifeFilePath = join(distDir, 'types', 'cache-life.d.ts')
writeCacheLifeTypes(nextConfig.cacheLife, cacheLifeFilePath) writeCacheLifeTypes(nextConfig.cacheLife, cacheLifeFilePath)
......
import os from 'os'
import path from 'path'
import { promises as fs } from 'fs'
export async function writeAppTypeDeclarations({
baseDir,
distDir,
imageImportsEnabled,
hasPagesDir,
hasAppDir,
}: {
baseDir: string
distDir: string
imageImportsEnabled: boolean
hasPagesDir: boolean
hasAppDir: boolean
}): Promise<void> {
// Reference `next` types
const appTypeDeclarations = path.join(baseDir, 'next-env.d.ts')
// Defaults EOL to system default
let eol = os.EOL
let currentContent: string | undefined
try {
currentContent = await fs.readFile(appTypeDeclarations, 'utf8')
// If file already exists then preserve its line ending
const lf = currentContent.indexOf('\n', /* skip first so we can lf - 1 */ 1)
if (lf !== -1) {
if (currentContent[lf - 1] === '\r') {
eol = '\r\n'
} else {
eol = '\n'
}
}
} catch {}
/**
* "Triple-slash directives" used to create typings files for Next.js projects
* using Typescript .
*
* @see https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html
*/
const directives: string[] = [
// Include the core Next.js typings.
'/// <reference types="next" />',
]
if (imageImportsEnabled) {
directives.push('/// <reference types="next/image-types/global" />')
}
if (hasAppDir && hasPagesDir) {
directives.push(
'/// <reference types="next/navigation-types/compat/navigation" />'
)
}
const routeTypesPath = path.posix.join(
distDir.replaceAll(path.win32.sep, path.posix.sep),
'types/routes.d.ts'
)
// Use ESM import instead of triple-slash reference for better ESLint compatibility
directives.push(`import "./${routeTypesPath}";`)
// Push the notice in.
directives.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
// Avoids an un-necessary write on read-only fs
if (currentContent === content) {
return
}
await fs.writeFile(appTypeDeclarations, content)
}
...@@ -84,7 +84,6 @@ describe('writeConfigurationDefaults()', () => { ...@@ -84,7 +84,6 @@ describe('writeConfigurationDefaults()', () => {
"node_modules", "node_modules",
], ],
"include": [ "include": [
"next-env.d.ts",
".next/types/**/*.ts", ".next/types/**/*.ts",
".next/dev/types/**/*.ts", ".next/dev/types/**/*.ts",
"**/*.mts", "**/*.mts",
...@@ -107,7 +106,7 @@ describe('writeConfigurationDefaults()', () => { ...@@ -107,7 +106,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/types/**/*.ts', '.next/dev/types/**/*.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']
......
...@@ -282,19 +282,16 @@ export async function writeConfigurationDefaults( ...@@ -282,19 +282,16 @@ export async function writeConfigurationDefaults(
) )
if (!('include' in userTsConfig)) { if (!('include' in userTsConfig)) {
userTsConfig.include = hasAppDir // Always include .next/types for dynamic types (image imports, route types, etc.)
? ['next-env.d.ts', ...nextAppTypes, '**/*.mts', '**/*.ts', '**/*.tsx'] userTsConfig.include = [...nextAppTypes, '**/*.mts', '**/*.ts', '**/*.tsx']
: ['next-env.d.ts', '**/*.mts', '**/*.ts', '**/*.tsx']
suggestedActions.push( suggestedActions.push(
cyan('include') + cyan('include') +
' was set to ' + ' was set to ' +
bold( bold(
hasAppDir `[${nextAppTypes.map((type) => `'${type}'`).join(', ')}, '**/*.mts', '**/*.ts', '**/*.tsx']`
? `['next-env.d.ts', ${nextAppTypes.map((type) => `'${type}'`).join(', ')}, '**/*.mts', '**/*.ts', '**/*.tsx']`
: `['next-env.d.ts', '**/*.mts', '**/*.ts', '**/*.tsx']`
) )
) )
} else if (hasAppDir) { } else {
const missingFromResolved = [] const missingFromResolved = []
for (const type of nextAppTypes) { for (const type of nextAppTypes) {
if (!userTsConfig.include.includes(type)) { if (!userTsConfig.include.includes(type)) {
......
...@@ -9,7 +9,6 @@ import * as log from '../build/output/log' ...@@ -9,7 +9,6 @@ import * as log from '../build/output/log'
import { getTypeScriptIntent } from './typescript/getTypeScriptIntent' import { getTypeScriptIntent } from './typescript/getTypeScriptIntent'
import type { TypeCheckResult } from './typescript/runTypeCheck' import type { TypeCheckResult } from './typescript/runTypeCheck'
import { writeAppTypeDeclarations } from './typescript/writeAppTypeDeclarations'
import { writeConfigurationDefaults } from './typescript/writeConfigurationDefaults' import { writeConfigurationDefaults } from './typescript/writeConfigurationDefaults'
import { installDependencies } from './install-dependencies' import { installDependencies } from './install-dependencies'
import { isCI } from '../server/ci-info' import { isCI } from '../server/ci-info'
...@@ -39,7 +38,6 @@ export async function verifyTypeScriptSetup({ ...@@ -39,7 +38,6 @@ export async function verifyTypeScriptSetup({
cacheDir, cacheDir,
tsconfigPath, tsconfigPath,
typeCheckPreflight, typeCheckPreflight,
disableStaticImages,
hasAppDir, hasAppDir,
hasPagesDir, hasPagesDir,
isolatedDevBuild, isolatedDevBuild,
...@@ -52,7 +50,6 @@ export async function verifyTypeScriptSetup({ ...@@ -52,7 +50,6 @@ export async function verifyTypeScriptSetup({
cacheDir?: string cacheDir?: string
tsconfigPath: string | undefined tsconfigPath: string | undefined
typeCheckPreflight: boolean typeCheckPreflight: boolean
disableStaticImages: boolean
hasAppDir: boolean hasAppDir: boolean
hasPagesDir: boolean hasPagesDir: boolean
isolatedDevBuild: boolean | undefined isolatedDevBuild: boolean | undefined
...@@ -138,16 +135,6 @@ export async function verifyTypeScriptSetup({ ...@@ -138,16 +135,6 @@ export async function verifyTypeScriptSetup({
hasPagesDir, hasPagesDir,
isolatedDevBuild isolatedDevBuild
) )
// Write out the necessary `next-env.d.ts` file to correctly register
// Next.js' types:
await writeAppTypeDeclarations({
baseDir: dir,
distDir,
imageImportsEnabled: !disableStaticImages,
hasPagesDir,
hasAppDir,
})
let result let result
if (typeCheckPreflight) { if (typeCheckPreflight) {
const { runTypeCheck } = const { runTypeCheck } =
......
...@@ -10,6 +10,7 @@ import { ...@@ -10,6 +10,7 @@ import {
generateRouteTypesFile, generateRouteTypesFile,
generateLinkTypesFile, generateLinkTypesFile,
generateValidatorFile, generateValidatorFile,
generateDynamicTypesFile,
} from './typegen' } from './typegen'
import { tryToParsePath } from '../../../lib/try-to-parse-path' import { tryToParsePath } from '../../../lib/try-to-parse-path'
import { import {
...@@ -382,3 +383,35 @@ export async function writeValidatorFile( ...@@ -382,3 +383,35 @@ export async function writeValidatorFile(
await fs.promises.writeFile(filePath, generateValidatorFile(manifest)) await fs.promises.writeFile(filePath, generateValidatorFile(manifest))
} }
/**
* Writes the dynamic types file (.next/types/next-env.d.ts) that contains
* config-dependent type references (image imports, navigation compat, etc.)
*/
export async function writeDynamicTypesFile({
distDir,
imageImportsEnabled,
hasPagesDir,
hasAppDir,
}: {
distDir: string
imageImportsEnabled: boolean
hasPagesDir: boolean
hasAppDir: boolean
}) {
const typesDir = path.join(distDir, 'types')
const filePath = path.join(typesDir, 'next-env.d.ts')
// Directory should already be created by writeRouteTypesManifest, but ensure it exists
if (!fs.existsSync(typesDir)) {
await fs.promises.mkdir(typesDir, { recursive: true })
}
const content = generateDynamicTypesFile({
imageImportsEnabled,
hasPagesDir,
hasAppDir,
})
await fs.promises.writeFile(filePath, content)
}
...@@ -85,6 +85,7 @@ import { ...@@ -85,6 +85,7 @@ import {
createRouteTypesManifest, createRouteTypesManifest,
writeRouteTypesManifest, writeRouteTypesManifest,
writeValidatorFile, writeValidatorFile,
writeDynamicTypesFile,
} from './route-types-utils' } from './route-types-utils'
import { writeCacheLifeTypes } from './cache-life-type-utils' import { writeCacheLifeTypes } from './cache-life-type-utils'
import { isParallelRouteSegment } from '../../../shared/lib/segment' import { isParallelRouteSegment } from '../../../shared/lib/segment'
...@@ -145,7 +146,6 @@ async function verifyTypeScript(opts: SetupOpts) { ...@@ -145,7 +146,6 @@ async function verifyTypeScript(opts: SetupOpts) {
distDir: opts.nextConfig.distDir, distDir: opts.nextConfig.distDir,
typeCheckPreflight: false, typeCheckPreflight: false,
tsconfigPath: opts.nextConfig.typescript.tsconfigPath, tsconfigPath: opts.nextConfig.typescript.tsconfigPath,
disableStaticImages: opts.nextConfig.images.disableStaticImages,
hasAppDir: !!opts.appDir, hasAppDir: !!opts.appDir,
hasPagesDir: !!opts.pagesDir, hasPagesDir: !!opts.pagesDir,
isolatedDevBuild: opts.nextConfig.experimental.isolatedDevBuild, isolatedDevBuild: opts.nextConfig.experimental.isolatedDevBuild,
...@@ -265,6 +265,12 @@ async function startWatcher( ...@@ -265,6 +265,12 @@ async function startWatcher(
path.join(distTypesDir, 'routes.d.ts'), path.join(distTypesDir, 'routes.d.ts'),
opts.nextConfig opts.nextConfig
) )
await writeDynamicTypesFile({
distDir,
imageImportsEnabled: !opts.nextConfig.images.disableStaticImages,
hasPagesDir: !!pagesDir,
hasAppDir: !!appDir,
})
const routesManifestPath = path.join(distDir, ROUTES_MANIFEST) const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)
const routesManifest: DevRoutesManifest = { const routesManifest: DevRoutesManifest = {
......
import type { RouteTypesManifest } from './route-types-utils' import type { RouteTypesManifest } from './route-types-utils'
import { isDynamicRoute } from '../../../shared/lib/router/utils/is-dynamic' import { isDynamicRoute } from '../../../shared/lib/router/utils/is-dynamic'
/**
* Generates the content for .next/types/next-env.d.ts
* This file contains dynamic type references that depend on project configuration.
*/
export function generateDynamicTypesFile({
imageImportsEnabled,
hasPagesDir,
hasAppDir,
}: {
imageImportsEnabled: boolean
hasPagesDir: boolean
hasAppDir: boolean
}): string {
const directives: string[] = [
// Include the core Next.js typings.
'/// <reference types="next" />',
'// This file is generated automatically by Next.js',
'// Do not edit this file manually',
'',
]
if (imageImportsEnabled) {
directives.push('/// <reference types="next/image-types/global" />')
}
if (hasAppDir && hasPagesDir) {
directives.push(
'/// <reference types="next/navigation-types/compat/navigation" />'
)
}
// Import routes types from the same directory
directives.push('import "./routes.d.ts"')
return directives.join('\n') + '\n'
}
function generateRouteTypes(routesManifest: RouteTypesManifest): string { function generateRouteTypes(routesManifest: RouteTypesManifest): string {
const appRoutes = Object.keys(routesManifest.appRoutes).sort() const appRoutes = Object.keys(routesManifest.appRoutes).sort()
const pageRoutes = Object.keys(routesManifest.pageRoutes).sort() const pageRoutes = Object.keys(routesManifest.pageRoutes).sort()
...@@ -574,7 +611,7 @@ export function generateValidatorFile( ...@@ -574,7 +611,7 @@ export function generateValidatorFile(
default: (req: any, res: any) => ReturnType<NextApiHandler> default: (req: any, res: any) => ReturnType<NextApiHandler>
config?: { config?: {
api?: { api?: {
bodyParser?: boolean | { sizeLimit?: string } bodyParser?: boolean | { sizeLimit?: string | number }
responseLimit?: string | number | boolean responseLimit?: string | number | boolean
externalResolver?: boolean externalResolver?: boolean
} }
......
...@@ -38,34 +38,35 @@ describe('tsconfig module: preserve', () => { ...@@ -38,34 +38,35 @@ describe('tsconfig module: preserve', () => {
expect(output).not.toContain('resolveJsonModule') expect(output).not.toContain('resolveJsonModule')
expect(await next.readFile('tsconfig.json')).toMatchInlineSnapshot(` expect(await next.readFile('tsconfig.json')).toMatchInlineSnapshot(`
"{ "{
"compilerOptions": { "compilerOptions": {
"module": "preserve", "module": "preserve",
"target": "ES2017", "target": "ES2017",
"lib": [ "lib": [
"dom", "dom",
"dom.iterable", "dom.iterable",
"esnext" "esnext"
], ],
"allowJs": true, "allowJs": true,
"skipLibCheck": true, "skipLibCheck": true,
"strict": false, "strict": false,
"noEmit": true, "noEmit": true,
"incremental": true, "incremental": true,
"isolatedModules": true, "isolatedModules": true,
"jsx": "react-jsx" "jsx": "react-jsx"
}, },
"include": [ "include": [
"next-env.d.ts", ".next/types/**/*.ts",
"**/*.mts", ".next/dev/types/**/*.ts",
"**/*.ts", "**/*.mts",
"**/*.tsx" "**/*.ts",
], "**/*.tsx"
"exclude": [ ],
"node_modules" "exclude": [
] "node_modules"
} ]
" }
"
`) `)
}) })
}) })
...@@ -8,10 +8,15 @@ import { ...@@ -8,10 +8,15 @@ import {
launchApp, launchApp,
nextBuild, nextBuild,
killApp, killApp,
retry,
} from 'next-test-utils' } from 'next-test-utils'
const appDir = join(__dirname, '..') const appDir = join(__dirname, '..')
const nextConfig = join(appDir, 'next.config.js') const nextConfig = join(appDir, 'next.config.js')
// Dynamic types (image types, navigation compat) are now generated in .next/types/
// In dev mode with isolatedDevBuild (default), types are in .next/dev/types/
const dynamicTypesFileBuild = join(appDir, '.next/types/next-env.d.ts')
const dynamicTypesFileDev = join(appDir, '.next/dev/types/next-env.d.ts')
let appPort let appPort
let app let app
let output let output
...@@ -20,6 +25,14 @@ const handleOutput = (msg) => { ...@@ -20,6 +25,14 @@ const handleOutput = (msg) => {
output += msg output += msg
} }
// Helper to read dynamic types file with retry (file may be written async)
async function readDynamicTypesFile(isDev: boolean) {
const filePath = isDev ? dynamicTypesFileDev : dynamicTypesFileBuild
return retry(async () => {
return await fs.readFile(filePath, 'utf8')
})
}
describe('TypeScript Image Component', () => { describe('TypeScript Image Component', () => {
;(process.env.TURBOPACK_DEV ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode', 'production mode',
...@@ -29,10 +42,7 @@ describe('TypeScript Image Component', () => { ...@@ -29,10 +42,7 @@ describe('TypeScript Image Component', () => {
expect(stderr).toMatch(/Failed to compile/) expect(stderr).toMatch(/Failed to compile/)
expect(stderr).toMatch(/is not assignable to type/) expect(stderr).toMatch(/is not assignable to type/)
expect(code).toBe(1) expect(code).toBe(1)
const envTypes = await fs.readFile( const envTypes = await readDynamicTypesFile(false)
join(appDir, 'next-env.d.ts'),
'utf8'
)
expect(envTypes).toContain('image-types/global') expect(envTypes).toContain('image-types/global')
}) })
...@@ -47,10 +57,7 @@ describe('TypeScript Image Component', () => { ...@@ -47,10 +57,7 @@ describe('TypeScript Image Component', () => {
expect(stderr).toMatch(/is not assignable to type/) expect(stderr).toMatch(/is not assignable to type/)
expect(code).toBe(1) expect(code).toBe(1)
await fs.writeFile(nextConfig, content) await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile( const envTypes = await readDynamicTypesFile(false)
join(appDir, 'next-env.d.ts'),
'utf8'
)
expect(envTypes).not.toContain('image-types/global') expect(envTypes).not.toContain('image-types/global')
}) })
} }
...@@ -69,10 +76,7 @@ describe('TypeScript Image Component', () => { ...@@ -69,10 +76,7 @@ describe('TypeScript Image Component', () => {
afterAll(() => killApp(app)) afterAll(() => killApp(app))
it('should have image types when enabled', async () => { it('should have image types when enabled', async () => {
const envTypes = await fs.readFile( const envTypes = await readDynamicTypesFile(true)
join(appDir, 'next-env.d.ts'),
'utf8'
)
expect(envTypes).toContain('image-types/global') expect(envTypes).toContain('image-types/global')
}) })
...@@ -99,7 +103,7 @@ describe('TypeScript Image Component', () => { ...@@ -99,7 +103,7 @@ describe('TypeScript Image Component', () => {
const app = await launchApp(appDir, await findPort()) const app = await launchApp(appDir, await findPort())
await killApp(app) await killApp(app)
await fs.writeFile(nextConfig, content) await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8') const envTypes = await readDynamicTypesFile(true)
expect(envTypes).not.toContain('image-types/global') expect(envTypes).not.toContain('image-types/global')
}) })
}) })
......
...@@ -8,10 +8,15 @@ import { ...@@ -8,10 +8,15 @@ import {
launchApp, launchApp,
nextBuild, nextBuild,
killApp, killApp,
retry,
} from 'next-test-utils' } from 'next-test-utils'
const appDir = join(__dirname, '..') const appDir = join(__dirname, '..')
const nextConfig = join(appDir, 'next.config.js') const nextConfig = join(appDir, 'next.config.js')
// Dynamic types (image types, navigation compat) are now generated in .next/types/
// In dev mode with isolatedDevBuild (default), types are in .next/dev/types/
const dynamicTypesFileBuild = join(appDir, '.next/types/next-env.d.ts')
const dynamicTypesFileDev = join(appDir, '.next/dev/types/next-env.d.ts')
let appPort let appPort
let app let app
let output let output
...@@ -20,6 +25,14 @@ const handleOutput = (msg) => { ...@@ -20,6 +25,14 @@ const handleOutput = (msg) => {
output += msg output += msg
} }
// Helper to read dynamic types file with retry (file may be written async)
async function readDynamicTypesFile(isDev: boolean) {
const filePath = isDev ? dynamicTypesFileDev : dynamicTypesFileBuild
return retry(async () => {
return await fs.readFile(filePath, 'utf8')
})
}
describe('TypeScript Image Component', () => { describe('TypeScript Image Component', () => {
;(process.env.TURBOPACK_DEV ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode', 'production mode',
...@@ -29,10 +42,7 @@ describe('TypeScript Image Component', () => { ...@@ -29,10 +42,7 @@ describe('TypeScript Image Component', () => {
expect(stderr).toMatch(/Failed to compile/) expect(stderr).toMatch(/Failed to compile/)
expect(stderr).toMatch(/is not assignable to type/) expect(stderr).toMatch(/is not assignable to type/)
expect(code).toBe(1) expect(code).toBe(1)
const envTypes = await fs.readFile( const envTypes = await readDynamicTypesFile(false)
join(appDir, 'next-env.d.ts'),
'utf8'
)
expect(envTypes).toContain('image-types/global') expect(envTypes).toContain('image-types/global')
}) })
...@@ -47,10 +57,7 @@ describe('TypeScript Image Component', () => { ...@@ -47,10 +57,7 @@ describe('TypeScript Image Component', () => {
expect(stderr).toMatch(/is not assignable to type/) expect(stderr).toMatch(/is not assignable to type/)
expect(code).toBe(1) expect(code).toBe(1)
await fs.writeFile(nextConfig, content) await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile( const envTypes = await readDynamicTypesFile(false)
join(appDir, 'next-env.d.ts'),
'utf8'
)
expect(envTypes).not.toContain('image-types/global') expect(envTypes).not.toContain('image-types/global')
}) })
} }
...@@ -69,10 +76,7 @@ describe('TypeScript Image Component', () => { ...@@ -69,10 +76,7 @@ describe('TypeScript Image Component', () => {
afterAll(() => killApp(app)) afterAll(() => killApp(app))
it('should have image types when enabled', async () => { it('should have image types when enabled', async () => {
const envTypes = await fs.readFile( const envTypes = await readDynamicTypesFile(true)
join(appDir, 'next-env.d.ts'),
'utf8'
)
expect(envTypes).toContain('image-types/global') expect(envTypes).toContain('image-types/global')
}) })
...@@ -98,7 +102,7 @@ describe('TypeScript Image Component', () => { ...@@ -98,7 +102,7 @@ describe('TypeScript Image Component', () => {
const app = await launchApp(appDir, await findPort()) const app = await launchApp(appDir, await findPort())
await killApp(app) await killApp(app)
await fs.writeFile(nextConfig, content) await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8') const envTypes = await readDynamicTypesFile(true)
expect(envTypes).not.toContain('image-types/global') expect(envTypes).not.toContain('image-types/global')
}) })
}) })
...@@ -52,7 +52,6 @@ import path from 'path' ...@@ -52,7 +52,6 @@ import path from 'path'
"strictNullChecks": true "strictNullChecks": true
}, },
"include": [ "include": [
"next-env.d.ts",
".next/types/**/*.ts", ".next/types/**/*.ts",
".next/dev/types/**/*.ts", ".next/dev/types/**/*.ts",
"**/*.mts", "**/*.mts",
...@@ -109,7 +108,6 @@ import path from 'path' ...@@ -109,7 +108,6 @@ import path from 'path'
"strictNullChecks": true "strictNullChecks": true
}, },
"include": [ "include": [
"next-env.d.ts",
".next/types/**/*.ts", ".next/types/**/*.ts",
".next/dev/types/**/*.ts", ".next/dev/types/**/*.ts",
"**/*.mts", "**/*.mts",
...@@ -185,7 +183,6 @@ import path from 'path' ...@@ -185,7 +183,6 @@ import path from 'path'
// in-object comment 2 // in-object comment 2
, ,
"include": [ "include": [
"next-env.d.ts",
".next/types/**/*.ts", ".next/types/**/*.ts",
".next/dev/types/**/*.ts", ".next/dev/types/**/*.ts",
"**/*.mts", "**/*.mts",
...@@ -240,7 +237,6 @@ import path from 'path' ...@@ -240,7 +237,6 @@ import path from 'path'
"strictNullChecks": true "strictNullChecks": true
}, },
"include": [ "include": [
"next-env.d.ts",
".next/types/**/*.ts", ".next/types/**/*.ts",
".next/dev/types/**/*.ts", ".next/dev/types/**/*.ts",
"**/*.mts", "**/*.mts",
...@@ -294,7 +290,6 @@ import path from 'path' ...@@ -294,7 +290,6 @@ import path from 'path'
"strictNullChecks": true "strictNullChecks": true
}, },
"include": [ "include": [
"next-env.d.ts",
".next/types/**/*.ts", ".next/types/**/*.ts",
".next/dev/types/**/*.ts", ".next/dev/types/**/*.ts",
"**/*.mts", "**/*.mts",
...@@ -352,7 +347,6 @@ import path from 'path' ...@@ -352,7 +347,6 @@ import path from 'path'
"strictNullChecks": true "strictNullChecks": true
}, },
"include": [ "include": [
"next-env.d.ts",
".next/types/**/*.ts", ".next/types/**/*.ts",
".next/dev/types/**/*.ts", ".next/dev/types/**/*.ts",
"**/*.mts", "**/*.mts",
...@@ -410,7 +404,6 @@ import path from 'path' ...@@ -410,7 +404,6 @@ import path from 'path'
"strictNullChecks": true "strictNullChecks": true
}, },
"include": [ "include": [
"next-env.d.ts",
".next/types/**/*.ts", ".next/types/**/*.ts",
".next/dev/types/**/*.ts", ".next/dev/types/**/*.ts",
"**/*.mts", "**/*.mts",
...@@ -465,7 +458,6 @@ import path from 'path' ...@@ -465,7 +458,6 @@ import path from 'path'
"strictNullChecks": true "strictNullChecks": true
}, },
"include": [ "include": [
"next-env.d.ts",
".next/types/**/*.ts", ".next/types/**/*.ts",
".next/dev/types/**/*.ts", ".next/dev/types/**/*.ts",
"**/*.mts", "**/*.mts",
...@@ -523,7 +515,6 @@ import path from 'path' ...@@ -523,7 +515,6 @@ import path from 'path'
"strictNullChecks": true "strictNullChecks": true
}, },
"include": [ "include": [
"next-env.d.ts",
".next/types/**/*.ts", ".next/types/**/*.ts",
".next/dev/types/**/*.ts", ".next/dev/types/**/*.ts",
"**/*.mts", "**/*.mts",
...@@ -581,7 +572,6 @@ import path from 'path' ...@@ -581,7 +572,6 @@ import path from 'path'
"strictNullChecks": true "strictNullChecks": true
}, },
"include": [ "include": [
"next-env.d.ts",
".next/types/**/*.ts", ".next/types/**/*.ts",
".next/dev/types/**/*.ts", ".next/dev/types/**/*.ts",
"**/*.mts", "**/*.mts",
...@@ -629,7 +619,6 @@ import path from 'path' ...@@ -629,7 +619,6 @@ import path from 'path'
"strictNullChecks": true "strictNullChecks": true
}, },
"include": [ "include": [
"next-env.d.ts",
".next/types/**/*.ts", ".next/types/**/*.ts",
"**/*.mts", "**/*.mts",
"**/*.ts", "**/*.ts",
...@@ -688,7 +677,6 @@ import path from 'path' ...@@ -688,7 +677,6 @@ import path from 'path'
"strictNullChecks": true "strictNullChecks": true
}, },
"include": [ "include": [
"next-env.d.ts",
".next/types/**/*.ts", ".next/types/**/*.ts",
"**/*.mts", "**/*.mts",
"**/*.ts", "**/*.ts",
...@@ -750,7 +738,6 @@ import path from 'path' ...@@ -750,7 +738,6 @@ import path from 'path'
"strictNullChecks": true "strictNullChecks": true
}, },
"include": [ "include": [
"next-env.d.ts",
".next/types/**/*.ts", ".next/types/**/*.ts",
"**/*.mts", "**/*.mts",
"**/*.ts", "**/*.ts",
...@@ -821,7 +808,6 @@ import path from 'path' ...@@ -821,7 +808,6 @@ import path from 'path'
"strictNullChecks": true "strictNullChecks": true
}, },
"include": [ "include": [
"next-env.d.ts",
".next/types/**/*.ts", ".next/types/**/*.ts",
"**/*.ts", "**/*.ts",
"**/*.tsx" "**/*.tsx"
......
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
...@@ -5,53 +5,61 @@ import { findPort, launchApp, killApp } from 'next-test-utils' ...@@ -5,53 +5,61 @@ import { findPort, launchApp, killApp } from 'next-test-utils'
import { promises as fs } from 'fs' import { promises as fs } from 'fs'
const appDir = join(__dirname, '..') const appDir = join(__dirname, '..')
const appTypeDeclarations = join(appDir, 'next-env.d.ts') const rootTypeDeclarations = join(appDir, 'next-env.d.ts')
const distTypeDeclarations = join(appDir, '.next/dev/types/next-env.d.ts')
describe('TypeScript App Type Declarations', () => { describe('TypeScript App Type Declarations', () => {
it('should write a new next-env.d.ts if none exist', async () => { it('should not create next-env.d.ts in project root', async () => {
const prevContent = await fs.readFile(appTypeDeclarations, 'utf8') // Ensure no next-env.d.ts exists before starting
try { try {
await fs.unlink(appTypeDeclarations) await fs.unlink(rootTypeDeclarations)
const appPort = await findPort() } catch {
let app // File doesn't exist, which is fine
try { }
app = await launchApp(appDir, appPort, {})
const content = await fs.readFile(appTypeDeclarations, 'utf8') const appPort = await findPort()
expect(content).toEqual(prevContent) let app
} finally { try {
await killApp(app) app = await launchApp(appDir, appPort, {})
} // Verify next-env.d.ts was NOT created in project root
await expect(fs.access(rootTypeDeclarations)).rejects.toThrow()
} finally { } finally {
await fs.writeFile(appTypeDeclarations, prevContent) await killApp(app)
} }
}) })
it('should overwrite next-env.d.ts if an incorrect one exists', async () => { it('should not modify existing next-env.d.ts in project root', async () => {
const prevContent = await fs.readFile(appTypeDeclarations, 'utf8') const existingContent = '// custom next-env.d.ts content\n'
await fs.writeFile(rootTypeDeclarations, existingContent)
const prevStat = await fs.stat(rootTypeDeclarations)
const appPort = await findPort()
let app
try { try {
await fs.writeFile(appTypeDeclarations, prevContent + 'modification') app = await launchApp(appDir, appPort, {})
const appPort = await findPort() // Verify next-env.d.ts was NOT modified
let app const stat = await fs.stat(rootTypeDeclarations)
try { expect(stat.mtime).toEqual(prevStat.mtime)
app = await launchApp(appDir, appPort, {}) const content = await fs.readFile(rootTypeDeclarations, 'utf8')
const content = await fs.readFile(appTypeDeclarations, 'utf8') expect(content).toEqual(existingContent)
expect(content).toEqual(prevContent)
} finally {
await killApp(app)
}
} finally { } finally {
await fs.writeFile(appTypeDeclarations, prevContent) await killApp(app)
// Clean up
await fs.unlink(rootTypeDeclarations).catch(() => {})
} }
}) })
it('should not touch an existing correct next-env.d.ts', async () => { it('should generate next-env.d.ts in .next/types', async () => {
const prevStat = await fs.stat(appTypeDeclarations) // Clean up any existing .next directory
await fs.rm(join(appDir, '.next'), { recursive: true, force: true })
const appPort = await findPort() const appPort = await findPort()
let app let app
try { try {
app = await launchApp(appDir, appPort, {}) app = await launchApp(appDir, appPort, {})
const stat = await fs.stat(appTypeDeclarations) // Verify next-env.d.ts was generated in .next/types
expect(stat.mtime).toEqual(prevStat.mtime) const content = await fs.readFile(distTypeDeclarations, 'utf8')
expect(content).toContain('/// <reference types="next" />')
} finally { } finally {
await killApp(app) await killApp(app)
} }
......
...@@ -17,5 +17,10 @@ ...@@ -17,5 +17,10 @@
"isolatedModules": true "isolatedModules": true
}, },
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"], "exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"],
"include": ["next-env.d.ts", "components", "pages"] "include": [
"components",
"pages",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
]
} }
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information. // see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
...@@ -22,6 +22,6 @@ ...@@ -22,6 +22,6 @@
"@/*": ["./*"] "@/*": ["./*"]
} }
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "include": ["**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }
...@@ -19994,17 +19994,6 @@ ...@@ -19994,17 +19994,6 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/integration/typescript-app-type-declarations/test/index.test.ts": {
"passed": [
"TypeScript App Type Declarations should not touch an existing correct next-env.d.ts",
"TypeScript App Type Declarations should overwrite next-env.d.ts if an incorrect one exists",
"TypeScript App Type Declarations should write a new next-env.d.ts if none exist"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/integration/typescript-baseurl/test/index.test.ts": { "test/integration/typescript-baseurl/test/index.test.ts": {
"passed": ["TypeScript Features default behavior should render the page"], "passed": ["TypeScript Features default behavior should render the page"],
"failed": [], "failed": [],
...@@ -22109,5 +22098,16 @@ ...@@ -22109,5 +22098,16 @@
"pending": [], "pending": [],
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
},
"test/integration/typescript-app-type-declarations/test/index.test.ts": {
"passed": [
"TypeScript App Type Declarations should not create next-env.d.ts in project root",
"TypeScript App Type Declarations should not modify existing next-env.d.ts in project root",
"TypeScript App Type Declarations should overwrite next-env.d.ts in .next/types if incorrect"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
} }
} }
...@@ -21995,17 +21995,6 @@ ...@@ -21995,17 +21995,6 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/integration/typescript-app-type-declarations/test/index.test.ts": {
"passed": [
"TypeScript App Type Declarations should not touch an existing correct next-env.d.ts",
"TypeScript App Type Declarations should overwrite next-env.d.ts if an incorrect one exists",
"TypeScript App Type Declarations should write a new next-env.d.ts if none exist"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/integration/typescript-baseurl/test/index.test.ts": { "test/integration/typescript-baseurl/test/index.test.ts": {
"passed": ["TypeScript Features default behavior should render the page"], "passed": ["TypeScript Features default behavior should render the page"],
"failed": [], "failed": [],
...@@ -22199,5 +22188,16 @@ ...@@ -22199,5 +22188,16 @@
], ],
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
},
"test/integration/typescript-app-type-declarations/test/index.test.ts": {
"passed": [
"TypeScript App Type Declarations should not create next-env.d.ts in project root",
"TypeScript App Type Declarations should not modify existing next-env.d.ts in project root",
"TypeScript App Type Declarations should overwrite next-env.d.ts in .next/types if incorrect"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
} }
} }
...@@ -17865,17 +17865,6 @@ ...@@ -17865,17 +17865,6 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/integration/typescript-app-type-declarations/test/index.test.ts": {
"passed": [
"TypeScript App Type Declarations should not touch an existing correct next-env.d.ts",
"TypeScript App Type Declarations should overwrite next-env.d.ts if an incorrect one exists",
"TypeScript App Type Declarations should write a new next-env.d.ts if none exist"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/integration/typescript-baseurl/test/index.test.ts": { "test/integration/typescript-baseurl/test/index.test.ts": {
"passed": ["TypeScript Features default behavior should render the page"], "passed": ["TypeScript Features default behavior should render the page"],
"failed": [], "failed": [],
...@@ -19631,5 +19620,16 @@ ...@@ -19631,5 +19620,16 @@
"pending": [], "pending": [],
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
},
"test/integration/typescript-app-type-declarations/test/index.test.ts": {
"passed": [
"TypeScript App Type Declarations should not create next-env.d.ts in project root",
"TypeScript App Type Declarations should not modify existing next-env.d.ts in project root",
"TypeScript App Type Declarations should overwrite next-env.d.ts in .next/types if incorrect"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
} }
} }
...@@ -21395,17 +21395,6 @@ ...@@ -21395,17 +21395,6 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/integration/typescript-app-type-declarations/test/index.test.ts": {
"passed": [
"TypeScript App Type Declarations should not touch an existing correct next-env.d.ts",
"TypeScript App Type Declarations should overwrite next-env.d.ts if an incorrect one exists",
"TypeScript App Type Declarations should write a new next-env.d.ts if none exist"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/integration/typescript-baseurl/test/index.test.ts": { "test/integration/typescript-baseurl/test/index.test.ts": {
"passed": ["TypeScript Features default behavior should render the page"], "passed": ["TypeScript Features default behavior should render the page"],
"failed": [], "failed": [],
...@@ -21636,5 +21625,16 @@ ...@@ -21636,5 +21625,16 @@
], ],
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
},
"test/integration/typescript-app-type-declarations/test/index.test.ts": {
"passed": [
"TypeScript App Type Declarations should not create next-env.d.ts in project root",
"TypeScript App Type Declarations should not modify existing next-env.d.ts in project root",
"TypeScript App Type Declarations should overwrite next-env.d.ts in .next/types if incorrect"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
} }
} }
/* eslint-env jest */
import os from 'os'
import fs from 'fs-extra'
import { join } from 'path'
import { writeAppTypeDeclarations } from 'next/dist/lib/typescript/writeAppTypeDeclarations'
const fixtureDir = join(__dirname, 'fixtures/app-declarations')
const declarationFile = join(fixtureDir, 'next-env.d.ts')
const imageImportsEnabled = false
describe('find config', () => {
beforeEach(async () => {
await fs.ensureDir(fixtureDir)
})
afterEach(() => fs.remove(declarationFile))
it('should preserve CRLF EOL', async () => {
const eol = '\r\n'
const content =
'/// <reference types="next" />' +
eol +
(imageImportsEnabled
? '/// <reference types="next/image-types/global" />' + eol
: '') +
`import "./.next/types/routes.d.ts";` +
eol +
eol +
'// NOTE: This file should not be edited' +
eol +
'// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.' +
eol
await fs.writeFile(declarationFile, content)
await writeAppTypeDeclarations({
baseDir: fixtureDir,
distDir: '.next',
imageImportsEnabled,
hasPagesDir: false,
hasAppDir: false,
})
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
})
it('should preserve LF EOL', async () => {
const eol = '\n'
const content =
'/// <reference types="next" />' +
eol +
(imageImportsEnabled
? '/// <reference types="next/image-types/global" />' + eol
: '') +
`import "./.next/types/routes.d.ts";` +
eol +
eol +
'// NOTE: This file should not be edited' +
eol +
'// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.' +
eol
await fs.writeFile(declarationFile, content)
await writeAppTypeDeclarations({
baseDir: fixtureDir,
distDir: '.next',
imageImportsEnabled,
hasPagesDir: false,
hasAppDir: false,
})
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
})
it('should use OS EOL by default', async () => {
const eol = os.EOL
const content =
'/// <reference types="next" />' +
eol +
(imageImportsEnabled
? '/// <reference types="next/image-types/global" />' + eol
: '') +
`import "./.next/types/routes.d.ts";` +
eol +
eol +
'// NOTE: This file should not be edited' +
eol +
'// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.' +
eol
await writeAppTypeDeclarations({
baseDir: fixtureDir,
distDir: '.next',
imageImportsEnabled,
hasPagesDir: false,
hasAppDir: false,
})
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
})
it('should include navigation types if app directory is enabled', async () => {
await writeAppTypeDeclarations({
baseDir: fixtureDir,
distDir: '.next',
imageImportsEnabled,
hasPagesDir: false,
hasAppDir: true,
})
await expect(fs.readFile(declarationFile, 'utf8')).resolves.not.toContain(
'next/navigation-types/compat/navigation'
)
await writeAppTypeDeclarations({
baseDir: fixtureDir,
distDir: '.next',
imageImportsEnabled,
hasPagesDir: true,
hasAppDir: true,
})
await expect(fs.readFile(declarationFile, 'utf8')).resolves.toContain(
'next/navigation-types/compat/navigation'
)
})
})
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