@trustify-da/trustify-da-javascript-client 0.3.0-ea.608d6fa → 0.3.0-ea.62b88e5

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 (94) hide show
  1. package/README.md +326 -21
  2. package/dist/package.json +36 -27
  3. package/dist/src/analysis.d.ts +58 -14
  4. package/dist/src/analysis.js +118 -17
  5. package/dist/src/batch_opts.d.ts +24 -0
  6. package/dist/src/batch_opts.js +35 -0
  7. package/dist/src/cli.js +357 -8
  8. package/dist/src/config.d.ts +120 -0
  9. package/dist/src/config.js +260 -0
  10. package/dist/src/cyclone_dx_sbom.d.ts +27 -1
  11. package/dist/src/cyclone_dx_sbom.js +84 -10
  12. package/dist/src/index.d.ts +151 -16
  13. package/dist/src/index.js +369 -36
  14. package/dist/src/license/index.d.ts +4 -4
  15. package/dist/src/license/index.js +13 -7
  16. package/dist/src/license/license_utils.js +4 -1
  17. package/dist/src/license/licenses_api.d.ts +3 -3
  18. package/dist/src/license/licenses_api.js +1 -1
  19. package/dist/src/oci_image/images.d.ts +1 -1
  20. package/dist/src/oci_image/images.js +15 -1
  21. package/dist/src/oci_image/utils.d.ts +5 -5
  22. package/dist/src/oci_image/utils.js +11 -2
  23. package/dist/src/package_version.d.ts +8 -0
  24. package/dist/src/package_version.js +31 -0
  25. package/dist/src/provider.d.ts +8 -4
  26. package/dist/src/provider.js +16 -5
  27. package/dist/src/providers/base_java.d.ts +67 -12
  28. package/dist/src/providers/base_java.js +82 -61
  29. package/dist/src/providers/base_javascript.d.ts +91 -10
  30. package/dist/src/providers/base_javascript.js +214 -24
  31. package/dist/src/providers/base_pyproject.d.ts +158 -0
  32. package/dist/src/providers/base_pyproject.js +322 -0
  33. package/dist/src/providers/containerfile_parser.d.ts +5 -0
  34. package/dist/src/providers/containerfile_parser.js +20 -0
  35. package/dist/src/providers/golang_gomodules.d.ts +23 -13
  36. package/dist/src/providers/golang_gomodules.js +208 -120
  37. package/dist/src/providers/gomod_parser.d.ts +4 -0
  38. package/dist/src/providers/gomod_parser.js +16 -0
  39. package/dist/src/providers/java_gradle.d.ts +67 -0
  40. package/dist/src/providers/java_gradle.js +320 -22
  41. package/dist/src/providers/java_gradle_groovy.d.ts +1 -1
  42. package/dist/src/providers/java_gradle_kotlin.d.ts +1 -1
  43. package/dist/src/providers/java_maven.d.ts +37 -9
  44. package/dist/src/providers/java_maven.js +269 -11
  45. package/dist/src/providers/javascript_bun.d.ts +22 -0
  46. package/dist/src/providers/javascript_bun.js +141 -0
  47. package/dist/src/providers/javascript_npm.d.ts +19 -0
  48. package/dist/src/providers/javascript_npm.js +61 -1
  49. package/dist/src/providers/javascript_pnpm.d.ts +14 -1
  50. package/dist/src/providers/javascript_pnpm.js +55 -5
  51. package/dist/src/providers/javascript_yarn.d.ts +12 -0
  52. package/dist/src/providers/javascript_yarn.js +75 -2
  53. package/dist/src/providers/manifest.d.ts +2 -0
  54. package/dist/src/providers/manifest.js +28 -7
  55. package/dist/src/providers/marker_evaluator.d.ts +14 -0
  56. package/dist/src/providers/marker_evaluator.js +191 -0
  57. package/dist/src/providers/oci_dockerfile.d.ts +51 -0
  58. package/dist/src/providers/oci_dockerfile.js +177 -0
  59. package/dist/src/providers/processors/yarn_berry_processor.d.ts +6 -2
  60. package/dist/src/providers/processors/yarn_berry_processor.js +91 -7
  61. package/dist/src/providers/processors/yarn_classic_processor.d.ts +6 -2
  62. package/dist/src/providers/processors/yarn_classic_processor.js +8 -6
  63. package/dist/src/providers/python_controller.d.ts +5 -1
  64. package/dist/src/providers/python_controller.js +69 -8
  65. package/dist/src/providers/python_pip.d.ts +5 -0
  66. package/dist/src/providers/python_pip.js +6 -6
  67. package/dist/src/providers/python_pip_pyproject.d.ts +61 -0
  68. package/dist/src/providers/python_pip_pyproject.js +146 -0
  69. package/dist/src/providers/python_poetry.d.ts +98 -0
  70. package/dist/src/providers/python_poetry.js +286 -0
  71. package/dist/src/providers/python_uv.d.ts +46 -0
  72. package/dist/src/providers/python_uv.js +275 -0
  73. package/dist/src/providers/requirements_parser.js +1 -1
  74. package/dist/src/providers/rust_cargo.d.ts +12 -3
  75. package/dist/src/providers/rust_cargo.js +107 -31
  76. package/dist/src/providers/tree-sitter-containerfile.wasm +0 -0
  77. package/dist/src/providers/tree-sitter-gomod.wasm +0 -0
  78. package/dist/src/remediate.d.ts +107 -0
  79. package/dist/src/remediate.js +244 -0
  80. package/dist/src/remediation.d.ts +81 -0
  81. package/dist/src/remediation.js +475 -0
  82. package/dist/src/remediation_report.d.ts +23 -0
  83. package/dist/src/remediation_report.js +180 -0
  84. package/dist/src/sbom.d.ts +25 -1
  85. package/dist/src/sbom.js +23 -2
  86. package/dist/src/tools.d.ts +37 -13
  87. package/dist/src/tools.js +92 -13
  88. package/dist/src/updaters/maven_updater.d.ts +58 -0
  89. package/dist/src/updaters/maven_updater.js +345 -0
  90. package/dist/src/updaters/toml_updater.d.ts +62 -0
  91. package/dist/src/updaters/toml_updater.js +276 -0
  92. package/dist/src/workspace.d.ts +71 -0
  93. package/dist/src/workspace.js +257 -0
  94. package/package.json +37 -28
