cve-lite-cli 1.33.0 → 1.35.0

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 (53) hide show
  1. package/README.md +6 -3
  2. package/dist/advisory/local-db.js +31 -2
  3. package/dist/advisory/osv-advisory-source.js +3 -0
  4. package/dist/cli/advisories-init.js +13 -0
  5. package/dist/cli/advisories-sync.js +30 -0
  6. package/dist/cli/args.js +41 -2
  7. package/dist/cli/config-command.js +15 -0
  8. package/dist/cli/config.js +29 -0
  9. package/dist/cli/help.js +7 -5
  10. package/dist/cli/overrides.js +10 -1
  11. package/dist/cli/validate.js +6 -2
  12. package/dist/constants.js +52 -0
  13. package/dist/index.js +25 -719
  14. package/dist/output/cyclonedx.js +28 -24
  15. package/dist/output/formatters.js +13 -0
  16. package/dist/output/html-reporter.js +81 -40
  17. package/dist/output/multi-folder-html-reporter.js +16 -10
  18. package/dist/output/multi-folder-printer.js +1 -1
  19. package/dist/output/override-findings-sarif.js +1 -0
  20. package/dist/output/printers.js +436 -271
  21. package/dist/output/sarif.js +17 -1
  22. package/dist/output/sbom-dependency-edges.js +86 -0
  23. package/dist/output/sbom-file.js +27 -0
  24. package/dist/output/spdx.js +293 -0
  25. package/dist/output/write-outputs.js +18 -3
  26. package/dist/overrides/admitted-scan.js +158 -0
  27. package/dist/overrides/api.js +16 -0
  28. package/dist/overrides/context-builder.js +4 -0
  29. package/dist/overrides/context.js +8 -1
  30. package/dist/overrides/detectors/index.js +2 -0
  31. package/dist/overrides/detectors/oa010-vulnerable-floor.js +123 -0
  32. package/dist/overrides/parsing/registry.js +53 -0
  33. package/dist/parsers/bun-lock-graph.js +182 -0
  34. package/dist/parsers/bun-lock.js +93 -132
  35. package/dist/parsers/index.js +75 -149
  36. package/dist/parsers/multi-package.js +5 -6
  37. package/dist/parsers/package-lock.js +11 -1
  38. package/dist/parsers/pnpm-lock-graph.js +94 -0
  39. package/dist/parsers/pnpm-lock.js +5 -5
  40. package/dist/parsers/utils.js +3 -0
  41. package/dist/parsers/yarn-lock-graph.js +148 -0
  42. package/dist/parsers/yarn-lock.js +3 -3
  43. package/dist/remediation/fix-commands.js +48 -7
  44. package/dist/remediation/npm-registry.js +8 -2
  45. package/dist/scan/completeness.js +1 -0
  46. package/dist/scan/single-scan.js +643 -0
  47. package/dist/scanner.js +62 -7
  48. package/dist/types.js +1 -1
  49. package/dist/utils/file.js +11 -14
  50. package/dist/utils/purl.js +10 -0
  51. package/dist/utils/sbom-format.js +12 -0
  52. package/dist/utils/version.js +84 -10
  53. package/package.json +2 -2
@@ -1,3 +1,10 @@
1
1
  // Single context object built once per scan/audit and consumed by every
2
2
  // detector. Filled by buildOverrideContext() from cve-lite's parser outputs.
3
- export {};
3
+ /**
4
+ * Key for the admitted-version maps. Name alone is not unique: pnpm lets the
5
+ * same package carry several overrides under different selectors, each with its
6
+ * own range.
7
+ */
8
+ export function admittedKey(name, range) {
9
+ return `${name}@${range.trim()}`;
10
+ }
@@ -7,6 +7,7 @@ import { detect as detectOA006 } from "./oa006-coupled-platform-binary.js";
7
7
  import { detect as detectOA007 } from "./oa007-frozen-latest.js";
8
8
  import { detect as detectOA008 } from "./oa008-materialized.js";
9
9
  import { detect as detectOA009 } from "./oa009-stale-floor.js";
10
+ import { detect as detectOA010 } from "./oa010-vulnerable-floor.js";
10
11
  import { detect as detectPD001 } from "./pd001-override-only-phantom.js";
11
12
  import { detect as detectPD002 } from "./pd002-transitive-only-phantom.js";
