@vitrinka/web 0.3.4 → 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 (69) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/README.md +93 -6
  3. package/build/hud.d.ts +4 -1
  4. package/build/hud.iife.js +46 -9
  5. package/build/one.iife.js +1 -0
  6. package/build/protocol/index.d.ts +55 -4
  7. package/build/protocol/index.js +4 -2
  8. package/build/recorder/RecorderProvider.js +48 -9
  9. package/build/recorder/api.d.ts +25 -5
  10. package/build/recorder/api.js +21 -9
  11. package/build/recorder/attachments.d.ts +19 -0
  12. package/build/recorder/attachments.js +31 -0
  13. package/build/recorder/capture/console.d.ts +2 -0
  14. package/build/recorder/capture/console.js +22 -2
  15. package/build/recorder/capture/nav.d.ts +13 -2
  16. package/build/recorder/capture/nav.js +49 -11
  17. package/build/recorder/capture/net.d.ts +2 -0
  18. package/build/recorder/capture/net.js +30 -4
  19. package/build/recorder/control.d.ts +17 -0
  20. package/build/recorder/control.js +39 -2
  21. package/build/recorder/hud/Hud.d.ts +1 -1
  22. package/build/recorder/hud/Hud.js +113 -30
  23. package/build/recorder/hud/RecorderPill.js +6 -2
  24. package/build/recorder/hud/Sheet.d.ts +40 -5
  25. package/build/recorder/hud/Sheet.js +134 -8
  26. package/build/recorder/hud/attach.d.ts +26 -0
  27. package/build/recorder/hud/attach.js +136 -0
  28. package/build/recorder/hud/chords.d.ts +10 -0
  29. package/build/recorder/hud/chords.js +34 -0
  30. package/build/recorder/hud/controller.d.ts +55 -3
  31. package/build/recorder/hud/controller.js +1 -1
  32. package/build/recorder/hud/flow.d.ts +22 -1
  33. package/build/recorder/hud/flow.js +16 -1
  34. package/build/recorder/hud/host.js +2 -0
  35. package/build/recorder/hud/icons.d.ts +3 -0
  36. package/build/recorder/hud/icons.js +7 -0
  37. package/build/recorder/hud/layer.d.ts +4 -1
  38. package/build/recorder/hud/layer.js +11 -3
  39. package/build/recorder/hud/resize.d.ts +83 -0
  40. package/build/recorder/hud/resize.js +236 -0
  41. package/build/recorder/hud/styles.d.ts +1 -1
  42. package/build/recorder/hud/styles.js +38 -1
  43. package/build/recorder/index.d.ts +1 -0
  44. package/build/recorder/index.js +1 -0
  45. package/build/recorder/lead.d.ts +90 -0
  46. package/build/recorder/lead.js +404 -0
  47. package/build/recorder/link.d.ts +4 -1
  48. package/build/recorder/link.js +6 -2
  49. package/build/recorder/me.d.ts +7 -0
  50. package/build/recorder/me.js +62 -12
  51. package/build/recorder/one-iife.d.ts +13 -0
  52. package/build/recorder/one-iife.js +13 -0
  53. package/build/recorder/one.d.ts +170 -0
  54. package/build/recorder/one.js +292 -0
  55. package/build/recorder/page-controller.js +26 -4
  56. package/build/recorder/queue.d.ts +33 -3
  57. package/build/recorder/queue.js +409 -26
  58. package/build/recorder/report.d.ts +9 -0
  59. package/build/recorder/report.js +55 -6
  60. package/build/recorder/session.d.ts +33 -7
  61. package/build/recorder/session.js +111 -31
  62. package/build/recorder/state.d.ts +9 -0
  63. package/build/recorder/state.js +7 -0
  64. package/build/recorder/storage/blobs.d.ts +32 -0
  65. package/build/recorder/storage/blobs.js +83 -0
  66. package/build/recorder/storage/index.js +3 -2
  67. package/build/recorder/version.d.ts +3 -0
  68. package/build/recorder/version.js +3 -0
  69. package/package.json +5 -3
