@trustify-da/trustify-da-javascript-client 0.3.0-ea.e12bc82 → 0.3.0-ea.e258fba

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 (97) hide show
  1. package/README.md +367 -13
  2. package/dist/package.json +48 -28
  3. package/dist/src/analysis.d.ts +28 -5
  4. package/dist/src/analysis.js +99 -89
  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 +346 -9
  8. package/dist/src/cyclone_dx_sbom.d.ts +30 -3
  9. package/dist/src/cyclone_dx_sbom.js +95 -9
  10. package/dist/src/index.d.ts +202 -12
  11. package/dist/src/index.js +365 -30
  12. package/dist/src/license/index.d.ts +28 -0
  13. package/dist/src/license/index.js +103 -0
  14. package/dist/src/license/license_utils.d.ts +40 -0
  15. package/dist/src/license/license_utils.js +137 -0
  16. package/dist/src/license/licenses_api.d.ts +34 -0
  17. package/dist/src/license/licenses_api.js +98 -0
  18. package/dist/src/license/project_license.d.ts +20 -0
  19. package/dist/src/license/project_license.js +62 -0
  20. package/dist/src/oci_image/images.d.ts +4 -5
  21. package/dist/src/oci_image/images.js +15 -1
  22. package/dist/src/oci_image/utils.d.ts +7 -7
  23. package/dist/src/oci_image/utils.js +11 -2
  24. package/dist/src/package_version.d.ts +8 -0
  25. package/dist/src/package_version.js +31 -0
  26. package/dist/src/provider.d.ts +18 -5
  27. package/dist/src/provider.js +33 -5
  28. package/dist/src/providers/base_java.d.ts +68 -15
  29. package/dist/src/providers/base_java.js +82 -61
  30. package/dist/src/providers/base_javascript.d.ts +99 -12
  31. package/dist/src/providers/base_javascript.js +243 -27
  32. package/dist/src/providers/base_pyproject.d.ts +158 -0
  33. package/dist/src/providers/base_pyproject.js +322 -0
  34. package/dist/src/providers/containerfile_parser.d.ts +5 -0
  35. package/dist/src/providers/containerfile_parser.js +20 -0
  36. package/dist/src/providers/golang_gomodules.d.ts +30 -13
  37. package/dist/src/providers/golang_gomodules.js +219 -122
  38. package/dist/src/providers/gomod_parser.d.ts +4 -0
  39. package/dist/src/providers/gomod_parser.js +16 -0
  40. package/dist/src/providers/java_gradle.d.ts +76 -3
  41. package/dist/src/providers/java_gradle.js +323 -21
  42. package/dist/src/providers/java_gradle_groovy.d.ts +1 -1
  43. package/dist/src/providers/java_gradle_kotlin.d.ts +1 -1
  44. package/dist/src/providers/java_maven.d.ts +45 -10
  45. package/dist/src/providers/java_maven.js +300 -14
  46. package/dist/src/providers/javascript_bun.d.ts +22 -0
  47. package/dist/src/providers/javascript_bun.js +141 -0
  48. package/dist/src/providers/javascript_npm.d.ts +19 -0
  49. package/dist/src/providers/javascript_npm.js +61 -1
  50. package/dist/src/providers/javascript_pnpm.d.ts +14 -1
  51. package/dist/src/providers/javascript_pnpm.js +55 -5
  52. package/dist/src/providers/javascript_yarn.d.ts +12 -0
  53. package/dist/src/providers/javascript_yarn.js +75 -2
  54. package/dist/src/providers/manifest.d.ts +2 -0
  55. package/dist/src/providers/manifest.js +28 -7
  56. package/dist/src/providers/marker_evaluator.d.ts +14 -0
  57. package/dist/src/providers/marker_evaluator.js +191 -0
  58. package/dist/src/providers/oci_dockerfile.d.ts +51 -0
  59. package/dist/src/providers/oci_dockerfile.js +177 -0
  60. package/dist/src/providers/processors/yarn_berry_processor.d.ts +6 -2
  61. package/dist/src/providers/processors/yarn_berry_processor.js +91 -7
  62. package/dist/src/providers/processors/yarn_classic_processor.d.ts +6 -2
  63. package/dist/src/providers/processors/yarn_classic_processor.js +8 -6
  64. package/dist/src/providers/python_controller.d.ts +10 -3
  65. package/dist/src/providers/python_controller.js +122 -63
  66. package/dist/src/providers/python_pip.d.ts +16 -4
  67. package/dist/src/providers/python_pip.js +51 -58
  68. package/dist/src/providers/python_pip_pyproject.d.ts +61 -0
  69. package/dist/src/providers/python_pip_pyproject.js +146 -0
  70. package/dist/src/providers/python_poetry.d.ts +98 -0
  71. package/dist/src/providers/python_poetry.js +286 -0
  72. package/dist/src/providers/python_uv.d.ts +46 -0
  73. package/dist/src/providers/python_uv.js +269 -0
  74. package/dist/src/providers/requirements_parser.d.ts +6 -0
  75. package/dist/src/providers/requirements_parser.js +24 -0
  76. package/dist/src/providers/rust_cargo.d.ts +56 -0
  77. package/dist/src/providers/rust_cargo.js +682 -0
  78. package/dist/src/providers/tree-sitter-containerfile.wasm +0 -0
  79. package/dist/src/providers/tree-sitter-gomod.wasm +0 -0
  80. package/dist/src/providers/tree-sitter-requirements.wasm +0 -0
  81. package/dist/src/remediate.d.ts +21 -0
  82. package/dist/src/remediate.js +149 -0
  83. package/dist/src/remediation.d.ts +57 -0
  84. package/dist/src/remediation.js +436 -0
  85. package/dist/src/remediation_report.d.ts +40 -0
  86. package/dist/src/remediation_report.js +159 -0
  87. package/dist/src/sbom.d.ts +28 -2
  88. package/dist/src/sbom.js +26 -4
  89. package/dist/src/tools.d.ts +48 -6
  90. package/dist/src/tools.js +138 -2
  91. package/dist/src/updaters/maven_updater.d.ts +26 -0
  92. package/dist/src/updaters/maven_updater.js +322 -0
  93. package/dist/src/updaters/toml_updater.d.ts +33 -0
  94. package/dist/src/updaters/toml_updater.js +244 -0
  95. package/dist/src/workspace.d.ts +70 -0
  96. package/dist/src/workspace.js +256 -0
  97. package/package.json +49 -29
