@trustify-da/trustify-da-javascript-client 0.3.0-ea.320ec49 → 0.3.0-ea.329b3cf

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 (73) hide show
  1. package/README.md +2 -2
  2. package/dist/package.json +25 -22
  3. package/dist/src/analysis.d.ts +14 -7
  4. package/dist/src/analysis.js +29 -13
  5. package/dist/src/cli.js +58 -1
  6. package/dist/src/cyclone_dx_sbom.d.ts +7 -1
  7. package/dist/src/cyclone_dx_sbom.js +29 -8
  8. package/dist/src/index.d.ts +74 -11
  9. package/dist/src/index.js +78 -7
  10. package/dist/src/license/index.d.ts +3 -3
  11. package/dist/src/license/index.js +4 -1
  12. package/dist/src/license/license_utils.js +4 -1
  13. package/dist/src/license/licenses_api.d.ts +2 -2
  14. package/dist/src/oci_image/images.d.ts +1 -1
  15. package/dist/src/oci_image/images.js +15 -1
  16. package/dist/src/oci_image/utils.d.ts +5 -5
  17. package/dist/src/provider.d.ts +4 -3
  18. package/dist/src/provider.js +6 -2
  19. package/dist/src/providers/base_java.d.ts +14 -12
  20. package/dist/src/providers/base_java.js +18 -44
  21. package/dist/src/providers/base_javascript.d.ts +20 -9
  22. package/dist/src/providers/base_javascript.js +10 -3
  23. package/dist/src/providers/base_pyproject.d.ts +15 -6
  24. package/dist/src/providers/base_pyproject.js +12 -4
  25. package/dist/src/providers/containerfile_parser.d.ts +5 -0
  26. package/dist/src/providers/containerfile_parser.js +20 -0
  27. package/dist/src/providers/golang_gomodules.d.ts +11 -1
  28. package/dist/src/providers/golang_gomodules.js +65 -8
  29. package/dist/src/providers/java_gradle.d.ts +19 -0
  30. package/dist/src/providers/java_gradle.js +116 -2
  31. package/dist/src/providers/java_gradle_groovy.d.ts +1 -1
  32. package/dist/src/providers/java_gradle_kotlin.d.ts +1 -1
  33. package/dist/src/providers/java_maven.d.ts +10 -2
  34. package/dist/src/providers/java_maven.js +165 -1
  35. package/dist/src/providers/javascript_bun.d.ts +10 -0
  36. package/dist/src/providers/javascript_bun.js +100 -0
  37. package/dist/src/providers/javascript_npm.d.ts +6 -0
  38. package/dist/src/providers/javascript_npm.js +21 -0
  39. package/dist/src/providers/javascript_pnpm.js +6 -2
  40. package/dist/src/providers/marker_evaluator.d.ts +14 -0
  41. package/dist/src/providers/marker_evaluator.js +191 -0
  42. package/dist/src/providers/oci_dockerfile.d.ts +51 -0
  43. package/dist/src/providers/oci_dockerfile.js +177 -0
  44. package/dist/src/providers/processors/yarn_berry_processor.d.ts +2 -2
  45. package/dist/src/providers/processors/yarn_berry_processor.js +6 -2
  46. package/dist/src/providers/processors/yarn_classic_processor.d.ts +2 -2
  47. package/dist/src/providers/python_controller.d.ts +5 -1
  48. package/dist/src/providers/python_controller.js +69 -8
  49. package/dist/src/providers/python_pip.d.ts +5 -0
  50. package/dist/src/providers/python_pip.js +5 -5
  51. package/dist/src/providers/python_pip_pyproject.js +3 -1
  52. package/dist/src/providers/python_poetry.d.ts +64 -8
  53. package/dist/src/providers/python_poetry.js +139 -22
  54. package/dist/src/providers/python_uv.d.ts +20 -1
  55. package/dist/src/providers/python_uv.js +126 -3
  56. package/dist/src/providers/rust_cargo.d.ts +6 -2
  57. package/dist/src/providers/rust_cargo.js +31 -4
  58. package/dist/src/providers/tree-sitter-containerfile.wasm +0 -0
  59. package/dist/src/remediation.d.ts +34 -0
  60. package/dist/src/remediation.js +321 -0
  61. package/dist/src/remediation_report.d.ts +40 -0
  62. package/dist/src/remediation_report.js +159 -0
  63. package/dist/src/sbom.d.ts +7 -1
  64. package/dist/src/sbom.js +4 -2
  65. package/dist/src/tools.d.ts +28 -2
  66. package/dist/src/tools.js +58 -0
  67. package/dist/src/updaters/maven_updater.d.ts +26 -0
  68. package/dist/src/updaters/maven_updater.js +322 -0
  69. package/dist/src/updaters/toml_updater.d.ts +33 -0
  70. package/dist/src/updaters/toml_updater.js +244 -0
  71. package/dist/src/workspace.d.ts +9 -0
  72. package/dist/src/workspace.js +1 -1
  73. package/package.json +26 -23
