claude-rpc 1.5.2 → 1.6.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.
Files changed (52) hide show
  1. package/README.md +72 -62
  2. package/SECURITY.md +99 -20
  3. package/package.json +2 -1
  4. package/src/atomic-rename.js +45 -2
  5. package/src/badge.js +3 -4
  6. package/src/card.js +1 -22
  7. package/src/cli-path.js +286 -0
  8. package/src/cli.js +430 -459
  9. package/src/commands.js +245 -0
  10. package/src/community.js +101 -60
  11. package/src/completion.js +196 -0
  12. package/src/config.js +4 -1
  13. package/src/daemon.js +45 -47
  14. package/src/default-config.js +4 -3
  15. package/src/discord-ipc.js +24 -13
  16. package/src/doctor.js +64 -38
  17. package/src/ensure-daemon.js +11 -4
  18. package/src/fmt.js +8 -6
  19. package/src/format.js +8 -13
  20. package/src/gist.js +8 -18
  21. package/src/git.js +4 -1
  22. package/src/help.js +117 -0
  23. package/src/hook.js +27 -32
  24. package/src/insights.js +3 -4
  25. package/src/install.js +100 -79
  26. package/src/leaderboard.js +3 -2
  27. package/src/mcp.js +2 -8
  28. package/src/nudge.js +10 -5
  29. package/src/png.js +135 -0
  30. package/src/pricing.js +25 -3
  31. package/src/privacy.js +22 -7
  32. package/src/profile.js +0 -6
  33. package/src/recap.js +4 -17
  34. package/src/scanner.js +103 -71
  35. package/src/select.js +60 -0
  36. package/src/server/api.js +64 -36
  37. package/src/server/assets/dashboard.client.js +75 -44
  38. package/src/server/assets/dashboard.css +18 -18
  39. package/src/server/assets/dashboard.html +13 -15
  40. package/src/server/assets/wrapped.client.js +26 -11
  41. package/src/server/assets/wrapped.css +2 -2
  42. package/src/server/index.js +43 -32
  43. package/src/server/page.js +6 -3
  44. package/src/server/sse.js +90 -34
  45. package/src/session-card.js +3 -1
  46. package/src/statcards.js +278 -0
  47. package/src/state.js +14 -24
  48. package/src/tui.js +3 -12
  49. package/src/ui.js +7 -5
  50. package/src/verify.js +3 -7
  51. package/src/version.js +1 -1
  52. package/src/week.js +4 -4
@@ -6,7 +6,8 @@
6
6
  // server/api.js — data helpers (snapshot, windowedAggregate, drilldowns)
7
7
  // server/routes.js — declarative /api/* route table
8
8
  // server/sse.js — SSE broadcast + file watchers
9
- // server/page.js — all browser-side assets (HTML/CSS/JS strings)
9
+ // server/page.js — composes the dashboard + /wrapped pages from the
10
+ // on-disk files in server/assets/ (via assets.js)
10
11
  //
11
12
  // Zero deps, vanilla browser JS, SVG charts. Designed to run alongside the
12
13
  // daemon on localhost:47474 so the user can poke at their own data.
@@ -18,12 +19,20 @@ import { projectDrilldown, dayDetail } from './api.js';
18
19
  import { watchSources, addClient, removeClient } from './sse.js';
19
20
  import { buildHtml, buildWrappedHtml } from './page.js';
20
21
 
22
+ const PORT = Number(process.env.CLAUDE_RPC_PORT) || 47474;
23
+
21
24
  // Pre-compose the HTML once at startup — the only dynamic bit is the port
22
- // (used in a breadcrumb), which is fixed for the life of the daemon.
23
- const HTML = buildHtml({ port: Number(process.env.CLAUDE_RPC_PORT) || 47474 });
25
+ // (shown in the footer), which is fixed for the life of the process.
26
+ const HTML = buildHtml({ port: PORT });
24
27
  const WRAPPED_HTML = buildWrappedHtml();
28
+ const PAGES = new Map([
29
+ ['/', HTML], ['/index.html', HTML],
30
+ ['/wrapped', WRAPPED_HTML], ['/wrapped.html', WRAPPED_HTML], // animated year-in-review
31
+ ]);
25
32
 