12
13
  export const ALL_DETECTORS = [
@@ -19,6 +20,7 @@ export const ALL_DETECTORS = [
19
20
  { ruleId: "OA007", detect: detectOA007 },
20
21
  { ruleId: "OA008", detect: detectOA008 },
21
22
  { ruleId: "OA009", detect: detectOA009 },
23
+ { ruleId: "OA010", detect: detectOA010 },
22
24
  { ruleId: "PD001", detect: detectPD001 },
23
25
  { ruleId: "PD002", detect: detectPD002 },
24
26
  ];
@@ -0,0 +1,123 @@
1
+ import { admittedKey } from "../context.js";
2
+ import { jsonPointer } from "../parsing/json-pointer.js";
3
+ import { looksLikeVersion, compareVersions, majorVersion } from "../../utils/version.js";
4
+ import { OVERRIDES_COMMAND } from "../../constants.js";
5
+ const RULE_ID = "OA010";
6
+ /**
7
+ * Severity ordering for picking the worst advisory in an admitted set. "unknown"
8
+ * and "none" sort below everything so a graded advisory always wins.
9
+ */
10
+ const SEVERITY_RANK = {
11
+ none: 0,
12
+ unknown: 0,
13
+ low: 1,
14
+ medium: 2,
15
+ high: 3,
16
+ critical: 4,
17
+ };
18
+ function worstSeverity(hits) {
19
+ let worst = "unknown";
20
+ for (const hit of hits) {
21
+ if (SEVERITY_RANK[hit.severity] > SEVERITY_RANK[worst])
22
+ worst = hit.severity;
23
+ }
24
+ return worst;
25
+ }
26
+ /**
27
+ * Rewrite the floor of an override range, preserving whatever ceiling it already
28
+ * carries. `>=5.7.0 <6` with a 5.10.1 floor becomes `>=5.10.1 <6`; a bare `^5.7.0`
29
+ * becomes `>=5.10.1 <6.0.0` because a caret cannot express a raised floor.
30
+ * Returns null when the shape is not one we can safely rewrite.
31
+ */
32
+ function raiseFloor(pin, newFloor) {
33
+ const tokens = pin.trim().split(/\s+/).filter(Boolean);
34
+ if (tokens.length > 0 && tokens.every((t) => t.startsWith(">=") || t.startsWith("<"))) {
35
+ return tokens.map((t) => (t.startsWith(">=") ? `>=${newFloor}` : t)).join(" ");
36
+ }
37
+ if (tokens.length === 1 && tokens[0].startsWith("^")) {
38
+ const major = majorVersion(newFloor);
39
+ return major === null ? null : `>=${newFloor} <${major + 1}.0.0`;
40
+ }
41
+ return null;
42
+ }
43
+ /**
44
+ * OA010: the range an override floor admits contains a known-vulnerable version.
45
+ *
46
+ * OA009 asks whether a floor is redundant. This asks whether it is safe. A floor
47
+ * is a range, so `>=X` admits every published version above X, and a later
48
+ * advisory can land inside that window without touching the installed version.
49
+ * The scan answers "what fixes the version you have"; nothing was asking "is
50
+ * everything this range permits clean".
51
+ *
52
+ * Pure consumer of ctx.admittedVersions / ctx.admittedVulnerable, both populated
53
+ * by audit() only under --check-network. Makes no network calls itself and
54
+ * no-ops when those maps are empty, the same contract as OA007.
55
+ */
56
+ export function detect(ctx) {
57
+ if (ctx.skippedDetectors.some((s) => s.ruleId === RULE_ID))
58
+ return [];
59
+ if (ctx.admittedVulnerable.size === 0)
60
+ return [];
61
+ const findings = [];
62
+ for (const entry of ctx.overrideEntries) {
63
+ if (typeof entry.value !== "string")
64
+ continue;
65
+ const pin = entry.value.trim();
66
+ // An exact pin admits exactly one version, which is OA008's question, not ours.
67
+ if (looksLikeVersion(pin))
68
+ continue;
69
+ // Keyed by name AND range: the same package can be floored more than once
70
+ // under different selectors, and each range admits a different set.
71
+ const key = admittedKey(entry.packageName, pin);
72
+ const hits = ctx.admittedVulnerable.get(key) ?? [];
73
+ if (hits.length === 0)
74
+ continue;
75
+ const admitted = ctx.admittedVersions.get(key) ?? [];
76
+ const vulnerableVersions = new Set(hits.map((h) => h.version));
77
+ const highestVulnerable = hits
78
+ .map((h) => h.version)
79
+ .reduce((a, b) => (compareVersions(a, b) >= 0 ? a : b));
80
+ // The replacement floor must clear every vulnerable version the range admits,
81
+ // not merely the lowest one, so search above the highest of them.
82
+ const newFloor = admitted
83
+ .filter((v) => !vulnerableVersions.has(v) && compareVersions(v, highestVulnerable) > 0)
84
+ .sort(compareVersions)[0];
85
+ const advisoryIds = [...new Set(hits.map((h) => h.advisoryId))];
86
+ const severity = worstSeverity(hits);
87
+ const versionList = hits.map((h) => h.version).sort(compareVersions).join(", ");
88
+ const base = {
89
+ ruleId: RULE_ID,
90
+ severity,
91
+ package: { name: entry.packageName },
92
+ location: { file: "package.json", jsonPath: jsonPointer(entry.path) },
93
+ references: [
94
+ "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/OA010.md",
95
+ ],
96
+ };
97
+ const rewritten = newFloor ? raiseFloor(pin, newFloor) : null;
98
+ if (!newFloor || !rewritten) {
99
+ findings.push({
100
+ ...base,
101
+ message: "Override floor admits a known-vulnerable version",
102
+ details: `${entry.packageName} is floored to ${pin}, which admits ${versionList} ` +
103
+ `(${advisoryIds.join(", ")}). There is no clean version above them inside ` +
104
+ `the current range, so the floor cannot be raised without widening the ceiling.`,
105
+ });
106
+ continue;
107
+ }
108
+ findings.push({
109
+ ...base,
110
+ message: "Override floor admits a known-vulnerable version",
111
+ details: `${entry.packageName} is floored to ${pin}, which admits ${versionList} ` +
112
+ `(${advisoryIds.join(", ")}). The installed version may be clean today, but ` +
113
+ `any resolution inside this range is permitted to pick a vulnerable one. ` +
114
+ `Raise the floor to ${newFloor}.`,
115
+ fix: {
116
+ type: "rfc6902",
117
+ patch: [{ op: "replace", path: jsonPointer(entry.path), value: rewritten }],
118
+ runnableCommand: `${OVERRIDES_COMMAND} --fix --rule ${RULE_ID}`,
119
+ },
120
+ });
121
+ }
122
+ return findings;
123
+ }
@@ -1,3 +1,4 @@
1
+ import { compareVersions, isPreReleaseVersion } from '../../utils/version.js';
1
2
  /**
2
3
  * Fetch the `dist-tags` map for `pkgName` from the npm registry.
3
4
  *
@@ -50,6 +51,58 @@ export async function fetchDistTagsBatch(pkgNames, opts = {}) {
50
51
  }));
51
52
  return out;
52
53
  }
54
+ /**
55
+ * Fetch every published version of `pkgName`, ascending, excluding prereleases.
56
+ *
57
+ * Uses the same abbreviated packument as `fetchDistTags`, which already carries
58
+ * the full `versions` map, so this costs no extra round trip shape-wise.
59
+ * Returns null on any failure, matching `fetchDistTags`.
60
+ */
61
+ export async function fetchVersions(pkgName, opts = {}) {
62
+ const baseUrl = opts.baseUrl ?? 'https://registry.npmjs.org';
63
+ const timeoutMs = opts.timeoutMs ?? 5000;
64
+ const fetchImpl = opts.fetchImpl ?? fetch;
65
+ const url = `${baseUrl}/${encodeRegistryPath(pkgName)}`;
66
+ const controller = new AbortController();
67
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
68
+ try {
69
+ const res = await fetchImpl(url, {
70
+ signal: controller.signal,
71
+ headers: {
72
+ Accept: 'application/vnd.npm.install-v1+json',
73
+ 'User-Agent': 'override-audit-cli',
74
+ },
75
+ });
76
+ if (!res.ok)
77
+ return null;
78
+ const body = await res.json();
79
+ if (!body.versions)
80
+ return null;
81
+ return Object.keys(body.versions)
82
+ .filter((v) => !isPreReleaseVersion(v))
83
+ .sort(compareVersions);
84
+ }
85
+ catch {
86
+ return null;
87
+ }
88
+ finally {
89
+ clearTimeout(timer);
90
+ }
91
+ }
92
+ /**
93
+ * Fetch version lists for many packages concurrently. Per-package failures
94
+ * collapse to an absent entry rather than failing the batch.
95
+ */
96
+ export async function fetchVersionsBatch(pkgNames, opts = {}) {
97
+ const out = new Map();
98
+ const unique = Array.from(new Set(pkgNames));
99
+ await Promise.all(unique.map(async (name) => {
100
+ const versions = await fetchVersions(name, opts);
101
+ if (versions)
102
+ out.set(name, versions);
103
+ }));
104
+ return out;
105
+ }
53
106
  /**
54
107
  * Encode a package name for the registry URL.
55
108
  * Scoped names like `@scope/pkg` need the slash kept literal — the registry
@@ -0,0 +1,182 @@
1
+ import fs from "node:fs";
2
+ /**
3
+ * Key resolution for `bun.lock`.
4
+ *
5
+ * Bun encodes duplicate versions in the package key the way npm encodes them in
6
+ * `node_modules` nesting: the top-level copy is keyed `lru-cache`, and a copy
7
+ * hoisted under a specific parent is keyed `@babel/helper-compilation-targets/lru-cache`.
8
+ * A dependency declaration only ever names the bare package, so resolving a
9
+ * declaration to the entry it actually installs means walking outward from the
10
+ * declaring package, exactly like Node's resolution algorithm.
11
+ *
12
+ * The parser previously looked children up by bare name against a map keyed by
13
+ * these full keys, so any nested copy resolved to the top-level entry instead of
14
+ * itself. See #1116.
15
+ */
16
+ /** Dependency sections of a lockfile entry that represent real installed edges. */
17
+ const DEPENDENCY_SECTIONS = ["dependencies", "optionalDependencies", "devDependencies"];
18
+ /**
19
+ * Splits a package key into the key of the package it is nested under and the
20
+ * bare name of the package itself.
21
+ *
22
+ * The trailing name may be scoped, so the split cannot simply take the last
23
+ * segment: `@cline/hub/@types/node` is `@types/node` nested under `@cline/hub`,
24
+ * while `@types/node` on its own is a top-level scoped package with no parent.
25
+ */
26
+ export function splitBunPackageKey(key) {
27
+ const parts = key.split("/");
28
+ if (parts.length === 1)
29
+ return { parentKey: null, childName: key };
30
+ const scopedChild = parts[parts.length - 2].startsWith("@");
31
+ const childName = scopedChild ? parts.slice(-2).join("/") : parts[parts.length - 1];
32
+ const parentKey = (scopedChild ? parts.slice(0, -2) : parts.slice(0, -1)).join("/");
33
+ return { parentKey: parentKey === "" ? null : parentKey, childName };
34
+ }
35
+ /**
36
+ * Resolves a dependency declared by `parentKey` to the package key that satisfies
37
+ * it, preferring the copy nested closest to the declaring package and falling
38
+ * back to the top-level copy. Returns null when no entry satisfies it, which
39
+ * happens for declarations Bun did not install (an unmet optional peer, say).
40
+ */
41
+ export function resolveBunChildKey(parentKey, childName, keys) {
42
+ let scope = parentKey;
43
+ while (scope !== null) {
44
+ const candidate = `${scope}/${childName}`;
45
+ if (keys.has(candidate))
46
+ return candidate;
47
+ scope = splitBunPackageKey(scope).parentKey;
48
+ }
49
+ return keys.has(childName) ? childName : null;
50
+ }
51
+ /**
52
+ * Reads the dependency names declared by one lockfile entry's metadata object.
53
+ *
54
+ * Bun writes the named sections, but also inlines some dependencies as bare
55
+ * `name: range` pairs alongside them, so both shapes count.
56
+ */
57
+ export function extractChildDependencyNames(depMeta) {
58
+ if (!depMeta || typeof depMeta !== "object")
59
+ return [];
60
+ const names = new Set();
61
+ const meta = depMeta;
62
+ for (const section of DEPENDENCY_SECTIONS) {
63
+ const sectionObj = meta[section];
64
+ if (!sectionObj || typeof sectionObj !== "object")
65
+ continue;
66
+ for (const name of Object.keys(sectionObj))
67
+ names.add(name);
68
+ }
69
+ for (const [key, value] of Object.entries(meta)) {
70
+ if (DEPENDENCY_SECTIONS.includes(key))
71
+ continue;
72
+ if (typeof value === "string")
73
+ names.add(key);
74
+ }
75
+ return [...names];
76
+ }
77
+ /**
78
+ * Builds the package-key dependency graph: every entry mapped to the keys of the
79
+ * entries it actually installs.
80
+ *
81
+ * Unlike the bare-name map this replaces, two versions of the same package are
82
+ * distinct nodes here, so a path through one is never attributed to the other.
83
+ */
84
+ export function buildBunChildKeyGraph(packages) {
85
+ const keys = new Set(Object.keys(packages));
86
+ const graph = new Map();
87
+ for (const [key, entry] of Object.entries(packages)) {
88
+ if (!Array.isArray(entry))
89
+ continue;
90
+ const resolved = new Set();
91
+ for (const childName of extractChildDependencyNames(entry[2])) {
92
+ const childKey = resolveBunChildKey(key, childName, keys);
93
+ if (childKey)
94
+ resolved.add(childKey);
95
+ }
96
+ graph.set(key, [...resolved]);
97
+ }
98
+ return graph;
99
+ }
100
+ /** Maps each package key to the name and version its entry resolves to. */
101
+ export function buildBunKeyIndex(packages) {
102
+ const index = new Map();
103
+ for (const [key, entry] of Object.entries(packages)) {
104
+ if (!Array.isArray(entry) || entry.length < 1)
105
+ continue;
106
+ const nameAtVersion = String(entry[0] ?? "");
107
+ const atIndex = nameAtVersion.lastIndexOf("@");
108
+ if (atIndex <= 0)
109
+ continue;
110
+ const name = nameAtVersion.slice(0, atIndex);
111
+ const version = nameAtVersion.slice(atIndex + 1);
112
+ if (!name || !version)
113
+ continue;
114
+ index.set(key, { name, version });
115
+ }
116
+ return index;
117
+ }
118
+ /** Walks the key graph from a set of roots and returns every reachable key. */
119
+ export function collectReachableKeys(rootKeys, graph) {
120
+ const reachable = new Set();
121
+ const stack = [...rootKeys];
122
+ while (stack.length > 0) {
123
+ const key = stack.pop();
124
+ if (reachable.has(key))
125
+ continue;
126
+ reachable.add(key);
127
+ for (const child of graph.get(key) ?? []) {
128
+ if (!reachable.has(child))
129
+ stack.push(child);
130
+ }
131
+ }
132
+ return reachable;
133
+ }
134
+ /** Reads and parses a bun.lock. Bun writes JSONC, so trailing commas are stripped. */
135
+ export function readAndParseBunLock(filePath) {
136
+ return JSON.parse(fs.readFileSync(filePath, "utf8").replace(/,(\s*[}\]])/g, "$1"));
137
+ }
138
+ const EMPTY = Object.freeze([]);
139
+ /**
140
+ * Builds the complete child-to-parents map for a bun.lock.
141
+ *
142
+ * The parser walks this same structure, but `collectBunPaths` caps it at five
143
+ * paths of at most ten segments per package. Rebuilding edges from those
144
+ * truncated paths loses routes on any sizeable tree, and a package whose
145
+ * surviving routes all traverse filtered-out packages ends up with no parent at
146
+ * all. This keeps every edge.
147
+ *
148
+ * Returns null for a lockfile it cannot read, so the caller falls back to
149
+ * path-derived behaviour rather than emitting an SBOM with no edges.
150
+ */
151
+ export function loadBunLockGraph(filePath) {
152
+ const raw = readAndParseBunLock(filePath);
153
+ const packages = raw?.packages;
154
+ if (!packages || typeof packages !== "object")
155
+ return null;
156
+ const keyIndex = buildBunKeyIndex(packages);
157
+ const childGraph = buildBunChildKeyGraph(packages);
158
+ const parentsByKey = new Map();
159
+ for (const [parentKey, childKeys] of childGraph) {
160
+ for (const childKey of childKeys) {
161
+ const parents = parentsByKey.get(childKey);
162
+ if (!parents)
163
+ parentsByKey.set(childKey, [parentKey]);
164
+ else if (!parents.includes(parentKey))
165
+ parents.push(parentKey);
166
+ }
167
+ }
168
+ const keysByNameVersion = new Map();
169
+ for (const [key, node] of keyIndex) {
170
+ const id = `${node.name}@${node.version}`;
171
+ const keys = keysByNameVersion.get(id);
172
+ if (!keys)
173
+ keysByNameVersion.set(id, [key]);
174
+ else
175
+ keys.push(key);
176
+ }
177
+ return {
178
+ nodeIdsFor: (name, version) => keysByNameVersion.get(`${name}@${version ?? ""}`) ?? EMPTY,
179
+ parentsFor: nodeId => parentsByKey.get(nodeId) ?? EMPTY,
180
+ getNode: nodeId => keyIndex.get(nodeId) ?? null,
181
+ };
182
+ }
@@ -1,83 +1,112 @@
1
- import fs from "node:fs";
2
1
  import { uniquePathArrays } from "../utils/array.js";