@@ -1,15 +1,22 @@
1
+ import crypto from 'node:crypto';
1
2
  import fs from 'node:fs';
2
3
  import os from 'node:os';
3
4
  import path from 'node:path';
4
5
  import { EOL } from 'os';
5
6
  import { XMLParser } from 'fast-xml-parser';
7
+ import { getLicense } from '../license/license_utils.js';
6
8
  import Sbom from '../sbom.js';
7
- import { getCustom } from '../tools.js';
9
+ import { getCustom, invokeCommand } from '../tools.js';
10
+ import { filterManifestPathsByDiscoveryIgnore, resolveWorkspaceDiscoveryIgnore } from '../workspace.js';
8
11
  import Base_java, { ecosystem_maven } from "./base_java.js";
9
12
  /** @typedef {import('../provider').Provider} */
10
13
  /** @typedef {import('../provider').Provided} Provided */
11
14
  /** @typedef {{name: string, version: string}} Package */
12
15
  /** @typedef {{groupId: string, artifactId: string, version: string, scope: string, ignore: boolean}} Dependency */
16
+ // Matches the legacy `exhortignore` and new `trustify-da-ignore` markers as whole
17
+ // tokens. The trailing `(?![\w-])` boundary prevents lookalikes such as
18
+ // `trustify-da-ignore-disabled` from being treated as ignore directives.
19
+ const IGNORE_MARKER_REGEX = /(exhortignore|trustify-da-ignore)(?![\w-])/;
13
20
  export default class Java_maven extends Base_java {
14
21
  constructor() {
15
22
  super('mvn', 'mvnw' + (process.platform === 'win32' ? '.cmd' : ''));
@@ -29,12 +36,12 @@ export default class Java_maven extends Base_java {
29
36
  * Provide content and content type for maven-maven stack analysis.
30
37
  * @param {string} manifest - the manifest path or name
31
38
  * @param {{}} [opts={}] - optional various options to pass along the application
32
- * @returns {Provided}
39
+ * @returns {Promise<Provided>}
33
40
  */
34
- provideStack(manifest, opts = {}) {
41
+ async provideStack(manifest, opts = {}) {
35
42
  return {
36
43
  ecosystem: ecosystem_maven,
37
- content: this.#createSbomStackAnalysis(manifest, opts),
44
+ content: await this.#createSbomStackAnalysis(manifest, opts),
38
45
  contentType: 'application/vnd.cyclonedx+json'
39
46
  };
40
47
  }
@@ -51,14 +58,38 @@ export default class Java_maven extends Base_java {
51
58
  contentType: 'application/vnd.cyclonedx+json'
52
59
  };
53
60
  }
61
+ /**
62
+ * Read license from pom.xml manifest, with fallback to LICENSE file
63
+ * @param {string} manifestPath - path to pom.xml
64
+ * @returns {string|null}
65
+ */
66
+ readLicenseFromManifest(manifestPath) {
67
+ let fromPom = null;
68
+ try {
69
+ const xml = fs.readFileSync(manifestPath, 'utf-8');
70
+ const parser = new XMLParser({ ignoreAttributes: false });
71
+ const obj = parser.parse(xml);
72
+ const project = obj?.project;
73
+ if (project?.licenses?.license) {
74
+ const license = Array.isArray(project.licenses.license)
75
+ ? project.licenses.license[0]
76
+ : project.licenses.license;
77
+ fromPom = (license?.name && license.name.trim()) || null;
78
+ }
79
+ }
80
+ catch {
81
+ // leave fromPom as null
82
+ }
83
+ return getLicense(fromPom, manifestPath);
84
+ }
54
85
  /**
55
86
  * Create a Dot Graph dependency tree for a manifest path.
56
87
  * @param {string} manifest - path for pom.xml
57
88
  * @param {{}} [opts={}] - optional various options to pass along the application
58
- * @returns {string} the Dot Graph content
89
+ * @returns {Promise<string>} the Dot Graph content
59
90
  * @private
60
91
  */
61
- #createSbomStackAnalysis(manifest, opts = {}) {
92
+ async #createSbomStackAnalysis(manifest, opts = {}) {
62
93
  const manifestDir = path.dirname(manifest);
63
94
  const mvn = this.selectToolBinary(manifest, opts);
64
95
  const mvnArgs = JSON.parse(getCustom('TRUSTIFY_DA_MVN_ARGS', '[]', opts));
@@ -105,26 +136,116 @@ export default class Java_maven extends Base_java {
105
136
  if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
106
137
  console.error("Dependency tree that will be used as input for creating the BOM =>" + EOL + EOL + content.toString());
107
138
  }
108
- let sbom = this.createSbomFileFromTextFormat(content.toString(), ignoredDeps, opts);
139
+ const depTreeContent = content.toString();
140
+ const hashMap = await this._buildMavenHashMap(depTreeContent, opts);
141
+ let sbom = this.createSbomFileFromTextFormat(depTreeContent, ignoredDeps, opts, manifest, hashMap);
109
142
  // delete temp file and directory
110
143
  fs.rmSync(tmpDir, { recursive: true, force: true });
111
144
  // return dependency graph as string
112
145
  return sbom;
113
146
  }
147
+ /** @type {Object<string, string>} Packaging types that produce .jar files despite non-jar packaging names. */
148
+ static PACKAGING_TO_JAR = { 'bundle': 'jar', 'eclipse-plugin': 'jar' };
114
149
  /**
150
+ * Build a Map of PURL string → CycloneDX hash entries by reading artifact files from the local Maven repository.
151
+ *
152
+ * Both the artifact file path and the hash-map key are derived from the
153
+ * shared {@link Base_java#parseCoordinate} parser: the file path uses the
154
+ * resolved version and raw classifier, while the key uses the same canonical
155
+ * PURL builder as {@link Base_java#parseDep}. This guarantees the key always
156
+ * matches the PURL that {@link Base_java#parseDependencyTree} looks up.
115
157
  *
158
+ * @param {string} depTreeText Raw dependency tree text from mvn dependency:tree
159
+ * @param {{}} [opts={}] Options bag (may contain TRUSTIFY_DA_MVN_REPO)
160
+ * @returns {Promise<Map<string, Array<{alg: string, content: string}>>>}
161
+ */
162
+ async _buildMavenHashMap(depTreeText, opts = {}) {
163
+ const m2Repo = getCustom('TRUSTIFY_DA_MVN_REPO', path.join(os.homedir(), '.m2', 'repository'), opts);
164
+ const hashMap = new Map();
165
+ const lines = depTreeText.split(EOL);
166
+ // Track hash coverage so an incomplete .m2 cache (e.g. ephemeral CI
167
+ // containers or resolve-only phases) surfaces a summary warning instead
168
+ // of silently producing an SBOM with missing hashes.
169
+ let attempted = 0;
170
+ let missed = 0;
171
+ for (const rawLine of lines) {
172
+ const trimmed = rawLine.trim();
173
+ // Strip leading tree-drawing characters (e.g. "\-", "+-", "|") so the
174
+ // parenthesized-line check sees the coordinate itself. Omitted
175
+ // duplicate/conflict lines start with these characters after trim(),
176
+ // then an opening "(" — without stripping, the "(" check never fires.
177
+ const cleaned = trimmed.replace(/^[|+\\\- ]+/, '');
178
+ if (!cleaned || cleaned.startsWith('(')) {
179
+ continue;
180
+ }
181
+ const coord = this.parseCoordinate(rawLine);
182
+ if (!coord.groupId || !coord.artifactId || !coord.packaging) {
183
+ continue;
184
+ }
185
+ if (coord.packaging === 'pom') {
186
+ continue;
187
+ }
188
+ // Key by the exact PURL parseDep() produces, so the lookup in
189
+ // parseDependencyTree (hashMap.get(to.toString())) always hits.
190
+ const purl = this._coordinateToPurl(coord).toString();
191
+ // The same artifact recurs across dependency-tree branches — notably in
192
+ // multi-module reactor builds, where every module re-lists shared deps.
193
+ // The digest is deterministic per PURL, so skip the redundant file read
194
+ // and SHA-256 computation once this PURL is already hashed.
195
+ if (hashMap.has(purl)) {
196
+ continue;
197
+ }
198
+ const ext = Java_maven.PACKAGING_TO_JAR[coord.packaging] || coord.packaging;
199
+ const groupPath = coord.groupId.replaceAll('.', path.sep);
200
+ const fileName = coord.classifier
201
+ ? `${coord.artifactId}-${coord.version}-${coord.classifier}.${ext}`
202
+ : `${coord.artifactId}-${coord.version}.${ext}`;
203
+ const artifactPath = path.join(m2Repo, groupPath, coord.artifactId, coord.version, fileName);
204
+ attempted++;
205
+ try {
206
+ const stream = fs.createReadStream(artifactPath);
207
+ const hash = crypto.createHash('sha256');
208
+ for await (const chunk of stream) {
209
+ hash.update(chunk);
210
+ }
211
+ const digest = hash.digest('hex');
212
+ hashMap.set(purl, [{ alg: 'SHA-256', content: digest }]);
213
+ }
214
+ catch {
215
+ missed++;
216
+ if (process.env['TRUSTIFY_DA_DEBUG'] === 'true') {
217
+ console.error(`Maven hash: artifact not found at ${artifactPath}, omitting hash`);
218
+ }
219
+ }
220
+ }
221
+ // Mirror the pip provider's convention (python_controller.js): surface an
222
+ // unconditional warning when hashes could not be computed, so incomplete
223
+ // hash coverage is visible even without TRUSTIFY_DA_DEBUG.
224
+ if (missed > 0) {
225
+ console.warn(`Maven hash: ${missed} of ${attempted} artifacts could not be read from the local .m2 cache; SBOM will be generated without hashes for those components.`);
226
+ }
227
+ return hashMap;
228
+ }
229
+ /**
116
230
  * @param {String} textGraphList Text graph String of the manifest
117
231
  * @param {[String]} ignoredDeps List of ignored dependencies to be omitted from sbom
232
+ * @param {{}} opts Options
233
+ * @param {String} manifestPath Path to the pom.xml manifest
234
+ * @param {Map<string, Array<{alg: string, content: string}>>} [hashMap] PURL→hashes map
118
235
  * @return {String} formatted sbom Json String with all dependencies
119
236
  */
120
- createSbomFileFromTextFormat(textGraphList, ignoredDeps, opts) {
237
+ createSbomFileFromTextFormat(textGraphList, ignoredDeps, opts, manifestPath, hashMap) {
121
238
  let lines = textGraphList.split(EOL);
122
239
  // get root component
123
240
  let root = lines[0];
124
241
  let rootPurl = this.parseDep(root);
242
+ const license = this.readLicenseFromManifest(manifestPath);
125
243
  let sbom = new Sbom();
126
- sbom.addRoot(rootPurl);
244
+ sbom.addRoot(rootPurl, license);
127
245
  this.parseDependencyTree(root, 0, lines.slice(1), sbom);
246
+ // Attach Maven artifact hashes as a post-processing step, keeping this
247
+ // Maven-specific concern out of the shared dependency-tree parser.
248
+ sbom.attachHashes(hashMap);
128
249
  return sbom.filterIgnoredDeps(ignoredDeps).getAsJsonString(opts);
129
250
  }
130
251
  /**
@@ -153,10 +274,12 @@ export default class Java_maven extends Base_java {
153
274
  /** @type [Dependency] */
154
275
  let dependencies = this.#getDependencies(tmpEffectivePom)
155
276
  .filter(d => !this.#dependencyIn(d, ignored));
277
+ dependencies = this.#resolveVersionRanges(dependencies, manifestPath, opts);
156
278
  let sbom = new Sbom();
157
279
  let rootDependency = this.#getRootFromPom(tmpEffectivePom, manifestPath);
158
280
  let purlRoot = this.toPurl(rootDependency.groupId, rootDependency.artifactId, rootDependency.version);
159
- sbom.addRoot(purlRoot);
281
+ const license = this.readLicenseFromManifest(manifestPath);
282
+ sbom.addRoot(purlRoot, license);
160
283
  dependencies.forEach(dep => {
161
284
  let currentPurl = this.toPurl(dep.groupId, dep.artifactId, dep.version);
162
285
  sbom.addDependency(purlRoot, currentPurl);
@@ -199,7 +322,8 @@ export default class Java_maven extends Base_java {
199
322
  return rootDependency;
200
323
  }
201
324
  /**
202
- * Get a list of dependencies with marking of dependencies commented with <!--exhortignore-->.
325
+ * Get a list of dependencies with marking of dependencies commented with
326
+ * <!--exhortignore--> or <!--trustify-da-ignore-->.
203
327
  * @param {string} manifest - path for pom.xml
204
328
  * @returns {[Dependency]} an array of dependencies
205
329
  * @private
@@ -209,7 +333,7 @@ export default class Java_maven extends Base_java {
209
333
  let ignored = [];
210
334
  // build xml parser with options
211
335
  let parser = new XMLParser({
212
- commentPropName: '#comment',
336
+ commentPropName: '#comment', // mark comments with #comment
213
337
  isArray: (_, jpath) => 'project.dependencies.dependency' === jpath,
214
338
  parseTagValue: false
215
339
  });
@@ -217,7 +341,7 @@ export default class Java_maven extends Base_java {
217
341
  let buf = fs.readFileSync(manifest);
218
342
  // parse manifest pom.xml to json
219
343
  let pomJson = parser.parse(buf.toString());
220
- // iterate over all dependencies and chery pick dependencies with a exhortignore comment
344
+ // iterate over all dependencies and chery pick dependencies with an ignore comment
221
345
  let pomXml;
222
346
  // project without modules
223
347
  if (pomJson['project']) {
@@ -233,7 +357,7 @@ export default class Java_maven extends Base_java {
233
357
  }
234
358
  pomXml.forEach(dep => {
235
359
  let ignore = false;
236
- if (dep['#comment'] && dep['#comment'].includes('exhortignore')) { // #comment is an array or a string
360
+ if (dep['#comment'] && [].concat(dep['#comment']).some(comment => IGNORE_MARKER_REGEX.test(comment))) { // #comment is an array or a string
237
361
  ignore = true;
238
362
  }
239
363
  if (dep['scope'] !== 'test') {
@@ -260,4 +384,166 @@ export default class Java_maven extends Base_java {
260
384
  #dependencyIn(dep, deps) {
261
385
  return deps.filter(d => dep.artifactId === d.artifactId && dep.groupId === d.groupId && dep.scope === d.scope).length > 0;
262
386
  }
387
+ /**
388
+ * Returns true if the given version string is a Maven version range
389
+ * (starts with '[' or '(').
390
+ * @param {string} version
391
+ * @returns {boolean}
392
+ * @private
393
+ */
394
+ #isVersionRange(version) {
395
+ return typeof version === 'string' && (version.startsWith('[') || version.startsWith('('));
396
+ }
397
+ /**
398
+ * Resolves Maven version ranges in the given dependency list by running
399
+ * maven-dependency-plugin:tree and reading the concrete versions it selects.
400
+ * If no dependency uses a version range, returns the list unchanged.
401
+ * @param {Dependency[]} dependencies
402
+ * @param {string} manifestPath
403
+ * @param {object} opts
404
+ * @returns {Dependency[]}
405
+ * @private
406
+ */
407
+ #resolveVersionRanges(dependencies, manifestPath, opts = {}) {
408
+ // short-circuit if no dependency has a version range
409
+ if (!dependencies.some(dep => this.#isVersionRange(dep.version))) {
410
+ return dependencies;
411
+ }
412
+ const mvn = this.selectToolBinary(manifestPath, opts);
413
+ const mvnArgs = JSON.parse(getCustom('TRUSTIFY_DA_MVN_ARGS', '[]', opts));
414
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trustify_da_range_'));
415
+ const tmpDepTree = path.join(tmpDir, 'mvn_deptree_ranges.txt');
416
+ try {
417
+ this._invokeCommand(mvn, [
418
+ '-q',
419
+ 'org.apache.maven.plugins:maven-dependency-plugin:3.6.0:tree',
420
+ '-Dscope=compile',
421
+ '-DoutputType=text',
422
+ `-DoutputFile=${tmpDepTree}`,
423
+ ...mvnArgs
424
+ ], { cwd: path.dirname(manifestPath) });
425
+ const content = fs.readFileSync(tmpDepTree);
426
+ const lines = content.toString().split(EOL).filter(l => l.trim() !== '');
427
+ // Build a map of groupId:artifactId -> resolved version from depth-1 entries
428
+ /** @type {Map<string, string>} */
429
+ const resolvedVersions = new Map();
430
+ for (const line of lines) {
431
+ if (this._getDepth(line) === 1) {
432
+ const purl = this.parseDep(line);
433
+ resolvedVersions.set(`${purl.namespace}:${purl.name}`, purl.version);
434
+ }
435
+ }
436
+ // Replace version ranges with resolved concrete versions
437
+ return dependencies.map(dep => {
438
+ if (this.#isVersionRange(dep.version)) {
439
+ const key = `${dep.groupId}:${dep.artifactId}`;
440
+ const resolved = resolvedVersions.get(key);
441
+ if (resolved) {
442
+ return { ...dep, version: resolved };
443
+ }
444
+ }
445
+ return dep;
446
+ });
447
+ }
448
+ catch (error) {
449
+ if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
450
+ console.error("Failed to resolve Maven version ranges: " + error.message);
451
+ }
452
+ return dependencies;
453
+ }
454
+ finally {
455
+ fs.rmSync(tmpDir, { recursive: true, force: true });
456
+ }
457
+ }
458
+ }
459
+ const DEFAULT_MAVEN_DISCOVERY_IGNORE = [
460
+ '**/target/**',
461
+ ];
462
+ /**
463
+ * Discover all pom.xml manifest paths in a Maven multi-module project.
464
+ *
465
+ * @param {string} workspaceRoot - Absolute or relative path to workspace root (must contain pom.xml)
466
+ * @param {object} [opts={}]
467
+ * @returns {Promise<string[]>} Paths to pom.xml files (absolute)
468
+ */
469
+ export async function discoverMavenModules(workspaceRoot, opts = {}) {
470
+ const root = path.resolve(workspaceRoot);
471
+ const rootPom = path.join(root, 'pom.xml');
472
+ if (!fs.existsSync(rootPom)) {
473
+ return [];
474
+ }
475
+ let mvnBin;
476
+ try {
477
+ mvnBin = new Java_maven().selectToolBinary(rootPom, opts);
478
+ }
479
+ catch {
480
+ return [rootPom];
481
+ }
482
+ const visited = new Set();
483
+ const manifestPaths = [rootPom];
484
+ collectMavenModules(root, mvnBin, visited, manifestPaths);
485
+ const ignorePatterns = [...resolveWorkspaceDiscoveryIgnore(opts), ...DEFAULT_MAVEN_DISCOVERY_IGNORE];
486
+ return filterManifestPathsByDiscoveryIgnore(manifestPaths, root, ignorePatterns);
487
+ }
488
+ /**
489
+ * @param {string} dir - Absolute path to directory containing pom.xml
490
+ * @param {string} mvnBin - Maven binary path
491
+ * @param {Set<string>} visited - Already-visited directories (cycle guard)
492
+ * @param {string[]} manifestPaths - Accumulator for discovered pom.xml paths
493
+ */
494
+ function collectMavenModules(dir, mvnBin, visited, manifestPaths) {
495
+ const resolvedDir = path.resolve(dir);
496
+ if (visited.has(resolvedDir)) {
497
+ return;
498
+ }
499
+ visited.add(resolvedDir);
500
+ const modules = listMavenModules(resolvedDir, mvnBin);
501
+ for (const mod of modules) {
502
+ const moduleDir = path.resolve(resolvedDir, mod);
503
+ const modulePom = path.join(moduleDir, 'pom.xml');
504
+ if (fs.existsSync(modulePom)) {
505
+ manifestPaths.push(modulePom);
506
+ collectMavenModules(moduleDir, mvnBin, visited, manifestPaths);
507
+ }
508
+ }
509
+ }
510
+ /**
511
+ * @param {string} dir - Directory containing pom.xml
512
+ * @param {string} mvnBin - Maven binary path
513
+ * @returns {string[]} Module directory names (relative to `dir`)
514
+ */
515
+ function listMavenModules(dir, mvnBin) {
516
+ let output;
517
+ try {
518
+ output = invokeCommand(mvnBin, [
519
+ 'help:evaluate',
520
+ '-Dexpression=project.modules',
521
+ '-q',
522
+ '-DforceStdout',
523
+ '-f', path.join(dir, 'pom.xml'),
524
+ '--batch-mode',
525
+ ], { cwd: dir });
526
+ }
527
+ catch {
528
+ return [];
529
+ }
530
+ const raw = output.toString().trim();
531
+ if (!raw || raw.startsWith('<modules')) {
532
+ return [];
533
+ }
534
+ return parseMavenModuleList(raw);
535
+ }
536
+ /**
537
+ * @param {string} raw - Raw stdout from mvn help:evaluate -DforceStdout
538
+ * @returns {string[]}
539
+ */
540
+ function parseMavenModuleList(raw) {
541
+ const parser = new XMLParser();
542
+ const parsed = parser.parse(raw);
543
+ const entries = parsed?.strings?.string;
544
+ if (!entries) {
545
+ return [];
546
+ }
547
+ const list = Array.isArray(entries) ? entries : [entries];
548
+ return list.map(s => String(s).trim()).filter(Boolean);
263
549
  }
@@ -0,0 +1,22 @@
1
+ export default class Javascript_bun extends Base_javascript {
2
+ /**
3
+ * Parses `bun.lock` into a hash map keyed by `name@version`. Each entry in
4
+ * the `packages` section is an array whose first element is the resolved id
5
+ * (`name@version`) and whose fourth element is the SRI integrity string.
6
+ * @param {string} lockDir - Directory containing bun.lock
7
+ * @returns {Map<string, Array<{alg: string, content: string}>>} Hash map
8
+ * @protected
9
+ */
10
+ protected _parseLockFileHashes(lockDir: string): Map<string, Array<{
11
+ alg: string;
12
+ content: string;
13
+ }>>;
14
+ _listCmdArgs(): void;
15
+ _buildDependencyTree(includeTransitive: any, opts?: {}): {
16
+ name: any;
17
+ version: any;
18
+ dependencies: {};
19
+ };
20
+ #private;
21
+ }
22
+ import Base_javascript from './base_javascript.js';
@@ -0,0 +1,141 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parse } from 'jsonc-parser';
4
+ import Base_javascript, { sriToHash } from './base_javascript.js';
5
+ export default class Javascript_bun extends Base_javascript {
6
+ _lockFileName() {
7
+ return "bun.lock";
8
+ }
9
+ /**
10
+ * Parses `bun.lock` into a hash map keyed by `name@version`. Each entry in
11
+ * the `packages` section is an array whose first element is the resolved id
12
+ * (`name@version`) and whose fourth element is the SRI integrity string.
13
+ * @param {string} lockDir - Directory containing bun.lock
14
+ * @returns {Map<string, Array<{alg: string, content: string}>>} Hash map
15
+ * @protected
16
+ */
17
+ _parseLockFileHashes(lockDir) {
18
+ const map = new Map();
19
+ const lockPath = path.join(lockDir, this._lockFileName());
20
+ if (!fs.existsSync(lockPath)) {
21
+ return map;
22
+ }
23
+ let lockData;
24
+ try {
25
+ lockData = parse(fs.readFileSync(lockPath, 'utf-8'));
26
+ }
27
+ catch (_) {
28
+ return map;
29
+ }
30
+ const packages = lockData?.packages || {};
31
+ for (const entry of Object.values(packages)) {
32
+ if (!Array.isArray(entry) || typeof entry[0] !== 'string' || typeof entry[3] !== 'string') {
33
+ continue;
34
+ }
35
+ const id = entry[0];
36
+ const at = id.lastIndexOf('@');
37
+ if (at <= 0) {
38
+ continue;
39
+ }
40
+ const name = id.slice(0, at);
41
+ const version = id.slice(at + 1);
42
+ const hash = sriToHash(entry[3]);
43
+ if (name && version && hash) {
44
+ map.set(`${name}@${version}`, [hash]);
45
+ }
46
+ }
47
+ return map;
48
+ }
49
+ _cmdName() {
50
+ return "bun";
51
+ }
52
+ _listCmdArgs() {
53
+ throw new Error("not supported by Bun");
54
+ }
55
+ _updateLockFileCmdArgs() {
56
+ return ['install', '--lockfile-only'];
57
+ }
58
+ _buildDependencyTree(includeTransitive, opts = {}) {
59
+ this._version();
60
+ const manifestDir = path.dirname(this._getManifest().manifestPath);
61
+ const lockDir = this._findLockFileDir(manifestDir, opts) || manifestDir;
62
+ this._createLockFile(lockDir);
63
+ this._loadHashes(lockDir);
64
+ const lockContent = fs.readFileSync(path.join(lockDir, 'bun.lock'), 'utf-8');
65
+ const lockData = parse(lockContent);
66
+ const packages = lockData.packages || {};
67
+ const memberName = this._getManifest().name;
68
+ const workspaceEntry = this.#findWorkspaceEntry(lockData, lockDir, manifestDir, memberName);
69
+ const directDeps = workspaceEntry?.dependencies || {};
70
+ const tree = { name: memberName, version: this._getManifest().version, dependencies: {} };
71
+ const visited = new Set();
72
+ for (const depName of Object.keys(directDeps)) {
73
+ const resolved = this.#resolvePackage(depName, '', packages);
74
+ if (resolved) {
75
+ tree.dependencies[depName] = this.#buildNode(depName, resolved, packages, includeTransitive, visited);
76
+ }
77
+ }
78
+ return tree;
79
+ }
80
+ #findWorkspaceEntry(lockData, lockDir, manifestDir, memberName) {
81
+ const workspaces = lockData.workspaces || {};
82
+ const relPath = path.relative(lockDir, path.resolve(manifestDir));
83
+ if (!relPath || relPath === '.') {
84
+ return workspaces[''] || {};
85
+ }
86
+ const normalised = relPath.split(path.sep).join('/');
87
+ if (workspaces[normalised]) {
88
+ return workspaces[normalised];
89
+ }
90
+ for (const [wsPath, entry] of Object.entries(workspaces)) {
91
+ if (entry.name === memberName && wsPath !== '') {
92
+ return entry;
93
+ }
94
+ }
95
+ return workspaces[''] || {};
96
+ }
97
+ #resolvePackage(depName, parentKey, packages) {
98
+ if (parentKey) {
99
+ const scopedKey = `${parentKey}/${depName}`;
100
+ if (packages[scopedKey]) {
101
+ return packages[scopedKey];
102
+ }
103
+ }
104
+ return packages[depName] || null;
105
+ }
106
+ #buildNode(depName, resolved, packages, includeTransitive, visited) {
107
+ const resolvedId = Array.isArray(resolved) ? resolved[0] : resolved;
108
+ const version = this.#extractVersion(resolvedId);
109
+ const node = { version };
110
+ if (!includeTransitive) {
111
+ return node;
112
+ }
113
+ const metadata = Array.isArray(resolved) ? (resolved[2] || {}) : {};
114
+ const subDeps = metadata.dependencies || {};
115
+ if (Object.keys(subDeps).length > 0) {
116
+ const visitKey = `${depName}@${version}`;
117
+ if (visited.has(visitKey)) {
118
+ return node;
119
+ }
120
+ visited.add(visitKey);
121
+ node.dependencies = {};
122
+ for (const subName of Object.keys(subDeps)) {
123
+ const subResolved = this.#resolvePackage(subName, depName, packages);
124
+ if (subResolved) {
125
+ node.dependencies[subName] = this.#buildNode(subName, subResolved, packages, true, visited);
126
+ }
127
+ }
128
+ }
129
+ return node;
130
+ }
131
+ #extractVersion(resolvedId) {
132
+ if (typeof resolvedId !== 'string') {
133
+ return '0.0.0';
134
+ }
135
+ const atIdx = resolvedId.lastIndexOf('@');
136
+ if (atIdx > 0) {
137
+ return resolvedId.substring(atIdx + 1);
138
+ }
139
+ return '0.0.0';
140
+ }
141
+ }
@@ -1,4 +1,23 @@
1
1
  export default class Javascript_npm extends Base_javascript {
2
+ /**
3
+ * Parses `package-lock.json` (lockfileVersion 2/3) into a hash map keyed by
4
+ * `name@version`. Each `packages` entry is keyed by its install path
5
+ * (e.g. `node_modules/@hapi/joi`); the package name is the segment after the
6
+ * final `node_modules/`. The `integrity` field holds an SRI string.
7
+ * @param {string} lockDir - Directory containing package-lock.json
8
+ * @returns {Map<string, Array<{alg: string, content: string}>>} Hash map
9
+ * @protected
10
+ */
11
+ protected _parseLockFileHashes(lockDir: string): Map<string, Array<{
12
+ alg: string;
13
+ content: string;
14
+ }>>;
2
15
  _listCmdArgs(includeTransitive: any): string[];
16
+ _buildDependencyTree(includeTransitive: any, opts?: {}): Object | {
17
+ name: any;
18
+ version: any;
19
+ dependencies: any;
20
+ optionalDependencies: any;
21
+ };
3
22
  }
