@trustify-da/trustify-da-javascript-client 0.3.0-ea.0e9ba23 → 0.3.0-ea.1d590b2

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 (66) hide show
  1. package/README.md +179 -11
  2. package/dist/package.json +12 -3
  3. package/dist/src/analysis.d.ts +16 -0
  4. package/dist/src/analysis.js +53 -4
  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 +171 -4
  8. package/dist/src/cyclone_dx_sbom.d.ts +14 -1
  9. package/dist/src/cyclone_dx_sbom.js +34 -6
  10. package/dist/src/index.d.ts +132 -2
  11. package/dist/src/index.js +334 -5
  12. package/dist/src/license/index.d.ts +2 -2
  13. package/dist/src/license/index.js +4 -4
  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.js +9 -2
  17. package/dist/src/license/project_license.d.ts +1 -6
  18. package/dist/src/license/project_license.js +4 -81
  19. package/dist/src/oci_image/utils.js +11 -2
  20. package/dist/src/provider.d.ts +6 -3
  21. package/dist/src/provider.js +14 -5
  22. package/dist/src/providers/base_java.d.ts +0 -9
  23. package/dist/src/providers/base_java.js +2 -38
  24. package/dist/src/providers/base_javascript.d.ts +19 -3
  25. package/dist/src/providers/base_javascript.js +106 -23
  26. package/dist/src/providers/base_pyproject.d.ts +153 -0
  27. package/dist/src/providers/base_pyproject.js +315 -0
  28. package/dist/src/providers/golang_gomodules.d.ts +12 -12
  29. package/dist/src/providers/golang_gomodules.js +102 -112
  30. package/dist/src/providers/gomod_parser.d.ts +4 -0
  31. package/dist/src/providers/gomod_parser.js +16 -0
  32. package/dist/src/providers/java_gradle.d.ts +19 -0
  33. package/dist/src/providers/java_gradle.js +116 -1
  34. package/dist/src/providers/java_maven.d.ts +9 -1
  35. package/dist/src/providers/java_maven.js +103 -10
  36. package/dist/src/providers/javascript_npm.d.ts +1 -0
  37. package/dist/src/providers/javascript_npm.js +21 -0
  38. package/dist/src/providers/javascript_pnpm.d.ts +1 -1
  39. package/dist/src/providers/javascript_pnpm.js +8 -4
  40. package/dist/src/providers/manifest.d.ts +2 -0
  41. package/dist/src/providers/manifest.js +22 -4
  42. package/dist/src/providers/processors/yarn_berry_processor.js +88 -5
  43. package/dist/src/providers/python_controller.d.ts +5 -1
  44. package/dist/src/providers/python_controller.js +8 -4
  45. package/dist/src/providers/python_pip.d.ts +4 -0
  46. package/dist/src/providers/python_pip.js +7 -6
  47. package/dist/src/providers/python_pip_pyproject.d.ts +61 -0
  48. package/dist/src/providers/python_pip_pyproject.js +144 -0
  49. package/dist/src/providers/python_poetry.d.ts +58 -0
  50. package/dist/src/providers/python_poetry.js +175 -0
  51. package/dist/src/providers/python_uv.d.ts +42 -0
  52. package/dist/src/providers/python_uv.js +149 -0
  53. package/dist/src/providers/requirements_parser.js +5 -8
  54. package/dist/src/providers/rust_cargo.d.ts +52 -0
  55. package/dist/src/providers/rust_cargo.js +614 -0
  56. package/dist/src/providers/tree-sitter-gomod.wasm +0 -0
  57. package/dist/src/providers/tree-sitter-requirements.wasm +0 -0
  58. package/dist/src/sbom.d.ts +14 -1
  59. package/dist/src/sbom.js +13 -2
  60. package/dist/src/tools.d.ts +26 -0
  61. package/dist/src/tools.js +58 -0
  62. package/dist/src/workspace.d.ts +61 -0
  63. package/dist/src/workspace.js +256 -0
  64. package/package.json +13 -4
  65. package/dist/src/license/compatibility.d.ts +0 -18
  66. package/dist/src/license/compatibility.js +0 -45
package/dist/src/index.js CHANGED
@@ -1,17 +1,24 @@
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 { discoverWorkspaceCrates, discoverWorkspacePackages, filterManifestPathsByDiscoveryIgnore, resolveWorkspaceDiscoveryIgnore, validatePackageJson, } from './workspace.js';
7
12
  import.meta.dirname;
8
13
  import * as url from 'url';
9
14
  export { parseImageRef } from "./oci_image/utils.js";
10
15
  export { ImageRef } from "./oci_image/images.js";
