feat(update): update Bun global installations (#1735)
* feat(update): update Bun global installations `rea update` only recognized npm global installations and looked up releases with `npm view`, so a `bun add --global rea-agents` install on a machine without npm failed with `spawn npm ENOENT`. Detect the running package inside Bun's global directory (BUN_INSTALL_GLOBAL_DIR, $BUN_INSTALL/install/global, $XDG_CACHE_HOME/.bun/install/global, ~/.bun/install/global), resolve the latest release with `bun info`, install with `bun add --global --ignore-scripts`, then verify the installed entry point and plan integration maintenance exactly as for npm. Bun commands run inside the owning global directory with BUN_INSTALL_GLOBAL_DIR pinned, so the caller's current project is never selected. A global directory without package.json is not treated as an owned installation: Bun then installs into the nearest ancestor project. npm installations keep their existing commands and messages. * fix(update): gate Bun self-updates on supported CLI versions --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
@@ -1,17 +1,20 @@
|
||||
import { realpath } from "node:fs/promises";
|
||||
import { realpath, stat } from "node:fs/promises";
|
||||
import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
|
||||
import { basename, dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import spawn from "cross-spawn";
|
||||
import { lt, valid } from "semver";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { safeParseJson } from "../domain/safeJson.js";
|
||||
import {
|
||||
updateInstallCommand,
|
||||
type BunInstallation,
|
||||
type NpmInstallation,
|
||||
type ReleaseLookupFailure,
|
||||
type UpdateHost,
|
||||
type UpdateInstallation,
|
||||
type UpdateOutput,
|
||||
} from "./Update.js";
|
||||
import { planIntegrationMaintenance } from "./UpdateMaintenance.js";
|
||||
@@ -23,11 +26,18 @@ export interface NpmInstallationHost {
|
||||
globalPrefix(): Promise<string>;
|
||||
}
|
||||
|
||||
/** Filesystem queries used to identify a Bun global installation. */
|
||||
export interface BunInstallationHost {
|
||||
canonicalPath(path: string): Promise<string>;
|
||||
isFile(path: string): Promise<boolean>;
|
||||
}
|
||||
|
||||
/** Run an updater subprocess with complete diagnostics and isolated machine output. */
|
||||
export const runUpdateCommand = (
|
||||
command: readonly string[],
|
||||
selectedEnvironment: Readonly<NodeJS.ProcessEnv>,
|
||||
output: UpdateOutput = "structured",
|
||||
workingDirectory: string | undefined = undefined,
|
||||
): Promise<Result<string, string>> =>
|
||||
new Promise((resolveResult) => {
|
||||
const [executable, ...args] = command;
|
||||
@@ -42,6 +52,7 @@ export const runUpdateCommand = (
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
env: environment,
|
||||
windowsHide: true,
|
||||
...(workingDirectory === undefined ? {} : { cwd: workingDirectory }),
|
||||
});
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
@@ -102,7 +113,7 @@ export const detectNpmInstallation = async (
|
||||
const prefix = await host.globalPrefix();
|
||||
return prefix.length === 0
|
||||
? undefined
|
||||
: { prefix, packageRoot: canonicalPackageRoot };
|
||||
: { manager: "npm", prefix, packageRoot: canonicalPackageRoot };
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
// The curl installer uses a Unix prefix that may differ from npm's current default.
|
||||
@@ -116,12 +127,80 @@ export const detectNpmInstallation = async (
|
||||
basename(library) !== "lib"
|
||||
)
|
||||
return undefined;
|
||||
return { prefix: dirname(library), packageRoot: canonicalPackageRoot };
|
||||
return {
|
||||
manager: "npm",
|
||||
prefix: dirname(library),
|
||||
packageRoot: canonicalPackageRoot,
|
||||
};
|
||||
};
|
||||
|
||||
const nonemptyEnvironment = (value: string | undefined): string | undefined =>
|
||||
value === undefined || value.length === 0 ? undefined : value;
|
||||
|
||||
/**
|
||||
* Bun's global project directory for the selected environment, in Bun's precedence:
|
||||
* BUN_INSTALL_GLOBAL_DIR, then $BUN_INSTALL/install/global, then
|
||||
* $XDG_CACHE_HOME/.bun/install/global, then ~/.bun/install/global.
|
||||
*/
|
||||
export const bunGlobalDirectory = (
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
platform: NodeJS.Platform,
|
||||
): string => {
|
||||
const explicit = nonemptyEnvironment(environment.BUN_INSTALL_GLOBAL_DIR);
|
||||
if (explicit !== undefined) return explicit;
|
||||
const installRoot = nonemptyEnvironment(environment.BUN_INSTALL);
|
||||
if (installRoot !== undefined) return join(installRoot, "install", "global");
|
||||
const cacheRoot =
|
||||
nonemptyEnvironment(environment.XDG_CACHE_HOME) ??
|
||||
homeDirectoryFromEnvironment(environment, platform);
|
||||
return join(cacheRoot, ".bun", "install", "global");
|
||||
};
|
||||
|
||||
/**
|
||||
* Identify the running package as Bun's global installation.
|
||||
* Bun walks up to an ancestor project when its global directory has no
|
||||
* package.json, so the global manifest must exist before `bun add --global`
|
||||
* can be trusted to update this package root.
|
||||
*/
|
||||
export const detectBunInstallation = async (
|
||||
packageRoot: string,
|
||||
globalDirectory: string,
|
||||
host: BunInstallationHost,
|
||||
): Promise<BunInstallation | undefined> => {
|
||||
try {
|
||||
const canonicalPackageRoot = await host.canonicalPath(packageRoot);
|
||||
const globalPackageRoot = await host.canonicalPath(
|
||||
join(globalDirectory, "node_modules", PRODUCT_IDENTITY.packageName),
|
||||
);
|
||||
if (
|
||||
canonicalPackageRoot !== globalPackageRoot ||
|
||||
!(await host.isFile(join(globalDirectory, "package.json")))
|
||||
)
|
||||
return undefined;
|
||||
return {
|
||||
manager: "bun",
|
||||
globalDirectory,
|
||||
packageRoot: canonicalPackageRoot,
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
// best-effort cleanup: optional install-location probing; unknown means not Bun-managed.
|
||||
void cause;
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const INVALID_NPM_RELEASE_METADATA =
|
||||
"Invalid npm release metadata: expected a version string or a single-element version array.";
|
||||
|
||||
/** bun info arguments for dist-tags.latest; Bun resolves its configured registry. */
|
||||
export const BUN_LATEST_VERSION_COMMAND: readonly string[] = [
|
||||
"bun",
|
||||
"info",
|
||||
PRODUCT_IDENTITY.packageName,
|
||||
"dist-tags.latest",
|
||||
"--json",
|
||||
];
|
||||
|
||||
/** npm view arguments for dist-tags.latest, scoped to the owning prefix when known. */
|
||||
export const npmLatestVersionCommand = (
|
||||
installation: NpmInstallation | undefined,
|
||||
@@ -162,7 +241,7 @@ const readNpmLatestVersion = (value: unknown): string | undefined => {
|
||||
const nonemptyVersion = (value: string): string | undefined =>
|
||||
value.length === 0 ? undefined : value;
|
||||
|
||||
/** Classify npm view output as a version or a lookup failure. */
|
||||
/** Classify `npm view` or `bun info` output as a version or a lookup failure. */
|
||||
export const npmReleaseLookup = (
|
||||
response: Result<string, string>,
|
||||
): Result<string, ReleaseLookupFailure> => {
|
||||
@@ -173,13 +252,51 @@ export const npmReleaseLookup = (
|
||||
: err({ kind: "invalid-metadata", detail: parsed.error });
|
||||
};
|
||||
|
||||
/** Create npm, registry, verification, and read-only maintenance effects. */
|
||||
const isFile = async (path: string): Promise<boolean> => {
|
||||
try {
|
||||
return (await stat(path)).isFile();
|
||||
} catch (cause: unknown) {
|
||||
// best-effort cleanup: a missing or unreadable manifest is not an owned Bun global project.
|
||||
void cause;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Environment and working directory for package-manager subprocesses.
|
||||
* Bun commands run inside the identified global project with that directory
|
||||
* pinned, so the caller's current project and Bun's ancestor search are never
|
||||
* selected. npm keeps the caller's working directory; its prefix is explicit.
|
||||
*/
|
||||
const packageManagerContext = (
|
||||
installation: UpdateInstallation | undefined,
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
): {
|
||||
readonly environment: Readonly<NodeJS.ProcessEnv>;
|
||||
readonly workingDirectory: string | undefined;
|
||||
} =>
|
||||
installation?.manager === "bun"
|
||||
? {
|
||||
environment: {
|
||||
...environment,
|
||||
BUN_INSTALL_GLOBAL_DIR: installation.globalDirectory,
|
||||
},
|
||||
workingDirectory: installation.globalDirectory,
|
||||
}
|
||||
: { environment, workingDirectory: undefined };
|
||||
|
||||
/** Create package-manager, registry, verification, and read-only maintenance effects. */
|
||||
export const systemUpdateHost = (
|
||||
packageRoot = fileURLToPath(new URL("../..", import.meta.url)),
|
||||
home: string | undefined = undefined,
|
||||
environment: Readonly<NodeJS.ProcessEnv> = process.env,
|
||||
): UpdateHost => ({
|
||||
installation: () =>
|
||||
installation: async () =>
|
||||
(await detectBunInstallation(
|
||||
packageRoot,
|
||||
bunGlobalDirectory(environment, process.platform),
|
||||
{ canonicalPath: realpath, isFile },
|
||||
)) ??
|
||||
detectNpmInstallation(packageRoot, {
|
||||
canonicalPath: realpath,
|
||||
globalRoot: () =>
|
||||
@@ -187,18 +304,43 @@ export const systemUpdateHost = (
|
||||
globalPrefix: () =>
|
||||
requireCommandOutput(["npm", "prefix", "--global"], environment),
|
||||
}),
|
||||
latestVersion: async (installation) =>
|
||||
npmReleaseLookup(
|
||||
latestVersion: async (installation) => {
|
||||
const context = packageManagerContext(installation, environment);
|
||||
if (installation?.manager === "bun") {
|
||||
const version = await runUpdateCommand(
|
||||
["bun", "--version"],
|
||||
context.environment,
|
||||
"structured",
|
||||
context.workingDirectory,
|
||||
);
|
||||
if (!version.ok)
|
||||
return err({ kind: "unavailable", detail: version.error });
|
||||
const bunVersion = valid(version.value);
|
||||
// bun info was introduced in 1.2.17; older releases reserve the command.
|
||||
if (bunVersion === null || lt(bunVersion, "1.2.17"))
|
||||
return err({
|
||||
kind: "unsupported-package-manager",
|
||||
detail: `REA updates for Bun global installations require Bun 1.2.17 or later; bun --version returned ${JSON.stringify(version.value)}. Upgrade Bun manually, then rerun rea update.`,
|
||||
});
|
||||
}
|
||||
return npmReleaseLookup(
|
||||
await runUpdateCommand(
|
||||
npmLatestVersionCommand(installation),
|
||||
environment,
|
||||
installation?.manager === "bun"
|
||||
? BUN_LATEST_VERSION_COMMAND
|
||||
: npmLatestVersionCommand(installation),
|
||||
context.environment,
|
||||
"structured",
|
||||
context.workingDirectory,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
installVersion: async (installation, version, output) => {
|
||||
const context = packageManagerContext(installation, environment);
|
||||
const result = await runUpdateCommand(
|
||||
updateInstallCommand(installation, version),
|
||||
environment,
|
||||
context.environment,
|
||||
output,
|
||||
context.workingDirectory,
|
||||
);
|
||||
return result.ok ? ok(undefined) : result;
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user