deictic 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/API.md +303 -0
  2. package/README.md +56 -104
  3. package/dist/annotations/index.d.ts +1 -1
  4. package/dist/astro.d.ts +1 -1
  5. package/dist/bun.d.ts +1 -1
  6. package/dist/bun.js +2 -2
  7. package/dist/client/index.d.ts +4 -2
  8. package/dist/client/index.d.ts.map +1 -1
  9. package/dist/client/index.js +130 -16
  10. package/dist/client/index.js.map +1 -1
  11. package/dist/index.d.ts +21 -218
  12. package/dist/index.js.map +1 -1
  13. package/dist/loader.js +1 -1
  14. package/dist/logs/client.d.ts +4 -0
  15. package/dist/logs/client.d.ts.map +1 -0
  16. package/dist/logs/client.js +16 -0
  17. package/dist/logs/client.js.map +1 -0
  18. package/dist/logs/index.d.ts +18 -0
  19. package/dist/logs/index.d.ts.map +1 -0
  20. package/dist/logs/index.js +21 -0
  21. package/dist/logs/index.js.map +1 -0
  22. package/dist/network/client.d.ts +4 -0
  23. package/dist/network/client.d.ts.map +1 -0
  24. package/dist/network/client.js +29 -0
  25. package/dist/network/client.js.map +1 -0
  26. package/dist/network/index.d.ts +2 -0
  27. package/dist/network/index.js +39 -0
  28. package/dist/network/index.js.map +1 -0
  29. package/dist/next.d.ts +1 -1
  30. package/dist/next.js +2 -2
  31. package/dist/recommended/index.d.ts +15 -5
  32. package/dist/recommended/index.d.ts.map +1 -1
  33. package/dist/recommended/index.js +10 -3
  34. package/dist/recommended/index.js.map +1 -1
  35. package/dist/recordings/client.d.ts +1 -1
  36. package/dist/recordings/client.d.ts.map +1 -1
  37. package/dist/recordings/client.js +177 -48
  38. package/dist/recordings/client.js.map +1 -1
  39. package/dist/recordings/index.d.ts +2 -2
  40. package/dist/recordings/index.js +3 -3
  41. package/dist/screenshots/client.d.ts +7 -1
  42. package/dist/screenshots/client.d.ts.map +1 -1
  43. package/dist/screenshots/client.js +36 -4
  44. package/dist/screenshots/client.js.map +1 -1
  45. package/dist/screenshots/dom.d.ts +1 -1
  46. package/dist/screenshots/dom.d.ts.map +1 -1
  47. package/dist/screenshots/dom.js +1 -28
  48. package/dist/screenshots/dom.js.map +1 -1
  49. package/dist/screenshots/index.d.ts +1 -1
  50. package/dist/screenshots/index.js +2 -2
  51. package/dist/screenshots/index.js.map +1 -1
  52. package/dist/screenshots/rrweb.d.ts +2 -2
  53. package/dist/screenshots/rrweb.js +5 -1
  54. package/dist/screenshots/rrweb.js.map +1 -1
  55. package/dist/{endpoints.js → shared/endpoints.js} +1 -1
  56. package/dist/shared/endpoints.js.map +1 -0
  57. package/dist/shared/index.d.ts +238 -0
  58. package/dist/shared/index.d.ts.map +1 -0
  59. package/dist/{index3.d.ts → shared/index2.d.ts} +3 -1
  60. package/dist/shared/index2.d.ts.map +1 -0
  61. package/dist/shared/index3.d.ts +112 -0
  62. package/dist/shared/index3.d.ts.map +1 -0
  63. package/dist/shared/index4.d.ts +64 -0
  64. package/dist/shared/index4.d.ts.map +1 -0
  65. package/dist/shared/index5.d.ts +220 -0
  66. package/dist/shared/index5.d.ts.map +1 -0
  67. package/dist/{index5.d.ts → shared/index6.d.ts} +2 -2
  68. package/dist/shared/index6.d.ts.map +1 -0
  69. package/dist/{integration.d.ts → shared/integration.d.ts} +4 -3
  70. package/dist/shared/integration.d.ts.map +1 -0
  71. package/dist/{integration.js → shared/integration.js} +5 -3
  72. package/dist/shared/integration.js.map +1 -0
  73. package/dist/{kept.js → shared/kept.js} +2 -2
  74. package/dist/shared/kept.js.map +1 -0
  75. package/dist/{marks.js → shared/marks.js} +6 -1
  76. package/dist/shared/marks.js.map +1 -0
  77. package/dist/shared/mask.js +107 -0
  78. package/dist/shared/mask.js.map +1 -0
  79. package/dist/{playwright.js → shared/playwright.js} +19 -4
  80. package/dist/shared/playwright.js.map +1 -0
  81. package/dist/shared/recordings.js +437 -0
  82. package/dist/shared/recordings.js.map +1 -0
  83. package/dist/shared/shortcut.js.map +1 -0
  84. package/dist/shared/tasks.js +632 -0
  85. package/dist/shared/tasks.js.map +1 -0
  86. package/dist/shared/waveform.js.map +1 -0
  87. package/dist/tailwind/client.d.ts +1 -1
  88. package/dist/tailwind/index.d.ts +1 -1
  89. package/dist/tasks/client.d.ts +1 -1
  90. package/dist/tasks/client.d.ts.map +1 -1
  91. package/dist/tasks/client.js +272 -57
  92. package/dist/tasks/client.js.map +1 -1
  93. package/dist/tasks/index.d.ts +2 -159
  94. package/dist/tasks/index.js +1 -348
  95. package/dist/vite.d.ts +11 -12
  96. package/dist/vite.d.ts.map +1 -1
  97. package/dist/vite.js +21 -4
  98. package/dist/vite.js.map +1 -1
  99. package/dist/voice/client.d.ts.map +1 -1
  100. package/dist/voice/client.js +36 -15
  101. package/dist/voice/client.js.map +1 -1
  102. package/dist/voice/index.d.ts +6 -1
  103. package/dist/voice/index.d.ts.map +1 -1
  104. package/dist/voice/index.js +13 -3
  105. package/dist/voice/index.js.map +1 -1
  106. package/dist/webpack.d.ts +1 -1
  107. package/dist/webpack.js +2 -2
  108. package/package.json +41 -2
  109. package/skills/deictic/SKILL.md +20 -14
  110. package/skills/deictic/references/install.md +32 -10
  111. package/skills/deictic/references/recordings.md +29 -0
  112. package/skills/deictic/references/tasks.md +49 -21
  113. package/skills/deictic/references/watch.md +38 -11
  114. package/skills/deictic/scripts/lib.mjs +88 -4
  115. package/skills/deictic/scripts/recording.mjs +84 -4
  116. package/skills/deictic/scripts/task.mjs +36 -7
  117. package/skills/deictic/scripts/vb.mjs +12 -0
  118. package/skills/deictic/scripts/watch.mjs +74 -10
  119. package/src/client/away.ts +105 -0
  120. package/src/client/index.ts +60 -16
  121. package/src/client/style.ts +1 -0
  122. package/src/index.ts +21 -2
  123. package/src/plugins/logs/client.ts +18 -0
  124. package/src/plugins/logs/index.ts +55 -0
  125. package/src/plugins/network/client.ts +30 -0
  126. package/src/plugins/network/index.ts +69 -0
  127. package/src/plugins/network/mask.ts +133 -0
  128. package/src/plugins/recommended/index.ts +14 -1
  129. package/src/plugins/recordings/client.ts +220 -40
  130. package/src/plugins/recordings/index.ts +111 -25
  131. package/src/plugins/recordings/marks.ts +6 -0
  132. package/src/plugins/recordings/replay.ts +159 -10
  133. package/src/plugins/screenshots/client.ts +38 -2
  134. package/src/plugins/screenshots/dom.ts +1 -32
  135. package/src/plugins/screenshots/index.ts +2 -0
  136. package/src/plugins/screenshots/playwright.ts +15 -4
  137. package/src/plugins/screenshots/rrweb.ts +2 -1
  138. package/src/plugins/tasks/client.ts +273 -41
  139. package/src/plugins/tasks/index.ts +207 -47
  140. package/src/plugins/tasks/local.ts +170 -0
  141. package/src/plugins/tasks/watchers.ts +36 -0
  142. package/src/plugins/voice/client.ts +33 -10
  143. package/src/plugins/voice/index.ts +21 -4
  144. package/src/tools/integration.ts +5 -3
  145. package/src/tools/kept.ts +2 -2
  146. package/src/vite.ts +23 -4
  147. package/dist/endpoints.js.map +0 -1
  148. package/dist/index.d.ts.map +0 -1
  149. package/dist/index2.d.ts +0 -23
  150. package/dist/index3.d.ts.map +0 -1
  151. package/dist/index4.d.ts +0 -74
  152. package/dist/index4.d.ts.map +0 -1
  153. package/dist/index5.d.ts.map +0 -1
  154. package/dist/integration.d.ts.map +0 -1
  155. package/dist/integration.js.map +0 -1
  156. package/dist/kept.js.map +0 -1
  157. package/dist/marks.js.map +0 -1
  158. package/dist/playwright.js.map +0 -1
  159. package/dist/recordings.js +0 -235
  160. package/dist/recordings.js.map +0 -1
  161. package/dist/shortcut.js.map +0 -1
  162. package/dist/tasks/index.d.ts.map +0 -1
  163. package/dist/tasks/index.js.map +0 -1
  164. package/dist/waveform.js.map +0 -1
  165. /package/dist/{shortcut.js → shared/shortcut.js} +0 -0
  166. /package/dist/{waveform.js → shared/waveform.js} +0 -0