@@ -1,8 +1,11 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import fg from 'fast-glob';
3
4
  import { parse as parseToml } from 'smol-toml';
4
5
  import { environmentVariableIsPopulated, getCustomPath, invokeCommand } from '../tools.js';
6
+ import { filterManifestPathsByDiscoveryIgnore, resolveWorkspaceDiscoveryIgnore, toManifestGlobPatterns } from '../workspace.js';
5
7
  import Base_pyproject from './base_pyproject.js';
8
+ import { evaluateMarker } from './marker_evaluator.js';
6
9
  import { getParser, getPinnedVersionQuery } from './requirements_parser.js';
7
10
  export default class Python_uv extends Base_pyproject {
8
11
  /** @returns {string} */
@@ -18,12 +21,54 @@ export default class Python_uv extends Base_pyproject {
18
21
  * @param {string} workspaceDir - workspace root (for resolving editable install paths)
19
22
  * @param {object} parsed - parsed pyproject.toml
20
23
  * @param {Object} opts
21
- * @returns {Promise<{directDeps: string[], graph: Map<string, {name: string, version: string, children: string[]}>}>}
24
+ * @returns {Promise<{directDeps: string[], graph: Map<string, import('./base_pyproject.js').GraphEntry>}>}
22
25
  */
23
26
  async _getDependencyData(manifestDir, workspaceDir, parsed, opts) {
24
27
  let projectName = this._getProjectName(parsed);
25
28
  let uvOutput = this._getUvExportOutput(manifestDir, opts);
26
- return this._parseUvExport(uvOutput, projectName, workspaceDir);
29
+ let { directDeps, graph } = await this._parseUvExport(uvOutput, projectName, workspaceDir);
30
+ await this._attachHashesFromLockFile(path.join(workspaceDir, 'uv.lock'), graph);
31
+ return { directDeps, graph };
32
+ }
33
+ /**
34
+ * Parse uv.lock and attach SHA-256 hashes to graph entries.
35
+ * @param {string} lockFilePath - path to uv.lock
36
+ * @param {Map<string, import('./base_pyproject.js').GraphEntry>} graph
37
+ */
38
+ async _attachHashesFromLockFile(lockFilePath, graph) {
39
+ let lockContent;
40
+ try {
41
+ lockContent = await fs.promises.readFile(lockFilePath, 'utf-8');
42
+ }
43
+ catch {
44
+ return;
45
+ }
46
+ let parsed;
47
+ try {
48
+ parsed = parseToml(lockContent);
49
+ }
50
+ catch {
51
+ return;
52
+ }
53
+ let packages = parsed.package;
54
+ if (!Array.isArray(packages)) {
55
+ return;
56
+ }
57
+ for (let pkg of packages) {
58
+ if (!pkg.name) {
59
+ continue;
60
+ }
61
+ let hashStr = pkg.sdist?.hash || pkg.wheels?.[0]?.hash;
62
+ if (!hashStr || !hashStr.startsWith('sha256:')) {
63
+ continue;
64
+ }
65
+ let key = this._canonicalize(pkg.name);
66
+ let entry = graph.get(key);
67
+ if (!entry || entry.hashes) {
68
+ continue;
69
+ }
70
+ entry.hashes = [{ alg: "SHA-256", content: hashStr.slice(7) }];
71
+ }
27
72
  }
28
73
  /**
29
74
  * Get the uv export output, either from env var or by running the command.
@@ -36,7 +81,7 @@ export default class Python_uv extends Base_pyproject {
36
81
  return Buffer.from(process.env['TRUSTIFY_DA_UV_EXPORT'], 'base64').toString('ascii');
37
82
  }
38
83
  let uvBin = getCustomPath('uv', opts);
39
- return invokeCommand(uvBin, ['export', '--format', 'requirements.txt', '--frozen', '--no-hashes'], { cwd: manifestDir }).toString();
84
+ return invokeCommand(uvBin, ['export', '--format', 'requirements.txt', '--frozen', '--no-hashes', '--no-dev', '--no-emit-project'], { cwd: manifestDir }).toString();
40
85
  }
41
86
  /**
42
87
  * Parse uv export output into a dependency graph using tree-sitter-requirements
@@ -70,6 +115,9 @@ export default class Python_uv extends Base_pyproject {
70
115
  let version = memberParsed.project?.version || memberParsed.tool?.poetry?.version;
71
116
  if (name && version) {
72
117
  let key = this._canonicalize(name);
118
+ if (key === canonProjectName) {
119
+ continue;
120
+ }
73
121
  currentPkg = { name, version, parents: new Set() };
74
122
  packages.set(key, currentPkg);
75
123
  collectingVia = false;
@@ -86,6 +134,16 @@ export default class Python_uv extends Base_pyproject {
86
134
  if (!nameNode) {
87
135
  continue;
88
136
  }
137
+ // Skip packages with non-matching PEP 508 markers, e.g. "pywin32==311 ; sys_platform == 'win32'"
138
+ let markerNode = child.children.find(c => c.type === 'marker_spec');
139
+ if (markerNode) {
140
+ let markerText = markerNode.text.replace(/^\s*;\s*/, '');
141
+ if (!evaluateMarker(markerText)) {
142
+ currentPkg = null;
143
+ collectingVia = false;
144
+ continue;
145
+ }
146
+ }
89
147
  let name = nameNode.text;
