-
Notifications
You must be signed in to change notification settings - Fork 12k
/
compiler-plugin.ts
579 lines (510 loc) · 21.5 KB
/
compiler-plugin.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
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
/**
* @license
* Copyright Google LLC 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
*/
import type {
BuildFailure,
Metafile,
OnStartResult,
OutputFile,
PartialMessage,
Plugin,
PluginBuild,
} from 'esbuild';
import assert from 'node:assert';
import * as path from 'node:path';
import { maxWorkers, useTypeChecking } from '../../../utils/environment-options';
import { JavaScriptTransformer } from '../javascript-transformer';
import { LoadResultCache, createCachedLoad } from '../load-result-cache';
import { logCumulativeDurations, profileAsync, resetCumulativeDurations } from '../profiling';
import { BundleStylesheetOptions } from '../stylesheets/bundle-options';
import { AngularHostOptions } from './angular-host';
import {
AngularCompilation,
DiagnosticModes,
NoopCompilation,
createAngularCompilation,
} from './compilation';
import { SharedTSCompilationState, getSharedCompilationState } from './compilation-state';
import { ComponentStylesheetBundler } from './component-stylesheets';
import { FileReferenceTracker } from './file-reference-tracker';
import { setupJitPluginCallbacks } from './jit-plugin-callbacks';
import { SourceFileCache } from './source-file-cache';
export interface CompilerPluginOptions {
sourcemap: boolean;
tsconfig: string;
jit?: boolean;
/** Skip TypeScript compilation setup. This is useful to re-use the TypeScript compilation from another plugin. */
noopTypeScriptCompilation?: boolean;
advancedOptimizations?: boolean;
thirdPartySourcemaps?: boolean;
fileReplacements?: Record<string, string>;
sourceFileCache?: SourceFileCache;
loadResultCache?: LoadResultCache;
incremental: boolean;
}
// eslint-disable-next-line max-lines-per-function
export function createCompilerPlugin(
pluginOptions: CompilerPluginOptions,
styleOptions: BundleStylesheetOptions & { inlineStyleLanguage: string },
): Plugin {
return {
name: 'angular-compiler',
// eslint-disable-next-line max-lines-per-function
async setup(build: PluginBuild): Promise<void> {
let setupWarnings: PartialMessage[] | undefined = [];
const preserveSymlinks = build.initialOptions.preserveSymlinks;
// Initialize a worker pool for JavaScript transformations
const javascriptTransformer = new JavaScriptTransformer(pluginOptions, maxWorkers);
// Setup defines based on the values used by the Angular compiler-cli
build.initialOptions.define ??= {};
build.initialOptions.define['ngI18nClosureMode'] ??= 'false';
// The in-memory cache of TypeScript file outputs will be used during the build in `onLoad` callbacks for TS files.
// A string value indicates direct TS/NG output and a Uint8Array indicates fully transformed code.
const typeScriptFileCache =
pluginOptions.sourceFileCache?.typeScriptFileCache ??
new Map<string, string | Uint8Array>();
// The resources from component stylesheets and web workers that will be added to the build results output files
const additionalResults = new Map<
string,
{ outputFiles?: OutputFile[]; metafile?: Metafile; errors?: PartialMessage[] }
>();
// Create new reusable compilation for the appropriate mode based on the `jit` plugin option
const compilation: AngularCompilation = pluginOptions.noopTypeScriptCompilation
? new NoopCompilation()
: await createAngularCompilation(!!pluginOptions.jit);
// Compilation is initially assumed to have errors until emitted
let hasCompilationErrors = true;
// Determines if TypeScript should process JavaScript files based on tsconfig `allowJs` option
let shouldTsIgnoreJs = true;
// Track incremental component stylesheet builds
const stylesheetBundler = new ComponentStylesheetBundler(
styleOptions,
pluginOptions.incremental,
);
let sharedTSCompilationState: SharedTSCompilationState | undefined;
// To fully invalidate files, track resource referenced files and their referencing source
const referencedFileTracker = new FileReferenceTracker();
// eslint-disable-next-line max-lines-per-function
build.onStart(async () => {
sharedTSCompilationState = getSharedCompilationState();
if (!(compilation instanceof NoopCompilation)) {
sharedTSCompilationState.markAsInProgress();
}
const result: OnStartResult = {
warnings: setupWarnings,
};
// Reset debug performance tracking
resetCumulativeDurations();
// Update the reference tracker and generate a full set of modified files for the
// Angular compiler which does not have direct knowledge of transitive resource
// dependencies or web worker processing.
let modifiedFiles;
if (
pluginOptions.sourceFileCache?.modifiedFiles.size &&
referencedFileTracker &&
!pluginOptions.noopTypeScriptCompilation
) {
// TODO: Differentiate between changed input files and stale output files
modifiedFiles = referencedFileTracker.update(pluginOptions.sourceFileCache.modifiedFiles);
pluginOptions.sourceFileCache.invalidate(modifiedFiles);
stylesheetBundler.invalidate(modifiedFiles);
}
if (
!pluginOptions.noopTypeScriptCompilation &&
compilation.update &&
pluginOptions.sourceFileCache?.modifiedFiles.size
) {
await compilation.update(modifiedFiles ?? pluginOptions.sourceFileCache.modifiedFiles);
}
// Create Angular compiler host options
const hostOptions: AngularHostOptions = {
fileReplacements: pluginOptions.fileReplacements,
modifiedFiles,
sourceFileCache: pluginOptions.sourceFileCache,
async transformStylesheet(data, containingFile, stylesheetFile) {
let stylesheetResult;
// Stylesheet file only exists for external stylesheets
if (stylesheetFile) {
stylesheetResult = await stylesheetBundler.bundleFile(stylesheetFile);
} else {
stylesheetResult = await stylesheetBundler.bundleInline(
data,
containingFile,
styleOptions.inlineStyleLanguage,
);
}
const { contents, outputFiles, metafile, referencedFiles, errors, warnings } =
stylesheetResult;
if (errors) {
(result.errors ??= []).push(...errors);
}
(result.warnings ??= []).push(...warnings);
additionalResults.set(stylesheetFile ?? containingFile, {
outputFiles,
metafile,
});
if (referencedFiles) {
referencedFileTracker.add(containingFile, referencedFiles);
if (stylesheetFile) {
// Angular AOT compiler needs modified direct resource files to correctly invalidate its analysis
referencedFileTracker.add(stylesheetFile, referencedFiles);
}
}
return contents;
},
processWebWorker(workerFile, containingFile) {
const fullWorkerPath = path.join(path.dirname(containingFile), workerFile);
// The synchronous API must be used due to the TypeScript compilation currently being
// fully synchronous and this process callback being called from within a TypeScript
// transformer.
const workerResult = bundleWebWorker(build, pluginOptions, fullWorkerPath);
(result.warnings ??= []).push(...workerResult.warnings);
if (workerResult.errors.length > 0) {
(result.errors ??= []).push(...workerResult.errors);
// Track worker file errors to allow rebuilds on changes
referencedFileTracker.add(
containingFile,
workerResult.errors
.map((error) => error.location?.file)
.filter((file): file is string => !!file)
.map((file) => path.join(build.initialOptions.absWorkingDir ?? '', file)),
);
additionalResults.set(fullWorkerPath, { errors: result.errors });
// Return the original path if the build failed
return workerFile;
}
assert('outputFiles' in workerResult, 'Invalid web worker bundle result.');
additionalResults.set(fullWorkerPath, {
outputFiles: workerResult.outputFiles,
metafile: workerResult.metafile,
});
referencedFileTracker.add(
containingFile,
Object.keys(workerResult.metafile.inputs).map((input) =>
path.join(build.initialOptions.absWorkingDir ?? '', input),
),
);
// Return bundled worker file entry name to be used in the built output
const workerCodeFile = workerResult.outputFiles.find((file) =>
/^worker-[A-Z0-9]{8}.[cm]?js$/.test(path.basename(file.path)),
);
assert(workerCodeFile, 'Web Worker bundled code file should always be present.');
const workerCodePath = path.relative(
build.initialOptions.outdir ?? '',
workerCodeFile.path,
);
return workerCodePath.replaceAll('\\', '/');
},
};
// Initialize the Angular compilation for the current build.
// In watch mode, previous build state will be reused.
let referencedFiles;
try {
const initializationResult = await compilation.initialize(
pluginOptions.tsconfig,
hostOptions,
createCompilerOptionsTransformer(setupWarnings, pluginOptions, preserveSymlinks),
);
shouldTsIgnoreJs = !initializationResult.compilerOptions.allowJs;
referencedFiles = initializationResult.referencedFiles;
} catch (error) {
(result.errors ??= []).push({
text: 'Angular compilation initialization failed.',
location: null,
notes: [
{
text: error instanceof Error ? error.stack ?? error.message : `${error}`,
location: null,
},
],
});
// Initialization failure prevents further compilation steps
hasCompilationErrors = true;
return result;
}
if (compilation instanceof NoopCompilation) {
hasCompilationErrors = await sharedTSCompilationState.waitUntilReady;
return result;
}
// Update TypeScript file output cache for all affected files
try {
await profileAsync('NG_EMIT_TS', async () => {
for (const { filename, contents } of await compilation.emitAffectedFiles()) {
typeScriptFileCache.set(path.normalize(filename), contents);
}
});
} catch (error) {
(result.errors ??= []).push({
text: 'Angular compilation emit failed.',
location: null,
notes: [
{
text: error instanceof Error ? error.stack ?? error.message : `${error}`,
location: null,
},
],
});
}
const diagnostics = await compilation.diagnoseFiles(
useTypeChecking ? DiagnosticModes.All : DiagnosticModes.All & ~DiagnosticModes.Semantic,
);
if (diagnostics.errors?.length) {
(result.errors ??= []).push(...diagnostics.errors);
}
if (diagnostics.warnings?.length) {
(result.warnings ??= []).push(...diagnostics.warnings);
}
// Add errors from failed additional results.
// This must be done after emit to capture latest web worker results.
for (const { errors } of additionalResults.values()) {
if (errors) {
(result.errors ??= []).push(...errors);
}
}
// Store referenced files for updated file watching if enabled
if (pluginOptions.sourceFileCache) {
pluginOptions.sourceFileCache.referencedFiles = [
...referencedFiles,
...referencedFileTracker.referencedFiles,
];
}
hasCompilationErrors = !!result.errors?.length;
// Reset the setup warnings so that they are only shown during the first build.
setupWarnings = undefined;
sharedTSCompilationState.markAsReady(hasCompilationErrors);
return result;
});
build.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async (args) => {
const request = path.normalize(
pluginOptions.fileReplacements?.[path.normalize(args.path)] ?? args.path,
);
// Skip TS load attempt if JS TypeScript compilation not enabled and file is JS
if (shouldTsIgnoreJs && /\.[cm]?js$/.test(request)) {
return undefined;
}
// The filename is currently used as a cache key. Since the cache is memory only,
// the options cannot change and do not need to be represented in the key. If the
// cache is later stored to disk, then the options that affect transform output
// would need to be added to the key as well as a check for any change of content.
let contents = typeScriptFileCache.get(request);
if (contents === undefined) {
// If the Angular compilation had errors the file may not have been emitted.
// To avoid additional errors about missing files, return empty contents.
if (hasCompilationErrors) {
return { contents: '', loader: 'js' };
}
// No TS result indicates the file is not part of the TypeScript program.
// If allowJs is enabled and the file is JS then defer to the next load hook.
if (!shouldTsIgnoreJs && /\.[cm]?js$/.test(request)) {
return undefined;
}
// Otherwise return an error
return {
errors: [
createMissingFileError(request, args.path, build.initialOptions.absWorkingDir ?? ''),
],
};
} else if (typeof contents === 'string') {
// A string indicates untransformed output from the TS/NG compiler
const sideEffects = await hasSideEffects(request);
contents = await javascriptTransformer.transformData(
request,
contents,
true /* skipLinker */,
sideEffects,
);
// Store as the returned Uint8Array to allow caching the fully transformed code
typeScriptFileCache.set(request, contents);
}
return {
contents,
loader: 'js',
};
});
build.onLoad(
{ filter: /\.[cm]?js$/ },
createCachedLoad(pluginOptions.loadResultCache, async (args) => {
return profileAsync(
'NG_EMIT_JS*',
async () => {
const sideEffects = await hasSideEffects(args.path);
const contents = await javascriptTransformer.transformFile(
args.path,
pluginOptions.jit,
sideEffects,
);
return {
contents,
loader: 'js',
};
},
true,
);
}),
);
// Setup bundling of component templates and stylesheets when in JIT mode
if (pluginOptions.jit) {
setupJitPluginCallbacks(
build,
stylesheetBundler,
additionalResults,
styleOptions.inlineStyleLanguage,
pluginOptions.loadResultCache,
);
}
build.onEnd((result) => {
// Ensure other compilations are unblocked if the main compilation throws during start
sharedTSCompilationState?.markAsReady(hasCompilationErrors);
for (const { outputFiles, metafile } of additionalResults.values()) {
// Add any additional output files to the main output files
if (outputFiles?.length) {
result.outputFiles?.push(...outputFiles);
}
// Combine additional metafiles with main metafile
if (result.metafile && metafile) {
// Append the existing object, by appending to it we prevent unnecessary new objections creations with spread
// mitigating significant performance overhead for large apps.
// See: https://bugs.chromium.org/p/v8/issues/detail?id=11536
Object.assign(result.metafile.inputs, metafile.inputs);
Object.assign(result.metafile.outputs, metafile.outputs);
}
}
logCumulativeDurations();
});
build.onDispose(() => {
sharedTSCompilationState?.dispose();
void stylesheetBundler.dispose();
void compilation.close?.();
});
/**
* Checks if the file has side-effects when `advancedOptimizations` is enabled.
*/
async function hasSideEffects(path: string): Promise<boolean | undefined> {
if (!pluginOptions.advancedOptimizations) {
return undefined;
}
const { sideEffects } = await build.resolve(path, {
kind: 'import-statement',
resolveDir: build.initialOptions.absWorkingDir ?? '',
});
return sideEffects;
}
},
};
}
function createCompilerOptionsTransformer(
setupWarnings: PartialMessage[] | undefined,
pluginOptions: CompilerPluginOptions,
preserveSymlinks: boolean | undefined,
): Parameters<AngularCompilation['initialize']>[2] {
return (compilerOptions) => {
// target of 9 is ES2022 (using the number avoids an expensive import of typescript just for an enum)
if (compilerOptions.target === undefined || compilerOptions.target < 9 /** ES2022 */) {
// If 'useDefineForClassFields' is already defined in the users project leave the value as is.
// Otherwise fallback to false due to https://github.com/microsoft/TypeScript/issues/45995
// which breaks the deprecated `@Effects` NGRX decorator and potentially other existing code as well.
compilerOptions.target = 9 /** ES2022 */;
compilerOptions.useDefineForClassFields ??= false;
// Only add the warning on the initial build
setupWarnings?.push({
text:
`TypeScript compiler options 'target' and 'useDefineForClassFields' are set to 'ES2022' and ` +
`'false' respectively by the Angular CLI.`,
location: { file: pluginOptions.tsconfig },
notes: [
{
text:
'To control ECMA version and features use the Browserslist configuration. ' +
'For more information, see https://angular.io/guide/build#configuring-browser-compatibility',
},
],
});
}
if (compilerOptions.compilationMode === 'partial') {
setupWarnings?.push({
text: 'Angular partial compilation mode is not supported when building applications.',
location: null,
notes: [{ text: 'Full compilation mode will be used instead.' }],
});
compilerOptions.compilationMode = 'full';
}
// Enable incremental compilation by default if caching is enabled
if (pluginOptions.sourceFileCache?.persistentCachePath) {
compilerOptions.incremental ??= true;
// Set the build info file location to the configured cache directory
compilerOptions.tsBuildInfoFile = path.join(
pluginOptions.sourceFileCache?.persistentCachePath,
'.tsbuildinfo',
);
} else {
compilerOptions.incremental = false;
}
if (compilerOptions.module === undefined || compilerOptions.module < 5 /** ES2015 */) {
compilerOptions.module = 7; /** ES2022 */
setupWarnings?.push({
text: `TypeScript compiler options 'module' values 'CommonJS', 'UMD', 'System' and 'AMD' are not supported.`,
location: null,
notes: [{ text: `The 'module' option will be set to 'ES2022' instead.` }],
});
}
return {
...compilerOptions,
noEmitOnError: false,
inlineSources: pluginOptions.sourcemap,
inlineSourceMap: pluginOptions.sourcemap,
mapRoot: undefined,
sourceRoot: undefined,
preserveSymlinks,
};
};
}
function bundleWebWorker(
build: PluginBuild,
pluginOptions: CompilerPluginOptions,
workerFile: string,
) {
try {
return build.esbuild.buildSync({
...build.initialOptions,
platform: 'browser',
write: false,
bundle: true,
metafile: true,
format: 'esm',
entryNames: 'worker-[hash]',
entryPoints: [workerFile],
sourcemap: pluginOptions.sourcemap,
// Zone.js is not used in Web workers so no need to disable
supported: undefined,
// Plugins are not supported in sync esbuild calls
plugins: undefined,
});
} catch (error) {
if (error && typeof error === 'object' && 'errors' in error && 'warnings' in error) {
return error as BuildFailure;
}
throw error;
}
}
function createMissingFileError(request: string, original: string, root: string): PartialMessage {
const relativeRequest = path.relative(root, request);
const error = {
text: `File '${relativeRequest}' is missing from the TypeScript compilation.`,
notes: [
{
text: `Ensure the file is part of the TypeScript program via the 'files' or 'include' property.`,
},
],
};
const relativeOriginal = path.relative(root, original);
if (relativeRequest !== relativeOriginal) {
error.notes.push({
text: `File is requested from a file replacement of '${relativeOriginal}'.`,
});
}
return error;
}