11
- export { getProjectLicense, findLicenseFilePath, identifyLicenseViaBackend, getLicenseDetails, licensesFromReport, normalizeLicensesResponse, runLicenseCheck, getCompatibility } from "./license/index.js";
12
- export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken };
16
+ export { getProjectLicense, findLicenseFilePath, identifyLicense, getLicenseDetails, licensesFromReport, normalizeLicensesResponse, runLicenseCheck, getCompatibility } from "./license/index.js";
17
+ export default { componentAnalysis, stackAnalysis, stackAnalysisBatch, imageAnalysis, validateToken, generateSbom };
18
+ export { discoverMavenModules, discoverGradleSubprojects, discoverWorkspacePackages, discoverWorkspaceCrates, validatePackageJson, resolveWorkspaceDiscoveryIgnore, filterManifestPathsByDiscoveryIgnore, resolveContinueOnError, resolveBatchMetadata, };
13
19
  /**
14
20
  * @typedef {{
21
+ * TRUSTIFY_DA_CARGO_PATH?: string | undefined,
15
22
  * TRUSTIFY_DA_DOCKER_PATH?: string | undefined,
16
23
  * TRUSTIFY_DA_GO_MVS_LOGIC_ENABLED?: string | undefined,
17
24
  * TRUSTIFY_DA_GO_PATH?: string | undefined,
@@ -36,14 +43,36 @@ export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken
36
43
  * TRUSTIFY_DA_SYFT_CONFIG_PATH?: string | undefined,
37
44
  * TRUSTIFY_DA_SYFT_PATH?: string | undefined,
38
45
  * TRUSTIFY_DA_YARN_PATH?: string | undefined,
46
+ * TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined,
39
47
  * TRUSTIFY_DA_LICENSE_CHECK?: string | undefined,
40
48
  * MATCH_MANIFEST_VERSIONS?: string | undefined,
41
49
  * TRUSTIFY_DA_SOURCE?: string | undefined,
42
50
  * TRUSTIFY_DA_TOKEN?: string | undefined,
43
51
  * TRUSTIFY_DA_TELEMETRY_ID?: string | undefined,
44
- * [key: string]: string | undefined,
52
+ * TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined,
53
+ * batchConcurrency?: number | undefined,
54
+ * TRUSTIFY_DA_BATCH_CONCURRENCY?: string | undefined,
55
+ * workspaceDiscoveryIgnore?: string[] | undefined,
56
+ * TRUSTIFY_DA_WORKSPACE_DISCOVERY_IGNORE?: string | undefined,
57
+ * continueOnError?: boolean | undefined,
58
+ * TRUSTIFY_DA_CONTINUE_ON_ERROR?: string | undefined,
59
+ * batchMetadata?: boolean | undefined,
60
+ * TRUSTIFY_DA_BATCH_METADATA?: string | undefined,
61
+ * TRUSTIFY_DA_UV_PATH?: string | undefined,
62
+ * TRUSTIFY_DA_POETRY_PATH?: string | undefined,
63
+ * [key: string]: string | number | boolean | string[] | undefined,
45
64
  * }} Options
46
65
  */
