@replayd/core 0.1.4 → 0.1.6

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.
@@ -15,24 +15,21 @@ export declare const own: (u: string) => boolean;
15
15
  type A = any;
16
16
  /** merges a remote config (PRD §4.12) over the local options */
17
17
  export declare const applyRc: (c: A) => void;
18
- /** cached remote config `{t, c}` (localStorage, 10 min or `ttl`) */
19
- export declare const cachedRc: () => {
18
+ export declare const dbgOn: () => boolean;
19
+ export declare const drop: () => number;
20
+ type C = {
20
21
  t: number;
21
22
  c: A;
22
- } | null;
23
+ };
24
+ export declare const cachedRc: () => C | null;
23
25
  /**
24
26
  * First localStorage access (~0.5 ms cold in Chromium), deliberately kept off the init() path: applies the
25
27
  * persisted X-Replayd-Disable and the cached remote config. Runs before the first upload and at load+idle.
26
28
  */
27
- export declare const ready: () => {
28
- t: number;
29
- c: A;
30
- } | null;
31
- export declare const stale: (cc: {
32
- t: number;
33
- c: A;
34
- } | null) => boolean;
29
+ export declare const ready: () => C | null;
30
+ export declare const stale: (cc: C | null) => any;
35
31
  /** fetches remote config, caches + applies it. Network failures are ignored (local config stays). `ids` = session,
36
- * user and device id, sent hashed so the server can answer a remote debug target (T-146). */
37
- export declare const fetchRc: (f: typeof fetch, hdr: (r: Response) => void, ids?: unknown[]) => Promise<void>;
32
+ * user and device id, sent hashed so the server can answer a remote debug target (T-146); its answer counts only
33
+ * while the ids are still the ones asked for, and while a match lasts the page asks again before it lapses. */
34
+ export declare const fetchRc: (f: typeof fetch, hdr: (r: Response) => void, ids: () => unknown[]) => Promise<void>;
38
35
  export {};
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * Rage click (T-115): the 3rd click on one element within 1 s of the burst's first click, once per burst.
6
6
  * Dead click (T-115): a click on a clickable element after which, for 3 s, the page records no DOM change, input,
7
- * scroll, page change, tab change or request started after the click. On a page whose DOM changes all the time
7
+ * scroll, page change, tab change or request started after the click (counted when it starts, not when it ends). On a page whose DOM changes all the time
8
8
  * (tickers without `data-rp-throttle`) dead clicks cannot be told apart and are not reported.
9
9
  *
