@vitrinka/web 0.3.2 → 0.3.4

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.
@@ -1,13 +1,15 @@
1
1
  import { api, fetchPolicy, permanentStatus, VitrinkaApiError } from './api';
2
2
  import { redactUrl, setRedactionPolicy } from './capture/redact';
3
3
  import { recorderConfig } from './config';
4
- import { adoptStoredState, armReconcile, capturesSettled, disarmReconcile, drainBuffer, getState, pushEvent, queuedCount, REC_KEY, resetHealth, resetIdle, resetQueues, setState, } from './queue';
5
- import { forgetRecents, noteRecent, RECENTS_KEY, updateRecent } from './recents';
4
+ import { adoptStoredState, armReconcile, capturesSettled, disarmReconcile, drainBuffer, getState, markStopping, persistNow, pushEvent, queuedCount, REC_KEY, resetHealth, resetIdle, resetQueues, runBeforeStopHooks, setState, stoppingElsewhere, } from './queue';
5
+ import { awaitBoard, boardUrlOf, forgetRecents, noteRecent, RECENTS_KEY, updateRecent } from './recents';
6
6
  import { currentRoute, notify } from './state';
7
7
  import { getRecorderStorage } from './storage';
8
+ import { recorderPeers, registerRecorderTab, waitForRecorderPeers } from './tabs';
8
9
  export { currentRoute, notify, subscribe } from './state';
10
+ export { onBeforeStop } from './queue';
9
11
  /** Sent as `meta.recorder`; bumped with the package version. */
10
- export const RECORDER_VERSION = '0.3.2';
12
+ export const RECORDER_VERSION = '0.3.4';
11
13
  export const RECORDER_ID = `web/${RECORDER_VERSION}`;
12
14
  /**
13
15
  * Re-apply a RECOVERED session's redaction policy after a reload — and
@@ -47,11 +49,13 @@ export function recoverRedactionPolicy() {
47
49
  */
