hookdesk 0.1.0 → 0.2.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/src/ui.js DELETED
@@ -1,323 +0,0 @@
1
- const $ = id => document.getElementById(id);
2
- // Settings come from GET /api/config, which mirrors config/default.json plus any overrides.
3
- const state = { config: null, events: [], selected: null, detail: null, listKey: '', online: true, seen: null, tab: 'body', flashes: new Map(), hover: null };
4
- const node = (tag, text, cls) => { const el = document.createElement(tag); if (text !== undefined) el.textContent = text; if (cls) el.className = cls; return el; };
5
- let toastTimer;
6
- const showToast = message => { const el = $('toast'); el.textContent = message; el.classList.add('show'); clearTimeout(toastTimer); toastTimer = setTimeout(() => el.classList.remove('show'), 2200); };
7
- const quote = s => "'" + String(s).replaceAll("'", "'\\''") + "'";
8
- const copyText = (text, message) => navigator.clipboard.writeText(text).then(() => showToast(message)).catch(() => showToast('Clipboard unavailable'));
9
- async function getJson(path, options) {
10
- const response = await fetch(path, { cache: 'no-store', ...options });
11
- const data = await response.json().catch(() => ({}));
12
- if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);
13
- return data;
14
- }
15
-
16
- const bytesParts = n => n < 1024 ? [String(n), n === 1 ? 'byte' : 'bytes'] : n < 1048576 ? [(n / 1024).toFixed(1), 'KB'] : [(n / 1048576).toFixed(1), 'MB'];
17
- const fmtBytes = n => bytesParts(n).join(' ');
18
- const exactBytes = n => `${n.toLocaleString()} bytes`;
19
- const fmtAge = t => { const s = Math.max(0, Math.round((Date.now() - t) / 1000)); return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m` : `${Math.floor(s / 3600)}h`; };
20
- const fmtSpan = ms => ms >= 3600000 ? `${+(ms / 3600000).toFixed(1)}h` : ms >= 60000 ? `${+(ms / 60000).toFixed(1)}m` : `${Math.round(ms / 1000)}s`;
21
- const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
22
- const methodClass = m => `m m-${METHODS.includes(m) ? m.toLowerCase() : 'other'}`;
23
-
24
- function setOnline(online) {
25
- if (online === state.online) return;
26
- state.online = online;
27
- $('live-label').textContent = online ? 'Live' : 'Offline';
28
- $('live').classList.toggle('offline', !online);
29
- showToast(online ? 'Reconnected to local server' : 'Cannot reach local server');
30
- }
31
-
32
- // The number is shown large and the unit small, so values like "119 bytes" fit the stat box.
33
- function setStat(id, value, unit = '', bump = true) {
34
- const el = $(id); const text = `${value} ${unit}`;
35
- if (el.dataset.v === text) return;
36
- el.dataset.v = text;
37
- el.replaceChildren(value);
38
- if (unit) el.append(node('span', unit, 'unit'));
39
- if (bump) { el.classList.remove('bump'); void el.offsetWidth; el.classList.add('bump'); }
40
- }
41
- function renderStats() {
42
- const now = Date.now();
43
- setStat('count', String(state.events.length));
44
- setStat('rate', String(state.events.filter(e => now - e.t < 60000).length));
45
- if (state.events.length) setStat('last', fmtAge(state.events[0].t), 'ago', false); else setStat('last', 'none', '', false);
46
- const total = state.events.reduce((sum, e) => sum + e.bytes, 0);
47
- setStat('bytes', ...bytesParts(total)); $('bytes').title = exactBytes(total);
48
- }
49
- const tickAges = () => { document.querySelectorAll('[data-t]').forEach(el => { el.textContent = fmtAge(Number(el.dataset.t)); }); renderStats(); };
50
-
51
- const currentListKey = () => `${state.selected}|${state.events.map(x => x.id).join(',')}`;
52
- function renderList() {
53
- state.listKey = currentListKey();
54
- const list = $('entries'); list.replaceChildren();
55
- if (!state.events.length) list.append(node('div', 'No requests yet.', 'empty'));
56
- // Only requests that arrived after the first render flash in the list and on the timeline.
57
- const firstRender = state.seen === null; state.seen ??= new Set();
58
- for (const event of state.events) {
59
- const isNew = !firstRender && !state.seen.has(event.id);
60
- if (isNew) state.flashes.set(event.id, performance.now());
61
- state.seen.add(event.id);
62
- const row = node('button', undefined, ['row', event.id === state.selected && 'selected', isNew && 'is-new'].filter(Boolean).join(' '));
63
- const path = node('span', event.path, 'path');
64
- if (event.replayOf) path.append(node('span', 'replay', 'replay-mark'));
65
- const age = node('span', fmtAge(event.t), 'num'); age.dataset.t = String(event.t);
66
- const size = node('span', fmtBytes(event.bytes), 'num'); size.title = exactBytes(event.bytes);
67
- row.append(node('span', event.method, methodClass(event.method)), path, size, age);
68
- row.addEventListener('click', () => select(event.id));
69
- list.append(row);
70
- if (event.id === state.selected) requestAnimationFrame(() => row.scrollIntoView({ block: 'nearest' }));
71
- }
72
- }
73
-
74
- function curlCommand(event) {
75
- const excluded = new Set(state.config.curlExcludedHeaders);
76
- const headers = Object.entries(event.headers).filter(([k, v]) => !excluded.has(k.toLowerCase()) && v !== state.config.redactedPlaceholder);
77
- return ['curl', '-X', quote(event.method), ...headers.flatMap(([k, v]) => ['-H', quote(`${k}: ${v}`)]), ...(event.body ? ['--data-raw', quote(event.body)] : []), quote(location.origin + event.path)].join(' ');
78
- }
79
-
80
- const TOKEN = /("(?:\\.|[^"\\])*")(\s*:)?|\b(true|false|null)\b|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|([{}[\],])/g;
81
- function highlightJsonLine(line) {
82
- const frag = document.createDocumentFragment(); let last = 0;
83
- for (const m of line.matchAll(TOKEN)) {
84
- if (m.index > last) frag.append(line.slice(last, m.index));
85
- if (m[1]) { frag.append(node('span', m[1], m[2] ? 't-key' : 't-str')); if (m[2]) frag.append(node('span', m[2], 't-punc')); }
86
- else if (m[3]) frag.append(node('span', m[3], 't-lit'));
87
- else if (m[4]) frag.append(node('span', m[4], 't-num'));
88
- else frag.append(node('span', m[5], 't-punc'));
89
- last = m.index + m[0].length;
90
- }
91
- if (last < line.length) frag.append(line.slice(last));
92
- return frag;
93
- }
94
- function codeBlock(text, highlight) {
95
- const block = node('div', undefined, 'code');
96
- for (const line of text.split('\n')) { const row = node('div', undefined, 'code-line'); const content = node('span'); content.append(highlight ? highlightJsonLine(line) : line); row.append(content); block.append(row); }
97
- return block;
98
- }
99
-
100
- function waitingState() {
101
- const box = node('div', undefined, 'waiting');
102
- const title = node('h2', 'Waiting for the first request', 'waiting-title'); title.append(node('span', undefined, 'cursor'));
103
- box.append(title, node('p', `Send any HTTP method to ${state.endpoint}/anything. It shows up here and on the timeline the moment it lands.`, 'waiting-text'));
104
- box.append(codeBlock(state.demoCommand, false));
105
- const actions = node('div', undefined, 'detail-actions');
106
- const copy = node('button', 'Copy curl', 'btn btn-primary'); copy.addEventListener('click', () => copyText(state.demoCommand, 'curl copied'));
107
- actions.append(copy); box.append(actions);
108
- return box;
109
- }
110
-
111
- function renderDetail() {
112
- const detail = $('detail'); detail.replaceChildren();
113
- const event = state.detail;
114
- if (!event) { detail.append(state.events.length ? node('div', 'Select a request.', 'empty') : waitingState()); return; }
115
- const meta = node('div', undefined, 'detail-meta');
116
- const chip = (text, cls = '') => node('span', text, `chip ${cls}`);
117
- meta.append(chip(event.method, methodClass(event.method)), chip(new Date(event.timestamp).toLocaleString()), chip(fmtBytes(event.bytes)), chip(event.id.slice(0, 8)));
118
- if (event.replayOf) meta.append(chip(`replay of ${event.replayOf.slice(0, 8)}`, 'chip-accent'));
119
- const actions = node('div', undefined, 'detail-actions');
120
- const replay = node('button', 'Replay locally', 'btn btn-primary'); replay.id = 'replay-btn';
121
- replay.addEventListener('click', replaySelected);
122
- const copy = node('button', 'Copy as curl', 'btn'); copy.addEventListener('click', () => copyText(curlCommand(event), 'curl copied. Check for secrets before sharing.'));
123
- actions.append(replay, copy);
124
-
125
- const headerCount = Object.keys(event.headers).length;
126
- const tabs = node('div', undefined, 'tabs'); tabs.setAttribute('role', 'tablist');
127
- for (const [id, label, count] of [['body', 'Body', fmtBytes(event.bytes)], ['headers', 'Headers', String(headerCount)], ['curl', 'cURL']]) {
128
- const tab = node('button', label, 'tab'); tab.setAttribute('role', 'tab'); tab.setAttribute('aria-selected', String(state.tab === id));
129
- if (count) tab.append(node('span', count, 'count'));
130
- tab.addEventListener('click', () => { state.tab = id; renderDetail(); });
131
- tabs.append(tab);
132
- }
133
- const panel = node('div', undefined, 'tab-panel');
134
- if (state.tab === 'body') {
135
- const contentType = String(event.headers['content-type'] || '');
136
- let text = event.body; let json = false;
137
- if (text) { try { text = JSON.stringify(JSON.parse(text), null, 2); json = true; } catch {} }
138
- panel.append(text ? codeBlock(text, json) : node('div', 'Empty body.', 'note'), node('div', `${contentType || 'no content-type'}${json ? ' / formatted' : ''}`, 'note'));
139
- } else if (state.tab === 'headers') {
140
- const table = node('div', undefined, 'headers');
141
- for (const [k, v] of Object.entries(event.headers)) { const row = node('div', undefined, 'header-row'); row.append(node('span', k, 'hk'), node('span', String(v), v === state.config.redactedPlaceholder ? 'hv redacted' : 'hv')); table.append(row); }
142
- panel.append(table, node('div', 'Sensitive header values are redacted.', 'note'));
143
- } else {
144
- panel.append(codeBlock(curlCommand(event), false), node('div', 'Redacted headers are left out. The body may still contain secrets.', 'note'));
145
- }
146
- detail.append(node('h2', event.path, 'detail-path'), meta, actions, tabs, panel);
147
- }
148
-
149
- // Full headers and body are fetched only for the selected event; the list carries summaries.
150
- async function loadDetail(id) {
151
- if (!id) { state.detail = null; renderDetail(); return; }
152
- try { const { event } = await getJson(`/api/events/${encodeURIComponent(id)}`); if (state.selected !== id) return; state.detail = event; }
153
- catch (error) { if (state.selected !== id) return; state.detail = null; showToast(`Cannot load request: ${error.message}`); }
154
- renderDetail();
155
- }
156
- function select(id) {
157
- if (!id || id === state.selected) return;
158
- state.selected = id;
159
- renderList();
160
- return loadDetail(id);
161
- }
162
- async function replaySelected() {
163
- const event = state.detail; if (!event) return;
164
- const button = $('replay-btn'); if (button) button.disabled = true;
165
- try { const data = await getJson(`/api/events/${encodeURIComponent(event.id)}/replay`, { method: 'POST' }); showToast(`Replayed locally / HTTP ${data.responseStatus}`); await refresh(); }
166
- catch (e) { showToast(`Replay failed: ${e.message}`); }
167
- finally { const b = $('replay-btn'); if (b) b.disabled = false; }
168
- }
169
-
170
- // Re-renders only what changed so scroll position and text selection survive polling.
171
- async function refresh() {
172
- let data;
173
- try { data = await getJson('/api/events'); } catch { setOnline(false); return; }
174
- setOnline(true);
175
- state.events = data.events.map(e => ({ ...e, t: Date.parse(e.timestamp) }));
176
- let target = state.selected;
177
- if (target && !state.events.some(x => x.id === target)) target = null;
178
- if (!target && state.events.length) target = state.events[0].id;
179
- const selectionChanged = target !== state.selected;
180
- state.selected = target;
181
- if (currentListKey() !== state.listKey) renderList();
182
- renderStats();
183
- if (selectionChanged) await loadDetail(target);
184
- }
185
- async function poll() { await refresh(); setTimeout(poll, state.config.pollIntervalMs); }
186
-
187
- // Timeline: one spike per request, height by payload size (log scale), color by method.
188
- const scope = { canvas: null, ctx: null, w: 0, h: 0, dpr: 1, colors: {}, lastDraw: 0 };
189
- // The canvas cannot use CSS variables directly, so theme colors are re-read whenever the theme changes.
190
- function readColors() {
191
- const css = getComputedStyle(document.documentElement);
192
- for (const name of ['line', 'line-strong', 'faint', 'dim', 'text', 'accent', 'raise', 'm-get', 'm-post', 'm-put', 'm-patch', 'm-delete', 'm-other']) scope.colors[name] = css.getPropertyValue(`--${name}`).trim();
193
- scope.lastDraw = 0;
194
- }
195
- function setupScope() {
196
- scope.canvas = $('scope'); scope.ctx = scope.canvas.getContext('2d');
197
- readColors();
198
- const resize = () => { const r = scope.canvas.getBoundingClientRect(); scope.dpr = window.devicePixelRatio || 1; scope.w = r.width; scope.h = r.height; scope.canvas.width = Math.round(r.width * scope.dpr); scope.canvas.height = Math.round(r.height * scope.dpr); scope.lastDraw = 0; };
199
- new ResizeObserver(resize).observe(scope.canvas); resize();
200
- const axis = $('axis'); const step = state.config.timelineWindowMs / 5;
201
- for (let i = 5; i >= 0; i--) axis.append(node('span', i ? `-${fmtSpan(step * i)}` : 'now'));
202
- scope.canvas.addEventListener('mousemove', e => {
203
- const x = e.clientX - scope.canvas.getBoundingClientRect().left;
204
- let best = null, bestDist = 8;
205
- for (const ev of state.events) { const d = Math.abs(spikeX(ev.t) - x); if (d < bestDist) { best = ev; bestDist = d; } }
206
- state.hover = best; scope.canvas.style.cursor = best ? 'pointer' : 'crosshair'; scope.lastDraw = 0;
207
- });
208
- scope.canvas.addEventListener('mouseleave', () => { state.hover = null; scope.lastDraw = 0; });
209
- scope.canvas.addEventListener('click', () => { if (state.hover) select(state.hover.id); });
210
- requestAnimationFrame(drawScope);
211
- }
212
- const spikeX = t => (t - (Date.now() - state.config.timelineWindowMs)) / state.config.timelineWindowMs * scope.w;
213
- function drawScope(now) {
214
- requestAnimationFrame(drawScope);
215
- const animating = [...state.flashes.values()].some(start => now - start < 1400);
216
- if (!animating && now - scope.lastDraw < 250) return;
217
- scope.lastDraw = now;
218
- for (const [id, start] of state.flashes) if (now - start > 1400) state.flashes.delete(id);
219
- const { ctx, w, h, dpr, colors } = scope;
220
- ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, w, h);
221
- const base = h - 0.5;
222
- ctx.lineWidth = 1;
223
- ctx.strokeStyle = colors.line;
224
- for (let i = 0; i <= 5; i++) { const x = Math.round(i * (w - 1) / 5) + 0.5; ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke(); }
225
- ctx.setLineDash([2, 4]);
226
- for (const y of [h * 0.33, h * 0.66]) { ctx.beginPath(); ctx.moveTo(0, Math.round(y) + 0.5); ctx.lineTo(w, Math.round(y) + 0.5); ctx.stroke(); }
227
- ctx.setLineDash([]);
228
- ctx.strokeStyle = colors['line-strong']; ctx.beginPath(); ctx.moveTo(0, base); ctx.lineTo(w, base); ctx.stroke();
229
-
230
- const maxLog = Math.log2(state.config.maxBodyBytes + 1);
231
- const emphasized = new Set([state.selected, state.hover?.id]);
232
- for (const ev of [...state.events].reverse()) {
233
- const x = spikeX(ev.t); if (x < -4 || x > w + 4) continue;
234
- const height = 8 + (h - 22) * Math.min(1, Math.log2(ev.bytes + 1) / maxLog);
235
- const color = colors[`m-${METHODS.includes(ev.method) ? ev.method.toLowerCase() : 'other'}`];
236
- const strong = emphasized.has(ev.id);
237
- ctx.globalAlpha = strong ? 1 : 0.7; ctx.fillStyle = color;
238
- ctx.fillRect(Math.round(x) - (strong ? 1 : 0.5), base - height, strong ? 2 : 1, height);
239
- ctx.beginPath(); ctx.arc(x, base - height, strong ? 3.5 : 2.5, 0, Math.PI * 2); ctx.fill();
240
- const start = state.flashes.get(ev.id);
241
- if (start !== undefined) {
242
- const p = (now - start) / 1400;
243
- ctx.globalAlpha = Math.max(0, 1 - p); ctx.strokeStyle = color; ctx.lineWidth = 1.5;
244
- ctx.beginPath(); ctx.arc(x, base - height, 3 + p * 18, 0, Math.PI * 2); ctx.stroke(); ctx.lineWidth = 1;
245
- }
246
- }
247
- ctx.globalAlpha = 1;
248
- const sel = state.events.find(e => e.id === state.selected);
249
- if (sel) { const x = Math.round(spikeX(sel.t)) + 0.5; ctx.strokeStyle = colors.accent; ctx.globalAlpha = 0.35; ctx.setLineDash([3, 3]); ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; }
250
- if (state.hover) {
251
- const label = `${state.hover.method} ${state.hover.path} ${fmtBytes(state.hover.bytes)} ${fmtAge(state.hover.t)} ago`;
252
- ctx.font = '11px "JetBrains Mono", "SF Mono", ui-monospace, Menlo, monospace';
253
- const tw = Math.min(ctx.measureText(label).width + 16, w);
254
- const lx = Math.min(Math.max(spikeX(state.hover.t) - tw / 2, 0), w - tw);
255
- ctx.fillStyle = colors.raise; ctx.strokeStyle = colors['line-strong'];
256
- ctx.fillRect(lx, 2, tw, 22); ctx.strokeRect(lx + 0.5, 2.5, tw - 1, 21);
257
- ctx.fillStyle = colors.text; ctx.fillText(label, lx + 8, 17, tw - 16);
258
- }
259
- }
260
-
261
- function moveSelection(step) {
262
- if (!state.events.length) return;
263
- const index = state.events.findIndex(e => e.id === state.selected);
264
- const next = state.events[Math.min(state.events.length - 1, Math.max(0, (index === -1 ? 0 : index + step)))];
265
- select(next.id);
266
- }
267
- function onKey(e) {
268
- if (e.metaKey || e.ctrlKey || e.altKey || /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName)) return;
269
- if (e.key === 'j' || e.key === 'ArrowDown') { e.preventDefault(); moveSelection(1); }
270
- else if (e.key === 'k' || e.key === 'ArrowUp') { e.preventDefault(); moveSelection(-1); }
271
- else if (e.key === 'r') replaySelected();
272
- else if (e.key === 'c' && state.detail) copyText(curlCommand(state.detail), 'curl copied. Check for secrets before sharing.');
273
- }
274
-
275
- // Theme: "auto" follows the OS. The viewer's choice is remembered in this browser only.
276
- const THEMES = ['auto', 'light', 'dark'];
277
- const THEME_KEY = 'hookdesk-theme';
278
- function applyTheme(choice, remember) {
279
- if (!THEMES.includes(choice)) choice = 'auto';
280
- if (choice === 'auto') delete document.documentElement.dataset.theme; else document.documentElement.dataset.theme = choice;
281
- document.querySelectorAll('[data-theme-choice]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.themeChoice === choice)));
282
- if (remember) { try { localStorage.setItem(THEME_KEY, choice); } catch {} }
283
- readColors();
284
- }
285
- function setupTheme() {
286
- let stored = null;
287
- try { stored = localStorage.getItem(THEME_KEY); } catch {}
288
- applyTheme(stored ?? state.config.defaultTheme, false);
289
- document.querySelectorAll('[data-theme-choice]').forEach(b => b.addEventListener('click', () => applyTheme(b.dataset.themeChoice, true)));
290
- matchMedia('(prefers-color-scheme: light)').addEventListener('change', readColors);
291
- }
292
-
293
- function renderCommand() {
294
- const el = $('command'); el.replaceChildren();
295
- el.append('curl -X POST ', node('span', `${state.endpoint}/demo`, 'url'), ` -H 'Content-Type: application/json' -d '{"hello":"world"}'`);
296
- }
297
-
298
- async function init() {
299
- try { state.config = await getJson('/api/config'); }
300
- catch { setOnline(false); setTimeout(init, 3000); return; }
301
- setOnline(true);
302
- state.endpoint = `${location.origin}${state.config.captureBase}`;
303
- state.demoCommand = `curl -X POST ${state.endpoint}/demo -H 'Content-Type: application/json' -d '{"hello":"world"}'`;
304
- document.querySelectorAll('[data-bind="host"]').forEach(el => { el.textContent = state.config.host; });
305
- document.querySelectorAll('[data-bind="limit"]').forEach(el => { el.textContent = String(state.config.maxEvents); });
306
- document.querySelectorAll('[data-bind="window"]').forEach(el => { el.textContent = fmtSpan(state.config.timelineWindowMs); });
307
- renderCommand();
308
- $('copy').addEventListener('click', () => copyText(state.endpoint, 'Endpoint copied'));
309
- $('copy-cmd').addEventListener('click', () => copyText(state.demoCommand, 'curl copied'));
310
- $('refresh').addEventListener('click', refresh);
311
- $('clear').addEventListener('click', async () => {
312
- if (!confirm('Clear all captured requests?')) return;
313
- try { await getJson('/api/events', { method: 'DELETE' }); } catch (e) { showToast(`Clear failed: ${e.message}`); return; }
314
- state.selected = null; state.detail = null; await refresh(); renderDetail();
315
- });
316
- document.addEventListener('keydown', onKey);
317
- setupScope();
318
- setupTheme();
319
- // The list renders on the first poll, so requests already in memory at page load don't flash as new.
320
- renderDetail(); poll();
321
- setInterval(tickAges, 1000);
322
- }
323
- init();
package/src/wordmark.svg DELETED
@@ -1,13 +0,0 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" width="290" height="64" viewBox="0 0 290 64" fill="none">
2
- <title>Hookdesk Mini</title>
3
- <rect width="290" height="64" rx="14" fill="#09090a"/>
4
- <g transform="translate(12 12)">
5
- <rect width="40" height="40" rx="11" fill="#c6ff3d"/>
6
- <path d="M13 13v10a8 8 0 0 0 16 0v-3" stroke="#0b0e02" stroke-width="3.5" stroke-linecap="round"/>
7
- <path d="m30.75 14-7 8 5.25-1 1.75 3Z" fill="#0b0e02"/>
8
- <circle cx="13" cy="10" r="3" stroke="#0b0e02" stroke-width="2.5"/>
9
- </g>
10
- <text x="65" y="41" fill="#ededef" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif" font-size="28" font-weight="650" letter-spacing="-1">hookdesk</text>
11
- <rect x="234" y="23" width="43" height="20" rx="5" stroke="#3e3e45"/>
12
- <text x="255.5" y="37" text-anchor="middle" fill="#a1a1aa" font-family="ui-monospace, monospace" font-size="11">mini</text>
13
- </svg>
File without changes