@@ -0,0 +1 @@
1
+ (()=>{var{defineProperty:E,getOwnPropertyNames:z,getOwnPropertyDescriptor:K}=Object,B=Object.prototype.hasOwnProperty;function j(e){return this[e]}var G=(e)=>{var n=(w??=new WeakMap).get(e),t;if(n)return n;if(n=E({},"__esModule",{value:!0}),e&&typeof e==="object"||typeof e==="function"){for(var o of z(e))if(!B.call(n,o))E(n,o,{get:j.bind(e,o),enumerable:!(t=K(e,o))||t.enumerable})}return w.set(e,n),n},w;var J=(e)=>e;function W(e,n){this[e]=J.bind(null,n)}var Z=(e,n)=>{for(var t in n)E(e,t,{get:n[t],enumerable:!0,configurable:!0,set:W.bind(n,t)})};var cn={};var _={};Z(_,{ACK_EVENT:()=>C,COMMAND_EVENT:()=>x,HELLO_EVENT:()=>c,LEAD_ATTR:()=>l,ONE_VERSION:()=>u,PAGE_ATTR:()=>d,announce:()=>H,answeredBy:()=>D,ask:()=>M,documentEnv:()=>F,holderAnswers:()=>V,isLive:()=>k,markPage:()=>rn,nonce:()=>h,pageMarked:()=>an,parseAck:()=>R,parseClaim:()=>L,parseCommand:()=>P,parseHello:()=>A,readClaim:()=>b,releaseClaim:()=>tn,sendCommand:()=>ln,serializeClaim:()=>I,serveCommands:()=>dn,serveHello:()=>un,takeClaim:()=>nn,unmarkPage:()=>sn,updateClaim:()=>en,watchClaim:()=>on});function S(e,n,t,o={}){let r=e,i=r.__zone_symbol__addEventListener??e.addEventListener,a=r.__zone_symbol__removeEventListener??e.removeEventListener,p=o.capture??!1;return i.call(e,n,t,{capture:p,passive:!1}),()=>a.call(e,n,t,p)}var u=1,d="data-vitrinka-page",l="data-vitrinka-lead",c="vitrinka:hello",x="vitrinka:command",C="vitrinka:ack";function F(){let n=globalThis.document?.documentElement;if(!n||typeof globalThis.dispatchEvent!=="function")return null;return{root:n,bus:globalThis}}function h(e){return`${e}.${Math.random().toString(36).slice(2,10)}`}var q=["page","extension"],Q=["starting","recording","paused","stopping","saved"],U=["pause","stop","note"],X=["not_recording","stopping","not_here","bad_command"];function v(e){if(typeof e!=="string")return null;try{let n=JSON.parse(e);return n!==null&&typeof n==="object"&&!Array.isArray(n)?n:null}catch{return null}}var s=(e)=>typeof e==="string",f=(e)=>s(e)&&q.includes(e),T=(e)=>s(e)&&Q.includes(e),g=(e)=>typeof e==="number"&&Number.isInteger(e)&&e>=1;function L(e){let n=v(e);if(!n||!g(n.v)||!f(n.by)||!s(n.id)||!n.id||!T(n.state))return null;return{v:n.v,by:n.by,id:n.id,state:n.state,sessionId:s(n.sessionId)?n.sessionId:"",since:typeof n.since==="number"?n.since:0}}function I(e){return JSON.stringify({v:e.v,by:e.by,id:e.id,state:e.state,sessionId:e.sessionId,since:e.since})}function k(e){return e!==void 0&&e!==null&&e!=="saved"}function Y(e){if(e===null||typeof e!=="object"||Array.isArray(e))return null;let n=e;if(!f(n.by)||!T(n.state))return null;return{by:n.by,state:n.state,here:n.here===!0,...s(n.id)&&n.id?{id:n.id}:{}}}function A(e){let n=v(e);if(!n||!g(n.v)||!f(n.from)||!s(n.inst)||!n.inst)return null;let t=Y(n.live);return{v:n.v,from:n.from,inst:n.inst,...n.ask===!0?{ask:!0}:{},...n.live!==void 0?{live:t}:{},...n.gone===!0?{gone:!0}:{}}}function P(e){let n=v(e);if(!n||!g(n.v)||!f(n.from)||!s(n.inst)||!n.inst||!s(n.id)||!n.id)return null;if(!s(n.op)||!U.includes(n.op))return null;return{v:n.v,from:n.from,inst:n.inst,id:n.id,op:n.op,...s(n.text)?{text:n.text}:{}}}function R(e){let n=v(e);if(!n||!g(n.v)||!f(n.from)||!s(n.inst)||!s(n.id)||typeof n.ok!=="boolean")return null;return{v:n.v,from:n.from,inst:n.inst,id:n.id,ok:n.ok,...s(n.code)&&X.includes(n.code)?{code:n.code}:{},...s(n.error)?{error:n.error}:{}}}function b(e){return L(e.root.getAttribute(l))}function N(e,n){let t=I(n);if(e.root.getAttribute(l)!==t)e.root.setAttribute(l,t)}function nn(e,n,t){let o=b(e);if(o&&o.id!==t.id&&k(o.state)&&V(e,n,o))return{ok:!1,holder:o};let r={v:u,by:n.from,id:t.id,state:t.state,sessionId:t.sessionId??"",since:o?.id===t.id&&k(o.state)?o.since:Date.now()};return N(e,r),{ok:!0,claim:r}}function en(e,n,t){let o=b(e);if(o?.id!==n)return!1;return N(e,{...o,v:u,state:t.state,sessionId:t.sessionId??o.sessionId}),!0}function tn(e,n){if(b(e)?.id!==n)return!1;return e.root.removeAttribute(l),!0}function on(e,n){if(e.watch)return e.watch(n);if(typeof MutationObserver!=="function"||typeof Node>"u"||!(e.root instanceof Node))return()=>{return};let t=new MutationObserver(n);return t.observe(e.root,{attributes:!0,attributeFilter:[l]}),()=>t.disconnect()}function rn(e,n){if(e.root.getAttribute(d)!==n)e.root.setAttribute(d,n)}function sn(e){e.root.removeAttribute(d)}function an(e){return e.root.getAttribute(d)!==null}function y(e,n,t){e.bus.dispatchEvent(new CustomEvent(n,{detail:JSON.stringify(t)}))}function O(e,n,t){return S(e.bus,n,(o)=>t(o.detail))}function M(e,n){let t=[],o=O(e,c,(r)=>{let i=A(r);if(i&&!i.ask&&i.inst!==n.inst)t.push(i)});try{y(e,c,{v:u,from:n.from,inst:n.inst,ask:!0})}finally{o()}return t}function H(e,n,t,o={}){y(e,c,{v:u,from:n.from,inst:n.inst,live:t,...o.gone?{gone:!0}:{}})}function un(e,n,t,o,r={}){return O(e,c,(i)=>{let a=A(i);if(!a||a.inst===n.inst)return;if(!a.ask)o?.(a);else if(r.answerIf?.()??!0)H(e,n,t())})}function D(e,n){return e.some((t)=>t.live?.here===!0&&(t.live.id?t.live.id===n.id:t.from===n.by))}function V(e,n,t){return D(M(e,n),t)}function ln(e,n,t,o){let r=h("c"),i=null,a=O(e,C,(p)=>{let m=R(p);if(m&&m.id===r&&m.inst!==n.inst&&!i)i=m});try{y(e,x,{v:u,from:n.from,inst:n.inst,id:r,op:t,...o!==void 0?{text:o}:{}})}finally{a()}return i}function dn(e,n,t){return O(e,x,(o)=>{let r=P(o);if(!r||r.inst===n.inst)return;let i=t(r);if(!i)return;y(e,C,{v:u,from:n.from,inst:n.inst,id:r.id,...i})})}globalThis.VitrinkaOne=Object.freeze({..._});})();
@@ -11,8 +11,10 @@
11
11
  *