48
50
  export function followOtherTabs() {
49
51
  const storage = getRecorderStorage();
52
+ const participant = registerRecorderTab();
50
53
  const offRec = storage.watch?.(REC_KEY, (raw) => {
51
54
  const had = getState()?.policy;
52
55
  const change = adoptStoredState(raw);
53
56
  if (change === 'unchanged')
54
57
  return;
58
+ participant?.sync();
55
59
  if (change === 'ended')
56
60
  setRedactionPolicy(null);
57
61
  if (change === 'joined') {
@@ -64,11 +68,16 @@ export function followOtherTabs() {
64
68
  if (change === 'updated' && had === undefined && policy !== undefined)
65
69
  setRedactionPolicy(policy);
66
70
  notify();
71
+ if (getState()?.stopping)
72
+ void participant?.settle().catch((error) => {
73
+ console.warn('vitrinka: cross-tab Stop remains unsaved', error);
74
+ });
67
75
  });
68
76
  const offRecents = storage.watch?.(RECENTS_KEY, forgetRecents);
69
77
  return () => {
70
78
  offRec?.();
71
79
  offRecents?.();
80
+ participant?.dispose();
72
81
  };
73
82
  }
74
83
  export function elapsedOf(rec) {
@@ -176,8 +185,10 @@ async function attachTags(sessionId, tags) {
176
185
  }
177
186
  export async function togglePause() {
178
187
  const rec = getState();
179
- if (!rec || rec.dead)
188
+ if (!rec || rec.dead || stoppingElsewhere(rec))
180
189
  return false;
190
+ // A stale mark: the tab that was stopping it is gone, so this is a plain pause.
191
+ delete rec.stopping;
181
192
  rec.paused = !rec.paused;
182
193
  if (rec.paused) {
183
194
  rec.activeMs = (rec.activeMs || 0) + (rec.resumeAt ? Date.now() - Date.parse(rec.resumeAt) : 0);
@@ -229,11 +240,6 @@ export function addAnnotation(text, rect, selector, opts = {}) {
229
240
  * Hooks that run at the top of Stop, before the drain snapshot — the rrweb
230
241
  * lane ships its sub-2s tail here so the last DOM events make the session.
231
242
  */
232
- const beforeStopHooks = new Set();
233
- export function onBeforeStop(fn) {
234
- beforeStopHooks.add(fn);
235
- return () => beforeStopHooks.delete(fn);
236
- }
237
243
  /**
238
244
  * Stop the session. Throws with the queued-item count when the server is
239
245
  * unreachable — the durable tail is NEVER deleted; capture freezes paused and
@@ -245,15 +251,20 @@ export async function stopSession() {
245
251
  return null;
246
252
  // The recording's length is what the tester saw at Stop, not Stop + drain.
247
253
  const durationMs = elapsedOf(rec);
248
- disarmReconcile();
249
- for (const fn of beforeStopHooks) {
250
- try {
251
- fn();
252
- }
253
- catch (e) {
254
- console.warn('vitrinka: before-stop hook failed', e);
255
- }
254
+ const peers = recorderPeers(rec.sessionId);
255
+ // The other tabs leave rec at the Stop, not when the save ends; a stop
256
+ // that keeps the session hands it back to them as it now is.
257
+ markStopping(rec.sessionId, durationMs);
258
+ try {
259
+ return await finishStop(rec, durationMs, peers);
260
+ }
261
+ finally {
262
+ markStopping(null);
256
263
  }
264
+ }
265
+ async function finishStop(rec, durationMs, peers) {
266
+ disarmReconcile();
267
+ runBeforeStopHooks();
257
268
  const completeDeadStop = (reason) => {
258
269
  const kept = queuedCount();
259
270
  updateRecent(rec.sessionId, { status: 'unsaved', durationMs });
@@ -269,7 +280,8 @@ export async function stopSession() {
269
280
  if (!(await capturesSettled())) {
270
281
  console.warn('vitrinka: stopping with unsettled captures — a late event may not make this session');
271
282
  }
272
- if (!(await drainBuffer())) {
283
+ const peersSaved = await waitForRecorderPeers(peers, rec.sessionId);
284
+ if (!peersSaved || !(await drainBuffer())) {
273
285
  const live = getState();
274
286
  // Another tab may have moved on to a session of its own meanwhile — never this stop's to hold.
275
287
  const held = live?.sessionId === rec.sessionId ? live : null;
@@ -281,9 +293,10 @@ export async function stopSession() {
281
293
  held.resumeAt = null;
282
294
  setState(held);
283
295
  }
296
+ persistNow();
284
297
  armReconcile();
285
298
  notify();
286
- throw new Error(`server unreachable — ${queuedCount()} item(s) kept; stop again once online`);
299
+ throw new Error(`${peersSaved ? 'server unreachable' : 'another tab has undelivered captures'} — ${queuedCount()} local item(s) kept; stop again once online`);
287
300
  }
288
301
  let done = null;
289
302
  try {
@@ -300,8 +313,10 @@ export async function stopSession() {
300
313
  }
301
314
  }
302
315
  // A permanent refusal still ends the recording locally, but it was not saved.
303
- const boardUrl = done?.board?.url ?? rec.boardUrl;
316
+ const boardUrl = boardUrlOf(done) ?? rec.boardUrl;
304
317
  updateRecent(rec.sessionId, { status: done ? 'saved' : 'unsaved', durationMs, ...(boardUrl ? { boardUrl } : {}) });
318
+ if (done && !boardUrl)
319
+ void awaitBoard(rec.sessionId);
305
320
  // Another tab may have ended this session or started the next one while
306
321
  // the stop was out: the state and the queues are then not this stop's to clear.
307
322
  if (getState()?.sessionId === rec.sessionId) {
@@ -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,16 +1,16 @@
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
  */
13
+ import { withRecorderLock } from './lock';
14
14
  // Keys land as `vitrinka.recorder.<key>`: rec · buffer · chunks · link (the
15
15
  // recorder) and dock · prefs · me · recents (the HUD).
16
16
  const PREFIX = 'vitrinka.recorder.';
@@ -47,6 +47,10 @@ export function localRecorderStorage() {
47
47
  getString: (k) => ls.getItem(PREFIX + k),
48
48
  set: (k, v) => ls.setItem(PREFIX + k, v),
49
49
  remove: (k) => ls.removeItem(PREFIX + k),
50
+ withLock: withRecorderLock,
51
+ keys: () => Array.from({ length: ls.length }, (_, i) => ls.key(i))
52
+ .filter((key) => key !== null && key.startsWith(PREFIX))
53
+ .map((key) => key.slice(PREFIX.length)),
50
54
  // localStorage is shared by every tab of the origin; its `storage`
51
55
  // event reaches the OTHER documents only. A clear() (key null) is not
52
56
  // a write of `k` and is ignored.
@@ -72,6 +76,7 @@ export function memoryRecorderStorage() {
72
76
  getString: (k) => m.get(k) ?? null,
73
77
  set: (k, v) => void m.set(k, v),
74
78
  remove: (k) => void m.delete(k),
79
+ keys: () => [...m.keys()],
75
80
  };
76
81
  }
77
82
  /** 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
+ }
@@ -0,0 +1,8 @@
1
+ export declare function recorderPeers(sessionId: string): string[];
2
+ export declare function registerRecorderTab(): {
3
+ sync: () => void;
4
+ dispose: () => void;
5
+ settle(): Promise<void>;
6
+ } | null;
7
+ /** Watch before reading, so an acknowledgement arriving during setup is never missed. */
8
+ export declare function waitForRecorderPeers(keys: readonly string[], sessionId: string, timeoutMs?: number): Promise<boolean>;
@@ -0,0 +1,137 @@
1
+ /** Each mounted tab saves its own tail before any tab closes the shared session. */
2
+ import { adoptStoredState, capturesSettled, drainBuffer, flush, getState, persistNow, queuedCount, RECORDER_DOCUMENT_KEY, runBeforeStopHooks, STOPPING_RENEW_MS, STOPPING_TTL_MS, tailIsDurable } from './queue';
3
+ import { getRecorderStorage } from './storage';
4
+ import { notify, subscribe } from './state';
5
+ const PREFIX = 'tab.';
6
+ // Document identity, independent of sessionStorage (duplicating a tab copies it).
7
+ const ownKey = `${PREFIX}${RECORDER_DOCUMENT_KEY}`;
8
+ function readParticipant(raw) {
9
+ return raw ? JSON.parse(raw) : null;
10
+ }
11
+ export function recorderPeers(sessionId) {
12
+ const storage = getRecorderStorage();
13
+ if (!storage.watch || !storage.keys)
14
+ return [];
15
+ return storage.keys().filter((key) => {
16
+ if (!key.startsWith(PREFIX) || key === ownKey)
17
+ return false;
18
+ const peer = readParticipant(storage.getString(key));
19
+ return peer?.sessionId === sessionId && (peer.failed || Date.now() - peer.at < STOPPING_TTL_MS);
20
+ });
21
+ }
22
+ export function registerRecorderTab() {
23
+ const storage = getRecorderStorage();
24
+ if (!storage.watch || !storage.keys)
25
+ return null;
26
+ let settling = false;
27
+ let hidden = false;
28
+ const sync = () => {
29
+ if (hidden)
30
+ return;
31
+ const rec = getState();
32
+ if (!rec)
33
+ storage.remove(ownKey);
34
+ else if (!rec.stopping)
35
+ storage.set(ownKey, JSON.stringify({ sessionId: rec.sessionId, at: Date.now() }));
36
+ };
37
+ let heartbeat = setInterval(sync, STOPPING_RENEW_MS);
38
+ const offState = subscribe(sync);
39
+ sync();
40
+ const onPageHide = () => {
41
+ hidden = true;
42
+ clearInterval(heartbeat);
43
+ runBeforeStopHooks();
44
+ persistNow();
45
+ const rec = getState();
46
+ if (rec && queuedCount())
47
+ storage.set(ownKey, JSON.stringify({ sessionId: rec.sessionId, at: Date.now(), failed: true, departed: true, recoverable: tailIsDurable() }));
48
+ else
49
+ storage.remove(ownKey);
50
+ };
51
+ const onPageShow = () => {
52
+ if (!hidden)
53
+ return;
54
+ hidden = false;
55
+ adoptStoredState(storage.getString('rec') ?? null);
56
+ heartbeat = setInterval(sync, STOPPING_RENEW_MS);
57
+ sync();
58
+ notify();
59
+ // Storage events may not have reached this document while suspended.
60
+ if (getState()?.stopping)
61
+ void participant.settle().catch((error) => console.warn('vitrinka: restored tab remains unsaved', error));
62
+ };
63
+ const dispose = () => {
64
+ onPageHide();
65
+ offState();
66
+ globalThis.removeEventListener?.('pagehide', onPageHide);
67
+ globalThis.removeEventListener?.('pageshow', onPageShow);
68
+ };
69
+ globalThis.addEventListener?.('pagehide', onPageHide);
70
+ globalThis.addEventListener?.('pageshow', onPageShow);
71
+ const participant = {
72
+ sync,
73
+ dispose,
74
+ async settle() {
75
+ if (settling)
76
+ return;
77
+ const sessionId = getState()?.sessionId;
78
+ if (!sessionId)
79
+ return;
80
+ settling = true;
81
+ try {
82
+ const saved = await capturesSettled() && await drainBuffer();
83
+ if (getState()?.sessionId !== sessionId)
84
+ return;
85
+ if (saved)
86
+ storage.remove(ownKey);
87
+ else
88
+ storage.set(ownKey, JSON.stringify({ sessionId, at: Date.now(), failed: true }));
89
+ }
90
+ catch (error) {
91
+ console.warn('vitrinka: another tab could not save its tail', error);
92
+ storage.set(ownKey, JSON.stringify({ sessionId, at: Date.now(), failed: true }));
93
+ throw error;
94
+ }
95
+ finally {
96
+ settling = false;
97
+ }
98
+ },
99
+ };
100
+ return participant;
101
+ }
102
+ /** Watch before reading, so an acknowledgement arriving during setup is never missed. */
103
+ export async function waitForRecorderPeers(keys, sessionId, timeoutMs = 60_000) {
104
+ const storage = getRecorderStorage();
105
+ if (!storage.watch || !keys.length)
106
+ return true;
107
+ const results = await Promise.all(keys.map((key) => new Promise((resolve) => {
108
+ let off = () => { };
109
+ let recovering = false;
110
+ const finish = (saved) => { clearTimeout(timer); off(); resolve(saved); };
111
+ const check = (raw) => {
112
+ const peer = readParticipant(raw);
113
+ if (!peer || peer.sessionId !== sessionId)
114
+ finish(true);
115
+ else if (peer.departed && peer.recoverable) {
116
+ if (recovering)
117
+ return;
118
+ recovering = true;
119
+ void (async () => {
120
+ await flush();
121
+ await drainBuffer();
122
+ const remaining = readParticipant(storage.getString(key));
123
+ finish(!remaining || remaining.sessionId !== sessionId);
124
+ })().catch((error) => {
125
+ console.warn('vitrinka: departed tab could not save its tail', error);
126
+ finish(false);
127
+ });
128
+ }
129
+ else if (peer.failed)
130
+ finish(false);
131
+ };
132
+ const timer = setTimeout(() => finish(false), timeoutMs);
133
+ off = storage.watch(key, check);
134
+ check(storage.getString(key));
135
+ })));
136
+ return results.every(Boolean);
137
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitrinka/web",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "vitrinka toolkit for React DOM apps — the journey recorder: capture manual-testing sessions (rrweb DOM stream, clicks, navigation, network, console, notes) straight into vitrinka boards.",
5
5
  "license": "Elastic-2.0",
6
6
  "repository": {