@trustify-da/trustify-da-javascript-client 0.3.0-ea.63ae5c2 → 0.3.0-ea.6645ba5

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 (69) hide show
  1. package/README.md +191 -11
  2. package/dist/package.json +14 -5
  3. package/dist/src/analysis.d.ts +16 -6
  4. package/dist/src/analysis.js +72 -68
  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 +17 -2
  9. package/dist/src/cyclone_dx_sbom.js +56 -8
  10. package/dist/src/index.d.ts +135 -1
  11. package/dist/src/index.js +353 -5
  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/utils.js +11 -2
  21. package/dist/src/provider.d.ts +16 -3
  22. package/dist/src/provider.js +31 -5
  23. package/dist/src/providers/base_java.d.ts +12 -10
  24. package/dist/src/providers/base_java.js +18 -44
  25. package/dist/src/providers/base_javascript.d.ts +40 -7
  26. package/dist/src/providers/base_javascript.js +138 -24
  27. package/dist/src/providers/base_pyproject.d.ts +158 -0
  28. package/dist/src/providers/base_pyproject.js +322 -0
  29. package/dist/src/providers/golang_gomodules.d.ts +29 -12
  30. package/dist/src/providers/golang_gomodules.js +176 -121
  31. package/dist/src/providers/gomod_parser.d.ts +4 -0
  32. package/dist/src/providers/gomod_parser.js +16 -0
  33. package/dist/src/providers/java_gradle.d.ts +25 -0
  34. package/dist/src/providers/java_gradle.js +128 -4
  35. package/dist/src/providers/java_maven.d.ts +16 -1
  36. package/dist/src/providers/java_maven.js +197 -5
  37. package/dist/src/providers/javascript_bun.d.ts +10 -0
  38. package/dist/src/providers/javascript_bun.js +100 -0
  39. package/dist/src/providers/javascript_npm.d.ts +1 -0
  40. package/dist/src/providers/javascript_npm.js +21 -0
  41. package/dist/src/providers/javascript_pnpm.d.ts +1 -1
  42. package/dist/src/providers/javascript_pnpm.js +8 -4
  43. package/dist/src/providers/manifest.d.ts +2 -0
  44. package/dist/src/providers/manifest.js +22 -4
  45. package/dist/src/providers/marker_evaluator.d.ts +14 -0
  46. package/dist/src/providers/marker_evaluator.js +191 -0
  47. package/dist/src/providers/processors/yarn_berry_processor.js +88 -5
  48. package/dist/src/providers/python_controller.d.ts +5 -1
  49. package/dist/src/providers/python_controller.js +65 -7
  50. package/dist/src/providers/python_pip.d.ts +12 -0
  51. package/dist/src/providers/python_pip.js +18 -8
  52. package/dist/src/providers/python_pip_pyproject.d.ts +61 -0
  53. package/dist/src/providers/python_pip_pyproject.js +146 -0
  54. package/dist/src/providers/python_poetry.d.ts +97 -0
  55. package/dist/src/providers/python_poetry.js +271 -0
  56. package/dist/src/providers/python_uv.d.ts +46 -0
  57. package/dist/src/providers/python_uv.js +269 -0
  58. package/dist/src/providers/requirements_parser.js +5 -8
  59. package/dist/src/providers/rust_cargo.d.ts +56 -0
  60. package/dist/src/providers/rust_cargo.js +641 -0
  61. package/dist/src/providers/tree-sitter-gomod.wasm +0 -0
  62. package/dist/src/providers/tree-sitter-requirements.wasm +0 -0
  63. package/dist/src/sbom.d.ts +17 -2
  64. package/dist/src/sbom.js +16 -4
  65. package/dist/src/tools.d.ts +44 -0
  66. package/dist/src/tools.js +113 -0
  67. package/dist/src/workspace.d.ts +70 -0
  68. package/dist/src/workspace.js +256 -0
  69. package/package.json +15 -6
