Skip to content
13 changes: 13 additions & 0 deletions src/install/PackageManager/PackageManagerEnqueue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2390,6 +2390,19 @@ fn get_or_put_resolved_package(

let find_result_opt: Option<Npm::FindResult> = match version_result {
Npm::FindVersionResult::Found(result) => Some(result),
Npm::FindVersionResult::FoundLatestFallback(result) => {
let package_name = this.lockfile.str(&name);
this.log_mut().add_warning_fmt(
None,
bun_ast::Loc::EMPTY,
format_args!(
"\"{}\" dist-tags.latest does not match a published version, falling back to {}",
bstr::BStr::new(package_name),
result.version.fmt(&manifest.string_buf),
),
);
Some(result)
}
Npm::FindVersionResult::FoundWithFilter {
result,
newest_filtered,
Expand Down
47 changes: 47 additions & 0 deletions src/install/npm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1535,6 +1535,35 @@
None
}

/// Highest release, or highest prerelease if there are no releases.
/// Both lists are sorted ascending at serialization time.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn find_highest_version(&self, min_age_ms: Option<f64>) -> Option<FindResult<'_>> {
for list in [&self.pkg.releases, &self.pkg.prereleases] {
let keys = list.keys.get(&self.versions);
if keys.is_empty() {
continue;
}
let values = list.values.get(&self.package_versions);
let mut i = keys.len();
while i > 0 {
i -= 1;
let package = &values[i];
if let Some(min_age_ms) = min_age_ms {
if Self::is_package_version_too_recent(package, min_age_ms) {
continue;
}
}
return Some(FindResult {
version: keys[i],
package,
});
}
// every release is age-gated; do not fall through to prereleases
return None;
}
None
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

pub(crate) fn should_exclude_from_age_filter(&self, exclusions: Option<&[&[u8]]>) -> bool {
if let Some(excl) = exclusions {
let pkg_name = self.name();
Expand Down Expand Up @@ -1644,6 +1673,9 @@
result: FindResult<'a>,
newest_filtered: Option<Semver::Version>,
},
/// `dist-tags.latest` did not resolve to a known version; fell back to the
/// highest published version.
Comment thread
robobun marked this conversation as resolved.
Resolved
FoundLatestFallback(FindResult<'a>),
Comment thread
robobun marked this conversation as resolved.
Resolved
Err(FindVersionError),
}

Expand All @@ -1652,6 +1684,7 @@
match self {
FindVersionResult::Found(result) => Some(result),
FindVersionResult::FoundWithFilter { result, .. } => Some(result),
FindVersionResult::FoundLatestFallback(result) => Some(result),
FindVersionResult::Err(_) => None,
}
}
Expand All @@ -1676,6 +1709,20 @@
exclusions: Option<&[&[u8]]>,
) -> FindVersionResult<'_> {
let Some(dist_result) = self.find_by_dist_tag(tag) else {
// https://github.com/oven-sh/bun/issues/12041: match npm and let
// `latest` fall back to the highest published version when the
// manifest's `dist-tags.latest` is stale or missing.
Comment thread
robobun marked this conversation as resolved.
Resolved
if tag == b"latest" {
let min_age_gate_ms = match minimum_release_age_ms {
Some(min_age_ms) if !self.should_exclude_from_age_filter(exclusions) => {
Some(min_age_ms)
}
_ => None,
};

Check warning on line 1721 in src/install/npm.rs

View check run for this annotation

Claude / Claude Code Review

Duplicated min_age_gate_ms computation

nit: this 6-line `min_age_gate_ms` match is byte-identical to the one immediately below at 1728-1733, and neither depends on `dist_result`. Compute it once above the `let Some(dist_result) = self.find_by_dist_tag(tag) else { ... }` and share it between the fallback branch and the main path (the same block also appears in `find_best_version_with_filter`, so a small helper on `PackageManifest` would work too).
Comment thread
robobun marked this conversation as resolved.
Resolved
if let Some(highest) = self.find_highest_version(min_age_gate_ms) {
return FindVersionResult::FoundLatestFallback(highest);
}
}
return FindVersionResult::Err(FindVersionError::NotFound);
};
let min_age_gate_ms = match minimum_release_age_ms {
Expand Down
126 changes: 126 additions & 0 deletions test/cli/install/bun-update.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -527,3 +527,129 @@ it("should print UTF-8 arrows correctly with colors enabled", async () => {
expect(out).not.toContain("â†");
expect(await exited2).toBe(0);
});

// https://github.com/oven-sh/bun/issues/12041
// Registry mirrors/CDNs can briefly serve a manifest whose `dist-tags.latest`
// points at a version that has not yet propagated into `versions`. `bun update
// --latest` should fall back to the highest published version rather than
// aborting the whole update.
it("should fall back to the highest version when dist-tags.latest is not in versions", async () => {
const urls: string[] = [];
// dist-tags.latest = 0.0.7 but only 0.0.3 and 0.0.5 are in `versions`
setHandler(
dummyRegistry(urls, {
"0.0.3": { bin: { "baz-run": "index.js" } },
"0.0.5": { bin: { "baz-exec": "index.js" } },
latest: "0.0.7",
}),
);
await writeFile(
join(package_dir, "package.json"),
JSON.stringify({
name: "foo",
dependencies: { baz: "0.0.3" },
}),
);

const install = spawn({
cmd: [bunExe(), "install", "--linker=hoisted"],
cwd: package_dir,
stdout: "pipe",
stderr: "pipe",
env,
});
const [, installErr, installExit] = await Promise.all([
new Response(install.stdout).text(),
new Response(install.stderr).text(),
install.exited,
]);
expect(installErr).not.toContain("error:");
expect(installExit).toBe(0);

const { stdout, stderr, exited } = spawn({
cmd: [bunExe(), "update", "--latest", "--linker=hoisted"],
cwd: package_dir,
stdout: "pipe",
stderr: "pipe",
env,
});
const [out, err, exitCode] = await Promise.all([new Response(stdout).text(), new Response(stderr).text(), exited]);

expect(err).not.toContain('with tag "latest" not found');
expect(err).not.toContain("failed to resolve");
expect(err).toContain("warn:");
expect(err).toContain("falling back to 0.0.5");
expect(out).toContain("baz 0.0.3 -> 0.0.5");
expect(exitCode).toBe(0);

expect(await file(join(package_dir, "node_modules", "baz", "package.json")).json()).toMatchObject({
name: "baz",
version: "0.0.5",
});
});

it("should fall back to the highest version when the manifest has no dist-tags", async () => {
const urls: string[] = [];
setHandler(async request => {
urls.push(request.url);
const url = request.url.replaceAll("%2f", "/");
if (url.endsWith(".tgz")) {
return new Response(file(join(import.meta.dir, "baz-0.0.3.tgz")));
}
const name = url.slice(url.indexOf("/", root_url.length) + 1);
return new Response(
JSON.stringify({
name,
versions: {
"0.0.3": {
name,
version: "0.0.3",
bin: { "baz-run": "index.js" },
dist: { tarball: `${root_url}/${name}-0.0.3.tgz` },
},
},
// no "dist-tags"
}),
);
});
await writeFile(
join(package_dir, "package.json"),
JSON.stringify({
name: "foo",
dependencies: { baz: "0.0.3" },
}),
);

const install = spawn({
cmd: [bunExe(), "install", "--linker=hoisted"],
cwd: package_dir,
stdout: "pipe",
stderr: "pipe",
env,
});
const [, installErr, installExit] = await Promise.all([
new Response(install.stdout).text(),
new Response(install.stderr).text(),
install.exited,
]);
expect(installErr).not.toContain("error:");
expect(installExit).toBe(0);

const { stdout, stderr, exited } = spawn({
cmd: [bunExe(), "update", "--latest", "--linker=hoisted"],
cwd: package_dir,
stdout: "pipe",
stderr: "pipe",
env,
});
const [out, err, exitCode] = await Promise.all([new Response(stdout).text(), new Response(stderr).text(), exited]);

expect(err).not.toContain('with tag "latest" not found');
expect(err).not.toContain("failed to resolve");
expect(exitCode).toBe(0);

expect(await file(join(package_dir, "node_modules", "baz", "package.json")).json()).toMatchObject({
name: "baz",
version: "0.0.3",
});
Comment thread
robobun marked this conversation as resolved.
Resolved
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Loading