@code-pushup/core 0.56.0 → 0.58.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 (39) hide show
  1. package/package.json +8 -7
  2. package/src/index.d.ts +11 -11
  3. package/src/index.js +10 -0
  4. package/src/index.js.map +1 -0
  5. package/src/lib/collect-and-persist.d.ts +1 -1
  6. package/src/lib/collect-and-persist.js +21 -0
  7. package/src/lib/collect-and-persist.js.map +1 -0
  8. package/src/lib/compare.js +96 -0
  9. package/src/lib/compare.js.map +1 -0
  10. package/src/lib/history.d.ts +1 -1
  11. package/src/lib/history.js +38 -0
  12. package/src/lib/history.js.map +1 -0
  13. package/src/lib/implementation/collect.d.ts +1 -1
  14. package/src/lib/implementation/collect.js +25 -0
  15. package/src/lib/implementation/collect.js.map +1 -0
  16. package/src/lib/implementation/compare-scorables.js +117 -0
  17. package/src/lib/implementation/compare-scorables.js.map +1 -0
  18. package/src/lib/implementation/execute-plugin.js +126 -0
  19. package/src/lib/implementation/execute-plugin.js.map +1 -0
  20. package/src/lib/implementation/persist.js +56 -0
  21. package/src/lib/implementation/persist.js.map +1 -0
  22. package/src/lib/implementation/read-rc-file.js +43 -0
  23. package/src/lib/implementation/read-rc-file.js.map +1 -0
  24. package/src/lib/implementation/report-to-gql.js +133 -0
  25. package/src/lib/implementation/report-to-gql.js.map +1 -0
  26. package/src/lib/implementation/runner.js +36 -0
  27. package/src/lib/implementation/runner.js.map +1 -0
  28. package/src/lib/load-portal-client.js +11 -0
  29. package/src/lib/load-portal-client.js.map +1 -0
  30. package/src/lib/merge-diffs.js +33 -0
  31. package/src/lib/merge-diffs.js.map +1 -0
  32. package/src/lib/normalize.js +31 -0
  33. package/src/lib/normalize.js.map +1 -0
  34. package/src/lib/types.js +2 -0
  35. package/src/lib/types.js.map +1 -0
  36. package/src/lib/upload.d.ts +1 -1
  37. package/src/lib/upload.js +34 -0
  38. package/src/lib/upload.js.map +1 -0
  39. package/index.js +0 -3249