@@ -1,8 +1,13 @@
1
1
  /**
2
2
  * The recordings plugin's page half: `record()` starts rrweb (imported then) and shows the toolbar, a bar
3
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.
4
+ * time, annotate mode's tools where that plugin is loaded, and Stop and Discard.
5
+ *
6
+ * The events go to the server as they happen (`begin`, a `part` each second, `end` on Stop), and what the next
7
+ * page needs to carry on is kept in the tab's session storage: a reload, or a link to another page of the site,
8
+ * leaves the recording going. The page that loads starts rrweb again under the same ID, which makes it a
9
+ * recording of several pages as rrweb has them (a `Meta` and a snapshot for each), puts the toolbar back with
10
+ * its time running, and turns the mic back on where it was.
6
11
  *
7
12
  * Nothing of deictic's is recorded: the overlay is blocked, as rrweb blocks. The marks are, as custom
8
13
  * events: the page's annotations and the toolbar's own, which go when it does, as SVGs in page
@@ -10,12 +15,13 @@
10
15
  */
11
16
  import { liveWaveform } from '#src/client/waveform.ts';
12
17
  import { defineClientPlugin } from '#src/index.ts';
18
+ import type { Shape } from '#src/plugins/annotations/index.ts';
13
19
  import type { ResolvedMasking } from '#src/plugins/screenshots/index.ts';
