deictic 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +167 -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 +95 -0
  20. package/dist/client/index.d.ts.map +1 -0
  21. package/dist/client/index.js +1333 -0
  22. package/dist/client/index.js.map +1 -0
  23. package/dist/index.d.ts +23 -0
  24. package/dist/index.js +10 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/loader.d.ts +15 -0
  27. package/dist/loader.d.ts.map +1 -0
  28. package/dist/loader.js +17 -0
  29. package/dist/loader.js.map +1 -0
  30. package/dist/next.d.ts +17 -0
  31. package/dist/next.d.ts.map +1 -0
  32. package/dist/next.js +150 -0
  33. package/dist/next.js.map +1 -0
  34. package/dist/recommended/index.d.ts +25 -0
  35. package/dist/recommended/index.d.ts.map +1 -0
  36. package/dist/recommended/index.js +19 -0
  37. package/dist/recommended/index.js.map +1 -0
  38. package/dist/recordings/client.d.ts +4 -0
  39. package/dist/recordings/client.d.ts.map +1 -0
  40. package/dist/recordings/client.js +376 -0
  41. package/dist/recordings/client.js.map +1 -0
  42. package/dist/recordings/index.d.ts +2 -0
  43. package/dist/recordings/index.js +3 -0
  44. package/dist/screenshots/client.d.ts +23 -0
  45. package/dist/screenshots/client.d.ts.map +1 -0
  46. package/dist/screenshots/client.js +76 -0
  47. package/dist/screenshots/client.js.map +1 -0
  48. package/dist/screenshots/dom.d.ts +4 -0
  49. package/dist/screenshots/dom.d.ts.map +1 -0
  50. package/dist/screenshots/dom.js +92 -0
  51. package/dist/screenshots/dom.js.map +1 -0
  52. package/dist/screenshots/index.d.ts +2 -0
  53. package/dist/screenshots/index.js +98 -0
  54. package/dist/screenshots/index.js.map +1 -0
  55. package/dist/screenshots/rrweb.d.ts +9 -0
  56. package/dist/screenshots/rrweb.d.ts.map +1 -0
  57. package/dist/screenshots/rrweb.js +60 -0
  58. package/dist/screenshots/rrweb.js.map +1 -0
  59. package/dist/shared/endpoints.js +354 -0
  60. package/dist/shared/endpoints.js.map +1 -0
  61. package/dist/shared/index.d.ts +226 -0
  62. package/dist/shared/index.d.ts.map +1 -0
  63. package/dist/shared/index2.d.ts +98 -0
  64. package/dist/shared/index2.d.ts.map +1 -0
  65. package/dist/shared/index3.d.ts +86 -0
  66. package/dist/shared/index3.d.ts.map +1 -0
  67. package/dist/shared/index4.d.ts +184 -0
  68. package/dist/shared/index4.d.ts.map +1 -0
  69. package/dist/shared/index5.d.ts +70 -0
  70. package/dist/shared/index5.d.ts.map +1 -0
  71. package/dist/shared/integration.d.ts +20 -0
  72. package/dist/shared/integration.d.ts.map +1 -0
  73. package/dist/shared/integration.js +279 -0
  74. package/dist/shared/integration.js.map +1 -0
  75. package/dist/shared/kept.js +23 -0
  76. package/dist/shared/kept.js.map +1 -0
  77. package/dist/shared/marks.js +14 -0
  78. package/dist/shared/marks.js.map +1 -0
  79. package/dist/shared/playwright.js +105 -0
  80. package/dist/shared/playwright.js.map +1 -0
  81. package/dist/shared/recordings.js +246 -0
  82. package/dist/shared/recordings.js.map +1 -0
  83. package/dist/shared/shortcut.js +63 -0
  84. package/dist/shared/shortcut.js.map +1 -0
  85. package/dist/shared/tasks.js +521 -0
  86. package/dist/shared/tasks.js.map +1 -0
  87. package/dist/shared/waveform.js +93 -0
  88. package/dist/shared/waveform.js.map +1 -0
  89. package/dist/tailwind/client.d.ts +4 -0
  90. package/dist/tailwind/client.d.ts.map +1 -0
  91. package/dist/tailwind/client.js +613 -0
  92. package/dist/tailwind/client.js.map +1 -0
  93. package/dist/tailwind/index.d.ts +2 -0
  94. package/dist/tailwind/index.js +557 -0
  95. package/dist/tailwind/index.js.map +1 -0
  96. package/dist/tasks/client.d.ts +6 -0
  97. package/dist/tasks/client.d.ts.map +1 -0
  98. package/dist/tasks/client.js +642 -0
  99. package/dist/tasks/client.js.map +1 -0
  100. package/dist/tasks/index.d.ts +2 -0
  101. package/dist/tasks/index.js +1 -0
  102. package/dist/vite.d.ts +16 -0
  103. package/dist/vite.d.ts.map +1 -0
  104. package/dist/vite.js +61 -0
  105. package/dist/vite.js.map +1 -0
  106. package/dist/voice/client.d.ts +4 -0
  107. package/dist/voice/client.d.ts.map +1 -0
  108. package/dist/voice/client.js +66 -0
  109. package/dist/voice/client.js.map +1 -0
  110. package/dist/voice/index.d.ts +47 -0
  111. package/dist/voice/index.d.ts.map +1 -0
  112. package/dist/voice/index.js +74 -0
  113. package/dist/voice/index.js.map +1 -0
  114. package/dist/webpack.d.ts +50 -0
  115. package/dist/webpack.d.ts.map +1 -0
  116. package/dist/webpack.js +78 -0
  117. package/dist/webpack.js.map +1 -0
  118. package/package.json +307 -7
  119. package/skills/deictic/SKILL.md +47 -0
  120. package/skills/deictic/references/install.md +96 -0
  121. package/skills/deictic/references/recordings.md +83 -0
  122. package/skills/deictic/references/tasks.md +79 -0
  123. package/skills/deictic/references/watch.md +43 -0
  124. package/skills/deictic/scripts/frame.mjs +62 -0
  125. package/skills/deictic/scripts/lib.mjs +211 -0
  126. package/skills/deictic/scripts/recording.mjs +186 -0
  127. package/skills/deictic/scripts/task.mjs +84 -0
  128. package/skills/deictic/scripts/transcribe.mjs +93 -0
  129. package/skills/deictic/scripts/voice.mjs +50 -0
  130. package/skills/deictic/scripts/watch.mjs +51 -0
  131. package/src/astro.ts +34 -0
  132. package/src/bun.ts +79 -0
  133. package/src/client/index.ts +846 -0
  134. package/src/client/lightbox.ts +256 -0
  135. package/src/client/style.ts +243 -0
  136. package/src/client/tooltip.ts +78 -0
  137. package/src/client/waveform.ts +98 -0
  138. package/src/index.ts +247 -0
  139. package/src/loader.ts +28 -0
  140. package/src/next.ts +133 -0
  141. package/src/plugins/annotations/client.ts +301 -0
  142. package/src/plugins/annotations/draw.ts +169 -0
  143. package/src/plugins/annotations/index.ts +105 -0
  144. package/src/plugins/annotations/svg.ts +61 -0
  145. package/src/plugins/recommended/index.ts +35 -0
  146. package/src/plugins/recordings/client.ts +316 -0
  147. package/src/plugins/recordings/index.ts +175 -0
  148. package/src/plugins/recordings/marks.ts +11 -0
  149. package/src/plugins/recordings/ours.ts +70 -0
  150. package/src/plugins/recordings/replay.ts +165 -0
  151. package/src/plugins/screenshots/client.ts +64 -0
  152. package/src/plugins/screenshots/dom.ts +79 -0
  153. package/src/plugins/screenshots/index.ts +194 -0
  154. package/src/plugins/screenshots/playwright.ts +119 -0
  155. package/src/plugins/screenshots/rrweb.ts +45 -0
  156. package/src/plugins/tailwind/catalog.ts +396 -0
  157. package/src/plugins/tailwind/client.ts +669 -0
  158. package/src/plugins/tailwind/index.ts +267 -0
  159. package/src/plugins/tasks/client.ts +622 -0
  160. package/src/plugins/tasks/index.ts +557 -0
  161. package/src/plugins/tasks/local.ts +170 -0
  162. package/src/plugins/voice/client.ts +58 -0
  163. package/src/plugins/voice/index.ts +114 -0
  164. package/src/shortcut.ts +83 -0
  165. package/src/tools/astro.ts +81 -0
  166. package/src/tools/editor.ts +22 -0
  167. package/src/tools/endpoints.ts +163 -0
  168. package/src/tools/history.ts +203 -0
  169. package/src/tools/integration.ts +108 -0
  170. package/src/tools/kept.ts +21 -0
  171. package/src/tools/locate.ts +94 -0
  172. package/src/tools/plugins.ts +41 -0
  173. package/src/tools/source.ts +72 -0
  174. package/src/vite.ts +81 -0
  175. package/src/webpack.ts +107 -0
  176. package/index.js +0 -1