90
148
  let version = null;
91
149
  let versionMatches = pinnedVersionQuery.matches(child);
@@ -144,3 +202,68 @@ export default class Python_uv extends Base_pyproject {
144
202
  return { directDeps, graph };
145
203
  }
146
204
  }
205
+ const DEFAULT_UV_DISCOVERY_IGNORE = [
206
+ '**/__pycache__/**',
207
+ '**/.venv/**',
208
+ ];
209
+ /**
210
+ * Discover all pyproject.toml manifest paths in a uv workspace.
211
+ * Parses `[tool.uv.workspace]` from root pyproject.toml and glob-expands member patterns.
212
+ *
213
+ * @param {string} workspaceRoot - Absolute or relative path to workspace root (must contain pyproject.toml and uv.lock)
214
+ * @param {{ workspaceDiscoveryIgnore?: string[], TRUSTIFY_DA_WORKSPACE_DISCOVERY_IGNORE?: string, [key: string]: unknown }} [opts={}]
215
+ * @returns {Promise<string[]>} Paths to pyproject.toml files (absolute)
216
+ */
217
+ export async function discoverUvWorkspaceMembers(workspaceRoot, opts = {}) {
218
+ const root = path.resolve(workspaceRoot);
219
+ const rootPyproject = path.join(root, 'pyproject.toml');
220
+ const uvLock = path.join(root, 'uv.lock');
221
+ if (!fs.existsSync(rootPyproject) || !fs.existsSync(uvLock)) {
222
+ return [];
223
+ }
224
+ let parsed;
225
+ try {
226
+ parsed = parseToml(fs.readFileSync(rootPyproject, 'utf-8'));
227
+ }
228
+ catch {
229
+ return [];
230
+ }
231
+ const workspaceConfig = parsed?.tool?.uv?.workspace;
232
+ if (!workspaceConfig) {
233
+ return [];
234
+ }
235
+ const memberPatterns = workspaceConfig.members;
236
+ if (!Array.isArray(memberPatterns) || memberPatterns.length === 0) {
237
+ return [];
238
+ }
239
+ const excludePatterns = Array.isArray(workspaceConfig.exclude) ? workspaceConfig.exclude : [];
240
+ const excludeGlobs = excludePatterns
241
+ .filter(p => typeof p === 'string' && p.trim())
242
+ .map(p => `${p.trim()}/pyproject.toml`);
243
+ const ignorePatterns = [...resolveWorkspaceDiscoveryIgnore(opts), ...DEFAULT_UV_DISCOVERY_IGNORE];
244
+ const globOpts = {
245
+ cwd: root,
246
+ absolute: true,
247
+ onlyFiles: true,
248
+ ignore: [...ignorePatterns, ...excludeGlobs],
249
+ followSymbolicLinks: false,
250
+ };
251
+ const patterns = toManifestGlobPatterns(memberPatterns.filter(p => typeof p === 'string'), 'pyproject.toml');
252
+ const manifestPaths = await fg(patterns, globOpts);
253
+ if (!manifestPaths.includes(rootPyproject) && hasProjectMetadata(parsed)) {
254
+ manifestPaths.unshift(rootPyproject);
255
+ }
256
+ return filterManifestPathsByDiscoveryIgnore(manifestPaths, root, ignorePatterns);
257
+ }
258
+ /**
259
+ * @param {import('smol-toml').TomlTable} parsedPyProject
260
+ * @returns {boolean}
261
+ */
262
+ function hasProjectMetadata(parsedPyProject) {
263
+ try {
264
+ return typeof parsedPyProject?.project?.name === 'string' && parsedPyProject.project.name.trim() !== '';
265
+ }
266
+ catch {
267
+ return false;
268
+ }
269
+ }
@@ -4,9 +4,10 @@ declare namespace _default {
4
4
  export { provideComponent };
5
5
  export { provideStack };
6
6
  export { readLicenseFromManifest };
7
+ export function packageManagerName(): string;
7
8
  }
