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

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 (52) hide show
  1. package/README.md +73 -8
  2. package/dist/package.json +6 -5
  3. package/dist/src/analysis.js +3 -2
  4. package/dist/src/cli.js +51 -2
  5. package/dist/src/cyclone_dx_sbom.d.ts +14 -1
  6. package/dist/src/cyclone_dx_sbom.js +32 -5
  7. package/dist/src/index.d.ts +74 -3
  8. package/dist/src/index.js +89 -6
  9. package/dist/src/oci_image/utils.js +11 -2
  10. package/dist/src/provider.js +8 -0
  11. package/dist/src/providers/base_java.d.ts +0 -9
  12. package/dist/src/providers/base_java.js +2 -38
  13. package/dist/src/providers/base_javascript.d.ts +6 -0
  14. package/dist/src/providers/base_javascript.js +37 -6
  15. package/dist/src/providers/base_pyproject.d.ts +153 -0
  16. package/dist/src/providers/base_pyproject.js +315 -0
  17. package/dist/src/providers/golang_gomodules.d.ts +21 -12
  18. package/dist/src/providers/golang_gomodules.js +164 -118
  19. package/dist/src/providers/gomod_parser.d.ts +4 -0
  20. package/dist/src/providers/gomod_parser.js +16 -0
  21. package/dist/src/providers/java_gradle.d.ts +19 -0
  22. package/dist/src/providers/java_gradle.js +116 -2
  23. package/dist/src/providers/java_maven.d.ts +8 -0
  24. package/dist/src/providers/java_maven.js +93 -1
  25. package/dist/src/providers/javascript_bun.d.ts +10 -0
  26. package/dist/src/providers/javascript_bun.js +100 -0
  27. package/dist/src/providers/javascript_npm.d.ts +1 -0
  28. package/dist/src/providers/javascript_npm.js +21 -0
  29. package/dist/src/providers/javascript_pnpm.js +6 -2
  30. package/dist/src/providers/manifest.d.ts +2 -0
  31. package/dist/src/providers/manifest.js +22 -4
  32. package/dist/src/providers/marker_evaluator.d.ts +14 -0
  33. package/dist/src/providers/marker_evaluator.js +191 -0
  34. package/dist/src/providers/processors/yarn_berry_processor.js +88 -5
  35. package/dist/src/providers/python_controller.d.ts +5 -1
  36. package/dist/src/providers/python_controller.js +8 -4
  37. package/dist/src/providers/python_pip.d.ts +4 -0
  38. package/dist/src/providers/python_pip.js +5 -5
  39. package/dist/src/providers/python_pip_pyproject.d.ts +61 -0
  40. package/dist/src/providers/python_pip_pyproject.js +146 -0
  41. package/dist/src/providers/python_poetry.d.ts +75 -0
  42. package/dist/src/providers/python_poetry.js +238 -0
  43. package/dist/src/providers/python_uv.d.ts +55 -0
  44. package/dist/src/providers/python_uv.js +227 -0
  45. package/dist/src/providers/tree-sitter-gomod.wasm +0 -0
  46. package/dist/src/sbom.d.ts +14 -1
  47. package/dist/src/sbom.js +13 -2
  48. package/dist/src/tools.d.ts +26 -0
  49. package/dist/src/tools.js +58 -0
  50. package/dist/src/workspace.d.ts +9 -0
  51. package/dist/src/workspace.js +1 -1
  52. package/package.json +7 -6
@@ -5,7 +5,8 @@ import { EOL } from 'os';
5
5
  import { XMLParser } from 'fast-xml-parser';
6
6
  import { getLicense } from '../license/license_utils.js';
7
7
  import Sbom from '../sbom.js';
8
- import { getCustom } from '../tools.js';
8
+ import { getCustom, invokeCommand } from '../tools.js';
9
+ import { filterManifestPathsByDiscoveryIgnore, resolveWorkspaceDiscoveryIgnore } from '../workspace.js';
9
10
  import Base_java, { ecosystem_maven } from "./base_java.js";
10
11
  /** @typedef {import('../provider').Provider} */
11
12
  /** @typedef {import('../provider').Provided} Provided */
