burrow-cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +594 -2
  3. package/bin/burrow.js +200 -0
  4. package/examples/acme-shop.tunnel.yml +18 -0
  5. package/package.json +45 -4
  6. package/src/access.js +163 -0
  7. package/src/add.js +106 -0
  8. package/src/cloudflare.js +131 -0
  9. package/src/commands.js +386 -0
  10. package/src/completion.js +127 -0
  11. package/src/config-file.js +31 -0
  12. package/src/config.js +82 -0
  13. package/src/dashboard/auth.js +79 -0
  14. package/src/dashboard/data.js +70 -0
  15. package/src/dashboard/logs.js +95 -0
  16. package/src/dashboard/manage.js +102 -0
  17. package/src/dashboard/panels/README.md +50 -0
  18. package/src/dashboard/panels/access.js +218 -0
  19. package/src/dashboard/panels/alerts.js +244 -0
  20. package/src/dashboard/panels/backup.js +193 -0
  21. package/src/dashboard/panels/bulk.js +246 -0
  22. package/src/dashboard/panels/cleanup.js +237 -0
  23. package/src/dashboard/panels/doctor.js +119 -0
  24. package/src/dashboard/panels/health.js +146 -0
  25. package/src/dashboard/panels/history.js +104 -0
  26. package/src/dashboard/panels/hooks.js +86 -0
  27. package/src/dashboard/panels/live.js +153 -0
  28. package/src/dashboard/panels/project-form.js +463 -0
  29. package/src/dashboard/panels/quick-actions.js +133 -0
  30. package/src/dashboard/panels/sessions.js +267 -0
  31. package/src/dashboard/panels/shares.js +280 -0
  32. package/src/dashboard/panels/stats.js +165 -0
  33. package/src/dashboard/panels/updates.js +156 -0
  34. package/src/dashboard/panels/uptime.js +115 -0
  35. package/src/dashboard/panels.js +53 -0
  36. package/src/dashboard/server.js +390 -0
  37. package/src/dashboard/session-store.js +47 -0
  38. package/src/dashboard/totp.js +103 -0
  39. package/src/dashboard/ui.js +454 -0
  40. package/src/doctor.js +342 -0
  41. package/src/edit.js +135 -0
  42. package/src/health-observer.js +81 -0
  43. package/src/history.js +145 -0
  44. package/src/hooks.js +256 -0
  45. package/src/naming.js +38 -0
  46. package/src/open.js +67 -0
  47. package/src/pending.js +72 -0
  48. package/src/process.js +95 -0
  49. package/src/project-form.js +134 -0
  50. package/src/project.js +114 -0
  51. package/src/prune.js +99 -0
  52. package/src/rename-state.js +39 -0
  53. package/src/restart.js +35 -0
  54. package/src/service.js +173 -0
  55. package/src/share-expiry.js +55 -0
  56. package/src/share.js +275 -0
  57. package/src/shell-words.js +284 -0
  58. package/src/stats.js +180 -0
  59. package/src/transfer.js +124 -0
  60. package/src/update.js +254 -0
  61. package/src/uptime.js +91 -0
  62. package/src/watch.js +263 -0
  63. package/src/zones.js +102 -0
