@trustify-da/trustify-da-javascript-client 0.3.0-ea.608d6fa → 0.3.0-ea.61444d4

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 (85) hide show
  1. package/README.md +304 -13
  2. package/dist/package.json +31 -23
  3. package/dist/src/analysis.d.ts +28 -5
  4. package/dist/src/analysis.js +78 -13
  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 +276 -5
  8. package/dist/src/cyclone_dx_sbom.d.ts +14 -1
  9. package/dist/src/cyclone_dx_sbom.js +45 -9
  10. package/dist/src/index.d.ts +142 -7
  11. package/dist/src/index.js +355 -6
  12. package/dist/src/license/index.d.ts +3 -3
  13. package/dist/src/license/index.js +4 -1
  14. package/dist/src/license/license_utils.js +4 -1
  15. package/dist/src/license/licenses_api.d.ts +2 -2
  16. package/dist/src/oci_image/images.d.ts +1 -1
  17. package/dist/src/oci_image/images.js +15 -1
  18. package/dist/src/oci_image/utils.d.ts +5 -5
  19. package/dist/src/oci_image/utils.js +11 -2
  20. package/dist/src/provider.d.ts +8 -4
  21. package/dist/src/provider.js +16 -5
  22. package/dist/src/providers/base_java.d.ts +14 -12
  23. package/dist/src/providers/base_java.js +18 -44
  24. package/dist/src/providers/base_javascript.d.ts +37 -10
  25. package/dist/src/providers/base_javascript.js +108 -20
  26. package/dist/src/providers/base_pyproject.d.ts +158 -0
  27. package/dist/src/providers/base_pyproject.js +322 -0
  28. package/dist/src/providers/containerfile_parser.d.ts +5 -0
  29. package/dist/src/providers/containerfile_parser.js +20 -0
  30. package/dist/src/providers/golang_gomodules.d.ts +23 -13
  31. package/dist/src/providers/golang_gomodules.js +207 -120
  32. package/dist/src/providers/gomod_parser.d.ts +4 -0
  33. package/dist/src/providers/gomod_parser.js +16 -0
  34. package/dist/src/providers/java_gradle.d.ts +19 -0
  35. package/dist/src/providers/java_gradle.js +116 -2
  36. package/dist/src/providers/java_gradle_groovy.d.ts +1 -1
  37. package/dist/src/providers/java_gradle_kotlin.d.ts +1 -1
  38. package/dist/src/providers/java_maven.d.ts +10 -2
  39. package/dist/src/providers/java_maven.js +165 -1
  40. package/dist/src/providers/javascript_bun.d.ts +10 -0
  41. package/dist/src/providers/javascript_bun.js +100 -0
  42. package/dist/src/providers/javascript_npm.d.ts +6 -0
  43. package/dist/src/providers/javascript_npm.js +21 -0
  44. package/dist/src/providers/javascript_pnpm.d.ts +1 -1
  45. package/dist/src/providers/javascript_pnpm.js +8 -4
  46. package/dist/src/providers/manifest.d.ts +2 -0
  47. package/dist/src/providers/manifest.js +22 -4
  48. package/dist/src/providers/marker_evaluator.d.ts +14 -0
  49. package/dist/src/providers/marker_evaluator.js +191 -0
  50. package/dist/src/providers/oci_dockerfile.d.ts +51 -0
  51. package/dist/src/providers/oci_dockerfile.js +177 -0
  52. package/dist/src/providers/processors/yarn_berry_processor.d.ts +2 -2
  53. package/dist/src/providers/processors/yarn_berry_processor.js +88 -5
  54. package/dist/src/providers/processors/yarn_classic_processor.d.ts +2 -2
  55. package/dist/src/providers/python_controller.d.ts +5 -1
  56. package/dist/src/providers/python_controller.js +69 -8
  57. package/dist/src/providers/python_pip.d.ts +5 -0
  58. package/dist/src/providers/python_pip.js +6 -6
  59. package/dist/src/providers/python_pip_pyproject.d.ts +61 -0
  60. package/dist/src/providers/python_pip_pyproject.js +146 -0
  61. package/dist/src/providers/python_poetry.d.ts +98 -0
  62. package/dist/src/providers/python_poetry.js +286 -0
  63. package/dist/src/providers/python_uv.d.ts +46 -0
  64. package/dist/src/providers/python_uv.js +269 -0
  65. package/dist/src/providers/rust_cargo.d.ts +12 -3
  66. package/dist/src/providers/rust_cargo.js +115 -21
  67. package/dist/src/providers/tree-sitter-containerfile.wasm +0 -0
  68. package/dist/src/providers/tree-sitter-gomod.wasm +0 -0
  69. package/dist/src/remediate.d.ts +21 -0
  70. package/dist/src/remediate.js +149 -0
  71. package/dist/src/remediation.d.ts +57 -0
  72. package/dist/src/remediation.js +436 -0
  73. package/dist/src/remediation_report.d.ts +40 -0
  74. package/dist/src/remediation_report.js +159 -0
  75. package/dist/src/sbom.d.ts +14 -1
  76. package/dist/src/sbom.js +13 -2
  77. package/dist/src/tools.d.ts +28 -2
  78. package/dist/src/tools.js +58 -0
  79. package/dist/src/updaters/maven_updater.d.ts +26 -0
  80. package/dist/src/updaters/maven_updater.js +322 -0
  81. package/dist/src/updaters/toml_updater.d.ts +33 -0
  82. package/dist/src/updaters/toml_updater.js +244 -0
  83. package/dist/src/workspace.d.ts +70 -0
  84. package/dist/src/workspace.js +256 -0
  85. package/package.json +32 -24
