@trustify-da/trustify-da-javascript-client 0.3.0-ea.b8af0f8 → 0.3.0-ea.bdaadb2

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 (88) hide show
  1. package/README.md +250 -11
  2. package/dist/package.json +33 -25
  3. package/dist/src/analysis.d.ts +14 -7
  4. package/dist/src/analysis.js +32 -15
  5. package/dist/src/cli.js +156 -3
  6. package/dist/src/cyclone_dx_sbom.d.ts +27 -1
  7. package/dist/src/cyclone_dx_sbom.js +82 -9
  8. package/dist/src/index.d.ts +86 -11
  9. package/dist/src/index.js +102 -30
  10. package/dist/src/license/index.d.ts +3 -3
  11. package/dist/src/license/index.js +4 -1
  12. package/dist/src/license/license_utils.js +4 -1
  13. package/dist/src/license/licenses_api.d.ts +2 -2
  14. package/dist/src/oci_image/images.d.ts +1 -1
  15. package/dist/src/oci_image/images.js +15 -1
  16. package/dist/src/oci_image/utils.d.ts +5 -5
  17. package/dist/src/oci_image/utils.js +11 -2
  18. package/dist/src/package_version.d.ts +8 -0
  19. package/dist/src/package_version.js +31 -0
  20. package/dist/src/provider.d.ts +4 -3
  21. package/dist/src/provider.js +12 -2
  22. package/dist/src/providers/base_java.d.ts +67 -12
  23. package/dist/src/providers/base_java.js +82 -61
  24. package/dist/src/providers/base_javascript.d.ts +74 -9
  25. package/dist/src/providers/base_javascript.js +149 -9
  26. package/dist/src/providers/base_pyproject.d.ts +158 -0
  27. package/dist/src/providers/base_pyproject.js +322 -0
  28. package/dist/src/providers/containerfile_parser.d.ts +5 -0
  29. package/dist/src/providers/containerfile_parser.js +20 -0
  30. package/dist/src/providers/golang_gomodules.d.ts +23 -13
  31. package/dist/src/providers/golang_gomodules.js +207 -120
  32. package/dist/src/providers/gomod_parser.d.ts +4 -0
  33. package/dist/src/providers/gomod_parser.js +16 -0
  34. package/dist/src/providers/java_gradle.d.ts +67 -0
  35. package/dist/src/providers/java_gradle.js +310 -17
  36. package/dist/src/providers/java_gradle_groovy.d.ts +1 -1
  37. package/dist/src/providers/java_gradle_kotlin.d.ts +1 -1
  38. package/dist/src/providers/java_maven.d.ts +38 -5
  39. package/dist/src/providers/java_maven.js +261 -8
  40. package/dist/src/providers/javascript_bun.d.ts +22 -0
  41. package/dist/src/providers/javascript_bun.js +141 -0
  42. package/dist/src/providers/javascript_npm.d.ts +19 -0
  43. package/dist/src/providers/javascript_npm.js +61 -1
  44. package/dist/src/providers/javascript_pnpm.d.ts +13 -0
  45. package/dist/src/providers/javascript_pnpm.js +53 -3
  46. package/dist/src/providers/javascript_yarn.d.ts +12 -0
  47. package/dist/src/providers/javascript_yarn.js +75 -2
  48. package/dist/src/providers/manifest.d.ts +2 -0
  49. package/dist/src/providers/manifest.js +22 -4
  50. package/dist/src/providers/marker_evaluator.d.ts +14 -0
  51. package/dist/src/providers/marker_evaluator.js +191 -0
  52. package/dist/src/providers/oci_dockerfile.d.ts +51 -0
  53. package/dist/src/providers/oci_dockerfile.js +177 -0
  54. package/dist/src/providers/processors/yarn_berry_processor.d.ts +6 -2
  55. package/dist/src/providers/processors/yarn_berry_processor.js +91 -7
  56. package/dist/src/providers/processors/yarn_classic_processor.d.ts +6 -2
  57. package/dist/src/providers/processors/yarn_classic_processor.js +8 -6
  58. package/dist/src/providers/python_controller.d.ts +5 -1
  59. package/dist/src/providers/python_controller.js +69 -8
  60. package/dist/src/providers/python_pip.d.ts +5 -0
  61. package/dist/src/providers/python_pip.js +6 -6
  62. package/dist/src/providers/python_pip_pyproject.d.ts +61 -0
  63. package/dist/src/providers/python_pip_pyproject.js +146 -0
  64. package/dist/src/providers/python_poetry.d.ts +98 -0
  65. package/dist/src/providers/python_poetry.js +286 -0
  66. package/dist/src/providers/python_uv.d.ts +46 -0
  67. package/dist/src/providers/python_uv.js +269 -0
  68. package/dist/src/providers/rust_cargo.d.ts +6 -2
  69. package/dist/src/providers/rust_cargo.js +101 -33
  70. package/dist/src/providers/tree-sitter-containerfile.wasm +0 -0
  71. package/dist/src/providers/tree-sitter-gomod.wasm +0 -0
  72. package/dist/src/remediate.d.ts +21 -0
  73. package/dist/src/remediate.js +149 -0
  74. package/dist/src/remediation.d.ts +57 -0
  75. package/dist/src/remediation.js +436 -0
  76. package/dist/src/remediation_report.d.ts +40 -0
  77. package/dist/src/remediation_report.js +159 -0
  78. package/dist/src/sbom.d.ts +25 -1
  79. package/dist/src/sbom.js +23 -2
  80. package/dist/src/tools.d.ts +28 -2
  81. package/dist/src/tools.js +82 -1
  82. package/dist/src/updaters/maven_updater.d.ts +26 -0
  83. package/dist/src/updaters/maven_updater.js +322 -0
  84. package/dist/src/updaters/toml_updater.d.ts +33 -0
  85. package/dist/src/updaters/toml_updater.js +244 -0
  86. package/dist/src/workspace.d.ts +9 -0
  87. package/dist/src/workspace.js +1 -1
  88. package/package.json +34 -26