package/dist/src/index.js CHANGED
@@ -1,15 +1,26 @@
1
+ import fs from 'node:fs';
1
2
  import path from "node:path";
2
3
  import { EOL } from "os";
3
- import { availableProviders, match } from './provider.js';
4
+ import pLimit from 'p-limit';
4
5
  import analysis from './analysis.js';
5
- import fs from 'node:fs';
6
+ import { resolveBatchMetadata, resolveContinueOnError } from './batch_opts.js';
7
+ import { getPackageVersion } from './package_version.js';
8
+ import { availableProviders, match } from './provider.js';
9
+ import { discoverGoWorkspaceModules } from './providers/golang_gomodules.js';
10
+ import { discoverGradleSubprojects } from './providers/java_gradle.js';
11
+ import { discoverMavenModules } from './providers/java_maven.js';
12
+ import { discoverUvWorkspaceMembers } from './providers/python_uv.js';
6
13
  import { getCustom } from "./tools.js";
7
- import.meta.dirname;
8
- import * as url from 'url';
14
+ import { discoverWorkspaceCrates, discoverWorkspacePackages, filterManifestPathsByDiscoveryIgnore, resolveWorkspaceDiscoveryIgnore, validatePackageJson, } from './workspace.js';
9
15
  export { parseImageRef } from "./oci_image/utils.js";
10
16
  export { ImageRef } from "./oci_image/images.js";
11
17
  export { getProjectLicense, findLicenseFilePath, identifyLicense, getLicenseDetails, licensesFromReport, normalizeLicensesResponse, runLicenseCheck, getCompatibility } from "./license/index.js";
12
- export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken };
18
+ export { extractRemediations, maxSeverity } from "./remediation.js";
19
+ export { generateReport, generateDeduplicationKey } from './remediation_report.js';
20
+ export { loadConfig, mergeConfig, resolveConfig, CONFIG_FILENAMES } from './config.js';
21
+ export { runRemediation, findManifests } from './remediate.js';
22
+ export default { componentAnalysis, stackAnalysis, stackAnalysisBatch, imageAnalysis, validateToken, generateSbom };
23
+ export { discoverMavenModules, discoverGradleSubprojects, discoverGoWorkspaceModules, discoverUvWorkspaceMembers, discoverWorkspacePackages, discoverWorkspaceCrates, validatePackageJson, resolveWorkspaceDiscoveryIgnore, filterManifestPathsByDiscoveryIgnore, resolveContinueOnError, resolveBatchMetadata, };
13
24
  /**
14
25
  * @typedef {{
15
26
  * TRUSTIFY_DA_CARGO_PATH?: string | undefined,
@@ -31,20 +42,44 @@ export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken
31
42
  * TRUSTIFY_DA_PYTHON_PATH?: string | undefined,
32
43
  * TRUSTIFY_DA_PYTHON_VIRTUAL_ENV?: string | undefined,
33
44
  * TRUSTIFY_DA_PYTHON3_PATH?: string | undefined,
34
- * TRUSTIFY_DA_RECOMMENDATIONS_ENABLED?: string | undefined,
45
+ * TRUSTIFY_DA_PROVIDERS?: string | undefined,
46
+ * TRUSTIFY_DA_RECOMMEND?: string | undefined,
47
+ * TRUSTIFY_DA_SOURCES?: string | undefined,
35
48
  * TRUSTIFY_DA_SKOPEO_CONFIG_PATH?: string | undefined,
36
49
  * TRUSTIFY_DA_SKOPEO_PATH?: string | undefined,
37
50
  * TRUSTIFY_DA_SYFT_CONFIG_PATH?: string | undefined,
38
51
  * TRUSTIFY_DA_SYFT_PATH?: string | undefined,
39
52
  * TRUSTIFY_DA_YARN_PATH?: string | undefined,
53
+ * TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined,
40
54
  * TRUSTIFY_DA_LICENSE_CHECK?: string | undefined,
55
+ * licenseCheck?: boolean | undefined,
41
56
  * MATCH_MANIFEST_VERSIONS?: string | undefined,
42
57
  * TRUSTIFY_DA_SOURCE?: string | undefined,
43
58
  * TRUSTIFY_DA_TOKEN?: string | undefined,
44
59
  * TRUSTIFY_DA_TELEMETRY_ID?: string | undefined,
45
- * [key: string]: string | undefined,
60
+ * batchConcurrency?: number | undefined,
61
+ * TRUSTIFY_DA_BATCH_CONCURRENCY?: string | undefined,
62
+ * workspaceDiscoveryIgnore?: string[] | undefined,
63
+ * TRUSTIFY_DA_WORKSPACE_DISCOVERY_IGNORE?: string | undefined,
64
+ * continueOnError?: boolean | undefined,
65
+ * TRUSTIFY_DA_CONTINUE_ON_ERROR?: string | undefined,
66
+ * batchMetadata?: boolean | undefined,
67
+ * TRUSTIFY_DA_BATCH_METADATA?: string | undefined,
68
+ * TRUSTIFY_DA_UV_PATH?: string | undefined,
69
+ * TRUSTIFY_DA_POETRY_PATH?: string | undefined,
70
+ * [key: string]: string | number | boolean | string[] | undefined,
46
71
  * }} Options
47
72
  */
