@code-pushup/coverage-plugin 0.55.0 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/package.json +8 -7
  2. package/src/bin.js +3 -0
  3. package/src/bin.js.map +1 -0
  4. package/src/index.d.ts +3 -3
  5. package/src/index.js +4 -0
  6. package/src/index.js.map +1 -0
  7. package/src/lib/config.js +54 -0
  8. package/src/lib/config.js.map +1 -0
  9. package/src/lib/coverage-plugin.d.ts +1 -1
  10. package/src/lib/coverage-plugin.js +57 -0
  11. package/src/lib/coverage-plugin.js.map +1 -0
  12. package/src/lib/nx/coverage-paths.d.ts +1 -1
  13. package/src/lib/nx/coverage-paths.js +94 -0
  14. package/src/lib/nx/coverage-paths.js.map +1 -0
  15. package/src/lib/runner/constants.js +7 -0
  16. package/src/lib/runner/constants.js.map +1 -0
  17. package/src/lib/runner/index.d.ts +1 -1
  18. package/src/lib/runner/index.js +45 -0
  19. package/src/lib/runner/index.js.map +1 -0
  20. package/src/lib/runner/lcov/lcov-runner.d.ts +1 -1
  21. package/src/lib/runner/lcov/lcov-runner.js +90 -0
  22. package/src/lib/runner/lcov/lcov-runner.js.map +1 -0
  23. package/src/lib/runner/lcov/merge-lcov.js +103 -0
  24. package/src/lib/runner/lcov/merge-lcov.js.map +1 -0
  25. package/src/lib/runner/lcov/parse-lcov.js +5 -0
  26. package/src/lib/runner/lcov/parse-lcov.js.map +1 -0
  27. package/src/lib/runner/lcov/transform.d.ts +2 -2
  28. package/src/lib/runner/lcov/transform.js +111 -0
  29. package/src/lib/runner/lcov/transform.js.map +1 -0
  30. package/src/lib/runner/lcov/types.d.ts +1 -1
  31. package/src/lib/runner/lcov/types.js +2 -0
  32. package/src/lib/runner/lcov/types.js.map +1 -0
  33. package/src/lib/runner/lcov/utils.d.ts +1 -1
  34. package/src/lib/runner/lcov/utils.js +25 -0
  35. package/src/lib/runner/lcov/utils.js.map +1 -0
  36. package/src/lib/utils.d.ts +1 -1
  37. package/src/lib/utils.js +22 -0
  38. package/src/lib/utils.js.map +1 -0
  39. package/bin.js +0 -1236
  40. package/index.js +0 -1065