66
+ /**
67
+ * @typedef {{
68
+ * workspaceRoot: string,
69
+ * ecosystem: 'javascript' | 'cargo' | 'unknown',
70
+ * total: number,
71
+ * successful: number,
72
+ * failed: number,
73
+ * errors: Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>
74
+ * }} BatchAnalysisMetadata
75
+ */
47
76
  /**
48
77
  * Logs messages to the console if the TRUSTIFY_DA_DEBUG environment variable is set to "true".
49
78
  * @param {string} alongsideText - The text to prepend to the log message.
@@ -129,7 +158,7 @@ export function selectTrustifyDABackend(opts = {}) {
129
158
  async function stackAnalysis(manifest, html = false, opts = {}) {
130
159
  const theUrl = selectTrustifyDABackend(opts);
131
160
  fs.accessSync(manifest, fs.constants.R_OK); // throws error if file unreadable
132
- let provider = match(manifest, availableProviders); // throws error if no matching provider
161
+ let provider = match(manifest, availableProviders, opts); // throws error if no matching provider
133
162
  return await analysis.requestStack(provider, manifest, theUrl, html, opts); // throws error request sending failed
134
163
  }
135
164
  /**
@@ -143,7 +172,7 @@ async function componentAnalysis(manifest, opts = {}) {
143
172
  const theUrl = selectTrustifyDABackend(opts);
144
173
  fs.accessSync(manifest, fs.constants.R_OK);
145
174
  opts["manifest-type"] = path.basename(manifest);
146
- let provider = match(manifest, availableProviders); // throws error if no matching provider
175
+ let provider = match(manifest, availableProviders, opts); // throws error if no matching provider
147
176
  return await analysis.requestComponent(provider, manifest, theUrl, opts); // throws error request sending failed
148
177
  }
149
178
  /**
@@ -176,6 +205,306 @@ async function imageAnalysis(imageRefs, html = false, opts = {}) {
176
205
  const theUrl = selectTrustifyDABackend(opts);
177
206
  return await analysis.requestImages(imageRefs, theUrl, html, opts);
178
207
  }
208
+ /**
209
+ * Max concurrent SBOM generations for batch workspace analysis. Env/opts override default 10.
210
+ * @param {Options} opts
211
+ * @returns {number}
212
+ * @private
213
+ */
214
+ function resolveBatchConcurrency(opts) {
215
+ const fromEnv = getCustom('TRUSTIFY_DA_BATCH_CONCURRENCY', null, opts);
216
+ const raw = opts.batchConcurrency ?? fromEnv ?? '10';
217
+ const n = typeof raw === 'number' ? raw : parseInt(String(raw), 10);
218
+ if (!Number.isFinite(n) || n < 1) {
219
+ return 10;
220
+ }
221
+ return Math.min(256, n);
222
+ }
223
+ /**
224
+ * @param {string} root
225
+ * @param {'javascript' | 'cargo' | 'unknown'} ecosystem
226
+ * @param {number} totalSbomAttempts
227
+ * @param {number} successfulSbomCount
228
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} errors
229
+ * @returns {BatchAnalysisMetadata}
230
+ * @private
231
+ */
232
+ function buildBatchAnalysisMetadata(root, ecosystem, totalSbomAttempts, successfulSbomCount, errors) {
233
+ return {
234
+ workspaceRoot: root,
235
+ ecosystem,
236
+ total: totalSbomAttempts,
237
+ successful: successfulSbomCount,
238
+ failed: errors.length,
239
+ errors: [...errors],
240
+ };
241
+ }
242
+ /**
243
+ * Generate a CycloneDX SBOM from a manifest file. No backend HTTP request is made.
244
+ *
245
+ * @param {string} manifestPath - path to the manifest file (e.g. pom.xml, package.json)
246
+ * @param {Options} [opts={}] - optional options (e.g. workspace dir, tool paths)
247
+ * @returns {Promise<object>} parsed CycloneDX SBOM JSON object
248
+ * @throws {Error} if the manifest is unsupported or SBOM generation fails
249
+ */
250
+ export async function generateSbom(manifestPath, opts = {}) {
251
+ fs.accessSync(manifestPath, fs.constants.R_OK);
252
+ const result = await generateOneSbom(manifestPath, opts);
253
+ if (!result.ok) {
254
+ throw new Error(`Failed to generate SBOM for ${result.manifestPath}: ${result.reason}`);
255
+ }
256
+ return result.sbom;
257
+ }
258
+ /**
259
+ * @typedef {{ ok: true, purl: string, sbom: object } | { ok: false, manifestPath: string, reason: string }} SbomResult
260
+ */
261
+ /**
262
+ * Generate an SBOM for a single manifest, returning a normalized result.
263
+ *
264
+ * @param {string} manifestPath
265
+ * @param {Options} workspaceOpts - opts with `TRUSTIFY_DA_WORKSPACE_DIR` set
266
+ * @returns {Promise<SbomResult>}
267
+ * @private
268
+ */
269
+ async function generateOneSbom(manifestPath, workspaceOpts) {
270
+ const provider = match(manifestPath, availableProviders, workspaceOpts);
271
+ const provided = await provider.provideStack(manifestPath, workspaceOpts);
272
+ const sbom = JSON.parse(provided.content);
273
+ const purl = sbom?.metadata?.component?.purl || sbom?.metadata?.component?.['bom-ref'];
274
+ if (!purl) {
275
+ return { ok: false, manifestPath, reason: 'missing purl in SBOM' };
276
+ }
277
+ return { ok: true, purl, sbom };
278
+ }
279
+ /**
280
+ * Detect the workspace ecosystem and discover manifest paths.
281
+ *
282
+ * @param {string} root - Resolved workspace root
283
+ * @param {Options} opts
284
+ * @returns {Promise<{ ecosystem: 'javascript' | 'cargo' | 'maven' | 'gradle' | 'unknown', manifestPaths: string[] }>}
285
+ * @private
286
+ */
287
+ async function detectWorkspaceManifests(root, opts) {
288
+ const cargoToml = path.join(root, 'Cargo.toml');
289
+ const cargoLock = path.join(root, 'Cargo.lock');
290
+ const packageJson = path.join(root, 'package.json');
291
+ const pomXml = path.join(root, 'pom.xml');
292
+ if (fs.existsSync(cargoToml) && fs.existsSync(cargoLock)) {
293
+ return { ecosystem: 'cargo', manifestPaths: await discoverWorkspaceCrates(root, opts) };
294
+ }
295
+ if (fs.existsSync(pomXml)) {
296
+ const manifestPaths = await discoverMavenModules(root, opts);
297
+ if (manifestPaths.length > 0) {
298
+ return { ecosystem: 'maven', manifestPaths };
299
+ }
300
+ }
301
+ const hasGradleSettings = fs.existsSync(path.join(root, 'settings.gradle'))
302
+ || fs.existsSync(path.join(root, 'settings.gradle.kts'));
303
+ if (hasGradleSettings) {
304
+ const manifestPaths = await discoverGradleSubprojects(root, opts);
305
+ if (manifestPaths.length > 0) {
306
+ return { ecosystem: 'gradle', manifestPaths };
307
+ }
308
+ }
309
+ const hasJsLock = fs.existsSync(path.join(root, 'pnpm-lock.yaml'))
310
+ || fs.existsSync(path.join(root, 'yarn.lock'))
311
+ || fs.existsSync(path.join(root, 'package-lock.json'));
312
+ if (fs.existsSync(packageJson) && hasJsLock) {
313
+ let manifestPaths = await discoverWorkspacePackages(root, opts);
314
+ if (manifestPaths.length === 0) {
315
+ manifestPaths = [packageJson];
316
+ }
317
+ return { ecosystem: 'javascript', manifestPaths };
318
+ }
319
+ return { ecosystem: 'unknown', manifestPaths: [] };
320
+ }
321
+ /**
322
+ * Validate discovered JS package.json manifests, collecting errors.
323
+ *
324
+ * @param {string[]} manifestPaths
325
+ * @param {boolean} continueOnError
326
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} collectedErrors - mutated in place
327
+ * @returns {{ validPaths: string[] }}
328
+ * @throws {Error} on first invalid manifest when `continueOnError` is false
329
+ * @private
330
+ */
331
+ function validateJsManifests(manifestPaths, continueOnError, collectedErrors) {
332
+ const validPaths = [];
333
+ for (const p of manifestPaths) {
334
+ const v = validatePackageJson(p);
335
+ if (v.valid) {
336
+ validPaths.push(p);
337
+ }
338
+ else {
339
+ collectedErrors.push({ manifestPath: p, phase: 'validation', reason: v.error });
340
+ console.warn(`Skipping invalid package.json (${v.error}): ${p}`);
341
+ if (!continueOnError) {
342
+ throw new Error(`Invalid package.json (${v.error}): ${p}`);
343
+ }
344
+ }
345
+ }
346
+ return { validPaths };
347
+ }
348
+ /**
349
+ * Generate SBOMs for all manifests. In fail-fast mode, stops on first error.
350
+ * In continue-on-error mode, runs concurrently and collects failures.
351
+ *
352
+ * @param {string[]} manifestPaths
353
+ * @param {Options} workspaceOpts
354
+ * @param {boolean} continueOnError
355
+ * @param {number} concurrency
356
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} collectedErrors - mutated in place
357
+ * @returns {Promise<Object.<string, object>>} sbomByPurl map
358
+ * @throws {Error} on first SBOM failure when `continueOnError` is false
359
+ * @private
360
+ */
361
+ async function generateSboms(manifestPaths, workspaceOpts, continueOnError, concurrency, collectedErrors) {
362
+ /** @type {SbomResult[]} */
363
+ const results = [];
364
+ if (!continueOnError) {
365
+ for (const manifestPath of manifestPaths) {
366
+ const result = await generateOneSbom(manifestPath, workspaceOpts);
367
+ if (!result.ok) {
368
+ collectedErrors.push({ manifestPath: result.manifestPath, phase: 'sbom', reason: result.reason });
369
+ throw new Error(`${result.manifestPath}: ${result.reason}`);
370
+ }
371
+ results.push(result);
372
+ }
373
+ }
374
+ else {
375
+ const limit = pLimit(concurrency);
376
+ const settled = await Promise.all(manifestPaths.map(manifestPath => limit(async () => {
377
+ try {
378
+ return await generateOneSbom(manifestPath, workspaceOpts);
379
+ }
380
+ catch (err) {
381
+ const msg = err instanceof Error ? err.message : String(err);
382
+ if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
383
+ console.log(`Skipping ${manifestPath}: ${msg}`);
384
+ }
385
+ return { ok: false, manifestPath, reason: msg };
386
+ }
387
+ })));
388
+ for (const r of settled) {
389
+ results.push(r);
390
+ if (!r.ok) {
391
+ collectedErrors.push({ manifestPath: r.manifestPath, phase: 'sbom', reason: r.reason });
392
+ }
393
+ }
394
+ }
395
+ const sbomByPurl = {};
396
+ for (const r of results) {
397
+ if (r.ok) {
398
+ sbomByPurl[r.purl] = r.sbom;
399
+ }
400
+ }
401
+ return sbomByPurl;
402
+ }
403
+ /**
404
+ * Create an Error with optional `batchMetadata` attached.
405
+ * @param {string} message
406
+ * @param {boolean} wantMetadata
407
+ * @param {BatchAnalysisMetadata} [metadata]
408
+ * @returns {Error}
409
+ * @private
410
+ */
411
+ function batchError(message, wantMetadata, metadata) {
412
+ const err = new Error(message);
413
+ if (wantMetadata && metadata) {
414
+ err.batchMetadata = metadata;
415
+ }
416
+ return err;
417
+ }
418
+ /**
419
+ * @overload
420
+ * @param {string} workspaceRoot
421
+ * @param {true} html
422
+ * @param {Options & { batchMetadata: true }} opts
423
+ * @returns {Promise<{ analysis: string, metadata: BatchAnalysisMetadata }>}
424
+ * @throws {Error}
425
+ */
426
+ /**
427
+ * @overload
428
+ * @param {string} workspaceRoot
429
+ * @param {true} html
430
+ * @param {Options & { batchMetadata?: false }} [opts={}]
431
+ * @returns {Promise<string>}
432
+ * @throws {Error}
433
+ */
434
+ /**
435
+ * @overload
436
+ * @param {string} workspaceRoot
437
+ * @param {false} html
438
+ * @param {Options & { batchMetadata: true }} opts
439
+ * @returns {Promise<{ analysis: Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>, metadata: BatchAnalysisMetadata }>}
440
+ * @throws {Error}
441
+ */
442
+ /**
443
+ * @overload
444
+ * @param {string} workspaceRoot
445
+ * @param {false} html
446
+ * @param {Options & { batchMetadata?: false }} [opts={}]
447
+ * @returns {Promise<Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>>}
448
+ * @throws {Error}
449
+ */
450
+ /**
451
+ * Get stack analysis for all workspace packages/crates (batch).
452
+ * Detects ecosystem from workspace root: Cargo (Cargo.toml + Cargo.lock) or JS/TS (package.json + lock file).
453
+ * SBOMs are generated in parallel (see `batchConcurrency`) unless `continueOnError: false` (fail-fast sequential).
454
+ * With `opts.batchMetadata` / `TRUSTIFY_DA_BATCH_METADATA`, returns `{ analysis, metadata }` including validation and SBOM errors.
455
+ *
456
+ * @overload
457
+ * @param {string} workspaceRoot - Path to workspace root (containing lock file and workspace config)
458
+ * @param {boolean} [html=false] - true returns HTML, false returns JSON report
459
+ * @param {Options} [opts={}] - `batchConcurrency`, discovery ignores, `continueOnError` (default true), `batchMetadata` (default false)
460
+ * @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 }>}
461
+ * @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.
462
+ */
463
+ async function stackAnalysisBatch(workspaceRoot, html = false, opts = {}) {
464
+ const theUrl = selectTrustifyDABackend(opts);
465
+ const root = path.resolve(workspaceRoot);
466
+ fs.accessSync(root, fs.constants.R_OK);
467
+ const continueOnError = resolveContinueOnError(opts);
468
+ const wantMetadata = resolveBatchMetadata(opts);
469
+ /** @type {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} */
470
+ const collectedErrors = [];
471
+ const { ecosystem, manifestPaths: discovered } = await detectWorkspaceManifests(root, opts);
472
+ let manifestPaths = discovered;
473
+ if (ecosystem === 'javascript') {
474
+ try {
475
+ const { validPaths } = validateJsManifests(manifestPaths, continueOnError, collectedErrors);
476
+ manifestPaths = validPaths;
477
+ }
478
+ catch (err) {
479
+ throw batchError(err.message, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, 0, 0, collectedErrors));
480
+ }
481
+ if (manifestPaths.length === 0 && discovered.length > 0) {
482
+ const detail = collectedErrors.map(e => `${e.manifestPath}: ${e.reason}`).join('; ');
483
+ throw batchError(`No valid packages after validation at ${root}. ${detail}`, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, 0, 0, collectedErrors));
484
+ }
485
+ }
486
+ if (manifestPaths.length === 0) {
487
+ throw new Error(`No workspace manifests found at ${root}. Ensure Cargo.toml+Cargo.lock or package.json+lock file exist.`);
488
+ }
489
+ const workspaceOpts = { ...opts, TRUSTIFY_DA_WORKSPACE_DIR: root };
490
+ const concurrency = resolveBatchConcurrency(opts);
491
+ let sbomByPurl;
492
+ try {
493
+ sbomByPurl = await generateSboms(manifestPaths, workspaceOpts, continueOnError, concurrency, collectedErrors);
494
+ }
495
+ catch (err) {
496
+ throw batchError(err.message, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, 0, collectedErrors));
497
+ }
498
+ if (Object.keys(sbomByPurl).length === 0) {
499
+ throw batchError(`No valid SBOMs produced from ${manifestPaths.length} manifest(s) at ${root}`, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, 0, collectedErrors));
500
+ }
501
+ const analysisResult = await analysis.requestStackBatch(sbomByPurl, theUrl, html, opts);
502
+ const meta = buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, Object.keys(sbomByPurl).length, collectedErrors);
503
+ if (wantMetadata) {
504
+ return { analysis: analysisResult, metadata: meta };
505
+ }
506
+ return analysisResult;
507
+ }
179
508
  /**
180
509
  * Validates the Exhort token.
181
510
  * @param {Options} [opts={}] - Optional parameters, potentially including token override.
@@ -23,6 +23,6 @@ export function runLicenseCheck(sbomContent: string, manifestPath: string, url:
23
23
  }>;
24
24
  error?: string;
25
25
  }>;
26
- export { getCompatibility } from "./compatibility.js";
27
- export { getProjectLicense, findLicenseFilePath, identifyLicense as identifyLicenseViaBackend } from "./project_license.js";
26
+ export { getCompatibility } from "./license_utils.js";
27
+ export { getProjectLicense, findLicenseFilePath, identifyLicense } from "./project_license.js";
28
28
  export { licensesFromReport, normalizeLicensesResponse, getLicenseDetails } from "./licenses_api.js";
@@ -3,10 +3,10 @@
3
3
  */