12
12
  * POST /api/v1/sessions SessionCreateRequest → SessionCreateResponse
13
13
  * POST /api/v1/sessions/:id/events { events: RecorderEvent[] }
14
- * POST /api/v1/sessions/:id/shot?seq=N (image body; the event stream
15
- * carries a matching 'shot' event)
14
+ * POST /api/v1/sessions/:id/shot?seq=N (image body, its own Content-Type;
15
+ * the event stream carries a
16
+ * matching 'shot' or 'attachment'
17
+ * event under the same seq)
16
18
  * PATCH /api/v1/sessions/:id { status: SessionStatus }
17
19
  *
18
20
  * This module is types-only and dependency-free on purpose: the vitrinka
@@ -29,12 +31,50 @@ export interface RecorderEvent {
29
31
  tabId: string;
30
32
  /** Full pathname/host context the event happened on. */
31
33
  tabHost: string;
32
- /** Event kind: 'nav' | 'click' | 'shot' | 'note' | 'net' | 'console' | … */
34
+ /** Event kind: 'nav' | 'click' | 'shot' | 'note' | 'attachment' | 'net' | 'console' | … */
33
35
  kind: string;
34
36
  payload?: Record<string, unknown>;
35
- /** Server blob reference for 'shot' events (set after upload). */
37
+ /**
38
+ * Server blob reference for 'shot' and 'attachment' events: the `blobKey`
39
+ * the `/shot?seq=N` upload of this event's bytes answered (set after upload).
40
+ */
36
41
  blobKey?: string;
37
42
  }