package/index.js DELETED
@@ -1,3249 +0,0 @@
1
- // packages/models/src/lib/implementation/schemas.ts
2
- import { MATERIAL_ICONS } from "vscode-material-icons";
3
- import { z } from "zod";
4
-
5
- // packages/models/src/lib/implementation/limits.ts
6
- var MAX_SLUG_LENGTH = 128;
7
- var MAX_TITLE_LENGTH = 256;
8
- var MAX_DESCRIPTION_LENGTH = 65536;
9
- var MAX_ISSUE_MESSAGE_LENGTH = 1024;
10
-
11
- // packages/models/src/lib/implementation/utils.ts
12
- var slugRegex = /^[a-z\d]+(?:-[a-z\d]+)*$/;
13
- var filenameRegex = /^(?!.*[ \\/:*?"<>|]).+$/;
14
- function hasDuplicateStrings(strings) {
15
- const sortedStrings = strings.toSorted();
16
- const duplStrings = sortedStrings.filter(
17
- (item, index) => index !== 0 && item === sortedStrings[index - 1]
18
- );
19
- return duplStrings.length === 0 ? false : [...new Set(duplStrings)];
20
- }
21
- function hasMissingStrings(toCheck, existing) {
22
- const nonExisting = toCheck.filter((s) => !existing.includes(s));
23
- return nonExisting.length === 0 ? false : nonExisting;
24
- }
25
- function errorItems(items, transform = (itemArr) => itemArr.join(", ")) {
26
- return transform(items || []);
27
- }
28
- function exists(value) {
29
- return value != null;
30
- }
31
- function getMissingRefsForCategories(categories, plugins) {
32
- if (!categories || categories.length === 0) {
33
- return false;
34
- }
35
- const auditRefsFromCategory = categories.flatMap(
36
- ({ refs }) => refs.filter(({ type }) => type === "audit").map(({ plugin, slug }) => `${plugin}/${slug}`)
37
- );
38
- const auditRefsFromPlugins = plugins.flatMap(
39
- ({ audits, slug: pluginSlug }) => audits.map(({ slug }) => `${pluginSlug}/${slug}`)
40
- );
41
- const missingAuditRefs = hasMissingStrings(
42
- auditRefsFromCategory,
43
- auditRefsFromPlugins
44
- );
45
- const groupRefsFromCategory = categories.flatMap(
46
- ({ refs }) => refs.filter(({ type }) => type === "group").map(({ plugin, slug }) => `${plugin}#${slug} (group)`)
47
- );
48
- const groupRefsFromPlugins = plugins.flatMap(
49
- ({ groups, slug: pluginSlug }) => Array.isArray(groups) ? groups.map(({ slug }) => `${pluginSlug}#${slug} (group)`) : []
50
- );
51
- const missingGroupRefs = hasMissingStrings(
52
- groupRefsFromCategory,
53
- groupRefsFromPlugins
54
- );
55
- const missingRefs = [missingAuditRefs, missingGroupRefs].filter((refs) => Array.isArray(refs) && refs.length > 0).flat();
56
- return missingRefs.length > 0 ? missingRefs : false;
57
- }
58
- function missingRefsForCategoriesErrorMsg(categories, plugins) {
59
- const missingRefs = getMissingRefsForCategories(categories, plugins);
60
- return `The following category references need to point to an audit or group: ${errorItems(
61
- missingRefs
62
- )}`;
63
- }
64
-
65
- // packages/models/src/lib/implementation/schemas.ts
66
- var tableCellValueSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]).default(null);
67
- function executionMetaSchema(options = {
68
- descriptionDate: "Execution start date and time",
69
- descriptionDuration: "Execution duration in ms"
70
- }) {
71
- return z.object({
72
- date: z.string({ description: options.descriptionDate }),
73
- duration: z.number({ description: options.descriptionDuration })
74
- });
75
- }
76
- var slugSchema = z.string({ description: "Unique ID (human-readable, URL-safe)" }).regex(slugRegex, {
77
- message: "The slug has to follow the pattern [0-9a-z] followed by multiple optional groups of -[0-9a-z]. e.g. my-slug"
78
- }).max(MAX_SLUG_LENGTH, {
79
- message: `slug can be max ${MAX_SLUG_LENGTH} characters long`
80
- });
81
- var descriptionSchema = z.string({ description: "Description (markdown)" }).max(MAX_DESCRIPTION_LENGTH).optional();
82
- var urlSchema = z.string().url();
83
- var docsUrlSchema = urlSchema.optional().or(z.literal("")).describe("Documentation site");
84
- var titleSchema = z.string({ description: "Descriptive name" }).max(MAX_TITLE_LENGTH);
85
- var scoreSchema = z.number({
86
- description: "Value between 0 and 1"
87
- }).min(0).max(1);
88
- function metaSchema(options) {
89
- const {
90
- descriptionDescription,
91
- titleDescription,
92
- docsUrlDescription,
93
- description
94
- } = options ?? {};
95
- return z.object(
96
- {
97
- title: titleDescription ? titleSchema.describe(titleDescription) : titleSchema,
98
- description: descriptionDescription ? descriptionSchema.describe(descriptionDescription) : descriptionSchema,
99
- docsUrl: docsUrlDescription ? docsUrlSchema.describe(docsUrlDescription) : docsUrlSchema
100
- },
101
- { description }
102
- );
103
- }
104
- var filePathSchema = z.string().trim().min(1, { message: "path is invalid" });
105
- var fileNameSchema = z.string().trim().regex(filenameRegex, {
106
- message: `The filename has to be valid`
107
- }).min(1, { message: "file name is invalid" });
108
- var positiveIntSchema = z.number().int().positive();
109
- var nonnegativeNumberSchema = z.number().nonnegative();
110
- function packageVersionSchema(options) {
111
- const { versionDescription = "NPM version of the package", required } = options ?? {};
112
- const packageSchema = z.string({ description: "NPM package name" });
113
- const versionSchema = z.string({ description: versionDescription });
114
- return z.object(
115
- {
116
- packageName: required ? packageSchema : packageSchema.optional(),
117
- version: required ? versionSchema : versionSchema.optional()
118
- },
119
- { description: "NPM package name and version of a published package" }
120
- );
121
- }
122
- var weightSchema = nonnegativeNumberSchema.describe(
123
- "Coefficient for the given score (use weight 0 if only for display)"
124
- );
125
- function weightedRefSchema(description, slugDescription) {
126
- return z.object(
127
- {
128
- slug: slugSchema.describe(slugDescription),
129
- weight: weightSchema.describe("Weight used to calculate score")
130
- },
131
- { description }
132
- );
133
- }
134
- function scorableSchema(description, refSchema, duplicateCheckFn, duplicateMessageFn) {
135
- return z.object(
136
- {
137
- slug: slugSchema.describe('Human-readable unique ID, e.g. "performance"'),
138
- refs: z.array(refSchema).min(1).refine(
139
- (refs) => !duplicateCheckFn(refs),
140
- (refs) => ({
141
- message: duplicateMessageFn(refs)
142
- })
143
- ).refine(hasNonZeroWeightedRef, () => ({
144
- message: "In a category there has to be at least one ref with weight > 0"
145
- }))
146
- },
147
- { description }
148
- );
149
- }
150
- var materialIconSchema = z.enum(MATERIAL_ICONS, {
151
- description: "Icon from VSCode Material Icons extension"
152
- });
153
- function hasNonZeroWeightedRef(refs) {
154
- return refs.reduce((acc, { weight }) => weight + acc, 0) !== 0;
155
- }
156
-
157
- // packages/models/src/lib/source.ts
158
- import { z as z2 } from "zod";
159
- var sourceFileLocationSchema = z2.object(
160
- {
161
- file: filePathSchema.describe("Relative path to source file in Git repo"),
162
- position: z2.object(
163
- {
164
- startLine: positiveIntSchema.describe("Start line"),
165
- startColumn: positiveIntSchema.describe("Start column").optional(),
166
- endLine: positiveIntSchema.describe("End line").optional(),
167
- endColumn: positiveIntSchema.describe("End column").optional()
168
- },
169
- { description: "Location in file" }
170
- ).optional()
171
- },
172
- { description: "Source file location" }
173
- );
174
-
175
- // packages/models/src/lib/audit.ts
176
- import { z as z3 } from "zod";
177
- var auditSchema = z3.object({
178
- slug: slugSchema.describe("ID (unique within plugin)")
179
- }).merge(
180
- metaSchema({
181
- titleDescription: "Descriptive name",
182
- descriptionDescription: "Description (markdown)",
183
- docsUrlDescription: "Link to documentation (rationale)",
184
- description: "List of scorable metrics for the given plugin"
185
- })
186
- );
187
- var pluginAuditsSchema = z3.array(auditSchema, {
188
- description: "List of audits maintained in a plugin"
189
- }).min(1).refine(
190
- (auditMetadata) => !getDuplicateSlugsInAudits(auditMetadata),
191
- (auditMetadata) => ({
192
- message: duplicateSlugsInAuditsErrorMsg(auditMetadata)
193
- })
194
- );
195
- function duplicateSlugsInAuditsErrorMsg(audits) {
196
- const duplicateRefs = getDuplicateSlugsInAudits(audits);
197
- return `In plugin audits the following slugs are not unique: ${errorItems(
198
- duplicateRefs
199
- )}`;
200
- }
201
- function getDuplicateSlugsInAudits(audits) {
202
- return hasDuplicateStrings(audits.map(({ slug }) => slug));
203
- }
204
-
205
- // packages/models/src/lib/audit-output.ts
206
- import { z as z6 } from "zod";
207
-
208
- // packages/models/src/lib/issue.ts
209
- import { z as z4 } from "zod";
210
- var issueSeveritySchema = z4.enum(["info", "warning", "error"], {
211
- description: "Severity level"
212
- });
213
- var issueSchema = z4.object(
214
- {
215
- message: z4.string({ description: "Descriptive error message" }).max(MAX_ISSUE_MESSAGE_LENGTH),
216
- severity: issueSeveritySchema,
217
- source: sourceFileLocationSchema.optional()
218
- },
219
- { description: "Issue information" }
220
- );
221
-
222
- // packages/models/src/lib/table.ts
223
- import { z as z5 } from "zod";
224
- var tableAlignmentSchema = z5.enum(["left", "center", "right"], {
225
- description: "Cell alignment"
226
- });
227
- var tableColumnObjectSchema = z5.object({
228
- key: z5.string(),
229
- label: z5.string().optional(),
230
- align: tableAlignmentSchema.optional()
231
- });
232
- var tableRowObjectSchema = z5.record(tableCellValueSchema, {
233
- description: "Object row"
234
- });
235
- var tableRowPrimitiveSchema = z5.array(tableCellValueSchema, {
236
- description: "Primitive row"
237
- });
238
- var tableSharedSchema = z5.object({
239
- title: z5.string().optional().describe("Display title for table")
240
- });
241
- var tablePrimitiveSchema = tableSharedSchema.merge(
242
- z5.object(
243
- {
244
- columns: z5.array(tableAlignmentSchema).optional(),
245
- rows: z5.array(tableRowPrimitiveSchema)
246
- },
247
- { description: "Table with primitive rows and optional alignment columns" }
248
- )
249
- );
250
- var tableObjectSchema = tableSharedSchema.merge(
251
- z5.object(
252
- {
253
- columns: z5.union([
254
- z5.array(tableAlignmentSchema),
255
- z5.array(tableColumnObjectSchema)
256
- ]).optional(),
257
- rows: z5.array(tableRowObjectSchema)
258
- },
259
- {
260
- description: "Table with object rows and optional alignment or object columns"
261
- }
262
- )
263
- );
264
- var tableSchema = (description = "Table information") => z5.union([tablePrimitiveSchema, tableObjectSchema], { description });
265
-
266
- // packages/models/src/lib/audit-output.ts
267
- var auditValueSchema = nonnegativeNumberSchema.describe("Raw numeric value");
268
- var auditDisplayValueSchema = z6.string({ description: "Formatted value (e.g. '0.9 s', '2.1 MB')" }).optional();
269
- var auditDetailsSchema = z6.object(
270
- {
271
- issues: z6.array(issueSchema, { description: "List of findings" }).optional(),
272
- table: tableSchema("Table of related findings").optional()
273
- },
274
- { description: "Detailed information" }
275
- );
276
- var auditOutputSchema = z6.object(
277
- {
278
- slug: slugSchema.describe("Reference to audit"),
279
- displayValue: auditDisplayValueSchema,
280
- value: auditValueSchema,
281
- score: scoreSchema,
282
- details: auditDetailsSchema.optional()
283
- },
284
- { description: "Audit information" }
285
- );
286
- var auditOutputsSchema = z6.array(auditOutputSchema, {
287
- description: "List of JSON formatted audit output emitted by the runner process of a plugin"
288
- }).refine(
289
- (audits) => !getDuplicateSlugsInAudits2(audits),
290
- (audits) => ({ message: duplicateSlugsInAuditsErrorMsg2(audits) })
291
- );
292
- function duplicateSlugsInAuditsErrorMsg2(audits) {
293
- const duplicateRefs = getDuplicateSlugsInAudits2(audits);
294
- return `In plugin audits the slugs are not unique: ${errorItems(
295
- duplicateRefs
296
- )}`;
297
- }
298
- function getDuplicateSlugsInAudits2(audits) {
299
- return hasDuplicateStrings(audits.map(({ slug }) => slug));
300
- }
301
-
302
- // packages/models/src/lib/category-config.ts
303
- import { z as z7 } from "zod";
304
- var categoryRefSchema = weightedRefSchema(
305
- "Weighted references to audits and/or groups for the category",
306
- "Slug of an audit or group (depending on `type`)"
307
- ).merge(
308
- z7.object({
309
- type: z7.enum(["audit", "group"], {
310
- description: "Discriminant for reference kind, affects where `slug` is looked up"
311
- }),
312
- plugin: slugSchema.describe(
313
- "Plugin slug (plugin should contain referenced audit or group)"
314
- )
315
- })
316
- );
317
- var categoryConfigSchema = scorableSchema(
318
- "Category with a score calculated from audits and groups from various plugins",
319
- categoryRefSchema,
320
- getDuplicateRefsInCategoryMetrics,
321
- duplicateRefsInCategoryMetricsErrorMsg
322
- ).merge(
323
- metaSchema({
324
- titleDescription: "Category Title",
325
- docsUrlDescription: "Category docs URL",
326
- descriptionDescription: "Category description",
327
- description: "Meta info for category"
328
- })
329
- ).merge(
330
- z7.object({
331
- isBinary: z7.boolean({
332
- description: 'Is this a binary category (i.e. only a perfect score considered a "pass")?'
333
- }).optional()
334
- })
335
- );
336
- function duplicateRefsInCategoryMetricsErrorMsg(metrics) {
337
- const duplicateRefs = getDuplicateRefsInCategoryMetrics(metrics);
338
- return `In the categories, the following audit or group refs are duplicates: ${errorItems(
339
- duplicateRefs
340
- )}`;
341
- }
342
- function getDuplicateRefsInCategoryMetrics(metrics) {
343
- return hasDuplicateStrings(
344
- metrics.map(({ slug, type, plugin }) => `${type} :: ${plugin} / ${slug}`)
345
- );
346
- }
347
- var categoriesSchema = z7.array(categoryConfigSchema, {
348
- description: "Categorization of individual audits"
349
- }).refine(
350
- (categoryCfg) => !getDuplicateSlugCategories(categoryCfg),
351
- (categoryCfg) => ({
352
- message: duplicateSlugCategoriesErrorMsg(categoryCfg)
353
- })
354
- );
355
- function duplicateSlugCategoriesErrorMsg(categories) {
356
- const duplicateStringSlugs = getDuplicateSlugCategories(categories);
357
- return `In the categories, the following slugs are duplicated: ${errorItems(
358
- duplicateStringSlugs
359
- )}`;
360
- }
361
- function getDuplicateSlugCategories(categories) {
362
- return hasDuplicateStrings(categories.map(({ slug }) => slug));
363
- }
364
-
365
- // packages/models/src/lib/commit.ts
366
- import { z as z8 } from "zod";
367
- var commitSchema = z8.object(
368
- {
369
- hash: z8.string({ description: "Commit SHA (full)" }).regex(
370
- /^[\da-f]{40}$/,
371
- "Commit SHA should be a 40-character hexadecimal string"
372
- ),
373
- message: z8.string({ description: "Commit message" }),
374
- date: z8.coerce.date({
375
- description: "Date and time when commit was authored"
376
- }),
377
- author: z8.string({
378
- description: "Commit author name"
379
- }).trim()
380
- },
381
- { description: "Git commit" }
382
- );
383
-
384
- // packages/models/src/lib/core-config.ts
385
- import { z as z14 } from "zod";
386
-
387
- // packages/models/src/lib/persist-config.ts
388
- import { z as z9 } from "zod";
389
- var formatSchema = z9.enum(["json", "md"]);
390
- var persistConfigSchema = z9.object({
391
- outputDir: filePathSchema.describe("Artifacts folder").optional(),
392
- filename: fileNameSchema.describe("Artifacts file name (without extension)").optional(),
393
- format: z9.array(formatSchema).optional()
394
- });
395
-
396
- // packages/models/src/lib/plugin-config.ts
397
- import { z as z12 } from "zod";
398
-
399
- // packages/models/src/lib/group.ts
400
- import { z as z10 } from "zod";
401
- var groupRefSchema = weightedRefSchema(
402
- "Weighted reference to a group",
403
- "Reference slug to a group within this plugin (e.g. 'max-lines')"
404
- );
405
- var groupMetaSchema = metaSchema({
406
- titleDescription: "Descriptive name for the group",
407
- descriptionDescription: "Description of the group (markdown)",
408
- docsUrlDescription: "Group documentation site",
409
- description: "Group metadata"
410
- });
411
- var groupSchema = scorableSchema(
412
- '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',
413
- groupRefSchema,
414
- getDuplicateRefsInGroups,
415
- duplicateRefsInGroupsErrorMsg
416
- ).merge(groupMetaSchema);
417
- var groupsSchema = z10.array(groupSchema, {
418
- description: "List of groups"
419
- }).optional().refine(
420
- (groups) => !getDuplicateSlugsInGroups(groups),
421
- (groups) => ({
422
- message: duplicateSlugsInGroupsErrorMsg(groups)
423
- })
424
- );
425
- function duplicateRefsInGroupsErrorMsg(groups) {
426
- const duplicateRefs = getDuplicateRefsInGroups(groups);
427
- return `In plugin groups the following references are not unique: ${errorItems(
428
- duplicateRefs
429
- )}`;
430
- }
431
- function getDuplicateRefsInGroups(groups) {
432
- return hasDuplicateStrings(groups.map(({ slug: ref }) => ref).filter(exists));
433
- }
434
- function duplicateSlugsInGroupsErrorMsg(groups) {
435
- const duplicateRefs = getDuplicateSlugsInGroups(groups);
436
- return `In groups the following slugs are not unique: ${errorItems(
437
- duplicateRefs
438
- )}`;
439
- }
440
- function getDuplicateSlugsInGroups(groups) {
441
- return Array.isArray(groups) ? hasDuplicateStrings(groups.map(({ slug }) => slug)) : false;
442
- }
443
-
444
- // packages/models/src/lib/runner-config.ts
445
- import { z as z11 } from "zod";
446
- var outputTransformSchema = z11.function().args(z11.unknown()).returns(z11.union([auditOutputsSchema, z11.promise(auditOutputsSchema)]));
447
- var runnerConfigSchema = z11.object(
448
- {
449
- command: z11.string({
450
- description: "Shell command to execute"
451
- }),
452
- args: z11.array(z11.string({ description: "Command arguments" })).optional(),
453
- outputFile: filePathSchema.describe("Output path"),
454
- outputTransform: outputTransformSchema.optional()
455
- },
456
- {
457
- description: "How to execute runner"
458
- }
459
- );
460
- var onProgressSchema = z11.function().args(z11.unknown()).returns(z11.void());
461
- var runnerFunctionSchema = z11.function().args(onProgressSchema.optional()).returns(z11.union([auditOutputsSchema, z11.promise(auditOutputsSchema)]));
462
-
463
- // packages/models/src/lib/plugin-config.ts
464
- var pluginMetaSchema = packageVersionSchema().merge(
465
- metaSchema({
466
- titleDescription: "Descriptive name",
467
- descriptionDescription: "Description (markdown)",
468
- docsUrlDescription: "Plugin documentation site",
469
- description: "Plugin metadata"
470
- })
471
- ).merge(
472
- z12.object({
473
- slug: slugSchema.describe("Unique plugin slug within core config"),
474
- icon: materialIconSchema
475
- })
476
- );
477
- var pluginDataSchema = z12.object({
478
- runner: z12.union([runnerConfigSchema, runnerFunctionSchema]),
479
- audits: pluginAuditsSchema,
480
- groups: groupsSchema
481
- });
482
- var pluginConfigSchema = pluginMetaSchema.merge(pluginDataSchema).refine(
483
- (pluginCfg) => !getMissingRefsFromGroups(pluginCfg),
484
- (pluginCfg) => ({
485
- message: missingRefsFromGroupsErrorMsg(pluginCfg)
486
- })
487
- );
488
- function missingRefsFromGroupsErrorMsg(pluginCfg) {
489
- const missingRefs = getMissingRefsFromGroups(pluginCfg);
490
- return `The following group references need to point to an existing audit in this plugin config: ${errorItems(
491
- missingRefs
492
- )}`;
493
- }
494
- function getMissingRefsFromGroups(pluginCfg) {
495
- return hasMissingStrings(
496
- pluginCfg.groups?.flatMap(
497
- ({ refs: audits }) => audits.map(({ slug: ref }) => ref)
498
- ) ?? [],
499
- pluginCfg.audits.map(({ slug }) => slug)
500
- );
501
- }
502
-
503
- // packages/models/src/lib/upload-config.ts
504
- import { z as z13 } from "zod";
505
- var uploadConfigSchema = z13.object({
506
- server: urlSchema.describe("URL of deployed portal API"),
507
- apiKey: z13.string({
508
- description: "API key with write access to portal (use `process.env` for security)"
509
- }),
510
- organization: slugSchema.describe(
511
- "Organization slug from Code PushUp portal"
512
- ),
513
- project: slugSchema.describe("Project slug from Code PushUp portal"),
514
- timeout: z13.number({ description: "Request timeout in minutes (default is 5)" }).positive().int().optional()
515
- });
516
-
517
- // packages/models/src/lib/core-config.ts
518
- var unrefinedCoreConfigSchema = z14.object({
519
- plugins: z14.array(pluginConfigSchema, {
520
- description: "List of plugins to be used (official, community-provided, or custom)"
521
- }).min(1),
522
- /** portal configuration for persisting results */
523
- persist: persistConfigSchema.optional(),
524
- /** portal configuration for uploading results */
525
- upload: uploadConfigSchema.optional(),
526
- categories: categoriesSchema.optional()
527
- });
528
- var coreConfigSchema = refineCoreConfig(unrefinedCoreConfigSchema);
529
- function refineCoreConfig(schema) {
530
- return schema.refine(
531
- ({ categories, plugins }) => !getMissingRefsForCategories(categories, plugins),
532
- ({ categories, plugins }) => ({
533
- message: missingRefsForCategoriesErrorMsg(categories, plugins)
534
- })
535
- );
536
- }
537
-
538
- // packages/models/src/lib/implementation/configuration.ts
539
- var CONFIG_FILE_NAME = "code-pushup.config";
540
- var SUPPORTED_CONFIG_FILE_FORMATS = ["ts", "mjs", "js"];
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/diff.ts
699
- function matchArrayItemsByKey({
700
- before,
701
- after,
702
- key
703
- }) {
704
- const pairs = [];
705
- const added = [];
706
- const afterKeys = /* @__PURE__ */ new Set();
707
- const keyFn = typeof key === "function" ? key : (item) => item[key];
708
- for (const afterItem of after) {
709
- const afterKey = keyFn(afterItem);
710
- afterKeys.add(afterKey);
711
- const match = before.find((beforeItem) => keyFn(beforeItem) === afterKey);
712
- if (match) {
713
- pairs.push({ before: match, after: afterItem });
714
- } else {
715
- added.push(afterItem);
716
- }
717
- }
718
- const removed = before.filter(
719
- (beforeItem) => !afterKeys.has(keyFn(beforeItem))
720
- );
721
- return {
722
- pairs,
723
- added,
724
- removed
725
- };
726
- }
727
- function comparePairs(pairs, equalsFn) {
728
- return pairs.reduce(
729
- (acc, pair) => ({
730
- ...acc,
731
- ...equalsFn(pair) ? { unchanged: [...acc.unchanged, pair.after] } : { changed: [...acc.changed, pair] }
732
- }),
733
- {
734
- changed: [],
735
- unchanged: []
736
- }
737
- );
738
- }
739
-
740
- // packages/utils/src/lib/errors.ts
741
- function stringifyError(error) {
742
- if (error instanceof Error) {
743
- if (error.name === "Error" || error.message.startsWith(error.name)) {
744
- return error.message;
745
- }
746
- return `${error.name}: ${error.message}`;
747
- }
748
- if (typeof error === "string") {
749
- return error;
750
- }
751
- return JSON.stringify(error);
752
- }
753
-
754
- // packages/utils/src/lib/execute-process.ts
755
- import {
756
- spawn
757
- } from "node:child_process";
758
-
759
- // packages/utils/src/lib/reports/utils.ts
760
- import ansis from "ansis";
761
- import { md } from "build-md";
762
-
763
- // packages/utils/src/lib/reports/constants.ts
764
- var TERMINAL_WIDTH = 80;
765
- var SCORE_COLOR_RANGE = {
766
- GREEN_MIN: 0.9,
767
- YELLOW_MIN: 0.5
768
- };
769
- var FOOTER_PREFIX = "Made with \u2764 by";
770
- var CODE_PUSHUP_DOMAIN = "code-pushup.dev";
771
- var README_LINK = "https://github.com/code-pushup/cli#readme";
772
- var REPORT_HEADLINE_TEXT = "Code PushUp Report";
773
- var REPORT_RAW_OVERVIEW_TABLE_HEADERS = [
774
- "Category",
775
- "Score",
776
- "Audits"
777
- ];
778
-
779
- // packages/utils/src/lib/reports/utils.ts
780
- function formatReportScore(score) {
781
- const scaledScore = score * 100;
782
- const roundedScore = Math.round(scaledScore);
783
- return roundedScore === 100 && score !== 1 ? Math.floor(scaledScore).toString() : roundedScore.toString();
784
- }
785
- function formatScoreWithColor(score, options) {
786
- const styledNumber = options?.skipBold ? formatReportScore(score) : md.bold(formatReportScore(score));
787
- return md`${scoreMarker(score)} ${styledNumber}`;
788
- }
789
- var MARKERS = {
790
- circle: {
791
- red: "\u{1F534}",
792
- yellow: "\u{1F7E1}",
793
- green: "\u{1F7E2}"
794
- },
795
- square: {
796
- red: "\u{1F7E5}",
797
- yellow: "\u{1F7E8}",
798
- green: "\u{1F7E9}"
799
- }
800
- };
801
- function scoreMarker(score, markerType = "circle") {
802
- if (score >= SCORE_COLOR_RANGE.GREEN_MIN) {
803
- return MARKERS[markerType].green;
804
- }
805
- if (score >= SCORE_COLOR_RANGE.YELLOW_MIN) {
806
- return MARKERS[markerType].yellow;
807
- }
808
- return MARKERS[markerType].red;
809
- }
810
- function getDiffMarker(diff) {
811
- if (diff > 0) {
812
- return "\u2191";
813
- }
814
- if (diff < 0) {
815
- return "\u2193";
816
- }
817
- return "";
818
- }
819
- function colorByScoreDiff(text, diff) {
820
- const color = diff > 0 ? "green" : diff < 0 ? "red" : "gray";
821
- return shieldsBadge(text, color);
822
- }
823
- function shieldsBadge(text, color) {
824
- return md.image(
825
- `https://img.shields.io/badge/${encodeURIComponent(text)}-${color}`,
826
- text
827
- );
828
- }
829
- function formatDiffNumber(diff) {
830
- const number = Math.abs(diff) === Number.POSITIVE_INFINITY ? "\u221E" : `${Math.abs(diff)}`;
831
- const sign = diff < 0 ? "\u2212" : "+";
832
- return `${sign}${number}`;
833
- }
834
- function severityMarker(severity) {
835
- if (severity === "error") {
836
- return "\u{1F6A8}";
837
- }
838
- if (severity === "warning") {
839
- return "\u26A0\uFE0F";
840
- }
841
- return "\u2139\uFE0F";
842
- }
843
- var MIN_NON_ZERO_RESULT = 0.1;
844
- function roundValue(value) {
845
- const roundedValue = Math.round(value * 10) / 10;
846
- if (roundedValue === 0 && value !== 0) {
847
- return MIN_NON_ZERO_RESULT * Math.sign(value);
848
- }
849
- return roundedValue;
850
- }
851
- function formatScoreChange(diff) {
852
- const marker = getDiffMarker(diff);
853
- const text = formatDiffNumber(roundValue(diff * 100));
854
- return colorByScoreDiff(`${marker} ${text}`, diff);
855
- }
856
- function formatValueChange({
857
- values,
858
- scores
859
- }) {
860
- const marker = getDiffMarker(values.diff);
861
- const percentage = values.before === 0 ? values.diff > 0 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY : roundValue(values.diff / values.before * 100);
862
- const text = `${formatDiffNumber(percentage)}\u2009%`;
863
- return colorByScoreDiff(`${marker} ${text}`, scores.diff);
864
- }
865
- function calcDuration(start, stop) {
866
- return Math.round((stop ?? performance.now()) - start);
867
- }
868
- function countCategoryAudits(refs, plugins) {
869
- const groupLookup = plugins.reduce(
870
- (lookup, plugin) => {
871
- if (plugin.groups == null || plugin.groups.length === 0) {
872
- return lookup;
873
- }
874
- return {
875
- ...lookup,
876
- [plugin.slug]: Object.fromEntries(
877
- plugin.groups.map((group) => [group.slug, group])
878
- )
879
- };
880
- },
881
- {}
882
- );
883
- return refs.reduce((acc, ref) => {
884
- if (ref.type === "group") {
885
- const groupRefs = groupLookup[ref.plugin]?.[ref.slug]?.refs;
886
- return acc + (groupRefs?.length ?? 0);
887
- }
888
- return acc + 1;
889
- }, 0);
890
- }
891
- function compareCategoryAuditsAndGroups(a, b) {
892
- if (a.score !== b.score) {
893
- return a.score - b.score;
894
- }
895
- if (a.weight !== b.weight) {
896
- return b.weight - a.weight;
897
- }
898
- if ("value" in a && "value" in b && a.value !== b.value) {
899
- return b.value - a.value;
900
- }
901
- return a.title.localeCompare(b.title);
902
- }
903
- function compareAudits(a, b) {
904
- if (a.score !== b.score) {
905
- return a.score - b.score;
906
- }
907
- if (a.value !== b.value) {
908
- return b.value - a.value;
909
- }
910
- return a.title.localeCompare(b.title);
911
- }
912
- function compareIssueSeverity(severity1, severity2) {
913
- const levels = {
914
- info: 0,
915
- warning: 1,
916
- error: 2
917
- };
918
- return levels[severity1] - levels[severity2];
919
- }
920
- function throwIsNotPresentError(itemName, presentPlace) {
921
- throw new Error(`${itemName} is not present in ${presentPlace}`);
922
- }
923
- function getPluginNameFromSlug(slug, plugins) {
924
- return plugins.find(({ slug: pluginSlug }) => pluginSlug === slug)?.title || slug;
925
- }
926
- function compareIssues(a, b) {
927
- if (a.severity !== b.severity) {
928
- return -compareIssueSeverity(a.severity, b.severity);
929
- }
930
- if (!a.source && b.source) {
931
- return -1;
932
- }
933
- if (a.source && !b.source) {
934
- return 1;
935
- }
936
- if (a.source?.file !== b.source?.file) {
937
- return a.source?.file.localeCompare(b.source?.file || "") ?? 0;
938
- }
939
- if (!a.source?.position && b.source?.position) {
940
- return -1;
941
- }
942
- if (a.source?.position && !b.source?.position) {
943
- return 1;
944
- }
945
- if (a.source?.position?.startLine !== b.source?.position?.startLine) {
946
- return (a.source?.position?.startLine ?? 0) - (b.source?.position?.startLine ?? 0);
947
- }
948
- return 0;
949
- }
950
- function applyScoreColor({ score, text }, style = ansis) {
951
- const formattedScore = text ?? formatReportScore(score);
952
- if (score >= SCORE_COLOR_RANGE.GREEN_MIN) {
953
- return text ? style.green(formattedScore) : style.bold(style.green(formattedScore));
954
- }
955
- if (score >= SCORE_COLOR_RANGE.YELLOW_MIN) {
956
- return text ? style.yellow(formattedScore) : style.bold(style.yellow(formattedScore));
957
- }
958
- return text ? style.red(formattedScore) : style.bold(style.red(formattedScore));
959
- }
960
- function targetScoreIcon(score, targetScore, options = {}) {
961
- if (targetScore != null) {
962
- const {
963
- passIcon = "\u2705",
964
- failIcon = "\u274C",
965
- prefix = "",
966
- postfix = ""
967
- } = options;
968
- if (score >= targetScore) {
969
- return `${prefix}${passIcon}${postfix}`;
970
- }
971
- return `${prefix}${failIcon}${postfix}`;
972
- }
973
- return "";
974
- }
975
-
976
- // packages/utils/src/lib/execute-process.ts
977
- var ProcessError = class extends Error {
978
- code;
979
- stderr;
980
- stdout;
981
- constructor(result) {
982
- super(result.stderr);
983
- this.code = result.code;
984
- this.stderr = result.stderr;
985
- this.stdout = result.stdout;
986
- }
987
- };
988
- function executeProcess(cfg) {
989
- const { command, args, observer, ignoreExitCode = false, ...options } = cfg;
990
- const { onStdout, onStderr, onError, onComplete } = observer ?? {};
991
- const date = (/* @__PURE__ */ new Date()).toISOString();
992
- const start = performance.now();
993
- return new Promise((resolve, reject) => {
994
- const spawnedProcess = spawn(command, args ?? [], {
995
- shell: true,
996
- windowsHide: true,
997
- ...options
998
- });
999
- let stdout = "";
1000
- let stderr = "";
1001
- spawnedProcess.stdout.on("data", (data) => {
1002
- stdout += String(data);
1003
- onStdout?.(String(data), spawnedProcess);
1004
- });
1005
- spawnedProcess.stderr.on("data", (data) => {
1006
- stderr += String(data);
1007
- onStderr?.(String(data), spawnedProcess);
1008
- });
1009
- spawnedProcess.on("error", (err) => {
1010
- stderr += err.toString();
1011
- });
1012
- spawnedProcess.on("close", (code2) => {
1013
- const timings = { date, duration: calcDuration(start) };
1014
- if (code2 === 0 || ignoreExitCode) {
1015
- onComplete?.();
1016
- resolve({ code: code2, stdout, stderr, ...timings });
1017
- } else {
1018
- const errorMsg = new ProcessError({ code: code2, stdout, stderr, ...timings });
1019
- onError?.(errorMsg);
1020
- reject(errorMsg);
1021
- }
1022
- });
1023
- });
1024
- }
1025
-
1026
- // packages/utils/src/lib/file-system.ts
1027
- import { bold, gray } from "ansis";
1028
- import { bundleRequire } from "bundle-require";
1029
- import { mkdir, readFile, readdir, rm, stat } from "node:fs/promises";
1030
-
1031
- // packages/utils/src/lib/formatting.ts
1032
- function slugify(text) {
1033
- return text.trim().toLowerCase().replace(/\s+|\//g, "-").replace(/[^a-z\d-]/g, "");
1034
- }
1035
- function pluralize(text, amount) {
1036
- if (amount != null && Math.abs(amount) === 1) {
1037
- return text;
1038
- }
1039
- if (text.endsWith("y")) {
1040
- return `${text.slice(0, -1)}ies`;
1041
- }
1042
- if (text.endsWith("s")) {
1043
- return `${text}es`;
1044
- }
1045
- return `${text}s`;
1046
- }
1047
- function formatBytes(bytes, decimals = 2) {
1048
- const positiveBytes = Math.max(bytes, 0);
1049
- if (positiveBytes === 0) {
1050
- return "0 B";
1051
- }
1052
- const k = 1024;
1053
- const dm = decimals < 0 ? 0 : decimals;
1054
- const sizes = ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
1055
- const i = Math.floor(Math.log(positiveBytes) / Math.log(k));
1056
- return `${Number.parseFloat((positiveBytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
1057
- }
1058
- function pluralizeToken(token, times) {
1059
- return `${times} ${Math.abs(times) === 1 ? token : pluralize(token)}`;
1060
- }
1061
- function formatDuration(duration, granularity = 0) {
1062
- if (duration < 1e3) {
1063
- return `${granularity ? duration.toFixed(granularity) : duration} ms`;
1064
- }
1065
- return `${(duration / 1e3).toFixed(2)} s`;
1066
- }
1067
- function formatDate(date) {
1068
- const locale = "en-US";
1069
- return date.toLocaleString(locale, {
1070
- weekday: "short",
1071
- month: "short",
1072
- day: "numeric",
1073
- year: "numeric",
1074
- hour: "numeric",
1075
- minute: "2-digit",
1076
- timeZoneName: "short"
1077
- }).replace(/\u202F/g, " ");
1078
- }
1079
-
1080
- // packages/utils/src/lib/guards.ts
1081
- function isPromiseFulfilledResult(result) {
1082
- return result.status === "fulfilled";
1083
- }
1084
- function isPromiseRejectedResult(result) {
1085
- return result.status === "rejected";
1086
- }
1087
-
1088
- // packages/utils/src/lib/logging.ts
1089
- import isaacs_cliui from "@isaacs/cliui";
1090
- import { cliui } from "@poppinss/cliui";
1091
- import { underline } from "ansis";
1092
- var singletonUiInstance;
1093
- function ui() {
1094
- if (singletonUiInstance === void 0) {
1095
- singletonUiInstance = cliui();
1096
- }
1097
- return {
1098
- ...singletonUiInstance,
1099
- row: (args) => {
1100
- logListItem(args);
1101
- }
1102
- };
1103
- }
1104
- var singletonisaacUi;
1105
- function logListItem(args) {
1106
- if (singletonisaacUi === void 0) {
1107
- singletonisaacUi = isaacs_cliui({ width: TERMINAL_WIDTH });
1108
- }
1109
- singletonisaacUi.div(...args);
1110
- const content = singletonisaacUi.toString();
1111
- singletonisaacUi.rows = [];
1112
- singletonUiInstance?.logger.log(content);
1113
- }
1114
-
1115
- // packages/utils/src/lib/log-results.ts
1116
- function logMultipleResults(results, messagePrefix, succeededTransform, failedTransform) {
1117
- if (succeededTransform) {
1118
- const succeededResults = results.filter(isPromiseFulfilledResult);
1119
- logPromiseResults(
1120
- succeededResults,
1121
- `${messagePrefix} successfully: `,
1122
- succeededTransform
1123
- );
1124
- }
1125
- if (failedTransform) {
1126
- const failedResults = results.filter(isPromiseRejectedResult);
1127
- logPromiseResults(
1128
- failedResults,
1129
- `${messagePrefix} failed: `,
1130
- failedTransform
1131
- );
1132
- }
1133
- }
1134
- function logPromiseResults(results, logMessage, getMsg) {
1135
- if (results.length > 0) {
1136
- const log2 = results[0]?.status === "fulfilled" ? (m) => {
1137
- ui().logger.success(m);
1138
- } : (m) => {
1139
- ui().logger.warning(m);
1140
- };
1141
- log2(logMessage);
1142
- results.forEach((result) => {
1143
- log2(getMsg(result));
1144
- });
1145
- }
1146
- }
1147
-
1148
- // packages/utils/src/lib/file-system.ts
1149
- async function readTextFile(path) {
1150
- const buffer = await readFile(path);
1151
- return buffer.toString();
1152
- }
1153
- async function readJsonFile(path) {
1154
- const text = await readTextFile(path);
1155
- return JSON.parse(text);
1156
- }
1157
- async function fileExists(path) {
1158
- try {
1159
- const stats = await stat(path);
1160
- return stats.isFile();
1161
- } catch {
1162
- return false;
1163
- }
1164
- }
1165
- async function directoryExists(path) {
1166
- try {
1167
- const stats = await stat(path);
1168
- return stats.isDirectory();
1169
- } catch {
1170
- return false;
1171
- }
1172
- }
1173
- async function ensureDirectoryExists(baseDir) {
1174
- try {
1175
- await mkdir(baseDir, { recursive: true });
1176
- return;
1177
- } catch (error) {
1178
- ui().logger.info(error.message);
1179
- if (error.code !== "EEXIST") {
1180
- throw error;
1181
- }
1182
- }
1183
- }
1184
- function logMultipleFileResults(fileResults, messagePrefix) {
1185
- const succeededTransform = (result) => {
1186
- const [fileName, size] = result.value;
1187
- const formattedSize = size ? ` (${gray(formatBytes(size))})` : "";
1188
- return `- ${bold(fileName)}${formattedSize}`;
1189
- };
1190
- const failedTransform = (result) => `- ${bold(result.reason)}`;
1191
- logMultipleResults(
1192
- fileResults,
1193
- messagePrefix,
1194
- succeededTransform,
1195
- failedTransform
1196
- );
1197
- }
1198
- async function importModule(options) {
1199
- const { mod } = await bundleRequire(options);
1200
- if (typeof mod === "object" && "default" in mod) {
1201
- return mod.default;
1202
- }
1203
- return mod;
1204
- }
1205
-
1206
- // packages/utils/src/lib/git/git.ts
1207
- import { isAbsolute, join, relative } from "node:path";
1208
- import { simpleGit } from "simple-git";
1209
-
1210
- // packages/utils/src/lib/transform.ts
1211
- function toArray(val) {
1212
- return Array.isArray(val) ? val : [val];
1213
- }
1214
- function objectToEntries(obj) {
1215
- return Object.entries(obj);
1216
- }
1217
- function deepClone(obj) {
1218
- return obj == null || typeof obj !== "object" ? obj : structuredClone(obj);
1219
- }
1220
- function toUnixPath(path) {
1221
- return path.replace(/\\/g, "/");
1222
- }
1223
- function capitalize(text) {
1224
- return `${text.charAt(0).toLocaleUpperCase()}${text.slice(
1225
- 1
1226
- )}`;
1227
- }
1228
-
1229
- // packages/utils/src/lib/git/git.ts
1230
- function getGitRoot(git = simpleGit()) {
1231
- return git.revparse("--show-toplevel");
1232
- }
1233
- function formatGitPath(path, gitRoot) {
1234
- const absolutePath = isAbsolute(path) ? path : join(process.cwd(), path);
1235
- const relativePath = relative(gitRoot, absolutePath);
1236
- return toUnixPath(relativePath);
1237
- }
1238
- var GitStatusError = class _GitStatusError extends Error {
1239
- static ignoredProps = /* @__PURE__ */ new Set(["current", "tracking"]);
1240
- static getReducedStatus(status) {
1241
- return Object.fromEntries(
1242
- Object.entries(status).filter(([key]) => !this.ignoredProps.has(key)).filter(
1243
- (entry) => {
1244
- const value = entry[1];
1245
- if (value == null) {
1246
- return false;
1247
- }
1248
- if (Array.isArray(value) && value.length === 0) {
1249
- return false;
1250
- }
1251
- if (typeof value === "number" && value === 0) {
1252
- return false;
1253
- }
1254
- return !(typeof value === "boolean" && !value);
1255
- }
1256
- )
1257
- );
1258
- }
1259
- constructor(status) {
1260
- super(
1261
- `Working directory needs to be clean before we you can proceed. Commit your local changes or stash them:
1262
- ${JSON.stringify(
1263
- _GitStatusError.getReducedStatus(status),
1264
- null,
1265
- 2
1266
- )}`
1267
- );
1268
- }
1269
- };
1270
- async function guardAgainstLocalChanges(git = simpleGit()) {
1271
- const status = await git.status(["-s"]);
1272
- if (status.files.length > 0) {
1273
- throw new GitStatusError(status);
1274
- }
1275
- }
1276
- async function safeCheckout(branchOrHash, forceCleanStatus = false, git = simpleGit()) {
1277
- if (forceCleanStatus) {
1278
- await git.raw(["reset", "--hard"]);
1279
- await git.clean(["f", "d"]);
1280
- ui().logger.info(`git status cleaned`);
1281
- }
1282
- await guardAgainstLocalChanges(git);
1283
- await git.checkout(branchOrHash);
1284
- }
1285
-
1286
- // packages/utils/src/lib/git/git.commits-and-tags.ts
1287
- import { simpleGit as simpleGit2 } from "simple-git";
1288
-
1289
- // packages/utils/src/lib/semver.ts
1290
- import { rcompare, valid } from "semver";
1291
-
1292
- // packages/utils/src/lib/git/git.commits-and-tags.ts
1293
- async function getLatestCommit(git = simpleGit2()) {
1294
- const log2 = await git.log({
1295
- maxCount: 1,
1296
- // git log -1 --pretty=format:"%H %s %an %aI" - See: https://git-scm.com/docs/pretty-formats
1297
- format: { hash: "%H", message: "%s", author: "%an", date: "%aI" }
1298
- });
1299
- return commitSchema.parse(log2.latest);
1300
- }
1301
- async function getCurrentBranchOrTag(git = simpleGit2()) {
1302
- return await git.branch().then((r) => r.current) || // If no current branch, try to get the tag
1303
- // @TODO use simple git
1304
- await git.raw(["describe", "--tags", "--exact-match"]).then((out) => out.trim());
1305
- }
1306
-
1307
- // packages/utils/src/lib/group-by-status.ts
1308
- function groupByStatus(results) {
1309
- return results.reduce(
1310
- (acc, result) => result.status === "fulfilled" ? { ...acc, fulfilled: [...acc.fulfilled, result] } : { ...acc, rejected: [...acc.rejected, result] },
1311
- { fulfilled: [], rejected: [] }
1312
- );
1313
- }
1314
-
1315
- // packages/utils/src/lib/progress.ts
1316
- import { black, bold as bold2, gray as gray2, green } from "ansis";
1317
- import { MultiProgressBars } from "multi-progress-bars";
1318
- var barStyles = {
1319
- active: (s) => green(s),
1320
- done: (s) => gray2(s),
1321
- idle: (s) => gray2(s)
1322
- };
1323
- var messageStyles = {
1324
- active: (s) => black(s),
1325
- done: (s) => bold2.green(s),
1326
- idle: (s) => gray2(s)
1327
- };
1328
- var mpb;
1329
- function getSingletonProgressBars(options) {
1330
- if (!mpb) {
1331
- mpb = new MultiProgressBars({
1332
- progressWidth: TERMINAL_WIDTH,
1333
- initMessage: "",
1334
- border: true,
1335
- ...options
1336
- });
1337
- }
1338
- return mpb;
1339
- }
1340
- function getProgressBar(taskName) {
1341
- const tasks = getSingletonProgressBars();
1342
- tasks.addTask(taskName, {
1343
- type: "percentage",
1344
- percentage: 0,
1345
- message: "",
1346
- barTransformFn: barStyles.idle
1347
- });
1348
- return {
1349
- incrementInSteps: (numPlugins) => {
1350
- tasks.incrementTask(taskName, {
1351
- percentage: 1 / numPlugins,
1352
- barTransformFn: barStyles.active
1353
- });
1354
- },
1355
- updateTitle: (title) => {
1356
- tasks.updateTask(taskName, {
1357
- message: title,
1358
- barTransformFn: barStyles.active
1359
- });
1360
- },
1361
- endProgress: (message = "") => {
1362
- tasks.done(taskName, {
1363
- message: messageStyles.done(message),
1364
- barTransformFn: barStyles.done
1365
- });
1366
- }
1367
- };
1368
- }
1369
-
1370
- // packages/utils/src/lib/reports/flatten-plugins.ts
1371
- function listGroupsFromAllPlugins(report) {
1372
- return report.plugins.flatMap(
1373
- (plugin) => plugin.groups?.map((group) => ({ plugin, group })) ?? []
1374
- );
1375
- }
1376
- function listAuditsFromAllPlugins(report) {
1377
- return report.plugins.flatMap(
1378
- (plugin) => plugin.audits.map((audit) => ({ plugin, audit }))
1379
- );
1380
- }
1381
-
1382
- // packages/utils/src/lib/reports/generate-md-report.ts
1383
- import { MarkdownDocument as MarkdownDocument3, md as md4 } from "build-md";
1384
-
1385
- // packages/utils/src/lib/text-formats/constants.ts
1386
- var HIERARCHY = {
1387
- level_1: 1,
1388
- level_2: 2,
1389
- level_3: 3,
1390
- level_4: 4,
1391
- level_5: 5,
1392
- level_6: 6
1393
- };
1394
-
1395
- // packages/utils/src/lib/text-formats/table.ts
1396
- function rowToStringArray({ rows, columns = [] }) {
1397
- if (Array.isArray(rows.at(0)) && typeof columns.at(0) === "object") {
1398
- throw new TypeError(
1399
- "Column can`t be object when rows are primitive values"
1400
- );
1401
- }
1402
- return rows.map((row) => {
1403
- if (Array.isArray(row)) {
1404
- return row.map(String);
1405
- }
1406
- const objectRow = row;
1407
- if (columns.length === 0 || typeof columns.at(0) === "string") {
1408
- return Object.values(objectRow).map(
1409
- (value) => value == null ? "" : String(value)
1410
- );
1411
- }
1412
- return columns.map(
1413
- ({ key }) => objectRow[key] == null ? "" : String(objectRow[key])
1414
- );
1415
- });
1416
- }
1417
- function columnsToStringArray({
1418
- rows,
1419
- columns = []
1420
- }) {
1421
- const firstRow = rows.at(0);
1422
- const primitiveRows = Array.isArray(firstRow);
1423
- if (typeof columns.at(0) === "string" && !primitiveRows) {
1424
- throw new Error("invalid union type. Caught by model parsing.");
1425
- }
1426
- if (columns.length === 0) {
1427
- if (Array.isArray(firstRow)) {
1428
- return firstRow.map((_, idx) => String(idx));
1429
- }
1430
- return Object.keys(firstRow);
1431
- }
1432
- if (typeof columns.at(0) === "string") {
1433
- return columns.map(String);
1434
- }
1435
- const cols = columns;
1436
- return cols.map(({ label, key }) => label ?? capitalize(key));
1437
- }
1438
- function getColumnAlignmentForKeyAndIndex(targetKey, targetIdx, columns = []) {
1439
- const column = columns.at(targetIdx) ?? columns.find((col) => col.key === targetKey);
1440
- if (typeof column === "string") {
1441
- return column;
1442
- } else if (typeof column === "object") {
1443
- return column.align ?? "center";
1444
- } else {
1445
- return "center";
1446
- }
1447
- }
1448
- function getColumnAlignmentForIndex(targetIdx, columns = []) {
1449
- const column = columns.at(targetIdx);
1450
- if (column == null) {
1451
- return "center";
1452
- } else if (typeof column === "string") {
1453
- return column;
1454
- } else if (typeof column === "object") {
1455
- return column.align ?? "center";
1456
- } else {
1457
- return "center";
1458
- }
1459
- }
1460
- function getColumnAlignments(tableData) {
1461
- const { rows, columns = [] } = tableData;
1462
- if (rows.at(0) == null) {
1463
- throw new Error("first row can`t be undefined.");
1464
- }
1465
- if (Array.isArray(rows.at(0))) {
1466
- const firstPrimitiveRow = rows.at(0);
1467
- return Array.from({ length: firstPrimitiveRow.length }).map(
1468
- (_, idx) => getColumnAlignmentForIndex(idx, columns)
1469
- );
1470
- }
1471
- const biggestRow = rows.toSorted((a, b) => Object.keys(a).length - Object.keys(b).length).at(-1);
1472
- if (columns.length > 0) {
1473
- return columns.map(
1474
- (column, idx) => typeof column === "string" ? column : getColumnAlignmentForKeyAndIndex(
1475
- column.key,
1476
- idx,
1477
- columns
1478
- )
1479
- );
1480
- }
1481
- return Object.keys(biggestRow ?? {}).map((_) => "center");
1482
- }
1483
-
1484
- // packages/utils/src/lib/reports/formatting.ts
1485
- import {
1486
- MarkdownDocument,
1487
- md as md2
1488
- } from "build-md";
1489
- import { posix as pathPosix } from "node:path";
1490
-
1491
- // packages/utils/src/lib/reports/types.ts
1492
- var SUPPORTED_ENVIRONMENTS = [
1493
- "vscode",
1494
- "github",
1495
- "gitlab",
1496
- "other"
1497
- ];
1498
-
1499
- // packages/utils/src/lib/reports/environment-type.ts
1500
- var environmentChecks = {
1501
- vscode: () => process.env["TERM_PROGRAM"] === "vscode",
1502
- github: () => process.env["GITHUB_ACTIONS"] === "true",
1503
- gitlab: () => process.env["GITLAB_CI"] === "true",
1504
- other: () => true
1505
- };
1506
- function getEnvironmentType() {
1507
- return SUPPORTED_ENVIRONMENTS.find((env) => environmentChecks[env]()) ?? "other";
1508
- }
1509
- function getGitHubBaseUrl() {
1510
- return `${process.env["GITHUB_SERVER_URL"]}/${process.env["GITHUB_REPOSITORY"]}/blob/${process.env["GITHUB_SHA"]}`;
1511
- }
1512
- function getGitLabBaseUrl() {
1513
- return `${process.env["CI_SERVER_URL"]}/${process.env["CI_PROJECT_PATH"]}/-/blob/${process.env["CI_COMMIT_SHA"]}`;
1514
- }
1515
-
1516
- // packages/utils/src/lib/reports/formatting.ts
1517
- function tableSection(tableData, options) {
1518
- if (tableData.rows.length === 0) {
1519
- return null;
1520
- }
1521
- const { level = HIERARCHY.level_4 } = options ?? {};
1522
- const columns = columnsToStringArray(tableData);
1523
- const alignments = getColumnAlignments(tableData);
1524
- const rows = rowToStringArray(tableData);
1525
- return new MarkdownDocument().heading(level, tableData.title).table(
1526
- columns.map((heading, i) => {
1527
- const alignment = alignments[i];
1528
- if (alignment) {
1529
- return { heading, alignment };
1530
- }
1531
- return heading;
1532
- }),
1533
- rows
1534
- );
1535
- }
1536
- function metaDescription(audit) {
1537
- const docsUrl = audit.docsUrl;
1538
- const description = audit.description?.trim();
1539
- if (docsUrl) {
1540
- const docsLink = md2.link(docsUrl, "\u{1F4D6} Docs");
1541
- if (!description) {
1542
- return docsLink;
1543
- }
1544
- const parsedDescription = description.endsWith("```") ? `${description}
1545
-
1546
- ` : `${description} `;
1547
- return md2`${parsedDescription}${docsLink}`;
1548
- }
1549
- if (description && description.trim().length > 0) {
1550
- return description;
1551
- }
1552
- return "";
1553
- }
1554
- function linkToLocalSourceForIde(source, options) {
1555
- const { file, position } = source;
1556
- const { outputDir } = options ?? {};
1557
- if (!outputDir) {
1558
- return md2.code(file);
1559
- }
1560
- return md2.link(formatFileLink(file, position, outputDir), md2.code(file));
1561
- }
1562
- function formatSourceLine(position) {
1563
- if (!position) {
1564
- return "";
1565
- }
1566
- const { startLine, endLine } = position;
1567
- return endLine && startLine !== endLine ? `${startLine}-${endLine}` : `${startLine}`;
1568
- }
1569
- function formatGitHubLink(file, position) {
1570
- const baseUrl = getGitHubBaseUrl();
1571
- if (!position) {
1572
- return `${baseUrl}/${file}`;
1573
- }
1574
- const { startLine, endLine, startColumn, endColumn } = position;
1575
- const start = startColumn ? `L${startLine}C${startColumn}` : `L${startLine}`;
1576
- const end = endLine ? endColumn ? `L${endLine}C${endColumn}` : `L${endLine}` : "";
1577
- const lineRange = end && start !== end ? `${start}-${end}` : start;
1578
- return `${baseUrl}/${file}#${lineRange}`;
1579
- }
1580
- function formatGitLabLink(file, position) {
1581
- const baseUrl = getGitLabBaseUrl();
1582
- if (!position) {
1583
- return `${baseUrl}/${file}`;
1584
- }
1585
- const { startLine, endLine } = position;
1586
- const lineRange = endLine && startLine !== endLine ? `${startLine}-${endLine}` : startLine;
1587
- return `${baseUrl}/${file}#L${lineRange}`;
1588
- }
1589
- function formatFileLink(file, position, outputDir) {
1590
- const relativePath = pathPosix.relative(outputDir, file);
1591
- const env = getEnvironmentType();
1592
- switch (env) {
1593
- case "vscode":
1594
- return position ? `${relativePath}#L${position.startLine}` : relativePath;
1595
- case "github":
1596
- return formatGitHubLink(file, position);
1597
- case "gitlab":
1598
- return formatGitLabLink(file, position);
1599
- default:
1600
- return relativePath;
1601
- }
1602
- }
1603
-
1604
- // packages/utils/src/lib/reports/generate-md-report-categoy-section.ts
1605
- import { MarkdownDocument as MarkdownDocument2, md as md3 } from "build-md";
1606
-
1607
- // packages/utils/src/lib/reports/sorting.ts
1608
- function getSortableAuditByRef({ slug, weight, plugin }, plugins) {
1609
- const auditPlugin = plugins.find((p) => p.slug === plugin);
1610
- if (!auditPlugin) {
1611
- throwIsNotPresentError(`Plugin ${plugin}`, "report");
1612
- }
1613
- const audit = auditPlugin.audits.find(
1614
- ({ slug: auditSlug }) => auditSlug === slug
1615
- );
1616
- if (!audit) {
1617
- throwIsNotPresentError(`Audit ${slug}`, auditPlugin.slug);
1618
- }
1619
- return {
1620
- ...audit,
1621
- weight,
1622
- plugin
1623
- };
1624
- }
1625
- function getSortedGroupAudits(group, plugin, plugins) {
1626
- return group.refs.map(
1627
- (ref) => getSortableAuditByRef(
1628
- {
1629
- plugin,
1630
- slug: ref.slug,
1631
- weight: ref.weight,
1632
- type: "audit"
1633
- },
1634
- plugins
1635
- )
1636
- ).sort(compareCategoryAuditsAndGroups);
1637
- }
1638
- function getSortableGroupByRef({ plugin, slug, weight }, plugins) {
1639
- const groupPlugin = plugins.find((p) => p.slug === plugin);
1640
- if (!groupPlugin) {
1641
- throwIsNotPresentError(`Plugin ${plugin}`, "report");
1642
- }
1643
- const group = groupPlugin.groups?.find(
1644
- ({ slug: groupSlug }) => groupSlug === slug
1645
- );
1646
- if (!group) {
1647
- throwIsNotPresentError(`Group ${slug}`, groupPlugin.slug);
1648
- }
1649
- const sortedAudits = getSortedGroupAudits(group, groupPlugin.slug, plugins);
1650
- const sortedAuditRefs = group.refs.toSorted((a, b) => {
1651
- const aIndex = sortedAudits.findIndex((ref) => ref.slug === a.slug);
1652
- const bIndex = sortedAudits.findIndex((ref) => ref.slug === b.slug);
1653
- return aIndex - bIndex;
1654
- });
1655
- return {
1656
- ...group,
1657
- refs: sortedAuditRefs,
1658
- plugin,
1659
- weight
1660
- };
1661
- }
1662
- function sortReport(report) {
1663
- const { categories, plugins } = report;
1664
- const sortedCategories = categories?.map((category) => {
1665
- const { audits, groups } = category.refs.reduce(
1666
- (acc, ref) => ({
1667
- ...acc,
1668
- ...ref.type === "group" ? {
1669
- groups: [...acc.groups, getSortableGroupByRef(ref, plugins)]
1670
- } : {
1671
- audits: [...acc.audits, getSortableAuditByRef(ref, plugins)]
1672
- }
1673
- }),
1674
- { groups: [], audits: [] }
1675
- );
1676
- const sortedAuditsAndGroups = [...audits, ...groups].sort(
1677
- compareCategoryAuditsAndGroups
1678
- );
1679
- const sortedRefs = category.refs.toSorted((a, b) => {
1680
- const aIndex = sortedAuditsAndGroups.findIndex(
1681
- (ref) => ref.slug === a.slug && ref.plugin === a.plugin
1682
- );
1683
- const bIndex = sortedAuditsAndGroups.findIndex(
1684
- (ref) => ref.slug === b.slug && ref.plugin === b.plugin
1685
- );
1686
- return aIndex - bIndex;
1687
- });
1688
- return { ...category, refs: sortedRefs };
1689
- });
1690
- return {
1691
- ...report,
1692
- categories: sortedCategories,
1693
- plugins: sortPlugins(plugins)
1694
- };
1695
- }
1696
- function sortPlugins(plugins) {
1697
- return plugins.map((plugin) => ({
1698
- ...plugin,
1699
- audits: plugin.audits.toSorted(compareAudits).map(
1700
- (audit) => audit.details?.issues ? {
1701
- ...audit,
1702
- details: {
1703
- ...audit.details,
1704
- issues: audit.details.issues.toSorted(compareIssues)
1705
- }
1706
- } : audit
1707
- )
1708
- }));
1709
- }
1710
-
1711
- // packages/utils/src/lib/reports/generate-md-report-categoy-section.ts
1712
- function categoriesOverviewSection(report) {
1713
- const { categories, plugins } = report;
1714
- return new MarkdownDocument2().table(
1715
- [
1716
- { heading: "\u{1F3F7} Category", alignment: "left" },
1717
- { heading: "\u2B50 Score", alignment: "center" },
1718
- { heading: "\u{1F6E1} Audits", alignment: "center" }
1719
- ],
1720
- categories.map(({ title, refs, score, isBinary }) => [
1721
- // @TODO refactor `isBinary: boolean` to `targetScore: number` #713
1722
- // The heading "ID" is inferred from the heading text in Markdown.
1723
- md3.link(`#${slugify(title)}`, title),
1724
- md3`${scoreMarker(score)} ${md3.bold(
1725
- formatReportScore(score)
1726
- )}${binaryIconSuffix(score, isBinary)}`,
1727
- countCategoryAudits(refs, plugins).toString()
1728
- ])
1729
- );
1730
- }
1731
- function categoriesDetailsSection(report) {
1732
- const { categories, plugins } = report;
1733
- return new MarkdownDocument2().heading(HIERARCHY.level_2, "\u{1F3F7} Categories").$foreach(
1734
- categories,
1735
- (doc, category) => doc.heading(HIERARCHY.level_3, category.title).paragraph(metaDescription(category)).paragraph(
1736
- md3`${scoreMarker(category.score)} Score: ${md3.bold(
1737
- formatReportScore(category.score)
1738
- )}${binaryIconSuffix(category.score, category.isBinary)}`
1739
- ).list(
1740
- category.refs.map((ref) => {
1741
- if (ref.type === "group") {
1742
- const group = getSortableGroupByRef(ref, plugins);
1743
- const groupAudits = group.refs.map(
1744
- (groupRef) => getSortableAuditByRef(
1745
- { ...groupRef, plugin: group.plugin, type: "audit" },
1746
- plugins
1747
- )
1748
- );
1749
- const pluginTitle = getPluginNameFromSlug(ref.plugin, plugins);
1750
- return categoryGroupItem(group, groupAudits, pluginTitle);
1751
- } else {
1752
- const audit = getSortableAuditByRef(ref, plugins);
1753
- const pluginTitle = getPluginNameFromSlug(ref.plugin, plugins);
1754
- return categoryRef(audit, pluginTitle);
1755
- }
1756
- })
1757
- )
1758
- );
1759
- }
1760
- function categoryRef({ title, score, value, displayValue }, pluginTitle) {
1761
- const auditTitleAsLink = md3.link(
1762
- `#${slugify(title)}-${slugify(pluginTitle)}`,
1763
- title
1764
- );
1765
- const marker = scoreMarker(score, "square");
1766
- return md3`${marker} ${auditTitleAsLink} (${md3.italic(
1767
- pluginTitle
1768
- )}) - ${md3.bold((displayValue || value).toString())}`;
1769
- }
1770
- function categoryGroupItem({ score = 0, title }, groupAudits, pluginTitle) {
1771
- const groupTitle = md3`${scoreMarker(score)} ${title} (${md3.italic(
1772
- pluginTitle
1773
- )})`;
1774
- const auditsList = md3.list(
1775
- groupAudits.map(
1776
- ({ title: auditTitle, score: auditScore, value, displayValue }) => {
1777
- const auditTitleLink = md3.link(
1778
- `#${slugify(auditTitle)}-${slugify(pluginTitle)}`,
1779
- auditTitle
1780
- );
1781
- const marker = scoreMarker(auditScore, "square");
1782
- return md3`${marker} ${auditTitleLink} - ${md3.bold(
1783
- String(displayValue ?? value)
1784
- )}`;
1785
- }
1786
- )
1787
- );
1788
- return md3`${groupTitle}${auditsList}`;
1789
- }
1790
- function binaryIconSuffix(score, isBinary) {
1791
- return targetScoreIcon(score, isBinary ? 1 : void 0, { prefix: " " });
1792
- }
1793
-
1794
- // packages/utils/src/lib/reports/generate-md-report.ts
1795
- function auditDetailsAuditValue({
1796
- score,
1797
- value,
1798
- displayValue
1799
- }) {
1800
- return md4`${scoreMarker(score, "square")} ${md4.bold(
1801
- String(displayValue ?? value)
1802
- )} (score: ${formatReportScore(score)})`;
1803
- }
1804
- function hasCategories(report) {
1805
- return !!report.categories && report.categories.length > 0;
1806
- }
1807
- function generateMdReport(report, options) {
1808
- return new MarkdownDocument3().heading(HIERARCHY.level_1, REPORT_HEADLINE_TEXT).$concat(
1809
- ...hasCategories(report) ? [categoriesOverviewSection(report), categoriesDetailsSection(report)] : [],
1810
- auditsSection(report, options),
1811
- aboutSection(report)
1812
- ).rule().paragraph(md4`${FOOTER_PREFIX} ${md4.link(README_LINK, "Code PushUp")}`).toString();
1813
- }
1814
- function auditDetailsIssues(issues = [], options) {
1815
- if (issues.length === 0) {
1816
- return null;
1817
- }
1818
- return new MarkdownDocument3().heading(HIERARCHY.level_4, "Issues").table(
1819
- [
1820
- { heading: "Severity", alignment: "center" },
1821
- { heading: "Message", alignment: "left" },
1822
- { heading: "Source file", alignment: "left" },
1823
- { heading: "Line(s)", alignment: "center" }
1824
- ],
1825
- issues.map(({ severity: level, message, source }) => {
1826
- const severity = md4`${severityMarker(level)} ${md4.italic(level)}`;
1827
- if (!source) {
1828
- return [severity, message];
1829
- }
1830
- const file = linkToLocalSourceForIde(source, options);
1831
- if (!source.position) {
1832
- return [severity, message, file];
1833
- }
1834
- const line = formatSourceLine(source.position);
1835
- return [severity, message, file, line];
1836
- })
1837
- );
1838
- }
1839
- function auditDetails(audit, options) {
1840
- const { table: table2, issues = [] } = audit.details ?? {};
1841
- const detailsValue = auditDetailsAuditValue(audit);
1842
- if (issues.length === 0 && !table2?.rows.length) {
1843
- return new MarkdownDocument3().paragraph(detailsValue);
1844
- }
1845
- const tableSectionContent = table2 && tableSection(table2);
1846
- const issuesSectionContent = issues.length > 0 && auditDetailsIssues(issues, options);
1847
- return new MarkdownDocument3().details(
1848
- detailsValue,
1849
- new MarkdownDocument3().$concat(tableSectionContent, issuesSectionContent)
1850
- );
1851
- }
1852
- function auditsSection({ plugins }, options) {
1853
- return new MarkdownDocument3().heading(HIERARCHY.level_2, "\u{1F6E1}\uFE0F Audits").$foreach(
1854
- plugins.flatMap(
1855
- (plugin) => plugin.audits.map((audit) => ({ ...audit, plugin }))
1856
- ),
1857
- (doc, { plugin, ...audit }) => {
1858
- const auditTitle = `${audit.title} (${plugin.title})`;
1859
- const detailsContent = auditDetails(audit, options);
1860
- const descriptionContent = metaDescription(audit);
1861
- return doc.heading(HIERARCHY.level_3, auditTitle).$concat(detailsContent).paragraph(descriptionContent);
1862
- }
1863
- );
1864
- }
1865
- function aboutSection(report) {
1866
- const { date, plugins } = report;
1867
- return new MarkdownDocument3().heading(HIERARCHY.level_2, "About").paragraph(
1868
- md4`Report was created by ${md4.link(
1869
- README_LINK,
1870
- "Code PushUp"
1871
- )} on ${formatDate(new Date(date))}.`
1872
- ).table(...pluginMetaTable({ plugins })).table(...reportMetaTable(report));
1873
- }
1874
- function pluginMetaTable({
1875
- plugins
1876
- }) {
1877
- return [
1878
- [
1879
- { heading: "Plugin", alignment: "left" },
1880
- { heading: "Audits", alignment: "center" },
1881
- { heading: "Version", alignment: "center" },
1882
- { heading: "Duration", alignment: "right" }
1883
- ],
1884
- plugins.map(({ title, audits, version: version2 = "", duration }) => [
1885
- title,
1886
- audits.length.toString(),
1887
- version2 && md4.code(version2),
1888
- formatDuration(duration)
1889
- ])
1890
- ];
1891
- }
1892
- function reportMetaTable({
1893
- commit,
1894
- version: version2,
1895
- duration,
1896
- plugins,
1897
- categories
1898
- }) {
1899
- return [
1900
- [
1901
- { heading: "Commit", alignment: "left" },
1902
- { heading: "Version", alignment: "center" },
1903
- { heading: "Duration", alignment: "right" },
1904
- { heading: "Plugins", alignment: "center" },
1905
- { heading: "Categories", alignment: "center" },
1906
- { heading: "Audits", alignment: "center" }
1907
- ],
1908
- [
1909
- [
1910
- commit ? `${commit.message} (${commit.hash})` : "N/A",
1911
- md4.code(version2),
1912
- formatDuration(duration),
1913
- plugins.length.toString(),
1914
- (categories?.length ?? 0).toString(),
1915
- plugins.reduce((acc, { audits }) => acc + audits.length, 0).toString()
1916
- ]
1917
- ]
1918
- ];
1919
- }
1920
-
1921
- // packages/utils/src/lib/reports/generate-md-reports-diff.ts
1922
- import {
1923
- MarkdownDocument as MarkdownDocument5,
1924
- md as md6
1925
- } from "build-md";
1926
-
1927
- // packages/utils/src/lib/reports/generate-md-reports-diff-utils.ts
1928
- import { MarkdownDocument as MarkdownDocument4, md as md5 } from "build-md";
1929
- var MAX_ROWS = 100;
1930
- function summarizeUnchanged(token, { changed, unchanged }) {
1931
- const pluralizedCount = changed.length > 0 ? pluralizeToken(`other ${token}`, unchanged.length) : `All of ${pluralizeToken(token, unchanged.length)}`;
1932
- const pluralizedVerb = unchanged.length === 1 ? "is" : "are";
1933
- return `${pluralizedCount} ${pluralizedVerb} unchanged.`;
1934
- }
1935
- function summarizeDiffOutcomes(outcomes, token) {
1936
- return objectToEntries(countDiffOutcomes(outcomes)).filter(
1937
- (entry) => entry[0] !== "unchanged" && entry[1] > 0
1938
- ).map(([outcome, count]) => {
1939
- const formattedCount = `<strong>${count}</strong> ${pluralize(
1940
- token,
1941
- count
1942
- )}`;
1943
- switch (outcome) {
1944
- case "positive":
1945
- return `\u{1F44D} ${formattedCount} improved`;
1946
- case "negative":
1947
- return `\u{1F44E} ${formattedCount} regressed`;
1948
- case "mixed":
1949
- return `${formattedCount} changed without impacting score`;
1950
- }
1951
- }).join(", ");
1952
- }
1953
- function createGroupsOrAuditsDetails(token, { changed, unchanged }, ...[columns, rows]) {
1954
- if (changed.length === 0) {
1955
- return new MarkdownDocument4().paragraph(
1956
- summarizeUnchanged(token, { changed, unchanged })
1957
- );
1958
- }
1959
- return new MarkdownDocument4().table(columns, rows.slice(0, MAX_ROWS)).paragraph(
1960
- changed.length > MAX_ROWS && md5.italic(
1961
- `Only the ${MAX_ROWS} most affected ${pluralize(
1962
- token
1963
- )} are listed above for brevity.`
1964
- )
1965
- ).paragraph(
1966
- unchanged.length > 0 && summarizeUnchanged(token, { changed, unchanged })
1967
- );
1968
- }
1969
- function formatTitle({
1970
- title,
1971
- docsUrl
1972
- }) {
1973
- if (docsUrl) {
1974
- return md5.link(docsUrl, title);
1975
- }
1976
- return title;
1977
- }
1978
- function formatPortalLink(portalUrl) {
1979
- return portalUrl && md5.link(portalUrl, "\u{1F575}\uFE0F See full comparison in Code PushUp portal \u{1F50D}");
1980
- }
1981
- function sortChanges(changes) {
1982
- return changes.toSorted(
1983
- (a, b) => Math.abs(b.scores.diff) - Math.abs(a.scores.diff) || Math.abs(b.values?.diff ?? 0) - Math.abs(a.values?.diff ?? 0)
1984
- );
1985
- }
1986
- function getDiffChanges(diff) {
1987
- return [
1988
- ...diff.categories.changed,
1989
- ...diff.groups.changed,
1990
- ...diff.audits.changed
1991
- ];
1992
- }
1993
- function changesToDiffOutcomes(changes) {
1994
- return changes.map((change) => {
1995
- if (change.scores.diff > 0) {
1996
- return "positive";
1997
- }
1998
- if (change.scores.diff < 0) {
1999
- return "negative";
2000
- }
2001
- if (change.values != null && change.values.diff !== 0) {
2002
- return "mixed";
2003
- }
2004
- return "unchanged";
2005
- });
2006
- }
2007
- function mergeDiffOutcomes(outcomes) {
2008
- if (outcomes.every((outcome) => outcome === "unchanged")) {
2009
- return "unchanged";
2010
- }
2011
- if (outcomes.includes("positive") && !outcomes.includes("negative")) {
2012
- return "positive";
2013
- }
2014
- if (outcomes.includes("negative") && !outcomes.includes("positive")) {
2015
- return "negative";
2016
- }
2017
- return "mixed";
2018
- }
2019
- function countDiffOutcomes(outcomes) {
2020
- return {
2021
- positive: outcomes.filter((outcome) => outcome === "positive").length,
2022
- negative: outcomes.filter((outcome) => outcome === "negative").length,
2023
- mixed: outcomes.filter((outcome) => outcome === "mixed").length,
2024
- unchanged: outcomes.filter((outcome) => outcome === "unchanged").length
2025
- };
2026
- }
2027
- function formatReportOutcome(outcome, commits) {
2028
- const outcomeTexts = {
2029
- positive: md5`🥳 Code PushUp report has ${md5.bold("improved")}`,
2030
- negative: md5`😟 Code PushUp report has ${md5.bold("regressed")}`,
2031
- mixed: md5`🤨 Code PushUp report has both ${md5.bold(
2032
- "improvements and regressions"
2033
- )}`,
2034
- unchanged: md5`😐 Code PushUp report is ${md5.bold("unchanged")}`
2035
- };
2036
- if (commits) {
2037
- const commitsText = `compared target commit ${commits.after.hash} with source commit ${commits.before.hash}`;
2038
- return md5`${outcomeTexts[outcome]} – ${commitsText}.`;
2039
- }
2040
- return md5`${outcomeTexts[outcome]}.`;
2041
- }
2042
- function compareDiffsBy(type, a, b) {
2043
- return sumScoreChanges(b[type].changed) - sumScoreChanges(a[type].changed) || sumConfigChanges(b[type]) - sumConfigChanges(a[type]);
2044
- }
2045
- function sumScoreChanges(changes) {
2046
- return changes.reduce(
2047
- (acc, { scores }) => acc + Math.abs(scores.diff),
2048
- 0
2049
- );
2050
- }
2051
- function sumConfigChanges({
2052
- added,
2053
- removed
2054
- }) {
2055
- return added.length + removed.length;
2056
- }
2057
-
2058
- // packages/utils/src/lib/reports/generate-md-reports-diff.ts
2059
- function generateMdReportsDiff(diff) {
2060
- return new MarkdownDocument5().$concat(
2061
- createDiffHeaderSection(diff),
2062
- createDiffCategoriesSection(diff),
2063
- createDiffDetailsSection(diff)
2064
- ).toString();
2065
- }
2066
- function generateMdReportsDiffForMonorepo(diffs) {
2067
- const diffsWithOutcomes = diffs.map((diff) => ({
2068
- ...diff,
2069
- outcome: mergeDiffOutcomes(changesToDiffOutcomes(getDiffChanges(diff)))
2070
- })).sort(
2071
- (a, b) => compareDiffsBy("categories", a, b) || compareDiffsBy("groups", a, b) || compareDiffsBy("audits", a, b) || a.label.localeCompare(b.label)
2072
- );
2073
- const unchanged = diffsWithOutcomes.filter(
2074
- ({ outcome }) => outcome === "unchanged"
2075
- );
2076
- const changed = diffsWithOutcomes.filter((diff) => !unchanged.includes(diff));
2077
- return new MarkdownDocument5().$concat(
2078
- createDiffHeaderSection(diffs),
2079
- ...changed.map(createDiffProjectSection)
2080
- ).$if(
2081
- unchanged.length > 0,
2082
- (doc) => doc.rule().paragraph(summarizeUnchanged("project", { unchanged, changed }))
2083
- ).toString();
2084
- }
2085
- function createDiffHeaderSection(diff) {
2086
- const outcome = mergeDiffOutcomes(
2087
- changesToDiffOutcomes(toArray(diff).flatMap(getDiffChanges))
2088
- );
2089
- const commits = Array.isArray(diff) ? diff[0]?.commits : diff.commits;
2090
- const portalUrl = Array.isArray(diff) ? void 0 : diff.portalUrl;
2091
- return new MarkdownDocument5().heading(HIERARCHY.level_1, "Code PushUp").paragraph(formatReportOutcome(outcome, commits)).paragraph(formatPortalLink(portalUrl));
2092
- }
2093
- function createDiffProjectSection(diff) {
2094
- return new MarkdownDocument5().heading(HIERARCHY.level_2, md6`💼 Project ${md6.code(diff.label)}`).paragraph(formatReportOutcome(diff.outcome)).paragraph(formatPortalLink(diff.portalUrl)).$concat(
2095
- createDiffCategoriesSection(diff, {
2096
- skipHeading: true,
2097
- skipUnchanged: true
2098
- }),
2099
- createDiffDetailsSection(diff, HIERARCHY.level_3)
2100
- );
2101
- }
2102
- function createDiffCategoriesSection(diff, options) {
2103
- const { changed, unchanged, added } = diff.categories;
2104
- const { skipHeading, skipUnchanged } = options ?? {};
2105
- const categoriesCount = changed.length + unchanged.length + added.length;
2106
- const hasChanges = unchanged.length < categoriesCount;
2107
- if (categoriesCount === 0) {
2108
- return null;
2109
- }
2110
- const [columns, rows] = createCategoriesTable(diff, {
2111
- hasChanges,
2112
- skipUnchanged
2113
- });
2114
- return new MarkdownDocument5().heading(HIERARCHY.level_2, !skipHeading && "\u{1F3F7}\uFE0F Categories").table(columns, rows).paragraph(added.length > 0 && md6.italic("(\\*) New category.")).paragraph(
2115
- skipUnchanged && unchanged.length > 0 && summarizeUnchanged("category", { changed, unchanged })
2116
- );
2117
- }
2118
- function createCategoriesTable(diff, options) {
2119
- const { changed, unchanged, added } = diff.categories;
2120
- const { hasChanges, skipUnchanged } = options;
2121
- const rows = [
2122
- ...sortChanges(changed).map((category) => [
2123
- formatTitle(category),
2124
- formatScoreWithColor(category.scores.before, {
2125
- skipBold: true
2126
- }),
2127
- formatScoreWithColor(category.scores.after),
2128
- formatScoreChange(category.scores.diff)
2129
- ]),
2130
- ...added.map((category) => [
2131
- formatTitle(category),
2132
- md6.italic("n/a (\\*)"),
2133
- formatScoreWithColor(category.score),
2134
- md6.italic("n/a (\\*)")
2135
- ]),
2136
- ...skipUnchanged ? [] : unchanged.map((category) => [
2137
- formatTitle(category),
2138
- formatScoreWithColor(category.score, { skipBold: true }),
2139
- formatScoreWithColor(category.score),
2140
- "\u2013"
2141
- ])
2142
- ];
2143
- if (rows.length === 0) {
2144
- return [[], []];
2145
- }
2146
- const columns = [
2147
- { heading: "\u{1F3F7}\uFE0F Category", alignment: "left" },
2148
- {
2149
- heading: hasChanges ? "\u2B50 Previous score" : "\u2B50 Score",
2150
- alignment: "center"
2151
- },
2152
- { heading: "\u2B50 Current score", alignment: "center" },
2153
- { heading: "\u{1F504} Score change", alignment: "center" }
2154
- ];
2155
- return [
2156
- hasChanges ? columns : columns.slice(0, 2),
2157
- rows.map((row) => hasChanges ? row : row.slice(0, 2))
2158
- ];
2159
- }
2160
- function createDiffDetailsSection(diff, level = HIERARCHY.level_2) {
2161
- if (diff.groups.changed.length + diff.audits.changed.length === 0) {
2162
- return null;
2163
- }
2164
- const summary = ["group", "audit"].map(
2165
- (token) => summarizeDiffOutcomes(
2166
- changesToDiffOutcomes(diff[`${token}s`].changed),
2167
- token
2168
- )
2169
- ).filter(Boolean).join(", ");
2170
- const details2 = new MarkdownDocument5().$concat(
2171
- createDiffGroupsSection(diff, level),
2172
- createDiffAuditsSection(diff, level)
2173
- );
2174
- return new MarkdownDocument5().details(summary, details2);
2175
- }
2176
- function createDiffGroupsSection(diff, level) {
2177
- if (diff.groups.changed.length + diff.groups.unchanged.length === 0) {
2178
- return null;
2179
- }
2180
- return new MarkdownDocument5().heading(level, "\u{1F5C3}\uFE0F Groups").$concat(
2181
- createGroupsOrAuditsDetails(
2182
- "group",
2183
- diff.groups,
2184
- [
2185
- { heading: "\u{1F50C} Plugin", alignment: "left" },
2186
- { heading: "\u{1F5C3}\uFE0F Group", alignment: "left" },
2187
- { heading: "\u2B50 Previous score", alignment: "center" },
2188
- { heading: "\u2B50 Current score", alignment: "center" },
2189
- { heading: "\u{1F504} Score change", alignment: "center" }
2190
- ],
2191
- sortChanges(diff.groups.changed).map((group) => [
2192
- formatTitle(group.plugin),
2193
- formatTitle(group),
2194
- formatScoreWithColor(group.scores.before, { skipBold: true }),
2195
- formatScoreWithColor(group.scores.after),
2196
- formatScoreChange(group.scores.diff)
2197
- ])
2198
- )
2199
- );
2200
- }
2201
- function createDiffAuditsSection(diff, level) {
2202
- return new MarkdownDocument5().heading(level, "\u{1F6E1}\uFE0F Audits").$concat(
2203
- createGroupsOrAuditsDetails(
2204
- "audit",
2205
- diff.audits,
2206
- [
2207
- { heading: "\u{1F50C} Plugin", alignment: "left" },
2208
- { heading: "\u{1F6E1}\uFE0F Audit", alignment: "left" },
2209
- { heading: "\u{1F4CF} Previous value", alignment: "center" },
2210
- { heading: "\u{1F4CF} Current value", alignment: "center" },
2211
- { heading: "\u{1F504} Value change", alignment: "center" }
2212
- ],
2213
- sortChanges(diff.audits.changed).map((audit) => [
2214
- formatTitle(audit.plugin),
2215
- formatTitle(audit),
2216
- `${scoreMarker(audit.scores.before, "square")} ${audit.displayValues.before || audit.values.before.toString()}`,
2217
- md6`${scoreMarker(audit.scores.after, "square")} ${md6.bold(
2218
- audit.displayValues.after || audit.values.after.toString()
2219
- )}`,
2220
- formatValueChange(audit)
2221
- ])
2222
- )
2223
- );
2224
- }
2225
-
2226
- // packages/utils/src/lib/reports/load-report.ts
2227
- import { join as join2 } from "node:path";
2228
- async function loadReport(options) {
2229
- const { outputDir, filename, format } = options;
2230
- await ensureDirectoryExists(outputDir);
2231
- const filePath = join2(outputDir, `${filename}.${format}`);
2232
- if (format === "json") {
2233
- const content = await readJsonFile(filePath);
2234
- return reportSchema.parse(content);
2235
- }
2236
- const text = await readTextFile(filePath);
2237
- return text;
2238
- }
2239
-
2240
- // packages/utils/src/lib/reports/log-stdout-summary.ts
2241
- import { bold as bold4, cyan, cyanBright, green as green2, red } from "ansis";
2242
- function log(msg = "") {
2243
- ui().logger.log(msg);
2244
- }
2245
- function logStdoutSummary(report, verbose = false) {
2246
- const { plugins, categories, packageName, version: version2 } = report;
2247
- log(reportToHeaderSection({ packageName, version: version2 }));
2248
- log();
2249
- logPlugins(plugins, verbose);
2250
- if (categories && categories.length > 0) {
2251
- logCategories({ plugins, categories });
2252
- }
2253
- log(`${FOOTER_PREFIX} ${CODE_PUSHUP_DOMAIN}`);
2254
- log();
2255
- }
2256
- function reportToHeaderSection({
2257
- packageName,
2258
- version: version2
2259
- }) {
2260
- return `${bold4(REPORT_HEADLINE_TEXT)} - ${packageName}@${version2}`;
2261
- }
2262
- function logPlugins(plugins, verbose) {
2263
- plugins.forEach((plugin) => {
2264
- const { title, audits } = plugin;
2265
- const filteredAudits = verbose || audits.length === 1 ? audits : audits.filter(({ score }) => score !== 1);
2266
- const diff = audits.length - filteredAudits.length;
2267
- logAudits(title, filteredAudits);
2268
- if (diff > 0) {
2269
- const notice = filteredAudits.length === 0 ? `... All ${diff} audits have perfect scores ...` : `... ${diff} audits with perfect scores omitted for brevity ...`;
2270
- logRow(1, notice);
2271
- }
2272
- log();
2273
- });
2274
- }
2275
- function logAudits(pluginTitle, audits) {
2276
- log();
2277
- log(bold4.magentaBright(`${pluginTitle} audits`));
2278
- log();
2279
- audits.forEach(({ score, title, displayValue, value }) => {
2280
- logRow(score, title, displayValue || `${value}`);
2281
- });
2282
- }
2283
- function logRow(score, title, value) {
2284
- ui().row([
2285
- {
2286
- text: applyScoreColor({ score, text: "\u25CF" }),
2287
- width: 2,
2288
- padding: [0, 1, 0, 0]
2289
- },
2290
- {
2291
- text: title,
2292
- // eslint-disable-next-line no-magic-numbers
2293
- padding: [0, 3, 0, 0]
2294
- },
2295
- ...value ? [
2296
- {
2297
- text: cyanBright(value),
2298
- // eslint-disable-next-line no-magic-numbers
2299
- width: 20,
2300
- padding: [0, 0, 0, 0]
2301
- }
2302
- ] : []
2303
- ]);
2304
- }
2305
- function logCategories({
2306
- plugins,
2307
- categories
2308
- }) {
2309
- const hAlign = (idx) => idx === 0 ? "left" : "right";
2310
- const rows = categories.map(({ title, score, refs, isBinary }) => [
2311
- title,
2312
- `${binaryIconPrefix(score, isBinary)}${applyScoreColor({ score })}`,
2313
- countCategoryAudits(refs, plugins)
2314
- ]);
2315
- const table2 = ui().table();
2316
- table2.columnWidths([TERMINAL_WIDTH - 9 - 10 - 4, 9, 10]);
2317
- table2.head(
2318
- REPORT_RAW_OVERVIEW_TABLE_HEADERS.map((heading, idx) => ({
2319
- content: cyan(heading),
2320
- hAlign: hAlign(idx)
2321
- }))
2322
- );
2323
- rows.forEach(
2324
- (row) => table2.row(
2325
- row.map((content, idx) => ({
2326
- content: content.toString(),
2327
- hAlign: hAlign(idx)
2328
- }))
2329
- )
2330
- );
2331
- log(bold4.magentaBright("Categories"));
2332
- log();
2333
- table2.render();
2334
- log();
2335
- }
2336
- function binaryIconPrefix(score, isBinary) {
2337
- return targetScoreIcon(score, isBinary ? 1 : void 0, {
2338
- passIcon: bold4(green2("\u2713")),
2339
- failIcon: bold4(red("\u2717")),
2340
- postfix: " "
2341
- });
2342
- }
2343
-
2344
- // packages/utils/src/lib/reports/scoring.ts
2345
- var GroupRefInvalidError = class extends Error {
2346
- constructor(auditSlug, pluginSlug) {
2347
- super(
2348
- `Group has invalid ref - audit with slug ${auditSlug} from plugin ${pluginSlug} not found`
2349
- );
2350
- }
2351
- };
2352
- function scoreReport(report) {
2353
- const allScoredAuditsAndGroups = /* @__PURE__ */ new Map();
2354
- const scoredPlugins = report.plugins.map((plugin) => {
2355
- const { groups, ...pluginProps } = plugin;
2356
- plugin.audits.forEach((audit) => {
2357
- allScoredAuditsAndGroups.set(`${plugin.slug}-${audit.slug}-audit`, audit);
2358
- });
2359
- function groupScoreFn(ref) {
2360
- const score = allScoredAuditsAndGroups.get(
2361
- `${plugin.slug}-${ref.slug}-audit`
2362
- )?.score;
2363
- if (score == null) {
2364
- throw new GroupRefInvalidError(ref.slug, plugin.slug);
2365
- }
2366
- return score;
2367
- }
2368
- const scoredGroups = groups?.map((group) => ({
2369
- ...group,
2370
- score: calculateScore(group.refs, groupScoreFn)
2371
- })) ?? [];
2372
- scoredGroups.forEach((group) => {
2373
- allScoredAuditsAndGroups.set(`${plugin.slug}-${group.slug}-group`, group);
2374
- });
2375
- return {
2376
- ...pluginProps,
2377
- ...scoredGroups.length > 0 && { groups: scoredGroups }
2378
- };
2379
- });
2380
- function catScoreFn(ref) {
2381
- const key = `${ref.plugin}-${ref.slug}-${ref.type}`;
2382
- const item = allScoredAuditsAndGroups.get(key);
2383
- if (!item) {
2384
- throw new Error(
2385
- `Category has invalid ref - ${ref.type} with slug ${key} not found in ${ref.plugin} plugin`
2386
- );
2387
- }
2388
- return item.score;
2389
- }
2390
- const scoredCategories = report.categories?.map((category) => ({
2391
- ...category,
2392
- score: calculateScore(category.refs, catScoreFn)
2393
- }));
2394
- return {
2395
- ...deepClone(report),
2396
- plugins: scoredPlugins,
2397
- categories: scoredCategories
2398
- };
2399
- }
2400
- function calculateScore(refs, scoreFn) {
2401
- const validatedRefs = parseScoringParameters(refs, scoreFn);
2402
- const { numerator, denominator } = validatedRefs.reduce(
2403
- (acc, ref) => ({
2404
- numerator: acc.numerator + ref.score * ref.weight,
2405
- denominator: acc.denominator + ref.weight
2406
- }),
2407
- { numerator: 0, denominator: 0 }
2408
- );
2409
- return numerator / denominator;
2410
- }
2411
- function parseScoringParameters(refs, scoreFn) {
2412
- if (refs.length === 0) {
2413
- throw new Error("Reference array cannot be empty.");
2414
- }
2415
- if (refs.some((ref) => ref.weight < 0)) {
2416
- throw new Error("Weight cannot be negative.");
2417
- }
2418
- if (refs.every((ref) => ref.weight === 0)) {
2419
- throw new Error("All references cannot have zero weight.");
2420
- }
2421
- const scoredRefs = refs.map((ref) => ({
2422
- weight: ref.weight,
2423
- score: scoreFn(ref)
2424
- }));
2425
- if (scoredRefs.some((ref) => ref.score < 0 || ref.score > 1)) {
2426
- throw new Error("All scores must be in range 0-1.");
2427
- }
2428
- return scoredRefs;
2429
- }
2430
-
2431
- // packages/utils/src/lib/verbose-utils.ts
2432
- function getLogVerbose(verbose = false) {
2433
- return (msg) => {
2434
- if (verbose) {
2435
- ui().logger.info(msg);
2436
- }
2437
- };
2438
- }
2439
- function getExecVerbose(verbose = false) {
2440
- return (fn) => {
2441
- if (verbose) {
2442
- fn();
2443
- }
2444
- };
2445
- }
2446
- var verboseUtils = (verbose = false) => ({
2447
- log: getLogVerbose(verbose),
2448
- exec: getExecVerbose(verbose)
2449
- });
2450
-
2451
- // packages/core/package.json
2452
- var name = "@code-pushup/core";
2453
- var version = "0.56.0";
2454
-
2455
- // packages/core/src/lib/implementation/execute-plugin.ts
2456
- import { bold as bold5 } from "ansis";
2457
-
2458
- // packages/core/src/lib/normalize.ts
2459
- function normalizeIssue(issue, gitRoot) {
2460
- const { source, ...issueWithoutSource } = issue;
2461
- return source == null ? issue : {
2462
- ...issueWithoutSource,
2463
- source: {
2464
- ...source,
2465
- file: formatGitPath(source.file, gitRoot)
2466
- }
2467
- };
2468
- }
2469
- async function normalizeAuditOutputs(audits) {
2470
- const gitRoot = await getGitRoot();
2471
- return audits.map((audit) => {
2472
- if (audit.details?.issues == null || audit.details.issues.every((issue) => issue.source == null)) {
2473
- return audit;
2474
- }
2475
- return {
2476
- ...audit,
2477
- details: {
2478
- ...audit.details,
2479
- issues: audit.details.issues.map(
2480
- (issue) => normalizeIssue(issue, gitRoot)
2481
- )
2482
- }
2483
- };
2484
- });
2485
- }
2486
-
2487
- // packages/core/src/lib/implementation/runner.ts
2488
- import { join as join3 } from "node:path";
2489
- async function executeRunnerConfig(cfg, onProgress) {
2490
- const { args, command, outputFile, outputTransform } = cfg;
2491
- const { duration, date } = await executeProcess({
2492
- command,
2493
- args,
2494
- observer: { onStdout: onProgress }
2495
- });
2496
- const outputs = await readJsonFile(join3(process.cwd(), outputFile));
2497
- const audits = outputTransform ? await outputTransform(outputs) : outputs;
2498
- return {
2499
- duration,
2500
- date,
2501
- audits
2502
- };
2503
- }
2504
- async function executeRunnerFunction(runner, onProgress) {
2505
- const date = (/* @__PURE__ */ new Date()).toISOString();
2506
- const start = performance.now();
2507
- const audits = await runner(onProgress);
2508
- return {
2509
- date,
2510
- duration: calcDuration(start),
2511
- audits
2512
- };
2513
- }
2514
-
2515
- // packages/core/src/lib/implementation/execute-plugin.ts
2516
- var PluginOutputMissingAuditError = class extends Error {
2517
- constructor(auditSlug) {
2518
- super(
2519
- `Audit metadata not present in plugin config. Missing slug: ${bold5(
2520
- auditSlug
2521
- )}`
2522
- );
2523
- }
2524
- };
2525
- async function executePlugin(pluginConfig, onProgress) {
2526
- const {
2527
- runner,
2528
- audits: pluginConfigAudits,
2529
- description,
2530
- docsUrl,
2531
- groups,
2532
- ...pluginMeta
2533
- } = pluginConfig;
2534
- const runnerResult = typeof runner === "object" ? await executeRunnerConfig(runner, onProgress) : await executeRunnerFunction(runner, onProgress);
2535
- const { audits: unvalidatedAuditOutputs, ...executionMeta } = runnerResult;
2536
- const result = auditOutputsSchema.safeParse(unvalidatedAuditOutputs);
2537
- if (!result.success) {
2538
- throw new Error(`Audit output is invalid: ${result.error.message}`);
2539
- }
2540
- const auditOutputs = result.data;
2541
- auditOutputsCorrelateWithPluginOutput(auditOutputs, pluginConfigAudits);
2542
- const normalizedAuditOutputs = await normalizeAuditOutputs(auditOutputs);
2543
- const auditReports = normalizedAuditOutputs.map(
2544
- (auditOutput) => ({
2545
- ...auditOutput,
2546
- ...pluginConfigAudits.find(
2547
- (audit) => audit.slug === auditOutput.slug
2548
- )
2549
- })
2550
- );
2551
- return {
2552
- ...pluginMeta,
2553
- ...executionMeta,
2554
- audits: auditReports,
2555
- ...description && { description },
2556
- ...docsUrl && { docsUrl },
2557
- ...groups && { groups }
2558
- };
2559
- }
2560
- var wrapProgress = async (pluginCfg, steps, progressBar) => {
2561
- progressBar?.updateTitle(`Executing ${bold5(pluginCfg.title)}`);
2562
- try {
2563
- const pluginReport = await executePlugin(pluginCfg);
2564
- progressBar?.incrementInSteps(steps);
2565
- return pluginReport;
2566
- } catch (error) {
2567
- progressBar?.incrementInSteps(steps);
2568
- throw new Error(
2569
- error instanceof Error ? `- Plugin ${bold5(pluginCfg.title)} (${bold5(
2570
- pluginCfg.slug
2571
- )}) produced the following error:
2572
- - ${error.message}` : String(error)
2573
- );
2574
- }
2575
- };
2576
- async function executePlugins(plugins, options) {
2577
- const { progress = false } = options ?? {};
2578
- const progressBar = progress ? getProgressBar("Run plugins") : null;
2579
- const pluginsResult = await plugins.reduce(
2580
- async (acc, pluginCfg) => [
2581
- ...await acc,
2582
- wrapProgress(pluginCfg, plugins.length, progressBar)
2583
- ],
2584
- Promise.resolve([])
2585
- );
2586
- progressBar?.endProgress("Done running plugins");
2587
- const errorsTransform = ({ reason }) => String(reason);
2588
- const results = await Promise.allSettled(pluginsResult);
2589
- logMultipleResults(results, "Plugins", void 0, errorsTransform);
2590
- const { fulfilled, rejected } = groupByStatus(results);
2591
- if (rejected.length > 0) {
2592
- const errorMessages = rejected.map(({ reason }) => String(reason)).join("\n");
2593
- throw new Error(
2594
- `Executing ${pluralizeToken(
2595
- "plugin",
2596
- rejected.length
2597
- )} failed.
2598
-
2599
- ${errorMessages}
2600
-
2601
- `
2602
- );
2603
- }
2604
- return fulfilled.map((result) => result.value);
2605
- }
2606
- function auditOutputsCorrelateWithPluginOutput(auditOutputs, pluginConfigAudits) {
2607
- auditOutputs.forEach((auditOutput) => {
2608
- const auditMetadata = pluginConfigAudits.find(
2609
- (audit) => audit.slug === auditOutput.slug
2610
- );
2611
- if (!auditMetadata) {
2612
- throw new PluginOutputMissingAuditError(auditOutput.slug);
2613
- }
2614
- });
2615
- }
2616
-
2617
- // packages/core/src/lib/implementation/collect.ts
2618
- async function collect(options) {
2619
- const { plugins, categories } = options;
2620
- const date = (/* @__PURE__ */ new Date()).toISOString();
2621
- const start = performance.now();
2622
- const commit = await getLatestCommit();
2623
- const pluginOutputs = await executePlugins(plugins, options);
2624
- return {
2625
- commit,
2626
- packageName: name,
2627
- version,
2628
- date,
2629
- duration: calcDuration(start),
2630
- categories,
2631
- plugins: pluginOutputs
2632
- };
2633
- }
2634
-
2635
- // packages/core/src/lib/implementation/persist.ts
2636
- import { mkdir as mkdir2, stat as stat2, writeFile } from "node:fs/promises";
2637
- import { join as join4 } from "node:path";
2638
- var PersistDirError = class extends Error {
2639
- constructor(outputDir) {
2640
- super(`outPath: ${outputDir} is no directory.`);
2641
- }
2642
- };
2643
- var PersistError = class extends Error {
2644
- constructor(reportPath) {
2645
- super(`fileName: ${reportPath} could not be saved.`);
2646
- }
2647
- };
2648
- async function persistReport(report, sortedScoredReport, options) {
2649
- const { outputDir, filename, format } = options;
2650
- const results = format.map((reportType) => {
2651
- switch (reportType) {
2652
- case "json":
2653
- return {
2654
- format: "json",
2655
- content: JSON.stringify(report, null, 2)
2656
- };
2657
- case "md":
2658
- return {
2659
- format: "md",
2660
- content: generateMdReport(sortedScoredReport, { outputDir })
2661
- };
2662
- }
2663
- });
2664
- if (!await directoryExists(outputDir)) {
2665
- try {
2666
- await mkdir2(outputDir, { recursive: true });
2667
- } catch (error) {
2668
- ui().logger.warning(error.toString());
2669
- throw new PersistDirError(outputDir);
2670
- }
2671
- }
2672
- return Promise.allSettled(
2673
- results.map(
2674
- (result) => persistResult(
2675
- join4(outputDir, `${filename}.${result.format}`),
2676
- result.content
2677
- )
2678
- )
2679
- );
2680
- }
2681
- async function persistResult(reportPath, content) {
2682
- return writeFile(reportPath, content).then(() => stat2(reportPath)).then((stats) => [reportPath, stats.size]).catch((error) => {
2683
- ui().logger.warning(error.toString());
2684
- throw new PersistError(reportPath);
2685
- });
2686
- }
2687
- function logPersistedResults(persistResults) {
2688
- logMultipleFileResults(persistResults, "Generated reports");
2689
- }
2690
-
2691
- // packages/core/src/lib/collect-and-persist.ts
2692
- async function collectAndPersistReports(options) {
2693
- const { exec } = verboseUtils(options.verbose);
2694
- const report = await collect(options);
2695
- const sortedScoredReport = sortReport(scoreReport(report));
2696
- const persistResults = await persistReport(
2697
- report,
2698
- sortedScoredReport,
2699
- options.persist
2700
- );
2701
- logStdoutSummary(sortedScoredReport, options.verbose);
2702
- exec(() => {
2703
- logPersistedResults(persistResults);
2704
- });
2705
- report.plugins.forEach((plugin) => {
2706
- pluginReportSchema.parse(plugin);
2707
- });
2708
- }
2709
-
2710
- // packages/core/src/lib/compare.ts
2711
- import { writeFile as writeFile2 } from "node:fs/promises";
2712
- import { join as join5 } from "node:path";
2713
-
2714
- // packages/core/src/lib/implementation/compare-scorables.ts
2715
- function compareCategories(reports) {
2716
- const { pairs, added, removed } = matchArrayItemsByKey({
2717
- before: reports.before.categories ?? [],
2718
- after: reports.after.categories ?? [],
2719
- key: "slug"
2720
- });
2721
- const { changed, unchanged } = comparePairs(
2722
- pairs,
2723
- ({ before, after }) => before.score === after.score
2724
- );
2725
- return {
2726
- changed: changed.map(categoryPairToDiff),
2727
- unchanged: unchanged.map(categoryToResult),
2728
- added: added.map(categoryToResult),
2729
- removed: removed.map(categoryToResult)
2730
- };
2731
- }
2732
- function compareGroups(reports) {
2733
- const { pairs, added, removed } = matchArrayItemsByKey({
2734
- before: listGroupsFromAllPlugins(reports.before),
2735
- after: listGroupsFromAllPlugins(reports.after),
2736
- key: ({ plugin, group }) => `${plugin.slug}/${group.slug}`
2737
- });
2738
- const { changed, unchanged } = comparePairs(
2739
- pairs,
2740
- ({ before, after }) => before.group.score === after.group.score
2741
- );
2742
- return {
2743
- changed: changed.map(pluginGroupPairToDiff),
2744
- unchanged: unchanged.map(pluginGroupToResult),
2745
- added: added.map(pluginGroupToResult),
2746
- removed: removed.map(pluginGroupToResult)
2747
- };
2748
- }
2749
- function compareAudits2(reports) {
2750
- const { pairs, added, removed } = matchArrayItemsByKey({
2751
- before: listAuditsFromAllPlugins(reports.before),
2752
- after: listAuditsFromAllPlugins(reports.after),
2753
- key: ({ plugin, audit }) => `${plugin.slug}/${audit.slug}`
2754
- });
2755
- const { changed, unchanged } = comparePairs(
2756
- pairs,
2757
- ({ before, after }) => before.audit.value === after.audit.value && before.audit.score === after.audit.score
2758
- );
2759
- return {
2760
- changed: changed.map(pluginAuditPairToDiff),
2761
- unchanged: unchanged.map(pluginAuditToResult),
2762
- added: added.map(pluginAuditToResult),
2763
- removed: removed.map(pluginAuditToResult)
2764
- };
2765
- }
2766
- function categoryToResult(category) {
2767
- return {
2768
- ...selectMeta(category),
2769
- score: category.score
2770
- };
2771
- }
2772
- function categoryPairToDiff({
2773
- before,
2774
- after
2775
- }) {
2776
- return {
2777
- ...selectMeta(after),
2778
- scores: {
2779
- before: before.score,
2780
- after: after.score,
2781
- diff: after.score - before.score
2782
- }
2783
- };
2784
- }
2785
- function pluginGroupToResult({ group, plugin }) {
2786
- return {
2787
- ...selectMeta(group),
2788
- plugin: selectMeta(plugin),
2789
- score: group.score
2790
- };
2791
- }
2792
- function pluginGroupPairToDiff({
2793
- before,
2794
- after
2795
- }) {
2796
- return {
2797
- ...selectMeta(after.group),
2798
- plugin: selectMeta(after.plugin),
2799
- scores: {
2800
- before: before.group.score,
2801
- after: after.group.score,
2802
- diff: after.group.score - before.group.score
2803
- }
2804
- };
2805
- }
2806
- function pluginAuditToResult({ audit, plugin }) {
2807
- return {
2808
- ...selectMeta(audit),
2809
- plugin: selectMeta(plugin),
2810
- score: audit.score,
2811
- value: audit.value,
2812
- displayValue: audit.displayValue
2813
- };
2814
- }
2815
- function pluginAuditPairToDiff({
2816
- before,
2817
- after
2818
- }) {
2819
- return {
2820
- ...selectMeta(after.audit),
2821
- plugin: selectMeta(after.plugin),
2822
- scores: {
2823
- before: before.audit.score,
2824
- after: after.audit.score,
2825
- diff: after.audit.score - before.audit.score
2826
- },
2827
- values: {
2828
- before: before.audit.value,
2829
- after: after.audit.value,
2830
- diff: after.audit.value - before.audit.value
2831
- },
2832
- displayValues: {
2833
- before: before.audit.displayValue,
2834
- after: after.audit.displayValue
2835
- }
2836
- };
2837
- }
2838
- function selectMeta(meta) {
2839
- return {
2840
- slug: meta.slug,
2841
- title: meta.title,
2842
- ...meta.docsUrl && {
2843
- docsUrl: meta.docsUrl
2844
- }
2845
- };
2846
- }
2847
-
2848
- // packages/core/src/lib/load-portal-client.ts
2849
- async function loadPortalClient() {
2850
- try {
2851
- return await import("@code-pushup/portal-client");
2852
- } catch {
2853
- ui().logger.error(
2854
- "Optional peer dependency @code-pushup/portal-client is not available. Make sure it is installed to enable upload functionality."
2855
- );
2856
- return null;
2857
- }
2858
- }
2859
-
2860
- // packages/core/src/lib/compare.ts
2861
- async function compareReportFiles(inputPaths, persistConfig, uploadConfig, label) {
2862
- const { outputDir, filename, format } = persistConfig;
2863
- const [reportBefore, reportAfter] = await Promise.all([
2864
- readJsonFile(inputPaths.before),
2865
- readJsonFile(inputPaths.after)
2866
- ]);
2867
- const reports = {
2868
- before: reportSchema.parse(reportBefore),
2869
- after: reportSchema.parse(reportAfter)
2870
- };
2871
- const diff = compareReports(reports);
2872
- if (label) {
2873
- diff.label = label;
2874
- }
2875
- if (uploadConfig && diff.commits) {
2876
- diff.portalUrl = await fetchPortalComparisonLink(
2877
- uploadConfig,
2878
- diff.commits
2879
- );
2880
- }
2881
- return Promise.all(
2882
- format.map(async (fmt) => {
2883
- const outputPath = join5(outputDir, `${filename}-diff.${fmt}`);
2884
- const content = reportsDiffToFileContent(diff, fmt);
2885
- await ensureDirectoryExists(outputDir);
2886
- await writeFile2(outputPath, content);
2887
- return outputPath;
2888
- })
2889
- );
2890
- }
2891
- function compareReports(reports) {
2892
- const start = performance.now();
2893
- const date = (/* @__PURE__ */ new Date()).toISOString();
2894
- const commits = reports.before.commit != null && reports.after.commit != null ? { before: reports.before.commit, after: reports.after.commit } : null;
2895
- const scoredReports = {
2896
- before: scoreReport(reports.before),
2897
- after: scoreReport(reports.after)
2898
- };
2899
- const categories = compareCategories(scoredReports);
2900
- const groups = compareGroups(scoredReports);
2901
- const audits = compareAudits2(scoredReports);
2902
- const duration = calcDuration(start);
2903
- return {
2904
- commits,
2905
- categories,
2906
- groups,
2907
- audits,
2908
- packageName: name,
2909
- version,
2910
- date,
2911
- duration
2912
- };
2913
- }
2914
- function reportsDiffToFileContent(reportsDiff, format) {
2915
- switch (format) {
2916
- case "json":
2917
- return JSON.stringify(reportsDiff, null, 2);
2918
- case "md":
2919
- return generateMdReportsDiff(reportsDiff);
2920
- }
2921
- }
2922
- async function fetchPortalComparisonLink(uploadConfig, commits) {
2923
- const { server, apiKey, organization, project } = uploadConfig;
2924
- const portalClient = await loadPortalClient();
2925
- if (!portalClient) {
2926
- return;
2927
- }
2928
- const { PortalOperationError, getPortalComparisonLink } = portalClient;
2929
- try {
2930
- return await getPortalComparisonLink({
2931
- server,
2932
- apiKey,
2933
- parameters: {
2934
- organization,
2935
- project,
2936
- before: commits.before.hash,
2937
- after: commits.after.hash
2938
- }
2939
- });
2940
- } catch (error) {
2941
- if (error instanceof PortalOperationError) {
2942
- ui().logger.warning(
2943
- `Failed to fetch portal comparison link - ${error.message}`
2944
- );
2945
- return void 0;
2946
- }
2947
- throw error;
2948
- }
2949
- }
2950
-
2951
- // packages/core/src/lib/implementation/report-to-gql.ts
2952
- function reportToGQL(report) {
2953
- return {
2954
- packageName: report.packageName,
2955
- packageVersion: report.version,
2956
- commandStartDate: report.date,
2957
- commandDuration: report.duration,
2958
- plugins: report.plugins.map(pluginToGQL),
2959
- categories: (report.categories ?? []).map(categoryToGQL)
2960
- };
2961
- }
2962
- function pluginToGQL(plugin) {
2963
- return {
2964
- slug: plugin.slug,
2965
- title: plugin.title,
2966
- icon: plugin.icon,
2967
- description: plugin.description,
2968
- docsUrl: plugin.docsUrl,
2969
- audits: plugin.audits.map(auditToGQL),
2970
- groups: plugin.groups?.map(groupToGQL),
2971
- packageName: plugin.packageName,
2972
- packageVersion: plugin.version,
2973
- runnerDuration: plugin.duration,
2974
- runnerStartDate: plugin.date
2975
- };
2976
- }
2977
- function groupToGQL(group) {
2978
- return {
2979
- slug: group.slug,
2980
- title: group.title,
2981
- description: group.description,
2982
- refs: group.refs.map((ref) => ({ slug: ref.slug, weight: ref.weight }))
2983
- };
2984
- }
2985
- function auditToGQL(audit) {
2986
- const {
2987
- slug,
2988
- title,
2989
- description,
2990
- docsUrl,
2991
- score,
2992
- value,
2993
- displayValue: formattedValue,
2994
- details: details2
2995
- } = audit;
2996
- const { issues, table: table2 } = details2 ?? {};
2997
- return {
2998
- slug,
2999
- title,
3000
- description,
3001
- docsUrl,
3002
- score,
3003
- value,
3004
- formattedValue,
3005
- ...details2 && {
3006
- details: {
3007
- ...issues && { issues: issues.map(issueToGQL) },
3008
- ...table2 && { tables: [tableToGQL(table2)] }
3009
- }
3010
- }
3011
- };
3012
- }
3013
- function issueToGQL(issue) {
3014
- return {
3015
- message: issue.message,
3016
- severity: issueSeverityToGQL(issue.severity),
3017
- ...issue.source?.file && {
3018
- sourceType: safeEnum("SourceCode"),
3019
- sourceFilePath: issue.source.file,
3020
- sourceStartLine: issue.source.position?.startLine,
3021
- sourceStartColumn: issue.source.position?.startColumn,
3022
- sourceEndLine: issue.source.position?.endLine,
3023
- sourceEndColumn: issue.source.position?.endColumn
3024
- }
3025
- };
3026
- }
3027
- function tableToGQL(table2) {
3028
- return {
3029
- ...table2.title && { title: table2.title },
3030
- ...table2.columns?.length && {
3031
- columns: table2.columns.map(
3032
- (column) => typeof column === "string" ? { alignment: tableAlignmentToGQL(column) } : {
3033
- key: column.key,
3034
- label: column.label,
3035
- alignment: column.align && tableAlignmentToGQL(column.align)
3036
- }
3037
- )
3038
- },
3039
- rows: table2.rows.map(
3040
- (row) => Array.isArray(row) ? row.map((content) => ({ content: content?.toString() ?? "" })) : Object.entries(row).map(([key, content]) => ({
3041
- key,
3042
- content: content?.toString() ?? ""
3043
- }))
3044
- )
3045
- };
3046
- }
3047
- function categoryToGQL(category) {
3048
- return {
3049
- slug: category.slug,
3050
- title: category.title,
3051
- description: category.description,
3052
- isBinary: category.isBinary,
3053
- refs: category.refs.map((ref) => ({
3054
- plugin: ref.plugin,
3055
- type: categoryRefTypeToGQL(ref.type),
3056
- weight: ref.weight,
3057
- slug: ref.slug
3058
- }))
3059
- };
3060
- }
3061
- function categoryRefTypeToGQL(type) {
3062
- switch (type) {
3063
- case "audit":
3064
- return safeEnum("Audit");
3065
- case "group":
3066
- return safeEnum("Group");
3067
- }
3068
- }
3069
- function issueSeverityToGQL(severity) {
3070
- switch (severity) {
3071
- case "info":
3072
- return safeEnum("Info");
3073
- case "error":
3074
- return safeEnum("Error");
3075
- case "warning":
3076
- return safeEnum("Warning");
3077
- }
3078
- }
3079
- function tableAlignmentToGQL(alignment) {
3080
- switch (alignment) {
3081
- case "left":
3082
- return safeEnum("Left");
3083
- case "center":
3084
- return safeEnum("Center");
3085
- case "right":
3086
- return safeEnum("Right");
3087
- }
3088
- }
3089
- function safeEnum(value) {
3090
- return value;
3091
- }
3092
-
3093
- // packages/core/src/lib/upload.ts
3094
- async function upload(options) {
3095
- if (options.upload == null) {
3096
- throw new Error("Upload configuration is not set.");
3097
- }
3098
- const portalClient = await loadPortalClient();
3099
- if (!portalClient) {
3100
- return;
3101
- }
3102
- const { uploadToPortal } = portalClient;
3103
- const { apiKey, server, organization, project, timeout } = options.upload;
3104
- const report = await loadReport({
3105
- ...options.persist,
3106
- format: "json"
3107
- });
3108
- if (!report.commit) {
3109
- throw new Error("Commit must be linked in order to upload report");
3110
- }
3111
- const data = {
3112
- organization,
3113
- project,
3114
- commit: report.commit.hash,
3115
- ...reportToGQL(report)
3116
- };
3117
- return uploadToPortal({ apiKey, server, data, timeout });
3118
- }
3119
-
3120
- // packages/core/src/lib/history.ts
3121
- async function history(config, commits) {
3122
- const initialBranch = await getCurrentBranchOrTag();
3123
- const { skipUploads = false, forceCleanStatus, persist } = config;
3124
- const reports = [];
3125
- for (const commit of commits) {
3126
- ui().logger.info(`Collect ${commit}`);
3127
- await safeCheckout(commit, forceCleanStatus);
3128
- const currentConfig = {
3129
- ...config,
3130
- persist: {
3131
- ...persist,
3132
- format: ["json"],
3133
- filename: `${commit}-report`
3134
- }
3135
- };
3136
- await collectAndPersistReports(currentConfig);
3137
- if (skipUploads) {
3138
- ui().logger.info("Upload is skipped because skipUploads is set to true.");
3139
- } else {
3140
- if (currentConfig.upload) {
3141
- await upload(currentConfig);
3142
- } else {
3143
- ui().logger.info(
3144
- "Upload is skipped because upload config is undefined."
3145
- );
3146
- }
3147
- }
3148
- reports.push(currentConfig.persist.filename);
3149
- }
3150
- await safeCheckout(initialBranch, forceCleanStatus);
3151
- return reports;
3152
- }
3153
-
3154
- // packages/core/src/lib/implementation/read-rc-file.ts
3155
- import { join as join6 } from "node:path";
3156
- var ConfigPathError = class extends Error {
3157
- constructor(configPath) {
3158
- super(`Provided path '${configPath}' is not valid.`);
3159
- }
3160
- };
3161
- async function readRcByPath(filepath, tsconfig) {
3162
- if (filepath.length === 0) {
3163
- throw new Error("The path to the configuration file is empty.");
3164
- }
3165
- if (!await fileExists(filepath)) {
3166
- throw new ConfigPathError(filepath);
3167
- }
3168
- const cfg = await importModule({ filepath, tsconfig, format: "esm" });
3169
- return coreConfigSchema.parse(cfg);
3170
- }
3171
- async function autoloadRc(tsconfig) {
3172
- let ext = "";
3173
- for (const extension of SUPPORTED_CONFIG_FILE_FORMATS) {
3174
- const path = `${CONFIG_FILE_NAME}.${extension}`;
3175
- const exists2 = await fileExists(path);
3176
- if (exists2) {
3177
- ext = extension;
3178
- break;
3179
- }
3180
- }
3181
- if (!ext) {
3182
- throw new Error(
3183
- `No file ${CONFIG_FILE_NAME}.(${SUPPORTED_CONFIG_FILE_FORMATS.join(
3184
- "|"
3185
- )}) present in ${process.cwd()}`
3186
- );
3187
- }
3188
- return readRcByPath(
3189
- join6(process.cwd(), `${CONFIG_FILE_NAME}.${ext}`),
3190
- tsconfig
3191
- );
3192
- }
3193
-
3194
- // packages/core/src/lib/merge-diffs.ts
3195
- import { writeFile as writeFile3 } from "node:fs/promises";
3196
- import { basename, dirname, join as join7 } from "node:path";
3197
- async function mergeDiffs(files, persistConfig) {
3198
- const results = await Promise.allSettled(
3199
- files.map(async (file) => {
3200
- const json = await readJsonFile(file).catch((error) => {
3201
- throw new Error(
3202
- `Failed to read JSON file ${file} - ${stringifyError(error)}`
3203
- );
3204
- });
3205
- const result = await reportsDiffSchema.safeParseAsync(json);
3206
- if (!result.success) {
3207
- throw new Error(
3208
- `Invalid reports diff in ${file} - ${result.error.message}`
3209
- );
3210
- }
3211
- return { ...result.data, file };
3212
- })
3213
- );
3214
- results.filter(isPromiseRejectedResult).forEach(({ reason }) => {
3215
- ui().logger.warning(
3216
- `Skipped invalid report diff - ${stringifyError(reason)}`
3217
- );
3218
- });
3219
- const diffs = results.filter(isPromiseFulfilledResult).map(({ value }) => value);
3220
- const labeledDiffs = diffs.map((diff) => ({
3221
- ...diff,
3222
- label: diff.label || basename(dirname(diff.file))
3223
- // fallback is parent folder name
3224
- }));
3225
- const markdown = generateMdReportsDiffForMonorepo(labeledDiffs);
3226
- const { outputDir, filename } = persistConfig;
3227
- const outputPath = join7(outputDir, `${filename}-diff.md`);
3228
- await ensureDirectoryExists(outputDir);
3229
- await writeFile3(outputPath, markdown);
3230
- return outputPath;
3231
- }
3232
- export {
3233
- ConfigPathError,
3234
- PersistDirError,
3235
- PersistError,
3236
- PluginOutputMissingAuditError,
3237
- autoloadRc,
3238
- collect,
3239
- collectAndPersistReports,
3240
- compareReportFiles,
3241
- compareReports,
3242
- executePlugin,
3243
- executePlugins,
3244
- history,
3245
- mergeDiffs,
3246
- persistReport,
3247
- readRcByPath,
3248
- upload
3249
- };