@@ -0,0 +1,165 @@
1
+ // Panel: request stats per hostname from Cloudflare analytics (the same GraphQL
2
+ // query as `burrow stats`), with a small inline-SVG chart. No chart library.
3
+ import { assertLabel } from '../../naming.js';
4
+ import { fetchStats, fetchSeries, parseSince } from '../../stats.js';
5
+
6
+ export const order = 30;
7
+ export const WINDOWS = ['1h', '6h', '24h', '7d'];
8
+ const CACHE_MS = 60000;
9
+ const cache = new Map();
10
+
11
+ export function clearCache() { cache.clear(); }
12
+
13
+ export async function projectStats(project, since, cfg) {
14
+ const s = await fetchStats(project, { since }, cfg);
15
+ const { step, series } = await fetchSeries({ cfg, zoneTag: s.zoneTag, hosts: s.hosts, since: s.since, until: s.until });
16
+ const pick = (r) => ({ hostname: r.hostname, requests: r.requests, bytes: r.bytes, classes: r.classes, status: r.status });
17
+ return {
18
+ project: s.project, window: since, since: s.since.toISOString(), until: s.until.toISOString(), sampled: true,
19
+ hostnames: s.rows.map(pick), total: pick({ ...s.total, hostname: 'total' }), step, series,
20
+ };
21
+ }
22
+
23
+ export async function route(ctx) {
24
+ const m = ctx.path.match(/^\/api\/stats\/([^/]+)$/);
25
+ if (ctx.method !== 'GET' || !m) return false;
26
+ const project = m[1];
27
+ try { assertLabel(project, 'project'); } catch { return ctx.json(400, { error: 'bad project' }) ?? true; }
28
+ const since = ctx.url.searchParams.get('since') || '24h';
29
+ if (!WINDOWS.includes(since)) return ctx.json(400, { error: `since must be one of ${WINDOWS.join(', ')}` }) ?? true;
30
+ parseSince(since);
31
+ const key = `${project}|${since}`;
32
+ const hit = cache.get(key);
33
+ if (hit && Date.now() - hit.at < CACHE_MS) return ctx.json(200, { ...hit.data, cached: true }) ?? true;
34
+ try {
35
+ const data = await projectStats(project, since, ctx.loadConfig());
36
+ cache.set(key, { at: Date.now(), data });
37
+ ctx.json(200, data);
38
+ } catch (e) {
39
+ ctx.json(502, { error: e.message });
40
+ }
41
+ return true;
42
+ }
43
+
44
+ export const html = {
45
+ rowActions: '<button class="secondary outline" @click="openStats(p)">Stats</button>',
46
+ sections: `
47
+ <article x-show="statsOpen" class="stats">
48
+ <header class="logs-head">
49
+ <strong x-text="statsTitle"></strong>
50
+ <span class="spacer"></span>
51
+ <select x-model="statsWindow" @change="loadStats" aria-label="Time window">
52
+ <option value="1h">Last hour</option><option value="6h">Last 6 hours</option>
53
+ <option value="24h">Last 24 hours</option><option value="7d">Last 7 days</option>
54
+ </select>
55
+ <select x-model="statsHost" aria-label="Hostname">
56
+ <option value="">All hostnames</option>
57
+ <template x-for="r in statsRows" :key="r.hostname"><option :value="r.hostname" x-text="r.hostname"></option></template>
58
+ </select>
59
+ <button class="secondary outline" @click="loadStats">Refresh</button>
60
+ <button class="secondary outline" @click="closeStats">Close</button>
61
+ </header>
62
+ <p x-show="statsLoading" aria-busy="true">Loading analytics…</p>
63
+ <p class="error" x-show="hasStatsError" x-text="statsError"></p>
64
+ <div x-show="hasStats">
65
+ <div class="chart-wrap">
66
+ <svg class="chart" viewBox="0 0 600 120" preserveAspectRatio="none" role="img" :aria-label="chartLabel">
67
+ <path class="area" :d="chartArea"></path>
68
+ <path class="line e4" :d="chartLine4"></path>
69
+ <path class="line e5" :d="chartLine5"></path>
70
+ </svg>
71
+ <div class="chart-axis"><small x-text="chartStart"></small><small x-text="chartMax"></small><small x-text="chartEnd"></small></div>
72
+ <small class="legend"><span class="key req"></span> requests <span class="key e4"></span> 4xx <span class="key e5"></span> 5xx · Cloudflare analytics are sampled</small>
73
+ </div>
74
+ <div class="overflow-auto">
75
+ <table class="striped">
76
+ <thead><tr><th>Hostname</th><th>Requests</th><th>Bandwidth</th><th>2xx</th><th>3xx</th><th>4xx</th><th>5xx</th><th>Errors</th></tr></thead>
77
+ <tbody>
78
+ <template x-for="r in statsTable" :key="r.hostname">
79
+ <tr>
80
+ <td x-text="r.hostname"></td><td x-text="fmtNum(r.requests)"></td><td x-text="fmtBytes(r.bytes)"></td>
81
+ <td x-text="fmtNum(r.classes['2xx'])"></td><td x-text="fmtNum(r.classes['3xx'])"></td>
82
+ <td x-text="fmtNum(r.classes['4xx'])"></td><td x-text="fmtNum(r.classes['5xx'])"></td><td x-text="errorRate(r)"></td>
83
+ </tr>
84
+ </template>
85
+ </tbody>
86
+ </table>
87
+ </div>
88
+ </div>
89
+ </article>`,
90
+ };
91
+
92
+ export const css = `
93
+ .stats select{width:auto;margin:0;padding:.3rem 2rem .3rem .6rem;font-size:.85rem}
94
+ .chart-wrap{margin-bottom:1rem}
95
+ .chart{width:100%;height:140px;display:block;border-bottom:1px solid var(--pico-muted-border-color)}
96
+ .chart .area{fill:rgba(1,114,173,.18);stroke:#0172ad;stroke-width:1.5;vector-effect:non-scaling-stroke}
97
+ .chart .line{fill:none;stroke-width:1.5;vector-effect:non-scaling-stroke}
98
+ .chart .e4{stroke:#d97706}.chart .e5{stroke:#dc2626}
99
+ .chart-axis{display:flex;justify-content:space-between;color:var(--pico-muted-color)}
100
+ .legend{color:var(--pico-muted-color)}
101
+ .key{display:inline-block;width:.7rem;height:.7rem;border-radius:2px;vertical-align:middle;margin-left:.5rem}
102
+ .key.req{background:#0172ad}.key.e4{background:#d97706}.key.e5{background:#dc2626}
103
+ `;
104
+
105
+ export const js = `
106
+ burrowPanel(function () {
107
+ var W = 600, H = 120;
108
+ function path(points) { return points.map(function (p, i) { return (i ? 'L' : 'M') + p[0].toFixed(1) + ',' + p[1].toFixed(1); }).join(' '); }
109
+ return {
110
+ statsOpen: false, statsProject: '', statsWindow: '24h', statsHost: '', statsLoading: false, statsError: '', stats: null,
111
+
112
+ get statsTitle() { return 'Stats · ' + this.statsProject; },
113
+ get hasStats() { return !!this.stats && !this.statsLoading; },
114
+ get hasStatsError() { return this.statsError.length > 0; },
115
+ get statsRows() { return this.stats ? this.stats.hostnames : []; },
116
+ get statsTable() {
117
+ if (!this.stats) return [];
118
+ var rows = this.stats.hostnames.slice();
119
+ if (rows.length > 1) rows.push(this.stats.total);
120
+ return rows;
121
+ },
122
+ get buckets() { return this.stats ? (this.stats.series[this.statsHost || 'all'] || []) : []; },
123
+ get chartPeak() { var m = 0; this.buckets.forEach(function (b) { if (b.requests > m) m = b.requests; }); return m; },
124
+ chartPoints: function (key) {
125
+ var b = this.buckets, n = b.length, max = this.chartPeak || 1;
126
+ return b.map(function (x, i) { return [n > 1 ? i * W / (n - 1) : 0, H - (x[key] / max) * (H - 4)]; });
127
+ },
128
+ get chartArea() {
129
+ var pts = this.chartPoints('requests');
130
+ if (!pts.length) return '';
131
+ return path([[0, H]].concat(pts).concat([[W, H]])) + ' Z';
132
+ },
133
+ get chartLine4() { return path(this.chartPoints('e4xx')); },
134
+ get chartLine5() { return path(this.chartPoints('e5xx')); },
135
+ fmtTime: function (t) {
136
+ var d = new Date(t);
137
+ return this.statsWindow === '7d' ? d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
138
+ },
139
+ get chartStart() { return this.buckets.length ? this.fmtTime(this.buckets[0].t) : ''; },
140
+ get chartEnd() { return this.buckets.length ? this.fmtTime(this.buckets[this.buckets.length - 1].t) : ''; },
141
+ get chartMax() { return 'peak ' + this.fmtNum(this.chartPeak) + ' req / ' + (this.stats && this.stats.step >= 3600000 ? 'hour' : '15 min'); },
142
+ get chartLabel() { return 'Requests over time, ' + this.chartMax; },
143
+ fmtNum: function (n) { return Number(n || 0).toLocaleString('en-US'); },
144
+ fmtBytes: function (n) {
145
+ var u = ['B', 'KB', 'MB', 'GB', 'TB'], i = 0, v = Number(n) || 0;
146
+ while (v >= 1000 && i < u.length - 1) { v /= 1000; i++; }
147
+ return i ? v.toFixed(v < 10 ? 2 : 1) + ' ' + u[i] : v + ' B';
148
+ },
149
+ errorRate: function (r) {
150
+ if (!r.requests) return '—';
151
+ return ((r.classes['4xx'] + r.classes['5xx']) / r.requests * 100).toFixed(1) + '%';
152
+ },
153
+ openStats: function (p) { this.statsProject = p.project; this.statsHost = ''; this.stats = null; this.statsOpen = true; this.loadStats(); },
154
+ closeStats: function () { this.statsOpen = false; },
155
+ loadStats: async function () {
156
+ this.statsLoading = true; this.statsError = '';
157
+ try {
158
+ this.stats = await getJson('/api/stats/' + encodeURIComponent(this.statsProject) + '?since=' + encodeURIComponent(this.statsWindow));
159
+ var self = this;
160
+ if (this.statsHost && !this.stats.hostnames.some(function (r) { return r.hostname === self.statsHost; })) this.statsHost = '';
161
+ } catch (e) { this.stats = null; this.statsError = e.message; } finally { this.statsLoading = false; }
162
+ },
163
+ };
164
+ });
165
+ `;
@@ -0,0 +1,156 @@
1
+ // Panel: update notice. Runs `burrow update --check --json` (git checkout: git fetch;
2
+ // global npm install: git ls-remote on the install source) at most once a day, only when
3
+ // someone has the dashboard open, and caches the result in the state dir. The page shows
4
+ // the version and, when something newer exists, an "Update available" notice with the new
5
+ // commits. Installing stays a terminal step (`burrow update`). BURROW_UPDATE_CHECK=off
6
+ // turns the check off.
7
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
8
+ import { dirname, join } from 'node:path';
9
+ import { stateDir } from '../../config.js';
10
+ import { detectInstall } from '../../update.js';
11
+
12
+ export const order = 95;
13
+ export const cacheFile = () => join(stateDir(), 'cache', 'update.json');
14
+ const maxAgeMs = () => (Number(process.env.BURROW_UPDATE_CHECK_HOURS) > 0 ? Number(process.env.BURROW_UPDATE_CHECK_HOURS) : 24) * 3600e3;
15
+ export const checksEnabled = (env = process.env) => !/^(off|0|false|no)$/i.test(env.BURROW_UPDATE_CHECK || '');
16
+
17
+ function readCache() { try { return JSON.parse(readFileSync(cacheFile(), 'utf8')); } catch { return null; } }
18
+ function writeCache(c) {
19
+ mkdirSync(dirname(cacheFile()), { recursive: true, mode: 0o700 });
20
+ writeFileSync(cacheFile(), JSON.stringify(c, null, 2) + '\n', { mode: 0o600 });
21
+ }
22
+ // Errors may quote a remote URL; drop any credentials in it.
23
+ export const scrub = (s) => String(s || '').replace(/\/\/[^/\s@]+@/g, '//').slice(0, 300);
24
+
25
+ // The JSON line `update --check --json` printed, or null.
26
+ export function parseCheck(output) {
27
+ for (const line of String(output || '').split('\n').reverse()) {
28
+ if (!line.startsWith('{')) continue;
29
+ try { const j = JSON.parse(line); if ('available' in j) return j; } catch {}
30
+ }
31
+ return null;
32
+ }
33
+
34
+ let inflight = null;
35
+ async function runCheck(ctx) {
36
+ if (inflight) return inflight;
37
+ inflight = (async () => {
38
+ const r = await ctx.runCli(['update', '--check', '--json'], 90000);
39
+ const result = r.ok ? parseCheck(r.output) : null;
40
+ const entry = result
41
+ ? { checkedAt: Date.now(), result, error: null }
42
+ : { checkedAt: Date.now(), result: readCache()?.result || null, error: scrub(r.output.trim().split('\n').pop() || 'check failed') };
43
+ writeCache(entry);
44
+ if (result?.available) ctx.log(`update available: ${result.version} ${result.head || ''} -> ${result.remoteVersion || ''} ${result.latest || ''}`.trim());
45
+ return entry;
46
+ })().finally(() => { inflight = null; });
47
+ return inflight;
48
+ }
49
+
50
+ function localVersion() {
51
+ try { const i = detectInstall(); return { version: i.pkg.version, mode: i.mode }; } catch { return { version: null, mode: 'unknown' }; }
52
+ }
53
+
54
+ export async function route(ctx) {
55
+ if (ctx.path !== '/api/update' && ctx.path !== '/api/update/check') return false;
56
+ const local = localVersion();
57
+ if (!checksEnabled()) return ctx.json(200, { enabled: false, ...local }) ?? true;
58
+ if (ctx.method === 'GET' && ctx.path === '/api/update') {
59
+ const c = readCache();
60
+ const stale = !c || Date.now() - c.checkedAt > maxAgeMs();
61
+ if (stale && !inflight) runCheck(ctx).catch((e) => ctx.log(`error: update check: ${e.message}`));
62
+ return ctx.json(200, { enabled: true, ...local, checking: !!inflight, ...(c || { checkedAt: null, result: null, error: null }) }) ?? true;
63
+ }
64
+ if (ctx.method === 'POST' && ctx.path === '/api/update/check') {
65
+ const entry = await ctx.withBusy('(update)', () => runCheck(ctx));
66
+ if (!entry) return ctx.json(409, { error: 'already checking' }) ?? true;
67
+ return ctx.json(200, { enabled: true, ...local, checking: false, ...entry }) ?? true;
68
+ }
69
+ return false;
70
+ }
71
+
72
+ export const html = {
73
+ toolbarMain: '<li x-show="updateAvailable"><button class="update-notice" @click="openUpdate">Update available</button></li>',
74
+ sections: `
75
+ <p class="version-line"><small class="muted">
76
+ <span x-text="versionText"></span>
77
+ <a href="#" x-show="updateEnabled" @click.prevent="checkUpdate" :aria-busy="updateChecking">Check for updates</a>
78
+ </small></p>`,
79
+ dialogs: `
80
+ <dialog :open="updateOpen">
81
+ <article>
82
+ <header><strong>burrow update available</strong></header>
83
+ <p x-text="updateSummary"></p>
84
+ <ul x-show="hasUpdateCommits"><template x-for="c in updateCommits" :key="c"><li><code x-text="c"></code></li></template></ul>
85
+ <p>Install it from a terminal on this machine, then restart the dashboard:</p>
86
+ <pre><code>burrow update
87
+ burrow dashboard up</code></pre>
88
+ <footer>
89
+ <button class="secondary" @click="dismissUpdate">Remind me later</button>
90
+ <button @click="closeUpdate">Close</button>
91
+ </footer>
92
+ </article>
93
+ </dialog>`,
94
+ };
95
+
96
+ export const css = `
97
+ .version-line{margin:.75rem 0 0;text-align:right}.version-line a{margin-left:.5rem}
98
+ .update-notice{padding:.35rem .8rem;background:#d97706;border-color:#d97706;color:#fff}
99
+ `;
100
+
101
+ export const js = `
102
+ burrowPanel(function () {
103
+ var DISMISS = 'burrow.update.dismissed';
104
+ return {
105
+ update: null, updateOpen: false, updateChecking: false, updateDismissed: '',
106
+ get updateEnabled() { return !!(this.update && this.update.enabled); },
107
+ get updateResult() { return this.update && this.update.result ? this.update.result : null; },
108
+ get updateAvailable() { var r = this.updateResult; return !!(r && r.available && this.updateDismissed !== r.latest); },
109
+ get updateCommits() { return this.updateResult && this.updateResult.commits ? this.updateResult.commits : []; },
110
+ get hasUpdateCommits() { return this.updateCommits.length > 0; },
111
+ get updateSummary() {
112
+ var r = this.updateResult;
113
+ if (!r) return '';
114
+ var to = r.remoteVersion && r.remoteVersion !== r.version ? r.remoteVersion : r.latest;
115
+ return 'burrow ' + r.version + ' → ' + to + (r.behind ? ' (' + r.behind + ' new commit' + (r.behind === 1 ? '' : 's') + ')' : '') + '.';
116
+ },
117
+ get versionText() {
118
+ var u = this.update;
119
+ if (!u) return '';
120
+ var t = 'burrow ' + (u.version || '?');
121
+ if (!u.enabled) return t + ' · update checks off';
122
+ if (u.checking || this.updateChecking) return t + ' · checking for updates…';
123
+ if (u.error) return t + ' · update check failed: ' + u.error;
124
+ if (!u.result) return t;
125
+ var when = u.checkedAt ? ' (checked ' + ago(Date.now() - u.checkedAt) + ' ago)' : '';
126
+ return t + (u.result.available ? ' · update available' : u.result.available === false ? ' · up to date' : '') + when;
127
+ },
128
+ init: function () {
129
+ try { this.updateDismissed = localStorage.getItem(DISMISS) || ''; } catch (e) {}
130
+ this.loadUpdate();
131
+ },
132
+ loadUpdate: async function () {
133
+ try {
134
+ this.update = await getJson('/api/update');
135
+ var self = this;
136
+ if (this.update.checking) setTimeout(function () { self.loadUpdate(); }, 5000);
137
+ } catch (e) {}
138
+ },
139
+ checkUpdate: async function () {
140
+ this.updateChecking = true;
141
+ try {
142
+ var r = await post('/api/update/check', {});
143
+ var j = await r.json().catch(function () { return {}; });
144
+ if (r.ok) this.update = j; else this.showToast('✗ ' + (j.error || 'HTTP ' + r.status), false);
145
+ } catch (e) { this.showToast('✗ update check failed', false); } finally { this.updateChecking = false; }
146
+ },
147
+ openUpdate: function () { this.updateOpen = true; },
148
+ closeUpdate: function () { this.updateOpen = false; },
149
+ dismissUpdate: function () {
150
+ var r = this.updateResult;
151
+ if (r) { this.updateDismissed = r.latest; try { localStorage.setItem(DISMISS, r.latest); } catch (e) {} }
152
+ this.updateOpen = false;
153
+ },
154
+ };
155
+ });
156
+ `;
@@ -0,0 +1,115 @@
1
+ // Panel: uptime timeline. A bar per project for the last hour, day or week, built from the
2
+ // event history (starts and stops from the CLI and dashboard, health transitions recorded
3
+ // by `burrow watch`, or by the dashboard itself while watch isn't running) and what the project
4
+ // is doing now; plus the uptime % and incidents.
5
+ import { collect } from '../data.js';
6
+ import { readPid } from '../../process.js';
7
+ import { timelines, WINDOWS } from '../../uptime.js';
8
+ import { observe } from '../../health-observer.js';
9
+
10
+ export const order = 65;
11
+ const OBSERVE_MS = 60 * 1000;
12
+
13
+ // Without `burrow watch`, the dashboard records the health changes it sees (health-observer.js):
14
+ // on every refresh of the project list, and once a minute with no browser open.
15
+ export async function enrich(projects) {
16
+ try { observe(projects); } catch {}
17
+ }
18
+ export function start(ctx) {
19
+ const tick = async () => { try { observe((await ctx.collect()).projects); } catch {} };
20
+ const timer = setInterval(tick, OBSERVE_MS);
21
+ const first = setTimeout(tick, 10 * 1000);
22
+ timer.unref?.(); first.unref?.();
23
+ return () => { clearInterval(timer); clearTimeout(first); };
24
+ }
25
+
26
+ export async function route(ctx) {
27
+ if (ctx.method !== 'GET' || ctx.path !== '/api/uptime') return false;
28
+ const window = ctx.url.searchParams.get('window') || '24h';
29
+ if (!WINDOWS[window]) return ctx.json(400, { error: `window must be one of ${Object.keys(WINDOWS).join(', ')}` }) ?? true;
30
+ const data = await collect(ctx.loadConfig());
31
+ const rows = data.projects.filter((p) => !p.builtIn).map((p) => ({
32
+ project: p.project, running: !!p.running, startedAt: p.startedAt, crashed: !p.running && !!readPid(p.project),
33
+ }));
34
+ const now = Date.now();
35
+ const t = timelines(rows, { now, windowMs: WINDOWS[window] });
36
+ ctx.json(200, { window, now, from: now - WINDOWS[window], projects: rows.map((r) => ({ project: r.project, running: r.running, ...t[r.project] })) });
37
+ return true;
38
+ }
39
+
40
+ export const html = {
41
+ toolbar: '<li><button class="secondary outline" @click="openUptime">Uptime</button></li>',
42
+ sections: `
43
+ <article x-show="uptimeOpen" class="uptime">
44
+ <header class="logs-head">
45
+ <strong>Uptime</strong>
46
+ <select x-model="uptimeWindow" @change="loadUptime" aria-label="Time window">
47
+ <option value="1h">Last hour</option><option value="24h">Last 24 hours</option><option value="7d">Last 7 days</option>
48
+ </select>
49
+ <span class="spacer"></span>
50
+ <button class="secondary outline" @click="closeUptime">Close</button>
51
+ </header>
52
+ <p class="error" x-show="hasUptimeError" x-text="uptimeError"></p>
53
+ <template x-for="u in uptimeRows" :key="u.project">
54
+ <div class="uptime-row">
55
+ <div class="uptime-name"><strong x-text="u.project"></strong> <small class="muted" x-text="uptimePct(u)"></small></div>
56
+ <div class="uptime-bar" role="img" :aria-label="uptimeAria(u)">
57
+ <template x-for="s in u.segments" :key="s.from">
58
+ <span :class="segClass(s)" :style="segStyle(s)" :title="segTitle(s)"></span>
59
+ </template>
60
+ </div>
61
+ <ul class="uptime-incidents" x-show="hasIncidents(u)">
62
+ <template x-for="i in firstIncidents(u)" :key="i.at">
63
+ <li><small><span class="badge" :class="incidentClass(i)" x-text="i.status"></span> <span x-text="incidentTime(i)"></span> <span class="muted" x-text="i.detail"></span></small></li>
64
+ </template>
65
+ </ul>
66
+ </div>
67
+ </template>
68
+ <p class="uptime-legend"><small><span class="seg seg-up"></span> up <span class="seg seg-degraded"></span> degraded
69
+ <span class="seg seg-down"></span> down <span class="seg seg-stopped"></span> stopped <span class="seg seg-unknown"></span> no data</small></p>
70
+ <p><small class="muted">Health changes come from <code>burrow watch</code> when it runs; without it the dashboard records the crashes and tunnel outages it sees (checked every minute).</small></p>
71
+ </article>`,
72
+ };
73
+
74
+ export const css = `
75
+ .uptime-row{margin:.6rem 0}
76
+ .uptime-name{display:flex;gap:.5rem;align-items:baseline}
77
+ .uptime-bar{display:flex;height:14px;border-radius:4px;overflow:hidden;background:var(--pico-muted-border-color)}
78
+ .uptime-bar span{display:block;height:100%;min-width:1px}
79
+ .seg-up{background:#1f9d55}.seg-degraded{background:#d97706}.seg-down{background:#dc2626}
80
+ .seg-stopped{background:#94a3b8}.seg-unknown{background:var(--pico-muted-border-color)}
81
+ .uptime-legend .seg{display:inline-block;width:.8rem;height:.6rem;border-radius:2px;margin-left:.5rem;vertical-align:middle}
82
+ .uptime-incidents{margin:.3rem 0 0;padding-left:0;list-style:none}.uptime-incidents li{list-style:none;margin:0}
83
+ .uptime select{width:auto;margin:0 0 0 .75rem;padding:.2rem 2rem .2rem .6rem;height:auto}
84
+ `;
85
+
86
+ export const js = `
87
+ burrowPanel(function () {
88
+ return {
89
+ uptimeOpen: false, uptimeWindow: '24h', uptimeRows: [], uptimeError: '', uptimeNow: 0,
90
+ get hasUptimeError() { return this.uptimeError.length > 0; },
91
+ openUptime: function () { this.uptimeOpen = true; this.loadUptime(); },
92
+ closeUptime: function () { this.uptimeOpen = false; },
93
+ loadUptime: async function () {
94
+ this.uptimeError = '';
95
+ try {
96
+ var j = await getJson('/api/uptime?window=' + encodeURIComponent(this.uptimeWindow));
97
+ this.uptimeRows = j.projects; this.uptimeNow = j.now;
98
+ } catch (e) { this.uptimeError = e.message; }
99
+ },
100
+ onLoad: function () { if (this.uptimeOpen) this.loadUptime(); },
101
+ uptimePct: function (u) { return u.uptimePct === null ? 'no data' : u.uptimePct + '% up'; },
102
+ uptimeAria: function (u) { return u.project + ': ' + this.uptimePct(u); },
103
+ segClass: function (s) { return 'seg-' + s.status; },
104
+ segStyle: function (s) { return { flexGrow: String(s.pct), flexBasis: '0' }; },
105
+ segTitle: function (s) {
106
+ var label = s.status === 'unknown' ? 'no data' : s.status;
107
+ return label + ': ' + new Date(s.from).toLocaleString() + ' to ' + new Date(s.to).toLocaleString() + ' (' + ago(s.to - s.from) + ')';
108
+ },
109
+ hasIncidents: function (u) { return u.incidents.length > 0; },
110
+ firstIncidents: function (u) { return u.incidents.slice(0, 3); },
111
+ incidentClass: function (i) { return i.status === 'down' ? 'bad' : 'warn'; },
112
+ incidentTime: function (i) { return ago(this.uptimeNow - Date.parse(i.at)) + ' ago'; },
113
+ };
114
+ });
115
+ `;
@@ -0,0 +1,53 @@
1
+ // Dashboard panels: optional features that plug into the dashboard without
2
+ // touching the core files. Each file in ./panels/*.js is one panel; see
3
+ // ./panels/README.md for the interface.
4
+ import { readdirSync } from 'node:fs';
5
+ import { EventEmitter } from 'node:events';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
+
8
+ const DIR = fileURLToPath(new URL('./panels/', import.meta.url));
9
+
10
+ // In-process events from panels (e.g. "a tunnel.yml was saved from the UI").
11
+ // Shape: { action, project, ok, detail }. The event history panel records them.
12
+ export const events = new EventEmitter();
13
+ events.setMaxListeners(50);
14
+
15
+ // Places in the dashboard page a panel can add HTML to.
16
+ export const SLOTS = [
17
+ 'toolbarMain', // always-visible items in the top bar (status, primary or contextual buttons)
18
+ 'toolbar', // buttons that open a panel; listed in the top bar's "More" menu
19
+ 'headLead', 'rowLead', // a leading <th>/<td> on the project table
20
+ 'rowBadges', // after the project name
21
+ 'hostExtras', // after each hostname link (h and p in scope)
22
+ 'localExtras', // under the Local state
23
+ 'headCols', 'rowCols', // extra <th>/<td> before the actions column
24
+ 'rowActions', // buttons at the start of each row's actions
25
+ 'sections', // <article>s under the table
26
+ 'dialogs', // <dialog>s at the end of <body>
27
+ ];
28
+
29
+ let loaded = null;
30
+ export function loadPanels(dir = DIR) {
31
+ if (dir !== DIR) return importPanels(dir);
32
+ if (!loaded) loaded = importPanels(DIR);
33
+ return loaded;
34
+ }
35
+
36
+ async function importPanels(dir) {
37
+ let files = [];
38
+ try { files = readdirSync(dir).filter((f) => /^[a-z0-9-]+\.js$/.test(f)).sort(); } catch {}
39
+ const out = [];
40
+ for (const f of files) {
41
+ const mod = await import(pathToFileURL(dir + f).href);
42
+ out.push({ id: f.slice(0, -3), ...mod });
43
+ }
44
+ return sortPanels(out);
45
+ }
46
+
47
+ export const sortPanels = (panels) =>
48
+ [...panels].sort((a, b) => (a.order ?? 50) - (b.order ?? 50) || String(a.id).localeCompare(String(b.id)));
49
+
50
+ export const slot = (panels, name) => panels.map((p) => p.html?.[name] || '').join('');
51
+ export const panelJs = (panels) => panels.map((p) => (p.js ? `// panel: ${p.id}\n${p.js}\n` : '')).join('');
52
+ export const panelCss = (panels) => panels.map((p) => p.css || '').join('\n');
53
+ export const panelVendor = (panels) => Object.assign({}, ...panels.map((p) => p.vendor || {}));