14
20
 
15
21
  import type { Take } from '#src/plugins/voice/index.ts';
16
22
 
17
- import type { Kept, Recorder, Recording, VoiceClip } from './index.ts';
18
- import { END, MARKS } from './marks.ts';
23
+ import type { Kept, Meta, Recorder, Recording, RecordPlugin, VoiceClip } from './index.ts';
24
+ import { END, MARKS, PAGE } from './marks.ts';
19
25
  import { dropOurs } from './ours.ts';
20
26
 
21
27
  type Edge = 'top' | 'bottom' | 'left' | 'right';
@@ -26,6 +32,42 @@ interface Dock {
26
32
  }
27
33
 
28
34
  const DOCK = 'deictic:recorder';
35
+ /** Where the recording going on is kept, for the tab's next page to carry on with. */
36
+ const GOING = 'deictic:recording';
37
+ /** How often the events are sent, in milliseconds. */
38
+ const EVERY = 1000;
39
+
40
+ /** A recording going on, as the next page needs it. */
41
+ interface Carried {
42
+ id: string;
43
+ startedAt: number;
44
+ /** The next part's place among the parts. */
45
+ seq: number;
46
+ /** The mic's clips so far, and whether it was on. */
47
+ clips: VoiceClip[];
48
+ mic: boolean;
49
+ /** What was drawn from the toolbar, and on which page: it's about that page, so only a reload of it shows it again. */
50
+ path: string;
51
+ marks: Shape[];
52
+ }
53
+
54
+ function carried(): Carried | undefined {
55
+ try {
56
+ return (JSON.parse(sessionStorage.getItem(GOING) ?? 'null') as Carried | null) ?? undefined;
57
+ } catch {
58
+ // Storage can be off: nothing carries over, then.
59
+ return undefined;
60
+ }
61
+ }
62
+
63
+ function carry(going: Carried | undefined): void {
64
+ try {
65
+ if (going === undefined) sessionStorage.removeItem(GOING);
66
+ else sessionStorage.setItem(GOING, JSON.stringify(going));
67
+ } catch {
68
+ // Not kept, then: a page load ends the recording.
69
+ }
70
+ }
29
71
  const MARGIN = 12;
30
72
 