@@ -289,3 +290,94 @@ export default class Java_maven extends Base_java {
289
290
  return deps.filter(d => dep.artifactId === d.artifactId && dep.groupId === d.groupId && dep.scope === d.scope).length > 0;
290
291
  }
291
292
  }
293
+ const DEFAULT_MAVEN_DISCOVERY_IGNORE = [
294
+ '**/target/**',
295
+ ];
296
+ /**
297
+ * Discover all pom.xml manifest paths in a Maven multi-module project.
298
+ *
299
+ * @param {string} workspaceRoot - Absolute or relative path to workspace root (must contain pom.xml)
300
+ * @param {object} [opts={}]
301
+ * @returns {Promise<string[]>} Paths to pom.xml files (absolute)
302
+ */
303
+ export async function discoverMavenModules(workspaceRoot, opts = {}) {
304
+ const root = path.resolve(workspaceRoot);
305
+ const rootPom = path.join(root, 'pom.xml');
306
+ if (!fs.existsSync(rootPom)) {
307
+ return [];
308
+ }
309
+ let mvnBin;
310
+ try {
311
+ mvnBin = new Java_maven().selectToolBinary(rootPom, opts);
312
+ }
313
+ catch {
314
+ return [rootPom];
315
+ }
316
+ const visited = new Set();
317
+ const manifestPaths = [rootPom];
318
+ collectMavenModules(root, mvnBin, visited, manifestPaths);
319
+ const ignorePatterns = [...resolveWorkspaceDiscoveryIgnore(opts), ...DEFAULT_MAVEN_DISCOVERY_IGNORE];
320
+ return filterManifestPathsByDiscoveryIgnore(manifestPaths, root, ignorePatterns);
321
+ }
322
+ /**
323
+ * @param {string} dir - Absolute path to directory containing pom.xml
324
+ * @param {string} mvnBin - Maven binary path
325
+ * @param {Set<string>} visited - Already-visited directories (cycle guard)
326
+ * @param {string[]} manifestPaths - Accumulator for discovered pom.xml paths
327
+ */
328
+ function collectMavenModules(dir, mvnBin, visited, manifestPaths) {
329
+ const resolvedDir = path.resolve(dir);
330
+ if (visited.has(resolvedDir)) {
331
+ return;
332
+ }
333
+ visited.add(resolvedDir);
334
+ const modules = listMavenModules(resolvedDir, mvnBin);
335
+ for (const mod of modules) {
336
+ const moduleDir = path.resolve(resolvedDir, mod);
337
+ const modulePom = path.join(moduleDir, 'pom.xml');
338
+ if (fs.existsSync(modulePom)) {
339
+ manifestPaths.push(modulePom);
340
+ collectMavenModules(moduleDir, mvnBin, visited, manifestPaths);
341
+ }
342
+ }
343
+ }
344
+ /**
345
+ * @param {string} dir - Directory containing pom.xml
346
+ * @param {string} mvnBin - Maven binary path
347
+ * @returns {string[]} Module directory names (relative to `dir`)
348
+ */
349
+ function listMavenModules(dir, mvnBin) {
350
+ let output;
351
+ try {
352
+ output = invokeCommand(mvnBin, [
353
+ 'help:evaluate',
354
+ '-Dexpression=project.modules',
355
+ '-q',
356
+ '-DforceStdout',
357
+ '-f', path.join(dir, 'pom.xml'),
358
+ '--batch-mode',
359
+ ], { cwd: dir });
360
+ }
361
+ catch {
362
+ return [];
363
+ }
364
+ const raw = output.toString().trim();
365
+ if (!raw || raw.startsWith('<modules')) {
366
+ return [];
367
+ }
368
+ return parseMavenModuleList(raw);
369
+ }
370
+ /**
371
+ * @param {string} raw - Raw stdout from mvn help:evaluate -DforceStdout
372
+ * @returns {string[]}
373
+ */
374
+ function parseMavenModuleList(raw) {
375
+ const parser = new XMLParser();
376
+ const parsed = parser.parse(raw);
377
+ const entries = parsed?.strings?.string;
378
+ if (!entries) {
379
+ return [];
380
+ }
381
+ const list = Array.isArray(entries) ? entries : [entries];
382
+ return list.map(s => String(s).trim()).filter(Boolean);
383
+ }
@@ -0,0 +1,10 @@
1
+ export default class Javascript_bun extends Base_javascript {
2
+ _listCmdArgs(): void;
3
+ _buildDependencyTree(includeTransitive: any, opts?: {}): {
4
+ name: any;
5
+ version: any;
6
+ dependencies: {};
7
+ };
8
+ #private;
9
+ }
10
+ import Base_javascript from './base_javascript.js';
@@ -0,0 +1,100 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parse } from 'jsonc-parser';
4
+ import Base_javascript from './base_javascript.js';
5
+ export default class Javascript_bun extends Base_javascript {
6
+ _lockFileName() {
7
+ return "bun.lock";
8
+ }
9
+ _cmdName() {
10
+ return "bun";
11
+ }
12
+ _listCmdArgs() {
13
+ throw new Error("not supported by Bun");
14
+ }
15
+ _updateLockFileCmdArgs() {
16
+ return ['install', '--lockfile-only'];
17
+ }
18
+ _buildDependencyTree(includeTransitive, opts = {}) {
19
+ this._version();
20
+ const manifestDir = path.dirname(this._getManifest().manifestPath);
21
+ const lockDir = this._findLockFileDir(manifestDir, opts) || manifestDir;
22
+ this._createLockFile(lockDir);
23
+ const lockContent = fs.readFileSync(path.join(lockDir, 'bun.lock'), 'utf-8');
24
+ const lockData = parse(lockContent);
25
+ const packages = lockData.packages || {};
26
+ const memberName = this._getManifest().name;
27
+ const workspaceEntry = this.#findWorkspaceEntry(lockData, lockDir, manifestDir, memberName);
28
+ const directDeps = workspaceEntry?.dependencies || {};
29
+ const tree = { name: memberName, version: this._getManifest().version, dependencies: {} };
30
+ const visited = new Set();
31
+ for (const depName of Object.keys(directDeps)) {
32
+ const resolved = this.#resolvePackage(depName, '', packages);
33
+ if (resolved) {
34
+ tree.dependencies[depName] = this.#buildNode(depName, resolved, packages, includeTransitive, visited);
35
+ }
36
+ }
37
+ return tree;
38
+ }
39
+ #findWorkspaceEntry(lockData, lockDir, manifestDir, memberName) {
40
+ const workspaces = lockData.workspaces || {};
41
+ const relPath = path.relative(lockDir, path.resolve(manifestDir));
42
+ if (!relPath || relPath === '.') {
43
+ return workspaces[''] || {};
44
+ }
45
+ const normalised = relPath.split(path.sep).join('/');
46
+ if (workspaces[normalised]) {
47
+ return workspaces[normalised];
48
+ }
49
+ for (const [wsPath, entry] of Object.entries(workspaces)) {
50
+ if (entry.name === memberName && wsPath !== '') {
51
+ return entry;
52
+ }
53
+ }
54
+ return workspaces[''] || {};
55
+ }
56
+ #resolvePackage(depName, parentKey, packages) {
57
+ if (parentKey) {
58
+ const scopedKey = `${parentKey}/${depName}`;
59
+ if (packages[scopedKey]) {
60
+ return packages[scopedKey];
61
+ }
62
+ }
63
+ return packages[depName] || null;
64
+ }
65
+ #buildNode(depName, resolved, packages, includeTransitive, visited) {
66
+ const resolvedId = Array.isArray(resolved) ? resolved[0] : resolved;
67
+ const version = this.#extractVersion(resolvedId);
68
+ const node = { version };
69
+ if (!includeTransitive) {
70
+ return node;
71
+ }
72
+ const metadata = Array.isArray(resolved) ? (resolved[2] || {}) : {};
73
+ const subDeps = metadata.dependencies || {};
74
+ if (Object.keys(subDeps).length > 0) {
75
+ const visitKey = `${depName}@${version}`;
76
+ if (visited.has(visitKey)) {
77
+ return node;
78
+ }
79
+ visited.add(visitKey);
80
+ node.dependencies = {};
81
+ for (const subName of Object.keys(subDeps)) {
82
+ const subResolved = this.#resolvePackage(subName, depName, packages);
83
+ if (subResolved) {
84
+ node.dependencies[subName] = this.#buildNode(subName, subResolved, packages, true, visited);
85
+ }
86
+ }
87
+ }
88
+ return node;
89
+ }
90
+ #extractVersion(resolvedId) {
91
+ if (typeof resolvedId !== 'string') {
92
+ return '0.0.0';
93
+ }
94
+ const atIdx = resolvedId.lastIndexOf('@');
95
+ if (atIdx > 0) {
96
+ return resolvedId.substring(atIdx + 1);
97
+ }
98
+ return '0.0.0';
99
+ }
100
+ }
@@ -1,4 +1,5 @@
1
1
  export default class Javascript_npm extends Base_javascript {
2
2
  _listCmdArgs(includeTransitive: any): string[];
3
+ _buildDependencyTree(includeTransitive: any, opts?: {}): any;
3
4
  }
