@trustify-da/trustify-da-javascript-client 0.3.0-ea.b6d9c3f → 0.3.0-ea.b77d624

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 (43) hide show
  1. package/README.md +187 -1
  2. package/dist/package.json +6 -2
  3. package/dist/src/cli.js +48 -1
  4. package/dist/src/cyclone_dx_sbom.d.ts +13 -0
  5. package/dist/src/cyclone_dx_sbom.js +39 -1
  6. package/dist/src/index.d.ts +1 -0
  7. package/dist/src/index.js +8 -24
  8. package/dist/src/package_version.d.ts +8 -0
  9. package/dist/src/package_version.js +31 -0
  10. package/dist/src/providers/base_java.d.ts +53 -0
  11. package/dist/src/providers/base_java.js +64 -17
  12. package/dist/src/providers/base_javascript.d.ts +54 -0
  13. package/dist/src/providers/base_javascript.js +105 -3
  14. package/dist/src/providers/golang_gomodules.js +49 -7
  15. package/dist/src/providers/java_gradle.d.ts +48 -0
  16. package/dist/src/providers/java_gradle.js +196 -18
  17. package/dist/src/providers/java_maven.d.ts +28 -8
  18. package/dist/src/providers/java_maven.js +104 -10
  19. package/dist/src/providers/javascript_bun.d.ts +12 -0
  20. package/dist/src/providers/javascript_bun.js +42 -1
  21. package/dist/src/providers/javascript_npm.d.ts +13 -0
  22. package/dist/src/providers/javascript_npm.js +40 -1
  23. package/dist/src/providers/javascript_pnpm.d.ts +13 -0
  24. package/dist/src/providers/javascript_pnpm.js +47 -1
  25. package/dist/src/providers/javascript_yarn.d.ts +12 -0
  26. package/dist/src/providers/javascript_yarn.js +75 -2
  27. package/dist/src/providers/manifest.js +6 -3
  28. package/dist/src/providers/processors/yarn_berry_processor.d.ts +5 -1
  29. package/dist/src/providers/processors/yarn_berry_processor.js +3 -2
  30. package/dist/src/providers/processors/yarn_classic_processor.d.ts +5 -1
  31. package/dist/src/providers/processors/yarn_classic_processor.js +8 -6
  32. package/dist/src/providers/requirements_parser.js +1 -1
  33. package/dist/src/providers/rust_cargo.js +70 -29
  34. package/dist/src/remediate.d.ts +21 -0
  35. package/dist/src/remediate.js +149 -0
  36. package/dist/src/remediation.d.ts +27 -3
  37. package/dist/src/remediation.js +135 -20
  38. package/dist/src/remediation_report.d.ts +40 -0
  39. package/dist/src/remediation_report.js +159 -0
  40. package/dist/src/sbom.d.ts +11 -0
  41. package/dist/src/sbom.js +10 -0
  42. package/dist/src/tools.js +24 -1
  43. package/package.json +7 -3