3
2
  import { upsertPackage } from "./utils.js";
3
+ import { buildBunChildKeyGraph, buildBunKeyIndex, collectReachableKeys, readAndParseBunLock, resolveBunChildKey, } from "./bun-lock-graph.js";
4
4
  const MAX_PATHS_PER_PACKAGE = 5;
5
5
  const MAX_PATH_DEPTH = 10;
6
- function parseJsonc(text) {
7
- // bun.lock uses JSONC (trailing commas). Strip them before parsing.
8
- return JSON.parse(text.replace(/,(\s*[}\]])/g, "$1"));
9
- }
10
- function extractChildDependencyNames(depMeta) {
11
- if (!depMeta || typeof depMeta !== "object")
12
- return [];
13
- const names = new Set();
14
- const meta = depMeta;
15
- for (const section of ["dependencies", "optionalDependencies", "devDependencies"]) {
16
- const sectionObj = meta[section];
17
- if (!sectionObj || typeof sectionObj !== "object")
18
- continue;
19
- for (const name of Object.keys(sectionObj)) {
20
- names.add(name);
21
- }
22
- }
23
- for (const [key, value] of Object.entries(meta)) {
24
- if (key === "dependencies" || key === "optionalDependencies" || key === "devDependencies")
25
- continue;
26
- if (typeof value === "string") {
27
- names.add(key);
6
+ const DEPENDENCY_SECTIONS = ["dependencies", "optionalDependencies", "devDependencies"];
7
+ /**
8
+ * Builds the traversal seeds for a lockfile.
9
+ *
10
+ * Seeds come from every workspace, not just the root. A workspace member's
11
+ * dependencies hang off `["project", <member name>]` so a transitive reachable
12
+ * only through that member resolves back to it rather than appearing to be a
13
+ * direct dependency of the root. Seeding from the root alone left anything
14
+ * declared by a member unvisited, which on a real monorepo is most of the tree
15
+ * (#1116).
16
+ *
17
+ * Each seed records whether its declaring edge was a devDependency, which drives
18
+ * the reachability-based dev classification below.
19
+ */
20
+ function buildBunSeeds(workspaces, keys) {
21
+ const seeds = [];
22
+ for (const [workspacePath, workspace] of Object.entries(workspaces)) {
23
+ const workspaceName = typeof workspace?.name === "string" ? workspace.name : "";
24
+ const isRoot = workspacePath === "" || workspaceName === "";
25
+ const path = isRoot ? ["project"] : ["project", workspaceName];
26
+ // A member's own dependencies may be nested under its package key, so resolve
27
+ // from there when the member is itself an entry in the lockfile.
28
+ const scope = keys.has(workspaceName) ? workspaceName : null;
29
+ for (const section of DEPENDENCY_SECTIONS) {
30
+ const depSection = workspace?.[section];
31
+ if (!depSection || typeof depSection !== "object")
32
+ continue;
33
+ const dev = section === "devDependencies";
34
+ for (const depName of Object.keys(depSection)) {
35
+ const key = resolveBunChildKey(scope, depName, keys);
36
+ if (key)
37
+ seeds.push({ key, path, dev });
38
+ }
28
39
  }
29
40
  }
30
- return [...names];
41
+ return seeds;
31
42
  }
32
- function collectBunPaths(rootDepNames, childDepsByPackageName, map, packageNameToVersion) {
33
- const queue = rootDepNames.map(name => ({ name, path: ["project"] }));
43
+ /**
44
+ * Records a dependency path for every package reachable from the seeds.
45
+ *
46
+ * The walk is keyed by package key rather than bare name, so two versions of the
47
+ * same package accumulate their own paths instead of collapsing onto whichever
48
+ * one happened to sit at the top level.
49
+ */
50
+ function collectBunPaths(seeds, graph, keyIndex, map) {
51
+ const queue = seeds.map(seed => ({ key: seed.key, path: seed.path }));
34
52
  const visitedStates = new Set();
35
53
  let head = 0;
36
54
  while (head < queue.length) {
37
55
  const current = queue[head++];
38
- const nextPath = [...current.path, current.name];
39
- const version = packageNameToVersion.get(current.name);
40
- const stateKey = `${current.name}@${version ?? ""}>${nextPath.join(">")}`;
56
+ const entry = keyIndex.get(current.key);
57
+ if (!entry)
58
+ continue;
59
+ const nextPath = [...current.path, entry.name];
60
+ const stateKey = `${current.key}>${nextPath.join(">")}`;
41
61
  if (visitedStates.has(stateKey))
42
62
  continue;
43
63
  visitedStates.add(stateKey);
44
- if (version) {
45
- const pkg = map.get(`${current.name}@${version}`);
46
- if (pkg) {
47
- pkg.paths = uniquePathArrays([...(pkg.paths ?? []), nextPath]).slice(0, MAX_PATHS_PER_PACKAGE);
48
- }
64
+ const pkg = map.get(`${entry.name}@${entry.version}`);
65
+ if (pkg) {
66
+ pkg.paths = uniquePathArrays([...(pkg.paths ?? []), nextPath]).slice(0, MAX_PATHS_PER_PACKAGE);
49
67
  }
50
68
  if (nextPath.length >= MAX_PATH_DEPTH)
51
69
  continue;
52
- for (const child of childDepsByPackageName.get(current.name) ?? []) {
53
- queue.push({ name: child, path: nextPath });
70
+ for (const child of graph.get(current.key) ?? []) {
71
+ queue.push({ key: child, path: nextPath });
54
72
  }
55
73
  }
56
74
  }
57
- // Walk the package graph from a set of root dependency names and return every reachable name.
58
- // Used to classify dev vs prod: a package is dev only when it is reachable from a
59
- // devDependency root but not from any production root.
60
- function collectReachableNames(rootNames, childDepsByPackageName) {
61
- const reachable = new Set();
62
- const stack = [...rootNames];
63
- while (stack.length > 0) {
64
- const name = stack.pop();
65
- if (reachable.has(name))
75
+ /**
76
+ * Creates one package ref per lockfile entry, classifying dev vs prod by graph
77
+ * reachability: a package is dev when it is reachable from a devDependency seed
78
+ * but from no production seed. Reachability is computed over package keys, so a
79
+ * nested copy is classified on its own merits.
80
+ */
81
+ function createPackageRefs(packages, keyIndex, prodReachable, devReachable, prodOnly, map) {
82
+ for (const [key, entry] of Object.entries(packages)) {
83
+ const parsed = keyIndex.get(key);
84
+ if (!parsed)
66
85
  continue;
67
- reachable.add(name);
68
- for (const child of childDepsByPackageName.get(name) ?? []) {
69
- if (!reachable.has(child))
70
- stack.push(child);
71
- }
86
+ const dev = devReachable.has(key) && !prodReachable.has(key);
87
+ if (prodOnly && dev)
88
+ continue;
89
+ const resolvedUrl = typeof entry[1] === "string" && entry[1] !== "" ? entry[1] : undefined;
90
+ upsertPackage(map, {
91
+ name: parsed.name,
92
+ version: parsed.version,
93
+ ecosystem: "npm",
94
+ dev,
95
+ paths: [],
96
+ resolvedUrl,
97
+ });
72
98
  }
73
- return reachable;
74
99
  }
75
100
  export function buildBunWorkspaceMap(filePath) {
76
- const raw = parseJsonc(fs.readFileSync(filePath, "utf8"));
101
+ const raw = readAndParseBunLock(filePath);
77
102
  const workspaces = raw?.workspaces ?? {};
78
103
  const map = new Map();
79
- for (const [workspacePath, workspace] of Object.entries(workspaces)) {
80
- for (const depSectionName of ["dependencies", "optionalDependencies", "devDependencies"]) {
104
+ for (const [rawWorkspacePath, workspace] of Object.entries(workspaces)) {
105
+ // Bun keys the root workspace "", where npm keys it "" and normalises to ".".
106
+ // Consumers drop the root with `w !== "."`, so an unnormalised "" survives and
107
+ // renders as a valueless `--filter ` in the fix command.
108
+ const workspacePath = rawWorkspacePath === "" ? "." : rawWorkspacePath;
109
+ for (const depSectionName of DEPENDENCY_SECTIONS) {
81
110
  const depSection = workspace?.[depSectionName];
82
111
  if (!depSection || typeof depSection !== "object")
83
112
  continue;
@@ -92,87 +121,19 @@ export function buildBunWorkspaceMap(filePath) {
92
121
  return map;
93
122
  }
94
123
  export function loadFromBunLock(filePath, prodOnly) {
95
- const raw = parseJsonc(fs.readFileSync(filePath, "utf8"));
124
+ const raw = readAndParseBunLock(filePath);
96
125
  const packages = raw?.packages ?? {};
97
126
  const workspaces = raw?.workspaces ?? {};
127
+ const keys = new Set(Object.keys(packages));
128
+ const keyIndex = buildBunKeyIndex(packages);
129
+ const graph = buildBunChildKeyGraph(packages);
130
+ const seeds = buildBunSeeds(workspaces, keys);
131
+ const prodReachable = collectReachableKeys(seeds.filter(seed => !seed.dev).map(seed => seed.key), graph);
132
+ const devReachable = collectReachableKeys(seeds.filter(seed => seed.dev).map(seed => seed.key), graph);
98
133
  const map = new Map();
99
- const childDepsByPackageName = new Map();
100
- const packageNameToVersion = new Map();
101
- const prodRootNames = new Set();
102
- const devRootNames = new Set();
103
- const rootDepNames = [];
104
- for (const workspace of Object.values(workspaces)) {
105
- for (const name of Object.keys(workspace?.dependencies ?? {})) {
106
- prodRootNames.add(name);
107
- }
108
- for (const name of Object.keys(workspace?.optionalDependencies ?? {})) {
109
- prodRootNames.add(name);
110
- }
111
- for (const name of Object.keys(workspace?.devDependencies ?? {})) {
112
- devRootNames.add(name);
113
- }
114
- }
115
- for (const [workspacePath, workspace] of Object.entries(workspaces)) {
116
- if (workspacePath !== "")
117
- continue;
118
- for (const depSectionName of ["dependencies", "optionalDependencies", "devDependencies"]) {
119
- if (prodOnly && depSectionName === "devDependencies")
120
- continue;
121
- const depSection = workspace?.[depSectionName];
122
- if (!depSection || typeof depSection !== "object")
123
- continue;
124
- for (const depName of Object.keys(depSection)) {
125
- rootDepNames.push(depName);
126
- }
127
- }
128
- }
129
- // First pass: build the package graph (package key -> version, package key -> child dep names).
130
- for (const [pkgName, entry] of Object.entries(packages)) {
131
- if (!Array.isArray(entry) || entry.length < 1)
132
- continue;
133
- const nameAtVersion = String(entry[0] ?? "");
134
- const atIndex = nameAtVersion.lastIndexOf("@");
135
- if (atIndex <= 0)
136
- continue;
137
- const version = nameAtVersion.slice(atIndex + 1);
138
- if (!version)
139
- continue;
140
- packageNameToVersion.set(pkgName, version);
141
- childDepsByPackageName.set(pkgName, extractChildDependencyNames(entry[2]));
142
- }
143
- // Classify dev vs prod by graph reachability rather than by direct declaration only: a
144
- // package is dev when it is reachable from a devDependency root but not from any production
145
- // (dependencies/optionalDependencies) root. This correctly marks a transitive pulled in only
146
- // through a devDependency as dev, while keeping any package used in production anywhere prod.
147
- const prodReachable = collectReachableNames(prodRootNames, childDepsByPackageName);
148
- const devReachable = collectReachableNames(devRootNames, childDepsByPackageName);
149
- // Second pass: create package refs with the reachability-based dev flag.
150
- for (const [, entry] of Object.entries(packages)) {
151
- if (!Array.isArray(entry) || entry.length < 1)
152
- continue;
153
- const nameAtVersion = String(entry[0] ?? "");
154
- const atIndex = nameAtVersion.lastIndexOf("@");
155
- if (atIndex <= 0)
156
- continue;
157
- const name = nameAtVersion.slice(0, atIndex);
158
- const version = nameAtVersion.slice(atIndex + 1);
159
- if (!name || !version)
160
- continue;
161
- const dev = devReachable.has(name) && !prodReachable.has(name);
162
- if (prodOnly && dev)
163
- continue;
164
- const resolvedUrl = typeof entry[1] === "string" && entry[1] !== "" ? entry[1] : undefined;
165
- upsertPackage(map, {
166
- name,
167
- version,
168
- ecosystem: "npm",
169
- dev,
170
- paths: [],
171
- resolvedUrl,
172
- });
173
- }
174
- collectBunPaths(rootDepNames, childDepsByPackageName, map, packageNameToVersion);
175
- for (const [pkgKey, pkg] of map.entries()) {
134
+ createPackageRefs(packages, keyIndex, prodReachable, devReachable, prodOnly, map);
135
+ collectBunPaths(prodOnly ? seeds.filter(seed => !seed.dev) : seeds, graph, keyIndex, map);
136
+ for (const pkg of map.values()) {
176
137
  if ((pkg.paths?.length ?? 0) === 0) {
177
138
  pkg.paths = [["project", pkg.name]];
178
139
  }