8
9
  export default _default;
9
- export type Provided = import("../provider").Provided;
10
+ export type Provided = any;
10
11
  /**
11
12
  * @param {string} manifestName - the subject manifest name-type
12
13
  * @returns {boolean} - return true if `Cargo.toml` is the manifest name-type
@@ -46,7 +47,10 @@ declare function provideStack(manifest: string, opts?: {}): Provided;
46
47
  * Read project license from Cargo.toml, with fallback to LICENSE file.
47
48
  * Supports the `license` field under `[package]` (single crate / workspace
48
49
  * with root) and under `[workspace.package]` (virtual workspaces).
50
+ * When a member crate uses `license = { workspace = true }`, the actual
51
+ * license is resolved from the workspace root Cargo.toml.
49
52
  * @param {string} manifestPath - path to Cargo.toml
53
+ * @param {object} [metadata] - cargo metadata output (needed for workspace license resolution)
50
54
  * @returns {string|null} SPDX identifier or null
51
55
  */
52
- declare function readLicenseFromManifest(manifestPath: string): string | null;
56
+ declare function readLicenseFromManifest(manifestPath: string, metadata?: object): string | null;
@@ -5,7 +5,7 @@ import { parse as parseToml } from 'smol-toml';
5
5
  import { getLicense } from '../license/license_utils.js';
6
6
  import Sbom from '../sbom.js';
7
7
  import { getCustom, getCustomPath, invokeCommand } from '../tools.js';
8
- export default { isSupported, validateLockFile, provideComponent, provideStack, readLicenseFromManifest };
8
+ export default { isSupported, validateLockFile, provideComponent, provideStack, readLicenseFromManifest, packageManagerName() { return 'cargo'; } };
9
9
  /** @typedef {import('../provider').Provider} */
10
10
  /** @typedef {import('../provider').Provided} Provided */
11
11
  /**
@@ -71,15 +71,22 @@ function isSupported(manifestName) {
71
71
  * Read project license from Cargo.toml, with fallback to LICENSE file.
72
72
  * Supports the `license` field under `[package]` (single crate / workspace
73
73
  * with root) and under `[workspace.package]` (virtual workspaces).
74
+ * When a member crate uses `license = { workspace = true }`, the actual
75
+ * license is resolved from the workspace root Cargo.toml.
74
76
  * @param {string} manifestPath - path to Cargo.toml
77
+ * @param {object} [metadata] - cargo metadata output (needed for workspace license resolution)
75
78
  * @returns {string|null} SPDX identifier or null
76
79
  */
