deictic 0.0.1 → 0.1.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.
Files changed (173) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +144 -0
  3. package/dist/annotations/client.d.ts +4 -0
  4. package/dist/annotations/client.d.ts.map +1 -0
  5. package/dist/annotations/client.js +497 -0
  6. package/dist/annotations/client.js.map +1 -0
  7. package/dist/annotations/index.d.ts +110 -0
  8. package/dist/annotations/index.d.ts.map +1 -0
  9. package/dist/annotations/index.js +22 -0
  10. package/dist/annotations/index.js.map +1 -0
  11. package/dist/astro.d.ts +29 -0
  12. package/dist/astro.d.ts.map +1 -0
  13. package/dist/astro.js +24 -0
  14. package/dist/astro.js.map +1 -0
  15. package/dist/bun.d.ts +12 -0
  16. package/dist/bun.d.ts.map +1 -0
  17. package/dist/bun.js +67 -0
  18. package/dist/bun.js.map +1 -0
  19. package/dist/client/index.d.ts +93 -0
  20. package/dist/client/index.d.ts.map +1 -0
  21. package/dist/client/index.js +1329 -0
  22. package/dist/client/index.js.map +1 -0
  23. package/dist/endpoints.js +354 -0
  24. package/dist/endpoints.js.map +1 -0
  25. package/dist/index.d.ts +220 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +10 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/index2.d.ts +23 -0
  30. package/dist/index3.d.ts +98 -0
  31. package/dist/index3.d.ts.map +1 -0
  32. package/dist/index4.d.ts +74 -0
  33. package/dist/index4.d.ts.map +1 -0
  34. package/dist/index5.d.ts +70 -0
  35. package/dist/index5.d.ts.map +1 -0
  36. package/dist/integration.d.ts +19 -0
  37. package/dist/integration.d.ts.map +1 -0
  38. package/dist/integration.js +277 -0
  39. package/dist/integration.js.map +1 -0
  40. package/dist/kept.js +23 -0
  41. package/dist/kept.js.map +1 -0
  42. package/dist/loader.d.ts +15 -0
  43. package/dist/loader.d.ts.map +1 -0
  44. package/dist/loader.js +17 -0
  45. package/dist/loader.js.map +1 -0
  46. package/dist/marks.js +14 -0
  47. package/dist/marks.js.map +1 -0
  48. package/dist/next.d.ts +17 -0
  49. package/dist/next.d.ts.map +1 -0
  50. package/dist/next.js +150 -0
  51. package/dist/next.js.map +1 -0
  52. package/dist/playwright.js +105 -0
  53. package/dist/playwright.js.map +1 -0
  54. package/dist/recommended/index.d.ts +25 -0
  55. package/dist/recommended/index.d.ts.map +1 -0
  56. package/dist/recommended/index.js +19 -0
  57. package/dist/recommended/index.js.map +1 -0
  58. package/dist/recordings/client.d.ts +4 -0
  59. package/dist/recordings/client.d.ts.map +1 -0
  60. package/dist/recordings/client.js +376 -0
  61. package/dist/recordings/client.js.map +1 -0
  62. package/dist/recordings/index.d.ts +2 -0
  63. package/dist/recordings/index.js +3 -0
  64. package/dist/recordings.js +235 -0
  65. package/dist/recordings.js.map +1 -0
  66. package/dist/screenshots/client.d.ts +23 -0
  67. package/dist/screenshots/client.d.ts.map +1 -0
  68. package/dist/screenshots/client.js +76 -0
  69. package/dist/screenshots/client.js.map +1 -0
  70. package/dist/screenshots/dom.d.ts +4 -0
  71. package/dist/screenshots/dom.d.ts.map +1 -0
  72. package/dist/screenshots/dom.js +92 -0
  73. package/dist/screenshots/dom.js.map +1 -0
  74. package/dist/screenshots/index.d.ts +2 -0
  75. package/dist/screenshots/index.js +98 -0
  76. package/dist/screenshots/index.js.map +1 -0
  77. package/dist/screenshots/rrweb.d.ts +9 -0
  78. package/dist/screenshots/rrweb.d.ts.map +1 -0
  79. package/dist/screenshots/rrweb.js +60 -0
  80. package/dist/screenshots/rrweb.js.map +1 -0
  81. package/dist/shortcut.js +63 -0
  82. package/dist/shortcut.js.map +1 -0
  83. package/dist/tailwind/client.d.ts +4 -0
  84. package/dist/tailwind/client.d.ts.map +1 -0
  85. package/dist/tailwind/client.js +613 -0
  86. package/dist/tailwind/client.js.map +1 -0
  87. package/dist/tailwind/index.d.ts +2 -0
  88. package/dist/tailwind/index.js +557 -0
  89. package/dist/tailwind/index.js.map +1 -0
  90. package/dist/tasks/client.d.ts +6 -0
  91. package/dist/tasks/client.d.ts.map +1 -0
  92. package/dist/tasks/client.js +642 -0
  93. package/dist/tasks/client.js.map +1 -0
  94. package/dist/tasks/index.d.ts +159 -0
  95. package/dist/tasks/index.d.ts.map +1 -0
  96. package/dist/tasks/index.js +348 -0
  97. package/dist/tasks/index.js.map +1 -0
  98. package/dist/vite.d.ts +17 -0
  99. package/dist/vite.d.ts.map +1 -0
  100. package/dist/vite.js +44 -0
  101. package/dist/vite.js.map +1 -0
  102. package/dist/voice/client.d.ts +4 -0
  103. package/dist/voice/client.d.ts.map +1 -0
  104. package/dist/voice/client.js +66 -0
  105. package/dist/voice/client.js.map +1 -0
  106. package/dist/voice/index.d.ts +47 -0
  107. package/dist/voice/index.d.ts.map +1 -0
  108. package/dist/voice/index.js +74 -0
  109. package/dist/voice/index.js.map +1 -0
  110. package/dist/waveform.js +93 -0
  111. package/dist/waveform.js.map +1 -0
  112. package/dist/webpack.d.ts +50 -0
  113. package/dist/webpack.d.ts.map +1 -0
  114. package/dist/webpack.js +78 -0
  115. package/dist/webpack.js.map +1 -0
  116. package/package.json +307 -7
  117. package/skills/deictic/SKILL.md +47 -0
  118. package/skills/deictic/references/install.md +81 -0
  119. package/skills/deictic/references/recordings.md +83 -0
  120. package/skills/deictic/references/tasks.md +79 -0
  121. package/skills/deictic/references/watch.md +43 -0
  122. package/skills/deictic/scripts/frame.mjs +62 -0
  123. package/skills/deictic/scripts/lib.mjs +193 -0
  124. package/skills/deictic/scripts/recording.mjs +186 -0
  125. package/skills/deictic/scripts/task.mjs +84 -0
  126. package/skills/deictic/scripts/transcribe.mjs +93 -0
  127. package/skills/deictic/scripts/voice.mjs +50 -0
  128. package/skills/deictic/scripts/watch.mjs +51 -0
  129. package/src/astro.ts +34 -0
  130. package/src/bun.ts +79 -0
  131. package/src/client/index.ts +833 -0
  132. package/src/client/lightbox.ts +256 -0
  133. package/src/client/style.ts +243 -0
  134. package/src/client/tooltip.ts +78 -0
  135. package/src/client/waveform.ts +98 -0
  136. package/src/index.ts +240 -0
  137. package/src/loader.ts +28 -0
  138. package/src/next.ts +133 -0
  139. package/src/plugins/annotations/client.ts +301 -0
  140. package/src/plugins/annotations/draw.ts +169 -0
  141. package/src/plugins/annotations/index.ts +105 -0
  142. package/src/plugins/annotations/svg.ts +61 -0
  143. package/src/plugins/recommended/index.ts +35 -0
  144. package/src/plugins/recordings/client.ts +315 -0
  145. package/src/plugins/recordings/index.ts +174 -0
  146. package/src/plugins/recordings/marks.ts +11 -0
  147. package/src/plugins/recordings/ours.ts +70 -0
  148. package/src/plugins/recordings/replay.ts +139 -0
  149. package/src/plugins/screenshots/client.ts +63 -0
  150. package/src/plugins/screenshots/dom.ts +79 -0
  151. package/src/plugins/screenshots/index.ts +194 -0
  152. package/src/plugins/screenshots/playwright.ts +119 -0
  153. package/src/plugins/screenshots/rrweb.ts +45 -0
  154. package/src/plugins/tailwind/catalog.ts +396 -0
  155. package/src/plugins/tailwind/client.ts +669 -0
  156. package/src/plugins/tailwind/index.ts +267 -0
  157. package/src/plugins/tasks/client.ts +622 -0
  158. package/src/plugins/tasks/index.ts +513 -0
  159. package/src/plugins/voice/client.ts +57 -0
  160. package/src/plugins/voice/index.ts +114 -0
  161. package/src/shortcut.ts +83 -0
  162. package/src/tools/astro.ts +81 -0
  163. package/src/tools/editor.ts +22 -0
  164. package/src/tools/endpoints.ts +163 -0
  165. package/src/tools/history.ts +203 -0
  166. package/src/tools/integration.ts +106 -0
  167. package/src/tools/kept.ts +21 -0
  168. package/src/tools/locate.ts +94 -0
  169. package/src/tools/plugins.ts +41 -0
  170. package/src/tools/source.ts +72 -0
  171. package/src/vite.ts +62 -0
  172. package/src/webpack.ts +107 -0
  173. package/index.js +0 -1
