-
Notifications
You must be signed in to change notification settings - Fork 202
/
Copy pathtsconfig.ts
421 lines (358 loc) · 14.3 KB
/
tsconfig.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
///ts:ref=globals
/// <reference path="../../globals.ts"/> ///ts:ref:generated
// Most compiler options come from require('typescript').CompilerOptions, but
// 'module' and 'target' cannot use the same enum as that interface since we
// do not want to force users to put magic numbers in their tsconfig files
// TODO: Use require('typescript').parseConfigFile when TS1.5 is released
interface CompilerOptions {
allowNonTsExtensions?: boolean;
charset?: string;
codepage?: number;
declaration?: boolean;
diagnostics?: boolean;
emitBOM?: boolean;
help?: boolean;
locale?: string;
mapRoot?: string; // Optionally Specifies the location where debugger should locate map files after deployment
module?: string; //'amd'|'commonjs' (default)
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noImplicitAny?: boolean; // Error on inferred `any` type
noLib?: boolean;
noLibCheck?: boolean;
noResolve?: boolean;
out?: string;
outDir?: string; // Redirect output structure to this directory
preserveConstEnums?: boolean;
removeComments?: boolean; // Do not emit comments in output
sourceMap?: boolean; // Generates SourceMaps (.map files)
sourceRoot?: string; // Optionally specifies the location where debugger should locate TypeScript source files after deployment
suppressImplicitAnyIndexErrors?: boolean;
target?: string; // 'es3'|'es5' (default)|'es6'
version?: boolean;
watch?: boolean;
}
interface TypeScriptProjectRawSpecification {
compilerOptions?: CompilerOptions;
files?: string[]; // optional: paths to files
filesGlob?: string[]; // optional: An array of 'glob / minimatch / RegExp' patterns to specify source files
format?: formatting.FormatCodeOptions; // optional: formatting options
}
// Main configuration
export interface TypeScriptProjectSpecification {
compilerOptions: ts.CompilerOptions;
files: string[];
format: ts.FormatCodeOptions;
}
///////// FOR USE WITH THE API /////////////
export interface TypeScriptProjectFileDetails {
projectFileDirectory: string; // The path to the project file. This acts as the baseDIR
projectFilePath: string;
project: TypeScriptProjectSpecification;
}
//////////////////////////////////////////////////////////////////////
export var errors = {
GET_PROJECT_INVALID_PATH: 'Invalid Path',
GET_PROJECT_NO_PROJECT_FOUND: 'No Project Found',
GET_PROJECT_FAILED_TO_OPEN_PROJECT_FILE: 'Failed to fs.readFileSync the project file',
GET_PROJECT_JSON_PARSE_FAILED: 'Failed to JSON.parse the project file',
CREATE_FILE_MUST_EXIST: 'To create a project the file must exist',
CREATE_PROJECT_ALREADY_EXISTS: 'Project file already exists',
};
import fs = require('fs');
import path = require('path');
import expand = require('glob-expand');
import ts = require('typescript');
import os = require('os');
import formatting = require('./formatting');
var projectFileName = 'tsconfig.json';
var defaultFilesGlob = ["./**/*.ts", "!node_modules/**/*.ts"];
export var defaults: ts.CompilerOptions = {
target: ts.ScriptTarget.ES5,
module: ts.ModuleKind.CommonJS,
declaration: false,
noImplicitAny: false,
removeComments: true,
noLib: false
};
// TODO: add validation and add all options
var deprecatedKeys = {
outdir: 'outDir',
noimplicitany: 'noImplicitAny',
removecomments: 'removeComments',
sourcemap: 'sourceMap',
sourceroot: 'sourceRoot',
maproot: 'mapRoot',
nolib: 'noLib'
};
var typescriptEnumMap = {
target: {
'es3': ts.ScriptTarget.ES3,
'es5': ts.ScriptTarget.ES5,
'es6': ts.ScriptTarget.ES6,
'latest': ts.ScriptTarget.Latest
},
module: {
'none': ts.ModuleKind.None,
'commonjs': ts.ModuleKind.CommonJS,
'amd': ts.ModuleKind.AMD
}
};
var jsonEnumMap = {
target: (function() {
var map: { [key: number]: string; } = {};
map[ts.ScriptTarget.ES3] = 'es3';
map[ts.ScriptTarget.ES5] = 'es5';
map[ts.ScriptTarget.ES6] = 'es6';
map[ts.ScriptTarget.Latest] = 'latest';
return map;
})(),
module: (function() {
var map: { [key: number]: string; } = {};
map[ts.ModuleKind.None] = 'none';
map[ts.ModuleKind.CommonJS] = 'commonjs';
map[ts.ModuleKind.AMD] = 'amd';
return map;
})()
};
function mixin(target: any, source: any): any {
for (var key in source) {
target[key] = source[key];
}
return target;
}
function rawToTsCompilerOptions(jsonOptions: CompilerOptions, projectDir: string): ts.CompilerOptions {
// Cannot use Object.create because the compiler checks hasOwnProperty
var compilerOptions = <ts.CompilerOptions> mixin({}, defaults);
for (var key in jsonOptions) {
if (deprecatedKeys[key]) {
// Warn using : https://github.com/TypeStrong/atom-typescript/issues/51
// atom.notifications.addWarning('Compiler option "' + key + '" is deprecated; use "' + deprecatedKeys[key] + '" instead');
key = deprecatedKeys[key];
}
if (typescriptEnumMap[key]) {
compilerOptions[key] = typescriptEnumMap[key][jsonOptions[key].toLowerCase()];
}
else {
compilerOptions[key] = jsonOptions[key];
}
}
if (compilerOptions.outDir !== undefined) {
compilerOptions.outDir = path.resolve(projectDir, compilerOptions.outDir);
}
return compilerOptions;
}
function tsToRawCompilerOptions(compilerOptions: ts.CompilerOptions): CompilerOptions {
// Cannot use Object.create because JSON.stringify will only serialize own properties
var jsonOptions = <CompilerOptions> mixin({}, compilerOptions);
if (compilerOptions.target !== undefined) {
jsonOptions.target = jsonEnumMap.target[compilerOptions.target];
}
if (compilerOptions.module !== undefined) {
jsonOptions.module = jsonEnumMap.module[compilerOptions.module];
}
return jsonOptions;
}
/** Given an src (source file or directory) goes up the directory tree to find the project specifications.
* Use this to bootstrap the UI for what project the user might want to work on.
* Note: Definition files (.d.ts) are considered thier own project
*/
export function getProjectSync(pathOrSrcFile: string): TypeScriptProjectFileDetails {
if (!fs.existsSync(pathOrSrcFile))
throw new Error(errors.GET_PROJECT_INVALID_PATH);
// Get the path directory
var dir = fs.lstatSync(pathOrSrcFile).isDirectory() ? pathOrSrcFile : path.dirname(pathOrSrcFile);
// If we have a .d.ts file then it is its own project and return
if (dir !== pathOrSrcFile) { // Not a directory
if (endsWith(pathOrSrcFile.toLowerCase(), '.d.ts')) {
return {
projectFileDirectory: dir,
projectFilePath: dir + '/' + projectFileName,
project: {
compilerOptions: defaults,
files: [pathOrSrcFile],
format: formatting.defaultFormatCodeOptions()
},
}
}
}
// Keep going up till we find the project file
var projectFile = '';
while (fs.existsSync(dir)) { // while directory exists
var potentialProjectFile = dir + '/' + projectFileName;
if (fs.existsSync(potentialProjectFile)) { // found it
projectFile = potentialProjectFile;
break;
}
else { // go up
var before = dir;
dir = path.dirname(dir);
// At root:
if (dir == before) throw new Error(errors.GET_PROJECT_NO_PROJECT_FOUND);
}
}
projectFile = path.normalize(projectFile);
var projectFileDirectory = path.dirname(projectFile) + path.sep;
// We now have a valid projectFile. Parse it:
var projectSpec: TypeScriptProjectRawSpecification;
try {
var projectFileTextContent = fs.readFileSync(projectFile, 'utf8');
} catch (ex) {
throw new Error(errors.GET_PROJECT_FAILED_TO_OPEN_PROJECT_FILE);
}
try {
projectSpec = JSON.parse(projectFileTextContent);
} catch (ex) {
throw new Error(errors.GET_PROJECT_JSON_PARSE_FAILED);
}
// Setup default project options
if (!projectSpec.compilerOptions) projectSpec.compilerOptions = {};
// Our customizations for "tsconfig.json"
// Use grunt.file.expand type of logic
var cwdPath = path.relative(process.cwd(), path.dirname(projectFile));
if (!projectSpec.files) {
projectSpec.filesGlob = defaultFilesGlob;
}
if (projectSpec.filesGlob) {
projectSpec.files = expand({ filter: 'isFile', cwd: cwdPath }, projectSpec.filesGlob);
fs.writeFileSync(projectFile, prettyJSON(projectSpec));
}
// Remove all relativeness
projectSpec.files = projectSpec.files.map((file) => path.resolve(projectFileDirectory, file));
var project: TypeScriptProjectSpecification = {
compilerOptions: {},
files: projectSpec.files,
format: formatting.makeFormatCodeOptions(projectSpec.format),
};
project.compilerOptions = rawToTsCompilerOptions(projectSpec.compilerOptions, projectFileDirectory);
// Expand files to include references
project.files = increaseProjectForReferenceAndImports(project.files);
// Normalize to "/" for all files
// And take the uniq values
project.files = uniq(project.files.map(consistentPath));
return {
projectFileDirectory: projectFileDirectory,
projectFilePath: projectFileDirectory + '/' + projectFileName,
project: project
};
}
/** Creates a project by source file location. Defaults are assumed unless overriden by the optional spec. */
export function createProjectRootSync(srcFile: string, defaultOptions?: ts.CompilerOptions) {
if (!fs.existsSync(srcFile)) {
throw new Error(errors.CREATE_FILE_MUST_EXIST);
}
// Get directory
var dir = fs.lstatSync(srcFile).isDirectory() ? srcFile : path.dirname(srcFile);
var projectFilePath = path.normalize(dir + '/' + projectFileName);
if (fs.existsSync(projectFilePath))
throw new Error(errors.CREATE_PROJECT_ALREADY_EXISTS);
// We need to write the raw spec
var projectSpec: TypeScriptProjectRawSpecification = {};
projectSpec.compilerOptions = tsToRawCompilerOptions(defaultOptions || defaults);
projectSpec.filesGlob = defaultFilesGlob;
fs.writeFileSync(projectFilePath, prettyJSON(projectSpec));
return getProjectSync(srcFile);
}
// we work with "/" for all paths
export function consistentPath(filePath: string): string {
return filePath.replace('\\', '/');
}
/////////////////////////////////////////////
/////////////// UTILITIES ///////////////////
/////////////////////////////////////////////
function increaseProjectForReferenceAndImports(files: string[]) {
var filesMap = createMap(files);
var willNeedMoreAnalysis = (file: string) => {
if (!filesMap[file]) {
filesMap[file] = true;
files.push(file);
return true;
} else {
return false;
}
}
var getReferencedOrImportedFiles = (files: string[]): string[]=> {
var referenced: string[][] = [];
files.forEach(file => {
try {
var content = fs.readFileSync(file).toString();
}
catch (ex) {
// if we cannot read a file for whatever reason just quit
return;
}
var preProcessedFileInfo = ts.preProcessFile(content, true),
dir = path.dirname(file);
referenced.push(
preProcessedFileInfo.referencedFiles.map(fileReference => path.resolve(dir, fileReference.filename))
.concat(
preProcessedFileInfo.importedFiles
.filter((fileReference) => pathIsRelative(fileReference.filename))
.map(fileReference => {
var file = path.resolve(dir, fileReference.filename + '.ts');
if (!fs.existsSync(file)) {
file = path.resolve(dir, fileReference.filename + '.d.ts');
}
return file;
})
)
);
});
return selectMany(referenced);
}
var more = getReferencedOrImportedFiles(files)
.filter(willNeedMoreAnalysis);
while (more.length) {
more = getReferencedOrImportedFiles(files)
.filter(willNeedMoreAnalysis);
}
return files;
}
function createMap(arr: string[]): { [string: string]: boolean } {
return arr.reduce((result: { [string: string]: boolean }, key: string) => {
result[key] = true;
return result;
}, <{ [string: string]: boolean }>{});
}
function prettyJSON(object: any): string {
var cache = [];
var value = JSON.stringify(object,
// fixup circular reference
function(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
},
// indent 4 spaces
4);
cache = null;
return value;
}
// Not particularly awesome e.g. '/..foo' will pass
function pathIsRelative(str: string) {
if (!str.length) return false;
return str[0] == '.' || str.substring(0, 2) == "./" || str.substring(0, 3) == "../";
}
// Not optimized
function selectMany<T>(arr: T[][]): T[] {
var result = [];
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
result.push(arr[i][j]);
}
}
return result;
}
function endsWith(str: string, suffix: string): boolean {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function uniq(arr: string[]): string[] {
var map = createMap(arr);
return Object.keys(map);
}