Repository navigation
Expand file tree
/
Copy pathtranspile.ts
More file actions
460 lines (358 loc) · 15 KB
/
Copy pathtranspile.ts
File metadata and controls
460 lines (358 loc) · 15 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
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
import { fork, ChildProcess } from 'child_process';
import { EventEmitter } from 'events';
import { readFileSync } from 'fs';
import * as path from 'path';
import * as ts from 'typescript';
import { getFileSystemCompilerHostInstance } from './aot/compiler-host-factory';
import { buildJsSourceMaps } from './bundle';
import {
getInjectDeepLinkConfigTypescriptTransform,
purgeDeepLinkDecoratorTSTransform }
from './deep-linking/util';
import {
convertDeepLinkConfigEntriesToString,
getUpdatedAppNgModuleContentWithDeepLinkConfig,
filterTypescriptFilesForDeepLinks,
hasExistingDeepLinkConfig,
isDeepLinkingFile,
purgeDeepLinkDecorator
} from './deep-linking/util';
import { Logger } from './logger/logger';
import { printDiagnostics, clearDiagnostics, DiagnosticsType } from './logger/logger-diagnostics';
import { runTypeScriptDiagnostics } from './logger/logger-typescript';
import { inlineTemplate } from './template';
import * as Constants from './util/constants';
import { BuildError } from './util/errors';
import { FileCache } from './util/file-cache';
import { changeExtension, getBooleanPropertyValue, getParsedDeepLinkConfig, getStringPropertyValue } from './util/helpers';
import { BuildContext, BuildState, ChangedFile, File } from './util/interfaces';
export function transpile(context: BuildContext) {
const workerConfig: TranspileWorkerConfig = {
configFile: getTsConfigPath(context),
writeInMemory: true,
sourceMaps: true,
cache: true,
inlineTemplate: context.inlineTemplates,
useTransforms: true
};
const logger = new Logger('transpile');
return transpileWorker(context, workerConfig)
.then(() => {
context.transpileState = BuildState.SuccessfulBuild;
logger.finish();
})
.catch(err => {
context.transpileState = BuildState.RequiresBuild;
throw logger.fail(err);
});
}
export function transpileUpdate(changedFiles: ChangedFile[], context: BuildContext) {
const workerConfig: TranspileWorkerConfig = {
configFile: getTsConfigPath(context),
writeInMemory: true,
sourceMaps: true,
cache: false,
inlineTemplate: context.inlineTemplates,
useTransforms: true
};
const logger = new Logger('transpile update');
const changedTypescriptFiles = changedFiles.filter(changedFile => changedFile.ext === '.ts');
const promises: Promise<void>[] = [];
for (const changedTypescriptFile of changedTypescriptFiles) {
promises.push(transpileUpdateWorker(changedTypescriptFile.event, changedTypescriptFile.filePath, context, workerConfig));
}
return Promise.all(promises)
.then(() => {
context.transpileState = BuildState.SuccessfulBuild;
logger.finish();
})
.catch(err => {
context.transpileState = BuildState.RequiresBuild;
throw logger.fail(err);
});
}
/**
* The full TS build for all app files.
*/
export function transpileWorker(context: BuildContext, workerConfig: TranspileWorkerConfig) {
// let's do this
return new Promise((resolve, reject) => {
clearDiagnostics(context, DiagnosticsType.TypeScript);
// get the tsconfig data
const tsConfig = getTsConfig(context, workerConfig.configFile);
if (workerConfig.sourceMaps === false) {
// the worker config say, "hey, don't ever bother making a source map, because."
tsConfig.options.sourceMap = false;
} else {
// build the ts source maps if the bundler is going to use source maps
tsConfig.options.sourceMap = buildJsSourceMaps(context);
}
// collect up all the files we need to transpile, tsConfig itself does all this for us
const tsFileNames = cleanFileNames(context, tsConfig.fileNames);
// for dev builds let's not create d.ts files
tsConfig.options.declaration = undefined;
// let's start a new tsFiles object to cache all the transpiled files in
const host = getFileSystemCompilerHostInstance(tsConfig.options);
if (workerConfig.useTransforms && getBooleanPropertyValue(Constants.ENV_PARSE_DEEPLINKS)) {
// beforeArray.push(purgeDeepLinkDecoratorTSTransform());
// beforeArray.push(getInjectDeepLinkConfigTypescriptTransform());
// temporarily copy the files to a new location
copyOriginalSourceFiles(context.fileCache);
// okay, purge the deep link files NOT using a transform
const deepLinkFiles = filterTypescriptFilesForDeepLinks(context.fileCache);
deepLinkFiles.forEach(file => {
file.content = purgeDeepLinkDecorator(file.content);
});
const file = context.fileCache.get(getStringPropertyValue(Constants.ENV_APP_NG_MODULE_PATH));
const hasExisting = hasExistingDeepLinkConfig(file.path, file.content);
if (!hasExisting) {
const deepLinkString = convertDeepLinkConfigEntriesToString(getParsedDeepLinkConfig());
file.content = getUpdatedAppNgModuleContentWithDeepLinkConfig(file.path, file.content, deepLinkString);
}
}
const program = ts.createProgram(tsFileNames, tsConfig.options, host, cachedProgram);
resetSourceFiles(context.fileCache);
const beforeArray: ts.TransformerFactory<ts.SourceFile>[] = [];
program.emit(undefined, (path: string, data: string, writeByteOrderMark: boolean, onError: Function, sourceFiles: ts.SourceFile[]) => {
if (workerConfig.writeInMemory) {
writeTranspiledFilesCallback(context.fileCache, path, data, workerConfig.inlineTemplate);
}
});
// cache the typescript program for later use
cachedProgram = program;
const tsDiagnostics = program.getSyntacticDiagnostics()
.concat(program.getSemanticDiagnostics())
.concat(program.getOptionsDiagnostics());
const diagnostics = runTypeScriptDiagnostics(context, tsDiagnostics);
if (diagnostics.length) {
// darn, we've got some things wrong, transpile failed :(
printDiagnostics(context, DiagnosticsType.TypeScript, diagnostics, true, true);
reject(new BuildError('Failed to transpile program'));
} else {
// transpile success :)
resolve();
}
});
}
export function canRunTranspileUpdate(event: string, filePath: string, context: BuildContext) {
if (event === 'change' && context.fileCache) {
return context.fileCache.has(path.resolve(filePath));
}
return false;
}
/**
* Iterative build for one TS file. If it's not an existing file change, or
* something errors out then it falls back to do the full build.
*/
function transpileUpdateWorker(event: string, filePath: string, context: BuildContext, workerConfig: TranspileWorkerConfig) {
try {
clearDiagnostics(context, DiagnosticsType.TypeScript);
filePath = path.normalize(path.resolve(filePath));
// an existing ts file we already know about has changed
// let's "TRY" to do a single module build for this one file
if (!cachedTsConfig) {
cachedTsConfig = getTsConfig(context, workerConfig.configFile);
}
// build the ts source maps if the bundler is going to use source maps
cachedTsConfig.options.sourceMap = buildJsSourceMaps(context);
const beforeArray: ts.TransformerFactory<ts.SourceFile>[] = [];
const transpileOptions: ts.TranspileOptions = {
compilerOptions: cachedTsConfig.options,
fileName: filePath,
reportDiagnostics: true,
};
// let's manually transpile just this one ts file
// since it is an update, it's in memory already
const sourceText = context.fileCache.get(filePath).content;
const textToTranspile = workerConfig.useTransforms && getBooleanPropertyValue(Constants.ENV_PARSE_DEEPLINKS) ? transformSource(filePath, sourceText) : sourceText;
// transpile this one module
const transpileOutput = ts.transpileModule(textToTranspile, transpileOptions);
const diagnostics = runTypeScriptDiagnostics(context, transpileOutput.diagnostics);
if (diagnostics.length) {
printDiagnostics(context, DiagnosticsType.TypeScript, diagnostics, false, true);
// darn, we've got some errors with this transpiling :(
// but at least we reported the errors like really really fast, so there's that
Logger.debug(`transpileUpdateWorker: transpileModule, diagnostics: ${diagnostics.length}`);
throw new BuildError(`Failed to transpile file - ${filePath}`);
} else {
// convert the path to have a .js file extension for consistency
const newPath = changeExtension(filePath, '.js');
const sourceMapFile = { path: newPath + '.map', content: transpileOutput.sourceMapText };
let jsContent: string = transpileOutput.outputText;
if (workerConfig.inlineTemplate) {
// use original path for template inlining
jsContent = inlineTemplate(transpileOutput.outputText, filePath);
}
const jsFile = { path: newPath, content: jsContent };
const tsFile = { path: filePath, content: sourceText };
context.fileCache.set(sourceMapFile.path, sourceMapFile);
context.fileCache.set(jsFile.path, jsFile);
context.fileCache.set(tsFile.path, tsFile);
}
return Promise.resolve();
} catch (ex) {
return Promise.reject(ex);
}
}
export function transpileDiagnosticsOnly(context: BuildContext) {
return new Promise(resolve => {
workerEvent.once('DiagnosticsWorkerDone', () => {
resolve();
});
runDiagnosticsWorker(context);
});
}
const workerEvent = new EventEmitter();
let diagnosticsWorker: ChildProcess = null;
function runDiagnosticsWorker(context: BuildContext) {
if (!diagnosticsWorker) {
const workerModule = path.join(__dirname, 'transpile-worker.js');
diagnosticsWorker = fork(workerModule, [], { env: { FORCE_COLOR: true } });
Logger.debug(`diagnosticsWorker created, pid: ${diagnosticsWorker.pid}`);
diagnosticsWorker.on('error', (err: any) => {
Logger.error(`diagnosticsWorker error, pid: ${diagnosticsWorker.pid}, error: ${err}`);
workerEvent.emit('DiagnosticsWorkerDone');
});
diagnosticsWorker.on('exit', (code: number) => {
Logger.debug(`diagnosticsWorker exited, pid: ${diagnosticsWorker.pid}`);
diagnosticsWorker = null;
});
diagnosticsWorker.on('message', (msg: TranspileWorkerMessage) => {
workerEvent.emit('DiagnosticsWorkerDone');
});
}
const msg: TranspileWorkerMessage = {
rootDir: context.rootDir,
buildDir: context.buildDir,
configFile: getTsConfigPath(context)
};
diagnosticsWorker.send(msg);
}
export interface TranspileWorkerMessage {
rootDir?: string;
buildDir?: string;
configFile?: string;
transpileSuccess?: boolean;
}
function cleanFileNames(context: BuildContext, fileNames: string[]) {
// make sure we're not transpiling the prod when dev and stuff
return fileNames;
}
function writeTranspiledFilesCallback(fileCache: FileCache, sourcePath: string, data: string, shouldInlineTemplate: boolean) {
sourcePath = path.normalize(path.resolve(sourcePath));
if (sourcePath.endsWith('.js')) {
let file = fileCache.get(sourcePath);
if (!file) {
file = { content: '', path: sourcePath };
}
if (shouldInlineTemplate) {
file.content = inlineTemplate(data, sourcePath);
} else {
file.content = data;
}
fileCache.set(sourcePath, file);
} else if (sourcePath.endsWith('.js.map')) {
let file = fileCache.get(sourcePath);
if (!file) {
file = { content: '', path: sourcePath };
}
file.content = data;
fileCache.set(sourcePath, file);
}
}
export async function getTsConfigAsync(context: BuildContext, tsConfigPath?: string): Promise<TsConfig> {
return await getTsConfig(context, tsConfigPath);
}
export function getTsConfig(context: BuildContext, tsConfigPath?: string): TsConfig {
let config: TsConfig = null;
tsConfigPath = tsConfigPath || getTsConfigPath(context);
const tsConfigFile = ts.readConfigFile(tsConfigPath, path => readFileSync(path, 'utf8'));
if (!tsConfigFile) {
throw new BuildError(`tsconfig: invalid tsconfig file, "${tsConfigPath}"`);
} else if (tsConfigFile.error && tsConfigFile.error.messageText) {
throw new BuildError(`tsconfig: ${tsConfigFile.error.messageText}`);
} else if (!tsConfigFile.config) {
throw new BuildError(`tsconfig: invalid config, "${tsConfigPath}""`);
} else {
const parsedConfig = ts.parseJsonConfigFileContent(
tsConfigFile.config,
ts.sys, context.rootDir,
{}, tsConfigPath);
const diagnostics = runTypeScriptDiagnostics(context, parsedConfig.errors);
if (diagnostics.length) {
printDiagnostics(context, DiagnosticsType.TypeScript, diagnostics, true, true);
throw new BuildError(`tsconfig: invalid config, "${tsConfigPath}""`);
}
config = {
options: parsedConfig.options,
fileNames: parsedConfig.fileNames,
raw: parsedConfig.raw
};
}
return config;
}
export function transpileTsString(context: BuildContext, filePath: string, stringToTranspile: string, ) {
if (!cachedTsConfig) {
cachedTsConfig = getTsConfig(context);
}
const transpileOptions: ts.TranspileOptions = {
compilerOptions: cachedTsConfig.options,
fileName: filePath,
reportDiagnostics: true,
};
transpileOptions.compilerOptions.allowJs = true;
transpileOptions.compilerOptions.sourceMap = true;
// transpile this one module
return ts.transpileModule(stringToTranspile, transpileOptions);
}
export function transformSource(filePath: string, input: string) {
if (isDeepLinkingFile(filePath) ) {
input = purgeDeepLinkDecorator(input);
} else if (filePath === getStringPropertyValue(Constants.ENV_APP_NG_MODULE_PATH) && !hasExistingDeepLinkConfig(filePath, input)) {
const deepLinkString = convertDeepLinkConfigEntriesToString(getParsedDeepLinkConfig());
input = getUpdatedAppNgModuleContentWithDeepLinkConfig(filePath, input, deepLinkString);
}
return input;
}
export function copyOriginalSourceFiles(fileCache: FileCache) {
const deepLinkFiles = filterTypescriptFilesForDeepLinks(fileCache);
const appNgModule = fileCache.get(getStringPropertyValue(Constants.ENV_APP_NG_MODULE_PATH));
deepLinkFiles.push(appNgModule);
deepLinkFiles.forEach(deepLinkFile => {
fileCache.set(deepLinkFile.path + inMemoryFileCopySuffix, {
path: deepLinkFile.path + inMemoryFileCopySuffix,
content: deepLinkFile.content
});
});
}
export function resetSourceFiles(fileCache: FileCache) {
fileCache.getAll().forEach(file => {
if (path.extname(file.path) === `.ts${inMemoryFileCopySuffix}`) {
const originalExtension = changeExtension(file.path, '.ts');
fileCache.set(originalExtension, {
path: originalExtension,
content: file.content
});
fileCache.getRawStore().delete(file.path);
}
});
}
export const inMemoryFileCopySuffix = 'original';
let cachedProgram: ts.Program = null;
let cachedTsConfig: TsConfig = null;
export function getTsConfigPath(context: BuildContext) {
return process.env[Constants.ENV_TS_CONFIG];
}
export interface TsConfig {
options: ts.CompilerOptions;
fileNames: string[];
raw: any;
}
export interface TranspileWorkerConfig {
configFile: string;
writeInMemory: boolean;
sourceMaps: boolean;
cache: boolean;
inlineTemplate: boolean;
useTransforms: boolean;
}