31
73
  const STYLE = `
@@ -130,27 +172,75 @@ function draggable(bar: HTMLElement, grip: HTMLElement, docked: (dock: Dock) =>
130
172
  export default defineClientPlugin<never, never, Recorder>({
131
173
  name: 'recordings',
132
174
  setup: ({ base, root, options, use, request }) => {
133
- const { masking } = options as { masking: ResolvedMasking };
134
- let going = false;
175
+ const { masking, canvas } = options as { masking: ResolvedMasking; canvas?: false | { fps: number } };
176
+ let going: Promise<Recording | undefined> | undefined;
135
177
 
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 });
178
+ const post = async (route: string, body: unknown, keepalive = false) => {
179
+ const res = await request(route, {
180
+ method: 'POST',
181
+ headers: { 'content-type': 'application/json' },
182
+ body: JSON.stringify(body),
183
+ ...(keepalive ? { keepalive } : {}),
139
184
  });
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';
185
+ // `url`: where it replays, said by what keeps it with no server to serve it from (a `standalone` build).
186
+ const answer = (await res.json()) as { id?: string; url?: string; problem?: string };
187
+ if (answer.id === undefined) throw new Error(`recordings: ${answer.problem ?? res.statusText}`);
188
+ return { id: answer.id, url: answer.url };
189
+ };
190
+
191
+ /** Records until Stop or Discard: a new recording, or `from`, one a page before this started. */
192
+ const record = async (from?: Carried): Promise<Recording | undefined> => {
193
+ const startedAt = from?.startedAt ?? Date.now();
194
+ const begin = async (): Promise<string> => {
195
+ const viewport = { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight };
196
+ const colorScheme = matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
197
+ return (await post('begin', { page: location.href, viewport, colorScheme, startedAt } satisfies Meta)).id;
198
+ };
199
+ // What else goes in the recording, where its plugin is loaded: the console's lines and the page's requests, each
200
+ // rrweb's own plugin, which listens from when rrweb starts until it stops. One that can't be had (its package
201
+ // isn't installed) is said, and the recording goes on without.
202
+ const extra = (name: 'logs' | 'network'): Promise<RecordPlugin | undefined> | undefined =>
203
+ use(name)
204
+ // A page that carries a recording on made requests before this: those of its load are the recording's too.
205
+ ?.plugin({ sinceLoad: from !== undefined })
206
+ .catch((e: unknown) => {
207
+ console.warn(`deictic: this recording has no ${name}`, e);
208
+ return undefined;
209
+ });
210
+ const [rrweb, id, ...extras] = await Promise.all([
211
+ import('rrweb').catch((e: unknown) => {
212
+ throw new Error('recordings need rrweb: add it to your devDependencies', { cause: e });
213
+ }),
214
+ from?.id ?? begin(),
215
+ extra('logs'),
216
+ extra('network'),
217
+ ]);
218
+ const clips: VoiceClip[] = from?.clips ?? [];
219
+ // What the server doesn't have yet, and the place of the next part sent.
220
+ let unsent: { type: number; data?: unknown }[] = [];
221
+ let seq = from?.seq ?? 0;
144
222
  const host = root.host;
145
- const keep = dropOurs<(typeof events)[number]>(
223
+ const keep = dropOurs<(typeof unsent)[number]>(
146
224
  () => rrweb.record.mirror.getId(host),
147
225
  () => rrweb.record.mirror.getId(document.documentElement),
148
226
  );
227
+ // The page's address changing with no load (a router's `pushState`, Back within the app, a hash), which rrweb
228
+ // doesn't record: a custom event, so the recording says where each stretch happened. Nothing tells of
229
+ // `pushState`, so it's read as each event comes, and as the clock ticks for a route that draws nothing.
230
+ let href = location.href;
231
+ const moved = () => {
232
+ if (location.href === href) return;
233
+ href = location.href;
234
+ rrweb.record.addCustomEvent(PAGE, { href });
235
+ };
149
236
  const stopRecording = rrweb.record({
150
237
  emit: (event) => {
238
+ // Before what the new route drew, which is what comes next.
239
+ moved();
151
240
  const kept = keep(event);
152
- if (kept !== undefined) events.push(kept);
241
+ if (kept !== undefined) unsent.push(kept);
153
242
  },
243
+ plugins: extras.filter((plugin) => plugin !== undefined),
154
244
  blockClass: masking.blockClass,
155
245
  // deictic's own UI, the overlay: a blocked element is kept as an empty box its size, and it has none.
156
246
  blockSelector: ['deictic-overlay', ...(masking.blockSelector ? [masking.blockSelector] : [])].join(', '),
@@ -159,12 +249,18 @@ export default defineClientPlugin<never, never, Recorder>({
159
249
  maskAllInputs: masking.maskAllInputs,
160
250
  maskInputOptions: { password: true },
161
251
  inlineStylesheet: true,
252
+ // A canvas as pictures of it, a few a second and only when it changed: rrweb's other way keeps every call
253
+ // drawn on it, for which it wraps each drawing method of every canvas.
254
+ ...(canvas === false || canvas === undefined
255
+ ? {}
256
+ : { recordCanvas: true, sampling: { canvas: canvas.fps }, dataURLOptions: { type: 'image/webp', quality: 0.6 } }),
162
257
  });
163
258
 
164
259
  // The marks, now and at each change: an SVG whose view is the page from its top left, at 1:1.
165
260
  const marks = use('annotations');
166
261
  // The toolbar's own, drawn while recording: shown with the page's, gone when it ends.
167
262
  const tools = marks?.tools();
263
+ if (from?.path === location.pathname) for (const shape of from.marks) tools?.marks.add(shape);
168
264
  const mark = () => {
169
265
  const area = { x: -scrollX, y: -scrollY, width: 1, height: 1 };
170
266
  rrweb.record.addCustomEvent(MARKS, {
@@ -174,7 +270,56 @@ export default defineClientPlugin<never, never, Recorder>({
174
270
  });
175
271
  };
176
272
  mark();
177
- const unsubscribe = [marks?.subscribe(mark), tools?.marks.subscribe(mark)];
273
+
274
+ // The mic, where the voice plugin is loaded: each stretch it's on is a clip, at its time in the recording.
275
+ const voice = use('voice');
276
+ let take: Take | undefined;
277
+ /** What the next page carries on from, kept as it changes: a page that's going has no time to say it then. */
278
+ let over = false;
279
+ const save = () =>
280
+ // Not once it's ended, as its last events go: the next page would carry on with one that's over.
281
+ over ||
282
+ carry({
283
+ id,
284
+ startedAt,
285
+ seq,
286
+ clips,
287
+ mic: take !== undefined,
288
+ path: location.pathname,
289
+ marks: tools?.marks.list().map((a) => a.shape) ?? [],
290
+ });
291
+ const unsubscribe = [
292
+ marks?.subscribe(mark),
293
+ tools?.marks.subscribe(() => {
294
+ mark();
295
+ save();
296
+ }),
297
+ ];
298
+
299
+ // One part at a time, each with its place. A part that didn't arrive goes again with the next, before it.
300
+ let sending: Promise<void> = Promise.resolve();
301
+ const flush = () => {
302
+ const next = sending
303
+ .catch(() => {})
304
+ .then(async () => {
305
+ if (unsent.length === 0) return;
306
+ const part = unsent;
307
+ unsent = [];
308
+ const at = seq++;
309
+ save();
310
+ try {
311
+ await post(`part/${id}?seq=${at}`, part);
312
+ } catch (e) {
313
+ unsent = [...part, ...unsent];
314
+ throw e;
315
+ }
316
+ });
317
+ sending = next;
318
+ return next;
319
+ };
320
+ // A problem is heard at Stop, where it matters: a part that fails meanwhile goes again a second on.
321
+ const flushing = setInterval(() => void flush().catch(() => {}), EVERY);
322
+ save();
178
323
 
179
324
  return new Promise((done, fail) => {
180
325
  const bar = document.createElement('div');
@@ -188,10 +333,6 @@ export default defineClientPlugin<never, never, Recorder>({
188
333
  live.append(dot, time);
189
334
  const sep = () => Object.assign(document.createElement('span'), { className: 'sep' });
190
335
 
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
336
  // The mic's live waveform beside it while it's on, so it's plain it hears.
196
337
  const wave = Object.assign(document.createElement('canvas'), { className: 'wave', hidden: true });
197
338
  let stopWave: (() => void) | undefined;
@@ -237,38 +378,56 @@ export default defineClientPlugin<never, never, Recorder>({
237
378
  mic.setAttribute('aria-pressed', String(on));
238
379
  mic.title = on ? 'Turn the mic off' : 'Turn the mic on';
239
380
  mic.setAttribute('aria-label', mic.title);
381
+ save();
240
382
  });
241
383
  };
242
384
  mic?.classList.add('mic');
243
385
  mic?.setAttribute('aria-pressed', 'false');
386
+ // On, as the page before left it: a browser that was let use the mic gives it again without asking.
387
+ if (from?.mic === true) toggle();
388
+
389
+ // The page is going, for another or for good, with no time to wait for anything: what's sent of the mic's
390
+ // take is its clip, the next page is told where things stand, and the last events go as the page does.
391
+ const leave = () => {
392
+ const spoken = take?.soFar();
393
+ if (take !== undefined && spoken !== undefined)
394
+ clips.push({ id: spoken.id, at: take.started - startedAt, duration: spoken.duration });
395
+ const part = unsent;
396
+ unsent = [];
397
+ const at = seq++;
398
+ save();
399
+ // Not behind `sending`, which a page that's going never gets to: the server orders the parts by their place.
400
+ // A browser sends 64 KB at most for a page that's gone, so a last second busier than that is lost.
401
+ if (part.length > 0) void post(`part/${id}?seq=${at}`, part, true).catch(() => {});
402
+ };
403
+ addEventListener('pagehide', leave);
244
404
 
245
- const end = async (keep: boolean) => {
405
+ const end = async (kept: boolean) => {
246
406
  rrweb.record.addCustomEvent(END, {});
247
407
  stopRecording?.();
248
408
  for (const stop of unsubscribe) stop?.();
249
409
  tools?.close();
410
+ clearInterval(flushing);
250
411
  clearInterval(ticking);
251
412
  removeEventListener('resize', replace);
413
+ removeEventListener('pagehide', leave);
252
414
  bar.remove();
415
+ over = true;
416
+ carry(undefined);
253
417
  await busy;
254
- if (!keep) {
418
+ if (!kept) {
255
419
  unwave();
256
420
  take?.cancel();
421
+ void post(`discard/${id}`, {}).catch(() => {});
257
422
  return done(undefined);
258
423
  }
259
424
  await micOff();
260
425
  const duration = Date.now() - startedAt;
261
426
  const voiced = clips.length > 0 ? { voice: clips } : {};
262
- const kept: Kept = { page: location.href, viewport, colorScheme, startedAt, duration, events, ...voiced };
263
427
  try {
264
- const res = await request('add', {
265
- method: 'POST',
266
- headers: { 'content-type': 'application/json' },
267
- body: JSON.stringify(kept),
268
- });
269
- const { id, problem } = (await res.json()) as { id?: string; problem?: string };
270
- if (id === undefined) throw new Error(`recordings: ${problem ?? res.statusText}`);
271
- done({ id, url: `${base}__deictic/plugins/recordings/replay/${id}`, duration, ...voiced });
428
+ await flush();
429
+ const { url } = await post(`end/${id}`, { duration, ...voiced } satisfies Pick<Kept, 'duration' | 'voice'>);
430
+ done({ id, url: url ?? `${base}__deictic/plugins/recordings/replay/${id}`, duration, ...voiced });
272
431
  } catch (e) {
273
432
  fail(e);
274
433
  }
@@ -280,7 +439,10 @@ export default defineClientPlugin<never, never, Recorder>({
280
439
  bar.prepend(style);
281
440
  root.append(bar);
282
441
 
283
- const tick = () => (time.textContent = clock(Date.now() - startedAt));
442
+ const tick = () => {
443
+ moved();
444
+ time.textContent = clock(Date.now() - startedAt);
445
+ };
284
446
  tick();
285
447
  const ticking = setInterval(tick, 250);
286
448
  let dock = storedDock();
@@ -299,16 +461,34 @@ export default defineClientPlugin<never, never, Recorder>({
299
461
  });
300
462
  };
301
463
 
464
+ const run = (from?: Carried) => {
465
+ const mine = record(from).finally(() => {
466
+ if (going === mine) going = undefined;
467
+ });
468
+ going = mine;
469
+ return mine;
470
+ };
471
+ // One the page before this left going: carried on at once, whoever asks for it later (`going`), or no one.
472
+ const left = carried();
473
+ if (left !== undefined) {
474
+ run(left).catch((e: unknown) => {
475
+ // Not for the page after this to try again.
476
+ carry(undefined);
477
+ console.warn('deictic: the recording did not carry on, or was not kept', e);
478
+ });
479
+ }
480
+ // A page shown again as it was left (Back, out of the browser's cache) knows nothing of what happened since:
481
+ // loaded afresh, it carries on like any other.
482
+ window.addEventListener('pageshow', (e) => {
483
+ if (e.persisted && (going !== undefined || carried() !== undefined)) location.reload();
484
+ });
485
+
302
486
  return {
303
- recording: () => going,
487
+ recording: () => going !== undefined,
488
+ going: () => going,
304
489
  record: async () => {
305
- if (going) throw new Error('recordings: one is going already: stop it first');
306
- going = true;
307
- try {
308
- return await record();
309
- } finally {
310
- going = false;
311
- }
490
+ if (going !== undefined) throw new Error('recordings: one is going already: stop it first');
491
+ return run();
312
492
  },
313
493
  };
314
494
  },
@@ -6,18 +6,25 @@
6
6
  *
7
7
  * Recordings are kept under `.deictic/recordings`, the latest `keep`, as JSON: rrweb's
8
8
  * events, with the page, its viewport and how long it ran. `replay/<id>` plays one back in the browser.
9
+ *
10
+ * The page sends one as it goes (`begin`, then `part/<id>` each second or so, then `end/<id>` or `discard/<id>`),
11
+ * not whole at the end, so it outlasts the page: after a reload, or a link to another page of the site, the next
12
+ * page carries on with the same recording, which then holds each page in turn.
9
13
  */
10
- import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
14
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
11
15
  import { createRequire } from 'node:module';
12
16
  import { dirname, join, resolve } from 'node:path';
13
17
 
18
+ import type { record } from 'rrweb';
19
+
14
20
  import { definePlugin } from '#src/index.ts';
15
21
  import type { Masking, ResolvedMasking } from '#src/plugins/screenshots/index.ts';
16
22
  import { keptIn } from '#src/tools/kept.ts';
17
23
 
18
- import { REPLAY } from './replay.ts';
24
+ import { replayPage } from './replay.ts';
19
25
 
20
26
  export { MARKS } from './marks.ts';
27
+ export { replayPage, type ReplaySources } from './replay.ts';
21
28
 
22
29
  /** A recording as the page knows it: its ID, where it plays back, and how long it ran, in milliseconds. */
23
30
  export interface Recording {
@@ -39,11 +46,26 @@ export interface VoiceClip {
39
46
  export interface Recorder {
40
47
  /**
41
48
  * Records the page, with the toolbar, until Stop: answers the recording, kept by the dev server, or
42
- * nothing when it's discarded. Rejects while another is going, or when it couldn't be kept.
49
+ * nothing when it's discarded. Rejects while another is going, or when it couldn't be kept. A page load
50
+ * doesn't end it: the next page of the site carries on, and `going` there answers what this would have.
43
51
  */
44
52
  record(): Promise<Recording | undefined>;
45
53
  /** Whether one is going. */
46
54
  recording(): boolean;
55
+ /** The one going, as `record` answers it: also one a page before this started, carried on here. */
56
+ going(): Promise<Recording | undefined> | undefined;
57
+ }
58
+
59
+ /** A plugin of rrweb's own, as its `record` takes them: what puts more than the page in a recording. */
60
+ export type RecordPlugin = NonNullable<NonNullable<Parameters<typeof record>[0]>['plugins']>[number];
61
+
62
+ /**
63
+ * What a plugin that adds to recordings answers in the page, under its name (`logs` and `network` do): the
64
+ * recorder asks each it knows for its rrweb plugin as a recording starts, so nothing listens before, or after it stops.
65
+ */
66
+ export interface Recorded {
67
+ /** `sinceLoad`: the recording was going as this page loaded, so what the page did before now is its too. */
68
+ plugin(from: { sinceLoad: boolean }): Promise<RecordPlugin>;
47
69
  }
48
70
 
49
71
  /** The server's half, for other plugins' server halves. */
@@ -52,8 +74,12 @@ export interface Recordings {
52
74
  read(id: string): { data: Uint8Array<ArrayBuffer>; name: string; type: 'application/json' } | undefined;
53
75
  }
54
76
 
55
- /** What the page sends, and what's kept: rrweb's events and what they can't say. */
77
+ /** What a recording says as it begins: all of a `Kept` that's known then. */
78
+ export type Meta = Omit<Kept, 'events' | 'duration' | 'voice'>;
79
+
80
+ /** What's kept: rrweb's events and what they can't say. */
56
81
  export interface Kept {
82
+ /** The page it started on. One that went on to others has each in its events, as rrweb's own: a `Meta`, then a snapshot. */
57
83
  page: string;
58
84
  viewport: { width: number; height: number };
59
85
  /**
@@ -82,11 +108,18 @@ export interface RecordingsOptions extends Masking {
82
108
  keep?: number;
83
109
  /** Where they're kept, from the project's root: `.deictic/recordings` by default. */
84
110
  dir?: string;
111
+ /**
112
+ * What a `<canvas>` draws (a chart, a map, WebGL), which is no part of the page's markup: a picture of each
113
+ * canvas that changed, `fps` times a second, 2 by default. `false` for none, and a canvas replays blank.
114
+ */
115
+ canvas?: boolean | { fps?: number };
85
116
  }
86
117
 
87
118
  const ID = /^[a-z0-9]+-[a-z0-9]+$/;
88
119
  /** What one recording may weigh: minutes of a busy page are a few MB. */
89
120
  const MAX = 50 * 1024 * 1024;
121
+ /** How long a recording nobody ended keeps its parts, in milliseconds. */
122
+ const STALE = 24 * 60 * 60 * 1000;
90
123
 
91
124
  /** rrweb's player (`rrweb-player`), served to the replay page: its build for a script tag, and its styles. */
92
125
  const player = (file: string) => {
@@ -107,16 +140,45 @@ export function recordings(options: RecordingsOptions = {}) {
107
140
  if (!ID.test(id) || !existsSync(pathOf(id))) return undefined;
108
141
  return { data: new Uint8Array(readFileSync(pathOf(id))), name: `recording-${id}.json`, type: 'application/json' };
109
142
  };
110
- const keepRecording = (data: Uint8Array) => {
143
+ const partOf = (id: string) => join(dir, `${id}.part`);
144
+ /** The recording going on that a request names, as its last segment: its ID, or the answer that there's none. */
145
+ const going = (req: Request): string | Response => {
146
+ const id = new URL(req.url).pathname.split('/').at(-1) ?? '';
147
+ if (ID.test(id) && existsSync(partOf(id))) return id;
148
+ return Response.json({ problem: `no recording ${id} is going any more: record again` }, { status: 404 });
149
+ };
150
+ const json = async <T>(req: Request): Promise<T | undefined> => {
151
+ try {
152
+ return (await req.json()) as T;
153
+ } catch {
154
+ return undefined;
155
+ }
156
+ };
157
+ /** A recording begun: its ID, and the file its parts are added to, which starts with what `Kept` says besides the events. */
158
+ const begin = (meta: Meta) => {
111
159
  // Sorts by when it was made, which is what pruning keeps by: the count orders two in one millisecond.
112
160
  const id = `${Date.now().toString(36).padStart(9, '0')}${(taken++ % 1296).toString(36).padStart(2, '0')}-${crypto.randomUUID().slice(0, 8)}`;
113
161
  mkdirSync(dir, { recursive: true });
114
- writeFileSync(pathOf(id), data);
115
- const kept = readdirSync(dir)
162
+ // One nobody ended, as its tab was closed: gone a day on.
163
+ for (const f of readdirSync(dir)) if (f.endsWith('.part') && Date.now() - statSync(join(dir, f)).mtimeMs > STALE) rmSync(join(dir, f));
164
+
165
+ writeFileSync(partOf(id), `${JSON.stringify(meta)}\n`);
166
+ return id;
167
+ };
168
+ /** The parts as one recording, in their order whatever order they came in: a page's last may overtake the one before. */
169
+ const end = (id: string, last: Pick<Kept, 'duration' | 'voice'>): boolean => {
170
+ const [meta, ...lines] = readFileSync(partOf(id), 'utf8').trimEnd().split('\n');
171
+ const parts = lines.map((line) => JSON.parse(line) as { seq: number; events: unknown[] });
172
+ const events = parts.toSorted((a, b) => a.seq - b.seq).flatMap((part) => part.events);
173
+ rmSync(partOf(id));
174
+ if (events.length === 0) return false;
175
+ const kept: Kept = { ...(JSON.parse(meta!) as Meta), ...last, events };
176
+ writeFileSync(pathOf(id), JSON.stringify(kept));
177
+ const all = readdirSync(dir)
116
178
  .filter((f) => f.endsWith('.json'))
117
179
  .toSorted();
118
- for (const old of kept.slice(0, Math.max(0, kept.length - keep))) rmSync(join(dir, old));
119
- return id;
180
+ for (const old of all.slice(0, Math.max(0, all.length - keep))) rmSync(join(dir, old));
181
+ return true;
120
182
  };
121
183
  const file = (path: string, type: string) => {
122
184
  if (!existsSync(path)) return new Response('rrweb-player is missing: add it to your devDependencies', { status: 404 });
@@ -134,28 +196,52 @@ export function recordings(options: RecordingsOptions = {}) {
134
196
  maskTextSelector: options.maskTextSelector,
135
197
  maskAllInputs: options.maskAllInputs ?? false,
136
198
  } satisfies ResolvedMasking,
199
+ canvas: options.canvas === false ? false : { fps: (options.canvas === true ? undefined : options.canvas?.fps) ?? 2 },
137
200
  },
138
201
  setup: ({ root }) => {
139
202
  dir = options.dir === undefined ? keptIn(root, 'recordings') : resolve(root, options.dir);
140
203
  return { read };
141
204
  },
142
205
  routes: {
143
- // What the page recorded, as JSON.
144
- add: async (req) => {
145
- if (!(req.headers.get('content-type') ?? '').startsWith('application/json'))
146
- return Response.json({ problem: 'send the recording as application/json' }, { status: 415 });
147
- const body = new Uint8Array(await req.arrayBuffer());
148
- if (body.byteLength > MAX)
149
- return Response.json({ problem: `a recording may weigh ${MAX / 1024 / 1024} MB at most` }, { status: 413 });
150
- let kept: Partial<Kept>;
151
- try {
152
- kept = JSON.parse(new TextDecoder().decode(body)) as Partial<Kept>;
153
- } catch {
154
- return Response.json({ problem: "the recording isn't JSON" }, { status: 400 });
155
- }
156
- if (!Array.isArray(kept.events) || kept.events.length === 0)
206
+ // A recording starts: the page, its viewport and when. Its events come in parts, as they happen, so a page
207
+ // load in the middle loses none of them, and the next page carries on under the same ID.
208
+ begin: async (req) => {
209
+ const meta = await json<Partial<Meta>>(req);
210
+ if (meta?.viewport === undefined || typeof meta.page !== 'string' || typeof meta.startedAt !== 'number')
211
+ return Response.json({ problem: 'send the page, its viewport and when it started, as JSON' }, { status: 400 });
212
+ const { page, viewport, colorScheme, startedAt } = meta;
213
+ return Response.json({ id: begin({ page, viewport, ...(colorScheme === undefined ? {} : { colorScheme }), startedAt }) });
214
+ },
215
+ // `part/<id>?seq=<n>`: more of its events, a JSON array, and their place among the parts.
216
+ part: async (req) => {
217
+ const id = going(req);
218
+ if (typeof id !== 'string') return id;
219
+ const seq = Number(new URL(req.url).searchParams.get('seq') ?? 'none');
220
+ const events = await json<unknown>(req);
221
+ if (!Array.isArray(events) || !Number.isInteger(seq))
222
+ return Response.json({ problem: 'send the events as a JSON array, and `seq`, their place' }, { status: 400 });
223
+ const line = `${JSON.stringify({ seq, events })}\n`;
224
+ if (statSync(partOf(id)).size + line.length > MAX)
225
+ return Response.json({ problem: `a recording may weigh ${MAX / 1024 / 1024} MB at most: stop this one` }, { status: 413 });
226
+ appendFileSync(partOf(id), line);
227
+ return Response.json({ id });
228
+ },
229
+ // `end/<id>`: it's over, and kept: how long it ran, and the mic's clips.
230
+ end: async (req) => {
231
+ const id = going(req);
232
+ if (typeof id !== 'string') return id;
233
+ const last = await json<Partial<Kept>>(req);
234
+ if (typeof last?.duration !== 'number') return Response.json({ problem: 'send how long it ran, as JSON' }, { status: 400 });
235
+ if (!end(id, { duration: last.duration, ...(last.voice === undefined ? {} : { voice: last.voice }) }))
157
236
  return Response.json({ problem: 'the recording has no events: record for a moment longer' }, { status: 400 });
158
- return Response.json({ id: keepRecording(body) });
237
+ return Response.json({ id });
238
+ },
239
+ // `discard/<id>`: it's over, and not kept.
240
+ discard: (req) => {
241
+ const id = going(req);
242
+ if (typeof id !== 'string') return id;
243
+ rmSync(partOf(id));
244
+ return Response.json({ id });
159
245
  },
160
246
  // `recording/<id>`: the JSON, for the replay page.
161
247
  recording: (req) => {
@@ -164,7 +250,7 @@ export function recordings(options: RecordingsOptions = {}) {
164
250
  return new Response(found.data, { headers: { 'content-type': found.type, 'cache-control': 'no-store' } });
165
251
  },
166
252
  // `replay/<id>`: a page that plays it back.
167
- replay: () => new Response(REPLAY, { headers: { 'content-type': 'text/html; charset=utf-8' } }),
253
+ replay: () => new Response(replayPage(), { headers: { 'content-type': 'text/html; charset=utf-8' } }),
168
254
  'player.js': () => file(player('rrweb-player.umd.min.cjs'), 'text/javascript'),
169
255
  'player.css': () => file(player('style.css'), 'text/css'),
170
256
  },
@@ -4,6 +4,12 @@
4
4
  */
5
5
  export const MARKS = 'deictic.annotations';
6
6
 
7
+ /**
8
+ * The custom event for the page's address changing with no load, as a router does it (`href`, the new one): rrweb
9
+ * records what the route drew, not that the address changed. A page that loads has rrweb's own `Meta` instead.
10
+ */
11
+ export const PAGE = 'deictic.page';
12
+
7
13
  /**
8
14
  * The custom event a recording ends with: rrweb's timeline lasts as long as its events, so without it a
9
15
  * recording of a still page (a voice-over, say) would replay as a moment, and its voice never play.