@@ -3,13 +3,38 @@ import ts from 'typescript';
33import { getLogger } from '../../helpers' ;
44import type { CommonLogger } from '../../models' ;
55
6+ const CONTEXT_LINES = 3 ;
7+
68export function reportCompileDiagnostic (
79 diagnostic : ts . Diagnostic ,
810 logger : CommonLogger = getLogger ( ) ,
911) : void {
10- const { line } = diagnostic . file ! . getLineAndCharacterOfPosition ( diagnostic . start ! ) ;
11- logger . log (
12- `TS Error ${ diagnostic . code } : ${ ts . flattenDiagnosticMessageText ( diagnostic . messageText , ts . sys . newLine ) } ` ,
13- ) ;
14- logger . log ( ` at ${ diagnostic . file ! . fileName } :${ line + 1 } ` ) ;
12+ const message = [
13+ `TS Error ${ diagnostic . code } :` ,
14+ ts . flattenDiagnosticMessageText ( diagnostic . messageText , ts . sys . newLine ) ,
15+ ] . join ( ' ' ) ;
16+
17+ if ( diagnostic . file && diagnostic . start !== undefined ) {
18+ const { line, character } = diagnostic . file . getLineAndCharacterOfPosition ( diagnostic . start ) ;
19+ const sourceCode = diagnostic . file . text ;
20+ const lines = sourceCode . split ( '\n' ) ;
21+
22+ const startLine = Math . max ( 0 , line - CONTEXT_LINES ) ;
23+ const endLine = Math . min ( lines . length - 1 , line + CONTEXT_LINES ) ;
24+
25+ logger . error ( message ) ;
26+ logger . error ( ` at ${ diagnostic . file . fileName } :${ line + 1 } :${ character + 1 } ` ) ;
27+
28+ for ( let i = startLine ; i <= endLine ; i ++ ) {
29+ const prefix = i === line ? '> ' : ' ' ;
30+ logger . error ( `${ prefix } ${ i + 1 } | ${ lines [ i ] } ` ) ;
31+
32+ if ( i === line ) {
33+ const caretPosition = prefix . length + ( i + 1 ) . toString ( ) . length + 3 + character ;
34+ logger . error ( `${ ' ' . repeat ( caretPosition ) } ^` ) ;
35+ }
36+ }
37+ } else {
38+ logger . error ( message ) ;
39+ }
1540}
0 commit comments