@vitrinka/web 0.3.3 → 0.4.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 (47) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.md +77 -5
  3. package/build/hud.d.ts +1 -1
  4. package/build/hud.iife.js +46 -9
  5. package/build/protocol/index.d.ts +55 -4
  6. package/build/protocol/index.js +4 -2
  7. package/build/recorder/api.d.ts +25 -5
  8. package/build/recorder/api.js +21 -9
  9. package/build/recorder/attachments.d.ts +19 -0
  10. package/build/recorder/attachments.js +31 -0
  11. package/build/recorder/hud/Hud.d.ts +1 -1
  12. package/build/recorder/hud/Hud.js +43 -10
  13. package/build/recorder/hud/Sheet.d.ts +40 -5
  14. package/build/recorder/hud/Sheet.js +134 -8
  15. package/build/recorder/hud/attach.d.ts +26 -0
  16. package/build/recorder/hud/attach.js +136 -0
  17. package/build/recorder/hud/controller.d.ts +31 -3
  18. package/build/recorder/hud/controller.js +1 -1
  19. package/build/recorder/hud/host.js +2 -0
  20. package/build/recorder/hud/icons.d.ts +3 -0
  21. package/build/recorder/hud/icons.js +7 -0
  22. package/build/recorder/hud/layer.d.ts +4 -1
  23. package/build/recorder/hud/layer.js +11 -3
  24. package/build/recorder/hud/resize.d.ts +83 -0
  25. package/build/recorder/hud/resize.js +236 -0
  26. package/build/recorder/hud/styles.d.ts +1 -1
  27. package/build/recorder/hud/styles.js +38 -1
  28. package/build/recorder/link.d.ts +4 -1
  29. package/build/recorder/link.js +6 -2
  30. package/build/recorder/me.d.ts +7 -0
  31. package/build/recorder/me.js +62 -12
  32. package/build/recorder/page-controller.js +4 -3
  33. package/build/recorder/queue.d.ts +42 -11
  34. package/build/recorder/queue.js +640 -47
  35. package/build/recorder/report.d.ts +9 -0
  36. package/build/recorder/report.js +46 -4
  37. package/build/recorder/session.d.ts +18 -6
  38. package/build/recorder/session.js +59 -29
  39. package/build/recorder/storage/blobs.d.ts +32 -0
  40. package/build/recorder/storage/blobs.js +83 -0
  41. package/build/recorder/storage/index.d.ts +4 -13
  42. package/build/recorder/storage/index.js +12 -6
  43. package/build/recorder/storage/lock.d.ts +2 -0
  44. package/build/recorder/storage/lock.js +48 -0
  45. package/build/recorder/tabs.d.ts +8 -0
  46. package/build/recorder/tabs.js +137 -0
  47. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  import { type ViewRect } from './session';
2
+ import type { HudAttachment } from './hud/controller';
2
3
  /** A mounted pill wants the flight recorder; returns the release. */
3
4
  export declare function wantFlight(): () => void;
4
5
  /**
@@ -8,6 +9,12 @@ export declare function wantFlight(): () => void;
8
9
  export declare function syncFlight(): Promise<void>;
9
10
  /** Can the pill offer "Report a bug" now — into the live session, or with the idle clip? */
10
11
  export declare function canReport(): boolean;
