hookdesk 0.0.0-stage → 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/CHANGELOG.md +53 -0
- package/LICENSE +21 -0
- package/README.md +490 -2
- package/config/app.json +198 -0
- package/config/default.json +66 -0
- package/config/limits.json +40 -0
- package/config/messages.json +193 -0
- package/package.json +44 -4
- package/src/cli.js +24 -0
- package/src/loader/fixed.js +18 -0
- package/src/loader/settings.js +94 -0
- package/src/mocks/rules.js +95 -0
- package/src/server.js +194 -0
- package/src/store/events.js +34 -0
- package/src/ui/index.html +83 -0
- package/src/ui/logo.svg +7 -0
- package/src/ui/ui.css +252 -0
- package/src/ui/ui.js +419 -0
package/src/ui/ui.js
ADDED
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
const $ = id => document.getElementById(id);
|
|
2
|
+
// Every setting, route, and text comes from the config route (config/default.json, app.json, limits.json, messages.json).
|
|
3
|
+
const state = { config: null, events: [], mocks: [], mocksKey: '', selected: null, detail: null, listKey: '', online: true, seen: null, tab: null, flashes: new Map(), hover: null };
|
|
4
|
+
const ui = () => state.config.ui;
|
|
5
|
+
const t = () => state.config.messages;
|
|
6
|
+
const routes = () => state.config.routes;
|
|
7
|
+
const format = (template, values = {}) => template.replace(/\{(\w+)\}/g, (match, key) => key in values ? String(values[key]) : match);
|
|
8
|
+
const route = (name, id) => format(routes()[name], { id: encodeURIComponent(id) });
|
|
9
|
+
const node = (tag, text, cls) => { const el = document.createElement(tag); if (text !== undefined) el.textContent = text; if (cls) el.className = cls; return el; };
|
|
10
|
+
let toastTimer;
|
|
11
|
+
const showToast = message => { const el = $('toast'); el.textContent = message; el.classList.add('show'); clearTimeout(toastTimer); toastTimer = setTimeout(() => el.classList.remove('show'), ui().toastMs); };
|
|
12
|
+
const quote = s => "'" + String(s).replaceAll("'", "'\\''") + "'";
|
|
13
|
+
const copyText = (text, message) => navigator.clipboard.writeText(text).then(() => showToast(message)).catch(() => showToast(t().clipboardUnavailable));
|
|
14
|
+
async function getJson(path, options) {
|
|
15
|
+
const response = await fetch(path, { cache: 'no-store', ...options });
|
|
16
|
+
const data = await response.json().catch(() => ({}));
|
|
17
|
+
if (!response.ok) throw new Error(data.error || format(t().httpStatus, { status: response.status }));
|
|
18
|
+
return data;
|
|
19
|
+
}
|
|
20
|
+
const sendJson = (path, method, value) => getJson(path, { method, headers: { [state.config.headers.contentType]: state.config.contentTypes.json }, body: JSON.stringify(value) });
|
|
21
|
+
|
|
22
|
+
// Unit conversions (1024 bytes per KB, 60 seconds per minute) are arithmetic, not settings.
|
|
23
|
+
const bytesParts = n => n < 1024 ? [String(n), n === 1 ? t().byte : t().bytes] : n < 1048576 ? [(n / 1024).toFixed(1), t().kilobytes] : [(n / 1048576).toFixed(1), t().megabytes];
|
|
24
|
+
const fmtBytes = n => bytesParts(n).join(' ');
|
|
25
|
+
const exactBytes = n => format(t().exactBytes, { count: n.toLocaleString() });
|
|
26
|
+
const fmtAge = time => { const s = Math.max(0, Math.round((Date.now() - time) / 1000)); return s < 60 ? format(t().seconds, { value: s }) : s < 3600 ? format(t().minutes, { value: Math.floor(s / 60) }) : format(t().hours, { value: Math.floor(s / 3600) }); };
|
|
27
|
+
const fmtSpan = ms => ms >= 3600000 ? format(t().hours, { value: +(ms / 3600000).toFixed(1) }) : ms >= 60000 ? format(t().minutes, { value: +(ms / 60000).toFixed(1) }) : format(t().seconds, { value: Math.round(ms / 1000) });
|
|
28
|
+
const OTHER = 'other';
|
|
29
|
+
const methodKey = m => ui().methods.includes(m) ? m.toLowerCase() : OTHER;
|
|
30
|
+
const methodClass = m => `m m-${methodKey(m)}`;
|
|
31
|
+
const statusClass = s => s >= ui().errorStatusFrom ? 'num status-error' : 'num';
|
|
32
|
+
|
|
33
|
+
function setOnline(online) {
|
|
34
|
+
if (online === state.online) return;
|
|
35
|
+
state.online = online;
|
|
36
|
+
$('live-label').textContent = online ? t().live : t().offline;
|
|
37
|
+
$('live').classList.toggle('offline', !online);
|
|
38
|
+
showToast(online ? t().reconnected : t().unreachable);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// The number is shown large and the unit small, so values like "119 bytes" fit the stat box.
|
|
42
|
+
function setStat(id, value, unit = '', bump = true) {
|
|
43
|
+
const el = $(id); const text = `${value} ${unit}`;
|
|
44
|
+
if (el.dataset.v === text) return;
|
|
45
|
+
el.dataset.v = text;
|
|
46
|
+
el.replaceChildren(value);
|
|
47
|
+
if (unit) el.append(node('span', unit, 'unit'));
|
|
48
|
+
if (bump) { el.classList.remove('bump'); void el.offsetWidth; el.classList.add('bump'); }
|
|
49
|
+
}
|
|
50
|
+
function renderStats() {
|
|
51
|
+
const now = Date.now();
|
|
52
|
+
setStat('count', String(state.events.length));
|
|
53
|
+
setStat('rate', String(state.events.filter(e => now - e.t < ui().rateWindowMs).length));
|
|
54
|
+
if (state.events.length) setStat('last', fmtAge(state.events[0].t), t().ago, false); else setStat('last', t().none, '', false);
|
|
55
|
+
const total = state.events.reduce((sum, e) => sum + e.bytes, 0);
|
|
56
|
+
setStat('bytes', ...bytesParts(total)); $('bytes').title = exactBytes(total);
|
|
57
|
+
}
|
|
58
|
+
const tickAges = () => { document.querySelectorAll('[data-t]').forEach(el => { el.textContent = fmtAge(Number(el.dataset.t)); }); renderStats(); };
|
|
59
|
+
|
|
60
|
+
const currentListKey = () => `${state.selected}|${state.events.map(x => x.id).join(',')}`;
|
|
61
|
+
function renderList() {
|
|
62
|
+
state.listKey = currentListKey();
|
|
63
|
+
const list = $('entries'); list.replaceChildren();
|
|
64
|
+
if (!state.events.length) list.append(node('div', t().noRequests, 'empty'));
|
|
65
|
+
// Only requests that arrived after the first render flash in the list and on the timeline.
|
|
66
|
+
const firstRender = state.seen === null; state.seen ??= new Set();
|
|
67
|
+
for (const event of state.events) {
|
|
68
|
+
const isNew = !firstRender && !state.seen.has(event.id);
|
|
69
|
+
if (isNew) state.flashes.set(event.id, performance.now());
|
|
70
|
+
state.seen.add(event.id);
|
|
71
|
+
const row = node('button', undefined, ['row', event.id === state.selected && 'selected', isNew && 'is-new'].filter(Boolean).join(' '));
|
|
72
|
+
const path = node('span', event.path, 'path');
|
|
73
|
+
if (event.replayOf) path.append(node('span', t().replayMark, 'replay-mark'));
|
|
74
|
+
if (event.mockId) path.append(node('span', t().mockMark, 'mock-mark'));
|
|
75
|
+
const age = node('span', fmtAge(event.t), 'num'); age.dataset.t = String(event.t);
|
|
76
|
+
const size = node('span', fmtBytes(event.bytes), 'num'); size.title = exactBytes(event.bytes);
|
|
77
|
+
row.append(node('span', event.method, methodClass(event.method)), path, node('span', String(event.status), statusClass(event.status)), size, age);
|
|
78
|
+
row.addEventListener('click', () => select(event.id));
|
|
79
|
+
list.append(row);
|
|
80
|
+
if (event.id === state.selected) requestAnimationFrame(() => row.scrollIntoView({ block: 'nearest' }));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function curlCommand(event) {
|
|
85
|
+
const excluded = new Set(state.config.curlExcludedHeaders);
|
|
86
|
+
const headers = Object.entries(event.headers).filter(([k, v]) => !excluded.has(k.toLowerCase()) && v !== state.config.redactedPlaceholder);
|
|
87
|
+
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(' ');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const TOKEN = /("(?:\\.|[^"\\])*")(\s*:)?|\b(true|false|null)\b|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|([{}[\],])/g;
|
|
91
|
+
function highlightJsonLine(line) {
|
|
92
|
+
const frag = document.createDocumentFragment(); let last = 0;
|
|
93
|
+
for (const m of line.matchAll(TOKEN)) {
|
|
94
|
+
if (m.index > last) frag.append(line.slice(last, m.index));
|
|
95
|
+
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')); }
|
|
96
|
+
else if (m[3]) frag.append(node('span', m[3], 't-lit'));
|
|
97
|
+
else if (m[4]) frag.append(node('span', m[4], 't-num'));
|
|
98
|
+
else frag.append(node('span', m[5], 't-punc'));
|
|
99
|
+
last = m.index + m[0].length;
|
|
100
|
+
}
|
|
101
|
+
if (last < line.length) frag.append(line.slice(last));
|
|
102
|
+
return frag;
|
|
103
|
+
}
|
|
104
|
+
function codeBlock(text, highlight) {
|
|
105
|
+
const block = node('div', undefined, 'code');
|
|
106
|
+
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); }
|
|
107
|
+
return block;
|
|
108
|
+
}
|
|
109
|
+
const keyValueTable = rows => {
|
|
110
|
+
const table = node('div', undefined, 'headers');
|
|
111
|
+
for (const [k, v, cls = 'hv'] of rows) { const row = node('div', undefined, 'header-row'); row.append(node('span', k, 'hk'), node('span', String(v), cls)); table.append(row); }
|
|
112
|
+
return table;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
function waitingState() {
|
|
116
|
+
const box = node('div', undefined, 'waiting');
|
|
117
|
+
const title = node('h2', t().waitingTitle, 'waiting-title'); title.append(node('span', undefined, 'cursor'));
|
|
118
|
+
box.append(title, node('p', format(t().waitingText, { endpoint: state.endpoint }), 'waiting-text'));
|
|
119
|
+
box.append(codeBlock(state.demoCommand, false));
|
|
120
|
+
const actions = node('div', undefined, 'detail-actions');
|
|
121
|
+
const copy = node('button', t().copyCurl, 'btn btn-primary'); copy.addEventListener('click', () => copyText(state.demoCommand, t().curlCopied));
|
|
122
|
+
actions.append(copy); box.append(actions);
|
|
123
|
+
return box;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Detail tabs, in display order. Each has a label from messages.json, an optional count, and a panel.
|
|
127
|
+
const TABS = [
|
|
128
|
+
{ id: 'body', label: () => t().tabBody, count: e => fmtBytes(e.bytes), panel: e => {
|
|
129
|
+
const contentType = String(e.headers[state.config.headers.contentType] || '');
|
|
130
|
+
let text = e.body; let json = false;
|
|
131
|
+
if (text) { try { text = JSON.stringify(JSON.parse(text), null, 2); json = true; } catch {} }
|
|
132
|
+
return [text ? codeBlock(text, json) : node('div', t().emptyBody, 'note'), node('div', `${contentType || t().noContentType}${json ? t().formatted : ''}`, 'note')];
|
|
133
|
+
} },
|
|
134
|
+
{ id: 'headers', label: () => t().tabHeaders, count: e => String(Object.keys(e.headers).length), panel: e =>
|
|
135
|
+
[keyValueTable(Object.entries(e.headers).map(([k, v]) => [k, v, v === state.config.redactedPlaceholder ? 'hv redacted' : 'hv'])), node('div', t().redactedNote, 'note')] },
|
|
136
|
+
{ id: 'response', label: () => t().tabResponse, count: e => String(e.response.status), panel: e => {
|
|
137
|
+
const { status, mockId, mockPath, delayMs } = e.response;
|
|
138
|
+
return [keyValueTable([
|
|
139
|
+
[t().responseStatus, status, status >= ui().errorStatusFrom ? 'hv redacted' : 'hv'],
|
|
140
|
+
[t().responseAnsweredBy, mockId ? format(t().answeredByRule, { id: mockId, path: mockPath }) : t().answeredByDefault],
|
|
141
|
+
[t().responseDelay, format(t().milliseconds, { value: delayMs })],
|
|
142
|
+
]), node('div', t().responseNote, 'note')];
|
|
143
|
+
} },
|
|
144
|
+
{ id: 'curl', label: () => t().tabCurl, count: () => '', panel: e => [codeBlock(curlCommand(e), false), node('div', t().curlNote, 'note')] },
|
|
145
|
+
];
|
|
146
|
+
|
|
147
|
+
function renderDetail() {
|
|
148
|
+
const detail = $('detail'); detail.replaceChildren();
|
|
149
|
+
const event = state.detail;
|
|
150
|
+
if (!event) { detail.append(state.events.length ? node('div', t().selectRequest, 'empty') : waitingState()); return; }
|
|
151
|
+
const short = id => id.slice(0, ui().shortIdLength);
|
|
152
|
+
const meta = node('div', undefined, 'detail-meta');
|
|
153
|
+
const chip = (text, cls = '') => node('span', text, `chip ${cls}`);
|
|
154
|
+
meta.append(chip(event.method, methodClass(event.method)), chip(new Date(event.timestamp).toLocaleString()), chip(fmtBytes(event.bytes)), chip(short(event.id)));
|
|
155
|
+
if (event.replayOf) meta.append(chip(format(t().replayOf, { id: short(event.replayOf) }), 'chip-accent'));
|
|
156
|
+
const actions = node('div', undefined, 'detail-actions');
|
|
157
|
+
const replay = node('button', t().replayLocally, 'btn btn-primary'); replay.id = 'replay-btn';
|
|
158
|
+
replay.addEventListener('click', replaySelected);
|
|
159
|
+
const copy = node('button', t().copyAsCurl, 'btn'); copy.addEventListener('click', () => copyText(curlCommand(event), t().curlCopiedWarning));
|
|
160
|
+
actions.append(replay, copy);
|
|
161
|
+
|
|
162
|
+
state.tab ??= TABS[0].id;
|
|
163
|
+
const tabs = node('div', undefined, 'tabs'); tabs.setAttribute('role', 'tablist');
|
|
164
|
+
for (const tab of TABS) {
|
|
165
|
+
const button = node('button', tab.label(), 'tab'); button.setAttribute('role', 'tab'); button.setAttribute('aria-selected', String(state.tab === tab.id));
|
|
166
|
+
const count = tab.count(event);
|
|
167
|
+
if (count) button.append(node('span', count, 'count'));
|
|
168
|
+
button.addEventListener('click', () => { state.tab = tab.id; renderDetail(); });
|
|
169
|
+
tabs.append(button);
|
|
170
|
+
}
|
|
171
|
+
const panel = node('div', undefined, 'tab-panel');
|
|
172
|
+
panel.append(...TABS.find(tab => tab.id === state.tab).panel(event));
|
|
173
|
+
detail.append(node('h2', event.path, 'detail-path'), meta, actions, tabs, panel);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Full headers and body are fetched only for the selected event; the list carries summaries.
|
|
177
|
+
async function loadDetail(id) {
|
|
178
|
+
if (!id) { state.detail = null; renderDetail(); return; }
|
|
179
|
+
try { const { event } = await getJson(route('event', id)); if (state.selected !== id) return; state.detail = event; }
|
|
180
|
+
catch (error) { if (state.selected !== id) return; state.detail = null; showToast(format(t().cannotLoadRequest, { reason: error.message })); }
|
|
181
|
+
renderDetail();
|
|
182
|
+
}
|
|
183
|
+
function select(id) {
|
|
184
|
+
if (!id || id === state.selected) return;
|
|
185
|
+
state.selected = id;
|
|
186
|
+
renderList();
|
|
187
|
+
return loadDetail(id);
|
|
188
|
+
}
|
|
189
|
+
async function replaySelected() {
|
|
190
|
+
const event = state.detail; if (!event) return;
|
|
191
|
+
const button = $('replay-btn'); if (button) button.disabled = true;
|
|
192
|
+
try { const data = await getJson(route('replay', event.id), { method: state.config.methods.post }); showToast(format(t().replayed, { status: data.responseStatus })); await refresh(); }
|
|
193
|
+
catch (e) { showToast(format(t().replayFailed, { reason: e.message })); }
|
|
194
|
+
finally { const b = $('replay-btn'); if (b) b.disabled = false; }
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Mock rules: listed newest first, the first matching rule answers.
|
|
198
|
+
function renderMocks() {
|
|
199
|
+
const key = JSON.stringify(state.mocks);
|
|
200
|
+
if (key === state.mocksKey) return;
|
|
201
|
+
state.mocksKey = key;
|
|
202
|
+
const count = state.mocks.length;
|
|
203
|
+
$('mocks-count').textContent = format(count === 1 ? t().rulesOne : t().rulesMany, { count });
|
|
204
|
+
const list = $('mocks-list'); list.replaceChildren();
|
|
205
|
+
if (!count) list.append(node('div', t().noRules, 'note'));
|
|
206
|
+
for (const rule of state.mocks) {
|
|
207
|
+
const row = node('div', undefined, 'mock-row');
|
|
208
|
+
const remove = node('button', t().remove, 'btn btn-ghost btn-danger');
|
|
209
|
+
remove.addEventListener('click', async () => {
|
|
210
|
+
try { await getJson(route('mock', rule.id), { method: state.config.methods.delete }); await refreshMocks(); }
|
|
211
|
+
catch (e) { showToast(format(t().cannotRemoveRule, { reason: e.message })); }
|
|
212
|
+
});
|
|
213
|
+
row.append(node('span', rule.method, rule.method === state.config.anyMethod ? `m m-${OTHER}` : methodClass(rule.method)), node('span', rule.path, 'path'), node('span', String(rule.status), statusClass(rule.status)), node('span', format(t().milliseconds, { value: rule.delayMs }), 'num'), node('span', rule.id, 'mock-id'), remove);
|
|
214
|
+
list.append(row);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
async function refreshMocks() {
|
|
218
|
+
try { state.mocks = (await getJson(routes().mocks)).rules; renderMocks(); } catch {}
|
|
219
|
+
}
|
|
220
|
+
async function addMock(e) {
|
|
221
|
+
e.preventDefault();
|
|
222
|
+
const f = e.target.elements;
|
|
223
|
+
const contentType = state.config.headers.contentType;
|
|
224
|
+
const rule = { method: f.method.value, path: f.path.value.trim(), status: Number(f.status.value), delayMs: Number(f.delayMs.value) };
|
|
225
|
+
try { if (f.headers.value.trim()) rule.headers = JSON.parse(f.headers.value); }
|
|
226
|
+
catch { showToast(t().headersNotJson); return; }
|
|
227
|
+
if (f.body.value) {
|
|
228
|
+
rule.body = f.body.value;
|
|
229
|
+
// A body that parses as JSON is sent as JSON unless the headers already name a content type.
|
|
230
|
+
const typed = Object.keys(rule.headers || {}).some(k => k.toLowerCase() === contentType);
|
|
231
|
+
if (!typed) { try { JSON.parse(rule.body); rule.headers = { ...rule.headers, [contentType]: state.config.contentTypes.json }; } catch {} }
|
|
232
|
+
}
|
|
233
|
+
try {
|
|
234
|
+
await sendJson(routes().mocks, state.config.methods.post, rule);
|
|
235
|
+
showToast(t().ruleAdded);
|
|
236
|
+
e.target.reset(); setupMockForm();
|
|
237
|
+
await refreshMocks();
|
|
238
|
+
} catch (err) { showToast(format(t().cannotAddRule, { reason: err.message })); }
|
|
239
|
+
}
|
|
240
|
+
function setupMockForm() {
|
|
241
|
+
const f = $('mock-form').elements;
|
|
242
|
+
const { mockRuleDefaults: defaults, statusRange } = state.config;
|
|
243
|
+
f.path.value = state.config.captureBase;
|
|
244
|
+
f.status.value = String(defaults.status); f.status.min = String(statusRange.min); f.status.max = String(statusRange.max);
|
|
245
|
+
f.delayMs.value = String(defaults.delayMs); f.delayMs.min = String(state.config.minDelayMs); f.delayMs.max = String(state.config.maxDelayMs);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Re-renders only what changed so scroll position and text selection survive polling.
|
|
249
|
+
async function refresh() {
|
|
250
|
+
let data;
|
|
251
|
+
try { data = await getJson(routes().events); } catch { setOnline(false); return; }
|
|
252
|
+
setOnline(true);
|
|
253
|
+
state.events = data.events.map(e => ({ ...e, t: Date.parse(e.timestamp) }));
|
|
254
|
+
let target = state.selected;
|
|
255
|
+
if (target && !state.events.some(x => x.id === target)) target = null;
|
|
256
|
+
if (!target && state.events.length) target = state.events[0].id;
|
|
257
|
+
const selectionChanged = target !== state.selected;
|
|
258
|
+
state.selected = target;
|
|
259
|
+
if (currentListKey() !== state.listKey) renderList();
|
|
260
|
+
renderStats();
|
|
261
|
+
if (selectionChanged) await loadDetail(target);
|
|
262
|
+
}
|
|
263
|
+
async function poll() { await Promise.all([refresh(), refreshMocks()]); setTimeout(poll, state.config.pollIntervalMs); }
|
|
264
|
+
|
|
265
|
+
// Timeline: one spike per request, height by payload size (log scale), color by method.
|
|
266
|
+
const scope = { canvas: null, ctx: null, w: 0, h: 0, dpr: 1, colors: {}, lastDraw: 0 };
|
|
267
|
+
// The canvas cannot use CSS variables directly, so theme colors are re-read whenever the theme changes.
|
|
268
|
+
function readColors() {
|
|
269
|
+
const css = getComputedStyle(document.documentElement);
|
|
270
|
+
for (const name of ['line', 'line-strong', 'text', 'accent', 'raise', 'mono', ...[...ui().methods, OTHER].map(m => `m-${m.toLowerCase()}`)]) scope.colors[name] = css.getPropertyValue(`--${name}`).trim();
|
|
271
|
+
scope.lastDraw = 0;
|
|
272
|
+
}
|
|
273
|
+
function setupScope() {
|
|
274
|
+
const tl = ui().timeline;
|
|
275
|
+
scope.canvas = $('scope'); scope.ctx = scope.canvas.getContext('2d');
|
|
276
|
+
readColors();
|
|
277
|
+
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; };
|
|
278
|
+
new ResizeObserver(resize).observe(scope.canvas); resize();
|
|
279
|
+
const axis = $('axis'); const step = state.config.timelineWindowMs / tl.divisions;
|
|
280
|
+
for (let i = tl.divisions; i >= 0; i--) axis.append(node('span', i ? `-${fmtSpan(step * i)}` : t().now));
|
|
281
|
+
scope.canvas.addEventListener('mousemove', e => {
|
|
282
|
+
const x = e.clientX - scope.canvas.getBoundingClientRect().left;
|
|
283
|
+
let best = null, bestDist = tl.hoverRadiusPx;
|
|
284
|
+
for (const ev of state.events) { const d = Math.abs(spikeX(ev.t) - x); if (d < bestDist) { best = ev; bestDist = d; } }
|
|
285
|
+
state.hover = best; scope.canvas.style.cursor = best ? 'pointer' : 'crosshair'; scope.lastDraw = 0;
|
|
286
|
+
});
|
|
287
|
+
scope.canvas.addEventListener('mouseleave', () => { state.hover = null; scope.lastDraw = 0; });
|
|
288
|
+
scope.canvas.addEventListener('click', () => { if (state.hover) select(state.hover.id); });
|
|
289
|
+
requestAnimationFrame(drawScope);
|
|
290
|
+
}
|
|
291
|
+
const spikeX = time => (time - (Date.now() - state.config.timelineWindowMs)) / state.config.timelineWindowMs * scope.w;
|
|
292
|
+
function drawScope(now) {
|
|
293
|
+
requestAnimationFrame(drawScope);
|
|
294
|
+
const tl = ui().timeline; const flashMs = ui().flashMs;
|
|
295
|
+
const animating = [...state.flashes.values()].some(start => now - start < flashMs);
|
|
296
|
+
if (!animating && now - scope.lastDraw < tl.redrawMs) return;
|
|
297
|
+
scope.lastDraw = now;
|
|
298
|
+
for (const [id, start] of state.flashes) if (now - start > flashMs) state.flashes.delete(id);
|
|
299
|
+
const { ctx, w, h, dpr, colors } = scope;
|
|
300
|
+
ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, w, h);
|
|
301
|
+
// The 0.5 offsets put 1-pixel lines on pixel centers so they stay sharp.
|
|
302
|
+
const base = h - 0.5;
|
|
303
|
+
ctx.lineWidth = tl.lineWidth;
|
|
304
|
+
ctx.strokeStyle = colors.line;
|
|
305
|
+
for (let i = 0; i <= tl.divisions; i++) { const x = Math.round(i * (w - 1) / tl.divisions) + 0.5; ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke(); }
|
|
306
|
+
ctx.setLineDash(tl.gridDash);
|
|
307
|
+
for (let row = 1; row < tl.gridRows; row++) { const y = Math.round(h * row / tl.gridRows) + 0.5; ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(w, y); ctx.stroke(); }
|
|
308
|
+
ctx.setLineDash([]);
|
|
309
|
+
ctx.strokeStyle = colors['line-strong']; ctx.beginPath(); ctx.moveTo(0, base); ctx.lineTo(w, base); ctx.stroke();
|
|
310
|
+
|
|
311
|
+
const maxLog = Math.log2(state.config.maxBodyBytes + 1);
|
|
312
|
+
const emphasized = new Set([state.selected, state.hover?.id]);
|
|
313
|
+
for (const ev of [...state.events].reverse()) {
|
|
314
|
+
const x = spikeX(ev.t); if (x < -tl.hoverRadiusPx || x > w + tl.hoverRadiusPx) continue;
|
|
315
|
+
const height = tl.minSpikePx + (h - tl.topPaddingPx) * Math.min(1, Math.log2(ev.bytes + 1) / maxLog);
|
|
316
|
+
const color = colors[`m-${methodKey(ev.method)}`];
|
|
317
|
+
const strong = emphasized.has(ev.id);
|
|
318
|
+
const spikeWidth = strong ? tl.selectedSpikeWidthPx : tl.spikeWidthPx;
|
|
319
|
+
ctx.globalAlpha = strong ? 1 : tl.idleAlpha; ctx.fillStyle = color;
|
|
320
|
+
ctx.fillRect(Math.round(x) - spikeWidth / 2, base - height, spikeWidth, height);
|
|
321
|
+
ctx.beginPath(); ctx.arc(x, base - height, strong ? tl.selectedDotRadiusPx : tl.dotRadiusPx, 0, Math.PI * 2); ctx.fill();
|
|
322
|
+
const start = state.flashes.get(ev.id);
|
|
323
|
+
if (start !== undefined) {
|
|
324
|
+
const p = (now - start) / flashMs;
|
|
325
|
+
ctx.globalAlpha = Math.max(0, 1 - p); ctx.strokeStyle = color; ctx.lineWidth = tl.pulseLineWidth;
|
|
326
|
+
ctx.beginPath(); ctx.arc(x, base - height, tl.selectedDotRadiusPx + p * tl.pulseGrowPx, 0, Math.PI * 2); ctx.stroke(); ctx.lineWidth = tl.lineWidth;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
ctx.globalAlpha = 1;
|
|
330
|
+
const sel = state.events.find(e => e.id === state.selected);
|
|
331
|
+
if (sel) { const x = Math.round(spikeX(sel.t)) + 0.5; ctx.strokeStyle = colors.accent; ctx.globalAlpha = tl.selectionAlpha; ctx.setLineDash(tl.selectionDash); ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; }
|
|
332
|
+
if (state.hover) {
|
|
333
|
+
const hv = state.hover;
|
|
334
|
+
const label = format(t().hoverLabel, { method: hv.method, path: hv.path, status: hv.status, size: fmtBytes(hv.bytes), age: fmtAge(hv.t) });
|
|
335
|
+
const pad = tl.labelPaddingPx; const lh = tl.labelHeightPx; const top = tl.labelTopPx;
|
|
336
|
+
ctx.font = `${tl.labelFontPx}px ${colors.mono}`;
|
|
337
|
+
const tw = Math.min(ctx.measureText(label).width + pad * 2, w);
|
|
338
|
+
const lx = Math.min(Math.max(spikeX(hv.t) - tw / 2, 0), w - tw);
|
|
339
|
+
ctx.fillStyle = colors.raise; ctx.strokeStyle = colors['line-strong'];
|
|
340
|
+
ctx.fillRect(lx, top, tw, lh); ctx.strokeRect(lx + 0.5, top + 0.5, tw - 1, lh - 1);
|
|
341
|
+
ctx.fillStyle = colors.text; ctx.textBaseline = 'middle'; ctx.fillText(label, lx + pad, top + lh / 2, tw - pad * 2);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function moveSelection(step) {
|
|
346
|
+
if (!state.events.length) return;
|
|
347
|
+
const index = state.events.findIndex(e => e.id === state.selected);
|
|
348
|
+
const next = state.events[Math.min(state.events.length - 1, Math.max(0, (index === -1 ? 0 : index + step)))];
|
|
349
|
+
select(next.id);
|
|
350
|
+
}
|
|
351
|
+
function onKey(e) {
|
|
352
|
+
if (e.metaKey || e.ctrlKey || e.altKey || /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName)) return;
|
|
353
|
+
const keys = ui().keys;
|
|
354
|
+
if (keys.next.includes(e.key)) { e.preventDefault(); moveSelection(1); }
|
|
355
|
+
else if (keys.previous.includes(e.key)) { e.preventDefault(); moveSelection(-1); }
|
|
356
|
+
else if (keys.replay.includes(e.key)) replaySelected();
|
|
357
|
+
else if (keys.copyCurl.includes(e.key) && state.detail) copyText(curlCommand(state.detail), t().curlCopiedWarning);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// Theme: the first theme in config/limits.json ("auto") follows the OS. The viewer's choice is remembered in this browser only.
|
|
361
|
+
function applyTheme(choice, remember) {
|
|
362
|
+
const themes = state.config.themes;
|
|
363
|
+
if (!themes.includes(choice)) choice = themes[0];
|
|
364
|
+
if (choice === themes[0]) delete document.documentElement.dataset.theme; else document.documentElement.dataset.theme = choice;
|
|
365
|
+
document.querySelectorAll('[data-theme-choice]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.themeChoice === choice)));
|
|
366
|
+
if (remember) { try { localStorage.setItem(ui().themeStorageKey, choice); } catch {} }
|
|
367
|
+
readColors();
|
|
368
|
+
}
|
|
369
|
+
function setupTheme() {
|
|
370
|
+
for (const theme of state.config.themes) { const b = node('button', t().themes[theme]); b.dataset.themeChoice = theme; $('themes').append(b); }
|
|
371
|
+
let stored = null;
|
|
372
|
+
try { stored = localStorage.getItem(ui().themeStorageKey); } catch {}
|
|
373
|
+
applyTheme(stored ?? state.config.defaultTheme, false);
|
|
374
|
+
document.querySelectorAll('[data-theme-choice]').forEach(b => b.addEventListener('click', () => applyTheme(b.dataset.themeChoice, true)));
|
|
375
|
+
matchMedia('(prefers-color-scheme: light)').addEventListener('change', readColors);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function bindText(name, value) { document.querySelectorAll(`[data-bind="${name}"]`).forEach(el => { el.textContent = value; }); }
|
|
379
|
+
|
|
380
|
+
async function init() {
|
|
381
|
+
try { state.config = await getJson(document.body.dataset.configUrl); }
|
|
382
|
+
catch { $('live-label').textContent = document.body.dataset.offline; $('live').classList.add('offline'); setTimeout(init, Number(document.body.dataset.retryMs)); return; }
|
|
383
|
+
state.online = true;
|
|
384
|
+
state.endpoint = `${location.origin}${state.config.captureBase}`;
|
|
385
|
+
state.demoCommand = format(state.config.exampleCommand, { url: `${state.endpoint}${state.config.examplePath}`, contentType: state.config.exampleContentType, body: state.config.exampleBody });
|
|
386
|
+
document.title = state.config.name;
|
|
387
|
+
bindText('host', state.config.host);
|
|
388
|
+
bindText('limit', String(state.config.maxEvents));
|
|
389
|
+
bindText('window', fmtSpan(state.config.timelineWindowMs));
|
|
390
|
+
bindText('version', state.config.version);
|
|
391
|
+
bindText('rate-window', fmtSpan(ui().rateWindowMs));
|
|
392
|
+
bindText('prefix-suffix', state.config.prefixSuffix);
|
|
393
|
+
document.querySelectorAll('[data-keys]').forEach(el => { for (const action of el.dataset.keys.split(' ')) el.append(node('kbd', ui().keys[action][0])); });
|
|
394
|
+
for (const method of ui().methods) $('legend').append(node('span', method, methodClass(method)));
|
|
395
|
+
$('legend').append(node('span', t().otherMethods, `m m-${OTHER}`));
|
|
396
|
+
for (const method of ui().mockMethods) $('mock-form').elements.method.append(node('option', method));
|
|
397
|
+
setupMockForm();
|
|
398
|
+
$('command').textContent = state.demoCommand;
|
|
399
|
+
$('copy').addEventListener('click', () => copyText(state.endpoint, t().endpointCopied));
|
|
400
|
+
$('copy-cmd').addEventListener('click', () => copyText(state.demoCommand, t().curlCopied));
|
|
401
|
+
$('refresh').addEventListener('click', refresh);
|
|
402
|
+
$('clear').addEventListener('click', async () => {
|
|
403
|
+
if (!confirm(t().confirmClear)) return;
|
|
404
|
+
try { await getJson(routes().events, { method: state.config.methods.delete }); } catch (e) { showToast(format(t().clearFailed, { reason: e.message })); return; }
|
|
405
|
+
state.selected = null; state.detail = null; await refresh(); renderDetail();
|
|
406
|
+
});
|
|
407
|
+
$('mock-form').addEventListener('submit', addMock);
|
|
408
|
+
$('mocks-clear').addEventListener('click', async () => {
|
|
409
|
+
if (!confirm(t().confirmRemoveRules)) return;
|
|
410
|
+
try { await getJson(routes().mocks, { method: state.config.methods.delete }); await refreshMocks(); } catch (e) { showToast(format(t().cannotRemoveRules, { reason: e.message })); }
|
|
411
|
+
});
|
|
412
|
+
document.addEventListener('keydown', onKey);
|
|
413
|
+
setupScope();
|
|
414
|
+
setupTheme();
|
|
415
|
+
// The list renders on the first poll, so requests already in memory at page load don't flash as new.
|
|
416
|
+
renderDetail(); poll();
|
|
417
|
+
setInterval(tickAges, ui().ageTickMs);
|
|
418
|
+
}
|
|
419
|
+
init();
|