26
- const PORT = Number(process.env.CLAUDE_RPC_PORT) || 47474;
33
+ // Path-prefix drilldowns — the project name / day key is in the URL path
34
+ // itself, not in a query string.
35
+ const DRILLDOWNS = [['/api/project/', projectDrilldown], ['/api/day/', dayDetail]];
27
36
 
28
37
  function parseUrl(rawUrl) {
29
38
  const url = new URL(rawUrl, 'http://x');
@@ -65,42 +74,25 @@ function dispatch(req, res) {
65
74
  return;
66
75
  }
67
76
 
68
- // Project drilldown. Path-prefix dispatch (the project name is in the
69
- // URL itself, not in a query string).
70
- if (req.method === 'GET' && path.startsWith('/api/project/')) {
71
- const name = safeDecode(path.slice('/api/project/'.length));
72
- if (name === null) { res.writeHead(400, JSON_HEADERS).end(JSON.stringify({ error: 'bad request' })); return; }
73
- const result = projectDrilldown(name);
74
- res.writeHead(result ? 200 : 404, JSON_HEADERS);
75
- res.end(JSON.stringify(result || { error: 'not found' }));
76
- return;
77
- }
78
-
79
- // Day detail. Same pattern — day key in the URL path.
80
- if (req.method === 'GET' && path.startsWith('/api/day/')) {
81
- const day = safeDecode(path.slice('/api/day/'.length));
82
- if (day === null) { res.writeHead(400, JSON_HEADERS).end(JSON.stringify({ error: 'bad request' })); return; }
83
- const result = dayDetail(day);
77
+ for (const [prefix, lookup] of DRILLDOWNS) {
78
+ if (req.method !== 'GET' || !path.startsWith(prefix)) continue;
79
+ const id = safeDecode(path.slice(prefix.length));
80
+ if (id === null) { res.writeHead(400, JSON_HEADERS).end(JSON.stringify({ error: 'bad request' })); return; }
81
+ const result = lookup(id);
84
82
  res.writeHead(result ? 200 : 404, JSON_HEADERS);
85
83
  res.end(JSON.stringify(result || { error: 'not found' }));
86
84
  return;
87
85
  }
88
86
 
89
- // Static /api/* endpoints (state, aggregate, insights, badge.svg, card.svg).
87
+ // Static /api/* endpoints (state, wrapped, aggregate, insights, badge.svg,
88
+ // card.svg, export.json, export.csv) — see routes.js.
90
89
  const handler = ROUTES.get(key);
91
90
  if (handler) return handler(req, res, { query });
92
91
 
93
- // Animated year-in-review.
94
- if (req.method === 'GET' && (path === '/wrapped' || path === '/wrapped.html')) {
92
+ const page = req.method === 'GET' && PAGES.get(path);
93
+ if (page) {
95
94
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
96
- res.end(WRAPPED_HTML);
97
- return;
98
- }
99
-
100
- // Page.
101
- if (req.method === 'GET' && (path === '/' || path === '/index.html')) {
102
- res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
103
- res.end(HTML);
95
+ res.end(page);
104
96
  return;
105
97
  }
106
98
 
@@ -119,9 +111,28 @@ const server = createServer((req, res) => {
119
111
  }
120
112
  });
121
113
 
122
- watchSources();
114
+ // Listen failures arrive as an 'error' event. Without a handler the
115
+ // uncaughtException floor below swallowed EADDRINUSE and the process then sat
116
+ // forever on the poll interval + fs watchers, serving nothing — e.g. a second
117
+ // `claude-rpc serve`, or the tray and the Stats tab each spawning one. Say why
118
+ // in one line and exit non-zero instead. Once listening, an 'error' is logged
119
+ // and the dashboard keeps running (same policy as the floor).
120
+ server.on('error', (e) => {
121
+ if (server.listening) {
122
+ try { console.error('dashboard error:', e?.message || e); } catch { /* ignore */ }
123
+ return;
124
+ }
125
+ const base = `http://127.0.0.1:${PORT}`;
126
+ console.error(e?.code === 'EADDRINUSE'
127
+ ? `✗ Port ${PORT} is already in use — a dashboard may already be running at ${base} (set CLAUDE_RPC_PORT to use another port).`
128
+ : `✗ Dashboard could not listen on 127.0.0.1:${PORT}: ${e?.message || e}`);
129
+ process.exit(1);
130
+ });
123
131
 
124
132
  server.listen(PORT, '127.0.0.1', () => {
133
+ // Start watching only once the port is ours, so a failed listen exits
134
+ // without leaving watchers behind.
135
+ watchSources();
125
136
  const base = `http://127.0.0.1:${PORT}`;
126
137
  // `claude-rpc wrapped` sets CLAUDE_RPC_OPEN_PATH=/wrapped to land on the
127
138
  // animated year-in-review instead of the dashboard.
@@ -1,15 +1,18 @@
1
- // Composes the local web dashboard's HTML from three on-disk assets:
1
+ // Composes the local web dashboard's two pages from six on-disk assets:
2
2
  // assets/dashboard.html — scaffold with {{STYLES}} {{SCRIPT}} {{PORT}}
3
3
  // assets/dashboard.css — stylesheet
4
4
  // assets/dashboard.client.js — vanilla browser runtime (one IIFE)
5
+ // assets/wrapped.html — /wrapped scaffold with {{STYLES}} {{SCRIPT}}
6
+ // assets/wrapped.css — /wrapped stylesheet
7
+ // assets/wrapped.client.js — /wrapped story runtime (one IIFE)
5
8
  //
6
9
  // These are real files you edit with full CSS/HTML/JS tooling — the reason
7
10
  // this module shrank from a 1,200-line string monolith. loadAsset() reads
8
11
  // them from disk in dev/npm and from the SEA blob in the packaged exe
9
12
  // (see src/server/assets.js + sea-config.json).
10
13
  //
11
- // Single export: buildHtml({ port }). The server composes it once at
12
- // startup and reuses the string for every request.
14
+ // Two exports: buildHtml({ port }) and buildWrappedHtml(). The server
15
+ // composes each once at startup and reuses the string for every request.
13
16
 
14
17
  import { loadAsset } from './assets.js';
15
18
 
package/src/server/sse.js CHANGED
@@ -1,13 +1,21 @@
1
1
  // Server-Sent Events: the dashboard pushes a one-line `data:` frame to
2
- // connected browsers whenever state.json or aggregate.json is touched.
3
- // Replaces the old 2-second poll. Two debounced fs.watch handles, one
4
- // shared client set.
2
+ // connected browsers whenever a session state file or aggregate.json is
3
+ // touched. Replaces the old 2-second poll. One debounced directory watcher
4
+ // per source plus an mtime-poll fallback, one shared client set.
5
5
 
6
- import { watch, existsSync, statSync } from 'node:fs';
7
- import { dirname, basename } from 'node:path';
8
- import { STATE_PATH, AGGREGATE_PATH } from '../paths.js';
6
+ import { watch, readdirSync, statSync } from 'node:fs';
7
+ import { dirname, basename, join } from 'node:path';
8
+ import { STATE_DIR, AGGREGATE_PATH } from '../paths.js';
9
9
  import { pollDecision, pollIntervalMs } from '../watch-poll.js';
10
10
 
11
+ // Hooks write one state-<sid>.json per Claude Code session (src/state.js
12
+ // statePathFor); the legacy global state.json is only written for payloads
13
+ // without a session id. Watch the whole family, same filter as the daemon's
14
+ // watchFiles() — matching only the literal 'state.json' meant real hook events
15
+ // never reached the live rail. Write-tmp (`*.json.<pid>.tmp`) and lock
16
+ // (`*.json.lock`) siblings don't end in `.json`, so they don't match.
17
+ export const STATE_FILE_RE = /^state(-.+)?\.json$/;
18
+
11
19
  export const sseClients = new Set();
12
20
 
13
21
  export function broadcast(payload) {
@@ -44,35 +52,65 @@ export function removeClient(res) {
44
52
  }
45
53
  }
46
54
 
47
- // Watch a file that is updated via atomic rename (write-tmp + renameSync).
48
- // Watching the file path directly binds to the inode at watch-time — on
49
- // Linux that inode is replaced by the first rename, so the watcher fires
50
- // once then goes permanently silent. Watching the parent directory avoids
51
- // this: directory inodes are stable across entry renames.
52
- export function watchFile(filePath, callback) {
53
- const dir = dirname(filePath);
54
- const name = basename(filePath);
55
+ // Watch a directory for entries whose name passes `matches`. Every writer here
56
+ // commits via atomic rename (write-tmp + renameSync), and watching a file path
57
+ // directly binds to the inode at watch-time — on Linux that inode is replaced
58
+ // by the first rename, so the watcher fires once then goes permanently silent.
59
+ // Directory inodes are stable across entry renames. A null filename (some
60
+ // platforms) is treated as a match. `onError` runs if the watcher dies (e.g.
61
+ // the directory was removed) so the caller can re-attach later.
62
+ export function watchDir(dir, matches, callback, onError) {
55
63
  try {
56
- return watch(dir, (_, filename) => {
57
- if (!filename || filename === name) callback();
64
+ const w = watch(dir, (_, filename) => {
65
+ if (!filename || matches(String(filename))) callback();
66
+ });
67
+ w.on('error', () => {
68
+ try { w.close(); } catch { /* already closed */ }
69
+ onError?.();
58
70
  });
71
+ return w;
59
72
  } catch {
60
73
  return null;
61
74
  }
62
75
  }
63
76
 
64
- function statMtime(filePath) {
65
- try {
66
- return existsSync(filePath) ? statSync(filePath).mtimeMs : undefined;
67
- } catch {
68
- return undefined; // mid-rename; a later observation records it
77
+ // Single-file convenience wrapper over watchDir (watches the parent directory).
78
+ export function watchFile(filePath, callback) {
79
+ const name = basename(filePath);
80
+ return watchDir(dirname(filePath), (f) => f === name, callback);
81
+ }
82
+
83
+ // Newest mtime among the entries of `dir` that pass `matches` (undefined when
84
+ // none exist or the directory is missing). For the state family this is the
85
+ // max across every session file — monotone under writes, so the poll's
86
+ // `cur > prev` test still detects a change in ANY session; a deleted session
87
+ // file lowers it, which correctly doesn't fire.
88
+ export function newestMtime(dir, matches) {
89
+ let max;
90
+ let names;
91
+ try { names = readdirSync(dir); } catch { return undefined; }
92
+ for (const name of names) {
93
+ if (!matches(name)) continue;
94
+ try {
95
+ const m = statSync(join(dir, name)).mtimeMs;
96
+ if (max === undefined || m > max) max = m;
97
+ } catch { /* vanished or mid-rename; a later observation records it */ }
69
98
  }
99
+ return max;
70
100
  }
71
101
 
72
- export function watchSources() {
102
+ // Start the watchers + poll fallback. Paths are injectable for tests; the
103
+ // server calls it with the defaults. Returns { close } to stop everything.
104
+ export function watchSources({
105
+ stateDir = STATE_DIR,
106
+ aggregatePath = AGGREGATE_PATH,
107
+ pollMs = pollIntervalMs(),
108
+ debounceMs = 200,
109
+ } = {}) {
110
+ const aggName = basename(aggregatePath);
73
111
  const targets = [
74
- { path: STATE_PATH, type: 'state' },
75
- { path: AGGREGATE_PATH, type: 'aggregate' },
112
+ { type: 'state', dir: stateDir, matches: (f) => STATE_FILE_RE.test(f), watcher: null },
113
+ { type: 'aggregate', dir: dirname(aggregatePath), matches: (f) => f === aggName, watcher: null },
76
114
  ];
77
115
 
78
116
  // Last mtime we've reacted to, per target. Updated by BOTH the watcher and
@@ -82,30 +120,48 @@ export function watchSources() {
82
120
  const lastMtime = new Map();
83
121
  const debounceTimers = new Map();
84
122
  const recordMtime = (t) => {
85
- const m = statMtime(t.path);
86
- if (m !== undefined) lastMtime.set(t.path, m);
123
+ const m = newestMtime(t.dir, t.matches);
124
+ if (m !== undefined) lastMtime.set(t.type, m);
87
125
  };
88
126
  targets.forEach(recordMtime); // seed baselines before watching starts
89
127
 
90
128
  const fire = (t) => {
91
129
  recordMtime(t); // record before the debounced broadcast so a re-entrant tick can't double-fire
92
- clearTimeout(debounceTimers.get(t.path));
93
- debounceTimers.set(t.path, setTimeout(() => broadcast({ type: t.type }), 200));
130
+ clearTimeout(debounceTimers.get(t.type));
131
+ debounceTimers.set(t.type, setTimeout(() => broadcast({ type: t.type }), debounceMs));
94
132
  };
95
133
 
96
- for (const t of targets) watchFile(t.path, () => fire(t));
134
+ // A directory that doesn't exist yet (fresh install, no hook has run) can't
135
+ // be watched; the poll tick below retries the attachment.
136
+ const attach = (t) => {
137
+ if (t.watcher) return;
138
+ t.watcher = watchDir(t.dir, t.matches, () => fire(t), () => { t.watcher = null; });
139
+ };
140
+ targets.forEach(attach);
97
141
 
98
142
  // Mtime-poll fallback. fs.watch drops atomic-rename events on Windows (see
99
143
  // watch-poll.js), and unlike the daemon this watcher previously had no
100
144
  // backstop at all — a missed event left the dashboard silently stale until
101
145
  // some unrelated broadcast happened to fire. Same cadence as the daemon's
102
146
  // fallback: fast on Windows, lazy on macOS/Linux.
103
- setInterval(() => {
147
+ const poll = setInterval(() => {
104
148
  for (const t of targets) {
105
- const cur = statMtime(t.path);
106
- const decision = pollDecision(lastMtime.get(t.path), cur);
107
- if (decision === 'seed') lastMtime.set(t.path, cur);
149
+ attach(t);
150
+ const cur = newestMtime(t.dir, t.matches);
151
+ const decision = pollDecision(lastMtime.get(t.type), cur);
152
+ if (decision === 'seed') lastMtime.set(t.type, cur);
108
153
  else if (decision === 'fire') fire(t);
109
154
  }
110
- }, pollIntervalMs());
155
+ }, pollMs);
156
+
157
+ return {
158
+ close() {
159
+ clearInterval(poll);
160
+ for (const timer of debounceTimers.values()) clearTimeout(timer);
161
+ for (const t of targets) {
162
+ try { t.watcher?.close(); } catch { /* already closed */ }
163
+ t.watcher = null;
164
+ }
165
+ },
166
+ };
111
167
  }
@@ -40,6 +40,8 @@ function tape(x, y, text) {
40
40
  export function renderSessionCard(vars = {}, { generatedAt = new Date() } = {}) {
41
41
  const v = vars || {};
42
42
  const C = [40, 210, 380];
43
+ // The day's estimated spend across ALL sessions — there's no per-session cost
44
+ // var — so the cell is labeled as today's, not this session's.
43
45
  const cost = v.todayCostFmt || '$0';
44
46
  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${H}" width="${W}" height="${H}" role="img" aria-label="Claude Code session recap">
45
47
  <defs><pattern id="dg" width="22" height="22" patternUnits="userSpaceOnUse"><circle cx="1" cy="1" r="1" fill="${PALETTE.ink}" opacity="0.06"/></pattern></defs>
@@ -58,7 +60,7 @@ export function renderSessionCard(vars = {}, { generatedAt = new Date() } = {})
58
60
  ${statCell(C[2], 120, 'Tokens', String(v.tokensFmt || '0'), PALETTE.rust)}
59
61
 
60
62
  ${statCell(C[0], 184, 'Files edited', String(v.filesEdited ?? 0), PALETTE.grass)}
61
- ${statCell(C[1], 184, 'Est. cost', String(cost), PALETTE.blurple)}
63
+ ${statCell(C[1], 184, 'Cost today', String(cost), PALETTE.blurple)}
62
64
  ${statCell(C[2], 184, 'Reads', String(v.filesRead ?? 0))}
63
65
 
64
66
  <text x="40" y="${H - 16}" font-family="JetBrains Mono, ui-monospace, monospace" font-size="10" fill="${PALETTE.inkFaint}">${escapeXml(`${v.currentFilePretty ? 'last: ' + v.currentFilePretty + ' · ' : ''}claude-rpc.com · v${VERSION}`)}</text>
@@ -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: `[![${alt}](${url})](${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
+ }