upgradr 0.2.0 → 0.4.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.
package/README.md CHANGED
@@ -1,11 +1,12 @@
1
1
  # upgradr
2
2
 
3
- Self-update for [Bun](https://bun.sh) CLIs. `upgradr` checks npm for a newer
4
- release, shows a non-blocking startup notice, and upgrades your tool in place —
5
- via `npm`/`bun` global install or by swapping a GitHub release binary.
3
+ Self-update for [Bun](https://bun.sh) & [Node](https://nodejs.org) CLIs. `upgradr`
4
+ checks npm for a newer release, shows a non-blocking startup notice, and upgrades
5
+ your tool in place — via `npm`/`bun` global install or by swapping a GitHub release
6
+ binary.
6
7
 
7
8
  It's the mechanism extracted from [Botholomew](https://github.com/evantahler/botholomew),
8
- generalized so any Bun CLI can drop it in.
9
+ generalized so any Bun or Node CLI can drop it in.
9
10
 
10
11
  ## Features
11
12
 
@@ -19,9 +20,12 @@ generalized so any Bun CLI can drop it in.
19
20
 
20
21
  ```sh
21
22
  bun add upgradr
23
+ # or
24
+ npm install upgradr
22
25
  ```
23
26
 
24
- Requires the Bun runtime (uses `Bun.semver`, `Bun.file`, and `bun`'s shell).
27
+ Runs on both Bun and Node (≥18). The package publishes compiled ESM (`dist/`), so
28
+ Node projects consume it like any other library — no Bun runtime required.
25
29
 
26
30
  ## Usage
27
31
 
@@ -59,7 +63,11 @@ notice.then((msg) => {
59
63
 
60
64
  ```ts
61
65
  const info = await updater.checkForUpdate();
62
- if (info.hasUpdate) {
66
+ if (info.error) {
67
+ // The check didn't complete (offline, rate-limited, registry down, …) —
68
+ // this is distinct from "confirmed up to date".
69
+ console.error(`Update check failed: ${info.error}`);
70
+ } else if (info.hasUpdate) {
63
71
  console.log(`Update available: ${info.currentVersion} → ${info.latestVersion}`);
64
72
  if (info.changelog) console.log(info.changelog);
65
73
  } else if (info.aheadOfLatest) {
@@ -74,7 +82,11 @@ if (info.hasUpdate) {
74
82
  ```ts
75
83
  const result = await updater.upgrade(); // always performs a fresh check first
76
84
 
77
- if (!result.hasUpdate) {
85
+ if (!result.success && !result.performed && result.error) {
86
+ // The check couldn't complete — don't claim "up to date".
87
+ console.error(result.error);
88
+ process.exit(1);
89
+ } else if (!result.hasUpdate) {
78
90
  console.log(`Already up to date (v${result.from})`);
79
91
  } else if (result.method === "local-dev") {
80
92
  console.log("Running from source. Use `git pull && bun install` to update.");
@@ -0,0 +1,7 @@
1
+ import type { UpdateCache } from "./checker.ts";
2
+ /** Load the cached update-check result, if it exists. Never throws. */
3
+ export declare function loadCache(cacheDir: string): Promise<UpdateCache | undefined>;
4
+ /** Save an update-check result to the cache file. Silently ignores write errors. */
5
+ export declare function saveCache(cacheDir: string, cache: UpdateCache): Promise<void>;
6
+ /** Remove the cached update-check result. Never throws. */
7
+ export declare function clearCache(cacheDir: string): Promise<void>;
package/dist/cache.js ADDED
@@ -0,0 +1,35 @@
1
+ import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ function cachePath(cacheDir) {
4
+ return join(cacheDir, "update.json");
5
+ }
6
+ /** Load the cached update-check result, if it exists. Never throws. */
7
+ export async function loadCache(cacheDir) {
8
+ try {
9
+ const text = await readFile(cachePath(cacheDir), "utf8");
10
+ return JSON.parse(text);
11
+ }
12
+ catch {
13
+ // Missing file, unreadable, or invalid JSON — treat as no cache.
14
+ return undefined;
15
+ }
16
+ }
17
+ /** Save an update-check result to the cache file. Silently ignores write errors. */
18
+ export async function saveCache(cacheDir, cache) {
19
+ try {
20
+ await mkdir(cacheDir, { recursive: true });
21
+ await writeFile(cachePath(cacheDir), `${JSON.stringify(cache, null, 2)}\n`);
22
+ }
23
+ catch {
24
+ // Ignore write failures (e.g. permissions).
25
+ }
26
+ }
27
+ /** Remove the cached update-check result. Never throws. */
28
+ export async function clearCache(cacheDir) {
29
+ try {
30
+ await unlink(cachePath(cacheDir));
31
+ }
32
+ catch {
33
+ // Ignore (e.g. file already absent).
34
+ }
35
+ }
@@ -0,0 +1,61 @@
1
+ import type { FetchLike, InstallMethod } from "./config.ts";
2
+ /** The result of checking for an update. */
3
+ export interface UpdateInfo {
4
+ currentVersion: string;
5
+ latestVersion: string;
6
+ /** `latest > current`. */
7
+ hasUpdate: boolean;
8
+ /** `current > latest` — running ahead of the published release (dev build). */
9
+ aheadOfLatest: boolean;
10
+ changelog?: string;
11
+ /**
12
+ * Set when the latest version could not be determined (registry non-OK,
13
+ * network failure, timeout, or offline). When present, `hasUpdate` is `false`
14
+ * because the check did not complete — not because the CLI is current.
15
+ */
16
+ error?: string;
17
+ }
18
+ /** The persisted result of a previous check (see `cache.ts`). */
19
+ export interface UpdateCache {
20
+ lastCheckAt: string;
21
+ latestVersion: string;
22
+ hasUpdate: boolean;
23
+ changelog?: string;
24
+ }
25
+ /** Compare two semver strings. Returns true if `latest > current`. */
26
+ export declare function isNewerVersion(current: string, latest: string): boolean;
27
+ /**
28
+ * Fetch the latest published version from the npm registry. Returns `null` when
29
+ * the version could not be determined (registry non-OK, network failure,
30
+ * timeout, or offline) so callers can distinguish "confirmed current" from
31
+ * "couldn't check".
32
+ */
33
+ export declare function fetchLatestVersion(opts: {
34
+ packageName: string;
35
+ fetchImpl?: FetchLike;
36
+ signal?: AbortSignal;
37
+ }): Promise<string | null>;
38
+ /** Fetch a markdown changelog from GitHub releases between two versions. */
39
+ export declare function fetchChangelog(opts: {
40
+ repo: string;
41
+ fromVersion: string;
42
+ toVersion: string;
43
+ fetchImpl?: FetchLike;
44
+ signal?: AbortSignal;
45
+ }): Promise<string | undefined>;
46
+ /** Check npm for a newer version and fetch the changelog if one is available. */
47
+ export declare function checkForUpdate(opts: {
48
+ packageName: string;
49
+ repo: string;
50
+ currentVersion: string;
51
+ fetchImpl?: FetchLike;
52
+ signal?: AbortSignal;
53
+ }): Promise<UpdateInfo>;
54
+ /** Returns true if the cache is missing or older than `intervalMs`. */
55
+ export declare function needsCheck(cache: UpdateCache | undefined, intervalMs: number): boolean;
56
+ /** Detect how the CLI was installed, from the entry script and exec path. */
57
+ export declare function detectInstallMethod(opts?: {
58
+ localDevEntry?: string;
59
+ argv?: string[];
60
+ execPath?: string;
61
+ }): InstallMethod;
@@ -0,0 +1,120 @@
1
+ import lt from "semver/functions/lt.js";
2
+ /** Compare two semver strings. Returns true if `latest > current`. */
3
+ export function isNewerVersion(current, latest) {
4
+ try {
5
+ return lt(current, latest, { loose: true });
6
+ }
7
+ catch {
8
+ // Unparseable version (e.g. a non-semver git tag) is never "newer".
9
+ return false;
10
+ }
11
+ }
12
+ /**
13
+ * Fetch the latest published version from the npm registry. Returns `null` when
14
+ * the version could not be determined (registry non-OK, network failure,
15
+ * timeout, or offline) so callers can distinguish "confirmed current" from
16
+ * "couldn't check".
17
+ */
18
+ export async function fetchLatestVersion(opts) {
19
+ const doFetch = opts.fetchImpl ?? fetch;
20
+ try {
21
+ const res = await doFetch(`https://registry.npmjs.org/${opts.packageName}/latest`, { signal: opts.signal });
22
+ if (!res.ok)
23
+ return null;
24
+ const data = (await res.json());
25
+ return data.version;
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ }
31
+ /** Fetch a markdown changelog from GitHub releases between two versions. */
32
+ export async function fetchChangelog(opts) {
33
+ const doFetch = opts.fetchImpl ?? fetch;
34
+ try {
35
+ const res = await doFetch(`https://api.github.com/repos/${opts.repo}/releases?per_page=20`, {
36
+ signal: opts.signal,
37
+ headers: { Accept: "application/vnd.github.v3+json" },
38
+ });
39
+ if (!res.ok)
40
+ return undefined;
41
+ const releases = (await res.json());
42
+ const relevant = releases.filter((r) => {
43
+ const v = r.tag_name.replace(/^v/, "");
44
+ return (isNewerVersion(opts.fromVersion, v) &&
45
+ !isNewerVersion(opts.toVersion, v));
46
+ });
47
+ if (relevant.length === 0)
48
+ return undefined;
49
+ return relevant
50
+ .map((r) => `## ${r.tag_name}\n${r.body ?? ""}`)
51
+ .join("\n\n")
52
+ .trim();
53
+ }
54
+ catch {
55
+ return undefined;
56
+ }
57
+ }
58
+ /** Check npm for a newer version and fetch the changelog if one is available. */
59
+ export async function checkForUpdate(opts) {
60
+ const latestVersion = await fetchLatestVersion({
61
+ packageName: opts.packageName,
62
+ fetchImpl: opts.fetchImpl,
63
+ signal: opts.signal,
64
+ });
65
+ if (latestVersion === null) {
66
+ // The check did not complete — surface it rather than reporting "current".
67
+ return {
68
+ currentVersion: opts.currentVersion,
69
+ latestVersion: opts.currentVersion,
70
+ hasUpdate: false,
71
+ aheadOfLatest: false,
72
+ error: `Could not determine the latest version of "${opts.packageName}" from the npm registry.`,
73
+ };
74
+ }
75
+ const hasUpdate = isNewerVersion(opts.currentVersion, latestVersion);
76
+ const aheadOfLatest = isNewerVersion(latestVersion, opts.currentVersion);
77
+ let changelog;
78
+ if (hasUpdate) {
79
+ changelog = await fetchChangelog({
80
+ repo: opts.repo,
81
+ fromVersion: opts.currentVersion,
82
+ toVersion: latestVersion,
83
+ fetchImpl: opts.fetchImpl,
84
+ signal: opts.signal,
85
+ });
86
+ }
87
+ return {
88
+ currentVersion: opts.currentVersion,
89
+ latestVersion,
90
+ hasUpdate,
91
+ aheadOfLatest,
92
+ changelog,
93
+ };
94
+ }
95
+ /** Returns true if the cache is missing or older than `intervalMs`. */
96
+ export function needsCheck(cache, intervalMs) {
97
+ if (!cache?.lastCheckAt)
98
+ return true;
99
+ return Date.now() - new Date(cache.lastCheckAt).getTime() > intervalMs;
100
+ }
101
+ /** Detect how the CLI was installed, from the entry script and exec path. */
102
+ export function detectInstallMethod(opts) {
103
+ const localDevEntry = opts?.localDevEntry ?? "src/cli.ts";
104
+ const script = opts?.argv?.[1] ?? process.argv[1] ?? "";
105
+ const execPath = opts?.execPath ?? process.execPath;
106
+ // Local dev: running the source entry directly, outside node_modules.
107
+ if (script.includes(localDevEntry) && !script.includes("node_modules")) {
108
+ return "local-dev";
109
+ }
110
+ // Compiled binary: execPath is the binary itself (not bun/node).
111
+ if (!execPath.includes("bun") && !execPath.includes("node")) {
112
+ return "binary";
113
+ }
114
+ // Bun global install: path lives under .bun/install or .bun/bin.
115
+ if (script.includes(".bun/install") || script.includes(".bun/bin")) {
116
+ return "bun";
117
+ }
118
+ // npm global install: fallback for node_modules paths.
119
+ return "npm";
120
+ }
@@ -0,0 +1,93 @@
1
+ /** How the current binary/script was installed. */
2
+ export type InstallMethod = "npm" | "bun" | "binary" | "local-dev";
3
+ /**
4
+ * A minimal `fetch`-compatible function. The global `fetch` satisfies this;
5
+ * tests can supply a stub without implementing `fetch.preconnect`.
6
+ */
7
+ export type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
8
+ /** Platform descriptor passed to a custom {@link UpdaterConfig.assetName}. */
9
+ export interface AssetTarget {
10
+ /** `process.platform` value, e.g. `"darwin"`, `"linux"`, `"win32"`. */
11
+ platform: string;
12
+ /** `process.arch` value, e.g. `"arm64"`, `"x64"`. */
13
+ arch: string;
14
+ }
15
+ /** Data passed to a custom {@link UpdaterConfig.formatNotice} renderer. */
16
+ export interface NoticeContext {
17
+ /** The currently-running version. */
18
+ currentVersion: string;
19
+ /** The newer version available. */
20
+ latestVersion: string;
21
+ /** Release changelog, when one was fetched. */
22
+ changelog?: string;
23
+ /** Display name for the CLI (see {@link UpdaterConfig.cliName}). */
24
+ cliName: string;
25
+ }
26
+ /**
27
+ * Configuration for {@link createUpdater}. Every value that would otherwise be
28
+ * hardcoded to a specific project (repo, package name, cache location, …) is a
29
+ * parameter here so the same logic works for any Bun CLI.
30
+ */
31
+ export interface UpdaterConfig {
32
+ /** The currently-running version, e.g. your `package.json` version. */
33
+ currentVersion: string;
34
+ /** npm package name — used for the registry lookup and `install -g <pkg>@<v>`. */
35
+ packageName: string;
36
+ /** GitHub repository as `"owner/name"` — used for release binaries + changelog. */
37
+ repo: string;
38
+ /**
39
+ * Prefix for GitHub release binary assets. The default asset name is
40
+ * `<binaryName>-<os>-<arch>[.exe]` (os ∈ darwin|linux|windows).
41
+ */
42
+ binaryName: string;
43
+ /** Directory that holds the `update.json` check cache (e.g. `~/.myapp`). */
44
+ cacheDir: string;
45
+ /** Display name used in notices and the "Run `<cliName> upgrade`" hint. Defaults to {@link packageName}. */
46
+ cliName?: string;
47
+ /** Env var name that, when set to `"1"`, disables the background check. Omit to never opt out. */
48
+ noUpdateCheckEnv?: string;
49
+ /** Substring of the entry script that marks a local source checkout. Defaults to `"src/cli.ts"`. */
50
+ localDevEntry?: string;
51
+ /** How long a cached check stays fresh, in ms. Defaults to 24h. */
52
+ checkIntervalMs?: number;
53
+ /** Timeout for the background network check, in ms. Defaults to 5000. */
54
+ timeoutMs?: number;
55
+ /** Commands for which the background notice is suppressed. Defaults to `["check-update", "upgrade"]`. */
56
+ backgroundSkipCommands?: string[];
57
+ /**
58
+ * Render the whole background notice string. Receives the update details and
59
+ * returns the text shown to the user. Defaults to the built-in {@link formatNotice},
60
+ * which you can import and compose with (e.g. prefix or suffix its output).
61
+ */
62
+ formatNotice?: (ctx: NoticeContext) => string;
63
+ /** Override the full release asset name for a platform. */
64
+ assetName?: (target: AssetTarget) => string;
65
+ /** Injectable `fetch` (for testing). Defaults to the global `fetch`. */
66
+ fetchImpl?: FetchLike;
67
+ /** Called with human-readable progress messages (e.g. sudo prompts). Defaults to a no-op. */
68
+ onProgress?: (message: string) => void;
69
+ }
70
+ /** {@link UpdaterConfig} with defaults applied. */
71
+ export interface ResolvedConfig {
72
+ currentVersion: string;
73
+ packageName: string;
74
+ repo: string;
75
+ binaryName: string;
76
+ cacheDir: string;
77
+ cliName: string;
78
+ noUpdateCheckEnv: string | undefined;
79
+ localDevEntry: string;
80
+ checkIntervalMs: number;
81
+ timeoutMs: number;
82
+ backgroundSkipCommands: string[];
83
+ formatNotice: ((ctx: NoticeContext) => string) | undefined;
84
+ assetName: ((target: AssetTarget) => string) | undefined;
85
+ fetchImpl: FetchLike;
86
+ onProgress: (message: string) => void;
87
+ }
88
+ export declare const DEFAULT_CHECK_INTERVAL_MS: number;
89
+ export declare const DEFAULT_TIMEOUT_MS = 5000;
90
+ export declare const DEFAULT_LOCAL_DEV_ENTRY = "src/cli.ts";
91
+ export declare const DEFAULT_BACKGROUND_SKIP_COMMANDS: string[];
92
+ /** Apply defaults to a user-supplied {@link UpdaterConfig}. */
93
+ export declare function resolveConfig(config: UpdaterConfig): ResolvedConfig;
package/dist/config.js ADDED
@@ -0,0 +1,24 @@
1
+ export const DEFAULT_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
2
+ export const DEFAULT_TIMEOUT_MS = 5_000;
3
+ export const DEFAULT_LOCAL_DEV_ENTRY = "src/cli.ts";
4
+ export const DEFAULT_BACKGROUND_SKIP_COMMANDS = ["check-update", "upgrade"];
5
+ /** Apply defaults to a user-supplied {@link UpdaterConfig}. */
6
+ export function resolveConfig(config) {
7
+ return {
8
+ currentVersion: config.currentVersion,
9
+ packageName: config.packageName,
10
+ repo: config.repo,
11
+ binaryName: config.binaryName,
12
+ cacheDir: config.cacheDir,
13
+ cliName: config.cliName ?? config.packageName,
14
+ noUpdateCheckEnv: config.noUpdateCheckEnv,
15
+ localDevEntry: config.localDevEntry ?? DEFAULT_LOCAL_DEV_ENTRY,
16
+ checkIntervalMs: config.checkIntervalMs ?? DEFAULT_CHECK_INTERVAL_MS,
17
+ timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,
18
+ backgroundSkipCommands: config.backgroundSkipCommands ?? DEFAULT_BACKGROUND_SKIP_COMMANDS,
19
+ formatNotice: config.formatNotice,
20
+ assetName: config.assetName,
21
+ fetchImpl: config.fetchImpl ?? fetch,
22
+ onProgress: config.onProgress ?? (() => { }),
23
+ };
24
+ }
@@ -0,0 +1,55 @@
1
+ import { type UpdateCache, type UpdateInfo } from "./checker.ts";
2
+ import { type InstallMethod, type ResolvedConfig, type UpdaterConfig } from "./config.ts";
3
+ export { fetchChangelog, fetchLatestVersion, isNewerVersion, type UpdateCache, type UpdateInfo, } from "./checker.ts";
4
+ export type { AssetTarget, FetchLike, InstallMethod, NoticeContext, ResolvedConfig, UpdaterConfig, } from "./config.ts";
5
+ export { formatNotice } from "./notice.ts";
6
+ export { type InstallOutcome, platformArtifactName, } from "./upgrade.ts";
7
+ /** The outcome of {@link Updater.upgrade}. */
8
+ export interface UpgradeResult {
9
+ /** How the running CLI was installed. */
10
+ method: InstallMethod;
11
+ /** The version that was running. */
12
+ from: string;
13
+ /** The latest published version. */
14
+ to: string;
15
+ /** Whether a newer version is available. */
16
+ hasUpdate: boolean;
17
+ /** Whether an install was attempted (false when already current or local-dev). */
18
+ performed: boolean;
19
+ /** Whether the upgrade succeeded (true and un-performed means already current). */
20
+ success: boolean;
21
+ /** Error detail when `success` is false. */
22
+ error?: string;
23
+ }
24
+ /** A configured self-updater. Returned by {@link createUpdater}. */
25
+ export interface Updater {
26
+ /** The resolved configuration (with defaults applied). */
27
+ readonly config: ResolvedConfig;
28
+ /** Perform a fresh update check against npm (and GitHub for the changelog). */
29
+ checkForUpdate(signal?: AbortSignal): Promise<UpdateInfo>;
30
+ /** Whether a cached result is missing or stale. */
31
+ needsCheck(cache?: UpdateCache): boolean;
32
+ /** Detect how the CLI was installed. */
33
+ detectInstallMethod(): InstallMethod;
34
+ /** Load the persisted check cache. */
35
+ loadCache(): Promise<UpdateCache | undefined>;
36
+ /** Persist a check result. */
37
+ saveCache(cache: UpdateCache): Promise<void>;
38
+ /** Remove the persisted check cache. */
39
+ clearCache(): Promise<void>;
40
+ /** Non-blocking startup notice (cache-first). Returns a string or `null`. */
41
+ maybeBackgroundNotice(overrides?: {
42
+ env?: NodeJS.ProcessEnv;
43
+ argv?: string[];
44
+ isTTY?: boolean;
45
+ }): Promise<string | null>;
46
+ /**
47
+ * Upgrade in place. Always performs a fresh check first (never trusting a
48
+ * possibly-stale cache), then installs via the detected method. The caller
49
+ * owns all presentation — this returns a result and never writes to the
50
+ * console or exits the process.
51
+ */
52
+ upgrade(): Promise<UpgradeResult>;
53
+ }
54
+ /** Create a self-updater bound to your project's {@link UpdaterConfig}. */
55
+ export declare function createUpdater(config: UpdaterConfig): Updater;
package/dist/index.js ADDED
@@ -0,0 +1,94 @@
1
+ import { clearCache, loadCache, saveCache } from "./cache.js";
2
+ import { checkForUpdate as checkForUpdateImpl, detectInstallMethod as detectInstallMethodImpl, needsCheck as needsCheckImpl, } from "./checker.js";
3
+ import { resolveConfig, } from "./config.js";
4
+ import { maybeBackgroundNotice } from "./notice.js";
5
+ import { upgradeFromBinary, upgradeWithPackageManager, } from "./upgrade.js";
6
+ export { fetchChangelog, fetchLatestVersion, isNewerVersion, } from "./checker.js";
7
+ export { formatNotice } from "./notice.js";
8
+ export { platformArtifactName, } from "./upgrade.js";
9
+ /** Create a self-updater bound to your project's {@link UpdaterConfig}. */
10
+ export function createUpdater(config) {
11
+ const cfg = resolveConfig(config);
12
+ const checkFresh = (signal) => checkForUpdateImpl({
13
+ packageName: cfg.packageName,
14
+ repo: cfg.repo,
15
+ currentVersion: cfg.currentVersion,
16
+ fetchImpl: cfg.fetchImpl,
17
+ signal,
18
+ });
19
+ return {
20
+ config: cfg,
21
+ checkForUpdate: checkFresh,
22
+ needsCheck: (cache) => needsCheckImpl(cache, cfg.checkIntervalMs),
23
+ detectInstallMethod: () => detectInstallMethodImpl({ localDevEntry: cfg.localDevEntry }),
24
+ loadCache: () => loadCache(cfg.cacheDir),
25
+ saveCache: (cache) => saveCache(cfg.cacheDir, cache),
26
+ clearCache: () => clearCache(cfg.cacheDir),
27
+ maybeBackgroundNotice: (overrides) => maybeBackgroundNotice(cfg, overrides),
28
+ async upgrade() {
29
+ // Always re-check: the background cache may be fresh but stale relative
30
+ // to a release that shipped since the last check.
31
+ const info = await checkFresh();
32
+ const method = detectInstallMethodImpl({
33
+ localDevEntry: cfg.localDevEntry,
34
+ });
35
+ const base = {
36
+ method,
37
+ from: cfg.currentVersion,
38
+ to: info.latestVersion,
39
+ hasUpdate: info.hasUpdate,
40
+ };
41
+ // The check itself failed — don't cache a bogus result or report success.
42
+ if (info.error) {
43
+ return { ...base, performed: false, success: false, error: info.error };
44
+ }
45
+ await saveCache(cfg.cacheDir, {
46
+ lastCheckAt: new Date().toISOString(),
47
+ latestVersion: info.latestVersion,
48
+ hasUpdate: info.hasUpdate,
49
+ changelog: info.changelog,
50
+ });
51
+ if (!info.hasUpdate) {
52
+ return { ...base, performed: false, success: true };
53
+ }
54
+ if (method === "local-dev") {
55
+ return { ...base, performed: false, success: false };
56
+ }
57
+ let outcome;
58
+ switch (method) {
59
+ case "bun":
60
+ outcome = await upgradeWithPackageManager("bun", [
61
+ "install",
62
+ "-g",
63
+ `${cfg.packageName}@${info.latestVersion}`,
64
+ ]);
65
+ break;
66
+ case "npm":
67
+ outcome = await upgradeWithPackageManager("npm", [
68
+ "install",
69
+ "-g",
70
+ `${cfg.packageName}@${info.latestVersion}`,
71
+ ]);
72
+ break;
73
+ case "binary":
74
+ outcome = await upgradeFromBinary({
75
+ repo: cfg.repo,
76
+ latestVersion: info.latestVersion,
77
+ binaryName: cfg.binaryName,
78
+ assetName: cfg.assetName,
79
+ fetchImpl: cfg.fetchImpl,
80
+ onProgress: cfg.onProgress,
81
+ });
82
+ break;
83
+ }
84
+ if (outcome.success)
85
+ await clearCache(cfg.cacheDir);
86
+ return {
87
+ ...base,
88
+ performed: true,
89
+ success: outcome.success,
90
+ error: outcome.error,
91
+ };
92
+ },
93
+ };
94
+ }
@@ -0,0 +1,16 @@
1
+ import type { NoticeContext, ResolvedConfig } from "./config.ts";
2
+ /** Format the "update available" notice shown on startup. */
3
+ export declare function formatNotice(ctx: NoticeContext): string;
4
+ /**
5
+ * Non-blocking background update check. Returns a formatted notice string if an
6
+ * update is available, or `null` otherwise. Never throws. Uses a fresh (<24h)
7
+ * cache when present; otherwise performs a network check bounded by `timeoutMs`
8
+ * and refreshes the cache.
9
+ *
10
+ * `env`, `argv`, and `isTTY` are injectable for testing.
11
+ */
12
+ export declare function maybeBackgroundNotice(cfg: ResolvedConfig, overrides?: {
13
+ env?: NodeJS.ProcessEnv;
14
+ argv?: string[];
15
+ isTTY?: boolean;
16
+ }): Promise<string | null>;
package/dist/notice.js ADDED
@@ -0,0 +1,96 @@
1
+ import { cyan, dim, yellow } from "ansis";
2
+ import { loadCache, saveCache } from "./cache.js";
3
+ import { checkForUpdate, needsCheck } from "./checker.js";
4
+ /** Format the "update available" notice shown on startup. */
5
+ export function formatNotice(ctx) {
6
+ const lines = [
7
+ "",
8
+ yellow(`Update available: ${ctx.currentVersion} → ${ctx.latestVersion}`),
9
+ ];
10
+ if (ctx.changelog) {
11
+ lines.push("");
12
+ lines.push(dim(ctx.changelog));
13
+ }
14
+ lines.push("");
15
+ lines.push(cyan(`Run \`${ctx.cliName} upgrade\` to update`));
16
+ lines.push("");
17
+ return lines.join("\n");
18
+ }
19
+ /**
20
+ * Non-blocking background update check. Returns a formatted notice string if an
21
+ * update is available, or `null` otherwise. Never throws. Uses a fresh (<24h)
22
+ * cache when present; otherwise performs a network check bounded by `timeoutMs`
23
+ * and refreshes the cache.
24
+ *
25
+ * `env`, `argv`, and `isTTY` are injectable for testing.
26
+ */
27
+ export async function maybeBackgroundNotice(cfg, overrides) {
28
+ try {
29
+ const env = overrides?.env ?? process.env;
30
+ const argv = overrides?.argv ?? process.argv;
31
+ const isTTY = overrides?.isTTY ?? process.stderr.isTTY ?? false;
32
+ // Opt-out via env var.
33
+ if (cfg.noUpdateCheckEnv && env[cfg.noUpdateCheckEnv] === "1")
34
+ return null;
35
+ // Skip when running an update-related command.
36
+ const args = argv.slice(2);
37
+ const command = args.find((a) => !a.startsWith("-"));
38
+ if (command && cfg.backgroundSkipCommands.includes(command))
39
+ return null;
40
+ // Only show in an interactive terminal.
41
+ if (!isTTY)
42
+ return null;
43
+ const render = cfg.formatNotice ?? formatNotice;
44
+ const cache = await loadCache(cfg.cacheDir);
45
+ if (!needsCheck(cache, cfg.checkIntervalMs)) {
46
+ // Cache is fresh — use the cached result.
47
+ if (cache?.hasUpdate) {
48
+ return render({
49
+ currentVersion: cfg.currentVersion,
50
+ latestVersion: cache.latestVersion,
51
+ changelog: cache.changelog,
52
+ cliName: cfg.cliName,
53
+ });
54
+ }
55
+ return null;
56
+ }
57
+ // Cache is stale or missing — check with a timeout.
58
+ const controller = new AbortController();
59
+ const timeout = setTimeout(() => controller.abort(), cfg.timeoutMs);
60
+ try {
61
+ const info = await checkForUpdate({
62
+ packageName: cfg.packageName,
63
+ repo: cfg.repo,
64
+ currentVersion: cfg.currentVersion,
65
+ fetchImpl: cfg.fetchImpl,
66
+ signal: controller.signal,
67
+ });
68
+ // Only cache a completed check — a failed check must not suppress the
69
+ // next attempt (nor be silently reported as "up to date").
70
+ if (info.error)
71
+ return null;
72
+ const newCache = {
73
+ lastCheckAt: new Date().toISOString(),
74
+ latestVersion: info.latestVersion,
75
+ hasUpdate: info.hasUpdate,
76
+ changelog: info.changelog,
77
+ };
78
+ await saveCache(cfg.cacheDir, newCache);
79
+ if (info.hasUpdate) {
80
+ return render({
81
+ currentVersion: cfg.currentVersion,
82
+ latestVersion: info.latestVersion,
83
+ changelog: info.changelog,
84
+ cliName: cfg.cliName,
85
+ });
86
+ }
87
+ }
88
+ finally {
89
+ clearTimeout(timeout);
90
+ }
91
+ return null;
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ }
@@ -0,0 +1,30 @@
1
+ import type { AssetTarget, FetchLike } from "./config.ts";
2
+ /** Outcome of a binary or package-manager install attempt. */
3
+ export interface InstallOutcome {
4
+ success: boolean;
5
+ error?: string;
6
+ }
7
+ /**
8
+ * Build the GitHub release asset name for the current platform.
9
+ * Defaults to `<binaryName>-<os>-<arch>[.exe]`, or delegates to `assetName`.
10
+ */
11
+ export declare function platformArtifactName(opts: {
12
+ binaryName: string;
13
+ platform?: string;
14
+ arch?: string;
15
+ assetName?: (target: AssetTarget) => string;
16
+ }): string;
17
+ /** Run a global install via a package manager, e.g. `npm install -g pkg@1.2.3`. */
18
+ export declare function upgradeWithPackageManager(command: string, args: string[]): Promise<InstallOutcome>;
19
+ /**
20
+ * Download the release binary for `latestVersion` and swap it into place at
21
+ * `process.execPath`, falling back to `sudo mv` when a plain move is denied.
22
+ */
23
+ export declare function upgradeFromBinary(opts: {
24
+ repo: string;
25
+ latestVersion: string;
26
+ binaryName: string;
27
+ assetName?: (target: AssetTarget) => string;
28
+ fetchImpl?: FetchLike;
29
+ onProgress?: (message: string) => void;
30
+ }): Promise<InstallOutcome>;
@@ -0,0 +1,103 @@
1
+ import { execFile } from "node:child_process";
2
+ import { chmod, unlink, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { promisify } from "node:util";
6
+ const execFileAsync = promisify(execFile);
7
+ /**
8
+ * Run a command without throwing, returning its exit code. Cross-runtime
9
+ * (Node + Bun) replacement for Bun's `$`…`.nothrow()`.
10
+ */
11
+ async function run(command, args) {
12
+ try {
13
+ await execFileAsync(command, args);
14
+ return { exitCode: 0 };
15
+ }
16
+ catch (err) {
17
+ const code = err.code;
18
+ return { exitCode: typeof code === "number" ? code : 1 };
19
+ }
20
+ }
21
+ /**
22
+ * Build the GitHub release asset name for the current platform.
23
+ * Defaults to `<binaryName>-<os>-<arch>[.exe]`, or delegates to `assetName`.
24
+ */
25
+ export function platformArtifactName(opts) {
26
+ const platform = opts.platform ?? process.platform;
27
+ const arch = opts.arch ?? process.arch;
28
+ if (opts.assetName)
29
+ return opts.assetName({ platform, arch });
30
+ let os;
31
+ let ext = "";
32
+ switch (platform) {
33
+ case "darwin":
34
+ os = "darwin";
35
+ break;
36
+ case "win32":
37
+ os = "windows";
38
+ ext = ".exe";
39
+ break;
40
+ default:
41
+ os = "linux";
42
+ break;
43
+ }
44
+ const normalizedArch = arch === "arm64" ? "arm64" : "x64";
45
+ return `${opts.binaryName}-${os}-${normalizedArch}${ext}`;
46
+ }
47
+ /** Run a global install via a package manager, e.g. `npm install -g pkg@1.2.3`. */
48
+ export async function upgradeWithPackageManager(command, args) {
49
+ const result = await run(command, args);
50
+ return result.exitCode === 0
51
+ ? { success: true }
52
+ : {
53
+ success: false,
54
+ error: `${command} exited with code ${result.exitCode}`,
55
+ };
56
+ }
57
+ /**
58
+ * Download the release binary for `latestVersion` and swap it into place at
59
+ * `process.execPath`, falling back to `sudo mv` when a plain move is denied.
60
+ */
61
+ export async function upgradeFromBinary(opts) {
62
+ const doFetch = opts.fetchImpl ?? fetch;
63
+ const onProgress = opts.onProgress ?? (() => { });
64
+ const artifact = platformArtifactName({
65
+ binaryName: opts.binaryName,
66
+ assetName: opts.assetName,
67
+ });
68
+ const tag = `v${opts.latestVersion}`;
69
+ const url = `https://github.com/${opts.repo}/releases/download/${tag}/${artifact}`;
70
+ const tmpPath = join(tmpdir(), `${opts.binaryName}-upgrade-${Date.now()}`);
71
+ const targetPath = process.execPath;
72
+ try {
73
+ const res = await doFetch(url);
74
+ if (!res.ok) {
75
+ return {
76
+ success: false,
77
+ error: `Failed to download binary: HTTP ${res.status}`,
78
+ };
79
+ }
80
+ const bytes = await res.arrayBuffer();
81
+ await writeFile(tmpPath, Buffer.from(bytes));
82
+ await chmod(tmpPath, 0o755);
83
+ // Try to move into place (mv handles cross-filesystem moves).
84
+ const mv = await run("mv", [tmpPath, targetPath]);
85
+ if (mv.exitCode !== 0) {
86
+ // Fall back to sudo.
87
+ onProgress("Requires elevated permissions...");
88
+ const sudo = await run("sudo", ["mv", tmpPath, targetPath]);
89
+ if (sudo.exitCode !== 0) {
90
+ return {
91
+ success: false,
92
+ error: "Failed to install binary. Try running with sudo.",
93
+ };
94
+ }
95
+ }
96
+ return { success: true };
97
+ }
98
+ catch (err) {
99
+ // Clean up temp file.
100
+ await unlink(tmpPath).catch(() => { });
101
+ return { success: false, error: `Failed to upgrade binary: ${err}` };
102
+ }
103
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "upgradr",
3
- "version": "0.2.0",
4
- "description": "Self-update for Bun CLIs: check npm for a newer release, then upgrade in place via npm/bun or a GitHub release binary.",
3
+ "version": "0.4.0",
4
+ "description": "Self-update for Bun & Node CLIs: check npm for a newer release, then upgrade in place via npm/bun or a GitHub release binary.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Evan Tahler",
@@ -24,22 +24,34 @@
24
24
  "url": "https://github.com/evantahler/upgradr/issues"
25
25
  },
26
26
  "exports": {
27
- ".": "./src/index.ts"
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "import": "./dist/index.js"
30
+ }
28
31
  },
29
- "main": "./src/index.ts",
30
- "types": "./src/index.ts",
31
- "files": ["src", "README.md", "LICENSE"],
32
+ "main": "./dist/index.js",
33
+ "module": "./dist/index.js",
34
+ "types": "./dist/index.d.ts",
35
+ "engines": {
36
+ "node": ">=18"
37
+ },
38
+ "files": ["dist", "src", "README.md", "LICENSE"],
32
39
  "scripts": {
33
40
  "test": "bun test",
34
41
  "lint": "tsc --noEmit && biome check .",
35
- "format": "biome check --write ."
42
+ "format": "biome check --write .",
43
+ "build": "tsc -p tsconfig.build.json",
44
+ "smoke": "node scripts/node-smoke.js",
45
+ "prepublishOnly": "npm run build"
36
46
  },
37
47
  "dependencies": {
38
- "ansis": "^4.3.1"
48
+ "ansis": "^4.3.1",
49
+ "semver": "^7.8.5"
39
50
  },
40
51
  "devDependencies": {
41
52
  "@biomejs/biome": "^2.4.16",
42
53
  "@types/bun": "^1.3.14",
54
+ "@types/semver": "^7.7.1",
43
55
  "typescript": "^6.0.3"
44
56
  }
45
57
  }
package/src/cache.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
1
2
  import { join } from "node:path";
2
3
  import type { UpdateCache } from "./checker.ts";
3
4
 
@@ -10,10 +11,10 @@ export async function loadCache(
10
11
  cacheDir: string,
11
12
  ): Promise<UpdateCache | undefined> {
12
13
  try {
13
- const file = Bun.file(cachePath(cacheDir));
14
- if (!(await file.exists())) return undefined;
15
- return JSON.parse(await file.text()) as UpdateCache;
14
+ const text = await readFile(cachePath(cacheDir), "utf8");
15
+ return JSON.parse(text) as UpdateCache;
16
16
  } catch {
17
+ // Missing file, unreadable, or invalid JSON — treat as no cache.
17
18
  return undefined;
18
19
  }
19
20
  }
@@ -24,9 +25,8 @@ export async function saveCache(
24
25
  cache: UpdateCache,
25
26
  ): Promise<void> {
26
27
  try {
27
- const { mkdir } = await import("node:fs/promises");
28
28
  await mkdir(cacheDir, { recursive: true });
29
- await Bun.write(cachePath(cacheDir), `${JSON.stringify(cache, null, 2)}\n`);
29
+ await writeFile(cachePath(cacheDir), `${JSON.stringify(cache, null, 2)}\n`);
30
30
  } catch {
31
31
  // Ignore write failures (e.g. permissions).
32
32
  }
@@ -35,12 +35,8 @@ export async function saveCache(
35
35
  /** Remove the cached update-check result. Never throws. */
36
36
  export async function clearCache(cacheDir: string): Promise<void> {
37
37
  try {
38
- const file = Bun.file(cachePath(cacheDir));
39
- if (await file.exists()) {
40
- const { unlink } = await import("node:fs/promises");
41
- await unlink(cachePath(cacheDir));
42
- }
38
+ await unlink(cachePath(cacheDir));
43
39
  } catch {
44
- // Ignore.
40
+ // Ignore (e.g. file already absent).
45
41
  }
46
42
  }
package/src/checker.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import lt from "semver/functions/lt.js";
1
2
  import type { FetchLike, InstallMethod } from "./config.ts";
2
3
 
3
4
  /** The result of checking for an update. */
@@ -9,6 +10,12 @@ export interface UpdateInfo {
9
10
  /** `current > latest` — running ahead of the published release (dev build). */
10
11
  aheadOfLatest: boolean;
11
12
  changelog?: string;
13
+ /**
14
+ * Set when the latest version could not be determined (registry non-OK,
15
+ * network failure, timeout, or offline). When present, `hasUpdate` is `false`
16
+ * because the check did not complete — not because the CLI is current.
17
+ */
18
+ error?: string;
12
19
  }
13
20
 
14
21
  /** The persisted result of a previous check (see `cache.ts`). */
@@ -21,27 +28,36 @@ export interface UpdateCache {
21
28
 
22
29
  /** Compare two semver strings. Returns true if `latest > current`. */
23
30
  export function isNewerVersion(current: string, latest: string): boolean {
24
- return Bun.semver.order(current, latest) === -1;
31
+ try {
32
+ return lt(current, latest, { loose: true });
33
+ } catch {
34
+ // Unparseable version (e.g. a non-semver git tag) is never "newer".
35
+ return false;
36
+ }
25
37
  }
26
38
 
27
- /** Fetch the latest published version from the npm registry. Falls back to `currentVersion` on error. */
39
+ /**
40
+ * Fetch the latest published version from the npm registry. Returns `null` when
41
+ * the version could not be determined (registry non-OK, network failure,
42
+ * timeout, or offline) so callers can distinguish "confirmed current" from
43
+ * "couldn't check".
44
+ */
28
45
  export async function fetchLatestVersion(opts: {
29
46
  packageName: string;
30
- currentVersion: string;
31
47
  fetchImpl?: FetchLike;
32
48
  signal?: AbortSignal;
33
- }): Promise<string> {
49
+ }): Promise<string | null> {
34
50
  const doFetch = opts.fetchImpl ?? fetch;
35
51
  try {
36
52
  const res = await doFetch(
37
53
  `https://registry.npmjs.org/${opts.packageName}/latest`,
38
54
  { signal: opts.signal },
39
55
  );
40
- if (!res.ok) return opts.currentVersion;
56
+ if (!res.ok) return null;
41
57
  const data = (await res.json()) as { version: string };
42
58
  return data.version;
43
59
  } catch {
44
- return opts.currentVersion;
60
+ return null;
45
61
  }
46
62
  }
47
63
 
@@ -98,10 +114,21 @@ export async function checkForUpdate(opts: {
98
114
  }): Promise<UpdateInfo> {
99
115
  const latestVersion = await fetchLatestVersion({
100
116
  packageName: opts.packageName,
101
- currentVersion: opts.currentVersion,
102
117
  fetchImpl: opts.fetchImpl,
103
118
  signal: opts.signal,
104
119
  });
120
+
121
+ if (latestVersion === null) {
122
+ // The check did not complete — surface it rather than reporting "current".
123
+ return {
124
+ currentVersion: opts.currentVersion,
125
+ latestVersion: opts.currentVersion,
126
+ hasUpdate: false,
127
+ aheadOfLatest: false,
128
+ error: `Could not determine the latest version of "${opts.packageName}" from the npm registry.`,
129
+ };
130
+ }
131
+
105
132
  const hasUpdate = isNewerVersion(opts.currentVersion, latestVersion);
106
133
  const aheadOfLatest = isNewerVersion(latestVersion, opts.currentVersion);
107
134
 
package/src/index.ts CHANGED
@@ -122,12 +122,6 @@ export function createUpdater(config: UpdaterConfig): Updater {
122
122
  // Always re-check: the background cache may be fresh but stale relative
123
123
  // to a release that shipped since the last check.
124
124
  const info = await checkFresh();
125
- await saveCache(cfg.cacheDir, {
126
- lastCheckAt: new Date().toISOString(),
127
- latestVersion: info.latestVersion,
128
- hasUpdate: info.hasUpdate,
129
- changelog: info.changelog,
130
- });
131
125
 
132
126
  const method = detectInstallMethodImpl({
133
127
  localDevEntry: cfg.localDevEntry,
@@ -139,6 +133,18 @@ export function createUpdater(config: UpdaterConfig): Updater {
139
133
  hasUpdate: info.hasUpdate,
140
134
  };
141
135
 
136
+ // The check itself failed — don't cache a bogus result or report success.
137
+ if (info.error) {
138
+ return { ...base, performed: false, success: false, error: info.error };
139
+ }
140
+
141
+ await saveCache(cfg.cacheDir, {
142
+ lastCheckAt: new Date().toISOString(),
143
+ latestVersion: info.latestVersion,
144
+ hasUpdate: info.hasUpdate,
145
+ changelog: info.changelog,
146
+ });
147
+
142
148
  if (!info.hasUpdate) {
143
149
  return { ...base, performed: false, success: true };
144
150
  }
package/src/notice.ts CHANGED
@@ -83,6 +83,10 @@ export async function maybeBackgroundNotice(
83
83
  signal: controller.signal,
84
84
  });
85
85
 
86
+ // Only cache a completed check — a failed check must not suppress the
87
+ // next attempt (nor be silently reported as "up to date").
88
+ if (info.error) return null;
89
+
86
90
  const newCache: UpdateCache = {
87
91
  lastCheckAt: new Date().toISOString(),
88
92
  latestVersion: info.latestVersion,
package/src/upgrade.ts CHANGED
@@ -1,14 +1,35 @@
1
+ import { execFile } from "node:child_process";
2
+ import { chmod, unlink, writeFile } from "node:fs/promises";
1
3
  import { tmpdir } from "node:os";
2
4
  import { join } from "node:path";
3
- import { $ } from "bun";
5
+ import { promisify } from "node:util";
4
6
  import type { AssetTarget, FetchLike } from "./config.ts";
5
7
 
8
+ const execFileAsync = promisify(execFile);
9
+
6
10
  /** Outcome of a binary or package-manager install attempt. */
7
11
  export interface InstallOutcome {
8
12
  success: boolean;
9
13
  error?: string;
10
14
  }
11
15
 
16
+ /**
17
+ * Run a command without throwing, returning its exit code. Cross-runtime
18
+ * (Node + Bun) replacement for Bun's `$`…`.nothrow()`.
19
+ */
20
+ async function run(
21
+ command: string,
22
+ args: string[],
23
+ ): Promise<{ exitCode: number }> {
24
+ try {
25
+ await execFileAsync(command, args);
26
+ return { exitCode: 0 };
27
+ } catch (err) {
28
+ const code = (err as { code?: number | string }).code;
29
+ return { exitCode: typeof code === "number" ? code : 1 };
30
+ }
31
+ }
32
+
12
33
  /**
13
34
  * Build the GitHub release asset name for the current platform.
14
35
  * Defaults to `<binaryName>-<os>-<arch>[.exe]`, or delegates to `assetName`.
@@ -47,7 +68,7 @@ export async function upgradeWithPackageManager(
47
68
  command: string,
48
69
  args: string[],
49
70
  ): Promise<InstallOutcome> {
50
- const result = await $`${command} ${args}`.nothrow();
71
+ const result = await run(command, args);
51
72
  return result.exitCode === 0
52
73
  ? { success: true }
53
74
  : {
@@ -91,17 +112,17 @@ export async function upgradeFromBinary(opts: {
91
112
  }
92
113
 
93
114
  const bytes = await res.arrayBuffer();
94
- await Bun.write(tmpPath, bytes);
115
+ await writeFile(tmpPath, Buffer.from(bytes));
95
116
 
96
- await $`chmod +x ${tmpPath}`.quiet();
117
+ await chmod(tmpPath, 0o755);
97
118
 
98
- // Try to move into place.
99
- const mv = await $`mv ${tmpPath} ${targetPath}`.quiet().nothrow();
119
+ // Try to move into place (mv handles cross-filesystem moves).
120
+ const mv = await run("mv", [tmpPath, targetPath]);
100
121
 
101
122
  if (mv.exitCode !== 0) {
102
123
  // Fall back to sudo.
103
124
  onProgress("Requires elevated permissions...");
104
- const sudo = await $`sudo mv ${tmpPath} ${targetPath}`.nothrow();
125
+ const sudo = await run("sudo", ["mv", tmpPath, targetPath]);
105
126
  if (sudo.exitCode !== 0) {
106
127
  return {
107
128
  success: false,
@@ -113,7 +134,7 @@ export async function upgradeFromBinary(opts: {
113
134
  return { success: true };
114
135
  } catch (err) {
115
136
  // Clean up temp file.
116
- await $`rm -f ${tmpPath}`.quiet().nothrow();
137
+ await unlink(tmpPath).catch(() => {});
117
138
  return { success: false, error: `Failed to upgrade binary: ${err}` };
118
139
  }
119
140
  }