Skip to content

[install] Add --transitive to bun update for transitive CVE remediation - #31143

Closed
charpeni wants to merge 2 commits into
oven-sh:mainfrom
charpeni:implement-recursive-update
Closed

charpeni wants to merge 2 commits into
oven-sh:mainfrom
charpeni:implement-recursive-update

Conversation

@charpeni

@charpeni charpeni commented May 20, 2026 •

Copy link
Copy Markdown

What does this PR do?

Adds -t/--transitive to bun update. Re-resolves transitive dependencies in bun.lock to the highest in-range version without modifying package.json. Standard workflow for remediating CVEs in nested deps, on par with yarn up --recursive and npm update <pkg>.

Closes #24523.

Why

Today, when a CVE is announced in a transitive dep, Bun users have two unsatisfying options:

  1. bun update <transitive> treats <transitive> as a direct dependency and adds it to package.json. This alters the dep graph and surfaces the inner dep where it shouldn't be.
  2. overrides/resolutions in package.json — a sledgehammer per this blog post. Recommended only as a last resort because it pins versions globally and survives even when the parent ships a fix.

Yarn, npm, and pnpm each solve this — via different surface syntax, but all three correctly update transitives without polluting package.json. Bun didn't, until now.

Naming: why --transitive and not --recursive

--recursive is overloaded across package managers:

Manager --recursive means
Yarn (yarn up --recursive) transitive-dep recursion
pnpm (pnpm update --recursive) workspace iteration
Bun today advertised as workspace iteration on bun update / bun outdated (and implemented as such on bun remove via #27897). The flag on bun update is parsed but has no consumer site reading it today; semantically reserved for #23507.

If we'd reused -r, --recursive for the new transitive behavior, it would conflict with bun remove --recursive (workspace iteration) and with bun outdated --recursive. So this PR introduces -t, --transitive specifically for the transitive-CVE-remediation flow and leaves --recursive alone (its bun update help text is restored to "Update packages in all workspaces", consistent with #23507's planned implementation).

This is a deliberate divergence from Yarn's flag name. It keeps Bun's own CLI vocabulary internally consistent across update / outdated / remove. Documented in docs/pm/cli/update.mdx.

Behavior

# Refresh every transitive to its highest in-range version
bun update --transitive

# Same, but only refresh the subtree under a specific direct dep
bun update parent --transitive

# Composes with --force
bun update --transitive --force

Walkthrough

// package.json — unchanged before & after
{
  "dependencies": { "parent": "^1.0.0" }
}

parent@1.1.0 declares "dep": "^1.0.0". Lockfile pins dep@1.0.0. Then dep@1.5.0 is published.

