@trustify-da/trustify-da-javascript-client 0.3.0-ea.b40d888 → 0.3.0-ea.c2f6c64

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 (65) hide show
  1. package/README.md +191 -11
  2. package/dist/package.json +23 -10
  3. package/dist/src/analysis.d.ts +21 -5
  4. package/dist/src/analysis.js +74 -80
  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 +241 -8
  8. package/dist/src/cyclone_dx_sbom.d.ts +10 -2
  9. package/dist/src/cyclone_dx_sbom.js +32 -5
  10. package/dist/src/index.d.ts +138 -11
  11. package/dist/src/index.js +288 -7
  12. package/dist/src/license/index.d.ts +28 -0
  13. package/dist/src/license/index.js +100 -0
  14. package/dist/src/license/license_utils.d.ts +40 -0
  15. package/dist/src/license/license_utils.js +134 -0
  16. package/dist/src/license/licenses_api.d.ts +34 -0
  17. package/dist/src/license/licenses_api.js +98 -0
  18. package/dist/src/license/project_license.d.ts +20 -0
  19. package/dist/src/license/project_license.js +62 -0
  20. package/dist/src/oci_image/images.d.ts +4 -5
  21. package/dist/src/oci_image/utils.d.ts +4 -4
  22. package/dist/src/oci_image/utils.js +11 -2
  23. package/dist/src/provider.d.ts +17 -5
  24. package/dist/src/provider.js +27 -5
  25. package/dist/src/providers/base_java.d.ts +3 -5
  26. package/dist/src/providers/base_javascript.d.ts +29 -7
  27. package/dist/src/providers/base_javascript.js +129 -22
  28. package/dist/src/providers/base_pyproject.d.ts +147 -0
  29. package/dist/src/providers/base_pyproject.js +279 -0
  30. package/dist/src/providers/golang_gomodules.d.ts +20 -13
  31. package/dist/src/providers/golang_gomodules.js +112 -114
  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 +9 -3
  35. package/dist/src/providers/java_gradle.js +12 -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 +12 -5
  39. package/dist/src/providers/java_maven.js +33 -5
  40. package/dist/src/providers/javascript_pnpm.d.ts +1 -1
  41. package/dist/src/providers/javascript_pnpm.js +2 -2
  42. package/dist/src/providers/manifest.d.ts +2 -0
  43. package/dist/src/providers/manifest.js +22 -4
  44. package/dist/src/providers/processors/yarn_berry_processor.js +82 -3
  45. package/dist/src/providers/python_controller.d.ts +5 -2
  46. package/dist/src/providers/python_controller.js +56 -58
  47. package/dist/src/providers/python_pip.d.ts +11 -4
  48. package/dist/src/providers/python_pip.js +47 -54
  49. package/dist/src/providers/python_poetry.d.ts +42 -0
  50. package/dist/src/providers/python_poetry.js +146 -0
  51. package/dist/src/providers/python_uv.d.ts +26 -0
  52. package/dist/src/providers/python_uv.js +118 -0
  53. package/dist/src/providers/requirements_parser.d.ts +6 -0
  54. package/dist/src/providers/requirements_parser.js +24 -0
  55. package/dist/src/providers/rust_cargo.d.ts +52 -0
  56. package/dist/src/providers/rust_cargo.js +614 -0
  57. package/dist/src/providers/tree-sitter-gomod.wasm +0 -0
  58. package/dist/src/providers/tree-sitter-requirements.wasm +0 -0
  59. package/dist/src/sbom.d.ts +10 -1
  60. package/dist/src/sbom.js +12 -2
  61. package/dist/src/tools.d.ts +22 -6
  62. package/dist/src/tools.js +56 -1
  63. package/dist/src/workspace.d.ts +61 -0
  64. package/dist/src/workspace.js +256 -0
  65. package/package.json +24 -11
@@ -5,10 +5,11 @@ import { PackageURL } from "packageurl-js";
5
5
  * @param component {PackageURL}
6
6
  * @param type type of package - application or library
7
7
  * @param scope scope of the component - runtime or compile
8
- * @return {{"bom-ref": string, name, purl: string, type, version, scope}}
8
+ * @param licenses optional license string or array of licenses for the component
9
+ * @return {{"bom-ref": string, name, purl: string, type, version, scope, licenses?}}
9
10
  * @private
10
11
  */