4
4
  import { getProjectLicense, findLicenseFilePath, identifyLicense } from './project_license.js';
5
5
  import { licensesFromReport, getLicenseDetails } from './licenses_api.js';
6
- import { getCompatibility } from './compatibility.js';
7
- export { getProjectLicense, findLicenseFilePath, identifyLicense as identifyLicenseViaBackend } from './project_license.js';
6
+ import { getCompatibility } from './license_utils.js';
7
+ export { getProjectLicense, findLicenseFilePath, identifyLicense } from './project_license.js';
8
8
  export { licensesFromReport, normalizeLicensesResponse, getLicenseDetails } from './licenses_api.js';
9
- export { getCompatibility } from './compatibility.js';
9
+ export { getCompatibility } from './license_utils.js';
10
10
  /**
11
11
  * Run full license check: resolve project license (with backend identification and details),
12
12
  * get dependency licenses from analysis report, and compute incompatibilities.
@@ -20,7 +20,7 @@ export { getCompatibility } from './compatibility.js';
20
20
  */
21
21
  export async function runLicenseCheck(sbomContent, manifestPath, url, opts = {}, analysisResult = null) {
22
22
  // Resolve project license from manifest and LICENSE file
23
- const projectLicense = getProjectLicense(manifestPath, opts);
23
+ const projectLicense = getProjectLicense(manifestPath);
24
24
  // Try backend identification for LICENSE file (more accurate than local pattern matching)
25
25
  const licenseFilePath = findLicenseFilePath(manifestPath);
26
26
  let backendFileId = null;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Find LICENSE file path in the same directory as the manifest.
3
+ * @param {string} manifestPath
4
+ * @returns {string|null} - path to LICENSE file or null if not found
5
+ */
6
+ export function findLicenseFilePath(manifestPath: string): string | null;
7
+ /**
8
+ * Very simple SPDX detection from common license text (first ~500 chars).
9
+ * @param {string} text
10
+ * @returns {string|null}
11
+ */
12
+ export function detectSpdxFromText(text: string): string | null;
13
+ /**
14
+ * Read LICENSE file and detect SPDX identifier.
15
+ * @param {string} manifestPath - path to manifest
16
+ * @returns {string|null} - SPDX identifier from LICENSE file or null
17
+ */
18
+ export function readLicenseFile(manifestPath: string): string | null;
19
+ /**
20
+ * Get project license from manifest or LICENSE file.
21
+ * Returns manifestLicense if provided, otherwise tries LICENSE file.
22
+ * @param {string|null} manifestLicense - license from manifest (or null)
23
+ * @param {string} manifestPath - path to manifest
24
+ * @returns {string|null} - SPDX identifier or null
25
+ */
26
+ export function getLicense(manifestLicense: string | null, manifestPath: string): string | null;
27
+ /**
28
+ * Normalize SPDX identifier for comparison (lowercase, strip common suffixes).
29
+ * @param {string} spdxOrName
30
+ * @returns {string}
31
+ */
32
+ export function normalizeSpdx(spdxOrName: string): string;
33
+ /**
34
+ * Check if a dependency's license is compatible with the project license based on backend categories.
35
+ *
36
+ * @param {string} [projectCategory] - backend category for project license: PERMISSIVE | WEAK_COPYLEFT | STRONG_COPYLEFT | UNKNOWN
37
+ * @param {string} [dependencyCategory] - backend category for dependency license: PERMISSIVE | WEAK_COPYLEFT | STRONG_COPYLEFT | UNKNOWN
38
+ * @returns {'compatible'|'incompatible'|'unknown'}
39
+ */
40
+ export function getCompatibility(projectCategory?: string, dependencyCategory?: string): "compatible" | "incompatible" | "unknown";
@@ -0,0 +1,134 @@
1
+ /**
2
+ * License utilities: file reading, SPDX detection, normalization, compatibility.
3
+ * This module has NO dependencies on providers or backend to avoid circular dependencies.
4
+ */
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ const LICENSE_FILES = ['LICENSE', 'LICENSE.md', 'LICENSE.txt'];
8
+ /**
9
+ * Find LICENSE file path in the same directory as the manifest.
10
+ * @param {string} manifestPath
11
+ * @returns {string|null} - path to LICENSE file or null if not found
12
+ */
13
+ export function findLicenseFilePath(manifestPath) {
14
+ const manifestDir = path.dirname(path.resolve(manifestPath));
15
+ for (const name of LICENSE_FILES) {
16
+ const filePath = path.join(manifestDir, name);
17
+ try {
18
+ if (fs.statSync(filePath).isFile()) {
19
+ return filePath;
20
+ }
21
+ }
22
+ catch {
23
+ // skip
24
+ }
25
+ }
26
+ return null;
27
+ }
28
+ /**
29
+ * Very simple SPDX detection from common license text (first ~500 chars).
30
+ * @param {string} text
31
+ * @returns {string|null}
32
+ */
33
+ export function detectSpdxFromText(text) {
34
+ const head = text.slice(0, 500);
35
+ if (/Apache License,?\s*Version 2\.0/i.test(head)) {
36
+ return 'Apache-2.0';
37
+ }
38
+ if (/MIT License/i.test(head) && /Permission is hereby granted/i.test(head)) {
39
+ return 'MIT';
40
+ }
41
+ if (/GNU AFFERO GENERAL PUBLIC LICENSE\s+Version 3/i.test(head)) {
42
+ return 'AGPL-3.0-only';
43
+ }
44
+ if (/GNU LESSER GENERAL PUBLIC LICENSE\s+Version 3/i.test(head)) {
45
+ return 'LGPL-3.0-only';
46
+ }
47
+ if (/GNU LESSER GENERAL PUBLIC LICENSE\s+Version 2\.1/i.test(head)) {
48
+ return 'LGPL-2.1-only';
49
+ }
50
+ if (/GNU GENERAL PUBLIC LICENSE\s+Version 2/i.test(head)) {
51
+ return 'GPL-2.0-only';
52
+ }
53
+ if (/GNU GENERAL PUBLIC LICENSE\s+Version 3/i.test(head)) {
54
+ return 'GPL-3.0-only';
55
+ }
56
+ if (/BSD 2-Clause/i.test(head)) {
57
+ return 'BSD-2-Clause';
58
+ }
59
+ if (/BSD 3-Clause/i.test(head)) {
60
+ return 'BSD-3-Clause';
61
+ }
62
+ return null;
63
+ }
64
+ /**
65
+ * Read LICENSE file and detect SPDX identifier.
66
+ * @param {string} manifestPath - path to manifest
67
+ * @returns {string|null} - SPDX identifier from LICENSE file or null
68
+ */
69
+ export function readLicenseFile(manifestPath) {
70
+ const licenseFilePath = findLicenseFilePath(manifestPath);
71
+ if (!licenseFilePath) {
72
+ return null;
73
+ }
74
+ try {
75
+ const content = fs.readFileSync(licenseFilePath, 'utf-8');
76
+ return detectSpdxFromText(content) || content.split('\n')[0]?.trim() || null;
77
+ }
78
+ catch {
79
+ return null;
80
+ }
81
+ }
82
+ /**
83
+ * Get project license from manifest or LICENSE file.
84
+ * Returns manifestLicense if provided, otherwise tries LICENSE file.
85
+ * @param {string|null} manifestLicense - license from manifest (or null)
86
+ * @param {string} manifestPath - path to manifest
87
+ * @returns {string|null} - SPDX identifier or null
88
+ */
89
+ export function getLicense(manifestLicense, manifestPath) {
90
+ return manifestLicense || readLicenseFile(manifestPath) || null;
91
+ }
92
+ /**
93
+ * Normalize SPDX identifier for comparison (lowercase, strip common suffixes).
94
+ * @param {string} spdxOrName
95
+ * @returns {string}
96
+ */
97
+ export function normalizeSpdx(spdxOrName) {
98
+ const s = String(spdxOrName).trim().toLowerCase();
99
+ if (s.endsWith(' license')) {
100
+ return s.slice(0, -8);
101
+ }
102
+ return s;
103
+ }
104
+ /**
105
+ * Check if a dependency's license is compatible with the project license based on backend categories.
106
+ *
107
+ * @param {string} [projectCategory] - backend category for project license: PERMISSIVE | WEAK_COPYLEFT | STRONG_COPYLEFT | UNKNOWN
108
+ * @param {string} [dependencyCategory] - backend category for dependency license: PERMISSIVE | WEAK_COPYLEFT | STRONG_COPYLEFT | UNKNOWN
109
+ * @returns {'compatible'|'incompatible'|'unknown'}
110
+ */
111
+ export function getCompatibility(projectCategory, dependencyCategory) {
112
+ if (!projectCategory || !dependencyCategory) {
113
+ return 'unknown';
114
+ }
115
+ const proj = projectCategory.toUpperCase();
116
+ const dep = dependencyCategory.toUpperCase();
117
+ if (proj === 'UNKNOWN' || dep === 'UNKNOWN') {
118
+ return 'unknown';
119
+ }
120
+ const restrictiveness = {
121
+ 'PERMISSIVE': 1,
122
+ 'WEAK_COPYLEFT': 2,
123
+ 'STRONG_COPYLEFT': 3
124
+ };
125
+ const projLevel = restrictiveness[proj];
126
+ const depLevel = restrictiveness[dep];
127
+ if (projLevel === undefined || depLevel === undefined) {
128
+ return 'unknown';
129
+ }
130
+ if (depLevel > projLevel) {
131
+ return 'incompatible';
132
+ }
133
+ return 'compatible';
134
+ }
@@ -4,6 +4,7 @@
4
4
  * @see https://github.com/guacsec/trustify-dependency-analytics#license-analysis-apiv5licenses
5
5
  * @see https://github.com/guacsec/trustify-da-api-spec/blob/main/api/v5/openapi.yaml
6
6
  */
7
+ import { PackageURL } from 'packageurl-js';
7
8
  import { selectTrustifyDABackend } from '../index.js';
8
9
  import { addProxyAgent, getTokenHeaders } from '../tools.js';
9
10
  /**
@@ -39,6 +40,10 @@ export async function getLicenseDetails(spdxId, opts = {}) {
39
40
  throw new Error(`Failed to fetch license details: ${err.message}`);
40
41
  }
41
42
  }
43
+ function normalizePurlString(purl) {
44
+ const parsed = PackageURL.fromString(purl);
45
+ return new PackageURL(parsed.type, parsed.namespace, parsed.name, parsed.version, null, null).toString();
46
+ }
42
47
  /**
43
48
  * Normalize the LicensesResponse shape (array of LicenseProviderResult) into a map of purl -> license info.
44
49
  * Each provider result has { status, summary, packages } where packages is { [purl]: { concluded, evidence } }.
@@ -53,6 +58,7 @@ export function normalizeLicensesResponse(data, purls = []) {
53
58
  if (!data || !Array.isArray(data)) {
54
59
  return map;
55
60
  }
61
+ const normalizedPurlsSet = purls.length > 0 ? new Set(purls.map(normalizePurlString)) : null;
56
62
  for (const providerResult of data) {
57
63
  const packages = providerResult?.packages;
58
64
  if (!packages || typeof packages !== 'object') {
@@ -64,8 +70,9 @@ export function normalizeLicensesResponse(data, purls = []) {
64
70
  const expression = concluded?.expression;
65
71
  const licenses = identifiers.length > 0 ? identifiers : (expression ? [expression] : []);
66
72
  const category = concluded?.category; // PERMISSIVE | WEAK_COPYLEFT | STRONG_COPYLEFT | UNKNOWN
67
- if (purls.length === 0 || purls.includes(purl)) {
68
- map.set(purl, { licenses: licenses.filter(Boolean), category });
73
+ const normalizedPurl = normalizePurlString(purl);
74
+ if (normalizedPurlsSet === null || normalizedPurlsSet.has(normalizedPurl)) {
75
+ map.set(normalizedPurl, { licenses: licenses.filter(Boolean), category });
69
76
  }
70
77
  }
71
78
  // Use first provider that has packages; backend may return multiple (e.g. deps.dev)
@@ -10,12 +10,6 @@ export function getProjectLicense(manifestPath: string): {
10
10
  fromFile: string | null;
11
11
  mismatch: boolean;
12
12
  };
13
- /**
14
- * Find LICENSE file path in the same directory as the manifest.
15
- * @param {string} manifestPath
16
- * @returns {string|null} - path to LICENSE file or null if not found
17
- */
18
- export function findLicenseFilePath(manifestPath: string): string | null;
19
13
  /**
20
14
  * Call backend /licenses/identify endpoint to identify license from file.
21
15
  * @param {string} licenseFilePath - path to LICENSE file
@@ -23,3 +17,4 @@ export function findLicenseFilePath(manifestPath: string): string | null;
23
17
  * @returns {Promise<string|null>} - SPDX identifier or null
24
18
  */
25
19
  export function identifyLicense(licenseFilePath: string, opts?: {}): Promise<string | null>;
20
+ export { findLicenseFilePath, readLicenseFile } from "./license_utils.js";