77
- function readLicenseFromManifest(manifestPath) {
80
+ function readLicenseFromManifest(manifestPath, metadata) {
78
81
  let fromManifest = null;
79
82
  try {
80
83
  let content = fs.readFileSync(manifestPath, 'utf-8');
81
84
  let parsed = parseToml(content);
82
- fromManifest = parsed.package?.license
85
+ let packageLicense = parsed.package?.license;
86
+ if (typeof packageLicense === 'object' && packageLicense?.workspace === true) {
87
+ packageLicense = resolveWorkspaceLicense(parsed, metadata);
88
+ }
89
+ fromManifest = packageLicense
83
90
  || parsed.workspace?.package?.license
84
91
  || null;
85
92
  }
@@ -88,6 +95,26 @@ function readLicenseFromManifest(manifestPath) {
88
95
  }
89
96
  return getLicense(fromManifest, manifestPath);
90
97
  }
98
+ /**
99
+ * Resolve a workspace-inherited license from the workspace root Cargo.toml.
100
+ * @param {object} parsed - the parsed member crate Cargo.toml
101
+ * @param {object} [metadata] - cargo metadata output with workspace_root
102
+ * @returns {string|null} resolved license string or null
103
+ */
104
+ function resolveWorkspaceLicense(parsed, metadata) {
105
+ if (metadata?.workspace_root) {
106
+ let cargoTomlPath = path.join(metadata.workspace_root, 'Cargo.toml');
107
+ try {
108
+ let content = fs.readFileSync(cargoTomlPath, 'utf-8');
109
+ let workspaceParsed = parseToml(content);
110
+ return workspaceParsed.workspace?.package?.license || null;
111
+ }
112
+ catch (_) {
113
+ // fall through
114
+ }
115
+ }
116
+ return parsed.workspace?.package?.license || null;
117
+ }
91
118
  /**
92
119
  * Validates that Cargo.lock exists in the manifest directory or in a parent
93
120
  * workspace root directory. In Cargo workspaces the lock file always lives at
@@ -173,7 +200,7 @@ function getSBOM(manifest, opts = {}, includeTransitive) {
173
200
  let metadata = executeCargoMetadata(cargoBin, manifestDir);
174
201
  let ignoredDeps = getIgnoredDeps(manifest, metadata);
175
202
  let crateType = detectCrateType(metadata);
176
- let license = readLicenseFromManifest(manifest);
203
+ let license = readLicenseFromManifest(manifest, metadata);
177
204
  let sbom;
178
205
  if (crateType === CrateType.WORKSPACE_VIRTUAL) {
179
206
  sbom = handleVirtualWorkspace(manifest, metadata, ignoredDeps, includeTransitive, opts, license);
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Extracts actionable remediation instructions from a DA AnalysisReport response.
3
+ *
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.
8
+ *
9
+ * @param {object} analysisReport - raw DA AnalysisReport JSON response
10
+ * @param {object} [options] - extraction options
11
+ * @param {string[]} [options.providerPriority] - provider names in descending priority order.
12
+ * The first entry has the highest priority. Providers not listed share the lowest priority.
13
+ * When omitted or empty, all providers are treated equally and the highest fix version wins.
14
+ * @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
+ */
16
+ export function extractRemediations(analysisReport: object, options?: {
17
+ providerPriority?: string[] | undefined;
18
+ }): Array<{
19
+ purl: string;
20
+ groupId: string;
21
+ artifactId: string;
22
+ currentVersion: string;
23
+ fixedInVersion: string;
24
+ fixedInPurl: string;
25
+ provider: string;
26
+ source: string;
27
+ advisories: Array<{
28
+ id: string;
29
+ url: string;
30
+ }>;
31
+ severity: string;
32
+ cves: string[];
33
+ }>;
34
+ export const SEVERITY_ORDER: string[];
@@ -0,0 +1,321 @@
1
+ import { PackageURL } from 'packageurl-js';
2
+ /**
3
+ * Extracts actionable remediation instructions from a DA AnalysisReport response.
4
+ *
5
+ * 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.
9
+ *
10
+ * @param {object} analysisReport - raw DA AnalysisReport JSON response
11
+ * @param {object} [options] - extraction options
12
+ * @param {string[]} [options.providerPriority] - provider names in descending priority order.
13
+ * The first entry has the highest priority. Providers not listed share the lowest priority.
14
+ * When omitted or empty, all providers are treated equally and the highest fix version wins.
15
+ * @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
+ */
17
+ export function extractRemediations(analysisReport, options = {}) {
18
+ if (!analysisReport || !analysisReport.providers) {
19
+ return [];
20
+ }
21
+ const priorityMap = buildPriorityMap(options.providerPriority);
22
+ const remediationsByDep = new Map();
23
+ const rankByDep = new Map();
24
+ for (const [providerName, providerReport] of Object.entries(analysisReport.providers)) {
25
+ const providerRank = priorityMap.get(providerName) ?? 0;
26
+ extractFromSources(providerReport, providerName, providerRank, remediationsByDep, rankByDep);
27
+ extractFromRecommendations(providerReport, providerName, providerRank, remediationsByDep, rankByDep);
28
+ }
29
+ return Array.from(remediationsByDep.values())
30
+ .sort((a, b) => a.purl.localeCompare(b.purl));
31
+ }
32
+ /**
33
+ * Builds a priority lookup map from a provider priority array.
34
+ * First entry gets the highest numeric priority.
35
+ * @param {string[]} [providerPriority]
36
+ * @returns {Map<string, number>}
37
+ */
38
+ function buildPriorityMap(providerPriority) {
39
+ const map = new Map();
40
+ if (!providerPriority || providerPriority.length === 0) {
41
+ return map;
42
+ }
43
+ for (let i = 0; i < providerPriority.length; i++) {
44
+ map.set(providerPriority[i], providerPriority.length - i);
45
+ }
46
+ return map;
47
+ }
48
+ /**
49
+ * Extracts remediations from the sources/dependencies/issues tree of a provider report.
50
+ * @param {object} providerReport
51
+ * @param {string} providerName
52
+ * @param {number} providerRank - numeric priority rank for this provider
53
+ * @param {Map<string, object>} remediationsByDep - accumulator keyed by dependency PURL
54
+ * @param {Map<string, number>} rankByDep - tracks current winning rank per dependency
55
+ */
56
+ function extractFromSources(providerReport, providerName, providerRank, remediationsByDep, rankByDep) {
57
+ if (!providerReport.sources) {
58
+ return;
59
+ }
60
+ for (const [sourceName, sourceReport] of Object.entries(providerReport.sources)) {
61
+ if (!sourceReport.dependencies) {
62
+ continue;
63
+ }
64
+ for (const dep of sourceReport.dependencies) {
65
+ if (!dep.issues) {
66
+ continue;
67
+ }
68
+ for (const issue of dep.issues) {
69
+ processIssueRemediation(issue, dep, providerName, sourceName, providerRank, remediationsByDep, rankByDep);
70
+ }
71
+ }
72
+ }
73
+ }
74
+ /**
75
+ * Processes a single issue's remediation data and merges it into the accumulator.
76
+ * @param {object} issue - issue object containing remediation and CVE data
77
+ * @param {object} dep - dependency object containing the ref PURL
78
+ * @param {string} providerName
79
+ * @param {string} sourceName
80
+ * @param {number} providerRank
81
+ * @param {Map<string, object>} remediationsByDep
82
+ * @param {Map<string, number>} rankByDep
83
+ */
84
+ function processIssueRemediation(issue, dep, providerName, sourceName, providerRank, remediationsByDep, rankByDep) {
85
+ const fixedInPurl = getFixedInPurl(issue);
86
+ if (!fixedInPurl) {
87
+ return;
88
+ }
89
+ const depPurl = dep.ref;
90
+ if (!depPurl) {
91
+ return;
92
+ }
93
+ let parsedDep;
94
+ let parsedFix;
95
+ try {
96
+ parsedDep = PackageURL.fromString(depPurl);
97
+ parsedFix = PackageURL.fromString(fixedInPurl);
98
+ }
99
+ catch {
100
+ return;
101
+ }
102
+ const fixedInVersion = parsedFix.version;
103
+ if (!fixedInVersion) {
104
+ return;
105
+ }
106
+ const cveId = issue.id || issue.cve;
107
+ const severity = issue.severity || 'UNKNOWN';
108
+ const advisories = extractAdvisories(issue);
109
+ const existing = remediationsByDep.get(depPurl);
110
+ if (!existing) {
111
+ remediationsByDep.set(depPurl, {
112
+ purl: depPurl,
113
+ groupId: parsedDep.namespace || '',
114
+ artifactId: parsedDep.name,
115
+ currentVersion: parsedDep.version || '',
116
+ fixedInVersion,
117
+ fixedInPurl,
118
+ provider: providerName,
119
+ source: sourceName,
120
+ advisories,
121
+ severity: severity.toUpperCase(),
122
+ cves: cveId ? [cveId] : [],
123
+ });
124
+ rankByDep.set(depPurl, providerRank);
125
+ return;
126
+ }
127
+ if (cveId && !existing.cves.includes(cveId)) {
128
+ existing.cves.push(cveId);
129
+ }
130
+ mergeAdvisories(existing.advisories, advisories);
131
+ const existingRank = rankByDep.get(depPurl);
132
+ if (providerRank > existingRank) {
133
+ existing.fixedInVersion = fixedInVersion;
134
+ existing.fixedInPurl = fixedInPurl;
135
+ existing.provider = providerName;
136
+ existing.source = sourceName;
137
+ existing.severity = higherSeverity(existing.severity, severity);
138
+ rankByDep.set(depPurl, providerRank);
139
+ }
140
+ else if (providerRank === existingRank) {
141
+ if (compareVersions(fixedInVersion, existing.fixedInVersion) > 0) {
142
+ existing.fixedInVersion = fixedInVersion;
143
+ existing.fixedInPurl = fixedInPurl;
144
+ existing.provider = providerName;
145
+ existing.source = sourceName;
146
+ }
147
+ existing.severity = higherSeverity(existing.severity, severity);
148
+ }
149
+ }
150
+ /**
151
+ * Extracts remediations from the recommendations section of a provider report.
152
+ * Merges CVEs and advisories into existing entries when present.
153
+ * @param {object} providerReport
154
+ * @param {string} providerName
155
+ * @param {number} providerRank
156
+ * @param {Map<string, object>} remediationsByDep
157
+ * @param {Map<string, number>} rankByDep
158
+ */
159
+ function extractFromRecommendations(providerReport, providerName, providerRank, remediationsByDep, rankByDep) {
160
+ if (!providerReport.recommendations || !providerReport.recommendations.dependencies) {
161
+ return;
162
+ }
163
+ for (const dep of providerReport.recommendations.dependencies) {
164
+ if (!dep.recommendation || !dep.ref) {
165
+ continue;
166
+ }
167
+ const recommendedPurl = dep.recommendation.ref || dep.recommendation;
168
+ if (typeof recommendedPurl !== 'string') {
169
+ continue;
170
+ }
171
+ let parsedDep;
172
+ let parsedRec;
173
+ try {
174
+ parsedDep = PackageURL.fromString(dep.ref);
175
+ parsedRec = PackageURL.fromString(recommendedPurl);
176
+ }
177
+ catch {
178
+ continue;
179
+ }
180
+ const fixedInVersion = parsedRec.version;
181
+ if (!fixedInVersion) {
182
+ continue;
183
+ }
184
+ const depPurl = dep.ref;
185
+ const existing = remediationsByDep.get(depPurl);
186
+ if (!existing) {
187
+ remediationsByDep.set(depPurl, {
188
+ purl: depPurl,
189
+ groupId: parsedDep.namespace || '',
190
+ artifactId: parsedDep.name,
191
+ currentVersion: parsedDep.version || '',
192
+ fixedInVersion,
193
+ fixedInPurl: recommendedPurl,
194
+ provider: providerName,
195
+ source: 'recommendation',
196
+ advisories: [],
197
+ severity: 'UNKNOWN',
198
+ cves: [],
199
+ });
200
+ rankByDep.set(depPurl, providerRank);
201
+ continue;
202
+ }
203
+ const existingRank = rankByDep.get(depPurl);
204
+ if (providerRank > existingRank) {
205
+ existing.fixedInVersion = fixedInVersion;
206
+ existing.fixedInPurl = recommendedPurl;
207
+ existing.provider = providerName;
208
+ existing.source = 'recommendation';
209
+ rankByDep.set(depPurl, providerRank);
210
+ }
211
+ else if (providerRank === existingRank) {
212
+ if (compareVersions(fixedInVersion, existing.fixedInVersion) > 0) {
213
+ existing.fixedInVersion = fixedInVersion;
214
+ existing.fixedInPurl = recommendedPurl;
215
+ existing.provider = providerName;
216
+ existing.source = 'recommendation';
217
+ }
218
+ }
219
+ }
220
+ }
221
+ /**
222
+ * Gets the fixedIn PURL from an issue's remediation, preferring trustedContent.
223
+ * @param {object} issue
224
+ * @returns {string|undefined}
225
+ */
226
+ function getFixedInPurl(issue) {
227
+ if (!issue.remediation) {
228
+ return undefined;
229
+ }
230
+ if (issue.remediation.trustedContent && issue.remediation.trustedContent.ref) {
231
+ return issue.remediation.trustedContent.ref;
232
+ }
233
+ if (issue.remediation.fixedIn) {
234
+ return issue.remediation.fixedIn;
235
+ }
236
+ return undefined;
237
+ }
238
+ /**
239
+ * Extracts advisory objects from an issue.
240
+ * @param {object} issue
241
+ * @returns {Array<{id: string, url: string}>}
242
+ */
243
+ function extractAdvisories(issue) {
244
+ const advisories = [];
245
+ if (issue.remediation && issue.remediation.trustedContent) {
246
+ const tc = issue.remediation.trustedContent;
247
+ if (tc.advisory) {
248
+ advisories.push({
249
+ id: tc.advisory.id || tc.advisory,
250
+ url: tc.advisory.url || '',
251
+ });
252
+ }
253
+ }
254
+ if (issue.advisories) {
255
+ for (const adv of issue.advisories) {
256
+ advisories.push({
257
+ id: adv.id || adv,
258
+ url: adv.url || '',
259
+ });
260
+ }
261
+ }
262
+ return advisories;
263
+ }
264
+ /**
265
+ * Merges new advisories into existing list, avoiding duplicates by id.
266
+ * @param {Array<{id: string, url: string}>} existing
267
+ * @param {Array<{id: string, url: string}>} incoming
268
+ */
269
+ function mergeAdvisories(existing, incoming) {
270
+ const seen = new Set(existing.map(a => a.id));
271
+ for (const adv of incoming) {
272
+ if (!seen.has(adv.id)) {
273
+ existing.push(adv);
274
+ seen.add(adv.id);
275
+ }
276
+ }
277
+ }
278
+ /**
279
+ * Compares two version strings segment by segment.
280
+ * Returns positive if a > b, negative if a < b, zero if equal.
281
+ * Falls back to lexicographic comparison for non-numeric segments.
282
+ * @param {string} a
283
+ * @param {string} b
284
+ * @returns {number}
285
+ */
286
+ function compareVersions(a, b) {
287
+ const partsA = a.split('.');
288
+ const partsB = b.split('.');
289
+ const len = Math.max(partsA.length, partsB.length);
290
+ for (let i = 0; i < len; i++) {
291
+ const segA = partsA[i] || '';
292
+ const segB = partsB[i] || '';
293
+ const numA = Number(segA);
294
+ const numB = Number(segB);
295
+ if (Number.isFinite(numA) && Number.isFinite(numB)) {
296
+ const diff = numA - numB;
297
+ if (diff !== 0)
298
+ return diff;
299
+ }
300
+ else {
301
+ const cmp = segA.localeCompare(segB);
302
+ if (cmp !== 0)
303
+ return cmp;
304
+ }
305
+ }
306
+ return 0;
307
+ }
308
+ export const SEVERITY_ORDER = ['UNKNOWN', 'LOW', 'MEDIUM', 'HIGH', 'CRITICAL'];
309
+ /**
310
+ * Returns the higher of two severity strings, normalized to uppercase.
311
+ * @param {string} a
312
+ * @param {string} b
313
+ * @returns {string}
314
+ */
315
+ function higherSeverity(a, b) {
316
+ const upperA = a.toUpperCase();
317
+ const upperB = b.toUpperCase();
318
+ const indexA = SEVERITY_ORDER.indexOf(upperA);
319
+ const indexB = SEVERITY_ORDER.indexOf(upperB);
320
+ return indexA >= indexB ? upperA : upperB;
321
+ }
@@ -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?: "dependency" | "bundle" | 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;