@trustify-da/trustify-da-javascript-client 0.3.0-ea.3aa725a → 0.3.0-ea.41ca049

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