73
+ /**
74
+ * @typedef {{
75
+ * workspaceRoot: string,
76
+ * ecosystem: 'javascript' | 'cargo' | 'pyproject' | 'unknown',
77
+ * total: number,
78
+ * successful: number,
79
+ * failed: number,
80
+ * errors: Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>
81
+ * }} BatchAnalysisMetadata
82
+ */
48
83
  /**
49
84
  * Logs messages to the console if the TRUSTIFY_DA_DEBUG environment variable is set to "true".
50
85
  * @param {string} alongsideText - The text to prepend to the log message.
@@ -61,29 +96,11 @@ function logOptionsAndEnvironmentsVariables(alongsideText, valueToBePrinted) {
61
96
  * @private
62
97
  */
63
98
  function readAndPrintVersionFromPackageJson() {
64
- let dirName;
65
- // new ESM way in nodeJS ( since node version 22 ) to bring module directory.
66
- dirName = import.meta.dirname;
67
- // old ESM way in nodeJS ( before node versions 22.00 to bring module directory)
68
- if (!dirName) {
69
- dirName = url.fileURLToPath(new URL('.', import.meta.url));
70
- }
71
- try {
72
- if (__dirname) {
73
- dirName = __dirname;
74
- }
75
- }
76
- catch (e) {
77
- console.log("__dirname is not defined, continue with fileUrlPath");
78
- }
79
- let packageJson = JSON.parse(fs.readFileSync(path.join(dirName, "..", "package.json")).toString());
80
- logOptionsAndEnvironmentsVariables("trustify-da-javascript-client analysis started, version: ", packageJson.version);
99
+ logOptionsAndEnvironmentsVariables("trustify-da-javascript-client analysis started, version: ", getPackageVersion());
81
100
  }
82
101
  /**
83
- * This function is used to determine the Trustify DA backend URL.
84
- * The TRUSTIFY_DA_BACKEND_URL is evaluated in the following order and selected when it finds it first:
85
- * 1. Environment Variable
86
- * 2. (key,value) from opts object
102
+ * Selects the Trustify DA backend URL from opts.TRUSTIFY_DA_BACKEND_URL, then environment
103
+ * variable TRUSTIFY_DA_BACKEND_URL. Options take precedence over environment variables.
87
104
  * If TRUSTIFY_DA_BACKEND_URL is not set, the function will throw an error.
88
105
  * @param {{TRUSTIFY_DA_DEBUG?: string | undefined; TRUSTIFY_DA_BACKEND_URL?: string | undefined}} [opts={}]
89
106
  * @return {string} - The selected Trustify DA backend URL
@@ -114,7 +131,7 @@ export function selectTrustifyDABackend(opts = {}) {
114
131
  * @param {string} manifest
115
132
  * @param {false} html
116
133
  * @param {Options} [opts={}]
117
- * @returns {Promise<import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>}
134
+ * @returns {Promise<import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>}
118
135
  * @throws {Error}
119
136
  */
120
137
  /**
@@ -123,29 +140,31 @@ export function selectTrustifyDABackend(opts = {}) {
123
140
  * @param {string} manifest - path for the manifest
124
141
  * @param {boolean} [html=false] - true will return a html string, false will return AnalysisReport object.
125
142
  * @param {Options} [opts={}] - optional various options to pass along the application
126
- * @returns {Promise<string|import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>}
143
+ * @returns {Promise<string|import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>}
127
144
  * @throws {Error} if manifest inaccessible, no matching provider, failed to get create content,
128
145
  * or backend request failed
129
146
  */
130
147
  async function stackAnalysis(manifest, html = false, opts = {}) {
131
148
  const theUrl = selectTrustifyDABackend(opts);
132
149
  fs.accessSync(manifest, fs.constants.R_OK); // throws error if file unreadable
133
- let provider = match(manifest, availableProviders); // throws error if no matching provider
150
+ let provider = match(manifest, availableProviders, opts); // throws error if no matching provider
134
151
  return await analysis.requestStack(provider, manifest, theUrl, html, opts); // throws error request sending failed
135
152
  }
136
153
  /**
137
154
  * Get component analysis report for a manifest content.
138
155
  * @param {string} manifest - path to the manifest
139
156
  * @param {Options} [opts={}] - optional various options to pass along the application
140
- * @returns {Promise<import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>}
157
+ * @returns {Promise<import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>}
141
158
  * @throws {Error} if no matching provider, failed to get create content, or backend request failed
142
159
  */