12
+ /**
13
+ * Do the sheets take images now (recorder attachments D6)? Recording: the
14
+ * session's policy read said so. Idle: the flight recorder's did — only the
15
+ * bug report sheet opens then.
16
+ */
17
+ export declare function canAttach(): boolean;
11
18
  export interface ReportNote {
12
19
  /** The description; its first line titles the report session. */
13
20
  text: string;
@@ -15,6 +22,8 @@ export interface ReportNote {
15
22
  rect: ViewRect | null;
16
23
  /** The marked element's selector; '' for a region or no mark. */
17
24
  selector: string;
25
+ /** Images the reporter attached (the HUD's, already normalized). */
26
+ attachments?: readonly HudAttachment[];
18
27
  }
19
28
  /**
20
29
  * The report sheet opened (freeze the last minute — the buffer itself keeps
@@ -1,4 +1,5 @@
1
- import { api, fetchPolicy, uploadChunk } from './api';
1
+ import { api, fetchPolicy, uploadChunk, uploadImage } from './api';
2
+ import { stageAttachments } from './attachments';
2
3
  import { setRedactionPolicy } from './capture/redact';
3
4
  import { checkoutRRWeb } from './capture/rrweb';
4
5
  import { recorderConfig, vitrinkaLinked } from './config';
@@ -12,6 +13,8 @@ let pills = 0;
12
13
  let armed = false;
13
14
  let generation = 0;
14
15
  let arming = Promise.resolve();
16
+ /** The armed buffer's policy read answered `attachments: true`. */
17
+ let flightAttachments = false;
15
18
  /** A mounted pill wants the flight recorder; returns the release. */
16
19
  export function wantFlight() {
17
20
  pills++;
@@ -39,10 +42,11 @@ export function syncFlight() {
39
42
  const gen = ++generation;
40
43
  setRedactionPolicy(null);
41
44
  // fetchPolicy never rejects: null is the engine's safe defaults.
42
- arming = fetchPolicy().then((policy) => {
45
+ arming = fetchPolicy().then(({ policy, attachments }) => {
43
46
  if (!armed || gen !== generation)
44
47
  return;
45
48
  setRedactionPolicy(policy);
49
+ flightAttachments = attachments;
46
50
  startFlightBuffer();
47
51
  notify();
48
52
  });
@@ -50,6 +54,7 @@ export function syncFlight() {
50
54
  else if (!want && armed) {
51
55
  armed = false;
52
56
  generation++;
57
+ flightAttachments = false;
53
58
  stopFlightBuffer();
54
59
  // A session that just started owns the rules now; only an idle page resets them.
55
60
  if (getState() === null)
@@ -64,6 +69,17 @@ export function canReport() {
64
69
  return !rec.paused && !rec.dead;
65
70
  return flightWanted() && flightActive();
66
71
  }
72
+ /**
73
+ * Do the sheets take images now (recorder attachments D6)? Recording: the
74
+ * session's policy read said so. Idle: the flight recorder's did — only the
75
+ * bug report sheet opens then.
76
+ */
77
+ export function canAttach() {
78
+ const rec = getState();
79
+ if (rec)
80
+ return rec.attachments === true;
81
+ return flightAttachments && canReport();
82
+ }
67
83
  let held = null;
68
84
  let job = null;
69
85
  let sending = false;
@@ -133,13 +149,25 @@ function buildJob(clip, note) {
133
149
  const lastLane = clip.lanes.at(-1);
134
150
  if (lastLane)
135
151
  endMs = Math.max(endMs, Date.parse(lastLane.ts));
152
+ const sentAt = new Date().toISOString();
153
+ // Stamped at Send like the note, in its lane; only when the workspace takes them.
154
+ const images = (flightAttachments ? stageAttachments(note.attachments) : []).map((image) => ({
155
+ seq: ++seq,
156
+ ts: sentAt,
157
+ ...tab,
158
+ ...image,
159
+ }));
160
+ if (!flightAttachments && note.attachments?.length) {
161
+ console.warn('vitrinka: this workspace takes no attachments — the report is sent without its images');
162
+ }
136
163
  return {
137
164
  title: reportTitle(note.text),
138
165
  events,
139
166
  chunks,
167
+ images,
140
168
  note: {
141
169
  seq: ++seq,
142
- ts: new Date().toISOString(),
170
+ ts: sentAt,
143
171
  ...tab,
144
172
  kind: 'note',
145
173
  payload: {
@@ -149,6 +177,7 @@ function buildJob(clip, note) {
149
177
  annotate: true,
150
178
  task: true,
151
179
  route: currentRoute.pathname,
180
+ ...(images.length ? { attachments: images.map((image) => image.seq) } : {}),
152
181
  },
153
182
  },
154
183
  durationMs: startMs !== undefined ? Math.max(0, endMs - startMs) : 0,
@@ -193,6 +222,15 @@ const steps = [
193
222
  }
194
223
  await postEvents(j.sessionId, rows);
195
224
  },
225
+ async (j) => {
226
+ // The images the same way, through the screenshot leaf: bytes first, then their rows.
227
+ const rows = [];
228
+ for (const im of j.images) {
229
+ const up = await uploadImage(j.sessionId, im.seq, im.blob);
230
+ rows.push({ seq: im.seq, ts: im.ts, tabId: im.tabId, tabHost: im.tabHost, kind: 'attachment', payload: { ...im.payload }, blobKey: up.blobKey });
231
+ }
232
+ await postEvents(j.sessionId, rows);
233
+ },
196
234
  (j) => postEvents(j.sessionId, [j.note]),
197
235
  async (j) => {
198
236
  const done = await api('PATCH', `/api/v1/sessions/${j.sessionId}`, { status: 'done' });
@@ -211,7 +249,10 @@ export async function sendReport(note) {
211
249
  if (rec) {
212
250
  if (rec.paused || rec.dead)
213
251
  throw new Error('the recording is not capturing — resume it to report');
214
- addAnnotation(note.text, note.rect ?? viewportRect(), note.selector, { task: true });
252
+ addAnnotation(note.text, note.rect ?? viewportRect(), note.selector, {
253
+ task: true,
254
+ ...(note.attachments?.length ? { attachments: note.attachments } : {}),
255
+ });
215
256
  return rec.boardUrl ? { boardUrl: rec.boardUrl } : {};
216
257
  }
217
258
  if (sending)
@@ -252,6 +293,7 @@ export async function sendReport(note) {
252
293
  export function dropFlight() {
253
294
  armed = false;
254
295
  generation++;
296
+ flightAttachments = false;
255
297
  arming = Promise.resolve();
256
298
  held = null;
257
299
  if (!sending)
@@ -13,12 +13,14 @@
13
13
  */
14
14
  import type { RedactionPolicy } from '@vitrinka/redact';
15
15
  import type { SessionDone } from '../protocol';
16
+ import type { HudAttachment } from './hud/controller';
16
17
  import { type SessionState } from './queue';
17
18
  export { currentRoute, notify, subscribe } from './state';
19
+ export { onBeforeStop } from './queue';
18
20
  export type { SessionDone } from '../protocol';
19
21
  /** Sent as `meta.recorder`; bumped with the package version. */
20
- export declare const RECORDER_VERSION = "0.3.3";
21
- export declare const RECORDER_ID = "web/0.3.3";
22
+ export declare const RECORDER_VERSION = "0.4.0";
23
+ export declare const RECORDER_ID = "web/0.4.0";
22
24
  /** What `POST /api/v1/sessions` answers (the fields this recorder keeps). */
23
25
  export interface SessionOut {
24
26
  id: string;
@@ -60,8 +62,14 @@ export declare function createSession(title: string, opts?: {
60
62
  }): Promise<SessionOut>;
61
63
  export declare function startSession(opts?: StartOptions): Promise<SessionState>;
62
64
  export declare function togglePause(): Promise<boolean>;
63
- /** A plain note — `{text, route}`, the extension's shape. */
64
- export declare function addNote(text: string): void;
65
+ /**
66
+ * A plain note — `{text, route}`, the extension's shape. With attachments
67
+ * (recorder attachments) each image becomes an `attachment` event whose seq
68
+ * is allocated just before the note's, in this tab's lane, and the note
69
+ * lists them: `{text, route, attachments: [seq…]}`; `text` may then be
70
+ * empty. Their bytes upload through `/shot` before their rows ride (queue.ts).
71
+ */
72
+ export declare function addNote(text: string, attachments?: readonly HudAttachment[]): void;
65
73
  /** A rect in CSS pixels (viewport coordinates). */
66
74
  export interface ViewRect {
67
75
  x: number;
@@ -76,12 +84,16 @@ export declare function imagePixels(r: ViewRect): ViewRect;
76
84
  * annotate: true}` (+ `task` when the tester chose the task destination);
77
85
  * vitrinka projects it into a board annotation. `selector` is '' for a free
78
86
  * region. The rect is in device pixels. An empty note is still a valid
79
- * annotation, matching the extension.
87
+ * annotation, matching the extension. `attachments` ride as for `addNote`.
80
88
  */
81
89
  export declare function addAnnotation(text: string, rect: ViewRect, selector: string, opts?: {
82
90
  task?: boolean;
91
+ attachments?: readonly HudAttachment[];
83
92
  }): void;
84
- export declare function onBeforeStop(fn: () => void): () => void;
93
+ /**
94
+ * Hooks that run at the top of Stop, before the drain snapshot — the rrweb
95
+ * lane ships its sub-2s tail here so the last DOM events make the session.
96
+ */
85
97
  /**
86
98
  * Stop the session. Throws with the queued-item count when the server is
87
99
  * unreachable — the durable tail is NEVER deleted; capture freezes paused and
@@ -1,17 +1,21 @@
1
1
  import { api, fetchPolicy, permanentStatus, VitrinkaApiError } from './api';
2
+ import { stageAttachments } from './attachments';
2
3
  import { redactUrl, setRedactionPolicy } from './capture/redact';
3
4
  import { recorderConfig } from './config';
4
- import { adoptStoredState, armReconcile, capturesSettled, disarmReconcile, drainBuffer, getState, markStopping, pushEvent, queuedCount, REC_KEY, resetHealth, resetIdle, resetQueues, setState, stoppingElsewhere, } from './queue';
5
+ import { adoptStoredState, armReconcile, capturesSettled, disarmReconcile, drainBuffer, getState, markStopping, persistNow, pruneBlobJournal, pushEvent, queuedCount, REC_KEY, resetHealth, resetIdle, resetQueues, runBeforeStopHooks, setState, stoppingElsewhere, } from './queue';
5
6
  import { awaitBoard, boardUrlOf, forgetRecents, noteRecent, RECENTS_KEY, updateRecent } from './recents';
6
7
  import { currentRoute, notify } from './state';
7
8
  import { getRecorderStorage } from './storage';
9
+ import { recorderPeers, registerRecorderTab, waitForRecorderPeers } from './tabs';
8
10
  export { currentRoute, notify, subscribe } from './state';
11
+ export { onBeforeStop } from './queue';
9
12
  /** Sent as `meta.recorder`; bumped with the package version. */
10
- export const RECORDER_VERSION = '0.3.3';
13
+ export const RECORDER_VERSION = '0.4.0';
11
14
  export const RECORDER_ID = `web/${RECORDER_VERSION}`;
12
15
  /**
13
16
  * Re-apply a RECOVERED session's redaction policy after a reload — and
14
- * re-FETCH it when the original fetch never settled (`policy === undefined`).
17
+ * re-FETCH it when the original fetch never settled (`policy === undefined`),
18
+ * with the `attachments` answer the same read carries.
15
19
  */
16
20
  let policyRecoveryInFlight = false;
17
21
  export function recoverRedactionPolicy() {
@@ -25,14 +29,15 @@ export function recoverRedactionPolicy() {
25
29
  return;
26
30
  policyRecoveryInFlight = true;
27
31
  void fetchPolicy()
28
- .then((policy) => {
32
+ .then(({ policy, attachments }) => {
29
33
  const live = getState();
30
34
  if (live?.sessionId !== rec.sessionId)
31
35
  return;
32
36
  if (live.policy !== undefined)
33
37
  return;
34
38
  setRedactionPolicy(policy);
35
- setState({ ...live, policy });
39
+ setState({ ...live, policy, attachments });
40
+ notify();
36
41
  })
37
42
  .finally(() => {
38
43
  policyRecoveryInFlight = false;
@@ -47,11 +52,13 @@ export function recoverRedactionPolicy() {
47
52
  */
48
53
  export function followOtherTabs() {
49
54
  const storage = getRecorderStorage();
55
+ const participant = registerRecorderTab();
50
56
  const offRec = storage.watch?.(REC_KEY, (raw) => {
51
57
  const had = getState()?.policy;
52
58
  const change = adoptStoredState(raw);
53
59
  if (change === 'unchanged')
54
60
  return;
61
+ participant?.sync();
55
62
  if (change === 'ended')
56
63
  setRedactionPolicy(null);
57
64
  if (change === 'joined') {
@@ -64,11 +71,16 @@ export function followOtherTabs() {
64
71
  if (change === 'updated' && had === undefined && policy !== undefined)
65
72
  setRedactionPolicy(policy);
66
73
  notify();
74
+ if (getState()?.stopping)
75
+ void participant?.settle().catch((error) => {
76
+ console.warn('vitrinka: cross-tab Stop remains unsaved', error);
77
+ });
67
78
  });
68
79
  const offRecents = storage.watch?.(RECENTS_KEY, forgetRecents);
69
80
  return () => {
70
81
  offRec?.();
71
82
  offRecents?.();
83
+ participant?.dispose();
72
84
  };
73
85
  }
74
86
  export function elapsedOf(rec) {
@@ -122,12 +134,14 @@ export async function startSession(opts = {}) {
122
134
  ...(opts.environment ? { environment: opts.environment } : {}),
123
135
  ...(opts.driver ? { meta: { driver: opts.driver } } : {}),
124
136
  });
125
- void policyPromise.then((policy) => {
137
+ void policyPromise.then(({ policy, attachments }) => {
126
138
  const rec = getState();
127
139
  if (rec?.sessionId !== ses.id)
128
140
  return;
129
141
  setRedactionPolicy(policy);
130
- setState({ ...rec, policy });
142
+ setState({ ...rec, policy, attachments });
143
+ // The sheets offer images from here on (canAttach).
144
+ notify();
131
145
  });
132
146
  setState({
133
147
  sessionId: ses.id,
@@ -143,6 +157,8 @@ export async function startSession(opts = {}) {
143
157
  resetQueues();
144
158
  resetHealth();
145
159
  resetIdle();
160
+ // Images an earlier session left in the blob journal (a tab closed mid-upload) never go now.
161
+ void pruneBlobJournal();
146
162
  noteRecent({
147
163
  sessionId: ses.id,
148
164
  title: ses.title,
@@ -196,9 +212,29 @@ export async function togglePause() {
196
212
  return rec.paused;
197
213
  }
198
214
  const route = () => ({ tabId: currentRoute.tabId, tabHost: currentRoute.tabHost });
199
- /** A plain note — `{text, route}`, the extension's shape. */
200
- export function addNote(text) {
201
- pushEvent('note', { text, route: currentRoute.pathname }, route());
215
+ /**
216
+ * The images a note may carry: none unless this session's policy read said
217
+ * `attachments: true` (the workspace switch, D6) — the HUD offers none then,
218
+ * and another caller's are not uploaded against it.
219
+ */
220
+ function imagesOf(list) {
221
+ if (!list?.length)
222
+ return [];
223
+ if (getState()?.attachments !== true) {
224
+ console.warn('vitrinka: this session takes no attachments — the note is sent without its images');
225
+ return [];
226
+ }
227
+ return stageAttachments(list);
228
+ }
229
+ /**
230
+ * A plain note — `{text, route}`, the extension's shape. With attachments
231
+ * (recorder attachments) each image becomes an `attachment` event whose seq
232
+ * is allocated just before the note's, in this tab's lane, and the note
233
+ * lists them: `{text, route, attachments: [seq…]}`; `text` may then be
234
+ * empty. Their bytes upload through `/shot` before their rows ride (queue.ts).
235
+ */
236
+ export function addNote(text, attachments) {
237
+ pushEvent('note', { text, route: currentRoute.pathname }, route(), imagesOf(attachments));
202
238
  }
203
239
  /** Scale a viewport rect to device pixels — the extension's `imageRect` space. */
204
240
  export function imagePixels(r) {
@@ -215,7 +251,7 @@ export function imagePixels(r) {
215
251
  * annotate: true}` (+ `task` when the tester chose the task destination);
216
252
  * vitrinka projects it into a board annotation. `selector` is '' for a free
217
253
  * region. The rect is in device pixels. An empty note is still a valid
218
- * annotation, matching the extension.
254
+ * annotation, matching the extension. `attachments` ride as for `addNote`.
219
255
  */
220
256
  export function addAnnotation(text, rect, selector, opts = {}) {
221
257
  pushEvent('note', {
@@ -225,17 +261,12 @@ export function addAnnotation(text, rect, selector, opts = {}) {
225
261
  annotate: true,
226
262
  route: currentRoute.pathname,
227
263
  ...(opts.task ? { task: true } : {}),
228
- }, route());
264
+ }, route(), imagesOf(opts.attachments));
229
265
  }
230
266
  /**
231
267
  * Hooks that run at the top of Stop, before the drain snapshot — the rrweb
232
268
  * lane ships its sub-2s tail here so the last DOM events make the session.
233
269
  */
234
- const beforeStopHooks = new Set();
235
- export function onBeforeStop(fn) {
236
- beforeStopHooks.add(fn);
237
- return () => beforeStopHooks.delete(fn);
238
- }
239
270
  /**
240
271
  * Stop the session. Throws with the queued-item count when the server is
241
272
  * unreachable — the durable tail is NEVER deleted; capture freezes paused and
@@ -247,32 +278,27 @@ export async function stopSession() {
247
278
  return null;
248
279
  // The recording's length is what the tester saw at Stop, not Stop + drain.
249
280
  const durationMs = elapsedOf(rec);
281
+ const peers = recorderPeers(rec.sessionId);
250
282
  // The other tabs leave rec at the Stop, not when the save ends; a stop
251
283
  // that keeps the session hands it back to them as it now is.
252
284
  markStopping(rec.sessionId, durationMs);
253
285
  try {
254
- return await finishStop(rec, durationMs);
286
+ return await finishStop(rec, durationMs, peers);
255
287
  }
256
288
  finally {
257
289
  markStopping(null);
258
290
  }
259
291
  }
260
- async function finishStop(rec, durationMs) {
292
+ async function finishStop(rec, durationMs, peers) {
261
293
  disarmReconcile();
262
- for (const fn of beforeStopHooks) {
263
- try {
264
- fn();
265
- }
266
- catch (e) {
267
- console.warn('vitrinka: before-stop hook failed', e);
268
- }
269
- }
294
+ runBeforeStopHooks();
270
295
  const completeDeadStop = (reason) => {
271
296
  const kept = queuedCount();
272
297
  updateRecent(rec.sessionId, { status: 'unsaved', durationMs });
273
298
  setState(null);
274
299
  setRedactionPolicy(null);
275
300
  resetQueues();
301
+ void pruneBlobJournal(rec.sessionId);
276
302
  notify();
277
303
  throw new Error(`${reason || 'session rejected by the server'} — recording ended locally` +
278
304
  (kept ? `; ${kept} undelivered item(s) discarded` : ''));
@@ -282,7 +308,8 @@ async function finishStop(rec, durationMs) {
282
308
  if (!(await capturesSettled())) {
283
309
  console.warn('vitrinka: stopping with unsettled captures — a late event may not make this session');
284
310
  }
285
- if (!(await drainBuffer())) {
311
+ const peersSaved = await waitForRecorderPeers(peers, rec.sessionId);
312
+ if (!peersSaved || !(await drainBuffer())) {
286
313
  const live = getState();
287
314
  // Another tab may have moved on to a session of its own meanwhile — never this stop's to hold.
288
315
  const held = live?.sessionId === rec.sessionId ? live : null;
@@ -294,9 +321,10 @@ async function finishStop(rec, durationMs) {
294
321
  held.resumeAt = null;
295
322
  setState(held);
296
323
  }
324
+ persistNow();
297
325
  armReconcile();
298
326
  notify();
299
- throw new Error(`server unreachable — ${queuedCount()} item(s) kept; stop again once online`);
327
+ throw new Error(`${peersSaved ? 'server unreachable' : 'another tab has undelivered captures'} — ${queuedCount()} local item(s) kept; stop again once online`);
300
328
  }
301
329
  let done = null;
302
330
  try {
@@ -324,6 +352,8 @@ async function finishStop(rec, durationMs) {
324
352
  setRedactionPolicy(null);
325
353
  resetQueues();
326
354
  }
355
+ // Every image of it is the server's (or never will be): the journal lets go of the session.
356
+ void pruneBlobJournal(rec.sessionId);
327
357
  notify();
328
358
  return done;
329
359
  }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The blob journal (recorder attachments D4): the bytes of an attached image
3
+ * waiting for upload, kept in IndexedDB so a queued image survives a tab
4
+ * reload the way the KV store's event tail does — the KV store (localStorage,
5
+ * a few MiB) cannot hold image bytes. Keys are `<sessionId>/<document>.<n>`;
6
+ * the queue writes one before the image's event is journaled, reads it back
7
+ * to upload after a reload, and deletes it once the server acknowledged the
8
+ * image's event. Shared by every tab of the origin, like the KV store.
9
+ *
10
+ * Where IndexedDB is absent the journal is memory; where it refuses to open
11
+ * or write (a storage-disabled profile, some private modes, the quota) its
12
+ * calls reject and the queue keeps the bytes in memory. Either way the image
13
+ * still uploads from this document, only the reload guarantee is lost — and
14
+ * the recorder says so.
15
+ */
16
+ export interface RecorderBlobStore {
17
+ /** Survives a reload (false for the memory fallback). */
18
+ readonly durable: boolean;
19
+ put(key: string, blob: Blob): Promise<void>;
20
+ /** null when the key was never written or is gone. */
21
+ get(key: string): Promise<Blob | null>;
22
+ delete(key: string): Promise<void>;
23
+ keys(): Promise<string[]>;
24
+ }
25
+ /** The active journal; lazily IndexedDB, else memory. */
26
+ export declare function getRecorderBlobStore(): RecorderBlobStore;
27
+ /** Install a journal (tests; a host with its own store). */
28
+ export declare function configureRecorderBlobStore(store: RecorderBlobStore): void;
29
+ /** In-memory journal — tests, and the non-durable fallback. */
30
+ export declare function memoryBlobStore(): RecorderBlobStore;
31
+ /** Test-only: forget the installed journal. */
32
+ export declare function __resetBlobStoreForTests(): void;
@@ -0,0 +1,83 @@
1
+ const DB = 'vitrinka.recorder.blobs';
2
+ const STORE = 'blobs';
3
+ let current = null;
4
+ /** The active journal; lazily IndexedDB, else memory. */
5
+ export function getRecorderBlobStore() {
6
+ if (!current)
7
+ current = typeof indexedDB === 'undefined' ? memoryBlobStore() : indexedDbBlobStore();
8
+ return current;
9
+ }
10
+ /** Install a journal (tests; a host with its own store). */
11
+ export function configureRecorderBlobStore(store) {
12
+ current = store;
13
+ }
14
+ /** In-memory journal — tests, and the non-durable fallback. */
15
+ export function memoryBlobStore() {
16
+ const m = new Map();
17
+ return {
18
+ durable: false,
19
+ put: async (k, b) => void m.set(k, b),
20
+ get: async (k) => m.get(k) ?? null,
21
+ delete: async (k) => void m.delete(k),
22
+ keys: async () => [...m.keys()],
23
+ };
24
+ }
25
+ function indexedDbBlobStore() {
26
+ let db;
27
+ const open = () => {
28
+ db ??= new Promise((resolve, reject) => {
29
+ const request = indexedDB.open(DB, 1);
30
+ request.onupgradeneeded = () => request.result.createObjectStore(STORE);
31
+ request.onerror = () => reject(request.error ?? new Error('vitrinka: blob journal did not open'));
32
+ request.onsuccess = () => {
33
+ const opened = request.result;
34
+ opened.onversionchange = () => {
35
+ opened.close();
36
+ db = undefined;
37
+ };
38
+ // Closed by the browser (site data cleared, a lost IndexedDB server): the next call reopens.
39
+ opened.onclose = () => {
40
+ db = undefined;
41
+ };
42
+ resolve(opened);
43
+ };
44
+ }).catch((error) => {
45
+ db = undefined;
46
+ throw error;
47
+ });
48
+ return db;
49
+ };
50
+ const run = async (mode, op) => {
51
+ const conn = open();
52
+ let tx;
53
+ try {
54
+ tx = (await conn).transaction(STORE, mode);
55
+ }
56
+ catch (error) {
57
+ // A connection that closed without a close event (Safari) refuses every transaction: reopen next time.
58
+ if (db === conn)
59
+ db = undefined;
60
+ throw error;
61
+ }
62
+ const request = op(tx.objectStore(STORE));
63
+ return new Promise((resolve, reject) => {
64
+ // A write counts once its transaction commits, not when the request succeeds.
65
+ tx.oncomplete = () => resolve(request.result);
66
+ tx.onabort = tx.onerror = () => reject(tx.error ?? request.error ?? new Error('vitrinka: blob journal transaction failed'));
67
+ });
68
+ };
69
+ return {
70
+ durable: true,
71
+ put: async (k, b) => void (await run('readwrite', (s) => s.put(b, k))),
72
+ get: async (k) => {
73
+ const v = await run('readonly', (s) => s.get(k));
74
+ return v instanceof Blob ? v : null;
75
+ },
76
+ delete: async (k) => void (await run('readwrite', (s) => s.delete(k))),
77
+ keys: async () => (await run('readonly', (s) => s.getAllKeys())).filter((k) => typeof k === 'string'),
78
+ };
79
+ }
80
+ /** Test-only: forget the installed journal. */
81
+ export function __resetBlobStoreForTests() {
82
+ current = null;
83
+ }
@@ -1,16 +1,3 @@
1
- /**
2
- * Pluggable durable KV storage for the recorder's queue and session state.
3
- *
4
- * The queue's correctness leans on SYNCHRONOUS reads/writes: every
5
- * read-modify-write completes in one JS tick, so no async mutex is needed and
6
- * delivery-ack bookkeeping stays race-free. Any driver plugged in here MUST be
7
- * synchronous — which is why the default is `localStorage` and not IndexedDB.
8
- *
9
- * When `localStorage` is unavailable or throws on first touch (Safari private
10
- * mode, a sandboxed iframe, a storage-disabled profile) the recorder falls
11
- * back to the in-memory driver: capture still works for the life of the
12
- * document, only the reload-survival guarantee is lost — and it says so once.
13
- */
14
1
  export interface RecorderStorage {
15
2
  /** Read a value; null/undefined when the key was never written. */
16
3
  getString(key: string): string | null | undefined;
@@ -24,6 +11,10 @@ export interface RecorderStorage {
24
11
  * shares (memory) has nothing to hear.
25
12
  */
26
13
  watch?(key: string, onChange: (value: string | null) => void): () => void;
14
+ /** Run synchronously inside an exclusive cross-document lock. Required when shared across tabs. */
15
+ withLock?(name: string, run: () => void): Promise<void>;
16
+ /** Enumerate this driver's namespaced keys (cross-tab Stop participants). */
17
+ keys?(): string[];
27
18
  }
28
19
  /**
29
20
  * Install a storage driver. Call before the recorder mounts; calling after
@@ -1,18 +1,19 @@
1
1
  /**
2
2
  * Pluggable durable KV storage for the recorder's queue and session state.
3
3
  *
4
- * The queue's correctness leans on SYNCHRONOUS reads/writes: every
5
- * read-modify-write completes in one JS tick, so no async mutex is needed and
6
- * delivery-ack bookkeeping stays race-free. Any driver plugged in here MUST be
7
- * synchronous — which is why the default is `localStorage` and not IndexedDB.
4
+ * Reads/writes are synchronous for queue bookkeeping within one document.
5
+ * A driver shared across documents must also serialize seq allocations:
6
+ * one JS tick in one tab does not exclude a second tab's read-modify-write.
8
7
  *
9
8
  * When `localStorage` is unavailable or throws on first touch (Safari private
10
9
  * mode, a sandboxed iframe, a storage-disabled profile) the recorder falls
11
10
  * back to the in-memory driver: capture still works for the life of the
12
11
  * document, only the reload-survival guarantee is lost — and it says so once.
13
12
  */
14
- // Keys land as `vitrinka.recorder.<key>`: rec · buffer · chunks · link (the
15
- // recorder) and dock · prefs · me · recents (the HUD).
13
+ import { withRecorderLock } from './lock';
14
+ // Keys land as `vitrinka.recorder.<key>`: rec · buffer · chunks · images ·
15
+ // blobs · link (the recorder) and dock · prefs · me · recents (the HUD). An
16
+ // attached image's bytes live in the blob journal (./blobs, IndexedDB).
16
17
  const PREFIX = 'vitrinka.recorder.';
17
18
  let current = null;
18
19
  let used = false;
@@ -47,6 +48,10 @@ export function localRecorderStorage() {
47
48
  getString: (k) => ls.getItem(PREFIX + k),
48
49
  set: (k, v) => ls.setItem(PREFIX + k, v),
49
50
  remove: (k) => ls.removeItem(PREFIX + k),
51
+ withLock: withRecorderLock,
52
+ keys: () => Array.from({ length: ls.length }, (_, i) => ls.key(i))
53
+ .filter((key) => key !== null && key.startsWith(PREFIX))
54
+ .map((key) => key.slice(PREFIX.length)),
50
55
  // localStorage is shared by every tab of the origin; its `storage`
51
56
  // event reaches the OTHER documents only. A clear() (key null) is not
52
57
  // a write of `k` and is ignored.
@@ -72,6 +77,7 @@ export function memoryRecorderStorage() {
72
77
  getString: (k) => m.get(k) ?? null,
73
78
  set: (k, v) => void m.set(k, v),
74
79
  remove: (k) => void m.delete(k),
80
+ keys: () => [...m.keys()],
75
81
  };
76
82
  }
77
83
  /** Test-only: forget the configured driver and the first-use latch. */
@@ -0,0 +1,2 @@
1
+ /** Cross-document exclusion for the shared localStorage driver's seq allocator. */
2
+ export declare function withRecorderLock(name: string, run: () => void): Promise<void>;
@@ -0,0 +1,48 @@
1
+ /** Cross-document exclusion for the shared localStorage driver's seq allocator. */
2
+ export async function withRecorderLock(name, run) {
3
+ const key = `vitrinka.recorder.${name}`;
4
+ if (globalThis.navigator?.locks) {
5
+ await navigator.locks.request(key, { signal: AbortSignal.timeout(5000) }, run);
6
+ return;
7
+ }
8
+ // Web Locks requires a secure context. IndexedDB readwrite transactions
9
+ // also serialize across tabs, including ordinary HTTP development hosts.
10
+ const db = await lockDatabase();
11
+ await new Promise((resolve, reject) => {
12
+ const tx = db.transaction('locks', 'readwrite');
13
+ tx.oncomplete = () => resolve();
14
+ tx.onabort = () => reject(tx.error ?? new Error('vitrinka: recorder lock transaction aborted'));
15
+ const request = tx.objectStore('locks').get(key);
16
+ request.onsuccess = () => {
17
+ try {
18
+ run();
19
+ }
20
+ catch (error) {
21
+ reject(error);
22
+ tx.abort();
23
+ }
24
+ };
25
+ });
26
+ }
27
+ let database;
28
+ function lockDatabase() {
29
+ if (!database) {
30
+ database = new Promise((resolve, reject) => {
31
+ const request = indexedDB.open('vitrinka.recorder.locks', 1);
32
+ request.onupgradeneeded = () => request.result.createObjectStore('locks');
33
+ request.onerror = () => reject(request.error);
34
+ request.onsuccess = () => {
35
+ const db = request.result;
36
+ db.onversionchange = () => {
37
+ db.close();
38
+ database = undefined;
39
+ };
40
+ resolve(db);
41
+ };
42
+ }).catch((error) => {
43
+ database = undefined;
44
+ throw error;
45
+ });
46
+ }
47
+ return database;
48
+ }