deictic 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.
- package/API.md +303 -0
- package/README.md +56 -127
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +117 -7
- package/dist/client/index.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/logs/client.d.ts +4 -0
- package/dist/logs/client.d.ts.map +1 -0
- package/dist/logs/client.js +16 -0
- package/dist/logs/client.js.map +1 -0
- package/dist/logs/index.d.ts +18 -0
- package/dist/logs/index.d.ts.map +1 -0
- package/dist/logs/index.js +21 -0
- package/dist/logs/index.js.map +1 -0
- package/dist/network/client.d.ts +4 -0
- package/dist/network/client.d.ts.map +1 -0
- package/dist/network/client.js +29 -0
- package/dist/network/client.js.map +1 -0
- package/dist/network/index.d.ts +2 -0
- package/dist/network/index.js +39 -0
- package/dist/network/index.js.map +1 -0
- package/dist/recommended/index.d.ts +13 -3
- package/dist/recommended/index.d.ts.map +1 -1
- package/dist/recommended/index.js +8 -1
- package/dist/recommended/index.js.map +1 -1
- package/dist/recordings/client.d.ts +1 -1
- package/dist/recordings/client.d.ts.map +1 -1
- package/dist/recordings/client.js +175 -46
- package/dist/recordings/client.js.map +1 -1
- package/dist/recordings/index.d.ts +2 -2
- package/dist/screenshots/client.d.ts +6 -0
- package/dist/screenshots/client.d.ts.map +1 -1
- package/dist/screenshots/client.js +34 -2
- package/dist/screenshots/client.js.map +1 -1
- package/dist/screenshots/dom.d.ts.map +1 -1
- package/dist/screenshots/dom.js +1 -28
- package/dist/screenshots/dom.js.map +1 -1
- package/dist/screenshots/index.js.map +1 -1
- package/dist/screenshots/rrweb.d.ts +1 -1
- package/dist/screenshots/rrweb.js +5 -1
- package/dist/screenshots/rrweb.js.map +1 -1
- package/dist/shared/index.d.ts +14 -2
- package/dist/shared/index.d.ts.map +1 -1
- package/dist/shared/index2.d.ts +2 -0
- package/dist/shared/index2.d.ts.map +1 -1
- package/dist/shared/index3.d.ts +29 -3
- package/dist/shared/index3.d.ts.map +1 -1
- package/dist/shared/index4.d.ts +52 -172
- package/dist/shared/index4.d.ts.map +1 -1
- package/dist/shared/index5.d.ts +208 -58
- package/dist/shared/index5.d.ts.map +1 -1
- package/dist/shared/index6.d.ts +70 -0
- package/dist/shared/index6.d.ts.map +1 -0
- package/dist/shared/marks.js +6 -1
- package/dist/shared/marks.js.map +1 -1
- package/dist/shared/mask.js +107 -0
- package/dist/shared/mask.js.map +1 -0
- package/dist/shared/playwright.js +19 -4
- package/dist/shared/playwright.js.map +1 -1
- package/dist/shared/recordings.js +219 -28
- package/dist/shared/recordings.js.map +1 -1
- package/dist/shared/tasks.js +145 -34
- package/dist/shared/tasks.js.map +1 -1
- package/dist/tailwind/client.d.ts +1 -1
- package/dist/tailwind/index.d.ts +1 -1
- package/dist/tasks/client.d.ts +1 -1
- package/dist/tasks/client.d.ts.map +1 -1
- package/dist/tasks/client.js +271 -56
- package/dist/tasks/client.js.map +1 -1
- package/dist/tasks/index.d.ts +2 -2
- package/dist/voice/client.d.ts.map +1 -1
- package/dist/voice/client.js +35 -14
- package/dist/voice/client.js.map +1 -1
- package/dist/voice/index.d.ts +6 -1
- package/dist/voice/index.d.ts.map +1 -1
- package/dist/voice/index.js +12 -2
- package/dist/voice/index.js.map +1 -1
- package/package.json +41 -2
- package/skills/deictic/SKILL.md +20 -14
- package/skills/deictic/references/install.md +18 -11
- package/skills/deictic/references/recordings.md +29 -0
- package/skills/deictic/references/tasks.md +49 -21
- package/skills/deictic/references/watch.md +38 -11
- package/skills/deictic/scripts/lib.mjs +69 -3
- package/skills/deictic/scripts/recording.mjs +84 -4
- package/skills/deictic/scripts/task.mjs +36 -7
- package/skills/deictic/scripts/vb.mjs +12 -0
- package/skills/deictic/scripts/watch.mjs +74 -10
- package/src/client/away.ts +105 -0
- package/src/client/index.ts +40 -9
- package/src/client/style.ts +1 -0
- package/src/index.ts +14 -2
- package/src/plugins/logs/client.ts +18 -0
- package/src/plugins/logs/index.ts +55 -0
- package/src/plugins/network/client.ts +30 -0
- package/src/plugins/network/index.ts +69 -0
- package/src/plugins/network/mask.ts +133 -0
- package/src/plugins/recommended/index.ts +14 -1
- package/src/plugins/recordings/client.ts +219 -40
- package/src/plugins/recordings/index.ts +108 -23
- package/src/plugins/recordings/marks.ts +6 -0
- package/src/plugins/recordings/replay.ts +127 -4
- package/src/plugins/screenshots/client.ts +35 -0
- package/src/plugins/screenshots/dom.ts +1 -32
- package/src/plugins/screenshots/index.ts +2 -0
- package/src/plugins/screenshots/playwright.ts +15 -4
- package/src/plugins/screenshots/rrweb.ts +2 -1
- package/src/plugins/tasks/client.ts +273 -41
- package/src/plugins/tasks/index.ts +155 -39
- package/src/plugins/tasks/watchers.ts +36 -0
- package/src/plugins/voice/client.ts +33 -11
- package/src/plugins/voice/index.ts +21 -4
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import { dirname, join, resolve } from "node:path";
|
|
4
4
|
import { definePlugin } from "../index.js";
|
|
@@ -17,6 +17,11 @@ import { n as MARKS } from "./marks.js";
|
|
|
17
17
|
* which the replayer rebuilds. Each is a marker on the timeline.
|
|
18
18
|
* - The voice clips play in step, at the player's speed. A recording with voice starts paused, as a browser
|
|
19
19
|
* plays sound only after a click.
|
|
20
|
+
* - What the page logged and asked for (rrweb's console and network plugins' events, which its player doesn't
|
|
21
|
+
* show) is a list beside the replay, where the window has the room: the row the replay is at is lit, a click on
|
|
22
|
+
* one goes to its moment and shows the rest of it, and each error and failed request is a mark on the timeline.
|
|
23
|
+
* - A recorded canvas is replayed (`UNSAFE_replayCanvas`, which lets the replay's frame run rrweb's own script
|
|
24
|
+
* to draw it), for a recording that has one.
|
|
20
25
|
*
|
|
21
26
|
* `?t=<seconds>` opens it paused there, and `&bare` without the controls at the recorded size, 1:1, for a
|
|
22
27
|
* screenshot; `?embed` is it filling a frame, with no header of its own (the lightbox's); `body[data-ready]` says
|
|
@@ -38,11 +43,35 @@ const replayPage = ({ player = "..", source } = {}) => `<!doctype html>
|
|
|
38
43
|
body { margin: 0; min-height: 100vh; display: flex; flex-direction: column; background: #18181b; color: #fafafa; font: 13px/1.4 system-ui, sans-serif; }
|
|
39
44
|
header { display: flex; gap: 10px; align-items: center; padding: 10px 16px; border-bottom: 1px solid #3f3f46; }
|
|
40
45
|
header a { color: #a1a1aa; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
41
|
-
|
|
46
|
+
#stage { flex: 1; display: flex; min-height: 0; }
|
|
47
|
+
main { flex: 1; min-width: 0; display: flex; justify-content: center; align-items: flex-start; padding: 16px; }
|
|
42
48
|
body.bare header { display: none; }
|
|
43
49
|
body.bare main { padding: 0; }
|
|
44
50
|
body.embed header { display: none; }
|
|
45
51
|
body.embed main { padding: 0; }
|
|
52
|
+
/* What the page logged and asked for, beside the replay: the window's height, its list scrolling in it. */
|
|
53
|
+
#log { display: none; flex: none; width: 340px; flex-direction: column; border-left: 1px solid #3f3f46; background: #1f1f23; }
|
|
54
|
+
body.logged { height: 100vh; }
|
|
55
|
+
body.logged #log { display: flex; }
|
|
56
|
+
@media (max-width: 899px) { body.logged #log { display: none; } }
|
|
57
|
+
#log .filters { display: flex; gap: 6px; padding: 8px; border-bottom: 1px solid #3f3f46; }
|
|
58
|
+
#log .filters button { padding: 3px 8px; border: 1px solid #3f3f46; border-radius: 6px; background: none; color: #a1a1aa; font: inherit; font-size: 12px; cursor: pointer; }
|
|
59
|
+
#log .filters button[aria-pressed='true'] { color: #fafafa; background: #3f3f46; }
|
|
60
|
+
#log ol { flex: 1; min-height: 0; overflow: auto; margin: 0; padding: 0; list-style: none; font: 12px/1.45 ui-monospace, monospace; }
|
|
61
|
+
#log li { border-bottom: 1px solid #2e2e33; border-left: 2px solid transparent; }
|
|
62
|
+
#log li.ahead { opacity: 0.45; }
|
|
63
|
+
#log li.now { border-left-color: var(--accent); background: #27272a; }
|
|
64
|
+
#log li.warn .label { color: #fbbf24; }
|
|
65
|
+
#log li.bad .label, #log li.bad .text { color: #f87171; }
|
|
66
|
+
#log li > button { display: flex; gap: 8px; align-items: baseline; width: 100%; padding: 5px 8px; border: 0; background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; }
|
|
67
|
+
#log li > button:hover { background: #2e2e33; }
|
|
68
|
+
#log time { flex: none; color: #71717a; }
|
|
69
|
+
#log .label { flex: none; min-width: 4ch; color: #a1a1aa; }
|
|
70
|
+
#log .text { min-width: 0; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow-wrap: anywhere; }
|
|
71
|
+
#log li.open .text { display: block; white-space: pre-wrap; }
|
|
72
|
+
#log pre { margin: 0; padding: 2px 8px 8px calc(8px + 6ch + 8px); color: #a1a1aa; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
73
|
+
#log.no-console li.console, #log.no-network li.network, #log.only-bad li:not(.bad) { display: none; }
|
|
74
|
+
#main .rr-player .rr-progress .bad-mark { position: absolute; top: -3px; width: 3px; height: 10px; margin-left: -1px; border-radius: 1px; background: #f87171; pointer-events: none; }
|
|
46
75
|
body.embed #main .rr-player { box-shadow: none; border-radius: 0; }
|
|
47
76
|
#marks { position: absolute; left: 0; top: 0; pointer-events: none; z-index: 3; }
|
|
48
77
|
#marks svg { position: absolute; left: 0; top: 0; overflow: visible; }
|
|
@@ -71,7 +100,17 @@ const replayPage = ({ player = "..", source } = {}) => `<!doctype html>
|
|
|
71
100
|
<strong>Recording</strong>
|
|
72
101
|
<a id="page" target="_blank" rel="noreferrer"></a>
|
|
73
102
|
</header>
|
|
74
|
-
<
|
|
103
|
+
<div id="stage">
|
|
104
|
+
<main id="main"></main>
|
|
105
|
+
<aside id="log" aria-label="Console and network">
|
|
106
|
+
<div class="filters">
|
|
107
|
+
<button type="button" data-hides="no-console" aria-pressed="true">Console</button>
|
|
108
|
+
<button type="button" data-hides="no-network" aria-pressed="true">Network</button>
|
|
109
|
+
<button type="button" data-shows="only-bad" aria-pressed="false" title="Errors, and requests that failed">Problems</button>
|
|
110
|
+
</div>
|
|
111
|
+
<ol></ol>
|
|
112
|
+
</aside>
|
|
113
|
+
</div>
|
|
75
114
|
<script src="${player}/player.js"><\/script>${source === void 0 ? "" : `
|
|
76
115
|
<script src="${source}"><\/script>`}
|
|
77
116
|
<script>
|
|
@@ -96,6 +135,46 @@ const replayPage = ({ player = "..", source } = {}) => `<!doctype html>
|
|
|
96
135
|
page.textContent = kept.page;
|
|
97
136
|
page.href = kept.page;
|
|
98
137
|
|
|
138
|
+
// What the page logged and asked for, where the recording has it (rrweb's console and network plugins' events):
|
|
139
|
+
// a row each, in their order, beside the replay. Not in a bare one, which is the page alone.
|
|
140
|
+
const t0 = events[0].timestamp;
|
|
141
|
+
const clock = (ms) => { const s = Math.max(0, ms) / 1000; return Math.floor(s / 60) + ':' + (s % 60).toFixed(1).padStart(4, '0'); };
|
|
142
|
+
// An argument is kept as JSON: a string reads better without its quotes.
|
|
143
|
+
const plain = (arg) => { try { const v = JSON.parse(arg); return typeof v === 'string' ? v : arg; } catch { return arg; } };
|
|
144
|
+
const origin = (() => { try { return new URL(kept.page).origin; } catch { return ''; } })();
|
|
145
|
+
const fields = (title, held) => (held && Object.keys(held).length > 0 ? [title, ...Object.entries(held).map(([k, v]) => ' ' + k + ': ' + v)] : []);
|
|
146
|
+
const rows = [];
|
|
147
|
+
for (const e of events) {
|
|
148
|
+
if (e.type !== 6 || bare) continue;
|
|
149
|
+
const at = e.timestamp - t0;
|
|
150
|
+
if (e.data.plugin === 'rrweb/console@1') {
|
|
151
|
+
const { level, payload = [], trace = [] } = e.data.payload;
|
|
152
|
+
rows.push({ at, kind: 'console', label: level, bad: level === 'error' || level === 'assert', warn: level === 'warn', text: payload.map(plain).join(' '), more: trace.map((l) => 'at ' + l) });
|
|
153
|
+
}
|
|
154
|
+
if (e.data.plugin === 'rrweb/network@1') {
|
|
155
|
+
for (const r of e.data.payload.requests ?? []) {
|
|
156
|
+
// The page's own origin goes without saying.
|
|
157
|
+
let name = r.name;
|
|
158
|
+
try { const u = new URL(r.name); if (u.origin === origin) name = u.pathname + u.search + u.hash; } catch {}
|
|
159
|
+
const more = [
|
|
160
|
+
r.name,
|
|
161
|
+
[r.initiatorType, Number.isFinite(r.duration) ? Math.round(r.duration) + ' ms' : '', e.data.payload.isInitial ? 'as the page loaded' : ''].filter(Boolean).join(' · '),
|
|
162
|
+
...fields('Request headers', r.requestHeaders),
|
|
163
|
+
...(r.requestBody ? ['Request body', ' ' + r.requestBody] : []),
|
|
164
|
+
...fields('Response headers', r.responseHeaders),
|
|
165
|
+
...(r.responseBody ? ['Response body', ' ' + r.responseBody] : []),
|
|
166
|
+
];
|
|
167
|
+
// No status is one the browser won't say (another origin's), not one that failed.
|
|
168
|
+
rows.push({ at, kind: 'network', label: r.status ? String(r.status) : '···', bad: r.status >= 400, text: (r.method ? r.method + ' ' : '') + name, more });
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const logged = rows.length > 0;
|
|
173
|
+
const log = document.getElementById('log');
|
|
174
|
+
if (logged) document.body.classList.add('logged');
|
|
175
|
+
// The panel's room, where the window is wide enough to show it (as the stylesheet has it).
|
|
176
|
+
const side = () => (logged && innerWidth >= 900 ? 340 : 0);
|
|
177
|
+
|
|
99
178
|
// A recording with the mic starts paused: a browser plays sound only after a click, which Play is.
|
|
100
179
|
const clips = await Promise.all((kept.voice ?? []).map(async (c) => ({ ...c, audio: Object.assign(new Audio(await from.clip(c.id)), { preload: 'auto' }) })));
|
|
101
180
|
const t = Number.parseFloat(params.get('t') ?? '');
|
|
@@ -103,8 +182,8 @@ const replayPage = ({ player = "..", source } = {}) => `<!doctype html>
|
|
|
103
182
|
const size = () => bare
|
|
104
183
|
? { width: kept.viewport.width, height: kept.viewport.height }
|
|
105
184
|
: embed
|
|
106
|
-
? { width: innerWidth, height: innerHeight - 80 }
|
|
107
|
-
: { width: Math.min(kept.viewport.width, innerWidth - 32), height: Math.min(kept.viewport.height, innerHeight - 90 - 80 - 16) };
|
|
185
|
+
? { width: innerWidth - side(), height: innerHeight - 80 }
|
|
186
|
+
: { width: Math.min(kept.viewport.width, innerWidth - 32 - side()), height: Math.min(kept.viewport.height, innerHeight - 90 - 80 - 16) };
|
|
108
187
|
const Player = rrwebPlayer.default ?? rrwebPlayer.Player ?? rrwebPlayer;
|
|
109
188
|
const player = new Player({
|
|
110
189
|
target: main,
|
|
@@ -117,6 +196,9 @@ const replayPage = ({ player = "..", source } = {}) => `<!doctype html>
|
|
|
117
196
|
tags: { ${JSON.stringify(MARKS)}: '#12b358' },
|
|
118
197
|
inactiveColor: '#3f3f46',
|
|
119
198
|
mouseTail: false,
|
|
199
|
+
// A recorded canvas is drawn by rrweb's own script in the replay's frame, which then must run scripts
|
|
200
|
+
// (the page's own were never recorded): only for a recording that has one.
|
|
201
|
+
...(events.some((e) => e.type === 3 && e.data.source === 9) ? { UNSAFE_replayCanvas: true } : {}),
|
|
120
202
|
},
|
|
121
203
|
});
|
|
122
204
|
addEventListener('resize', () => { player.$set(size()); player.triggerResize(); });
|
|
@@ -130,10 +212,51 @@ const replayPage = ({ player = "..", source } = {}) => `<!doctype html>
|
|
|
130
212
|
|
|
131
213
|
let playing = false;
|
|
132
214
|
player.addEventListener('ui-update-player-state', (e) => { playing = e.payload === 'playing'; });
|
|
215
|
+
|
|
216
|
+
// The rows: a click goes to its moment, and shows the rest of it (where a line was logged from, a request's
|
|
217
|
+
// headers and bodies). All set as text: it's the recorded page's, not ours.
|
|
218
|
+
const list = log.querySelector('ol');
|
|
219
|
+
const bar = main.querySelector('.rr-progress');
|
|
220
|
+
for (const row of rows) {
|
|
221
|
+
const cell = (tag, name, text) => Object.assign(document.createElement(tag), { className: name, textContent: text });
|
|
222
|
+
const go = Object.assign(document.createElement('button'), { type: 'button' });
|
|
223
|
+
go.append(cell('time', '', clock(row.at)), cell('span', 'label', row.label), cell('span', 'text', row.text));
|
|
224
|
+
const more = Object.assign(cell('pre', '', row.more.join('\\n')), { hidden: true });
|
|
225
|
+
row.el = Object.assign(document.createElement('li'), { className: row.kind + (row.bad ? ' bad' : row.warn ? ' warn' : '') });
|
|
226
|
+
go.addEventListener('click', () => {
|
|
227
|
+
player.goto(Math.min(row.at, total), playing);
|
|
228
|
+
more.hidden = !more.hidden || row.more.length === 0;
|
|
229
|
+
row.el.classList.toggle('open', !more.hidden);
|
|
230
|
+
});
|
|
231
|
+
row.el.append(go, more);
|
|
232
|
+
list.append(row.el);
|
|
233
|
+
// An error, or a request that failed, is a mark on the timeline too.
|
|
234
|
+
if (row.bad && bar) bar.append(Object.assign(cell('i', 'bad-mark', ''), { title: row.text.slice(0, 200), style: 'left:' + (total > 0 ? (row.at / total) * 100 : 0) + '%' }));
|
|
235
|
+
}
|
|
236
|
+
for (const button of log.querySelectorAll('.filters button')) {
|
|
237
|
+
button.addEventListener('click', () => {
|
|
238
|
+
const on = button.getAttribute('aria-pressed') !== 'true';
|
|
239
|
+
button.setAttribute('aria-pressed', String(on));
|
|
240
|
+
if (button.dataset.hides) log.classList.toggle(button.dataset.hides, !on);
|
|
241
|
+
if (button.dataset.shows) log.classList.toggle(button.dataset.shows, on);
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
// The row the replay is at: the last whose moment has come, lit, the ones to come faint, kept in sight unless
|
|
245
|
+
// the list is being read.
|
|
246
|
+
let lit;
|
|
247
|
+
const light = (now) => {
|
|
248
|
+
let i = -1;
|
|
249
|
+
while (i + 1 < rows.length && rows[i + 1].at <= now) i++;
|
|
250
|
+
if (i === lit) return;
|
|
251
|
+
lit = i;
|
|
252
|
+
rows.forEach((row, k) => { row.el.classList.toggle('ahead', k > i); row.el.classList.toggle('now', k === i); });
|
|
253
|
+
if (i >= 0 && !log.matches(':hover')) rows[i].el.scrollIntoView({ block: 'nearest' });
|
|
254
|
+
};
|
|
133
255
|
const follow = () => {
|
|
134
256
|
const win = replayer.iframe.contentWindow;
|
|
135
257
|
if (win) marks.style.transform = 'translate(' + -win.scrollX + 'px,' + -win.scrollY + 'px)';
|
|
136
258
|
const now = Math.min(replayer.getCurrentTime(), total);
|
|
259
|
+
light(now);
|
|
137
260
|
const speed = replayer.config.speed ?? 1;
|
|
138
261
|
// Each clip plays while the replay is inside it, at its speed, kept within a few frames of the replay's time.
|
|
139
262
|
for (const c of clips) {
|
|
@@ -162,10 +285,16 @@ const replayPage = ({ player = "..", source } = {}) => `<!doctype html>
|
|
|
162
285
|
*
|
|
163
286
|
* Recordings are kept under `.deictic/recordings`, the latest `keep`, as JSON: rrweb's
|
|
164
287
|
* events, with the page, its viewport and how long it ran. `replay/<id>` plays one back in the browser.
|
|
288
|
+
*
|
|
289
|
+
* The page sends one as it goes (`begin`, then `part/<id>` each second or so, then `end/<id>` or `discard/<id>`),
|
|
290
|
+
* not whole at the end, so it outlasts the page: after a reload, or a link to another page of the site, the next
|
|
291
|
+
* page carries on with the same recording, which then holds each page in turn.
|
|
165
292
|
*/
|
|
166
293
|
const ID = /^[a-z0-9]+-[a-z0-9]+$/;
|
|
167
294
|
/** What one recording may weigh: minutes of a busy page are a few MB. */
|
|
168
295
|
const MAX = 52428800;
|
|
296
|
+
/** How long a recording nobody ended keeps its parts, in milliseconds. */
|
|
297
|
+
const STALE = 864e5;
|
|
169
298
|
/** rrweb's player (`rrweb-player`), served to the replay page: its build for a script tag, and its styles. */
|
|
170
299
|
const player = (file) => {
|
|
171
300
|
try {
|
|
@@ -187,14 +316,44 @@ function recordings(options = {}) {
|
|
|
187
316
|
type: "application/json"
|
|
188
317
|
};
|
|
189
318
|
};
|
|
190
|
-
const
|
|
319
|
+
const partOf = (id) => join(dir, `${id}.part`);
|
|
320
|
+
/** The recording going on that a request names, as its last segment: its ID, or the answer that there's none. */
|
|
321
|
+
const going = (req) => {
|
|
322
|
+
const id = new URL(req.url).pathname.split("/").at(-1) ?? "";
|
|
323
|
+
if (ID.test(id) && existsSync(partOf(id))) return id;
|
|
324
|
+
return Response.json({ problem: `no recording ${id} is going any more: record again` }, { status: 404 });
|
|
325
|
+
};
|
|
326
|
+
const json = async (req) => {
|
|
327
|
+
try {
|
|
328
|
+
return await req.json();
|
|
329
|
+
} catch {
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
/** A recording begun: its ID, and the file its parts are added to, which starts with what `Kept` says besides the events. */
|
|
334
|
+
const begin = (meta) => {
|
|
191
335
|
const id = `${Date.now().toString(36).padStart(9, "0")}${(taken++ % 1296).toString(36).padStart(2, "0")}-${crypto.randomUUID().slice(0, 8)}`;
|
|
192
336
|
mkdirSync(dir, { recursive: true });
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
for (const old of kept.slice(0, Math.max(0, kept.length - keep))) rmSync(join(dir, old));
|
|
337
|
+
for (const f of readdirSync(dir)) if (f.endsWith(".part") && Date.now() - statSync(join(dir, f)).mtimeMs > STALE) rmSync(join(dir, f));
|
|
338
|
+
writeFileSync(partOf(id), `${JSON.stringify(meta)}\n`);
|
|
196
339
|
return id;
|
|
197
340
|
};
|
|
341
|
+
/** The parts as one recording, in their order whatever order they came in: a page's last may overtake the one before. */
|
|
342
|
+
const end = (id, last) => {
|
|
343
|
+
const [meta, ...lines] = readFileSync(partOf(id), "utf8").trimEnd().split("\n");
|
|
344
|
+
const events = lines.map((line) => JSON.parse(line)).toSorted((a, b) => a.seq - b.seq).flatMap((part) => part.events);
|
|
345
|
+
rmSync(partOf(id));
|
|
346
|
+
if (events.length === 0) return false;
|
|
347
|
+
const kept = {
|
|
348
|
+
...JSON.parse(meta),
|
|
349
|
+
...last,
|
|
350
|
+
events
|
|
351
|
+
};
|
|
352
|
+
writeFileSync(pathOf(id), JSON.stringify(kept));
|
|
353
|
+
const all = readdirSync(dir).filter((f) => f.endsWith(".json")).toSorted();
|
|
354
|
+
for (const old of all.slice(0, Math.max(0, all.length - keep))) rmSync(join(dir, old));
|
|
355
|
+
return true;
|
|
356
|
+
};
|
|
198
357
|
const file = (path, type) => {
|
|
199
358
|
if (!existsSync(path)) return new Response("rrweb-player is missing: add it to your devDependencies", { status: 404 });
|
|
200
359
|
return new Response(readFileSync(path), { headers: { "content-type": type } });
|
|
@@ -202,30 +361,62 @@ function recordings(options = {}) {
|
|
|
202
361
|
return definePlugin({
|
|
203
362
|
name: "recordings",
|
|
204
363
|
client: "deictic/recordings/client",
|
|
205
|
-
clientOptions: {
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
364
|
+
clientOptions: {
|
|
365
|
+
masking: {
|
|
366
|
+
blockClass: options.blockClass ?? "rr-block",
|
|
367
|
+
blockSelector: options.blockSelector,
|
|
368
|
+
maskTextClass: options.maskTextClass ?? "rr-mask",
|
|
369
|
+
maskTextSelector: options.maskTextSelector,
|
|
370
|
+
maskAllInputs: options.maskAllInputs ?? false
|
|
371
|
+
},
|
|
372
|
+
canvas: options.canvas === false ? false : { fps: (options.canvas === true ? void 0 : options.canvas?.fps) ?? 2 }
|
|
373
|
+
},
|
|
212
374
|
setup: ({ root }) => {
|
|
213
375
|
dir = options.dir === void 0 ? keptIn(root, "recordings") : resolve(root, options.dir);
|
|
214
376
|
return { read };
|
|
215
377
|
},
|
|
216
378
|
routes: {
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
|
|
379
|
+
begin: async (req) => {
|
|
380
|
+
const meta = await json(req);
|
|
381
|
+
if (meta?.viewport === void 0 || typeof meta.page !== "string" || typeof meta.startedAt !== "number") return Response.json({ problem: "send the page, its viewport and when it started, as JSON" }, { status: 400 });
|
|
382
|
+
const { page, viewport, colorScheme, startedAt } = meta;
|
|
383
|
+
return Response.json({ id: begin({
|
|
384
|
+
page,
|
|
385
|
+
viewport,
|
|
386
|
+
...colorScheme === void 0 ? {} : { colorScheme },
|
|
387
|
+
startedAt
|
|
388
|
+
}) });
|
|
389
|
+
},
|
|
390
|
+
part: async (req) => {
|
|
391
|
+
const id = going(req);
|
|
392
|
+
if (typeof id !== "string") return id;
|
|
393
|
+
const seq = Number(new URL(req.url).searchParams.get("seq") ?? "none");
|
|
394
|
+
const events = await json(req);
|
|
395
|
+
if (!Array.isArray(events) || !Number.isInteger(seq)) return Response.json({ problem: "send the events as a JSON array, and `seq`, their place" }, { status: 400 });
|
|
396
|
+
const line = `${JSON.stringify({
|
|
397
|
+
seq,
|
|
398
|
+
events
|
|
399
|
+
})}\n`;
|
|
400
|
+
if (statSync(partOf(id)).size + line.length > MAX) return Response.json({ problem: `a recording may weigh ${MAX / 1024 / 1024} MB at most: stop this one` }, { status: 413 });
|
|
401
|
+
appendFileSync(partOf(id), line);
|
|
402
|
+
return Response.json({ id });
|
|
403
|
+
},
|
|
404
|
+
end: async (req) => {
|
|
405
|
+
const id = going(req);
|
|
406
|
+
if (typeof id !== "string") return id;
|
|
407
|
+
const last = await json(req);
|
|
408
|
+
if (typeof last?.duration !== "number") return Response.json({ problem: "send how long it ran, as JSON" }, { status: 400 });
|
|
409
|
+
if (!end(id, {
|
|
410
|
+
duration: last.duration,
|
|
411
|
+
...last.voice === void 0 ? {} : { voice: last.voice }
|
|
412
|
+
})) return Response.json({ problem: "the recording has no events: record for a moment longer" }, { status: 400 });
|
|
413
|
+
return Response.json({ id });
|
|
414
|
+
},
|
|
415
|
+
discard: (req) => {
|
|
416
|
+
const id = going(req);
|
|
417
|
+
if (typeof id !== "string") return id;
|
|
418
|
+
rmSync(partOf(id));
|
|
419
|
+
return Response.json({ id });
|
|
229
420
|
},
|
|
230
421
|
recording: (req) => {
|
|
231
422
|
const found = read(new URL(req.url).pathname.split("/").at(-1) ?? "");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recordings.js","names":[],"sources":["../../src/plugins/recordings/replay.ts","../../src/plugins/recordings/index.ts"],"sourcesContent":["/**\n * The replay page, `replay/<id>`: rrweb's own player (`rrweb-player`), its timeline, speeds, skipping idle\n * stretches and fullscreen, sized to the window, with what it doesn't do drawn over it:\n *\n * - The page shows in the colour scheme it was recorded in, whatever the viewer's: the replay's iframe\n * answers `prefers-color-scheme` as the viewer's browser does, so the recorded CSS's queries are rewritten\n * before it's replayed, the recorded scheme's to always match and the other's never.\n * - The marks drawn while recording come as custom events, an SVG in page coordinates each; they're drawn\n * over the replay in the player's own scaled wrapper, moved with its scroll, rather than into its document,\n * which the replayer rebuilds. Each is a marker on the timeline.\n * - The voice clips play in step, at the player's speed. A recording with voice starts paused, as a browser\n * plays sound only after a click.\n *\n * `?t=<seconds>` opens it paused there, and `&bare` without the controls at the recorded size, 1:1, for a\n * screenshot; `?embed` is it filling a frame, with no header of its own (the lightbox's); `body[data-ready]` says\n * it's in place.\n *\n * The plugin's routes serve it, the player and what it plays. A page with no server behind it (a `standalone` build)\n * publishes it as a file instead, `replayPage(sources)`: which recording is `?id=`, and a script of its own says\n * where one is.\n */\nimport { MARKS } from './marks.ts';\n\n/** Where the replay page finds what the plugin's routes would serve it, for a page published as a file. */\nexport interface ReplaySources {\n /** The folder `player.js` and `player.css` are in (`rrweb-player`'s `rrweb-player.umd.min.cjs` and `style.css`), from the page: `..`, the routes', by default. */\n player?: string;\n /**\n * A script, from the page, that sets `globalThis.deicticReplay` before the page asks: `recording(id)` answers the\n * recording (a `Kept`) and `clip(id)` a voice clip's URL, either as a promise. The routes by default.\n */\n source?: string;\n}\n\n/** The replay page's HTML: the routes' as it is, or one for a page published as a file. */\nexport const replayPage = ({ player = '..', source }: ReplaySources = {}) => `<!doctype html>\n<html lang=\"en\">\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Recording · deictic</title>\n<link rel=\"stylesheet\" href=\"${player}/player.css\">\n<style>\n :root { color-scheme: dark; --accent: #12b358; }\n body { margin: 0; min-height: 100vh; display: flex; flex-direction: column; background: #18181b; color: #fafafa; font: 13px/1.4 system-ui, sans-serif; }\n header { display: flex; gap: 10px; align-items: center; padding: 10px 16px; border-bottom: 1px solid #3f3f46; }\n header a { color: #a1a1aa; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n main { flex: 1; display: flex; justify-content: center; align-items: flex-start; padding: 16px; }\n body.bare header { display: none; }\n body.bare main { padding: 0; }\n body.embed header { display: none; }\n body.embed main { padding: 0; }\n body.embed #main .rr-player { box-shadow: none; border-radius: 0; }\n #marks { position: absolute; left: 0; top: 0; pointer-events: none; z-index: 3; }\n #marks svg { position: absolute; left: 0; top: 0; overflow: visible; }\n .problem { color: #f87171; padding: 16px; }\n /* rrweb-player, in the dark of the rest of deictic. Its rules repeat Svelte's scoping class, so these start\n from #main, which outweighs any number of classes. */\n #main .rr-player { background: #27272a; box-shadow: 0 12px 32px rgb(0 0 0 / 0.5); border-radius: 8px; overflow: hidden; }\n body.bare #main .rr-player { box-shadow: none; border-radius: 0; }\n #main .rr-player .rr-player__frame { background: #fff; }\n #main .rr-player .rr-controller { background: #18181b; border-top: 1px solid #3f3f46; border-radius: 0; }\n #main .rr-player .rr-timeline__time { color: #a1a1aa; font: 12px ui-monospace, monospace; }\n #main .rr-player .rr-progress { background: #3f3f46; border-color: #18181b; }\n #main .rr-player .rr-progress__step { background: color-mix(in srgb, var(--accent) 45%, transparent); }\n #main .rr-player .rr-progress__handler { background: var(--accent); }\n #main .rr-player .rr-controller__btns button { color: #e4e4e7; }\n #main .rr-player .rr-controller__btns button:disabled { color: #52525b; }\n #main .rr-player .rr-controller__btns button svg { fill: currentColor; }\n #main .rr-player .rr-controller__btns button.active { color: #04130b; background: var(--accent); }\n #main .rr-player .rr-controller__btns button:active { background: color-mix(in srgb, var(--accent) 60%, transparent); }\n #main .rr-player .switch .label { color: #e4e4e7; }\n #main .rr-player .switch.disabled .label { color: #52525b; }\n #main .rr-player .switch label:before { background: #52525b; }\n #main .rr-player .switch input:checked + label:before { background: var(--accent); }\n</style>\n<header>\n <strong>Recording</strong>\n <a id=\"page\" target=\"_blank\" rel=\"noreferrer\"></a>\n</header>\n<main id=\"main\"></main>\n<script src=\"${player}/player.js\"></script>${\n source === undefined\n ? ''\n : `\n<script src=\"${source}\"></script>`\n}\n<script>\n const params = new URLSearchParams(location.search);\n const bare = params.has('bare');\n const embed = params.has('embed');\n if (bare) document.body.classList.add('bare');\n if (embed) document.body.classList.add('embed');\n const id = params.get('id') ?? location.pathname.split('/').at(-1);\n // The plugin's routes, unless the page was given a source of its own (\\`replayPage\\`).\n const from = globalThis.deicticReplay ?? {\n recording: (id) => fetch('../recording/' + id).then((r) => (r.ok ? r.json() : r.text().then((t) => Promise.reject(new Error(t))))),\n clip: (id) => '../../voice/clip/' + id,\n };\n Promise.resolve(from.recording(id)).then(async (kept) => {\n const scheme = kept.colorScheme ?? 'light';\n const events = JSON.parse(\n JSON.stringify(kept.events).replace(/\\\\(\\\\s*prefers-color-scheme\\\\s*:\\\\s*(light|dark)\\\\s*\\\\)/g, (_, s) =>\n s === scheme ? '(min-width: 0px)' : '(max-width: 0px) and (min-width: 1px)',\n ),\n );\n page.textContent = kept.page;\n page.href = kept.page;\n\n // A recording with the mic starts paused: a browser plays sound only after a click, which Play is.\n const clips = await Promise.all((kept.voice ?? []).map(async (c) => ({ ...c, audio: Object.assign(new Audio(await from.clip(c.id)), { preload: 'auto' }) })));\n const t = Number.parseFloat(params.get('t') ?? '');\n // The player's frame, at most the window's room, the controls (80px) under it; 1:1 when bare.\n const size = () => bare\n ? { width: kept.viewport.width, height: kept.viewport.height }\n : embed\n ? { width: innerWidth, height: innerHeight - 80 }\n : { width: Math.min(kept.viewport.width, innerWidth - 32), height: Math.min(kept.viewport.height, innerHeight - 90 - 80 - 16) };\n const Player = rrwebPlayer.default ?? rrwebPlayer.Player ?? rrwebPlayer;\n const player = new Player({\n target: main,\n props: {\n events,\n ...size(),\n autoPlay: !Number.isFinite(t) && clips.length === 0,\n showController: !bare,\n speedOption: [1, 2, 4, 8],\n tags: { ${JSON.stringify(MARKS)}: '#12b358' },\n inactiveColor: '#3f3f46',\n mouseTail: false,\n },\n });\n addEventListener('resize', () => { player.$set(size()); player.triggerResize(); });\n const replayer = player.getReplayer();\n const total = player.getMetaData().totalTime;\n\n // The marks as they were at this point: the latest custom event's, in the player's scaled wrapper, moved with the replay's scroll.\n const marks = Object.assign(document.createElement('div'), { id: 'marks' });\n replayer.wrapper.append(marks);\n replayer.on('custom-event', (e) => { if (e.data.tag === ${JSON.stringify(MARKS)}) marks.innerHTML = e.data.payload.svg; });\n\n let playing = false;\n player.addEventListener('ui-update-player-state', (e) => { playing = e.payload === 'playing'; });\n const follow = () => {\n const win = replayer.iframe.contentWindow;\n if (win) marks.style.transform = 'translate(' + -win.scrollX + 'px,' + -win.scrollY + 'px)';\n const now = Math.min(replayer.getCurrentTime(), total);\n const speed = replayer.config.speed ?? 1;\n // Each clip plays while the replay is inside it, at its speed, kept within a few frames of the replay's time.\n for (const c of clips) {\n const into = now - c.at;\n if (!playing || into < 0 || into >= c.duration) { if (!c.audio.paused) c.audio.pause(); continue; }\n if (c.audio.playbackRate !== speed) c.audio.playbackRate = speed;\n if (Math.abs(c.audio.currentTime * 1000 - into) > 250 * speed) c.audio.currentTime = into / 1000;\n if (c.audio.paused) c.audio.play().catch(() => {});\n }\n requestAnimationFrame(follow);\n };\n follow();\n\n if (Number.isFinite(t)) player.goto(Math.min(Math.max(0, t * 1000), total), false);\n document.body.dataset.ready = '';\n }).catch((e) => { document.querySelector('main').innerHTML = '<p class=\"problem\"></p>'; document.querySelector('.problem').textContent = e.message; });\n</script>\n</html>\n`;\n","/**\n * `deictic/recordings`: records the page with rrweb, for other plugins to attach (tasks does). No tab of\n * its own: `use('recordings').record()` shows a toolbar on the page (drag it to any edge) with annotate\n * mode's tools, where that plugin is loaded, a mic where the voice plugin is, and Stop and Discard. What's drawn while recording is in the\n * recording too, as custom events the replay draws.\n *\n * Recordings are kept under `.deictic/recordings`, the latest `keep`, as JSON: rrweb's\n * events, with the page, its viewport and how long it ran. `replay/<id>` plays one back in the browser.\n */\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join, resolve } from 'node:path';\n\nimport { definePlugin } from '#src/index.ts';\nimport type { Masking, ResolvedMasking } from '#src/plugins/screenshots/index.ts';\nimport { keptIn } from '#src/tools/kept.ts';\n\nimport { replayPage } from './replay.ts';\n\nexport { MARKS } from './marks.ts';\nexport { replayPage, type ReplaySources } from './replay.ts';\n\n/** A recording as the page knows it: its ID, where it plays back, and how long it ran, in milliseconds. */\nexport interface Recording {\n id: string;\n url: string;\n duration: number;\n /** What the mic took while it was on, where the voice plugin is loaded. */\n voice?: VoiceClip[];\n}\n\n/** A stretch of the mic in a recording: the voice plugin's clip, and when it starts in the recording, in milliseconds. */\nexport interface VoiceClip {\n id: string;\n at: number;\n duration: number;\n}\n\n/** The page's half, for other plugins' page halves. */\nexport interface Recorder {\n /**\n * Records the page, with the toolbar, until Stop: answers the recording, kept by the dev server, or\n * nothing when it's discarded. Rejects while another is going, or when it couldn't be kept.\n */\n record(): Promise<Recording | undefined>;\n /** Whether one is going. */\n recording(): boolean;\n}\n\n/** The server's half, for other plugins' server halves. */\nexport interface Recordings {\n /** A recording's JSON, or nothing for one not kept (any more). */\n read(id: string): { data: Uint8Array<ArrayBuffer>; name: string; type: 'application/json' } | undefined;\n}\n\n/** What the page sends, and what's kept: rrweb's events and what they can't say. */\nexport interface Kept {\n page: string;\n viewport: { width: number; height: number };\n /**\n * The colour scheme the page was in, which rrweb doesn't record: the replay shows it in the same, or a\n * page styled by `prefers-color-scheme` would take the replay's.\n */\n colorScheme?: 'light' | 'dark';\n startedAt: number;\n duration: number;\n events: unknown[];\n /** The mic's clips, played along with the replay. */\n voice?: VoiceClip[];\n}\n\ndeclare module 'deictic' {\n interface ServerApis {\n recordings: Recordings;\n }\n interface ClientApis {\n recordings: Recorder;\n }\n}\n\nexport interface RecordingsOptions extends Masking {\n /** How many recordings to keep, the latest: 20 by default. */\n keep?: number;\n /** Where they're kept, from the project's root: `.deictic/recordings` by default. */\n dir?: string;\n}\n\nconst ID = /^[a-z0-9]+-[a-z0-9]+$/;\n/** What one recording may weigh: minutes of a busy page are a few MB. */\nconst MAX = 50 * 1024 * 1024;\n\n/** rrweb's player (`rrweb-player`), served to the replay page: its build for a script tag, and its styles. */\nconst player = (file: string) => {\n try {\n return join(dirname(createRequire(import.meta.url).resolve('rrweb-player')), file);\n } catch {\n // Not installed: `file` answers what to add.\n return '';\n }\n};\n\nexport function recordings(options: RecordingsOptions = {}) {\n const keep = options.keep ?? 20;\n let dir = '';\n let taken = 0;\n const pathOf = (id: string) => join(dir, `${id}.json`);\n const read: Recordings['read'] = (id) => {\n if (!ID.test(id) || !existsSync(pathOf(id))) return undefined;\n return { data: new Uint8Array(readFileSync(pathOf(id))), name: `recording-${id}.json`, type: 'application/json' };\n };\n const keepRecording = (data: Uint8Array) => {\n // Sorts by when it was made, which is what pruning keeps by: the count orders two in one millisecond.\n const id = `${Date.now().toString(36).padStart(9, '0')}${(taken++ % 1296).toString(36).padStart(2, '0')}-${crypto.randomUUID().slice(0, 8)}`;\n mkdirSync(dir, { recursive: true });\n writeFileSync(pathOf(id), data);\n const kept = readdirSync(dir)\n .filter((f) => f.endsWith('.json'))\n .toSorted();\n for (const old of kept.slice(0, Math.max(0, kept.length - keep))) rmSync(join(dir, old));\n return id;\n };\n const file = (path: string, type: string) => {\n if (!existsSync(path)) return new Response('rrweb-player is missing: add it to your devDependencies', { status: 404 });\n return new Response(readFileSync(path), { headers: { 'content-type': type } });\n };\n\n return definePlugin<never, never, never, Recordings>({\n name: 'recordings',\n client: 'deictic/recordings/client',\n clientOptions: {\n masking: {\n blockClass: options.blockClass ?? 'rr-block',\n blockSelector: options.blockSelector,\n maskTextClass: options.maskTextClass ?? 'rr-mask',\n maskTextSelector: options.maskTextSelector,\n maskAllInputs: options.maskAllInputs ?? false,\n } satisfies ResolvedMasking,\n },\n setup: ({ root }) => {\n dir = options.dir === undefined ? keptIn(root, 'recordings') : resolve(root, options.dir);\n return { read };\n },\n routes: {\n // What the page recorded, as JSON.\n add: async (req) => {\n if (!(req.headers.get('content-type') ?? '').startsWith('application/json'))\n return Response.json({ problem: 'send the recording as application/json' }, { status: 415 });\n const body = new Uint8Array(await req.arrayBuffer());\n if (body.byteLength > MAX)\n return Response.json({ problem: `a recording may weigh ${MAX / 1024 / 1024} MB at most` }, { status: 413 });\n let kept: Partial<Kept>;\n try {\n kept = JSON.parse(new TextDecoder().decode(body)) as Partial<Kept>;\n } catch {\n return Response.json({ problem: \"the recording isn't JSON\" }, { status: 400 });\n }\n if (!Array.isArray(kept.events) || kept.events.length === 0)\n return Response.json({ problem: 'the recording has no events: record for a moment longer' }, { status: 400 });\n return Response.json({ id: keepRecording(body) });\n },\n // `recording/<id>`: the JSON, for the replay page.\n recording: (req) => {\n const found = read(new URL(req.url).pathname.split('/').at(-1) ?? '');\n if (found === undefined) return new Response('no such recording, or not kept any more', { status: 404 });\n return new Response(found.data, { headers: { 'content-type': found.type, 'cache-control': 'no-store' } });\n },\n // `replay/<id>`: a page that plays it back.\n replay: () => new Response(replayPage(), { headers: { 'content-type': 'text/html; charset=utf-8' } }),\n 'player.js': () => file(player('rrweb-player.umd.min.cjs'), 'text/javascript'),\n 'player.css': () => file(player('style.css'), 'text/css'),\n },\n });\n}\n\nexport default recordings;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAa,cAAc,EAAE,SAAS,MAAM,WAA0B,CAAC,MAAM;;;;;+BAK9C,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eAwCvB,OAAO,wBACpB,WAAW,KAAA,IACP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CAAC,MAAM,QAAQ,KAAK,MAAM,KAAK,KAAK,OAAO,WAAW,GACxD,OAAO,SAAS,KAAK,EAAE,SAAS,0DAA0D,GAAG,EAAE,QAAQ,IAAI,CAAC;IAC9G,OAAO,SAAS,KAAK,EAAE,IAAI,cAAc,IAAI,EAAE,CAAC;GAClD;GAEA,YAAY,QAAQ;IAClB,MAAM,QAAQ,KAAK,IAAI,IAAI,IAAI,GAAG,CAAC,CAAC,SAAS,MAAM,GAAG,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE;IACpE,IAAI,UAAU,KAAA,GAAW,OAAO,IAAI,SAAS,2CAA2C,EAAE,QAAQ,IAAI,CAAC;IACvG,OAAO,IAAI,SAAS,MAAM,MAAM,EAAE,SAAS;KAAE,gBAAgB,MAAM;KAAM,iBAAiB;IAAW,EAAE,CAAC;GAC1G;GAEA,cAAc,IAAI,SAAS,WAAW,GAAG,EAAE,SAAS,EAAE,gBAAgB,2BAA2B,EAAE,CAAC;GACpG,mBAAmB,KAAK,OAAO,0BAA0B,GAAG,iBAAiB;GAC7E,oBAAoB,KAAK,OAAO,WAAW,GAAG,UAAU;EAC1D;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"recordings.js","names":[],"sources":["../../src/plugins/recordings/replay.ts","../../src/plugins/recordings/index.ts"],"sourcesContent":["/**\n * The replay page, `replay/<id>`: rrweb's own player (`rrweb-player`), its timeline, speeds, skipping idle\n * stretches and fullscreen, sized to the window, with what it doesn't do drawn over it:\n *\n * - The page shows in the colour scheme it was recorded in, whatever the viewer's: the replay's iframe\n * answers `prefers-color-scheme` as the viewer's browser does, so the recorded CSS's queries are rewritten\n * before it's replayed, the recorded scheme's to always match and the other's never.\n * - The marks drawn while recording come as custom events, an SVG in page coordinates each; they're drawn\n * over the replay in the player's own scaled wrapper, moved with its scroll, rather than into its document,\n * which the replayer rebuilds. Each is a marker on the timeline.\n * - The voice clips play in step, at the player's speed. A recording with voice starts paused, as a browser\n * plays sound only after a click.\n * - What the page logged and asked for (rrweb's console and network plugins' events, which its player doesn't\n * show) is a list beside the replay, where the window has the room: the row the replay is at is lit, a click on\n * one goes to its moment and shows the rest of it, and each error and failed request is a mark on the timeline.\n * - A recorded canvas is replayed (`UNSAFE_replayCanvas`, which lets the replay's frame run rrweb's own script\n * to draw it), for a recording that has one.\n *\n * `?t=<seconds>` opens it paused there, and `&bare` without the controls at the recorded size, 1:1, for a\n * screenshot; `?embed` is it filling a frame, with no header of its own (the lightbox's); `body[data-ready]` says\n * it's in place.\n *\n * The plugin's routes serve it, the player and what it plays. A page with no server behind it (a `standalone` build)\n * publishes it as a file instead, `replayPage(sources)`: which recording is `?id=`, and a script of its own says\n * where one is.\n */\nimport { MARKS } from './marks.ts';\n\n/** Where the replay page finds what the plugin's routes would serve it, for a page published as a file. */\nexport interface ReplaySources {\n /** The folder `player.js` and `player.css` are in (`rrweb-player`'s `rrweb-player.umd.min.cjs` and `style.css`), from the page: `..`, the routes', by default. */\n player?: string;\n /**\n * A script, from the page, that sets `globalThis.deicticReplay` before the page asks: `recording(id)` answers the\n * recording (a `Kept`) and `clip(id)` a voice clip's URL, either as a promise. The routes by default.\n */\n source?: string;\n}\n\n/** The replay page's HTML: the routes' as it is, or one for a page published as a file. */\nexport const replayPage = ({ player = '..', source }: ReplaySources = {}) => `<!doctype html>\n<html lang=\"en\">\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Recording · deictic</title>\n<link rel=\"stylesheet\" href=\"${player}/player.css\">\n<style>\n :root { color-scheme: dark; --accent: #12b358; }\n body { margin: 0; min-height: 100vh; display: flex; flex-direction: column; background: #18181b; color: #fafafa; font: 13px/1.4 system-ui, sans-serif; }\n header { display: flex; gap: 10px; align-items: center; padding: 10px 16px; border-bottom: 1px solid #3f3f46; }\n header a { color: #a1a1aa; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n #stage { flex: 1; display: flex; min-height: 0; }\n main { flex: 1; min-width: 0; display: flex; justify-content: center; align-items: flex-start; padding: 16px; }\n body.bare header { display: none; }\n body.bare main { padding: 0; }\n body.embed header { display: none; }\n body.embed main { padding: 0; }\n /* What the page logged and asked for, beside the replay: the window's height, its list scrolling in it. */\n #log { display: none; flex: none; width: 340px; flex-direction: column; border-left: 1px solid #3f3f46; background: #1f1f23; }\n body.logged { height: 100vh; }\n body.logged #log { display: flex; }\n @media (max-width: 899px) { body.logged #log { display: none; } }\n #log .filters { display: flex; gap: 6px; padding: 8px; border-bottom: 1px solid #3f3f46; }\n #log .filters button { padding: 3px 8px; border: 1px solid #3f3f46; border-radius: 6px; background: none; color: #a1a1aa; font: inherit; font-size: 12px; cursor: pointer; }\n #log .filters button[aria-pressed='true'] { color: #fafafa; background: #3f3f46; }\n #log ol { flex: 1; min-height: 0; overflow: auto; margin: 0; padding: 0; list-style: none; font: 12px/1.45 ui-monospace, monospace; }\n #log li { border-bottom: 1px solid #2e2e33; border-left: 2px solid transparent; }\n #log li.ahead { opacity: 0.45; }\n #log li.now { border-left-color: var(--accent); background: #27272a; }\n #log li.warn .label { color: #fbbf24; }\n #log li.bad .label, #log li.bad .text { color: #f87171; }\n #log li > button { display: flex; gap: 8px; align-items: baseline; width: 100%; padding: 5px 8px; border: 0; background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; }\n #log li > button:hover { background: #2e2e33; }\n #log time { flex: none; color: #71717a; }\n #log .label { flex: none; min-width: 4ch; color: #a1a1aa; }\n #log .text { min-width: 0; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow-wrap: anywhere; }\n #log li.open .text { display: block; white-space: pre-wrap; }\n #log pre { margin: 0; padding: 2px 8px 8px calc(8px + 6ch + 8px); color: #a1a1aa; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; }\n #log.no-console li.console, #log.no-network li.network, #log.only-bad li:not(.bad) { display: none; }\n #main .rr-player .rr-progress .bad-mark { position: absolute; top: -3px; width: 3px; height: 10px; margin-left: -1px; border-radius: 1px; background: #f87171; pointer-events: none; }\n body.embed #main .rr-player { box-shadow: none; border-radius: 0; }\n #marks { position: absolute; left: 0; top: 0; pointer-events: none; z-index: 3; }\n #marks svg { position: absolute; left: 0; top: 0; overflow: visible; }\n .problem { color: #f87171; padding: 16px; }\n /* rrweb-player, in the dark of the rest of deictic. Its rules repeat Svelte's scoping class, so these start\n from #main, which outweighs any number of classes. */\n #main .rr-player { background: #27272a; box-shadow: 0 12px 32px rgb(0 0 0 / 0.5); border-radius: 8px; overflow: hidden; }\n body.bare #main .rr-player { box-shadow: none; border-radius: 0; }\n #main .rr-player .rr-player__frame { background: #fff; }\n #main .rr-player .rr-controller { background: #18181b; border-top: 1px solid #3f3f46; border-radius: 0; }\n #main .rr-player .rr-timeline__time { color: #a1a1aa; font: 12px ui-monospace, monospace; }\n #main .rr-player .rr-progress { background: #3f3f46; border-color: #18181b; }\n #main .rr-player .rr-progress__step { background: color-mix(in srgb, var(--accent) 45%, transparent); }\n #main .rr-player .rr-progress__handler { background: var(--accent); }\n #main .rr-player .rr-controller__btns button { color: #e4e4e7; }\n #main .rr-player .rr-controller__btns button:disabled { color: #52525b; }\n #main .rr-player .rr-controller__btns button svg { fill: currentColor; }\n #main .rr-player .rr-controller__btns button.active { color: #04130b; background: var(--accent); }\n #main .rr-player .rr-controller__btns button:active { background: color-mix(in srgb, var(--accent) 60%, transparent); }\n #main .rr-player .switch .label { color: #e4e4e7; }\n #main .rr-player .switch.disabled .label { color: #52525b; }\n #main .rr-player .switch label:before { background: #52525b; }\n #main .rr-player .switch input:checked + label:before { background: var(--accent); }\n</style>\n<header>\n <strong>Recording</strong>\n <a id=\"page\" target=\"_blank\" rel=\"noreferrer\"></a>\n</header>\n<div id=\"stage\">\n <main id=\"main\"></main>\n <aside id=\"log\" aria-label=\"Console and network\">\n <div class=\"filters\">\n <button type=\"button\" data-hides=\"no-console\" aria-pressed=\"true\">Console</button>\n <button type=\"button\" data-hides=\"no-network\" aria-pressed=\"true\">Network</button>\n <button type=\"button\" data-shows=\"only-bad\" aria-pressed=\"false\" title=\"Errors, and requests that failed\">Problems</button>\n </div>\n <ol></ol>\n </aside>\n</div>\n<script src=\"${player}/player.js\"></script>${\n source === undefined\n ? ''\n : `\n<script src=\"${source}\"></script>`\n}\n<script>\n const params = new URLSearchParams(location.search);\n const bare = params.has('bare');\n const embed = params.has('embed');\n if (bare) document.body.classList.add('bare');\n if (embed) document.body.classList.add('embed');\n const id = params.get('id') ?? location.pathname.split('/').at(-1);\n // The plugin's routes, unless the page was given a source of its own (\\`replayPage\\`).\n const from = globalThis.deicticReplay ?? {\n recording: (id) => fetch('../recording/' + id).then((r) => (r.ok ? r.json() : r.text().then((t) => Promise.reject(new Error(t))))),\n clip: (id) => '../../voice/clip/' + id,\n };\n Promise.resolve(from.recording(id)).then(async (kept) => {\n const scheme = kept.colorScheme ?? 'light';\n const events = JSON.parse(\n JSON.stringify(kept.events).replace(/\\\\(\\\\s*prefers-color-scheme\\\\s*:\\\\s*(light|dark)\\\\s*\\\\)/g, (_, s) =>\n s === scheme ? '(min-width: 0px)' : '(max-width: 0px) and (min-width: 1px)',\n ),\n );\n page.textContent = kept.page;\n page.href = kept.page;\n\n // What the page logged and asked for, where the recording has it (rrweb's console and network plugins' events):\n // a row each, in their order, beside the replay. Not in a bare one, which is the page alone.\n const t0 = events[0].timestamp;\n const clock = (ms) => { const s = Math.max(0, ms) / 1000; return Math.floor(s / 60) + ':' + (s % 60).toFixed(1).padStart(4, '0'); };\n // An argument is kept as JSON: a string reads better without its quotes.\n const plain = (arg) => { try { const v = JSON.parse(arg); return typeof v === 'string' ? v : arg; } catch { return arg; } };\n const origin = (() => { try { return new URL(kept.page).origin; } catch { return ''; } })();\n const fields = (title, held) => (held && Object.keys(held).length > 0 ? [title, ...Object.entries(held).map(([k, v]) => ' ' + k + ': ' + v)] : []);\n const rows = [];\n for (const e of events) {\n if (e.type !== 6 || bare) continue;\n const at = e.timestamp - t0;\n if (e.data.plugin === 'rrweb/console@1') {\n const { level, payload = [], trace = [] } = e.data.payload;\n rows.push({ at, kind: 'console', label: level, bad: level === 'error' || level === 'assert', warn: level === 'warn', text: payload.map(plain).join(' '), more: trace.map((l) => 'at ' + l) });\n }\n if (e.data.plugin === 'rrweb/network@1') {\n for (const r of e.data.payload.requests ?? []) {\n // The page's own origin goes without saying.\n let name = r.name;\n try { const u = new URL(r.name); if (u.origin === origin) name = u.pathname + u.search + u.hash; } catch {}\n const more = [\n r.name,\n [r.initiatorType, Number.isFinite(r.duration) ? Math.round(r.duration) + ' ms' : '', e.data.payload.isInitial ? 'as the page loaded' : ''].filter(Boolean).join(' · '),\n ...fields('Request headers', r.requestHeaders),\n ...(r.requestBody ? ['Request body', ' ' + r.requestBody] : []),\n ...fields('Response headers', r.responseHeaders),\n ...(r.responseBody ? ['Response body', ' ' + r.responseBody] : []),\n ];\n // No status is one the browser won't say (another origin's), not one that failed.\n rows.push({ at, kind: 'network', label: r.status ? String(r.status) : '···', bad: r.status >= 400, text: (r.method ? r.method + ' ' : '') + name, more });\n }\n }\n }\n const logged = rows.length > 0;\n const log = document.getElementById('log');\n if (logged) document.body.classList.add('logged');\n // The panel's room, where the window is wide enough to show it (as the stylesheet has it).\n const side = () => (logged && innerWidth >= 900 ? 340 : 0);\n\n // A recording with the mic starts paused: a browser plays sound only after a click, which Play is.\n const clips = await Promise.all((kept.voice ?? []).map(async (c) => ({ ...c, audio: Object.assign(new Audio(await from.clip(c.id)), { preload: 'auto' }) })));\n const t = Number.parseFloat(params.get('t') ?? '');\n // The player's frame, at most the window's room, the controls (80px) under it; 1:1 when bare.\n const size = () => bare\n ? { width: kept.viewport.width, height: kept.viewport.height }\n : embed\n ? { width: innerWidth - side(), height: innerHeight - 80 }\n : { width: Math.min(kept.viewport.width, innerWidth - 32 - side()), height: Math.min(kept.viewport.height, innerHeight - 90 - 80 - 16) };\n const Player = rrwebPlayer.default ?? rrwebPlayer.Player ?? rrwebPlayer;\n const player = new Player({\n target: main,\n props: {\n events,\n ...size(),\n autoPlay: !Number.isFinite(t) && clips.length === 0,\n showController: !bare,\n speedOption: [1, 2, 4, 8],\n tags: { ${JSON.stringify(MARKS)}: '#12b358' },\n inactiveColor: '#3f3f46',\n mouseTail: false,\n // A recorded canvas is drawn by rrweb's own script in the replay's frame, which then must run scripts\n // (the page's own were never recorded): only for a recording that has one.\n ...(events.some((e) => e.type === 3 && e.data.source === 9) ? { UNSAFE_replayCanvas: true } : {}),\n },\n });\n addEventListener('resize', () => { player.$set(size()); player.triggerResize(); });\n const replayer = player.getReplayer();\n const total = player.getMetaData().totalTime;\n\n // The marks as they were at this point: the latest custom event's, in the player's scaled wrapper, moved with the replay's scroll.\n const marks = Object.assign(document.createElement('div'), { id: 'marks' });\n replayer.wrapper.append(marks);\n replayer.on('custom-event', (e) => { if (e.data.tag === ${JSON.stringify(MARKS)}) marks.innerHTML = e.data.payload.svg; });\n\n let playing = false;\n player.addEventListener('ui-update-player-state', (e) => { playing = e.payload === 'playing'; });\n\n // The rows: a click goes to its moment, and shows the rest of it (where a line was logged from, a request's\n // headers and bodies). All set as text: it's the recorded page's, not ours.\n const list = log.querySelector('ol');\n const bar = main.querySelector('.rr-progress');\n for (const row of rows) {\n const cell = (tag, name, text) => Object.assign(document.createElement(tag), { className: name, textContent: text });\n const go = Object.assign(document.createElement('button'), { type: 'button' });\n go.append(cell('time', '', clock(row.at)), cell('span', 'label', row.label), cell('span', 'text', row.text));\n const more = Object.assign(cell('pre', '', row.more.join('\\\\n')), { hidden: true });\n row.el = Object.assign(document.createElement('li'), { className: row.kind + (row.bad ? ' bad' : row.warn ? ' warn' : '') });\n go.addEventListener('click', () => {\n player.goto(Math.min(row.at, total), playing);\n more.hidden = !more.hidden || row.more.length === 0;\n row.el.classList.toggle('open', !more.hidden);\n });\n row.el.append(go, more);\n list.append(row.el);\n // An error, or a request that failed, is a mark on the timeline too.\n if (row.bad && bar) bar.append(Object.assign(cell('i', 'bad-mark', ''), { title: row.text.slice(0, 200), style: 'left:' + (total > 0 ? (row.at / total) * 100 : 0) + '%' }));\n }\n for (const button of log.querySelectorAll('.filters button')) {\n button.addEventListener('click', () => {\n const on = button.getAttribute('aria-pressed') !== 'true';\n button.setAttribute('aria-pressed', String(on));\n if (button.dataset.hides) log.classList.toggle(button.dataset.hides, !on);\n if (button.dataset.shows) log.classList.toggle(button.dataset.shows, on);\n });\n }\n // The row the replay is at: the last whose moment has come, lit, the ones to come faint, kept in sight unless\n // the list is being read.\n let lit;\n const light = (now) => {\n let i = -1;\n while (i + 1 < rows.length && rows[i + 1].at <= now) i++;\n if (i === lit) return;\n lit = i;\n rows.forEach((row, k) => { row.el.classList.toggle('ahead', k > i); row.el.classList.toggle('now', k === i); });\n if (i >= 0 && !log.matches(':hover')) rows[i].el.scrollIntoView({ block: 'nearest' });\n };\n const follow = () => {\n const win = replayer.iframe.contentWindow;\n if (win) marks.style.transform = 'translate(' + -win.scrollX + 'px,' + -win.scrollY + 'px)';\n const now = Math.min(replayer.getCurrentTime(), total);\n light(now);\n const speed = replayer.config.speed ?? 1;\n // Each clip plays while the replay is inside it, at its speed, kept within a few frames of the replay's time.\n for (const c of clips) {\n const into = now - c.at;\n if (!playing || into < 0 || into >= c.duration) { if (!c.audio.paused) c.audio.pause(); continue; }\n if (c.audio.playbackRate !== speed) c.audio.playbackRate = speed;\n if (Math.abs(c.audio.currentTime * 1000 - into) > 250 * speed) c.audio.currentTime = into / 1000;\n if (c.audio.paused) c.audio.play().catch(() => {});\n }\n requestAnimationFrame(follow);\n };\n follow();\n\n if (Number.isFinite(t)) player.goto(Math.min(Math.max(0, t * 1000), total), false);\n document.body.dataset.ready = '';\n }).catch((e) => { document.querySelector('main').innerHTML = '<p class=\"problem\"></p>'; document.querySelector('.problem').textContent = e.message; });\n</script>\n</html>\n`;\n","/**\n * `deictic/recordings`: records the page with rrweb, for other plugins to attach (tasks does). No tab of\n * its own: `use('recordings').record()` shows a toolbar on the page (drag it to any edge) with annotate\n * mode's tools, where that plugin is loaded, a mic where the voice plugin is, and Stop and Discard. What's drawn while recording is in the\n * recording too, as custom events the replay draws.\n *\n * Recordings are kept under `.deictic/recordings`, the latest `keep`, as JSON: rrweb's\n * events, with the page, its viewport and how long it ran. `replay/<id>` plays one back in the browser.\n *\n * The page sends one as it goes (`begin`, then `part/<id>` each second or so, then `end/<id>` or `discard/<id>`),\n * not whole at the end, so it outlasts the page: after a reload, or a link to another page of the site, the next\n * page carries on with the same recording, which then holds each page in turn.\n */\nimport { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join, resolve } from 'node:path';\n\nimport type { record } from 'rrweb';\n\nimport { definePlugin } from '#src/index.ts';\nimport type { Masking, ResolvedMasking } from '#src/plugins/screenshots/index.ts';\nimport { keptIn } from '#src/tools/kept.ts';\n\nimport { replayPage } from './replay.ts';\n\nexport { MARKS } from './marks.ts';\nexport { replayPage, type ReplaySources } from './replay.ts';\n\n/** A recording as the page knows it: its ID, where it plays back, and how long it ran, in milliseconds. */\nexport interface Recording {\n id: string;\n url: string;\n duration: number;\n /** What the mic took while it was on, where the voice plugin is loaded. */\n voice?: VoiceClip[];\n}\n\n/** A stretch of the mic in a recording: the voice plugin's clip, and when it starts in the recording, in milliseconds. */\nexport interface VoiceClip {\n id: string;\n at: number;\n duration: number;\n}\n\n/** The page's half, for other plugins' page halves. */\nexport interface Recorder {\n /**\n * Records the page, with the toolbar, until Stop: answers the recording, kept by the dev server, or\n * nothing when it's discarded. Rejects while another is going, or when it couldn't be kept. A page load\n * doesn't end it: the next page of the site carries on, and `going` there answers what this would have.\n */\n record(): Promise<Recording | undefined>;\n /** Whether one is going. */\n recording(): boolean;\n /** The one going, as `record` answers it: also one a page before this started, carried on here. */\n going(): Promise<Recording | undefined> | undefined;\n}\n\n/** A plugin of rrweb's own, as its `record` takes them: what puts more than the page in a recording. */\nexport type RecordPlugin = NonNullable<NonNullable<Parameters<typeof record>[0]>['plugins']>[number];\n\n/**\n * What a plugin that adds to recordings answers in the page, under its name (`logs` and `network` do): the\n * recorder asks each it knows for its rrweb plugin as a recording starts, so nothing listens before, or after it stops.\n */\nexport interface Recorded {\n /** `sinceLoad`: the recording was going as this page loaded, so what the page did before now is its too. */\n plugin(from: { sinceLoad: boolean }): Promise<RecordPlugin>;\n}\n\n/** The server's half, for other plugins' server halves. */\nexport interface Recordings {\n /** A recording's JSON, or nothing for one not kept (any more). */\n read(id: string): { data: Uint8Array<ArrayBuffer>; name: string; type: 'application/json' } | undefined;\n}\n\n/** What a recording says as it begins: all of a `Kept` that's known then. */\nexport type Meta = Omit<Kept, 'events' | 'duration' | 'voice'>;\n\n/** What's kept: rrweb's events and what they can't say. */\nexport interface Kept {\n /** The page it started on. One that went on to others has each in its events, as rrweb's own: a `Meta`, then a snapshot. */\n page: string;\n viewport: { width: number; height: number };\n /**\n * The colour scheme the page was in, which rrweb doesn't record: the replay shows it in the same, or a\n * page styled by `prefers-color-scheme` would take the replay's.\n */\n colorScheme?: 'light' | 'dark';\n startedAt: number;\n duration: number;\n events: unknown[];\n /** The mic's clips, played along with the replay. */\n voice?: VoiceClip[];\n}\n\ndeclare module 'deictic' {\n interface ServerApis {\n recordings: Recordings;\n }\n interface ClientApis {\n recordings: Recorder;\n }\n}\n\nexport interface RecordingsOptions extends Masking {\n /** How many recordings to keep, the latest: 20 by default. */\n keep?: number;\n /** Where they're kept, from the project's root: `.deictic/recordings` by default. */\n dir?: string;\n /**\n * What a `<canvas>` draws (a chart, a map, WebGL), which is no part of the page's markup: a picture of each\n * canvas that changed, `fps` times a second, 2 by default. `false` for none, and a canvas replays blank.\n */\n canvas?: boolean | { fps?: number };\n}\n\nconst ID = /^[a-z0-9]+-[a-z0-9]+$/;\n/** What one recording may weigh: minutes of a busy page are a few MB. */\nconst MAX = 50 * 1024 * 1024;\n/** How long a recording nobody ended keeps its parts, in milliseconds. */\nconst STALE = 24 * 60 * 60 * 1000;\n\n/** rrweb's player (`rrweb-player`), served to the replay page: its build for a script tag, and its styles. */\nconst player = (file: string) => {\n try {\n return join(dirname(createRequire(import.meta.url).resolve('rrweb-player')), file);\n } catch {\n // Not installed: `file` answers what to add.\n return '';\n }\n};\n\nexport function recordings(options: RecordingsOptions = {}) {\n const keep = options.keep ?? 20;\n let dir = '';\n let taken = 0;\n const pathOf = (id: string) => join(dir, `${id}.json`);\n const read: Recordings['read'] = (id) => {\n if (!ID.test(id) || !existsSync(pathOf(id))) return undefined;\n return { data: new Uint8Array(readFileSync(pathOf(id))), name: `recording-${id}.json`, type: 'application/json' };\n };\n const partOf = (id: string) => join(dir, `${id}.part`);\n /** The recording going on that a request names, as its last segment: its ID, or the answer that there's none. */\n const going = (req: Request): string | Response => {\n const id = new URL(req.url).pathname.split('/').at(-1) ?? '';\n if (ID.test(id) && existsSync(partOf(id))) return id;\n return Response.json({ problem: `no recording ${id} is going any more: record again` }, { status: 404 });\n };\n const json = async <T>(req: Request): Promise<T | undefined> => {\n try {\n return (await req.json()) as T;\n } catch {\n return undefined;\n }\n };\n /** A recording begun: its ID, and the file its parts are added to, which starts with what `Kept` says besides the events. */\n const begin = (meta: Meta) => {\n // Sorts by when it was made, which is what pruning keeps by: the count orders two in one millisecond.\n const id = `${Date.now().toString(36).padStart(9, '0')}${(taken++ % 1296).toString(36).padStart(2, '0')}-${crypto.randomUUID().slice(0, 8)}`;\n mkdirSync(dir, { recursive: true });\n // One nobody ended, as its tab was closed: gone a day on.\n for (const f of readdirSync(dir)) if (f.endsWith('.part') && Date.now() - statSync(join(dir, f)).mtimeMs > STALE) rmSync(join(dir, f));\n\n writeFileSync(partOf(id), `${JSON.stringify(meta)}\\n`);\n return id;\n };\n /** The parts as one recording, in their order whatever order they came in: a page's last may overtake the one before. */\n const end = (id: string, last: Pick<Kept, 'duration' | 'voice'>): boolean => {\n const [meta, ...lines] = readFileSync(partOf(id), 'utf8').trimEnd().split('\\n');\n const parts = lines.map((line) => JSON.parse(line) as { seq: number; events: unknown[] });\n const events = parts.toSorted((a, b) => a.seq - b.seq).flatMap((part) => part.events);\n rmSync(partOf(id));\n if (events.length === 0) return false;\n const kept: Kept = { ...(JSON.parse(meta!) as Meta), ...last, events };\n writeFileSync(pathOf(id), JSON.stringify(kept));\n const all = readdirSync(dir)\n .filter((f) => f.endsWith('.json'))\n .toSorted();\n for (const old of all.slice(0, Math.max(0, all.length - keep))) rmSync(join(dir, old));\n return true;\n };\n const file = (path: string, type: string) => {\n if (!existsSync(path)) return new Response('rrweb-player is missing: add it to your devDependencies', { status: 404 });\n return new Response(readFileSync(path), { headers: { 'content-type': type } });\n };\n\n return definePlugin<never, never, never, Recordings>({\n name: 'recordings',\n client: 'deictic/recordings/client',\n clientOptions: {\n masking: {\n blockClass: options.blockClass ?? 'rr-block',\n blockSelector: options.blockSelector,\n maskTextClass: options.maskTextClass ?? 'rr-mask',\n maskTextSelector: options.maskTextSelector,\n maskAllInputs: options.maskAllInputs ?? false,\n } satisfies ResolvedMasking,\n canvas: options.canvas === false ? false : { fps: (options.canvas === true ? undefined : options.canvas?.fps) ?? 2 },\n },\n setup: ({ root }) => {\n dir = options.dir === undefined ? keptIn(root, 'recordings') : resolve(root, options.dir);\n return { read };\n },\n routes: {\n // A recording starts: the page, its viewport and when. Its events come in parts, as they happen, so a page\n // load in the middle loses none of them, and the next page carries on under the same ID.\n begin: async (req) => {\n const meta = await json<Partial<Meta>>(req);\n if (meta?.viewport === undefined || typeof meta.page !== 'string' || typeof meta.startedAt !== 'number')\n return Response.json({ problem: 'send the page, its viewport and when it started, as JSON' }, { status: 400 });\n const { page, viewport, colorScheme, startedAt } = meta;\n return Response.json({ id: begin({ page, viewport, ...(colorScheme === undefined ? {} : { colorScheme }), startedAt }) });\n },\n // `part/<id>?seq=<n>`: more of its events, a JSON array, and their place among the parts.\n part: async (req) => {\n const id = going(req);\n if (typeof id !== 'string') return id;\n const seq = Number(new URL(req.url).searchParams.get('seq') ?? 'none');\n const events = await json<unknown>(req);\n if (!Array.isArray(events) || !Number.isInteger(seq))\n return Response.json({ problem: 'send the events as a JSON array, and `seq`, their place' }, { status: 400 });\n const line = `${JSON.stringify({ seq, events })}\\n`;\n if (statSync(partOf(id)).size + line.length > MAX)\n return Response.json({ problem: `a recording may weigh ${MAX / 1024 / 1024} MB at most: stop this one` }, { status: 413 });\n appendFileSync(partOf(id), line);\n return Response.json({ id });\n },\n // `end/<id>`: it's over, and kept: how long it ran, and the mic's clips.\n end: async (req) => {\n const id = going(req);\n if (typeof id !== 'string') return id;\n const last = await json<Partial<Kept>>(req);\n if (typeof last?.duration !== 'number') return Response.json({ problem: 'send how long it ran, as JSON' }, { status: 400 });\n if (!end(id, { duration: last.duration, ...(last.voice === undefined ? {} : { voice: last.voice }) }))\n return Response.json({ problem: 'the recording has no events: record for a moment longer' }, { status: 400 });\n return Response.json({ id });\n },\n // `discard/<id>`: it's over, and not kept.\n discard: (req) => {\n const id = going(req);\n if (typeof id !== 'string') return id;\n rmSync(partOf(id));\n return Response.json({ id });\n },\n // `recording/<id>`: the JSON, for the replay page.\n recording: (req) => {\n const found = read(new URL(req.url).pathname.split('/').at(-1) ?? '');\n if (found === undefined) return new Response('no such recording, or not kept any more', { status: 404 });\n return new Response(found.data, { headers: { 'content-type': found.type, 'cache-control': 'no-store' } });\n },\n // `replay/<id>`: a page that plays it back.\n replay: () => new Response(replayPage(), { headers: { 'content-type': 'text/html; charset=utf-8' } }),\n 'player.js': () => file(player('rrweb-player.umd.min.cjs'), 'text/javascript'),\n 'player.css': () => file(player('style.css'), 'text/css'),\n },\n });\n}\n\nexport default recordings;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAa,cAAc,EAAE,SAAS,MAAM,WAA0B,CAAC,MAAM;;;;;+BAK9C,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eA0EvB,OAAO,wBACpB,WAAW,KAAA,IACP,KACA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