143
160
  async function componentAnalysis(manifest, opts = {}) {
144
161
  const theUrl = selectTrustifyDABackend(opts);
145
162
  fs.accessSync(manifest, fs.constants.R_OK);
146
163
  opts["manifest-type"] = path.basename(manifest);
147
- let provider = match(manifest, availableProviders); // throws error if no matching provider
148
- return await analysis.requestComponent(provider, manifest, theUrl, opts); // throws error request sending failed
164
+ let provider = match(manifest, availableProviders, opts); // throws error if no matching provider
165
+ const result = await analysis.requestComponent(provider, manifest, theUrl, opts); // throws error request sending failed
166
+ result.packageManager = provider.packageManagerName();
167
+ return result;
149
168
  }
150
169
  /**
151
170
  * @overload
@@ -160,7 +179,7 @@ async function componentAnalysis(manifest, opts = {}) {
160
179
  * @param {Array<string>} imageRefs
161
180
  * @param {false} html
162
181
  * @param {Options} [opts={}]
163
- * @returns {Promise<Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>>}
182
+ * @returns {Promise<Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>>}
164
183
  * @throws {Error}
165
184
  */
166
185
  /**
@@ -169,7 +188,7 @@ async function componentAnalysis(manifest, opts = {}) {
169
188
  * @param {Array<string>} imageRefs - OCI image references
170
189
  * @param {boolean} [html=false] - true will return a html string, false will return AnalysisReport
171
190
  * @param {Options} [opts={}] - optional various options to pass along the application
172
- * @returns {Promise<string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>>}
191
+ * @returns {Promise<string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>>}
173
192
  * @throws {Error} if manifest inaccessible, no matching provider, failed to get create content,
174
193
  * or backend request failed
175
194
  */
@@ -177,6 +196,320 @@ async function imageAnalysis(imageRefs, html = false, opts = {}) {
177
196
  const theUrl = selectTrustifyDABackend(opts);
178
197
  return await analysis.requestImages(imageRefs, theUrl, html, opts);
179
198
  }