4
23
  import Base_javascript from './base_javascript.js';
@@ -1,8 +1,47 @@
1
- import Base_javascript from './base_javascript.js';
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import Base_javascript, { sriToHash } from './base_javascript.js';
2
4
  export default class Javascript_npm extends Base_javascript {
3
5
  _lockFileName() {
4
6
  return "package-lock.json";
5
7
  }
8
+ /**
9
+ * Parses `package-lock.json` (lockfileVersion 2/3) into a hash map keyed by
10
+ * `name@version`. Each `packages` entry is keyed by its install path
11
+ * (e.g. `node_modules/@hapi/joi`); the package name is the segment after the
12
+ * final `node_modules/`. The `integrity` field holds an SRI string.
13
+ * @param {string} lockDir - Directory containing package-lock.json
14
+ * @returns {Map<string, Array<{alg: string, content: string}>>} Hash map
15
+ * @protected
16
+ */
17
+ _parseLockFileHashes(lockDir) {
18
+ const map = new Map();
19
+ const lockPath = path.join(lockDir, this._lockFileName());
20
+ if (!fs.existsSync(lockPath)) {
21
+ return map;
22
+ }
23
+ let lock;
24
+ try {
25
+ lock = JSON.parse(fs.readFileSync(lockPath, 'utf-8'));
26
+ }
27
+ catch (_) {
28
+ return map;
29
+ }
30
+ const packages = lock.packages || {};
31
+ for (const [pkgPath, entry] of Object.entries(packages)) {
32
+ if (!pkgPath || !entry || !entry.integrity || !entry.version) {
33
+ continue;
34
+ }
35
+ const marker = 'node_modules/';
36
+ const idx = pkgPath.lastIndexOf(marker);
37
+ const name = idx < 0 ? pkgPath : pkgPath.slice(idx + marker.length);
38
+ const hash = sriToHash(entry.integrity);
39
+ if (name && hash) {
40
+ map.set(`${name}@${entry.version}`, [hash]);
41
+ }
42
+ }
43
+ return map;
44
+ }
6
45
  _cmdName() {
7
46
  return "npm";
8
47
  }
@@ -12,4 +51,25 @@ export default class Javascript_npm extends Base_javascript {
12
51
  _updateLockFileCmdArgs() {
13
52
  return ['install', '--package-lock-only'];
14
53
  }
54
+ _buildDependencyTree(includeTransitive, opts = {}) {
55
+ // npm ls --json returns a single tree rooted at the workspace root.
56
+ // When analyzing a workspace member, its deps are nested under the
57
+ // root's dependencies keyed by the member name — extract that subtree
58
+ // so downstream analysis sees only the member's dependencies.
59
+ const tree = super._buildDependencyTree(includeTransitive, opts);
60
+ const memberName = this._getManifest().name;
61
+ if (tree.name === memberName) {
62
+ return tree;
63
+ }
64
+ const memberEntry = tree.dependencies?.[memberName];
65
+ if (memberEntry) {
66
+ return {
67
+ name: memberName,
68
+ version: memberEntry.version || this._getManifest().version,
69
+ dependencies: memberEntry.dependencies,
70
+ optionalDependencies: memberEntry.optionalDependencies,
71
+ };
72
+ }
73
+ return tree;
74
+ }
15
75
  }