@@ -13,16 +13,28 @@ export function selectTrustifyDABackend(opts?: {
13
13
  TRUSTIFY_DA_DEBUG?: string | undefined;
14
14
  TRUSTIFY_DA_BACKEND_URL?: string | undefined;
15
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 = {
37
+ TRUSTIFY_DA_CARGO_PATH?: string | undefined;
26
38
  TRUSTIFY_DA_DOCKER_PATH?: string | undefined;
27
39
  TRUSTIFY_DA_GO_MVS_LOGIC_ENABLED?: string | undefined;
28
40
  TRUSTIFY_DA_GO_PATH?: string | undefined;
@@ -47,11 +59,45 @@ export type Options = {
47
59
  TRUSTIFY_DA_SYFT_CONFIG_PATH?: string | undefined;
48
60
  TRUSTIFY_DA_SYFT_PATH?: string | undefined;
49
61
  TRUSTIFY_DA_YARN_PATH?: string | undefined;
62
+ TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined;
63
+ TRUSTIFY_DA_LICENSE_CHECK?: string | undefined;
50
64
  MATCH_MANIFEST_VERSIONS?: string | undefined;
51
65
  TRUSTIFY_DA_SOURCE?: string | undefined;
52
66
  TRUSTIFY_DA_TOKEN?: string | undefined;
53
67
  TRUSTIFY_DA_TELEMETRY_ID?: string | undefined;
54
- [key: string]: 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" | "pyproject" | "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.
@@ -90,6 +136,81 @@ declare function stackAnalysis(manifest: string, html: false, opts?: Options | u
90
136
  * or backend request failed
91
137
  */
92
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
+ * @overload
141
+ * @param {string} workspaceRoot
142
+ * @param {true} html
143
+ * @param {Options & { batchMetadata: true }} opts
144
+ * @returns {Promise<{ analysis: string, metadata: BatchAnalysisMetadata }>}
145
+ * @throws {Error}
146
+ */
147
+ declare function stackAnalysisBatch(workspaceRoot: string, html: true, opts: Options & {
148
+ batchMetadata: true;
149
+ }): Promise<{
150
+ analysis: string;
151
+ metadata: BatchAnalysisMetadata;
152
+ }>;
153
+ /**
154
+ * @overload
155
+ * @param {string} workspaceRoot
156
+ * @param {true} html
157
+ * @param {Options & { batchMetadata?: false }} [opts={}]
158
+ * @returns {Promise<string>}
159
+ * @throws {Error}
160
+ */
161
+ declare function stackAnalysisBatch(workspaceRoot: string, html: true, opts?: (Options & {
162
+ batchMetadata?: false;
163
+ }) | undefined): Promise<string>;
164
+ /**
165
+ * @overload
166
+ * @param {string} workspaceRoot
167
+ * @param {false} html
168
+ * @param {Options & { batchMetadata: true }} opts
169
+ * @returns {Promise<{ analysis: Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>, metadata: BatchAnalysisMetadata }>}
170
+ * @throws {Error}
171
+ */
172
+ declare function stackAnalysisBatch(workspaceRoot: string, html: false, opts: Options & {
173
+ batchMetadata: true;
174
+ }): Promise<{
175
+ analysis: {
176
+ [x: string]: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport;
177
+ };
178
+ metadata: BatchAnalysisMetadata;
179
+ }>;
180
+ /**
181
+ * @overload
182
+ * @param {string} workspaceRoot
183
+ * @param {false} html
184
+ * @param {Options & { batchMetadata?: false }} [opts={}]
185
+ * @returns {Promise<Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>>}
186
+ * @throws {Error}
187
+ */
188
+ declare function stackAnalysisBatch(workspaceRoot: string, html: false, opts?: (Options & {
189
+ batchMetadata?: false;
190
+ }) | undefined): Promise<{
191
+ [x: string]: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport;
192
+ }>;
193
+ /**
194
+ * Get stack analysis for all workspace packages/crates (batch).
195
+ * Detects ecosystem from workspace root: Cargo (Cargo.toml + Cargo.lock) or JS/TS (package.json + lock file).
196
+ * SBOMs are generated in parallel (see `batchConcurrency`) unless `continueOnError: false` (fail-fast sequential).
197
+ * With `opts.batchMetadata` / `TRUSTIFY_DA_BATCH_METADATA`, returns `{ analysis, metadata }` including validation and SBOM errors.
198
+ *
199
+ * @overload
200
+ * @param {string} workspaceRoot - Path to workspace root (containing lock file and workspace config)
201
+ * @param {boolean} [html=false] - true returns HTML, false returns JSON report
202
+ * @param {Options} [opts={}] - `batchConcurrency`, discovery ignores, `continueOnError` (default true), `batchMetadata` (default false)
203
+ * @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 }>}
204
+ * @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.
205
+ */
206
+ declare function stackAnalysisBatch(workspaceRoot: string, html?: boolean | undefined, opts?: Options | undefined): Promise<string | {
207
+ [x: string]: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport;
208
+ } | {
209
+ analysis: string | {
210
+ [x: string]: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport;
211
+ };
212
+ metadata: BatchAnalysisMetadata;
213
+ }>;
93
214
  /**
94
215
  * @overload
95
216
  * @param {Array<string>} imageRefs
@@ -130,3 +251,16 @@ declare function imageAnalysis(imageRefs: Array<string>, html?: boolean | undefi
130
251
  * @throws {Error} if the backend request failed.
131
252
  */
132
253
  declare function validateToken(opts?: Options): Promise<object>;
254
+ import { discoverMavenModules } from './providers/java_maven.js';
255
+ import { discoverGradleSubprojects } from './providers/java_gradle.js';
256
+ import { discoverGoWorkspaceModules } from './providers/golang_gomodules.js';
257
+ import { discoverUvWorkspaceMembers } from './providers/python_uv.js';
258
+ import { discoverWorkspacePackages } from './workspace.js';
259
+ import { discoverWorkspaceCrates } from './workspace.js';
260
+ import { validatePackageJson } from './workspace.js';
261
+ import { resolveWorkspaceDiscoveryIgnore } from './workspace.js';
262
+ import { filterManifestPathsByDiscoveryIgnore } from './workspace.js';
263
+ import { resolveContinueOnError } from './batch_opts.js';
264
+ import { resolveBatchMetadata } from './batch_opts.js';
265
+ export { discoverMavenModules, discoverGradleSubprojects, discoverGoWorkspaceModules, discoverUvWorkspaceMembers, discoverWorkspacePackages, discoverWorkspaceCrates, validatePackageJson, resolveWorkspaceDiscoveryIgnore, filterManifestPathsByDiscoveryIgnore, resolveContinueOnError, resolveBatchMetadata };
266
+ export { getProjectLicense, findLicenseFilePath, identifyLicense, getLicenseDetails, licensesFromReport, normalizeLicensesResponse, runLicenseCheck, getCompatibility } from "./license/index.js";
package/dist/src/index.js CHANGED
@@ -1,16 +1,26 @@
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
- export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken };
18
+ export { getProjectLicense, findLicenseFilePath, identifyLicense, getLicenseDetails, licensesFromReport, normalizeLicensesResponse, runLicenseCheck, getCompatibility } from "./license/index.js";
19
+ export default { componentAnalysis, stackAnalysis, stackAnalysisBatch, imageAnalysis, validateToken, generateSbom };
20
+ export { discoverMavenModules, discoverGradleSubprojects, discoverGoWorkspaceModules, discoverUvWorkspaceMembers, discoverWorkspacePackages, discoverWorkspaceCrates, validatePackageJson, resolveWorkspaceDiscoveryIgnore, filterManifestPathsByDiscoveryIgnore, resolveContinueOnError, resolveBatchMetadata, };
12
21
  /**
13
22
  * @typedef {{
23
+ * TRUSTIFY_DA_CARGO_PATH?: string | undefined,
14
24
  * TRUSTIFY_DA_DOCKER_PATH?: string | undefined,
15
25
  * TRUSTIFY_DA_GO_MVS_LOGIC_ENABLED?: string | undefined,
16
26
  * TRUSTIFY_DA_GO_PATH?: string | undefined,
@@ -35,13 +45,36 @@ export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken
35
45
  * TRUSTIFY_DA_SYFT_CONFIG_PATH?: string | undefined,
36
46
  * TRUSTIFY_DA_SYFT_PATH?: string | undefined,
37
47
  * TRUSTIFY_DA_YARN_PATH?: string | undefined,
48
+ * TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined,
49
+ * TRUSTIFY_DA_LICENSE_CHECK?: string | undefined,
38
50
  * MATCH_MANIFEST_VERSIONS?: string | undefined,
39
51
  * TRUSTIFY_DA_SOURCE?: string | undefined,
40
52
  * TRUSTIFY_DA_TOKEN?: string | undefined,
41
53
  * TRUSTIFY_DA_TELEMETRY_ID?: string | undefined,
42
- * [key: string]: string | undefined,
54
+ * TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined,
55
+ * batchConcurrency?: number | undefined,
56
+ * TRUSTIFY_DA_BATCH_CONCURRENCY?: string | undefined,
57
+ * workspaceDiscoveryIgnore?: string[] | undefined,
58
+ * TRUSTIFY_DA_WORKSPACE_DISCOVERY_IGNORE?: string | undefined,
59
+ * continueOnError?: boolean | undefined,
60
+ * TRUSTIFY_DA_CONTINUE_ON_ERROR?: string | undefined,
61
+ * batchMetadata?: boolean | undefined,
62
+ * TRUSTIFY_DA_BATCH_METADATA?: string | undefined,
63
+ * TRUSTIFY_DA_UV_PATH?: string | undefined,
64
+ * TRUSTIFY_DA_POETRY_PATH?: string | undefined,
65
+ * [key: string]: string | number | boolean | string[] | undefined,
43
66
  * }} Options
44
67
  */
68
+ /**
69
+ * @typedef {{
70
+ * workspaceRoot: string,
71
+ * ecosystem: 'javascript' | 'cargo' | 'pyproject' | 'unknown',
72
+ * total: number,
73
+ * successful: number,
74
+ * failed: number,
75
+ * errors: Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>
76
+ * }} BatchAnalysisMetadata
77
+ */
45
78
  /**
46
79
  * Logs messages to the console if the TRUSTIFY_DA_DEBUG environment variable is set to "true".
47
80
  * @param {string} alongsideText - The text to prepend to the log message.
@@ -127,7 +160,7 @@ export function selectTrustifyDABackend(opts = {}) {
127
160
  async function stackAnalysis(manifest, html = false, opts = {}) {
128
161
  const theUrl = selectTrustifyDABackend(opts);
129
162
  fs.accessSync(manifest, fs.constants.R_OK); // throws error if file unreadable
130
- let provider = match(manifest, availableProviders); // throws error if no matching provider
163
+ let provider = match(manifest, availableProviders, opts); // throws error if no matching provider
131
164
  return await analysis.requestStack(provider, manifest, theUrl, html, opts); // throws error request sending failed
132
165
  }
133
166
  /**
@@ -141,8 +174,10 @@ async function componentAnalysis(manifest, opts = {}) {
141
174
  const theUrl = selectTrustifyDABackend(opts);
142
175
  fs.accessSync(manifest, fs.constants.R_OK);
143
176
  opts["manifest-type"] = path.basename(manifest);
144
- let provider = match(manifest, availableProviders); // throws error if no matching provider
145
- return await analysis.requestComponent(provider, manifest, theUrl, opts); // throws error request sending failed
177
+ let provider = match(manifest, availableProviders, opts); // throws error if no matching provider
178
+ const result = await analysis.requestComponent(provider, manifest, theUrl, opts); // throws error request sending failed
179
+ result.packageManager = provider.packageManagerName();
180
+ return result;
146
181
  }
147
182
  /**
148
183
  * @overload
@@ -174,6 +209,319 @@ async function imageAnalysis(imageRefs, html = false, opts = {}) {
174
209
  const theUrl = selectTrustifyDABackend(opts);
175
210
  return await analysis.requestImages(imageRefs, theUrl, html, opts);
176
211
  }
212
+ /**
213
+ * Max concurrent SBOM generations for batch workspace analysis. Env/opts override default 10.
214
+ * @param {Options} opts
215
+ * @returns {number}
216
+ * @private
217
+ */
218
+ function resolveBatchConcurrency(opts) {
219
+ const fromEnv = getCustom('TRUSTIFY_DA_BATCH_CONCURRENCY', null, opts);
220
+ const raw = opts.batchConcurrency ?? fromEnv ?? '10';
221
+ const n = typeof raw === 'number' ? raw : parseInt(String(raw), 10);
222
+ if (!Number.isFinite(n) || n < 1) {
223
+ return 10;
224
+ }
225
+ return Math.min(256, n);
226
+ }
227
+ /**
228
+ * @param {string} root
229
+ * @param {'javascript' | 'cargo' | 'unknown'} ecosystem
230
+ * @param {number} totalSbomAttempts
231
+ * @param {number} successfulSbomCount
232
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} errors
233
+ * @returns {BatchAnalysisMetadata}
234
+ * @private
235
+ */
236
+ function buildBatchAnalysisMetadata(root, ecosystem, totalSbomAttempts, successfulSbomCount, errors) {
237
+ return {
238
+ workspaceRoot: root,
239
+ ecosystem,
240
+ total: totalSbomAttempts,
241
+ successful: successfulSbomCount,
242
+ failed: errors.length,
243
+ errors: [...errors],
244
+ };
245
+ }
246
+ /**
247
+ * Generate a CycloneDX SBOM from a manifest file. No backend HTTP request is made.
248
+ *
249
+ * @param {string} manifestPath - path to the manifest file (e.g. pom.xml, package.json)
250
+ * @param {Options} [opts={}] - optional options (e.g. workspace dir, tool paths)
251
+ * @returns {Promise<object>} parsed CycloneDX SBOM JSON object
252
+ * @throws {Error} if the manifest is unsupported or SBOM generation fails
253
+ */
254
+ export async function generateSbom(manifestPath, opts = {}) {
255
+ fs.accessSync(manifestPath, fs.constants.R_OK);
256
+ const result = await generateOneSbom(manifestPath, opts);
257
+ if (!result.ok) {
258
+ throw new Error(`Failed to generate SBOM for ${result.manifestPath}: ${result.reason}`);
259
+ }
260
+ return result.sbom;
261
+ }
262
+ /**
263
+ * @typedef {{ ok: true, purl: string, sbom: object } | { ok: false, manifestPath: string, reason: string }} SbomResult
264
+ */
265
+ /**
266
+ * Generate an SBOM for a single manifest, returning a normalized result.
267
+ *
268
+ * @param {string} manifestPath
269
+ * @param {Options} workspaceOpts - opts with `TRUSTIFY_DA_WORKSPACE_DIR` set
270
+ * @returns {Promise<SbomResult>}
271
+ * @private
272
+ */
273
+ async function generateOneSbom(manifestPath, workspaceOpts) {
274
+ const provider = match(manifestPath, availableProviders, workspaceOpts);
275
+ const provided = await provider.provideStack(manifestPath, workspaceOpts);
276
+ const sbom = JSON.parse(provided.content);
277
+ const purl = sbom?.metadata?.component?.purl || sbom?.metadata?.component?.['bom-ref'];
278
+ if (!purl) {
279
+ return { ok: false, manifestPath, reason: 'missing purl in SBOM' };
280
+ }
281
+ return { ok: true, purl, sbom };
282
+ }
283
+ /**
284
+ * Detect the workspace ecosystem and discover manifest paths.
285
+ *
286
+ * @param {string} root - Resolved workspace root
287
+ * @param {Options} opts
288
+ * @returns {Promise<{ ecosystem: 'javascript' | 'cargo' | 'maven' | 'gradle' | 'gomodules' | 'pyproject' | 'unknown', manifestPaths: string[] }>}
289
+ * @private
290
+ */
291
+ async function detectWorkspaceManifests(root, opts) {
292
+ const cargoToml = path.join(root, 'Cargo.toml');
293
+ const cargoLock = path.join(root, 'Cargo.lock');
294
+ const packageJson = path.join(root, 'package.json');
295
+ const pomXml = path.join(root, 'pom.xml');
296
+ if (fs.existsSync(cargoToml) && fs.existsSync(cargoLock)) {
297
+ return { ecosystem: 'cargo', manifestPaths: await discoverWorkspaceCrates(root, opts) };
298
+ }
299
+ if (fs.existsSync(pomXml)) {
300
+ const manifestPaths = await discoverMavenModules(root, opts);
301
+ if (manifestPaths.length > 0) {
302
+ return { ecosystem: 'maven', manifestPaths };
303
+ }
304
+ }
305
+ const hasGradleSettings = fs.existsSync(path.join(root, 'settings.gradle'))
306
+ || fs.existsSync(path.join(root, 'settings.gradle.kts'));
307
+ if (hasGradleSettings) {
308
+ const manifestPaths = await discoverGradleSubprojects(root, opts);
309
+ if (manifestPaths.length > 0) {
310
+ return { ecosystem: 'gradle', manifestPaths };
311
+ }
312
+ }
313
+ if (fs.existsSync(path.join(root, 'go.work'))) {
314
+ const manifestPaths = await discoverGoWorkspaceModules(root, opts);
315
+ if (manifestPaths.length > 0) {
316
+ return { ecosystem: 'gomodules', manifestPaths };
317
+ }
318
+ }
319
+ if (fs.existsSync(path.join(root, 'pyproject.toml')) && fs.existsSync(path.join(root, 'uv.lock'))) {
320
+ const manifestPaths = await discoverUvWorkspaceMembers(root, opts);
321
+ if (manifestPaths.length > 0) {
322
+ return { ecosystem: 'pyproject', manifestPaths };
323
+ }
324
+ }
325
+ const hasJsLock = fs.existsSync(path.join(root, 'bun.lock'))
326
+ || fs.existsSync(path.join(root, 'pnpm-lock.yaml'))
327
+ || fs.existsSync(path.join(root, 'yarn.lock'))
328
+ || fs.existsSync(path.join(root, 'package-lock.json'));
329
+ if (fs.existsSync(packageJson) && hasJsLock) {
330
+ let manifestPaths = await discoverWorkspacePackages(root, opts);
331
+ if (manifestPaths.length === 0) {
332
+ manifestPaths = [packageJson];
333
+ }
334
+ return { ecosystem: 'javascript', manifestPaths };
335
+ }
336
+ return { ecosystem: 'unknown', manifestPaths: [] };
337
+ }
338
+ /**
339
+ * Validate discovered JS package.json manifests, collecting errors.
340
+ *
341
+ * @param {string[]} manifestPaths
342
+ * @param {boolean} continueOnError
343
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} collectedErrors - mutated in place
344
+ * @returns {{ validPaths: string[] }}
345
+ * @throws {Error} on first invalid manifest when `continueOnError` is false
346
+ * @private
347
+ */
348
+ function validateJsManifests(manifestPaths, continueOnError, collectedErrors) {
349
+ const validPaths = [];
350
+ for (const p of manifestPaths) {
351
+ const v = validatePackageJson(p);
352
+ if (v.valid) {
353
+ validPaths.push(p);
354
+ }
355
+ else {
356
+ collectedErrors.push({ manifestPath: p, phase: 'validation', reason: v.error });
357
+ console.warn(`Skipping invalid package.json (${v.error}): ${p}`);
358
+ if (!continueOnError) {
359
+ throw new Error(`Invalid package.json (${v.error}): ${p}`);
360
+ }
361
+ }
362
+ }
363
+ return { validPaths };
364
+ }
365
+ /**
366
+ * Generate SBOMs for all manifests. In fail-fast mode, stops on first error.
367
+ * In continue-on-error mode, runs concurrently and collects failures.
368
+ *
369
+ * @param {string[]} manifestPaths
370
+ * @param {Options} workspaceOpts
371
+ * @param {boolean} continueOnError
372
+ * @param {number} concurrency
373
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} collectedErrors - mutated in place
374
+ * @returns {Promise<Object.<string, object>>} sbomByPurl map
375
+ * @throws {Error} on first SBOM failure when `continueOnError` is false
376
+ * @private
377
+ */
378
+ async function generateSboms(manifestPaths, workspaceOpts, continueOnError, concurrency, collectedErrors) {
379
+ /** @type {SbomResult[]} */
380
+ const results = [];
381
+ if (!continueOnError) {
382
+ for (const manifestPath of manifestPaths) {
383
+ const result = await generateOneSbom(manifestPath, workspaceOpts);
384
+ if (!result.ok) {
385
+ collectedErrors.push({ manifestPath: result.manifestPath, phase: 'sbom', reason: result.reason });
386
+ throw new Error(`${result.manifestPath}: ${result.reason}`);
387
+ }
388
+ results.push(result);
389
+ }
390
+ }
391
+ else {
392
+ const limit = pLimit(concurrency);
393
+ const settled = await Promise.all(manifestPaths.map(manifestPath => limit(async () => {
394
+ try {
395
+ return await generateOneSbom(manifestPath, workspaceOpts);
396
+ }
397
+ catch (err) {
398
+ const msg = err instanceof Error ? err.message : String(err);
399
+ if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
400
+ console.log(`Skipping ${manifestPath}: ${msg}`);
401
+ }
402
+ return { ok: false, manifestPath, reason: msg };
403
+ }
404
+ })));
405
+ for (const r of settled) {
406
+ results.push(r);
407
+ if (!r.ok) {
408
+ collectedErrors.push({ manifestPath: r.manifestPath, phase: 'sbom', reason: r.reason });
409
+ }
410
+ }
411
+ }
412
+ const sbomByPurl = {};
413
+ for (const r of results) {
414
+ if (r.ok) {
415
+ sbomByPurl[r.purl] = r.sbom;
416
+ }
417
+ }
418
+ return sbomByPurl;
419
+ }
420
+ /**
421
+ * Create an Error with optional `batchMetadata` attached.
422
+ * @param {string} message
423
+ * @param {boolean} wantMetadata
424
+ * @param {BatchAnalysisMetadata} [metadata]
425
+ * @returns {Error}
426
+ * @private
427
+ */
428
+ function batchError(message, wantMetadata, metadata) {
429
+ const err = new Error(message);
430
+ if (wantMetadata && metadata) {
431
+ err.batchMetadata = metadata;
432
+ }
433
+ return err;
434
+ }
435
+ /**
436
+ * @overload
437
+ * @param {string} workspaceRoot
438
+ * @param {true} html
439
+ * @param {Options & { batchMetadata: true }} opts
440
+ * @returns {Promise<{ analysis: string, metadata: BatchAnalysisMetadata }>}
441
+ * @throws {Error}
442
+ */
443
+ /**
444
+ * @overload
445
+ * @param {string} workspaceRoot
446
+ * @param {true} html
447
+ * @param {Options & { batchMetadata?: false }} [opts={}]
448
+ * @returns {Promise<string>}
449
+ * @throws {Error}
450
+ */
451
+ /**
452
+ * @overload
453
+ * @param {string} workspaceRoot
454
+ * @param {false} html
455
+ * @param {Options & { batchMetadata: true }} opts
456
+ * @returns {Promise<{ analysis: Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>, metadata: BatchAnalysisMetadata }>}
457
+ * @throws {Error}
458
+ */
459
+ /**
460
+ * @overload
461
+ * @param {string} workspaceRoot
462
+ * @param {false} html
463
+ * @param {Options & { batchMetadata?: false }} [opts={}]
464
+ * @returns {Promise<Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>>}
465
+ * @throws {Error}
466
+ */
467
+ /**
468
+ * Get stack analysis for all workspace packages/crates (batch).
469
+ * Detects ecosystem from workspace root: Cargo (Cargo.toml + Cargo.lock) or JS/TS (package.json + lock file).
470
+ * SBOMs are generated in parallel (see `batchConcurrency`) unless `continueOnError: false` (fail-fast sequential).
471
+ * With `opts.batchMetadata` / `TRUSTIFY_DA_BATCH_METADATA`, returns `{ analysis, metadata }` including validation and SBOM errors.
472
+ *
473
+ * @overload
474
+ * @param {string} workspaceRoot - Path to workspace root (containing lock file and workspace config)
475
+ * @param {boolean} [html=false] - true returns HTML, false returns JSON report
476
+ * @param {Options} [opts={}] - `batchConcurrency`, discovery ignores, `continueOnError` (default true), `batchMetadata` (default false)
477
+ * @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 }>}
478
+ * @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.
479
+ */
480
+ async function stackAnalysisBatch(workspaceRoot, html = false, opts = {}) {
481
+ const theUrl = selectTrustifyDABackend(opts);
482
+ const root = path.resolve(workspaceRoot);
483
+ fs.accessSync(root, fs.constants.R_OK);
484
+ const continueOnError = resolveContinueOnError(opts);
485
+ const wantMetadata = resolveBatchMetadata(opts);
486
+ /** @type {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} */
487
+ const collectedErrors = [];
488
+ const { ecosystem, manifestPaths: discovered } = await detectWorkspaceManifests(root, opts);
489
+ let manifestPaths = discovered;
490
+ if (ecosystem === 'javascript') {
491
+ try {
492
+ const { validPaths } = validateJsManifests(manifestPaths, continueOnError, collectedErrors);
493
+ manifestPaths = validPaths;
494
+ }
495
+ catch (err) {
496
+ throw batchError(err.message, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, 0, 0, collectedErrors));
497
+ }
498
+ if (manifestPaths.length === 0 && discovered.length > 0) {
499
+ const detail = collectedErrors.map(e => `${e.manifestPath}: ${e.reason}`).join('; ');
500
+ throw batchError(`No valid packages after validation at ${root}. ${detail}`, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, 0, 0, collectedErrors));
501
+ }
502
+ }
503
+ if (manifestPaths.length === 0) {
504
+ 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).`);
505
+ }
506
+ const workspaceOpts = { ...opts, TRUSTIFY_DA_WORKSPACE_DIR: root };
507
+ const concurrency = resolveBatchConcurrency(opts);
508
+ let sbomByPurl;
509
+ try {
510
+ sbomByPurl = await generateSboms(manifestPaths, workspaceOpts, continueOnError, concurrency, collectedErrors);
511
+ }
512
+ catch (err) {
513
+ throw batchError(err.message, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, 0, collectedErrors));
514
+ }
515
+ if (Object.keys(sbomByPurl).length === 0) {
516
+ throw batchError(`No valid SBOMs produced from ${manifestPaths.length} manifest(s) at ${root}`, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, 0, collectedErrors));
517
+ }
518
+ const analysisResult = await analysis.requestStackBatch(sbomByPurl, theUrl, html, opts);
519
+ const meta = buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, Object.keys(sbomByPurl).length, collectedErrors);
520
+ if (wantMetadata) {
521
+ return { analysis: analysisResult, metadata: meta };
522
+ }
523
+ return analysisResult;
524
+ }
177
525
  /**
178
526
  * Validates the Exhort token.
179
527
  * @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";