Repository navigation
Expand file tree
/
Copy pathngc.ts
More file actions
207 lines (174 loc) · 6.77 KB
/
Copy pathngc.ts
File metadata and controls
207 lines (174 loc) · 6.77 KB
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
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// Must be imported first, because Angular decorators throw on load.
import 'reflect-metadata';
import {isSyntaxError, syntaxError} from '@angular/compiler';
import {MetadataBundler, createBundleIndexHost} from '@angular/tsc-wrapped';
import * as fs from 'fs';
import * as path from 'path';
import * as ts from 'typescript';
import * as api from './transformers/api';
import * as ng from './transformers/entry_points';
const TS_EXT = /\.ts$/;
type Diagnostics = ts.Diagnostic[] | api.Diagnostic[];
function isTsDiagnostics(diagnostics: any): diagnostics is ts.Diagnostic[] {
return diagnostics && diagnostics[0] && (diagnostics[0].file || diagnostics[0].messageText);
}
function formatDiagnostics(cwd: string, diags: Diagnostics): string {
if (diags && diags.length) {
if (isTsDiagnostics(diags)) {
return ts.formatDiagnostics(diags, {
getCurrentDirectory: () => cwd,
getCanonicalFileName: fileName => fileName,
getNewLine: () => ts.sys.newLine
});
} else {
return diags
.map(d => {
let res = api.DiagnosticCategory[d.category];
if (d.span) {
res +=
` at ${d.span.start.file.url}(${d.span.start.line + 1},${d.span.start.col + 1})`;
}
if (d.span && d.span.details) {
res += `: ${d.span.details}, ${d.message}\n`;
} else {
res += `: ${d.message}\n`;
}
return res;
})
.join();
}
} else
return '';
}
function check(cwd: string, ...args: Diagnostics[]) {
if (args.some(diags => !!(diags && diags[0]))) {
throw syntaxError(args.map(diags => {
if (diags && diags[0]) {
return formatDiagnostics(cwd, diags);
}
})
.filter(message => !!message)
.join(''));
}
}
function syntheticError(message: string): ts.Diagnostic {
return {
file: null as any as ts.SourceFile,
start: 0,
length: 0,
messageText: message,
category: ts.DiagnosticCategory.Error,
code: 0
};
}
export function readConfiguration(
project: string, basePath: string, existingOptions?: ts.CompilerOptions) {
// Allow a directory containing tsconfig.json as the project value
// Note, TS@next returns an empty array, while earlier versions throw
const projectFile =
fs.lstatSync(project).isDirectory() ? path.join(project, 'tsconfig.json') : project;
let {config, error} = ts.readConfigFile(projectFile, ts.sys.readFile);
if (error) check(basePath, [error]);
const parseConfigHost = {
useCaseSensitiveFileNames: true,
fileExists: fs.existsSync,
readDirectory: ts.sys.readDirectory,
readFile: ts.sys.readFile
};
const parsed = ts.parseJsonConfigFileContent(config, parseConfigHost, basePath, existingOptions);
check(basePath, parsed.errors);
// Default codegen goes to the current directory
// Parsed options are already converted to absolute paths
const ngOptions = config.angularCompilerOptions || {};
// Ignore the genDir option
ngOptions.genDir = basePath;
return {parsed, ngOptions};
}
function getProjectDirectory(project: string): string {
let isFile: boolean;
try {
isFile = fs.lstatSync(project).isFile();
} catch (e) {
// Project doesn't exist. Assume it is a file has an extension. This case happens
// when the project file is passed to set basePath but no tsconfig.json file exists.
// It is used in tests to ensure that the options can be passed in without there being
// an actual config file.
isFile = path.extname(project) !== '';
}
// If project refers to a file, the project directory is the file's parent directory
// otherwise project is the project directory.
return isFile ? path.dirname(project) : project;
}
export function main(
args: string[], consoleError: (s: string) => void = console.error, files?: string[],
options?: ts.CompilerOptions, ngOptions?: any): number {
try {
const parsedArgs = require('minimist')(args);
const project = parsedArgs.p || parsedArgs.project || '.';
const projectDir = getProjectDirectory(project);
// file names in tsconfig are resolved relative to this absolute path
const basePath = path.resolve(process.cwd(), projectDir);
if (!files || !options || !ngOptions) {
const {parsed, ngOptions: readNgOptions} = readConfiguration(project, basePath);
if (!files) files = parsed.fileNames;
if (!options) options = parsed.options;
if (!ngOptions) ngOptions = readNgOptions;
}
// Ignore what the tsconfig.json for baseDir and genDir
ngOptions.basePath = basePath;
ngOptions.genDir = basePath;
let host = ts.createCompilerHost(options, true);
host.realpath = p => p;
const rootFileNames = files.map(f => path.normalize(f));
const addGeneratedFileName =
(fileName: string) => {
if (fileName.startsWith(basePath) && TS_EXT.exec(fileName)) {
rootFileNames.push(fileName);
}
}
if (ngOptions.flatModuleOutFile && !ngOptions.skipMetadataEmit) {
const {host: bundleHost, indexName, errors} =
createBundleIndexHost(ngOptions, rootFileNames, host);
if (errors) check(basePath, errors);
if (indexName) addGeneratedFileName(indexName);
host = bundleHost;
}
const ngHostOptions = {...options, ...ngOptions};
const ngHost = ng.createHost({tsHost: host, options: ngHostOptions});
const ngProgram =
ng.createProgram({rootNames: rootFileNames, host: ngHost, options: ngHostOptions});
// Check parameter diagnostics
check(basePath, ngProgram.getTsOptionDiagnostics(), ngProgram.getNgOptionDiagnostics());
// Check syntactic diagnostics
check(basePath, ngProgram.getTsSyntacticDiagnostics());
// Check TypeScript semantic and Angular structure diagnostics
check(basePath, ngProgram.getTsSemanticDiagnostics(), ngProgram.getNgStructuralDiagnostics());
// Check Angular semantic diagnostics
check(basePath, ngProgram.getNgSemanticDiagnostics());
ngProgram.emit({
emitFlags: api.EmitFlags.Default |
((ngOptions.skipMetadataEmit || ngOptions.flatModuleOutFile) ? 0 : api.EmitFlags.Metadata)
});
} catch (e) {
if (isSyntaxError(e)) {
consoleError(e.message);
return 1;
} else {
consoleError(e.stack);
consoleError('Compilation failed');
return 2;
}
}
return 0;
}
// CLI entry point
if (require.main === module) {
process.exit(main(process.argv.slice(2), s => console.error(s)));
}