package/dist/src/index.js CHANGED
@@ -1,15 +1,25 @@
1
1
  import path from "node:path";
2
2
  import { EOL } from "os";
3
+ import pLimit from 'p-limit';
3
4
  import { availableProviders, match } from './provider.js';
4
5
  import analysis from './analysis.js';
5
6
  import fs from 'node:fs';
6
7
  import { getCustom } from "./tools.js";
8
+ import { resolveBatchMetadata, resolveContinueOnError } from './batch_opts.js';
9
+ import { discoverMavenModules } from './providers/java_maven.js';
10
+ import { discoverGradleSubprojects } from './providers/java_gradle.js';
11
+ import { discoverGoWorkspaceModules } from './providers/golang_gomodules.js';
12
+ import { discoverUvWorkspaceMembers } from './providers/python_uv.js';
13
+ import { discoverWorkspaceCrates, discoverWorkspacePackages, filterManifestPathsByDiscoveryIgnore, resolveWorkspaceDiscoveryIgnore, validatePackageJson, } from './workspace.js';
7
14
  import.meta.dirname;
8
15
  import * as url from 'url';
9
16
  export { parseImageRef } from "./oci_image/utils.js";
10
17
  export { ImageRef } from "./oci_image/images.js";
11
18
  export { getProjectLicense, findLicenseFilePath, identifyLicense, getLicenseDetails, licensesFromReport, normalizeLicensesResponse, runLicenseCheck, getCompatibility } from "./license/index.js";
12
- export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken };
19
+ export { extractRemediations } from "./remediation.js";
20
+ export { generateReport, generateDeduplicationKey } from './remediation_report.js';
21
+ export default { componentAnalysis, stackAnalysis, stackAnalysisBatch, imageAnalysis, validateToken, generateSbom };
22
+ export { discoverMavenModules, discoverGradleSubprojects, discoverGoWorkspaceModules, discoverUvWorkspaceMembers, discoverWorkspacePackages, discoverWorkspaceCrates, validatePackageJson, resolveWorkspaceDiscoveryIgnore, filterManifestPathsByDiscoveryIgnore, resolveContinueOnError, resolveBatchMetadata, };
13
23
  /**
14
24
  * @typedef {{
15
25
  * TRUSTIFY_DA_CARGO_PATH?: string | undefined,
@@ -31,20 +41,44 @@ export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken
31
41
  * TRUSTIFY_DA_PYTHON_PATH?: string | undefined,
32
42
  * TRUSTIFY_DA_PYTHON_VIRTUAL_ENV?: string | undefined,
33
43
  * TRUSTIFY_DA_PYTHON3_PATH?: string | undefined,
34
- * TRUSTIFY_DA_RECOMMENDATIONS_ENABLED?: string | undefined,
44
+ * TRUSTIFY_DA_PROVIDERS?: string | undefined,
45
+ * TRUSTIFY_DA_RECOMMEND?: string | undefined,
46
+ * TRUSTIFY_DA_SOURCES?: string | undefined,
35
47
  * TRUSTIFY_DA_SKOPEO_CONFIG_PATH?: string | undefined,
36
48
  * TRUSTIFY_DA_SKOPEO_PATH?: string | undefined,
37
49
  * TRUSTIFY_DA_SYFT_CONFIG_PATH?: string | undefined,
38
50
  * TRUSTIFY_DA_SYFT_PATH?: string | undefined,
39
51
  * TRUSTIFY_DA_YARN_PATH?: string | undefined,
52
+ * TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined,
40
53
  * TRUSTIFY_DA_LICENSE_CHECK?: string | undefined,
41
54
  * MATCH_MANIFEST_VERSIONS?: string | undefined,
42
55
  * TRUSTIFY_DA_SOURCE?: string | undefined,
43
56
  * TRUSTIFY_DA_TOKEN?: string | undefined,
44
57
  * TRUSTIFY_DA_TELEMETRY_ID?: string | undefined,
45
- * [key: string]: string | undefined,
58
+ * TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined,
59
+ * batchConcurrency?: number | undefined,
60
+ * TRUSTIFY_DA_BATCH_CONCURRENCY?: string | undefined,
61
+ * workspaceDiscoveryIgnore?: string[] | undefined,
62
+ * TRUSTIFY_DA_WORKSPACE_DISCOVERY_IGNORE?: string | undefined,
63
+ * continueOnError?: boolean | undefined,
64
+ * TRUSTIFY_DA_CONTINUE_ON_ERROR?: string | undefined,
65
+ * batchMetadata?: boolean | undefined,
66
+ * TRUSTIFY_DA_BATCH_METADATA?: string | undefined,
67
+ * TRUSTIFY_DA_UV_PATH?: string | undefined,
68
+ * TRUSTIFY_DA_POETRY_PATH?: string | undefined,
69
+ * [key: string]: string | number | boolean | string[] | undefined,
46
70
  * }} Options
47
71
  */