@@ -1,3 +1,4 @@
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';
@@ -5,7 +6,8 @@ import { EOL } from 'os';
5
6
  import { XMLParser } from 'fast-xml-parser';
6
7
  import { getLicense } from '../license/license_utils.js';
7
8
  import Sbom from '../sbom.js';
8
- import { getCustom } from '../tools.js';
9
+ import { getCustom, invokeCommand } from '../tools.js';
10
+ import { filterManifestPathsByDiscoveryIgnore, resolveWorkspaceDiscoveryIgnore } from '../workspace.js';
9
11
  import Base_java, { ecosystem_maven } from "./base_java.js";
10
12
  /** @typedef {import('../provider').Provider} */
11
13
  /** @typedef {import('../provider').Provided} Provided */
@@ -30,12 +32,12 @@ export default class Java_maven extends Base_java {
30
32
  * Provide content and content type for maven-maven stack analysis.
31
33
  * @param {string} manifest - the manifest path or name
32
34
  * @param {{}} [opts={}] - optional various options to pass along the application
33
- * @returns {Provided}
35
+ * @returns {Promise<Provided>}
34
36
  */
35
- provideStack(manifest, opts = {}) {
37
+ async provideStack(manifest, opts = {}) {
36
38
  return {
37
39
  ecosystem: ecosystem_maven,
38
- content: this.#createSbomStackAnalysis(manifest, opts),
40
+ content: await this.#createSbomStackAnalysis(manifest, opts),
39
41
  contentType: 'application/vnd.cyclonedx+json'
40
42
  };
41
43
  }
@@ -80,10 +82,10 @@ export default class Java_maven extends Base_java {
80
82
  * Create a Dot Graph dependency tree for a manifest path.
81
83
  * @param {string} manifest - path for pom.xml
82
84
  * @param {{}} [opts={}] - optional various options to pass along the application
83
- * @returns {string} the Dot Graph content
85
+ * @returns {Promise<string>} the Dot Graph content
84
86
  * @private
85
87
  */
86
- #createSbomStackAnalysis(manifest, opts = {}) {
88
+ async #createSbomStackAnalysis(manifest, opts = {}) {
87
89
  const manifestDir = path.dirname(manifest);
88
90
  const mvn = this.selectToolBinary(manifest, opts);
89
91
  const mvnArgs = JSON.parse(getCustom('TRUSTIFY_DA_MVN_ARGS', '[]', opts));
@@ -130,20 +132,105 @@ export default class Java_maven extends Base_java {
130
132
  if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
131
133
  console.error("Dependency tree that will be used as input for creating the BOM =>" + EOL + EOL + content.toString());
132
134
  }
133
- let sbom = this.createSbomFileFromTextFormat(content.toString(), ignoredDeps, opts, manifest);
135
+ const depTreeContent = content.toString();
136
+ const hashMap = await this._buildMavenHashMap(depTreeContent, opts);
137
+ let sbom = this.createSbomFileFromTextFormat(depTreeContent, ignoredDeps, opts, manifest, hashMap);
134
138
  // delete temp file and directory
135
139
  fs.rmSync(tmpDir, { recursive: true, force: true });
136
140
  // return dependency graph as string
137
141
  return sbom;
138
142
  }
143
+ /** @type {Object<string, string>} Packaging types that produce .jar files despite non-jar packaging names. */
144
+ static PACKAGING_TO_JAR = { 'bundle': 'jar', 'eclipse-plugin': 'jar' };
139
145
  /**
146
+ * Build a Map of PURL string → CycloneDX hash entries by reading artifact files from the local Maven repository.
147
+ *
148
+ * Both the artifact file path and the hash-map key are derived from the
149
+ * shared {@link Base_java#parseCoordinate} parser: the file path uses the
150
+ * resolved version and raw classifier, while the key uses the same canonical
151
+ * PURL builder as {@link Base_java#parseDep}. This guarantees the key always
152
+ * matches the PURL that {@link Base_java#parseDependencyTree} looks up.
140
153
  *
154
+ * @param {string} depTreeText Raw dependency tree text from mvn dependency:tree
155
+ * @param {{}} [opts={}] Options bag (may contain TRUSTIFY_DA_MVN_REPO)
156
+ * @returns {Promise<Map<string, Array<{alg: string, content: string}>>>}
157
+ */
158
+ async _buildMavenHashMap(depTreeText, opts = {}) {
159
+ const m2Repo = getCustom('TRUSTIFY_DA_MVN_REPO', path.join(os.homedir(), '.m2', 'repository'), opts);
160
+ const hashMap = new Map();
161
+ const lines = depTreeText.split(EOL);
162
+ // Track hash coverage so an incomplete .m2 cache (e.g. ephemeral CI
163
+ // containers or resolve-only phases) surfaces a summary warning instead
164
+ // of silently producing an SBOM with missing hashes.
165
+ let attempted = 0;
166
+ let missed = 0;
167
+ for (const rawLine of lines) {
168
+ const trimmed = rawLine.trim();
169
+ // Strip leading tree-drawing characters (e.g. "\-", "+-", "|") so the
170
+ // parenthesized-line check sees the coordinate itself. Omitted
171
+ // duplicate/conflict lines start with these characters after trim(),
172
+ // then an opening "(" — without stripping, the "(" check never fires.
173
+ const cleaned = trimmed.replace(/^[|+\\\- ]+/, '');
174
+ if (!cleaned || cleaned.startsWith('(')) {
175
+ continue;
176
+ }
177
+ const coord = this.parseCoordinate(rawLine);
178
+ if (!coord.groupId || !coord.artifactId || !coord.packaging) {
179
+ continue;
180
+ }
181
+ if (coord.packaging === 'pom') {
182
+ continue;
183
+ }
184
+ // Key by the exact PURL parseDep() produces, so the lookup in
185
+ // parseDependencyTree (hashMap.get(to.toString())) always hits.
186
+ const purl = this._coordinateToPurl(coord).toString();
187
+ // The same artifact recurs across dependency-tree branches — notably in
188
+ // multi-module reactor builds, where every module re-lists shared deps.
189
+ // The digest is deterministic per PURL, so skip the redundant file read
190
+ // and SHA-256 computation once this PURL is already hashed.
191
+ if (hashMap.has(purl)) {
192
+ continue;
193
+ }
194
+ const ext = Java_maven.PACKAGING_TO_JAR[coord.packaging] || coord.packaging;
195
+ const groupPath = coord.groupId.replaceAll('.', path.sep);
196
+ const fileName = coord.classifier
197
+ ? `${coord.artifactId}-${coord.version}-${coord.classifier}.${ext}`
198
+ : `${coord.artifactId}-${coord.version}.${ext}`;
199
+ const artifactPath = path.join(m2Repo, groupPath, coord.artifactId, coord.version, fileName);
200
+ attempted++;
201
+ try {
202
+ const stream = fs.createReadStream(artifactPath);
203
+ const hash = crypto.createHash('sha256');
204
+ for await (const chunk of stream) {
205
+ hash.update(chunk);
206
+ }
207
+ const digest = hash.digest('hex');
208
+ hashMap.set(purl, [{ alg: 'SHA-256', content: digest }]);
209
+ }
210
+ catch {
211
+ missed++;
212
+ if (process.env['TRUSTIFY_DA_DEBUG'] === 'true') {
213
+ console.error(`Maven hash: artifact not found at ${artifactPath}, omitting hash`);
214
+ }
215
+ }
216
+ }
217
+ // Mirror the pip provider's convention (python_controller.js): surface an
218
+ // unconditional warning when hashes could not be computed, so incomplete
219
+ // hash coverage is visible even without TRUSTIFY_DA_DEBUG.
220
+ if (missed > 0) {
221
+ 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.`);
222
+ }
223
+ return hashMap;
224
+ }
225
+ /**
141
226
  * @param {String} textGraphList Text graph String of the manifest
142
227
  * @param {[String]} ignoredDeps List of ignored dependencies to be omitted from sbom
228
+ * @param {{}} opts Options
143
229
  * @param {String} manifestPath Path to the pom.xml manifest
230
+ * @param {Map<string, Array<{alg: string, content: string}>>} [hashMap] PURL→hashes map
144
231
  * @return {String} formatted sbom Json String with all dependencies
145
232
  */
146
- createSbomFileFromTextFormat(textGraphList, ignoredDeps, opts, manifestPath) {
233
+ createSbomFileFromTextFormat(textGraphList, ignoredDeps, opts, manifestPath, hashMap) {
147
234
  let lines = textGraphList.split(EOL);
148
235
  // get root component
149
236
  let root = lines[0];
@@ -152,6 +239,9 @@ export default class Java_maven extends Base_java {
152
239
  let sbom = new Sbom();
153
240
  sbom.addRoot(rootPurl, license);
154
241
  this.parseDependencyTree(root, 0, lines.slice(1), sbom);
242
+ // Attach Maven artifact hashes as a post-processing step, keeping this
243
+ // Maven-specific concern out of the shared dependency-tree parser.
244
+ sbom.attachHashes(hashMap);
155
245
  return sbom.filterIgnoredDeps(ignoredDeps).getAsJsonString(opts);
156
246
  }
157
247
  /**
@@ -180,6 +270,7 @@ export default class Java_maven extends Base_java {
180
270
  /** @type [Dependency] */
181
271
  let dependencies = this.#getDependencies(tmpEffectivePom)
182
272
  .filter(d => !this.#dependencyIn(d, ignored));
273
+ dependencies = this.#resolveVersionRanges(dependencies, manifestPath, opts);
183
274
  let sbom = new Sbom();
184
275
  let rootDependency = this.#getRootFromPom(tmpEffectivePom, manifestPath);
185
276
  let purlRoot = this.toPurl(rootDependency.groupId, rootDependency.artifactId, rootDependency.version);
@@ -288,4 +379,166 @@ export default class Java_maven extends Base_java {
288
379
  #dependencyIn(dep, deps) {
289
380
  return deps.filter(d => dep.artifactId === d.artifactId && dep.groupId === d.groupId && dep.scope === d.scope).length > 0;
290
381
  }
382
+ /**
383
+ * Returns true if the given version string is a Maven version range
384
+ * (starts with '[' or '(').
385
+ * @param {string} version
386
+ * @returns {boolean}
387
+ * @private
388
+ */
389
+ #isVersionRange(version) {
390
+ return typeof version === 'string' && (version.startsWith('[') || version.startsWith('('));
391
+ }
392
+ /**
393
+ * Resolves Maven version ranges in the given dependency list by running
394
+ * maven-dependency-plugin:tree and reading the concrete versions it selects.
395
+ * If no dependency uses a version range, returns the list unchanged.
396
+ * @param {Dependency[]} dependencies
397
+ * @param {string} manifestPath
398
+ * @param {object} opts
399
+ * @returns {Dependency[]}
400
+ * @private
401
+ */
402
+ #resolveVersionRanges(dependencies, manifestPath, opts = {}) {
403
+ // short-circuit if no dependency has a version range
404
+ if (!dependencies.some(dep => this.#isVersionRange(dep.version))) {
405
+ return dependencies;
406
+ }
407
+ const mvn = this.selectToolBinary(manifestPath, opts);
408
+ const mvnArgs = JSON.parse(getCustom('TRUSTIFY_DA_MVN_ARGS', '[]', opts));
409
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trustify_da_range_'));
410
+ const tmpDepTree = path.join(tmpDir, 'mvn_deptree_ranges.txt');
411
+ try {
412
+ this._invokeCommand(mvn, [
413
+ '-q',
414
+ 'org.apache.maven.plugins:maven-dependency-plugin:3.6.0:tree',
415
+ '-Dscope=compile',
416
+ '-DoutputType=text',
417
+ `-DoutputFile=${tmpDepTree}`,
418
+ ...mvnArgs
419
+ ], { cwd: path.dirname(manifestPath) });
420
+ const content = fs.readFileSync(tmpDepTree);
421
+ const lines = content.toString().split(EOL).filter(l => l.trim() !== '');
422
+ // Build a map of groupId:artifactId -> resolved version from depth-1 entries
423
+ /** @type {Map<string, string>} */
424
+ const resolvedVersions = new Map();
425
+ for (const line of lines) {
426
+ if (this._getDepth(line) === 1) {
427
+ const purl = this.parseDep(line);
428
+ resolvedVersions.set(`${purl.namespace}:${purl.name}`, purl.version);
429
+ }
430
+ }
431
+ // Replace version ranges with resolved concrete versions
432
+ return dependencies.map(dep => {
433
+ if (this.#isVersionRange(dep.version)) {
434
+ const key = `${dep.groupId}:${dep.artifactId}`;
435
+ const resolved = resolvedVersions.get(key);
436
+ if (resolved) {
437
+ return { ...dep, version: resolved };
438
+ }
439
+ }
440
+ return dep;
441
+ });
442
+ }
443
+ catch (error) {
444
+ if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
445
+ console.error("Failed to resolve Maven version ranges: " + error.message);
446
+ }
447
+ return dependencies;
448
+ }
449
+ finally {
450
+ fs.rmSync(tmpDir, { recursive: true, force: true });
451
+ }
452
+ }
453
+ }
454
+ const DEFAULT_MAVEN_DISCOVERY_IGNORE = [
455
+ '**/target/**',
456
+ ];
457
+ /**
458
+ * Discover all pom.xml manifest paths in a Maven multi-module project.
459
+ *
460
+ * @param {string} workspaceRoot - Absolute or relative path to workspace root (must contain pom.xml)
461
+ * @param {object} [opts={}]
462
+ * @returns {Promise<string[]>} Paths to pom.xml files (absolute)
463
+ */
464
+ export async function discoverMavenModules(workspaceRoot, opts = {}) {
465
+ const root = path.resolve(workspaceRoot);
466
+ const rootPom = path.join(root, 'pom.xml');
467
+ if (!fs.existsSync(rootPom)) {
468
+ return [];
469
+ }
470
+ let mvnBin;
471
+ try {
472
+ mvnBin = new Java_maven().selectToolBinary(rootPom, opts);
473
+ }
474
+ catch {
475
+ return [rootPom];
476
+ }
477
+ const visited = new Set();
478
+ const manifestPaths = [rootPom];
479
+ collectMavenModules(root, mvnBin, visited, manifestPaths);
480
+ const ignorePatterns = [...resolveWorkspaceDiscoveryIgnore(opts), ...DEFAULT_MAVEN_DISCOVERY_IGNORE];
481
+ return filterManifestPathsByDiscoveryIgnore(manifestPaths, root, ignorePatterns);
482
+ }
483
+ /**
484
+ * @param {string} dir - Absolute path to directory containing pom.xml
485
+ * @param {string} mvnBin - Maven binary path
486
+ * @param {Set<string>} visited - Already-visited directories (cycle guard)
487
+ * @param {string[]} manifestPaths - Accumulator for discovered pom.xml paths
488
+ */
489
+ function collectMavenModules(dir, mvnBin, visited, manifestPaths) {
490
+ const resolvedDir = path.resolve(dir);
491
+ if (visited.has(resolvedDir)) {
492
+ return;
493
+ }
494
+ visited.add(resolvedDir);
495
+ const modules = listMavenModules(resolvedDir, mvnBin);
496
+ for (const mod of modules) {
497
+ const moduleDir = path.resolve(resolvedDir, mod);
498
+ const modulePom = path.join(moduleDir, 'pom.xml');
499
+ if (fs.existsSync(modulePom)) {
500
+ manifestPaths.push(modulePom);
501
+ collectMavenModules(moduleDir, mvnBin, visited, manifestPaths);
502
+ }
503
+ }
504
+ }
505
+ /**
506
+ * @param {string} dir - Directory containing pom.xml
507
+ * @param {string} mvnBin - Maven binary path
508
+ * @returns {string[]} Module directory names (relative to `dir`)
509
+ */
510
+ function listMavenModules(dir, mvnBin) {
511
+ let output;
512
+ try {
513
+ output = invokeCommand(mvnBin, [
514
+ 'help:evaluate',
515
+ '-Dexpression=project.modules',
516
+ '-q',
517
+ '-DforceStdout',
518
+ '-f', path.join(dir, 'pom.xml'),
519
+ '--batch-mode',
520
+ ], { cwd: dir });
521
+ }
522
+ catch {
523
+ return [];
524
+ }
525
+ const raw = output.toString().trim();
526
+ if (!raw || raw.startsWith('<modules')) {
527
+ return [];
528
+ }
529
+ return parseMavenModuleList(raw);
530
+ }
531
+ /**
532
+ * @param {string} raw - Raw stdout from mvn help:evaluate -DforceStdout
533
+ * @returns {string[]}
534
+ */
535
+ function parseMavenModuleList(raw) {
536
+ const parser = new XMLParser();
537
+ const parsed = parser.parse(raw);
538
+ const entries = parsed?.strings?.string;
539
+ if (!entries) {
540
+ return [];
541
+ }
542
+ const list = Array.isArray(entries) ? entries : [entries];
543
+ return list.map(s => String(s).trim()).filter(Boolean);
291
544
  }
@@ -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
  }
@@ -1,4 +1,17 @@
1
1
  export default class Javascript_pnpm extends Base_javascript {
2
+ /**
3
+ * Parses `pnpm-lock.yaml` (lockfileVersion 9) into a hash map keyed by
4
+ * `name@version`. Entries in the `packages` section are keyed by
5
+ * `<name>@<version>` (optionally followed by a `(peer@x)` suffix); the
6
+ * `resolution.integrity` field holds an SRI string.
7
+ * @param {string} lockDir - Directory containing pnpm-lock.yaml
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[];
3
16
  _buildDependencyTree(includeTransitive: any, opts?: {}): any;
4
17
  }