( onStart: () => void, onComplete: (isSuccess: boolean) => void, )
| 13 | import {execSync} from 'child_process'; |
| 14 | |
| 15 | export function watchSrc( |
| 16 | onStart: () => void, |
| 17 | onComplete: (isSuccess: boolean) => void, |
| 18 | ): ts.WatchOfConfigFile<ts.SemanticDiagnosticsBuilderProgram> { |
| 19 | const configPath = ts.findConfigFile( |
| 20 | /*searchPath*/ PROJECT_ROOT, |
| 21 | ts.sys.fileExists, |
| 22 | 'tsconfig.json', |
| 23 | ); |
| 24 | if (!configPath) { |
| 25 | throw new Error("Could not find a valid 'tsconfig.json'."); |
| 26 | } |
| 27 | const createProgram = ts.createSemanticDiagnosticsBuilderProgram; |
| 28 | const host = ts.createWatchCompilerHost( |
| 29 | configPath, |
| 30 | undefined, |
| 31 | ts.sys, |
| 32 | createProgram, |
| 33 | () => {}, // we manually report errors in afterProgramCreate |
| 34 | () => {}, // we manually report watch status |
| 35 | ); |
| 36 | |
| 37 | const origCreateProgram = host.createProgram; |
| 38 | host.createProgram = (rootNames, options, host, oldProgram) => { |
| 39 | onStart(); |
| 40 | return origCreateProgram(rootNames, options, host, oldProgram); |
| 41 | }; |
| 42 | host.afterProgramCreate = program => { |
| 43 | /** |
| 44 | * Avoid calling original postProgramCreate because it always emits tsc |
| 45 | * compilation output |
| 46 | */ |
| 47 | |
| 48 | // syntactic diagnostics refer to javascript syntax |
| 49 | const errors = program |
| 50 | .getSyntacticDiagnostics() |
| 51 | .filter(diag => diag.category === ts.DiagnosticCategory.Error); |
| 52 | // semantic diagnostics refer to typescript semantics |
| 53 | errors.push( |
| 54 | ...program |
| 55 | .getSemanticDiagnostics() |
| 56 | .filter(diag => diag.category === ts.DiagnosticCategory.Error), |
| 57 | ); |
| 58 | |
| 59 | if (errors.length > 0) { |
| 60 | for (const diagnostic of errors) { |
| 61 | let fileLoc: string; |
| 62 | if (diagnostic.file) { |
| 63 | // https://github.com/microsoft/TypeScript/blob/ddd5084659c423f4003d2176e12d879b6a5bcf30/src/compiler/program.ts#L663-L674 |
| 64 | const {line, character} = ts.getLineAndCharacterOfPosition( |
| 65 | diagnostic.file, |
| 66 | diagnostic.start!, |
| 67 | ); |
| 68 | const fileName = path.relative( |
| 69 | ts.sys.getCurrentDirectory(), |
| 70 | diagnostic.file.fileName, |
| 71 | ); |
| 72 | fileLoc = `${fileName}:${line + 1}:${character + 1} - `; |
no test coverage detected