Command package.json bun.lock dep version
bun update parent (today, buggy — #24523) bumped to ^1.1.0 still 1.0.0
bun update dep (today, wrong tool) gains a top-level dep entry 1.5.0
bun update parent --transitive (this PR) unchanged 1.5.0
bun update --transitive (this PR) unchanged 1.5.0

Range semantics are preserved: if parent declares "dep": "^1.0.0" and dep@2.0.0 exists, dep@1.5.0 is still the pick. For across-major upgrades, update the direct dep that owns the range.

How

Four layers, each fixing a distinct reason "just re-run bun update" doesn't propagate to transitives today. Everything is gated on subcommand == Subcommand::Update && options.do_.transitive(), so the default install path is untouched.

bun update [pkg] --transitive
  │
  ▼
1. updatePackageJSONAndInstall.rs
   ├─ Sets manifest_refresh_all = true
   ├─ Records positional targets in manifest_refresh_targets
   └─ SKIPS PackageJSONEditor::edit (pre- + post-install)  ← protects package.json
  │
  ▼
2. install_with_manager.rs (after the diff phase)
   └─ Even with no package.json diffs, walks every npm/dist-tag dep edge,
      clears the resolution, and re-enqueues — so the resolver consults
      fresh manifests for transitives, not just root deps.
  │
  ▼
3. PackageManagerEnqueue.rs::get_or_put_resolved_package_with_find_result
   └─ Passes a None version filter when force_fresh_resolution holds.
      get_package_id then requires an exact-resolution match; the old
      entry misses; control falls through to append_package with the
      fresh version.
  │
  ▼
4. lockfile.rs::Cloner::flush (post-clone re-resolve pass)
   └─ Walks every dep edge in the new lockfile, picks the highest
      in-range npm package in the new package_index, repoints the edge
      if a better candidate exists.

Files

File Δ Purpose
src/install/PackageManager.rs +32 New manifest_refresh_targets, manifest_refresh_all, should_use_manifest_cache(name_hash) helper
src/install/PackageManager/PackageManagerDirectories.rs +14/-1 New manifest_disk_cache_ctx_for(name_hash) that consults the refresh set
src/install/PackageManager/PackageManagerEnqueue.rs +18/-5 Cache check via helper; force_fresh_resolution short-circuit in resolution lookup
src/install/PackageManager/install_with_manager.rs +43 Re-enqueue all eligible dep edges when --transitive, even with no package.json diffs
src/install/PackageManager/updatePackageJSONAndInstall.rs +46/-1 Skip PackageJSONEditor::edit (pre + post); populate refresh set
src/install/PackageManager/PackageManagerOptions.rs +12 New Do::TRANSITIVE bit + transitive() / set_transitive() accessors
src/install/lockfile.rs +100 Cloner::transitive_re_resolve() + pick_better_resolution() post-clone repointing
src/install/PackageManager/CommandLineArguments.rs +6/-1 New -t, --transitive flag wired into Subcommand::Update
src/install/PackageManager/CommandLineArguments.zig +1 Same flag in Zig (port-in-flight)
docs/pm/cli/update.mdx +42 New --transitive section + Naming note
test/cli/install/bun-update-transitive.test.ts +449 New test file

Design notes

  • manifest_refresh_all = true always under --transitive, even with positional args. Targeted manifest refresh would require walking the transitive closure of named packages — significantly more code. Refreshing extras is fine for an opt-in CVE-remediation tool. The manifest_refresh_targets set is still populated, providing a clean extension point for future targeted refresh.

  • should_use_manifest_cache() is the single source of truth for per-name cache decisions. Both PackageManagerEnqueue.rs:1142 and manifest_disk_cache_ctx_for() consult it. Future bypass logic (e.g. --force-package <name>) has a clean hook.

  • The post-clone Cloner pass is the lockfile-side complement to the resolver-side force_fresh_resolution. Layer 3 ensures the fresh version lands in the new lockfile; layer 4 ensures dep edges point to it. Defensive against ordering edge cases (older entries landing first during the breadth-first clone).

Compatibility

Performance

Default bun install is untouched — all changes are gated on subcommand == Subcommand::Update && do_.transitive(). No new field reads on the hot install path.

--transitive itself fetches every manifest fresh from the registry (intentional — that's the point), plus one additional walk over lockfile dep edges in Cloner::flush. The walk is O(edges) and operates on already-loaded structures.

How did you verify your code works?

test/cli/install/bun-update-transitive.test.ts — 6 tests, all passing. Uses a stand-alone Bun.serve mock registry with on-the-fly tarball generation (pattern from minimum-release-age.test.ts).

✓ baseline: initial install resolves dep to the highest in-range (1.5.0)
✓ repro of #24523: bun update without --transitive leaves stale transitive
✓ bun update parent --transitive re-resolves transitive dep to 1.5.0
✓ --transitive does NOT mutate package.json
✓ bare `bun update --transitive` re-resolves everything in range
✓ composes with --force

Two tests use toMatchInlineSnapshot() against the full port-normalized bun.lock as regression guards.

Pre-existing wart documented by snapshot

The targeted-update snapshot reveals an unrelated, pre-existing bug: bun update <pkg> (with positional arg) records the resolved version range in bun.lock's workspaces."".dependencies, while package.json correctly retains the user-declared range:

// package.json: "parent": "^1.0.0"  ← correct, unchanged
// bun.lock workspaces."".dependencies: "parent": "^1.1.0"  ← wart

The bare bun update --transitive (no positional) path doesn't have this — both files agree. The wart is orthogonal to --transitive (reproducible without it) and is noted in the test as a follow-up. The next bun install reconciles bun.lock against package.json, so runtime behavior is correct.

Manual verification

bun update --help               # confirms new flag in help, alongside --recursive
bun update --transitive         # no positional, refreshes all transitives
bun update lodash --transitive  # targeted, refreshes lodash subtree
bun update --transitive --force # combines with --force

git diff package.json after any of the above: empty.

Out of scope (deferred)

References

…ation

`bun update --recursive` re-resolves transitive dependencies in
`bun.lock` to the highest in-range version without modifying
`package.json`. This is the standard workflow for remediating CVEs in
nested dependencies, on par with `yarn up --recursive` and `npm update
<pkg>`.

Behavior:
- Refreshes manifests for all (or targeted) names so the resolver sees
  fresh registry data.
- Re-resolves every transitive dep edge to the highest version that
  satisfies the parent's declared range.
- Leaves `package.json` byte-for-byte unchanged.
- Composes with `--force`.

Implementation: four-layer composition gated on
`subcommand == Update && do_.recursive()` so the default install path
is unaffected.

1. `updatePackageJSONAndInstall.rs`: skip `PackageJSONEditor::edit`
   (pre- and post-install); populate `manifest_refresh_targets` and set
   `manifest_refresh_all = true`.
2. `install_with_manager.rs`: walk every npm/dist-tag dep edge, clear
   its resolution, and re-enqueue so the resolver consults fresh
   manifests for transitives, not just root deps.
3. `PackageManagerEnqueue.rs`: in
   `get_or_put_resolved_package_with_find_result`, pass a `None` version
   filter when `force_fresh_resolution` holds so the exact-match lookup
   misses stale entries and falls through to `append_package` with the
   fresh version.
4. `lockfile::Cloner`: post-clone re-resolve pass repoints every dep
   edge to the highest in-range npm package in the new
   `package_index`.

Reuses the existing `-r`/`--recursive` flag (previously advertised but
unimplemented for `bun update`). Workspace recursion (oven-sh#23507) can
compose with this when implemented.

Tests: `test/cli/install/bun-update-recursive.test.ts` adds 6 tests
with a stand-alone mock registry and on-the-fly tarball generation. Two
tests pin the full post-update `bun.lock` via `toMatchInlineSnapshot`.

Closes oven-sh#24523

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@coderabbitai

coderabbitai Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

This PR implements bun update --transitive to re-resolve transitive dependencies to the highest versions satisfying each parent's semver ranges without modifying package.json. The feature adds per-package manifest refresh control, integrates fresh resolution logic in the enqueue path, re-enqueues dependencies during install, and applies lockfile-side upgrade algorithms.

Changes

Transitive Dependency Re-resolution

Layer / File(s) Summary
CLI flag, options, and documentation
docs/pm/cli/update.mdx, src/install/PackageManager/CommandLineArguments.rs, src/install/PackageManager/CommandLineArguments.zig, src/install/PackageManager/PackageManagerOptions.rs
--transitive / -t flag added to bun update CLI, parsed into CommandLineArguments.transitive, propagated through Options::load to Do::TRANSITIVE bitflag with accessor methods. Documentation explains behavior, usage, when-to-use scenarios, naming consistency with other package managers, and compatibility with --force.
Per-package manifest refresh control
src/install/PackageManager.rs, src/install/PackageManager/PackageManagerDirectories.rs
PackageManager gains manifest_refresh_targets set and manifest_refresh_all flag; new should_use_manifest_cache(name_hash) gates reuse per package; manifest_disk_cache_ctx_for(name_hash) provides scoped cache context creation. Both fields initialized in init() and init_with_runtime_once().
Update initialization and package.json preservation
src/install/PackageManager/updatePackageJSONAndInstall.rs
When bun update --transitive invoked, set manifest_refresh_all and populate manifest_refresh_targets with update roots' name_hash; skip PackageJSONEditor::edit calls in pre-install and post-install phases to keep package.json unchanged.
Enqueue-path fresh resolution
src/install/PackageManager/PackageManagerEnqueue.rs
Route manifest cache context through per-package manifest_disk_cache_ctx_for(Some(name_hash)), update manifest reuse gate to should_use_manifest_cache(name_hash), implement force_fresh_resolution for Update subcommand in transitive mode to force lockfile.get_package_id filter to None when manifests were refreshed, preventing stale lockfile reuse.
Install-phase re-enqueue
src/install/PackageManager/install_with_manager.rs
When bun update --transitive and no new lockfile needed, iterate lockfile dependencies, keep only Npm/DistTag-tagged, optionally filter to manifest_refresh_targets, clear resolutions, and re-enqueue via enqueue_dependency_with_main to pick fresh manifest versions.
Lockfile re-resolution algorithms
src/install/lockfile.rs
After breadth-first cloning in Cloner::flush(), when bun update --transitive active, invoke transitive re-resolution. pick_better_resolution() scans package_index for highest in-range npm candidates; transitive_re_resolve() walks dependency edges and upgrades npm-range/dist-tag resolutions to best candidates.
Test suite for transitive re-resolution
test/cli/install/bun-update-transitive.test.ts
Helpers createTarball() and startRegistry() enable controllable HTTP registry testing. Six test cases validate baseline resolution, regression reproduction (#24523), core transitive fix, package.json preservation, bare bun update --transitive, and composition with --force. Snapshots include localhost port normalization.

Suggested reviewers

  • RiskyMH
  • dylan-conway
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed Title clearly describes the main change: adding a --transitive flag to bun update for transitive CVE remediation, which is the central feature of this PR.
Description check ✅ Passed Description covers both required sections: 'What does this PR do?' explains the feature in detail, and 'How did you verify your code works?' documents comprehensive testing including 6 passing tests with snapshot regression guards.
Linked Issues check ✅ Passed The PR implements the core requirement from #24523: updating transitive dependencies to highest in-range versions without modifying package.json, matching npm/yarn behavior. Implementation is complete across four layers with proper manifest refresh control and lockfile re-resolution.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing the --transitive flag feature. No unrelated code modifications observed. Workspace recursion and --latest --transitive are explicitly documented as deferred out-of-scope items.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/install/PackageManager/updatePackageJSONAndInstall.rs (1)

604-638: 🧹 Nitpick | 🔵 Trivial | 💤 Low value

Comment may overstate "byte-for-byte" guarantee.

The comment at line 612 states "keep package.json byte-for-byte identical", but the code path still goes through the parse-print cycle at lines 639-669 (which executes unconditionally after this block). While no AST edits are made, the JSON printer could normalize formatting in ways that differ from the original file.

In practice this is likely fine (indentation and trailing newlines are preserved), but consider either:

  1. Adjusting the comment to reflect "semantic content preserved" rather than "byte-for-byte", or
  2. Short-circuiting the print/write entirely for recursive updates by skipping lines 639-669 when is_recursive_update is true
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/install/PackageManager/updatePackageJSONAndInstall.rs` around lines 604 -
638, The comment claiming "byte-for-byte" identical is inaccurate because the
unconditional parse/print later can reformat JSON; update the behavior by
short-circuiting the print/write stage when is_recursive_update is true: after
the block that sets is_recursive_update (and the if/else that may call
PackageJSONEditor::edit or edit_update_no_args), add a guard that when
is_recursive_update is true you skip the subsequent parse/print/write logic (the
code that reads/parses new_package_json and writes it back), so the file is left
untouched, or alternatively change the comment to say "semantic content
preserved" instead of "byte-for-byte" if you prefer not to alter runtime
behavior; reference is_recursive_update and the PackageJSONEditor edit paths to
locate the code to modify.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/cli/install/bun-update-recursive.test.ts`:
- Around line 21-22: Add an explicit 5-minute test timeout by calling
beforeAll(() => setDefaultTimeout(1000 * 60 * 5)) at the top of this test file
(immediately after the imports and before the describe/test blocks); use the
existing beforeAll helper from bun:test and ensure the call is present for both
suites (the initial suite near the top and the second suite referenced around
lines 154-160) so describe/test flows like bunEnv, bunExe, tempDir installations
use the extended timeout.
- Around line 187-311: Add a new test that ensures the direct package ("parent")
stays pinned at 1.0.0 while only the transitive ("dep") is re-resolved when
running `bun update parent --recursive`: create a registry (e.g., reuse pattern
from recDb/limitedDb) where "parent" has only "1.0.0" (so parent cannot move)
and "dep" publishes a new "1.5.0"; install, assert bun.lock initially contains
"dep@1.0.0", then publish dep@1.5.0, run Bun.spawn with cmd [bunExe(), "update",
"parent", "--recursive"], assert success and that the final bun.lock contains
"dep@1.5.0" while package.json and parent in the lock remain at 1.0.0; reference
existing helpers startRegistry, tempDir, Bun.spawn and test name strings to
match style of other tests.

---

Outside diff comments:
In `@src/install/PackageManager/updatePackageJSONAndInstall.rs`:
- Around line 604-638: The comment claiming "byte-for-byte" identical is
inaccurate because the unconditional parse/print later can reformat JSON; update
the behavior by short-circuiting the print/write stage when is_recursive_update
is true: after the block that sets is_recursive_update (and the if/else that may
call PackageJSONEditor::edit or edit_update_no_args), add a guard that when
is_recursive_update is true you skip the subsequent parse/print/write logic (the
code that reads/parses new_package_json and writes it back), so the file is left
untouched, or alternatively change the comment to say "semantic content
preserved" instead of "byte-for-byte" if you prefer not to alter runtime
behavior; reference is_recursive_update and the PackageJSONEditor edit paths to
locate the code to modify.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9871fd3b-220e-4291-9ea8-9a7d10417534

📥 Commits

Reviewing files that changed from the base of the PR and between a43a01b and 542a00e.

📒 Files selected for processing (10)
  • docs/pm/cli/update.mdx
  • src/install/PackageManager.rs
  • src/install/PackageManager/CommandLineArguments.rs
  • src/install/PackageManager/CommandLineArguments.zig
  • src/install/PackageManager/PackageManagerDirectories.rs
  • src/install/PackageManager/PackageManagerEnqueue.rs
  • src/install/PackageManager/install_with_manager.rs
  • src/install/PackageManager/updatePackageJSONAndInstall.rs
  • src/install/lockfile.rs
  • test/cli/install/bun-update-recursive.test.ts

Comment on lines +21 to +22
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { bunEnv, bunExe, tempDir } from "harness";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Set the install-suite timeout explicitly.

This new test/cli/install/ file does not opt into the repo's 5-minute timeout, so these registry + install flows can still hit the default test timeout in debug CI. Please call setDefaultTimeout(1000 * 60 * 5) in the suite setup. As per coding guidelines, "For install CLI tests under test/cli/install/ (including subdirectories like migration/), it’s expected to set a 5-minute default timeout at the top of each test file using beforeAll(() => setDefaultTimeout(1000 * 60 * 5)) because these tests perform network/package-install operations that can exceed Bun’s default timeout."

Also applies to: 154-160

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/cli/install/bun-update-recursive.test.ts` around lines 21 - 22, Add an
explicit 5-minute test timeout by calling beforeAll(() => setDefaultTimeout(1000
* 60 * 5)) at the top of this test file (immediately after the imports and
before the describe/test blocks); use the existing beforeAll helper from
bun:test and ensure the call is present for both suites (the initial suite near
the top and the second suite referenced around lines 154-160) so describe/test
flows like bunEnv, bunExe, tempDir installations use the extended timeout.

Comment on lines +187 to +311
test("repro of #24523: bun update without --recursive leaves stale transitive", async () => {
// Simulate a "stale lockfile" by installing against a registry that only has
// dep@1.0.0, then "publishing" dep@1.5.0 in the registry mutation step.
const limitedDb: RegistryDB = {
parent: { "1.0.0": { dep: "^1.0.0" }, "1.1.0": { dep: "^1.0.0" } },
dep: { "1.0.0": undefined },
};
const { server: s, url } = startRegistry(limitedDb);
try {
using dir = tempDir("update-recursive-repro", {
"package.json": JSON.stringify({ name: "consumer", dependencies: { parent: "^1.0.0" } }),
"bunfig.toml": `[install]\nregistry = "${url}"\ncache = false\nsaveTextLockfile = true\n`,
});

const install = Bun.spawn({
cmd: [bunExe(), "install"],
cwd: dir + "",
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
expect(await install.exited).toBe(0);

const lockBefore = await Bun.file(`${dir}/bun.lock`).text();
expect(lockBefore).toContain("\"dep@1.0.0\"");

// Now "publish" dep@1.5.0.
limitedDb.dep["1.5.0"] = undefined;

// `bun update parent` (without --recursive) bumps package.json but leaves
// the transitive dep at 1.0.0.
const update = Bun.spawn({
cmd: [bunExe(), "update", "parent"],
cwd: dir + "",
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
expect(await update.exited).toBe(0);

const lockAfter = await Bun.file(`${dir}/bun.lock`).text();
// BUG today: dep@1.0.0 remains.
expect(lockAfter).toContain("\"dep@1.0.0\"");
} finally {
s.stop();
}
});

test("bun update parent --recursive re-resolves transitive dep to 1.5.0", async () => {
const recDb: RegistryDB = {
parent: { "1.0.0": { dep: "^1.0.0" }, "1.1.0": { dep: "^1.0.0" } },
dep: { "1.0.0": undefined },
};
const { server: s, url } = startRegistry(recDb);
try {
using dir = tempDir("update-recursive-fix", {
"package.json": JSON.stringify({ name: "consumer", dependencies: { parent: "^1.0.0" } }),
"bunfig.toml": `[install]\nregistry = "${url}"\ncache = false\nsaveTextLockfile = true\n`,
});

const install = Bun.spawn({
cmd: [bunExe(), "install"],
cwd: dir + "",
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
expect(await install.exited).toBe(0);

const lockBefore = await Bun.file(`${dir}/bun.lock`).text();
expect(lockBefore).toContain("\"dep@1.0.0\"");

// Publish dep@1.5.0.
recDb.dep["1.5.0"] = undefined;

const update = Bun.spawn({
cmd: [bunExe(), "update", "parent", "--recursive"],
cwd: dir + "",
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const stderr = await new Response(update.stderr).text();
expect(stderr).not.toContain("error:");
expect(await update.exited).toBe(0);

// Snapshot the full lockfile post-update. This pins down both the
// transitive re-resolution (dep@1.0.0 -> dep@1.5.0) AND the absence
// of any unexpected changes elsewhere. Port is normalized so the
// snapshot is stable across runs.
// Sanity: package.json on disk is preserved (^1.0.0). The lockfile
// workspace-deps section may temporarily show ^1.1.0 (the resolved
// version) — a known, pre-existing lockfile bookkeeping wart in
// `bun update <pkg>` that's orthogonal to --recursive. The snapshot
// below documents the current state; the next `bun install` will
// reconcile workspace deps against package.json.
const pkg = JSON.parse(await Bun.file(`${dir}/package.json`).text());
expect(pkg.dependencies.parent).toBe("^1.0.0");

const lockAfter = (await Bun.file(`${dir}/bun.lock`).text())
.replaceAll(/localhost:\d+/g, "localhost:PORT");
expect(lockAfter).toMatchInlineSnapshot(`
"{
"lockfileVersion": 1,
"configVersion": 1,
"workspaces": {
"": {
"name": "consumer",
"dependencies": {
"parent": "^1.1.0",
},
},
},
"packages": {
"dep": ["dep@1.5.0", "http://localhost:PORT/dep/-/dep-1.5.0.tgz", {}, ""],

"parent": ["parent@1.1.0", "http://localhost:PORT/parent/-/parent-1.1.0.tgz", { "dependencies": { "dep": "^1.0.0" } }, ""],
}
}
"
`);
} finally {
s.stop();
}
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Add a case where the direct target stays pinned and only the transitive changes.

All targeted --recursive tests here also let parent move from 1.0.0 to 1.1.0. That can mask a bug where we only refresh the requested package name and never walk the existing subtree. Please add a regression where parent@1.0.0 remains the best match while dep publishes 1.5.0; that is the case that proves bun update parent --recursive really fixes stale transitives.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/cli/install/bun-update-recursive.test.ts` around lines 187 - 311, Add a
new test that ensures the direct package ("parent") stays pinned at 1.0.0 while
only the transitive ("dep") is re-resolved when running `bun update parent
--recursive`: create a registry (e.g., reuse pattern from recDb/limitedDb) where
"parent" has only "1.0.0" (so parent cannot move) and "dep" publishes a new
"1.5.0"; install, assert bun.lock initially contains "dep@1.0.0", then publish
dep@1.5.0, run Bun.spawn with cmd [bunExe(), "update", "parent", "--recursive"],
assert success and that the final bun.lock contains "dep@1.5.0" while
package.json and parent in the lock remain at 1.0.0; reference existing helpers
startRegistry, tempDir, Bun.spawn and test name strings to match style of other
tests.

`-r, --recursive` is already advertised on `bun update` (from oven-sh#21482) with
the meaning "Update packages in all workspaces" — the workspace-iteration
semantics tracked as oven-sh#23507. Although no consumer reads it on `bun update`
today, repurposing the same flag for transitive recursion would conflict
with that intent and with `bun outdated --recursive` / `bun remove
--recursive` which already implement workspace iteration.

Introduce a dedicated `-t, --transitive` flag for the transitive
CVE-remediation behavior. Restore the original `--recursive` help text on
`bun update` so it remains aligned with the rest of Bun's CLI vocabulary
and with oven-sh#23507's eventual implementation.

This means Bun's `--transitive` corresponds to Yarn's `yarn up --recursive`
(transitive recursion), while Bun's `--recursive` corresponds to pnpm's
`pnpm update --recursive` (workspace iteration). Documented in docs/pm/cli/
update.mdx.
@charpeni charpeni changed the title [install] Add --recursive to bun update for transitive CVE remediation [install] Add --transitive to bun update for transitive CVE remediation May 20, 2026
@charpeni

Copy link
Copy Markdown
Author

Renamed --recursive → --transitive (commit a449911)

Reviewing more carefully: -r, --recursive on bun update isn't unused — it was added in #21482, parsed into Do::RECURSIVE, and reserved for the workspace-iteration work in #23507. The same flag is already implemented with workspace-iteration semantics on bun remove (#27897) and bun outdated.

Reusing it for transitive recursion would have broken that Bun-wide vocabulary, even though Yarn's yarn up --recursive uses the name for exactly this behavior. --recursive is overloaded across the ecosystem (Yarn = transitive, pnpm = workspace iteration), so rather than pick one and break the other, this PR adds a dedicated -t, --transitive flag and leaves --recursive untouched for #23507.

Changes in a449911: new Do::TRANSITIVE bit + accessors; read sites flipped to do_.transitive(); recursive_re_resolve → transitive_re_resolve; test file renamed; original --recursive help text restored. All 6 tests still pass.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
test/cli/install/bun-update-transitive.test.ts (3)

286-288: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Use normalizeBunSnapshot instead of ad-hoc port replacement.

Both snapshot inputs should go through the harness normalizer for stable output across environments.

As per coding guidelines, “Use normalizeBunSnapshot to normalize snapshot output in tests”.

Also applies to: 384-386

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/cli/install/bun-update-transitive.test.ts` around lines 286 - 288, The
test currently mutates lockAfter by replacing ports with a regex instead of
using the harness normalizer; update the assertion to pass the raw file text
through normalizeBunSnapshot and assert that result against the inline snapshot.
Locate the code that reads the lock file (Bun.file(...).text()) and the variable
lockAfter, remove the replaceAll(/localhost:\d+/g, "localhost:PORT") call, and
call normalizeBunSnapshot(lockAfter) (or normalizeBunSnapshot(await
Bun.file(...).text())) before expect(...).toMatchInlineSnapshot(...); apply the
same change to the other occurrence noted (lines ~384-386).

106-107: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

latest dist-tag is computed with lexicographic sort, not semver sort.

Object.keys(...).sort() can mis-order versions like 1.10.0 and 1.9.0, causing incorrect manifest behavior in this test registry.

Suggested fix
-        const versionList = Object.keys(db[name]).sort();
+        const versionList = Object.keys(db[name]).sort((a, b) => {
+          const pa = a.split(".").map(Number);
+          const pb = b.split(".").map(Number);
+          for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
+            const da = pa[i] ?? 0;
+            const db = pb[i] ?? 0;
+            if (da !== db) return da - db;
+          }
+          return 0;
+        });

Also applies to: 119-119

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/cli/install/bun-update-transitive.test.ts` around lines 106 - 107, The
test computes the `latest` dist-tag using a lexicographic sort (versionList =
Object.keys(db[name]).sort()) which misorders semantic versions (e.g., 1.10.0 vs
1.9.0); change the sort to a semver-aware comparator (use
semver.compare/semver.rcompare or an equivalent semver-aware sort) when building
`versionList` and anywhere else the same pattern appears (e.g., the second
occurrence at the other block), so the highest semver version becomes `latest`.
Ensure you import the semver utility used and replace .sort() with the semver
comparator when constructing `versionList` from Object.keys(db[name]).

170-179: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Assert process output before checking exit code in spawn-based tests.

Several tests check await proc.exited first, which makes failures harder to diagnose. Read/assert stdout (and stderr where relevant) before the exit assertion.

As per coding guidelines, “When spawning processes in tests, expect stdout before expecting exit code for more useful error messages”.

Also applies to: 201-209, 247-255, 326-334, 364-372, 423-431

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/cli/install/bun-update-transitive.test.ts` around lines 170 - 179, The
test reads process output after awaiting the exit code which hides useful
failure output; change the order in the spawn-based tests (e.g., the install
Bun.spawn block using variables install, stderr, stdout) to read and assert
stdout/stderr first (await new Response(install.stdout).text() and await new
Response(install.stderr).text() and perform the expect(...) checks) and only
then await install.exited to assert the exit code; apply the same reorder to the
other spawn usages referenced (lines around 201-209, 247-255, 326-334, 364-372,
423-431) so stdout/stderr assertions happen before awaiting exited.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@test/cli/install/bun-update-transitive.test.ts`:
- Around line 286-288: The test currently mutates lockAfter by replacing ports
with a regex instead of using the harness normalizer; update the assertion to
pass the raw file text through normalizeBunSnapshot and assert that result
against the inline snapshot. Locate the code that reads the lock file
(Bun.file(...).text()) and the variable lockAfter, remove the
replaceAll(/localhost:\d+/g, "localhost:PORT") call, and call
normalizeBunSnapshot(lockAfter) (or normalizeBunSnapshot(await
Bun.file(...).text())) before expect(...).toMatchInlineSnapshot(...); apply the
same change to the other occurrence noted (lines ~384-386).
- Around line 106-107: The test computes the `latest` dist-tag using a
lexicographic sort (versionList = Object.keys(db[name]).sort()) which misorders
semantic versions (e.g., 1.10.0 vs 1.9.0); change the sort to a semver-aware
comparator (use semver.compare/semver.rcompare or an equivalent semver-aware
sort) when building `versionList` and anywhere else the same pattern appears
(e.g., the second occurrence at the other block), so the highest semver version
becomes `latest`. Ensure you import the semver utility used and replace .sort()
with the semver comparator when constructing `versionList` from
Object.keys(db[name]).
- Around line 170-179: The test reads process output after awaiting the exit
code which hides useful failure output; change the order in the spawn-based
tests (e.g., the install Bun.spawn block using variables install, stderr,
stdout) to read and assert stdout/stderr first (await new
Response(install.stdout).text() and await new Response(install.stderr).text()
and perform the expect(...) checks) and only then await install.exited to assert
the exit code; apply the same reorder to the other spawn usages referenced
(lines around 201-209, 247-255, 326-334, 364-372, 423-431) so stdout/stderr
assertions happen before awaiting exited.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: baea13b1-a26f-4065-ae08-6b8006fe0465

📥 Commits

Reviewing files that changed from the base of the PR and between 542a00e and a449911.

📒 Files selected for processing (11)
  • docs/pm/cli/update.mdx
  • src/install/PackageManager.rs
  • src/install/PackageManager/CommandLineArguments.rs
  • src/install/PackageManager/CommandLineArguments.zig
  • src/install/PackageManager/PackageManagerDirectories.rs
  • src/install/PackageManager/PackageManagerEnqueue.rs
  • src/install/PackageManager/PackageManagerOptions.rs
  • src/install/PackageManager/install_with_manager.rs
  • src/install/PackageManager/updatePackageJSONAndInstall.rs
  • src/install/lockfile.rs
  • test/cli/install/bun-update-transitive.test.ts

@semperos

Copy link
Copy Markdown

Thanks for this contribution, found this reading your recent post on Bun's limitations in updating transitive dependencies.

@RiskyMH @dylan-conway , charpeni is someone who will follow through on this work.

pull Bot pushed a commit to MC-MAGA/bun that referenced this pull request Aug 14, 2026
…ilter/--catalog, nested overrides, transitive update, and workspace fixes (oven-sh#38333)

Brings Bun's package manager to parity with pnpm for monorepo workflows,
and fixes the bugs found while checking every command against pnpm's
implementation, pnpm's test suites, pnpm's open issue tracker, pnpm's
docs, npm's arborist fixtures, and — for `bun update` — running real
pnpm and Bun side by side on the same projects.

### What does this PR do?

#### New commands

- **`bun dedupe [--check]`** — collapses duplicate versions in
`bun.lock` onto the smallest set that still satisfies every dependent's
range, using only versions already in the lockfile, then installs. Never
downgrades a direct dependency unless that is the only way to drop a
version; keeps patched versions (and anything needed to reach them, and
says so); refuses to run on a lockfile that is behind `package.json`.
`--check` exits 1 without writing.
- **`bun prune [--production | --omit=…] [--dry-run] [--filter <ws>]`**
— removes everything in `node_modules` that the lockfile does not put
there; `--production` leaves exactly what `bun install --production`
would. Hoisted and isolated layouts, Windows junctions and shims,
workspace links, bundled deps; refuses when `package.json` and
`bun.lock` disagree or when `node_modules` was laid out by a different
linker; understands turbo-pruned checkouts.
- **`bun pm licenses [--json] [--prod|--dev] [--long] [--filter <ws>]`**
— installed packages grouped by license, with a `(dev)` marker and
`paths`/`license`/`description` in `--json`.
- **`bun audit fix [--latest] [--dry-run] [--json]`** — moves each
vulnerable package to the lowest safe version its dependents accept, per
installed instance; rewrites exact pins when that is the only way;
`--latest` also rewrites your own declared ranges (root, workspace,
catalog) so a semver-major fix can be taken, and every blocked or
unfixable item is followed by the command that resolves it (`bun audit
fix --latest`, `bun audit --ignore GHSA-…`); re-audits the tree it
actually installed and reports/exits from that second response (npm's
`_submitQuickAudit`), so an advisory that starts at the version it moved
to is not missed; works across registries; security fixes bypass
`minimumReleaseAge` with an annotation. `bun audit --json` honors
`--audit-level`/`--ignore` for its exit code; `--omit` is honored by
`audit` and `licenses`.

#### `bun update` semantics (pnpm's model)

- A bare `bun update` re-resolves **transitive** packages too — every
edge moves to the newest version its own range (or dist-tag) allows, per
dependent, so `bun.lock` no longer stays stale after an update;
overrides/catalogs changed since the last install are honored. From a
workspace member or `--filter`, only what the selected workspaces reach
is re-resolved; from the root, everything.
- `bun update <name>` reaches any depth, matches `npm:` aliases by real
name, updates in place, never adds to `package.json`, and errors on a
name nothing selected depends on. `-r`/`--filter` fan a named update out
across workspaces. `--latest` never downgrades a locked version that is
ahead of the tag, and `update <name> --latest` also refreshes that
package's own dependencies.
- Plain updates keep dist-tag literals and non-caret ranges (`*`, `1.x`,
`^1 || ^2`) exactly as written and only move the lockfile; `--latest`
rewrites them to the resolved version as before. `bun update -i` applies
only what you selected. New: positional patterns (`bun update
'@types/*'`), `--dev`/`--prod`/`--no-optional`, `-L`, `bun up`.
- `package.json` is written after resolution and `bun.lock`'s declared
ranges, overrides and catalogs are re-derived from the final
`package.json`, replacing the per-command literal rewriting; a no-op
update leaves the file byte-identical.

#### Overrides

- **Nested overrides** (oven-sh#6608): npm's nested objects, yarn's `a/b` paths
and pnpm's `a>b` selectors, applied to the direct parent→child edge;
**version-scoped targets** (`"lodash@<4.17.21": "4.17.21"`, the shape
`pnpm audit --fix` writes), matched against the dependent's declared
range as pnpm does. Rules persist inside the `overrides` section and the
file is stamped `lockfileVersion: 3` **only when such rules exist** —
existing lockfiles are byte-identical. Flat overrides additionally fix
`$ref` to workspace-member deps, catalog-valued rules going stale, and
warn on pnpm's `-` / `pkg@` forms.

#### Workspaces and filters

- `bun add|remove|update … --filter <ws>` (also `-F`, also `bun install
<pkg> --filter`) edits the selected workspaces' `package.json` files and
**links only those workspaces**, like `bun install --filter`. Filters
gain pnpm's relation selectors (`foo...`, `...foo`, `foo^...`,
`...^foo`) and `{dir}` subtrees, for the install family **and** `bun run
--filter`; `--filter` may precede the subcommand; every command warns
about patterns that match nothing; `add`/`remove` no longer select the
root implicitly.
- `bun add <pkg> --catalog[=name]` reuses an existing catalog entry,
keeps a range an explicit version fits, catalogs the range a package
already declares, decides per target, and refuses workspace names and
local paths; a plain `bun add` uses a default-catalog entry when one
exists. A package defined in both `catalog` and `catalogs.default` is an
error. `catalog:` peers of registry packages bind to the importer's copy
instead of the root catalog.
- `--frozen-lockfile` / `bun ci` on turbo-pruned monorepos: pruned-away
workspaces are tolerated, a survivor depending on a pruned workspace is
an error, catalog subsets are accepted, and an overrides/catalogs change
is a frozen failure.

#### One output vocabulary

Every command here prints the install family's shapes: header, glyph
rows (`+`/`-`/`↑`, dedupe's `↳ name old → new`), exactly one noun-first
summary line with counts and a duration (`2 duplicate versions removed,
3 packages installed (checked 5 packages) [12ms]`, `N packages removed
(checked C) [t]`), no-ops that say what was checked, remedies printed as
copy-pasteable command lines, warnings as `warn:`, `--silent` printing
nothing, and errors with their remedy together on stderr. Transitive and
named updates render as the summary's `↑` rows (once per package;
`--dry-run` prints the same rows plus `N packages would be updated`);
dedupe reports after the install it triggers, so lifecycle-script output
never splits it. A lockfile whose bytes did not change is no longer
rewritten (`Saved lockfile` only prints on a real write;
`--lockfile-only` no-ops print `Done! Checked N packages (no changes)`).
This came out of running every command against fixtures and comparing
with `install`/`add`/`remove` (95 findings, all fixed).

#### Config precedence

A project's `bunfig.toml` now beats any `.npmrc` (project or user-level)
for the same key (npmrc files → bunfig's set fields → CLI); npmrc-only
settings such as `//host/:_authToken` still attach to bunfig-declared
registries, matched by host and path regardless of how either file
spells the trailing slash.

#### Lockfile migration

- `package-lock.json`: rebuilt around a reachability walk that derives
each resolution from the entry itself. Fixes `git+https://github.com/…`
resolutions being written unparseably (the next install threw the
lockfile away), root `bundleDependencies` migrating to an **empty**
lockfile, lockfileVersion 1 (and npm's upcoming 4) making `bun install`
exit 1 instead of resolving fresh, dependency-level bundles,
`dependencies`+`optionalDependencies` double edges, unreferenced entries
aborting the migration, duplicate packages for identical `name@version`
at nested paths, lost `optionalPeers`, lost integrity when a bundled
copy was seen first, and `overrides` not being carried over. All 57 of
arborist's v2/v3 fixture projects are vendored and migrated under
snapshot.
- `pnpm-lock.yaml` v9: bare-hash `patchedDependencies`, snapshot
aliases, `catalog:default`, recorded tarball URLs, git `path:`,
multi-document files, `runtime:` entries, named registries,
peer-suffixed keys chosen per importer, injected workspaces,
manifest-only importer deps.

#### Isolated linker

- An existing store entry whose dependencies re-resolved (override,
dedupe, update) now has its links refreshed on the next install
(measured cost below). `bun prune` builds the same store the installer
builds, so stale `name@version+<peerhash>` variants left by peer bumps
are removed and a kept package's real entry never is (whether it was
installed with full or `--production` features); on the hoisted linker,
dedupe / audit fix / update delete the nested copies whose rows they
collapsed instead of leaving the old copy loadable.
- Blocked entries resume through per-entry intrusive waiter lists
instead of a scan of every store entry after each completion (robobun's
oven-sh#25983/oven-sh#28425 attempted this). Measured on the reporter's repro from
oven-sh#25799 (2,259 store entries) and a synthetic 6,425-entry monorepo, PR
build vs merge-base build: main-thread CPU in the link phase drops 0.85
→ 0.33 s and 5.5 → 0.85 s (the removed work grows quadratically); wall
time is unchanged with spare cores and 16% / 26% faster pinned to one
CPU, the CI/Docker shape in those reports. (The minute-long installs
originally reported were peer resolution, fixed before this PR's base.)
- Two pre-existing leaks surfaced by the new LSan-enabled tests are
fixed: the header buffer of every authenticated registry request, and
the per-entry lifecycle-script lists.

#### Other bug fixes

`bun add x@npm:pkg` writes a range; `bun add --trust a b` no longer
drops `b` when `a` was already trusted; `bun add x --dev` no longer
rewrote every group in `bun.lock`; `catalog:` peer hoisting;
`dependency::Version::eql` treated all `catalog:` specifiers as equal; a
`file:` package whose dependencies reach itself (its own name, an `npm:`
alias under its own name, two link targets depending on each other — the
shapes a `package-lock.json` migration produces, and oven-sh#25202's
`workspace:.` self-reference) hung `bun install` forever in the hoisting
tree — the migration shapes now install, and oven-sh#25202's literal shape now
terminates with `Workspace dependency "foo" not found` rather than
installing as npm does; a peer of a `file:` package that was only placed
nested was also written to `optionalPeers` in a migrated bun.lock, so
the next `--frozen-lockfile` failed and a plain install rewrote the
lockfile; `catalog:` literals in `bun update`; alias output in the
install summary; help/completions for everything above.

#### Behavior changes to note in the release notes

- `bun update` moves transitive packages; `bun update <name>` no longer
adds an undeclared package (exit 1); `--production`/`--prod` on update
means "only update `dependencies` and `optionalDependencies`" (a group
filter like `--dev`, not the install flag) and `-r`+names with no match
is an error; `-i` updates only the selection.
- Project `bunfig.toml` overrides any `.npmrc`.
- `bun install <pkg> --filter x` edits `x` (not the root); `bun add y
--filter x` no longer installs a package named `x`; `add`/`remove
--filter '*'` no longer includes the root.
- A plain `bun add x` in a workspace whose default catalog lists `x`
writes `catalog:`; `audit fix` may rewrite exact pins;
`--frozen-lockfile --lockfile-only` writes nothing; overrides/catalog
changes fail frozen installs.
- One-time lockfile churn after upgrading for projects with `catalog:`
peers or dead `pkg@range` override rows; lockfiles that use
nested/scoped overrides are v3 and unreadable by older Bun (only when
opted in). Turborepo, Nx and Dependabot have been checked; the needed
upstream changes are open (nrwl/nx#36666 covers v2 and v3;
vercel/turborepo#13740 accepts v3 and preserves the object rows through
prune — turborepo main today parses v2 and rejects v3; dependabot needs
nothing). Note v2 itself only exists on the 1.4 line.
- `bun audit --json` keeps npm's contract: `--audit-level`/`--ignore`
decide the exit code, the JSON document is the full registry report
(closes oven-sh#31013 as won't-change). Automatic removal of stale
`node_modules` entries on plain `bun install` (oven-sh#32974) is separate from
this PR: `bun prune` is the manual form, and dedupe / audit fix / update
now clean up the nested copies they collapse on the hoisted linker;
oven-sh#32974 should reuse prune's planner, and oven-sh#29512 (sbom) is sequenced
after this so it can build on `reachable.rs` instead of carrying its own
walk.
- Deliberately kept where we differ from pnpm: root `bun update` covers
the whole workspace; dependents whose ranges allow follow a moved
version (one copy, not two); `--latest` works on transitive names;
`--no-save` touches neither file; prune deletion failures exit 1; audit
requests stay per-registry.

#### Performance

Measured on a 1,113-package Next/Prisma/MUI app (PR build vs a PR build
of the merge base, interleaved, plus canary and 1.3.14): every hoisted
cell is within noise except no-op install, +0.8 ms (+2%, identical
syscalls); isolated no-op is +1.9 ms (+3.9%) — the deliberate cost of
re-checking existing entries' links every install rather than persisting
a stamp file. Everything added is otherwise off the plain-install path
(gated on the feature being used or on a diff), and id-indexed sets are
bitsets.

### How did you verify your code works?

~1,100 new or ported test cases across the install suites (designed
behavior, cases ported from pnpm's suites, pinning tests for pnpm bugs
this implementation is immune to, arborist's fixtures, and the CI review
findings), all `toStrictEqual`; the whole `test/cli/install` directory
passes locally and the existing suites are unchanged except where a
pre-existing expectation was deliberately changed (each listed above).
`bun update` was additionally verified with a rerunnable differential
harness that runs pnpm 11 and this branch on 26 scenario families
against one registry and diffs the resulting resolutions edge by edge —
after this PR only the deliberate differences above remain. Ecosystem:
Turborepo, Nx and Dependabot were checked against the new lockfile
output.

Co-authored work absorbed with credit: @kjanat's oven-sh#38190 (alias handling,
co-author on the commit), @charpeni's oven-sh#31143 and @crystalin's oven-sh#34407
(both superseded), and the tests of the earlier `bun update` PRs (oven-sh#31752
by @zlotnika, oven-sh#33127, oven-sh#36381, oven-sh#36729, oven-sh#38224). robobun's oven-sh#34688
(folder-dependency cycles; its tests are lifted, co-author on the
commit) and oven-sh#37289 (migrated optionalPeers; its test is lifted,
co-author on the commit) were fixed independently here and are closed by
this PR. oven-sh#28422's quadratic scan is fixed here as well (already closed).

Related but not closed — `bun prune` gives these a manual fix while the
automatic-cleanup asks stay open: oven-sh#8662, oven-sh#26305, oven-sh#29793, oven-sh#21216, oven-sh#16176.
Also related: oven-sh#10930, oven-sh#26970, oven-sh#26751.

Fixes oven-sh#1343
Fixes oven-sh#3605
Fixes oven-sh#14719
Fixes oven-sh#24122
Fixes oven-sh#18612
Fixes oven-sh#20238
Fixes oven-sh#25826
Fixes oven-sh#23615
Fixes oven-sh#26973
Fixes oven-sh#20593
Closes oven-sh#31013
Fixes oven-sh#28959
Fixes oven-sh#28402
Fixes oven-sh#27897
Fixes oven-sh#26675
Fixes oven-sh#10949
Fixes oven-sh#18504
Fixes oven-sh#13388
Fixes oven-sh#24523
Fixes oven-sh#6608
Fixes oven-sh#19059
Fixes oven-sh#16569
Fixes oven-sh#8262
Fixes oven-sh#11901
Fixes oven-sh#13469
Fixes oven-sh#25202
Closes oven-sh#29664
Closes oven-sh#31143
Closes oven-sh#34407
Closes oven-sh#34688
Closes oven-sh#37289
Closes oven-sh#38190

---------

Co-authored-by: Kaj Kowalski <info@kajkowalski.nl>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: robobun <117481402+robobun@users.noreply.github.com>
@Jarred-Sumner

Copy link
Copy Markdown
Collaborator

Thanks for this PR, @charpeni — closing it in favor of #38333, which makes transitive updates the default behavior of bun update instead of an opt-in flag (fixes #24523).

Your walkthrough scenario: parent@^1.0.0 depends on dep@^1.0.0, dep@1.0.0 is locked, and dep@1.5.0 and dep@2.0.0 are published. On that branch:

$ bun update dep
dep@1.0.0 → 1.5.0
  • bun update (bare) does the same for every package in bun.lock, like pnpm update / npm update.
  • dep@2.0.0 is never picked, because parent's range is never widened.
  • package.json stays byte-identical when the name isn't declared there; only bun.lock and node_modules change.
  • No -t/--transitive flag; -r/--recursive still means "all workspaces", as you argued.

One shape doesn't map one-to-one: bun update parent leaves parent's own deps locked, so name the nested package or run a bare bun update. The bun.lock workspace-range wart you flagged is also gone, and your scenarios are covered in test/cli/install/bun-update-transitive.test.ts. #31143 is credited in the #38333 description.

It'll be in the next canary (bun upgrade --canary) and in Bun v1.4 — if it doesn't cover the workflow you had in mind, comment here or on #38333.

(This comment was written by Claude, on behalf of the Bun team.)

@charpeni

Copy link
Copy Markdown
Author

Thanks @Jarred-Sumner, this is better than expected as I wanted this behavior to be the default. 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bun update for transitive dependencies

3 participants