-
Notifications
You must be signed in to change notification settings - Fork 187
/
program.ts
81 lines (69 loc) · 2.46 KB
/
program.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
import * as glob from "glob";
import * as path from "path";
import ts from "typescript";
import normalize from "normalize-path";
import { Config } from "../src/Config";
import { DiagnosticError } from "../src/Error/DiagnosticError";
import { LogicError } from "../src/Error/LogicError";
import { NoRootNamesError } from "../src/Error/NoRootNamesError";
import { NoTSConfigError } from "../src/Error/NoTSConfigError";
function loadTsConfigFile(configFile: string) {
const raw = ts.sys.readFile(configFile);
if (raw) {
const config = ts.parseConfigFileTextToJson(configFile, raw);
if (config.error) {
throw new DiagnosticError([config.error]);
} else if (!config.config) {
throw new LogicError(`Invalid parsed config file "${configFile}"`);
}
const parseResult = ts.parseJsonConfigFileContent(
config.config,
ts.sys,
path.resolve(path.dirname(configFile)),
{},
configFile
);
parseResult.options.noEmit = true;
delete parseResult.options.out;
delete parseResult.options.outDir;
delete parseResult.options.outFile;
delete parseResult.options.declaration;
delete parseResult.options.declarationDir;
delete parseResult.options.declarationMap;
return parseResult;
} else {
throw new NoTSConfigError();
}
}
function getTsConfig(config: Config) {
if (config.tsconfig) {
return loadTsConfigFile(config.tsconfig);
}
return {
fileNames: [],
options: {
noEmit: true,
emitDecoratorMetadata: true,
experimentalDecorators: true,
target: ts.ScriptTarget.ES5,
module: ts.ModuleKind.CommonJS,
strictNullChecks: false,
},
};
}
export function createProgram(config: Config): ts.Program {
const rootNamesFromPath = config.path ? glob.sync(normalize(path.resolve(config.path))) : [];
const tsconfig = getTsConfig(config);
const rootNames = rootNamesFromPath.length ? rootNamesFromPath : tsconfig.fileNames;
if (!rootNames.length) {
throw new NoRootNamesError();
}
const program: ts.Program = ts.createProgram(rootNames, tsconfig.options);
if (!config.skipTypeCheck) {
const diagnostics = ts.getPreEmitDiagnostics(program);
if (diagnostics.length) {
throw new DiagnosticError(diagnostics);
}
}
return program;
}