upgradr 0.3.0 → 0.4.1
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 +9 -5
- package/dist/cache.d.ts +7 -0
- package/dist/cache.js +35 -0
- package/dist/checker.d.ts +61 -0
- package/dist/checker.js +120 -0
- package/dist/config.d.ts +93 -0
- package/dist/config.js +24 -0
- package/dist/index.d.ts +55 -0
- package/dist/index.js +97 -0
- package/dist/notice.d.ts +16 -0
- package/dist/notice.js +96 -0
- package/dist/upgrade.d.ts +30 -0
- package/dist/upgrade.js +126 -0
- package/package.json +20 -8
- package/src/cache.ts +7 -11
- package/src/checker.ts +7 -1
- package/src/index.ts +3 -0
- package/src/upgrade.ts +73 -13
package/README.md
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
# upgradr
|
|
2
2
|
|
|
3
|
-
Self-update for [Bun](https://bun.sh) CLIs. `upgradr`
|
|
4
|
-
release, shows a non-blocking startup notice, and upgrades
|
|
5
|
-
via `npm`/`bun` global install or by swapping a GitHub release
|
|
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
|
-
|
|
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
|
|
package/dist/cache.d.ts
ADDED
|
@@ -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;
|
package/dist/checker.js
ADDED
|
@@ -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
|
+
}
|
package/dist/config.d.ts
ADDED
|
@@ -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
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -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,97 @@
|
|
|
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
|
+
// upgradr just confirmed this version on the registry, so skip
|
|
61
|
+
// bun's manifest cache — it can lag right after a publish.
|
|
62
|
+
outcome = await upgradeWithPackageManager("bun", [
|
|
63
|
+
"install",
|
|
64
|
+
"-g",
|
|
65
|
+
"--no-cache",
|
|
66
|
+
`${cfg.packageName}@${info.latestVersion}`,
|
|
67
|
+
]);
|
|
68
|
+
break;
|
|
69
|
+
case "npm":
|
|
70
|
+
outcome = await upgradeWithPackageManager("npm", [
|
|
71
|
+
"install",
|
|
72
|
+
"-g",
|
|
73
|
+
`${cfg.packageName}@${info.latestVersion}`,
|
|
74
|
+
]);
|
|
75
|
+
break;
|
|
76
|
+
case "binary":
|
|
77
|
+
outcome = await upgradeFromBinary({
|
|
78
|
+
repo: cfg.repo,
|
|
79
|
+
latestVersion: info.latestVersion,
|
|
80
|
+
binaryName: cfg.binaryName,
|
|
81
|
+
assetName: cfg.assetName,
|
|
82
|
+
fetchImpl: cfg.fetchImpl,
|
|
83
|
+
onProgress: cfg.onProgress,
|
|
84
|
+
});
|
|
85
|
+
break;
|
|
86
|
+
}
|
|
87
|
+
if (outcome.success)
|
|
88
|
+
await clearCache(cfg.cacheDir);
|
|
89
|
+
return {
|
|
90
|
+
...base,
|
|
91
|
+
performed: true,
|
|
92
|
+
success: outcome.success,
|
|
93
|
+
error: outcome.error,
|
|
94
|
+
};
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
package/dist/notice.d.ts
ADDED
|
@@ -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>;
|
package/dist/upgrade.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
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
|
+
/** Max number of trailing output lines kept in an error message. */
|
|
8
|
+
const OUTPUT_TAIL_LINES = 10;
|
|
9
|
+
/**
|
|
10
|
+
* Run a command without throwing, returning its exit code and output.
|
|
11
|
+
* Cross-runtime (Node + Bun) replacement for Bun's `$`…`.nothrow()`.
|
|
12
|
+
*/
|
|
13
|
+
async function run(command, args) {
|
|
14
|
+
try {
|
|
15
|
+
const { stdout, stderr } = await execFileAsync(command, args);
|
|
16
|
+
return { exitCode: 0, stdout: String(stdout), stderr: String(stderr) };
|
|
17
|
+
}
|
|
18
|
+
catch (err) {
|
|
19
|
+
const e = err;
|
|
20
|
+
return {
|
|
21
|
+
exitCode: typeof e.code === "number" ? e.code : 1,
|
|
22
|
+
stdout: String(e.stdout ?? ""),
|
|
23
|
+
stderr: String(e.stderr ?? ""),
|
|
24
|
+
spawnError: typeof e.code === "string" ? e.message : undefined,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Describe a failed {@link run}: the exact command, its exit code, and the
|
|
30
|
+
* tail of its stderr (or stdout when stderr is empty).
|
|
31
|
+
*/
|
|
32
|
+
function describeFailure(command, args, result) {
|
|
33
|
+
const cmd = [command, ...args].join(" ");
|
|
34
|
+
if (result.spawnError)
|
|
35
|
+
return `${cmd} failed: ${result.spawnError}`;
|
|
36
|
+
const output = (result.stderr.trim() || result.stdout.trim())
|
|
37
|
+
.split("\n")
|
|
38
|
+
.slice(-OUTPUT_TAIL_LINES)
|
|
39
|
+
.join("\n");
|
|
40
|
+
const head = `${cmd} exited with code ${result.exitCode}`;
|
|
41
|
+
return output ? `${head}:\n${output}` : head;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Build the GitHub release asset name for the current platform.
|
|
45
|
+
* Defaults to `<binaryName>-<os>-<arch>[.exe]`, or delegates to `assetName`.
|
|
46
|
+
*/
|
|
47
|
+
export function platformArtifactName(opts) {
|
|
48
|
+
const platform = opts.platform ?? process.platform;
|
|
49
|
+
const arch = opts.arch ?? process.arch;
|
|
50
|
+
if (opts.assetName)
|
|
51
|
+
return opts.assetName({ platform, arch });
|
|
52
|
+
let os;
|
|
53
|
+
let ext = "";
|
|
54
|
+
switch (platform) {
|
|
55
|
+
case "darwin":
|
|
56
|
+
os = "darwin";
|
|
57
|
+
break;
|
|
58
|
+
case "win32":
|
|
59
|
+
os = "windows";
|
|
60
|
+
ext = ".exe";
|
|
61
|
+
break;
|
|
62
|
+
default:
|
|
63
|
+
os = "linux";
|
|
64
|
+
break;
|
|
65
|
+
}
|
|
66
|
+
const normalizedArch = arch === "arm64" ? "arm64" : "x64";
|
|
67
|
+
return `${opts.binaryName}-${os}-${normalizedArch}${ext}`;
|
|
68
|
+
}
|
|
69
|
+
/** Run a global install via a package manager, e.g. `npm install -g pkg@1.2.3`. */
|
|
70
|
+
export async function upgradeWithPackageManager(command, args) {
|
|
71
|
+
const result = await run(command, args);
|
|
72
|
+
return result.exitCode === 0
|
|
73
|
+
? { success: true }
|
|
74
|
+
: { success: false, error: describeFailure(command, args, result) };
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Download the release binary for `latestVersion` and swap it into place at
|
|
78
|
+
* `process.execPath`, falling back to `sudo mv` when a plain move is denied.
|
|
79
|
+
*/
|
|
80
|
+
export async function upgradeFromBinary(opts) {
|
|
81
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
82
|
+
const onProgress = opts.onProgress ?? (() => { });
|
|
83
|
+
const artifact = platformArtifactName({
|
|
84
|
+
binaryName: opts.binaryName,
|
|
85
|
+
assetName: opts.assetName,
|
|
86
|
+
});
|
|
87
|
+
const tag = `v${opts.latestVersion}`;
|
|
88
|
+
const url = `https://github.com/${opts.repo}/releases/download/${tag}/${artifact}`;
|
|
89
|
+
const tmpPath = join(tmpdir(), `${opts.binaryName}-upgrade-${Date.now()}`);
|
|
90
|
+
const targetPath = process.execPath;
|
|
91
|
+
try {
|
|
92
|
+
const res = await doFetch(url);
|
|
93
|
+
if (!res.ok) {
|
|
94
|
+
return {
|
|
95
|
+
success: false,
|
|
96
|
+
error: `Failed to download binary: HTTP ${res.status}`,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
const bytes = await res.arrayBuffer();
|
|
100
|
+
await writeFile(tmpPath, Buffer.from(bytes));
|
|
101
|
+
await chmod(tmpPath, 0o755);
|
|
102
|
+
// Try to move into place (mv handles cross-filesystem moves).
|
|
103
|
+
const mv = await run("mv", [tmpPath, targetPath]);
|
|
104
|
+
if (mv.exitCode !== 0) {
|
|
105
|
+
// Fall back to sudo.
|
|
106
|
+
onProgress("Requires elevated permissions...");
|
|
107
|
+
const sudoArgs = ["mv", tmpPath, targetPath];
|
|
108
|
+
const sudo = await run("sudo", sudoArgs);
|
|
109
|
+
if (sudo.exitCode !== 0) {
|
|
110
|
+
await unlink(tmpPath).catch(() => { });
|
|
111
|
+
return {
|
|
112
|
+
success: false,
|
|
113
|
+
error: `Failed to install binary. Try running with sudo.\n` +
|
|
114
|
+
`${describeFailure("mv", [tmpPath, targetPath], mv)}\n` +
|
|
115
|
+
describeFailure("sudo", sudoArgs, sudo),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return { success: true };
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
// Clean up temp file.
|
|
123
|
+
await unlink(tmpPath).catch(() => { });
|
|
124
|
+
return { success: false, error: `Failed to upgrade binary: ${err}` };
|
|
125
|
+
}
|
|
126
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "upgradr",
|
|
3
|
-
"version": "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.1",
|
|
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
|
-
".":
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"import": "./dist/index.js"
|
|
30
|
+
}
|
|
28
31
|
},
|
|
29
|
-
"main": "./
|
|
30
|
-
"
|
|
31
|
-
"
|
|
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
|
|
14
|
-
|
|
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
|
|
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
|
-
|
|
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. */
|
|
@@ -27,7 +28,12 @@ export interface UpdateCache {
|
|
|
27
28
|
|
|
28
29
|
/** Compare two semver strings. Returns true if `latest > current`. */
|
|
29
30
|
export function isNewerVersion(current: string, latest: string): boolean {
|
|
30
|
-
|
|
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
|
+
}
|
|
31
37
|
}
|
|
32
38
|
|
|
33
39
|
/**
|
package/src/index.ts
CHANGED
|
@@ -156,9 +156,12 @@ export function createUpdater(config: UpdaterConfig): Updater {
|
|
|
156
156
|
let outcome: InstallOutcome;
|
|
157
157
|
switch (method) {
|
|
158
158
|
case "bun":
|
|
159
|
+
// upgradr just confirmed this version on the registry, so skip
|
|
160
|
+
// bun's manifest cache — it can lag right after a publish.
|
|
159
161
|
outcome = await upgradeWithPackageManager("bun", [
|
|
160
162
|
"install",
|
|
161
163
|
"-g",
|
|
164
|
+
"--no-cache",
|
|
162
165
|
`${cfg.packageName}@${info.latestVersion}`,
|
|
163
166
|
]);
|
|
164
167
|
break;
|
package/src/upgrade.ts
CHANGED
|
@@ -1,14 +1,72 @@
|
|
|
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 {
|
|
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
|
+
/** Max number of trailing output lines kept in an error message. */
|
|
17
|
+
const OUTPUT_TAIL_LINES = 10;
|
|
18
|
+
|
|
19
|
+
interface RunResult {
|
|
20
|
+
exitCode: number;
|
|
21
|
+
stdout: string;
|
|
22
|
+
stderr: string;
|
|
23
|
+
/** Spawn failure (e.g. ENOENT) when the command never ran. */
|
|
24
|
+
spawnError?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Run a command without throwing, returning its exit code and output.
|
|
29
|
+
* Cross-runtime (Node + Bun) replacement for Bun's `$`…`.nothrow()`.
|
|
30
|
+
*/
|
|
31
|
+
async function run(command: string, args: string[]): Promise<RunResult> {
|
|
32
|
+
try {
|
|
33
|
+
const { stdout, stderr } = await execFileAsync(command, args);
|
|
34
|
+
return { exitCode: 0, stdout: String(stdout), stderr: String(stderr) };
|
|
35
|
+
} catch (err) {
|
|
36
|
+
const e = err as {
|
|
37
|
+
code?: number | string;
|
|
38
|
+
stdout?: unknown;
|
|
39
|
+
stderr?: unknown;
|
|
40
|
+
message?: string;
|
|
41
|
+
};
|
|
42
|
+
return {
|
|
43
|
+
exitCode: typeof e.code === "number" ? e.code : 1,
|
|
44
|
+
stdout: String(e.stdout ?? ""),
|
|
45
|
+
stderr: String(e.stderr ?? ""),
|
|
46
|
+
spawnError: typeof e.code === "string" ? e.message : undefined,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Describe a failed {@link run}: the exact command, its exit code, and the
|
|
53
|
+
* tail of its stderr (or stdout when stderr is empty).
|
|
54
|
+
*/
|
|
55
|
+
function describeFailure(
|
|
56
|
+
command: string,
|
|
57
|
+
args: string[],
|
|
58
|
+
result: RunResult,
|
|
59
|
+
): string {
|
|
60
|
+
const cmd = [command, ...args].join(" ");
|
|
61
|
+
if (result.spawnError) return `${cmd} failed: ${result.spawnError}`;
|
|
62
|
+
const output = (result.stderr.trim() || result.stdout.trim())
|
|
63
|
+
.split("\n")
|
|
64
|
+
.slice(-OUTPUT_TAIL_LINES)
|
|
65
|
+
.join("\n");
|
|
66
|
+
const head = `${cmd} exited with code ${result.exitCode}`;
|
|
67
|
+
return output ? `${head}:\n${output}` : head;
|
|
68
|
+
}
|
|
69
|
+
|
|
12
70
|
/**
|
|
13
71
|
* Build the GitHub release asset name for the current platform.
|
|
14
72
|
* Defaults to `<binaryName>-<os>-<arch>[.exe]`, or delegates to `assetName`.
|
|
@@ -47,13 +105,10 @@ export async function upgradeWithPackageManager(
|
|
|
47
105
|
command: string,
|
|
48
106
|
args: string[],
|
|
49
107
|
): Promise<InstallOutcome> {
|
|
50
|
-
const result = await
|
|
108
|
+
const result = await run(command, args);
|
|
51
109
|
return result.exitCode === 0
|
|
52
110
|
? { success: true }
|
|
53
|
-
: {
|
|
54
|
-
success: false,
|
|
55
|
-
error: `${command} exited with code ${result.exitCode}`,
|
|
56
|
-
};
|
|
111
|
+
: { success: false, error: describeFailure(command, args, result) };
|
|
57
112
|
}
|
|
58
113
|
|
|
59
114
|
/**
|
|
@@ -91,21 +146,26 @@ export async function upgradeFromBinary(opts: {
|
|
|
91
146
|
}
|
|
92
147
|
|
|
93
148
|
const bytes = await res.arrayBuffer();
|
|
94
|
-
await
|
|
149
|
+
await writeFile(tmpPath, Buffer.from(bytes));
|
|
95
150
|
|
|
96
|
-
await
|
|
151
|
+
await chmod(tmpPath, 0o755);
|
|
97
152
|
|
|
98
|
-
// Try to move into place.
|
|
99
|
-
const mv = await
|
|
153
|
+
// Try to move into place (mv handles cross-filesystem moves).
|
|
154
|
+
const mv = await run("mv", [tmpPath, targetPath]);
|
|
100
155
|
|
|
101
156
|
if (mv.exitCode !== 0) {
|
|
102
157
|
// Fall back to sudo.
|
|
103
158
|
onProgress("Requires elevated permissions...");
|
|
104
|
-
const
|
|
159
|
+
const sudoArgs = ["mv", tmpPath, targetPath];
|
|
160
|
+
const sudo = await run("sudo", sudoArgs);
|
|
105
161
|
if (sudo.exitCode !== 0) {
|
|
162
|
+
await unlink(tmpPath).catch(() => {});
|
|
106
163
|
return {
|
|
107
164
|
success: false,
|
|
108
|
-
error:
|
|
165
|
+
error:
|
|
166
|
+
`Failed to install binary. Try running with sudo.\n` +
|
|
167
|
+
`${describeFailure("mv", [tmpPath, targetPath], mv)}\n` +
|
|
168
|
+
describeFailure("sudo", sudoArgs, sudo),
|
|
109
169
|
};
|
|
110
170
|
}
|
|
111
171
|
}
|
|
@@ -113,7 +173,7 @@ export async function upgradeFromBinary(opts: {
|
|
|
113
173
|
return { success: true };
|
|
114
174
|
} catch (err) {
|
|
115
175
|
// Clean up temp file.
|
|
116
|
-
await
|
|
176
|
+
await unlink(tmpPath).catch(() => {});
|
|
117
177
|
return { success: false, error: `Failed to upgrade binary: ${err}` };
|
|
118
178
|
}
|
|
119
179
|
}
|