@@ -0,0 +1,235 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { definePlugin } from "./index.js";
5
+ import { t as keptIn } from "./kept.js";
6
+ import { n as MARKS } from "./marks.js";
7
+ // src/plugins/recordings/replay.ts
8
+ /**
9
+ * The replay page, `replay/<id>`: rrweb's own player (`rrweb-player`), its timeline, speeds, skipping idle
10
+ * stretches and fullscreen, sized to the window, with what it doesn't do drawn over it:
11
+ *
12
+ * - The page shows in the colour scheme it was recorded in, whatever the viewer's: the replay's iframe
13
+ * answers `prefers-color-scheme` as the viewer's browser does, so the recorded CSS's queries are rewritten
14
+ * before it's replayed, the recorded scheme's to always match and the other's never.
15
+ * - The marks drawn while recording come as custom events, an SVG in page coordinates each; they're drawn
16
+ * over the replay in the player's own scaled wrapper, moved with its scroll, rather than into its document,
17
+ * which the replayer rebuilds. Each is a marker on the timeline.
18
+ * - The voice clips play in step, at the player's speed. A recording with voice starts paused, as a browser
19
+ * plays sound only after a click.
20
+ *
21
+ * `?t=<seconds>` opens it paused there, and `&bare` without the controls at the recorded size, 1:1, for a
22
+ * screenshot; `?embed` is it filling a frame, with no header of its own (the lightbox's); `body[data-ready]` says
23
+ * it's in place.
24
+ */
25
+ const REPLAY = `<!doctype html>
26
+ <html lang="en">
27
+ <meta charset="utf-8">
28
+ <meta name="viewport" content="width=device-width, initial-scale=1">
29
+ <title>Recording · deictic</title>
30
+ <link rel="stylesheet" href="../player.css">
31
+ <style>
32
+ :root { color-scheme: dark; --accent: #12b358; }
33
+ body { margin: 0; min-height: 100vh; display: flex; flex-direction: column; background: #18181b; color: #fafafa; font: 13px/1.4 system-ui, sans-serif; }
34
+ header { display: flex; gap: 10px; align-items: center; padding: 10px 16px; border-bottom: 1px solid #3f3f46; }
35
+ header a { color: #a1a1aa; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
36
+ main { flex: 1; display: flex; justify-content: center; align-items: flex-start; padding: 16px; }
37
+ body.bare header { display: none; }
38
+ body.bare main { padding: 0; }
39
+ body.embed header { display: none; }
40
+ body.embed main { padding: 0; }
41
+ body.embed #main .rr-player { box-shadow: none; border-radius: 0; }
42
+ #marks { position: absolute; left: 0; top: 0; pointer-events: none; z-index: 3; }
43
+ #marks svg { position: absolute; left: 0; top: 0; overflow: visible; }
44
+ .problem { color: #f87171; padding: 16px; }
45
+ /* rrweb-player, in the dark of the rest of deictic. Its rules repeat Svelte's scoping class, so these start
46
+ from #main, which outweighs any number of classes. */
47
+ #main .rr-player { background: #27272a; box-shadow: 0 12px 32px rgb(0 0 0 / 0.5); border-radius: 8px; overflow: hidden; }
48
+ body.bare #main .rr-player { box-shadow: none; border-radius: 0; }
49
+ #main .rr-player .rr-player__frame { background: #fff; }
50
+ #main .rr-player .rr-controller { background: #18181b; border-top: 1px solid #3f3f46; border-radius: 0; }
51
+ #main .rr-player .rr-timeline__time { color: #a1a1aa; font: 12px ui-monospace, monospace; }
52
+ #main .rr-player .rr-progress { background: #3f3f46; border-color: #18181b; }
53
+ #main .rr-player .rr-progress__step { background: color-mix(in srgb, var(--accent) 45%, transparent); }
54
+ #main .rr-player .rr-progress__handler { background: var(--accent); }
55
+ #main .rr-player .rr-controller__btns button { color: #e4e4e7; }
56
+ #main .rr-player .rr-controller__btns button:disabled { color: #52525b; }
57
+ #main .rr-player .rr-controller__btns button svg { fill: currentColor; }
58
+ #main .rr-player .rr-controller__btns button.active { color: #04130b; background: var(--accent); }
59
+ #main .rr-player .rr-controller__btns button:active { background: color-mix(in srgb, var(--accent) 60%, transparent); }
60
+ #main .rr-player .switch .label { color: #e4e4e7; }
61
+ #main .rr-player .switch.disabled .label { color: #52525b; }
62
+ #main .rr-player .switch label:before { background: #52525b; }
63
+ #main .rr-player .switch input:checked + label:before { background: var(--accent); }
64
+ </style>
65
+ <header>
66
+ <strong>Recording</strong>
67
+ <a id="page" target="_blank" rel="noreferrer"></a>
68
+ </header>
69
+ <main id="main"></main>
70
+ <script src="../player.js"><\/script>
71
+ <script>
72
+ const params = new URLSearchParams(location.search);
73
+ const bare = params.has('bare');
74
+ const embed = params.has('embed');
75
+ if (bare) document.body.classList.add('bare');
76
+ if (embed) document.body.classList.add('embed');
77
+ const id = location.pathname.split('/').at(-1);
78
+ fetch('../recording/' + id).then((r) => (r.ok ? r.json() : r.text().then((t) => Promise.reject(new Error(t))))).then((kept) => {
79
+ const scheme = kept.colorScheme ?? 'light';
80
+ const events = JSON.parse(
81
+ JSON.stringify(kept.events).replace(/\\(\\s*prefers-color-scheme\\s*:\\s*(light|dark)\\s*\\)/g, (_, s) =>
82
+ s === scheme ? '(min-width: 0px)' : '(max-width: 0px) and (min-width: 1px)',
83
+ ),
84
+ );
85
+ page.textContent = kept.page;
86
+ page.href = kept.page;
87
+
88
+ // A recording with the mic starts paused: a browser plays sound only after a click, which Play is.
89
+ const clips = (kept.voice ?? []).map((c) => ({ ...c, audio: Object.assign(new Audio('../../voice/clip/' + c.id), { preload: 'auto' }) }));
90
+ const t = Number.parseFloat(params.get('t') ?? '');
91
+ // The player's frame, at most the window's room, the controls (80px) under it; 1:1 when bare.
92
+ const size = () => bare
93
+ ? { width: kept.viewport.width, height: kept.viewport.height }
94
+ : embed
95
+ ? { width: innerWidth, height: innerHeight - 80 }
96
+ : { width: Math.min(kept.viewport.width, innerWidth - 32), height: Math.min(kept.viewport.height, innerHeight - 90 - 80 - 16) };
97
+ const Player = rrwebPlayer.default ?? rrwebPlayer.Player ?? rrwebPlayer;
98
+ const player = new Player({
99
+ target: main,
100
+ props: {
101
+ events,
102
+ ...size(),
103
+ autoPlay: !Number.isFinite(t) && clips.length === 0,
104
+ showController: !bare,
105
+ speedOption: [1, 2, 4, 8],
106
+ tags: { ${JSON.stringify(MARKS)}: '#12b358' },
107
+ inactiveColor: '#3f3f46',
108
+ mouseTail: false,
109
+ },
110
+ });
111
+ addEventListener('resize', () => { player.$set(size()); player.triggerResize(); });
112
+ const replayer = player.getReplayer();
113
+ const total = player.getMetaData().totalTime;
114
+
115
+ // 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.
116
+ const marks = Object.assign(document.createElement('div'), { id: 'marks' });
117
+ replayer.wrapper.append(marks);
118
+ replayer.on('custom-event', (e) => { if (e.data.tag === ${JSON.stringify(MARKS)}) marks.innerHTML = e.data.payload.svg; });
119
+
120
+ let playing = false;
121
+ player.addEventListener('ui-update-player-state', (e) => { playing = e.payload === 'playing'; });
122
+ const follow = () => {
123
+ const win = replayer.iframe.contentWindow;
124
+ if (win) marks.style.transform = 'translate(' + -win.scrollX + 'px,' + -win.scrollY + 'px)';
125
+ const now = Math.min(replayer.getCurrentTime(), total);
126
+ const speed = replayer.config.speed ?? 1;
127
+ // Each clip plays while the replay is inside it, at its speed, kept within a few frames of the replay's time.
128
+ for (const c of clips) {
129
+ const into = now - c.at;
130
+ if (!playing || into < 0 || into >= c.duration) { if (!c.audio.paused) c.audio.pause(); continue; }
131
+ if (c.audio.playbackRate !== speed) c.audio.playbackRate = speed;
132
+ if (Math.abs(c.audio.currentTime * 1000 - into) > 250 * speed) c.audio.currentTime = into / 1000;
133
+ if (c.audio.paused) c.audio.play().catch(() => {});
134
+ }
135
+ requestAnimationFrame(follow);
136
+ };
137
+ follow();
138
+
139
+ if (Number.isFinite(t)) player.goto(Math.min(Math.max(0, t * 1000), total), false);
140
+ document.body.dataset.ready = '';
141
+ }).catch((e) => { document.querySelector('main').innerHTML = '<p class="problem"></p>'; document.querySelector('.problem').textContent = e.message; });
142
+ <\/script>
143
+ </html>
144
+ `;
145
+ // src/plugins/recordings/index.ts
146
+ /**
147
+ * `deictic/recordings`: records the page with rrweb, for other plugins to attach (tasks does). No tab of
148
+ * its own: `use('recordings').record()` shows a toolbar on the page (drag it to any edge) with annotate
149
+ * 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
150
+ * recording too, as custom events the replay draws.
151
+ *
152
+ * Recordings are kept under `.deictic/recordings`, the latest `keep`, as JSON: rrweb's
153
+ * events, with the page, its viewport and how long it ran. `replay/<id>` plays one back in the browser.
154
+ */
155
+ const ID = /^[a-z0-9]+-[a-z0-9]+$/;
156
+ /** What one recording may weigh: minutes of a busy page are a few MB. */
157
+ const MAX = 52428800;
158
+ /** rrweb's player (`rrweb-player`), served to the replay page: its build for a script tag, and its styles. */
159
+ const player = (file) => {
160
+ try {
161
+ return join(dirname(createRequire(import.meta.url).resolve("rrweb-player")), file);
162
+ } catch {
163
+ return "";
164
+ }
165
+ };
166
+ function recordings(options = {}) {
167
+ const keep = options.keep ?? 20;
168
+ let dir = "";
169
+ let taken = 0;
170
+ const pathOf = (id) => join(dir, `${id}.json`);
171
+ const read = (id) => {
172
+ if (!ID.test(id) || !existsSync(pathOf(id))) return void 0;
173
+ return {
174
+ data: new Uint8Array(readFileSync(pathOf(id))),
175
+ name: `recording-${id}.json`,
176
+ type: "application/json"
177
+ };
178
+ };
179
+ const keepRecording = (data) => {
180
+ const id = `${Date.now().toString(36).padStart(9, "0")}${(taken++ % 1296).toString(36).padStart(2, "0")}-${crypto.randomUUID().slice(0, 8)}`;
181
+ mkdirSync(dir, { recursive: true });
182
+ writeFileSync(pathOf(id), data);
183
+ const kept = readdirSync(dir).filter((f) => f.endsWith(".json")).toSorted();
184
+ for (const old of kept.slice(0, Math.max(0, kept.length - keep))) rmSync(join(dir, old));
185
+ return id;
186
+ };
187
+ const file = (path, type) => {
188
+ if (!existsSync(path)) return new Response("rrweb-player is missing: add it to your devDependencies", { status: 404 });
189
+ return new Response(readFileSync(path), { headers: { "content-type": type } });
190
+ };
191
+ return definePlugin({
192
+ name: "recordings",
193
+ client: "deictic/recordings/client",
194
+ clientOptions: { masking: {
195
+ blockClass: options.blockClass ?? "rr-block",
196
+ blockSelector: options.blockSelector,
197
+ maskTextClass: options.maskTextClass ?? "rr-mask",
198
+ maskTextSelector: options.maskTextSelector,
199
+ maskAllInputs: options.maskAllInputs ?? false
200
+ } },
201
+ setup: ({ root }) => {
202
+ dir = options.dir === void 0 ? keptIn(root, "recordings") : resolve(root, options.dir);
203
+ return { read };
204
+ },
205
+ routes: {
206
+ add: async (req) => {
207
+ if (!(req.headers.get("content-type") ?? "").startsWith("application/json")) return Response.json({ problem: "send the recording as application/json" }, { status: 415 });
208
+ const body = new Uint8Array(await req.arrayBuffer());
209
+ if (body.byteLength > MAX) return Response.json({ problem: `a recording may weigh ${MAX / 1024 / 1024} MB at most` }, { status: 413 });
210
+ let kept;
211
+ try {
212
+ kept = JSON.parse(new TextDecoder().decode(body));
213
+ } catch {
214
+ return Response.json({ problem: "the recording isn't JSON" }, { status: 400 });
215
+ }
216
+ if (!Array.isArray(kept.events) || kept.events.length === 0) return Response.json({ problem: "the recording has no events: record for a moment longer" }, { status: 400 });
217
+ return Response.json({ id: keepRecording(body) });
218
+ },
219
+ recording: (req) => {
220
+ const found = read(new URL(req.url).pathname.split("/").at(-1) ?? "");
221
+ if (found === void 0) return new Response("no such recording, or not kept any more", { status: 404 });
222
+ return new Response(found.data, { headers: {
223
+ "content-type": found.type,
224
+ "cache-control": "no-store"
225
+ } });
226
+ },
227
+ replay: () => new Response(REPLAY, { headers: { "content-type": "text/html; charset=utf-8" } }),
228
+ "player.js": () => file(player("rrweb-player.umd.min.cjs"), "text/javascript"),
229
+ "player.css": () => file(player("style.css"), "text/css")
230
+ }
231
+ });
232
+ }
233
+ export { recordings as t };
234
+
235
+ //# sourceMappingURL=recordings.js.map
@@ -0,0 +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 */\nimport { MARKS } from './marks.ts';\n\nexport const REPLAY = `<!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.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.js\"></script>\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 = location.pathname.split('/').at(-1);\n fetch('../recording/' + id).then((r) => (r.ok ? r.json() : r.text().then((t) => Promise.reject(new Error(t))))).then((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 = (kept.voice ?? []).map((c) => ({ ...c, audio: Object.assign(new Audio('../../voice/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 { REPLAY } from './replay.ts';\n\nexport { MARKS } from './marks.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(REPLAY, { 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":";;;;;;;;;;;;;;;;;;;;;;;;AAmBA,MAAa,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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K,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,QAAQ,EAAE,SAAS,EAAE,gBAAgB,2BAA2B,EAAE,CAAC;GAC9F,mBAAmB,KAAK,OAAO,0BAA0B,GAAG,iBAAiB;GAC7E,oBAAoB,KAAK,OAAO,WAAW,GAAG,UAAU;EAC1D;CACF,CAAC;AACH"}
@@ -0,0 +1,23 @@
1
+ import { i as CaptureOptions, r as Capture, s as ResolvedMasking, t as Box } from "../index3.js";
2
+ /**
3
+ * What a renderer's page half makes of the element: a body for `add`, its type, and where the element is
4
+ * in the shot. `overlay(area)` is what's drawn over the page in that part of the viewport, in viewport CSS
5
+ * pixels, as an SVG that size, or nothing: the annotations plugin's marks, where it's loaded. The renderer
6
+ * draws it over the shot, as deictic's own layers are left out.
7
+ */
8
+ export type PageCapture = (element: Element, options: {
9
+ area: NonNullable<CaptureOptions['area']>;
10
+ masking: ResolvedMasking;
11
+ renderer: unknown;
12
+ overlay: (area: Box) => string | undefined;
13
+ }) => Promise<{
14
+ body: Blob | string;
15
+ type: string;
16
+ box: Box;
17
+ }>;
18
+ /** Leaves out deictic's own UI: the overlay with its hover outline and any open panel. */
19
+ export declare const notOurs: (node: Node) => boolean;
20
+ /** The element's box, in CSS pixels from the viewport's top left, or from its own for a shot of it alone. */
21
+ export declare function boxOf(element: Element, area: NonNullable<CaptureOptions['area']>): Box;
22
+ export declare function screenshotsClient(capture: PageCapture): import("deictic").ClientPlugin<never, never, Capture>;
23
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","names":[],"sources":["../../src/plugins/screenshots/client.ts"],"mappings":";;;;;;;YAgBY,eACV,SAAS,SACT;EACE,MAAM,YAAY;EAClB,SAAS;EACT;EACA,UAAU,MAAM;MAEf;EAAU,MAAM;EAAe;EAAc,KAAK;;;qBAG1C,UAAO,MAAU;;wBAGd,MAAM,SAAS,SAAS,MAAM,YAAY,0BAA0B;wBAKpE,kBAAkB,SAAS,gCAAW,2BAAA"}
@@ -0,0 +1,76 @@
1
+ import { defineClientPlugin } from "../index.js";
2
+ // src/plugins/screenshots/client.ts
3
+ /**
4
+ * The screenshots plugin's page half, around a renderer's capture: the renderer makes the shot (a PNG,
5
+ * or what its server half makes one of), and this sends it to the plugin's `add` route and answers the
6
+ * `Shot`. A renderer's page module default-exports `screenshotsClient(itsCapture)`.
7
+ */
8
+ /** Leaves out deictic's own UI: the overlay with its hover outline and any open panel. */
9
+ const notOurs = (node) => !(node instanceof Element && node.localName === "deictic-overlay");
10
+ /** The element's box, in CSS pixels from the viewport's top left, or from its own for a shot of it alone. */
11
+ function boxOf(element, area) {
12
+ const { x, y, width, height } = element.getBoundingClientRect();
13
+ return area === "element" ? {
14
+ x: 0,
15
+ y: 0,
16
+ width,
17
+ height
18
+ } : {
19
+ x,
20
+ y,
21
+ width,
22
+ height
23
+ };
24
+ }
25
+ function screenshotsClient(capture) {
26
+ return defineClientPlugin({
27
+ name: "screenshots",
28
+ setup: ({ base, request, options, use }) => {
29
+ const { masking, renderer } = options;
30
+ const overlay = (area) => {
31
+ return use("annotations")?.svg(area);
32
+ };
33
+ const add = async (body, type, { box, size }) => {
34
+ const res = await request("add", {
35
+ method: "POST",
36
+ headers: { "content-type": type },
37
+ body
38
+ });
39
+ const { id, problem } = await res.json();
40
+ if (id === void 0) throw new Error(`screenshots: ${problem ?? res.statusText}`);
41
+ return {
42
+ id,
43
+ url: `${base}__deictic/plugins/screenshots/shot/${id}`,
44
+ box,
45
+ size
46
+ };
47
+ };
48
+ return {
49
+ capture: async (element, { area = "viewport" } = {}) => {
50
+ const { body, type, box } = await capture(element, {
51
+ area,
52
+ masking,
53
+ renderer,
54
+ overlay
55
+ });
56
+ const { clientWidth, clientHeight } = document.documentElement;
57
+ const size = area === "element" ? {
58
+ width: box.width,
59
+ height: box.height
60
+ } : {
61
+ width: clientWidth,
62
+ height: clientHeight
63
+ };
64
+ return add(body, type, {
65
+ box,
66
+ size
67
+ });
68
+ },
69
+ upload: (png, of) => add(png, "image/png", of)
70
+ };
71
+ }
72
+ });
73
+ }
74
+ export { boxOf, notOurs, screenshotsClient };
75
+
76
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","names":[],"sources":["../../src/plugins/screenshots/client.ts"],"sourcesContent":["/**\n * The screenshots plugin's page half, around a renderer's capture: the renderer makes the shot (a PNG,\n * or what its server half makes one of), and this sends it to the plugin's `add` route and answers the\n * `Shot`. A renderer's page module default-exports `screenshotsClient(itsCapture)`.\n */\nimport { defineClientPlugin } from '#src/index.ts';\nimport type { Annotations } from '#src/plugins/annotations/index.ts';\n\nimport type { Box, Capture, CaptureOptions, ResolvedMasking, Shot } from './index.ts';\n\n/**\n * What a renderer's page half makes of the element: a body for `add`, its type, and where the element is\n * in the shot. `overlay(area)` is what's drawn over the page in that part of the viewport, in viewport CSS\n * pixels, as an SVG that size, or nothing: the annotations plugin's marks, where it's loaded. The renderer\n * draws it over the shot, as deictic's own layers are left out.\n */\nexport type PageCapture = (\n element: Element,\n options: {\n area: NonNullable<CaptureOptions['area']>;\n masking: ResolvedMasking;\n renderer: unknown;\n overlay: (area: Box) => string | undefined;\n },\n) => Promise<{ body: Blob | string; type: string; box: Box }>;\n\n/** Leaves out deictic's own UI: the overlay with its hover outline and any open panel. */\nexport const notOurs = (node: Node) => !(node instanceof Element && node.localName === 'deictic-overlay');\n\n/** The element's box, in CSS pixels from the viewport's top left, or from its own for a shot of it alone. */\nexport function boxOf(element: Element, area: NonNullable<CaptureOptions['area']>): Box {\n const { x, y, width, height } = element.getBoundingClientRect();\n return area === 'element' ? { x: 0, y: 0, width, height } : { x, y, width, height };\n}\n\nexport function screenshotsClient(capture: PageCapture) {\n return defineClientPlugin<never, never, Capture>({\n name: 'screenshots',\n setup: ({ base, request, options, use }) => {\n const { masking, renderer } = options as { masking: ResolvedMasking; renderer: unknown };\n // Asked at each shot: the annotations plugin may be set up after this one.\n const overlay = (area: Box) => {\n const marks: Annotations | undefined = use('annotations');\n return marks?.svg(area);\n };\n const add = async (body: Blob | string, type: string, { box, size }: Pick<Shot, 'box' | 'size'>): Promise<Shot> => {\n const res = await request('add', { method: 'POST', headers: { 'content-type': type }, body });\n const { id, problem } = (await res.json()) as { id?: string; problem?: string };\n if (id === undefined) throw new Error(`screenshots: ${problem ?? res.statusText}`);\n return { id, url: `${base}__deictic/plugins/screenshots/shot/${id}`, box, size };\n };\n return {\n capture: async (element, { area = 'viewport' } = {}) => {\n const { body, type, box } = await capture(element, { area, masking, renderer, overlay });\n const { clientWidth, clientHeight } = document.documentElement;\n const size = area === 'element' ? { width: box.width, height: box.height } : { width: clientWidth, height: clientHeight };\n return add(body, type, { box, size });\n },\n upload: (png, of) => add(png, 'image/png', of),\n };\n },\n });\n}\n"],"mappings":";;;;;;;;AA2BA,MAAa,WAAW,SAAe,EAAE,gBAAgB,WAAW,KAAK,cAAc;;AAGvF,SAAgB,MAAM,SAAkB,MAAgD;CACtF,MAAM,EAAE,GAAG,GAAG,OAAO,WAAW,QAAQ,sBAAsB;CAC9D,OAAO,SAAS,YAAY;EAAE,GAAG;EAAG,GAAG;EAAG;EAAO;CAAO,IAAI;EAAE;EAAG;EAAG;EAAO;CAAO;AACpF;AAEA,SAAgB,kBAAkB,SAAsB;CACtD,OAAO,mBAA0C;EAC/C,MAAM;EACN,QAAQ,EAAE,MAAM,SAAS,SAAS,UAAU;GAC1C,MAAM,EAAE,SAAS,aAAa;GAE9B,MAAM,WAAW,SAAc;IAE7B,OADuC,IAAI,aAChC,CAAC,EAAE,IAAI,IAAI;GACxB;GACA,MAAM,MAAM,OAAO,MAAqB,MAAc,EAAE,KAAK,WAAsD;IACjH,MAAM,MAAM,MAAM,QAAQ,OAAO;KAAE,QAAQ;KAAQ,SAAS,EAAE,gBAAgB,KAAK;KAAG;IAAK,CAAC;IAC5F,MAAM,EAAE,IAAI,YAAa,MAAM,IAAI,KAAK;IACxC,IAAI,OAAO,KAAA,GAAW,MAAM,IAAI,MAAM,gBAAgB,WAAW,IAAI,YAAY;IACjF,OAAO;KAAE;KAAI,KAAK,GAAG,KAAK,qCAAqC;KAAM;KAAK;IAAK;GACjF;GACA,OAAO;IACL,SAAS,OAAO,SAAS,EAAE,OAAO,eAAe,CAAC,MAAM;KACtD,MAAM,EAAE,MAAM,MAAM,QAAQ,MAAM,QAAQ,SAAS;MAAE;MAAM;MAAS;MAAU;KAAQ,CAAC;KACvF,MAAM,EAAE,aAAa,iBAAiB,SAAS;KAC/C,MAAM,OAAO,SAAS,YAAY;MAAE,OAAO,IAAI;MAAO,QAAQ,IAAI;KAAO,IAAI;MAAE,OAAO;MAAa,QAAQ;KAAa;KACxH,OAAO,IAAI,MAAM,MAAM;MAAE;MAAK;KAAK,CAAC;IACtC;IACA,SAAS,KAAK,OAAO,IAAI,KAAK,aAAa,EAAE;GAC/C;EACF;CACF,CAAC;AACH"}
@@ -0,0 +1,4 @@
1
+ import { r as Capture } from "../index3.js";
2
+ declare const _default: import("deictic").ClientPlugin<never, never, Capture>;
3
+ export { _default as default };
4
+ //# sourceMappingURL=dom.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dom.d.ts","names":["_$__index_ts0.Capture"],"sources":["../../src/plugins/screenshots/dom.ts"],"mappings":";cAgDA,4B,2BAAAA"}
@@ -0,0 +1,92 @@
1
+ import { boxOf, notOurs, screenshotsClient } from "./client.js";
2
+ // src/plugins/screenshots/dom.ts
3
+ /**
4
+ * The `dom()` renderer's page half: draws the page in the page from its DOM with `modern-screenshot`
5
+ * (imported on the first shot), so it needs no server, but text may lay out a little differently than
6
+ * the page's. Masking changes only the copy that's drawn, never the page.
7
+ */
8
+ const BLANK = "#d4d4d8";
9
+ const selector = (className, extra) => [`.${CSS.escape(className)}`, ...extra ? [extra] : []].join(", ");
10
+ /**
11
+ * Hides in the copy what rrweb would: blocked elements become a blank box their size (the copy keeps each
12
+ * element's size as its styles), masked text keeps its spaces but shows `*`, and so do passwords' values,
13
+ * or every field's.
14
+ */
15
+ function mask(copy, m) {
16
+ if (!(copy instanceof Element)) return;
17
+ const all = (sel) => [...copy.matches(sel) ? [copy] : [], ...copy.querySelectorAll(sel)];
18
+ const stars = (text) => text.replace(/\S/g, "*");
19
+ for (const el of all(selector(m.blockClass, m.blockSelector))) {
20
+ el.replaceChildren();
21
+ if (el instanceof HTMLElement || el instanceof SVGElement) el.style.background = BLANK;
22
+ }
23
+ for (const el of all(selector(m.maskTextClass, m.maskTextSelector))) {
24
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
25
+ for (let text = walker.nextNode(); text !== null; text = walker.nextNode()) text.textContent = stars(text.textContent ?? "");
26
+ }
27
+ for (const field of all("input, textarea")) {
28
+ if (!(field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement)) continue;
29
+ if (!m.maskAllInputs && !(field instanceof HTMLInputElement && field.type === "password")) continue;
30
+ field.value = stars(field.value);
31
+ field.setAttribute("value", field.value);
32
+ if (field instanceof HTMLTextAreaElement) field.textContent = field.value;
33
+ }
34
+ }
35
+ /** Draws an SVG over the whole canvas, which is the area it was made for at the canvas's scale. */
36
+ async function drawOver(canvas, svg) {
37
+ if (svg === void 0) return canvas;
38
+ const image = new Image();
39
+ image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
40
+ await image.decode();
41
+ canvas.getContext("2d")?.drawImage(image, 0, 0, canvas.width, canvas.height);
42
+ return canvas;
43
+ }
44
+ var dom_default = screenshotsClient(async (element, { area, masking, overlay }) => {
45
+ const { domToCanvas } = await import("modern-screenshot").catch((e) => {
46
+ throw new Error("the dom() renderer needs modern-screenshot: add it to your devDependencies", { cause: e });
47
+ });
48
+ const scale = Math.min(devicePixelRatio, 2);
49
+ const options = {
50
+ filter: notOurs,
51
+ scale,
52
+ onCloneNode: (copy) => mask(copy, masking)
53
+ };
54
+ const box = boxOf(element, area);
55
+ const toPng = (canvas) => new Promise((done, fail) => canvas.toBlob((blob) => blob === null ? fail(/* @__PURE__ */ new Error("screenshots: the page drew nothing")) : done(blob), "image/png"));
56
+ if (area === "element") {
57
+ const { x, y, width, height } = element.getBoundingClientRect();
58
+ return {
59
+ body: await toPng(await drawOver(await domToCanvas(element, options), overlay({
60
+ x,
61
+ y,
62
+ width,
63
+ height
64
+ }))),
65
+ type: "image/png",
66
+ box
67
+ };
68
+ }
69
+ const page = await domToCanvas(document.documentElement, options);
70
+ const { clientWidth: width, clientHeight: height } = document.documentElement;
71
+ const at = document.documentElement.getBoundingClientRect();
72
+ const canvas = document.createElement("canvas");
73
+ canvas.width = width * scale;
74
+ canvas.height = height * scale;
75
+ const ctx = canvas.getContext("2d");
76
+ if (ctx === null) throw new Error("screenshots: this browser won't draw to a canvas");
77
+ ctx.drawImage(page, -at.left * scale, -at.top * scale, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
78
+ await drawOver(canvas, overlay({
79
+ x: 0,
80
+ y: 0,
81
+ width,
82
+ height
83
+ }));
84
+ return {
85
+ body: await toPng(canvas),
86
+ type: "image/png",
87
+ box
88
+ };
89
+ });
90
+ export { dom_default as default };
91
+
92
+ //# sourceMappingURL=dom.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dom.js","names":[],"sources":["../../src/plugins/screenshots/dom.ts"],"sourcesContent":["/**\n * The `dom()` renderer's page half: draws the page in the page from its DOM with `modern-screenshot`\n * (imported on the first shot), so it needs no server, but text may lay out a little differently than\n * the page's. Masking changes only the copy that's drawn, never the page.\n */\nimport { boxOf, notOurs, screenshotsClient } from './client.ts';\nimport type { ResolvedMasking } from './index.ts';\n\nconst BLANK = '#d4d4d8';\n\nconst selector = (className: string, extra: string | undefined) => [`.${CSS.escape(className)}`, ...(extra ? [extra] : [])].join(', ');\n\n/**\n * Hides in the copy what rrweb would: blocked elements become a blank box their size (the copy keeps each\n * element's size as its styles), masked text keeps its spaces but shows `*`, and so do passwords' values,\n * or every field's.\n */\nfunction mask(copy: Node, m: ResolvedMasking): void {\n if (!(copy instanceof Element)) return;\n const all = (sel: string) => [...(copy.matches(sel) ? [copy] : []), ...copy.querySelectorAll(sel)];\n const stars = (text: string) => text.replace(/\\S/g, '*');\n for (const el of all(selector(m.blockClass, m.blockSelector))) {\n el.replaceChildren();\n if (el instanceof HTMLElement || el instanceof SVGElement) el.style.background = BLANK;\n }\n for (const el of all(selector(m.maskTextClass, m.maskTextSelector))) {\n const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);\n for (let text = walker.nextNode(); text !== null; text = walker.nextNode()) text.textContent = stars(text.textContent ?? '');\n }\n for (const field of all('input, textarea')) {\n if (!(field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement)) continue;\n if (!m.maskAllInputs && !(field instanceof HTMLInputElement && field.type === 'password')) continue;\n field.value = stars(field.value);\n field.setAttribute('value', field.value);\n if (field instanceof HTMLTextAreaElement) field.textContent = field.value;\n }\n}\n\n/** Draws an SVG over the whole canvas, which is the area it was made for at the canvas's scale. */\nasync function drawOver(canvas: HTMLCanvasElement, svg: string | undefined): Promise<HTMLCanvasElement> {\n if (svg === undefined) return canvas;\n const image = new Image();\n image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;\n await image.decode();\n canvas.getContext('2d')?.drawImage(image, 0, 0, canvas.width, canvas.height);\n return canvas;\n}\n\nexport default screenshotsClient(async (element, { area, masking, overlay }) => {\n const { domToCanvas } = await import('modern-screenshot').catch((e: unknown) => {\n throw new Error('the dom() renderer needs modern-screenshot: add it to your devDependencies', { cause: e });\n });\n // Sharp on a high-density screen, without drawing a long page at more than twice its size.\n const scale = Math.min(devicePixelRatio, 2);\n const options = { filter: notOurs, scale, onCloneNode: (copy: Node) => mask(copy, masking) };\n const box = boxOf(element, area);\n const toPng = (canvas: HTMLCanvasElement) =>\n new Promise<Blob>((done, fail) =>\n canvas.toBlob((blob) => (blob === null ? fail(new Error('screenshots: the page drew nothing')) : done(blob)), 'image/png'),\n );\n if (area === 'element') {\n const { x, y, width, height } = element.getBoundingClientRect();\n const shot = await drawOver(await domToCanvas(element, options), overlay({ x, y, width, height }));\n return { body: await toPng(shot), type: 'image/png', box };\n }\n\n // The whole document, then the part the viewport shows: the document's box is where it scrolled to.\n const page = await domToCanvas(document.documentElement, options);\n const { clientWidth: width, clientHeight: height } = document.documentElement;\n const at = document.documentElement.getBoundingClientRect();\n const canvas = document.createElement('canvas');\n canvas.width = width * scale;\n canvas.height = height * scale;\n const ctx = canvas.getContext('2d');\n if (ctx === null) throw new Error(\"screenshots: this browser won't draw to a canvas\");\n ctx.drawImage(page, -at.left * scale, -at.top * scale, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);\n await drawOver(canvas, overlay({ x: 0, y: 0, width, height }));\n return { body: await toPng(canvas), type: 'image/png', box };\n});\n"],"mappings":";;;;;;;AAQA,MAAM,QAAQ;AAEd,MAAM,YAAY,WAAmB,UAA8B,CAAC,IAAI,IAAI,OAAO,SAAS,KAAK,GAAI,QAAQ,CAAC,KAAK,IAAI,CAAC,CAAE,CAAC,CAAC,KAAK,IAAI;;;;;;AAOrI,SAAS,KAAK,MAAY,GAA0B;CAClD,IAAI,EAAE,gBAAgB,UAAU;CAChC,MAAM,OAAO,QAAgB,CAAC,GAAI,KAAK,QAAQ,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AC7D,CAAC"}
@@ -0,0 +1,2 @@
1
+ import { a as Masking, c as Screenshots, d as dom, f as rrweb, i as CaptureOptions, l as ScreenshotsOptions, n as BrowserOptions, o as Renderer, p as screenshots, r as Capture, s as ResolvedMasking, t as Box, u as Shot } from "../index3.js";
2
+ export { Box, BrowserOptions, Capture, CaptureOptions, Masking, Renderer, ResolvedMasking, Screenshots, ScreenshotsOptions, Shot, screenshots as default, screenshots, dom, rrweb };
@@ -0,0 +1,98 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { definePlugin } from "../index.js";
4
+ import { t as keptIn } from "../kept.js";
5
+ // src/plugins/screenshots/index.ts
6
+ /**
7
+ * `deictic/screenshots`: a plugin with no panel, for others to build on. In the page,
8
+ * `use('screenshots').capture(element)` takes what the viewport shows (or the element alone), with
9
+ * nothing of deictic's in it, and says where the element is; on the server, `use('screenshots').read(id)`
10
+ * hands the PNG to another plugin, which the tasks plugin attaches to a task.
11
+ *
12
+ * How a shot is made is its renderer's: `rrweb()` by default, which snapshots the page's DOM and renders it
13
+ * in a browser beside the dev server, so text lays out as the page's does; or `dom()`, which draws the page
14
+ * in the page itself, for a target with no server to render on. A renderer is a page module and, where it
15
+ * renders elsewhere, a `render` here (`Renderer`): another may take pixels from screen sharing or devtools.
16
+ *
17
+ * Shots are kept under `.deictic/screenshots`, the latest `keep` of them, so they outlive a
18
+ * restart of the dev server and stay out of git.
19
+ */
20
+ /** Draws the page in the page, from its DOM (`modern-screenshot`): no server needed, but text may lay out a little differently. */
21
+ const dom = () => ({ client: "deictic/screenshots/dom" });
22
+ /**
23
+ * Snapshots the page's DOM in the page (`rrweb-snapshot`, masking as rrweb does) and renders it in a
24
+ * browser beside the dev server (`playwright-core`), so text lays out as the page's does.
25
+ */
26
+ const rrweb = (options = {}) => ({
27
+ client: "deictic/screenshots/rrweb",
28
+ render: async (input) => (await import("../playwright.js")).render(input, options)
29
+ });
30
+ const ID = /^[a-z0-9]+-[a-z0-9]+$/;
31
+ /** What one PNG, or one snapshot to render, may weigh: a viewport at twice its pixels is a few MB. */
32
+ const MAX = 20971520;
33
+ function screenshots(options = {}) {
34
+ const renderer = options.renderer ?? rrweb();
35
+ const keep = options.keep ?? 100;
36
+ let dir = "";
37
+ let taken = 0;
38
+ const pathOf = (id) => join(dir, `${id}.png`);
39
+ const read = (id) => {
40
+ if (!ID.test(id) || !existsSync(pathOf(id))) return void 0;
41
+ return {
42
+ data: new Uint8Array(readFileSync(pathOf(id))),
43
+ name: `${id}.png`,
44
+ type: "image/png"
45
+ };
46
+ };
47
+ const keepShot = (data) => {
48
+ const id = `${Date.now().toString(36).padStart(9, "0")}${(taken++ % 1296).toString(36).padStart(2, "0")}-${crypto.randomUUID().slice(0, 8)}`;
49
+ mkdirSync(dir, { recursive: true });
50
+ writeFileSync(pathOf(id), data);
51
+ const kept = readdirSync(dir).filter((f) => f.endsWith(".png")).toSorted();
52
+ for (const old of kept.slice(0, Math.max(0, kept.length - keep))) rmSync(join(dir, old));
53
+ return id;
54
+ };
55
+ return definePlugin({
56
+ name: "screenshots",
57
+ client: renderer.client,
58
+ clientOptions: {
59
+ masking: {
60
+ blockClass: options.blockClass ?? "rr-block",
61
+ blockSelector: options.blockSelector,
62
+ maskTextClass: options.maskTextClass ?? "rr-mask",
63
+ maskTextSelector: options.maskTextSelector,
64
+ maskAllInputs: options.maskAllInputs ?? false
65
+ },
66
+ renderer: renderer.clientOptions
67
+ },
68
+ setup: ({ root }) => {
69
+ dir = options.dir === void 0 ? keptIn(root, "screenshots") : resolve(root, options.dir);
70
+ return { read };
71
+ },
72
+ routes: {
73
+ add: async (req) => {
74
+ const type = req.headers.get("content-type") ?? "";
75
+ const body = new Uint8Array(await req.arrayBuffer());
76
+ if (body.byteLength > MAX) return Response.json({ problem: `a shot may weigh ${MAX / 1024 / 1024} MB at most` }, { status: 413 });
77
+ if (type === "image/png") return Response.json({ id: keepShot(body) });
78
+ if (renderer.render === void 0 || !type.startsWith("application/json")) return Response.json({ problem: "send the shot as image/png" }, { status: 415 });
79
+ try {
80
+ return Response.json({ id: keepShot(await renderer.render(JSON.parse(new TextDecoder().decode(body)))) });
81
+ } catch (e) {
82
+ return Response.json({ problem: e instanceof Error ? e.message : String(e) }, { status: 500 });
83
+ }
84
+ },
85
+ shot: (req) => {
86
+ const shot = read(new URL(req.url).pathname.split("/").at(-1) ?? "");
87
+ if (shot === void 0) return new Response("no such shot, or not kept any more", { status: 404 });
88
+ return new Response(shot.data, { headers: {
89
+ "content-type": shot.type,
90
+ "cache-control": "no-store"
91
+ } });
92
+ }
93
+ }
94
+ });
95
+ }
96
+ export { screenshots as default, screenshots, dom, rrweb };
97
+
98
+ //# sourceMappingURL=index.js.map