@vitrinka/web 0.4.0 → 0.5.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 (39) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +34 -1
  3. package/build/hud.d.ts +4 -1
  4. package/build/hud.iife.js +6 -6
  5. package/build/one.iife.js +1 -0
  6. package/build/recorder/RecorderProvider.js +48 -9
  7. package/build/recorder/capture/console.d.ts +2 -0
  8. package/build/recorder/capture/console.js +22 -2
  9. package/build/recorder/capture/nav.d.ts +13 -2
  10. package/build/recorder/capture/nav.js +49 -11
  11. package/build/recorder/capture/net.d.ts +2 -0
  12. package/build/recorder/capture/net.js +30 -4
  13. package/build/recorder/control.d.ts +17 -0
  14. package/build/recorder/control.js +39 -2
  15. package/build/recorder/hud/Hud.js +70 -20
  16. package/build/recorder/hud/RecorderPill.js +6 -2
  17. package/build/recorder/hud/chords.d.ts +10 -0
  18. package/build/recorder/hud/chords.js +34 -0
  19. package/build/recorder/hud/controller.d.ts +24 -0
  20. package/build/recorder/hud/flow.d.ts +22 -1
  21. package/build/recorder/hud/flow.js +16 -1
  22. package/build/recorder/index.d.ts +1 -0
  23. package/build/recorder/index.js +1 -0
  24. package/build/recorder/lead.d.ts +90 -0
  25. package/build/recorder/lead.js +404 -0
  26. package/build/recorder/one-iife.d.ts +13 -0
  27. package/build/recorder/one-iife.js +13 -0
  28. package/build/recorder/one.d.ts +170 -0
  29. package/build/recorder/one.js +292 -0
  30. package/build/recorder/page-controller.js +23 -2
  31. package/build/recorder/queue.js +5 -2
  32. package/build/recorder/report.js +9 -2
  33. package/build/recorder/session.d.ts +22 -4
  34. package/build/recorder/session.js +70 -20
  35. package/build/recorder/state.d.ts +9 -0
  36. package/build/recorder/state.js +7 -0
  37. package/build/recorder/version.d.ts +3 -0
  38. package/build/recorder/version.js +3 -0
  39. package/package.json +5 -3