4
5
  import Base_javascript from './base_javascript.js';
@@ -12,4 +12,25 @@ export default class Javascript_npm extends Base_javascript {
12
12
  _updateLockFileCmdArgs() {
13
13
  return ['install', '--package-lock-only'];
14
14
  }
15
+ _buildDependencyTree(includeTransitive, opts = {}) {
16
+ // npm ls --json returns a single tree rooted at the workspace root.
17
+ // When analyzing a workspace member, its deps are nested under the
18
+ // root's dependencies keyed by the member name — extract that subtree
19
+ // so downstream analysis sees only the member's dependencies.
20
+ const tree = super._buildDependencyTree(includeTransitive, opts);
21
+ const memberName = this._getManifest().name;
22
+ if (tree.name === memberName) {
23
+ return tree;
24
+ }
25
+ const memberEntry = tree.dependencies?.[memberName];
26
+ if (memberEntry) {
27
+ return {
28
+ name: memberName,
29
+ version: memberEntry.version || this._getManifest().version,
30
+ dependencies: memberEntry.dependencies,
31
+ optionalDependencies: memberEntry.optionalDependencies,
32
+ };
33
+ }
34
+ return tree;
35
+ }
15
36
  }
@@ -7,15 +7,19 @@ export default class Javascript_pnpm extends Base_javascript {
7
7
  return "pnpm";
8
8
  }
