Unverified Commit 1faf0323 authored by Ben Gubler's avatar Ben Gubler Committed by GitHub

feat: Turbopack typed links (#81528)

# Typed Links: Turbopack support

This PR replaces the old `experimental.typedRoutes` implementation with
a new approach that works on both Turbopack and Webpack.

_Note: a previous version of this PR contained new props for the `Link`
component: `path`, `params`, and `searchParams`. In the interest of
bringing typed links support to Turbopack as soon as possible, I've
removed that change from this PR and will create a new one later._
parent a4661042
......@@ -1316,7 +1316,11 @@ export default async function build(
rewrites: config.rewrites,
})
await writeRouteTypesManifest(routeTypesManifest, routeTypesFilePath)
await writeRouteTypesManifest(
routeTypesManifest,
routeTypesFilePath,
config
)
})
// Turbopack already handles conflicting app and page routes.
......
......@@ -389,7 +389,6 @@ export default async function getBaseWebpackConfig(
const hasAppDir = !!appDir
const disableOptimizedLoading = true
const enableTypedRoutes = !!config.experimental.typedRoutes && hasAppDir
const bundledReactChannel = needsExperimentalReact(config)
? '-experimental'
: ''
......@@ -2152,7 +2151,6 @@ export default async function getBaseWebpackConfig(
dev,
isEdgeServer,
pageExtensions: config.pageExtensions,
typedRoutes: enableTypedRoutes,
cacheLifeConfig: config.experimental.cacheLife,
originalRewrites,
originalRedirects,
......
......@@ -11,7 +11,6 @@ describe('next-types-plugin', () => {
dev: false,
isEdgeServer: false,
pageExtensions: ['tsx', 'ts', 'jsx', 'js'],
typedRoutes: false,
cacheLifeConfig: undefined,
originalRewrites: undefined,
originalRedirects: undefined,
......@@ -40,7 +39,6 @@ describe('next-types-plugin', () => {
dev: false,
isEdgeServer: false,
pageExtensions: ['tsx', 'ts', 'jsx', 'js'],
typedRoutes: false,
cacheLifeConfig: undefined,
originalRewrites: undefined,
originalRedirects: undefined,
......@@ -61,7 +59,6 @@ describe('next-types-plugin', () => {
dev: false,
isEdgeServer: false,
pageExtensions: ['tsx', 'ts', 'jsx', 'js'],
typedRoutes: false,
cacheLifeConfig: undefined,
originalRewrites: undefined,
originalRedirects: undefined,
......
......@@ -129,7 +129,11 @@ const nextTypegen = async (
rewrites: nextConfig.rewrites,
})
await writeRouteTypesManifest(routeTypesManifest, routeTypesFilePath)
await writeRouteTypesManifest(
routeTypesManifest,
routeTypesFilePath,
nextConfig
)
console.log('✓ Route types generated successfully')
}
......
......@@ -35,7 +35,6 @@ const unsupportedTurbopackNextConfigOptions = [
'experimental.sri.algorithm',
'experimental.swcTraceProfiling',
'experimental.typedRoutes',
// Left to be implemented (Might not be needed for Turbopack)
'experimental.craCompat',
......
......@@ -6,7 +6,7 @@ import {
import type { NextConfigComplete } from '../../config-shared'
import { isParallelRouteSegment } from '../../../shared/lib/segment'
import fs from 'fs'
import { generateRouteTypesFile } from './typegen'
import { generateRouteTypesFile, generateLinkTypesFile } from './typegen'
import { tryToParsePath } from '../../../lib/try-to-parse-path'
interface RouteInfo {
......@@ -27,46 +27,71 @@ export interface RouteTypesManifest {
// Convert a custom-route source string (`/blog/:slug`, `/docs/:path*`, ...)
// into the bracket-syntax used by other Next.js route helpers so that we can
// reuse `getRouteRegex()` to extract groups.
export function convertCustomRouteSource(source: string): string {
export function convertCustomRouteSource(source: string): string[] {
const parseResult = tryToParsePath(source)
if (parseResult.error || !parseResult.tokens) {
// Fallback to original source if parsing fails
return source.startsWith('/') ? source : '/' + source
return source.startsWith('/') ? [source] : ['/' + source]
}
let result = ''
const possibleNormalizedRoutes = ['']
let slugCnt = 1
function append(suffix: string) {
for (let i = 0; i < possibleNormalizedRoutes.length; i++) {
possibleNormalizedRoutes[i] += suffix
}
}
function fork(suffix: string) {
const currentLength = possibleNormalizedRoutes.length
for (let i = 0; i < currentLength; i++) {
possibleNormalizedRoutes.push(possibleNormalizedRoutes[i] + suffix)
}
}
for (const token of parseResult.tokens) {
if (typeof token === 'string') {
// Literal path segment
result += token
} else {
// Parameter token
const { name, modifier, prefix } = token
// Add the prefix (usually '/')
result += prefix
if (modifier === '*') {
// Catch-all zero or more: :param* -> [[...param]]
result += `[[...${name}]]`
} else if (modifier === '+') {
// Catch-all one or more: :param+ -> [...param]
result += `[...${name}]`
} else if (modifier === '?') {
// Optional catch-all: :param? -> [[...param]]
result += `[[...${name}]]`
} else {
// Standard dynamic segment: :param -> [param]
result += `[${name}]`
if (typeof token === 'object') {
// Make sure the slug is always named.
const slug = token.name || (slugCnt++ === 1 ? 'slug' : `slug${slugCnt}`)
if (token.modifier === '*') {
append(`${token.prefix}[[...${slug}]]`)
} else if (token.modifier === '+') {
append(`${token.prefix}[...${slug}]`)
} else if (token.modifier === '') {
if (token.pattern === '[^\\/#\\?]+?') {
// A safe slug
append(`${token.prefix}[${slug}]`)
} else if (token.pattern === '.*') {
// An optional catch-all slug
append(`${token.prefix}[[...${slug}]]`)
} else if (token.pattern === '.+') {
// A catch-all slug
append(`${token.prefix}[...${slug}]`)
} else {
// Other regex patterns are not supported. Skip this route.
return []
}
} else if (token.modifier === '?') {
if (/^[a-zA-Z0-9_/]*$/.test(token.pattern)) {
// An optional slug with plain text only, fork the route.
append(token.prefix)
fork(token.pattern)
} else {
// Optional modifier `?` and regex patterns are not supported.
return []
}
}
} else if (typeof token === 'string') {
append(token)
}
}
// Ensure leading slash
if (!result.startsWith('/')) result = '/' + result
return result
return possibleNormalizedRoutes.map((route) =>
route.startsWith('/') ? route : '/' + route
)
}
/**
......@@ -165,11 +190,12 @@ export async function createRouteTypesManifest({
const rd = await redirects()
for (const item of rd) {
const source = convertCustomRouteSource(item.source)
manifest.redirectRoutes[source] = {
path: source,
groups: extractRouteParams(source),
const possibleRoutes = convertCustomRouteSource(item.source)
for (const route of possibleRoutes) {
manifest.redirectRoutes[route] = {
path: route,
groups: extractRouteParams(route),
}
}
}
}
......@@ -187,10 +213,12 @@ export async function createRouteTypesManifest({
]
for (const item of allSources) {
const source = convertCustomRouteSource(item.source)
manifest.rewriteRoutes[source] = {
path: source,
groups: extractRouteParams(source),
const possibleRoutes = convertCustomRouteSource(item.source)
for (const route of possibleRoutes) {
manifest.rewriteRoutes[route] = {
path: route,
groups: extractRouteParams(route),
}
}
}
}
......@@ -200,7 +228,8 @@ export async function createRouteTypesManifest({
export async function writeRouteTypesManifest(
manifest: RouteTypesManifest,
filePath: string
filePath: string,
config: NextConfigComplete
) {
const dirname = path.dirname(filePath)
......@@ -208,5 +237,12 @@ export async function writeRouteTypesManifest(
await fs.promises.mkdir(dirname, { recursive: true })
}
// Write the main routes.d.ts file
await fs.promises.writeFile(filePath, generateRouteTypesFile(manifest))
// Write the link.d.ts file if typedRoutes is enabled
if (config.experimental?.typedRoutes === true) {
const linkTypesPath = path.join(dirname, 'link.d.ts')
await fs.promises.writeFile(linkTypesPath, generateLinkTypesFile(manifest))
}
}
......@@ -222,7 +222,8 @@ async function startWatcher(
redirectRoutes: {},
rewriteRoutes: {},
},
path.join(distTypesDir, 'routes.d.ts')
path.join(distTypesDir, 'routes.d.ts'),
opts.nextConfig
)
const usingTypeScript = await verifyTypeScript(opts)
......@@ -1023,7 +1024,11 @@ async function startWatcher(
rewrites: opts.nextConfig.rewrites,
})
await writeRouteTypesManifest(routeTypesManifest, routeTypesFilePath)
await writeRouteTypesManifest(
routeTypesManifest,
routeTypesFilePath,
opts.nextConfig
)
}
if (!resolved) {
......
......@@ -136,6 +136,210 @@ function generateLayoutSlotMap(routesManifest: RouteTypesManifest): string {
return slotMap
}
// Helper function to format routes to route types (matches the plugin logic exactly)
function formatRouteToRouteType(route: string) {
const isDynamic = isDynamicRoute(route)
if (isDynamic) {
route = route
.split('/')
.map((part) => {
if (part.startsWith('[') && part.endsWith(']')) {
if (part.startsWith('[...')) {
// /[...slug]
return `\${CatchAllSlug<T>}`
} else if (part.startsWith('[[...') && part.endsWith(']]')) {
// /[[...slug]]
return `\${OptionalCatchAllSlug<T>}`
}
// /[slug]
return `\${SafeSlug<T>}`
}
return part
})
.join('/')
}
return {
isDynamic,
routeType: route,
}
}
// Helper function to serialize route types (matches the plugin logic exactly)
function serializeRouteTypes(routeTypes: string[]) {
// route collection is not deterministic, this makes the output of the file deterministic
return routeTypes
.sort()
.map((route) => `\n | \`${route}\``)
.join('')
}
export function generateLinkTypesFile(
routesManifest: RouteTypesManifest
): string {
// Generate serialized static and dynamic routes for the internal namespace
const allRoutes = {
...routesManifest.appRoutes,
...routesManifest.pageRoutes,
...routesManifest.redirectRoutes,
...routesManifest.rewriteRoutes,
}
const staticRouteTypes: string[] = []
const dynamicRouteTypes: string[] = []
// Process each route using the same logic as the plugin
for (const route of Object.keys(allRoutes)) {
const { isDynamic, routeType } = formatRouteToRouteType(route)
if (isDynamic) {
dynamicRouteTypes.push(routeType)
} else {
staticRouteTypes.push(routeType)
}
}
const serializedStaticRouteTypes = serializeRouteTypes(staticRouteTypes)
const serializedDynamicRouteTypes = serializeRouteTypes(dynamicRouteTypes)
// If both StaticRoutes and DynamicRoutes are empty, fallback to type 'string & {}'.
const routeTypesFallback =
!serializedStaticRouteTypes && !serializedDynamicRouteTypes
? 'string & {}'
: ''
return `// This file is generated automatically by Next.js
// Do not edit this file manually
// Type definitions for Next.js routes
/**
* Internal types used by the Next.js router and Link component.
* These types are not meant to be used directly.
* @internal
*/
declare namespace __next_route_internal_types__ {
type SearchOrHash = \`?\${string}\` | \`#\${string}\`
type WithProtocol = \`\${string}:\${string}\`
type Suffix = '' | SearchOrHash
type SafeSlug<S extends string> = S extends \`\${string}/\${string}\`
? never
: S extends \`\${string}\${SearchOrHash}\`
? never
: S extends ''
? never
: S
type CatchAllSlug<S extends string> = S extends \`\${string}\${SearchOrHash}\`
? never
: S extends ''
? never
: S
type OptionalCatchAllSlug<S extends string> =
S extends \`\${string}\${SearchOrHash}\` ? never : S
type StaticRoutes = ${serializedStaticRouteTypes || 'never'}
type DynamicRoutes<T extends string = string> = ${
serializedDynamicRouteTypes || 'never'
}
type RouteImpl<T> = ${
routeTypesFallback ||
`
${
// This keeps autocompletion working for static routes.
'| StaticRoutes'
}
| SearchOrHash
| WithProtocol
| \`\${StaticRoutes}\${SearchOrHash}\`
| (T extends \`\${DynamicRoutes<infer _>}\${Suffix}\` ? T : never)
`
}
}
declare module 'next' {
export { default } from 'next/types.js'
export * from 'next/types.js'
export type Route<T extends string = string> =
__next_route_internal_types__.RouteImpl<T>
}
declare module 'next/link' {
import type { LinkProps as OriginalLinkProps } from 'next/dist/client/link.js'
import type { AnchorHTMLAttributes, DetailedHTMLProps } from 'react'
import type { UrlObject } from 'url'
type LinkRestProps = Omit<
Omit<
DetailedHTMLProps<
AnchorHTMLAttributes<HTMLAnchorElement>,
HTMLAnchorElement
>,
keyof OriginalLinkProps
> &
OriginalLinkProps,
'href'
>
export type LinkProps<RouteInferType> = LinkRestProps & {
/**
* The path or URL to navigate to. This is the only required prop. It can also be an object.
* @see https://nextjs.org/docs/api-reference/next/link
*/
href: __next_route_internal_types__.RouteImpl<RouteInferType> | UrlObject
}
export default function Link<RouteType>(props: LinkProps<RouteType>): JSX.Element
}
declare module 'next/navigation' {
export * from 'next/dist/client/components/navigation.js'
import type { NavigateOptions, AppRouterInstance as OriginalAppRouterInstance } from 'next/dist/shared/lib/app-router-context.shared-runtime.js'
interface AppRouterInstance extends OriginalAppRouterInstance {
/**
* Navigate to the provided href.
* Pushes a new history entry.
*/
push<RouteType>(href: __next_route_internal_types__.RouteImpl<RouteType>, options?: NavigateOptions): void
/**
* Navigate to the provided href.
* Replaces the current history entry.
*/
replace<RouteType>(href: __next_route_internal_types__.RouteImpl<RouteType>, options?: NavigateOptions): void
/**
* Prefetch the provided href.
*/
prefetch<RouteType>(href: __next_route_internal_types__.RouteImpl<RouteType>): void
}
export function useRouter(): AppRouterInstance;
}
declare module 'next/form' {
import type { FormProps as OriginalFormProps } from 'next/dist/client/form.js'
type FormRestProps = Omit<OriginalFormProps, 'action'>
export type FormProps<RouteInferType> = {
/**
* \`action\` can be either a \`string\` or a function.
* - If \`action\` is a string, it will be interpreted as a path or URL to navigate to when the form is submitted.
* The path will be prefetched when the form becomes visible.
* - If \`action\` is a function, it will be called when the form is submitted. See the [React docs](https://react.dev/reference/react-dom/components/form#props) for more.
*/
action: __next_route_internal_types__.RouteImpl<RouteInferType> | ((formData: FormData) => void)
} & FormRestProps
export default function Form<RouteType>(props: FormProps<RouteType>): JSX.Element
}
`
}
export function generateRouteTypesFile(
routesManifest: RouteTypesManifest
): string {
......
import Link from 'next/link'
export default function Page() {
return <p>hello world</p>
return (
<div>
<p>hello world</p>
<div>
<Link href="/">Simple Route</Link>
<Link href="/dashboard">Simple Route</Link>
<Link href="/project/123">Dynamic Route</Link>
<Link href="/gallery/photo/some-slug">Dynamic Route</Link>
<Link href="/_shop/">Optional Catchall Route</Link>
<Link href="/docs/some/thing">Catchall Route</Link>
<Link href="/api-legacy/v1/testing">Rewrite Route</Link>
<Link href="/blog/category/testing">Redirect Route</Link>
</div>
</div>
)
}
......@@ -2,6 +2,9 @@
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
typedRoutes: true,
},
async redirects() {
return [
{
......@@ -14,11 +17,6 @@ const nextConfig = {
destination: '/posts/:category/:slug*',
permanent: false,
},
{
source: '/optional/:param?',
destination: '/fallback',
permanent: false,
},
]
},
async rewrites() {
......
import { nextTestSetup } from 'e2e-utils'
describe('typed-links', () => {
const { next, isNextStart, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should generate types for next/link', async () => {
const dts = await next.readFile('.next/types/link.d.ts')
expect(dts).toContain(`declare module 'next/link'`)
})
if (isNextStart) {
it('should pass type checking with valid routes', async () => {
await next.stop()
await next.patchFile(
'app/valid-links.tsx',
`
import Link from 'next/link'
export default function ValidLinks() {
return (
<div>
<Link href="/">Simple Route</Link>
<Link href="/dashboard">Simple Route</Link>
<Link href="/project/123">Dynamic Route</Link>
<Link href="/gallery/photo/some-slug">Dynamic Route</Link>
<Link href="/_shop/">Optional Catchall Route</Link>
<Link href="/docs/some/thing">Catchall Route</Link>
<Link href="/api-legacy/v1/testing">Rewrite Route</Link>
<Link href="/blog/category/testing">Redirect Route</Link>
</div>
)
}
`
)
const { exitCode } = await next.build()
expect(exitCode).toBe(0)
})
it('should work with Route type casting', async () => {
await next.stop()
await next.patchFile(
'app/route-casting.tsx',
`
import type { Route } from 'next'
import Link from 'next/link'
export default function RouteCasting() {
const dynamicPath = '/dynamic-path'
return (
<Link href={dynamicPath as Route}>Casted Route</Link>
)
}
`
)
const { exitCode } = await next.build()
expect(exitCode).toBe(0)
})
it('should fail type checking with invalid routes', async () => {
await next.stop()
await next.patchFile(
'app/invalid-links.tsx',
`
import Link from 'next/link'
export default function InvalidLinks() {
return (
<div>
<Link href="/invalid-route">Invalid</Link>
</div>
)
}
`
)
const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1)
expect(cliOutput).toContain(
`Type error: "/invalid-route" is not an existing route. If it is intentional, please type it explicitly with \`as Route\`.`
)
})
}
})
......@@ -4,7 +4,7 @@ const expectedDts = `
type AppRoutes = "/" | "/_shop/[[...category]]" | "/dashboard" | "/dashboard/settings" | "/docs/[...slug]" | "/gallery/photo/[id]" | "/project/[slug]"
type PageRoutes = "/about" | "/users/[id]"
type LayoutRoutes = "/" | "/dashboard"
type RedirectRoutes = "/blog/[category]/[[...slug]]" | "/optional/[[...param]]" | "/project/[slug]"
type RedirectRoutes = "/blog/[category]/[[...slug]]" | "/project/[slug]"
type RewriteRoutes = "/api-legacy/[version]/[[...endpoint]]" | "/docs-old/[...path]"
type Routes = AppRoutes | PageRoutes | LayoutRoutes | RedirectRoutes | RewriteRoutes
`
......@@ -36,9 +36,6 @@ describe('typed-routes', () => {
// Test catch-all zero-or-more: :slug* -> [[...slug]]
expect(dts).toContain('"/blog/[category]/[[...slug]]"')
expect(dts).toContain('"/api-legacy/[version]/[[...endpoint]]"')
// Test optional parameter: :param? -> [[...param]]
expect(dts).toContain('"/optional/[[...param]]"')
})
if (isNextDev) {
......
......@@ -7,125 +7,116 @@ import { nextBuild } from 'next-test-utils'
const appDir = __dirname
// Turbopack doesn't support additional experimental features in the first version
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'app type checking',
() => {
;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode',
() => {
let stderr, errors
beforeAll(async () => {
stderr = (await nextBuild(appDir, [], { stderr: true })).stderr
errors = stderr.match(
/===== TS errors =====(.+)===== TS errors =====/s
)?.[1]
})
it('should generate route types correctly and report link error', async () => {
// Make sure the d.ts file is generated
const dts = (
await fs.readFile(path.join(appDir, '.next', 'types', 'link.d.ts'))
).toString()
expect(dts.includes('`/dashboard/user/')).toBeTruthy()
expect(dts.includes('`/dashboard/another')).toBeTruthy()
// Check type checking errors
expect(errors).toContain(
'Type error: "/(newroot)/dashboard/another" is not an existing route. If it is intentional, please type it explicitly with `as Route`.'
)
// Make sure all errors were reported and other links passed type checking
const errorLines = [
...errors.matchAll(
/\.\/src\/app\/type-checks\/link\/page\.tsx:(\d+):/g
),
].map(([, line]) => +line)
const ST = 18
const ED = 35
expect(errorLines).toEqual(
Array.from({ length: ED - ST + 1 }, (_, i) => i + ST)
)
})
it('should generate route types correctly and report router API errors', async () => {
// Make sure all errors were reported and other links passed type checking
const errorLines = [
...errors.matchAll(
/\.\/src\/app\/type-checks\/router\/page\.tsx:(\d+):/g
),
].map(([, line]) => +line)
const ST = 11
const ED = 13
expect(errorLines).toEqual(
Array.from({ length: ED - ST + 1 }, (_, i) => i + ST)
)
})
it('should generate route types correctly and report form errors', async () => {
// Make sure all errors were reported and other Forms passed type checking
const errorLines = [
...errors.matchAll(
/\.\/src\/app\/type-checks\/form\/page\.tsx:(\d+):/g
),
].map(([, line]) => +line)
const ST = 8
const ED = 10
expect(errorLines).toEqual(
Array.from({ length: ED - ST + 1 }, (_, i) => i + ST)
)
})
it('should type check invalid entry exports', () => {
// Can't export arbitrary things.
expect(errors).toContain(`"foo" is not a valid Page export field.`)
// Can't export invalid fields.
expect(errors).toMatch(
/Invalid configuration "revalidate":\s+Expected "false | number (>= 0)", got "-1"/
)
// Avoid invalid argument types for exported functions.
expect(errors).toMatch(
/Page "src\/app\/type-checks\/config\/page\.tsx" has an invalid "default" export:\s+Type "{ foo: string; }" is not valid/
)
expect(errors).toMatch(
/Page "src\/app\/type-checks\/config\/page\.tsx" has an invalid "generateMetadata" export:\s+Type "{ s: number; }" is not valid/
)
expect(errors).toMatch(
/Page "src\/app\/type-checks\/config\/page\.tsx" has an invalid "generateStaticParams" export:\s+Type "string" is not valid/
)
// Avoid invalid return types for exported functions.
expect(errors).toContain(
`"Promise<number>" is not a valid generateStaticParams return type`
)
// Can't export arbitrary things.
expect(errors).toContain(`"bar" is not a valid Route export field.`)
// Can't export invalid fields.
expect(errors).toMatch(
/Invalid configuration "revalidate":\s+Expected "false | number (>= 0)", got "-1"/
)
// Avoid invalid argument types for exported functions.
expect(errors).toMatch(
/Route "src\/app\/type-checks\/route-handlers\/route\.ts" has an invalid "GET" export:\s+Type "boolean" is not a valid type for the function's first argument/
)
expect(errors).toMatch(
/Route "src\/app\/type-checks\/route-handlers\/route\.ts" has an invalid "generateStaticParams" export:\s+Type "string" is not valid/
)
// Avoid invalid return types for exported functions.
expect(errors).toContain(
`"Promise<boolean>" is not a valid generateStaticParams return type`
)
})
}
describe('app type checking - production mode', () => {
let stderr, errors
beforeAll(async () => {
stderr = (await nextBuild(appDir, [], { stderr: true })).stderr
errors = stderr.match(
/===== TS errors =====(.+)===== TS errors =====/s
)?.[1]
})
it('should report link errors', async () => {
// Make sure the d.ts file is generated
const dts = (
await fs.readFile(path.join(appDir, '.next', 'types', 'link.d.ts'))
).toString()
expect(dts.includes('`/dashboard/user/')).toBeTruthy()
expect(dts.includes('`/dashboard/another')).toBeTruthy()
// Check type checking errors
expect(errors).toContain(
'Type error: "/(newroot)/dashboard/another" is not an existing route. If it is intentional, please type it explicitly with `as Route`.'
)
// Make sure all errors were reported and other links passed type checking
const errorLines = [
...errors.matchAll(/\.\/src\/app\/type-checks\/link\/page\.tsx:(\d+):/g),
].map(([, line]) => +line)
const ST = 18
const ED = 35
expect(errorLines).toEqual(
Array.from({ length: ED - ST + 1 }, (_, i) => i + ST)
)
})
it('should generate route types correctly and report router API errors', async () => {
// Make sure all errors were reported and other links passed type checking
const errorLines = [
...errors.matchAll(
/\.\/src\/app\/type-checks\/router\/page\.tsx:(\d+):/g
),
].map(([, line]) => +line)
const ST = 11
const ED = 13
expect(errorLines).toEqual(
Array.from({ length: ED - ST + 1 }, (_, i) => i + ST)
)
})
it('should generate route types correctly and report form errors', async () => {
// Make sure all errors were reported and other Forms passed type checking
const errorLines = [
...errors.matchAll(/\.\/src\/app\/type-checks\/form\/page\.tsx:(\d+):/g),
].map(([, line]) => +line)
const ST = 8
const ED = 10
expect(errorLines).toEqual(
Array.from({ length: ED - ST + 1 }, (_, i) => i + ST)
)
})
// Type validation is not supported in Turbopack yet.
if (!process.env.IS_TURBOPACK_TEST && !process.env.TURBOPACK_DEV) {
it('should type check invalid entry exports', () => {
// Can't export arbitrary things.
expect(errors).toContain(`"foo" is not a valid Page export field.`)
// Can't export invalid fields.
expect(errors).toMatch(
/Invalid configuration "revalidate":\s+Expected "false | number (>= 0)", got "-1"/
)
// Avoid invalid argument types for exported functions.
expect(errors).toMatch(
/Page "src\/app\/type-checks\/config\/page\.tsx" has an invalid "default" export:\s+Type "{ foo: string; }" is not valid/
)
expect(errors).toMatch(
/Page "src\/app\/type-checks\/config\/page\.tsx" has an invalid "generateMetadata" export:\s+Type "{ s: number; }" is not valid/
)
expect(errors).toMatch(
/Page "src\/app\/type-checks\/config\/page\.tsx" has an invalid "generateStaticParams" export:\s+Type "string" is not valid/
)
// Avoid invalid return types for exported functions.
expect(errors).toContain(
`"Promise<number>" is not a valid generateStaticParams return type`
)
// Can't export arbitrary things.
expect(errors).toContain(`"bar" is not a valid Route export field.`)
// Can't export invalid fields.
expect(errors).toMatch(
/Invalid configuration "revalidate":\s+Expected "false | number (>= 0)", got "-1"/
)
// Avoid invalid argument types for exported functions.
expect(errors).toMatch(
/Route "src\/app\/type-checks\/route-handlers\/route\.ts" has an invalid "GET" export:\s+Type "boolean" is not a valid type for the function's first argument/
)
expect(errors).toMatch(
/Route "src\/app\/type-checks\/route-handlers\/route\.ts" has an invalid "generateStaticParams" export:\s+Type "string" is not valid/
)
// Avoid invalid return types for exported functions.
expect(errors).toContain(
`"Promise<boolean>" is not a valid generateStaticParams return type`
)
})
}
)
})
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