@@ -0,0 +1,292 @@
1
+ /**
2
+ * ONE recorder (extension + page recorder decisions, 2026-10-12): the
3
+ * page-embedded recorder (main world) and the browser extension's content
4
+ * scripts (isolated world) share nothing but the DOM, so this is the whole
5
+ * protocol they speak over it — written once here, imported by the page
6
+ * recorder (`lead.ts`) and shipped to the extension as `build/one.iife.js`
7
+ * (`globalThis.VitrinkaOne`). DOM-light and React-free: every function takes
8
+ * a `OneEnv` (the `<html>` element and `window` by default), so it runs
9
+ * under bun without a DOM.
10
+ *
11
+ * - State lives on `<html>` attributes: `data-vitrinka-page` (a page
12
+ * recorder is mounted here) and `data-vitrinka-lead` (the claim: who
13
+ * records this document). A claim is written only by its holder, taken by
14
+ * a synchronous check-and-set (`takeClaim`), and cleared by anyone else
15
+ * only under its own `id` once its holder no longer answers (D4, D5).
16
+ * - Actions travel as `window` CustomEvents whose `detail` is a JSON STRING
17
+ * (an object `detail` from the isolated world reads `null` in the main
18
+ * world). `dispatchEvent` runs every world's listeners synchronously, so a
19
+ * `hello` ask and a `command` are answered inside their own dispatch: no
20
+ * answer means no live holder, and nobody ever waits on a timer.
21
+ * - Never `data-vitrinka-recorder` on `<html>`: that is rrweb's block
22
+ * selector and the click lanes' "ours" marker.
23
+ */
24
+ import { listen } from './hud/listen';
25
+ /** Protocol version; a reader takes the fields it knows from a higher one. */
26
+ export const ONE_VERSION = 1;
27
+ /** `<html>` attribute: a page recorder is mounted here (its recorder id, e.g. `web/0.5.0`). */
28
+ export const PAGE_ATTR = 'data-vitrinka-page';
29
+ /** `<html>` attribute: the claim (JSON). */
30
+ export const LEAD_ATTR = 'data-vitrinka-lead';
31
+ export const HELLO_EVENT = 'vitrinka:hello';
32
+ export const COMMAND_EVENT = 'vitrinka:command';
33
+ export const ACK_EVENT = 'vitrinka:ack';
34
+ /** The document's env; null where there is no DOM (SSR, a worker). */
35
+ export function documentEnv() {
36
+ const doc = globalThis.document;
37
+ const root = doc?.documentElement;
38
+ if (!root || typeof globalThis.dispatchEvent !== 'function')
39
+ return null;
40
+ return { root, bus: globalThis };
41
+ }
42
+ /** A fresh nonce: `p.k3x9q2…` for a page instance. */
43
+ export function nonce(prefix) {
44
+ return `${prefix}.${Math.random().toString(36).slice(2, 10)}`;
45
+ }
46
+ // -- the codec ---------------------------------------------------------------
47
+ const PARTIES = ['page', 'extension'];
48
+ const STATES = ['starting', 'recording', 'paused', 'stopping', 'saved'];
49
+ const OPS = ['pause', 'stop', 'note'];
50
+ const CODES = ['not_recording', 'stopping', 'not_here', 'bad_command'];
51
+ function bagOf(raw) {
52
+ if (typeof raw !== 'string')
53
+ return null;
54
+ try {
55
+ const v = JSON.parse(raw);
56
+ return v !== null && typeof v === 'object' && !Array.isArray(v) ? v : null;
57
+ }
58
+ catch {
59
+ return null;
60
+ }
61
+ }
62
+ const str = (v) => typeof v === 'string';
63
+ const party = (v) => str(v) && PARTIES.includes(v);
64
+ const claimState = (v) => str(v) && STATES.includes(v);
65
+ /** `v` is a positive integer; a higher one still parses (D18). */
66
+ const version = (v) => typeof v === 'number' && Number.isInteger(v) && v >= 1;
67
+ /** Parse a claim attribute; null for anything that is not one. */
68
+ export function parseClaim(raw) {
69
+ const b = bagOf(raw);
70
+ if (!b || !version(b.v) || !party(b.by) || !str(b.id) || !b.id || !claimState(b.state))
71
+ return null;
72
+ return {
73
+ v: b.v,
74
+ by: b.by,
75
+ id: b.id,
76
+ state: b.state,
77
+ sessionId: str(b.sessionId) ? b.sessionId : '',
78
+ since: typeof b.since === 'number' ? b.since : 0,
79
+ };
80
+ }
81
+ export function serializeClaim(c) {
82
+ return JSON.stringify({ v: c.v, by: c.by, id: c.id, state: c.state, sessionId: c.sessionId, since: c.since });
83
+ }
84
+ /** Live = a recording is (or is about to be) under way; `saved` is not. */
85
+ export function isLive(state) {
86
+ return state !== undefined && state !== null && state !== 'saved';
87
+ }
88
+ function parseLive(raw) {
89
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
90
+ return null;
91
+ const b = raw;
92
+ if (!party(b.by) || !claimState(b.state))
93
+ return null;
94
+ return { by: b.by, state: b.state, here: b.here === true, ...(str(b.id) && b.id ? { id: b.id } : {}) };
95
+ }
96
+ export function parseHello(raw) {
97
+ const b = bagOf(raw);
98
+ if (!b || !version(b.v) || !party(b.from) || !str(b.inst) || !b.inst)
99
+ return null;
100
+ const live = parseLive(b.live);
101
+ return {
102
+ v: b.v,
103
+ from: b.from,
104
+ inst: b.inst,
105
+ ...(b.ask === true ? { ask: true } : {}),
106
+ ...(b.live !== undefined ? { live } : {}),
107
+ ...(b.gone === true ? { gone: true } : {}),
108
+ };
109
+ }
110
+ /** A command; null when it does not parse or names an unknown op (treated as absent). */
111
+ export function parseCommand(raw) {
112
+ const b = bagOf(raw);
113
+ if (!b || !version(b.v) || !party(b.from) || !str(b.inst) || !b.inst || !str(b.id) || !b.id)
114
+ return null;
115
+ if (!str(b.op) || !OPS.includes(b.op))
116
+ return null;
117
+ return { v: b.v, from: b.from, inst: b.inst, id: b.id, op: b.op, ...(str(b.text) ? { text: b.text } : {}) };
118
+ }
119
+ export function parseAck(raw) {
120
+ const b = bagOf(raw);
121
+ if (!b || !version(b.v) || !party(b.from) || !str(b.inst) || !str(b.id) || typeof b.ok !== 'boolean')
122
+ return null;
123
+ return {
124
+ v: b.v,
125
+ from: b.from,
126
+ inst: b.inst,
127
+ id: b.id,
128
+ ok: b.ok,
129
+ ...(str(b.code) && CODES.includes(b.code) ? { code: b.code } : {}),
130
+ ...(str(b.error) ? { error: b.error } : {}),
131
+ };
132
+ }
133
+ // -- state: the attributes ---------------------------------------------------
134
+ export function readClaim(env) {
135
+ return parseClaim(env.root.getAttribute(LEAD_ATTR));
136
+ }
137
+ function writeClaim(env, c) {
138
+ const next = serializeClaim(c);
139
+ // Transitions only: the leader's rrweb and the page's own observers see every write.
140
+ if (env.root.getAttribute(LEAD_ATTR) !== next)
141
+ env.root.setAttribute(LEAD_ATTR, next);
142
+ }
143
+ /**
144
+ * The synchronous check-and-set (D4): take this document's claim unless a
145
+ * LIVE claim of another holder stands and that holder still answers (D5).
146
+ * A `saved` claim, a stale one and the caller's own are taken over. Call it
147
+ * before any network call, inside one task.
148
+ */
149
+ export function takeClaim(env, self, next) {
150
+ const cur = readClaim(env);
151
+ if (cur && cur.id !== next.id && isLive(cur.state) && holderAnswers(env, self, cur))
152
+ return { ok: false, holder: cur };
153
+ const claim = {
154
+ v: ONE_VERSION,
155
+ by: self.from,
156
+ id: next.id,
157
+ state: next.state,
158
+ sessionId: next.sessionId ?? '',
159
+ // Re-taking its own live claim keeps its age; a new claim (or one over a `saved` face) starts now.
160
+ since: cur?.id === next.id && isLive(cur.state) ? cur.since : Date.now(),
161
+ };
162
+ writeClaim(env, claim);
163
+ return { ok: true, claim };
164
+ }
165
+ /** Move the holder's claim to `state` (and `sessionId`); false when the claim is not `id`'s. */
166
+ export function updateClaim(env, id, patch) {
167
+ const cur = readClaim(env);
168
+ if (cur?.id !== id)
169
+ return false;
170
+ writeClaim(env, { ...cur, v: ONE_VERSION, state: patch.state, sessionId: patch.sessionId ?? cur.sessionId });
171
+ return true;
172
+ }
173
+ /** Remove the claim only if it is `id`'s — the holder releasing, or anyone clearing a stale one. */
174
+ export function releaseClaim(env, id) {
175
+ if (readClaim(env)?.id !== id)
176
+ return false;
177
+ env.root.removeAttribute(LEAD_ATTR);
178
+ return true;
179
+ }
180
+ /** Call back on every change of the claim attribute; returns the stop. */
181
+ export function watchClaim(env, fn) {
182
+ if (env.watch)
183
+ return env.watch(fn);
184
+ if (typeof MutationObserver !== 'function' || typeof Node === 'undefined' || !(env.root instanceof Node))
185
+ return () => undefined;
186
+ const mo = new MutationObserver(fn);
187
+ mo.observe(env.root, { attributes: true, attributeFilter: [LEAD_ATTR] });
188
+ return () => mo.disconnect();
189
+ }
190
+ export function markPage(env, recorderId) {
191
+ if (env.root.getAttribute(PAGE_ATTR) !== recorderId)
192
+ env.root.setAttribute(PAGE_ATTR, recorderId);
193
+ }
194
+ export function unmarkPage(env) {
195
+ env.root.removeAttribute(PAGE_ATTR);
196
+ }
197
+ export function pageMarked(env) {
198
+ return env.root.getAttribute(PAGE_ATTR) !== null;
199
+ }
200
+ // -- actions: the events -----------------------------------------------------
201
+ function emit(env, type, msg) {
202
+ env.bus.dispatchEvent(new CustomEvent(type, { detail: JSON.stringify(msg) }));
203
+ }
204
+ /** Listen natively (`hud/listen.ts`: a zone.js host routes it like any other). */
205
+ function on(env, type, fn) {
206
+ return listen(env.bus, type, (e) => fn(e.detail));
207
+ }
208
+ /**
209
+ * Ask who is here: every live party answers inside this dispatch. Returns
210
+ * the answers (never the caller's own).
211
+ */
212
+ export function ask(env, self) {
213
+ const answers = [];
214
+ const off = on(env, HELLO_EVENT, (d) => {
215
+ const h = parseHello(d);
216
+ if (h && !h.ask && h.inst !== self.inst)
217
+ answers.push(h);
218
+ });
219
+ try {
220
+ emit(env, HELLO_EVENT, { v: ONE_VERSION, from: self.from, inst: self.inst, ask: true });
221
+ }
222
+ finally {
223
+ off();
224
+ }
225
+ return answers;
226
+ }
227
+ /** Say what this party knows (no `ask`): an answer, a change, or `gone` on leaving. */
228
+ export function announce(env, self, live, opts = {}) {
229
+ emit(env, HELLO_EVENT, { v: ONE_VERSION, from: self.from, inst: self.inst, live, ...(opts.gone ? { gone: true } : {}) });
230
+ }
231
+ /**
232
+ * Serve the hello channel: an ask is answered at once with `live()`; any
233
+ * other hello (an answer to someone else, a change, a `gone`) reaches
234
+ * `onHello`. The party's own dispatches are ignored. `answerIf` keeps a
235
+ * party silent where it must not speak — the extension's `one.js` answers
236
+ * only in documents that carry `data-vitrinka-page` (D6).
237
+ */
238
+ export function serveHello(env, self, live, onHello, opts = {}) {
239
+ return on(env, HELLO_EVENT, (d) => {
240
+ const h = parseHello(d);
241
+ if (!h || h.inst === self.inst)
242
+ return;
243
+ if (!h.ask)
244
+ onHello?.(h);
245
+ else if (opts.answerIf?.() ?? true)
246
+ announce(env, self, live());
247
+ });
248
+ }
249
+ /** Did the claim's holder answer? Matched on its `id` when the answer names one, else on its side. */
250
+ export function answeredBy(answers, holder) {
251
+ return answers.some((h) => h.live?.here === true && (h.live.id ? h.live.id === holder.id : h.from === holder.by));
252
+ }
253
+ /** Ping the claim's holder (D5): true when it answers inside the dispatch. */
254
+ export function holderAnswers(env, self, holder) {
255
+ return answeredBy(ask(env, self), holder);
256
+ }
257
+ /**
258
+ * Send a command to the claim's holder; its ack arrives inside this
259
+ * dispatch. Null = nobody answered (the holder is gone, D5).
260
+ */
261
+ export function sendCommand(env, self, op, text) {
262
+ const id = nonce('c');
263
+ let ack = null;
264
+ const off = on(env, ACK_EVENT, (d) => {
265
+ const a = parseAck(d);
266
+ if (a && a.id === id && a.inst !== self.inst && !ack)
267
+ ack = a;
268
+ });
269
+ try {
270
+ emit(env, COMMAND_EVENT, { v: ONE_VERSION, from: self.from, inst: self.inst, id, op, ...(text !== undefined ? { text } : {}) });
271
+ }
272
+ finally {
273
+ off();
274
+ }
275
+ return ack;
276
+ }
277
+ /**
278
+ * Serve commands: `handle` answers a parsed command (another party's, a
279
+ * known op) with its reply — synchronously, inside the command's dispatch —
280
+ * or `null` when this party is not the holder, which sends no ack at all.
281
+ */
282
+ export function serveCommands(env, self, handle) {
283
+ return on(env, COMMAND_EVENT, (d) => {
284
+ const c = parseCommand(d);
285
+ if (!c || c.inst === self.inst)
286
+ return;
287
+ const reply = handle(c);
288
+ if (!reply)
289
+ return;
290
+ emit(env, ACK_EVENT, { v: ONE_VERSION, from: self.from, inst: self.inst, id: c.id, ...reply });
291
+ });
292
+ }
@@ -1,11 +1,12 @@
1
1
  import { readLink, recorderConfig, vitrinkaLinked } from './config';