9
9
  _listCmdArgs(includeTransitive) {
10
- return ['ls', includeTransitive ? '--depth=Infinity' : '--depth=0', '--prod', '--json'];
10
+ return ['ls', includeTransitive ? '--depth=Infinity' : '--depth=0', '--prod', '--json', '-r'];
11
11
  }
12
12
  _updateLockFileCmdArgs() {
13
13
  return ['install', '--frozen-lockfile'];
14
14
  }
15
15
  _buildDependencyTree(includeTransitive, opts = {}) {
16
+ // pnpm ls --json returns an array with one entry per workspace package.
17
+ // When analyzing a workspace member, find its entry by name instead of
18
+ // blindly taking the first element (which is the workspace root).
16
19
  const tree = super._buildDependencyTree(includeTransitive, opts);
17
20
  if (Array.isArray(tree) && tree.length > 0) {
18
- return tree[0];
21
+ const memberName = this._getManifest().name;
22
+ return tree.find(pkg => pkg.name === memberName) || tree[0];
19
23
  }
20
24
  return {};
21
25
  }
@@ -2,6 +2,8 @@ export default class Manifest {
2
2
  constructor(manifestPath: any);
3
3
  manifestPath: any;
4
4
  dependencies: any[];
5
+ peerDependencies: any;
6
+ optionalDependencies: any;
5
7
  name: any;
6
8
  version: any;
7
9
  ignored: any[];
@@ -9,6 +9,8 @@ export default class Manifest {
9
9
  this.manifestPath = manifestPath;
10
10
  const content = this.loadManifest();
11
11
  this.dependencies = this.loadDependencies(content);
12
+ this.peerDependencies = content.peerDependencies || {};
13
+ this.optionalDependencies = content.optionalDependencies || {};
12
14
  this.name = content.name;
13
15
  this.version = content.version || DEFAULT_VERSION;
14
16
  this.ignored = this.loadIgnored(content);
@@ -27,11 +29,27 @@ export default class Manifest {
27
29
  }
28
30
  loadDependencies(content) {
29
31
  let deps = [];
30
- if (!content.dependencies) {
31
- return deps;
32
+ const depSources = [
33
+ content.dependencies,
34
+ content.peerDependencies,
35
+ content.optionalDependencies,
36
+ ];
37
+ for (const source of depSources) {
38
+ if (source) {
39
+ for (let dep in source) {
40
+ if (!deps.includes(dep)) {
41
+ deps.push(dep);
42
+ }
43
+ }
44
+ }
32
45
  }
33
- for (let dep in content.dependencies) {
34
- deps.push(dep);
46
+ // bundledDependencies is an array of package names (subset of dependencies)
47
+ if (Array.isArray(content.bundledDependencies)) {
48
+ for (const dep of content.bundledDependencies) {
49
+ if (!deps.includes(dep)) {
50
+ deps.push(dep);
51
+ }
52
+ }
35
53
  }
36
54
  return deps;
37
55
  }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Maps Node.js/OS values to PEP 508 marker variables.
3
+ * Example: on Linux, sys_platform='linux', platform_system='Linux', os_name='posix'
4
+ * @returns {Record<string, string>}
5
+ */
6
+ export function getEnvironmentMarkers(): Record<string, string>;
7
+ /**
8
+ * Evaluates a full PEP 508 marker expression against the current platform.
9
+ * Example: "sys_platform == 'win32' and python_version >= '3.8'" → false on Linux
10
+ * Empty/missing markers return true (unconditional dependency).
11
+ * @param {string} markerExpr
12
+ * @returns {boolean}
13
+ */
14
+ export function evaluateMarker(markerExpr: string): boolean;
@@ -0,0 +1,191 @@
1
+ // PEP 508 environment marker evaluator.
2
+ // Filters Python dependencies by platform/version markers so that e.g.
3
+ // "pywin32 ; sys_platform == 'win32'" is excluded on Linux/macOS.
4
+ // See https://peps.python.org/pep-0508/#environment-markers
5
+ import os from 'node:os';
6
+ import { getCustomPath, invokeCommand } from '../tools.js';
7
+ let cachedPythonVersions = undefined;
8
+ function getPythonVersions() {
9
+ if (cachedPythonVersions !== undefined) {
10
+ return cachedPythonVersions;
11
+ }
12
+ try {
13
+ let python = getCustomPath('python3');
14
+ let out = invokeCommand(python, ['-c', "import sys; v=sys.version_info; print(f'{v.major}.{v.minor} {v.major}.{v.minor}.{v.micro}')"], { timeout: 5000 }).toString().trim();
15
+ let [short, full] = out.split(' ');
16
+ cachedPythonVersions = { short, full };
17
+ }
18
+ catch {
19
+ cachedPythonVersions = null;
20
+ }
21
+ return cachedPythonVersions;
22
+ }
23
+ /**
24
+ * Maps Node.js/OS values to PEP 508 marker variables.
25
+ * Example: on Linux, sys_platform='linux', platform_system='Linux', os_name='posix'
26
+ * @returns {Record<string, string>}
27
+ */
28
+ export function getEnvironmentMarkers() {
29
+ let platform = process.platform;
30
+ let systemMap = { win32: 'Windows', linux: 'Linux', darwin: 'Darwin' };
31
+ let machine = typeof os.machine === 'function' ? os.machine() : process.arch;
32
+ let pyVer = getPythonVersions();
33
+ return {
34
+ sys_platform: platform,
35
+ platform_system: systemMap[platform] || platform,
36
+ os_name: platform === 'win32' ? 'nt' : 'posix',
37
+ platform_machine: machine,
38
+ platform_release: os.release(),
39
+ platform_version: os.version?.() || '',
40
+ python_version: pyVer?.short || '',
41
+ python_full_version: pyVer?.full || '',
42
+ implementation_name: 'cpython',
43
+ };
44
+ }
45
+ function compareVersions(left, right) {
46
+ let lParts = left.split('.').map(Number);
47
+ let rParts = right.split('.').map(Number);
48
+ let len = Math.max(lParts.length, rParts.length);
49
+ for (let i = 0; i < len; i++) {
50
+ let l = lParts[i] || 0;
51
+ let r = rParts[i] || 0;
52
+ if (l < r) {
53
+ return -1;
54
+ }
55
+ if (l > r) {
56
+ return 1;
57
+ }
58
+ }
59
+ return 0;
60
+ }
61
+ // Evaluates a single comparison like sys_platform == 'win32' or python_version >= '3.8'.
62
+ // Version-bearing variables (python_version, python_full_version) use numeric comparison;
63
+ // all others use string equality. Returns false when the env value is missing.
64
+ function evaluateComparison(variable, op, value, env) {
65
+ let envVal = env[variable];
66
+ if (envVal === undefined || envVal === '') {
67
+ return false;
68
+ }
69
+ let isVersion = variable.includes('version');
70
+ if (isVersion) {
71
+ let cmp = compareVersions(envVal, value);
72
+ switch (op) {
73
+ case '==': return cmp === 0;
74
+ case '!=': return cmp !== 0;
75
+ case '>=': return cmp >= 0;
76
+ case '<=': return cmp <= 0;
77
+ case '>': return cmp > 0;
78
+ case '<': return cmp < 0;
79
+ case '~=': {
80
+ let parts = value.split('.');
81
+ parts.pop();
82
+ let prefix = parts.join('.');
83
+ return envVal.startsWith(prefix) && cmp >= 0;
84
+ }
85
+ default: return true;
86
+ }
87
+ }
88
+ switch (op) {
89
+ case '==': return envVal === value;
90
+ case '!=': return envVal !== value;
91
+ case 'in': return value.includes(envVal);
92
+ case 'not in': return !value.includes(envVal);
93
+ default: return envVal === value;
94
+ }
95
+ }
96
+ // Parses a single marker comparison into {variable, op, value}.
97
+ // Handles both normal and reversed forms:
98
+ // "sys_platform == 'linux'" → { variable: 'sys_platform', op: '==', value: 'linux' }
99
+ // "'linux' == sys_platform" → { variable: 'sys_platform', op: '==', value: 'linux' }
100
+ function parseAtom(expr) {
101
+ // Normal form: variable op 'value'
102
+ let m = expr.match(/^\s*([\w.]+)\s*(~=|!=|==|>=|<=|>|<|not\s+in|in)\s*["']([^"']*)["']\s*$/);
103
+ if (m) {
104
+ return { variable: m[1], op: m[2].replace(/\s+/g, ' '), value: m[3] };
105
+ }
106
+ // Reversed form: 'value' op variable — reverse directional operators
107
+ let mReverse = expr.match(/^\s*["']([^"']*)['"]\s*(~=|!=|==|>=|<=|>|<|not\s+in|in)\s*([\w.]+)\s*$/);
108
+ if (mReverse) {
109
+ let reverseOp = { '<': '>', '>': '<', '<=': '>=', '>=': '<=' };
110
+ let op = mReverse[2].replace(/\s+/g, ' ');
111
+ return { variable: mReverse[3], op: reverseOp[op] || op, value: mReverse[1] };
112
+ }
113
+ return null;
114
+ }
115
+ /**
116
+ * Evaluates a full PEP 508 marker expression against the current platform.
117
+ * Example: "sys_platform == 'win32' and python_version >= '3.8'" → false on Linux
118
+ * Empty/missing markers return true (unconditional dependency).
119
+ * @param {string} markerExpr
120
+ * @returns {boolean}
121
+ */
122
+ export function evaluateMarker(markerExpr) {
123
+ if (!markerExpr || !markerExpr.trim()) {
124
+ return true;
125
+ }
126
+ let env = getEnvironmentMarkers();
127
+ return evaluateExpr(markerExpr.trim(), env);
128
+ }
129
+ function evaluateExpr(expr, env) {
130
+ let orParts = splitLogical(expr, ' or ');
131
+ if (orParts.length > 1) {
132
+ return orParts.some(part => evaluateExpr(part, env));
133
+ }
134
+ let andParts = splitLogical(expr, ' and ');
135
+ if (andParts.length > 1) {
136
+ return andParts.every(part => evaluateExpr(part, env));
137
+ }
138
+ let trimmed = expr.trim();
139
+ if (trimmed.startsWith('(') && trimmed.endsWith(')')) {
140
+ return evaluateExpr(trimmed.slice(1, -1), env);
141
+ }
142
+ let atom = parseAtom(trimmed);
143
+ if (!atom) {
144
+ return true;
145
+ }
146
+ return evaluateComparison(atom.variable, atom.op, atom.value, env);
147
+ }
148
+ // Splits an expression by " and " or " or " at the top level, skipping
149
+ // separators inside parentheses or quoted strings.
150
+ // Example: splitLogical("a == 'x' and (b == 'y' or c == 'z')", " and ")
151
+ // → ["a == 'x'", "(b == 'y' or c == 'z')"]
152
+ function splitLogical(expr, sep) {
153
+ let parts = [];
154
+ let depth = 0;
155
+ let current = '';
156
+ let i = 0;
157
+ let quoteChar = null;
158
+ while (i < expr.length) {
159
+ let ch = expr[i];
160
+ if (quoteChar) {
161
+ if (ch === quoteChar) {
162
+ quoteChar = null;
163
+ }
164
+ current += ch;
165
+ i++;
166
+ continue;
167
+ }
168
+ if (ch === '"' || ch === "'") {
169
+ quoteChar = ch;
170
+ current += ch;
171
+ i++;
172
+ continue;
173
+ }
174
+ if (ch === '(') {
175
+ depth++;
176
+ }
177
+ if (ch === ')') {
178
+ depth--;
179
+ }
180
+ if (depth === 0 && expr.substring(i, i + sep.length) === sep) {
181
+ parts.push(current);
182
+ current = '';
183
+ i += sep.length;
184
+ continue;
185
+ }
186
+ current += ch;
187
+ i++;
188
+ }
189
+ parts.push(current);
190
+ return parts.filter(p => p.trim());
191
+ }
@@ -15,7 +15,10 @@ export default class Yarn_berry_processor extends Yarn_processor {
15
15
  * @returns {string[]} Command arguments for listing dependencies
16
16
  */
17
17
  listCmdArgs(includeTransitive) {
18
- return ['info', includeTransitive ? '--recursive' : '--all', '--json'];
18
+ // --all is needed to include workspace members in the output
19
+ return includeTransitive
20
+ ? ['info', '--recursive', '--all', '--json']
21
+ : ['info', '--all', '--json'];
19
22
  }
20
23
  /**
21
24
  * Returns the command arguments for updating the lock file
@@ -48,13 +51,15 @@ export default class Yarn_berry_processor extends Yarn_processor {
48
51
  if (!depTree) {
49
52
  return new Map();
50
53
  }
51
- return new Map(depTree.filter(dep => !this.#isRoot(dep.value)).map(dep => {
54
+ return new Map(depTree.filter(dep => !this.#isRoot(dep.value))
55
+ .map(dep => {
52
56
  const depName = dep.value;
53
57
  const idx = depName.lastIndexOf('@');
54
58
  const name = depName.substring(0, idx);
55
59
  const version = dep.children.Version;
56
60
  return [name, toPurl(purlType, name, version)];
57
- }));
61
+ })
62
+ .filter(([name]) => this._manifest.dependencies.includes(name)));
58
63
  }
59
64
  /**
60
65
  * Checks if a dependency is the root package
@@ -66,7 +71,8 @@ export default class Yarn_berry_processor extends Yarn_processor {
66
71
  if (!name) {
67
72
  return false;
68
73
  }
69
- return name.endsWith("@workspace:.");
74
+ // Workspace members use paths like "member-a@workspace:packages/member-a", not just "@workspace:."
75
+ return name.startsWith(`${this._manifest.name}@workspace:`);
70
76
  }
71
77
  /**
72
78
  * Adds dependencies to the SBOM
@@ -77,14 +83,58 @@ export default class Yarn_berry_processor extends Yarn_processor {
77
83
  if (!depTree) {
78
84
  return;
79
85
  }
86
+ // Build index of nodes by their value for quick lookup
87
+ const nodeIndex = new Map();
88
+ depTree.forEach(n => nodeIndex.set(n.value, n));
89
+ // Determine the set of node values reachable from root via production deps
90
+ const prodDeps = new Set(this._manifest.dependencies);
91
+ const reachable = new Set();
92
+ const queue = [];
93
+ // Seed with root's production dependencies
94
+ const rootNode = depTree.find(n => this.#isRoot(n.value));
95
+ if (rootNode?.children?.Dependencies) {
96
+ for (const d of rootNode.children.Dependencies) {
97
+ const to = this.#purlFromLocator(d.locator);
98
+ if (to) {
99
+ const fullName = to.namespace ? `${to.namespace}/${to.name}` : to.name;
100
+ if (prodDeps.has(fullName)) {
101
+ queue.push(d.locator);
102
+ }
103
+ }
104
+ }
105
+ }
106
+ // BFS to find all transitively reachable packages
107
+ while (queue.length > 0) {
108
+ const locator = queue.shift();
109
+ if (reachable.has(locator)) {
110
+ continue;
111
+ }
112
+ reachable.add(locator);
113
+ const node = nodeIndex.get(this.#nodeValueFromLocator(locator));
114
+ if (node?.children?.Dependencies) {
115
+ for (const d of node.children.Dependencies) {
116
+ if (!reachable.has(d.locator)) {
117
+ queue.push(d.locator);
118
+ }
119
+ }
120
+ }
121
+ }
122
+ // Only emit edges for root and reachable nodes
80
123
  depTree.forEach(n => {
81
124
  const depName = n.value;
82
- const from = this.#isRoot(depName) ? toPurlFromString(sbom.getRoot().purl) : this.#purlFromNode(depName, n);
125
+ const isRoot = this.#isRoot(depName);
126
+ if (!isRoot && !this.#isReachableNode(depName, reachable)) {
127
+ return;
128
+ }
129
+ const from = isRoot ? toPurlFromString(sbom.getRoot().purl) : this.#purlFromNode(depName, n);
83
130
  const deps = n.children?.Dependencies;
84
131
  if (!deps) {
85
132
  return;
86
133
  }
87
134
  deps.forEach(d => {
135
+ if (!reachable.has(d.locator)) {
136
+ return;
137
+ }
88
138
  const to = this.#purlFromLocator(d.locator);
89
139
  if (to) {
90
140
  sbom.addDependency(from, to);
@@ -92,6 +142,39 @@ export default class Yarn_berry_processor extends Yarn_processor {
92
142
  });
93
143
  });
94
144
  }
145
+ /**
146
+ * Converts a locator to the node value format used in yarn info output
147
+ * @param {string} locator - e.g. "express@npm:4.17.1"
148
+ * @returns {string} The node value, same as locator for non-virtual
149
+ * @private
150
+ */
151
+ #nodeValueFromLocator(locator) {
152
+ // Virtual locators: "@scope/name@virtual:hash#npm:version" → "@scope/name@npm:version"
153
+ const virtualMatch = Yarn_berry_processor.VIRTUAL_LOCATOR_PATTERN.exec(locator);
154
+ if (virtualMatch) {
155
+ return `${virtualMatch[1]}@npm:${virtualMatch[2]}`;
156
+ }
157
+ return locator;
158
+ }
159
+ /**
160
+ * Checks if a node is in the reachable set by matching its value against reachable locators
161
+ * @param {string} depName - The node value (e.g. "express@npm:4.17.1")
162
+ * @param {Set<string>} reachable - Set of reachable locators
163
+ * @returns {boolean}
164
+ * @private
165
+ */
166
+ #isReachableNode(depName, reachable) {
167
+ if (reachable.has(depName)) {
168
+ return true;
169
+ }
170
+ // Check if any reachable locator resolves to this node value
171
+ for (const locator of reachable) {
172
+ if (this.#nodeValueFromLocator(locator) === depName) {
173
+ return true;
174
+ }
175
+ }
176
+ return false;
177
+ }
95
178
  /**
96
179
  * Creates a PackageURL from a dependency locator
97
180
  * @param {string} locator - The dependency locator