forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathplugins.ts
More file actions
550 lines (489 loc) · 18.5 KB
/
plugins.ts
File metadata and controls
550 lines (489 loc) · 18.5 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
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
/**
* @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.dev/license
*/
import assert from 'node:assert';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { platform } from 'node:os';
import path from 'node:path';
import type {
BrowserConfigOptions,
InlineConfig,
ResolvedConfig,
UserWorkspaceConfig,
VitestPlugin,
} from 'vitest/node';
import { createBuildAssetsMiddleware } from '../../../../tools/vite/middlewares/assets-middleware';
import { toPosixPath } from '../../../../utils/path';
import type { ResultFile } from '../../../application/results';
import type { NormalizedUnitTestBuilderOptions } from '../../options';
import { normalizeBrowserName } from './browser-provider';
interface ExistingRawSourceMap {
sources?: string[];
sourcesContent?: string[];
mappings?: string;
}
type VitestPlugins = Awaited<ReturnType<typeof VitestPlugin>>;
interface PluginOptions {
workspaceRoot: string;
projectSourceRoot: string;
projectName: string;
buildResultFiles: ReadonlyMap<string, ResultFile>;
testFileToEntryPoint: ReadonlyMap<string, string>;
}
type VitestCoverageOption = Exclude<InlineConfig['coverage'], undefined>;
interface VitestConfigPluginOptions {
browser: BrowserConfigOptions | undefined;
coverage: NormalizedUnitTestBuilderOptions['coverage'];
projectName: string;
projectSourceRoot: string;
reporters?: string[] | [string, object][];
setupFiles: string[];
projectPlugins: Exclude<UserWorkspaceConfig['plugins'], undefined>;
include: string[];
optimizeDepsInclude: string[];
watch: boolean;
}
async function findTestEnvironment(
projectResolver: NodeJS.RequireResolve,
): Promise<'jsdom' | 'happy-dom'> {
try {
projectResolver('happy-dom');
return 'happy-dom';
} catch {
// happy-dom is not installed, fallback to jsdom
return 'jsdom';
}
}
export async function createVitestConfigPlugin(
options: VitestConfigPluginOptions,
): Promise<VitestPlugins[0]> {
const {
include,
browser,
projectName,
reporters,
setupFiles,
projectPlugins,
projectSourceRoot,
} = options;
const { mergeConfig } = await import('vitest/config');
return {
name: 'angular:vitest-configuration',
async config(config) {
const testConfig = config.test;
if (reporters !== undefined) {
delete testConfig?.reporters;
}
if (
options.coverage.reporters !== undefined &&
testConfig?.coverage &&
'reporter' in testConfig.coverage
) {
delete testConfig.coverage.reporter;
}
if (testConfig?.projects?.length) {
this.warn(
'The "test.projects" option in the Vitest configuration file is not supported. ' +
'The Angular CLI Test system will construct its own project configuration.',
);
delete testConfig.projects;
}
if (testConfig?.include) {
this.warn(
'The "test.include" option in the Vitest configuration file is not supported. ' +
'The Angular CLI Test system will manage test file discovery.',
);
delete testConfig.include;
}
if (testConfig?.watch !== undefined && testConfig.watch !== options.watch) {
this.warn(
`The "test.watch" option in the Vitest configuration file is overridden by the builder's ` +
`watch option. Please use the Angular CLI "--watch" option to enable or disable watch mode.`,
);
delete testConfig.watch;
}
if (testConfig?.exclude) {
this.warn(
'The "test.exclude" option in the Vitest configuration file is evaluated after ' +
'tests are compiled. For better build performance, please use the Angular CLI ' +
'"exclude" option instead.',
);
}
// Merge user-defined plugins from the Vitest config with the CLI's internal plugins.
if (config.plugins) {
const userPlugins = config.plugins.filter(
(plugin) =>
// Only inspect objects with a `name` property as these would be the internal injected plugins
!plugin ||
typeof plugin !== 'object' ||
!('name' in plugin) ||
(!plugin.name.startsWith('angular:') && !plugin.name.startsWith('vitest')),
);
if (userPlugins.length > 0) {
projectPlugins.push(...userPlugins);
}
delete config.plugins;
}
// Add browser source map support if coverage is enabled
if (
(browser || testConfig?.browser?.enabled) &&
(options.coverage.enabled || testConfig?.coverage?.enabled)
) {
// Validate that enabled browsers support V8 coverage
validateBrowserCoverage(browser, testConfig?.browser);
projectPlugins.unshift(createSourcemapSupportPlugin());
setupFiles.unshift('virtual:source-map-support');
}
const projectResolver = createRequire(projectSourceRoot + '/').resolve;
const projectDefaults: UserWorkspaceConfig = {
test: {
setupFiles,
globals: true,
// Default to `false` to align with the Karma/Jasmine experience.
isolate: false,
sequence: { setupFiles: 'list' },
},
optimizeDeps: {
noDiscovery: true,
include: options.optimizeDepsInclude,
},
resolve: {
mainFields: ['es2020', 'module', 'main'],
conditions: ['es2015', 'es2020', 'module', ...(browser ? ['browser'] : [])],
},
};
const { optimizeDeps, resolve } = config;
const projectOverrides: UserWorkspaceConfig = {
test: {
name: projectName,
include,
// CLI provider browser options override, if present
...(browser ? { browser } : {}),
// If the user has not specified an environment, use a smart default.
...(!testConfig?.environment
? { environment: await findTestEnvironment(projectResolver) }
: {}),
},
plugins: projectPlugins,
optimizeDeps,
resolve,
};
const projectBase = mergeConfig(projectDefaults, testConfig ? { test: testConfig } : {});
const projectConfig = mergeConfig(projectBase, projectOverrides);
return {
test: {
coverage: await generateCoverageOption(
options.coverage,
testConfig?.coverage,
projectName,
),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
...(reporters ? ({ reporters } as any) : {}),
projects: [projectConfig],
},
};
},
};
}
const textDecoder = new TextDecoder('utf-8');
async function loadResultFile(file: ResultFile): Promise<string> {
if (file.origin === 'memory') {
return textDecoder.decode(file.contents);
}
return readFile(file.inputPath, 'utf-8');
}
export function createVitestPlugins(pluginOptions: PluginOptions): VitestPlugins {
const { workspaceRoot, buildResultFiles, testFileToEntryPoint } = pluginOptions;
const isWindows = platform() === 'win32';
let vitestConfig: ResolvedConfig;
return [
{
name: 'angular:test-in-memory-provider',
enforce: 'pre',
configureVitest(context) {
vitestConfig = context.vitest.config;
},
resolveId: (id, importer) => {
// Fast path for test entry points.
if (testFileToEntryPoint.has(id)) {
return id;
}
// Workaround for Vitest in Windows when a fully qualified absolute path is provided with
// a superfluous leading slash. This can currently occur with the `@vitest/coverage-v8` provider
// when it uses `removeStartsWith(url, FILE_PROTOCOL)` to convert a file URL resulting in
// `/D:/tmp_dir/...` instead of `D:/tmp_dir/...`.
if (id[0] === '/' && isWindows) {
const slicedId = id.slice(1);
if (path.isAbsolute(slicedId)) {
return slicedId;
}
}
// Determine the base directory for resolution.
let baseDir: string;
if (importer) {
// If the importer is a test entry point, resolve relative to the workspace root.
// Otherwise, resolve relative to the importer's directory.
baseDir = testFileToEntryPoint.has(importer) ? workspaceRoot : path.dirname(importer);
} else {
// If there's no importer, assume the id is relative to the workspace root.
baseDir = workspaceRoot;
}
// Construct the full, absolute path and normalize it to POSIX format.
let fullPath: string;
if (path.isAbsolute(id)) {
const relativeId = path.relative(baseDir, id);
fullPath =
!relativeId.startsWith('..') && !path.isAbsolute(relativeId)
? id
: path.join(baseDir, id);
} else {
fullPath = path.join(baseDir, id);
}
fullPath = toPosixPath(fullPath);
if (testFileToEntryPoint.has(fullPath)) {
return fullPath;
}
// Check if the resolved path corresponds to a known build artifact.
const relativePath = path.relative(workspaceRoot, fullPath);
if (buildResultFiles.has(toPosixPath(relativePath))) {
return fullPath;
}
// If the module cannot be resolved from the build artifacts, let other plugins handle it.
return undefined;
},
async load(id) {
assert(buildResultFiles.size > 0, 'buildResult must be available for in-memory loading.');
// Attempt to load as a source test file.
const entryPoint = testFileToEntryPoint.get(id);
let outputPath;
if (entryPoint) {
outputPath = entryPoint + '.js';
if (vitestConfig?.coverage?.enabled) {
// To support coverage exclusion of the actual test file, the virtual
// test entry point only references the built and bundled intermediate file.
// If vitest supported an "excludeOnlyAfterRemap" option, this could be removed completely.
return {
code: `import "./${outputPath}";`,
};
}
} else {
// Attempt to load as a built artifact.
const relativePath = path.relative(workspaceRoot, id);
outputPath = toPosixPath(relativePath);
}
const outputFile = buildResultFiles.get(outputPath);
if (outputFile) {
const code = await loadResultFile(outputFile);
const sourceMapPath = outputPath + '.map';
const sourceMapFile = buildResultFiles.get(sourceMapPath);
const sourceMapText = sourceMapFile ? await loadResultFile(sourceMapFile) : undefined;
const map = sourceMapText ? JSON.parse(sourceMapText) : undefined;
if (map) {
adjustSourcemapSources(map, !vitestConfig?.coverage?.enabled, workspaceRoot, id);
}
return {
code,
map,
};
}
},
configureServer: (server) => {
server.middlewares.use(createBuildAssetsMiddleware(server.config.base, buildResultFiles));
},
},
{
name: 'angular:html-index',
transformIndexHtml: () => {
// Add all global stylesheets
if (buildResultFiles.has('styles.css')) {
return [
{
tag: 'link',
attrs: { href: 'styles.css', rel: 'stylesheet' },
injectTo: 'head',
},
];
}
return [];
},
},
];
}
/**
* Adjusts the sources field in a sourcemap to ensure correct source mapping and coverage reporting.
*
* @param map The raw sourcemap to adjust.
* @param rebaseSources Whether to rebase the source paths relative to the test file.
* @param workspaceRoot The root directory of the workspace.
* @param id The ID (path) of the file being loaded.
*/
function adjustSourcemapSources(
map: ExistingRawSourceMap,
rebaseSources: boolean,
workspaceRoot: string,
id: string,
): void {
if (!map.sources?.length && !map.sourcesContent?.length && !map.mappings) {
// Vitest will include files in the coverage report if the sourcemap contains no sources.
// For builder-internal generated code chunks, which are typically helper functions,
// a virtual source is added to the sourcemap to prevent them from being incorrectly
// included in the final coverage report.
map.sources = ['virtual:builder'];
} else if (rebaseSources && map.sources) {
map.sources = map.sources.map((source) => {
if (!source || source.startsWith('angular:')) {
return source;
}
// source is relative to the workspace root because the output file is at the root of the output.
const absoluteSource = path.join(workspaceRoot, source);
return toPosixPath(path.relative(path.dirname(id), absoluteSource));
});
}
}
function createSourcemapSupportPlugin(): VitestPlugins[0] {
return {
name: 'angular:source-map-support',
enforce: 'pre',
resolveId(source) {
if (source.includes('virtual:source-map-support')) {
return '\0source-map-support';
}
},
async load(id) {
if (id !== '\0source-map-support') {
return;
}
const packageResolve = createRequire(__filename).resolve;
const supportPath = packageResolve('source-map-support/browser-source-map-support.js');
const content = await readFile(supportPath, 'utf-8');
// The `source-map-support` library currently relies on `this` being defined in the global scope.
// However, when running in an ESM environment, `this` is undefined.
// To workaround this, we patch the library to use `globalThis` instead of `this`.
return (
content.replaceAll(/this\.(define|sourceMapSupport|base64js)/g, 'globalThis.$1') +
'\n;globalThis.sourceMapSupport.install();'
);
},
};
}
interface CustomBrowserConfigOptions {
instances?: { browser: string }[];
name?: string;
}
/**
* Validates that all enabled browsers support V8 coverage when coverage is enabled.
* Throws an error if an unsupported browser is detected.
*/
function validateBrowserCoverage(
browser: BrowserConfigOptions | undefined,
testConfigBrowser: BrowserConfigOptions | undefined,
): void {
const browsersToCheck: string[] = [];
// 1. Check browsers passed by the Angular CLI options
const cliBrowser = browser as CustomBrowserConfigOptions | undefined;
if (cliBrowser?.instances) {
browsersToCheck.push(...cliBrowser.instances.map((i) => i.browser));
}
// 2. Check browsers defined in the user's vitest.config.ts
const userBrowser = testConfigBrowser as CustomBrowserConfigOptions | undefined;
if (userBrowser) {
if (userBrowser.instances) {
browsersToCheck.push(...userBrowser.instances.map((i) => i.browser));
}
if (userBrowser.name) {
browsersToCheck.push(userBrowser.name);
}
}
// Normalize and filter unsupported browsers
const unsupportedBrowsers = browsersToCheck
.map((b) => normalizeBrowserName(b).browser)
.filter((b) => !['chrome', 'chromium', 'edge'].includes(b));
if (unsupportedBrowsers.length > 0) {
throw new Error(
`Code coverage is enabled, but the following configured browsers do not support the V8 coverage provider: ` +
`${unsupportedBrowsers.join(', ')}. ` +
`V8 coverage is only supported on Chromium-based browsers (e.g., Chrome, Chromium, Edge). ` +
`Please disable coverage or remove the unsupported browsers.`,
);
}
}
async function generateCoverageOption(
optionsCoverage: NormalizedUnitTestBuilderOptions['coverage'],
configCoverage: VitestCoverageOption | undefined,
projectName: string,
): Promise<VitestCoverageOption> {
let defaultExcludes: string[] = [];
// When a coverage exclude option is provided, Vitest's default coverage excludes
// will be overridden. To retain them, we manually fetch the defaults to append to the
// user's provided exclusions.
if (optionsCoverage.exclude) {
try {
const vitestConfig = await import('vitest/config');
defaultExcludes = vitestConfig.coverageConfigDefaults.exclude;
} catch {}
}
return {
excludeAfterRemap: true,
reportsDirectory:
configCoverage?.reportsDirectory ?? toPosixPath(path.join('coverage', projectName)),
...(optionsCoverage.enabled !== undefined ? { enabled: optionsCoverage.enabled } : {}),
// Vitest performs a pre-check and a post-check for sourcemaps.
// The pre-check uses the bundled files, so specific bundled entry points and chunks need to be included.
// The post-check uses the original source files, so the user's include is used.
...(optionsCoverage.include
? { include: ['spec-*.js', 'chunk-*.js', ...optionsCoverage.include] }
: {}),
// The 'in' operator is used here because 'configCoverage' is a union type and
// not all coverage providers support thresholds or watermarks.
thresholds: mergeCoverageObjects(
configCoverage && 'thresholds' in configCoverage ? configCoverage.thresholds : undefined,
optionsCoverage.thresholds,
),
watermarks: mergeCoverageObjects(
configCoverage && 'watermarks' in configCoverage ? configCoverage.watermarks : undefined,
optionsCoverage.watermarks,
),
// Special handling for `exclude`/`reporters` due to an undefined value causing upstream failures
...(optionsCoverage.exclude
? {
exclude: Array.from(
new Set([
// Augment the default exclude https://vitest.dev/config/#coverage-exclude
// with the user defined exclusions
...(configCoverage?.exclude || []),
...optionsCoverage.exclude,
...defaultExcludes,
]),
),
}
: {}),
...(optionsCoverage.reporters
? ({ reporter: optionsCoverage.reporters } satisfies VitestCoverageOption)
: {}),
};
}
/**
* Merges coverage related objects while ignoring any `undefined` values.
* This ensures that Angular CLI options correctly override Vitest configuration
* only when explicitly provided.
*/
function mergeCoverageObjects<T extends object>(
configValue: T | undefined,
optionsValue: T | undefined,
): T | undefined {
if (optionsValue === undefined) {
return configValue;
}
const result: Record<string, unknown> = { ...(configValue ?? {}) };
for (const [key, value] of Object.entries(optionsValue)) {
if (value !== undefined) {
result[key] = value;
}
}
return Object.keys(result).length > 0 ? (result as T) : undefined;
}