@code-pushup/js-packages-plugin 0.26.1
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.
- package/README.md +190 -0
- package/bin.js +1040 -0
- package/index.js +910 -0
- package/package.json +49 -0
- package/src/bin.d.ts +1 -0
- package/src/index.d.ts +3 -0
- package/src/lib/config.d.ts +28 -0
- package/src/lib/constants.d.ts +9 -0
- package/src/lib/js-packages-plugin.d.ts +19 -0
- package/src/lib/runner/audit/constants.d.ts +2 -0
- package/src/lib/runner/audit/transform.d.ts +7 -0
- package/src/lib/runner/audit/types.d.ts +27 -0
- package/src/lib/runner/constants.d.ts +3 -0
- package/src/lib/runner/index.d.ts +4 -0
- package/src/lib/runner/outdated/constants.d.ts +3 -0
- package/src/lib/runner/outdated/transform.d.ts +29 -0
- package/src/lib/runner/outdated/types.d.ts +15 -0
package/bin.js
ADDED
|
@@ -0,0 +1,1040 @@
|
|
|
1
|
+
// packages/plugin-js-packages/src/lib/runner/index.ts
|
|
2
|
+
import { writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
|
|
5
|
+
// packages/models/src/lib/audit.ts
|
|
6
|
+
import { z as z2 } from "zod";
|
|
7
|
+
|
|
8
|
+
// packages/models/src/lib/implementation/schemas.ts
|
|
9
|
+
import { MATERIAL_ICONS } from "vscode-material-icons";
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
|
|
12
|
+
// packages/models/src/lib/implementation/limits.ts
|
|
13
|
+
var MAX_SLUG_LENGTH = 128;
|
|
14
|
+
var MAX_TITLE_LENGTH = 256;
|
|
15
|
+
var MAX_DESCRIPTION_LENGTH = 65536;
|
|
16
|
+
var MAX_ISSUE_MESSAGE_LENGTH = 1024;
|
|
17
|
+
|
|
18
|
+
// packages/models/src/lib/implementation/utils.ts
|
|
19
|
+
var slugRegex = /^[a-z\d]+(?:-[a-z\d]+)*$/;
|
|
20
|
+
var filenameRegex = /^(?!.*[ \\/:*?"<>|]).+$/;
|
|
21
|
+
function hasDuplicateStrings(strings) {
|
|
22
|
+
const sortedStrings = [...strings].sort();
|
|
23
|
+
const duplStrings = sortedStrings.filter(
|
|
24
|
+
(item, index) => index !== 0 && item === sortedStrings[index - 1]
|
|
25
|
+
);
|
|
26
|
+
return duplStrings.length === 0 ? false : [...new Set(duplStrings)];
|
|
27
|
+
}
|
|
28
|
+
function hasMissingStrings(toCheck, existing) {
|
|
29
|
+
const nonExisting = toCheck.filter((s) => !existing.includes(s));
|
|
30
|
+
return nonExisting.length === 0 ? false : nonExisting;
|
|
31
|
+
}
|
|
32
|
+
function errorItems(items, transform = (itemArr) => itemArr.join(", ")) {
|
|
33
|
+
return transform(items || []);
|
|
34
|
+
}
|
|
35
|
+
function exists(value) {
|
|
36
|
+
return value != null;
|
|
37
|
+
}
|
|
38
|
+
function getMissingRefsForCategories(categories, plugins) {
|
|
39
|
+
if (categories.length === 0) {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
const auditRefsFromCategory = categories.flatMap(
|
|
43
|
+
({ refs }) => refs.filter(({ type }) => type === "audit").map(({ plugin, slug }) => `${plugin}/${slug}`)
|
|
44
|
+
);
|
|
45
|
+
const auditRefsFromPlugins = plugins.flatMap(
|
|
46
|
+
({ audits, slug: pluginSlug }) => audits.map(({ slug }) => `${pluginSlug}/${slug}`)
|
|
47
|
+
);
|
|
48
|
+
const missingAuditRefs = hasMissingStrings(
|
|
49
|
+
auditRefsFromCategory,
|
|
50
|
+
auditRefsFromPlugins
|
|
51
|
+
);
|
|
52
|
+
const groupRefsFromCategory = categories.flatMap(
|
|
53
|
+
({ refs }) => refs.filter(({ type }) => type === "group").map(({ plugin, slug }) => `${plugin}#${slug} (group)`)
|
|
54
|
+
);
|
|
55
|
+
const groupRefsFromPlugins = plugins.flatMap(
|
|
56
|
+
({ groups, slug: pluginSlug }) => Array.isArray(groups) ? groups.map(({ slug }) => `${pluginSlug}#${slug} (group)`) : []
|
|
57
|
+
);
|
|
58
|
+
const missingGroupRefs = hasMissingStrings(
|
|
59
|
+
groupRefsFromCategory,
|
|
60
|
+
groupRefsFromPlugins
|
|
61
|
+
);
|
|
62
|
+
const missingRefs = [missingAuditRefs, missingGroupRefs].filter((refs) => Array.isArray(refs) && refs.length > 0).flat();
|
|
63
|
+
return missingRefs.length > 0 ? missingRefs : false;
|
|
64
|
+
}
|
|
65
|
+
function missingRefsForCategoriesErrorMsg(categories, plugins) {
|
|
66
|
+
const missingRefs = getMissingRefsForCategories(categories, plugins);
|
|
67
|
+
return `The following category references need to point to an audit or group: ${errorItems(
|
|
68
|
+
missingRefs
|
|
69
|
+
)}`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// packages/models/src/lib/implementation/schemas.ts
|
|
73
|
+
function executionMetaSchema(options = {
|
|
74
|
+
descriptionDate: "Execution start date and time",
|
|
75
|
+
descriptionDuration: "Execution duration in ms"
|
|
76
|
+
}) {
|
|
77
|
+
return z.object({
|
|
78
|
+
date: z.string({ description: options.descriptionDate }),
|
|
79
|
+
duration: z.number({ description: options.descriptionDuration })
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
var slugSchema = z.string({ description: "Unique ID (human-readable, URL-safe)" }).regex(slugRegex, {
|
|
83
|
+
message: "The slug has to follow the pattern [0-9a-z] followed by multiple optional groups of -[0-9a-z]. e.g. my-slug"
|
|
84
|
+
}).max(MAX_SLUG_LENGTH, {
|
|
85
|
+
message: `slug can be max ${MAX_SLUG_LENGTH} characters long`
|
|
86
|
+
});
|
|
87
|
+
var descriptionSchema = z.string({ description: "Description (markdown)" }).max(MAX_DESCRIPTION_LENGTH).optional();
|
|
88
|
+
var urlSchema = z.string().url();
|
|
89
|
+
var docsUrlSchema = urlSchema.optional().or(z.literal("")).describe("Documentation site");
|
|
90
|
+
var titleSchema = z.string({ description: "Descriptive name" }).max(MAX_TITLE_LENGTH);
|
|
91
|
+
var scoreSchema = z.number({
|
|
92
|
+
description: "Value between 0 and 1"
|
|
93
|
+
}).min(0).max(1);
|
|
94
|
+
function metaSchema(options) {
|
|
95
|
+
const {
|
|
96
|
+
descriptionDescription,
|
|
97
|
+
titleDescription,
|
|
98
|
+
docsUrlDescription,
|
|
99
|
+
description
|
|
100
|
+
} = options ?? {};
|
|
101
|
+
return z.object(
|
|
102
|
+
{
|
|
103
|
+
title: titleDescription ? titleSchema.describe(titleDescription) : titleSchema,
|
|
104
|
+
description: descriptionDescription ? descriptionSchema.describe(descriptionDescription) : descriptionSchema,
|
|
105
|
+
docsUrl: docsUrlDescription ? docsUrlSchema.describe(docsUrlDescription) : docsUrlSchema
|
|
106
|
+
},
|
|
107
|
+
{ description }
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
var filePathSchema = z.string().trim().min(1, { message: "path is invalid" });
|
|
111
|
+
var fileNameSchema = z.string().trim().regex(filenameRegex, {
|
|
112
|
+
message: `The filename has to be valid`
|
|
113
|
+
}).min(1, { message: "file name is invalid" });
|
|
114
|
+
var positiveIntSchema = z.number().int().positive();
|
|
115
|
+
var nonnegativeIntSchema = z.number().int().nonnegative();
|
|
116
|
+
function packageVersionSchema(options) {
|
|
117
|
+
const { versionDescription = "NPM version of the package", required } = options ?? {};
|
|
118
|
+
const packageSchema = z.string({ description: "NPM package name" });
|
|
119
|
+
const versionSchema = z.string({ description: versionDescription });
|
|
120
|
+
return z.object(
|
|
121
|
+
{
|
|
122
|
+
packageName: required ? packageSchema : packageSchema.optional(),
|
|
123
|
+
version: required ? versionSchema : versionSchema.optional()
|
|
124
|
+
},
|
|
125
|
+
{ description: "NPM package name and version of a published package" }
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
var weightSchema = nonnegativeIntSchema.describe(
|
|
129
|
+
"Coefficient for the given score (use weight 0 if only for display)"
|
|
130
|
+
);
|
|
131
|
+
function weightedRefSchema(description, slugDescription) {
|
|
132
|
+
return z.object(
|
|
133
|
+
{
|
|
134
|
+
slug: slugSchema.describe(slugDescription),
|
|
135
|
+
weight: weightSchema.describe("Weight used to calculate score")
|
|
136
|
+
},
|
|
137
|
+
{ description }
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
function scorableSchema(description, refSchema, duplicateCheckFn, duplicateMessageFn) {
|
|
141
|
+
return z.object(
|
|
142
|
+
{
|
|
143
|
+
slug: slugSchema.describe('Human-readable unique ID, e.g. "performance"'),
|
|
144
|
+
refs: z.array(refSchema).min(1).refine(
|
|
145
|
+
(refs) => !duplicateCheckFn(refs),
|
|
146
|
+
(refs) => ({
|
|
147
|
+
message: duplicateMessageFn(refs)
|
|
148
|
+
})
|
|
149
|
+
).refine(hasNonZeroWeightedRef, () => ({
|
|
150
|
+
message: "In a category there has to be at least one ref with weight > 0"
|
|
151
|
+
}))
|
|
152
|
+
},
|
|
153
|
+
{ description }
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
var materialIconSchema = z.enum(MATERIAL_ICONS, {
|
|
157
|
+
description: "Icon from VSCode Material Icons extension"
|
|
158
|
+
});
|
|
159
|
+
function hasNonZeroWeightedRef(refs) {
|
|
160
|
+
return refs.reduce((acc, { weight }) => weight + acc, 0) !== 0;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// packages/models/src/lib/audit.ts
|
|
164
|
+
var auditSchema = z2.object({
|
|
165
|
+
slug: slugSchema.describe("ID (unique within plugin)")
|
|
166
|
+
}).merge(
|
|
167
|
+
metaSchema({
|
|
168
|
+
titleDescription: "Descriptive name",
|
|
169
|
+
descriptionDescription: "Description (markdown)",
|
|
170
|
+
docsUrlDescription: "Link to documentation (rationale)",
|
|
171
|
+
description: "List of scorable metrics for the given plugin"
|
|
172
|
+
})
|
|
173
|
+
);
|
|
174
|
+
var pluginAuditsSchema = z2.array(auditSchema, {
|
|
175
|
+
description: "List of audits maintained in a plugin"
|
|
176
|
+
}).min(1).refine(
|
|
177
|
+
(auditMetadata) => !getDuplicateSlugsInAudits(auditMetadata),
|
|
178
|
+
(auditMetadata) => ({
|
|
179
|
+
message: duplicateSlugsInAuditsErrorMsg(auditMetadata)
|
|
180
|
+
})
|
|
181
|
+
);
|
|
182
|
+
function duplicateSlugsInAuditsErrorMsg(audits) {
|
|
183
|
+
const duplicateRefs = getDuplicateSlugsInAudits(audits);
|
|
184
|
+
return `In plugin audits the following slugs are not unique: ${errorItems(
|
|
185
|
+
duplicateRefs
|
|
186
|
+
)}`;
|
|
187
|
+
}
|
|
188
|
+
function getDuplicateSlugsInAudits(audits) {
|
|
189
|
+
return hasDuplicateStrings(audits.map(({ slug }) => slug));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// packages/models/src/lib/audit-output.ts
|
|
193
|
+
import { z as z4 } from "zod";
|
|
194
|
+
|
|
195
|
+
// packages/models/src/lib/issue.ts
|
|
196
|
+
import { z as z3 } from "zod";
|
|
197
|
+
var sourceFileLocationSchema = z3.object(
|
|
198
|
+
{
|
|
199
|
+
file: filePathSchema.describe("Relative path to source file in Git repo"),
|
|
200
|
+
position: z3.object(
|
|
201
|
+
{
|
|
202
|
+
startLine: positiveIntSchema.describe("Start line"),
|
|
203
|
+
startColumn: positiveIntSchema.describe("Start column").optional(),
|
|
204
|
+
endLine: positiveIntSchema.describe("End line").optional(),
|
|
205
|
+
endColumn: positiveIntSchema.describe("End column").optional()
|
|
206
|
+
},
|
|
207
|
+
{ description: "Location in file" }
|
|
208
|
+
).optional()
|
|
209
|
+
},
|
|
210
|
+
{ description: "Source file location" }
|
|
211
|
+
);
|
|
212
|
+
var issueSeveritySchema = z3.enum(["info", "warning", "error"], {
|
|
213
|
+
description: "Severity level"
|
|
214
|
+
});
|
|
215
|
+
var issueSchema = z3.object(
|
|
216
|
+
{
|
|
217
|
+
message: z3.string({ description: "Descriptive error message" }).max(MAX_ISSUE_MESSAGE_LENGTH),
|
|
218
|
+
severity: issueSeveritySchema,
|
|
219
|
+
source: sourceFileLocationSchema.optional()
|
|
220
|
+
},
|
|
221
|
+
{ description: "Issue information" }
|
|
222
|
+
);
|
|
223
|
+
|
|
224
|
+
// packages/models/src/lib/audit-output.ts
|
|
225
|
+
var auditValueSchema = nonnegativeIntSchema.describe("Raw numeric value");
|
|
226
|
+
var auditDisplayValueSchema = z4.string({ description: "Formatted value (e.g. '0.9 s', '2.1 MB')" }).optional();
|
|
227
|
+
var auditDetailsSchema = z4.object(
|
|
228
|
+
{
|
|
229
|
+
issues: z4.array(issueSchema, { description: "List of findings" })
|
|
230
|
+
},
|
|
231
|
+
{ description: "Detailed information" }
|
|
232
|
+
);
|
|
233
|
+
var auditOutputSchema = z4.object(
|
|
234
|
+
{
|
|
235
|
+
slug: slugSchema.describe("Reference to audit"),
|
|
236
|
+
displayValue: auditDisplayValueSchema,
|
|
237
|
+
value: auditValueSchema,
|
|
238
|
+
score: scoreSchema,
|
|
239
|
+
details: auditDetailsSchema.optional()
|
|
240
|
+
},
|
|
241
|
+
{ description: "Audit information" }
|
|
242
|
+
);
|
|
243
|
+
var auditOutputsSchema = z4.array(auditOutputSchema, {
|
|
244
|
+
description: "List of JSON formatted audit output emitted by the runner process of a plugin"
|
|
245
|
+
}).refine(
|
|
246
|
+
(audits) => !getDuplicateSlugsInAudits2(audits),
|
|
247
|
+
(audits) => ({ message: duplicateSlugsInAuditsErrorMsg2(audits) })
|
|
248
|
+
);
|
|
249
|
+
function duplicateSlugsInAuditsErrorMsg2(audits) {
|
|
250
|
+
const duplicateRefs = getDuplicateSlugsInAudits2(audits);
|
|
251
|
+
return `In plugin audits the slugs are not unique: ${errorItems(
|
|
252
|
+
duplicateRefs
|
|
253
|
+
)}`;
|
|
254
|
+
}
|
|
255
|
+
function getDuplicateSlugsInAudits2(audits) {
|
|
256
|
+
return hasDuplicateStrings(audits.map(({ slug }) => slug));
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// packages/models/src/lib/category-config.ts
|
|
260
|
+
import { z as z5 } from "zod";
|
|
261
|
+
var categoryRefSchema = weightedRefSchema(
|
|
262
|
+
"Weighted references to audits and/or groups for the category",
|
|
263
|
+
"Slug of an audit or group (depending on `type`)"
|
|
264
|
+
).merge(
|
|
265
|
+
z5.object({
|
|
266
|
+
type: z5.enum(["audit", "group"], {
|
|
267
|
+
description: "Discriminant for reference kind, affects where `slug` is looked up"
|
|
268
|
+
}),
|
|
269
|
+
plugin: slugSchema.describe(
|
|
270
|
+
"Plugin slug (plugin should contain referenced audit or group)"
|
|
271
|
+
)
|
|
272
|
+
})
|
|
273
|
+
);
|
|
274
|
+
var categoryConfigSchema = scorableSchema(
|
|
275
|
+
"Category with a score calculated from audits and groups from various plugins",
|
|
276
|
+
categoryRefSchema,
|
|
277
|
+
getDuplicateRefsInCategoryMetrics,
|
|
278
|
+
duplicateRefsInCategoryMetricsErrorMsg
|
|
279
|
+
).merge(
|
|
280
|
+
metaSchema({
|
|
281
|
+
titleDescription: "Category Title",
|
|
282
|
+
docsUrlDescription: "Category docs URL",
|
|
283
|
+
descriptionDescription: "Category description",
|
|
284
|
+
description: "Meta info for category"
|
|
285
|
+
})
|
|
286
|
+
).merge(
|
|
287
|
+
z5.object({
|
|
288
|
+
isBinary: z5.boolean({
|
|
289
|
+
description: 'Is this a binary category (i.e. only a perfect score considered a "pass")?'
|
|
290
|
+
}).optional()
|
|
291
|
+
})
|
|
292
|
+
);
|
|
293
|
+
function duplicateRefsInCategoryMetricsErrorMsg(metrics) {
|
|
294
|
+
const duplicateRefs = getDuplicateRefsInCategoryMetrics(metrics);
|
|
295
|
+
return `In the categories, the following audit or group refs are duplicates: ${errorItems(
|
|
296
|
+
duplicateRefs
|
|
297
|
+
)}`;
|
|
298
|
+
}
|
|
299
|
+
function getDuplicateRefsInCategoryMetrics(metrics) {
|
|
300
|
+
return hasDuplicateStrings(
|
|
301
|
+
metrics.map(({ slug, type, plugin }) => `${type} :: ${plugin} / ${slug}`)
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
var categoriesSchema = z5.array(categoryConfigSchema, {
|
|
305
|
+
description: "Categorization of individual audits"
|
|
306
|
+
}).refine(
|
|
307
|
+
(categoryCfg) => !getDuplicateSlugCategories(categoryCfg),
|
|
308
|
+
(categoryCfg) => ({
|
|
309
|
+
message: duplicateSlugCategoriesErrorMsg(categoryCfg)
|
|
310
|
+
})
|
|
311
|
+
);
|
|
312
|
+
function duplicateSlugCategoriesErrorMsg(categories) {
|
|
313
|
+
const duplicateStringSlugs = getDuplicateSlugCategories(categories);
|
|
314
|
+
return `In the categories, the following slugs are duplicated: ${errorItems(
|
|
315
|
+
duplicateStringSlugs
|
|
316
|
+
)}`;
|
|
317
|
+
}
|
|
318
|
+
function getDuplicateSlugCategories(categories) {
|
|
319
|
+
return hasDuplicateStrings(categories.map(({ slug }) => slug));
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// packages/models/src/lib/commit.ts
|
|
323
|
+
import { z as z6 } from "zod";
|
|
324
|
+
var commitSchema = z6.object(
|
|
325
|
+
{
|
|
326
|
+
hash: z6.string({ description: "Commit SHA (full)" }).regex(
|
|
327
|
+
/^[\da-f]{40}$/,
|
|
328
|
+
"Commit SHA should be a 40-character hexadecimal string"
|
|
329
|
+
),
|
|
330
|
+
message: z6.string({ description: "Commit message" }),
|
|
331
|
+
date: z6.coerce.date({
|
|
332
|
+
description: "Date and time when commit was authored"
|
|
333
|
+
}),
|
|
334
|
+
author: z6.string({
|
|
335
|
+
description: "Commit author name"
|
|
336
|
+
}).trim()
|
|
337
|
+
},
|
|
338
|
+
{ description: "Git commit" }
|
|
339
|
+
);
|
|
340
|
+
|
|
341
|
+
// packages/models/src/lib/core-config.ts
|
|
342
|
+
import { z as z12 } from "zod";
|
|
343
|
+
|
|
344
|
+
// packages/models/src/lib/persist-config.ts
|
|
345
|
+
import { z as z7 } from "zod";
|
|
346
|
+
var formatSchema = z7.enum(["json", "md"]);
|
|
347
|
+
var persistConfigSchema = z7.object({
|
|
348
|
+
outputDir: filePathSchema.describe("Artifacts folder").optional(),
|
|
349
|
+
filename: fileNameSchema.describe("Artifacts file name (without extension)").optional(),
|
|
350
|
+
format: z7.array(formatSchema).optional()
|
|
351
|
+
});
|
|
352
|
+
|
|
353
|
+
// packages/models/src/lib/plugin-config.ts
|
|
354
|
+
import { z as z10 } from "zod";
|
|
355
|
+
|
|
356
|
+
// packages/models/src/lib/group.ts
|
|
357
|
+
import { z as z8 } from "zod";
|
|
358
|
+
var groupRefSchema = weightedRefSchema(
|
|
359
|
+
"Weighted reference to a group",
|
|
360
|
+
"Reference slug to a group within this plugin (e.g. 'max-lines')"
|
|
361
|
+
);
|
|
362
|
+
var groupMetaSchema = metaSchema({
|
|
363
|
+
titleDescription: "Descriptive name for the group",
|
|
364
|
+
descriptionDescription: "Description of the group (markdown)",
|
|
365
|
+
docsUrlDescription: "Group documentation site",
|
|
366
|
+
description: "Group metadata"
|
|
367
|
+
});
|
|
368
|
+
var groupSchema = scorableSchema(
|
|
369
|
+
'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',
|
|
370
|
+
groupRefSchema,
|
|
371
|
+
getDuplicateRefsInGroups,
|
|
372
|
+
duplicateRefsInGroupsErrorMsg
|
|
373
|
+
).merge(groupMetaSchema);
|
|
374
|
+
var groupsSchema = z8.array(groupSchema, {
|
|
375
|
+
description: "List of groups"
|
|
376
|
+
}).optional().refine(
|
|
377
|
+
(groups) => !getDuplicateSlugsInGroups(groups),
|
|
378
|
+
(groups) => ({
|
|
379
|
+
message: duplicateSlugsInGroupsErrorMsg(groups)
|
|
380
|
+
})
|
|
381
|
+
);
|
|
382
|
+
function duplicateRefsInGroupsErrorMsg(groups) {
|
|
383
|
+
const duplicateRefs = getDuplicateRefsInGroups(groups);
|
|
384
|
+
return `In plugin groups the following references are not unique: ${errorItems(
|
|
385
|
+
duplicateRefs
|
|
386
|
+
)}`;
|
|
387
|
+
}
|
|
388
|
+
function getDuplicateRefsInGroups(groups) {
|
|
389
|
+
return hasDuplicateStrings(groups.map(({ slug: ref }) => ref).filter(exists));
|
|
390
|
+
}
|
|
391
|
+
function duplicateSlugsInGroupsErrorMsg(groups) {
|
|
392
|
+
const duplicateRefs = getDuplicateSlugsInGroups(groups);
|
|
393
|
+
return `In groups the following slugs are not unique: ${errorItems(
|
|
394
|
+
duplicateRefs
|
|
395
|
+
)}`;
|
|
396
|
+
}
|
|
397
|
+
function getDuplicateSlugsInGroups(groups) {
|
|
398
|
+
return Array.isArray(groups) ? hasDuplicateStrings(groups.map(({ slug }) => slug)) : false;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// packages/models/src/lib/runner-config.ts
|
|
402
|
+
import { z as z9 } from "zod";
|
|
403
|
+
var outputTransformSchema = z9.function().args(z9.unknown()).returns(z9.union([auditOutputsSchema, z9.promise(auditOutputsSchema)]));
|
|
404
|
+
var runnerConfigSchema = z9.object(
|
|
405
|
+
{
|
|
406
|
+
command: z9.string({
|
|
407
|
+
description: "Shell command to execute"
|
|
408
|
+
}),
|
|
409
|
+
args: z9.array(z9.string({ description: "Command arguments" })).optional(),
|
|
410
|
+
outputFile: filePathSchema.describe("Output path"),
|
|
411
|
+
outputTransform: outputTransformSchema.optional()
|
|
412
|
+
},
|
|
413
|
+
{
|
|
414
|
+
description: "How to execute runner"
|
|
415
|
+
}
|
|
416
|
+
);
|
|
417
|
+
var onProgressSchema = z9.function().args(z9.unknown()).returns(z9.void());
|
|
418
|
+
var runnerFunctionSchema = z9.function().args(onProgressSchema.optional()).returns(z9.union([auditOutputsSchema, z9.promise(auditOutputsSchema)]));
|
|
419
|
+
|
|
420
|
+
// packages/models/src/lib/plugin-config.ts
|
|
421
|
+
var pluginMetaSchema = packageVersionSchema().merge(
|
|
422
|
+
metaSchema({
|
|
423
|
+
titleDescription: "Descriptive name",
|
|
424
|
+
descriptionDescription: "Description (markdown)",
|
|
425
|
+
docsUrlDescription: "Plugin documentation site",
|
|
426
|
+
description: "Plugin metadata"
|
|
427
|
+
})
|
|
428
|
+
).merge(
|
|
429
|
+
z10.object({
|
|
430
|
+
slug: slugSchema.describe("Unique plugin slug within core config"),
|
|
431
|
+
icon: materialIconSchema
|
|
432
|
+
})
|
|
433
|
+
);
|
|
434
|
+
var pluginDataSchema = z10.object({
|
|
435
|
+
runner: z10.union([runnerConfigSchema, runnerFunctionSchema]),
|
|
436
|
+
audits: pluginAuditsSchema,
|
|
437
|
+
groups: groupsSchema
|
|
438
|
+
});
|
|
439
|
+
var pluginConfigSchema = pluginMetaSchema.merge(pluginDataSchema).refine(
|
|
440
|
+
(pluginCfg) => !getMissingRefsFromGroups(pluginCfg),
|
|
441
|
+
(pluginCfg) => ({
|
|
442
|
+
message: missingRefsFromGroupsErrorMsg(pluginCfg)
|
|
443
|
+
})
|
|
444
|
+
);
|
|
445
|
+
function missingRefsFromGroupsErrorMsg(pluginCfg) {
|
|
446
|
+
const missingRefs = getMissingRefsFromGroups(pluginCfg);
|
|
447
|
+
return `The following group references need to point to an existing audit in this plugin config: ${errorItems(
|
|
448
|
+
missingRefs
|
|
449
|
+
)}`;
|
|
450
|
+
}
|
|
451
|
+
function getMissingRefsFromGroups(pluginCfg) {
|
|
452
|
+
return hasMissingStrings(
|
|
453
|
+
pluginCfg.groups?.flatMap(
|
|
454
|
+
({ refs: audits }) => audits.map(({ slug: ref }) => ref)
|
|
455
|
+
) ?? [],
|
|
456
|
+
pluginCfg.audits.map(({ slug }) => slug)
|
|
457
|
+
);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// packages/models/src/lib/upload-config.ts
|
|
461
|
+
import { z as z11 } from "zod";
|
|
462
|
+
var uploadConfigSchema = z11.object({
|
|
463
|
+
server: urlSchema.describe("URL of deployed portal API"),
|
|
464
|
+
apiKey: z11.string({
|
|
465
|
+
description: "API key with write access to portal (use `process.env` for security)"
|
|
466
|
+
}),
|
|
467
|
+
organization: slugSchema.describe(
|
|
468
|
+
"Organization slug from Code PushUp portal"
|
|
469
|
+
),
|
|
470
|
+
project: slugSchema.describe("Project slug from Code PushUp portal"),
|
|
471
|
+
timeout: z11.number({ description: "Request timeout in minutes (default is 5)" }).positive().int().optional()
|
|
472
|
+
});
|
|
473
|
+
|
|
474
|
+
// packages/models/src/lib/core-config.ts
|
|
475
|
+
var unrefinedCoreConfigSchema = z12.object({
|
|
476
|
+
plugins: z12.array(pluginConfigSchema, {
|
|
477
|
+
description: "List of plugins to be used (official, community-provided, or custom)"
|
|
478
|
+
}).min(1),
|
|
479
|
+
/** portal configuration for persisting results */
|
|
480
|
+
persist: persistConfigSchema.optional(),
|
|
481
|
+
/** portal configuration for uploading results */
|
|
482
|
+
upload: uploadConfigSchema.optional(),
|
|
483
|
+
categories: categoriesSchema.optional()
|
|
484
|
+
});
|
|
485
|
+
var coreConfigSchema = refineCoreConfig(unrefinedCoreConfigSchema);
|
|
486
|
+
function refineCoreConfig(schema) {
|
|
487
|
+
return schema.refine(
|
|
488
|
+
(coreCfg) => !getMissingRefsForCategories(coreCfg.categories ?? [], coreCfg.plugins),
|
|
489
|
+
(coreCfg) => ({
|
|
490
|
+
message: missingRefsForCategoriesErrorMsg(
|
|
491
|
+
coreCfg.categories ?? [],
|
|
492
|
+
coreCfg.plugins
|
|
493
|
+
)
|
|
494
|
+
})
|
|
495
|
+
);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
// packages/models/src/lib/report.ts
|
|
499
|
+
import { z as z13 } from "zod";
|
|
500
|
+
var auditReportSchema = auditSchema.merge(auditOutputSchema);
|
|
501
|
+
var pluginReportSchema = pluginMetaSchema.merge(
|
|
502
|
+
executionMetaSchema({
|
|
503
|
+
descriptionDate: "Start date and time of plugin run",
|
|
504
|
+
descriptionDuration: "Duration of the plugin run in ms"
|
|
505
|
+
})
|
|
506
|
+
).merge(
|
|
507
|
+
z13.object({
|
|
508
|
+
audits: z13.array(auditReportSchema).min(1),
|
|
509
|
+
groups: z13.array(groupSchema).optional()
|
|
510
|
+
})
|
|
511
|
+
).refine(
|
|
512
|
+
(pluginReport) => !getMissingRefsFromGroups2(pluginReport.audits, pluginReport.groups ?? []),
|
|
513
|
+
(pluginReport) => ({
|
|
514
|
+
message: missingRefsFromGroupsErrorMsg2(
|
|
515
|
+
pluginReport.audits,
|
|
516
|
+
pluginReport.groups ?? []
|
|
517
|
+
)
|
|
518
|
+
})
|
|
519
|
+
);
|
|
520
|
+
function missingRefsFromGroupsErrorMsg2(audits, groups) {
|
|
521
|
+
const missingRefs = getMissingRefsFromGroups2(audits, groups);
|
|
522
|
+
return `group references need to point to an existing audit in this plugin report: ${errorItems(
|
|
523
|
+
missingRefs
|
|
524
|
+
)}`;
|
|
525
|
+
}
|
|
526
|
+
function getMissingRefsFromGroups2(audits, groups) {
|
|
527
|
+
return hasMissingStrings(
|
|
528
|
+
groups.flatMap(
|
|
529
|
+
({ refs: auditRefs }) => auditRefs.map(({ slug: ref }) => ref)
|
|
530
|
+
),
|
|
531
|
+
audits.map(({ slug }) => slug)
|
|
532
|
+
);
|
|
533
|
+
}
|
|
534
|
+
var reportSchema = packageVersionSchema({
|
|
535
|
+
versionDescription: "NPM version of the CLI",
|
|
536
|
+
required: true
|
|
537
|
+
}).merge(
|
|
538
|
+
executionMetaSchema({
|
|
539
|
+
descriptionDate: "Start date and time of the collect run",
|
|
540
|
+
descriptionDuration: "Duration of the collect run in ms"
|
|
541
|
+
})
|
|
542
|
+
).merge(
|
|
543
|
+
z13.object(
|
|
544
|
+
{
|
|
545
|
+
categories: z13.array(categoryConfigSchema),
|
|
546
|
+
plugins: z13.array(pluginReportSchema).min(1),
|
|
547
|
+
commit: commitSchema.describe("Git commit for which report was collected").nullable()
|
|
548
|
+
},
|
|
549
|
+
{ description: "Collect output data" }
|
|
550
|
+
)
|
|
551
|
+
).refine(
|
|
552
|
+
(report) => !getMissingRefsForCategories(report.categories, report.plugins),
|
|
553
|
+
(report) => ({
|
|
554
|
+
message: missingRefsForCategoriesErrorMsg(
|
|
555
|
+
report.categories,
|
|
556
|
+
report.plugins
|
|
557
|
+
)
|
|
558
|
+
})
|
|
559
|
+
);
|
|
560
|
+
|
|
561
|
+
// packages/models/src/lib/reports-diff.ts
|
|
562
|
+
import { z as z14 } from "zod";
|
|
563
|
+
function makeComparisonSchema(schema) {
|
|
564
|
+
const sharedDescription = schema.description || "Result";
|
|
565
|
+
return z14.object({
|
|
566
|
+
before: schema.describe(`${sharedDescription} (source commit)`),
|
|
567
|
+
after: schema.describe(`${sharedDescription} (target commit)`)
|
|
568
|
+
});
|
|
569
|
+
}
|
|
570
|
+
function makeArraysComparisonSchema(diffSchema, resultSchema, description) {
|
|
571
|
+
return z14.object(
|
|
572
|
+
{
|
|
573
|
+
changed: z14.array(diffSchema),
|
|
574
|
+
unchanged: z14.array(resultSchema),
|
|
575
|
+
added: z14.array(resultSchema),
|
|
576
|
+
removed: z14.array(resultSchema)
|
|
577
|
+
},
|
|
578
|
+
{ description }
|
|
579
|
+
);
|
|
580
|
+
}
|
|
581
|
+
var scorableMetaSchema = z14.object({ slug: slugSchema, title: titleSchema });
|
|
582
|
+
var scorableWithPluginMetaSchema = scorableMetaSchema.merge(
|
|
583
|
+
z14.object({
|
|
584
|
+
plugin: pluginMetaSchema.pick({ slug: true, title: true }).describe("Plugin which defines it")
|
|
585
|
+
})
|
|
586
|
+
);
|
|
587
|
+
var scorableDiffSchema = scorableMetaSchema.merge(
|
|
588
|
+
z14.object({
|
|
589
|
+
scores: makeComparisonSchema(scoreSchema).merge(
|
|
590
|
+
z14.object({
|
|
591
|
+
diff: z14.number().min(-1).max(1).describe("Score change (`scores.after - scores.before`)")
|
|
592
|
+
})
|
|
593
|
+
).describe("Score comparison")
|
|
594
|
+
})
|
|
595
|
+
);
|
|
596
|
+
var scorableWithPluginDiffSchema = scorableDiffSchema.merge(
|
|
597
|
+
scorableWithPluginMetaSchema
|
|
598
|
+
);
|
|
599
|
+
var categoryDiffSchema = scorableDiffSchema;
|
|
600
|
+
var groupDiffSchema = scorableWithPluginDiffSchema;
|
|
601
|
+
var auditDiffSchema = scorableWithPluginDiffSchema.merge(
|
|
602
|
+
z14.object({
|
|
603
|
+
values: makeComparisonSchema(auditValueSchema).merge(
|
|
604
|
+
z14.object({
|
|
605
|
+
diff: z14.number().int().describe("Value change (`values.after - values.before`)")
|
|
606
|
+
})
|
|
607
|
+
).describe("Audit `value` comparison"),
|
|
608
|
+
displayValues: makeComparisonSchema(auditDisplayValueSchema).describe(
|
|
609
|
+
"Audit `displayValue` comparison"
|
|
610
|
+
)
|
|
611
|
+
})
|
|
612
|
+
);
|
|
613
|
+
var categoryResultSchema = scorableMetaSchema.merge(
|
|
614
|
+
z14.object({ score: scoreSchema })
|
|
615
|
+
);
|
|
616
|
+
var groupResultSchema = scorableWithPluginMetaSchema.merge(
|
|
617
|
+
z14.object({ score: scoreSchema })
|
|
618
|
+
);
|
|
619
|
+
var auditResultSchema = scorableWithPluginMetaSchema.merge(
|
|
620
|
+
auditOutputSchema.pick({ score: true, value: true, displayValue: true })
|
|
621
|
+
);
|
|
622
|
+
var reportsDiffSchema = z14.object({
|
|
623
|
+
commits: makeComparisonSchema(commitSchema).nullable().describe("Commits identifying compared reports"),
|
|
624
|
+
categories: makeArraysComparisonSchema(
|
|
625
|
+
categoryDiffSchema,
|
|
626
|
+
categoryResultSchema,
|
|
627
|
+
"Changes affecting categories"
|
|
628
|
+
),
|
|
629
|
+
groups: makeArraysComparisonSchema(
|
|
630
|
+
groupDiffSchema,
|
|
631
|
+
groupResultSchema,
|
|
632
|
+
"Changes affecting groups"
|
|
633
|
+
),
|
|
634
|
+
audits: makeArraysComparisonSchema(
|
|
635
|
+
auditDiffSchema,
|
|
636
|
+
auditResultSchema,
|
|
637
|
+
"Changes affecting audits"
|
|
638
|
+
)
|
|
639
|
+
}).merge(
|
|
640
|
+
packageVersionSchema({
|
|
641
|
+
versionDescription: "NPM version of the CLI (when `compare` was run)",
|
|
642
|
+
required: true
|
|
643
|
+
})
|
|
644
|
+
).merge(
|
|
645
|
+
executionMetaSchema({
|
|
646
|
+
descriptionDate: "Start date and time of the compare run",
|
|
647
|
+
descriptionDuration: "Duration of the compare run in ms"
|
|
648
|
+
})
|
|
649
|
+
);
|
|
650
|
+
|
|
651
|
+
// packages/utils/src/lib/execute-process.ts
|
|
652
|
+
import { spawn } from "node:child_process";
|
|
653
|
+
|
|
654
|
+
// packages/utils/src/lib/file-system.ts
|
|
655
|
+
import { bundleRequire } from "bundle-require";
|
|
656
|
+
import chalk2 from "chalk";
|
|
657
|
+
import { mkdir, readFile, readdir, rm, stat } from "node:fs/promises";
|
|
658
|
+
import { join } from "node:path";
|
|
659
|
+
|
|
660
|
+
// packages/utils/src/lib/guards.ts
|
|
661
|
+
function isPromiseFulfilledResult(result) {
|
|
662
|
+
return result.status === "fulfilled";
|
|
663
|
+
}
|
|
664
|
+
function isPromiseRejectedResult(result) {
|
|
665
|
+
return result.status === "rejected";
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
// packages/utils/src/lib/logging.ts
|
|
669
|
+
import isaacs_cliui from "@isaacs/cliui";
|
|
670
|
+
import { cliui } from "@poppinss/cliui";
|
|
671
|
+
import chalk from "chalk";
|
|
672
|
+
|
|
673
|
+
// packages/utils/src/lib/reports/constants.ts
|
|
674
|
+
var TERMINAL_WIDTH = 80;
|
|
675
|
+
|
|
676
|
+
// packages/utils/src/lib/logging.ts
|
|
677
|
+
var singletonUiInstance;
|
|
678
|
+
function ui() {
|
|
679
|
+
if (singletonUiInstance === void 0) {
|
|
680
|
+
singletonUiInstance = cliui();
|
|
681
|
+
}
|
|
682
|
+
return {
|
|
683
|
+
...singletonUiInstance,
|
|
684
|
+
row: (args) => {
|
|
685
|
+
logListItem(args);
|
|
686
|
+
}
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
var singletonisaacUi;
|
|
690
|
+
function logListItem(args) {
|
|
691
|
+
if (singletonisaacUi === void 0) {
|
|
692
|
+
singletonisaacUi = isaacs_cliui({ width: TERMINAL_WIDTH });
|
|
693
|
+
}
|
|
694
|
+
singletonisaacUi.div(...args);
|
|
695
|
+
const content = singletonisaacUi.toString();
|
|
696
|
+
singletonisaacUi.rows = [];
|
|
697
|
+
singletonUiInstance?.logger.log(content);
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
// packages/utils/src/lib/file-system.ts
|
|
701
|
+
async function readTextFile(path) {
|
|
702
|
+
const buffer = await readFile(path);
|
|
703
|
+
return buffer.toString();
|
|
704
|
+
}
|
|
705
|
+
async function readJsonFile(path) {
|
|
706
|
+
const text = await readTextFile(path);
|
|
707
|
+
return JSON.parse(text);
|
|
708
|
+
}
|
|
709
|
+
async function ensureDirectoryExists(baseDir) {
|
|
710
|
+
try {
|
|
711
|
+
await mkdir(baseDir, { recursive: true });
|
|
712
|
+
return;
|
|
713
|
+
} catch (error) {
|
|
714
|
+
ui().logger.error(error.message);
|
|
715
|
+
if (error.code !== "EEXIST") {
|
|
716
|
+
throw error;
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
function pluginWorkDir(slug) {
|
|
721
|
+
return join("node_modules", ".code-pushup", slug);
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
// packages/utils/src/lib/reports/utils.ts
|
|
725
|
+
function calcDuration(start, stop) {
|
|
726
|
+
return Math.floor((stop ?? performance.now()) - start);
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
// packages/utils/src/lib/execute-process.ts
|
|
730
|
+
var ProcessError = class extends Error {
|
|
731
|
+
code;
|
|
732
|
+
stderr;
|
|
733
|
+
stdout;
|
|
734
|
+
constructor(result) {
|
|
735
|
+
super(result.stderr);
|
|
736
|
+
this.code = result.code;
|
|
737
|
+
this.stderr = result.stderr;
|
|
738
|
+
this.stdout = result.stdout;
|
|
739
|
+
}
|
|
740
|
+
};
|
|
741
|
+
function executeProcess(cfg) {
|
|
742
|
+
const { observer, cwd, command, args, alwaysResolve = false } = cfg;
|
|
743
|
+
const { onStdout, onError, onComplete } = observer ?? {};
|
|
744
|
+
const date = (/* @__PURE__ */ new Date()).toISOString();
|
|
745
|
+
const start = performance.now();
|
|
746
|
+
return new Promise((resolve, reject) => {
|
|
747
|
+
const process2 = spawn(command, args, { cwd, shell: true });
|
|
748
|
+
let stdout = "";
|
|
749
|
+
let stderr = "";
|
|
750
|
+
process2.stdout.on("data", (data) => {
|
|
751
|
+
stdout += String(data);
|
|
752
|
+
onStdout?.(String(data));
|
|
753
|
+
});
|
|
754
|
+
process2.stderr.on("data", (data) => {
|
|
755
|
+
stderr += String(data);
|
|
756
|
+
});
|
|
757
|
+
process2.on("error", (err) => {
|
|
758
|
+
stderr += err.toString();
|
|
759
|
+
});
|
|
760
|
+
process2.on("close", (code) => {
|
|
761
|
+
const timings = { date, duration: calcDuration(start) };
|
|
762
|
+
if (code === 0 || alwaysResolve) {
|
|
763
|
+
onComplete?.();
|
|
764
|
+
resolve({ code, stdout, stderr, ...timings });
|
|
765
|
+
} else {
|
|
766
|
+
const errorMsg = new ProcessError({ code, stdout, stderr, ...timings });
|
|
767
|
+
onError?.(errorMsg);
|
|
768
|
+
reject(errorMsg);
|
|
769
|
+
}
|
|
770
|
+
});
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
// packages/utils/src/lib/git.ts
|
|
775
|
+
import { simpleGit } from "simple-git";
|
|
776
|
+
|
|
777
|
+
// packages/utils/src/lib/transform.ts
|
|
778
|
+
function objectToEntries(obj) {
|
|
779
|
+
return Object.entries(obj);
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// packages/utils/src/lib/progress.ts
|
|
783
|
+
import chalk3 from "chalk";
|
|
784
|
+
import { MultiProgressBars } from "multi-progress-bars";
|
|
785
|
+
|
|
786
|
+
// packages/utils/src/lib/reports/log-stdout-summary.ts
|
|
787
|
+
import chalk4 from "chalk";
|
|
788
|
+
|
|
789
|
+
// packages/plugin-js-packages/src/lib/config.ts
|
|
790
|
+
import { z as z15 } from "zod";
|
|
791
|
+
|
|
792
|
+
// packages/plugin-js-packages/src/lib/constants.ts
|
|
793
|
+
var defaultAuditLevelMapping = {
|
|
794
|
+
critical: "error",
|
|
795
|
+
high: "error",
|
|
796
|
+
moderate: "warning",
|
|
797
|
+
low: "warning",
|
|
798
|
+
info: "info"
|
|
799
|
+
};
|
|
800
|
+
|
|
801
|
+
// packages/plugin-js-packages/src/lib/config.ts
|
|
802
|
+
var dependencyGroups = ["prod", "dev", "optional"];
|
|
803
|
+
var packageCommandSchema = z15.enum(["audit", "outdated"]);
|
|
804
|
+
var packageManagerSchema = z15.enum([
|
|
805
|
+
"npm",
|
|
806
|
+
"yarn-classic",
|
|
807
|
+
"yarn-modern",
|
|
808
|
+
"pnpm"
|
|
809
|
+
]);
|
|
810
|
+
var packageAuditLevels = [
|
|
811
|
+
"critical",
|
|
812
|
+
"high",
|
|
813
|
+
"moderate",
|
|
814
|
+
"low",
|
|
815
|
+
"info"
|
|
816
|
+
];
|
|
817
|
+
var packageAuditLevelSchema = z15.enum(packageAuditLevels);
|
|
818
|
+
function fillAuditLevelMapping(mapping) {
|
|
819
|
+
return {
|
|
820
|
+
critical: mapping.critical ?? defaultAuditLevelMapping.critical,
|
|
821
|
+
high: mapping.high ?? defaultAuditLevelMapping.high,
|
|
822
|
+
moderate: mapping.moderate ?? defaultAuditLevelMapping.moderate,
|
|
823
|
+
low: mapping.low ?? defaultAuditLevelMapping.low,
|
|
824
|
+
info: mapping.info ?? defaultAuditLevelMapping.info
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
var jsPackagesPluginConfigSchema = z15.object({
|
|
828
|
+
checks: z15.array(packageCommandSchema, {
|
|
829
|
+
description: "Package manager commands to be run. Defaults to both audit and outdated."
|
|
830
|
+
}).min(1).default(["audit", "outdated"]),
|
|
831
|
+
packageManager: packageManagerSchema.describe("Package manager to be used."),
|
|
832
|
+
auditLevelMapping: z15.record(packageAuditLevelSchema, issueSeveritySchema, {
|
|
833
|
+
description: "Mapping of audit levels to issue severity. Custom mapping or overrides may be entered manually, otherwise has a default preset."
|
|
834
|
+
}).default(defaultAuditLevelMapping).transform(fillAuditLevelMapping)
|
|
835
|
+
});
|
|
836
|
+
|
|
837
|
+
// packages/plugin-js-packages/src/lib/runner/audit/constants.ts
|
|
838
|
+
var auditScoreModifiers = {
|
|
839
|
+
critical: 1,
|
|
840
|
+
high: 0.1,
|
|
841
|
+
moderate: 0.05,
|
|
842
|
+
low: 0.02,
|
|
843
|
+
info: 0.01
|
|
844
|
+
};
|
|
845
|
+
|
|
846
|
+
// packages/plugin-js-packages/src/lib/runner/audit/transform.ts
|
|
847
|
+
function auditResultToAuditOutput(result, dependenciesType, auditLevelMapping) {
|
|
848
|
+
const issues = vulnerabilitiesToIssues(
|
|
849
|
+
result.vulnerabilities,
|
|
850
|
+
auditLevelMapping
|
|
851
|
+
);
|
|
852
|
+
return {
|
|
853
|
+
slug: `npm-audit-${dependenciesType}`,
|
|
854
|
+
score: calculateAuditScore(result.metadata.vulnerabilities),
|
|
855
|
+
value: result.metadata.vulnerabilities.total,
|
|
856
|
+
displayValue: vulnerabilitiesToDisplayValue(
|
|
857
|
+
result.metadata.vulnerabilities
|
|
858
|
+
),
|
|
859
|
+
...issues.length > 0 && { details: { issues } }
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
function calculateAuditScore(stats) {
|
|
863
|
+
if (stats.total === 0) {
|
|
864
|
+
return 1;
|
|
865
|
+
}
|
|
866
|
+
return objectToEntries(stats).reduce(
|
|
867
|
+
(score, [level, vulnerabilities]) => {
|
|
868
|
+
if (level === "total") {
|
|
869
|
+
return score;
|
|
870
|
+
}
|
|
871
|
+
const reducedScore = score - auditScoreModifiers[level] * vulnerabilities;
|
|
872
|
+
return Math.max(reducedScore, 0);
|
|
873
|
+
},
|
|
874
|
+
1
|
|
875
|
+
);
|
|
876
|
+
}
|
|
877
|
+
function vulnerabilitiesToDisplayValue(vulnerabilities) {
|
|
878
|
+
if (vulnerabilities.total === 0) {
|
|
879
|
+
return "0 vulnerabilities";
|
|
880
|
+
}
|
|
881
|
+
const vulnerabilityStats = packageAuditLevels.map(
|
|
882
|
+
(level) => vulnerabilities[level] > 0 ? `${vulnerabilities[level]} ${level}` : ""
|
|
883
|
+
).filter((text) => text !== "").join(", ");
|
|
884
|
+
return `${vulnerabilities.total} ${vulnerabilities.total === 1 ? "vulnerability" : "vulnerabilities"} (${vulnerabilityStats})`;
|
|
885
|
+
}
|
|
886
|
+
function vulnerabilitiesToIssues(vulnerabilities, auditLevelMapping) {
|
|
887
|
+
if (Object.keys(vulnerabilities).length === 0) {
|
|
888
|
+
return [];
|
|
889
|
+
}
|
|
890
|
+
return Object.values(vulnerabilities).map((detail) => {
|
|
891
|
+
const versionRange = detail.range === "*" ? "**all** versions" : `versions **${detail.range}**`;
|
|
892
|
+
const vulnerabilitySummary = `\`${detail.name}\` dependency has a **${detail.severity}** vulnerability in ${versionRange}.`;
|
|
893
|
+
const fixInformation = typeof detail.fixAvailable === "boolean" ? `Fix is ${detail.fixAvailable ? "" : "not "}available.` : `Fix available: Update \`${detail.fixAvailable.name}\` to version **${detail.fixAvailable.version}**${detail.fixAvailable.isSemVerMajor ? " (breaking change)." : "."}`;
|
|
894
|
+
if (Array.isArray(detail.via) && detail.via.length > 0 && typeof detail.via[0] === "object") {
|
|
895
|
+
return {
|
|
896
|
+
message: `${vulnerabilitySummary} ${fixInformation} More information: [${detail.via[0].title}](${detail.via[0].url})`,
|
|
897
|
+
severity: auditLevelMapping[detail.severity]
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
return {
|
|
901
|
+
message: `${vulnerabilitySummary} ${fixInformation}`,
|
|
902
|
+
severity: auditLevelMapping[detail.severity]
|
|
903
|
+
};
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
// packages/plugin-js-packages/src/lib/runner/constants.ts
|
|
908
|
+
import { join as join2 } from "node:path";
|
|
909
|
+
var WORKDIR = pluginWorkDir("js-packages");
|
|
910
|
+
var RUNNER_OUTPUT_PATH = join2(WORKDIR, "runner-output.json");
|
|
911
|
+
var PLUGIN_CONFIG_PATH = join2(
|
|
912
|
+
process.cwd(),
|
|
913
|
+
WORKDIR,
|
|
914
|
+
"plugin-config.json"
|
|
915
|
+
);
|
|
916
|
+
|
|
917
|
+
// packages/plugin-js-packages/src/lib/runner/outdated/constants.ts
|
|
918
|
+
var outdatedSeverity = {
|
|
919
|
+
major: "error",
|
|
920
|
+
minor: "warning",
|
|
921
|
+
patch: "info"
|
|
922
|
+
};
|
|
923
|
+
|
|
924
|
+
// packages/plugin-js-packages/src/lib/runner/outdated/transform.ts
|
|
925
|
+
function outdatedResultToAuditOutput(result, dependenciesType) {
|
|
926
|
+
const validDependencies = objectToEntries(result).filter(
|
|
927
|
+
(entry) => entry[1].current != null
|
|
928
|
+
).filter(
|
|
929
|
+
([, detail]) => dependenciesType === "prod" ? detail.type === "dependencies" : detail.type === `${dependenciesType}Dependencies`
|
|
930
|
+
);
|
|
931
|
+
const outdatedDependencies = validDependencies.filter(
|
|
932
|
+
([, versions]) => versions.current !== versions.wanted
|
|
933
|
+
);
|
|
934
|
+
const majorOutdatedAmount = outdatedDependencies.filter(
|
|
935
|
+
([, versions]) => getOutdatedLevel(versions.current, versions.wanted) === "major"
|
|
936
|
+
).length;
|
|
937
|
+
const issues = outdatedDependencies.length === 0 ? [] : outdatedToIssues(outdatedDependencies);
|
|
938
|
+
return {
|
|
939
|
+
slug: `npm-outdated-${dependenciesType}`,
|
|
940
|
+
score: calculateOutdatedScore(
|
|
941
|
+
majorOutdatedAmount,
|
|
942
|
+
validDependencies.length
|
|
943
|
+
),
|
|
944
|
+
value: outdatedDependencies.length,
|
|
945
|
+
displayValue: outdatedToDisplayValue(
|
|
946
|
+
majorOutdatedAmount,
|
|
947
|
+
outdatedDependencies.length
|
|
948
|
+
),
|
|
949
|
+
...issues.length > 0 && { details: { issues } }
|
|
950
|
+
};
|
|
951
|
+
}
|
|
952
|
+
function calculateOutdatedScore(majorOutdated, totalDeps) {
|
|
953
|
+
return totalDeps > 0 ? (totalDeps - majorOutdated) / totalDeps : 1;
|
|
954
|
+
}
|
|
955
|
+
function outdatedToDisplayValue(majorOutdated, totalOutdated) {
|
|
956
|
+
return totalOutdated === 0 ? "all dependencies are up to date" : majorOutdated > 0 ? `${majorOutdated} out of ${totalOutdated} outdated dependencies require major update` : `${totalOutdated} outdated ${totalOutdated === 1 ? "dependency" : "dependencies"}`;
|
|
957
|
+
}
|
|
958
|
+
function outdatedToIssues(dependencies) {
|
|
959
|
+
return dependencies.map(([name, versions]) => {
|
|
960
|
+
const outdatedLevel = getOutdatedLevel(versions.current, versions.wanted);
|
|
961
|
+
const packageReference = versions.homepage == null ? `\`${name}\`` : `[\`${name}\`](${versions.homepage})`;
|
|
962
|
+
return {
|
|
963
|
+
message: `Package ${packageReference} requires a **${outdatedLevel}** update from **${versions.current}** to **${versions.wanted}**.`,
|
|
964
|
+
severity: outdatedSeverity[outdatedLevel]
|
|
965
|
+
};
|
|
966
|
+
});
|
|
967
|
+
}
|
|
968
|
+
function getOutdatedLevel(currentFullVersion, wantedFullVersion) {
|
|
969
|
+
const current = splitPackageVersion(currentFullVersion);
|
|
970
|
+
const wanted = splitPackageVersion(wantedFullVersion);
|
|
971
|
+
if (current.major < wanted.major) {
|
|
972
|
+
return "major";
|
|
973
|
+
}
|
|
974
|
+
if (current.minor < wanted.minor) {
|
|
975
|
+
return "minor";
|
|
976
|
+
}
|
|
977
|
+
if (current.patch < wanted.patch) {
|
|
978
|
+
return "patch";
|
|
979
|
+
}
|
|
980
|
+
throw new Error("Package is not outdated.");
|
|
981
|
+
}
|
|
982
|
+
function splitPackageVersion(fullVersion) {
|
|
983
|
+
const [major, minor, patch] = fullVersion.split(".").map(Number);
|
|
984
|
+
if (major == null || minor == null || patch == null) {
|
|
985
|
+
throw new Error(`Invalid version description ${fullVersion}`);
|
|
986
|
+
}
|
|
987
|
+
return { major, minor, patch };
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
// packages/plugin-js-packages/src/lib/runner/index.ts
|
|
991
|
+
async function executeRunner() {
|
|
992
|
+
const { packageManager, checks, auditLevelMapping } = await readJsonFile(PLUGIN_CONFIG_PATH);
|
|
993
|
+
const auditResults = checks.includes("audit") ? await processAudit(packageManager, auditLevelMapping) : [];
|
|
994
|
+
const outdatedResults = checks.includes("outdated") ? await processOutdated(packageManager) : [];
|
|
995
|
+
const checkResults = [...auditResults, ...outdatedResults];
|
|
996
|
+
await ensureDirectoryExists(dirname(RUNNER_OUTPUT_PATH));
|
|
997
|
+
await writeFile(RUNNER_OUTPUT_PATH, JSON.stringify(checkResults));
|
|
998
|
+
}
|
|
999
|
+
async function processOutdated(packageManager) {
|
|
1000
|
+
const { stdout } = await executeProcess({
|
|
1001
|
+
command: packageManager,
|
|
1002
|
+
args: ["outdated", "--json", "--long"],
|
|
1003
|
+
alwaysResolve: true
|
|
1004
|
+
// npm outdated returns exit code 1 when outdated dependencies are found
|
|
1005
|
+
});
|
|
1006
|
+
const outdatedResult = JSON.parse(stdout);
|
|
1007
|
+
return dependencyGroups.map(
|
|
1008
|
+
(dep) => outdatedResultToAuditOutput(outdatedResult, dep)
|
|
1009
|
+
);
|
|
1010
|
+
}
|
|
1011
|
+
async function processAudit(packageManager, auditLevelMapping) {
|
|
1012
|
+
const auditResults = await Promise.allSettled(
|
|
1013
|
+
dependencyGroups.map(async (dep) => {
|
|
1014
|
+
const { stdout } = await executeProcess({
|
|
1015
|
+
command: packageManager,
|
|
1016
|
+
args: ["audit", ...getNpmAuditOptions(dep)]
|
|
1017
|
+
});
|
|
1018
|
+
const auditResult = JSON.parse(stdout);
|
|
1019
|
+
return auditResultToAuditOutput(auditResult, dep, auditLevelMapping);
|
|
1020
|
+
})
|
|
1021
|
+
);
|
|
1022
|
+
const rejected = auditResults.filter(isPromiseRejectedResult);
|
|
1023
|
+
if (rejected.length > 0) {
|
|
1024
|
+
rejected.map((result) => {
|
|
1025
|
+
console.error(result.reason);
|
|
1026
|
+
});
|
|
1027
|
+
throw new Error(`JS Packages plugin: Running npm audit failed.`);
|
|
1028
|
+
}
|
|
1029
|
+
return auditResults.filter(isPromiseFulfilledResult).map((x) => x.value);
|
|
1030
|
+
}
|
|
1031
|
+
function getNpmAuditOptions(currentDep) {
|
|
1032
|
+
const flags = [
|
|
1033
|
+
`--include=${currentDep}`,
|
|
1034
|
+
...dependencyGroups.filter((dep) => dep !== currentDep).map((dep) => `--omit=${dep}`)
|
|
1035
|
+
];
|
|
1036
|
+
return [...flags, "--json", "--audit-level=none"];
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
// packages/plugin-js-packages/src/bin.ts
|
|
1040
|
+
await executeRunner();
|