/
createIsolatedProgram.ts
71 lines (63 loc) · 1.74 KB
/
createIsolatedProgram.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
import debug from 'debug';
import * as ts from 'typescript'; // leave this as * as ts so people using util package don't need syntheticDefaultImports
import { Extra } from '../parser-options';
import { ASTAndProgram, DEFAULT_COMPILER_OPTIONS } from './shared';
const log = debug('typescript-eslint:typescript-estree:createIsolatedProgram');
/**
* @param code The code of the file being linted
* @returns Returns a new source file and program corresponding to the linted code
*/
function createIsolatedProgram(code: string, extra: Extra): ASTAndProgram {
log('Getting isolated program for: %s', extra.filePath);
const compilerHost: ts.CompilerHost = {
fileExists() {
return true;
},
getCanonicalFileName() {
return extra.filePath;
},
getCurrentDirectory() {
return '';
},
getDirectories() {
return [];
},
getDefaultLibFileName() {
return 'lib.d.ts';
},
// TODO: Support Windows CRLF
getNewLine() {
return '\n';
},
getSourceFile(filename: string) {
return ts.createSourceFile(filename, code, ts.ScriptTarget.Latest, true);
},
readFile() {
return undefined;
},
useCaseSensitiveFileNames() {
return true;
},
writeFile() {
return null;
},
};
const program = ts.createProgram(
[extra.filePath],
{
noResolve: true,
target: ts.ScriptTarget.Latest,
jsx: extra.jsx ? ts.JsxEmit.Preserve : undefined,
...DEFAULT_COMPILER_OPTIONS,
},
compilerHost,
);
const ast = program.getSourceFile(extra.filePath);
if (!ast) {
throw new Error(
'Expected an ast to be returned for the single-file isolated program.',
);
}
return { ast, program };
}
export { createIsolatedProgram };