@@ -0,0 +1,149 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import analysis from './analysis.js';
4
+ import { availableProviders, match } from './provider.js';
5
+ import { extractRemediations } from './remediation.js';
6
+ import { generateReport } from './remediation_report.js';
7
+ import { updateMavenVersions } from './updaters/maven_updater.js';
8
+ import { updateTomlVersions } from './updaters/toml_updater.js';
9
+ import { selectTrustifyDABackend } from './index.js';
10
+ // Mirrors DEFAULT_WORKSPACE_DISCOVERY_IGNORE in workspace.js
11
+ const SKIP_DIRS = new Set(['node_modules', '.git']);
12
+ const MANIFEST_TYPES = [
13
+ {
14
+ test: (basename) => basename === 'pom.xml',
15
+ updater: updateMavenVersions,
16
+ label: 'maven',
17
+ },
18
+ {
19
+ test: (basename) => basename.endsWith('.versions.toml') || basename === 'libs.versions.toml',
20
+ updater: updateTomlVersions,
21
+ label: 'toml',
22
+ },
23
+ ];
24
+ /**
25
+ * Discovers supported manifest files recursively within a directory.
26
+ * @param {string} dirPath - absolute path to the directory
27
+ * @returns {string[]} array of absolute paths to supported manifest files
28
+ */
29
+ function discoverManifests(dirPath) {
30
+ const manifests = [];
31
+ function walk(dir) {
32
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
33
+ for (const entry of entries) {
34
+ if (SKIP_DIRS.has(entry.name)) {
35
+ continue;
36
+ }
37
+ const fullPath = path.join(dir, entry.name);
38
+ if (entry.isDirectory()) {
39
+ walk(fullPath);
40
+ }
41
+ else if (getManifestType(entry.name)) {
42
+ manifests.push(fullPath);
43
+ }
44
+ }
45
+ }
46
+ walk(dirPath);
47
+ return manifests;
48
+ }
49
+ /**
50
+ * Returns the manifest type descriptor for a given filename, or null if unsupported.
51
+ * @param {string} basename - the file name to check
52
+ * @returns {{test: function, updater: function, label: string}|null}
53
+ */
54
+ function getManifestType(basename) {
55
+ return MANIFEST_TYPES.find(t => t.test(basename)) || null;
56
+ }
57
+ /**
58
+ * Orchestrates the full remediation pipeline for a single manifest or directory:
59
+ * discover manifests → scan via DA backend → extract remediations → apply or preview.
60
+ *
61
+ * @param {string} targetPath - path to a manifest file or directory
62
+ * @param {object} [options]
63
+ * @param {boolean} [options.dryRun=false] - preview changes without modifying files (applies by default)
64
+ * @param {string} [options.providers] - comma-separated provider list
65
+ * @param {string} [options.sources] - comma-separated source list
66
+ * @param {'dependency'|'bundle'} [options.groupBy='dependency'] - report grouping strategy
67
+ * @returns {Promise<{exitCode: number, output: string}>}
68
+ */
69
+ export async function runRemediation(targetPath, options = {}) {
70
+ const { dryRun = false, providers, sources, groupBy = 'dependency' } = options;
71
+ const resolvedPath = path.resolve(targetPath);
72
+ let manifestPaths;
73
+ let stat;
74
+ try {
75
+ stat = fs.statSync(resolvedPath);
76
+ }
77
+ catch {
78
+ throw new Error(`Path not found: ${resolvedPath}`);
79
+ }
80
+ if (stat.isDirectory()) {
81
+ manifestPaths = discoverManifests(resolvedPath);
82
+ if (manifestPaths.length === 0) {
83
+ return { exitCode: 0, output: 'No supported manifest files found.' };
84
+ }
85
+ }
86
+ else {
87
+ const basename = path.basename(resolvedPath);
88
+ if (!getManifestType(basename)) {
89
+ throw new Error(`Unsupported manifest type: ${basename}`);
90
+ }
91
+ manifestPaths = [resolvedPath];
92
+ }
93
+ const opts = {};
94
+ if (providers) {
95
+ opts.TRUSTIFY_DA_PROVIDERS = providers;
96
+ }
97
+ if (sources) {
98
+ opts.TRUSTIFY_DA_SOURCES = sources;
99
+ }
100
+ const url = selectTrustifyDABackend(opts);
101
+ const allRemediations = [];
102
+ const appliedFiles = [];
103
+ for (const manifestPath of manifestPaths) {
104
+ const basename = path.basename(manifestPath);
105
+ const manifestType = getManifestType(basename);
106
+ if (!manifestType) {
107
+ continue;
108
+ }
109
+ let provider;
110
+ try {
111
+ provider = match(manifestPath, availableProviders, opts);
112
+ }
113
+ catch {
114
+ continue;
115
+ }
116
+ const analysisReport = await analysis.requestStack(provider, manifestPath, url, false, opts);
117
+ const remediations = extractRemediations(analysisReport, {
118
+ providerPriority: providers ? providers.split(',').map(p => p.trim()).filter(Boolean) : undefined,
119
+ });
120
+ if (remediations.length === 0) {
121
+ continue;
122
+ }
123
+ allRemediations.push(...remediations);
124
+ if (!dryRun) {
125
+ const content = fs.readFileSync(manifestPath, 'utf-8');
126
+ const versionChanges = remediations.map(r => ({
127
+ groupId: r.groupId,
128
+ artifactId: r.artifactId,
129
+ newVersion: r.fixedInVersion,
130
+ }));
131
+ const result = manifestType.updater(content, versionChanges);
132
+ if (result.applied.length > 0) {
133
+ fs.writeFileSync(manifestPath, result.content, 'utf-8');
134
+ appliedFiles.push(manifestPath);
135
+ }
136
+ }
137
+ }
138
+ if (allRemediations.length === 0) {
139
+ return { exitCode: 0, output: 'No remediations found.' };
140
+ }
141
+ const report = generateReport(allRemediations, { groupBy });
142
+ if (dryRun) {
143
+ return { exitCode: 2, output: report };
144
+ }
145
+ const summary = appliedFiles.length > 0
146
+ ? `Updated ${appliedFiles.length} file(s):\n${appliedFiles.map(f => ` ${f}`).join('\n')}\n\n${report}`
147
+ : report;
148
+ return { exitCode: 0, output: summary };
149
+ }
@@ -2,19 +2,22 @@
2
2
  * Extracts actionable remediation instructions from a DA AnalysisReport response.
