portpreview 0.2.0 → 0.3.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.
@@ -0,0 +1,625 @@
1
+ /**
2
+ * Single-page inspector UI: inline CSS and JS, no framework, no external assets.
3
+ * Captured data is rendered with textContent only. The inline script avoids backticks and
4
+ * dollar-brace sequences so it can live inside this template literal (String.raw keeps its
5
+ * backslash escapes intact).
6
+ * @param {{ nonce: string }} options
7
+ */
8
+ export function renderInspectorPage({ nonce }) {
9
+ const n = String(nonce).replace(/[^A-Za-z0-9+/=]/g, '')
10
+ return String.raw`<!doctype html>
11
+ <html lang="en">
12
+ <head>
13
+ <meta charset="utf-8">
14
+ <meta name="viewport" content="width=device-width, initial-scale=1">
15
+ <meta name="referrer" content="no-referrer">
16
+ <title>PortPreview Inspector</title>
17
+ <link rel="icon" href="data:,">
18
+ <style nonce="${n}">
19
+ :root { --bg: #f7f7f8; --panel: #fff; --line: #e3e3e8; --text: #1d1d22; --muted: #6b6b76; --accent: #3a5bd9; --ok: #1f8a4c; --warn: #b26a00; --bad: #c0362c; --chip: #eef0f6; --sel: #e8edff; --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
20
+ @media (prefers-color-scheme: dark) { :root { --bg: #141417; --panel: #1c1c21; --line: #2e2e36; --text: #e8e8ee; --muted: #9a9aa6; --accent: #7d97ff; --ok: #4cc37f; --warn: #e0a043; --bad: #ff6b5e; --chip: #2a2a33; --sel: #262d48; } }
21
+ * { box-sizing: border-box; }
22
+ html, body { height: 100%; }
23
+ body { margin: 0; font: 13px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; color: var(--text); background: var(--bg); display: flex; flex-direction: column; }
24
+ button, select, input { font: inherit; color: inherit; }
25
+ button { background: var(--panel); border: 1px solid var(--line); border-radius: 6px; padding: 4px 10px; cursor: pointer; }
26
+ button:hover:not(:disabled) { border-color: var(--accent); }
27
+ button:disabled { opacity: .45; cursor: not-allowed; }
28
+ button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
29
+ select, input[type=search] { background: var(--panel); border: 1px solid var(--line); border-radius: 6px; padding: 4px 8px; }
30
+ header.top { display: flex; align-items: center; gap: 14px; padding: 10px 16px; background: var(--panel); border-bottom: 1px solid var(--line); flex-wrap: wrap; }
31
+ .brand { font-weight: 650; font-size: 14px; }
32
+ .brand span { color: var(--muted); font-weight: 500; }
33
+ .meta { color: var(--muted); font-family: var(--mono); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; flex: 1; }
34
+ .meta b { color: var(--text); font-weight: 500; }
35
+ .conn { font-size: 12px; color: var(--muted); }
36
+ .conn::before { content: ""; display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; background: var(--warn); vertical-align: 0; }
37
+ .conn.live::before { background: var(--ok); }
38
+ .filters { display: flex; gap: 8px; align-items: center; padding: 8px 16px; border-bottom: 1px solid var(--line); flex-wrap: wrap; }
39
+ .filters input[type=search] { width: 220px; }
40
+ .filters label { display: flex; align-items: center; gap: 5px; color: var(--muted); }
41
+ .filters .count { margin-left: auto; color: var(--muted); }
42
+ main { flex: 1; display: flex; min-height: 0; }
43
+ .list { width: 48%; min-width: 340px; overflow: auto; border-right: 1px solid var(--line); background: var(--panel); }
44
+ table { width: 100%; border-collapse: collapse; }
45
+ th { position: sticky; top: 0; background: var(--panel); text-align: left; font-weight: 600; color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: .03em; padding: 6px 8px; border-bottom: 1px solid var(--line); }
46
+ td { padding: 5px 8px; border-bottom: 1px solid var(--line); white-space: nowrap; font-family: var(--mono); font-size: 12px; }
47
+ td.path { max-width: 1px; width: 100%; overflow: hidden; text-overflow: ellipsis; }
48
+ tr.row { cursor: pointer; }
49
+ tr.row:hover td { background: var(--bg); }
50
+ tr.row.selected td { background: var(--sel); }
51
+ .s2 { color: var(--ok); } .s3 { color: var(--accent); } .s4 { color: var(--warn); } .s5, .serr { color: var(--bad); } .spend { color: var(--muted); }
52
+ .badge { display: inline-block; font-family: system-ui, sans-serif; font-size: 10px; padding: 0 5px; border-radius: 4px; background: var(--chip); color: var(--muted); margin-left: 5px; vertical-align: 1px; }
53
+ .badge.replay { color: var(--accent); }
54
+ .badge.trunc { color: var(--warn); }
55
+ .empty, .placeholder { color: var(--muted); padding: 24px 16px; margin: 0; }
56
+ .detail { flex: 1; overflow: auto; padding: 14px 18px 40px; min-width: 0; }
57
+ .d-head { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }
58
+ .d-title { font-family: var(--mono); font-size: 14px; font-weight: 600; word-break: break-all; flex: 1; min-width: 200px; }
59
+ .d-actions { display: flex; gap: 6px; flex-wrap: wrap; }
60
+ .d-meta { color: var(--muted); margin: 8px 0 4px; display: flex; flex-wrap: wrap; gap: 4px 14px; }
61
+ .d-meta a { color: var(--accent); cursor: pointer; text-decoration: underline; }
62
+ .note { margin: 8px 0; padding: 6px 10px; border-radius: 6px; background: var(--chip); color: var(--text); }
63
+ .note.bad { color: var(--bad); }
64
+ .note.warn { color: var(--warn); }
65
+ .tabs { display: flex; gap: 2px; margin: 14px 0 0; border-bottom: 1px solid var(--line); }
66
+ .tabs button, .views button { border: 0; border-radius: 0; background: none; padding: 6px 12px; color: var(--muted); border-bottom: 2px solid transparent; }
67
+ .tabs button.on, .views button.on { color: var(--text); border-bottom-color: var(--accent); }
68
+ h3 { font-size: 12px; text-transform: uppercase; letter-spacing: .03em; color: var(--muted); margin: 16px 0 6px; font-weight: 600; }
69
+ table.headers td { white-space: normal; word-break: break-all; vertical-align: top; }
70
+ table.headers td.name { width: 30%; color: var(--muted); }
71
+ .mask { font-family: var(--mono); font-size: 12px; padding: 0 6px; }
72
+ .bodybar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin: 16px 0 6px; }
73
+ .bodybar h3 { margin: 0; }
74
+ .views { display: flex; }
75
+ .bodyinfo { color: var(--muted); font-size: 12px; }
76
+ .bodybar a { color: var(--accent); font-size: 12px; }
77
+ pre { margin: 0; padding: 10px 12px; background: var(--panel); border: 1px solid var(--line); border-radius: 6px; font: 12px/1.5 var(--mono); white-space: pre-wrap; word-break: break-all; max-height: 60vh; overflow: auto; }
78
+ pre.hex { white-space: pre; word-break: normal; }
79
+ footer { padding: 6px 16px; border-top: 1px solid var(--line); color: var(--muted); font-size: 11.5px; background: var(--panel); display: flex; gap: 12px; flex-wrap: wrap; }
80
+ footer .stats { margin-left: auto; }
81
+ .toast { position: fixed; right: 16px; bottom: 40px; max-width: 420px; background: var(--text); color: var(--bg); padding: 8px 12px; border-radius: 8px; box-shadow: 0 4px 18px rgba(0,0,0,.2); }
82
+ .copybox { margin-top: 10px; }
83
+ .copybox textarea { width: 100%; min-height: 120px; font: 12px var(--mono); background: var(--panel); color: var(--text); border: 1px solid var(--line); border-radius: 6px; padding: 8px; }
84
+ [hidden] { display: none !important; }
85
+ @media (max-width: 860px) { main { flex-direction: column; } .list { width: auto; min-width: 0; max-height: 45vh; border-right: 0; border-bottom: 1px solid var(--line); } }
86
+ </style>
87
+ </head>
88
+ <body>
89
+ <header class="top">
90
+ <div class="brand">PortPreview <span>Inspector</span></div>
91
+ <div class="meta" id="meta">Loading…</div>
92
+ <div class="conn" id="conn">Connecting…</div>
93
+ <button id="clear" type="button" title="Remove every captured request from memory">Clear</button>
94
+ </header>
95
+ <div class="filters">
96
+ <select id="f-method" aria-label="Method">
97
+ <option value="">All methods</option><option>GET</option><option>POST</option><option>PUT</option><option>PATCH</option><option>DELETE</option><option>HEAD</option><option>OPTIONS</option><option value="WS">WebSocket</option>
98
+ </select>
99
+ <select id="f-status" aria-label="Status">
100
+ <option value="">All statuses</option><option value="2">2xx</option><option value="3">3xx</option><option value="4">4xx</option><option value="5">5xx</option><option value="err">Errors</option><option value="pending">In flight</option>
101
+ </select>
102
+ <input id="f-path" type="search" placeholder="Filter by path" aria-label="Path contains">
103
+ <label><input id="f-static" type="checkbox"> Hide static assets</label>
104
+ <span class="count" id="count"></span>
105
+ </div>
106
+ <main>
107
+ <section class="list">
108
+ <table><thead><tr><th>Time</th><th>Method</th><th>Path</th><th>Status</th><th>Duration</th><th>Size</th></tr></thead><tbody id="rows"></tbody></table>
109
+ <p class="empty" id="empty">No requests yet. Requests that reach this CLI through the tunnel appear here as they arrive.</p>
110
+ </section>
111
+ <section class="detail" id="detail"><p class="placeholder">Select a request to see its headers and body.</p></section>
112
+ </main>
113
+ <footer>
114
+ <span>Only requests that reached this CLI are listed. Requests the gateway rejected (body too large, preview password, IP allowlist, tunnel offline) never arrive here.</span>
115
+ <span>Captured data stays in this process's memory and is gone when the CLI exits.</span>
116
+ <span class="stats" id="stats"></span>
117
+ </footer>
118
+ <div class="toast" id="toast" hidden></div>
119
+ <script nonce="${n}">
120
+ (function () {
121
+ 'use strict';
122
+ var MUTATE = { 'X-PortPreview-Inspector': '1', 'Content-Type': 'application/json' };
123
+ var SECRET = { 'authorization': 1, 'proxy-authorization': 1, 'cookie': 1, 'set-cookie': 1, 'x-api-key': 1 };
124
+ var CURL_OMIT = { 'host': 1, 'content-length': 1, 'connection': 1, 'keep-alive': 1, 'proxy-authenticate': 1, 'proxy-authorization': 1, 'te': 1, 'trailer': 1, 'transfer-encoding': 1, 'upgrade': 1, 'accept-encoding': 1 };
125
+ var STATIC_EXT = /\.(?:m?js|css|map|png|jpe?g|gif|svg|ico|webp|avif|bmp|woff2?|ttf|otf|eot|mp4|webm|mp3|wav|wasm)$/i;
126
+ var STATIC_PREFIX = /^\/(?:_next\/static\/|_next\/image|@vite\/|@fs\/|@id\/|@react-refresh|node_modules\/|__vite_ping|assets\/|static\/|favicon)/i;
127
+ var HEX_LIMIT = 4096;
128
+
129
+ var entries = new Map();
130
+ var selected = null;
131
+ var detail = null;
132
+ var tab = 'request';
133
+ var view = 'pretty';
134
+ var status = null;
135
+ var revealed = new Set();
136
+ var renderQueued = false;
137
+ var detailTimer = null;
138
+ var detailLoading = false;
139
+ var detailDirty = false;
140
+
141
+ function $(id) { return document.getElementById(id); }
142
+ function el(tag, cls, text) {
143
+ var node = document.createElement(tag);
144
+ if (cls) node.className = cls;
145
+ if (text !== undefined && text !== null) node.textContent = String(text);
146
+ return node;
147
+ }
148
+ function clear(node) { while (node.firstChild) node.removeChild(node.firstChild); }
149
+ function api(path, options) {
150
+ return fetch(path, options).then(function (response) {
151
+ return response.json().catch(function () { return {}; }).then(function (body) {
152
+ if (!response.ok) throw new Error((body && body.error) || ('HTTP ' + response.status));
153
+ return body;
154
+ });
155
+ });
156
+ }
157
+ function toast(text, ms) {
158
+ var node = $('toast');
159
+ node.textContent = text;
160
+ node.hidden = false;
161
+ clearTimeout(toast.timer);
162
+ toast.timer = setTimeout(function () { node.hidden = true; }, ms || 3500);
163
+ }
164
+ function fmtBytes(n) {
165
+ if (n === null || n === undefined) return '';
166
+ if (n < 1024) return n + ' B';
167
+ if (n < 1048576) return (n / 1024).toFixed(n < 10240 ? 1 : 0) + ' KB';
168
+ return (n / 1048576).toFixed(1) + ' MB';
169
+ }
170
+ function pad(value, width) { value = String(value); while (value.length < width) value = '0' + value; return value; }
171
+ function fmtTime(ms) {
172
+ var d = new Date(ms);
173
+ return pad(d.getHours(), 2) + ':' + pad(d.getMinutes(), 2) + ':' + pad(d.getSeconds(), 2) + '.' + pad(d.getMilliseconds(), 3);
174
+ }
175
+ function fmtDuration(entry) {
176
+ if (!entry.done) return '…';
177
+ var ms = entry.durationMs;
178
+ return ms < 1000 ? ms + ' ms' : (ms / 1000).toFixed(ms < 10000 ? 2 : 1) + ' s';
179
+ }
180
+ function statusText(entry) {
181
+ if (entry.status) return String(entry.status);
182
+ if (entry.error) return 'ERR';
183
+ return '…';
184
+ }
185
+ function statusClass(entry) {
186
+ if (entry.status) return 's' + String(entry.status).charAt(0);
187
+ return entry.error ? 'serr' : 'spend';
188
+ }
189
+ function bytesFrom64(b64) {
190
+ var bin = atob(b64 || '');
191
+ var out = new Uint8Array(bin.length);
192
+ for (var i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
193
+ return out;
194
+ }
195
+ function utf8(bytes, fatal) {
196
+ try { return new TextDecoder('utf-8', { fatal: !!fatal }).decode(bytes); } catch (e) { return null; }
197
+ }
198
+ function looksBinary(text) { return /[\u0000-\u0008\u000e-\u001f]/.test(text); }
199
+
200
+ // ---------- list ----------
201
+ function matches(entry) {
202
+ var method = $('f-method').value;
203
+ if (method === 'WS' ? entry.kind !== 'websocket' : (method && (entry.method !== method || entry.kind === 'websocket'))) return false;
204
+ var cls = $('f-status').value;
205
+ if (cls === 'err' && !(entry.error || entry.status >= 500)) return false;
206
+ if (cls === 'pending' && entry.done) return false;
207
+ if (/^[2-5]$/.test(cls) && String(entry.status || '').charAt(0) !== cls) return false;
208
+ var needle = $('f-path').value.trim().toLowerCase();
209
+ if (needle && entry.path.toLowerCase().indexOf(needle) === -1) return false;
210
+ if ($('f-static').checked) {
211
+ var path = entry.path.split('?')[0];
212
+ if (STATIC_EXT.test(path) || STATIC_PREFIX.test(path)) return false;
213
+ }
214
+ return true;
215
+ }
216
+ function queueRender() {
217
+ if (renderQueued) return;
218
+ renderQueued = true;
219
+ requestAnimationFrame(function () { renderQueued = false; renderList(); });
220
+ }
221
+ function renderList() {
222
+ var rows = $('rows');
223
+ var fragment = document.createDocumentFragment();
224
+ var ids = Array.from(entries.keys()).sort(function (a, b) { return b - a; });
225
+ var shown = 0;
226
+ ids.forEach(function (id) {
227
+ var entry = entries.get(id);
228
+ if (!matches(entry)) return;
229
+ shown++;
230
+ var tr = el('tr', 'row' + (id === selected ? ' selected' : ''));
231
+ tr.dataset.id = String(id);
232
+ tr.appendChild(el('td', '', fmtTime(entry.startedAt)));
233
+ tr.appendChild(el('td', '', entry.kind === 'websocket' ? 'WS' : entry.method));
234
+ var path = el('td', 'path', entry.path);
235
+ path.title = entry.path;
236
+ if (entry.source === 'replay') path.appendChild(el('span', 'badge replay', 'replay'));
237
+ if (entry.request.truncated || entry.response.truncated) path.appendChild(el('span', 'badge trunc', 'truncated'));
238
+ tr.appendChild(path);
239
+ tr.appendChild(el('td', statusClass(entry), statusText(entry)));
240
+ tr.appendChild(el('td', '', fmtDuration(entry)));
241
+ tr.appendChild(el('td', '', entry.kind === 'websocket'
242
+ ? (entry.websocket.framesIn + entry.websocket.framesOut) + ' frames'
243
+ : fmtBytes(entry.response.bytes)));
244
+ fragment.appendChild(tr);
245
+ });
246
+ clear(rows);
247
+ rows.appendChild(fragment);
248
+ $('empty').hidden = entries.size > 0;
249
+ $('count').textContent = shown === entries.size ? entries.size + ' requests' : shown + ' of ' + entries.size + ' requests';
250
+ }
251
+ $('rows').addEventListener('click', function (event) {
252
+ var tr = event.target.closest('tr.row');
253
+ if (tr) select(Number(tr.dataset.id));
254
+ });
255
+ ['f-method', 'f-status', 'f-static'].forEach(function (id) { $(id).addEventListener('change', queueRender); });
256
+ $('f-path').addEventListener('input', queueRender);
257
+
258
+ // ---------- detail ----------
259
+ function select(id) {
260
+ if (selected !== id) { selected = id; detail = null; revealed.clear(); }
261
+ queueRender();
262
+ loadDetail();
263
+ }
264
+ function loadDetail() {
265
+ if (selected === null) return;
266
+ if (detailLoading) { detailDirty = true; return; }
267
+ detailLoading = true;
268
+ var id = selected;
269
+ api('/api/requests/' + id).then(function (body) {
270
+ if (id === selected) { detail = body; renderDetail(); }
271
+ }).catch(function (error) {
272
+ if (id === selected) { detail = null; renderMissing(error.message); }
273
+ }).then(function () {
274
+ detailLoading = false;
275
+ if (detailDirty) { detailDirty = false; scheduleDetail(); }
276
+ });
277
+ }
278
+ function scheduleDetail() {
279
+ if (detailTimer) return;
280
+ detailTimer = setTimeout(function () { detailTimer = null; loadDetail(); }, 400);
281
+ }
282
+ function renderMissing(message) {
283
+ var root = $('detail');
284
+ clear(root);
285
+ root.appendChild(el('p', 'placeholder', message || 'Select a request to see its headers and body.'));
286
+ }
287
+ function link(text, id) {
288
+ var a = el('a', '', text);
289
+ a.addEventListener('click', function () { select(id); });
290
+ return a;
291
+ }
292
+ function renderDetail() {
293
+ var d = detail;
294
+ var root = $('detail');
295
+ var scroll = root.scrollTop;
296
+ clear(root);
297
+ var head = el('div', 'd-head');
298
+ var title = el('div', 'd-title', (d.kind === 'websocket' ? 'WS' : d.method) + ' ' + d.path);
299
+ head.appendChild(title);
300
+ var actions = el('div', 'd-actions');
301
+ if (d.kind !== 'websocket') {
302
+ var replay = el('button', 'primary', 'Replay');
303
+ replay.type = 'button';
304
+ replay.disabled = !d.replayable;
305
+ replay.title = d.replayable ? 'Send this exact request to the local app again' : d.replayBlockedReason;
306
+ replay.addEventListener('click', function () { doReplay(d.id, replay); });
307
+ actions.appendChild(replay);
308
+ var curlLocal = el('button', '', 'Copy cURL (local)');
309
+ var curlPublic = el('button', '', 'Copy cURL (public URL)');
310
+ var curlBlocked = d.request.truncated || !d.request.complete;
311
+ [curlLocal, curlPublic].forEach(function (button, index) {
312
+ button.type = 'button';
313
+ button.disabled = curlBlocked || (index === 1 && !publicBase(d));
314
+ button.title = curlBlocked ? 'The request body was not fully captured' : 'The command contains captured header values, which may include secrets';
315
+ button.addEventListener('click', function () { copyCurl(d, index === 1 ? 'public' : 'local'); });
316
+ actions.appendChild(button);
317
+ });
318
+ }
319
+ head.appendChild(actions);
320
+ root.appendChild(head);
321
+
322
+ var meta = el('div', 'd-meta');
323
+ meta.appendChild(el('span', '', '#' + d.id + ' · ' + new Date(d.startedAt).toLocaleString()));
324
+ meta.appendChild(el('span', statusClass(d), 'Status ' + statusText(d)));
325
+ meta.appendChild(el('span', '', 'Duration ' + fmtDuration(d)));
326
+ if (d.protocolVersion) meta.appendChild(el('span', '', 'Protocol v' + d.protocolVersion));
327
+ if (d.replayOf !== null) {
328
+ var of = el('span', '', 'Replay of ');
329
+ of.appendChild(entries.has(d.replayOf) ? link('#' + d.replayOf, d.replayOf) : el('span', '', '#' + d.replayOf + ' (evicted)'));
330
+ meta.appendChild(of);
331
+ }
332
+ if (d.replays.length) {
333
+ var reps = el('span', '', 'Replays: ');
334
+ d.replays.forEach(function (id, i) {
335
+ if (i) reps.appendChild(document.createTextNode(', '));
336
+ reps.appendChild(entries.has(id) ? link('#' + id, id) : el('span', '', '#' + id));
337
+ });
338
+ meta.appendChild(reps);
339
+ }
340
+ root.appendChild(meta);
341
+ if (d.error) root.appendChild(el('div', 'note bad', 'Error: ' + d.error));
342
+ if (d.synthetic) root.appendChild(el('div', 'note warn', 'The CLI generated this 502 because the local app could not be reached.'));
343
+
344
+ if (d.kind === 'websocket') { renderWebSocket(root, d); root.scrollTop = scroll; return; }
345
+
346
+ var tabs = el('div', 'tabs');
347
+ ['request', 'response'].forEach(function (name) {
348
+ var button = el('button', tab === name ? 'on' : '', name === 'request' ? 'Request' : 'Response');
349
+ button.type = 'button';
350
+ button.addEventListener('click', function () { tab = name; renderDetail(); });
351
+ tabs.appendChild(button);
352
+ });
353
+ root.appendChild(tabs);
354
+ var side = d[tab];
355
+ if (tab === 'response' && !d.status) {
356
+ root.appendChild(el('p', 'placeholder', d.done ? 'No response was received.' : 'Waiting for the response…'));
357
+ } else {
358
+ root.appendChild(el('h3', '', tab === 'request' ? 'Headers sent to the local app' : 'Headers from the local app'));
359
+ root.appendChild(headerTable(side.headers, tab));
360
+ renderBody(root, d, side, tab);
361
+ }
362
+ root.scrollTop = scroll;
363
+ }
364
+ function headerTable(pairs, sideName) {
365
+ var table = el('table', 'headers');
366
+ var body = el('tbody');
367
+ if (!pairs.length) {
368
+ var tr0 = el('tr');
369
+ tr0.appendChild(el('td', 'name', '(none)'));
370
+ body.appendChild(tr0);
371
+ }
372
+ pairs.forEach(function (pair, index) {
373
+ var tr = el('tr');
374
+ tr.appendChild(el('td', 'name', pair[0]));
375
+ var value = el('td');
376
+ var key = detail.id + ':' + sideName + ':' + index;
377
+ if (SECRET[pair[0].toLowerCase()] && !revealed.has(key)) {
378
+ var mask = el('button', 'mask', '•••••••• click to reveal');
379
+ mask.type = 'button';
380
+ mask.title = 'Hidden on screen; stored unmodified for replay';
381
+ mask.addEventListener('click', function () { revealed.add(key); clear(value); value.textContent = pair[1]; });
382
+ value.appendChild(mask);
383
+ } else value.textContent = pair[1];
384
+ tr.appendChild(value);
385
+ body.appendChild(tr);
386
+ });
387
+ table.appendChild(body);
388
+ return table;
389
+ }
390
+ function renderBody(root, d, side, sideName) {
391
+ var bar = el('div', 'bodybar');
392
+ bar.appendChild(el('h3', '', 'Body'));
393
+ var views = el('div', 'views');
394
+ ['pretty', 'raw', 'hex'].forEach(function (name) {
395
+ var button = el('button', view === name ? 'on' : '', name === 'pretty' ? 'Pretty' : name === 'raw' ? 'Raw' : 'Hex');
396
+ button.type = 'button';
397
+ button.addEventListener('click', function () { view = name; renderDetail(); });
398
+ views.appendChild(button);
399
+ });
400
+ bar.appendChild(views);
401
+ var info = fmtBytes(side.bytes);
402
+ if (side.retained !== side.bytes) info += ', ' + fmtBytes(side.retained) + ' captured';
403
+ bar.appendChild(el('span', 'bodyinfo', info));
404
+ if (side.retained) {
405
+ var download = el('a', '', 'Download');
406
+ download.href = '/api/requests/' + d.id + '/body/' + sideName;
407
+ download.setAttribute('download', 'request-' + d.id + '-' + sideName + '.bin');
408
+ bar.appendChild(download);
409
+ }
410
+ root.appendChild(bar);
411
+ if (side.truncated === 'limit') root.appendChild(el('div', 'note warn', 'Only the first ' + fmtBytes(side.retained) + ' of this body were captured (per-body limit). The app and the visitor still received all of it.'));
412
+ else if (side.truncated === 'budget') root.appendChild(el('div', 'note warn', 'Capture stopped early because the inspector memory budget was full. The app and the visitor still received all of it.'));
413
+ else if (side.truncated === 'tunnel') root.appendChild(el('div', 'note warn', 'The legacy v2 tunnel truncated this response to 1 MiB for the visitor.'));
414
+ if (!side.complete && d.done && side.bytes) root.appendChild(el('div', 'note warn', 'This body did not finish (the transfer was cancelled or failed).'));
415
+ if (!side.complete && !d.done && sideName === 'response' && d.status) root.appendChild(el('div', 'note', 'Still streaming…'));
416
+
417
+ if (!side.retained) { root.appendChild(el('pre', '', side.bytes ? '(not captured)' : '(empty body)')); return; }
418
+ var raw = bytesFrom64(side.base64);
419
+ var shownBytes = raw;
420
+ if (side.decodedBase64 && view !== 'hex') {
421
+ shownBytes = bytesFrom64(side.decodedBase64);
422
+ root.appendChild(el('div', 'note', 'Decoded from Content-Encoding: ' + side.contentEncoding + (side.decodedPartial ? ' (partial body)' : '') + '. Hex and Download show the raw bytes.'));
423
+ } else if (side.decodeError && view !== 'hex') root.appendChild(el('div', 'note warn', side.decodeError));
424
+ if (view === 'hex') { root.appendChild(el('pre', 'hex', hexDump(raw))); return; }
425
+ if (view === 'raw') {
426
+ var text = utf8(shownBytes, false);
427
+ root.appendChild(el('pre', '', text));
428
+ return;
429
+ }
430
+ root.appendChild(el('pre', '', pretty(shownBytes, side.contentType || '')));
431
+ }
432
+ function pretty(bytes, contentType) {
433
+ var text = utf8(bytes, true);
434
+ if (text === null || looksBinary(text)) return 'Binary body (' + fmtBytes(bytes.length) + '). Use Hex or Download.';
435
+ var trimmed = text.trim();
436
+ if (/json/i.test(contentType) || /^[\[{]/.test(trimmed)) {
437
+ try { return JSON.stringify(JSON.parse(trimmed), null, 2); } catch (e) { }
438
+ }
439
+ if (/x-www-form-urlencoded/i.test(contentType)) {
440
+ try {
441
+ return trimmed.split('&').filter(Boolean).map(function (part) {
442
+ var eq = part.indexOf('=');
443
+ var key = eq === -1 ? part : part.slice(0, eq);
444
+ var value = eq === -1 ? '' : part.slice(eq + 1);
445
+ return decodeURIComponent(key.replace(/\+/g, ' ')) + ' = ' + decodeURIComponent(value.replace(/\+/g, ' '));
446
+ }).join('\n');
447
+ } catch (e) { }
448
+ }
449
+ return text;
450
+ }
451
+ function hexDump(bytes) {
452
+ var lines = [];
453
+ var n = Math.min(bytes.length, HEX_LIMIT);
454
+ for (var i = 0; i < n; i += 16) {
455
+ var hex = [];
456
+ var ascii = '';
457
+ for (var j = i; j < i + 16; j++) {
458
+ if (j < n) {
459
+ var b = bytes[j];
460
+ hex.push((b < 16 ? '0' : '') + b.toString(16));
461
+ ascii += b >= 32 && b < 127 ? String.fromCharCode(b) : '.';
462
+ } else hex.push(' ');
463
+ }
464
+ lines.push(pad(i.toString(16), 8) + ' ' + hex.slice(0, 8).join(' ') + ' ' + hex.slice(8).join(' ') + ' |' + ascii + '|');
465
+ }
466
+ if (bytes.length > HEX_LIMIT) lines.push('… first 4 KiB of ' + bytes.length + ' bytes shown. Use Download for the rest.');
467
+ return lines.join('\n');
468
+ }
469
+ function renderWebSocket(root, d) {
470
+ var ws = d.websocket;
471
+ root.appendChild(el('h3', '', 'WebSocket'));
472
+ var rows = [
473
+ ['Frames visitor → app', ws.framesIn + ' (' + fmtBytes(ws.bytesIn) + ')'],
474
+ ['Frames app → visitor', ws.framesOut + ' (' + fmtBytes(ws.bytesOut) + ')'],
475
+ ['State', d.done ? 'closed' : (d.status === 101 ? 'open' : 'connecting')],
476
+ ];
477
+ if (ws.closeCode !== null) rows.push(['Close code', String(ws.closeCode) + (ws.closeReason ? ' ' + ws.closeReason : '')]);
478
+ root.appendChild(headerTableStatic(rows));
479
+ root.appendChild(el('div', 'note', 'Frame contents are not recorded yet. WebSocket connections cannot be replayed.'));
480
+ root.appendChild(el('h3', '', 'Handshake headers sent to the local app'));
481
+ root.appendChild(headerTable(d.request.headers, 'request'));
482
+ if (d.response.headers.length) {
483
+ root.appendChild(el('h3', '', 'Handshake response headers'));
484
+ root.appendChild(headerTable(d.response.headers, 'response'));
485
+ }
486
+ }
487
+ function headerTableStatic(rows) {
488
+ var table = el('table', 'headers');
489
+ var body = el('tbody');
490
+ rows.forEach(function (row) {
491
+ var tr = el('tr');
492
+ tr.appendChild(el('td', 'name', row[0]));
493
+ tr.appendChild(el('td', '', row[1]));
494
+ body.appendChild(tr);
495
+ });
496
+ table.appendChild(body);
497
+ return table;
498
+ }
499
+
500
+ // ---------- actions ----------
501
+ function doReplay(id, button) {
502
+ button.disabled = true;
503
+ api('/api/requests/' + id + '/replay', { method: 'POST', headers: MUTATE, body: '{}' }).then(function (body) {
504
+ toast('Replayed as #' + body.id);
505
+ if (body.id) select(body.id);
506
+ }).catch(function (error) {
507
+ toast('Replay failed: ' + error.message, 5000);
508
+ button.disabled = false;
509
+ });
510
+ }
511
+ function shellQuote(value) { return "'" + String(value).replace(/'/g, "'\\''") + "'"; }
512
+ function publicBase(d) {
513
+ var url = (status && status.publicUrl) || d.publicUrl;
514
+ return url ? String(url).replace(/\/+$/, '') : '';
515
+ }
516
+ function localBase() { return status && status.target ? status.target : ''; }
517
+ function curlCommand(d, where) {
518
+ var omit = Object.assign({}, CURL_OMIT);
519
+ d.request.headers.forEach(function (pair) {
520
+ if (pair[0].toLowerCase() === 'connection') pair[1].split(',').forEach(function (name) { omit[name.trim().toLowerCase()] = 1; });
521
+ });
522
+ var args = ['curl --globoff --path-as-is', '--request ' + shellQuote(d.method)];
523
+ d.request.headers.forEach(function (pair) {
524
+ if (!omit[pair[0].toLowerCase()]) args.push('--header ' + shellQuote(pair[0] + ': ' + pair[1]));
525
+ });
526
+ args.push('--url ' + shellQuote((where === 'public' ? publicBase(d) : localBase()) + d.path));
527
+ if (d.request.retained) {
528
+ args.push('--data-binary @-');
529
+ return 'printf ' + shellQuote('%s') + ' ' + shellQuote(d.request.base64) + ' | base64 -d | ' + args.join(' \\\n ');
530
+ }
531
+ return args.join(' \\\n ');
532
+ }
533
+ function copyCurl(d, where) {
534
+ var command = curlCommand(d, where);
535
+ var warning = 'Copied. The command contains captured header values (for example Authorization or Cookie); treat it as a secret.';
536
+ var fallback = function () {
537
+ var root = $('detail');
538
+ var box = el('div', 'copybox');
539
+ box.appendChild(el('div', 'note warn', 'Clipboard access is unavailable. Copy the command below; it may contain secrets.'));
540
+ var area = el('textarea');
541
+ area.value = command;
542
+ area.readOnly = true;
543
+ box.appendChild(area);
544
+ root.appendChild(box);
545
+ area.focus();
546
+ area.select();
547
+ };
548
+ if (navigator.clipboard && navigator.clipboard.writeText) {
549
+ navigator.clipboard.writeText(command).then(function () { toast(warning, 5000); }, fallback);
550
+ } else fallback();
551
+ }
552
+ $('clear').addEventListener('click', function () {
553
+ api('/api/requests', { method: 'DELETE', headers: MUTATE, body: '{}' }).catch(function (error) { toast('Clear failed: ' + error.message); });
554
+ });
555
+
556
+ // ---------- data ----------
557
+ function loadStatus() {
558
+ return api('/api/status').then(function (body) {
559
+ status = body;
560
+ var meta = $('meta');
561
+ clear(meta);
562
+ meta.appendChild(el('b', '', body.publicUrl || 'Tunnel not connected'));
563
+ meta.appendChild(document.createTextNode(' → ' + body.target));
564
+ var stats = body.inspector || {};
565
+ $('stats').textContent = (stats.entries || 0) + ' / ' + stats.maxEntries + ' entries · ' + fmtBytes(stats.bytes || 0) + ' of ' + fmtBytes(stats.maxBytes) + ' memory';
566
+ }).catch(function () { });
567
+ }
568
+ function loadAll() {
569
+ return api('/api/requests').then(function (body) {
570
+ entries.clear();
571
+ body.entries.forEach(function (entry) { entries.set(entry.id, entry); });
572
+ if (selected !== null && !entries.has(selected)) { selected = null; detail = null; renderMissing(); }
573
+ queueRender();
574
+ if (selected !== null) loadDetail();
575
+ }).catch(function () { });
576
+ }
577
+ function scheduleStatus() {
578
+ if (scheduleStatus.timer) return;
579
+ scheduleStatus.timer = setTimeout(function () { scheduleStatus.timer = null; loadStatus(); }, 1000);
580
+ }
581
+ function upsert(entry) {
582
+ var isNew = !entries.has(entry.id);
583
+ entries.set(entry.id, entry);
584
+ if (isNew || entry.done) scheduleStatus();
585
+ queueRender();
586
+ if (entry.id === selected) scheduleDetail();
587
+ if (detail && detail.replays && detail.replays.indexOf(entry.id) !== -1 && entry.id !== selected) scheduleDetail();
588
+ }
589
+ function connect() {
590
+ var source = new EventSource('/api/events');
591
+ source.addEventListener('open', function () {
592
+ $('conn').textContent = 'Live';
593
+ $('conn').className = 'conn live';
594
+ loadAll();
595
+ loadStatus();
596
+ });
597
+ source.addEventListener('error', function () {
598
+ $('conn').textContent = 'Reconnecting…';
599
+ $('conn').className = 'conn';
600
+ });
601
+ source.addEventListener('created', function (event) { upsert(JSON.parse(event.data)); });
602
+ source.addEventListener('updated', function (event) { upsert(JSON.parse(event.data)); });
603
+ source.addEventListener('evicted', function (event) {
604
+ JSON.parse(event.data).ids.forEach(function (id) { entries.delete(id); });
605
+ scheduleStatus();
606
+ if (selected !== null && !entries.has(selected)) { selected = null; detail = null; renderMissing('That request was evicted to stay within the memory limit.'); }
607
+ queueRender();
608
+ });
609
+ source.addEventListener('cleared', function () {
610
+ entries.clear();
611
+ selected = null;
612
+ detail = null;
613
+ renderMissing();
614
+ queueRender();
615
+ loadStatus();
616
+ });
617
+ }
618
+ setInterval(loadStatus, 10000);
619
+ connect();
620
+ })();
621
+ </script>
622
+ </body>
623
+ </html>
624
+ `
625
+ }