-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
typechecker.ts
295 lines (259 loc) · 8.53 KB
/
typechecker.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import { rm } from 'node:fs/promises'
import type { ExecaChildProcess } from 'execa'
import { execa } from 'execa'
import { basename, extname, resolve } from 'pathe'
import { TraceMap, generatedPositionFor } from '@jridgewell/trace-mapping'
import type { RawSourceMap } from '@ampproject/remapping'
import { getTasks } from '../utils'
import { ensurePackageInstalled } from '../node/pkg'
import type { Awaitable, File, ParsedStack, Task, TaskResultPack, TaskState, TscErrorInfo } from '../types'
import type { WorkspaceProject } from '../node/workspace'
import { getRawErrsMapFromTsCompile, getTsconfig } from './parse'
import { createIndexMap } from './utils'
import type { FileInformation } from './collect'
import { collectTests } from './collect'
export class TypeCheckError extends Error {
name = 'TypeCheckError'
constructor(public message: string, public stacks: ParsedStack[]) {
super(message)
}
}
interface ErrorsCache {
files: File[]
sourceErrors: TypeCheckError[]
}
type Callback<Args extends Array<any> = []> = (...args: Args) => Awaitable<void>
export class Typechecker {
private _onParseStart?: Callback
private _onParseEnd?: Callback<[ErrorsCache]>
private _onWatcherRerun?: Callback
private _result: ErrorsCache = {
files: [],
sourceErrors: [],
}
private _output = ''
private _tests: Record<string, FileInformation> | null = {}
private tempConfigPath?: string
private allowJs?: boolean
private process?: ExecaChildProcess
constructor(protected ctx: WorkspaceProject, protected files: string[]) { }
public onParseStart(fn: Callback) {
this._onParseStart = fn
}
public onParseEnd(fn: Callback<[ErrorsCache]>) {
this._onParseEnd = fn
}
public onWatcherRerun(fn: Callback) {
this._onWatcherRerun = fn
}
protected async collectFileTests(filepath: string): Promise<FileInformation | null> {
return collectTests(this.ctx, filepath)
}
protected getFiles() {
return this.files.filter((filename) => {
const extension = extname(filename)
return extension !== '.js' || this.allowJs
})
}
public async collectTests() {
const tests = (await Promise.all(
this.getFiles().map(filepath => this.collectFileTests(filepath)),
)).reduce((acc, data) => {
if (!data)
return acc
acc[data.filepath] = data
return acc
}, {} as Record<string, FileInformation>)
this._tests = tests
return tests
}
protected markPassed(file: File) {
if (!file.result?.state) {
file.result = {
state: 'pass',
}
}
const markTasks = (tasks: Task[]): void => {
for (const task of tasks) {
if ('tasks' in task)
markTasks(task.tasks)
if (!task.result?.state && task.mode === 'run') {
task.result = {
state: 'pass',
}
}
}
}
markTasks(file.tasks)
}
protected async prepareResults(output: string) {
const typeErrors = await this.parseTscLikeOutput(output)
const testFiles = new Set(this.getFiles())
if (!this._tests)
this._tests = await this.collectTests()
const sourceErrors: TypeCheckError[] = []
const files: File[] = []
testFiles.forEach((path) => {
const { file, definitions, map, parsed } = this._tests![path]
const errors = typeErrors.get(path)
files.push(file)
if (!errors) {
this.markPassed(file)
return
}
const sortedDefinitions = [...definitions.sort((a, b) => b.start - a.start)]
// has no map for ".js" files that use // @ts-check
const traceMap = map && new TraceMap(map as unknown as RawSourceMap)
const indexMap = createIndexMap(parsed)
const markState = (task: Task, state: TaskState) => {
task.result = {
state: (task.mode === 'run' || task.mode === 'only') ? state : task.mode,
}
if (task.suite)
markState(task.suite, state)
}
errors.forEach(({ error, originalError }) => {
const processedPos = traceMap
? generatedPositionFor(traceMap, {
line: originalError.line,
column: originalError.column,
source: basename(path),
})
: originalError
const line = processedPos.line ?? originalError.line
const column = processedPos.column ?? originalError.column
const index = indexMap.get(`${line}:${column}`)
const definition = (index != null && sortedDefinitions.find(def => def.start <= index && def.end >= index))
const suite = definition ? definition.task : file
const state: TaskState = (suite.mode === 'run' || suite.mode === 'only') ? 'fail' : suite.mode
const errors = suite.result?.errors || []
suite.result = {
state,
errors,
}
errors.push(error)
if (state === 'fail' && suite.suite)
markState(suite.suite, 'fail')
})
this.markPassed(file)
})
typeErrors.forEach((errors, path) => {
if (!testFiles.has(path))
sourceErrors.push(...errors.map(({ error }) => error))
})
return {
files,
sourceErrors,
}
}
protected async parseTscLikeOutput(output: string) {
const errorsMap = await getRawErrsMapFromTsCompile(output)
const typesErrors = new Map<string, { error: TypeCheckError; originalError: TscErrorInfo }[]>()
errorsMap.forEach((errors, path) => {
const filepath = resolve(this.ctx.config.root, path)
const suiteErrors = errors.map((info) => {
const limit = Error.stackTraceLimit
Error.stackTraceLimit = 0
const error = new TypeCheckError(info.errMsg, [
{
file: filepath,
line: info.line,
column: info.column,
method: '',
},
])
Error.stackTraceLimit = limit
return {
originalError: info,
error,
}
})
typesErrors.set(filepath, suiteErrors)
})
return typesErrors
}
public async clear() {
if (this.tempConfigPath)
await rm(this.tempConfigPath, { force: true })
}
public async stop() {
await this.clear()
this.process?.kill()
}
protected async ensurePackageInstalled(root: string, checker: string) {
if (checker !== 'tsc' && checker !== 'vue-tsc')
return
const packageName = checker === 'tsc' ? 'typescript' : 'vue-tsc'
await ensurePackageInstalled(packageName, root)
}
public async prepare() {
const { root, typecheck } = this.ctx.config
await this.ensurePackageInstalled(root, typecheck.checker)
const { config, path } = await getTsconfig(root, typecheck)
this.tempConfigPath = path
this.allowJs = typecheck.allowJs || config.allowJs || false
}
public getExitCode() {
return this.process?.exitCode != null && this.process.exitCode
}
public getOutput() {
return this._output
}
public async start() {
if (!this.tempConfigPath)
throw new Error('tsconfig was not initialized')
const { root, watch, typecheck } = this.ctx.config
const args = ['--noEmit', '--pretty', 'false', '-p', this.tempConfigPath]
// use builtin watcher, because it's faster
if (watch)
args.push('--watch')
if (typecheck.allowJs)
args.push('--allowJs', '--checkJs')
this._output = ''
const child = execa(typecheck.checker, args, {
cwd: root,
stdout: 'pipe',
reject: false,
})
this.process = child
await this._onParseStart?.()
let rerunTriggered = false
child.stdout?.on('data', (chunk) => {
this._output += chunk
if (!watch)
return
if (this._output.includes('File change detected') && !rerunTriggered) {
this._onWatcherRerun?.()
this._result.sourceErrors = []
this._result.files = []
this._tests = null // test structure might've changed
rerunTriggered = true
}
if (/Found \w+ errors*. Watching for/.test(this._output)) {
rerunTriggered = false
this.prepareResults(this._output).then((result) => {
this._result = result
this._onParseEnd?.(result)
})
this._output = ''
}
})
if (!watch) {
await child
this._result = await this.prepareResults(this._output)
await this._onParseEnd?.(this._result)
}
}
public getResult() {
return this._result
}
public getTestFiles() {
return Object.values(this._tests || {}).map(i => i.file)
}
public getTestPacks() {
return Object.values(this._tests || {})
.map(({ file }) => getTasks(file))
.flat()
.map(i => [i.id, undefined] as TaskResultPack)
}
}