package/index.js DELETED
@@ -1,1065 +0,0 @@
1
- // packages/plugin-coverage/src/lib/coverage-plugin.ts
2
- import { dirname as dirname3, join as join3 } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
-
5
- // packages/models/src/lib/implementation/schemas.ts
6
- import { MATERIAL_ICONS } from "vscode-material-icons";
7
- import { z } from "zod";
8
-
9
- // packages/models/src/lib/implementation/limits.ts
10
- var MAX_SLUG_LENGTH = 128;
11
- var MAX_TITLE_LENGTH = 256;
12
- var MAX_DESCRIPTION_LENGTH = 65536;
13
- var MAX_ISSUE_MESSAGE_LENGTH = 1024;
14
-
15
- // packages/models/src/lib/implementation/utils.ts
16
- var slugRegex = /^[a-z\d]+(?:-[a-z\d]+)*$/;
17
- var filenameRegex = /^(?!.*[ \\/:*?"<>|]).+$/;
18
- function hasDuplicateStrings(strings) {
19
- const sortedStrings = strings.toSorted();
20
- const duplStrings = sortedStrings.filter(
21
- (item, index) => index !== 0 && item === sortedStrings[index - 1]
22
- );
23
- return duplStrings.length === 0 ? false : [...new Set(duplStrings)];
24
- }
25
- function hasMissingStrings(toCheck, existing) {
26
- const nonExisting = toCheck.filter((s) => !existing.includes(s));
27
- return nonExisting.length === 0 ? false : nonExisting;
28
- }
29
- function errorItems(items, transform = (itemArr) => itemArr.join(", ")) {
30
- return transform(items || []);
31
- }
32
- function exists(value) {
33
- return value != null;
34
- }
35
- function getMissingRefsForCategories(categories, plugins) {
36
- if (!categories || categories.length === 0) {
37
- return false;
38
- }
39
- const auditRefsFromCategory = categories.flatMap(
40
- ({ refs }) => refs.filter(({ type }) => type === "audit").map(({ plugin, slug }) => `${plugin}/${slug}`)
41
- );
42
- const auditRefsFromPlugins = plugins.flatMap(
43
- ({ audits, slug: pluginSlug }) => audits.map(({ slug }) => `${pluginSlug}/${slug}`)
44
- );
45
- const missingAuditRefs = hasMissingStrings(
46
- auditRefsFromCategory,
47
- auditRefsFromPlugins
48
- );
49
- const groupRefsFromCategory = categories.flatMap(
50
- ({ refs }) => refs.filter(({ type }) => type === "group").map(({ plugin, slug }) => `${plugin}#${slug} (group)`)
51
- );
52
- const groupRefsFromPlugins = plugins.flatMap(
53
- ({ groups, slug: pluginSlug }) => Array.isArray(groups) ? groups.map(({ slug }) => `${pluginSlug}#${slug} (group)`) : []
54
- );
55
- const missingGroupRefs = hasMissingStrings(
56
- groupRefsFromCategory,
57
- groupRefsFromPlugins
58
- );
59
- const missingRefs = [missingAuditRefs, missingGroupRefs].filter((refs) => Array.isArray(refs) && refs.length > 0).flat();
60
- return missingRefs.length > 0 ? missingRefs : false;
61
- }
62
- function missingRefsForCategoriesErrorMsg(categories, plugins) {
63
- const missingRefs = getMissingRefsForCategories(categories, plugins);
64
- return `The following category references need to point to an audit or group: ${errorItems(
65
- missingRefs
66
- )}`;
67
- }
68
-
69
- // packages/models/src/lib/implementation/schemas.ts
70
- var tableCellValueSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]).default(null);
71
- function executionMetaSchema(options = {
72
- descriptionDate: "Execution start date and time",
73
- descriptionDuration: "Execution duration in ms"
74
- }) {
75
- return z.object({
76
- date: z.string({ description: options.descriptionDate }),
77
- duration: z.number({ description: options.descriptionDuration })
78
- });
79
- }
80
- var slugSchema = z.string({ description: "Unique ID (human-readable, URL-safe)" }).regex(slugRegex, {
81
- message: "The slug has to follow the pattern [0-9a-z] followed by multiple optional groups of -[0-9a-z]. e.g. my-slug"
82
- }).max(MAX_SLUG_LENGTH, {
83
- message: `slug can be max ${MAX_SLUG_LENGTH} characters long`
84
- });
85
- var descriptionSchema = z.string({ description: "Description (markdown)" }).max(MAX_DESCRIPTION_LENGTH).optional();
86
- var urlSchema = z.string().url();
87
- var docsUrlSchema = urlSchema.optional().or(z.literal("")).describe("Documentation site");
88
- var titleSchema = z.string({ description: "Descriptive name" }).max(MAX_TITLE_LENGTH);
89
- var scoreSchema = z.number({
90
- description: "Value between 0 and 1"
91
- }).min(0).max(1);
92
- function metaSchema(options) {
93
- const {
94
- descriptionDescription,
95
- titleDescription,
96
- docsUrlDescription,
97
- description
98
- } = options ?? {};
99
- return z.object(
100
- {
101
- title: titleDescription ? titleSchema.describe(titleDescription) : titleSchema,
102
- description: descriptionDescription ? descriptionSchema.describe(descriptionDescription) : descriptionSchema,
103
- docsUrl: docsUrlDescription ? docsUrlSchema.describe(docsUrlDescription) : docsUrlSchema
104
- },
105
- { description }
106
- );
107
- }
108
- var filePathSchema = z.string().trim().min(1, { message: "path is invalid" });
109
- var fileNameSchema = z.string().trim().regex(filenameRegex, {
110
- message: `The filename has to be valid`
111
- }).min(1, { message: "file name is invalid" });
112
- var positiveIntSchema = z.number().int().positive();
113
- var nonnegativeNumberSchema = z.number().nonnegative();
114
- function packageVersionSchema(options) {
115
- const { versionDescription = "NPM version of the package", required } = options ?? {};
116
- const packageSchema = z.string({ description: "NPM package name" });
117
- const versionSchema = z.string({ description: versionDescription });
118
- return z.object(
119
- {
120
- packageName: required ? packageSchema : packageSchema.optional(),
121
- version: required ? versionSchema : versionSchema.optional()
122
- },
123
- { description: "NPM package name and version of a published package" }
124
- );
125
- }
126
- var weightSchema = nonnegativeNumberSchema.describe(
127
- "Coefficient for the given score (use weight 0 if only for display)"
128
- );
129
- function weightedRefSchema(description, slugDescription) {
130
- return z.object(
131
- {
132
- slug: slugSchema.describe(slugDescription),
133
- weight: weightSchema.describe("Weight used to calculate score")
134
- },
135
- { description }
136
- );
137
- }
138
- function scorableSchema(description, refSchema, duplicateCheckFn, duplicateMessageFn) {
139
- return z.object(
140
- {
141
- slug: slugSchema.describe('Human-readable unique ID, e.g. "performance"'),
142
- refs: z.array(refSchema).min(1).refine(
143
- (refs) => !duplicateCheckFn(refs),
144
- (refs) => ({
145
- message: duplicateMessageFn(refs)
146
- })
147
- ).refine(hasNonZeroWeightedRef, () => ({
148
- message: "In a category there has to be at least one ref with weight > 0"
149
- }))
150
- },
151
- { description }
152
- );
153
- }
154
- var materialIconSchema = z.enum(MATERIAL_ICONS, {
155
- description: "Icon from VSCode Material Icons extension"
156
- });
157
- function hasNonZeroWeightedRef(refs) {
158
- return refs.reduce((acc, { weight }) => weight + acc, 0) !== 0;
159
- }
160
-
161
- // packages/models/src/lib/source.ts
162
- import { z as z2 } from "zod";
163
- var sourceFileLocationSchema = z2.object(
164
- {
165
- file: filePathSchema.describe("Relative path to source file in Git repo"),
166
- position: z2.object(
167
- {
168
- startLine: positiveIntSchema.describe("Start line"),
169
- startColumn: positiveIntSchema.describe("Start column").optional(),
170
- endLine: positiveIntSchema.describe("End line").optional(),
171
- endColumn: positiveIntSchema.describe("End column").optional()
172
- },
173
- { description: "Location in file" }
174
- ).optional()
175
- },
176
- { description: "Source file location" }
177
- );
178
-
179
- // packages/models/src/lib/audit.ts
180
- import { z as z3 } from "zod";
181
- var auditSchema = z3.object({
182
- slug: slugSchema.describe("ID (unique within plugin)")
183
- }).merge(
184
- metaSchema({
185
- titleDescription: "Descriptive name",
186
- descriptionDescription: "Description (markdown)",
187
- docsUrlDescription: "Link to documentation (rationale)",
188
- description: "List of scorable metrics for the given plugin"
189
- })
190
- );
191
- var pluginAuditsSchema = z3.array(auditSchema, {
192
- description: "List of audits maintained in a plugin"
193
- }).min(1).refine(
194
- (auditMetadata) => !getDuplicateSlugsInAudits(auditMetadata),
195
- (auditMetadata) => ({
196
- message: duplicateSlugsInAuditsErrorMsg(auditMetadata)
197
- })
198
- );
199
- function duplicateSlugsInAuditsErrorMsg(audits) {
200
- const duplicateRefs = getDuplicateSlugsInAudits(audits);
201
- return `In plugin audits the following slugs are not unique: ${errorItems(
202
- duplicateRefs
203
- )}`;
204
- }
205
- function getDuplicateSlugsInAudits(audits) {
206
- return hasDuplicateStrings(audits.map(({ slug }) => slug));
207
- }
208
-
209
- // packages/models/src/lib/audit-output.ts
210
- import { z as z6 } from "zod";
211
-
212
- // packages/models/src/lib/issue.ts
213
- import { z as z4 } from "zod";
214
- var issueSeveritySchema = z4.enum(["info", "warning", "error"], {
215
- description: "Severity level"
216
- });
217
- var issueSchema = z4.object(
218
- {
219
- message: z4.string({ description: "Descriptive error message" }).max(MAX_ISSUE_MESSAGE_LENGTH),
220
- severity: issueSeveritySchema,
221
- source: sourceFileLocationSchema.optional()
222
- },
223
- { description: "Issue information" }
224
- );
225
-
226
- // packages/models/src/lib/table.ts
227
- import { z as z5 } from "zod";
228
- var tableAlignmentSchema = z5.enum(["left", "center", "right"], {
229
- description: "Cell alignment"
230
- });
231
- var tableColumnObjectSchema = z5.object({
232
- key: z5.string(),
233
- label: z5.string().optional(),
234
- align: tableAlignmentSchema.optional()
235
- });
236
- var tableRowObjectSchema = z5.record(tableCellValueSchema, {
237
- description: "Object row"
238
- });
239
- var tableRowPrimitiveSchema = z5.array(tableCellValueSchema, {
240
- description: "Primitive row"
241
- });
242
- var tableSharedSchema = z5.object({
243
- title: z5.string().optional().describe("Display title for table")
244
- });
245
- var tablePrimitiveSchema = tableSharedSchema.merge(
246
- z5.object(
247
- {
248
- columns: z5.array(tableAlignmentSchema).optional(),
249
- rows: z5.array(tableRowPrimitiveSchema)
250
- },
251
- { description: "Table with primitive rows and optional alignment columns" }
252
- )
253
- );
254
- var tableObjectSchema = tableSharedSchema.merge(
255
- z5.object(
256
- {
257
- columns: z5.union([
258
- z5.array(tableAlignmentSchema),
259
- z5.array(tableColumnObjectSchema)
260
- ]).optional(),
261
- rows: z5.array(tableRowObjectSchema)
262
- },
263
- {
264
- description: "Table with object rows and optional alignment or object columns"
265
- }
266
- )
267
- );
268
- var tableSchema = (description = "Table information") => z5.union([tablePrimitiveSchema, tableObjectSchema], { description });
269
-
270
- // packages/models/src/lib/audit-output.ts
271
- var auditValueSchema = nonnegativeNumberSchema.describe("Raw numeric value");
272
- var auditDisplayValueSchema = z6.string({ description: "Formatted value (e.g. '0.9 s', '2.1 MB')" }).optional();
273
- var auditDetailsSchema = z6.object(
274
- {
275
- issues: z6.array(issueSchema, { description: "List of findings" }).optional(),
276
- table: tableSchema("Table of related findings").optional()
277
- },
278
- { description: "Detailed information" }
279
- );
280
- var auditOutputSchema = z6.object(
281
- {
282
- slug: slugSchema.describe("Reference to audit"),
283
- displayValue: auditDisplayValueSchema,
284
- value: auditValueSchema,
285
- score: scoreSchema,
286
- details: auditDetailsSchema.optional()
287
- },
288
- { description: "Audit information" }
289
- );
290
- var auditOutputsSchema = z6.array(auditOutputSchema, {
291
- description: "List of JSON formatted audit output emitted by the runner process of a plugin"
292
- }).refine(
293
- (audits) => !getDuplicateSlugsInAudits2(audits),
294
- (audits) => ({ message: duplicateSlugsInAuditsErrorMsg2(audits) })
295
- );
296
- function duplicateSlugsInAuditsErrorMsg2(audits) {
297
- const duplicateRefs = getDuplicateSlugsInAudits2(audits);
298
- return `In plugin audits the slugs are not unique: ${errorItems(
299
- duplicateRefs
300
- )}`;
301
- }
302
- function getDuplicateSlugsInAudits2(audits) {
303
- return hasDuplicateStrings(audits.map(({ slug }) => slug));
304
- }
305
-
306
- // packages/models/src/lib/category-config.ts
307
- import { z as z7 } from "zod";
308
- var categoryRefSchema = weightedRefSchema(
309
- "Weighted references to audits and/or groups for the category",
310
- "Slug of an audit or group (depending on `type`)"
311
- ).merge(
312
- z7.object({
313
- type: z7.enum(["audit", "group"], {
314
- description: "Discriminant for reference kind, affects where `slug` is looked up"
315
- }),
316
- plugin: slugSchema.describe(
317
- "Plugin slug (plugin should contain referenced audit or group)"
318
- )
319
- })
320
- );
321
- var categoryConfigSchema = scorableSchema(
322
- "Category with a score calculated from audits and groups from various plugins",
323
- categoryRefSchema,
324
- getDuplicateRefsInCategoryMetrics,
325
- duplicateRefsInCategoryMetricsErrorMsg
326
- ).merge(
327
- metaSchema({
328
- titleDescription: "Category Title",
329
- docsUrlDescription: "Category docs URL",
330
- descriptionDescription: "Category description",
331
- description: "Meta info for category"
332
- })
333
- ).merge(
334
- z7.object({
335
- isBinary: z7.boolean({
336
- description: 'Is this a binary category (i.e. only a perfect score considered a "pass")?'
337
- }).optional()
338
- })
339
- );
340
- function duplicateRefsInCategoryMetricsErrorMsg(metrics) {
341
- const duplicateRefs = getDuplicateRefsInCategoryMetrics(metrics);
342
- return `In the categories, the following audit or group refs are duplicates: ${errorItems(
343
- duplicateRefs
344
- )}`;
345
- }
346
- function getDuplicateRefsInCategoryMetrics(metrics) {
347
- return hasDuplicateStrings(
348
- metrics.map(({ slug, type, plugin }) => `${type} :: ${plugin} / ${slug}`)
349
- );
350
- }
351
- var categoriesSchema = z7.array(categoryConfigSchema, {
352
- description: "Categorization of individual audits"
353
- }).refine(
354
- (categoryCfg) => !getDuplicateSlugCategories(categoryCfg),
355
- (categoryCfg) => ({
356
- message: duplicateSlugCategoriesErrorMsg(categoryCfg)
357
- })
358
- );
359
- function duplicateSlugCategoriesErrorMsg(categories) {
360
- const duplicateStringSlugs = getDuplicateSlugCategories(categories);
361
- return `In the categories, the following slugs are duplicated: ${errorItems(
362
- duplicateStringSlugs
363
- )}`;
364
- }
365
- function getDuplicateSlugCategories(categories) {
366
- return hasDuplicateStrings(categories.map(({ slug }) => slug));
367
- }
368
-
369
- // packages/models/src/lib/commit.ts
370
- import { z as z8 } from "zod";
371
- var commitSchema = z8.object(
372
- {
373
- hash: z8.string({ description: "Commit SHA (full)" }).regex(
374
- /^[\da-f]{40}$/,
375
- "Commit SHA should be a 40-character hexadecimal string"
376
- ),
377
- message: z8.string({ description: "Commit message" }),
378
- date: z8.coerce.date({
379
- description: "Date and time when commit was authored"
380
- }),
381
- author: z8.string({
382
- description: "Commit author name"
383
- }).trim()
384
- },
385
- { description: "Git commit" }
386
- );
387
-
388
- // packages/models/src/lib/core-config.ts
389
- import { z as z14 } from "zod";
390
-
391
- // packages/models/src/lib/persist-config.ts
392
- import { z as z9 } from "zod";
393
- var formatSchema = z9.enum(["json", "md"]);
394
- var persistConfigSchema = z9.object({
395
- outputDir: filePathSchema.describe("Artifacts folder").optional(),
396
- filename: fileNameSchema.describe("Artifacts file name (without extension)").optional(),
397
- format: z9.array(formatSchema).optional()
398
- });
399
-
400
- // packages/models/src/lib/plugin-config.ts
401
- import { z as z12 } from "zod";
402
-
403
- // packages/models/src/lib/group.ts
404
- import { z as z10 } from "zod";
405
- var groupRefSchema = weightedRefSchema(
406
- "Weighted reference to a group",
407
- "Reference slug to a group within this plugin (e.g. 'max-lines')"
408
- );
409
- var groupMetaSchema = metaSchema({
410
- titleDescription: "Descriptive name for the group",
411
- descriptionDescription: "Description of the group (markdown)",
412
- docsUrlDescription: "Group documentation site",
413
- description: "Group metadata"
414
- });
415
- var groupSchema = scorableSchema(
416
- 'A group aggregates a set of audits into a single score which can be referenced from a category. E.g. the group slug "performance" groups audits and can be referenced in a category',
417
- groupRefSchema,
418
- getDuplicateRefsInGroups,
419
- duplicateRefsInGroupsErrorMsg
420
- ).merge(groupMetaSchema);
421
- var groupsSchema = z10.array(groupSchema, {
422
- description: "List of groups"
423
- }).optional().refine(
424
- (groups) => !getDuplicateSlugsInGroups(groups),
425
- (groups) => ({
426
- message: duplicateSlugsInGroupsErrorMsg(groups)
427
- })
428
- );
429
- function duplicateRefsInGroupsErrorMsg(groups) {
430
- const duplicateRefs = getDuplicateRefsInGroups(groups);
431
- return `In plugin groups the following references are not unique: ${errorItems(
432
- duplicateRefs
433
- )}`;
434
- }
435
- function getDuplicateRefsInGroups(groups) {
436
- return hasDuplicateStrings(groups.map(({ slug: ref }) => ref).filter(exists));
437
- }
438
- function duplicateSlugsInGroupsErrorMsg(groups) {
439
- const duplicateRefs = getDuplicateSlugsInGroups(groups);
440
- return `In groups the following slugs are not unique: ${errorItems(
441
- duplicateRefs
442
- )}`;
443
- }
444
- function getDuplicateSlugsInGroups(groups) {
445
- return Array.isArray(groups) ? hasDuplicateStrings(groups.map(({ slug }) => slug)) : false;
446
- }
447
-
448
- // packages/models/src/lib/runner-config.ts
449
- import { z as z11 } from "zod";
450
- var outputTransformSchema = z11.function().args(z11.unknown()).returns(z11.union([auditOutputsSchema, z11.promise(auditOutputsSchema)]));
451
- var runnerConfigSchema = z11.object(
452
- {
453
- command: z11.string({
454
- description: "Shell command to execute"
455
- }),
456
- args: z11.array(z11.string({ description: "Command arguments" })).optional(),
457
- outputFile: filePathSchema.describe("Output path"),
458
- outputTransform: outputTransformSchema.optional()
459
- },
460
- {
461
- description: "How to execute runner"
462
- }
463
- );
464
- var onProgressSchema = z11.function().args(z11.unknown()).returns(z11.void());
465
- var runnerFunctionSchema = z11.function().args(onProgressSchema.optional()).returns(z11.union([auditOutputsSchema, z11.promise(auditOutputsSchema)]));
466
-
467
- // packages/models/src/lib/plugin-config.ts
468
- var pluginMetaSchema = packageVersionSchema().merge(
469
- metaSchema({
470
- titleDescription: "Descriptive name",
471
- descriptionDescription: "Description (markdown)",
472
- docsUrlDescription: "Plugin documentation site",
473
- description: "Plugin metadata"
474
- })
475
- ).merge(
476
- z12.object({
477
- slug: slugSchema.describe("Unique plugin slug within core config"),
478
- icon: materialIconSchema
479
- })
480
- );
481
- var pluginDataSchema = z12.object({
482
- runner: z12.union([runnerConfigSchema, runnerFunctionSchema]),
483
- audits: pluginAuditsSchema,
484
- groups: groupsSchema
485
- });
486
- var pluginConfigSchema = pluginMetaSchema.merge(pluginDataSchema).refine(
487
- (pluginCfg) => !getMissingRefsFromGroups(pluginCfg),
488
- (pluginCfg) => ({
489
- message: missingRefsFromGroupsErrorMsg(pluginCfg)
490
- })
491
- );
492
- function missingRefsFromGroupsErrorMsg(pluginCfg) {
493
- const missingRefs = getMissingRefsFromGroups(pluginCfg);
494
- return `The following group references need to point to an existing audit in this plugin config: ${errorItems(
495
- missingRefs
496
- )}`;
497
- }
498
- function getMissingRefsFromGroups(pluginCfg) {
499
- return hasMissingStrings(
500
- pluginCfg.groups?.flatMap(
501
- ({ refs: audits }) => audits.map(({ slug: ref }) => ref)
502
- ) ?? [],
503
- pluginCfg.audits.map(({ slug }) => slug)
504
- );
505
- }
506
-
507
- // packages/models/src/lib/upload-config.ts
508
- import { z as z13 } from "zod";
509
- var uploadConfigSchema = z13.object({
510
- server: urlSchema.describe("URL of deployed portal API"),
511
- apiKey: z13.string({
512
- description: "API key with write access to portal (use `process.env` for security)"
513
- }),
514
- organization: slugSchema.describe(
515
- "Organization slug from Code PushUp portal"
516
- ),
517
- project: slugSchema.describe("Project slug from Code PushUp portal"),
518
- timeout: z13.number({ description: "Request timeout in minutes (default is 5)" }).positive().int().optional()
519
- });
520
-
521
- // packages/models/src/lib/core-config.ts
522
- var unrefinedCoreConfigSchema = z14.object({
523
- plugins: z14.array(pluginConfigSchema, {
524
- description: "List of plugins to be used (official, community-provided, or custom)"
525
- }).min(1),
526
- /** portal configuration for persisting results */
527
- persist: persistConfigSchema.optional(),
528
- /** portal configuration for uploading results */
529
- upload: uploadConfigSchema.optional(),
530
- categories: categoriesSchema.optional()
531
- });
532
- var coreConfigSchema = refineCoreConfig(unrefinedCoreConfigSchema);
533
- function refineCoreConfig(schema) {
534
- return schema.refine(
535
- ({ categories, plugins }) => !getMissingRefsForCategories(categories, plugins),
536
- ({ categories, plugins }) => ({
537
- message: missingRefsForCategoriesErrorMsg(categories, plugins)
538
- })
539
- );
540
- }
541
-
542
- // packages/models/src/lib/report.ts
543
- import { z as z15 } from "zod";
544
- var auditReportSchema = auditSchema.merge(auditOutputSchema);
545
- var pluginReportSchema = pluginMetaSchema.merge(
546
- executionMetaSchema({
547
- descriptionDate: "Start date and time of plugin run",
548
- descriptionDuration: "Duration of the plugin run in ms"
549
- })
550
- ).merge(
551
- z15.object({
552
- audits: z15.array(auditReportSchema).min(1),
553
- groups: z15.array(groupSchema).optional()
554
- })
555
- ).refine(
556
- (pluginReport) => !getMissingRefsFromGroups2(pluginReport.audits, pluginReport.groups ?? []),
557
- (pluginReport) => ({
558
- message: missingRefsFromGroupsErrorMsg2(
559
- pluginReport.audits,
560
- pluginReport.groups ?? []
561
- )
562
- })
563
- );
564
- function missingRefsFromGroupsErrorMsg2(audits, groups) {
565
- const missingRefs = getMissingRefsFromGroups2(audits, groups);
566
- return `group references need to point to an existing audit in this plugin report: ${errorItems(
567
- missingRefs
568
- )}`;
569
- }
570
- function getMissingRefsFromGroups2(audits, groups) {
571
- return hasMissingStrings(
572
- groups.flatMap(
573
- ({ refs: auditRefs }) => auditRefs.map(({ slug: ref }) => ref)
574
- ),
575
- audits.map(({ slug }) => slug)
576
- );
577
- }
578
- var reportSchema = packageVersionSchema({
579
- versionDescription: "NPM version of the CLI",
580
- required: true
581
- }).merge(
582
- executionMetaSchema({
583
- descriptionDate: "Start date and time of the collect run",
584
- descriptionDuration: "Duration of the collect run in ms"
585
- })
586
- ).merge(
587
- z15.object(
588
- {
589
- plugins: z15.array(pluginReportSchema).min(1),
590
- categories: z15.array(categoryConfigSchema).optional(),
591
- commit: commitSchema.describe("Git commit for which report was collected").nullable()
592
- },
593
- { description: "Collect output data" }
594
- )
595
- ).refine(
596
- ({ categories, plugins }) => !getMissingRefsForCategories(categories, plugins),
597
- ({ categories, plugins }) => ({
598
- message: missingRefsForCategoriesErrorMsg(categories, plugins)
599
- })
600
- );
601
-
602
- // packages/models/src/lib/reports-diff.ts
603
- import { z as z16 } from "zod";
604
- function makeComparisonSchema(schema) {
605
- const sharedDescription = schema.description || "Result";
606
- return z16.object({
607
- before: schema.describe(`${sharedDescription} (source commit)`),
608
- after: schema.describe(`${sharedDescription} (target commit)`)
609
- });
610
- }
611
- function makeArraysComparisonSchema(diffSchema, resultSchema, description) {
612
- return z16.object(
613
- {
614
- changed: z16.array(diffSchema),
615
- unchanged: z16.array(resultSchema),
616
- added: z16.array(resultSchema),
617
- removed: z16.array(resultSchema)
618
- },
619
- { description }
620
- );
621
- }
622
- var scorableMetaSchema = z16.object({
623
- slug: slugSchema,
624
- title: titleSchema,
625
- docsUrl: docsUrlSchema
626
- });
627
- var scorableWithPluginMetaSchema = scorableMetaSchema.merge(
628
- z16.object({
629
- plugin: pluginMetaSchema.pick({ slug: true, title: true, docsUrl: true }).describe("Plugin which defines it")
630
- })
631
- );
632
- var scorableDiffSchema = scorableMetaSchema.merge(
633
- z16.object({
634
- scores: makeComparisonSchema(scoreSchema).merge(
635
- z16.object({
636
- diff: z16.number().min(-1).max(1).describe("Score change (`scores.after - scores.before`)")
637
- })
638
- ).describe("Score comparison")
639
- })
640
- );
641
- var scorableWithPluginDiffSchema = scorableDiffSchema.merge(
642
- scorableWithPluginMetaSchema
643
- );
644
- var categoryDiffSchema = scorableDiffSchema;
645
- var groupDiffSchema = scorableWithPluginDiffSchema;
646
- var auditDiffSchema = scorableWithPluginDiffSchema.merge(
647
- z16.object({
648
- values: makeComparisonSchema(auditValueSchema).merge(
649
- z16.object({
650
- diff: z16.number().describe("Value change (`values.after - values.before`)")
651
- })
652
- ).describe("Audit `value` comparison"),
653
- displayValues: makeComparisonSchema(auditDisplayValueSchema).describe(
654
- "Audit `displayValue` comparison"
655
- )
656
- })
657
- );
658
- var categoryResultSchema = scorableMetaSchema.merge(
659
- z16.object({ score: scoreSchema })
660
- );
661
- var groupResultSchema = scorableWithPluginMetaSchema.merge(
662
- z16.object({ score: scoreSchema })
663
- );
664
- var auditResultSchema = scorableWithPluginMetaSchema.merge(
665
- auditOutputSchema.pick({ score: true, value: true, displayValue: true })
666
- );
667
- var reportsDiffSchema = z16.object({
668
- commits: makeComparisonSchema(commitSchema).nullable().describe("Commits identifying compared reports"),
669
- portalUrl: urlSchema.optional().describe("Link to comparison page in Code PushUp portal"),
670
- label: z16.string().optional().describe("Label (e.g. project name)"),
671
- categories: makeArraysComparisonSchema(
672
- categoryDiffSchema,
673
- categoryResultSchema,
674
- "Changes affecting categories"
675
- ),
676
- groups: makeArraysComparisonSchema(
677
- groupDiffSchema,
678
- groupResultSchema,
679
- "Changes affecting groups"
680
- ),
681
- audits: makeArraysComparisonSchema(
682
- auditDiffSchema,
683
- auditResultSchema,
684
- "Changes affecting audits"
685
- )
686
- }).merge(
687
- packageVersionSchema({
688
- versionDescription: "NPM version of the CLI (when `compare` was run)",
689
- required: true
690
- })
691
- ).merge(
692
- executionMetaSchema({
693
- descriptionDate: "Start date and time of the compare run",
694
- descriptionDuration: "Duration of the compare run in ms"
695
- })
696
- );
697
-
698
- // packages/utils/src/lib/reports/utils.ts
699
- import ansis from "ansis";
700
- import { md } from "build-md";
701
-
702
- // packages/utils/src/lib/reports/constants.ts
703
- var TERMINAL_WIDTH = 80;
704
-
705
- // packages/utils/src/lib/file-system.ts
706
- import { bold, gray } from "ansis";
707
- import { bundleRequire } from "bundle-require";
708
- import { mkdir, readFile, readdir, rm, stat } from "node:fs/promises";
709
- import { dirname, join } from "node:path";
710
-
711
- // packages/utils/src/lib/logging.ts
712
- import isaacs_cliui from "@isaacs/cliui";
713
- import { cliui } from "@poppinss/cliui";
714
- import { underline } from "ansis";
715
- var singletonUiInstance;
716
- function ui() {
717
- if (singletonUiInstance === void 0) {
718
- singletonUiInstance = cliui();
719
- }
720
- return {
721
- ...singletonUiInstance,
722
- row: (args) => {
723
- logListItem(args);
724
- }
725
- };
726
- }
727
- var singletonisaacUi;
728
- function logListItem(args) {
729
- if (singletonisaacUi === void 0) {
730
- singletonisaacUi = isaacs_cliui({ width: TERMINAL_WIDTH });
731
- }
732
- singletonisaacUi.div(...args);
733
- const content = singletonisaacUi.toString();
734
- singletonisaacUi.rows = [];
735
- singletonUiInstance?.logger.log(content);
736
- }
737
-
738
- // packages/utils/src/lib/file-system.ts
739
- async function ensureDirectoryExists(baseDir) {
740
- try {
741
- await mkdir(baseDir, { recursive: true });
742
- return;
743
- } catch (error) {
744
- ui().logger.info(error.message);
745
- if (error.code !== "EEXIST") {
746
- throw error;
747
- }
748
- }
749
- }
750
- async function importModule(options) {
751
- const { mod } = await bundleRequire(options);
752
- if (typeof mod === "object" && "default" in mod) {
753
- return mod.default;
754
- }
755
- return mod;
756
- }
757
- function pluginWorkDir(slug) {
758
- return join("node_modules", ".code-pushup", slug);
759
- }
760
- function filePathToCliArg(path) {
761
- return `"${path}"`;
762
- }
763
-
764
- // packages/utils/src/lib/git/git.ts
765
- import { simpleGit } from "simple-git";
766
-
767
- // packages/utils/src/lib/transform.ts
768
- function capitalize(text) {
769
- return `${text.charAt(0).toLocaleUpperCase()}${text.slice(
770
- 1
771
- )}`;
772
- }
773
-
774
- // packages/utils/src/lib/git/git.commits-and-tags.ts
775
- import { simpleGit as simpleGit2 } from "simple-git";
776
-
777
- // packages/utils/src/lib/semver.ts
778
- import { rcompare, valid } from "semver";
779
-
780
- // packages/utils/src/lib/progress.ts
781
- import { black, bold as bold2, gray as gray2, green } from "ansis";
782
- import { MultiProgressBars } from "multi-progress-bars";
783
-
784
- // packages/utils/src/lib/reports/generate-md-report.ts
785
- import { MarkdownDocument as MarkdownDocument3, md as md4 } from "build-md";
786
-
787
- // packages/utils/src/lib/reports/formatting.ts
788
- import {
789
- MarkdownDocument,
790
- md as md2
791
- } from "build-md";
792
-
793
- // packages/utils/src/lib/reports/generate-md-report-categoy-section.ts
794
- import { MarkdownDocument as MarkdownDocument2, md as md3 } from "build-md";
795
-
796
- // packages/utils/src/lib/reports/generate-md-reports-diff.ts
797
- import {
798
- MarkdownDocument as MarkdownDocument5,
799
- md as md6
800
- } from "build-md";
801
-
802
- // packages/utils/src/lib/reports/generate-md-reports-diff-utils.ts
803
- import { MarkdownDocument as MarkdownDocument4, md as md5 } from "build-md";
804
-
805
- // packages/utils/src/lib/reports/log-stdout-summary.ts
806
- import { bold as bold4, cyan, cyanBright, green as green2, red } from "ansis";
807
-
808
- // packages/plugin-coverage/package.json
809
- var name = "@code-pushup/coverage-plugin";
810
- var version = "0.55.0";
811
-
812
- // packages/plugin-coverage/src/lib/config.ts
813
- import { z as z17 } from "zod";
814
- var coverageTypeSchema = z17.enum(["function", "branch", "line"]);
815
- var coverageResultSchema = z17.union([
816
- z17.object({
817
- resultsPath: z17.string({
818
- description: "Path to coverage results for Nx setup."
819
- }).includes("lcov"),
820
- pathToProject: z17.string({
821
- description: "Path from workspace root to project root. Necessary for LCOV reports which provide a relative path."
822
- }).optional()
823
- }),
824
- z17.string({
825
- description: "Path to coverage results for a single project setup."
826
- }).includes("lcov")
827
- ]);
828
- var coveragePluginConfigSchema = z17.object({
829
- coverageToolCommand: z17.object({
830
- command: z17.string({ description: "Command to run coverage tool." }).min(1),
831
- args: z17.array(z17.string(), {
832
- description: "Arguments to be passed to the coverage tool."
833
- }).optional()
834
- }).optional(),
835
- coverageTypes: z17.array(coverageTypeSchema, {
836
- description: "Coverage types measured. Defaults to all available types."
837
- }).min(1).default(["function", "branch", "line"]),
838
- reports: z17.array(coverageResultSchema, {
839
- description: "Path to all code coverage report files. Only LCOV format is supported for now."
840
- }).min(1),
841
- perfectScoreThreshold: z17.number({
842
- description: "Score will be 1 (perfect) for this coverage and above. Score range is 0 - 1."
843
- }).gt(0).max(1).optional()
844
- });
845
-
846
- // packages/plugin-coverage/src/lib/runner/index.ts
847
- import { bold as bold5 } from "ansis";
848
- import { writeFile } from "node:fs/promises";
849
- import { dirname as dirname2 } from "node:path";
850
-
851
- // packages/plugin-coverage/src/lib/utils.ts
852
- var coverageDescription = {
853
- branch: "Measures how many branches were executed after conditional statements in at least one test.",
854
- line: "Measures how many lines of code were executed in at least one test.",
855
- function: "Measures how many functions were called in at least one test."
856
- };
857
- function applyMaxScoreAboveThreshold(outputs, threshold) {
858
- return outputs.map(
859
- (output) => output.score >= threshold ? { ...output, score: 1 } : output
860
- );
861
- }
862
- var coverageTypeWeightMapper = {
863
- function: 6,
864
- branch: 3,
865
- line: 1
866
- };
867
-
868
- // packages/plugin-coverage/src/lib/runner/constants.ts
869
- import { join as join2 } from "node:path";
870
- var WORKDIR = pluginWorkDir("coverage");
871
- var RUNNER_OUTPUT_PATH = join2(WORKDIR, "runner-output.json");
872
- var PLUGIN_CONFIG_PATH = join2(
873
- process.cwd(),
874
- WORKDIR,
875
- "plugin-config.json"
876
- );
877
-
878
- // packages/plugin-coverage/src/lib/runner/lcov/parse-lcov.ts
879
- import parseLcovExport from "parse-lcov";
880
- var godKnows = parseLcovExport;
881
- var parseLcov = "default" in godKnows ? godKnows.default : godKnows;
882
-
883
- // packages/plugin-coverage/src/lib/runner/index.ts
884
- async function createRunnerConfig(scriptPath, config) {
885
- await ensureDirectoryExists(dirname2(PLUGIN_CONFIG_PATH));
886
- await writeFile(PLUGIN_CONFIG_PATH, JSON.stringify(config));
887
- const threshold = config.perfectScoreThreshold;
888
- return {
889
- command: "node",
890
- args: [filePathToCliArg(scriptPath)],
891
- outputFile: RUNNER_OUTPUT_PATH,
892
- ...threshold != null && {
893
- outputTransform: (outputs) => applyMaxScoreAboveThreshold(outputs, threshold)
894
- }
895
- };
896
- }
897
-
898
- // packages/plugin-coverage/src/lib/coverage-plugin.ts
899
- async function coveragePlugin(config) {
900
- const coverageConfig = coveragePluginConfigSchema.parse(config);
901
- const audits = coverageConfig.coverageTypes.map(
902
- (type) => ({
903
- slug: `${type}-coverage`,
904
- title: `${capitalize(type)} coverage`,
905
- description: coverageDescription[type]
906
- })
907
- );
908
- const group = {
909
- slug: "coverage",
910
- title: "Code coverage metrics",
911
- description: "Group containing all defined coverage types as audits.",
912
- refs: audits.map((audit) => ({
913
- ...audit,
914
- weight: coverageTypeWeightMapper[audit.slug.slice(0, audit.slug.indexOf("-"))]
915
- }))
916
- };
917
- const runnerScriptPath = join3(
918
- fileURLToPath(dirname3(import.meta.url)),
919
- "bin.js"
920
- );
921
- return {
922
- slug: "coverage",
923
- title: "Code coverage",
924
- icon: "folder-coverage-open",
925
- description: "Official Code PushUp code coverage plugin.",
926
- docsUrl: "https://www.npmjs.com/package/@code-pushup/coverage-plugin/",
927
- packageName: name,
928
- version,
929
- audits,
930
- groups: [group],
931
- runner: await createRunnerConfig(runnerScriptPath, coverageConfig)
932
- };
933
- }
934
-
935
- // packages/plugin-coverage/src/lib/nx/coverage-paths.ts
936
- import { bold as bold6 } from "ansis";
937
- import { isAbsolute, join as join4 } from "node:path";
938
- async function getNxCoveragePaths(targets = ["test"], verbose) {
939
- if (verbose) {
940
- ui().logger.info(
941
- bold6("\u{1F4A1} Gathering coverage from the following nx projects:")
942
- );
943
- }
944
- const { createProjectGraphAsync } = await import("@nx/devkit");
945
- const { nodes } = await createProjectGraphAsync({ exitOnError: false });
946
- const coverageResults = await Promise.all(
947
- targets.map(async (target) => {
948
- const relevantNodes = Object.values(nodes).filter(
949
- (graph) => hasNxTarget(graph, target)
950
- );
951
- return await Promise.all(
952
- relevantNodes.map(async ({ name: name2, data }) => {
953
- const coveragePaths = await getCoveragePathsForTarget(data, target);
954
- if (verbose) {
955
- ui().logger.info(`- ${name2}: ${target}`);
956
- }
957
- return coveragePaths;
958
- })
959
- );
960
- })
961
- );
962
- if (verbose) {
963
- ui().logger.info("\n");
964
- }
965
- return coverageResults.flat();
966
- }
967
- function hasNxTarget(project, target) {
968
- return project.data.targets != null && target in project.data.targets;
969
- }
970
- async function getCoveragePathsForTarget(project, target) {
971
- const targetConfig = project.targets?.[target];
972
- if (!targetConfig) {
973
- throw new Error(
974
- `No configuration found for target ${target} in project ${project.name}`
975
- );
976
- }
977
- if (targetConfig.executor?.includes("@nx/vite")) {
978
- return getCoveragePathForVitest(
979
- targetConfig.options,
980
- project,
981
- target
982
- );
983
- }
984
- if (targetConfig.executor?.includes("@nx/jest")) {
985
- return getCoveragePathForJest(
986
- targetConfig.options,
987
- project,
988
- target
989
- );
990
- }
991
- throw new Error(
992
- `Unsupported executor ${targetConfig.executor}. Only @nx/vite and @nx/jest are currently supported.`
993
- );
994
- }
995
- async function getCoveragePathForVitest(options, project, target) {
996
- const {
997
- default: { normalizeViteConfigFilePathWithTree }
998
- } = await import("@nx/vite");
999
- const config = normalizeViteConfigFilePathWithTree(
1000
- // HACK: only tree.exists is called, so injecting existSync from node:fs instead
1001
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions, n/no-sync
1002
- { exists: (await import("node:fs")).existsSync },
1003
- project.root,
1004
- options.configFile
1005
- );
1006
- if (!config) {
1007
- throw new Error(
1008
- `Could not find Vitest config file for target ${target} in project ${project.name}`
1009
- );
1010
- }
1011
- const vitestConfig = await importModule({
1012
- filepath: config,
1013
- format: "esm"
1014
- });
1015
- const reportsDirectory = options.reportsDirectory ?? vitestConfig.test.coverage?.reportsDirectory;
1016
- const reporter = vitestConfig.test.coverage?.reporter;
1017
- if (reportsDirectory == null) {
1018
- throw new Error(
1019
- `Vitest coverage configuration at ${config} does not include coverage path for target ${target} in project ${project.name}. Add the path under coverage > reportsDirectory.`
1020
- );
1021
- }
1022
- if (!reporter?.includes("lcov")) {
1023
- throw new Error(
1024
- `Vitest coverage configuration at ${config} does not include LCOV report format for target ${target} in project ${project.name}. Add 'lcov' format under coverage > reporter.`
1025
- );
1026
- }
1027
- if (isAbsolute(reportsDirectory)) {
1028
- return join4(reportsDirectory, "lcov.info");
1029
- }
1030
- return {
1031
- pathToProject: project.root,
1032
- resultsPath: join4(project.root, reportsDirectory, "lcov.info")
1033
- };
1034
- }
1035
- async function getCoveragePathForJest(options, project, target) {
1036
- const { jestConfig } = options;
1037
- const testConfig = await importModule({
1038
- filepath: jestConfig
1039
- });
1040
- const { coverageDirectory, coverageReporters } = {
1041
- ...testConfig,
1042
- ...options
1043
- };
1044
- if (coverageDirectory == null) {
1045
- throw new Error(
1046
- `Jest coverage configuration at ${jestConfig} does not include coverage path for target ${target} in ${project.name}. Add the path under coverageDirectory.`
1047
- );
1048
- }
1049
- if (!coverageReporters?.includes("lcov") && !("preset" in testConfig)) {
1050
- throw new Error(
1051
- `Jest coverage configuration at ${jestConfig} does not include LCOV report format for target ${target} in ${project.name}. Add 'lcov' format under coverageReporters.`
1052
- );
1053
- }
1054
- if (isAbsolute(coverageDirectory)) {
1055
- return join4(coverageDirectory, "lcov.info");
1056
- }
1057
- return join4(project.root, coverageDirectory, "lcov.info");
1058
- }
1059
-
1060
- // packages/plugin-coverage/src/index.ts
1061
- var src_default = coveragePlugin;
1062
- export {
1063
- src_default as default,
1064
- getNxCoveragePaths
1065
- };