43
+ /** The image types `/shot` accepts. */
44
+ export type ImageMime = 'image/png' | 'image/webp' | 'image/jpeg';
45
+ /**
46
+ * Payload of an 'attachment' event — one image a tester attached to a note.
47
+ * Its bytes are uploaded FIRST through `/shot?seq=<this event's seq>` (≤ 12
48
+ * MiB, the blob's own Content-Type) and the answer's `blobKey` rides the
49
+ * event, exactly like a 'shot'. Same `tabId`/`tabHost` as its note.
50
+ */
51
+ export interface AttachmentPayload {
52
+ /** The original file name ("pasted image.png" for a paste). */
53
+ name: string;
54
+ mime: ImageMime;
55
+ /** The uploaded size in bytes. */
56
+ bytes: number;
57
+ /** Pixel size. */
58
+ w?: number;
59
+ h?: number;
60
+ }
61
+ /**
62
+ * Payload of a 'note' event. An annotation adds `rect`/`selector`/`annotate`
63
+ * (+ `task`); a note with `attachments` may have empty `text` (an image can
64
+ * BE the note), a bug report still needs its description.
65
+ */
66
+ export interface NotePayload {
67
+ text: string;
68
+ route?: string;
69
+ /**
70
+ * The seqs of the 'attachment' events this note carries, allocated BEFORE
71
+ * the note's (strictly lower) so a stream replays in order. The server
72
+ * takes at most 10 per note, tolerates one that arrives after its note and
73
+ * one that never arrives (the note lands without it).
74
+ */
75
+ attachments?: number[];
76
+ [key: string]: unknown;
77
+ }
38
78
  export interface SessionCreateRequest {
39
79
  /** App id the server resolves project+environment from. */
40
80
  app: string;
@@ -65,6 +105,17 @@ export interface SessionReconcileResponse {
65
105
  status?: string;
66
106
  deletedAt?: string | null;
67
107
  }
108
+ /** GET /api/v1/recorder/policy — read at session start. */
109
+ export interface RecorderPolicyResponse {
110
+ /** The workspace redaction policy (`@vitrinka/redact`); null = the engine's defaults. */
111
+ policy?: Record<string, unknown> | null;
112
+ fullFidelityAllowed?: boolean;
113
+ /**
114
+ * Recorders offer image attachments only on `true`: absent on a server
115
+ * before them, `false` when the workspace switched them off.
116
+ */
117
+ attachments?: boolean;
118
+ }
68
119
  /**
69
120
  * PATCH response when a session completes. The board is projected AFTER the
70
121
  * stop, so `boardUrl` is usually absent here: `projection` says how far it
@@ -11,8 +11,10 @@
11
11
  *
12
12
  * POST /api/v1/sessions SessionCreateRequest → SessionCreateResponse
13
13
  * POST /api/v1/sessions/:id/events { events: RecorderEvent[] }
14
- * POST /api/v1/sessions/:id/shot?seq=N (image body; the event stream
15
- * carries a matching 'shot' event)
14
+ * POST /api/v1/sessions/:id/shot?seq=N (image body, its own Content-Type;
15
+ * the event stream carries a
16
+ * matching 'shot' or 'attachment'
17
+ * event under the same seq)
16
18
  * PATCH /api/v1/sessions/:id { status: SessionStatus }
17
19
  *
18
20
  * This module is types-only and dependency-free on purpose: the vitrinka
@@ -7,19 +7,20 @@ import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
7
7
  */
8
8
  import { useEffect } from 'react';
9
9
  import { installClickLane } from './capture/click';
10
- import { patchConsole, unpatchConsole } from './capture/console';
11
- import { installNavLane, noteNavigation, primeNavigation } from './capture/nav';
12
- import { patchNetwork, unpatchNetwork } from './capture/net';
10
+ import { ownConsolePatch, patchConsole, unpatchConsole } from './capture/console';
11
+ import { installNavLane, noteNavigation, ownNavLane, primeNavigation } from './capture/nav';
12
+ import { ownNetworkPatch, patchNetwork, unpatchNetwork } from './capture/net';
13
13
  import { checkoutRRWeb, flushRRWeb, startFlightRRWeb, startRRWeb, stopRRWeb } from './capture/rrweb';
14
14
  import { configureRecorder } from './config';
15
15
  import { installControl } from './control';
16
16
  import { flightActive } from './flight';
17
17
  import { installUnauthorizedHandler } from './link';
18
18
  import { insideHud } from './hud/host';
19
+ import { startLead } from './lead';
19
20
  import { armReconcile, flush, getState, persistNow, reconcile, scheduleFlush } from './queue';
20
21
  import { dropFlight, syncFlight } from './report';
21
- import { followOtherTabs, onBeforeStop, recoverRedactionPolicy } from './session';
22
- import { annotateState, setTabIdentity, subscribe } from './state';
22
+ import { addNote, followOtherTabs, onBeforeStop, recoverRedactionPolicy, resyncStoredSession, stopSession, togglePause } from './session';
23
+ import { annotateState, leadState, setTabIdentity, subscribe } from './state';
23
24
  const TAB_KEY = 'vitrinka.tab';
24
25
  /** One lane per browser tab: a per-tab id kept in sessionStorage (survives reloads). */
25
26
  function tabId() {
@@ -43,13 +44,38 @@ export function RecorderProvider({ config, children, }) {
43
44
  }, [config]);
44
45
  useEffect(() => {
45
46
  setTabIdentity(tabId(), location.host);
47
+ // ONE recorder: mark the document, hear who records, then lead or follow.
48
+ // A remote command opens this recorder's own doors.
49
+ const leaveLead = startLead({
50
+ pause: () => void togglePause(),
51
+ stop: () => void stopSession().catch((e) => console.warn('vitrinka: remote stop —', e instanceof Error ? e.message : e)),
52
+ note: (text) => addNote(text),
53
+ resync: resyncStoredSession,
54
+ });
46
55
  primeNavigation();
47
56
  // The fetch/XHR and console patches are idempotent (a globalThis mark)
48
57
  // and UNINSTALLED on unmount below, so the recorder never outlives its
49
58
  // tree; the History wrap is idempotent too and stays (a nav event with no
50
59
  // session is dropped at the queue unless the flight recorder holds it).
51
- patchNetwork();
52
- patchConsole();
60
+ // They are global, so with two recorder bundles on the page the one that
61
+ // starts capturing takes them over (`own*`): whoever leads, not whoever
62
+ // mounted first, hears the traffic. A mount takes the wrappers over too
63
+ // (a stale Fast Refresh copy's, an idle bundle's) unless another bundle
64
+ // on the page leads — never from under a live recording.
65
+ /** True when the nav takeover recorded the navigation it had missed. */
66
+ const ownLanes = () => {
67
+ ownNetworkPatch();
68
+ ownConsolePatch();
69
+ return ownNavLane();
70
+ };
71
+ if (leadState.following === 'page') {
72
+ patchNetwork();
73
+ patchConsole();
74
+ }
75
+ else {
76
+ ownNetworkPatch();
77
+ ownConsolePatch();
78
+ }
53
79
  installNavLane();
54
80
  const uninstallClicks = installClickLane({
55
81
  ignore: (t) => annotateState.active || insideHud(t),
@@ -59,15 +85,27 @@ export function RecorderProvider({ config, children, }) {
59
85
  // Keep the rrweb lane in step with the session: start on record, a fresh
60
86
  // checkout on resume, ship-and-stop on stop. While idle the same lane
61
87
  // feeds the pill's flight recorder; it hands rrweb over (one record() at
62
- // a time) before a recording takes it.
88
+ // a time) before a recording takes it. A follower records nothing: its
89
+ // own session (if any) waits until the leader lets go.
63
90
  let wasRecording = false;
64
91
  let wasPaused = false;
65
92
  let wasFlying = false;
93
+ // This document's own session waited while another recorder led (D14).
94
+ let waited = false;
66
95
  const syncLanes = () => {
67
96
  void syncFlight();
68
97
  const rec = getState();
69
- const recording = rec !== null && !rec.dead;
98
+ if (rec !== null && leadState.following !== null)
99
+ waited = true;
100
+ const recording = rec !== null && !rec.dead && leadState.following === null;
70
101
  const flying = flightActive();
102
+ const caughtUp = (recording && !wasRecording) || (flying && !wasFlying) ? ownLanes() : false;
103
+ // A waiting session resumes: its timeline gets this document's nav as a
104
+ // keyframe (the mount's, captured while following, was dropped).
105
+ if (recording && !wasRecording && waited && !caughtUp)
106
+ noteNavigation(true);
107
+ if (rec === null || recording)
108
+ waited = false;
71
109
  if (wasFlying && !flying)
72
110
  stopRRWeb();
73
111
  if (recording && !wasRecording)
@@ -123,6 +161,7 @@ export function RecorderProvider({ config, children, }) {
123
161
  dropFlight();
124
162
  unpatchNetwork();
125
163
  unpatchConsole();
164
+ leaveLead();
126
165
  };
127
166
  // The lanes install once per mount; config changes are handled above.
128
167
  // eslint-disable-next-line react-hooks/exhaustive-deps
@@ -2,12 +2,13 @@
2
2
  * Vitrinka API client for the web journey recorder.
3
3
  *
4
4
  * Ingest contract, shared with the Expo recorder and the browser extension:
5
- * GET /api/v1/recorder/policy workspace redaction policy
5
+ * GET /api/v1/recorder/policy workspace redaction policy + `attachments`
6
6
  * GET /api/v1/recorder/me who the token is + HUD prefs (me.ts)
7
7
  * PATCH /api/v1/recorder/me {prefs} (me.ts)
8
8
  * POST /api/v1/sessions {host, title, environment?, meta} → session
9
9
  * POST /api/v1/sessions/:id/events {events: [...]}
10
10
  * POST /api/v1/sessions/:id/chunk?seq=N (rrweb batch body, application/json)
11
+ * POST /api/v1/sessions/:id/shot?seq=N (an attached image, its own Content-Type)
11
12
  * POST /api/v1/sessions/:id/tags {tags} (non-fatal)
12
13
  * GET /api/v1/sessions/:id reconcile
13
14
  * PATCH /api/v1/sessions/:id {status: recording|paused|done}
@@ -18,12 +19,22 @@
18
19
  import type { RedactionPolicy } from '@vitrinka/redact';
19
20
  export { permanentStatus, VitrinkaApiError } from './api-status';
20
21
  export declare function onUnauthorized(fn: () => void): () => void;
22
+ /** What the policy read decides for a session (or the idle flight recorder). */
23
+ export interface RecorderPolicy {
24
+ /** null = the engine's safe defaults. */
25
+ policy: RedactionPolicy | null;
26
+ /**
27
+ * The sheets take images: the server answered `attachments: true`. Absent
28
+ * (a server before attachments) and `false` (switched off) both read false.
29
+ */
30
+ attachments: boolean;
31
+ }
21
32
  /**
22
- * Fetch the workspace redaction policy at session start. NEVER rejects: null
23
- * (server too old, network down, 4xx) means the engine's safe defaults — fail
24
- * closed, never capture-everything.
33
+ * Fetch the workspace redaction policy at session start. NEVER rejects: a
34
+ * null policy (server too old, network down, 4xx) means the engine's safe
35
+ * defaults — fail closed, never capture-everything — and no attachments.
25
36
  */
26
- export declare function fetchPolicy(): Promise<RedactionPolicy | null>;
37
+ export declare function fetchPolicy(): Promise<RecorderPolicy>;
27
38
  export interface ApiOptions {
28
39
  /**
29
40
  * Survive page unload (the pagehide flush). Browsers cap keepalive bodies at
@@ -40,3 +51,12 @@ export declare function api<T = Record<string, unknown>>(method: string, path: s
40
51
  export declare function uploadChunk(sessionId: string, seq: number, body: string): Promise<{
41
52
  blobKey?: string;
42
53
  }>;
54
+ /**
55
+ * Upload one attached image (png, webp or jpeg; ≤ 12 MiB) under its
56
+ * `attachment` event's pre-allocated seq through the screenshot leaf, with
57
+ * the blob's own Content-Type. Returns the server's blobKey — the event
58
+ * carries it, exactly like a `shot`.
59
+ */
60
+ export declare function uploadImage(sessionId: string, seq: number, blob: Blob): Promise<{
61
+ blobKey?: string;
62
+ }>;
@@ -20,18 +20,18 @@ function reportStatus(status) {
20
20
  unauthorizedHandler?.();
21
21
  }
22
22
  /**
23
- * Fetch the workspace redaction policy at session start. NEVER rejects: null
24
- * (server too old, network down, 4xx) means the engine's safe defaults — fail
25
- * closed, never capture-everything.
23
+ * Fetch the workspace redaction policy at session start. NEVER rejects: a
24
+ * null policy (server too old, network down, 4xx) means the engine's safe
25
+ * defaults — fail closed, never capture-everything — and no attachments.
26
26
  */
27
27
  export async function fetchPolicy() {
28
28
  try {
29
29
  const res = await api('GET', '/api/v1/recorder/policy');
30
- return res.policy ?? null;
30
+ return { policy: res.policy ?? null, attachments: res.attachments === true };
31
31
  }
32
32
  catch (e) {
33
33
  console.warn('vitrinka: redaction policy fetch failed — using safe defaults', e);
34
- return null;
34
+ return { policy: null, attachments: false };
35
35
  }
36
36
  }
37
37
  export async function api(method, path, body, opts = {}) {
@@ -60,20 +60,32 @@ export async function api(method, path, body, opts = {}) {
60
60
  * under a pre-allocated seq. Returns the server's blobKey — the matching
61
61
  * `rrweb` event row carries it.
62
62
  */
63
- export async function uploadChunk(sessionId, seq, body) {
63
+ export function uploadChunk(sessionId, seq, body) {
64
+ return upload(sessionId, 'chunk', seq, 'application/json', body);
65
+ }
66
+ /**
67
+ * Upload one attached image (png, webp or jpeg; ≤ 12 MiB) under its
68
+ * `attachment` event's pre-allocated seq through the screenshot leaf, with
69
+ * the blob's own Content-Type. Returns the server's blobKey — the event
70
+ * carries it, exactly like a `shot`.
71
+ */
72
+ export function uploadImage(sessionId, seq, blob) {
73
+ return upload(sessionId, 'shot', seq, blob.type, blob);
74
+ }
75
+ async function upload(sessionId, leaf, seq, contentType, body) {
64
76
  const { url } = recorderConfig();
65
77
  const key = bearerToken();
66
- const res = await fetch(`${url}/api/v1/sessions/${sessionId}/chunk?seq=${seq}`, {
78
+ const res = await fetch(`${url}/api/v1/sessions/${sessionId}/${leaf}?seq=${seq}`, {
67
79
  method: 'POST',
68
80
  mode: 'cors',
69
81
  credentials: 'omit',
70
- headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json' },
82
+ headers: { authorization: `Bearer ${key}`, 'content-type': contentType },
71
83
  body,
72
84
  });
73
85
  const text = await res.text();
74
86
  if (!res.ok) {
75
87
  reportStatus(res.status);
76
- throw new VitrinkaApiError(`POST chunk seq ${seq} → ${res.status}: ${text}`, res.status);
88
+ throw new VitrinkaApiError(`POST ${leaf} seq ${seq} → ${res.status}: ${text}`, res.status);
77
89
  }
78
90
  try {
79
91
  return JSON.parse(text);
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The host half of recorder attachments: what an image must be to ride the
3
+ * wire — png, webp or jpeg, ≤ 12 MiB, what `/shot` accepts — and how many one
4
+ * note carries (the server takes 10 and ignores the rest). The HUD already
5
+ * normalizes what it hands over (hud/attach.ts); this gate stands for any
6
+ * other caller of the controller, dropping what the server would refuse
7
+ * instead of uploading it.
8
+ */
9
+ import type { AttachmentPayload } from '../protocol';
10
+ import type { HudAttachment } from './hud/controller';
11
+ /** What the server keeps of one note; the rest is never uploaded. */
12
+ export declare const NOTE_ATTACHMENT_CAP = 10;
13
+ /** One image ready for the queue: its event payload and its bytes. */
14
+ export interface StagedImage {
15
+ payload: AttachmentPayload;
16
+ blob: Blob;
17
+ }
18
+ /** The images of one note that can ride, in order; each one left out is said once. */
19
+ export declare function stageAttachments(list: readonly HudAttachment[] | undefined): StagedImage[];
@@ -0,0 +1,31 @@
1
+ import { MAX_ATTACHMENT_BYTES } from './hud/attach';
2
+ /** What the server keeps of one note; the rest is never uploaded. */
3
+ export const NOTE_ATTACHMENT_CAP = 10;
4
+ const MIMES = ['image/png', 'image/webp', 'image/jpeg'];
5
+ /** The images of one note that can ride, in order; each one left out is said once. */
6
+ export function stageAttachments(list) {
7
+ const out = [];
8
+ for (const a of list ?? []) {
9
+ if (out.length >= NOTE_ATTACHMENT_CAP) {
10
+ console.warn(`vitrinka: a note carries at most ${NOTE_ATTACHMENT_CAP} images — the rest are left out`);
11
+ break;
12
+ }
13
+ const mime = MIMES.find((m) => m === a.blob.type);
14
+ if (!mime || a.blob.size === 0 || a.blob.size > MAX_ATTACHMENT_BYTES) {
15
+ const why = !mime ? `${a.blob.type || 'an untyped blob'} is not png, webp or jpeg` : a.blob.size ? 'over 12 MiB' : 'empty';
16
+ console.warn(`vitrinka: attachment ${a.name} left out — ${why}`);
17
+ continue;
18
+ }
19
+ out.push({
20
+ blob: a.blob,
21
+ payload: {
22
+ name: a.name,
23
+ mime,
24
+ bytes: a.blob.size,
25
+ ...(a.w > 0 ? { w: Math.round(a.w) } : {}),
26
+ ...(a.h > 0 ? { h: Math.round(a.h) } : {}),
27
+ },
28
+ });
29
+ }
30
+ return out;
31
+ }
@@ -1,3 +1,5 @@
1
1
  /** Restore console.error (while it is still ours) and drop the window listeners. */
2
2
  export declare function unpatchConsole(): void;
3
+ /** Make this module's wrapper the live one (a no-op when it already is). */
4
+ export declare function ownConsolePatch(): void;
3
5
  export declare function patchConsole(): void;
@@ -34,15 +34,35 @@ function record(text) {
34
34
  pushEvent('console', { level: 'error', text: redactText(text) }, { tabId: currentRoute.tabId, tabHost: currentRoute.tabHost });
35
35
  }
36
36
  const UNPATCH_MARK = '__vitrinkaRecorderConsoleUnpatch';
37
+ /**
38
+ * This module instance's mark. The wrappers are global, so the mark says WHOSE
39
+ * are live: another recorder bundle's on the page, or a stale Fast Refresh
40
+ * copy's. `ownConsolePatch` hands them to this one (ONE recorder: whoever leads
41
+ * captures, not whoever mounted first).
42
+ */
43
+ const OWNER = {};
37
44
  /** Restore console.error (while it is still ours) and drop the window listeners. */
38
45
  export function unpatchConsole() {
39
- globalThis[UNPATCH_MARK]?.();
46
+ const g = globalThis;
47
+ // Another bundle's live wrapper is its own to remove.
48
+ if (g[PATCH_MARK] !== undefined && g[PATCH_MARK] !== OWNER)
49
+ return;
50
+ g[UNPATCH_MARK]?.();
51
+ }
52
+ /** Make this module's wrapper the live one (a no-op when it already is). */
53
+ export function ownConsolePatch() {
54
+ const g = globalThis;
55
+ if (g[PATCH_MARK] === OWNER)
56
+ return;
57
+ g[UNPATCH_MARK]?.();
58
+ delete g[PATCH_MARK];
59
+ patchConsole();
40
60
  }
41
61
  export function patchConsole() {
42
62
  const g = globalThis;
43
63
  if (g[PATCH_MARK])
44
64
  return;
45
- g[PATCH_MARK] = true;
65
+ g[PATCH_MARK] = OWNER;
46
66
  const origError = console.error;
47
67
  const orig = origError.bind(console);
48
68
  const patched = (...args) => {
@@ -1,8 +1,19 @@
1
- /** Record a navigation to the document's current URL (idempotent per URL). */
2
- export declare function noteNavigation(): void;
1
+ /**
2
+ * Record a navigation to the document's current URL (idempotent per URL;
3
+ * `force` records it again — the keyframe of a session that resumes here).
4
+ * True when it recorded one.
5
+ */
6
+ export declare function noteNavigation(force?: boolean): boolean;
3
7
  /** Seed the dedupe with the URL the session started on (its nav is pushed by startSession). */
4
8
  export declare function primeNavigation(): void;
5
9
  /** Wrap pushState/replaceState + popstate/hashchange. Idempotent across HMR. */
6
10
  export declare function installNavLane(): void;
11
+ /**
12
+ * Make this module's History wrap the live one (ONE recorder): the first
13
+ * recorder bundle on the page installs it, but whichever bundle leads must
14
+ * hear the navigations. A no-op when it already is; true when the takeover
15
+ * recorded the navigation it had missed.
16
+ */
17
+ export declare function ownNavLane(): boolean;
7
18
  /** Test-only. */
8
19
  export declare function __resetNavForTests(): void;
@@ -9,17 +9,21 @@ import { pushEvent } from '../queue';
9
9
  import { currentRoute, setCurrentPath } from '../state';
10
10
  import { redactUrl } from './redact';
11
11
  let lastUrl = '';
12
- /** Record a navigation to the document's current URL (idempotent per URL). */
13
- export function noteNavigation() {
12
+ /**
13
+ * Record a navigation to the document's current URL (idempotent per URL;
14
+ * `force` records it again — the keyframe of a session that resumes here).
15
+ * True when it recorded one.
16
+ */
17
+ export function noteNavigation(force = false) {
14
18
  const loc = globalThis.location;
15
19
  if (!loc)
16
- return;
20
+ return false;
17
21
  const url = loc.href;
18
22
  setCurrentPath(loc.pathname);
19
- if (url === lastUrl)
20
- return;
23
+ if (url === lastUrl && !force)
24
+ return false;
21
25
  lastUrl = url;
22
- pushEvent('nav', { url: redactUrl(url), route: loc.pathname, spa: true }, { tabId: currentRoute.tabId, tabHost: currentRoute.tabHost });
26
+ return null !== pushEvent('nav', { url: redactUrl(url), route: loc.pathname, spa: true }, { tabId: currentRoute.tabId, tabHost: currentRoute.tabHost });
23
27
  }
24
28
  /** Seed the dedupe with the URL the session started on (its nav is pushed by startSession). */
25
29
  export function primeNavigation() {
@@ -27,26 +31,60 @@ export function primeNavigation() {
27
31
  setCurrentPath(globalThis.location?.pathname ?? '/');
28
32
  }
29
33
  const PATCH_MARK = '__vitrinkaRecorderNavPatched';
34
+ const UNPATCH_MARK = '__vitrinkaRecorderNavUnpatch';
35
+ /** This module instance's mark — whose History wrap is live (see `ownNavLane`). */
36
+ const OWNER = {};
30
37
  /** Wrap pushState/replaceState + popstate/hashchange. Idempotent across HMR. */
31
38
  export function installNavLane() {
32
39
  const g = globalThis;
33
40
  if (g[PATCH_MARK] || typeof history === 'undefined')
34
41
  return;
35
- g[PATCH_MARK] = true;
42
+ g[PATCH_MARK] = OWNER;
43
+ const restores = [];
36
44
  const wrap = (name) => {
37
45
  const orig = history[name];
38
- history[name] = function (...args) {
46
+ const wrapped = (history[name] = function (...args) {
39
47
  const r = orig.apply(this, args);
40
48
  // After the URL changed, off the caller's stack so a router's own
41
49
  // synchronous state update never sees the recorder in its way.
42
50
  queueMicrotask(noteNavigation);
43
51
  return r;
44
- };
52
+ });
53
+ // Restored only while it is still ours: a wrap stacked on top keeps ours beneath it.
54
+ restores.push(() => {
55
+ if (history[name] === wrapped)
56
+ history[name] = orig;
57
+ });
45
58
  };
46
59
  wrap('pushState');
47
60
  wrap('replaceState');
48
- addEventListener('popstate', () => queueMicrotask(noteNavigation));
49
- addEventListener('hashchange', () => queueMicrotask(noteNavigation));
61
+ const onNav = () => queueMicrotask(noteNavigation);
62
+ addEventListener('popstate', onNav);
63
+ addEventListener('hashchange', onNav);
64
+ g[UNPATCH_MARK] = () => {
65
+ for (const r of restores.splice(0))
66
+ r();
67
+ removeEventListener('popstate', onNav);
68
+ removeEventListener('hashchange', onNav);
69
+ delete g[PATCH_MARK];
70
+ delete g[UNPATCH_MARK];
71
+ };
72
+ }
73
+ /**
74
+ * Make this module's History wrap the live one (ONE recorder): the first
75
+ * recorder bundle on the page installs it, but whichever bundle leads must
76
+ * hear the navigations. A no-op when it already is; true when the takeover
77
+ * recorded the navigation it had missed.
78
+ */
79
+ export function ownNavLane() {
80
+ const g = globalThis;
81
+ if (g[PATCH_MARK] === OWNER)
82
+ return false;
83
+ g[UNPATCH_MARK]?.();
84
+ delete g[PATCH_MARK];
85
+ installNavLane();
86
+ // The navigations before the takeover reached the other bundle only: catch up.
87
+ return noteNavigation();
50
88
  }
51
89
  /** Test-only. */
52
90
  export function __resetNavForTests() {
@@ -19,4 +19,6 @@ export declare function __readBoundedTextForTests(clone: Response, headers: Head
19
19
  * (no session ⇒ the wrapper passes straight through).
20
20
  */
21
21
  export declare function unpatchNetwork(): void;
22
+ /** Make this module's wrappers the live ones (a no-op when they already are). */
23
+ export declare function ownNetworkPatch(): void;
22
24
  export declare function patchNetwork(): void;
@@ -16,7 +16,7 @@
16
16
  import { isVitrinkaUrl } from '../config';
17
17
  import { flightTarget } from '../flight';
18
18
  import { getState, pushEvent, trackCapture } from '../queue';
19
- import { currentRoute } from '../state';
19
+ import { currentRoute, leadState } from '../state';
20
20
  import { redactAndCap, redactHeaders, redactUrl } from './redact';
21
21
  const BODY_CAP = 64 * 1024;
22
22
  /**
@@ -47,6 +47,9 @@ function capturing() {
47
47
  * null), else the idle flight recorder's buffer, else null.
48
48
  */
49
49
  function captureTarget() {
50
+ // A follower captures nothing (ONE recorder D2).
51
+ if (leadState.following)
52
+ return null;
50
53
  const rec = getState();
51
54
  if (rec)
52
55
  return !rec.paused && !rec.dead ? rec.sessionId : null;
@@ -343,6 +346,13 @@ export function __readBoundedTextForTests(clone, headers) {
343
346
  const PATCH_MARK = '__vitrinkaRecorderNetPatched';
344
347
  /** The uninstaller of the live patch, kept on globalThis for the same reason as the mark. */
345
348
  const UNPATCH_MARK = '__vitrinkaRecorderNetUnpatch';
349
+ /**
350
+ * This module instance's mark. The wrappers are global, so the mark says WHOSE
351
+ * are live: another recorder bundle's on the page, or a stale Fast Refresh
352
+ * copy's. `ownNetworkPatch` hands them to this one (ONE recorder: whoever leads
353
+ * captures, not whoever mounted first).
354
+ */
355
+ const OWNER = {};
346
356
  /**
347
357
  * Remove the fetch/XHR wrappers installed by `patchNetwork` — the provider's
348
358
  * unmount calls it so the recorder never outlives its tree. Each global is
@@ -353,13 +363,25 @@ const UNPATCH_MARK = '__vitrinkaRecorderNetUnpatch';
353
363
  */
354
364
  export function unpatchNetwork() {
355
365
  const g = globalThis;
366
+ // Another bundle's live wrappers are its own to remove.
367
+ if (g[PATCH_MARK] !== undefined && g[PATCH_MARK] !== OWNER)
368
+ return;
369
+ g[UNPATCH_MARK]?.();
370
+ }
371
+ /** Make this module's wrappers the live ones (a no-op when they already are). */
372
+ export function ownNetworkPatch() {
373
+ const g = globalThis;
374
+ if (g[PATCH_MARK] === OWNER)
375
+ return;
356
376
  g[UNPATCH_MARK]?.();
377
+ delete g[PATCH_MARK];
378
+ patchNetwork();
357
379
  }
358
380
  export function patchNetwork() {
359
381
  const g = globalThis;
360
382
  if (g[PATCH_MARK])
361
383
  return;
362
- g[PATCH_MARK] = true;
384
+ g[PATCH_MARK] = OWNER;
363
385
  const restores = [];
364
386
  g[UNPATCH_MARK] = () => {
365
387
  for (const r of restores.splice(0))
@@ -396,9 +418,13 @@ export function patchNetwork() {
396
418
  const status = res.status;
397
419
  trackCapture((async () => {
398
420
  // Re-check AFTER the await, and require the SAME session — the run may
399
- // have been paused/stopped meanwhile.
400
- if (!stillCapturing(origin))
421
+ // have been paused/stopped meanwhile, or another recorder took the
422
+ // lead. An abandoned clone is cancelled, never left buffering its tee.
423
+ if (!stillCapturing(origin)) {
424
+ if (clone)
425
+ discard(clone);
401
426
  return;
427
+ }
402
428
  const resBody = clone ? await readBoundedBody(clone, headers) : undefined;
403
429
  if (!stillCapturing(origin))
404
430
  return;