3
3
  *
4
4
  * Walks the provider/source/dependency/issue tree, collects fixedIn and trustedContent
5
- * remediation data, applies provider priority resolution, and for the same dependency
6
- * affected by multiple CVEs selects the highest fixedIn version from the highest-priority
7
- * provider. Dependencies with no remediation data are skipped.
5
+ * remediation data, applies provider priority resolution, and uses the configured
6
+ * version selection strategy to resolve conflicts. Dependencies with no remediation
7
+ * data are skipped.
8
8
  *
9
9
  * @param {object} analysisReport - raw DA AnalysisReport JSON response
10
10
  * @param {object} [options] - extraction options
11
11
  * @param {string[]} [options.providerPriority] - provider names in descending priority order.
12
12
  * The first entry has the highest priority. Providers not listed share the lowest priority.
13
13
  * When omitted or empty, all providers are treated equally and the highest fix version wins.
14
+ * @param {object} [options.versionStrategy] - version selection strategy with selectVersion
15
+ * and resolveConflict methods. Defaults to closestCoverageStrategy.
14
16
  * @returns {Array<{purl: string, groupId: string, artifactId: string, currentVersion: string, fixedInVersion: string, fixedInPurl: string, provider: string, source: string, advisories: Array<{id: string, url: string}>, severity: string, cves: string[]}>}
15
17
  */