10
10
  * Freeze (T-116): a main-thread stall of ≥ 200 ms: a long animation frame (Chromium 123+, with the script that ran
@@ -6,6 +6,10 @@ export declare const rec: (type: RingEvent["type"], data: RingEvent["data"], ts?
6
6
  /** drains the ring (oldest first); WS frames and network bodies are redacted here, lazily, never on the hot path */
7
7
  export declare const drain: () => RingEvent[];
8
8
  export declare const setSink: (f: typeof sink) => void;
9
+ /** request-start marker for dead-click detection (set by the replay chunk): a request that has not finished is activity */
10
+ export declare const go: {
11
+ f?: (() => void) | null;
12
+ };
9
13
  /** the replay chunk is recording this page (its sink is attached) */
10
14
  export declare const live: () => boolean;
11
15
  export declare let crumbs: Breadcrumb[];
@@ -21,7 +21,9 @@ export interface ReplayOptions {
21
21
  /** Per-session replay sample rate, decided once per session. Default 1. */
22
22
  sampleRate?: number;
23
23
  start?: 'idle';
24
- /** URLs whose request/response headers + bodies are captured. `'self'` = `location.origin`. */
24
+ /** URLs whose request/response headers + bodies are captured. `'self'` = exactly `location.origin`; an origin or URL
25
+ * (`https://api.example.com`, `https://x.example/v1`), `//host[:port]` or `/path` matches that origin and that path or a
26
+ * path below it, never a substring; a RegExp is tested against the whole URL. */
25
27
  networkDetailAllowUrls?: Matcher[];
26
28
  networkCaptureBodies?: boolean;
27
29
  maskAllText?: boolean;
@@ -210,6 +212,10 @@ export interface Internal {
210
212
  drain: () => RingEvent[];
211
213
  /** live custom events go to `f` instead of the ring buffer (null = back to ring) */
212
214
  sink: (f: ((e: RingEvent) => void) | null) => void;
215
+ /** `go.f`: called when the app starts a request (the SDK's own excluded), null = off: the dead-click check's activity marker */
216
+ go: {
217
+ f?: (() => void) | null;
218
+ };
213
219
  /** registers the "force segment flush" hook called on every captured error */
214
220
  onError: (f: () => void) => void;
215
221
  /** capture currently enabled (kill switch / X-Replayd-Disable / close) */
@@ -257,12 +263,14 @@ export interface Internal {
257
263
  /** queues a ready event through `beforeSend` (false: dropped); used by `@replayd/core/flows` (T-153) */
258
264
  ev: (e: ReplaydEvent) => boolean;
259
265
  platform: 'web' | 'capacitor-android' | 'capacitor-ios';
266
+ /** T-146: a remote debug target matches this session/user/device right now */
267
+ d: () => boolean;
260
268
  }
261
269
  export interface Resolved extends ReplaydOptions {
262
270
  replay: ReplayOptions & {
263
271
  sampleRate: number;
264
272
  networkDetailAllowUrls: Matcher[];
265
- canvas: Required<Omit<CanvasOptions, 'groupBy'>>;
273
+ canvas: CanvasOptions;
266
274
  };
267
275
  /** `channelOf` (default 'centrifugo-json') and `sample.outgoing` (default 'all') are defaulted by their consumers */
268
276
  websocket: Required<Pick<WebSocketOptions, 'enabled' | 'urls'>> & WebSocketOptions & {
@@ -275,6 +283,4 @@ export interface Resolved extends ReplaydOptions {
275
283
  errors: Required<ErrorOptions>;
276
284
  redact: Required<RedactOptions>;
277
285
  signals: SignalOptions;
278
- /** T-146: 1 while a remote debug target matches this session/user/device */
279
- dbg?: number;
280
286
  }
@@ -8,16 +8,18 @@
8
8
  * judged from the frames that passed, so on a busy socket it can be a sampling effect: the event says `sampled`.
9
9
  */
10
10
  type A = any;
11
- declare const rpx: (sm: number, path: string) => {
11
+ declare const rpx: (sm: number, path: string, gate: number, sig: (x: A) => void, post: (st: [string, number, number][]) => void) => {
12
12
  /** an incoming Centrifugo push of channel `ch` (`o` = the parsed line) on socket `id`, received at `ts` */
13
13
  f(ch: string, o: A, ts: number, id: number): void;
14
14
  /** any event of the segment: a closed socket's channels and unsubscribed channels are not stale */
15
15
  e(e: A): void;
16
+ /** the main thread's page state: hidden, or asleep (idle expiry) = nothing is judged; shown / awake again restarts the clock */
17
+ p(off: number): void;
16
18
  /**
17
- * a segment cut: `hide` = the page is being hidden. Adds `sig` events through `add`, returns the channels that
18
- * went silent while the page was visible (≤ 1 per channel per minute) for the main thread's warning.
19
+ * a segment cut. Adds `sig` events through `add`, returns the channels that went silent while the page was
20
+ * visible (≤ 1 per channel per minute) for the main thread's warning.
19
21
  */
20
- c(hide: boolean, gate: number, add: (x: A) => void): [string, number, number][];
22
+ c(gate: number, add: (x: A) => void): [string, number, number][];
21
23
  };
22
24
  export type Rpx = ReturnType<typeof rpx>;
23
25
  export {};
package/dist/worker.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";(()=>{var e,t,a,r,s=new TextEncoder,n={redact:{headers:[],bodyKeys:[],queryParams:[]}},i=0,l=()=>i,o=e=>{let t=n.redact;e.headers.length+e.bodyKeys.length+e.queryParams.length!=t.headers.length+t.bodyKeys.length+t.queryParams.length&&(n.redact=e,i++)},d="[Filtered]",f=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=-1,g=()=>{if(u==l())return;u=l();let a=n.redact.bodyKeys.map(f).join("|");e=new RegExp(`([?&#;](?:${n.redact.queryParams.map(f).join("|")}|${a})=)[^&#;]*`,"gi"),t=new RegExp(`("(?:${a})"\\s*:\\s*)("(?:[^"\\\\]|\\\\.)*"?|[^,}\\]\\s]+)|((?:^|&)(?:${a})=)[^&\\s]*`,"gi")},p=(e,t=0)=>{if(!e||"object"!=typeof e)return e;if(t>7)return"[Depth]";if(Array.isArray(e))return e.map(e=>p(e,t+1));let a=Object.create(null);for(let r in e)a[r]=n.redact.bodyKeys.includes(r.toLowerCase())?d:p(e[r],t+1);return a},h=e=>{g();let a=e.trimStart()[0];if(("{"==a||"["==a)&&e.length<1e5)try{return JSON.stringify(p(JSON.parse(e)))}catch{}return e.includes("\n")?e.split("\n").map(h).join("\n"):e.replace(t,(e,t,a,r)=>t?`${t}"${d}"`:r+d)},c=null,y=(e,t,a)=>(c??=new Promise((e,t)=>{let a=indexedDB.open("replayd",1);a.onupgradeneeded=()=>{for(let e of["q","e"])a.result.createObjectStore(e,{autoIncrement:!0})},a.onsuccess=()=>e(a.result),a.onerror=()=>t(a.error)})).catch(e=>{throw c=null,e}).then(r=>new Promise((s,n)=>{let i=r.transaction(e,t?"readwrite":"readonly"),l=a(i.objectStore(e));i.oncomplete=()=>s(l?l.result:void 0),i.onerror=i.onabort=()=>n(i.error)})),m=(e,t)=>y(e,!0,e=>{e.delete(t)}),w=self,b=5<<20,v="",M=0,x=1,S=new Map,j=0,$=0,q=20,O=new Set,k=0,P=0,T=((e,t)=>{let a,r=[],s=0,n=0,i=0,l=0,o=0,d=0,f=0,u=0,g=[],p={},h=[],c=[],y=[],m=e=>y.length<30&&!y.includes(e)&&y.push(e),w=e=>"string"==typeof e&&(m("u:"+e),g.length<10&&!g.includes(e)&&g.push(e)),b=()=>{r=[],s=n=l=o=d=f=u=0,g=[],p={},h=[],a=void 0,c=[],y=[]};return{raw:()=>s,n:()=>n,reset:b,add(g){let y=g.data,b=g.timestamp;if(4==g.type&&y.href)w(y.href=e.u(y.href));else if(3==g.type&&2==y.source&&2==y.type)o++;else if(5==g.type){let r=y.payload;if("error"==y.tag)"warning"==r.level?f++:d++;else if("sig"==y.tag)p[r.k]=(p[r.k]??0)+1,"vitals"==r.k&&h.push(r),"lag"==r.k&&(u=Math.max(u,r.max)),"mem"==r.k&&(a={...a,...r,used:Math.max(a?.used??0,r.used??0)});else if("fields"==y.tag)r.value=e.j(r.value);else if("nav"==y.tag&&"string"==typeof r.to)w(r.to=e.u(r.to));else if("network"==y.tag){for(let t of["reqBody","resBody"])"string"==typeof r[t]&&(r[t]=e.t(r[t]));(r.status>=400||0===r.status)&&c.length<10&&!c.includes(r.status)&&c.push(r.status)}else if("breadcrumb"==y.tag)m(("c:"+r.cat+":"+r.msg).slice(0,100));else if("ws"==y.tag&&"string"==typeof r.raw){if(t&&"in"==r.dir){let e=t(r.raw,b,r.id);if(null==e)return;r.raw=e}r.raw=e.t(r.raw)}}n++||(i=b),b>l&&(l=b);let v=JSON.stringify(g);s+=v.length,r.push(v)},take(t,s){t.init&&(t.init.url=e.u(t.init.url),t.init.ref=e.u(t.init.ref),t.init.user=e.j(t.init.user)),t.fields&&(t.fields.user=e.j(t.fields.user),t.fields.custom_fields=e.j(t.fields.custom_fields),t.fields.tags=e.j(t.fields.tags),(new TextEncoder).encode(JSON.stringify(t.fields.tags)).length>8192&&delete t.fields.tags),s&&r.unshift(JSON.stringify({type:5,timestamp:i,data:{tag:"gap",payload:{reason:"dropped",segments:s}}}));let m=JSON.stringify({canvas_bytes:0,...t,t0:i,t1:l,enc:"gzip",n,urls:g,clicks:o,errs:d,warns:f,sig:p,vitals:h,mem:a,st:c,tr:y,lag:u||void 0,has_error:d>0,gap:s>0}),w=`[${r.join(",")}]`;return b(),[m,w]}}})({u:t=>(g(),t.replace(e,`$1${d}`)),t:h,j:p},(e,t,r)=>M?((e,t,r)=>{let s=[];for(let n of e.split("\n")){let e,i;try{e=(i=JSON.parse(n)).push?.channel}catch{}if("string"==typeof e){if(a?.f(e,i,t,r),t-(S.get(e)??-1e15)<1e3/x)continue;S.size>999&&(S=new Map),S.set(e,t)}s.push(n)}return s.join("\n")})(e,t,r)||null:e),U=[],J=0,N=0,B=0,D=new Map,_=0,A=e=>{if(a?.e(e),2==e.type){_=Math.max(_,e.timestamp);for(let[t,[,a]]of D)a<e.timestamp&&D.delete(t)}T.add(e)},C=[],K=0,E=0,L=0,R=!1,z=e=>{let t=C.indexOf(e);t>=0&&(K-=C.splice(t,1)[0].b.length),e.s&&w.postMessage([3,e.s])},I=(e,t)=>{e.f=!0,E++,fetch(v,{method:"POST",body:e.b,keepalive:t,credentials:"omit",headers:{"Content-Type":"text/plain"}}).then(e=>{let t=+(e.headers.get("x-replayd-disable")??0);t>0&&w.postMessage([1,t]);let a=e.status;return a<400?0:a<500&&429!=a?-2:+(e.headers.get("retry-after")??0)||-1},()=>-1).then(t=>{if(e.f=!1,E--,t>-2&&t&&++e.n<5)return clearTimeout(L),R=t>0,void(L=setTimeout(()=>{L=0,G()},t>0?1e3*t:Math.min(6e4,500*2**e.n)));j&&-1==t?z(e):(t&&P++,F(e),G())})},F=e=>{z(e),e.p?.then(e=>null!=e&&m("q",e)).catch(()=>{})},V=async e=>{if(e&&L&&!R&&(clearTimeout(L),L=0,G()),!$){$=1;try{let e=new Set(await Promise.all(C.map(e=>e.p))),[t,a]=await(()=>{let e=[],t=[],a=0,r=0;return y("q",!0,s=>{let n=Date.now(),i=s.openCursor();i.onsuccess=()=>{let l=i.result;if(l)return t.push([l.primaryKey,l.value]),void l.continue();for(let i=t.length-1;i>=0;i--){let[l,o]=t[i];n-o.t>864e5||(r+=o.b.byteLength)>20971520?(s.delete(l),a++):e.unshift([l,o])}}}).then(()=>[e,a])})();P+=a;for(let[a,r]of t)if(!(e.has(a)||K+r.b.byteLength>b)){if(r.s&&O.has(r.s)){m("q",a).catch(()=>{});continue}C.push({b:r.b,n:0,p:Promise.resolve(a)}),K+=r.b.byteLength}}catch{}$=0,G()}},G=e=>{if(!e&&(E||L))return;let t=6e4;for(let a of C){if(a.f)continue;let r=a.b.length;if(!e)return I(a,r<6e4);let s=r<t;s&&(t-=r),I(a,s)}},H=async(e,t,a,r,n)=>{let i=function(e,t,a=[]){let r=s.encode(e);if(r.length>32768)throw new RangeError("meta too large");let n=2+r.length+4+t.length+2;for(let e of a)n+=9+e.data.length;let i=new Uint8Array(n),l=new DataView(i.buffer),o=0;l.setUint16(o,r.length,!0),o+=2,i.set(r,o),o+=r.length,l.setUint32(o,t.length,!0),o+=4,i.set(t,o),o+=t.length,l.setUint16(o,a.length,!0),o+=2;for(let e of a)l.setUint32(o,e.id,!0),o+=4,i[o++]=e.type,l.setUint32(o,e.data.length,!0),o+=4,i.set(e.data,o),o+=e.data.length;return i}(e,new Uint8Array(await new Response(new Blob([t]).stream().pipeThrough(new CompressionStream("gzip"))).arrayBuffer()),n),l={b:i,n:0,s:a};j&&(l.p=((e,t)=>y("q",!0,e=>e.add(t)))(0,{t:Date.now(),b:i}).catch(()=>{})),C.push(l),K+=i.length;for(let e=0;K>b&&e<C.length-1;)C[e].f?e++:(z(C[e]),j||P++);G(r)};w.onmessage=e=>{let t=e.data;try{if(1==t[0]){t[2]&&o(t[2]);for(let e of t[1])A(e)}else if(2==t[0]){t[5]&&o(t[5]);for(let e of t[4]??[])A(e);let e=t[1],a=t[2].split("\0"),r=[];for(let t=0;t<e.length;t++)r.push({id:e[t],value:a[t]});A({type:3,timestamp:t[3],data:{source:0,texts:r,attributes:[],removes:[],adds:[]}})}else if(3==t[0])((e,t,s)=>{o(t);let n=a?.c(s,q,e=>A({type:5,timestamp:Date.now(),data:{tag:"sig",payload:e}}));n?.length&&w.postMessage([8,n]),r&&r.sid==e.sid&&(e.init??=r.init,e.fields??=r.fields,e.ws_disc+=r.ws_disc),r=0;let i=`${e.sid}:${e.seq}`;if(!T.n())return r=e,void w.postMessage([3,i]);let[l,d]=T.take({...e,canvas_bytes:J},P),f=U;return k=P=J=0,U=[],H(l,d,i,s,f)})(t[1],t[2],t[3])?.catch(()=>{});else if(5==t[0])T.reset(),U=[],k=J=0,D.clear(),t[1]&&G(!0);else if(6==t[0]){let e=JSON.parse(t[1]),a=`${e.sid}:${e.seq}`;O.add(a),P+=0|t[3],H(t[1],t[2],a).catch(()=>{})}else 7==t[0]?(async(e,t,a,r,s)=>{try{if(B)return;if(N>30<<20)return A({type:5,timestamp:a,data:{tag:"gap",payload:{reason:"canvas cap"}}}),void(B=1);let n=t.width,i=t.height,l=Math.min(1,r/n),o=Math.max(1,Math.round(n*l)),d=Math.max(1,Math.round(i*l)),f=new OffscreenCanvas(o,d),u=f.getContext("2d");u.drawImage(t,0,0,o,d);let g=new Uint32Array(u.getImageData(0,0,o,d).data.buffer),p=2166136261^n^i<<16;for(let e=0;e<g.length;e++)p=Math.imul(p^g[e],16777619);if(D.get(e)?.[0]===p)return;let h=await f.convertToBlob({type:"image/webp",quality:s});if("image/webp"!=h.type)return void(B=1);let c=new Uint8Array(await h.arrayBuffer());a>=_&&D.set(e,[p,a]),U.push({id:U.length,type:1,data:c}),J+=c.length,N+=c.length,A({type:5,timestamp:a,data:{tag:"canvas",payload:{id:e,a:U.length-1,w:n,h:i}}})}finally{t.close(),w.postMessage([2,e,B])}})(t[1],t[2],t[3],t[4],t[5]):0==t[0]?(v=t[1],o(t[2]),M=t[3],x=t[4]||1,j=t[5]?1:0,q=t[9]||20,t[6]&&(importScripts(t[6]),a=self.rpx(t[7],t[8])),V()):4==t[0]&&V(1);(T.raw()>=262144||J>=1<<20)&&!k&&(k=1,w.postMessage([0]))}catch{}}})();
1
+ "use strict";(()=>{var e,t,a,r,s=new TextEncoder,n={redact:{headers:[],bodyKeys:[],queryParams:[]}},i=0,l=()=>i,o=e=>{let t=n.redact;e.headers.length+e.bodyKeys.length+e.queryParams.length!=t.headers.length+t.bodyKeys.length+t.queryParams.length&&(n.redact=e,i++)},d="[Filtered]",f=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=-1,p=()=>{if(u==l())return;u=l();let a=n.redact.bodyKeys.map(f).join("|");e=new RegExp(`([?&#;](?:${n.redact.queryParams.map(f).join("|")}|${a})=)[^&#;]*`,"gi"),t=new RegExp(`("(?:${a})"\\s*:\\s*)("(?:[^"\\\\]|\\\\.)*"?|[^,}\\]\\s]+)|((?:^|&)(?:${a})=)[^&\\s]*`,"gi")},g=(e,t=0)=>{if(!e||"object"!=typeof e)return e;if(t>7)return"[Depth]";if(Array.isArray(e))return e.map(e=>g(e,t+1));let a=Object.create(null);for(let r in e)a[r]=n.redact.bodyKeys.includes(r.toLowerCase())?d:g(e[r],t+1);return a},h=e=>{p();let a=e.trimStart()[0];if(("{"==a||"["==a)&&e.length<1e5)try{return JSON.stringify(g(JSON.parse(e)))}catch{}return e.includes("\n")?e.split("\n").map(h).join("\n"):e.replace(t,(e,t,a,r)=>t?`${t}"${d}"`:r+d)},c=null,y=(e,t,a)=>(c??=new Promise((e,t)=>{let a=indexedDB.open("replayd",1);a.onupgradeneeded=()=>{for(let e of["q","e"])a.result.createObjectStore(e,{autoIncrement:!0})},a.onsuccess=()=>e(a.result),a.onerror=()=>t(a.error)})).catch(e=>{throw c=null,e}).then(r=>new Promise((s,n)=>{let i=r.transaction(e,t?"readwrite":"readonly"),l=a(i.objectStore(e));i.oncomplete=()=>s(l?l.result:void 0),i.onerror=i.onabort=()=>n(i.error)})),m=(e,t)=>y(e,!0,e=>{e.delete(t)}),w=self,b=5<<20,v="",M=0,S=1,j=new Map,x=0,$=0,q=20,O=new Set,k=0,P=0,T=((e,t)=>{let a,r=[],s=0,n=0,i=0,l=0,o=0,d=0,f=0,u=0,p=[],g={},h=[],c=[],y=[],m=e=>y.length<30&&!y.includes(e)&&y.push(e),w=e=>"string"==typeof e&&(m("u:"+e),p.length<10&&!p.includes(e)&&p.push(e)),b=()=>{r=[],s=n=l=o=d=f=u=0,p=[],g={},h=[],a=void 0,c=[],y=[]};return{raw:()=>s,n:()=>n,reset:b,add(p){let y=p.data,b=p.timestamp;if(4==p.type&&y.href)w(y.href=e.u(y.href));else if(3==p.type&&2==y.source&&2==y.type)o++;else if(5==p.type){let r=y.payload;if("error"==y.tag)"warning"==r.level?f++:d++;else if("sig"==y.tag)g[r.k]=(g[r.k]??0)+1,"vitals"==r.k&&h.push(r),"lag"==r.k&&(u=Math.max(u,r.max)),"mem"==r.k&&(a={...a,...r,used:Math.max(a?.used??0,r.used??0)});else if("fields"==y.tag)r.value=e.j(r.value);else if("nav"==y.tag&&"string"==typeof r.to)w(r.to=e.u(r.to));else if("network"==y.tag){for(let t of["reqBody","resBody"])"string"==typeof r[t]&&(r[t]=e.t(r[t]));(r.status>=400||0===r.status)&&c.length<10&&!c.includes(r.status)&&c.push(r.status)}else if("breadcrumb"==y.tag)m(("c:"+r.cat+":"+r.msg).slice(0,100));else if("ws"==y.tag&&"string"==typeof r.raw){if(t&&"in"==r.dir){let e=t(r.raw,b,r.id);if(null==e)return;r.raw=e}r.raw=e.t(r.raw)}}n++||(i=b),b>l&&(l=b);let v=JSON.stringify(p);s+=v.length,r.push(v)},take(t,s){t.init&&(t.init.url=e.u(t.init.url),t.init.ref=e.u(t.init.ref),t.init.user=e.j(t.init.user)),t.fields&&(t.fields.user=e.j(t.fields.user),t.fields.custom_fields=e.j(t.fields.custom_fields),t.fields.tags=e.j(t.fields.tags),(new TextEncoder).encode(JSON.stringify(t.fields.tags)).length>8192&&delete t.fields.tags),s&&r.unshift(JSON.stringify({type:5,timestamp:i,data:{tag:"gap",payload:{reason:"dropped",segments:s}}}));let m=JSON.stringify({canvas_bytes:0,...t,t0:i,t1:l,enc:"gzip",n,urls:p,clicks:o,errs:d,warns:f,sig:g,vitals:h,mem:a,st:c,tr:y,lag:u||void 0,has_error:d>0,gap:s>0}),w=`[${r.join(",")}]`;return b(),[m,w]}}})({u:t=>(p(),t.replace(e,`$1${d}`)),t:h,j:g},(e,t,r)=>M?((e,t,r)=>{let s=[];for(let n of e.split("\n")){let e,i;try{e=(i=JSON.parse(n)).push?.channel}catch{}if("string"==typeof e){if(a?.f(e,i,t,r),t-(j.get(e)??-1e15)<1e3/S)continue;j.size>999&&(j=new Map),j.set(e,t)}s.push(n)}return s.join("\n")})(e,t,r)||null:e),U=[],J=0,N=0,B=0,D=new Map,_=0,A=e=>{if(a?.e(e),2==e.type){_=Math.max(_,e.timestamp);for(let[t,[,a]]of D)a<e.timestamp&&D.delete(t)}T.add(e)},C=[],K=0,z=0,E=0,L=!1,R=e=>{let t=C.indexOf(e);t>=0&&(K-=C.splice(t,1)[0].b.length),e.s&&w.postMessage([3,e.s])},I=(e,t)=>{e.f=!0,z++,fetch(v,{method:"POST",body:e.b,keepalive:t,credentials:"omit",headers:{"Content-Type":"text/plain"}}).then(e=>{let t=+(e.headers.get("x-replayd-disable")??0);t>0&&w.postMessage([1,t]);let a=e.status;return a<400?0:a<500&&429!=a?-2:+(e.headers.get("retry-after")??0)||-1},()=>-1).then(t=>{if(e.f=!1,z--,t>-2&&t&&++e.n<5)return clearTimeout(E),L=t>0,void(E=setTimeout(()=>{E=0,G()},t>0?1e3*t:Math.min(6e4,500*2**e.n)));x&&-1==t?R(e):(t&&P++,F(e),G())})},F=e=>{R(e),e.p?.then(e=>null!=e&&m("q",e)).catch(()=>{})},V=async e=>{if(e&&E&&!L&&(clearTimeout(E),E=0,G()),!$){$=1;try{let e=new Set(await Promise.all(C.map(e=>e.p))),[t,a]=await(()=>{let e=[],t=[],a=0,r=0;return y("q",!0,s=>{let n=Date.now(),i=s.openCursor();i.onsuccess=()=>{let l=i.result;if(l)return t.push([l.primaryKey,l.value]),void l.continue();for(let i=t.length-1;i>=0;i--){let[l,o]=t[i];n-o.t>864e5||(r+=o.b.byteLength)>20971520?(s.delete(l),a++):e.unshift([l,o])}}}).then(()=>[e,a])})();P+=a;for(let[a,r]of t)if(!(e.has(a)||K+r.b.byteLength>b)){if(r.s&&O.has(r.s)){m("q",a).catch(()=>{});continue}C.push({b:r.b,n:0,p:Promise.resolve(a)}),K+=r.b.byteLength}}catch{}$=0,G()}},G=e=>{if(!e&&(z||E))return;let t=6e4;for(let a of C){if(a.f)continue;let r=a.b.length;if(!e)return I(a,r<6e4);let s=r<t;s&&(t-=r),I(a,s)}},H=e=>A({type:5,timestamp:Date.now(),data:{tag:"sig",payload:e}}),Q=async(e,t,a,r,n)=>{let i=function(e,t,a=[]){let r=s.encode(e);if(r.length>32768)throw new RangeError("meta too large");let n=2+r.length+4+t.length+2;for(let e of a)n+=9+e.data.length;let i=new Uint8Array(n),l=new DataView(i.buffer),o=0;l.setUint16(o,r.length,!0),o+=2,i.set(r,o),o+=r.length,l.setUint32(o,t.length,!0),o+=4,i.set(t,o),o+=t.length,l.setUint16(o,a.length,!0),o+=2;for(let e of a)l.setUint32(o,e.id,!0),o+=4,i[o++]=e.type,l.setUint32(o,e.data.length,!0),o+=4,i.set(e.data,o),o+=e.data.length;return i}(e,new Uint8Array(await new Response(new Blob([t]).stream().pipeThrough(new CompressionStream("gzip"))).arrayBuffer()),n),l={b:i,n:0,s:a};x&&(l.p=((e,t)=>y("q",!0,e=>e.add(t)))(0,{t:Date.now(),b:i}).catch(()=>{})),C.push(l),K+=i.length;for(let e=0;K>b&&e<C.length-1;)C[e].f?e++:(R(C[e]),x||P++);G(r)};w.onmessage=e=>{let t=e.data;try{if(1==t[0]){t[2]&&o(t[2]);for(let e of t[1])A(e)}else if(2==t[0]){t[5]&&o(t[5]);for(let e of t[4]??[])A(e);let e=t[1],a=t[2].split("\0"),r=[];for(let t=0;t<e.length;t++)r.push({id:e[t],value:a[t]});A({type:3,timestamp:t[3],data:{source:0,texts:r,attributes:[],removes:[],adds:[]}})}else if(3==t[0])((e,t,s)=>{o(t);let n=a?.c(q,H);n?.length&&w.postMessage([8,n]),r&&r.sid==e.sid&&(e.init??=r.init,e.fields??=r.fields,e.ws_disc+=r.ws_disc),r=0;let i=`${e.sid}:${e.seq}`;if(!T.n())return r=e,void w.postMessage([3,i]);let[l,d]=T.take({...e,canvas_bytes:J},P),f=U;return k=P=J=0,U=[],Q(l,d,i,s,f)})(t[1],t[2],t[3])?.catch(()=>{});else if(5==t[0])T.reset(),U=[],k=J=0,D.clear(),t[1]&&G(!0);else if(6==t[0]){let e=JSON.parse(t[1]),a=`${e.sid}:${e.seq}`;O.add(a),P+=0|t[3],Q(t[1],t[2],a).catch(()=>{})}else 7==t[0]?(async(e,t,a,r,s)=>{try{let n=t.width,i=t.height,l=Math.min(1,r/n),o=Math.round(n*l)||1,d=Math.round(i*l)||1,f=new OffscreenCanvas(o,d),u=f.getContext("2d");u.drawImage(t,0,0,o,d);let p=new Uint32Array(u.getImageData(0,0,o,d).data.buffer),g=2166136261^n^i<<16;for(let e=0;e<p.length;e++)g=Math.imul(g^p[e],16777619);if(D.get(e)?.[0]===g)return;let h=await f.convertToBlob({type:"image/webp",quality:s});if(B)return;let c=N+h.size>30<<20;if(c||"image/webp"!=h.type)return c&&A({type:5,timestamp:a,data:{tag:"gap",payload:{reason:"canvas cap"}}}),void(B=1);N+=h.size;let y=new Uint8Array(await h.arrayBuffer());a>=_&&D.set(e,[g,a]),U.push({id:U.length,type:1,data:y}),J+=y.length,A({type:5,timestamp:a,data:{tag:"canvas",payload:{id:e,a:U.length-1,w:n,h:i}}})}finally{t.close(),w.postMessage([2,e,B])}})(t[1],t[2],t[3],t[4],t[5]):0==t[0]?(v=t[1],o(t[2]),M=t[3],S=t[4]||1,x=t[5]?1:0,q=t[9]||20,t[6]&&(importScripts(t[6]),a=self.rpx(t[7],t[8],q,H,e=>w.postMessage([8,e,1]))),V()):4==t[0]?V(1):9==t[0]&&a?.p(t[1]);(T.raw()>=262144||J>=1<<20)&&!k&&(k=1,w.postMessage([0]))}catch{}}})();
2
2
  //# sourceMappingURL=worker.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["qre","kre","X","late","te","TextEncoder","O","redact","headers","bodyKeys","queryParams","v","redactVer","setRedact","r","d","length","FILTERED","esc","s","replace","re","k","map","join","RegExp","rJson","x","Array","isArray","y","o","Object","create","includes","toLowerCase","rText","c","trimStart","JSON","stringify","parse","split","_m","a","_x","f","db","run","st","rw","Promise","ok","no","indexedDB","open","onupgradeneeded","result","createObjectStore","autoIncrement","onsuccess","onerror","error","catch","e","then","t","transaction","objectStore","oncomplete","onabort","del","delete","G","self","CAP","url","co","cpc","last","Map","ob","draining","gate","kept","Set","asked","gap","S","sample","mem","P","raw","n","t0","t1","clicks","errs","warns","lag","urls","sig","vit","tr","tr1","push","url1","u","reset","add","data","ts","timestamp","type","href","source","p","payload","tag","level","Math","max","used","value","j","to","status","cat","msg","slice","dir","id","take","m","init","ref","user","fields","custom_fields","tags","encode","unshift","reason","segments","meta","canvas_bytes","enc","vitals","has_error","json","seg","l","ch","channel","get","size","set","A","ab","cvb","cvOff","sum","fs","q","qb","fl","tm","sv","rm","it","i","indexOf","splice","b","postMessage","go","ka","fetch","method","body","keepalive","credentials","off","ra","clearTimeout","setTimeout","pump","min","done","drain","async","now","mine","all","recs","lost","out","Date","openCursor","primaryKey","continue","byteLength","load","has","resolve","hide","send","metaJson","eventsGz","assets","RangeError","Uint8Array","dv","DataView","buffer","setUint16","setUint32","encodeSegment","Response","Blob","stream","pipeThrough","CompressionStream","arrayBuffer","put","onmessage","ids","texts","attributes","removes","adds","sid","ws_disc","seq","cut","clear","bmp","mw","ql","W0","width","H0","height","w","round","h","oc","OffscreenCanvas","getContext","drawImage","px","Uint32Array","getImageData","imul","convertToBlob","quality","close","shot","importScripts","rpx"],"sources":["../src/wire.ts","../src/redact.ts","../src/worker/index.ts","../src/worker/cfg.ts","../src/idb.ts","../src/seg.ts"],"sourcesContent":["/**\n * Replay segment wire format (PRD §4.10) and `.rpl` reader (PRD §5.3). Little-endian.\n *\n * body: u16 meta_len | meta JSON | u32 events_len | events (gzip) | u16 asset_count | assets…\n * asset: u32 asset_id | u8 type (1 = webp) | u32 len | bytes\n * .rpl: \"RPL2\" | u16 version | 16-byte sid, then frames:\n * u32 len | u32 seq | u64 t0 | u64 t1 | u32 received_at | u8 flags | body-without-meta\n *\n * Mirrors server/crates/common/src/{wire,rpl}.rs; cross-checked by fixtures in /fixtures/wire.\n */\n\nexport const ASSET_WEBP = 1;\nexport const RPL_HEADER_LEN = 22;\nexport const RPL_FRAME_HEADER_LEN = 29;\nexport const RPL_FLAG_GAP = 1;\nexport const RPL_FLAG_HAS_ERROR = 2;\nexport const RPL_FLAG_REDACTED = 4;\n\nexport interface WireAsset {\n id: number;\n type: number;\n data: Uint8Array;\n}\n\nconst te = /* @__PURE__ */ new TextEncoder();\n\n/** Encodes a replay segment body. `metaJson` must be a JSON object string; `eventsGz` gzip bytes. */\nexport function encodeSegment(metaJson: string, eventsGz: Uint8Array, assets: WireAsset[] = []): Uint8Array {\n const meta = te.encode(metaJson);\n if (meta.length > 32 * 1024) throw new RangeError('meta too large');\n let size = 2 + meta.length + 4 + eventsGz.length + 2;\n for (const a of assets) size += 9 + a.data.length;\n const out = new Uint8Array(size);\n const dv = new DataView(out.buffer);\n let p = 0;\n dv.setUint16(p, meta.length, true); p += 2;\n out.set(meta, p); p += meta.length;\n dv.setUint32(p, eventsGz.length, true); p += 4;\n out.set(eventsGz, p); p += eventsGz.length;\n dv.setUint16(p, assets.length, true); p += 2;\n for (const a of assets) {\n dv.setUint32(p, a.id, true); p += 4;\n out[p++] = a.type;\n dv.setUint32(p, a.data.length, true); p += 4;\n out.set(a.data, p); p += a.data.length;\n }\n return out;\n}\n\nexport interface StoredBody {\n events: Uint8Array;\n assets: WireAsset[];\n}\n\n/** Parses a body-without-meta (as stored in a `.rpl` frame). Throws on malformed input. */\nexport function parseStoredBody(b: Uint8Array): StoredBody {\n const dv = new DataView(b.buffer, b.byteOffset, b.byteLength);\n const need = (p: number, n: number) => {\n if (p + n > b.length) throw new RangeError('truncated body');\n };\n let p = 0;\n need(p, 4);\n const el = dv.getUint32(p, true); p += 4;\n need(p, el);\n const events = b.subarray(p, p + el); p += el;\n need(p, 2);\n const n = dv.getUint16(p, true); p += 2;\n const assets: WireAsset[] = [];\n for (let i = 0; i < n; i++) {\n need(p, 9);\n const id = dv.getUint32(p, true);\n const type = b[p + 4]!;\n const len = dv.getUint32(p + 5, true);\n p += 9;\n need(p, len);\n assets.push({ id, type, data: b.subarray(p, p + len) });\n p += len;\n }\n if (p !== b.length) throw new RangeError('trailing bytes');\n return { events, assets };\n}\n\n/** Splits a full segment body into meta JSON text and the stored body. */\nexport function splitSegment(b: Uint8Array): { meta: string; body: Uint8Array } {\n if (b.length < 2) throw new RangeError('truncated');\n const ml = b[0]! | (b[1]! << 8);\n if (2 + ml > b.length) throw new RangeError('truncated meta');\n return { meta: new TextDecoder().decode(b.subarray(2, 2 + ml)), body: b.subarray(2 + ml) };\n}\n\nexport interface RplFrame {\n seq: number;\n t0: number;\n t1: number;\n receivedAt: number;\n flags: number;\n body: Uint8Array;\n}\n\nexport interface RplIndex {\n sid: string;\n frames: RplFrame[];\n validLen: number;\n duplicates: number;\n}\n\nconst hex = (b: Uint8Array) => Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');\n\n/** Formats 16 raw bytes as a UUID string. */\nexport function uuidFromBytes(b: Uint8Array): string {\n const h = hex(b);\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n}\n\n/**\n * Indexes an `.rpl` buffer: ignores a truncated tail, keeps the first copy of each seq, sorts by seq.\n * Works on partial (streamed) buffers too: `validLen` tells how far complete frames go.\n */\nexport function indexRpl(buf: Uint8Array): RplIndex {\n if (buf.length < RPL_HEADER_LEN) throw new RangeError('short');\n if (buf[0] !== 0x52 || buf[1] !== 0x50 || buf[2] !== 0x4c || buf[3] !== 0x32) throw new Error('bad magic');\n const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n const version = dv.getUint16(4, true);\n if (version !== 1) throw new Error(`unsupported version ${version}`);\n const sid = uuidFromBytes(buf.subarray(6, 22));\n const frames: RplFrame[] = [];\n let p = RPL_HEADER_LEN;\n while (p + RPL_FRAME_HEADER_LEN <= buf.length) {\n const len = dv.getUint32(p, true);\n const end = p + RPL_FRAME_HEADER_LEN + len;\n if (len > 4 * 1024 * 1024 || end > buf.length) break;\n frames.push({\n seq: dv.getUint32(p + 4, true),\n t0: Number(dv.getBigUint64(p + 8, true)),\n t1: Number(dv.getBigUint64(p + 16, true)),\n receivedAt: dv.getUint32(p + 24, true),\n flags: buf[p + 28]!,\n body: buf.subarray(p + RPL_FRAME_HEADER_LEN, end),\n });\n p = end;\n }\n frames.sort((a, b) => a.seq - b.seq); // stable: first copy of a seq stays first\n const out: RplFrame[] = [];\n for (const f of frames) if (out.length === 0 || out[out.length - 1]!.seq !== f.seq) out.push(f);\n return { sid, frames: out, validLen: p, duplicates: frames.length - out.length };\n}\n","/**\n * Redaction (PRD §0.2, §4.11): headers stripped, query params + JSON keys replaced by `[Filtered]`,\n * recursive to depth 8, case-insensitive. Pure functions over `O.redact` — reusable by the worker (T-20).\n */\nimport { O, redactVer } from './config';\n\nexport const FILTERED = '[Filtered]';\nconst esc = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\nlet v = -1, qre: RegExp, kre: RegExp;\nconst re = () => {\n if (v == redactVer()) return;\n v = redactVer();\n const k = O.redact.bodyKeys.map(esc).join('|');\n // URL params: query-param list + body keys (e.g. `#access_token=` in OAuth redirects)\n qre = new RegExp(`([?&#;](?:${O.redact.queryParams.map(esc).join('|')}|${k})=)[^&#;]*`, 'gi');\n // fallback for non-JSON / truncated text: `\"key\": value` and form fields `key=value`\n kre = new RegExp(`(\"(?:${k})\"\\\\s*:\\\\s*)(\"(?:[^\"\\\\\\\\]|\\\\\\\\.)*\"?|[^,}\\\\]\\\\s]+)|((?:^|&)(?:${k})=)[^&\\\\s]*`, 'gi');\n};\n\n/** redacts secret query params (and fragment params) of a URL string */\nexport const rUrl = (u: string) => (re(), u.replace(qre, `$1${FILTERED}`));\n\n/** copies headers into a lower-cased plain object, dropping the header denylist */\nexport const rHeaders = (h: Iterable<[string, string]>) => {\n const o: Record<string, string> = {};\n for (const [k, x] of h) {\n const l = k.toLowerCase();\n if (!O.redact.headers.includes(l)) o[l] = x;\n }\n return o;\n};\n\n/** recursive key redaction; subtrees deeper than 8 levels are dropped (never leaked unredacted) */\nexport const rJson = (x: unknown, d = 0): unknown => {\n if (!x || typeof x != 'object') return x;\n if (d > 7) return '[Depth]';\n if (Array.isArray(x)) return x.map((y) => rJson(y, d + 1));\n const o: Record<string, unknown> = Object.create(null);\n for (const k in x) o[k] = O.redact.bodyKeys.includes(k.toLowerCase()) ? FILTERED : rJson((x as Record<string, unknown>)[k], d + 1);\n return o;\n};\n\n/**\n * Redacts a text body / WS frame. JSON (≤ 100 KB) is parsed and redacted structurally; newline-batched\n * JSON (Centrifugo) line by line; anything else (truncated frames, form bodies) by regex.\n */\nexport const rText = (s: string): string => {\n re();\n const c = s.trimStart()[0];\n if ((c == '{' || c == '[') && s.length < 1e5)\n try {\n return JSON.stringify(rJson(JSON.parse(s)));\n } catch {\n /* not (complete) JSON */\n }\n if (s.includes('\\n')) return s.split('\\n').map(rText).join('\\n');\n return s.replace(kre, (_m, a, _x, f) => (a ? `${a}\"${FILTERED}\"` : f + FILTERED));\n};\n","/**\n * Replay worker (PRD §4.10, D-09/D-15): per-event redaction + bookkeeping, Centrifugo per-channel sampling,\n * JSON encoding, gzip (CompressionStream), segment wrapping (wire.ts) and upload with retry/backoff, a 5 MB\n * drop-oldest queue and gap markers. Built as a classic IIFE script (build.json) with `./config` aliased to\n * ./cfg so redact.ts runs here without the main-thread config module.\n *\n * Main → worker: [0, url, redact, centrifugo, perChannelPerSec, outbox] init · [4] drain the outbox (online/resume) · [1, events] batch ·\n * [2, ids, values, ts, events] events, then coalesced texts (D-04) · [3, meta, redact, hide] cut a segment ·\n * [5, unload] drop the current segment (idle expiry, T-90); unload: the main thread sent it itself,\n * send the queue now ·\n * [6, meta, events, gap] send a segment the previous page of this tab kept when it unloaded (T-89); gap:\n * kept segments dropped before it (D-80) ·\n * [7, nodeId, ImageBitmap, ts, maxWidth, quality] canvas snapshot (T-91) ·\n * init [6, 7, 8] = stale-data extension URL (0 = off), threshold ms, lag field (T-151)\n * Worker → main: [0] raw events / canvas bytes over the segment limit (please cut) · [1, seconds] X-Replayd-Disable ·\n * [2, nodeId, off] canvas snapshot handled (the next one of that canvas may follow; off: no more) ·\n * [3, 'sid:seq'] that segment is out of this worker's hands (sent, rejected, stored or dropped, D-80) ·\n * [8, [[channel, ms, sampled]…]] Centrifugo channels that went silent while the page was visible (T-151)\n */\nimport type { RedactOptions } from '../types';\nimport { encodeSegment, type WireAsset } from '../wire';\nimport { rJson, rText, rUrl } from '../redact';\nimport { seg } from '../seg';\nimport { setRedact } from './cfg';\nimport { del, load, put } from '../idb';\nimport type { Rpx } from './wsx';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype A = any;\ninterface Q {\n b: Uint8Array;\n n: number;\n f?: boolean;\n /** outbox key (IndexedDB), when the outbox is on */\n p?: Promise<IDBValidKey | undefined>;\n /** 'sid:seq', acknowledged to the main thread once the segment leaves the queue */\n s?: string;\n}\nconst G = self as unknown as { postMessage(m: unknown): void; onmessage: ((e: MessageEvent) => void) | null };\nconst CAP = 5 << 20, KA = 6e4, FULL = 256 << 10;\n\nlet url = '', co = 0, cpc = 1, last = new Map<string, number>();\n/** T-151 stale-data / lag extension (wsx.js), when the project turned it on */\nlet X: Rpx | undefined;\n/** IndexedDB outbox (PRD §4.9: Capacitor always, web with `offlineQueue: true`): every segment is stored before\n * it is sent and deleted once the server answered; network failures stay stored and are drained later */\nlet ob = 0, draining = 0, gate = 20;\n/** 'sid:seq' of the segments the previous page of this tab handed over ([6]): their outbox copies are not sent twice */\nconst kept = new Set<string>();\n// cut already asked for the current segment\nlet asked = 0;\n// segments lost since the last one that went out (queue cap, retries exhausted, rejected)\nlet gap = 0;\n\n/** Centrifugo JSON: keeps lines whose `push.channel` passed its 1/perChannelPerSec gate (others: replies etc.) */\nconst sample = (s: string, ts: number, id: number) => {\n const k: string[] = [];\n for (const l of s.split('\\n')) {\n let ch: unknown, o: A;\n try {\n ch = (o = JSON.parse(l)).push?.channel;\n } catch {\n /* truncated / not JSON: keep */\n }\n if (typeof ch == 'string') {\n X?.f(ch, o, ts, id);\n if (ts - (last.get(ch) ?? -1e15) < 1e3 / cpc) continue;\n if (last.size > 999) last = new Map();\n last.set(ch, ts);\n }\n k.push(l);\n }\n return k.join('\\n');\n};\n\n// current segment (redaction, sampling, counters)\nconst S = seg({ u: rUrl, t: rText, j: rJson }, (s, ts, id) => (co ? sample(s, ts, id) || null : s));\n\n// ---- canvas snapshots (PRD §4.7, T-91): downscale, skip unchanged, WebP, binary asset of the current segment\n/** assets of the current segment (a canvas event names its asset by index: both always land in one segment) */\nlet A: WireAsset[] = [], ab = 0;\n/** canvas bytes of this page (PRD: 30 MB per session, then capture stops with a gap marker, `cvOff`) */\nlet cvb = 0, cvOff = 0;\n/** last frame per canvas node: [checksum, time]. A full snapshot (latest: `fs`) rebuilds blank canvases, so no frame\n * taken before it may hide a later one; its event can reach the worker before or after such frames. */\nconst sum = new Map<number, [number, number]>();\nlet fs = 0;\nconst add = (e: A) => {\n X?.e(e);\n if (e.type == 2) {\n fs = Math.max(fs, e.timestamp);\n for (const [id, [, t]] of sum) if (t < e.timestamp) sum.delete(id);\n }\n S.add(e);\n};\nconst shot = async (id: number, bmp: ImageBitmap, ts: number, mw: number, ql: number) => {\n try {\n if (cvOff) return;\n if (cvb > 30 << 20) {\n add({ type: 5, timestamp: ts, data: { tag: 'gap', payload: { reason: 'canvas cap' } } });\n cvOff = 1;\n return;\n }\n const W0 = bmp.width, H0 = bmp.height, s = Math.min(1, mw / W0), w = Math.max(1, Math.round(W0 * s)), h = Math.max(1, Math.round(H0 * s));\n const oc = new OffscreenCanvas(w, h), x = oc.getContext('2d')!;\n x.drawImage(bmp, 0, 0, w, h);\n // FNV-1a over the scaled pixels: an unchanged canvas (idle chart, weekend) costs no bytes\n const px = new Uint32Array(x.getImageData(0, 0, w, h).data.buffer);\n let c = 0x811c9dc5 ^ W0 ^ (H0 << 16);\n for (let i = 0; i < px.length; i++) c = Math.imul(c ^ px[i]!, 16777619);\n if (sum.get(id)?.[0] === c) return;\n const b = await oc.convertToBlob({ type: 'image/webp', quality: ql });\n // a browser without a WebP encoder (Safari) returns PNG: the wire format only carries WebP, so no canvases here\n if (b.type != 'image/webp') return void (cvOff = 1);\n const data = new Uint8Array(await b.arrayBuffer());\n if (ts >= fs) sum.set(id, [c, ts]);\n A.push({ id: A.length, type: 1, data });\n ab += data.length;\n cvb += data.length;\n add({ type: 5, timestamp: ts, data: { tag: 'canvas', payload: { id, a: A.length - 1, w: W0, h: H0 } } });\n } finally {\n bmp.close();\n G.postMessage([2, id, cvOff]);\n }\n};\n\n// ---- upload queue: one request in flight, exp. backoff 1 s → 60 s, max 5 attempts, Retry-After on 429/503\nconst q: Q[] = [];\n// sv: the pending timer is a server Retry-After (honoured even on online/resume), else a network backoff\nlet qb = 0, fl = 0, tm: ReturnType<typeof setTimeout> | 0 = 0, sv = false;\nconst rm = (it: Q) => {\n const i = q.indexOf(it);\n if (i >= 0) qb -= q.splice(i, 1)[0]!.b.length;\n if (it.s) G.postMessage([3, it.s]);\n};\nconst go = (it: Q, ka: boolean) => {\n it.f = true;\n fl++;\n fetch(url, { method: 'POST', body: it.b as BodyInit, keepalive: ka, credentials: 'omit', headers: { 'Content-Type': 'text/plain' } })\n .then(\n (r) => {\n const off = +(r.headers.get('x-replayd-disable') ?? 0);\n if (off > 0) G.postMessage([1, off]);\n const s = r.status;\n // 0 = done; -2 = rejected (4xx other than 429: retrying can't fix it); > 0 Retry-After s; -1 backoff\n return s < 400 ? 0 : s < 500 && s != 429 ? -2 : +(r.headers.get('retry-after') ?? 0) || -1;\n },\n () => -1,\n )\n .then((ra) => {\n it.f = false;\n fl--;\n if (ra > -2 && ra && ++it.n < 5) {\n clearTimeout(tm);\n sv = ra > 0;\n tm = setTimeout(\n () => {\n tm = 0;\n pump();\n },\n ra > 0 ? ra * 1e3 : Math.min(6e4, 500 * 2 ** it.n),\n );\n return;\n }\n // stored segments survive network/5xx failures (drained on online/resume/next start); else: lost\n if (ob && ra == -1) {\n rm(it);\n return;\n }\n if (ra) gap++;\n done(it);\n pump();\n });\n};\n/** finished (sent or rejected): out of memory and out of the outbox */\nconst done = (it: Q) => {\n rm(it);\n it.p?.then((k) => k != null && del('q', k)).catch(() => {});\n};\n/** loads stored segments that are not in memory (oldest first, ≤ the memory cap); expired/over-cap → gap */\nconst drain = async (now?: 1) => {\n // back online / resumed: a network backoff (up to 60 s) would hold the whole outbox, retry now\n if (now && tm && !sv) {\n clearTimeout(tm);\n tm = 0;\n pump();\n }\n // also without the outbox: an unloading page stores the segments it could not send there (D-80)\n if (draining) return;\n draining = 1;\n try {\n const mine = new Set(await Promise.all(q.map((x) => x.p)));\n const [recs, lost] = await load('q');\n gap += lost;\n for (const [k, r] of recs) {\n if (mine.has(k) || qb + r.b.byteLength > CAP) continue;\n if (r.s && kept.has(r.s)) {\n del('q', k).catch(() => {});\n continue;\n }\n q.push({ b: r.b, n: 0, p: Promise.resolve(k) });\n qb += r.b.byteLength;\n }\n } catch {\n /* no IndexedDB (private mode, quota): memory queue only */\n }\n draining = 0;\n pump();\n};\n/** sends the head (sequential); on hide: everything not in flight, keepalive within a 60 KB total */\nconst pump = (hide?: boolean) => {\n if (!hide && (fl || tm)) return;\n let ka = KA;\n for (const it of q) {\n if (it.f) continue;\n const s = it.b.length;\n if (!hide) return go(it, s < KA);\n const k = s < ka;\n if (k) ka -= s;\n go(it, k);\n }\n};\n\n/** meta of a cut that had no events to go with (all of them sampled out). The main thread has already counted its\n * init, field snapshot and WS disconnects as sent: they go with the next segment of that session. */\nlet late: A;\nconst cut = (m: A, r: Required<RedactOptions>, hide: boolean) => {\n setRedact(r);\n const st = X?.c(hide, gate, (x) => add({ type: 5, timestamp: Date.now(), data: { tag: 'sig', payload: x } }));\n if (st?.length) G.postMessage([8, st]);\n if (late && late.sid == m.sid) {\n m.init ??= late.init;\n m.fields ??= late.fields;\n m.ws_disc += late.ws_disc;\n }\n late = 0;\n const s = `${m.sid}:${m.seq}`;\n if (!S.n()) return void ((late = m), G.postMessage([3, s]));\n const [meta, json] = S.take({ ...m, canvas_bytes: ab }, gap), a = A;\n asked = gap = ab = 0;\n A = [];\n return send(meta, json, s, hide, a);\n};\nconst send = async (meta: string, json: string, s: string, hide?: boolean, a?: WireAsset[]) => {\n const gz = new Uint8Array(await new Response(new Blob([json]).stream().pipeThrough(new CompressionStream('gzip'))).arrayBuffer());\n const b = encodeSegment(meta, gz, a), it: Q = { b, n: 0, s };\n if (ob) it.p = put('q', { t: Date.now(), b }).catch(() => undefined);\n q.push(it);\n qb += b.length;\n // 5 MB memory cap: drop the oldest segments that are not in flight (with the outbox they stay stored)\n for (let i = 0; qb > CAP && i < q.length - 1; )\n if (q[i]!.f) i++;\n else {\n rm(q[i]!);\n if (!ob) gap++;\n }\n pump(hide);\n};\n\nG.onmessage = (e: MessageEvent) => {\n const m = e.data;\n try {\n // redaction lists that grew since the last message apply before this batch is redacted\n if (m[0] == 1) {\n if (m[2]) setRedact(m[2]);\n for (const x of m[1]) add(x);\n } else if (m[0] == 2) {\n if (m[5]) setRedact(m[5]);\n for (const x of m[4] ?? []) add(x);\n const ids: Int32Array = m[1], v: string[] = m[2].split('\\0'), texts = [];\n for (let i = 0; i < ids.length; i++) texts.push({ id: ids[i], value: v[i] });\n add({ type: 3, timestamp: m[3], data: { source: 0, texts, attributes: [], removes: [], adds: [] } });\n } else if (m[0] == 3) cut(m[1], m[2], m[3])?.catch(() => {});\n else if (m[0] == 5) {\n S.reset();\n A = [];\n asked = ab = 0;\n // the dropped frames never reach the replay: an unchanged canvas has to be sent again\n sum.clear();\n if (m[1]) pump(true);\n } else if (m[0] == 6) {\n const x = JSON.parse(m[1]), s = `${x.sid}:${x.seq}`;\n kept.add(s);\n gap += m[3] | 0;\n send(m[1], m[2], s).catch(() => {});\n }\n else if (m[0] == 7) void shot(m[1], m[2], m[3], m[4], m[5]);\n else if (m[0] == 0) {\n url = m[1];\n setRedact(m[2]);\n co = m[3];\n cpc = m[4] || 1;\n ob = m[5] ? 1 : 0;\n gate = m[9] || 20;\n if (m[6]) {\n importScripts(m[6]);\n X = (self as A).rpx(m[7], m[8]);\n }\n void drain();\n } else if (m[0] == 4) void drain(1);\n // canvas frames count as well: a segment stays well under the 2 MB ingest limit\n if ((S.raw() >= FULL || ab >= 1 << 20) && !asked) {\n asked = 1;\n G.postMessage([0]);\n }\n } catch {\n /* a malformed event must not kill the worker */\n }\n};\n","/**\n * Worker build stand-in for `../config` (build.json alias): redact.ts reads its lists from `O.redact`.\n * The main thread sends the resolved lists (defaults + user + remote extensions) with every segment cut.\n */\nimport type { RedactOptions } from '../types';\n\nexport const O = { redact: { headers: [], bodyKeys: [], queryParams: [] } as Required<RedactOptions> };\nlet v = 0;\nexport const redactVer = () => v;\n/** replaces the lists when they changed (they only ever grow, so comparing lengths is enough) */\nexport const setRedact = (r: Required<RedactOptions>) => {\n const d = O.redact;\n if (r.headers.length + r.bodyKeys.length + r.queryParams.length != d.headers.length + d.bodyKeys.length + d.queryParams.length) {\n O.redact = r;\n v++;\n }\n};\n","/**\n * Tiny IndexedDB outbox shared by the replay worker (store `q`: segments) and the Capacitor chunk (store `e`:\n * error-event bodies). PRD §4.9: cap 20 MB, max age 24 h, oldest first. Never imported by index.js.\n * Records: `{ t: enqueued ms, b: body bytes, k?: ingest kind }`, auto-increment keys (= insertion order).\n */\nexport interface Rec {\n t: number;\n b: Uint8Array;\n k?: string;\n /** 'sid:seq' of a replay segment an unloading page stored (D-80) */\n s?: string;\n}\nexport const CAP = 20 << 20, AGE = 864e5;\nlet db: Promise<IDBDatabase> | null = null;\nconst open = () =>\n (db ??= new Promise<IDBDatabase>((ok, no) => {\n const r = indexedDB.open('replayd', 1);\n r.onupgradeneeded = () => {\n for (const s of ['q', 'e']) r.result.createObjectStore(s, { autoIncrement: true });\n };\n r.onsuccess = () => ok(r.result);\n r.onerror = () => no(r.error);\n })).catch((e) => {\n db = null;\n throw e;\n });\n\nconst run = <T>(st: string, rw: boolean, f: (s: IDBObjectStore) => IDBRequest<T> | void) =>\n open().then(\n (d) =>\n new Promise<T | undefined>((ok, no) => {\n const t = d.transaction(st, rw ? 'readwrite' : 'readonly'), r = f(t.objectStore(st));\n t.oncomplete = () => ok(r ? r.result : undefined);\n t.onerror = t.onabort = () => no(t.error);\n }),\n );\n\n/** appends a record; resolves to its key */\nexport const put = (st: string, v: Rec) => run<IDBValidKey>(st, true, (s) => s.add(v));\nexport const del = (st: string, k: IDBValidKey) => run(st, true, (s) => void s.delete(k));\n\n/**\n * All records oldest first, after dropping the expired (> 24 h) and the oldest beyond 20 MB.\n * Resolves to `[kept: [key, rec][], dropped count]`.\n */\nexport const load = (st: string): Promise<[[IDBValidKey, Rec][], number]> => {\n const out: [IDBValidKey, Rec][] = [], all: [IDBValidKey, Rec][] = [];\n let n = 0, size = 0;\n return run(st, true, (s) => {\n const now = Date.now(), c = s.openCursor();\n c.onsuccess = () => {\n const x = c.result;\n if (x) {\n all.push([x.primaryKey, x.value as Rec]);\n x.continue();\n return;\n }\n // newest first for the size cap, then back to oldest-first order\n for (let i = all.length - 1; i >= 0; i--) {\n const [k, v] = all[i]!;\n if (now - v.t > AGE || (size += v.b.byteLength) > CAP) {\n s.delete(k);\n n++;\n } else out.unshift([k, v]);\n }\n };\n }).then(() => [out, n]);\n};\n","/**\n * Replay segment builder (PRD §4.10), shared by the worker and, on page unload, the replay chunk's main thread\n * (T-89): per-event redaction and bookkeeping, then the meta + events JSON of one segment. It imports nothing: the\n * redaction functions are passed in (the worker has its own copy of redact.ts, the main thread core's through\n * `Internal`), so neither build pulls a core module into a shared chunk.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype A = any;\nexport interface Red {\n /** URL redaction (query/fragment params) */\n u: (s: string) => string;\n /** text body / WS frame redaction */\n t: (s: string) => string;\n /** recursive JSON key redaction */\n j: (x: unknown) => unknown;\n}\n\n/** `sample`: incoming WS frame (raw, time, socket id) → the frame to keep, null = drop it (worker: Centrifugo per-channel\n * sampling, T-151 stale-data bookkeeping) */\nexport const seg = (r: Red, sample?: (raw: string, ts: number, id: number) => string | null) => {\n let P: string[] = [], raw = 0, n = 0, t0 = 0, t1 = 0, clicks = 0, errs = 0, warns = 0, lag = 0, urls: string[] = [], sig: Record<string, number> = {}, vit: A[] = [], mem: A, st: number[] = [], tr: string[] = [];\n // T-123: the order things first happened in (`u:` page URL, `c:` app breadcrumb `cat:msg`), for search and funnels\n const tr1 = (x: string) => tr.length < 30 && !tr.includes(x) && tr.push(x);\n const url1 = (u: unknown) => typeof u == 'string' && (tr1('u:' + u), urls.length < 10 && !urls.includes(u) && urls.push(u));\n const reset = () => {\n P = [];\n raw = n = t1 = clicks = errs = warns = lag = 0;\n urls = [];\n sig = {};\n vit = [];\n mem = undefined;\n st = [];\n tr = [];\n };\n return {\n raw: () => raw,\n n: () => n,\n reset,\n add(e: A) {\n const d = e.data, ts = e.timestamp;\n if (e.type == 4 && d.href) url1((d.href = r.u(d.href)));\n else if (e.type == 3 && d.source == 2 && d.type == 2) clicks++;\n else if (e.type == 5) {\n const p = d.payload;\n if (d.tag == 'error') {\n if (p.level == 'warning') warns++;\n else errs++;\n }\n else if (d.tag == 'sig') {\n sig[p.k] = (sig[p.k] ?? 0) + 1;\n if (p.k == 'vitals') vit.push(p);\n // T-151: the segment's largest server-to-client lag (ms)\n if (p.k == 'lag') lag = Math.max(lag, p.max);\n // T-119: the segment's heap peak (and device memory from the first sample)\n if (p.k == 'mem') mem = { ...mem, ...p, used: Math.max(mem?.used ?? 0, p.used ?? 0) };\n }\n else if (d.tag == 'fields') p.value = r.j(p.value);\n // core redacts its history navigations; the page-load entry comes raw from the replay chunk\n else if (d.tag == 'nav' && typeof p.to == 'string') url1((p.to = r.u(p.to)));\n else if (d.tag == 'network') {\n for (const k of ['reqBody', 'resBody']) if (typeof p[k] == 'string') p[k] = r.t(p[k]);\n // T-123: failed statuses seen (0 = no response)\n if ((p.status >= 400 || p.status === 0) && st.length < 10 && !st.includes(p.status)) st.push(p.status);\n }\n else if (d.tag == 'breadcrumb') tr1(('c:' + p.cat + ':' + p.msg).slice(0, 100));\n else if (d.tag == 'ws' && typeof p.raw == 'string') {\n if (sample && p.dir == 'in') {\n const x = sample(p.raw, ts, p.id);\n if (x == null) return;\n p.raw = x;\n }\n p.raw = r.t(p.raw);\n }\n }\n if (!n++) t0 = ts;\n if (ts > t1) t1 = ts;\n const s = JSON.stringify(e);\n raw += s.length;\n P.push(s);\n },\n /** the segment's [meta JSON, events JSON]; `m` = sid/seq/init/fields from the main thread, `gap` = segments lost\n * before it. Starts the next segment. */\n take(m: A, gap: number): [string, string] {\n if (m.init) {\n m.init.url = r.u(m.init.url);\n m.init.ref = r.u(m.init.ref);\n m.init.user = r.j(m.init.user);\n }\n if (m.fields) {\n m.fields.user = r.j(m.fields.user);\n m.fields.custom_fields = r.j(m.fields.custom_fields);\n m.fields.tags = r.j(m.fields.tags);\n // tags have no limit of their own: past 8 KB they stay out (the server keeps the last ones) so the 32 KB meta fits\n if (new TextEncoder().encode(JSON.stringify(m.fields.tags)).length > 8192) delete m.fields.tags;\n }\n if (gap) P.unshift(JSON.stringify({ type: 5, timestamp: t0, data: { tag: 'gap', payload: { reason: 'dropped', segments: gap } } }));\n const meta = JSON.stringify({ canvas_bytes: 0, ...m, t0, t1, enc: 'gzip', n, urls, clicks, errs, warns, sig, vitals: vit, mem, st, tr, lag: lag || undefined, has_error: errs > 0, gap: gap > 0 });\n const json = `[${P.join(',')}]`;\n reset();\n return [meta, json];\n },\n };\n};\n\nlet CRC: Int32Array | undefined;\n/**\n * gzip without compression (stored deflate blocks), built synchronously: a page that is unloading cannot wait for\n * CompressionStream. Larger than real gzip, so it is only used for the unload segment's keepalive request.\n */\nexport const stored = (d: Uint8Array): Uint8Array => {\n if (!CRC) {\n CRC = new Int32Array(256);\n for (let i = 0; i < 256; i++) {\n let c = i;\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n CRC[i] = c;\n }\n }\n const len = d.length, nb = Math.ceil(len / 65535) || 1, o = new Uint8Array(18 + len + nb * 5), v = new DataView(o.buffer);\n o.set([31, 139, 8, 0, 0, 0, 0, 0, 0, 255]);\n let p = 10, i = 0, c = -1;\n for (let b = 0; b < nb; b++) {\n const l = Math.min(65535, len - i);\n o[p] = +(b == nb - 1);\n v.setUint16(p + 1, l, true);\n v.setUint16(p + 3, ~l, true);\n o.set(d.subarray(i, (i += l)), (p += 5));\n p += l;\n }\n for (let k = 0; k < len; k++) c = CRC[(c ^ d[k]!) & 255]! ^ (c >>> 8);\n v.setUint32(p, ~c, true);\n v.setUint32(p + 4, len, true);\n return o;\n};\n\n/** segment body without assets (wire.ts layout; the replay chunk must not import wire.ts, also a build entry) */\nexport const body = (meta: string, gz: Uint8Array): Uint8Array => {\n const m = new TextEncoder().encode(meta), o = new Uint8Array(8 + m.length + gz.length), v = new DataView(o.buffer);\n v.setUint16(0, m.length, true);\n o.set(m, 2);\n v.setUint32(2 + m.length, gz.length, true);\n o.set(gz, 6 + m.length);\n return o;\n};\n"],"mappings":"mBAwBA,IChBY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AAO9F,EAAG,OAC5B,IAAMwI,QAAUyE,EAAGQ,cAAc,CAAE7I,KAAM,aAAc8I,QAASjB,IAEhE,GAAc,cAAVjE,EAAE5D,KAAsB,YAAa+C,EAAQ,GACjD,IAAMlD,EAAO,IAAIqG,iBAAiBtC,EAAEkD,eAChChH,GAAMmD,GAAID,EAAIL,IAAIzB,EAAI,CAAC9F,EAAG0E,IAC9B8C,EAAEpD,KAAK,CAAE0B,GAAI0B,EAAE7I,OAAQiG,KAAM,EAAGH,SAChCgD,GAAMhD,EAAK9F,OACX+I,GAAOjD,EAAK9F,OACZ6F,EAAI,CAAEI,KAAM,EAAGD,UAAWD,EAAID,KAAM,CAAEQ,IAAK,SAAUD,QAAS,CAAEc,KAAIvF,EAAGiH,EAAE7I,OAAS,EAAGmO,EAAGJ,EAAIM,EAAGJ,KACjG,SACEL,EAAIoB,QACJvL,EAAEqG,YAAY,CAAC,EAAG3C,EAAI6B,GACxB,GAmK2BiG,CAAK5H,EAAE,GAAIA,EAAE,GAAIA,EAAE,GAAIA,EAAE,GAAIA,EAAE,IACvC,GAARA,EAAE,IACTzD,EAAMyD,EAAE,GACRxH,EAAUwH,EAAE,IACZxD,EAAKwD,EAAE,GACPvD,EAAMuD,EAAE,IAAM,EACdpD,EAAKoD,EAAE,GAAK,EAAI,EAChBlD,EAAOkD,EAAE,IAAM,GACXA,EAAE,KACJ6H,cAAc7H,EAAE,IAChBnI,EAAKwE,KAAWyL,IAAI9H,EAAE,GAAIA,EAAE,KAEzBwD,KACY,GAARxD,EAAE,IAAcwD,EAAM,IAE5BrG,EAAEI,OAtQ2B,QAsQVkE,GAAM,GAAK,MAAQxE,IACzCA,EAAQ,EACRb,EAAEqG,YAAY,CAAC,IAEnB,OAEA,EACF,E","ignoreList":[]}
1
+ {"version":3,"names":["qre","kre","X","late","te","TextEncoder","O","redact","headers","bodyKeys","queryParams","v","redactVer","setRedact","r","d","length","FILTERED","esc","s","replace","re","k","map","join","RegExp","rJson","x","Array","isArray","y","o","Object","create","includes","toLowerCase","rText","c","trimStart","JSON","stringify","parse","split","_m","a","_x","f","db","run","st","rw","Promise","ok","no","indexedDB","open","onupgradeneeded","result","createObjectStore","autoIncrement","onsuccess","onerror","error","catch","e","then","t","transaction","objectStore","oncomplete","onabort","del","delete","G","self","CAP","url","co","cpc","last","Map","ob","draining","gate","kept","Set","asked","gap","S","sample","mem","P","raw","n","t0","t1","clicks","errs","warns","lag","urls","sig","vit","tr","tr1","push","url1","u","reset","add","data","ts","timestamp","type","href","source","p","payload","tag","level","Math","max","used","value","j","to","status","cat","msg","slice","dir","id","take","m","init","ref","user","fields","custom_fields","tags","encode","unshift","reason","segments","meta","canvas_bytes","enc","vitals","has_error","json","seg","l","ch","channel","get","size","set","A","ab","cvb","cvOff","sum","fs","q","qb","fl","tm","sv","rm","it","i","indexOf","splice","b","postMessage","go","ka","fetch","method","body","keepalive","credentials","off","ra","clearTimeout","setTimeout","pump","min","done","drain","async","now","mine","all","recs","lost","out","Date","openCursor","primaryKey","continue","byteLength","load","has","resolve","hide","send","metaJson","eventsGz","assets","RangeError","Uint8Array","dv","DataView","buffer","setUint16","setUint32","encodeSegment","Response","Blob","stream","pipeThrough","CompressionStream","arrayBuffer","put","onmessage","ids","texts","attributes","removes","adds","sid","ws_disc","seq","cut","clear","bmp","mw","ql","W0","width","H0","height","w","round","h","oc","OffscreenCanvas","getContext","drawImage","px","Uint32Array","getImageData","imul","convertToBlob","quality","full","close","shot","importScripts","rpx"],"sources":["../src/wire.ts","../src/redact.ts","../src/worker/index.ts","../src/worker/cfg.ts","../src/idb.ts","../src/seg.ts"],"sourcesContent":["/**\n * Replay segment wire format (PRD §4.10) and `.rpl` reader (PRD §5.3). Little-endian.\n *\n * body: u16 meta_len | meta JSON | u32 events_len | events (gzip) | u16 asset_count | assets…\n * asset: u32 asset_id | u8 type (1 = webp) | u32 len | bytes\n * .rpl: \"RPL2\" | u16 version | 16-byte sid, then frames:\n * u32 len | u32 seq | u64 t0 | u64 t1 | u32 received_at | u8 flags | body-without-meta\n *\n * Mirrors server/crates/common/src/{wire,rpl}.rs; cross-checked by fixtures in /fixtures/wire.\n */\n\nexport const ASSET_WEBP = 1;\nexport const RPL_HEADER_LEN = 22;\nexport const RPL_FRAME_HEADER_LEN = 29;\nexport const RPL_FLAG_GAP = 1;\nexport const RPL_FLAG_HAS_ERROR = 2;\nexport const RPL_FLAG_REDACTED = 4;\n\nexport interface WireAsset {\n id: number;\n type: number;\n data: Uint8Array;\n}\n\nconst te = /* @__PURE__ */ new TextEncoder();\n\n/** Encodes a replay segment body. `metaJson` must be a JSON object string; `eventsGz` gzip bytes. */\nexport function encodeSegment(metaJson: string, eventsGz: Uint8Array, assets: WireAsset[] = []): Uint8Array {\n const meta = te.encode(metaJson);\n if (meta.length > 32 * 1024) throw new RangeError('meta too large');\n let size = 2 + meta.length + 4 + eventsGz.length + 2;\n for (const a of assets) size += 9 + a.data.length;\n const out = new Uint8Array(size);\n const dv = new DataView(out.buffer);\n let p = 0;\n dv.setUint16(p, meta.length, true); p += 2;\n out.set(meta, p); p += meta.length;\n dv.setUint32(p, eventsGz.length, true); p += 4;\n out.set(eventsGz, p); p += eventsGz.length;\n dv.setUint16(p, assets.length, true); p += 2;\n for (const a of assets) {\n dv.setUint32(p, a.id, true); p += 4;\n out[p++] = a.type;\n dv.setUint32(p, a.data.length, true); p += 4;\n out.set(a.data, p); p += a.data.length;\n }\n return out;\n}\n\nexport interface StoredBody {\n events: Uint8Array;\n assets: WireAsset[];\n}\n\n/** Parses a body-without-meta (as stored in a `.rpl` frame). Throws on malformed input. */\nexport function parseStoredBody(b: Uint8Array): StoredBody {\n const dv = new DataView(b.buffer, b.byteOffset, b.byteLength);\n const need = (p: number, n: number) => {\n if (p + n > b.length) throw new RangeError('truncated body');\n };\n let p = 0;\n need(p, 4);\n const el = dv.getUint32(p, true); p += 4;\n need(p, el);\n const events = b.subarray(p, p + el); p += el;\n need(p, 2);\n const n = dv.getUint16(p, true); p += 2;\n const assets: WireAsset[] = [];\n for (let i = 0; i < n; i++) {\n need(p, 9);\n const id = dv.getUint32(p, true);\n const type = b[p + 4]!;\n const len = dv.getUint32(p + 5, true);\n p += 9;\n need(p, len);\n assets.push({ id, type, data: b.subarray(p, p + len) });\n p += len;\n }\n if (p !== b.length) throw new RangeError('trailing bytes');\n return { events, assets };\n}\n\n/** Splits a full segment body into meta JSON text and the stored body. */\nexport function splitSegment(b: Uint8Array): { meta: string; body: Uint8Array } {\n if (b.length < 2) throw new RangeError('truncated');\n const ml = b[0]! | (b[1]! << 8);\n if (2 + ml > b.length) throw new RangeError('truncated meta');\n return { meta: new TextDecoder().decode(b.subarray(2, 2 + ml)), body: b.subarray(2 + ml) };\n}\n\nexport interface RplFrame {\n seq: number;\n t0: number;\n t1: number;\n receivedAt: number;\n flags: number;\n body: Uint8Array;\n}\n\nexport interface RplIndex {\n sid: string;\n frames: RplFrame[];\n validLen: number;\n duplicates: number;\n}\n\nconst hex = (b: Uint8Array) => Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');\n\n/** Formats 16 raw bytes as a UUID string. */\nexport function uuidFromBytes(b: Uint8Array): string {\n const h = hex(b);\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n}\n\n/**\n * Indexes an `.rpl` buffer: ignores a truncated tail, keeps the first copy of each seq, sorts by seq.\n * Works on partial (streamed) buffers too: `validLen` tells how far complete frames go.\n */\nexport function indexRpl(buf: Uint8Array): RplIndex {\n if (buf.length < RPL_HEADER_LEN) throw new RangeError('short');\n if (buf[0] !== 0x52 || buf[1] !== 0x50 || buf[2] !== 0x4c || buf[3] !== 0x32) throw new Error('bad magic');\n const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n const version = dv.getUint16(4, true);\n if (version !== 1) throw new Error(`unsupported version ${version}`);\n const sid = uuidFromBytes(buf.subarray(6, 22));\n const frames: RplFrame[] = [];\n let p = RPL_HEADER_LEN;\n while (p + RPL_FRAME_HEADER_LEN <= buf.length) {\n const len = dv.getUint32(p, true);\n const end = p + RPL_FRAME_HEADER_LEN + len;\n if (len > 4 * 1024 * 1024 || end > buf.length) break;\n frames.push({\n seq: dv.getUint32(p + 4, true),\n t0: Number(dv.getBigUint64(p + 8, true)),\n t1: Number(dv.getBigUint64(p + 16, true)),\n receivedAt: dv.getUint32(p + 24, true),\n flags: buf[p + 28]!,\n body: buf.subarray(p + RPL_FRAME_HEADER_LEN, end),\n });\n p = end;\n }\n frames.sort((a, b) => a.seq - b.seq); // stable: first copy of a seq stays first\n const out: RplFrame[] = [];\n for (const f of frames) if (out.length === 0 || out[out.length - 1]!.seq !== f.seq) out.push(f);\n return { sid, frames: out, validLen: p, duplicates: frames.length - out.length };\n}\n","/**\n * Redaction (PRD §0.2, §4.11): headers stripped, query params + JSON keys replaced by `[Filtered]`,\n * recursive to depth 8, case-insensitive. Pure functions over `O.redact` — reusable by the worker (T-20).\n */\nimport { O, redactVer } from './config';\n\nexport const FILTERED = '[Filtered]';\nconst esc = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\nlet v = -1, qre: RegExp, kre: RegExp;\nconst re = () => {\n if (v == redactVer()) return;\n v = redactVer();\n const k = O.redact.bodyKeys.map(esc).join('|');\n // URL params: query-param list + body keys (e.g. `#access_token=` in OAuth redirects)\n qre = new RegExp(`([?&#;](?:${O.redact.queryParams.map(esc).join('|')}|${k})=)[^&#;]*`, 'gi');\n // fallback for non-JSON / truncated text: `\"key\": value` and form fields `key=value`\n kre = new RegExp(`(\"(?:${k})\"\\\\s*:\\\\s*)(\"(?:[^\"\\\\\\\\]|\\\\\\\\.)*\"?|[^,}\\\\]\\\\s]+)|((?:^|&)(?:${k})=)[^&\\\\s]*`, 'gi');\n};\n\n/** redacts secret query params (and fragment params) of a URL string */\nexport const rUrl = (u: string) => (re(), u.replace(qre, `$1${FILTERED}`));\n\n/** copies headers into a lower-cased plain object, dropping the header denylist */\nexport const rHeaders = (h: Iterable<[string, string]>) => {\n const o: Record<string, string> = {};\n for (const [k, x] of h) {\n const l = k.toLowerCase();\n if (!O.redact.headers.includes(l)) o[l] = x;\n }\n return o;\n};\n\n/** recursive key redaction; subtrees deeper than 8 levels are dropped (never leaked unredacted) */\nexport const rJson = (x: unknown, d = 0): unknown => {\n if (!x || typeof x != 'object') return x;\n if (d > 7) return '[Depth]';\n if (Array.isArray(x)) return x.map((y) => rJson(y, d + 1));\n const o: Record<string, unknown> = Object.create(null);\n for (const k in x) o[k] = O.redact.bodyKeys.includes(k.toLowerCase()) ? FILTERED : rJson((x as Record<string, unknown>)[k], d + 1);\n return o;\n};\n\n/**\n * Redacts a text body / WS frame. JSON (≤ 100 KB) is parsed and redacted structurally; newline-batched\n * JSON (Centrifugo) line by line; anything else (truncated frames, form bodies) by regex.\n */\nexport const rText = (s: string): string => {\n re();\n const c = s.trimStart()[0];\n if ((c == '{' || c == '[') && s.length < 1e5)\n try {\n return JSON.stringify(rJson(JSON.parse(s)));\n } catch {\n /* not (complete) JSON */\n }\n if (s.includes('\\n')) return s.split('\\n').map(rText).join('\\n');\n return s.replace(kre, (_m, a, _x, f) => (a ? `${a}\"${FILTERED}\"` : f + FILTERED));\n};\n","/**\n * Replay worker (PRD §4.10, D-09/D-15): per-event redaction + bookkeeping, Centrifugo per-channel sampling,\n * JSON encoding, gzip (CompressionStream), segment wrapping (wire.ts) and upload with retry/backoff, a 5 MB\n * drop-oldest queue and gap markers. Built as a classic IIFE script (build.json) with `./config` aliased to\n * ./cfg so redact.ts runs here without the main-thread config module.\n *\n * Main → worker: [0, url, redact, centrifugo, perChannelPerSec, outbox] init · [4] drain the outbox (online/resume) · [1, events] batch ·\n * [2, ids, values, ts, events] events, then coalesced texts (D-04) · [3, meta, redact, hide] cut a segment ·\n * [5, unload] drop the current segment (idle expiry, T-90); unload: the main thread sent it itself,\n * send the queue now ·\n * [6, meta, events, gap] send a segment the previous page of this tab kept when it unloaded (T-89); gap:\n * kept segments dropped before it (D-80) ·\n * [7, nodeId, ImageBitmap, ts, maxWidth, quality] canvas snapshot (T-91) ·\n * init [6, 7, 8] = stale-data extension URL (0 = off), threshold ms, lag field (T-151)\n * Worker → main: [0] raw events / canvas bytes over the segment limit (please cut) · [1, seconds] X-Replayd-Disable ·\n * [2, nodeId, off] canvas snapshot handled (the next one of that canvas may follow; off: no more) ·\n * [3, 'sid:seq'] that segment is out of this worker's hands (sent, rejected, stored or dropped, D-80) ·\n * [8, [[channel, ms, sampled]…]] Centrifugo channels that went silent while the page was visible (T-151)\n */\nimport type { RedactOptions } from '../types';\nimport { encodeSegment, type WireAsset } from '../wire';\nimport { rJson, rText, rUrl } from '../redact';\nimport { seg } from '../seg';\nimport { setRedact } from './cfg';\nimport { del, load, put } from '../idb';\nimport type { Rpx } from './wsx';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype A = any;\ninterface Q {\n b: Uint8Array;\n n: number;\n f?: boolean;\n /** outbox key (IndexedDB), when the outbox is on */\n p?: Promise<IDBValidKey | undefined>;\n /** 'sid:seq', acknowledged to the main thread once the segment leaves the queue */\n s?: string;\n}\nconst G = self as unknown as { postMessage(m: unknown): void; onmessage: ((e: MessageEvent) => void) | null };\nconst CAP = 5 << 20, KA = 6e4, FULL = 256 << 10;\n\nlet url = '', co = 0, cpc = 1, last = new Map<string, number>();\n/** T-151 stale-data / lag extension (wsx.js), when the project turned it on */\nlet X: Rpx | undefined;\n/** IndexedDB outbox (PRD §4.9: Capacitor always, web with `offlineQueue: true`): every segment is stored before\n * it is sent and deleted once the server answered; network failures stay stored and are drained later */\nlet ob = 0, draining = 0, gate = 20;\n/** 'sid:seq' of the segments the previous page of this tab handed over ([6]): their outbox copies are not sent twice */\nconst kept = new Set<string>();\n// cut already asked for the current segment\nlet asked = 0;\n// segments lost since the last one that went out (queue cap, retries exhausted, rejected)\nlet gap = 0;\n\n/** Centrifugo JSON: keeps lines whose `push.channel` passed its 1/perChannelPerSec gate (others: replies etc.) */\nconst sample = (s: string, ts: number, id: number) => {\n const k: string[] = [];\n for (const l of s.split('\\n')) {\n let ch: unknown, o: A;\n try {\n ch = (o = JSON.parse(l)).push?.channel;\n } catch {\n /* truncated / not JSON: keep */\n }\n if (typeof ch == 'string') {\n X?.f(ch, o, ts, id);\n if (ts - (last.get(ch) ?? -1e15) < 1e3 / cpc) continue;\n if (last.size > 999) last = new Map();\n last.set(ch, ts);\n }\n k.push(l);\n }\n return k.join('\\n');\n};\n\n// current segment (redaction, sampling, counters)\nconst S = seg({ u: rUrl, t: rText, j: rJson }, (s, ts, id) => (co ? sample(s, ts, id) || null : s));\n\n// ---- canvas snapshots (PRD §4.7, T-91): downscale, skip unchanged, WebP, binary asset of the current segment\n/** assets of the current segment (a canvas event names its asset by index: both always land in one segment) */\nlet A: WireAsset[] = [], ab = 0;\n/** canvas bytes of this page (PRD: 30 MB per session, then capture stops with a gap marker, `cvOff`) */\nlet cvb = 0, cvOff = 0;\n/** last frame per canvas node: [checksum, time]. A full snapshot (latest: `fs`) rebuilds blank canvases, so no frame\n * taken before it may hide a later one; its event can reach the worker before or after such frames. */\nconst sum = new Map<number, [number, number]>();\nlet fs = 0;\nconst add = (e: A) => {\n X?.e(e);\n if (e.type == 2) {\n fs = Math.max(fs, e.timestamp);\n for (const [id, [, t]] of sum) if (t < e.timestamp) sum.delete(id);\n }\n S.add(e);\n};\nconst shot = async (id: number, bmp: ImageBitmap, ts: number, mw: number, ql: number) => {\n try {\n const W0 = bmp.width, H0 = bmp.height, s = Math.min(1, mw / W0), w = Math.round(W0 * s) || 1, h = Math.round(H0 * s) || 1;\n const oc = new OffscreenCanvas(w, h), x = oc.getContext('2d')!;\n x.drawImage(bmp, 0, 0, w, h);\n // FNV-1a over the scaled pixels: an unchanged canvas (idle chart, weekend) costs no bytes\n const px = new Uint32Array(x.getImageData(0, 0, w, h).data.buffer);\n let c = 0x811c9dc5 ^ W0 ^ (H0 << 16);\n for (let i = 0; i < px.length; i++) c = Math.imul(c ^ px[i]!, 16777619);\n if (sum.get(id)?.[0] === c) return;\n const b = await oc.convertToBlob({ type: 'image/webp', quality: ql });\n // frames finish in any order: the first to cap (or to find no WebP encoder: Safari returns PNG, the wire format only\n // carries WebP, so no canvases there) stops the others. The page budget is checked with the finished frame, which\n // must fit whole, and reserved before anything else awaits: encodes in flight cannot overshoot it together.\n if (cvOff) return;\n const full = cvb + b.size > 30 << 20;\n if (full || b.type != 'image/webp') {\n if (full) add({ type: 5, timestamp: ts, data: { tag: 'gap', payload: { reason: 'canvas cap' } } });\n return void (cvOff = 1);\n }\n cvb += b.size;\n const data = new Uint8Array(await b.arrayBuffer());\n if (ts >= fs) sum.set(id, [c, ts]);\n A.push({ id: A.length, type: 1, data });\n ab += data.length;\n add({ type: 5, timestamp: ts, data: { tag: 'canvas', payload: { id, a: A.length - 1, w: W0, h: H0 } } });\n } finally {\n bmp.close();\n G.postMessage([2, id, cvOff]);\n }\n};\n\n// ---- upload queue: one request in flight, exp. backoff 1 s → 60 s, max 5 attempts, Retry-After on 429/503\nconst q: Q[] = [];\n// sv: the pending timer is a server Retry-After (honoured even on online/resume), else a network backoff\nlet qb = 0, fl = 0, tm: ReturnType<typeof setTimeout> | 0 = 0, sv = false;\nconst rm = (it: Q) => {\n const i = q.indexOf(it);\n if (i >= 0) qb -= q.splice(i, 1)[0]!.b.length;\n if (it.s) G.postMessage([3, it.s]);\n};\nconst go = (it: Q, ka: boolean) => {\n it.f = true;\n fl++;\n fetch(url, { method: 'POST', body: it.b as BodyInit, keepalive: ka, credentials: 'omit', headers: { 'Content-Type': 'text/plain' } })\n .then(\n (r) => {\n const off = +(r.headers.get('x-replayd-disable') ?? 0);\n if (off > 0) G.postMessage([1, off]);\n const s = r.status;\n // 0 = done; -2 = rejected (4xx other than 429: retrying can't fix it); > 0 Retry-After s; -1 backoff\n return s < 400 ? 0 : s < 500 && s != 429 ? -2 : +(r.headers.get('retry-after') ?? 0) || -1;\n },\n () => -1,\n )\n .then((ra) => {\n it.f = false;\n fl--;\n if (ra > -2 && ra && ++it.n < 5) {\n clearTimeout(tm);\n sv = ra > 0;\n tm = setTimeout(\n () => {\n tm = 0;\n pump();\n },\n ra > 0 ? ra * 1e3 : Math.min(6e4, 500 * 2 ** it.n),\n );\n return;\n }\n // stored segments survive network/5xx failures (drained on online/resume/next start); else: lost\n if (ob && ra == -1) {\n rm(it);\n return;\n }\n if (ra) gap++;\n done(it);\n pump();\n });\n};\n/** finished (sent or rejected): out of memory and out of the outbox */\nconst done = (it: Q) => {\n rm(it);\n it.p?.then((k) => k != null && del('q', k)).catch(() => {});\n};\n/** loads stored segments that are not in memory (oldest first, ≤ the memory cap); expired/over-cap → gap */\nconst drain = async (now?: 1) => {\n // back online / resumed: a network backoff (up to 60 s) would hold the whole outbox, retry now\n if (now && tm && !sv) {\n clearTimeout(tm);\n tm = 0;\n pump();\n }\n // also without the outbox: an unloading page stores the segments it could not send there (D-80)\n if (draining) return;\n draining = 1;\n try {\n const mine = new Set(await Promise.all(q.map((x) => x.p)));\n const [recs, lost] = await load('q');\n gap += lost;\n for (const [k, r] of recs) {\n if (mine.has(k) || qb + r.b.byteLength > CAP) continue;\n if (r.s && kept.has(r.s)) {\n del('q', k).catch(() => {});\n continue;\n }\n q.push({ b: r.b, n: 0, p: Promise.resolve(k) });\n qb += r.b.byteLength;\n }\n } catch {\n /* no IndexedDB (private mode, quota): memory queue only */\n }\n draining = 0;\n pump();\n};\n/** sends the head (sequential); on hide: everything not in flight, keepalive within a 60 KB total */\nconst pump = (hide?: boolean) => {\n if (!hide && (fl || tm)) return;\n let ka = KA;\n for (const it of q) {\n if (it.f) continue;\n const s = it.b.length;\n if (!hide) return go(it, s < KA);\n const k = s < ka;\n if (k) ka -= s;\n go(it, k);\n }\n};\n\n/** meta of a cut that had no events to go with (all of them sampled out). The main thread has already counted its\n * init, field snapshot and WS disconnects as sent: they go with the next segment of that session. */\nlet late: A;\nconst sig = (x: A) => add({ type: 5, timestamp: Date.now(), data: { tag: 'sig', payload: x } });\nconst cut =(m: A, r: Required<RedactOptions>, hide: boolean) => {\n setRedact(r);\n const st = X?.c(gate, sig);\n if (st?.length) G.postMessage([8, st]);\n if (late && late.sid == m.sid) {\n m.init ??= late.init;\n m.fields ??= late.fields;\n m.ws_disc += late.ws_disc;\n }\n late = 0;\n const s = `${m.sid}:${m.seq}`;\n if (!S.n()) return void ((late = m), G.postMessage([3, s]));\n const [meta, json] = S.take({ ...m, canvas_bytes: ab }, gap), a = A;\n asked = gap = ab = 0;\n A = [];\n return send(meta, json, s, hide, a);\n};\nconst send = async (meta: string, json: string, s: string, hide?: boolean, a?: WireAsset[]) => {\n const gz = new Uint8Array(await new Response(new Blob([json]).stream().pipeThrough(new CompressionStream('gzip'))).arrayBuffer());\n const b = encodeSegment(meta, gz, a), it: Q = { b, n: 0, s };\n if (ob) it.p = put('q', { t: Date.now(), b }).catch(() => undefined);\n q.push(it);\n qb += b.length;\n // 5 MB memory cap: drop the oldest segments that are not in flight (with the outbox they stay stored)\n for (let i = 0; qb > CAP && i < q.length - 1; )\n if (q[i]!.f) i++;\n else {\n rm(q[i]!);\n if (!ob) gap++;\n }\n pump(hide);\n};\n\nG.onmessage = (e: MessageEvent) => {\n const m = e.data;\n try {\n // redaction lists that grew since the last message apply before this batch is redacted\n if (m[0] == 1) {\n if (m[2]) setRedact(m[2]);\n for (const x of m[1]) add(x);\n } else if (m[0] == 2) {\n if (m[5]) setRedact(m[5]);\n for (const x of m[4] ?? []) add(x);\n const ids: Int32Array = m[1], v: string[] = m[2].split('\\0'), texts = [];\n for (let i = 0; i < ids.length; i++) texts.push({ id: ids[i], value: v[i] });\n add({ type: 3, timestamp: m[3], data: { source: 0, texts, attributes: [], removes: [], adds: [] } });\n } else if (m[0] == 3) cut(m[1], m[2], m[3])?.catch(() => {});\n else if (m[0] == 5) {\n S.reset();\n A = [];\n asked = ab = 0;\n // the dropped frames never reach the replay: an unchanged canvas has to be sent again\n sum.clear();\n if (m[1]) pump(true);\n } else if (m[0] == 6) {\n const x = JSON.parse(m[1]), s = `${x.sid}:${x.seq}`;\n kept.add(s);\n gap += m[3] | 0;\n send(m[1], m[2], s).catch(() => {});\n }\n else if (m[0] == 7) void shot(m[1], m[2], m[3], m[4], m[5]);\n else if (m[0] == 0) {\n url = m[1];\n setRedact(m[2]);\n co = m[3];\n cpc = m[4] || 1;\n ob = m[5] ? 1 : 0;\n gate = m[9] || 20;\n if (m[6]) {\n importScripts(m[6]);\n // a quiet page sends no cut: the extension checks for silent channels on its own timer (the main thread has the\n // warning shown and marks the segment dirty so the `sig` event ships)\n X = (self as A).rpx(m[7], m[8], gate, sig, (st: A) => G.postMessage([8, st, 1]));\n }\n void drain();\n } else if (m[0] == 4) void drain(1);\n // [9, 1] = the page is hidden or asleep: no stale check until [9, 0]\n else if (m[0] == 9) X?.p(m[1]);\n // canvas frames count as well: a segment stays well under the 2 MB ingest limit\n if ((S.raw() >= FULL || ab >= 1 << 20) && !asked) {\n asked = 1;\n G.postMessage([0]);\n }\n } catch {\n /* a malformed event must not kill the worker */\n }\n};\n","/**\n * Worker build stand-in for `../config` (build.json alias): redact.ts reads its lists from `O.redact`.\n * The main thread sends the resolved lists (defaults + user + remote extensions) with every segment cut.\n */\nimport type { RedactOptions } from '../types';\n\nexport const O = { redact: { headers: [], bodyKeys: [], queryParams: [] } as Required<RedactOptions> };\nlet v = 0;\nexport const redactVer = () => v;\n/** replaces the lists when they changed (they only ever grow, so comparing lengths is enough) */\nexport const setRedact = (r: Required<RedactOptions>) => {\n const d = O.redact;\n if (r.headers.length + r.bodyKeys.length + r.queryParams.length != d.headers.length + d.bodyKeys.length + d.queryParams.length) {\n O.redact = r;\n v++;\n }\n};\n","/**\n * Tiny IndexedDB outbox shared by the replay worker (store `q`: segments) and the Capacitor chunk (store `e`:\n * error-event bodies). PRD §4.9: cap 20 MB, max age 24 h, oldest first. Never imported by index.js.\n * Records: `{ t: enqueued ms, b: body bytes, k?: ingest kind }`, auto-increment keys (= insertion order).\n */\nexport interface Rec {\n t: number;\n b: Uint8Array;\n k?: string;\n /** 'sid:seq' of a replay segment an unloading page stored (D-80) */\n s?: string;\n}\nexport const CAP = 20 << 20, AGE = 864e5;\nlet db: Promise<IDBDatabase> | null = null;\nconst open = () =>\n (db ??= new Promise<IDBDatabase>((ok, no) => {\n const r = indexedDB.open('replayd', 1);\n r.onupgradeneeded = () => {\n for (const s of ['q', 'e']) r.result.createObjectStore(s, { autoIncrement: true });\n };\n r.onsuccess = () => ok(r.result);\n r.onerror = () => no(r.error);\n })).catch((e) => {\n db = null;\n throw e;\n });\n\nconst run = <T>(st: string, rw: boolean, f: (s: IDBObjectStore) => IDBRequest<T> | void) =>\n open().then(\n (d) =>\n new Promise<T | undefined>((ok, no) => {\n const t = d.transaction(st, rw ? 'readwrite' : 'readonly'), r = f(t.objectStore(st));\n t.oncomplete = () => ok(r ? r.result : undefined);\n t.onerror = t.onabort = () => no(t.error);\n }),\n );\n\n/** appends a record; resolves to its key */\nexport const put = (st: string, v: Rec) => run<IDBValidKey>(st, true, (s) => s.add(v));\nexport const del = (st: string, k: IDBValidKey) => run(st, true, (s) => void s.delete(k));\n\n/**\n * All records oldest first, after dropping the expired (> 24 h) and the oldest beyond 20 MB.\n * Resolves to `[kept: [key, rec][], dropped count]`.\n */\nexport const load = (st: string): Promise<[[IDBValidKey, Rec][], number]> => {\n const out: [IDBValidKey, Rec][] = [], all: [IDBValidKey, Rec][] = [];\n let n = 0, size = 0;\n return run(st, true, (s) => {\n const now = Date.now(), c = s.openCursor();\n c.onsuccess = () => {\n const x = c.result;\n if (x) {\n all.push([x.primaryKey, x.value as Rec]);\n x.continue();\n return;\n }\n // newest first for the size cap, then back to oldest-first order\n for (let i = all.length - 1; i >= 0; i--) {\n const [k, v] = all[i]!;\n if (now - v.t > AGE || (size += v.b.byteLength) > CAP) {\n s.delete(k);\n n++;\n } else out.unshift([k, v]);\n }\n };\n }).then(() => [out, n]);\n};\n","/**\n * Replay segment builder (PRD §4.10), shared by the worker and, on page unload, the replay chunk's main thread\n * (T-89): per-event redaction and bookkeeping, then the meta + events JSON of one segment. It imports nothing: the\n * redaction functions are passed in (the worker has its own copy of redact.ts, the main thread core's through\n * `Internal`), so neither build pulls a core module into a shared chunk.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype A = any;\nexport interface Red {\n /** URL redaction (query/fragment params) */\n u: (s: string) => string;\n /** text body / WS frame redaction */\n t: (s: string) => string;\n /** recursive JSON key redaction */\n j: (x: unknown) => unknown;\n}\n\n/** `sample`: incoming WS frame (raw, time, socket id) → the frame to keep, null = drop it (worker: Centrifugo per-channel\n * sampling, T-151 stale-data bookkeeping) */\nexport const seg = (r: Red, sample?: (raw: string, ts: number, id: number) => string | null) => {\n let P: string[] = [], raw = 0, n = 0, t0 = 0, t1 = 0, clicks = 0, errs = 0, warns = 0, lag = 0, urls: string[] = [], sig: Record<string, number> = {}, vit: A[] = [], mem: A, st: number[] = [], tr: string[] = [];\n // T-123: the order things first happened in (`u:` page URL, `c:` app breadcrumb `cat:msg`), for search and funnels\n const tr1 = (x: string) => tr.length < 30 && !tr.includes(x) && tr.push(x);\n const url1 = (u: unknown) => typeof u == 'string' && (tr1('u:' + u), urls.length < 10 && !urls.includes(u) && urls.push(u));\n const reset = () => {\n P = [];\n raw = n = t1 = clicks = errs = warns = lag = 0;\n urls = [];\n sig = {};\n vit = [];\n mem = undefined;\n st = [];\n tr = [];\n };\n return {\n raw: () => raw,\n n: () => n,\n reset,\n add(e: A) {\n const d = e.data, ts = e.timestamp;\n if (e.type == 4 && d.href) url1((d.href = r.u(d.href)));\n else if (e.type == 3 && d.source == 2 && d.type == 2) clicks++;\n else if (e.type == 5) {\n const p = d.payload;\n if (d.tag == 'error') {\n if (p.level == 'warning') warns++;\n else errs++;\n }\n else if (d.tag == 'sig') {\n sig[p.k] = (sig[p.k] ?? 0) + 1;\n if (p.k == 'vitals') vit.push(p);\n // T-151: the segment's largest server-to-client lag (ms)\n if (p.k == 'lag') lag = Math.max(lag, p.max);\n // T-119: the segment's heap peak (and device memory from the first sample)\n if (p.k == 'mem') mem = { ...mem, ...p, used: Math.max(mem?.used ?? 0, p.used ?? 0) };\n }\n else if (d.tag == 'fields') p.value = r.j(p.value);\n // core redacts its history navigations; the page-load entry comes raw from the replay chunk\n else if (d.tag == 'nav' && typeof p.to == 'string') url1((p.to = r.u(p.to)));\n else if (d.tag == 'network') {\n for (const k of ['reqBody', 'resBody']) if (typeof p[k] == 'string') p[k] = r.t(p[k]);\n // T-123: failed statuses seen (0 = no response)\n if ((p.status >= 400 || p.status === 0) && st.length < 10 && !st.includes(p.status)) st.push(p.status);\n }\n else if (d.tag == 'breadcrumb') tr1(('c:' + p.cat + ':' + p.msg).slice(0, 100));\n else if (d.tag == 'ws' && typeof p.raw == 'string') {\n if (sample && p.dir == 'in') {\n const x = sample(p.raw, ts, p.id);\n if (x == null) return;\n p.raw = x;\n }\n p.raw = r.t(p.raw);\n }\n }\n if (!n++) t0 = ts;\n if (ts > t1) t1 = ts;\n const s = JSON.stringify(e);\n raw += s.length;\n P.push(s);\n },\n /** the segment's [meta JSON, events JSON]; `m` = sid/seq/init/fields from the main thread, `gap` = segments lost\n * before it. Starts the next segment. */\n take(m: A, gap: number): [string, string] {\n if (m.init) {\n m.init.url = r.u(m.init.url);\n m.init.ref = r.u(m.init.ref);\n m.init.user = r.j(m.init.user);\n }\n if (m.fields) {\n m.fields.user = r.j(m.fields.user);\n m.fields.custom_fields = r.j(m.fields.custom_fields);\n m.fields.tags = r.j(m.fields.tags);\n // tags have no limit of their own: past 8 KB they stay out (the server keeps the last ones) so the 32 KB meta fits\n if (new TextEncoder().encode(JSON.stringify(m.fields.tags)).length > 8192) delete m.fields.tags;\n }\n if (gap) P.unshift(JSON.stringify({ type: 5, timestamp: t0, data: { tag: 'gap', payload: { reason: 'dropped', segments: gap } } }));\n const meta = JSON.stringify({ canvas_bytes: 0, ...m, t0, t1, enc: 'gzip', n, urls, clicks, errs, warns, sig, vitals: vit, mem, st, tr, lag: lag || undefined, has_error: errs > 0, gap: gap > 0 });\n const json = `[${P.join(',')}]`;\n reset();\n return [meta, json];\n },\n };\n};\n\nlet CRC: Int32Array | undefined;\n/**\n * gzip without compression (stored deflate blocks), built synchronously: a page that is unloading cannot wait for\n * CompressionStream. Larger than real gzip, so it is only used for the unload segment's keepalive request.\n */\nexport const stored = (d: Uint8Array): Uint8Array => {\n if (!CRC) {\n CRC = new Int32Array(256);\n for (let i = 0; i < 256; i++) {\n let c = i;\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n CRC[i] = c;\n }\n }\n const len = d.length, nb = Math.ceil(len / 65535) || 1, o = new Uint8Array(18 + len + nb * 5), v = new DataView(o.buffer);\n o.set([31, 139, 8, 0, 0, 0, 0, 0, 0, 255]);\n let p = 10, i = 0, c = -1;\n for (let b = 0; b < nb; b++) {\n const l = Math.min(65535, len - i);\n o[p] = +(b == nb - 1);\n v.setUint16(p + 1, l, true);\n v.setUint16(p + 3, ~l, true);\n o.set(d.subarray(i, (i += l)), (p += 5));\n p += l;\n }\n for (let k = 0; k < len; k++) c = CRC[(c ^ d[k]!) & 255]! ^ (c >>> 8);\n v.setUint32(p, ~c, true);\n v.setUint32(p + 4, len, true);\n return o;\n};\n\n/** segment body without assets (wire.ts layout; the replay chunk must not import wire.ts, also a build entry) */\nexport const body = (meta: string, gz: Uint8Array): Uint8Array => {\n const m = new TextEncoder().encode(meta), o = new Uint8Array(8 + m.length + gz.length), v = new DataView(o.buffer);\n v.setUint16(0, m.length, true);\n o.set(m, 2);\n v.setUint32(2 + m.length, gz.length, true);\n o.set(gz, 6 + m.length);\n return o;\n};\n"],"mappings":"mBAwBA,IChBYA,EAAaC,ECmCrBC,EAuLAC,EF1MEC,EAAqB,IAAIC,YGlBlBC,EAAI,CAAEC,OAAQ,CAAEC,QAAS,GAAIC,SAAU,GAAIC,YAAa,KACjEC,EAAI,EACKC,EAAY,IAAMD,EAElBE,EAAaC,IACx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AAO,IAAIqG,iBAAiBtC,EAAEkD,eAChChH,GAAMmD,GAAID,EAAIL,IAAIzB,EAAI,CAAC9F,EAAG0E,IAC9B8C,EAAEpD,KAAK,CAAE0B,GAAI0B,EAAE7I,OAAQiG,KAAM,EAAGH,SAChCgD,GAAMhD,EAAK9F,OACX6F,EAAI,CAAEI,KAAM,EAAGD,UAAWD,EAAID,KAAM,CAAEQ,IAAK,SAAUD,QAAS,CAAEc,KAAIvF,EAAGiH,EAAE7I,OAAS,EAAGmO,EAAGJ,EAAIM,EAAGJ,KACjG,SACEL,EAAIqB,QACJxL,EAAEqG,YAAY,CAAC,EAAG3C,EAAI6B,GACxB,GAoK2BkG,CAAK7H,EAAE,GAAIA,EAAE,GAAIA,EAAE,GAAIA,EAAE,GAAIA,EAAE,IACvC,GAARA,EAAE,IACTzD,EAAMyD,EAAE,GACRxH,EAAUwH,EAAE,IACZxD,EAAKwD,EAAE,GACPvD,EAAMuD,EAAE,IAAM,EACdpD,EAAKoD,EAAE,GAAK,EAAI,EAChBlD,EAAOkD,EAAE,IAAM,GACXA,EAAE,KACJ8H,cAAc9H,EAAE,IAGhBnI,EAAKwE,KAAW0L,IAAI/H,EAAE,GAAIA,EAAE,GAAIlD,EAAMkB,EAAMpD,GAAUwB,EAAEqG,YAAY,CAAC,EAAG7H,EAAI,MAEzE4I,KACY,GAARxD,EAAE,GAAcwD,EAAM,GAEhB,GAARxD,EAAE,IAASnI,GAAGkH,EAAEiB,EAAE,KAEtB7C,EAAEI,OA5Q2B,QA4QVkE,GAAM,GAAK,MAAQxE,IACzCA,EAAQ,EACRb,EAAEqG,YAAY,CAAC,IAEnB,OAEA,EACF,E","ignoreList":[]}
package/dist/wsx.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";self.rpx=(e,t)=>{let a=new Map,l=new Map,r=new Map,s=t?t.split("."):[],n=0,f=0,o=Date.now();return{f(t,n,f,o){l.set(o,(l.get(o)??0)+1);let i=a.get(t)??(a.size<200?[0,0,0,0]:0);if(e&&i&&(i[0]=f,i[1]=o,i[2]++,a.set(t,i)),!s.length)return;let p=n.push.pub?.data;for(let e of s)p=p?.[e];let h="number"==typeof p?p<1e12?1e3*p:p:"string"==typeof p?Date.parse(p):NaN;if(h>0){let e=r.get(t)??[];e.length<256&&r.set(t,(e.push(f-h),e))}},e(e){let t="ws"==e.data?.tag&&e.data.payload;if(t){if("close"==t.k)for(let[e,l]of a)l[1]==t.id&&a.delete(e);if("out"==t.dir&&"string"==typeof t.raw&&t.raw.includes('"unsubscribe"'))for(let e of t.raw.split("\n"))try{a.delete(JSON.parse(e).unsubscribe.channel)}catch{}}},c(t,s,i){let p=Date.now(),h=[],u=new Set;for(let[e,t]of l)t>=(p-o)/1e3*s*.5&&u.add(e);if(l.clear(),o=p,t?f=1:f&&(f=0,n=p),e&&!f)for(let[t,l]of a)if(l[2]>2&&p-Math.max(l[0],n)>e&&p-l[3]>6e4){l[3]=p;let e=p-l[0],a=u.has(l[1])?1:0;i({k:"stale",ch:t,ms:e,...a?{sampled:1}:{}}),h.push([t,e,a])}for(let[e,t]of r)t.sort((e,t)=>e-t),i({k:"lag",ch:e,n:t.length,max:t[t.length-1],p95:t[Math.min(t.length-1,Math.floor(.95*t.length))]});return r.clear(),h}}};
1
+ "use strict";self.rpx=(e,t,l,a,r)=>{let n=new Map,s=new Map,f=new Map,o=0,i=t?t.split("."):[],p=0,h=0,u=Date.now(),g=(e,t)=>{let l=new Set;for(let[a,r]of s)r>=(e-u)/1e3*t*.5&&l.add(a);return l},c=(t,l,a)=>{let r=[];if(e&&!h)for(let[s,f]of n)if(f[2]>2&&t-Math.max(f[0],p)>e&&t-f[3]>6e4){f[3]=t;let e=t-f[0],n=l.has(f[1])?1:0;a({k:"stale",ch:s,ms:e,...n?{sampled:1}:{}}),r.push([s,e,n])}return r};return e&&setInterval(()=>{let e=Date.now(),t=c(e,g(e,l),a);t.length&&r(t)},5e3),{f(t,l,a,r){s.set(r,(s.get(r)??0)+1);let p=n.get(t)??(n.size<200?[0,0,0,0]:0);if(e&&p&&(p[0]=a,p[1]=r,p[2]++,n.set(t,p)),!i.length)return;let h=l.push.pub?.data;for(let e of i)h=h?.[e];let u="number"==typeof h?h<1e12?1e3*h:h:"string"==typeof h?Date.parse(h):NaN;if(u>0){let e=f.get(t)??(n.has(t)||n.size+f.size<200?[]:0);e?e.length<256&&f.set(t,(e.push(a-u),e)):o++}},e(e){let t="ws"==e.data?.tag&&e.data.payload;if(t){if("close"==t.k)for(let[e,l]of n)l[1]==t.id&&n.delete(e);if("out"==t.dir&&"string"==typeof t.raw&&t.raw.includes('"unsubscribe"'))for(let e of t.raw.split("\n"))try{n.delete(JSON.parse(e).unsubscribe.channel)}catch{}}},p(e){h=e,e||(p=Date.now())},c(e,t){let l=Date.now(),a=g(l,e);s.clear(),u=l;let r=c(l,a,t);for(let[e,l]of f)l.sort((e,t)=>e-t),t({k:"lag",ch:e,n:l.length,max:l[l.length-1],p95:l[Math.min(l.length-1,Math.floor(.95*l.length))]});return f.clear(),o&&t({k:"lagskip",n:o}),o=0,r}}};
2
2
  //# sourceMappingURL=wsx.js.map
package/dist/wsx.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"names":["self","rpx","sm","path","cs","Map","sk","lag","lf","split","vs","hid","last","Date","now","f","ch","o","ts","id","set","get","c","size","length","v","push","pub","data","t","parse","NaN","a","e","p","tag","payload","k","delete","dir","raw","includes","l","JSON","unsubscribe","channel","hide","gate","add","out","busy","Set","n","clear","Math","max","ms","s","has","sampled","sort","x","y","p95","min","floor"],"sources":["../src/worker/wsx.ts"],"sourcesContent":["/**\n * T-151 worker extension: stale data and server-to-client lag per Centrifugo channel. Built as its own classic script\n * (`wsx.js`) and loaded into the replay worker with `importScripts` only when a project turns the detector on (remote\n * config `ws.staleMs` / `ws.lagField`), so the worker itself stays within its budget and nothing runs otherwise.\n *\n * It only sees frames that already passed the main thread's timestamp gate (no work is added to the per-message\n * path). Socket silence is exact (the gate always passes the first message after a gap); a channel's silence is\n * judged from the frames that passed, so on a busy socket it can be a sampling effect: the event says `sampled`.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype A = any;\n\nconst rpx = (sm: number, path: string) => {\n /** per channel: [last frame, socket id, frames seen, last flagged] (≤ 200 channels) */\n const cs = new Map<string, number[]>();\n /** per socket: frames that passed the gate since the last cut, and the gate's own limit (frames/s) */\n const sk = new Map<number, number>();\n /** lag samples (ms) per channel since the last cut (≤ 256 each) */\n const lag = new Map<string, number[]>();\n const lf = path ? path.split('.') : [];\n let vs = 0, hid = 0, last = Date.now();\n return {\n /** an incoming Centrifugo push of channel `ch` (`o` = the parsed line) on socket `id`, received at `ts` */\n f(ch: string, o: A, ts: number, id: number) {\n sk.set(id, (sk.get(id) ?? 0) + 1);\n const c = cs.get(ch) ?? (cs.size < 200 ? [0, 0, 0, 0] : 0);\n if (sm && c) {\n c[0] = ts;\n c[1] = id;\n c[2]!++;\n cs.set(ch, c);\n }\n if (!lf.length) return;\n let v = o.push.pub?.data;\n for (const f of lf) v = v?.[f];\n // epoch ms, epoch seconds or an ISO date\n const t = typeof v == 'number' ? (v < 1e12 ? v * 1e3 : v) : typeof v == 'string' ? Date.parse(v) : NaN;\n if (t > 0) {\n const a = lag.get(ch) ?? [];\n if (a.length < 256) lag.set(ch, (a.push(ts - t), a));\n }\n },\n /** any event of the segment: a closed socket's channels and unsubscribed channels are not stale */\n e(e: A) {\n const p = e.data?.tag == 'ws' && e.data.payload;\n if (!p) return;\n if (p.k == 'close') for (const [ch, c] of cs) if (c[1] == p.id) cs.delete(ch);\n if (p.dir == 'out' && typeof p.raw == 'string' && p.raw.includes('\"unsubscribe\"'))\n for (const l of p.raw.split('\\n'))\n try {\n cs.delete(JSON.parse(l).unsubscribe.channel);\n } catch {\n /* another command */\n }\n },\n /**\n * a segment cut: `hide` = the page is being hidden. Adds `sig` events through `add`, returns the channels that\n * went silent while the page was visible (≤ 1 per channel per minute) for the main thread's warning.\n */\n c(hide: boolean, gate: number, add: (x: A) => void): [string, number, number][] {\n const now = Date.now(), out: [string, number, number][] = [];\n // a socket whose gate let through at least half of what it allows was dropping frames: channel silence there\n // can be sampling\n const busy = new Set<number>();\n for (const [id, n] of sk) if (n >= ((now - last) / 1e3) * gate * 0.5) busy.add(id);\n sk.clear();\n last = now;\n if (hide) hid = 1;\n else if (hid) {\n hid = 0;\n vs = now;\n }\n if (sm && !hid)\n for (const [ch, c] of cs)\n if (c[2]! > 2 && now - Math.max(c[0]!, vs) > sm && now - c[3]! > 6e4) {\n c[3] = now;\n const ms = now - c[0]!, s = busy.has(c[1]!) ? 1 : 0;\n add({ k: 'stale', ch, ms, ...(s ? { sampled: 1 } : {}) });\n out.push([ch, ms, s]);\n }\n for (const [ch, a] of lag) {\n a.sort((x, y) => x - y);\n add({ k: 'lag', ch, n: a.length, max: a[a.length - 1], p95: a[Math.min(a.length - 1, Math.floor(a.length * 0.95))] });\n }\n lag.clear();\n return out;\n },\n };\n};\n(self as A).rpx = rpx;\nexport type Rpx = ReturnType<typeof rpx>;\n"],"mappings":"aAyFCA,KAAWC,IA7EA,CAACC,EAAYC,KAEvB,IAAMC,EAAK,IAAIC,IAETC,EAAK,IAAID,IAETE,EAAM,IAAIF,IACVG,EAAKL,EAAOA,EAAKM,MAAM,KAAO,GAChCC,EAAK,EAAGC,EAAM,EAAGC,EAAOC,KAAKC,MACjC,MAAO,CAEL,CAAAC,CAAEC,EAAYC,EAAMC,EAAYC,GAC9Bb,EAAGc,IAAID,GAAKb,EAAGe,IAAIF,IAAO,GAAK,GAC/B,IAAMG,EAAIlB,EAAGiB,IAAIL,KAAQZ,EAAGmB,KAAO,IAAM,CAAC,EAAG,EAAG,EAAG,GAAK,GAOxD,GANIrB,GAAMoB,IACRA,EAAE,GAAKJ,EACPI,EAAE,GAAKH,EACPG,EAAE,KACFlB,EAAGgB,IAAIJ,EAAIM,KAERd,EAAGgB,OAAQ,OAChB,IAAIC,EAAIR,EAAES,KAAKC,KAAKC,KACpB,QAAWb,KA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,IAAIpC,EAAE,IAAO,EAAI,EAClD0B,EAAI,CAAEX,EAAG,QAASrB,KAAIwC,QAAQC,EAAI,CAAEE,QAAS,GAAM,CAAC,IACpDV,EAAIvB,KAAK,CAACV,EAAIwC,EAAIC,GACpB,CACJ,QAAYzC,EAAIgB,KAAMzB,EACpByB,EAAE4B,KAAK,CAACC,EAAGC,IAAMD,EAAIC,GACrBd,EAAI,CAAEX,EAAG,MAAOrB,KAAIoC,EAAGpB,EAAER,OAAQ+B,IAAKvB,EAAEA,EAAER,OAAS,GAAIuC,IAAK/B,EAAEsB,KAAKU,IAAIhC,EAAER,OAAS,EAAG8B,KAAKW,MAAiB,IAAXjC,EAAER,YAEpG,OAAAjB,EAAI8C,QACGJ,CACT","ignoreList":[]}
1
+ {"version":3,"names":["self","rpx","sm","path","gate","sig","post","cs","Map","sk","lag","dr","lf","split","vs","hid","last","Date","now","busy","b","Set","id","n","add","stale","out","ch","c","Math","max","ms","s","has","k","sampled","push","setInterval","st","length","f","o","ts","set","get","size","v","pub","data","t","parse","NaN","a","e","p","tag","payload","delete","dir","raw","includes","l","JSON","unsubscribe","channel","off","clear","sort","x","y","p95","min","floor"],"sources":["../src/worker/wsx.ts"],"sourcesContent":["/**\n * T-151 worker extension: stale data and server-to-client lag per Centrifugo channel. Built as its own classic script\n * (`wsx.js`) and loaded into the replay worker with `importScripts` only when a project turns the detector on (remote\n * config `ws.staleMs` / `ws.lagField`), so the worker itself stays within its budget and nothing runs otherwise.\n *\n * It only sees frames that already passed the main thread's timestamp gate (no work is added to the per-message\n * path). Socket silence is exact (the gate always passes the first message after a gap); a channel's silence is\n * judged from the frames that passed, so on a busy socket it can be a sampling effect: the event says `sampled`.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype A = any;\n\nconst rpx = (sm: number, path: string, gate: number, sig: (x: A) => void, post: (st: [string, number, number][]) => void) => {\n /** per channel: [last frame, socket id, frames seen, last flagged] (≤ 200 channels) */\n const cs = new Map<string, number[]>();\n /** per socket: frames that passed the gate since the last cut, and the gate's own limit (frames/s) */\n const sk = new Map<number, number>();\n /** lag samples (ms) per channel since the last cut (≤ 256 each); with `cs` they share one budget of 200 channel names */\n const lag = new Map<string, number[]>();\n /** lag observations of channels over that budget since the last cut */\n let dr = 0;\n const lf = path ? path.split('.') : [];\n let vs = 0, hid = 0, last = Date.now();\n // a socket whose gate let through at least half of what it allows was dropping frames: channel silence there can be\n // sampling\n const busy = (now: number, gate: number) => {\n const b = new Set<number>();\n for (const [id, n] of sk) if (n >= ((now - last) / 1e3) * gate * 0.5) b.add(id);\n return b;\n };\n const stale = (now: number, b: Set<number>, add: (x: A) => void) => {\n const out: [string, number, number][] = [];\n if (sm && !hid)\n for (const [ch, c] of cs)\n if (c[2]! > 2 && now - Math.max(c[0]!, vs) > sm && now - c[3]! > 6e4) {\n c[3] = now;\n const ms = now - c[0]!, s = b.has(c[1]!) ? 1 : 0;\n add({ k: 'stale', ch, ms, ...(s ? { sampled: 1 } : {}) });\n out.push([ch, ms, s]);\n }\n return out;\n };\n // the 5 s check of a quiet page (it sends no cut): the stale part of `c` alone, same cooldown\n if (sm)\n setInterval(() => {\n const now = Date.now(), st = stale(now, busy(now, gate), sig);\n if (st.length) post(st);\n }, 5e3);\n return {\n /** an incoming Centrifugo push of channel `ch` (`o` = the parsed line) on socket `id`, received at `ts` */\n f(ch: string, o: A, ts: number, id: number) {\n sk.set(id, (sk.get(id) ?? 0) + 1);\n const c = cs.get(ch) ?? (cs.size < 200 ? [0, 0, 0, 0] : 0);\n if (sm && c) {\n c[0] = ts;\n c[1] = id;\n c[2]!++;\n cs.set(ch, c);\n }\n if (!lf.length) return;\n let v = o.push.pub?.data;\n for (const f of lf) v = v?.[f];\n // epoch ms, epoch seconds or an ISO date\n const t = typeof v == 'number' ? (v < 1e12 ? v * 1e3 : v) : typeof v == 'string' ? Date.parse(v) : NaN;\n if (t > 0) {\n const a = lag.get(ch) ?? (cs.has(ch) || cs.size + lag.size < 200 ? [] : 0);\n if (!a) dr++;\n else if (a.length < 256) lag.set(ch, (a.push(ts - t), a));\n }\n },\n /** any event of the segment: a closed socket's channels and unsubscribed channels are not stale */\n e(e: A) {\n const p = e.data?.tag == 'ws' && e.data.payload;\n if (!p) return;\n if (p.k == 'close') for (const [ch, c] of cs) if (c[1] == p.id) cs.delete(ch);\n if (p.dir == 'out' && typeof p.raw == 'string' && p.raw.includes('\"unsubscribe\"'))\n for (const l of p.raw.split('\\n'))\n try {\n cs.delete(JSON.parse(l).unsubscribe.channel);\n } catch {\n /* another command */\n }\n },\n /** the main thread's page state: hidden, or asleep (idle expiry) = nothing is judged; shown / awake again restarts the clock */\n p(off: number) {\n hid = off;\n if (!off) vs = Date.now();\n },\n /**\n * a segment cut. Adds `sig` events through `add`, returns the channels that went silent while the page was\n * visible (≤ 1 per channel per minute) for the main thread's warning.\n */\n c(gate: number, add: (x: A) => void): [string, number, number][] {\n const now = Date.now(), b = busy(now, gate);\n sk.clear();\n last = now;\n const out = stale(now, b, add);\n for (const [ch, a] of lag) {\n a.sort((x, y) => x - y);\n add({ k: 'lag', ch, n: a.length, max: a[a.length - 1], p95: a[Math.min(a.length - 1, Math.floor(a.length * 0.95))] });\n }\n lag.clear();\n if (dr) add({ k: 'lagskip', n: dr });\n dr = 0;\n return out;\n },\n };\n};\n(self as A).rpx = rpx;\nexport type Rpx = ReturnType<typeof rpx>;\n"],"mappings":"aA4GCA,KAAWC,IAhGA,CAACC,EAAYC,EAAcC,EAAcC,EAAqBC,KAExE,IAAMC,EAAK,IAAIC,IAETC,EAAK,IAAID,IAETE,EAAM,IAAIF,IAEZG,EAAK,EACHC,EAAKT,EAAOA,EAAKU,MAAM,KAAO,GAChCC,EAAK,EAAGC,EAAM,EAAGC,EAAOC,KAAKC,MAG3BC,EAAO,CAACD,EAAad,KACzB,IAAMgB,EAAI,IAAIC,IACd,QAAYC,EAAIC,KAAMd,EAAQc,IAAOL,EAAMF,GAAQ,IAAOZ,EAAO,IAAKgB,EAAEI,IA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"name": "@replayd/core",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "replayd browser SDK: errors, breadcrumbs, console, network and WebSocket capture, session replay",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -39,7 +39,7 @@
39
39
  "devDependencies": {
40
40
  "@rrweb/record": "2.2.0"
41
41
  },
42
- "gitHead": "4f56f61ca8ca290a1a6e2dc38bbef707b282d4c0",
42
+ "gitHead": "a9944f30367f1963b0791e3e011b7f55d49ead82",
43
43
  "scripts": {
44
44
  "build": "node ../../scripts/build.mjs build.json && tsc -p tsconfig.build.json"
45
45
  }