claude-rpc 1.5.4 → 1.7.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 +56 -56
- package/SECURITY.md +22 -6
- package/package.json +2 -1
- package/src/cli.js +176 -90
- package/src/commands.js +248 -0
- package/src/completion.js +196 -0
- package/src/daemon.js +27 -1
- package/src/default-config.js +10 -3
- package/src/doctor.js +1 -1
- package/src/help.js +117 -0
- package/src/install.js +2 -0
- package/src/nudge.js +2 -2
- package/src/png.js +135 -0
- package/src/pricing.js +1 -1
- package/src/select.js +60 -0
- package/src/statcards.js +278 -0
- package/src/updater.js +141 -0
- package/src/version.js +1 -1
package/src/statcards.js
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
// `claude-rpc statcards` — every shareable card in one place, each to a live
|
|
2
|
+
// link (served by the worker, refreshes itself as you work), a PNG, or an SVG.
|
|
3
|
+
//
|
|
4
|
+
// claude-rpc statcards menu: pick a card, then where it goes
|
|
5
|
+
// claude-rpc statcards stats --link --md Markdown for a README, to stdout
|
|
6
|
+
// claude-rpc statcards poster --png ./claude-poster.png
|
|
7
|
+
// claude-rpc statcards badge --metric streak --svg streak.svg
|
|
8
|
+
// claude-rpc statcards list what exists and where it can go
|
|
9
|
+
//
|
|
10
|
+
// Live links need a public profile (the worker renders from what it has
|
|
11
|
+
// published). PNG/SVG render locally from the aggregate when the card has a
|
|
12
|
+
// local renderer, otherwise from the live link. The older one-card commands
|
|
13
|
+
// (badge, card, github-stat, calendar, session-card, readme) still work
|
|
14
|
+
// unchanged.
|
|
15
|
+
|
|
16
|
+
import { writeFileSync } from 'node:fs';
|
|
17
|
+
import { resolve, relative } from 'node:path';
|
|
18
|
+
import { c, fail, EX_USER_ERROR, EX_BAD_STATE, EX_SYS_ERROR } from './ui.js';
|
|
19
|
+
import { isValidHandle } from './leaderboard.js';
|
|
20
|
+
|
|
21
|
+
const SITE = 'https://claude-rpc.com';
|
|
22
|
+
const DEFAULT_ENDPOINT = 'https://claude-rpc-totals.claude-rpc.workers.dev';
|
|
23
|
+
|
|
24
|
+
const q = (metric, fallback) => (metric && metric !== fallback ? `?metric=${metric}` : '');
|
|
25
|
+
|
|
26
|
+
export const CARDS = [
|
|
27
|
+
{ id: 'stats', title: 'Stats + heatmap', blurb: 'totals over your year heatmap — the README hero',
|
|
28
|
+
metrics: ['tokens', 'hours'],
|
|
29
|
+
hosted: (h, o) => `/stats/${h}.svg${q(o.metric, 'tokens')}`, page: (h) => `${SITE}/u/${h}`,
|
|
30
|
+
local: async (ctx, o) => (await import('./calendar.js')).renderCalendarCard(ctx.aggregate(), { metric: o.metric || 'tokens', handle: ctx.handle }) },
|
|
31
|
+
{ id: 'profile', title: 'Profile card', blurb: 'tokens, sessions, hours and streak on one card',
|
|
32
|
+
hosted: (h) => `/card/${h}.svg`, page: (h) => `${SITE}/u/${h}`,
|
|
33
|
+
local: async (ctx) => (await import('./profile.js')).renderProfileCard(ctx.aggregate(), { handle: ctx.handle }) },
|
|
34
|
+
{ id: 'badge', title: 'Badge', blurb: 'a small shields-style badge',
|
|
35
|
+
metrics: ['hours', 'tokens', 'streak', 'sessions'], localMetrics: ['hours', 'tokens', 'streak', 'prompts', 'cost', 'lines', 'files'],
|
|
36
|
+
hosted: (h, o) => `/badge/${h}.svg?metric=${o.metric || 'hours'}`, page: () => `${SITE}/?ref=badge`,
|
|
37
|
+
local: async (ctx, o) => (await import('./badge.js')).badgeSvg({ aggregate: ctx.aggregate(), metric: o.metric || 'hours', range: o.range || '7d' }) },
|
|
38
|
+
{ id: 'heatmap', title: 'Year heatmap', blurb: 'just the GitHub-style year grid',
|
|
39
|
+
metrics: ['tokens', 'hours'],
|
|
40
|
+
hosted: (h, o) => `/heatmap/${h}.svg${q(o.metric, 'tokens')}`, page: (h) => `${SITE}/u/${h}`,
|
|
41
|
+
local: async (ctx, o) => (await import('./calendar.js')).renderCalendar(ctx.aggregate(), { metric: o.metric || 'tokens' }) },
|
|
42
|
+
{ id: 'poster', title: 'Poster', blurb: 'the big summary poster (great in Discord)',
|
|
43
|
+
ranges: ['year', 'month', 'week', 'all'],
|
|
44
|
+
local: async (ctx, o) => (await import('./card.js')).renderCard(ctx.aggregate(), { range: o.range || 'year' }) },
|
|
45
|
+
{ id: 'session', title: 'This session', blurb: 'recap of the session you are in',
|
|
46
|
+
local: async (ctx) => (await import('./session-card.js')).renderSessionCard(ctx.liveVars(), {}) },
|
|
47
|
+
{ id: 'wrapped', title: 'Wrapped card', blurb: 'your year in review (after wrapped --publish)',
|
|
48
|
+
hosted: (h, o) => `/wrapped/${h}.svg${o.year ? `?year=${o.year}` : ''}`, page: (h) => `${SITE}/wrapped/${h}` },
|
|
49
|
+
];
|
|
50
|
+
|
|
51
|
+
export const OUTPUTS = ['link', 'png', 'svg'];
|
|
52
|
+
const cardById = (id) => CARDS.find((k) => k.id === id) || null;
|
|
53
|
+
|
|
54
|
+
// Parse statcards' argv. `--png`/`--svg` take an optional path: the next token,
|
|
55
|
+
// unless it is a flag or a card name.
|
|
56
|
+
export function parseArgs(argv) {
|
|
57
|
+
const o = { card: null, out: null, path: null, md: false, html: false, copy: false, metric: null, range: null, year: null };
|
|
58
|
+
for (let i = 0; i < argv.length; i++) {
|
|
59
|
+
let a = argv[i];
|
|
60
|
+
let val = null;
|
|
61
|
+
const eq = a.indexOf('=');
|
|
62
|
+
if (a.startsWith('--') && eq !== -1) { val = a.slice(eq + 1); a = a.slice(0, eq); }
|
|
63
|
+
const next = () => val ?? (argv[i + 1] && !argv[i + 1].startsWith('-') ? argv[++i] : null);
|
|
64
|
+
if (a === '--link' || a === '--url') o.out = 'link';
|
|
65
|
+
else if (a === '--png' || a === '--svg') {
|
|
66
|
+
o.out = a.slice(2);
|
|
67
|
+
const n = val ?? argv[i + 1];
|
|
68
|
+
if (n && !n.startsWith('-') && !cardById(n)) { o.path = n; if (val === null) i++; }
|
|
69
|
+
} else if (a === '--md' || a === '--markdown') { o.md = true; o.out = o.out || 'link'; }
|
|
70
|
+
else if (a === '--html') { o.html = true; o.out = o.out || 'link'; }
|
|
71
|
+
else if (a === '--copy') o.copy = true;
|
|
72
|
+
else if (a === '--metric' || a === '-m') o.metric = next();
|
|
73
|
+
else if (a === '--range' || a === '-r') o.range = next();
|
|
74
|
+
else if (a === '--year') o.year = next();
|
|
75
|
+
else if (!a.startsWith('-') && !o.card) o.card = a;
|
|
76
|
+
else return { error: `unknown option ${argv[i]}` };
|
|
77
|
+
}
|
|
78
|
+
return o;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function snippets(card, handle, opts, endpoint = DEFAULT_ENDPOINT) {
|
|
82
|
+
const url = endpoint.replace(/\/+$/, '') + card.hosted(handle, opts);
|
|
83
|
+
const page = card.page(handle);
|
|
84
|
+
const alt = card.id === 'badge' ? `Claude Code ${opts.metric || 'hours'}` : 'Claude Code stats';
|
|
85
|
+
return {
|
|
86
|
+
url,
|
|
87
|
+
md: `[](${page})`,
|
|
88
|
+
html: `<a href="${page}"><img src="${url}" alt="${alt}" /></a>`,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Copy text to the system clipboard. Returns the tool used, or null.
|
|
93
|
+
export async function copyToClipboard(text, platform = process.platform, env = process.env) {
|
|
94
|
+
const { spawnSync } = await import('node:child_process');
|
|
95
|
+
const tries = platform === 'darwin' ? [['pbcopy', []]]
|
|
96
|
+
: platform === 'win32' ? [['clip', []]]
|
|
97
|
+
: [...(env.WAYLAND_DISPLAY ? [['wl-copy', []]] : []), ['xclip', ['-selection', 'clipboard']], ['xsel', ['--clipboard', '--input']]];
|
|
98
|
+
for (const [bin, args] of tries) {
|
|
99
|
+
try {
|
|
100
|
+
const r = spawnSync(bin, args, { input: text, timeout: 3000, windowsHide: true, stdio: ['pipe', 'ignore', 'ignore'] });
|
|
101
|
+
if (r.status === 0) return bin;
|
|
102
|
+
} catch { /* not installed — next */ }
|
|
103
|
+
}
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function printList(ctx) {
|
|
108
|
+
const live = ctx.live;
|
|
109
|
+
console.log('');
|
|
110
|
+
console.log(` ${c.bold}${c.magenta}◆ Stat cards${c.reset} ${c.dim}— claude-rpc statcards <card> [--link|--png|--svg]${c.reset}`);
|
|
111
|
+
console.log('');
|
|
112
|
+
const w = CARDS.reduce((m, k) => Math.max(m, k.id.length), 0);
|
|
113
|
+
for (const k of CARDS) {
|
|
114
|
+
const where = [k.hosted ? 'link' : null, 'png', 'svg'].filter(Boolean).join(' · ');
|
|
115
|
+
const extra = k.metrics ? ` ${c.gray}--metric ${(k.localMetrics ? [...new Set([...k.metrics, ...k.localMetrics])] : k.metrics).join('|')}${c.reset}`
|
|
116
|
+
: k.ranges ? ` ${c.gray}--range ${k.ranges.join('|')}${c.reset}` : '';
|
|
117
|
+
console.log(` ${c.cyan}${k.id.padEnd(w)}${c.reset} ${k.blurb} ${c.dim}[${where}]${c.reset}${extra}`);
|
|
118
|
+
}
|
|
119
|
+
console.log('');
|
|
120
|
+
console.log(live
|
|
121
|
+
? ` ${c.green}●${c.reset} ${c.dim}live links on — public profile ${c.reset}${c.cyan}@${ctx.handle}${c.reset}`
|
|
122
|
+
: ` ${c.yellow}○${c.reset} ${c.dim}live links need a public profile: ${c.reset}${c.cyan}claude-rpc profile set --handle <name>${c.reset}${c.dim} then ${c.reset}${c.cyan}claude-rpc profile on${c.reset}`);
|
|
123
|
+
console.log('');
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function renderSvg(card, ctx, opts) {
|
|
127
|
+
if (card.local) return card.local(ctx, opts);
|
|
128
|
+
// Hosted-only card: fetch what the worker serves.
|
|
129
|
+
const { url } = snippets(card, ctx.handle, opts, ctx.endpoint);
|
|
130
|
+
const res = await fetch(url, { headers: { 'user-agent': 'claude-rpc statcards' } });
|
|
131
|
+
if (!res.ok) throw new Error(`${url} answered HTTP ${res.status}`);
|
|
132
|
+
return res.text();
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// ctx: { aggregate(), liveVars(), config, prompt(q), enableProfile() }
|
|
136
|
+
export async function runStatcards(argv, ctx) {
|
|
137
|
+
const o = parseArgs(argv);
|
|
138
|
+
if (o.error) return fail(o.error, { hint: 'claude-rpc help statcards', code: EX_USER_ERROR });
|
|
139
|
+
const cfg = ctx.config;
|
|
140
|
+
const profile = cfg.profile || {};
|
|
141
|
+
ctx.handle = isValidHandle(profile.handle) ? profile.handle : '';
|
|
142
|
+
ctx.live = !!profile.enabled && !!ctx.handle;
|
|
143
|
+
ctx.endpoint = (cfg.community?.endpoint || DEFAULT_ENDPOINT).replace(/\/+$/, '');
|
|
144
|
+
const tty = !!(process.stdout.isTTY && process.stdin.isTTY);
|
|
145
|
+
const { select } = tty ? await import('./select.js') : {};
|
|
146
|
+
|
|
147
|
+
if (o.card === 'list') return printList(ctx);
|
|
148
|
+
|
|
149
|
+
// 1. Which card.
|
|
150
|
+
let card = o.card ? cardById(o.card) : null;
|
|
151
|
+
if (o.card && !card) {
|
|
152
|
+
return fail(`no card called "${o.card}"`, { hint: `cards: ${CARDS.map((k) => k.id).join(', ')}`, code: EX_USER_ERROR });
|
|
153
|
+
}
|
|
154
|
+
if (!card) {
|
|
155
|
+
if (!tty) return printList(ctx);
|
|
156
|
+
console.log('');
|
|
157
|
+
const i = await select({
|
|
158
|
+
title: 'Which card?',
|
|
159
|
+
options: CARDS.map((k) => ({ label: k.title, hint: k.blurb })),
|
|
160
|
+
});
|
|
161
|
+
if (i === null) return;
|
|
162
|
+
card = CARDS[i];
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// 2. Where it goes.
|
|
166
|
+
let out = o.out;
|
|
167
|
+
if (out === 'link' && !card.hosted) {
|
|
168
|
+
return fail(`the ${card.id} card has no live link`, { hint: `save it instead: claude-rpc statcards ${card.id} --png`, code: EX_USER_ERROR });
|
|
169
|
+
}
|
|
170
|
+
if (!out && !tty) out = 'svg';
|
|
171
|
+
if (!out) {
|
|
172
|
+
const linkWhy = !card.hosted ? 'only renders on this machine' : !ctx.live ? 'needs a public profile — you can turn it on next' : '';
|
|
173
|
+
const i = await select({
|
|
174
|
+
title: 'Where to?',
|
|
175
|
+
options: [
|
|
176
|
+
{ label: 'Live link', hint: 'paste once in a README or site; it keeps itself up to date', disabled: !card.hosted ? linkWhy : '' },
|
|
177
|
+
{ label: 'PNG image', hint: 'for Discord, X, LinkedIn, slides' },
|
|
178
|
+
{ label: 'SVG file', hint: 'crisp at any size' },
|
|
179
|
+
],
|
|
180
|
+
initial: card.hosted && ctx.live ? 0 : 1,
|
|
181
|
+
});
|
|
182
|
+
if (i === null) return;
|
|
183
|
+
out = OUTPUTS[i];
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// 3. Options the card takes.
|
|
187
|
+
const metrics = out === 'link' || !card.local ? card.metrics : (card.localMetrics || card.metrics);
|
|
188
|
+
if (o.metric && metrics && !metrics.includes(o.metric)) {
|
|
189
|
+
return fail(`--metric ${o.metric} isn't available for the ${card.id} card${out === 'link' ? ' as a live link' : ''}`,
|
|
190
|
+
{ hint: `use one of: ${metrics.join(', ')}`, code: EX_USER_ERROR });
|
|
191
|
+
}
|
|
192
|
+
if (o.metric && !metrics) return fail(`the ${card.id} card has no --metric`, { code: EX_USER_ERROR });
|
|
193
|
+
if (o.range && !(card.ranges || card.id === 'badge')) return fail(`the ${card.id} card has no --range`, { code: EX_USER_ERROR });
|
|
194
|
+
if (tty && !o.metric && metrics) {
|
|
195
|
+
const list = metrics;
|
|
196
|
+
const i = await select({ title: 'Counting?', options: list.map((m) => ({ label: m })) });
|
|
197
|
+
if (i === null) return;
|
|
198
|
+
o.metric = list[i];
|
|
199
|
+
}
|
|
200
|
+
if (tty && !o.range && card.ranges && out !== 'link') {
|
|
201
|
+
const i = await select({ title: 'Covering?', options: card.ranges.map((r) => ({ label: r === 'all' ? 'all time' : `this ${r}` })) });
|
|
202
|
+
if (i === null) return;
|
|
203
|
+
o.range = card.ranges[i];
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Live link (or a hosted-only card's file) needs the public profile.
|
|
207
|
+
if ((out === 'link' || !card.local) && !ctx.live) {
|
|
208
|
+
if (!ctx.handle) {
|
|
209
|
+
return fail('live cards need a public profile', {
|
|
210
|
+
hint: ['claude-rpc profile set --handle <name>', 'claude-rpc profile on — then run this again'], code: EX_BAD_STATE,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
if (!tty) return fail(`your profile @${ctx.handle} is private`, { hint: 'claude-rpc profile on', code: EX_BAD_STATE });
|
|
214
|
+
const answer = (await ctx.prompt(` Make @${ctx.handle} public so the link works? ${c.dim}[y/N]${c.reset} `)).trim().toLowerCase();
|
|
215
|
+
if (answer !== 'y' && answer !== 'yes') {
|
|
216
|
+
console.log(` ${c.dim}left private — PNG and SVG work without it.${c.reset}`);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
await ctx.enableProfile();
|
|
220
|
+
ctx.live = true;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (out === 'link') return emitLink(card, ctx, o, tty);
|
|
224
|
+
return emitFile(card, ctx, o, out, tty);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async function emitLink(card, ctx, o, tty) {
|
|
228
|
+
const s = snippets(card, ctx.handle, o, ctx.endpoint);
|
|
229
|
+
// Pipe-friendly: just the one thing asked for.
|
|
230
|
+
if (!tty) {
|
|
231
|
+
const text = o.md ? s.md : o.html ? s.html : s.url;
|
|
232
|
+
if (o.copy) await copyToClipboard(text);
|
|
233
|
+
process.stdout.write(text + '\n');
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
console.log('');
|
|
238
|
+
console.log(` ${c.green}✓${c.reset} ${c.bold}${card.title}${c.reset} ${c.dim}— live; it refreshes itself as you work${c.reset}`);
|
|
239
|
+
console.log('');
|
|
240
|
+
console.log(` ${c.dim}link ${c.reset}${c.cyan}${s.url}${c.reset}`);
|
|
241
|
+
console.log(` ${c.dim}markdown ${c.reset}${s.md}`);
|
|
242
|
+
console.log(` ${c.dim}html ${c.reset}${s.html}`);
|
|
243
|
+
console.log('');
|
|
244
|
+
const which = o.html ? 'html' : 'md';
|
|
245
|
+
const tool = await copyToClipboard(s[which]);
|
|
246
|
+
if (tool) console.log(` ${c.magenta}⧉${c.reset} ${c.dim}${which === 'html' ? 'HTML' : 'Markdown'} copied — paste it into your README${c.reset}`);
|
|
247
|
+
if (card.id === 'wrapped') console.log(` ${c.dim}shows your year once it's published: ${c.reset}${c.cyan}claude-rpc wrapped --publish${c.reset}`);
|
|
248
|
+
console.log('');
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async function emitFile(card, ctx, o, out, tty) {
|
|
252
|
+
let svg;
|
|
253
|
+
try {
|
|
254
|
+
svg = await renderSvg(card, ctx, o);
|
|
255
|
+
} catch (e) {
|
|
256
|
+
return fail(`couldn't render the ${card.id} card: ${e.message}`, { code: EX_SYS_ERROR });
|
|
257
|
+
}
|
|
258
|
+
const suffix = [card.id, o.metric && card.metrics && o.metric !== card.metrics[0] ? o.metric : null, o.range && o.range !== 'year' ? o.range : null]
|
|
259
|
+
.filter(Boolean).join('-');
|
|
260
|
+
const path = resolve(o.path || `claude-${suffix}.${out}`);
|
|
261
|
+
const shown = relative(process.cwd(), path) || path;
|
|
262
|
+
|
|
263
|
+
if (out === 'svg') {
|
|
264
|
+
if (!o.path && !tty && !o.out) { process.stdout.write(svg); return; }
|
|
265
|
+
writeFileSync(path, svg);
|
|
266
|
+
console.log(` ${c.green}✓${c.reset} saved ${c.cyan}${shown}${c.reset} ${c.dim}(${svg.length} bytes)${c.reset}`);
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const { svgToPng } = await import('./png.js');
|
|
271
|
+
try {
|
|
272
|
+
const r = await svgToPng(svg, path);
|
|
273
|
+
console.log(` ${c.green}✓${c.reset} saved ${c.cyan}${shown}${c.reset} ${c.dim}(${r.width}×${r.height}, via ${r.via})${c.reset}`);
|
|
274
|
+
if (tty) console.log(` ${c.dim}drag it into Discord, X or a slide — it's 2× for sharp screens${c.reset}`);
|
|
275
|
+
} catch (e) {
|
|
276
|
+
return fail(e.message, { hint: e.hint || '', code: EX_SYS_ERROR });
|
|
277
|
+
}
|
|
278
|
+
}
|
package/src/updater.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Auto-update for npm global installs.
|
|
2
|
+
//
|
|
3
|
+
// The daemon checks the npm registry every few hours; when a newer release in
|
|
4
|
+
// the SAME major line exists it runs `npm install -g claude-rpc@<exact
|
|
5
|
+
// version>`, then restarts itself. Hooks and config follow on their own — the
|
|
6
|
+
// daemon's self-heal-on-update (daemon.js) re-wires them on first boot of the
|
|
7
|
+
// new version. Everything else (brew, npx, the packaged exe, a source checkout)
|
|
8
|
+
// is never touched: those get a one-line "update available" with the right
|
|
9
|
+
// command. A new MAJOR is never installed unattended.
|
|
10
|
+
//
|
|
11
|
+
// Pure decision functions up top (unit-tested); side effects below.
|
|
12
|
+
|
|
13
|
+
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
14
|
+
import { join, dirname, delimiter } from 'node:path';
|
|
15
|
+
import { STATE_DIR, ROOT, IS_PACKAGED, IS_NPM_INSTALL, IS_NPX } from './paths.js';
|
|
16
|
+
|
|
17
|
+
export const UPDATE_STATE_PATH = join(STATE_DIR, 'update.json');
|
|
18
|
+
export const REGISTRY_URL = 'https://registry.npmjs.org/claude-rpc/latest';
|
|
19
|
+
const RETRY_FAILED_MS = 24 * 3_600_000; // don't hammer a version that failed to install
|
|
20
|
+
const COOLDOWN_MS = 2 * 3_600_000; // a release must be seen this long before it's installed — a yank window
|
|
21
|
+
const INSTALL_TIMEOUT_MS = 180_000;
|
|
22
|
+
const FETCH_TIMEOUT_MS = 8_000;
|
|
23
|
+
|
|
24
|
+
const SEMVER = /^(\d+)\.(\d+)\.(\d+)$/; // no prereleases: only stable tags are ever considered
|
|
25
|
+
|
|
26
|
+
export function parseVersion(v) {
|
|
27
|
+
const m = SEMVER.exec(String(v || '').trim());
|
|
28
|
+
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function isNewer(latest, current) {
|
|
32
|
+
const a = parseVersion(latest), b = parseVersion(current);
|
|
33
|
+
if (!a || !b) return false;
|
|
34
|
+
for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function sameMajor(a, b) {
|
|
39
|
+
const x = parseVersion(a), y = parseVersion(b);
|
|
40
|
+
return !!x && !!y && x[0] === y[0];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// How this copy was installed → whether we may update it ourselves and what to
|
|
44
|
+
// tell the user otherwise.
|
|
45
|
+
export function installKind({ packaged = IS_PACKAGED, npm = IS_NPM_INSTALL, npx = IS_NPX, root = ROOT } = {}) {
|
|
46
|
+
if (packaged) return 'packaged';
|
|
47
|
+
if (npx) return 'npx';
|
|
48
|
+
if (/[\\/]Cellar[\\/]/.test(root)) return 'brew';
|
|
49
|
+
if (npm) return 'npm-global';
|
|
50
|
+
return 'dev';
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function updateCommand(kind) {
|
|
54
|
+
switch (kind) {
|
|
55
|
+
case 'packaged': return 'download the latest release from https://github.com/rar-file/claude-rpc/releases/latest';
|
|
56
|
+
case 'npx': return 'npx claude-rpc@latest setup';
|
|
57
|
+
case 'brew': return 'brew upgrade claude-rpc';
|
|
58
|
+
case 'dev': return 'git pull';
|
|
59
|
+
default: return 'npm install -g claude-rpc@latest';
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// → { action: 'none' | 'notify' | 'install', reason }
|
|
64
|
+
export function planUpdate({ current, latest, auto = true, kind, failed = null, seen = null, cooldownMs = COOLDOWN_MS, now = Date.now() }) {
|
|
65
|
+
if (!isNewer(latest, current)) return { action: 'none', reason: 'up to date' };
|
|
66
|
+
if (kind !== 'npm-global') return { action: 'notify', reason: `installed via ${kind}` };
|
|
67
|
+
if (!auto) return { action: 'notify', reason: 'auto-update is off' };
|
|
68
|
+
if (!sameMajor(latest, current)) return { action: 'notify', reason: 'new major version — update manually' };
|
|
69
|
+
if (failed && failed.version === latest && now - failed.at < RETRY_FAILED_MS) {
|
|
70
|
+
return { action: 'notify', reason: 'last install attempt failed — retrying later' };
|
|
71
|
+
}
|
|
72
|
+
if (cooldownMs > 0 && !(seen && seen.version === latest && now - seen.at >= cooldownMs)) {
|
|
73
|
+
return { action: 'notify', reason: 'new release is settling — installing after the cooldown' };
|
|
74
|
+
}
|
|
75
|
+
return { action: 'install', reason: 'newer release available' };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function readUpdateState(path = UPDATE_STATE_PATH) {
|
|
79
|
+
try { return JSON.parse(readFileSync(path, 'utf8')) || {}; } catch { return {}; }
|
|
80
|
+
}
|
|
81
|
+
export function writeUpdateState(patch, path = UPDATE_STATE_PATH) {
|
|
82
|
+
try {
|
|
83
|
+
mkdirSync(STATE_DIR, { recursive: true });
|
|
84
|
+
writeFileSync(path, JSON.stringify({ ...readUpdateState(path), ...patch }));
|
|
85
|
+
} catch { /* best-effort: state is advisory */ }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Latest published version, or null on any failure. Only the version string is
|
|
89
|
+
// read; nothing about this machine is sent (a bare GET to the public registry).
|
|
90
|
+
export async function fetchLatest({ url = REGISTRY_URL, timeoutMs = FETCH_TIMEOUT_MS } = {}) {
|
|
91
|
+
try {
|
|
92
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs), headers: { accept: 'application/json' } });
|
|
93
|
+
if (!res.ok) return null;
|
|
94
|
+
const v = (await res.json())?.version;
|
|
95
|
+
return parseVersion(v) ? v : null;
|
|
96
|
+
} catch { return null; }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Install exactly `version` globally. Resolves { ok, output }. `npm` is a .cmd
|
|
100
|
+
// shim on Windows, which only spawns through a shell.
|
|
101
|
+
export async function installVersion(version) {
|
|
102
|
+
if (!parseVersion(version)) return { ok: false, output: 'bad version' }; // also keeps the shell arg safe
|
|
103
|
+
const { spawn } = await import('node:child_process');
|
|
104
|
+
return new Promise((resolve) => {
|
|
105
|
+
let out = '';
|
|
106
|
+
const win = process.platform === 'win32';
|
|
107
|
+
const child = spawn(win ? 'npm.cmd' : 'npm', ['install', '-g', `claude-rpc@${version}`, '--no-fund', '--no-audit'],
|
|
108
|
+
// Put the running node's own dir first so `npm` is the one that belongs to
|
|
109
|
+
// this node (nvm/fnm/volta installs; a login-launched daemon often has a
|
|
110
|
+
// bare PATH) — i.e. the npm that created the global we're replacing.
|
|
111
|
+
{ shell: win, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],
|
|
112
|
+
env: { ...process.env, PATH: `${dirname(process.execPath)}${delimiter}${process.env.PATH || ''}` } });
|
|
113
|
+
const timer = setTimeout(() => { try { child.kill(); } catch { /* gone */ } }, INSTALL_TIMEOUT_MS);
|
|
114
|
+
const take = (d) => { out = (out + d).slice(-2000); };
|
|
115
|
+
child.stdout.on('data', take); child.stderr.on('data', take);
|
|
116
|
+
child.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, output: e.message }); });
|
|
117
|
+
child.on('close', (code) => { clearTimeout(timer); resolve({ ok: code === 0, output: out.trim() }); });
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// One check cycle. Returns { plan, latest, installed }. `install` is injectable
|
|
122
|
+
// for tests; callers restart the daemon when `installed` is true.
|
|
123
|
+
export async function checkForUpdate({ current, auto, kind = installKind(), fetchLatestFn = fetchLatest, install = installVersion, now = Date.now(), cooldownMs = COOLDOWN_MS, statePath = UPDATE_STATE_PATH } = {}) {
|
|
124
|
+
const latest = await fetchLatestFn();
|
|
125
|
+
writeUpdateState({ checkedAt: now, ...(latest ? { latest } : {}) }, statePath);
|
|
126
|
+
if (!latest) return { plan: { action: 'none', reason: 'registry unreachable' }, latest: null, installed: false };
|
|
127
|
+
let state = readUpdateState(statePath);
|
|
128
|
+
if (state.seen?.version !== latest) { // first sighting starts the cooldown clock
|
|
129
|
+
writeUpdateState({ seen: { version: latest, at: now } }, statePath);
|
|
130
|
+
state = readUpdateState(statePath);
|
|
131
|
+
}
|
|
132
|
+
const plan = planUpdate({ current, latest, auto, kind, failed: state.failed || null, seen: state.seen || null, cooldownMs, now });
|
|
133
|
+
if (plan.action !== 'install') return { plan, latest, installed: false };
|
|
134
|
+
const res = await install(latest);
|
|
135
|
+
if (res.ok) {
|
|
136
|
+
writeUpdateState({ updatedFrom: current, updatedTo: latest, updatedAt: now, failed: null }, statePath);
|
|
137
|
+
return { plan, latest, installed: true };
|
|
138
|
+
}
|
|
139
|
+
writeUpdateState({ failed: { version: latest, at: now, output: res.output.slice(-300) } }, statePath);
|
|
140
|
+
return { plan: { action: 'notify', reason: 'install failed' }, latest, installed: false, error: res.output };
|
|
141
|
+
}
|