upgradr 0.1.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/LICENSE +21 -0
- package/README.md +237 -0
- package/package.json +45 -0
- package/src/cache.ts +46 -0
- package/src/checker.ts +164 -0
- package/src/config.ts +103 -0
- package/src/index.ts +186 -0
- package/src/notice.ts +114 -0
- package/src/upgrade.ts +119 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Evan Tahler
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
# upgradr
|
|
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.
|
|
6
|
+
|
|
7
|
+
It's the mechanism extracted from [Botholomew](https://github.com/evantahler/botholomew),
|
|
8
|
+
generalized so any Bun CLI can drop it in.
|
|
9
|
+
|
|
10
|
+
## Features
|
|
11
|
+
|
|
12
|
+
- **Version check** against the npm registry, with a GitHub-releases changelog.
|
|
13
|
+
- **Cached background notice** — a throttled "update available" line on startup, shown only in a TTY, with an env-var opt-out.
|
|
14
|
+
- **`upgrade` that always re-checks** — an explicit upgrade never trusts a stale cache.
|
|
15
|
+
- **Four install methods, auto-detected** — `npm` / `bun` global installs, a compiled release **binary** (downloaded + swapped in place, with `sudo` fallback), and `local-dev` (source checkout → no-op).
|
|
16
|
+
- **No framework coupling** — a `createUpdater(config)` factory returns plain async methods. Bring your own CLI (Commander, etc.). The library never writes to the console or exits the process; you own presentation.
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
bun add upgradr
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Requires the Bun runtime (uses `Bun.semver`, `Bun.file`, and `bun`'s shell).
|
|
25
|
+
|
|
26
|
+
## Usage
|
|
27
|
+
|
|
28
|
+
Create one updater for your CLI, wired to your `package.json` and config dir:
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { createUpdater } from "upgradr";
|
|
32
|
+
import pkg from "./package.json" with { type: "json" };
|
|
33
|
+
import { homedir } from "node:os";
|
|
34
|
+
import { join } from "node:path";
|
|
35
|
+
|
|
36
|
+
export const updater = createUpdater({
|
|
37
|
+
currentVersion: pkg.version,
|
|
38
|
+
packageName: pkg.name, // npm registry + `install -g <pkg>@<v>`
|
|
39
|
+
repo: "you/your-cli", // GitHub "owner/name" for release binaries + changelog
|
|
40
|
+
binaryName: "your-cli", // release asset prefix: your-cli-<os>-<arch>[.exe]
|
|
41
|
+
cacheDir: join(homedir(), ".your-cli"),
|
|
42
|
+
cliName: "your-cli", // shown in notices / "Run `your-cli upgrade`"
|
|
43
|
+
noUpdateCheckEnv: "YOUR_CLI_NO_UPDATE_CHECK",
|
|
44
|
+
});
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Startup notice (non-blocking)
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
// Kick off the check before parsing, print the notice after.
|
|
51
|
+
const notice = updater.maybeBackgroundNotice();
|
|
52
|
+
program.parse();
|
|
53
|
+
notice.then((msg) => {
|
|
54
|
+
if (msg) process.stderr.write(msg);
|
|
55
|
+
});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### `check-update` command
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
const info = await updater.checkForUpdate();
|
|
62
|
+
if (info.hasUpdate) {
|
|
63
|
+
console.log(`Update available: ${info.currentVersion} → ${info.latestVersion}`);
|
|
64
|
+
if (info.changelog) console.log(info.changelog);
|
|
65
|
+
} else if (info.aheadOfLatest) {
|
|
66
|
+
console.log(`Running ahead of the latest published release (v${info.latestVersion})`);
|
|
67
|
+
} else {
|
|
68
|
+
console.log(`Up to date (v${info.currentVersion})`);
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### `upgrade` command
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
const result = await updater.upgrade(); // always performs a fresh check first
|
|
76
|
+
|
|
77
|
+
if (!result.hasUpdate) {
|
|
78
|
+
console.log(`Already up to date (v${result.from})`);
|
|
79
|
+
} else if (result.method === "local-dev") {
|
|
80
|
+
console.log("Running from source. Use `git pull && bun install` to update.");
|
|
81
|
+
} else if (result.success) {
|
|
82
|
+
console.log(`Upgraded ${result.from} → ${result.to} (${result.method})`);
|
|
83
|
+
} else {
|
|
84
|
+
console.error(result.error ?? "Upgrade failed");
|
|
85
|
+
process.exit(1);
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Configuration
|
|
90
|
+
|
|
91
|
+
| Option | Required | Default | Purpose |
|
|
92
|
+
| --- | --- | --- | --- |
|
|
93
|
+
| `currentVersion` | ✓ | — | The running version. |
|
|
94
|
+
| `packageName` | ✓ | — | npm package name (registry lookup + global install target). |
|
|
95
|
+
| `repo` | ✓ | — | GitHub `"owner/name"` for release binaries + changelog. |
|
|
96
|
+
| `binaryName` | ✓ | — | Release asset prefix → `<binaryName>-<os>-<arch>[.exe]`. |
|
|
97
|
+
| `cacheDir` | ✓ | — | Directory holding the `update.json` check cache. |
|
|
98
|
+
| `cliName` | | `packageName` | Display name in notices / upgrade hint. |
|
|
99
|
+
| `noUpdateCheckEnv` | | — | Env var that disables the background check when set to `"1"`. |
|
|
100
|
+
| `localDevEntry` | | `"src/cli.ts"` | Entry-script substring marking a source checkout. |
|
|
101
|
+
| `checkIntervalMs` | | 24h | How long a cached check stays fresh. |
|
|
102
|
+
| `timeoutMs` | | 5000 | Timeout for the background network check. |
|
|
103
|
+
| `backgroundSkipCommands` | | `["check-update","upgrade"]` | Commands that suppress the startup notice. |
|
|
104
|
+
| `assetName` | | — | `(target) => string` to fully override the release asset name. |
|
|
105
|
+
| `fetchImpl` | | global `fetch` | Injectable `fetch` (for testing). |
|
|
106
|
+
| `onProgress` | | no-op | Progress callback (e.g. the sudo heads-up during a binary swap). |
|
|
107
|
+
|
|
108
|
+
## Install-method detection
|
|
109
|
+
|
|
110
|
+
`detectInstallMethod()` inspects `process.argv[1]` and `process.execPath`:
|
|
111
|
+
|
|
112
|
+
- **`local-dev`** — running your source entry (`localDevEntry`) outside `node_modules`. `upgrade()` is a no-op here.
|
|
113
|
+
- **`binary`** — the exec path is a compiled binary (not `bun`/`node`). Upgraded by downloading the matching GitHub release asset and swapping it into place.
|
|
114
|
+
- **`bun`** — installed under `.bun/install` or `.bun/bin`. Upgraded with `bun install -g`.
|
|
115
|
+
- **`npm`** — the `node_modules` fallback. Upgraded with `npm install -g`.
|
|
116
|
+
|
|
117
|
+
## Producing the release artifacts upgradr expects
|
|
118
|
+
|
|
119
|
+
upgradr doesn't build or publish anything — it *consumes* what your CI already
|
|
120
|
+
produces. For each upgrade path to work, your repo must publish the matching
|
|
121
|
+
artifact:
|
|
122
|
+
|
|
123
|
+
| Upgrade path | What upgradr does | What your repo must publish |
|
|
124
|
+
| --- | --- | --- |
|
|
125
|
+
| `npm` / `bun` | `npm\|bun install -g <packageName>@<latestVersion>` | The package on **npm** at that version. |
|
|
126
|
+
| `binary` | `GET https://github.com/<repo>/releases/download/v<version>/<asset>` | A **GitHub release** tagged `v<version>` with an asset per platform. |
|
|
127
|
+
| `check-update` notice | reads npm for the version, GitHub releases for the changelog | Published npm versions + GitHub releases (release **notes** become the changelog). |
|
|
128
|
+
|
|
129
|
+
**The version check reads npm**, so you must publish to npm even if your primary
|
|
130
|
+
distribution is a binary. **The changelog reads GitHub releases**, so tag and
|
|
131
|
+
release on GitHub too.
|
|
132
|
+
|
|
133
|
+
### Required asset names
|
|
134
|
+
|
|
135
|
+
The `binary` path downloads exactly:
|
|
136
|
+
|
|
137
|
+
```
|
|
138
|
+
https://github.com/<repo>/releases/download/v<version>/<binaryName>-<os>-<arch>[.exe]
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
- `<os>` ∈ `darwin` | `linux` | `windows`
|
|
142
|
+
- `<arch>` ∈ `arm64` | `x64`
|
|
143
|
+
- `.exe` suffix on Windows only
|
|
144
|
+
|
|
145
|
+
So a v1.2.3 release of `binaryName: "your-cli"` needs assets like
|
|
146
|
+
`your-cli-darwin-arm64`, `your-cli-linux-x64`, `your-cli-windows-x64.exe`.
|
|
147
|
+
(Ship a different scheme? Override `assetName` in the config.)
|
|
148
|
+
|
|
149
|
+
### Example release workflow
|
|
150
|
+
|
|
151
|
+
Trigger a release when `package.json`'s `version` changes on `main`: create the
|
|
152
|
+
tag + GitHub release, build a binary per platform, upload each under the name
|
|
153
|
+
above, and publish to npm.
|
|
154
|
+
|
|
155
|
+
```yaml
|
|
156
|
+
# .github/workflows/release.yml
|
|
157
|
+
name: Release
|
|
158
|
+
on:
|
|
159
|
+
push:
|
|
160
|
+
branches: [main]
|
|
161
|
+
permissions:
|
|
162
|
+
contents: write # create releases + upload assets
|
|
163
|
+
id-token: write # npm provenance
|
|
164
|
+
jobs:
|
|
165
|
+
release:
|
|
166
|
+
runs-on: ubuntu-latest
|
|
167
|
+
outputs:
|
|
168
|
+
tag: v${{ steps.v.outputs.version }}
|
|
169
|
+
new: ${{ steps.v.outputs.new }}
|
|
170
|
+
steps:
|
|
171
|
+
- uses: actions/checkout@v4
|
|
172
|
+
- id: v
|
|
173
|
+
run: |
|
|
174
|
+
V=$(jq -r .version package.json)
|
|
175
|
+
echo "version=$V" >> "$GITHUB_OUTPUT"
|
|
176
|
+
gh release view "v$V" >/dev/null 2>&1 && echo "new=false" >> "$GITHUB_OUTPUT" || echo "new=true" >> "$GITHUB_OUTPUT"
|
|
177
|
+
env: { GH_TOKEN: "${{ secrets.GITHUB_TOKEN }}" }
|
|
178
|
+
- if: steps.v.outputs.new == 'true'
|
|
179
|
+
run: gh release create "v${{ steps.v.outputs.version }}" --generate-notes
|
|
180
|
+
env: { GH_TOKEN: "${{ secrets.GITHUB_TOKEN }}" }
|
|
181
|
+
|
|
182
|
+
binaries:
|
|
183
|
+
needs: release
|
|
184
|
+
if: needs.release.outputs.new == 'true'
|
|
185
|
+
strategy:
|
|
186
|
+
fail-fast: false
|
|
187
|
+
matrix:
|
|
188
|
+
include:
|
|
189
|
+
- { os: macos-latest, target: darwin-arm64, ext: "" }
|
|
190
|
+
- { os: ubuntu-latest, target: linux-x64, ext: "" }
|
|
191
|
+
- { os: windows-latest, target: windows-x64, ext: ".exe" }
|
|
192
|
+
runs-on: ${{ matrix.os }}
|
|
193
|
+
defaults: { run: { shell: bash } }
|
|
194
|
+
steps:
|
|
195
|
+
- uses: actions/checkout@v4
|
|
196
|
+
- uses: oven-sh/setup-bun@v2
|
|
197
|
+
- run: bun install --frozen-lockfile
|
|
198
|
+
- run: bun build --compile ./src/cli.ts --outfile "dist/your-cli${{ matrix.ext }}"
|
|
199
|
+
- name: Upload asset (name MUST match what upgradr downloads)
|
|
200
|
+
env: { GH_TOKEN: "${{ secrets.GITHUB_TOKEN }}" }
|
|
201
|
+
run: |
|
|
202
|
+
asset="your-cli-${{ matrix.target }}${{ matrix.ext }}"
|
|
203
|
+
cp "dist/your-cli${{ matrix.ext }}" "$asset"
|
|
204
|
+
gh release upload "${{ needs.release.outputs.tag }}" "$asset" --clobber
|
|
205
|
+
|
|
206
|
+
npm:
|
|
207
|
+
needs: release
|
|
208
|
+
if: needs.release.outputs.new == 'true'
|
|
209
|
+
runs-on: ubuntu-latest
|
|
210
|
+
permissions: { contents: read, id-token: write }
|
|
211
|
+
steps:
|
|
212
|
+
- uses: actions/checkout@v4
|
|
213
|
+
- uses: actions/setup-node@v4
|
|
214
|
+
with: { node-version: "22", registry-url: "https://registry.npmjs.org" }
|
|
215
|
+
- run: npm publish --provenance --access public
|
|
216
|
+
env: { NODE_AUTH_TOKEN: "${{ secrets.NPM_TOKEN }}" }
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
**Repo setup checklist**
|
|
220
|
+
|
|
221
|
+
1. Authenticate npm publishing. Preferred: **trusted publishing (OIDC)** — configure a trusted publisher for your package on npmjs.com pointing at this repo + workflow, keep `id-token: write`, use npm ≥ 11.5.1, and drop `NODE_AUTH_TOKEN` entirely (as this repo's own `release.yml` does). Alternative: an `NPM_TOKEN` automation-token secret + `NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}`.
|
|
222
|
+
2. Allow Actions to write releases — `Settings → Actions → General → Workflow permissions → Read and write` (or the per-job `permissions:` above).
|
|
223
|
+
3. For provenance, keep `id-token: write` on the publish job and publish from CI (not locally).
|
|
224
|
+
4. First install for users is a shell one-liner that pulls the same assets:
|
|
225
|
+
`curl -fsSL https://github.com/<repo>/releases/latest/download/<binaryName>-$(uname -s)-$(uname -m) -o your-cli` (normalize `uname` output to the `darwin|linux` / `arm64|x64` names above).
|
|
226
|
+
|
|
227
|
+
## API
|
|
228
|
+
|
|
229
|
+
`createUpdater(config)` returns an `Updater` with:
|
|
230
|
+
`checkForUpdate(signal?)`, `needsCheck(cache?)`, `detectInstallMethod()`,
|
|
231
|
+
`loadCache()`, `saveCache(cache)`, `clearCache()`, `maybeBackgroundNotice(overrides?)`,
|
|
232
|
+
and `upgrade()`. The standalone helpers `isNewerVersion`, `fetchLatestVersion`,
|
|
233
|
+
`fetchChangelog`, `platformArtifactName`, and `formatNotice` are also exported.
|
|
234
|
+
|
|
235
|
+
## License
|
|
236
|
+
|
|
237
|
+
MIT © Evan Tahler
|
package/package.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "upgradr",
|
|
3
|
+
"version": "0.1.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.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Evan Tahler",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"cli",
|
|
10
|
+
"self-update",
|
|
11
|
+
"auto-update",
|
|
12
|
+
"upgrade",
|
|
13
|
+
"bun",
|
|
14
|
+
"semver",
|
|
15
|
+
"npm",
|
|
16
|
+
"github-releases"
|
|
17
|
+
],
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "https://github.com/evantahler/upgradr.git"
|
|
21
|
+
},
|
|
22
|
+
"homepage": "https://github.com/evantahler/upgradr#readme",
|
|
23
|
+
"bugs": {
|
|
24
|
+
"url": "https://github.com/evantahler/upgradr/issues"
|
|
25
|
+
},
|
|
26
|
+
"exports": {
|
|
27
|
+
".": "./src/index.ts"
|
|
28
|
+
},
|
|
29
|
+
"main": "./src/index.ts",
|
|
30
|
+
"types": "./src/index.ts",
|
|
31
|
+
"files": ["src", "README.md", "LICENSE"],
|
|
32
|
+
"scripts": {
|
|
33
|
+
"test": "bun test",
|
|
34
|
+
"lint": "tsc --noEmit && biome check .",
|
|
35
|
+
"format": "biome check --write ."
|
|
36
|
+
},
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"ansis": "^4.3.1"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@biomejs/biome": "^2.4.16",
|
|
42
|
+
"@types/bun": "^1.3.14",
|
|
43
|
+
"typescript": "^6.0.3"
|
|
44
|
+
}
|
|
45
|
+
}
|
package/src/cache.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import type { UpdateCache } from "./checker.ts";
|
|
3
|
+
|
|
4
|
+
function cachePath(cacheDir: string): string {
|
|
5
|
+
return join(cacheDir, "update.json");
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** Load the cached update-check result, if it exists. Never throws. */
|
|
9
|
+
export async function loadCache(
|
|
10
|
+
cacheDir: string,
|
|
11
|
+
): Promise<UpdateCache | undefined> {
|
|
12
|
+
try {
|
|
13
|
+
const file = Bun.file(cachePath(cacheDir));
|
|
14
|
+
if (!(await file.exists())) return undefined;
|
|
15
|
+
return JSON.parse(await file.text()) as UpdateCache;
|
|
16
|
+
} catch {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Save an update-check result to the cache file. Silently ignores write errors. */
|
|
22
|
+
export async function saveCache(
|
|
23
|
+
cacheDir: string,
|
|
24
|
+
cache: UpdateCache,
|
|
25
|
+
): Promise<void> {
|
|
26
|
+
try {
|
|
27
|
+
const { mkdir } = await import("node:fs/promises");
|
|
28
|
+
await mkdir(cacheDir, { recursive: true });
|
|
29
|
+
await Bun.write(cachePath(cacheDir), `${JSON.stringify(cache, null, 2)}\n`);
|
|
30
|
+
} catch {
|
|
31
|
+
// Ignore write failures (e.g. permissions).
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Remove the cached update-check result. Never throws. */
|
|
36
|
+
export async function clearCache(cacheDir: string): Promise<void> {
|
|
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
|
+
}
|
|
43
|
+
} catch {
|
|
44
|
+
// Ignore.
|
|
45
|
+
}
|
|
46
|
+
}
|
package/src/checker.ts
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import type { FetchLike, InstallMethod } from "./config.ts";
|
|
2
|
+
|
|
3
|
+
/** The result of checking for an update. */
|
|
4
|
+
export interface UpdateInfo {
|
|
5
|
+
currentVersion: string;
|
|
6
|
+
latestVersion: string;
|
|
7
|
+
/** `latest > current`. */
|
|
8
|
+
hasUpdate: boolean;
|
|
9
|
+
/** `current > latest` — running ahead of the published release (dev build). */
|
|
10
|
+
aheadOfLatest: boolean;
|
|
11
|
+
changelog?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** The persisted result of a previous check (see `cache.ts`). */
|
|
15
|
+
export interface UpdateCache {
|
|
16
|
+
lastCheckAt: string;
|
|
17
|
+
latestVersion: string;
|
|
18
|
+
hasUpdate: boolean;
|
|
19
|
+
changelog?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Compare two semver strings. Returns true if `latest > current`. */
|
|
23
|
+
export function isNewerVersion(current: string, latest: string): boolean {
|
|
24
|
+
return Bun.semver.order(current, latest) === -1;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Fetch the latest published version from the npm registry. Falls back to `currentVersion` on error. */
|
|
28
|
+
export async function fetchLatestVersion(opts: {
|
|
29
|
+
packageName: string;
|
|
30
|
+
currentVersion: string;
|
|
31
|
+
fetchImpl?: FetchLike;
|
|
32
|
+
signal?: AbortSignal;
|
|
33
|
+
}): Promise<string> {
|
|
34
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
35
|
+
try {
|
|
36
|
+
const res = await doFetch(
|
|
37
|
+
`https://registry.npmjs.org/${opts.packageName}/latest`,
|
|
38
|
+
{ signal: opts.signal },
|
|
39
|
+
);
|
|
40
|
+
if (!res.ok) return opts.currentVersion;
|
|
41
|
+
const data = (await res.json()) as { version: string };
|
|
42
|
+
return data.version;
|
|
43
|
+
} catch {
|
|
44
|
+
return opts.currentVersion;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Fetch a markdown changelog from GitHub releases between two versions. */
|
|
49
|
+
export async function fetchChangelog(opts: {
|
|
50
|
+
repo: string;
|
|
51
|
+
fromVersion: string;
|
|
52
|
+
toVersion: string;
|
|
53
|
+
fetchImpl?: FetchLike;
|
|
54
|
+
signal?: AbortSignal;
|
|
55
|
+
}): Promise<string | undefined> {
|
|
56
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
57
|
+
try {
|
|
58
|
+
const res = await doFetch(
|
|
59
|
+
`https://api.github.com/repos/${opts.repo}/releases?per_page=20`,
|
|
60
|
+
{
|
|
61
|
+
signal: opts.signal,
|
|
62
|
+
headers: { Accept: "application/vnd.github.v3+json" },
|
|
63
|
+
},
|
|
64
|
+
);
|
|
65
|
+
if (!res.ok) return undefined;
|
|
66
|
+
|
|
67
|
+
const releases = (await res.json()) as Array<{
|
|
68
|
+
tag_name: string;
|
|
69
|
+
body: string | null;
|
|
70
|
+
}>;
|
|
71
|
+
|
|
72
|
+
const relevant = releases.filter((r) => {
|
|
73
|
+
const v = r.tag_name.replace(/^v/, "");
|
|
74
|
+
return (
|
|
75
|
+
isNewerVersion(opts.fromVersion, v) &&
|
|
76
|
+
!isNewerVersion(opts.toVersion, v)
|
|
77
|
+
);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
if (relevant.length === 0) return undefined;
|
|
81
|
+
|
|
82
|
+
return relevant
|
|
83
|
+
.map((r) => `## ${r.tag_name}\n${r.body ?? ""}`)
|
|
84
|
+
.join("\n\n")
|
|
85
|
+
.trim();
|
|
86
|
+
} catch {
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Check npm for a newer version and fetch the changelog if one is available. */
|
|
92
|
+
export async function checkForUpdate(opts: {
|
|
93
|
+
packageName: string;
|
|
94
|
+
repo: string;
|
|
95
|
+
currentVersion: string;
|
|
96
|
+
fetchImpl?: FetchLike;
|
|
97
|
+
signal?: AbortSignal;
|
|
98
|
+
}): Promise<UpdateInfo> {
|
|
99
|
+
const latestVersion = await fetchLatestVersion({
|
|
100
|
+
packageName: opts.packageName,
|
|
101
|
+
currentVersion: opts.currentVersion,
|
|
102
|
+
fetchImpl: opts.fetchImpl,
|
|
103
|
+
signal: opts.signal,
|
|
104
|
+
});
|
|
105
|
+
const hasUpdate = isNewerVersion(opts.currentVersion, latestVersion);
|
|
106
|
+
const aheadOfLatest = isNewerVersion(latestVersion, opts.currentVersion);
|
|
107
|
+
|
|
108
|
+
let changelog: string | undefined;
|
|
109
|
+
if (hasUpdate) {
|
|
110
|
+
changelog = await fetchChangelog({
|
|
111
|
+
repo: opts.repo,
|
|
112
|
+
fromVersion: opts.currentVersion,
|
|
113
|
+
toVersion: latestVersion,
|
|
114
|
+
fetchImpl: opts.fetchImpl,
|
|
115
|
+
signal: opts.signal,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
currentVersion: opts.currentVersion,
|
|
121
|
+
latestVersion,
|
|
122
|
+
hasUpdate,
|
|
123
|
+
aheadOfLatest,
|
|
124
|
+
changelog,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Returns true if the cache is missing or older than `intervalMs`. */
|
|
129
|
+
export function needsCheck(
|
|
130
|
+
cache: UpdateCache | undefined,
|
|
131
|
+
intervalMs: number,
|
|
132
|
+
): boolean {
|
|
133
|
+
if (!cache?.lastCheckAt) return true;
|
|
134
|
+
return Date.now() - new Date(cache.lastCheckAt).getTime() > intervalMs;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Detect how the CLI was installed, from the entry script and exec path. */
|
|
138
|
+
export function detectInstallMethod(opts?: {
|
|
139
|
+
localDevEntry?: string;
|
|
140
|
+
argv?: string[];
|
|
141
|
+
execPath?: string;
|
|
142
|
+
}): InstallMethod {
|
|
143
|
+
const localDevEntry = opts?.localDevEntry ?? "src/cli.ts";
|
|
144
|
+
const script = opts?.argv?.[1] ?? process.argv[1] ?? "";
|
|
145
|
+
const execPath = opts?.execPath ?? process.execPath;
|
|
146
|
+
|
|
147
|
+
// Local dev: running the source entry directly, outside node_modules.
|
|
148
|
+
if (script.includes(localDevEntry) && !script.includes("node_modules")) {
|
|
149
|
+
return "local-dev";
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Compiled binary: execPath is the binary itself (not bun/node).
|
|
153
|
+
if (!execPath.includes("bun") && !execPath.includes("node")) {
|
|
154
|
+
return "binary";
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Bun global install: path lives under .bun/install or .bun/bin.
|
|
158
|
+
if (script.includes(".bun/install") || script.includes(".bun/bin")) {
|
|
159
|
+
return "bun";
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// npm global install: fallback for node_modules paths.
|
|
163
|
+
return "npm";
|
|
164
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/** How the current binary/script was installed. */
|
|
2
|
+
export type InstallMethod = "npm" | "bun" | "binary" | "local-dev";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A minimal `fetch`-compatible function. The global `fetch` satisfies this;
|
|
6
|
+
* tests can supply a stub without implementing `fetch.preconnect`.
|
|
7
|
+
*/
|
|
8
|
+
export type FetchLike = (
|
|
9
|
+
input: string | URL | Request,
|
|
10
|
+
init?: RequestInit,
|
|
11
|
+
) => Promise<Response>;
|
|
12
|
+
|
|
13
|
+
/** Platform descriptor passed to a custom {@link UpdaterConfig.assetName}. */
|
|
14
|
+
export interface AssetTarget {
|
|
15
|
+
/** `process.platform` value, e.g. `"darwin"`, `"linux"`, `"win32"`. */
|
|
16
|
+
platform: string;
|
|
17
|
+
/** `process.arch` value, e.g. `"arm64"`, `"x64"`. */
|
|
18
|
+
arch: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Configuration for {@link createUpdater}. Every value that would otherwise be
|
|
23
|
+
* hardcoded to a specific project (repo, package name, cache location, …) is a
|
|
24
|
+
* parameter here so the same logic works for any Bun CLI.
|
|
25
|
+
*/
|
|
26
|
+
export interface UpdaterConfig {
|
|
27
|
+
/** The currently-running version, e.g. your `package.json` version. */
|
|
28
|
+
currentVersion: string;
|
|
29
|
+
/** npm package name — used for the registry lookup and `install -g <pkg>@<v>`. */
|
|
30
|
+
packageName: string;
|
|
31
|
+
/** GitHub repository as `"owner/name"` — used for release binaries + changelog. */
|
|
32
|
+
repo: string;
|
|
33
|
+
/**
|
|
34
|
+
* Prefix for GitHub release binary assets. The default asset name is
|
|
35
|
+
* `<binaryName>-<os>-<arch>[.exe]` (os ∈ darwin|linux|windows).
|
|
36
|
+
*/
|
|
37
|
+
binaryName: string;
|
|
38
|
+
/** Directory that holds the `update.json` check cache (e.g. `~/.myapp`). */
|
|
39
|
+
cacheDir: string;
|
|
40
|
+
|
|
41
|
+
/** Display name used in notices and the "Run `<cliName> upgrade`" hint. Defaults to {@link packageName}. */
|
|
42
|
+
cliName?: string;
|
|
43
|
+
/** Env var name that, when set to `"1"`, disables the background check. Omit to never opt out. */
|
|
44
|
+
noUpdateCheckEnv?: string;
|
|
45
|
+
/** Substring of the entry script that marks a local source checkout. Defaults to `"src/cli.ts"`. */
|
|
46
|
+
localDevEntry?: string;
|
|
47
|
+
/** How long a cached check stays fresh, in ms. Defaults to 24h. */
|
|
48
|
+
checkIntervalMs?: number;
|
|
49
|
+
/** Timeout for the background network check, in ms. Defaults to 5000. */
|
|
50
|
+
timeoutMs?: number;
|
|
51
|
+
/** Commands for which the background notice is suppressed. Defaults to `["check-update", "upgrade"]`. */
|
|
52
|
+
backgroundSkipCommands?: string[];
|
|
53
|
+
/** Override the full release asset name for a platform. */
|
|
54
|
+
assetName?: (target: AssetTarget) => string;
|
|
55
|
+
/** Injectable `fetch` (for testing). Defaults to the global `fetch`. */
|
|
56
|
+
fetchImpl?: FetchLike;
|
|
57
|
+
/** Called with human-readable progress messages (e.g. sudo prompts). Defaults to a no-op. */
|
|
58
|
+
onProgress?: (message: string) => void;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** {@link UpdaterConfig} with defaults applied. */
|
|
62
|
+
export interface ResolvedConfig {
|
|
63
|
+
currentVersion: string;
|
|
64
|
+
packageName: string;
|
|
65
|
+
repo: string;
|
|
66
|
+
binaryName: string;
|
|
67
|
+
cacheDir: string;
|
|
68
|
+
cliName: string;
|
|
69
|
+
noUpdateCheckEnv: string | undefined;
|
|
70
|
+
localDevEntry: string;
|
|
71
|
+
checkIntervalMs: number;
|
|
72
|
+
timeoutMs: number;
|
|
73
|
+
backgroundSkipCommands: string[];
|
|
74
|
+
assetName: ((target: AssetTarget) => string) | undefined;
|
|
75
|
+
fetchImpl: FetchLike;
|
|
76
|
+
onProgress: (message: string) => void;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export const DEFAULT_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
|
80
|
+
export const DEFAULT_TIMEOUT_MS = 5_000;
|
|
81
|
+
export const DEFAULT_LOCAL_DEV_ENTRY = "src/cli.ts";
|
|
82
|
+
export const DEFAULT_BACKGROUND_SKIP_COMMANDS = ["check-update", "upgrade"];
|
|
83
|
+
|
|
84
|
+
/** Apply defaults to a user-supplied {@link UpdaterConfig}. */
|
|
85
|
+
export function resolveConfig(config: UpdaterConfig): ResolvedConfig {
|
|
86
|
+
return {
|
|
87
|
+
currentVersion: config.currentVersion,
|
|
88
|
+
packageName: config.packageName,
|
|
89
|
+
repo: config.repo,
|
|
90
|
+
binaryName: config.binaryName,
|
|
91
|
+
cacheDir: config.cacheDir,
|
|
92
|
+
cliName: config.cliName ?? config.packageName,
|
|
93
|
+
noUpdateCheckEnv: config.noUpdateCheckEnv,
|
|
94
|
+
localDevEntry: config.localDevEntry ?? DEFAULT_LOCAL_DEV_ENTRY,
|
|
95
|
+
checkIntervalMs: config.checkIntervalMs ?? DEFAULT_CHECK_INTERVAL_MS,
|
|
96
|
+
timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
97
|
+
backgroundSkipCommands:
|
|
98
|
+
config.backgroundSkipCommands ?? DEFAULT_BACKGROUND_SKIP_COMMANDS,
|
|
99
|
+
assetName: config.assetName,
|
|
100
|
+
fetchImpl: config.fetchImpl ?? fetch,
|
|
101
|
+
onProgress: config.onProgress ?? (() => {}),
|
|
102
|
+
};
|
|
103
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { clearCache, loadCache, saveCache } from "./cache.ts";
|
|
2
|
+
import {
|
|
3
|
+
checkForUpdate as checkForUpdateImpl,
|
|
4
|
+
detectInstallMethod as detectInstallMethodImpl,
|
|
5
|
+
needsCheck as needsCheckImpl,
|
|
6
|
+
type UpdateCache,
|
|
7
|
+
type UpdateInfo,
|
|
8
|
+
} from "./checker.ts";
|
|
9
|
+
import {
|
|
10
|
+
type InstallMethod,
|
|
11
|
+
type ResolvedConfig,
|
|
12
|
+
resolveConfig,
|
|
13
|
+
type UpdaterConfig,
|
|
14
|
+
} from "./config.ts";
|
|
15
|
+
import { maybeBackgroundNotice } from "./notice.ts";
|
|
16
|
+
import {
|
|
17
|
+
type InstallOutcome,
|
|
18
|
+
upgradeFromBinary,
|
|
19
|
+
upgradeWithPackageManager,
|
|
20
|
+
} from "./upgrade.ts";
|
|
21
|
+
|
|
22
|
+
export {
|
|
23
|
+
fetchChangelog,
|
|
24
|
+
fetchLatestVersion,
|
|
25
|
+
isNewerVersion,
|
|
26
|
+
type UpdateCache,
|
|
27
|
+
type UpdateInfo,
|
|
28
|
+
} from "./checker.ts";
|
|
29
|
+
export type {
|
|
30
|
+
AssetTarget,
|
|
31
|
+
FetchLike,
|
|
32
|
+
InstallMethod,
|
|
33
|
+
ResolvedConfig,
|
|
34
|
+
UpdaterConfig,
|
|
35
|
+
} from "./config.ts";
|
|
36
|
+
export { formatNotice } from "./notice.ts";
|
|
37
|
+
export {
|
|
38
|
+
type InstallOutcome,
|
|
39
|
+
platformArtifactName,
|
|
40
|
+
} from "./upgrade.ts";
|
|
41
|
+
|
|
42
|
+
/** The outcome of {@link Updater.upgrade}. */
|
|
43
|
+
export interface UpgradeResult {
|
|
44
|
+
/** How the running CLI was installed. */
|
|
45
|
+
method: InstallMethod;
|
|
46
|
+
/** The version that was running. */
|
|
47
|
+
from: string;
|
|
48
|
+
/** The latest published version. */
|
|
49
|
+
to: string;
|
|
50
|
+
/** Whether a newer version is available. */
|
|
51
|
+
hasUpdate: boolean;
|
|
52
|
+
/** Whether an install was attempted (false when already current or local-dev). */
|
|
53
|
+
performed: boolean;
|
|
54
|
+
/** Whether the upgrade succeeded (true and un-performed means already current). */
|
|
55
|
+
success: boolean;
|
|
56
|
+
/** Error detail when `success` is false. */
|
|
57
|
+
error?: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A configured self-updater. Returned by {@link createUpdater}. */
|
|
61
|
+
export interface Updater {
|
|
62
|
+
/** The resolved configuration (with defaults applied). */
|
|
63
|
+
readonly config: ResolvedConfig;
|
|
64
|
+
/** Perform a fresh update check against npm (and GitHub for the changelog). */
|
|
65
|
+
checkForUpdate(signal?: AbortSignal): Promise<UpdateInfo>;
|
|
66
|
+
/** Whether a cached result is missing or stale. */
|
|
67
|
+
needsCheck(cache?: UpdateCache): boolean;
|
|
68
|
+
/** Detect how the CLI was installed. */
|
|
69
|
+
detectInstallMethod(): InstallMethod;
|
|
70
|
+
/** Load the persisted check cache. */
|
|
71
|
+
loadCache(): Promise<UpdateCache | undefined>;
|
|
72
|
+
/** Persist a check result. */
|
|
73
|
+
saveCache(cache: UpdateCache): Promise<void>;
|
|
74
|
+
/** Remove the persisted check cache. */
|
|
75
|
+
clearCache(): Promise<void>;
|
|
76
|
+
/** Non-blocking startup notice (cache-first). Returns a string or `null`. */
|
|
77
|
+
maybeBackgroundNotice(overrides?: {
|
|
78
|
+
env?: NodeJS.ProcessEnv;
|
|
79
|
+
argv?: string[];
|
|
80
|
+
isTTY?: boolean;
|
|
81
|
+
}): Promise<string | null>;
|
|
82
|
+
/**
|
|
83
|
+
* Upgrade in place. Always performs a fresh check first (never trusting a
|
|
84
|
+
* possibly-stale cache), then installs via the detected method. The caller
|
|
85
|
+
* owns all presentation — this returns a result and never writes to the
|
|
86
|
+
* console or exits the process.
|
|
87
|
+
*/
|
|
88
|
+
upgrade(): Promise<UpgradeResult>;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Create a self-updater bound to your project's {@link UpdaterConfig}. */
|
|
92
|
+
export function createUpdater(config: UpdaterConfig): Updater {
|
|
93
|
+
const cfg = resolveConfig(config);
|
|
94
|
+
|
|
95
|
+
const checkFresh = (signal?: AbortSignal): Promise<UpdateInfo> =>
|
|
96
|
+
checkForUpdateImpl({
|
|
97
|
+
packageName: cfg.packageName,
|
|
98
|
+
repo: cfg.repo,
|
|
99
|
+
currentVersion: cfg.currentVersion,
|
|
100
|
+
fetchImpl: cfg.fetchImpl,
|
|
101
|
+
signal,
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
return {
|
|
105
|
+
config: cfg,
|
|
106
|
+
|
|
107
|
+
checkForUpdate: checkFresh,
|
|
108
|
+
|
|
109
|
+
needsCheck: (cache) => needsCheckImpl(cache, cfg.checkIntervalMs),
|
|
110
|
+
|
|
111
|
+
detectInstallMethod: () =>
|
|
112
|
+
detectInstallMethodImpl({ localDevEntry: cfg.localDevEntry }),
|
|
113
|
+
|
|
114
|
+
loadCache: () => loadCache(cfg.cacheDir),
|
|
115
|
+
saveCache: (cache) => saveCache(cfg.cacheDir, cache),
|
|
116
|
+
clearCache: () => clearCache(cfg.cacheDir),
|
|
117
|
+
|
|
118
|
+
maybeBackgroundNotice: (overrides) => maybeBackgroundNotice(cfg, overrides),
|
|
119
|
+
|
|
120
|
+
async upgrade(): Promise<UpgradeResult> {
|
|
121
|
+
// Always re-check: the background cache may be fresh but stale relative
|
|
122
|
+
// to a release that shipped since the last check.
|
|
123
|
+
const info = await checkFresh();
|
|
124
|
+
await saveCache(cfg.cacheDir, {
|
|
125
|
+
lastCheckAt: new Date().toISOString(),
|
|
126
|
+
latestVersion: info.latestVersion,
|
|
127
|
+
hasUpdate: info.hasUpdate,
|
|
128
|
+
changelog: info.changelog,
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
const method = detectInstallMethodImpl({
|
|
132
|
+
localDevEntry: cfg.localDevEntry,
|
|
133
|
+
});
|
|
134
|
+
const base = {
|
|
135
|
+
method,
|
|
136
|
+
from: cfg.currentVersion,
|
|
137
|
+
to: info.latestVersion,
|
|
138
|
+
hasUpdate: info.hasUpdate,
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
if (!info.hasUpdate) {
|
|
142
|
+
return { ...base, performed: false, success: true };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (method === "local-dev") {
|
|
146
|
+
return { ...base, performed: false, success: false };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
let outcome: InstallOutcome;
|
|
150
|
+
switch (method) {
|
|
151
|
+
case "bun":
|
|
152
|
+
outcome = await upgradeWithPackageManager("bun", [
|
|
153
|
+
"install",
|
|
154
|
+
"-g",
|
|
155
|
+
`${cfg.packageName}@${info.latestVersion}`,
|
|
156
|
+
]);
|
|
157
|
+
break;
|
|
158
|
+
case "npm":
|
|
159
|
+
outcome = await upgradeWithPackageManager("npm", [
|
|
160
|
+
"install",
|
|
161
|
+
"-g",
|
|
162
|
+
`${cfg.packageName}@${info.latestVersion}`,
|
|
163
|
+
]);
|
|
164
|
+
break;
|
|
165
|
+
case "binary":
|
|
166
|
+
outcome = await upgradeFromBinary({
|
|
167
|
+
repo: cfg.repo,
|
|
168
|
+
latestVersion: info.latestVersion,
|
|
169
|
+
binaryName: cfg.binaryName,
|
|
170
|
+
assetName: cfg.assetName,
|
|
171
|
+
fetchImpl: cfg.fetchImpl,
|
|
172
|
+
onProgress: cfg.onProgress,
|
|
173
|
+
});
|
|
174
|
+
break;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (outcome.success) await clearCache(cfg.cacheDir);
|
|
178
|
+
return {
|
|
179
|
+
...base,
|
|
180
|
+
performed: true,
|
|
181
|
+
success: outcome.success,
|
|
182
|
+
error: outcome.error,
|
|
183
|
+
};
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
}
|
package/src/notice.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { cyan, dim, yellow } from "ansis";
|
|
2
|
+
import { loadCache, saveCache } from "./cache.ts";
|
|
3
|
+
import { checkForUpdate, needsCheck, type UpdateCache } from "./checker.ts";
|
|
4
|
+
import type { ResolvedConfig } from "./config.ts";
|
|
5
|
+
|
|
6
|
+
/** Format the "update available" notice shown on startup. */
|
|
7
|
+
export function formatNotice(opts: {
|
|
8
|
+
currentVersion: string;
|
|
9
|
+
latestVersion: string;
|
|
10
|
+
changelog?: string;
|
|
11
|
+
cliName: string;
|
|
12
|
+
}): string {
|
|
13
|
+
const lines: string[] = [
|
|
14
|
+
"",
|
|
15
|
+
yellow(`Update available: ${opts.currentVersion} → ${opts.latestVersion}`),
|
|
16
|
+
];
|
|
17
|
+
|
|
18
|
+
if (opts.changelog) {
|
|
19
|
+
lines.push("");
|
|
20
|
+
lines.push(dim(opts.changelog));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
lines.push("");
|
|
24
|
+
lines.push(cyan(`Run \`${opts.cliName} upgrade\` to update`));
|
|
25
|
+
lines.push("");
|
|
26
|
+
|
|
27
|
+
return lines.join("\n");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Non-blocking background update check. Returns a formatted notice string if an
|
|
32
|
+
* update is available, or `null` otherwise. Never throws. Uses a fresh (<24h)
|
|
33
|
+
* cache when present; otherwise performs a network check bounded by `timeoutMs`
|
|
34
|
+
* and refreshes the cache.
|
|
35
|
+
*
|
|
36
|
+
* `env`, `argv`, and `isTTY` are injectable for testing.
|
|
37
|
+
*/
|
|
38
|
+
export async function maybeBackgroundNotice(
|
|
39
|
+
cfg: ResolvedConfig,
|
|
40
|
+
overrides?: {
|
|
41
|
+
env?: NodeJS.ProcessEnv;
|
|
42
|
+
argv?: string[];
|
|
43
|
+
isTTY?: boolean;
|
|
44
|
+
},
|
|
45
|
+
): Promise<string | null> {
|
|
46
|
+
try {
|
|
47
|
+
const env = overrides?.env ?? process.env;
|
|
48
|
+
const argv = overrides?.argv ?? process.argv;
|
|
49
|
+
const isTTY = overrides?.isTTY ?? process.stderr.isTTY ?? false;
|
|
50
|
+
|
|
51
|
+
// Opt-out via env var.
|
|
52
|
+
if (cfg.noUpdateCheckEnv && env[cfg.noUpdateCheckEnv] === "1") return null;
|
|
53
|
+
|
|
54
|
+
// Skip when running an update-related command.
|
|
55
|
+
const args = argv.slice(2);
|
|
56
|
+
const command = args.find((a) => !a.startsWith("-"));
|
|
57
|
+
if (command && cfg.backgroundSkipCommands.includes(command)) return null;
|
|
58
|
+
|
|
59
|
+
// Only show in an interactive terminal.
|
|
60
|
+
if (!isTTY) return null;
|
|
61
|
+
|
|
62
|
+
const cache = await loadCache(cfg.cacheDir);
|
|
63
|
+
|
|
64
|
+
if (!needsCheck(cache, cfg.checkIntervalMs)) {
|
|
65
|
+
// Cache is fresh — use the cached result.
|
|
66
|
+
if (cache?.hasUpdate) {
|
|
67
|
+
return formatNotice({
|
|
68
|
+
currentVersion: cfg.currentVersion,
|
|
69
|
+
latestVersion: cache.latestVersion,
|
|
70
|
+
changelog: cache.changelog,
|
|
71
|
+
cliName: cfg.cliName,
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Cache is stale or missing — check with a timeout.
|
|
78
|
+
const controller = new AbortController();
|
|
79
|
+
const timeout = setTimeout(() => controller.abort(), cfg.timeoutMs);
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
const info = await checkForUpdate({
|
|
83
|
+
packageName: cfg.packageName,
|
|
84
|
+
repo: cfg.repo,
|
|
85
|
+
currentVersion: cfg.currentVersion,
|
|
86
|
+
fetchImpl: cfg.fetchImpl,
|
|
87
|
+
signal: controller.signal,
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
const newCache: UpdateCache = {
|
|
91
|
+
lastCheckAt: new Date().toISOString(),
|
|
92
|
+
latestVersion: info.latestVersion,
|
|
93
|
+
hasUpdate: info.hasUpdate,
|
|
94
|
+
changelog: info.changelog,
|
|
95
|
+
};
|
|
96
|
+
await saveCache(cfg.cacheDir, newCache);
|
|
97
|
+
|
|
98
|
+
if (info.hasUpdate) {
|
|
99
|
+
return formatNotice({
|
|
100
|
+
currentVersion: cfg.currentVersion,
|
|
101
|
+
latestVersion: info.latestVersion,
|
|
102
|
+
changelog: info.changelog,
|
|
103
|
+
cliName: cfg.cliName,
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
} finally {
|
|
107
|
+
clearTimeout(timeout);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
return null;
|
|
111
|
+
} catch {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
}
|
package/src/upgrade.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { tmpdir } from "node:os";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { $ } from "bun";
|
|
4
|
+
import type { AssetTarget, FetchLike } from "./config.ts";
|
|
5
|
+
|
|
6
|
+
/** Outcome of a binary or package-manager install attempt. */
|
|
7
|
+
export interface InstallOutcome {
|
|
8
|
+
success: boolean;
|
|
9
|
+
error?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Build the GitHub release asset name for the current platform.
|
|
14
|
+
* Defaults to `<binaryName>-<os>-<arch>[.exe]`, or delegates to `assetName`.
|
|
15
|
+
*/
|
|
16
|
+
export function platformArtifactName(opts: {
|
|
17
|
+
binaryName: string;
|
|
18
|
+
platform?: string;
|
|
19
|
+
arch?: string;
|
|
20
|
+
assetName?: (target: AssetTarget) => string;
|
|
21
|
+
}): string {
|
|
22
|
+
const platform = opts.platform ?? process.platform;
|
|
23
|
+
const arch = opts.arch ?? process.arch;
|
|
24
|
+
|
|
25
|
+
if (opts.assetName) return opts.assetName({ platform, arch });
|
|
26
|
+
|
|
27
|
+
let os: string;
|
|
28
|
+
let ext = "";
|
|
29
|
+
switch (platform) {
|
|
30
|
+
case "darwin":
|
|
31
|
+
os = "darwin";
|
|
32
|
+
break;
|
|
33
|
+
case "win32":
|
|
34
|
+
os = "windows";
|
|
35
|
+
ext = ".exe";
|
|
36
|
+
break;
|
|
37
|
+
default:
|
|
38
|
+
os = "linux";
|
|
39
|
+
break;
|
|
40
|
+
}
|
|
41
|
+
const normalizedArch = arch === "arm64" ? "arm64" : "x64";
|
|
42
|
+
return `${opts.binaryName}-${os}-${normalizedArch}${ext}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Run a global install via a package manager, e.g. `npm install -g pkg@1.2.3`. */
|
|
46
|
+
export async function upgradeWithPackageManager(
|
|
47
|
+
command: string,
|
|
48
|
+
args: string[],
|
|
49
|
+
): Promise<InstallOutcome> {
|
|
50
|
+
const result = await $`${command} ${args}`.nothrow();
|
|
51
|
+
return result.exitCode === 0
|
|
52
|
+
? { success: true }
|
|
53
|
+
: {
|
|
54
|
+
success: false,
|
|
55
|
+
error: `${command} exited with code ${result.exitCode}`,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Download the release binary for `latestVersion` and swap it into place at
|
|
61
|
+
* `process.execPath`, falling back to `sudo mv` when a plain move is denied.
|
|
62
|
+
*/
|
|
63
|
+
export async function upgradeFromBinary(opts: {
|
|
64
|
+
repo: string;
|
|
65
|
+
latestVersion: string;
|
|
66
|
+
binaryName: string;
|
|
67
|
+
assetName?: (target: AssetTarget) => string;
|
|
68
|
+
fetchImpl?: FetchLike;
|
|
69
|
+
onProgress?: (message: string) => void;
|
|
70
|
+
}): Promise<InstallOutcome> {
|
|
71
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
72
|
+
const onProgress = opts.onProgress ?? (() => {});
|
|
73
|
+
|
|
74
|
+
const artifact = platformArtifactName({
|
|
75
|
+
binaryName: opts.binaryName,
|
|
76
|
+
assetName: opts.assetName,
|
|
77
|
+
});
|
|
78
|
+
const tag = `v${opts.latestVersion}`;
|
|
79
|
+
const url = `https://github.com/${opts.repo}/releases/download/${tag}/${artifact}`;
|
|
80
|
+
|
|
81
|
+
const tmpPath = join(tmpdir(), `${opts.binaryName}-upgrade-${Date.now()}`);
|
|
82
|
+
const targetPath = process.execPath;
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
const res = await doFetch(url);
|
|
86
|
+
if (!res.ok) {
|
|
87
|
+
return {
|
|
88
|
+
success: false,
|
|
89
|
+
error: `Failed to download binary: HTTP ${res.status}`,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const bytes = await res.arrayBuffer();
|
|
94
|
+
await Bun.write(tmpPath, bytes);
|
|
95
|
+
|
|
96
|
+
await $`chmod +x ${tmpPath}`.quiet();
|
|
97
|
+
|
|
98
|
+
// Try to move into place.
|
|
99
|
+
const mv = await $`mv ${tmpPath} ${targetPath}`.quiet().nothrow();
|
|
100
|
+
|
|
101
|
+
if (mv.exitCode !== 0) {
|
|
102
|
+
// Fall back to sudo.
|
|
103
|
+
onProgress("Requires elevated permissions...");
|
|
104
|
+
const sudo = await $`sudo mv ${tmpPath} ${targetPath}`.nothrow();
|
|
105
|
+
if (sudo.exitCode !== 0) {
|
|
106
|
+
return {
|
|
107
|
+
success: false,
|
|
108
|
+
error: "Failed to install binary. Try running with sudo.",
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return { success: true };
|
|
114
|
+
} catch (err) {
|
|
115
|
+
// Clean up temp file.
|
|
116
|
+
await $`rm -f ${tmpPath}`.quiet().nothrow();
|
|
117
|
+
return { success: false, error: `Failed to upgrade binary: ${err}` };
|
|
118
|
+
}
|
|
119
|
+
}
|