11
- function getComponent(component, type, scope) {
12
+ function getComponent(component, type, scope, licenses) {
12
13
  let componentObject;
13
14
  if (component instanceof PackageURL) {
14
15
  if (component.namespace) {
@@ -36,6 +37,16 @@ function getComponent(component, type, scope) {
36
37
  else {
37
38
  componentObject = component;
38
39
  }
40
+ // Add licenses if provided (CycloneDX format). Callers must provide valid SPDX identifiers.
41
+ if (licenses) {
42
+ const licenseArray = Array.isArray(licenses) ? licenses : [licenses];
43
+ componentObject.licenses = licenseArray.map(lic => {
44
+ if (typeof lic === 'string') {
45
+ return { license: { id: lic } };
46
+ }
47
+ return lic;
48
+ });
49
+ }
39
50
  return componentObject;
40
51
  }
41
52
  function createDependency(dependency) {
@@ -56,11 +67,12 @@ export default class CycloneDxSbom {
56
67
  }
57
68
  /**
58
69
  * @param {PackageURL} root - add main/root component for sbom
70
+ * @param {string|Array} [licenses] - optional license(s) for the root component
59
71
  * @return {CycloneDxSbom} the CycloneDxSbom Sbom Object
60
72
  */
61
- addRoot(root) {
73
+ addRoot(root, licenses) {
62
74
  this.rootComponent =
63
- getComponent(root, "application");
75
+ getComponent(root, "application", undefined, licenses);
64
76
  this.components.push(this.rootComponent);
65
77
  return this;
66
78
  }
@@ -108,6 +120,7 @@ export default class CycloneDxSbom {
108
120
  getAsJsonString(opts) {
109
121
  let manifestType = opts["manifest-type"];
110
122
  this.setSourceManifest(opts["source-manifest"]);
123
+ const rootPurl = this.rootComponent?.purl;
111
124
  this.sbomObject = {
112
125
  "bomFormat": "CycloneDX",
113
126
  "specVersion": "1.4",
@@ -117,7 +130,7 @@ export default class CycloneDxSbom {
117
130
  "component": this.rootComponent,
118
131
  "properties": new Array()
119
132
  },
120
- "components": this.components,
133
+ "components": this.components.filter(c => c.purl !== rootPurl),
121
134
  "dependencies": this.dependencies
122
135
  };
123
136
  if (this.rootComponent === undefined) {
@@ -229,6 +242,20 @@ export default class CycloneDxSbom {
229
242
  return false;
230
243
  }
231
244
  }
245
+ /**
246
+ * Checks if any entry in the dependsOn list of sourceRef starts with the given purl prefix.
247
+ * @param {PackageURL} sourceRef - The source component
248
+ * @param {string} purlPrefix - The purl prefix to match (e.g. "pkg:npm/minimist@")
249
+ * @return {boolean}
250
+ */
251
+ checkDependsOnByPurlPrefix(sourceRef, purlPrefix) {
252
+ const sourcePurl = sourceRef.toString();
253
+ const depIndex = this.getDependencyIndex(sourcePurl);
254
+ if (depIndex < 0) {
255
+ return false;
256
+ }
257
+ return this.dependencies[depIndex].dependsOn.some(dep => dep.startsWith(purlPrefix));
258
+ }
232
259
  /** Removes the root component from the sbom
233
260
  */
234
261
  removeRootComponent() {
@@ -12,18 +12,29 @@
12
12
  export function selectTrustifyDABackend(opts?: {
13
13
  TRUSTIFY_DA_DEBUG?: string | undefined;
14
14
  TRUSTIFY_DA_BACKEND_URL?: string | undefined;
15
- } | undefined): string;
15
+ }): string;
16
+ /**
17
+ * Generate a CycloneDX SBOM from a manifest file. No backend HTTP request is made.
18
+ *
19
+ * @param {string} manifestPath - path to the manifest file (e.g. pom.xml, package.json)
20
+ * @param {Options} [opts={}] - optional options (e.g. workspace dir, tool paths)
21
+ * @returns {Promise<object>} parsed CycloneDX SBOM JSON object
22
+ * @throws {Error} if the manifest is unsupported or SBOM generation fails
23
+ */
24
+ export function generateSbom(manifestPath: string, opts?: Options): Promise<object>;
16
25
  export { parseImageRef } from "./oci_image/utils.js";
17
26
  export { ImageRef } from "./oci_image/images.js";
18
27
  declare namespace _default {
19
28
  export { componentAnalysis };
20
29
  export { stackAnalysis };
30
+ export { stackAnalysisBatch };
21
31
  export { imageAnalysis };
22
32
  export { validateToken };
33
+ export { generateSbom };
23
34
  }
24
35
  export default _default;
25
36
  export type Options = {
26
- [key: string]: string | undefined;
37
+ TRUSTIFY_DA_CARGO_PATH?: string | undefined;
27
38
  TRUSTIFY_DA_DOCKER_PATH?: string | undefined;
28
39
  TRUSTIFY_DA_GO_MVS_LOGIC_ENABLED?: string | undefined;
29
40
  TRUSTIFY_DA_GO_PATH?: string | undefined;
@@ -48,10 +59,45 @@ export type Options = {
48
59
  TRUSTIFY_DA_SYFT_CONFIG_PATH?: string | undefined;
49
60
  TRUSTIFY_DA_SYFT_PATH?: string | undefined;
50
61
  TRUSTIFY_DA_YARN_PATH?: string | undefined;
62
+ TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined;
63
+ TRUSTIFY_DA_LICENSE_CHECK?: string | undefined;
51
64
  MATCH_MANIFEST_VERSIONS?: string | undefined;
52
- RHDA_SOURCE?: string | undefined;
53
- RHDA_TOKEN?: string | undefined;
54
- RHDA_TELEMETRY_ID?: string | undefined;
65
+ TRUSTIFY_DA_SOURCE?: string | undefined;
66
+ TRUSTIFY_DA_TOKEN?: string | undefined;
67
+ TRUSTIFY_DA_TELEMETRY_ID?: string | undefined;
68
+ TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined;
69
+ batchConcurrency?: number | undefined;
70
+ TRUSTIFY_DA_BATCH_CONCURRENCY?: string | undefined;
71
+ workspaceDiscoveryIgnore?: string[] | undefined;
72
+ TRUSTIFY_DA_WORKSPACE_DISCOVERY_IGNORE?: string | undefined;
73
+ continueOnError?: boolean | undefined;
74
+ TRUSTIFY_DA_CONTINUE_ON_ERROR?: string | undefined;
75
+ batchMetadata?: boolean | undefined;
76
+ TRUSTIFY_DA_BATCH_METADATA?: string | undefined;
77
+ TRUSTIFY_DA_UV_PATH?: string | undefined;
78
+ TRUSTIFY_DA_POETRY_PATH?: string | undefined;
79
+ [key: string]: string | number | boolean | string[] | undefined;
80
+ };
81
+ export type BatchAnalysisMetadata = {
82
+ workspaceRoot: string;
83
+ ecosystem: "javascript" | "cargo" | "unknown";
84
+ total: number;
85
+ successful: number;
86
+ failed: number;
87
+ errors: Array<{
88
+ manifestPath: string;
89
+ phase: "validation" | "sbom";
90
+ reason: string;
91
+ }>;
92
+ };
93
+ export type SbomResult = {
94
+ ok: true;
95
+ purl: string;
96
+ sbom: object;
97
+ } | {
98
+ ok: false;
99
+ manifestPath: string;
100
+ reason: string;
55
101
  };
56
102
  /**
57
103
  * Get component analysis report for a manifest content.
@@ -60,16 +106,88 @@ export type Options = {
60
106
  * @returns {Promise<import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>}
61
107
  * @throws {Error} if no matching provider, failed to get create content, or backend request failed
62
108
  */
63
- declare function componentAnalysis(manifest: string, opts?: Options | undefined): Promise<import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>;
109
+ declare function componentAnalysis(manifest: string, opts?: Options): Promise<import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport>;
110
+ /**
111
+ * @overload
112
+ * @param {string} manifest
113
+ * @param {true} html
114
+ * @param {Options} [opts={}]
115
+ * @returns {Promise<string>}
116
+ * @throws {Error}
117
+ */
64
118
  declare function stackAnalysis(manifest: string, html: true, opts?: Options | undefined): Promise<string>;
65
- declare function stackAnalysis(manifest: string, html: false, opts?: Options | undefined): Promise<import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>;
66
- declare function stackAnalysis(manifest: string, html?: boolean | undefined, opts?: Options | undefined): Promise<string | import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>;
119
+ /**
120
+ * @overload
121
+ * @param {string} manifest
122
+ * @param {false} html
123
+ * @param {Options} [opts={}]
124
+ * @returns {Promise<import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>}
125
+ * @throws {Error}
126
+ */
127
+ declare function stackAnalysis(manifest: string, html: false, opts?: Options | undefined): Promise<import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport>;
128
+ /**
129
+ * Get stack analysis report for a manifest file.
130
+ * @overload
131
+ * @param {string} manifest - path for the manifest
132
+ * @param {boolean} [html=false] - true will return a html string, false will return AnalysisReport object.
133
+ * @param {Options} [opts={}] - optional various options to pass along the application
134
+ * @returns {Promise<string|import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>}
135
+ * @throws {Error} if manifest inaccessible, no matching provider, failed to get create content,
136
+ * or backend request failed
137
+ */
138
+ declare function stackAnalysis(manifest: string, html?: boolean | undefined, opts?: Options | undefined): Promise<string | import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport>;
139
+ /**
140
+ * Get stack analysis for all workspace packages/crates (batch).
141
+ * Detects ecosystem from workspace root: Cargo (Cargo.toml + Cargo.lock) or JS/TS (package.json + lock file).
142
+ * SBOMs are generated in parallel (see `batchConcurrency`) unless `continueOnError: false` (fail-fast sequential).
143
+ * With `opts.batchMetadata` / `TRUSTIFY_DA_BATCH_METADATA`, returns `{ analysis, metadata }` including validation and SBOM errors.
144
+ *
145
+ * @param {string} workspaceRoot - Path to workspace root (containing lock file and workspace config)
146
+ * @param {boolean} [html=false] - true returns HTML, false returns JSON report
147
+ * @param {Options} [opts={}] - `batchConcurrency`, discovery ignores, `continueOnError` (default true), `batchMetadata` (default false)
148
+ * @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 }>}
149
+ * @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.
150
+ */
151
+ declare function stackAnalysisBatch(workspaceRoot: string, html?: boolean, opts?: Options): Promise<string | {
152
+ [x: string]: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport;
153
+ } | {
154
+ analysis: string | {
155
+ [x: string]: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport;
156
+ };
157
+ metadata: BatchAnalysisMetadata;
158
+ }>;
159
+ /**
160
+ * @overload
161
+ * @param {Array<string>} imageRefs
162
+ * @param {true} html
163
+ * @param {Options} [opts={}]
164
+ * @returns {Promise<string>}
165
+ * @throws {Error}
166
+ */
67
167
  declare function imageAnalysis(imageRefs: Array<string>, html: true, opts?: Options | undefined): Promise<string>;
168
+ /**
169
+ * @overload
170
+ * @param {Array<string>} imageRefs
171
+ * @param {false} html
172
+ * @param {Options} [opts={}]
173
+ * @returns {Promise<Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>>}
174
+ * @throws {Error}
175
+ */
68
176
  declare function imageAnalysis(imageRefs: Array<string>, html: false, opts?: Options | undefined): Promise<{
69
- [x: string]: import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport;
177
+ [x: string]: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport;
70
178
  }>;
179
+ /**
180
+ * Get image analysis report for a set of OCI image references.
181
+ * @overload
182
+ * @param {Array<string>} imageRefs - OCI image references
183
+ * @param {boolean} [html=false] - true will return a html string, false will return AnalysisReport
184
+ * @param {Options} [opts={}] - optional various options to pass along the application
185
+ * @returns {Promise<string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>>}
186
+ * @throws {Error} if manifest inaccessible, no matching provider, failed to get create content,
187
+ * or backend request failed
188
+ */
71
189
  declare function imageAnalysis(imageRefs: Array<string>, html?: boolean | undefined, opts?: Options | undefined): Promise<string | {
72
- [x: string]: import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport;
190
+ [x: string]: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport;
73
191
  }>;
74
192
  /**
75
193
  * Validates the Exhort token.
@@ -77,4 +195,13 @@ declare function imageAnalysis(imageRefs: Array<string>, html?: boolean | undefi
77
195
  * @returns {Promise<object>} A promise that resolves with the validation result from the backend.
78
196
  * @throws {Error} if the backend request failed.
79
197
  */
80
- declare function validateToken(opts?: Options | undefined): Promise<object>;
198
+ declare function validateToken(opts?: Options): Promise<object>;
199
+ import { discoverWorkspacePackages } from './workspace.js';
200
+ import { discoverWorkspaceCrates } from './workspace.js';
201
+ import { validatePackageJson } from './workspace.js';
202
+ import { resolveWorkspaceDiscoveryIgnore } from './workspace.js';
203
+ import { filterManifestPathsByDiscoveryIgnore } from './workspace.js';
204
+ import { resolveContinueOnError } from './batch_opts.js';
205
+ import { resolveBatchMetadata } from './batch_opts.js';
206
+ export { discoverWorkspacePackages, discoverWorkspaceCrates, validatePackageJson, resolveWorkspaceDiscoveryIgnore, filterManifestPathsByDiscoveryIgnore, resolveContinueOnError, resolveBatchMetadata };
207
+ export { getProjectLicense, findLicenseFilePath, identifyLicense, getLicenseDetails, licensesFromReport, normalizeLicensesResponse, runLicenseCheck, getCompatibility } from "./license/index.js";
package/dist/src/index.js CHANGED
@@ -1,16 +1,22 @@
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 { discoverWorkspaceCrates, discoverWorkspacePackages, filterManifestPathsByDiscoveryIgnore, resolveWorkspaceDiscoveryIgnore, validatePackageJson, } from './workspace.js';
7
10
  import.meta.dirname;
8
11
  import * as url from 'url';
9
12
  export { parseImageRef } from "./oci_image/utils.js";
10
13
  export { ImageRef } from "./oci_image/images.js";
11
- export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken };
14
+ export { getProjectLicense, findLicenseFilePath, identifyLicense, getLicenseDetails, licensesFromReport, normalizeLicensesResponse, runLicenseCheck, getCompatibility } from "./license/index.js";
15
+ export default { componentAnalysis, stackAnalysis, stackAnalysisBatch, imageAnalysis, validateToken, generateSbom };
16
+ export { discoverWorkspacePackages, discoverWorkspaceCrates, validatePackageJson, resolveWorkspaceDiscoveryIgnore, filterManifestPathsByDiscoveryIgnore, resolveContinueOnError, resolveBatchMetadata, };
12
17
  /**
13
18
  * @typedef {{
19
+ * TRUSTIFY_DA_CARGO_PATH?: string | undefined,
14
20
  * TRUSTIFY_DA_DOCKER_PATH?: string | undefined,
15
21
  * TRUSTIFY_DA_GO_MVS_LOGIC_ENABLED?: string | undefined,
16
22
  * TRUSTIFY_DA_GO_PATH?: string | undefined,
@@ -35,13 +41,36 @@ export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken
35
41
  * TRUSTIFY_DA_SYFT_CONFIG_PATH?: string | undefined,
36
42
  * TRUSTIFY_DA_SYFT_PATH?: string | undefined,
37
43
  * TRUSTIFY_DA_YARN_PATH?: string | undefined,
44
+ * TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined,
45
+ * TRUSTIFY_DA_LICENSE_CHECK?: string | undefined,
38
46
  * MATCH_MANIFEST_VERSIONS?: string | undefined,
39
- * RHDA_SOURCE?: string | undefined,
40
- * RHDA_TOKEN?: string | undefined,
41
- * RHDA_TELEMETRY_ID?: string | undefined,
42
- * [key: string]: string | undefined,
47
+ * TRUSTIFY_DA_SOURCE?: string | undefined,
48
+ * TRUSTIFY_DA_TOKEN?: string | undefined,
49
+ * TRUSTIFY_DA_TELEMETRY_ID?: string | undefined,
50
+ * TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined,
51
+ * batchConcurrency?: number | undefined,
52
+ * TRUSTIFY_DA_BATCH_CONCURRENCY?: string | undefined,
53
+ * workspaceDiscoveryIgnore?: string[] | undefined,
54
+ * TRUSTIFY_DA_WORKSPACE_DISCOVERY_IGNORE?: string | undefined,
55
+ * continueOnError?: boolean | undefined,
56
+ * TRUSTIFY_DA_CONTINUE_ON_ERROR?: string | undefined,
57
+ * batchMetadata?: boolean | undefined,
58
+ * TRUSTIFY_DA_BATCH_METADATA?: string | undefined,
59
+ * TRUSTIFY_DA_UV_PATH?: string | undefined,
60
+ * TRUSTIFY_DA_POETRY_PATH?: string | undefined,
61
+ * [key: string]: string | number | boolean | string[] | undefined,
43
62
  * }} Options
44
63
  */
64
+ /**
65
+ * @typedef {{
66
+ * workspaceRoot: string,
67
+ * ecosystem: 'javascript' | 'cargo' | 'unknown',
68
+ * total: number,
69
+ * successful: number,
70
+ * failed: number,
71
+ * errors: Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>
72
+ * }} BatchAnalysisMetadata
73
+ */
45
74
  /**
46
75
  * Logs messages to the console if the TRUSTIFY_DA_DEBUG environment variable is set to "true".
47
76
  * @param {string} alongsideText - The text to prepend to the log message.
@@ -127,7 +156,7 @@ export function selectTrustifyDABackend(opts = {}) {
127
156
  async function stackAnalysis(manifest, html = false, opts = {}) {
128
157
  const theUrl = selectTrustifyDABackend(opts);
129
158
  fs.accessSync(manifest, fs.constants.R_OK); // throws error if file unreadable
130
- let provider = match(manifest, availableProviders); // throws error if no matching provider
159
+ let provider = match(manifest, availableProviders, opts); // throws error if no matching provider
131
160
  return await analysis.requestStack(provider, manifest, theUrl, html, opts); // throws error request sending failed
132
161
  }
133
162
  /**
@@ -141,7 +170,7 @@ async function componentAnalysis(manifest, opts = {}) {
141
170
  const theUrl = selectTrustifyDABackend(opts);
142
171
  fs.accessSync(manifest, fs.constants.R_OK);
143
172
  opts["manifest-type"] = path.basename(manifest);
144
- let provider = match(manifest, availableProviders); // throws error if no matching provider
173
+ let provider = match(manifest, availableProviders, opts); // throws error if no matching provider
145
174
  return await analysis.requestComponent(provider, manifest, theUrl, opts); // throws error request sending failed
146
175
  }
147
176
  /**
@@ -174,6 +203,258 @@ async function imageAnalysis(imageRefs, html = false, opts = {}) {
174
203
  const theUrl = selectTrustifyDABackend(opts);
175
204
  return await analysis.requestImages(imageRefs, theUrl, html, opts);
176
205
  }
206
+ /**
207
+ * Max concurrent SBOM generations for batch workspace analysis. Env/opts override default 10.
208
+ * @param {Options} opts
209
+ * @returns {number}
210
+ * @private
211
+ */
212
+ function resolveBatchConcurrency(opts) {
213
+ const fromEnv = getCustom('TRUSTIFY_DA_BATCH_CONCURRENCY', null, opts);
214
+ const raw = opts.batchConcurrency ?? fromEnv ?? '10';
215
+ const n = typeof raw === 'number' ? raw : parseInt(String(raw), 10);
216
+ if (!Number.isFinite(n) || n < 1) {
217
+ return 10;
218
+ }
219
+ return Math.min(256, n);
220
+ }
221
+ /**
222
+ * @param {string} root
223
+ * @param {'javascript' | 'cargo' | 'unknown'} ecosystem
224
+ * @param {number} totalSbomAttempts
225
+ * @param {number} successfulSbomCount
226
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} errors
227
+ * @returns {BatchAnalysisMetadata}
228
+ * @private
229
+ */
230
+ function buildBatchAnalysisMetadata(root, ecosystem, totalSbomAttempts, successfulSbomCount, errors) {
231
+ return {
232
+ workspaceRoot: root,
233
+ ecosystem,
234
+ total: totalSbomAttempts,
235
+ successful: successfulSbomCount,
236
+ failed: errors.length,
237
+ errors: [...errors],
238
+ };
239
+ }
240
+ /**
241
+ * Generate a CycloneDX SBOM from a manifest file. No backend HTTP request is made.
242
+ *
243
+ * @param {string} manifestPath - path to the manifest file (e.g. pom.xml, package.json)
244
+ * @param {Options} [opts={}] - optional options (e.g. workspace dir, tool paths)
245
+ * @returns {Promise<object>} parsed CycloneDX SBOM JSON object
246
+ * @throws {Error} if the manifest is unsupported or SBOM generation fails
247
+ */
248
+ export async function generateSbom(manifestPath, opts = {}) {
249
+ fs.accessSync(manifestPath, fs.constants.R_OK);
250
+ const result = await generateOneSbom(manifestPath, opts);
251
+ if (!result.ok) {
252
+ throw new Error(`Failed to generate SBOM for ${result.manifestPath}: ${result.reason}`);
253
+ }
254
+ return result.sbom;
255
+ }
256
+ /**
257
+ * @typedef {{ ok: true, purl: string, sbom: object } | { ok: false, manifestPath: string, reason: string }} SbomResult
258
+ */
259
+ /**
260
+ * Generate an SBOM for a single manifest, returning a normalized result.
261
+ *
262
+ * @param {string} manifestPath
263
+ * @param {Options} workspaceOpts - opts with `TRUSTIFY_DA_WORKSPACE_DIR` set
264
+ * @returns {Promise<SbomResult>}
265
+ * @private
266
+ */
267
+ async function generateOneSbom(manifestPath, workspaceOpts) {
268
+ const provider = match(manifestPath, availableProviders, workspaceOpts);
269
+ const provided = await provider.provideStack(manifestPath, workspaceOpts);
270
+ const sbom = JSON.parse(provided.content);
271
+ const purl = sbom?.metadata?.component?.purl || sbom?.metadata?.component?.['bom-ref'];
272
+ if (!purl) {
273
+ return { ok: false, manifestPath, reason: 'missing purl in SBOM' };
274
+ }
275
+ return { ok: true, purl, sbom };
276
+ }
277
+ /**
278
+ * Detect the workspace ecosystem and discover manifest paths.
279
+ *
280
+ * @param {string} root - Resolved workspace root
281
+ * @param {Options} opts
282
+ * @returns {Promise<{ ecosystem: 'javascript' | 'cargo' | 'unknown', manifestPaths: string[] }>}
283
+ * @private
284
+ */
285
+ async function detectWorkspaceManifests(root, opts) {
286
+ const cargoToml = path.join(root, 'Cargo.toml');
287
+ const cargoLock = path.join(root, 'Cargo.lock');
288
+ const packageJson = path.join(root, 'package.json');
289
+ if (fs.existsSync(cargoToml) && fs.existsSync(cargoLock)) {
290
+ return { ecosystem: 'cargo', manifestPaths: await discoverWorkspaceCrates(root, opts) };
291
+ }
292
+ const hasJsLock = fs.existsSync(path.join(root, 'pnpm-lock.yaml'))
293
+ || fs.existsSync(path.join(root, 'yarn.lock'))
294
+ || fs.existsSync(path.join(root, 'package-lock.json'));
295
+ if (fs.existsSync(packageJson) && hasJsLock) {
296
+ let manifestPaths = await discoverWorkspacePackages(root, opts);
297
+ if (manifestPaths.length === 0) {
298
+ manifestPaths = [packageJson];
299
+ }
300
+ return { ecosystem: 'javascript', manifestPaths };
301
+ }
302
+ return { ecosystem: 'unknown', manifestPaths: [] };
303
+ }
304
+ /**
305
+ * Validate discovered JS package.json manifests, collecting errors.
306
+ *
307
+ * @param {string[]} manifestPaths
308
+ * @param {boolean} continueOnError
309
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} collectedErrors - mutated in place
310
+ * @returns {{ validPaths: string[] }}
311
+ * @throws {Error} on first invalid manifest when `continueOnError` is false
312
+ * @private
313
+ */
314
+ function validateJsManifests(manifestPaths, continueOnError, collectedErrors) {
315
+ const validPaths = [];
316
+ for (const p of manifestPaths) {
317
+ const v = validatePackageJson(p);
318
+ if (v.valid) {
319
+ validPaths.push(p);
320
+ }
321
+ else {
322
+ collectedErrors.push({ manifestPath: p, phase: 'validation', reason: v.error });
323
+ console.warn(`Skipping invalid package.json (${v.error}): ${p}`);
324
+ if (!continueOnError) {
325
+ throw new Error(`Invalid package.json (${v.error}): ${p}`);
326
+ }
327
+ }
328
+ }
329
+ return { validPaths };
330
+ }
331
+ /**
332
+ * Generate SBOMs for all manifests. In fail-fast mode, stops on first error.
333
+ * In continue-on-error mode, runs concurrently and collects failures.
334
+ *
335
+ * @param {string[]} manifestPaths
336
+ * @param {Options} workspaceOpts
337
+ * @param {boolean} continueOnError
338
+ * @param {number} concurrency
339
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} collectedErrors - mutated in place
340
+ * @returns {Promise<Object.<string, object>>} sbomByPurl map
341
+ * @throws {Error} on first SBOM failure when `continueOnError` is false
342
+ * @private
343
+ */
344
+ async function generateSboms(manifestPaths, workspaceOpts, continueOnError, concurrency, collectedErrors) {
345
+ /** @type {SbomResult[]} */
346
+ const results = [];
347
+ if (!continueOnError) {
348
+ for (const manifestPath of manifestPaths) {
349
+ const result = await generateOneSbom(manifestPath, workspaceOpts);
350
+ if (!result.ok) {
351
+ collectedErrors.push({ manifestPath: result.manifestPath, phase: 'sbom', reason: result.reason });
352
+ throw new Error(`${result.manifestPath}: ${result.reason}`);
353
+ }
354
+ results.push(result);
355
+ }
356
+ }
357
+ else {
358
+ const limit = pLimit(concurrency);
359
+ const settled = await Promise.all(manifestPaths.map(manifestPath => limit(async () => {
360
+ try {
361
+ return await generateOneSbom(manifestPath, workspaceOpts);
362
+ }
363
+ catch (err) {
364
+ const msg = err instanceof Error ? err.message : String(err);
365
+ if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
366
+ console.log(`Skipping ${manifestPath}: ${msg}`);
367
+ }
368
+ return { ok: false, manifestPath, reason: msg };
369
+ }
370
+ })));
371
+ for (const r of settled) {
372
+ results.push(r);
373
+ if (!r.ok) {
374
+ collectedErrors.push({ manifestPath: r.manifestPath, phase: 'sbom', reason: r.reason });
375
+ }
376
+ }
377
+ }
378
+ const sbomByPurl = {};
379
+ for (const r of results) {
380
+ if (r.ok) {
381
+ sbomByPurl[r.purl] = r.sbom;
382
+ }
383
+ }
384
+ return sbomByPurl;
385
+ }
386
+ /**
387
+ * Create an Error with optional `batchMetadata` attached.
388
+ * @param {string} message
389
+ * @param {boolean} wantMetadata
390
+ * @param {BatchAnalysisMetadata} [metadata]
391
+ * @returns {Error}
392
+ * @private
393
+ */
394
+ function batchError(message, wantMetadata, metadata) {
395
+ const err = new Error(message);
396
+ if (wantMetadata && metadata) {
397
+ err.batchMetadata = metadata;
398
+ }
399
+ return err;
400
+ }
401
+ /**
402
+ * Get stack analysis for all workspace packages/crates (batch).
403
+ * Detects ecosystem from workspace root: Cargo (Cargo.toml + Cargo.lock) or JS/TS (package.json + lock file).
404
+ * SBOMs are generated in parallel (see `batchConcurrency`) unless `continueOnError: false` (fail-fast sequential).
405
+ * With `opts.batchMetadata` / `TRUSTIFY_DA_BATCH_METADATA`, returns `{ analysis, metadata }` including validation and SBOM errors.
406
+ *
407
+ * @param {string} workspaceRoot - Path to workspace root (containing lock file and workspace config)
408
+ * @param {boolean} [html=false] - true returns HTML, false returns JSON report
409
+ * @param {Options} [opts={}] - `batchConcurrency`, discovery ignores, `continueOnError` (default true), `batchMetadata` (default false)
410
+ * @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 }>}
411
+ * @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.
412
+ */
413
+ async function stackAnalysisBatch(workspaceRoot, html = false, opts = {}) {
414
+ const theUrl = selectTrustifyDABackend(opts);
415
+ const root = path.resolve(workspaceRoot);
416
+ fs.accessSync(root, fs.constants.R_OK);
417
+ const continueOnError = resolveContinueOnError(opts);
418
+ const wantMetadata = resolveBatchMetadata(opts);
419
+ /** @type {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} */
420
+ const collectedErrors = [];
421
+ const { ecosystem, manifestPaths: discovered } = await detectWorkspaceManifests(root, opts);
422
+ let manifestPaths = discovered;
423
+ if (ecosystem === 'javascript') {
424
+ try {
425
+ const { validPaths } = validateJsManifests(manifestPaths, continueOnError, collectedErrors);
426
+ manifestPaths = validPaths;
427
+ }
428
+ catch (err) {
429
+ throw batchError(err.message, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, 0, 0, collectedErrors));
430
+ }
431
+ if (manifestPaths.length === 0 && discovered.length > 0) {
432
+ const detail = collectedErrors.map(e => `${e.manifestPath}: ${e.reason}`).join('; ');
433
+ throw batchError(`No valid packages after validation at ${root}. ${detail}`, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, 0, 0, collectedErrors));
434
+ }
435
+ }
436
+ if (manifestPaths.length === 0) {
437
+ throw new Error(`No workspace manifests found at ${root}. Ensure Cargo.toml+Cargo.lock or package.json+lock file exist.`);
438
+ }
439
+ const workspaceOpts = { ...opts, TRUSTIFY_DA_WORKSPACE_DIR: root };
440
+ const concurrency = resolveBatchConcurrency(opts);
441
+ let sbomByPurl;
442
+ try {
443
+ sbomByPurl = await generateSboms(manifestPaths, workspaceOpts, continueOnError, concurrency, collectedErrors);
444
+ }
445
+ catch (err) {
446
+ throw batchError(err.message, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, 0, collectedErrors));
447
+ }
448
+ if (Object.keys(sbomByPurl).length === 0) {
449
+ throw batchError(`No valid SBOMs produced from ${manifestPaths.length} manifest(s) at ${root}`, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, 0, collectedErrors));
450
+ }
451
+ const analysisResult = await analysis.requestStackBatch(sbomByPurl, theUrl, html, opts);
452
+ const meta = buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, Object.keys(sbomByPurl).length, collectedErrors);
453
+ if (wantMetadata) {
454
+ return { analysis: analysisResult, metadata: meta };
455
+ }
456
+ return analysisResult;
457
+ }
177
458
  /**
178
459
  * Validates the Exhort token.
179
460
  * @param {Options} [opts={}] - Optional parameters, potentially including token override.
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Run full license check: resolve project license (with backend identification and details),
3
+ * get dependency licenses from analysis report, and compute incompatibilities.
4
+ *
5
+ * @param {string} sbomContent - CycloneDX SBOM JSON string (the one sent for component analysis)
6
+ * @param {string} manifestPath - path to manifest
7
+ * @param {string} url - the backend url to send the request to
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
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
+ */
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<{
13
+ projectLicense: {
14
+ manifest: any | null;
15
+ file: any | null;
16
+ mismatch: boolean;
17
+ };
18
+ incompatibleDependencies: Array<{
19
+ purl: string;
20
+ licenses: string[];
21
+ category?: string;
22
+ reason: string;
23
+ }>;
24
+ error?: string;
25
+ }>;
26
+ export { getCompatibility } from "./license_utils.js";
27
+ export { getProjectLicense, findLicenseFilePath, identifyLicense } from "./project_license.js";
28
+ export { licensesFromReport, normalizeLicensesResponse, getLicenseDetails } from "./licenses_api.js";