199
+ /**
200
+ * Max concurrent SBOM generations for batch workspace analysis. Options override environment;
201
+ * environment overrides the default of 10.
202
+ * @param {Options} opts
203
+ * @returns {number}
204
+ * @private
205
+ */
206
+ function resolveBatchConcurrency(opts) {
207
+ const fromEnv = getCustom('TRUSTIFY_DA_BATCH_CONCURRENCY', null, opts);
208
+ const raw = opts.batchConcurrency ?? fromEnv ?? '10';
209
+ const n = typeof raw === 'number' ? raw : parseInt(String(raw), 10);
210
+ if (!Number.isFinite(n) || n < 1) {
211
+ return 10;
212
+ }
213
+ return Math.min(256, n);
214
+ }
215
+ /**
216
+ * @param {string} root
217
+ * @param {'javascript' | 'cargo' | 'unknown'} ecosystem
218
+ * @param {number} totalSbomAttempts
219
+ * @param {number} successfulSbomCount
220
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} errors
221
+ * @returns {BatchAnalysisMetadata}
222
+ * @private
223
+ */
224
+ function buildBatchAnalysisMetadata(root, ecosystem, totalSbomAttempts, successfulSbomCount, errors) {
225
+ return {
226
+ workspaceRoot: root,
227
+ ecosystem,
228
+ total: totalSbomAttempts,
229
+ successful: successfulSbomCount,
230
+ failed: errors.length,
231
+ errors: [...errors],
232
+ };
233
+ }
234
+ /**
235
+ * Generate a CycloneDX SBOM from a manifest file. No backend HTTP request is made.
236
+ *
237
+ * @param {string} manifestPath - path to the manifest file (e.g. pom.xml, package.json)
238
+ * @param {Options} [opts={}] - optional options (e.g. workspace dir, tool paths)
239
+ * @returns {Promise<object>} parsed CycloneDX SBOM JSON object
240
+ * @throws {Error} if the manifest is unsupported or SBOM generation fails
241
+ */
242
+ export async function generateSbom(manifestPath, opts = {}) {
243
+ fs.accessSync(manifestPath, fs.constants.R_OK);
244
+ const result = await generateOneSbom(manifestPath, opts);
245
+ if (!result.ok) {
246
+ throw new Error(`Failed to generate SBOM for ${result.manifestPath}: ${result.reason}`);
247
+ }
248
+ return result.sbom;
249
+ }
250
+ /**
251
+ * @typedef {{ ok: true, purl: string, sbom: object } | { ok: false, manifestPath: string, reason: string }} SbomResult
252
+ */
253
+ /**
254
+ * Generate an SBOM for a single manifest, returning a normalized result.
255
+ *
256
+ * @param {string} manifestPath
257
+ * @param {Options} workspaceOpts - opts with `TRUSTIFY_DA_WORKSPACE_DIR` set
258
+ * @returns {Promise<SbomResult>}
259
+ * @private
260
+ */
261
+ async function generateOneSbom(manifestPath, workspaceOpts) {
262
+ const provider = match(manifestPath, availableProviders, workspaceOpts);
263
+ const provided = await provider.provideStack(manifestPath, workspaceOpts);
264
+ const sbom = JSON.parse(provided.content);
265
+ const purl = sbom?.metadata?.component?.purl || sbom?.metadata?.component?.['bom-ref'];
266
+ if (!purl) {
267
+ return { ok: false, manifestPath, reason: 'missing purl in SBOM' };
268
+ }
269
+ return { ok: true, purl, sbom };
270
+ }
271
+ /**
272
+ * Detect the workspace ecosystem and discover manifest paths.
273
+ *
274
+ * @param {string} root - Resolved workspace root
275
+ * @param {Options} opts
276
+ * @returns {Promise<{ ecosystem: 'javascript' | 'cargo' | 'maven' | 'gradle' | 'gomodules' | 'pyproject' | 'unknown', manifestPaths: string[] }>}
277
+ * @private
278
+ */
279
+ async function detectWorkspaceManifests(root, opts) {
280
+ const cargoToml = path.join(root, 'Cargo.toml');
281
+ const cargoLock = path.join(root, 'Cargo.lock');
282
+ const packageJson = path.join(root, 'package.json');
283
+ const pomXml = path.join(root, 'pom.xml');
284
+ if (fs.existsSync(cargoToml) && fs.existsSync(cargoLock)) {
285
+ return { ecosystem: 'cargo', manifestPaths: await discoverWorkspaceCrates(root, opts) };
286
+ }
287
+ if (fs.existsSync(pomXml)) {
288
+ const manifestPaths = await discoverMavenModules(root, opts);
289
+ if (manifestPaths.length > 0) {
290
+ return { ecosystem: 'maven', manifestPaths };
291
+ }
292
+ }
293
+ const hasGradleSettings = fs.existsSync(path.join(root, 'settings.gradle'))
294
+ || fs.existsSync(path.join(root, 'settings.gradle.kts'));
295
+ if (hasGradleSettings) {
296
+ const manifestPaths = await discoverGradleSubprojects(root, opts);
297
+ if (manifestPaths.length > 0) {
298
+ return { ecosystem: 'gradle', manifestPaths };
299
+ }
300
+ }
301
+ if (fs.existsSync(path.join(root, 'go.work'))) {
302
+ const manifestPaths = await discoverGoWorkspaceModules(root, opts);
303
+ if (manifestPaths.length > 0) {
304
+ return { ecosystem: 'gomodules', manifestPaths };
305
+ }
306
+ }
307
+ if (fs.existsSync(path.join(root, 'pyproject.toml')) && fs.existsSync(path.join(root, 'uv.lock'))) {
308
+ const manifestPaths = await discoverUvWorkspaceMembers(root, opts);
309
+ if (manifestPaths.length > 0) {
310
+ return { ecosystem: 'pyproject', manifestPaths };
311
+ }
312
+ }
313
+ const hasJsLock = fs.existsSync(path.join(root, 'bun.lock'))
314
+ || fs.existsSync(path.join(root, 'pnpm-lock.yaml'))
315
+ || fs.existsSync(path.join(root, 'yarn.lock'))
316
+ || fs.existsSync(path.join(root, 'package-lock.json'));
317
+ if (fs.existsSync(packageJson) && hasJsLock) {
318
+ let manifestPaths = await discoverWorkspacePackages(root, opts);
319
+ if (manifestPaths.length === 0) {
320
+ manifestPaths = [packageJson];
321
+ }
322
+ return { ecosystem: 'javascript', manifestPaths };
323
+ }
324
+ return { ecosystem: 'unknown', manifestPaths: [] };
325
+ }
326
+ /**
327
+ * Validate discovered JS package.json manifests, collecting errors.
328
+ *
329
+ * @param {string[]} manifestPaths
330
+ * @param {boolean} continueOnError
331
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} collectedErrors - mutated in place
332
+ * @returns {{ validPaths: string[] }}
333
+ * @throws {Error} on first invalid manifest when `continueOnError` is false
334
+ * @private
335
+ */
336
+ function validateJsManifests(manifestPaths, continueOnError, collectedErrors) {
337
+ const validPaths = [];
338
+ for (const p of manifestPaths) {
339
+ const v = validatePackageJson(p);
340
+ if (v.valid) {
341
+ validPaths.push(p);
342
+ }
343
+ else {
344
+ collectedErrors.push({ manifestPath: p, phase: 'validation', reason: v.error });
345
+ console.warn(`Skipping invalid package.json (${v.error}): ${p}`);
346
+ if (!continueOnError) {
347
+ throw new Error(`Invalid package.json (${v.error}): ${p}`);
348
+ }
349
+ }
350
+ }
351
+ return { validPaths };
352
+ }
353
+ /**
354
+ * Generate SBOMs for all manifests. In fail-fast mode, stops on first error.
355
+ * In continue-on-error mode, runs concurrently and collects failures.
356
+ *
357
+ * @param {string[]} manifestPaths
358
+ * @param {Options} workspaceOpts
359
+ * @param {boolean} continueOnError
360
+ * @param {number} concurrency
361
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} collectedErrors - mutated in place
362
+ * @returns {Promise<Object.<string, object>>} sbomByPurl map
363
+ * @throws {Error} on first SBOM failure when `continueOnError` is false
364
+ * @private
365
+ */
366
+ async function generateSboms(manifestPaths, workspaceOpts, continueOnError, concurrency, collectedErrors) {
367
+ /** @type {SbomResult[]} */
368
+ const results = [];
369
+ if (!continueOnError) {
370
+ for (const manifestPath of manifestPaths) {
371
+ const result = await generateOneSbom(manifestPath, workspaceOpts);
372
+ if (!result.ok) {
373
+ collectedErrors.push({ manifestPath: result.manifestPath, phase: 'sbom', reason: result.reason });
374
+ throw new Error(`${result.manifestPath}: ${result.reason}`);
375
+ }
376
+ results.push(result);
377
+ }
378
+ }
379
+ else {
380
+ const limit = pLimit(concurrency);
381
+ const settled = await Promise.all(manifestPaths.map(manifestPath => limit(async () => {
382
+ try {
383
+ return await generateOneSbom(manifestPath, workspaceOpts);
384
+ }
385
+ catch (err) {
386
+ const msg = err instanceof Error ? err.message : String(err);
387
+ if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
388
+ console.log(`Skipping ${manifestPath}: ${msg}`);
389
+ }
390
+ return { ok: false, manifestPath, reason: msg };
391
+ }
392
+ })));
393
+ for (const r of settled) {
394
+ results.push(r);
395
+ if (!r.ok) {
396
+ collectedErrors.push({ manifestPath: r.manifestPath, phase: 'sbom', reason: r.reason });
397
+ }
398
+ }
399
+ }
400
+ const sbomByPurl = {};
401
+ for (const r of results) {
402
+ if (r.ok) {
403
+ sbomByPurl[r.purl] = r.sbom;
404
+ }
405
+ }
406
+ return sbomByPurl;
407
+ }
408
+ /**
409
+ * Create an Error with optional `batchMetadata` attached.
410
+ * @param {string} message
411
+ * @param {boolean} wantMetadata
412
+ * @param {BatchAnalysisMetadata} [metadata]
413
+ * @returns {Error}
414
+ * @private
415
+ */
416
+ function batchError(message, wantMetadata, metadata) {
417
+ const err = new Error(message);
418
+ if (wantMetadata && metadata) {
419
+ err.batchMetadata = metadata;
420
+ }
421
+ return err;
422
+ }
423
+ /**
424
+ * @overload
425
+ * @param {string} workspaceRoot
426
+ * @param {true} html
427
+ * @param {Options & { batchMetadata: true }} opts
428
+ * @returns {Promise<{ analysis: string, metadata: BatchAnalysisMetadata }>}
429
+ * @throws {Error}
430
+ */
431
+ /**
432
+ * @overload
433
+ * @param {string} workspaceRoot
434
+ * @param {true} html
435
+ * @param {Options & { batchMetadata?: false }} [opts={}]
436
+ * @returns {Promise<string>}
437
+ * @throws {Error}
438
+ */
439
+ /**
440
+ * @overload
441
+ * @param {string} workspaceRoot
442
+ * @param {false} html
443
+ * @param {Options & { batchMetadata: true }} opts
444
+ * @returns {Promise<{ analysis: Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>, metadata: BatchAnalysisMetadata }>}
445
+ * @throws {Error}
446
+ */
447
+ /**
448
+ * @overload
449
+ * @param {string} workspaceRoot
450
+ * @param {false} html
451
+ * @param {Options & { batchMetadata?: false }} [opts={}]
452
+ * @returns {Promise<Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>>}
453
+ * @throws {Error}
454
+ */
455
+ /**
456
+ * Get stack analysis for all workspace packages/crates (batch).
457
+ * Detects ecosystem from workspace root: Cargo (Cargo.toml + Cargo.lock) or JS/TS (package.json + lock file).
458
+ * SBOMs are generated in parallel (see `batchConcurrency`) unless `continueOnError: false` (fail-fast sequential).
459
+ * With `opts.batchMetadata` / `TRUSTIFY_DA_BATCH_METADATA`, returns `{ analysis, metadata }` including validation and SBOM errors.
460
+ *
461
+ * @overload
462
+ * @param {string} workspaceRoot - Path to workspace root (containing lock file and workspace config)
463
+ * @param {boolean} [html=false] - true returns HTML, false returns JSON report
464
+ * @param {Options} [opts={}] - `batchConcurrency`, discovery ignores, `continueOnError` (default true), `batchMetadata` (default false)
465
+ * @returns {Promise<string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>|{ analysis: string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>, metadata: BatchAnalysisMetadata }>}
466
+ * @throws {Error} if workspace root invalid, no manifests found, no packages pass validation, no SBOMs produced, or backend request failed. When `opts.batchMetadata` is set, `error.batchMetadata` may be set on thrown errors.
467
+ */
468
+ async function stackAnalysisBatch(workspaceRoot, html = false, opts = {}) {
469
+ const theUrl = selectTrustifyDABackend(opts);
470
+ const root = path.resolve(workspaceRoot);
471
+ fs.accessSync(root, fs.constants.R_OK);
472
+ const continueOnError = resolveContinueOnError(opts);
473
+ const wantMetadata = resolveBatchMetadata(opts);
474
+ /** @type {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} */
475
+ const collectedErrors = [];
476
+ const { ecosystem, manifestPaths: discovered } = await detectWorkspaceManifests(root, opts);
477
+ let manifestPaths = discovered;
478
+ if (ecosystem === 'javascript') {
479
+ try {
480
+ const { validPaths } = validateJsManifests(manifestPaths, continueOnError, collectedErrors);
481
+ manifestPaths = validPaths;
482
+ }
483
+ catch (err) {
484
+ throw batchError(err.message, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, 0, 0, collectedErrors));
485
+ }
486
+ if (manifestPaths.length === 0 && discovered.length > 0) {
487
+ const detail = collectedErrors.map(e => `${e.manifestPath}: ${e.reason}`).join('; ');
488
+ throw batchError(`No valid packages after validation at ${root}. ${detail}`, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, 0, 0, collectedErrors));
489
+ }
490
+ }
491
+ if (manifestPaths.length === 0) {
492
+ throw new Error(`No workspace manifests found at ${root}. Ensure a supported workspace root exists (Cargo.toml+Cargo.lock, pom.xml, build.gradle, go.work, pyproject.toml+uv.lock, or package.json+lock file).`);
493
+ }
494
+ const workspaceOpts = { ...opts, TRUSTIFY_DA_WORKSPACE_DIR: root };
495
+ const concurrency = resolveBatchConcurrency(opts);
496
+ let sbomByPurl;
497
+ try {
498
+ sbomByPurl = await generateSboms(manifestPaths, workspaceOpts, continueOnError, concurrency, collectedErrors);
499
+ }
500
+ catch (err) {
501
+ throw batchError(err.message, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, 0, collectedErrors));
502
+ }
503
+ if (Object.keys(sbomByPurl).length === 0) {
504
+ throw batchError(`No valid SBOMs produced from ${manifestPaths.length} manifest(s) at ${root}`, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, 0, collectedErrors));
505
+ }
506
+ const analysisResult = await analysis.requestStackBatch(sbomByPurl, theUrl, html, opts);
507
+ const meta = buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, Object.keys(sbomByPurl).length, collectedErrors);
508
+ if (wantMetadata) {
509
+ return { analysis: analysisResult, metadata: meta };
510
+ }
511
+ return analysisResult;
512
+ }
180
513
  /**
181
514
  * Validates the Exhort token.
182
515
  * @param {Options} [opts={}] - Optional parameters, potentially including token override.
@@ -6,13 +6,13 @@
6
6
  * @param {string} manifestPath - path to manifest
7
7
  * @param {string} url - the backend url to send the request to
8
8
  * @param {import('../index.js').Options} [opts={}]
9
- * @param {import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport} [analysisResult] - analysis result that includes licenses array from backend
9
+ * @param {import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport} [analysisResult] - analysis result that includes licenses array from backend
10
10
  * @returns {Promise<{ projectLicense: { manifest: Object|null, file: Object|null, mismatch: boolean }, incompatibleDependencies: Array<{ purl: string, licenses: string[], category?: string, reason: string }>, error?: string }>}
11
11
  */
