Skip to content

Commit 41ac37f

Browse files
authored
feat: add typecheck option to fail on type errors (#347)
1 parent 9c5e70d commit 41ac37f

26 files changed

Lines changed: 550 additions & 13 deletions

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ dts({
110110
| `resolver` | Resolve declaration imports with `oxc` or `tsc`. | `oxc` |
111111
| `cjsDefault` | Convert a single default export to `export =`. | `false` |
112112
| `sideEffects` | Mark declaration modules as having side effects. | `false` |
113+
| `typecheck` | Fail the build on type errors. Not supported by `oxc`. | `false` |
113114
| `logger` | Logger implementing `info`, `warn`, and `error`. | `console` |
114115

115116
`tsc.*`, `oxc.*`, `tsgo.*`, and `tsrs.*` apply only to their respective

‎__snapshots__/tsnapi/index.snapshot.d.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ export interface Options extends DeprecatedOptions {
4040
sideEffects?: boolean;
4141
logger?: Logger;
4242
emitJs?: boolean;
43+
typecheck?: boolean;
4344
tsc?: TscOptions;
4445
oxc?: Omit<IsolatedDeclarationsOptions, "sourcemap">;
4546
tsgo?: TsgoOptions;
@@ -58,9 +59,9 @@ export interface TscOptions {
5859

5960
// #region Functions
6061
export declare function createFakeJsPlugin({ sourcemap, cjsDefault, sideEffects }: Pick<OptionsResolved, "sourcemap" | "cjsDefault" | "sideEffects">): Plugin;
61-
export declare function createGeneratePlugin(_: Pick<OptionsResolved, "generator" | "entry" | "cwd" | "tsconfig" | "tsconfigRaw" | "oxc" | "dtsOnly" | "languageContext" | "tsc" | "tsgo" | "tsrs" | "emitJs" | "sourcemap">): Plugin;
62+
export declare function createGeneratePlugin(_: Pick<OptionsResolved, "generator" | "entry" | "cwd" | "tsconfig" | "tsconfigRaw" | "oxc" | "dtsOnly" | "languageContext" | "tsc" | "tsgo" | "tsrs" | "emitJs" | "sourcemap" | "typecheck">): Plugin;
6263
export declare function dts(_?: Options): Plugin[];
63-
export declare function resolveOptions({ generator, entry, cwd, dtsOnly, tsconfig, tsconfigRaw: overriddenTsconfigRaw, compilerOptions, sourcemap, resolver, cjsDefault, sideEffects, logger, customLanguages, tsc, emitJs, oxc, tsgo, tsrs, ...deprecated }: Options): OptionsResolved;
64+
export declare function resolveOptions({ generator, entry, cwd, dtsOnly, tsconfig, tsconfigRaw: overriddenTsconfigRaw, compilerOptions, sourcemap, resolver, cjsDefault, sideEffects, logger, customLanguages, typecheck, tsc, emitJs, oxc, tsgo, tsrs, ...deprecated }: Options): OptionsResolved;
6465
// #endregion
6566

6667
// #region Referenced (internal)

‎__snapshots__/tsnapi/tsc.snapshot.d.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ export interface TscOptions {
1515
entries?: string[];
1616
id: string;
1717
sourcemap: boolean;
18+
typecheck?: boolean;
1819
languageContext: LanguageContext;
1920
context?: TscContext;
2021
}

‎src/generate.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ export function createGeneratePlugin(
4747
| 'tsrs'
4848
| 'emitJs'
4949
| 'sourcemap'
50+
| 'typecheck'
5051
>,
5152
): Plugin {
5253
const { entry, cwd, dtsOnly, languageContext, tsc, emitJs } = options

‎src/generator/index.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ export function createGenerator(
4444
tsgo,
4545
tsrs,
4646
sourcemap,
47+
typecheck,
4748
}: Pick<
4849
OptionsResolved,
4950
| 'generator'
@@ -56,6 +57,7 @@ export function createGenerator(
5657
| 'tsgo'
5758
| 'tsrs'
5859
| 'sourcemap'
60+
| 'typecheck'
5961
>,
6062
getEntries: () => string[] | undefined,
6163
loadSource?: (fileName: string) => Promise<void>,
@@ -71,6 +73,7 @@ export function createGenerator(
7173
tsgoPath: tsgo.path!,
7274
tsconfig: tsconfig!,
7375
sourcemap,
76+
typecheck,
7477
languageContext,
7578
})
7679
}
@@ -85,6 +88,7 @@ export function createGenerator(
8588
cwd,
8689
tsconfig: tsconfig!,
8790
vfs: !!native.vfs,
91+
typecheck,
8892
languageContext,
8993
loadSource,
9094
})
@@ -97,6 +101,7 @@ export function createGenerator(
97101
incremental: tsc.incremental,
98102
cwd,
99103
sourcemap,
104+
typecheck,
100105
languageContext,
101106
vue: tsc.vue,
102107
parallel: tsc.parallel,

‎src/generator/tsgo-cli.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ export interface TsgoCliGeneratorOptions {
6666
tsgoPath: string
6767
tsconfig: string
6868
sourcemap?: boolean
69+
typecheck?: boolean
6970
languageContext: LanguageContext
7071
}
7172

@@ -80,8 +81,14 @@ export class TsgoCliGenerator implements Generator {
8081
}
8182

8283
async init(): Promise<void> {
83-
const { tsgoPath, tsconfig, sourcemap } = this.options
84-
this.context = await runTsgo(tsgoPath, this.rootDir, tsconfig, sourcemap)
84+
const { tsgoPath, tsconfig, sourcemap, typecheck } = this.options
85+
this.context = await runTsgo(
86+
tsgoPath,
87+
this.rootDir,
88+
tsconfig,
89+
sourcemap,
90+
typecheck,
91+
)
8592
}
8693

8794
async emit(_code: string, fileName: string): Promise<GeneratorResult> {
@@ -131,6 +138,7 @@ async function runTsgo(
131138
rootDir: string,
132139
tsconfig: string,
133140
sourcemap?: boolean,
141+
typecheck?: boolean,
134142
): Promise<TsgoContext> {
135143
debug('[tsgo] rootDir', rootDir)
136144
debug('[tsgo] using tsgo binary', tsgoPath)
@@ -149,7 +157,7 @@ async function runTsgo(
149157
tsgoDist,
150158
'--rootDir',
151159
rootDir,
152-
'--noCheck',
160+
...(typecheck ? [] : ['--noCheck']),
153161
...(sourcemap ? ['--declarationMap'] : []),
154162
]
155163
debug('[tsgo] args %o', args)

‎src/generator/tsgo.ts‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import type { LanguageContext } from '../custom-language.ts'
1111
import type { Generator, GeneratorResult } from './index.ts'
1212
import type { SourceMapInput } from 'rolldown'
1313
import type * as TsgoApiModule from 'typescript-next/async'
14-
import type { API, Snapshot } from 'typescript-next/async'
14+
import type { API, Program, Snapshot } from 'typescript-next/async'
1515
import type * as TsgoFsModule from 'typescript-next/fs'
1616
import type { Diagnostic } from 'typescript-next/proto'
1717

@@ -29,6 +29,7 @@ export interface TsgoGeneratorOptions {
2929
cwd: string
3030
tsconfig: string
3131
vfs: boolean
32+
typecheck?: boolean
3233
languageContext: LanguageContext
3334
loadSource?: (fileName: string) => Promise<void>
3435
}
@@ -45,6 +46,8 @@ export class TsgoGenerator implements Generator {
4546
private loadedSourceFiles = new Set<string>()
4647
private rootFileProjects = new Map<string, string>()
4748
private emitQueue: Promise<void> = Promise.resolve()
49+
// A new snapshot creates new programs, so changed code is checked again.
50+
private programErrors = new WeakMap<Program, Promise<string>>()
4851

4952
constructor(options: TsgoGeneratorOptions) {
5053
this.options = options
@@ -100,6 +103,8 @@ export class TsgoGenerator implements Generator {
100103
}
101104
}
102105

106+
if (this.options.typecheck) this.assertNoCheckDisabled()
107+
103108
// eslint-disable-next-line unicorn/prefer-early-return
104109
if (this.options.languageContext.contentMapperExtensions.length) {
105110
// Mapper setup and transform errors can otherwise produce empty declarations.
@@ -120,6 +125,20 @@ export class TsgoGenerator implements Generator {
120125
}
121126
}
122127

128+
private assertNoCheckDisabled(): void {
129+
const configs = this.snapshot!.getProjects()
130+
.filter(
131+
({ configFileName, parsedCommandLine }) =>
132+
configFileName && parsedCommandLine.options.noCheck,
133+
)
134+
.map(({ configFileName }) => configFileName)
135+
if (configs.length) {
136+
throw new Error(
137+
`The \`typecheck\` option conflicts with \`noCheck\` in ${configs.join(', ')}. Remove \`noCheck\` from the tsconfig or disable \`typecheck\`.`,
138+
)
139+
}
140+
}
141+
123142
addFile(code: string, fileName: string): void {
124143
if (!this.options.vfs) return
125144
this.pendingFiles.set(this.toTsFilename(fileName), code)
@@ -255,6 +274,31 @@ export class TsgoGenerator implements Generator {
255274
await this.replaceSnapshot(nextSnapshot)
256275
}
257276

277+
private checkProgram(program: Program): Promise<string> {
278+
let errors = this.programErrors.get(program)
279+
if (!errors) {
280+
debug('type checking program %s', program.id)
281+
errors = Promise.all([
282+
program.getConfigFileParsingDiagnostics(),
283+
program.getProgramDiagnostics(),
284+
program.getGlobalDiagnostics(),
285+
program.getSyntacticDiagnostics(),
286+
program.getSemanticDiagnostics(),
287+
program.getDeclarationDiagnostics(),
288+
]).then((diagnostics) => {
289+
const errors = diagnostics
290+
.flat()
291+
.filter(
292+
({ category }) =>
293+
category === this.apiModule!.DiagnosticCategory.Error,
294+
)
295+
return errors.length ? this.formatDiagnostics(errors) : ''
296+
})
297+
this.programErrors.set(program, errors)
298+
}
299+
return errors
300+
}
301+
258302
private async emitFromSnapshot(fileName: string): Promise<GeneratorResult> {
259303
if (!this.apiModule || !this.api || !this.snapshot) {
260304
throw new Error('TsgoGenerator has not been initialized.')
@@ -307,6 +351,17 @@ export class TsgoGenerator implements Generator {
307351
}
308352
}
309353

354+
if (this.options.typecheck) {
355+
const error = await this.checkProgram(project.program).catch(
356+
(error: unknown) => {
357+
throw new Error(mapError(error, tsFileName, fileName), {
358+
cause: error,
359+
})
360+
},
361+
)
362+
if (error) return { error: mapError(error, tsFileName, fileName) }
363+
}
364+
310365
const output = await project.program
311366
.getDeclarationEmit([tsFileName])
312367
.catch((error: unknown) => {

‎src/options.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,13 @@ export interface Options extends DeprecatedOptions {
159159
*/
160160
emitJs?: boolean
161161

162+
/**
163+
* Fails the build on type errors. Not supported by `oxc`.
164+
*
165+
* @default false
166+
*/
167+
typecheck?: boolean
168+
162169
/** Options for the built-in `tsc` generator. */
163170
tsc?: TscOptions
164171

@@ -375,6 +382,7 @@ export function resolveOptions({
375382
sideEffects = false,
376383
logger = console,
377384
customLanguages,
385+
typecheck = false,
378386
tsc,
379387

380388
emitJs,
@@ -516,6 +524,12 @@ export function resolveOptions({
516524
}
517525
}
518526

527+
if (typecheck && generator === 'oxc') {
528+
throw new Error(
529+
"The `typecheck` option is not supported by the `oxc` generator. Use `generator: 'tsc'` or `generator: 'tsgo'` instead.",
530+
)
531+
}
532+
519533
if (generator === 'tsc' && tscOptions.parallel && hasCustomLanguages) {
520534
throw new Error(
521535
'The `tsc.parallel` option does not support `customLanguages`. Disable `tsc.parallel` or use the built-in `tsc.vue` option for Vue.',
@@ -627,6 +641,7 @@ export function resolveOptions({
627641
resolver,
628642
cjsDefault,
629643
sideEffects,
644+
typecheck,
630645

631646
tsc: tscOptions,
632647
emitJs,

0 commit comments

Comments
 (0)