@@ -0,0 +1,316 @@
1
+ /**
2
+ * The recordings plugin's page half: `record()` starts rrweb (imported then) and shows the toolbar, a bar
3
+ * docked to an edge of the window that its grip drags to any other, kept between recordings. It holds the
4
+ * time, annotate mode's tools where that plugin is loaded, and Stop and Discard. Stop sends the events to
5
+ * the `add` route.
6
+ *
7
+ * Nothing of deictic's is recorded: the overlay is blocked, as rrweb blocks. The marks are, as custom
8
+ * events: the page's annotations and the toolbar's own, which go when it does, as SVGs in page
9
+ * coordinates, at the start and at each change.
10
+ */
11
+ import { liveWaveform } from '#src/client/waveform.ts';
12
+ import { defineClientPlugin } from '#src/index.ts';
13
+ import type { ResolvedMasking } from '#src/plugins/screenshots/index.ts';
14
+
15
+ import type { Take } from '#src/plugins/voice/index.ts';
16
+
17
+ import type { Kept, Recorder, Recording, VoiceClip } from './index.ts';
18
+ import { END, MARKS } from './marks.ts';
19
+ import { dropOurs } from './ours.ts';
20
+
21
+ type Edge = 'top' | 'bottom' | 'left' | 'right';
22
+ /** Where the bar is: the edge it's docked to, and how far along it, from 0 to 1. */
23
+ interface Dock {
24
+ edge: Edge;
25
+ along: number;
26
+ }
27
+
28
+ const DOCK = 'deictic:recorder';
29
+ const MARGIN = 12;
30
+
31
+ const STYLE = `
32
+ .recorder { position: fixed; z-index: 2147483647; display: flex; align-items: center; gap: 6px; padding: 6px 8px;
33
+ border: 1px solid var(--deictic-line); border-radius: 10px; background: var(--deictic-bg); color: var(--deictic-fg);
34
+ box-shadow: 0 12px 32px rgb(0 0 0 / 0.35); font: 13px/1.4 system-ui, sans-serif; user-select: none; }
35
+ .recorder.vertical { flex-direction: column; }
36
+ .recorder.vertical .annotations-tools { flex-direction: column; }
37
+ .recorder.vertical .annotations-tools .gap { width: auto; height: 1px; margin: 4px 2px; }
38
+ .recorder .grip { display: inline-flex; padding: 2px; color: var(--deictic-muted); cursor: grab; touch-action: none; }
39
+ .recorder .grip:active { cursor: grabbing; }
40
+ .recorder .grip svg { width: 16px; height: 16px; }
41
+ .recorder .live { display: inline-flex; align-items: center; gap: 6px; font: 12px ui-monospace, monospace; }
42
+ .recorder .dot { width: 8px; height: 8px; border-radius: 50%; background: #ef4444; animation: deictic-blink 1.2s infinite; }
43
+ .recorder .sep { align-self: stretch; width: 1px; background: var(--deictic-line); }
44
+ .recorder.vertical .sep { width: auto; height: 1px; }
45
+ .recorder .icon { display: inline-flex; align-items: center; justify-content: center; padding: 3px 5px; }
46
+ .recorder .icon svg { width: 16px; height: 16px; }
47
+ .recorder .mic[aria-pressed='true'] { background: #ef4444; border-color: #ef4444; color: #fff; }
48
+ .recorder .wave { width: 44px; height: 18px; }
49
+ .recorder.vertical .wave { width: 28px; }
50
+ .recorder .wave[hidden] { display: none; }
51
+ .recorder .mic.problem { border-color: var(--deictic-problem); color: var(--deictic-problem); }
52
+ @keyframes deictic-blink { 50% { opacity: 0.3; } }
53
+ `;
54
+
55
+ const svg = (paths: string) =>
56
+ `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths}</svg>`;
57
+ const GRIP = svg(
58
+ '<circle cx="9" cy="6" r="1"/><circle cx="15" cy="6" r="1"/><circle cx="9" cy="12" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="9" cy="18" r="1"/><circle cx="15" cy="18" r="1"/>',
59
+ );
60
+ const STOP = svg('<rect x="6" y="6" width="12" height="12" rx="1" fill="currentColor"/>');
61
+ const DISCARD = svg('<path d="M6 6l12 12M18 6 6 18"/>');
62
+ const MIC = svg('<rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v3"/>');
63
+
64
+ const clock = (ms: number) => {
65
+ const s = Math.floor(ms / 1000);
66
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
67
+ };
68
+
69
+ function storedDock(): Dock {
70
+ try {
71
+ const dock = JSON.parse(localStorage.getItem(DOCK) ?? 'null') as Dock | null;
72
+ if (dock !== null && ['top', 'bottom', 'left', 'right'].includes(dock.edge) && dock.along >= 0 && dock.along <= 1) return dock;
73
+ } catch {
74
+ // Storage can be off, or hold something else: the default, then.
75
+ }
76
+ return { edge: 'bottom', along: 0.5 };
77
+ }
78
+
79
+ function iconButton(icon: string, name: string, run: () => void): HTMLButtonElement {
80
+ const el = Object.assign(document.createElement('button'), { type: 'button', className: 'icon', title: name, innerHTML: icon });
81
+ el.setAttribute('aria-label', name);
82
+ el.addEventListener('click', run);
83
+ return el;
84
+ }
85
+
86
+ /** Puts the bar on its edge, laid out along it, and how far along. */
87
+ function place(bar: HTMLElement, { edge, along }: Dock): void {
88
+ bar.classList.toggle('vertical', edge === 'left' || edge === 'right');
89
+ const { width, height } = bar.getBoundingClientRect();
90
+ const across = (room: number, size: number) => `${MARGIN + along * Math.max(0, room - size - MARGIN * 2)}px`;
91
+ Object.assign(bar.style, {
92
+ left: edge === 'left' ? `${MARGIN}px` : edge === 'right' ? `${innerWidth - width - MARGIN}px` : across(innerWidth, width),
93
+ top: edge === 'top' ? `${MARGIN}px` : edge === 'bottom' ? `${innerHeight - height - MARGIN}px` : across(innerHeight, height),
94
+ });
95
+ }
96
+
97
+ /** Dragging the bar by its grip, freely; let go, it docks to the nearest edge. */
98
+ function draggable(bar: HTMLElement, grip: HTMLElement, docked: (dock: Dock) => void): void {
99
+ grip.addEventListener('pointerdown', (e) => {
100
+ if (e.button !== 0) return;
101
+ e.preventDefault();
102
+ grip.setPointerCapture(e.pointerId);
103
+ const start = bar.getBoundingClientRect();
104
+ const dx = e.clientX - start.left;
105
+ const dy = e.clientY - start.top;
106
+ const move = (m: PointerEvent) => {
107
+ bar.style.left = `${m.clientX - dx}px`;
108
+ bar.style.top = `${m.clientY - dy}px`;
109
+ };
110
+ const up = () => {
111
+ grip.removeEventListener('pointermove', move);
112
+ const r = bar.getBoundingClientRect();
113
+ const x = r.left + r.width / 2;
114
+ const y = r.top + r.height / 2;
115
+ const away: [Edge, number][] = [
116
+ ['left', x],
117
+ ['right', innerWidth - x],
118
+ ['top', y],
119
+ ['bottom', innerHeight - y],
120
+ ];
121
+ const [edge] = away.reduce((a, b) => (b[1] < a[1] ? b : a));
122
+ const ratio = (at: number, room: number) => Math.min(1, Math.max(0, at / room));
123
+ docked({ edge, along: edge === 'left' || edge === 'right' ? ratio(y, innerHeight) : ratio(x, innerWidth) });
124
+ };
125
+ grip.addEventListener('pointermove', move);
126
+ grip.addEventListener('pointerup', up, { once: true });
127
+ });
128
+ }
129
+
130
+ export default defineClientPlugin<never, never, Recorder>({
131
+ name: 'recordings',
132
+ setup: ({ base, root, options, use, request }) => {
133
+ const { masking } = options as { masking: ResolvedMasking };
134
+ let going = false;
135
+
136
+ const record = async (): Promise<Recording | undefined> => {
137
+ const rrweb = await import('rrweb').catch((e: unknown) => {
138
+ throw new Error('recordings need rrweb: add it to your devDependencies', { cause: e });
139
+ });
140
+ const events: { type: number; data?: unknown }[] = [];
141
+ const startedAt = Date.now();
142
+ const viewport = { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight };
143
+ const colorScheme = matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
144
+ const host = root.host;
145
+ const keep = dropOurs<(typeof events)[number]>(
146
+ () => rrweb.record.mirror.getId(host),
147
+ () => rrweb.record.mirror.getId(document.documentElement),
148
+ );
149
+ const stopRecording = rrweb.record({
150
+ emit: (event) => {
151
+ const kept = keep(event);
152
+ if (kept !== undefined) events.push(kept);
153
+ },
154
+ blockClass: masking.blockClass,
155
+ // deictic's own UI, the overlay: a blocked element is kept as an empty box its size, and it has none.
156
+ blockSelector: ['deictic-overlay', ...(masking.blockSelector ? [masking.blockSelector] : [])].join(', '),
157
+ maskTextClass: masking.maskTextClass,
158
+ ...(masking.maskTextSelector ? { maskTextSelector: masking.maskTextSelector } : {}),
159
+ maskAllInputs: masking.maskAllInputs,
160
+ maskInputOptions: { password: true },
161
+ inlineStylesheet: true,
162
+ });
163
+
164
+ // The marks, now and at each change: an SVG whose view is the page from its top left, at 1:1.
165
+ const marks = use('annotations');
166
+ // The toolbar's own, drawn while recording: shown with the page's, gone when it ends.
167
+ const tools = marks?.tools();
168
+ const mark = () => {
169
+ const area = { x: -scrollX, y: -scrollY, width: 1, height: 1 };
170
+ rrweb.record.addCustomEvent(MARKS, {
171
+ svg: [marks?.svg(area), tools?.marks.svg(area)].filter(Boolean).join(''),
172
+ // The same marks as data, in page coordinates, for whatever reads the recording but doesn't draw it.
173
+ annotations: [...(marks?.list() ?? []), ...(tools?.marks.list() ?? [])],
174
+ });
175
+ };
176
+ mark();
177
+ const unsubscribe = [marks?.subscribe(mark), tools?.marks.subscribe(mark)];
178
+
179
+ return new Promise((done, fail) => {
180
+ const bar = document.createElement('div');
181
+ bar.className = 'recorder';
182
+ bar.setAttribute('role', 'toolbar');
183
+ bar.setAttribute('aria-label', 'Recording');
184
+ const grip = Object.assign(document.createElement('span'), { className: 'grip', title: 'Drag to any edge', innerHTML: GRIP });
185
+ const live = Object.assign(document.createElement('span'), { className: 'live' });
186
+ const dot = Object.assign(document.createElement('span'), { className: 'dot' });
187
+ const time = document.createElement('span');
188
+ live.append(dot, time);
189
+ const sep = () => Object.assign(document.createElement('span'), { className: 'sep' });
190
+
191
+ // The mic, where the voice plugin is loaded: each stretch it's on is a clip, at its time in the recording.
192
+ const voice = use('voice');
193
+ const clips: VoiceClip[] = [];
194
+ let take: Take | undefined;
195
+ // The mic's live waveform beside it while it's on, so it's plain it hears.
196
+ const wave = Object.assign(document.createElement('canvas'), { className: 'wave', hidden: true });
197
+ let stopWave: (() => void) | undefined;
198
+ const unwave = () => {
199
+ stopWave?.();
200
+ stopWave = undefined;
201
+ wave.hidden = true;
202
+ };
203
+ // What the mic is doing (asking for it, keeping a take): the next toggle, and the end, wait for it.
204
+ let busy: Promise<void> = Promise.resolve();
205
+ const micOff = async () => {
206
+ const ending = take;
207
+ take = undefined;
208
+ unwave();
209
+ if (ending === undefined) return;
210
+ try {
211
+ const clip = await ending.stop();
212
+ clips.push({ id: clip.id, at: ending.started - startedAt, duration: clip.duration });
213
+ } catch (e) {
214
+ // The recording is worth keeping without it.
215
+ console.warn('deictic: the voice clip was not kept', e);
216
+ }
217
+ };
218
+ const mic = voice === undefined ? undefined : iconButton(MIC, 'Turn the mic on', () => toggle());
219
+ const toggle = () => {
220
+ busy = busy.then(async () => {
221
+ if (voice === undefined || mic === undefined) return;
222
+ if (take !== undefined) {
223
+ await micOff();
224
+ } else {
225
+ try {
226
+ take = await voice.start();
227
+ mic.classList.remove('problem');
228
+ wave.hidden = false;
229
+ stopWave = liveWaveform(wave, take.stream, { played: '#ef4444', rest: '#52525b' });
230
+ } catch (e) {
231
+ mic.classList.add('problem');
232
+ mic.title = e instanceof Error ? e.message : String(e);
233
+ return;
234
+ }
235
+ }
236
+ const on = take !== undefined;
237
+ mic.setAttribute('aria-pressed', String(on));
238
+ mic.title = on ? 'Turn the mic off' : 'Turn the mic on';
239
+ mic.setAttribute('aria-label', mic.title);
240
+ });
241
+ };
242
+ mic?.classList.add('mic');
243
+ mic?.setAttribute('aria-pressed', 'false');
244
+
245
+ const end = async (keep: boolean) => {
246
+ rrweb.record.addCustomEvent(END, {});
247
+ stopRecording?.();
248
+ for (const stop of unsubscribe) stop?.();
249
+ tools?.close();
250
+ clearInterval(ticking);
251
+ removeEventListener('resize', replace);
252
+ bar.remove();
253
+ await busy;
254
+ if (!keep) {
255
+ unwave();
256
+ take?.cancel();
257
+ return done(undefined);
258
+ }
259
+ await micOff();
260
+ const duration = Date.now() - startedAt;
261
+ const voiced = clips.length > 0 ? { voice: clips } : {};
262
+ const kept: Kept = { page: location.href, viewport, colorScheme, startedAt, duration, events, ...voiced };
263
+ try {
264
+ const res = await request('add', {
265
+ method: 'POST',
266
+ headers: { 'content-type': 'application/json' },
267
+ body: JSON.stringify(kept),
268
+ });
269
+ // `url`: where it replays, said by what keeps it with no server to serve it from (a `standalone` build).
270
+ const { id, url, problem } = (await res.json()) as { id?: string; url?: string; problem?: string };
271
+ if (id === undefined) throw new Error(`recordings: ${problem ?? res.statusText}`);
272
+ done({ id, url: url ?? `${base}__deictic/plugins/recordings/replay/${id}`, duration, ...voiced });
273
+ } catch (e) {
274
+ fail(e);
275
+ }
276
+ };
277
+ const stop = iconButton(STOP, 'Stop, and keep the recording', () => void end(true));
278
+ const discard = iconButton(DISCARD, 'Discard the recording', () => void end(false));
279
+ bar.append(grip, live, ...(tools ? [sep(), tools.element] : []), sep(), ...(mic ? [mic, wave] : []), stop, discard);
280
+ const style = Object.assign(document.createElement('style'), { textContent: STYLE });
281
+ bar.prepend(style);
282
+ root.append(bar);
283
+
284
+ const tick = () => (time.textContent = clock(Date.now() - startedAt));
285
+ tick();
286
+ const ticking = setInterval(tick, 250);
287
+ let dock = storedDock();
288
+ const replace = () => place(bar, dock);
289
+ replace();
290
+ addEventListener('resize', replace);
291
+ draggable(bar, grip, (next) => {
292
+ dock = next;
293
+ replace();
294
+ try {
295
+ localStorage.setItem(DOCK, JSON.stringify(dock));
296
+ } catch {
297
+ // Not kept, then: the next recording starts at the bottom.
298
+ }
299
+ });
300
+ });
301
+ };
302
+
303
+ return {
304
+ recording: () => going,
305
+ record: async () => {
306
+ if (going) throw new Error('recordings: one is going already: stop it first');
307
+ going = true;
308
+ try {
309
+ return await record();
310
+ } finally {
311
+ going = false;
312
+ }
313
+ },
314
+ };
315
+ },
316
+ });
@@ -0,0 +1,175 @@
1
+ /**
2
+ * `deictic/recordings`: records the page with rrweb, for other plugins to attach (tasks does). No tab of
3
+ * its own: `use('recordings').record()` shows a toolbar on the page (drag it to any edge) with annotate
4
+ * 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
5
+ * recording too, as custom events the replay draws.
6
+ *
7
+ * Recordings are kept under `.deictic/recordings`, the latest `keep`, as JSON: rrweb's
8
+ * events, with the page, its viewport and how long it ran. `replay/<id>` plays one back in the browser.
9
+ */
10
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
11
+ import { createRequire } from 'node:module';
12
+ import { dirname, join, resolve } from 'node:path';
13
+
14
+ import { definePlugin } from '#src/index.ts';
15
+ import type { Masking, ResolvedMasking } from '#src/plugins/screenshots/index.ts';
16
+ import { keptIn } from '#src/tools/kept.ts';
17
+
18
+ import { replayPage } from './replay.ts';
19
+
20
+ export { MARKS } from './marks.ts';
21
+ export { replayPage, type ReplaySources } from './replay.ts';
22
+
23
+ /** A recording as the page knows it: its ID, where it plays back, and how long it ran, in milliseconds. */
24
+ export interface Recording {
25
+ id: string;
26
+ url: string;
27
+ duration: number;
28
+ /** What the mic took while it was on, where the voice plugin is loaded. */
29
+ voice?: VoiceClip[];
30
+ }
31
+
32
+ /** A stretch of the mic in a recording: the voice plugin's clip, and when it starts in the recording, in milliseconds. */
33
+ export interface VoiceClip {
34
+ id: string;
35
+ at: number;
36
+ duration: number;
37
+ }
38
+
39
+ /** The page's half, for other plugins' page halves. */
40
+ export interface Recorder {
41
+ /**
42
+ * Records the page, with the toolbar, until Stop: answers the recording, kept by the dev server, or
43
+ * nothing when it's discarded. Rejects while another is going, or when it couldn't be kept.
44
+ */
45
+ record(): Promise<Recording | undefined>;
46
+ /** Whether one is going. */
47
+ recording(): boolean;
48
+ }
49
+
50
+ /** The server's half, for other plugins' server halves. */
51
+ export interface Recordings {
52
+ /** A recording's JSON, or nothing for one not kept (any more). */
53
+ read(id: string): { data: Uint8Array<ArrayBuffer>; name: string; type: 'application/json' } | undefined;
54
+ }
55
+
56
+ /** What the page sends, and what's kept: rrweb's events and what they can't say. */
57
+ export interface Kept {
58
+ page: string;
59
+ viewport: { width: number; height: number };
60
+ /**
61
+ * The colour scheme the page was in, which rrweb doesn't record: the replay shows it in the same, or a
62
+ * page styled by `prefers-color-scheme` would take the replay's.
63
+ */
64
+ colorScheme?: 'light' | 'dark';
65
+ startedAt: number;
66
+ duration: number;
67
+ events: unknown[];
68
+ /** The mic's clips, played along with the replay. */
69
+ voice?: VoiceClip[];
70
+ }
71
+
72
+ declare module 'deictic' {
73
+ interface ServerApis {
74
+ recordings: Recordings;
75
+ }
76
+ interface ClientApis {
77
+ recordings: Recorder;
78
+ }
79
+ }
80
+
81
+ export interface RecordingsOptions extends Masking {
82
+ /** How many recordings to keep, the latest: 20 by default. */
83
+ keep?: number;
84
+ /** Where they're kept, from the project's root: `.deictic/recordings` by default. */
85
+ dir?: string;
86
+ }
87
+
88
+ const ID = /^[a-z0-9]+-[a-z0-9]+$/;
89
+ /** What one recording may weigh: minutes of a busy page are a few MB. */
90
+ const MAX = 50 * 1024 * 1024;
91
+
92
+ /** rrweb's player (`rrweb-player`), served to the replay page: its build for a script tag, and its styles. */
93
+ const player = (file: string) => {
94
+ try {
95
+ return join(dirname(createRequire(import.meta.url).resolve('rrweb-player')), file);
96
+ } catch {
97
+ // Not installed: `file` answers what to add.
98
+ return '';
99
+ }
100
+ };
101
+
102
+ export function recordings(options: RecordingsOptions = {}) {
103
+ const keep = options.keep ?? 20;
104
+ let dir = '';
105
+ let taken = 0;
106
+ const pathOf = (id: string) => join(dir, `${id}.json`);
107
+ const read: Recordings['read'] = (id) => {
108
+ if (!ID.test(id) || !existsSync(pathOf(id))) return undefined;
109
+ return { data: new Uint8Array(readFileSync(pathOf(id))), name: `recording-${id}.json`, type: 'application/json' };
110
+ };
111
+ const keepRecording = (data: Uint8Array) => {
112
+ // Sorts by when it was made, which is what pruning keeps by: the count orders two in one millisecond.
113
+ const id = `${Date.now().toString(36).padStart(9, '0')}${(taken++ % 1296).toString(36).padStart(2, '0')}-${crypto.randomUUID().slice(0, 8)}`;
114
+ mkdirSync(dir, { recursive: true });
115
+ writeFileSync(pathOf(id), data);
116
+ const kept = readdirSync(dir)
117
+ .filter((f) => f.endsWith('.json'))
118
+ .toSorted();
119
+ for (const old of kept.slice(0, Math.max(0, kept.length - keep))) rmSync(join(dir, old));
120
+ return id;
121
+ };
122
+ const file = (path: string, type: string) => {
123
+ if (!existsSync(path)) return new Response('rrweb-player is missing: add it to your devDependencies', { status: 404 });
124
+ return new Response(readFileSync(path), { headers: { 'content-type': type } });
125
+ };
126
+
127
+ return definePlugin<never, never, never, Recordings>({
128
+ name: 'recordings',
129
+ client: 'deictic/recordings/client',
130
+ clientOptions: {
131
+ masking: {
132
+ blockClass: options.blockClass ?? 'rr-block',
133
+ blockSelector: options.blockSelector,
134
+ maskTextClass: options.maskTextClass ?? 'rr-mask',
135
+ maskTextSelector: options.maskTextSelector,
136
+ maskAllInputs: options.maskAllInputs ?? false,
137
+ } satisfies ResolvedMasking,
138
+ },
139
+ setup: ({ root }) => {
140
+ dir = options.dir === undefined ? keptIn(root, 'recordings') : resolve(root, options.dir);
141
+ return { read };
142
+ },
143
+ routes: {
144
+ // What the page recorded, as JSON.
145
+ add: async (req) => {
146
+ if (!(req.headers.get('content-type') ?? '').startsWith('application/json'))
147
+ return Response.json({ problem: 'send the recording as application/json' }, { status: 415 });
148
+ const body = new Uint8Array(await req.arrayBuffer());
149
+ if (body.byteLength > MAX)
150
+ return Response.json({ problem: `a recording may weigh ${MAX / 1024 / 1024} MB at most` }, { status: 413 });
151
+ let kept: Partial<Kept>;
152
+ try {
153
+ kept = JSON.parse(new TextDecoder().decode(body)) as Partial<Kept>;
154
+ } catch {
155
+ return Response.json({ problem: "the recording isn't JSON" }, { status: 400 });
156
+ }
157
+ if (!Array.isArray(kept.events) || kept.events.length === 0)
158
+ return Response.json({ problem: 'the recording has no events: record for a moment longer' }, { status: 400 });
159
+ return Response.json({ id: keepRecording(body) });
160
+ },
161
+ // `recording/<id>`: the JSON, for the replay page.
162
+ recording: (req) => {
163
+ const found = read(new URL(req.url).pathname.split('/').at(-1) ?? '');
164
+ if (found === undefined) return new Response('no such recording, or not kept any more', { status: 404 });
165
+ return new Response(found.data, { headers: { 'content-type': found.type, 'cache-control': 'no-store' } });
166
+ },
167
+ // `replay/<id>`: a page that plays it back.
168
+ replay: () => new Response(replayPage(), { headers: { 'content-type': 'text/html; charset=utf-8' } }),
169
+ 'player.js': () => file(player('rrweb-player.umd.min.cjs'), 'text/javascript'),
170
+ 'player.css': () => file(player('style.css'), 'text/css'),
171
+ },
172
+ });
173
+ }
174
+
175
+ export default recordings;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The custom event's tag the marks go in: the page's annotations, as an SVG in page coordinates (`svg`),
3
+ * and as the annotations themselves (`annotations`, absent from recordings made before it was added).
4
+ */
5
+ export const MARKS = 'deictic.annotations';
6
+
7
+ /**
8
+ * The custom event a recording ends with: rrweb's timeline lasts as long as its events, so without it a
9
+ * recording of a still page (a voice-over, say) would replay as a moment, and its voice never play.
10
+ */
11
+ export const END = 'deictic.end';
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Keeps deictic's own UI out of a recording. Blocking the overlay keeps it out of the first snapshot,
3
+ * but rrweb watches a blocked host's shadow root all the same, so what's added there later (the toolbar,
4
+ * a note's field) comes as mutations. This drops them, and clicks and input on those nodes, by the IDs
5
+ * rrweb gave them: the host's, and every node added under one of ours.
6
+ *
7
+ * The pointer's moves over them stay, on the page's root instead: the replay moves its cursor only over a
8
+ * node it has, and while a drawing tool is picked the pointer is over ours the whole time.
9
+ */
10
+
11
+ /** The parts of rrweb's events this reads; the rest passes as it is. */
12
+ interface Event {
13
+ type: number;
14
+ data?: unknown;
15
+ }
16
+
17
+ interface Mutation {
18
+ source: 0;
19
+ adds: { parentId: number; node: { id: number } }[];
20
+ removes: { parentId: number; id: number }[];
21
+ texts: { id: number }[];
22
+ attributes: { id: number }[];
23
+ }
24
+
25
+ /** rrweb's numbers: an incremental snapshot, and the sources whose data is a list of pointer positions. */
26
+ const INCREMENTAL = 3;
27
+ const MUTATION = 0;
28
+ const POSITIONS = new Set([1, 6, 12]);
29
+
30
+ /** A filter for `emit`: the event without our nodes, or nothing when nothing else is left in it. */
31
+ export function dropOurs<E extends Event>(hostId: () => number, pageId: () => number): (event: E) => E | undefined {
32
+ const ours = new Set<number>();
33
+ return (event) => {
34
+ if (ours.size === 0) {
35
+ const id = hostId();
36
+ if (id > 0) ours.add(id);
37
+ }
38
+ if (event.type !== INCREMENTAL || typeof event.data !== 'object' || event.data === null) return event;
39
+ const data = event.data as { source: number; id?: number; positions?: { id: number }[] };
40
+
41
+ if (data.source === MUTATION) {
42
+ const m = data as Mutation;
43
+ // Added parents and children come in any order: claim until nothing more is ours.
44
+ for (let grew = true; grew;) {
45
+ grew = false;
46
+ for (const add of m.adds) {
47
+ if (ours.has(add.parentId) && !ours.has(add.node.id)) {
48
+ ours.add(add.node.id);
49
+ grew = true;
50
+ }
51
+ }
52
+ }
53
+ const kept: Mutation = {
54
+ ...m,
55
+ adds: m.adds.filter((a) => !ours.has(a.node.id)),
56
+ removes: m.removes.filter((r) => !ours.has(r.id) && !ours.has(r.parentId)),
57
+ texts: m.texts.filter((t) => !ours.has(t.id)),
58
+ attributes: m.attributes.filter((a) => !ours.has(a.id)),
59
+ };
60
+ const left = kept.adds.length + kept.removes.length + kept.texts.length + kept.attributes.length;
61
+ return left === 0 ? undefined : { ...event, data: kept };
62
+ }
63
+ if (POSITIONS.has(data.source) && Array.isArray(data.positions)) {
64
+ const page = pageId();
65
+ const positions = data.positions.map((p) => (ours.has(p.id) ? { ...p, id: page } : p));
66
+ return { ...event, data: { ...data, positions } };
67
+ }
68
+ return data.id !== undefined && ours.has(data.id) ? undefined : event;
69
+ };
70
+ }