2
+ import { holdFace, leadStatus, sendToLeader, setRemoteStop } from './lead';
2
3
  import { forgetLink, linkDevice } from './link';
3
4
  import { cachedAccount, cachedPrefs, fetchMe, savePrefs } from './me';
4
5
  import { getState, health } from './queue';
5
6
  import { boardUrlOf, readRecents, refreshRecents } from './recents';
6
7
  import { canAttach, canReport, holdReport, sendReport } from './report';
7
8
  import { addAnnotation, addNote, RECORDER_ID, startSession, stopSession, togglePause } from './session';
8
- import { annotateState, setAnnotating, subscribe } from './state';
9
+ import { annotateState, leadState, setAnnotating, subscribe } from './state';
9
10
  function build() {
10
11
  const rec = getState();
11
12
  const cfg = recorderConfig();
@@ -48,6 +49,7 @@ function build() {
48
49
  version: RECORDER_ID,
49
50
  canReport: canReport(),
50
51
  canAttach: canAttach(),
52
+ ...(leadState.following ? { following: leadState.following } : {}),
51
53
  };
52
54
  }
53
55
  export function createPageController() {
@@ -67,10 +69,20 @@ export function createPageController() {
67
69
  async start({ title }) {
68
70
  await startSession({ title });
69
71
  },
72
+ // While another recorder leads, pause, stop and a note act on it (ONE recorder D11).
70
73
  async togglePause() {
74
+ if (leadState.following)
75
+ return sendToLeader('pause');
71
76
  await togglePause();
72
77
  },
73
78
  async stop() {
79
+ if (leadState.following) {
80
+ sendToLeader('stop');
81
+ const sessionId = leadStatus().claim?.sessionId;
82
+ return sessionId ? { sessionId } : {};
83
+ }
84
+ // The stop's face holds the claim as `saved` from its first moment (D7).
85
+ holdFace('saving');
74
86
  const boardUrl = getState()?.boardUrl;
75
87
  const sessionId = getState()?.sessionId;
76
88
  const done = await stopSession();
@@ -80,7 +92,14 @@ export function createPageController() {
80
92
  const url = boardUrlOf(done) ?? boardUrl;
81
93
  return { ...(url ? { boardUrl: url } : {}), ...(sessionId ? { sessionId } : {}) };
82
94
  },
83
- note: (text, attachments) => addNote(text, attachments),
95
+ note(text, attachments) {
96
+ if (!leadState.following)
97
+ return addNote(text, attachments);
98
+ // Images never cross to the other recorder; its note carries the text.
99
+ if (attachments?.length)
100
+ console.warn('vitrinka: the note goes to the recorder that leads — without its images');
101
+ sendToLeader('note', text);
102
+ },
84
103
  annotate: ({ text, rect, selector, task, attachments }) => addAnnotation(text, rect, selector, { task, ...(attachments ? { attachments } : {}) }),
85
104
  setAnnotating,
86
105
  async link() {
@@ -101,5 +120,7 @@ export function createPageController() {
101
120
  refreshRecents: () => refreshRecents(getState()?.sessionId ?? null),
102
121
  holdReport,
103
122
  report: (r) => sendReport(r),
123
+ onRemoteStop: setRemoteStop,
124
+ faceChanged: holdFace,
104
125
  };
105
126
  }
@@ -1,6 +1,6 @@
1
1
  import { api, permanentStatus, uploadChunk, uploadImage, VitrinkaApiError } from './api';
2
2
  import { pushFlightEvent } from './flight';
3
- import { notify } from './state';
3
+ import { leadState, notify } from './state';
4
4
  import { getRecorderStorage } from './storage';
5
5
  import { getRecorderBlobStore } from './storage/blobs';
6
6
  const FLUSH_MS = 2000;
@@ -893,6 +893,9 @@ export function isSessionLive(id) {
893
893
  * take the seqs just before the event's, which lists them as `attachments`.
894
894
  */
895
895
  export function pushEvent(kind, payload, route, images = []) {
896
+ // A follower captures nothing: the leader records this document (ONE recorder D2).
897
+ if (leadState.following)
898
+ return null;
896
899
  const rec = getState();
897
900
  if (!rec)
898
901
  return pushFlightEvent(kind, payload, route);
@@ -978,7 +981,7 @@ export function pushRRWebBatch(events, route) {
978
981
  if (!events.length)
979
982
  return 0;
980
983
  const rec = getState();
981
- if (!rec || rec.paused || rec.dead)
984
+ if (!rec || rec.paused || rec.dead || leadState.following)
982
985
  return 0;
983
986
  const { parts, dropped } = splitRRWebEvents(events);
984
987
  for (const b of dropped) {
@@ -7,7 +7,7 @@ import { clipHasSnapshot, flightActive, startFlightBuffer, stopFlightBuffer, tak
7
7
  import { EVENTS_PER_POST, getState, MAX_BATCH_BYTES, splitRRWebEvents, utf8Bytes } from './queue';
8
8
  import { awaitBoard, boardUrlOf, noteRecent } from './recents';
9
9
  import { addAnnotation, createSession, imagePixels } from './session';
10
- import { currentRoute, notify } from './state';
10
+ import { currentRoute, leadState, notify } from './state';
11
11
  // -- the gate ----------------------------------------------------------------
12
12
  let pills = 0;
13
13
  let armed = false;
@@ -28,8 +28,13 @@ export function wantFlight() {
28
28
  notify();
29
29
  };
30
30
  }
31
+ /** …and this recorder leads or is idle: a follower keeps no last minute (ONE recorder D2). */
31
32
  function flightWanted() {
32
- return pills > 0 && getState() === null && vitrinkaLinked() && recorderConfig().flightRecorder !== false;
33
+ return (pills > 0 &&
34
+ getState() === null &&
35
+ leadState.following === null &&
36
+ vitrinkaLinked() &&
37
+ recorderConfig().flightRecorder !== false);
33
38
  }
34
39
  /**
35
40
  * Arm or disarm the flight recorder to match the gate; the provider calls it
@@ -64,6 +69,8 @@ export function syncFlight() {
64
69
  }
65
70
  /** Can the pill offer "Report a bug" now — into the live session, or with the idle clip? */
66
71
  export function canReport() {
72
+ if (leadState.following)
73
+ return false;
67
74
  const rec = getState();
68
75
  if (rec)
69
76
  return !rec.paused && !rec.dead;
@@ -14,13 +14,11 @@
14
14
  import type { RedactionPolicy } from '@vitrinka/redact';
15
15
  import type { SessionDone } from '../protocol';
16
16
  import type { HudAttachment } from './hud/controller';
17
- import { type SessionState } from './queue';
17
+ import { type SessionState, type StoredChange } from './queue';
18
18
  export { currentRoute, notify, subscribe } from './state';
19
19
  export { onBeforeStop } from './queue';
20
20
  export type { SessionDone } from '../protocol';
21
- /** Sent as `meta.recorder`; bumped with the package version. */
22
- export declare const RECORDER_VERSION = "0.4.0";
23
- export declare const RECORDER_ID = "web/0.4.0";
21
+ export { RECORDER_ID, RECORDER_VERSION } from './version';
24
22
  /** What `POST /api/v1/sessions` answers (the fields this recorder keeps). */
25
23
  export interface SessionOut {
26
24
  id: string;
@@ -39,6 +37,20 @@ export declare function recoverRedactionPolicy(): void;
39
37
  * others (their pills go idle, their lanes stop sending into it), a Start
40
38
  * is joined as a reload joins it, a pause follows. Returns the unsubscribe.
41
39
  */
40
+ /**
41
+ * Take a session record this document did not write — another tab's, or
42
+ * another recorder bundle's in this very document — with what it implies:
43
+ * an ended session drops its rules, a joined one recovers its policy and
44
+ * reconcile poll, and a policy that arrived late applies at once.
45
+ */
46
+ export declare function applyStoredRecord(raw: string | null): StoredChange;
47
+ /**
48
+ * Re-read the durable record before a waiting session resumes (ONE
49
+ * recorder): another recorder bundle in THIS document may have ended or
50
+ * replaced it, and storage events never reach the document that wrote them.
51
+ * True when the cached session is still the one to resume.
52
+ */
53
+ export declare function resyncStoredSession(): boolean;
42
54
  export declare function followOtherTabs(): () => void;
43
55
  export declare function elapsedOf(rec: SessionState | null): number;
44
56
  export interface StartOptions {
@@ -60,6 +72,12 @@ export declare function createSession(title: string, opts?: {
60
72
  environment?: string;
61
73
  meta?: Record<string, unknown>;
62
74
  }): Promise<SessionOut>;
75
+ /**
76
+ * Start a recording. The claim on this document comes first, synchronously
77
+ * and before any network call: while the extension (or another recorder on
78
+ * this page) leads, this rejects with a `RecorderBusyError` and nothing is
79
+ * created (ONE recorder D12).
80
+ */
63
81
  export declare function startSession(opts?: StartOptions): Promise<SessionState>;
64
82
  export declare function togglePause(): Promise<boolean>;
65
83
  /**
@@ -1,17 +1,18 @@
1
1
  import { api, fetchPolicy, permanentStatus, VitrinkaApiError } from './api';
2
2
  import { stageAttachments } from './attachments';
3
+ import { primeNavigation } from './capture/nav';
3
4
  import { redactUrl, setRedactionPolicy } from './capture/redact';
4
5
  import { recorderConfig } from './config';
5
6
  import { adoptStoredState, armReconcile, capturesSettled, disarmReconcile, drainBuffer, getState, markStopping, persistNow, pruneBlobJournal, pushEvent, queuedCount, REC_KEY, resetHealth, resetIdle, resetQueues, runBeforeStopHooks, setState, stoppingElsewhere, } from './queue';
7
+ import { claimForStart, settleStart, setLeadStopping } from './lead';
6
8
  import { awaitBoard, boardUrlOf, forgetRecents, noteRecent, RECENTS_KEY, updateRecent } from './recents';
7
9
  import { currentRoute, notify } from './state';
8
10
  import { getRecorderStorage } from './storage';
9
11
  import { recorderPeers, registerRecorderTab, waitForRecorderPeers } from './tabs';
12
+ import { RECORDER_ID } from './version';
10
13
  export { currentRoute, notify, subscribe } from './state';
11
14
  export { onBeforeStop } from './queue';
12
- /** Sent as `meta.recorder`; bumped with the package version. */
13
- export const RECORDER_VERSION = '0.4.0';
14
- export const RECORDER_ID = `web/${RECORDER_VERSION}`;
15
+ export { RECORDER_ID, RECORDER_VERSION } from './version';
15
16
  /**
16
17
  * Re-apply a RECOVERED session's redaction policy after a reload — and
17
18
  * re-FETCH it when the original fetch never settled (`policy === undefined`),
@@ -50,26 +51,51 @@ export function recoverRedactionPolicy() {
50
51
  * others (their pills go idle, their lanes stop sending into it), a Start
51
52
  * is joined as a reload joins it, a pause follows. Returns the unsubscribe.
52
53
  */
54
+ /**
55
+ * Take a session record this document did not write — another tab's, or
56
+ * another recorder bundle's in this very document — with what it implies:
57
+ * an ended session drops its rules, a joined one recovers its policy and
58
+ * reconcile poll, and a policy that arrived late applies at once.
59
+ */
60
+ export function applyStoredRecord(raw) {
61
+ const had = getState()?.policy;
62
+ const change = adoptStoredState(raw);
63
+ if (change === 'unchanged')
64
+ return change;
65
+ if (change === 'ended')
66
+ setRedactionPolicy(null);
67
+ if (change === 'joined') {
68
+ recoverRedactionPolicy();
69
+ armReconcile();
70
+ }
71
+ // The starting tab writes the workspace policy after its first record:
72
+ // its rules apply here the moment they arrive.
73
+ const policy = getState()?.policy;
74
+ if (change === 'updated' && had === undefined && policy !== undefined)
75
+ setRedactionPolicy(policy);
76
+ return change;
77
+ }
78
+ /**
79
+ * Re-read the durable record before a waiting session resumes (ONE
80
+ * recorder): another recorder bundle in THIS document may have ended or
81
+ * replaced it, and storage events never reach the document that wrote them.
82
+ * True when the cached session is still the one to resume.
83
+ */
84
+ export function resyncStoredSession() {
85
+ const change = applyStoredRecord(getRecorderStorage().getString(REC_KEY) ?? null);
86
+ if (change !== 'ended' && change !== 'joined')
87
+ return true;
88
+ notify();
89
+ return false;
90
+ }
53
91
  export function followOtherTabs() {
54
92
  const storage = getRecorderStorage();
55
93
  const participant = registerRecorderTab();
56
94
  const offRec = storage.watch?.(REC_KEY, (raw) => {
57
- const had = getState()?.policy;
58
- const change = adoptStoredState(raw);
95
+ const change = applyStoredRecord(raw);
59
96
  if (change === 'unchanged')
60
97
  return;
61
98
  participant?.sync();
62
- if (change === 'ended')
63
- setRedactionPolicy(null);
64
- if (change === 'joined') {
65
- recoverRedactionPolicy();
66
- armReconcile();
67
- }
68
- // The starting tab writes the workspace policy after its first record:
69
- // its rules apply here the moment they arrive.
70
- const policy = getState()?.policy;
71
- if (change === 'updated' && had === undefined && policy !== undefined)
72
- setRedactionPolicy(policy);
73
99
  notify();
74
100
  if (getState()?.stopping)
75
101
  void participant?.settle().catch((error) => {
@@ -124,16 +150,31 @@ export function createSession(title, opts = {}) {
124
150
  },
125
151
  });
126
152
  }
153
+ /**
154
+ * Start a recording. The claim on this document comes first, synchronously
155
+ * and before any network call: while the extension (or another recorder on
156
+ * this page) leads, this rejects with a `RecorderBusyError` and nothing is
157
+ * created (ONE recorder D12).
158
+ */
127
159
  export async function startSession(opts = {}) {
160
+ claimForStart();
128
161
  // The safe defaults apply from the first captured byte; the workspace
129
162
  // policy (fetched in parallel — fetchPolicy never rejects) can only ADD
130
163
  // rules or, self-host only, fullFidelity.
131
164
  setRedactionPolicy(null);
132
165
  const policyPromise = fetchPolicy();
133
- const ses = await createSession(opts.title || '', {
134
- ...(opts.environment ? { environment: opts.environment } : {}),
135
- ...(opts.driver ? { meta: { driver: opts.driver } } : {}),
136
- });
166
+ let ses;
167
+ try {
168
+ ses = await createSession(opts.title || '', {
169
+ ...(opts.environment ? { environment: opts.environment } : {}),
170
+ ...(opts.driver ? { meta: { driver: opts.driver } } : {}),
171
+ });
172
+ }
173
+ catch (e) {
174
+ // Nothing was created: the `starting` claim goes.
175
+ settleStart(false);
176
+ throw e;
177
+ }
137
178
  void policyPromise.then(({ policy, attachments }) => {
138
179
  const rec = getState();
139
180
  if (rec?.sessionId !== ses.id)
@@ -154,6 +195,8 @@ export async function startSession(opts = {}) {
154
195
  activeMs: 0,
155
196
  resumeAt: new Date().toISOString(),
156
197
  });
198
+ // The claim moves from `starting` to `recording` with the session's id.
199
+ settleStart(true);
157
200
  resetQueues();
158
201
  resetHealth();
159
202
  resetIdle();
@@ -168,6 +211,10 @@ export async function startSession(opts = {}) {
168
211
  });
169
212
  await attachTags(ses.id, opts.tags);
170
213
  armReconcile();
214
+ // The start's nav names where the document is NOW (a recorder bundle that
215
+ // followed until this Start never heard the navigations in between) and
216
+ // seeds the nav lane's dedupe with it.
217
+ primeNavigation();
171
218
  pushEvent('nav', { url: redactUrl(currentUrl()), route: currentRoute.pathname }, { tabId: currentRoute.tabId, tabHost: currentRoute.tabHost });
172
219
  notify();
173
220
  return getState();
@@ -282,11 +329,14 @@ export async function stopSession() {
282
329
  // The other tabs leave rec at the Stop, not when the save ends; a stop
283
330
  // that keeps the session hands it back to them as it now is.
284
331
  markStopping(rec.sessionId, durationMs);
332
+ // The claim reads `stopping` while the drain runs (a remote stop or pause is refused meanwhile).
333
+ setLeadStopping(rec.sessionId);
285
334
  try {
286
335
  return await finishStop(rec, durationMs, peers);
287
336
  }
288
337
  finally {
289
338
  markStopping(null);
339
+ setLeadStopping(null);
290
340
  }
291
341
  }
292
342
  async function finishStop(rec, durationMs, peers) {
@@ -22,5 +22,14 @@ export declare const annotateState: {
22
22
  active: boolean;
23
23
  };
24
24
  export declare function setAnnotating(active: boolean): void;
25
+ /**
26
+ * ONE recorder (lead.ts): who else leads this document's recording while
27
+ * this recorder follows — `'extension'` or `'page'` (another recorder bundle
28
+ * on the page) — else null. A follower captures nothing: every lane, the
29
+ * rrweb stream and the flight recorder check it.
30
+ */
31
+ export declare const leadState: {
32
+ following: 'page' | 'extension' | null;
33
+ };
25
34
  export declare function subscribe(fn: () => void): () => void;
26
35
  export declare function notify(): void;
@@ -30,6 +30,13 @@ export function setAnnotating(active) {
30
30
  annotateState.active = active;
31
31
  notify();
32
32
  }
33
+ /**
34
+ * ONE recorder (lead.ts): who else leads this document's recording while
35
+ * this recorder follows — `'extension'` or `'page'` (another recorder bundle
36
+ * on the page) — else null. A follower captures nothing: every lane, the
37
+ * rrweb stream and the flight recorder check it.
38
+ */
39
+ export const leadState = { following: null };
33
40
  // -- change subscription (the HUD re-renders off this) -----------------------
34
41
  const listeners = new Set();
35
42
  export function subscribe(fn) {
@@ -0,0 +1,3 @@
1
+ /** Sent as `meta.recorder` and written as `data-vitrinka-page`; bumped with the package version. */
2
+ export declare const RECORDER_VERSION = "0.5.0";
3
+ export declare const RECORDER_ID = "web/0.5.0";
@@ -0,0 +1,3 @@
1
+ /** Sent as `meta.recorder` and written as `data-vitrinka-page`; bumped with the package version. */
2
+ export const RECORDER_VERSION = '0.5.0';
3
+ export const RECORDER_ID = `web/${RECORDER_VERSION}`;