16
18
  export function extractRemediations(analysisReport: object, options?: {
17
19
  providerPriority?: string[] | undefined;
20
+ versionStrategy?: object | undefined;
18
21
  }): Array<{
19
22
  purl: string;
20
23
  groupId: string;
@@ -31,3 +34,24 @@ export function extractRemediations(analysisReport: object, options?: {
31
34
  severity: string;
32
35
  cves: string[];
33
36
  }>;
37
+ /**
38
+ * Version selection strategy that prefers the closest compatible version
39
+ * within the same major version stream. Falls back to the lowest cross-major
40
+ * version when no same-major option exists.
41
+ * @type {{selectVersion: function(string[], string): string, resolveConflict: function(object, object): string}}
42
+ */
43
+ export const closestCoverageStrategy: {
44
+ selectVersion: (arg0: string[], arg1: string) => string;
45
+ resolveConflict: (arg0: object, arg1: object) => string;
46
+ };
47
+ /**
48
+ * Version selection strategy that always picks the highest version regardless
49
+ * of major version distance. Guarantees maximum CVE coverage but may produce
50
+ * large version jumps. This is the original behavior before pluggable strategies.
51
+ * @type {{selectVersion: function(string[], string): string, resolveConflict: function(object, object): string}}
52
+ */
53
+ export const highestStrategy: {
54
+ selectVersion: (arg0: string[], arg1: string) => string;
55
+ resolveConflict: (arg0: object, arg1: object) => string;
56
+ };
57
+ export const SEVERITY_ORDER: string[];
@@ -1,17 +1,85 @@
1
1
  import { PackageURL } from 'packageurl-js';
2
+ /**
3
+ * Extracts the major version segment from a version string.
4
+ * @param {string} version
5
+ * @returns {string} the first dot-separated segment
6
+ */
7
+ function getMajorVersion(version) {
8
+ return version.split('.')[0] || '';
9
+ }
10
+ /**
11
+ * Version selection strategy that prefers the closest compatible version
12
+ * within the same major version stream. Falls back to the lowest cross-major
13
+ * version when no same-major option exists.
14
+ * @type {{selectVersion: function(string[], string): string, resolveConflict: function(object, object): string}}
15
+ */
16
+ export const closestCoverageStrategy = {
17
+ selectVersion(fixedInVersions, currentVersion) {
18
+ const currentMajor = getMajorVersion(currentVersion);
19
+ const sameMajor = fixedInVersions.filter(v => getMajorVersion(v) === currentMajor);
20
+ if (sameMajor.length > 0) {
21
+ return sameMajor.sort((a, b) => compareVersions(b, a))[0];
22
+ }
23
+ return fixedInVersions.sort((a, b) => compareVersions(a, b))[0];
24
+ },
25
+ resolveConflict(existing, candidate) {
26
+ if (existing._fromTrustedContent && !candidate._fromTrustedContent) {
27
+ return 'existing';
28
+ }
29
+ if (!existing._fromTrustedContent && candidate._fromTrustedContent) {
30
+ return 'candidate';
31
+ }
32
+ const currentMajor = getMajorVersion(existing.currentVersion);
33
+ const existingSameMajor = getMajorVersion(existing.fixedInVersion) === currentMajor;
34
+ const candidateSameMajor = getMajorVersion(candidate.fixedInVersion) === currentMajor;
35
+ if (existingSameMajor && !candidateSameMajor) {
36
+ return 'existing';
37
+ }
38
+ if (!existingSameMajor && candidateSameMajor) {
39
+ return 'candidate';
40
+ }
41
+ return compareVersions(candidate.fixedInVersion, existing.fixedInVersion) > 0
42
+ ? 'candidate'
43
+ : 'existing';
44
+ },
45
+ };
46
+ /**
47
+ * Version selection strategy that always picks the highest version regardless
48
+ * of major version distance. Guarantees maximum CVE coverage but may produce
49
+ * large version jumps. This is the original behavior before pluggable strategies.
50
+ * @type {{selectVersion: function(string[], string): string, resolveConflict: function(object, object): string}}
51
+ */
52
+ export const highestStrategy = {
53
+ selectVersion(fixedInVersions) {
54
+ return fixedInVersions.sort((a, b) => compareVersions(b, a))[0];
55
+ },
56
+ resolveConflict(existing, candidate) {
57
+ if (existing._fromTrustedContent && !candidate._fromTrustedContent) {
58
+ return 'existing';
59
+ }
60
+ if (!existing._fromTrustedContent && candidate._fromTrustedContent) {
61
+ return 'candidate';
62
+ }
63
+ return compareVersions(candidate.fixedInVersion, existing.fixedInVersion) > 0
64
+ ? 'candidate'
65
+ : 'existing';
66
+ },
67
+ };
2
68
  /**
3
69
  * Extracts actionable remediation instructions from a DA AnalysisReport response.
4
70
  *
5
71
  * Walks the provider/source/dependency/issue tree, collects fixedIn and trustedContent
6
- * remediation data, applies provider priority resolution, and for the same dependency
7
- * affected by multiple CVEs selects the highest fixedIn version from the highest-priority
8
- * provider. Dependencies with no remediation data are skipped.
72
+ * remediation data, applies provider priority resolution, and uses the configured
73
+ * version selection strategy to resolve conflicts. Dependencies with no remediation
74
+ * data are skipped.
9
75
  *
10
76
  * @param {object} analysisReport - raw DA AnalysisReport JSON response
11
77
  * @param {object} [options] - extraction options
12
78
  * @param {string[]} [options.providerPriority] - provider names in descending priority order.
13
79
  * The first entry has the highest priority. Providers not listed share the lowest priority.
14
80
  * When omitted or empty, all providers are treated equally and the highest fix version wins.
81
+ * @param {object} [options.versionStrategy] - version selection strategy with selectVersion
82
+ * and resolveConflict methods. Defaults to closestCoverageStrategy.
15
83
  * @returns {Array<{purl: string, groupId: string, artifactId: string, currentVersion: string, fixedInVersion: string, fixedInPurl: string, provider: string, source: string, advisories: Array<{id: string, url: string}>, severity: string, cves: string[]}>}
16
84
  */
17
85
  export function extractRemediations(analysisReport, options = {}) {
@@ -19,14 +87,19 @@ export function extractRemediations(analysisReport, options = {}) {
19
87
  return [];
20
88
  }
21
89
  const priorityMap = buildPriorityMap(options.providerPriority);
90
+ const strategy = options.versionStrategy || closestCoverageStrategy;
22
91
  const remediationsByDep = new Map();
23
92
  const rankByDep = new Map();
24
93
  for (const [providerName, providerReport] of Object.entries(analysisReport.providers)) {
25
94
  const providerRank = priorityMap.get(providerName) ?? 0;
26
- extractFromSources(providerReport, providerName, providerRank, remediationsByDep, rankByDep);
95
+ extractFromSources(providerReport, providerName, providerRank, remediationsByDep, rankByDep, strategy);
27
96
  extractFromRecommendations(providerReport, providerName, providerRank, remediationsByDep, rankByDep);
28
97
  }
29
98
  return Array.from(remediationsByDep.values())
99
+ .map((entry) => {
100
+ delete entry._fromTrustedContent;
101
+ return entry;
102
+ })
30
103
  .sort((a, b) => a.purl.localeCompare(b.purl));
31
104
  }
32
105
  /**
@@ -52,8 +125,9 @@ function buildPriorityMap(providerPriority) {
52
125
  * @param {number} providerRank - numeric priority rank for this provider
53
126
  * @param {Map<string, object>} remediationsByDep - accumulator keyed by dependency PURL
54
127
  * @param {Map<string, number>} rankByDep - tracks current winning rank per dependency
128
+ * @param {object} strategy - version selection strategy
55
129
  */
56
- function extractFromSources(providerReport, providerName, providerRank, remediationsByDep, rankByDep) {
130
+ function extractFromSources(providerReport, providerName, providerRank, remediationsByDep, rankByDep, strategy) {
57
131
  if (!providerReport.sources) {
58
132
  return;
59
133
  }
@@ -66,7 +140,7 @@ function extractFromSources(providerReport, providerName, providerRank, remediat
66
140
  continue;
67
141
  }
68
142
  for (const issue of dep.issues) {
69
- processIssueRemediation(issue, dep, providerName, sourceName, providerRank, remediationsByDep, rankByDep);
143
+ processIssueRemediation(issue, dep, providerName, sourceName, providerRank, remediationsByDep, rankByDep, strategy);
70
144
  }
71
145
  }
72
146
  }
@@ -80,20 +154,28 @@ function extractFromSources(providerReport, providerName, providerRank, remediat
80
154
  * @param {number} providerRank
81
155
  * @param {Map<string, object>} remediationsByDep
82
156
  * @param {Map<string, number>} rankByDep
157
+ * @param {object} strategy - version selection strategy
83
158
  */
84
- function processIssueRemediation(issue, dep, providerName, sourceName, providerRank, remediationsByDep, rankByDep) {
85
- const fixedInPurl = getFixedInPurl(issue);
86
- if (!fixedInPurl) {
87
- return;
88
- }
159
+ function processIssueRemediation(issue, dep, providerName, sourceName, providerRank, remediationsByDep, rankByDep, strategy) {
89
160
  const depPurl = dep.ref;
90
161
  if (!depPurl) {
91
162
  return;
92
163
  }
93
164
  let parsedDep;
94
- let parsedFix;
95
165
  try {
96
166
  parsedDep = PackageURL.fromString(depPurl);
167
+ }
168
+ catch {
169
+ return;
170
+ }
171
+ const currentVersion = parsedDep.version || '';
172
+ const fixedInPurl = getFixedInPurl(issue, depPurl, strategy, currentVersion);
173
+ if (!fixedInPurl) {
174
+ return;
175
+ }
176
+ const isTrustedContent = !!(issue.remediation && issue.remediation.trustedContent && issue.remediation.trustedContent.ref);
177
+ let parsedFix;
178
+ try {
97
179
  parsedFix = PackageURL.fromString(fixedInPurl);
98
180
  }
99
181
  catch {
@@ -112,7 +194,7 @@ function processIssueRemediation(issue, dep, providerName, sourceName, providerR
112
194
  purl: depPurl,
113
195
  groupId: parsedDep.namespace || '',
114
196
  artifactId: parsedDep.name,
115
- currentVersion: parsedDep.version || '',
197
+ currentVersion,
116
198
  fixedInVersion,
117
199
  fixedInPurl,
118
200
  provider: providerName,
@@ -120,6 +202,7 @@ function processIssueRemediation(issue, dep, providerName, sourceName, providerR
120
202
  advisories,
121
203
  severity: severity.toUpperCase(),
122
204
  cves: cveId ? [cveId] : [],
205
+ _fromTrustedContent: isTrustedContent,
123
206
  });
124
207
  rankByDep.set(depPurl, providerRank);
125
208
  return;
@@ -135,14 +218,17 @@ function processIssueRemediation(issue, dep, providerName, sourceName, providerR
135
218
  existing.provider = providerName;
136
219
  existing.source = sourceName;
137
220
  existing.severity = higherSeverity(existing.severity, severity);
221
+ existing._fromTrustedContent = isTrustedContent;
138
222
  rankByDep.set(depPurl, providerRank);
139
223
  }
140
224
  else if (providerRank === existingRank) {
141
- if (compareVersions(fixedInVersion, existing.fixedInVersion) > 0) {
225
+ const winner = strategy.resolveConflict({ fixedInVersion: existing.fixedInVersion, _fromTrustedContent: existing._fromTrustedContent, currentVersion }, { fixedInVersion, _fromTrustedContent: isTrustedContent, currentVersion });
226
+ if (winner === 'candidate') {
142
227
  existing.fixedInVersion = fixedInVersion;
143
228
  existing.fixedInPurl = fixedInPurl;
144
229
  existing.provider = providerName;
145
230
  existing.source = sourceName;
231
+ existing._fromTrustedContent = isTrustedContent;
146
232
  }
147
233
  existing.severity = higherSeverity(existing.severity, severity);
148
234
  }
@@ -220,18 +306,45 @@ function extractFromRecommendations(providerReport, providerName, providerRank,
220
306
  }
221
307
  /**
222
308
  * Gets the fixedIn PURL from an issue's remediation, preferring trustedContent.
309
+ * When fixedIn is an array of version strings (not PURLs), uses the strategy's
310
+ * selectVersion to pick the best candidate and constructs a PURL from the dependency ref.
223
311
  * @param {object} issue
312
+ * @param {string} depPurl - the dependency PURL, used to construct fixedIn PURLs from version strings
313
+ * @param {object} strategy - version selection strategy
314
+ * @param {string} currentVersion - the dependency's current version
224
315
  * @returns {string|undefined}
225
316
  */
226
- function getFixedInPurl(issue) {
317
+ function getFixedInPurl(issue, depPurl, strategy, currentVersion) {
227
318
  if (!issue.remediation) {
228
319
  return undefined;
229
320
  }
230
321
  if (issue.remediation.trustedContent && issue.remediation.trustedContent.ref) {
231
322
  return issue.remediation.trustedContent.ref;
232
323
  }
233
- if (issue.remediation.fixedIn) {
234
- return issue.remediation.fixedIn;
324
+ const fixedIn = issue.remediation.fixedIn;
325
+ if (!fixedIn) {
326
+ return undefined;
327
+ }
328
+ if (typeof fixedIn === 'string') {
329
+ return fixedIn;
330
+ }
331
+ if (Array.isArray(fixedIn) && fixedIn.length > 0) {
332
+ const version = fixedIn.length > 1
333
+ ? strategy.selectVersion(fixedIn, currentVersion)
334
+ : fixedIn[0];
335
+ if (typeof version === 'string' && version.startsWith('pkg:')) {
336
+ return version;
337
+ }
338
+ if (typeof version === 'string' && depPurl) {
339
+ try {
340
+ const parsed = PackageURL.fromString(depPurl);
341
+ parsed.version = version;
342
+ return parsed.toString();
343
+ }
344
+ catch {
345
+ return undefined;
346
+ }
347
+ }
235
348
  }
236
349
  return undefined;
237
350
  }
@@ -294,18 +407,20 @@ function compareVersions(a, b) {
294
407
  const numB = Number(segB);
295
408
  if (Number.isFinite(numA) && Number.isFinite(numB)) {
296
409
  const diff = numA - numB;
297
- if (diff !== 0)
410
+ if (diff !== 0) {
298
411
  return diff;
412
+ }
299
413
  }
300
414
  else {
301
415
  const cmp = segA.localeCompare(segB);
302
- if (cmp !== 0)
416
+ if (cmp !== 0) {
303
417
  return cmp;
418
+ }
304
419
  }
305
420
  }
306
421
  return 0;
307
422
  }
308
- const SEVERITY_ORDER = ['UNKNOWN', 'LOW', 'MEDIUM', 'HIGH', 'CRITICAL'];
423
+ export const SEVERITY_ORDER = ['UNKNOWN', 'LOW', 'MEDIUM', 'HIGH', 'CRITICAL'];
309
424
  /**
310
425
  * Returns the higher of two severity strings, normalized to uppercase.
311
426
  * @param {string} a
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Generates a formatted report from an array of remediation entries.
3
+ *
4
+ * @param {Array<{purl: string, groupId: string, artifactId: string, currentVersion: string,
5
+ * fixedInVersion: string, fixedInPurl: string, provider: string, source: string,
6
+ * advisories: Array<{id: string, url: string}>, severity: string, cves: string[]}>} remediations
7
+ * @param {object} [options]
8
+ * @param {'dependency'|'bundle'} [options.groupBy='dependency'] - grouping strategy
9
+ * @param {'markdown'|'json'} [options.format='markdown'] - output format
10
+ * @param {boolean} [options.dryRun=false] - when true, produces tabular summary
11
+ * @returns {string}
12
+ */
13
+ export function generateReport(remediations: Array<{
14
+ purl: string;
15
+ groupId: string;
16
+ artifactId: string;
17
+ currentVersion: string;
18
+ fixedInVersion: string;
19
+ fixedInPurl: string;
20
+ provider: string;
21
+ source: string;
22
+ advisories: Array<{
23
+ id: string;
24
+ url: string;
25
+ }>;
26
+ severity: string;
27
+ cves: string[];
28
+ }>, options?: {
29
+ groupBy?: "bundle" | "dependency" | undefined;
30
+ format?: "markdown" | "json" | undefined;
31
+ dryRun?: boolean | undefined;
32
+ }): string;
33
+ /**
34
+ * Generates a deterministic deduplication key for a remediation entry.
35
+ * Suitable for checking existing PR titles or branch names.
36
+ *
37
+ * @param {object} remediation - a single remediation entry
38
+ * @returns {string} stable key in the form `groupId:artifactId:newVersion`
39
+ */
40
+ export function generateDeduplicationKey(remediation: object): string;
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Report generator that transforms remediation extractor output into structured
3
+ * markdown for PR bodies, CLI dry-run output, and JSON.
4
+ */
5
+ import { SEVERITY_ORDER } from './remediation.js';
6
+ /**
7
+ * Generates a formatted report from an array of remediation entries.
8
+ *
9
+ * @param {Array<{purl: string, groupId: string, artifactId: string, currentVersion: string,
10
+ * fixedInVersion: string, fixedInPurl: string, provider: string, source: string,
11
+ * advisories: Array<{id: string, url: string}>, severity: string, cves: string[]}>} remediations
12
+ * @param {object} [options]
13
+ * @param {'dependency'|'bundle'} [options.groupBy='dependency'] - grouping strategy
14
+ * @param {'markdown'|'json'} [options.format='markdown'] - output format
15
+ * @param {boolean} [options.dryRun=false] - when true, produces tabular summary
16
+ * @returns {string}
17
+ */
18
+ export function generateReport(remediations, options = {}) {
19
+ const { groupBy = 'dependency', format = 'markdown', dryRun = false } = options;
20
+ if (!remediations || remediations.length === 0) {
21
+ return format === 'json' ? '[]' : 'No remediations found.';
22
+ }
23
+ if (format === 'json') {
24
+ return JSON.stringify(remediations, null, '\t');
25
+ }
26
+ if (dryRun) {
27
+ return generateDryRunReport(remediations);
28
+ }
29
+ if (groupBy === 'bundle') {
30
+ return generateBundledReport(remediations);
31
+ }
32
+ return generatePerDependencyReport(remediations);
33
+ }
34
+ /**
35
+ * Generates a per-dependency markdown report with one section per remediation entry.
36
+ * @param {Array<object>} remediations
37
+ * @returns {string}
38
+ */
39
+ function generatePerDependencyReport(remediations) {
40
+ const sections = remediations.map(rem => {
41
+ const depName = rem.groupId
42
+ ? `${rem.groupId}:${rem.artifactId}`
43
+ : rem.artifactId;
44
+ const lines = [
45
+ `## Security Update: ${depName} ${rem.currentVersion} → ${rem.fixedInVersion}`,
46
+ '',
47
+ `**Provider:** ${rem.provider} | **Source:** ${rem.source}`,
48
+ '',
49
+ ];
50
+ if (rem.cves && rem.cves.length > 0) {
51
+ lines.push('### Vulnerabilities resolved');
52
+ lines.push('');
53
+ lines.push('| CVE | Severity | Advisory |');
54
+ lines.push('| --- | --- | --- |');
55
+ const advisoryLinks = formatAdvisoryLinks(rem.advisories);
56
+ for (const cve of rem.cves) {
57
+ lines.push(`| ${cve} | ${rem.severity} | ${advisoryLinks} |`);
58
+ }
59
+ }
60
+ return lines.join('\n');
61
+ });
62
+ return sections.join('\n\n');
63
+ }
64
+ /**
65
+ * Generates a bundled markdown report grouping all remediations by severity.
66
+ * @param {Array<object>} remediations
67
+ * @returns {string}
68
+ */
69
+ function generateBundledReport(remediations) {
70
+ const lines = ['# Security Update Summary', ''];
71
+ const bySeverity = groupBySeverity(remediations);
72
+ for (const severity of [...SEVERITY_ORDER].reverse()) {
73
+ const group = bySeverity.get(severity);
74
+ if (!group || group.length === 0) {
75
+ continue;
76
+ }
77
+ lines.push(`## ${severity}`);
78
+ lines.push('');
79
+ lines.push('| Dependency | Current | Fixed | Provider | CVEs | Advisory |');
80
+ lines.push('| --- | --- | --- | --- | --- | --- |');
81
+ for (const rem of group) {
82
+ const depName = rem.groupId
83
+ ? `${rem.groupId}:${rem.artifactId}`
84
+ : rem.artifactId;
85
+ const cves = (rem.cves || []).join(', ');
86
+ const advisoryLinks = formatAdvisoryLinks(rem.advisories);
87
+ lines.push(`| ${depName} | ${rem.currentVersion} | ${rem.fixedInVersion}`
88
+ + ` | ${rem.provider} | ${cves} | ${advisoryLinks} |`);
89
+ }
90
+ lines.push('');
91
+ }
92
+ return lines.join('\n').trimEnd();
93
+ }
94
+ /**
95
+ * Generates a tabular dry-run summary of proposed changes.
96
+ * @param {Array<object>} remediations
97
+ * @returns {string}
98
+ */
99
+ function generateDryRunReport(remediations) {
100
+ const lines = [
101
+ 'Proposed dependency updates:',
102
+ '',
103
+ '| Dependency | Current | Fixed | Severity | Provider |',
104
+ '| --- | --- | --- | --- | --- |',
105
+ ];
106
+ for (const rem of remediations) {
107
+ const depName = rem.groupId
108
+ ? `${rem.groupId}:${rem.artifactId}`
109
+ : rem.artifactId;
110
+ lines.push(`| ${depName} | ${rem.currentVersion} | ${rem.fixedInVersion}`
111
+ + ` | ${rem.severity} | ${rem.provider} |`);
112
+ }
113
+ return lines.join('\n');
114
+ }
115
+ /**
116
+ * Groups remediations by their severity.
117
+ * @param {Array<object>} remediations
118
+ * @returns {Map<string, Array<object>>}
119
+ */
120
+ function groupBySeverity(remediations) {
121
+ const map = new Map();
122
+ for (const severity of SEVERITY_ORDER) {
123
+ map.set(severity, []);
124
+ }
125
+ for (const rem of remediations) {
126
+ const sev = rem.severity || 'UNKNOWN';
127
+ if (!map.has(sev)) {
128
+ map.set(sev, []);
129
+ }
130
+ map.get(sev).push(rem);
131
+ }
132
+ return map;
133
+ }
134
+ /**
135
+ * Formats advisory entries into markdown links or plain text.
136
+ * @param {Array<{id: string, url: string}>} advisories
137
+ * @returns {string}
138
+ */
139
+ function formatAdvisoryLinks(advisories) {
140
+ if (!advisories || advisories.length === 0) {
141
+ return '-';
142
+ }
143
+ return advisories
144
+ .map(adv => adv.url ? `[${adv.id}](${adv.url})` : adv.id)
145
+ .join(', ');
146
+ }
147
+ /**
148
+ * Generates a deterministic deduplication key for a remediation entry.
149
+ * Suitable for checking existing PR titles or branch names.
150
+ *
151
+ * @param {object} remediation - a single remediation entry
152
+ * @returns {string} stable key in the form `groupId:artifactId:newVersion`
153
+ */
154
+ export function generateDeduplicationKey(remediation) {
155
+ const group = remediation.groupId || '';
156
+ const artifact = remediation.artifactId || '';
157
+ const version = remediation.fixedInVersion || '';
158
+ return `${group}:${artifact}:${version}`;
159
+ }