upgradr 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -59,7 +59,11 @@ notice.then((msg) => {
59
59
 
60
60
  ```ts
61
61
  const info = await updater.checkForUpdate();
62
- if (info.hasUpdate) {
62
+ if (info.error) {
63
+ // The check didn't complete (offline, rate-limited, registry down, …) —
64
+ // this is distinct from "confirmed up to date".
65
+ console.error(`Update check failed: ${info.error}`);
66
+ } else if (info.hasUpdate) {
63
67
  console.log(`Update available: ${info.currentVersion} → ${info.latestVersion}`);
64
68
  if (info.changelog) console.log(info.changelog);
65
69
  } else if (info.aheadOfLatest) {
@@ -74,7 +78,11 @@ if (info.hasUpdate) {
74
78
  ```ts
75
79
  const result = await updater.upgrade(); // always performs a fresh check first
76
80
 
77
- if (!result.hasUpdate) {
81
+ if (!result.success && !result.performed && result.error) {
82
+ // The check couldn't complete — don't claim "up to date".
83
+ console.error(result.error);
84
+ process.exit(1);
85
+ } else if (!result.hasUpdate) {
78
86
  console.log(`Already up to date (v${result.from})`);
79
87
  } else if (result.method === "local-dev") {
80
88
  console.log("Running from source. Use `git pull && bun install` to update.");
@@ -101,10 +109,30 @@ if (!result.hasUpdate) {
101
109
  | `checkIntervalMs` | | 24h | How long a cached check stays fresh. |
102
110
  | `timeoutMs` | | 5000 | Timeout for the background network check. |
103
111
  | `backgroundSkipCommands` | | `["check-update","upgrade"]` | Commands that suppress the startup notice. |
112
+ | `formatNotice` | | built-in | `(ctx) => string` to fully render the startup notice. |
104
113
  | `assetName` | | — | `(target) => string` to fully override the release asset name. |
105
114
  | `fetchImpl` | | global `fetch` | Injectable `fetch` (for testing). |
106
115
  | `onProgress` | | no-op | Progress callback (e.g. the sudo heads-up during a binary swap). |
107
116
 
117
+ ## Customizing the notice
118
+
119
+ By default the startup notice is a yellow "Update available" header, an optional
120
+ dimmed changelog, and a cyan `Run <cli> upgrade` hint. Pass `formatNotice` to render
121
+ it yourself — you get the update details and return the whole string. The built-in
122
+ renderer is exported, so you can compose with it:
123
+
124
+ ```ts
125
+ import { createUpdater, formatNotice } from "upgradr";
126
+
127
+ const updater = createUpdater({
128
+ // …required config…
129
+ formatNotice: (ctx) =>
130
+ `${formatNotice(ctx)}\n (docs: https://example.com/changelog)\n`,
131
+ });
132
+ ```
133
+
134
+ `ctx` is `{ currentVersion, latestVersion, changelog?, cliName }`.
135
+
108
136
  ## Install-method detection
109
137
 
110
138
  `detectInstallMethod()` inspects `process.argv[1]` and `process.execPath`:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "upgradr",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
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
5
  "type": "module",
6
6
  "license": "MIT",
package/src/checker.ts CHANGED
@@ -9,6 +9,12 @@ export interface UpdateInfo {
9
9
  /** `current > latest` — running ahead of the published release (dev build). */
10
10
  aheadOfLatest: boolean;
11
11
  changelog?: string;
12
+ /**
13
+ * Set when the latest version could not be determined (registry non-OK,
14
+ * network failure, timeout, or offline). When present, `hasUpdate` is `false`
15
+ * because the check did not complete — not because the CLI is current.
16
+ */
17
+ error?: string;
12
18
  }
13
19
 
14
20
  /** The persisted result of a previous check (see `cache.ts`). */
@@ -24,24 +30,28 @@ export function isNewerVersion(current: string, latest: string): boolean {
24
30
  return Bun.semver.order(current, latest) === -1;
25
31
  }
26
32
 
27
- /** Fetch the latest published version from the npm registry. Falls back to `currentVersion` on error. */
33
+ /**
34
+ * Fetch the latest published version from the npm registry. Returns `null` when
35
+ * the version could not be determined (registry non-OK, network failure,
36
+ * timeout, or offline) so callers can distinguish "confirmed current" from
37
+ * "couldn't check".
38
+ */
28
39
  export async function fetchLatestVersion(opts: {
29
40
  packageName: string;
30
- currentVersion: string;
31
41
  fetchImpl?: FetchLike;
32
42
  signal?: AbortSignal;
33
- }): Promise<string> {
43
+ }): Promise<string | null> {
34
44
  const doFetch = opts.fetchImpl ?? fetch;
35
45
  try {
36
46
  const res = await doFetch(
37
47
  `https://registry.npmjs.org/${opts.packageName}/latest`,
38
48
  { signal: opts.signal },
39
49
  );
40
- if (!res.ok) return opts.currentVersion;
50
+ if (!res.ok) return null;
41
51
  const data = (await res.json()) as { version: string };
42
52
  return data.version;
43
53
  } catch {
44
- return opts.currentVersion;
54
+ return null;
45
55
  }
46
56
  }
47
57
 
@@ -98,10 +108,21 @@ export async function checkForUpdate(opts: {
98
108
  }): Promise<UpdateInfo> {
99
109
  const latestVersion = await fetchLatestVersion({
100
110
  packageName: opts.packageName,
101
- currentVersion: opts.currentVersion,
102
111
  fetchImpl: opts.fetchImpl,
103
112
  signal: opts.signal,
104
113
  });
114
+
115
+ if (latestVersion === null) {
116
+ // The check did not complete — surface it rather than reporting "current".
117
+ return {
118
+ currentVersion: opts.currentVersion,
119
+ latestVersion: opts.currentVersion,
120
+ hasUpdate: false,
121
+ aheadOfLatest: false,
122
+ error: `Could not determine the latest version of "${opts.packageName}" from the npm registry.`,
123
+ };
124
+ }
125
+
105
126
  const hasUpdate = isNewerVersion(opts.currentVersion, latestVersion);
106
127
  const aheadOfLatest = isNewerVersion(latestVersion, opts.currentVersion);
107
128
 
package/src/config.ts CHANGED
@@ -18,6 +18,18 @@ export interface AssetTarget {
18
18
  arch: string;
19
19
  }
20
20
 
21
+ /** Data passed to a custom {@link UpdaterConfig.formatNotice} renderer. */
22
+ export interface NoticeContext {
23
+ /** The currently-running version. */
24
+ currentVersion: string;
25
+ /** The newer version available. */
26
+ latestVersion: string;
27
+ /** Release changelog, when one was fetched. */
28
+ changelog?: string;
29
+ /** Display name for the CLI (see {@link UpdaterConfig.cliName}). */
30
+ cliName: string;
31
+ }
32
+
21
33
  /**
22
34
  * Configuration for {@link createUpdater}. Every value that would otherwise be
23
35
  * hardcoded to a specific project (repo, package name, cache location, …) is a
@@ -50,6 +62,12 @@ export interface UpdaterConfig {
50
62
  timeoutMs?: number;
51
63
  /** Commands for which the background notice is suppressed. Defaults to `["check-update", "upgrade"]`. */
52
64
  backgroundSkipCommands?: string[];
65
+ /**
66
+ * Render the whole background notice string. Receives the update details and
67
+ * returns the text shown to the user. Defaults to the built-in {@link formatNotice},
68
+ * which you can import and compose with (e.g. prefix or suffix its output).
69
+ */
70
+ formatNotice?: (ctx: NoticeContext) => string;
53
71
  /** Override the full release asset name for a platform. */
54
72
  assetName?: (target: AssetTarget) => string;
55
73
  /** Injectable `fetch` (for testing). Defaults to the global `fetch`. */
@@ -71,6 +89,7 @@ export interface ResolvedConfig {
71
89
  checkIntervalMs: number;
72
90
  timeoutMs: number;
73
91
  backgroundSkipCommands: string[];
92
+ formatNotice: ((ctx: NoticeContext) => string) | undefined;
74
93
  assetName: ((target: AssetTarget) => string) | undefined;
75
94
  fetchImpl: FetchLike;
76
95
  onProgress: (message: string) => void;
@@ -96,6 +115,7 @@ export function resolveConfig(config: UpdaterConfig): ResolvedConfig {
96
115
  timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,
97
116
  backgroundSkipCommands:
98
117
  config.backgroundSkipCommands ?? DEFAULT_BACKGROUND_SKIP_COMMANDS,
118
+ formatNotice: config.formatNotice,
99
119
  assetName: config.assetName,
100
120
  fetchImpl: config.fetchImpl ?? fetch,
101
121
  onProgress: config.onProgress ?? (() => {}),
package/src/index.ts CHANGED
@@ -30,6 +30,7 @@ export type {
30
30
  AssetTarget,
31
31
  FetchLike,
32
32
  InstallMethod,
33
+ NoticeContext,
33
34
  ResolvedConfig,
34
35
  UpdaterConfig,
35
36
  } from "./config.ts";
@@ -121,12 +122,6 @@ export function createUpdater(config: UpdaterConfig): Updater {
121
122
  // Always re-check: the background cache may be fresh but stale relative
122
123
  // to a release that shipped since the last check.
123
124
  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
125
 
131
126
  const method = detectInstallMethodImpl({
132
127
  localDevEntry: cfg.localDevEntry,
@@ -138,6 +133,18 @@ export function createUpdater(config: UpdaterConfig): Updater {
138
133
  hasUpdate: info.hasUpdate,
139
134
  };
140
135
 
136
+ // The check itself failed — don't cache a bogus result or report success.
137
+ if (info.error) {
138
+ return { ...base, performed: false, success: false, error: info.error };
139
+ }
140
+
141
+ await saveCache(cfg.cacheDir, {
142
+ lastCheckAt: new Date().toISOString(),
143
+ latestVersion: info.latestVersion,
144
+ hasUpdate: info.hasUpdate,
145
+ changelog: info.changelog,
146
+ });
147
+
141
148
  if (!info.hasUpdate) {
142
149
  return { ...base, performed: false, success: true };
143
150
  }
package/src/notice.ts CHANGED
@@ -1,27 +1,22 @@
1
1
  import { cyan, dim, yellow } from "ansis";
2
2
  import { loadCache, saveCache } from "./cache.ts";
3
3
  import { checkForUpdate, needsCheck, type UpdateCache } from "./checker.ts";
4
- import type { ResolvedConfig } from "./config.ts";
4
+ import type { NoticeContext, ResolvedConfig } from "./config.ts";
5
5
 
6
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 {
7
+ export function formatNotice(ctx: NoticeContext): string {
13
8
  const lines: string[] = [
14
9
  "",
15
- yellow(`Update available: ${opts.currentVersion} → ${opts.latestVersion}`),
10
+ yellow(`Update available: ${ctx.currentVersion} → ${ctx.latestVersion}`),
16
11
  ];
17
12
 
18
- if (opts.changelog) {
13
+ if (ctx.changelog) {
19
14
  lines.push("");
20
- lines.push(dim(opts.changelog));
15
+ lines.push(dim(ctx.changelog));
21
16
  }
22
17
 
23
18
  lines.push("");
24
- lines.push(cyan(`Run \`${opts.cliName} upgrade\` to update`));
19
+ lines.push(cyan(`Run \`${ctx.cliName} upgrade\` to update`));
25
20
  lines.push("");
26
21
 
27
22
  return lines.join("\n");
@@ -59,12 +54,13 @@ export async function maybeBackgroundNotice(
59
54
  // Only show in an interactive terminal.
60
55
  if (!isTTY) return null;
61
56
 
57
+ const render = cfg.formatNotice ?? formatNotice;
62
58
  const cache = await loadCache(cfg.cacheDir);
63
59
 
64
60
  if (!needsCheck(cache, cfg.checkIntervalMs)) {
65
61
  // Cache is fresh — use the cached result.
66
62
  if (cache?.hasUpdate) {
67
- return formatNotice({
63
+ return render({
68
64
  currentVersion: cfg.currentVersion,
69
65
  latestVersion: cache.latestVersion,
70
66
  changelog: cache.changelog,
@@ -87,6 +83,10 @@ export async function maybeBackgroundNotice(
87
83
  signal: controller.signal,
88
84
  });
89
85
 
86
+ // Only cache a completed check — a failed check must not suppress the
87
+ // next attempt (nor be silently reported as "up to date").
88
+ if (info.error) return null;
89
+
90
90
  const newCache: UpdateCache = {
91
91
  lastCheckAt: new Date().toISOString(),
92
92
  latestVersion: info.latestVersion,
@@ -96,7 +96,7 @@ export async function maybeBackgroundNotice(
96
96
  await saveCache(cfg.cacheDir, newCache);
97
97
 
98
98
  if (info.hasUpdate) {
99
- return formatNotice({
99
+ return render({
100
100
  currentVersion: cfg.currentVersion,
101
101
  latestVersion: info.latestVersion,
102
102
  changelog: info.changelog,