72
+ /**
73
+ * @typedef {{
74
+ * workspaceRoot: string,
75
+ * ecosystem: 'javascript' | 'cargo' | 'pyproject' | 'unknown',
76
+ * total: number,
77
+ * successful: number,
78
+ * failed: number,
79
+ * errors: Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>
80
+ * }} BatchAnalysisMetadata
81
+ */
48
82
  /**
49
83
  * Logs messages to the console if the TRUSTIFY_DA_DEBUG environment variable is set to "true".
50
84
  * @param {string} alongsideText - The text to prepend to the log message.
@@ -130,7 +164,7 @@ export function selectTrustifyDABackend(opts = {}) {
130
164
  async function stackAnalysis(manifest, html = false, opts = {}) {
131
165
  const theUrl = selectTrustifyDABackend(opts);
132
166
  fs.accessSync(manifest, fs.constants.R_OK); // throws error if file unreadable
133
- let provider = match(manifest, availableProviders); // throws error if no matching provider
167
+ let provider = match(manifest, availableProviders, opts); // throws error if no matching provider
134
168
  return await analysis.requestStack(provider, manifest, theUrl, html, opts); // throws error request sending failed
135
169
  }
136
170
  /**
@@ -144,8 +178,10 @@ async function componentAnalysis(manifest, opts = {}) {
144
178
  const theUrl = selectTrustifyDABackend(opts);
145
179
  fs.accessSync(manifest, fs.constants.R_OK);
146
180
  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
181
+ let provider = match(manifest, availableProviders, opts); // throws error if no matching provider
182
+ const result = await analysis.requestComponent(provider, manifest, theUrl, opts); // throws error request sending failed
183
+ result.packageManager = provider.packageManagerName();
184
+ return result;
149
185
  }
150
186
  /**
151
187
  * @overload
@@ -177,6 +213,319 @@ async function imageAnalysis(imageRefs, html = false, opts = {}) {
177
213
  const theUrl = selectTrustifyDABackend(opts);
178
214
  return await analysis.requestImages(imageRefs, theUrl, html, opts);
179
215
  }
216
+ /**
217
+ * Max concurrent SBOM generations for batch workspace analysis. Env/opts override default 10.
218
+ * @param {Options} opts
219
+ * @returns {number}
220
+ * @private
221
+ */
222
+ function resolveBatchConcurrency(opts) {
223
+ const fromEnv = getCustom('TRUSTIFY_DA_BATCH_CONCURRENCY', null, opts);
224
+ const raw = opts.batchConcurrency ?? fromEnv ?? '10';
225
+ const n = typeof raw === 'number' ? raw : parseInt(String(raw), 10);
226
+ if (!Number.isFinite(n) || n < 1) {
227
+ return 10;
228
+ }
229
+ return Math.min(256, n);
230
+ }
231
+ /**
232
+ * @param {string} root
233
+ * @param {'javascript' | 'cargo' | 'unknown'} ecosystem
234
+ * @param {number} totalSbomAttempts
235
+ * @param {number} successfulSbomCount
236
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} errors
237
+ * @returns {BatchAnalysisMetadata}
238
+ * @private
239
+ */
240
+ function buildBatchAnalysisMetadata(root, ecosystem, totalSbomAttempts, successfulSbomCount, errors) {
241
+ return {
242
+ workspaceRoot: root,
243
+ ecosystem,
244
+ total: totalSbomAttempts,
245
+ successful: successfulSbomCount,
246
+ failed: errors.length,
247
+ errors: [...errors],
248
+ };
249
+ }
250
+ /**
251
+ * Generate a CycloneDX SBOM from a manifest file. No backend HTTP request is made.
252
+ *
253
+ * @param {string} manifestPath - path to the manifest file (e.g. pom.xml, package.json)
254
+ * @param {Options} [opts={}] - optional options (e.g. workspace dir, tool paths)
255
+ * @returns {Promise<object>} parsed CycloneDX SBOM JSON object
256
+ * @throws {Error} if the manifest is unsupported or SBOM generation fails
257
+ */
258
+ export async function generateSbom(manifestPath, opts = {}) {
259
+ fs.accessSync(manifestPath, fs.constants.R_OK);
260
+ const result = await generateOneSbom(manifestPath, opts);
261
+ if (!result.ok) {
262
+ throw new Error(`Failed to generate SBOM for ${result.manifestPath}: ${result.reason}`);
263
+ }
264
+ return result.sbom;
265
+ }
266
+ /**
267
+ * @typedef {{ ok: true, purl: string, sbom: object } | { ok: false, manifestPath: string, reason: string }} SbomResult
268
+ */
269
+ /**
270
+ * Generate an SBOM for a single manifest, returning a normalized result.
271
+ *
272
+ * @param {string} manifestPath
273
+ * @param {Options} workspaceOpts - opts with `TRUSTIFY_DA_WORKSPACE_DIR` set
274
+ * @returns {Promise<SbomResult>}
275
+ * @private
276
+ */
277
+ async function generateOneSbom(manifestPath, workspaceOpts) {
278
+ const provider = match(manifestPath, availableProviders, workspaceOpts);
279
+ const provided = await provider.provideStack(manifestPath, workspaceOpts);
280
+ const sbom = JSON.parse(provided.content);
281
+ const purl = sbom?.metadata?.component?.purl || sbom?.metadata?.component?.['bom-ref'];
282
+ if (!purl) {
283
+ return { ok: false, manifestPath, reason: 'missing purl in SBOM' };
284
+ }
285
+ return { ok: true, purl, sbom };
286
+ }
287
+ /**
288
+ * Detect the workspace ecosystem and discover manifest paths.
289
+ *
290
+ * @param {string} root - Resolved workspace root
291
+ * @param {Options} opts
292
+ * @returns {Promise<{ ecosystem: 'javascript' | 'cargo' | 'maven' | 'gradle' | 'gomodules' | 'pyproject' | 'unknown', manifestPaths: string[] }>}
293
+ * @private
294
+ */
295
+ async function detectWorkspaceManifests(root, opts) {
296
+ const cargoToml = path.join(root, 'Cargo.toml');
297
+ const cargoLock = path.join(root, 'Cargo.lock');
298
+ const packageJson = path.join(root, 'package.json');
299
+ const pomXml = path.join(root, 'pom.xml');
300
+ if (fs.existsSync(cargoToml) && fs.existsSync(cargoLock)) {
301
+ return { ecosystem: 'cargo', manifestPaths: await discoverWorkspaceCrates(root, opts) };
302
+ }
303
+ if (fs.existsSync(pomXml)) {
304
+ const manifestPaths = await discoverMavenModules(root, opts);
305
+ if (manifestPaths.length > 0) {
306
+ return { ecosystem: 'maven', manifestPaths };
307
+ }
308
+ }
309
+ const hasGradleSettings = fs.existsSync(path.join(root, 'settings.gradle'))
310
+ || fs.existsSync(path.join(root, 'settings.gradle.kts'));
311
+ if (hasGradleSettings) {
312
+ const manifestPaths = await discoverGradleSubprojects(root, opts);
313
+ if (manifestPaths.length > 0) {
314
+ return { ecosystem: 'gradle', manifestPaths };
315
+ }
316
+ }
317
+ if (fs.existsSync(path.join(root, 'go.work'))) {
318
+ const manifestPaths = await discoverGoWorkspaceModules(root, opts);
319
+ if (manifestPaths.length > 0) {
320
+ return { ecosystem: 'gomodules', manifestPaths };
321
+ }
322
+ }
323
+ if (fs.existsSync(path.join(root, 'pyproject.toml')) && fs.existsSync(path.join(root, 'uv.lock'))) {
324
+ const manifestPaths = await discoverUvWorkspaceMembers(root, opts);
325
+ if (manifestPaths.length > 0) {
326
+ return { ecosystem: 'pyproject', manifestPaths };
327
+ }
328
+ }
329
+ const hasJsLock = fs.existsSync(path.join(root, 'bun.lock'))
330
+ || fs.existsSync(path.join(root, 'pnpm-lock.yaml'))
331
+ || fs.existsSync(path.join(root, 'yarn.lock'))
332
+ || fs.existsSync(path.join(root, 'package-lock.json'));
333
+ if (fs.existsSync(packageJson) && hasJsLock) {
334
+ let manifestPaths = await discoverWorkspacePackages(root, opts);
335
+ if (manifestPaths.length === 0) {
336
+ manifestPaths = [packageJson];
337
+ }
338
+ return { ecosystem: 'javascript', manifestPaths };
339
+ }
340
+ return { ecosystem: 'unknown', manifestPaths: [] };
341
+ }
342
+ /**
343
+ * Validate discovered JS package.json manifests, collecting errors.
344
+ *
345
+ * @param {string[]} manifestPaths
346
+ * @param {boolean} continueOnError
347
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} collectedErrors - mutated in place
348
+ * @returns {{ validPaths: string[] }}
349
+ * @throws {Error} on first invalid manifest when `continueOnError` is false
350
+ * @private
351
+ */
352
+ function validateJsManifests(manifestPaths, continueOnError, collectedErrors) {
353
+ const validPaths = [];
354
+ for (const p of manifestPaths) {
355
+ const v = validatePackageJson(p);
356
+ if (v.valid) {
357
+ validPaths.push(p);
358
+ }
359
+ else {
360
+ collectedErrors.push({ manifestPath: p, phase: 'validation', reason: v.error });
361
+ console.warn(`Skipping invalid package.json (${v.error}): ${p}`);
362
+ if (!continueOnError) {
363
+ throw new Error(`Invalid package.json (${v.error}): ${p}`);
364
+ }
365
+ }
366
+ }
367
+ return { validPaths };
368
+ }
369
+ /**
370
+ * Generate SBOMs for all manifests. In fail-fast mode, stops on first error.
371
+ * In continue-on-error mode, runs concurrently and collects failures.
372
+ *
373
+ * @param {string[]} manifestPaths
374
+ * @param {Options} workspaceOpts
375
+ * @param {boolean} continueOnError
376
+ * @param {number} concurrency
377
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} collectedErrors - mutated in place
378
+ * @returns {Promise<Object.<string, object>>} sbomByPurl map
379
+ * @throws {Error} on first SBOM failure when `continueOnError` is false
380
+ * @private
381
+ */
382
+ async function generateSboms(manifestPaths, workspaceOpts, continueOnError, concurrency, collectedErrors) {
383
+ /** @type {SbomResult[]} */
384
+ const results = [];
385
+ if (!continueOnError) {
386
+ for (const manifestPath of manifestPaths) {
387
+ const result = await generateOneSbom(manifestPath, workspaceOpts);
388
+ if (!result.ok) {
389
+ collectedErrors.push({ manifestPath: result.manifestPath, phase: 'sbom', reason: result.reason });
390
+ throw new Error(`${result.manifestPath}: ${result.reason}`);
391
+ }
392
+ results.push(result);
393
+ }
394
+ }
395
+ else {
396
+ const limit = pLimit(concurrency);
397
+ const settled = await Promise.all(manifestPaths.map(manifestPath => limit(async () => {
398
+ try {
399
+ return await generateOneSbom(manifestPath, workspaceOpts);
400
+ }
401
+ catch (err) {
402
+ const msg = err instanceof Error ? err.message : String(err);
403
+ if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
404
+ console.log(`Skipping ${manifestPath}: ${msg}`);
405
+ }
406
+ return { ok: false, manifestPath, reason: msg };
407
+ }
408
+ })));
409
+ for (const r of settled) {
410
+ results.push(r);
411
+ if (!r.ok) {
412
+ collectedErrors.push({ manifestPath: r.manifestPath, phase: 'sbom', reason: r.reason });
413
+ }
414
+ }
415
+ }
416
+ const sbomByPurl = {};
417
+ for (const r of results) {
418
+ if (r.ok) {
419
+ sbomByPurl[r.purl] = r.sbom;
420
+ }
421
+ }
422
+ return sbomByPurl;
423
+ }
424
+ /**
425
+ * Create an Error with optional `batchMetadata` attached.
426
+ * @param {string} message
427
+ * @param {boolean} wantMetadata
428
+ * @param {BatchAnalysisMetadata} [metadata]
429
+ * @returns {Error}
430
+ * @private
431
+ */
432
+ function batchError(message, wantMetadata, metadata) {
433
+ const err = new Error(message);
434
+ if (wantMetadata && metadata) {
435
+ err.batchMetadata = metadata;
436
+ }
437
+ return err;
438
+ }
439
+ /**
440
+ * @overload
441
+ * @param {string} workspaceRoot
442
+ * @param {true} html
443
+ * @param {Options & { batchMetadata: true }} opts
444
+ * @returns {Promise<{ analysis: string, metadata: BatchAnalysisMetadata }>}
445
+ * @throws {Error}
446
+ */
447
+ /**
448
+ * @overload
449
+ * @param {string} workspaceRoot
450
+ * @param {true} html
451
+ * @param {Options & { batchMetadata?: false }} [opts={}]
452
+ * @returns {Promise<string>}
453
+ * @throws {Error}
454
+ */
455
+ /**
456
+ * @overload
457
+ * @param {string} workspaceRoot
458
+ * @param {false} html
459
+ * @param {Options & { batchMetadata: true }} opts
460
+ * @returns {Promise<{ analysis: Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>, metadata: BatchAnalysisMetadata }>}
461
+ * @throws {Error}
462
+ */
463
+ /**
464
+ * @overload
465
+ * @param {string} workspaceRoot
466
+ * @param {false} html
467
+ * @param {Options & { batchMetadata?: false }} [opts={}]
468
+ * @returns {Promise<Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>>}
469
+ * @throws {Error}
470
+ */
471
+ /**
472
+ * Get stack analysis for all workspace packages/crates (batch).
473
+ * Detects ecosystem from workspace root: Cargo (Cargo.toml + Cargo.lock) or JS/TS (package.json + lock file).
474
+ * SBOMs are generated in parallel (see `batchConcurrency`) unless `continueOnError: false` (fail-fast sequential).
475
+ * With `opts.batchMetadata` / `TRUSTIFY_DA_BATCH_METADATA`, returns `{ analysis, metadata }` including validation and SBOM errors.
476
+ *
477
+ * @overload
478
+ * @param {string} workspaceRoot - Path to workspace root (containing lock file and workspace config)
479
+ * @param {boolean} [html=false] - true returns HTML, false returns JSON report
480
+ * @param {Options} [opts={}] - `batchConcurrency`, discovery ignores, `continueOnError` (default true), `batchMetadata` (default false)
481
+ * @returns {Promise<string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>|{ analysis: string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>, metadata: BatchAnalysisMetadata }>}
482
+ * @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.
483
+ */
484
+ async function stackAnalysisBatch(workspaceRoot, html = false, opts = {}) {
485
+ const theUrl = selectTrustifyDABackend(opts);
486
+ const root = path.resolve(workspaceRoot);
487
+ fs.accessSync(root, fs.constants.R_OK);
488
+ const continueOnError = resolveContinueOnError(opts);
489
+ const wantMetadata = resolveBatchMetadata(opts);
490
+ /** @type {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} */
491
+ const collectedErrors = [];
492
+ const { ecosystem, manifestPaths: discovered } = await detectWorkspaceManifests(root, opts);
493
+ let manifestPaths = discovered;
494
+ if (ecosystem === 'javascript') {
495
+ try {
496
+ const { validPaths } = validateJsManifests(manifestPaths, continueOnError, collectedErrors);
497
+ manifestPaths = validPaths;
498
+ }
499
+ catch (err) {
500
+ throw batchError(err.message, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, 0, 0, collectedErrors));
501
+ }
502
+ if (manifestPaths.length === 0 && discovered.length > 0) {
503
+ const detail = collectedErrors.map(e => `${e.manifestPath}: ${e.reason}`).join('; ');
504
+ throw batchError(`No valid packages after validation at ${root}. ${detail}`, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, 0, 0, collectedErrors));
505
+ }
506
+ }
507
+ if (manifestPaths.length === 0) {
508
+ 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).`);
509
+ }
510
+ const workspaceOpts = { ...opts, TRUSTIFY_DA_WORKSPACE_DIR: root };
511
+ const concurrency = resolveBatchConcurrency(opts);
512
+ let sbomByPurl;
513
+ try {
514
+ sbomByPurl = await generateSboms(manifestPaths, workspaceOpts, continueOnError, concurrency, collectedErrors);
515
+ }
516
+ catch (err) {
517
+ throw batchError(err.message, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, 0, collectedErrors));
518
+ }
519
+ if (Object.keys(sbomByPurl).length === 0) {
520
+ throw batchError(`No valid SBOMs produced from ${manifestPaths.length} manifest(s) at ${root}`, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, 0, collectedErrors));
521
+ }
522
+ const analysisResult = await analysis.requestStackBatch(sbomByPurl, theUrl, html, opts);
523
+ const meta = buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, Object.keys(sbomByPurl).length, collectedErrors);
524
+ if (wantMetadata) {
525
+ return { analysis: analysisResult, metadata: meta };
526
+ }
527
+ return analysisResult;
528
+ }
180
529
  /**
181
530
  * Validates the Exhort token.
182
531
  * @param {Options} [opts={}] - Optional parameters, potentially including token override.
@@ -9,10 +9,10 @@
9
9
  * @param {import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').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?: any): 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<{
@@ -85,11 +85,14 @@ export async function runLicenseCheck(sbomContent, manifestPath, url, opts = {},
85
85
  continue;
86
86
  const status = getCompatibility(projectCategory, entry.category);
87
87
  if (status === 'incompatible') {
88
+ const reason = entry.category?.toUpperCase() === 'UNKNOWN'
89
+ ? 'License not recognized as a standard SPDX identifier. Manual review recommended to verify compatibility.'
90
+ : 'Dependency license(s) are incompatible with the project license.';
88
91
  incompatibleDependencies.push({
89
92
  purl,
90
93
  licenses: entry.licenses,
91
94
  category: entry.category,
92
- reason: 'Dependency license(s) are incompatible with the project license.'
95
+ reason
93
96
  });
94
97
  }
95
98
  }
@@ -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 } }.
@@ -28,7 +28,7 @@ export function normalizeLicensesResponse(data: unknown, purls?: string[]): Map<
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: any, purls?: string[]): Map<string, {
32
32
  licenses: string[];
33
33
  category?: string;
34
34
  }>;
@@ -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
  }
@@ -4,7 +4,7 @@
4
4
  * @param {import("../index.js").Options} [opts={}] - optional various options to pass along the application
5
5
  * @returns {{}}
6
6
  */
7
- export function generateImageSBOM(imageRef: import("./images").ImageRef, opts?: import("../index.js").Options): {};
7
+ export function generateImageSBOM(imageRef: any, opts?: import("../index.js").Options): {};
8
8
  /**
9
9
  *
10
10
  * @param {string} image
@@ -25,7 +25,7 @@ export function getImagePlatform(opts?: import("../index.js").Options): Platform
25
25
  * @returns {Object.<string, string>} - The image digests
26
26
  * @throws {Error} If the image info is invalid
27
27
  */
28
- export function getImageDigests(imageRef: import("./images").ImageRef, opts?: import("../index.js").Options): {
28
+ export function getImageDigests(imageRef: any, opts?: import("../index.js").Options): {
29
29
  [x: string]: string;
30
30
  };
31
31
  export type SyftImageSource = {
@@ -34,9 +34,9 @@ export type SyftImageSource = {
34
34
  getVariant: () => string;
35
35
  };
36
36
  export type SyftImageSourceType = {
37
- getOs: (arg0: any) => string;
38
- getArch: (arg0: any) => string;
39
- getVariant: (arg0: any) => string;
37
+ getOs: (arg0: Object) => string;
38
+ getArch: (arg0: Object) => string;
39
+ getVariant: (arg0: Object) => string;
40
40
  };
41
41
  import { ImageRef } from './images.js';
42
42
  import { Platform } from './platform.js';
@@ -135,7 +135,7 @@ function execSyft(imageRef, opts = {}) {
135
135
  function getSyftEnvs(dockerPath, podmanPath) {
136
136
  let path = null;
137
137
  if (dockerPath && podmanPath) {
138
- path = `${dockerPath}${File.pathSeparator}${podmanPath}`;
138
+ path = `${dockerPath}${delimiter}${podmanPath}`;
139
139
  }
140
140
  else if (dockerPath) {
141
141
  path = dockerPath;
@@ -276,7 +276,16 @@ function podmanGetVariant(opts = {}) {
276
276
  * @returns {string} - The information
277
277
  */
278
278
  function dockerPodmanInfo(dockerSupplier, podmanSupplier, opts = {}) {
279
- return dockerSupplier(opts) || podmanSupplier(opts);
279
+ try {
280
+ const result = dockerSupplier(opts);
281
+ if (result) {
282
+ return result;
283
+ }
284
+ }
285
+ catch (_) {
286
+ // docker not available, fall through to podman
287
+ }
288
+ return podmanSupplier(opts);
280
289
  }
281
290
  /**
282
291
  * Gets the digests for an image
@@ -13,12 +13,15 @@ export function matchForLicense(manifestPath: string, providers: [Provider]): Pr
13
13
  * Each provider MUST export 'provideStack' taking manifest path returning a {@link Provided}.
14
14
  * @param {string} manifest - the name-type or path of the manifest
15
15
  * @param {[Provider]} providers - list of providers to iterate over
16
+ * @param {{TRUSTIFY_DA_WORKSPACE_DIR?: string}} [opts={}] - optional; TRUSTIFY_DA_WORKSPACE_DIR overrides lock file location for workspaces
16
17
  * @returns {Provider}
17
18
  * @throws {Error} when the manifest is not supported and no provider was matched
18
19
  */
19
- export function match(manifest: string, providers: [Provider]): Provider;
20
+ export function match(manifest: string, providers: [Provider], opts?: {
21
+ TRUSTIFY_DA_WORKSPACE_DIR?: string;
22
+ }): Provider;
20
23
  /** @typedef {{ecosystem: string, contentType: string, content: string}} Provided */
21
- /** @typedef {{isSupported: function(string): boolean, validateLockFile: function(string): void, provideComponent: function(string, {}): Provided | Promise<Provided>, provideStack: function(string, {}): Provided | Promise<Provided>, readLicenseFromManifest: function(string): string | null}} Provider */
24
+ /** @typedef {{isSupported: function(string): boolean, validateLockFile: function(string, Object): void, provideComponent: function(string, {}): Provided | Promise<Provided>, provideStack: function(string, {}): Provided | Promise<Provided>, readLicenseFromManifest: function(string, Object=): string | null, packageManagerName: function(): string}} Provider */
22
25
  /**
23
26
  * MUST include all providers here.
24
27
  * @type {[Provider]}
@@ -31,8 +34,9 @@ export type Provided = {
31
34
  };
32
35
  export type Provider = {
33
36
  isSupported: (arg0: string) => boolean;
34
- validateLockFile: (arg0: string) => void;
37
+ validateLockFile: (arg0: string, arg1: Object) => void;
35
38
  provideComponent: (arg0: string, arg1: {}) => Provided | Promise<Provided>;
36
39
  provideStack: (arg0: string, arg1: {}) => Provided | Promise<Provided>;
37
- readLicenseFromManifest: (arg0: string) => string | null;
40
+ readLicenseFromManifest: (arg0: string, arg1: Object | undefined) => string | null;
41
+ packageManagerName: () => string;
38
42
  };
@@ -3,13 +3,18 @@ import golangGomodulesProvider from './providers/golang_gomodules.js';
3
3
  import Java_gradle_groovy from "./providers/java_gradle_groovy.js";
4
4
  import Java_gradle_kotlin from "./providers/java_gradle_kotlin.js";
5
5
  import Java_maven from "./providers/java_maven.js";
6
+ import Javascript_bun from './providers/javascript_bun.js';
6
7
  import Javascript_npm from './providers/javascript_npm.js';
7
8
  import Javascript_pnpm from './providers/javascript_pnpm.js';
8
9
  import Javascript_yarn from './providers/javascript_yarn.js';
10
+ import dockerfileProvider from './providers/oci_dockerfile.js';
9
11
  import pythonPipProvider from './providers/python_pip.js';
12
+ import Python_pip_pyproject from './providers/python_pip_pyproject.js';
13
+ import Python_poetry from './providers/python_poetry.js';
14
+ import Python_uv from './providers/python_uv.js';
10
15
  import rustCargoProvider from './providers/rust_cargo.js';
11
16
  /** @typedef {{ecosystem: string, contentType: string, content: string}} Provided */
12
- /** @typedef {{isSupported: function(string): boolean, validateLockFile: function(string): void, provideComponent: function(string, {}): Provided | Promise<Provided>, provideStack: function(string, {}): Provided | Promise<Provided>, readLicenseFromManifest: function(string): string | null}} Provider */
17
+ /** @typedef {{isSupported: function(string): boolean, validateLockFile: function(string, Object): void, provideComponent: function(string, {}): Provided | Promise<Provided>, provideStack: function(string, {}): Provided | Promise<Provided>, readLicenseFromManifest: function(string, Object=): string | null, packageManagerName: function(): string}} Provider */
13
18
  /**
14
19
  * MUST include all providers here.
15
20
  * @type {[Provider]}
@@ -18,12 +23,17 @@ export const availableProviders = [
18
23
  new Java_maven(),
19
24
  new Java_gradle_groovy(),
20
25
  new Java_gradle_kotlin(),
21
- new Javascript_npm(),
26
+ new Javascript_bun(),
22
27
  new Javascript_pnpm(),
23
28
  new Javascript_yarn(),
29
+ new Javascript_npm(),
24
30
  golangGomodulesProvider,
25
31
  pythonPipProvider,
26
- rustCargoProvider
32
+ new Python_poetry(),
33
+ new Python_uv(),
34
+ new Python_pip_pyproject(),
35
+ rustCargoProvider,
36
+ dockerfileProvider
27
37
  ];
28
38
  /**
29
39
  * Match a provider by manifest type only (no lock file check). Used for license reading.
@@ -47,16 +57,17 @@ export function matchForLicense(manifestPath, providers) {
47
57
  * Each provider MUST export 'provideStack' taking manifest path returning a {@link Provided}.
48
58
  * @param {string} manifest - the name-type or path of the manifest
49
59
  * @param {[Provider]} providers - list of providers to iterate over
60
+ * @param {{TRUSTIFY_DA_WORKSPACE_DIR?: string}} [opts={}] - optional; TRUSTIFY_DA_WORKSPACE_DIR overrides lock file location for workspaces
50
61
  * @returns {Provider}
51
62
  * @throws {Error} when the manifest is not supported and no provider was matched
52
63
  */
53
- export function match(manifest, providers) {
64
+ export function match(manifest, providers, opts = {}) {
54
65
  const manifestPath = path.parse(manifest);
55
66
  const supported = providers.filter(prov => prov.isSupported(manifestPath.base));
56
67
  if (supported.length === 0) {
57
68
  throw new Error(`${manifestPath.base} is not supported`);
58
69
  }
59
- const provider = supported.find(prov => prov.validateLockFile(manifestPath.dir));
70
+ const provider = supported.find(prov => prov.validateLockFile(manifestPath.dir, opts));
60
71
  if (!provider) {
61
72
  throw new Error(`${manifestPath.base} requires a lock file. Use your preferred package manager to generate the lock file.`);
62
73
  }