12
- export function runLicenseCheck(sbomContent: string, manifestPath: string, url: string, opts?: import("../index.js").Options, analysisResult?: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport): Promise<{
12
+ export function runLicenseCheck(sbomContent: string, manifestPath: string, url: string, opts?: import("../index.js").Options, analysisResult?: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts").AnalysisReport): Promise<{
13
13
  projectLicense: {
14
- manifest: any | null;
15
- file: any | null;
14
+ manifest: Object | null;
15
+ file: Object | null;
16
16
  mismatch: boolean;
17
17
  };
18
18
  incompatibleDependencies: Array<{
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * License resolution and dependency license compatibility for component analysis.
3
3
  */
4
- import { getProjectLicense, findLicenseFilePath, identifyLicense } from './project_license.js';
5
- import { licensesFromReport, getLicenseDetails } from './licenses_api.js';
6
4
  import { getCompatibility } from './license_utils.js';
5
+ import { licensesFromReport, getLicenseDetails } from './licenses_api.js';
6
+ import { getProjectLicense, findLicenseFilePath, identifyLicense } from './project_license.js';
7
7
  export { getProjectLicense, findLicenseFilePath, identifyLicense } from './project_license.js';
8
8
  export { licensesFromReport, normalizeLicensesResponse, getLicenseDetails } from './licenses_api.js';
9
9
  export { getCompatibility } from './license_utils.js';
@@ -15,7 +15,7 @@ export { getCompatibility } from './license_utils.js';
15
15
  * @param {string} manifestPath - path to manifest
16
16
  * @param {string} url - the backend url to send the request to
17
17
  * @param {import('../index.js').Options} [opts={}]
18
- * @param {import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport} [analysisResult] - analysis result that includes licenses array from backend
18
+ * @param {import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport} [analysisResult] - analysis result that includes licenses array from backend
19
19
  * @returns {Promise<{ projectLicense: { manifest: Object|null, file: Object|null, mismatch: boolean }, incompatibleDependencies: Array<{ purl: string, licenses: string[], category?: string, reason: string }>, error?: string }>}
20
20
  */
21
21
  export async function runLicenseCheck(sbomContent, manifestPath, url, opts = {}, analysisResult = null) {
@@ -39,10 +39,12 @@ export async function runLicenseCheck(sbomContent, manifestPath, url, opts = {},
39
39
  // Fetch detailed license info from backend (avoid duplicate calls if same license)
40
40
  const licenseDetailsCache = new Map();
41
41
  async function getDetails(spdxId) {
42
- if (!spdxId || !url)
42
+ if (!spdxId || !url) {
43
43
  return null;
44
- if (licenseDetailsCache.has(spdxId))
44
+ }
45
+ if (licenseDetailsCache.has(spdxId)) {
45
46
  return licenseDetailsCache.get(spdxId);
47
+ }
46
48
  try {
47
49
  const details = await getLicenseDetails(spdxId, { ...opts, TRUSTIFY_DA_BACKEND_URL: url });
48
50
  licenseDetailsCache.set(spdxId, details);
@@ -81,15 +83,19 @@ export async function runLicenseCheck(sbomContent, manifestPath, url, opts = {},
81
83
  const incompatibleDependencies = [];
82
84
  for (const purl of purls) {
83
85
  const entry = licenseByPurl.get(purl);
84
- if (!entry)
86
+ if (!entry) {
85
87
  continue;
88
+ }
86
89
  const status = getCompatibility(projectCategory, entry.category);
87
90
  if (status === 'incompatible') {
91
+ const reason = entry.category?.toUpperCase() === 'UNKNOWN'
92
+ ? 'License not recognized as a standard SPDX identifier. Manual review recommended to verify compatibility.'
93
+ : 'Dependency license(s) are incompatible with the project license.';
88
94
  incompatibleDependencies.push({
89
95
  purl,
90
96
  licenses: entry.licenses,
91
97
  category: entry.category,
92
- reason: 'Dependency license(s) are incompatible with the project license.'
98
+ reason
93
99
  });
94
100
  }
95
101
  }
@@ -114,9 +114,12 @@ export function getCompatibility(projectCategory, dependencyCategory) {
114
114
  }
115
115
  const proj = projectCategory.toUpperCase();
116
116
  const dep = dependencyCategory.toUpperCase();
117
- if (proj === 'UNKNOWN' || dep === 'UNKNOWN') {
117
+ if (proj === 'UNKNOWN') {
118
118
  return 'unknown';
119
119
  }
120
+ if (dep === 'UNKNOWN') {
121
+ return 'incompatible';
122
+ }
120
123
  const restrictiveness = {
121
124
  'PERMISSIVE': 1,
122
125
  'WEAK_COPYLEFT': 2,
@@ -6,7 +6,7 @@
6
6
  * @param {import('../index.js').Options} [opts={}] - options (proxy, token, TRUSTIFY_DA_BACKEND_URL, etc.)
7
7
  * @returns {Promise<Object|null>} License details or null if not found
8
8
  */
9
- export function getLicenseDetails(spdxId: string, opts?: import("../index.js").Options): Promise<any | null>;
9
+ export function getLicenseDetails(spdxId: string, opts?: import("../index.js").Options): Promise<Object | null>;
10
10
  /**
11
11
  * Normalize the LicensesResponse shape (array of LicenseProviderResult) into a map of purl -> license info.
12
12
  * Each provider result has { status, summary, packages } where packages is { [purl]: { concluded, evidence } }.
@@ -24,11 +24,11 @@ export function normalizeLicensesResponse(data: unknown, purls?: string[]): Map<
24
24
  * Build license map from an analysis report that already includes license data (result.licenses).
25
25
  * Use this when the dependency analysis response already contains the licenses array to avoid a second request.
26
26
  *
27
- * @param {import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport} analysisReport - full analysis JSON
27
+ * @param {import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport} analysisReport - full analysis JSON
28
28
  * @param {string[]} [purls] - optional list of purls to restrict to
29
29
  * @returns {Map<string, { licenses: string[], category?: string }>}
30
30
  */
31
- export function licensesFromReport(analysisReport: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport, purls?: string[]): Map<string, {
31
+ export function licensesFromReport(analysisReport: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts").AnalysisReport, purls?: string[]): Map<string, {
32
32
  licenses: string[];
33
33
  category?: string;
34
34
  }>;
@@ -86,7 +86,7 @@ export function normalizeLicensesResponse(data, purls = []) {
86
86
  * Build license map from an analysis report that already includes license data (result.licenses).
87
87
  * Use this when the dependency analysis response already contains the licenses array to avoid a second request.
88
88
  *
89
- * @param {import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport} analysisReport - full analysis JSON
89
+ * @param {import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport} analysisReport - full analysis JSON
90
90
  * @param {string[]} [purls] - optional list of purls to restrict to
91
91
  * @returns {Map<string, { licenses: string[], category?: string }>}
92
92
  */
@@ -78,7 +78,7 @@ export class ImageRef {
78
78
  * @param {string} [platform]
79
79
  * @param {import("index.js").Options} [opts={}]
80
80
  */
81
- constructor(image: string, platform?: string, opts?: import("index.js").Options);
81
+ constructor(image: string, platform?: string, opts?: any);
82
82
  /** @type {Image} */
83
83
  image: Image;
84
84
  /** @type {Platform} */
@@ -242,8 +242,22 @@ export class ImageRef {
242
242
  getPackageURL() {
243
243
  /** @type {Object.<string, string>} */
244
244
  const qualifiers = {};
245
- const repositoryUrl = this.image.getNameWithoutTag();
245
+ let repositoryUrl = this.image.getNameWithoutTag();
246
246
  const simpleName = this.image.getSimpleName();
247
+ // Normalize Docker Hub image references so all forms produce the same PURL:
248
+ // node → docker.io/node
249
+ // docker.io/library/node → docker.io/node
250
+ if (repositoryUrl != null) {
251
+ const lower = repositoryUrl.toLowerCase();
252
+ if (lower === simpleName.toLowerCase()) {
253
+ // Bare name (e.g. "node") — default to docker.io
254
+ repositoryUrl = `docker.io/${simpleName}`;
255
+ }
256
+ else if (lower.startsWith('docker.io/library/')) {
257
+ // Official image with library/ prefix — strip it
258
+ repositoryUrl = `docker.io/${lower.substring('docker.io/library/'.length)}`;
259
+ }
260
+ }
247
261
  if (repositoryUrl != null && repositoryUrl.toLowerCase() !== simpleName.toLowerCase()) {
248
262
  qualifiers[ImageRef.REPOSITORY_QUALIFIER] = repositoryUrl.toLowerCase();
249
263
  }