@pydantic/logfire-session-replay 0.6.0 → 0.7.1
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.
- package/README.md +23 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -348,3 +348,26 @@ When a Vite workspace example imports unpublished package output directly from
|
|
|
348
348
|
(`@rrweb/record/dist/record.js`). Resolving it to `record.cjs` can fail at runtime
|
|
349
349
|
because that build does not provide the named `record` export used by this
|
|
350
350
|
package.
|
|
351
|
+
|
|
352
|
+
### Background delivery
|
|
353
|
+
|
|
354
|
+
Hidden-tab flushes share the serial upload queue and retry budget with ordinary
|
|
355
|
+
flushes, including `Retry-After` handling for 429 and 503 responses. A hidden
|
|
356
|
+
tab can be frozen or discarded without a `pagehide`, so its buffered events are
|
|
357
|
+
split at event boundaries into chunks whose compressed envelope fits the 48 KB
|
|
358
|
+
keepalive budget. Each request uses keepalive while the aggregate budget allows.
|
|
359
|
+
A single event that does not fit uses ordinary fetch.
|
|
360
|
+
|
|
361
|
+
On `pagehide`, the SDK gives queued, unsent chunks and buffered events immediate
|
|
362
|
+
best-effort attempts. Buffered events are packed at event boundaries into the
|
|
363
|
+
remaining keepalive budget using their compressed envelope size, with a 1 MB raw
|
|
364
|
+
batching ceiling. Events left once the budget is spent go in one ordinary
|
|
365
|
+
request. Page-close attempts do not retry, and browser termination can still
|
|
366
|
+
lose data.
|
|
367
|
+
|
|
368
|
+
The browser SDK exports `ReplayUploadError` outcomes as warning records with
|
|
369
|
+
`replay.upload.reason`, `replay.upload.status_code`, `replay.recording_id`,
|
|
370
|
+
`replay.chunk.seq`, and `replay.upload.dropped_seqs`. These use the configured
|
|
371
|
+
trace exporter and its sampling policy; delivery after page termination is not
|
|
372
|
+
guaranteed. `unconfirmed` means the server might have stored the chunk. The
|
|
373
|
+
standalone recorder reports the same structured errors through `onError`.
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@rrweb/record"),t=require("fflate");const n={DomContentLoaded:0,Load:1,FullSnapshot:2,IncrementalSnapshot:3,Meta:4,Custom:5,Plugin:6},r={Mutation:0,MouseMove:1,MouseInteraction:2,Scroll:3,ViewportResize:4,Input:5,TouchMove:6,MediaInteraction:7,Drag:12,Selection:14},i={MouseUp:0,MouseDown:1,Click:2,ContextMenu:3,DblClick:4},a={Error:`logfire.error`,Console:`logfire.console`,Network:`logfire.network`,Navigation:`logfire.navigation`},o={sessionSampleRate:1,onErrorSampleRate:1,maskAllText:!0,maskAllInputs:!0,maskTextSelector:``,blockSelector:``,flushIntervalMs:5e3,maxBufferBytes:1e6,minSessionDurationMs:1e4,sessionIdleTimeoutMs:18e5,maxSessionDurationMs:72e5,distinctId:``,captureConsole:!1,captureNetwork:!0,captureNavigation:!0,captureGlobalErrors:!0,redactUrlPatterns:[/.+/u]},s=/* @__PURE__ */ new Set([r.MouseMove,r.MouseInteraction,r.Scroll,r.ViewportResize,r.Input,r.TouchMove,r.MediaInteraction,r.Drag,r.Selection]);function c(e){return e.type!==n.IncrementalSnapshot||typeof e.data!=`object`||e.data===null||!(`source`in e.data)?!1:typeof e.data.source==`number`&&s.has(e.data.source)}function l(e,t){return t<3e4?e:t<3e5?Math.max(e,6e4):Math.max(e,3e5)}function u(e,t){return t.some(t=>new RegExp(t.source,t.flags).test(e))}function d(e,t,n){if(!u(e,t))return e;try{let t=new URL(e,n);return`${t.origin}${t.pathname}`}catch{let[t=e]=e.split(`?`),[n=t]=t.split(`#`);return n}}const f=[`log`,`info`,`warn`,`error`,`debug`],p=1024,m=()=>void 0;function h(e,t={}){let n=[],r=C(t.onError);try{for(let t of f)typeof console[t]==`function`&&n.push(T(console,t,(n,i)=>function(...o){return i()&&S(e,a.Console,{level:t,args:o.slice(0,10).map(ee)},r),n.apply(this,o)}));return E(n)}catch(e){throw D(n),e}}function g(e,t){let n=b(t),r={...n,onError:C(n.onError)},i=v(e,r);try{return E([i,y(e,r)])}catch(e){throw i(),e}}function _(e,t={redactUrlPatterns:[]}){let n=C(t.onError),r=r=>{let i=d(window.location.href,t.redactUrlPatterns??[],window.location.href);S(e,a.Navigation,{url:i,kind:r},n)},i=[];try{i.push(T(history,`pushState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`push`),i})),i.push(T(history,`replaceState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`replace`),i}));let e=!0,t=()=>{e&&r(`pop`)};return window.addEventListener(`popstate`,t),i.push(()=>{e=!1,window.removeEventListener(`popstate`,t)}),E(i)}catch(e){throw D(i),e}}function v(e,t){return typeof window.fetch==`function`?T(window,`fetch`,(n,r)=>{let i=async function(i,o){let s=n;if(!r())return s.call(this,i,o);let c=t.now(),l=te(i,o),u=ne(i);if(ae(u,t.ignoreUrlPatterns))return s.call(this,i,o);let f=d(u,t.redactUrlPatterns,window.location.href),p=A(o?.body);try{let n=await s.call(this,i,o);return r()&&S(e,a.Network,k({method:l,url:f,status:n.status,durationMs:Math.max(0,t.now()-c),reqBytes:p,resBytes:re(n.headers)}),t.onError),n}catch(n){throw r()&&S(e,a.Network,k({method:l,url:f,status:0,durationMs:Math.max(0,t.now()-c),failed:!0,reqBytes:p}),t.onError),n}},o=Reflect.get(n,`__original`);return Object.defineProperty(i,"__original",{configurable:!0,value:typeof o==`function`?o:n,writable:!0}),i}):m}function y(e,t){let n=window.XMLHttpRequest.prototype,r=/* @__PURE__ */ new WeakMap,i=[];try{return i.push(T(n,`open`,(e,n)=>function(...i){let[a,o]=i;if(!n())return e.apply(this,i);let s=o.toString();return ae(s,t.ignoreUrlPatterns)?(r.delete(this),e.apply(this,i)):(r.set(this,{method:a.toUpperCase(),url:d(s,t.redactUrlPatterns,window.location.href),startedAt:0,reqBytes:0,failed:!1,emitted:!1}),e.apply(this,i))})),i.push(T(n,`send`,(n,i)=>function(...o){let[s]=o,c=i()?r.get(this):void 0;if(c===void 0)return n.apply(this,o);c.startedAt=t.now(),c.reqBytes=A(s);let l=()=>{c.failed=!0},u=()=>{c.emitted||(c.emitted=!0,this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),i()&&S(e,a.Network,k({method:c.method,url:c.url,status:this.status,durationMs:Math.max(0,t.now()-c.startedAt),failed:c.failed||this.status===0,reqBytes:c.reqBytes,resBytes:ie(this)}),t.onError))};this.addEventListener(`error`,l),this.addEventListener(`abort`,l),this.addEventListener(`timeout`,l),this.addEventListener(`loadend`,u,{once:!0});try{return n.apply(this,o)}catch(n){throw this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),this.removeEventListener(`loadend`,u),i()&&S(e,a.Network,k({method:c.method,url:c.url,status:0,durationMs:Math.max(0,t.now()-c.startedAt),failed:!0,reqBytes:c.reqBytes}),t.onError),n}})),E(i)}catch(e){throw D(i),e}}function b(e){return{...e,ignoreUrlPatterns:x(e.ignoreUrlPatterns),redactUrlPatterns:x(e.redactUrlPatterns)}}function x(e){return e.map(e=>{let t=e.flags.replace(/[gy]/gu,``);return t===e.flags?e:new RegExp(e.source,t)})}function S(e,t,n,r){try{e(t,n)}catch(e){r?.(e)}}function C(e){let t=!1;return n=>{if(!t){t=!0;try{let t=e?.(n);w(t)&&Promise.resolve(t).catch(()=>void 0)}catch{}finally{t=!1}}}}function w(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function T(e,t,n){let r=e,i=r[t];if(typeof i!=`function`)return m;let a=!0,o=n(i,()=>a);return r[t]=o,()=>{a&&(a=!1,r[t]===o&&(r[t]=i))}}function E(e){let t=!1;return()=>{t||(t=!0,D(e))}}function D(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}}function ee(e){if(e==null)return String(e);if(typeof e==`string`)return O(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(e instanceof Error)return O(e.stack??`${e.name}: ${e.message}`);try{return O(JSON.stringify(e))}catch{return Object.prototype.toString.call(e)}}function O(e){if(e.length<=p)return e;let t=e.charCodeAt(1023),n=t>=55296&&t<=56319?1023:p;return`${e.slice(0,n)}...(+${String(e.length-n)} chars)`}function te(e,t){return(t?.method??(typeof e==`object`&&`method`in e?e.method:`GET`)).toUpperCase()}function ne(e){return typeof e==`string`||e instanceof URL?e.toString():e.url}function re(e){let t=e.get(`content-length`);if(t===null)return;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}function ie(e){try{let t=e.getResponseHeader(`content-length`);if(t===null)return;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}catch{return}}function k(e){return{method:e.method,url:e.url,status:e.status,durationMs:e.durationMs,...e.failed===void 0?{}:{failed:e.failed},...e.reqBytes===void 0?{}:{reqBytes:e.reqBytes},...e.resBytes===void 0?{}:{resBytes:e.resBytes}}}function A(e){if(e==null)return 0;if(typeof e==`string`)return new TextEncoder().encode(e).byteLength;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Blob)return e.size}function ae(e,t){return u(e,t)}const oe=/* @__PURE__ */ new Set([`action`,`formaction`,`href`,`src`]);function se(t){let n=()=>{t.beforeUserActivity?.()},r={emit:e=>{t.emit(ce(e,t.redactUrlPatterns))},maskAllInputs:t.maskAllInputs,recordCanvas:!1,collectFonts:!1,inlineImages:!1,recordCrossOriginIframes:!1,slimDOMOptions:`all`,hooks:{input:n,mediaInteaction:n,mouseInteraction:n,mousemove:n,scroll:n,selection:n,viewportResize:n},sampling:{mousemove:100,mouseInteraction:!0,scroll:250,media:800,input:`last`}};t.maskAllText?r.maskTextSelector=`*`:t.maskTextSelector!==void 0&&t.maskTextSelector.length>0&&(r.maskTextSelector=t.maskTextSelector),t.blockSelector!==void 0&&t.blockSelector.length>0&&(r.blockSelector=t.blockSelector),t.checkoutEveryNms!==void 0&&t.checkoutEveryNms>0&&(r.checkoutEveryNms=t.checkoutEveryNms);let i=(0,e.record)(r);if(i===void 0)throw Error(`logfire session replay: rrweb failed to start recording`);return{stop:()=>{i()},addCustomEvent:(t,n)=>{e.record.addCustomEvent(t,n)},takeFullSnapshot:()=>{e.record.takeFullSnapshot(!0)}}}function ce(e,t){if(typeof e.data!=`object`||e.data===null)return e;let i=e.data;if(e.type===n.Meta){if(typeof i.href!=`string`)return e;let n=d(i.href,t,window.location.href);return n===i.href?e:{...e,data:{...i,href:n}}}if(e.type!==n.FullSnapshot&&(e.type!==n.IncrementalSnapshot||i.source!==r.Mutation))return e;let a=j(i,t);return a===i?e:{...e,data:a}}function j(e,t){if(Array.isArray(e)){let n=!1,r=[];for(let i of e){let e=j(i,t);e!==i&&(n=!0),r.push(e)}return n?r:e}if(typeof e!=`object`||!e)return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){let n=e===`attributes`&&!Array.isArray(a)?le(a,t):j(a,t);n!==a&&(r=!0),i[e]=n}return r?i:e}function le(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){if(!oe.has(e.toLowerCase())||typeof a!=`string`){i[e]=a;continue}let n=d(a,t,window.location.href);n!==a&&(r=!0),i[e]=n}return r?i:e}function M(e){return typeof e==`object`&&e?e:void 0}function N(e){return typeof e==`string`&&e.length>0?e:void 0}function ue(e){let t=M(e),n=N(t?.id);if(t===void 0||n===void 0)return;let r=N(t.name),i=N(t.email);return{id:n,...r===void 0?{}:{name:r},...i===void 0?{}:{email:i}}}function de(e,t,o,s={},c){let l=1/0,u=0,d=0,f=0,p=0,m=!1,h=/* @__PURE__ */ new Set;for(let e of t){e.timestamp<l&&(l=e.timestamp),e.timestamp>u&&(u=e.timestamp);let t=M(e.data);if(e.type===n.FullSnapshot)m=!0;else if(e.type===n.Meta){let e=N(t?.href);e!==void 0&&h.add(e)}else if(e.type===n.IncrementalSnapshot&&t!==void 0){let e=t.source;if(e===r.MouseInteraction){let e=t.type;(e===i.Click||e===i.DblClick)&&d++}else e===r.Input&&f++}else if(e.type===n.Custom&&t!==void 0){let e=N(t.tag),n=M(t.payload);if(e===a.Error)p++;else if(e===a.Console)n?.level===`error`&&p++;else if(e===a.Navigation){let e=N(n?.url);e!==void 0&&h.add(e)}}}return{seq:e,firstTimestamp:l===1/0?0:l,lastTimestamp:u,eventCount:t.length,clickCount:d,keypressCount:f,errorCount:p,hasFullSnapshot:m,urls:[...h],...o!==void 0&&o.length>0?{distinctId:o}:{},...c===void 0?{}:{user:{...c}},...Object.keys(s).length===0?{}:{sessionAttributes:{...s}}}}function P(e=Date.now){let t=e(),n=new Uint8Array(/* @__PURE__ */ new ArrayBuffer(16));fe(n),n[0]=Math.floor(t/2**40)&255,n[1]=Math.floor(t/2**32)&255,n[2]=Math.floor(t/2**24)&255,n[3]=Math.floor(t/2**16)&255,n[4]=Math.floor(t/256)&255,n[5]=t&255,n[6]=(n[6]??0)&15|112,n[8]=(n[8]??0)&63|128;let r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function fe(e){let t=globalThis.crypto;if(typeof t?.getRandomValues==`function`){t.getRandomValues(e);return}for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}const pe=`lf_session_replay`;var me=class{idleTimeoutMs;maxDurationMs;now;storage;memorySession;pendingSession;persistenceTimer;constructor(e){this.idleTimeoutMs=e.idleTimeoutMs,this.maxDurationMs=e.maxDurationMs,this.now=e.now??Date.now,this.storage=e.storage===void 0?F():e.storage}getSession(){let e=this.now();if(this.memorySession!==void 0&&!this.isExpired(this.memorySession,e))return this.memorySession;let t=this.read();return t!==void 0&&!this.isExpired(t,e)?t:this.createSession(e)}touch(){let e=this.now(),t={...this.getSession(),lastActivityAt:e};return this.memorySession=t,this.scheduleWrite(t),t}reset(){return this.createSession(this.now())}flushPendingStorage(){this.persistenceTimer!==void 0&&(clearTimeout(this.persistenceTimer),this.persistenceTimer=void 0);let e=this.pendingSession;this.pendingSession=void 0,e!==void 0&&this.writeNow(e)}isExpired(e,t){return t-e.lastActivityAt>this.idleTimeoutMs||t-e.startedAt>this.maxDurationMs}createSession(e){let t={id:P(this.now),startedAt:e,lastActivityAt:e};return this.flushPendingStorage(),this.writeNow(t),t}read(){if(this.storage!==null)try{let e=this.storage.getItem(pe);if(e!==null){let t=JSON.parse(e);if(he(t))return this.memorySession=t,t}}catch{return this.memorySession}return this.memorySession}write(e){if(this.memorySession=e,this.storage!==null)try{this.storage.setItem(pe,JSON.stringify(e))}catch{}}scheduleWrite(e){this.pendingSession=e,this.persistenceTimer===void 0&&(this.persistenceTimer=setTimeout(()=>{this.persistenceTimer=void 0;let e=this.pendingSession;this.pendingSession=void 0,e!==void 0&&this.writeNow(e)},1e3))}writeNow(e){this.memorySession=e,this.write(e)}};function F(){try{return globalThis.sessionStorage??null}catch{return null}}function he(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.startedAt==`number`&&Number.isFinite(t.startedAt)&&typeof t.lastActivityAt==`number`&&Number.isFinite(t.lastActivityAt)}var I=class extends Error{droppedSeqs;reason;seq;sessionId;status;constructor(e){super(ge(e),{cause:e.cause}),this.name=`ReplayUploadError`,this.droppedSeqs=Object.freeze([...e.droppedSeqs??[]]),this.reason=e.reason,this.seq=e.seq,this.sessionId=e.sessionId,this.status=e.status}};function ge(e){let t=e.seq===void 0?`replay chunk`:`replay chunk seq=${String(e.seq)}`,n=e.cause instanceof Error?`: ${e.cause.message}`:``;return`${t} ${e.reason}${n}`}const L=`lf_session_replay_seq`,R=1e4,z=3e4,_e={gzip:t.gzip,gzipSync:t.gzipSync};var ve=class{buffer=[];bufferHasFullSnapshot=!1;pendingBytes=0;seq=0;timer;nextFlushAt;lastUserActivityAt;startedAt;started=!1;held;heldBufferIncomplete=!1;minimumBufferIncomplete=!1;minimumDurationSatisfied=!1;firstObservedTimestamp;lastObservedTimestamp;refreshingMinimumSnapshot=!1;mode;queue=[];retainedBytes=0;activeUpload;drainPromise;draining=!1;lifecycleFlights=/* @__PURE__ */ new Set;closed=!1;shuttingDown=!1;retryAbort=new AbortController;deadlineAbort=new AbortController;resyncPending=!1;resyncTimer;lastResyncAt;reservedKeepaliveBytes=0;asyncCompressionAvailable=!0;config;compression;storage;sessionId;sessionAttributes;takeFullSnapshot;constructor(e,t,n,r=F(),i=_e,a={},o={}){this.config=e,this.sessionId=t,this.sessionAttributes=Object.freeze({...a}),this.mode=n,this.storage=r,this.compression=i,this.held=o.holdUntilActivity===!0&&n===`full`,this.takeFullSnapshot=o.takeFullSnapshot,this.minimumDurationSatisfied=e.minSessionDurationMs===0,this.seq=this.readPersistedSequence()??0,this.startedAt=this.config.now(),this.lastUserActivityAt=this.startedAt}start(){this.started||this.mode!==`full`||(this.started=!0,this.scheduleFlush())}add(e){this.minimumDurationSatisfied||(this.firstObservedTimestamp??=e.timestamp,this.lastObservedTimestamp=Math.max(this.lastObservedTimestamp??e.timestamp,e.timestamp)),c(e)&&(this.lastUserActivityAt=this.config.now());let t=H(e);if(this.resyncPending){this.addDuringResync(e,t);return}if(this.refreshingMinimumSnapshot){this.buffer.push(e),this.pendingBytes+=t;return}let r=!this.minimumDurationSatisfied;if(this.mode===`buffer`||this.held||r){if(e.type===n.Meta){this.buffer=[e],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=t,r&&(this.mode===`full`&&(this.firstObservedTimestamp=e.timestamp),this.finishMinimumBufferingEvent());return}if(e.type===n.FullSnapshot){let i=!this.bufferHasFullSnapshot&&this.buffer.length===1&&this.buffer[0]?.type===n.Meta?this.buffer[0]:void 0;this.buffer=i===void 0?[e]:[i,e],this.bufferHasFullSnapshot=!0,this.pendingBytes=t+(i===void 0?0:H(i)),this.heldBufferIncomplete=!1,this.minimumBufferIncomplete=!1,r&&(this.mode===`full`&&(this.firstObservedTimestamp=i?.timestamp??e.timestamp),this.finishMinimumBufferingEvent());return}if(!this.bufferHasFullSnapshot||t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held,this.minimumBufferIncomplete||=r,r&&this.finishMinimumBufferingEvent();return}if(this.pendingBytes+t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held,this.minimumBufferIncomplete||=r,r&&this.finishMinimumBufferingEvent();return}}if(e.type===n.Meta&&this.mode===`full`&&this.buffer.length>0&&this.flushAndReport(),this.buffer.push(e),this.pendingBytes+=t,r&&this.minimumDurationReached()){this.flushAndReport();return}this.mode===`full`&&this.pendingBytes>=this.config.maxBufferBytes&&e.type!==n.Meta?this.flushAndReport():this.scheduleFlush()}addDuringResync(e,t){if(e.type===n.Meta){this.buffer=[e],this.pendingBytes=t;return}if(e.type!==n.FullSnapshot)return;let r=this.buffer.length===1&&this.buffer[0]?.type===n.Meta?this.buffer[0]:void 0;this.buffer=r===void 0?[e]:[r,e],this.pendingBytes=t+(r===void 0?0:H(r)),this.resyncPending=!1,this.clearResyncTimer(),this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush()}async triggerFlush(){return this.mode===`buffer`&&(this.bufferHasFullSnapshot||(this.buffer=[],this.pendingBytes=0),this.mode=`full`,this.start()),this.flush()}async flush(e={}){return this.flushInternal(e)}async flushInternal(e={}){if(this.closed||this.mode===`buffer`||this.held||this.buffer.length===0||!this.minimumDurationReached()||(this.clearScheduledFlush(),this.minimumBufferIncomplete&&!this.refreshMinimumBuffer()))return;this.minimumDurationSatisfied=!0;let t=this.buffer,n=this.pendingBytes;this.buffer=[],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=0;let r=this.sessionId,i=this.snapshotIdentity();if(e.keepalive===!0){let e=Se(t),n=this.allocateSeq(e.length),a=this.deliverLifecycle(e,n,r,i);this.lifecycleFlights.add(a);let o=()=>{this.lifecycleFlights.delete(a)};a.then(o,o),await a;return}await this.enqueue(t,n,r,i)?.done}async shutdown(e={}){if(this.started=!1,this.clearScheduledFlush(),this.held||!this.minimumDurationReached()){this.discard(),await this.settleWithinDeadline([]);return}if(e.keepalive===!0){await this.flush(e),this.closed=!0,this.clearResyncTimer(),await this.settleWithinDeadline([]);return}let t=this.flushInternal();this.closed=!0,this.shuttingDown=!0,this.clearResyncTimer(),this.retryAbort.abort();let n=this.queue.filter(e=>e!==this.activeUpload).map(async e=>this.finalAttempt(e));await this.settleWithinDeadline([t,...n])}discard(){this.started=!1,this.closed=!0,this.clearScheduledFlush(),this.clearResyncTimer(),this.buffer=[],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=0}getMode(){return this.mode}isHeld(){return this.held}releaseHeld(e){this.held&&((this.heldBufferIncomplete||!this.bufferHasFullSnapshot)&&(this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,e()),this.held=!1,this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush())}flushAndReport(){this.flushInternal().catch(e=>{B(this.config.onError,e)})}scheduleFlush(){let e=this.config.now(),t=Math.max(0,this.config.minSessionDurationMs-(e-this.startedAt)),n=Math.max(l(this.config.flushIntervalMs,e-this.lastUserActivityAt),t);this.scheduleFlushIn(e,n)}scheduleFlushIn(e,t){if(!this.started||this.mode!==`full`||this.held||this.buffer.length===0)return;let n=e+t;this.timer!==void 0&&this.nextFlushAt!==void 0&&this.nextFlushAt<=n||(this.clearScheduledFlush(),this.nextFlushAt=n,this.timer=setTimeout(()=>{this.timer=void 0,this.nextFlushAt=void 0,this.flushAndReport()},t))}clearScheduledFlush(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0),this.nextFlushAt=void 0}minimumDurationReached(){return this.minimumDurationSatisfied||this.config.minSessionDurationMs===0?!0:this.firstObservedTimestamp===void 0||this.lastObservedTimestamp===void 0?!1:this.lastObservedTimestamp-this.firstObservedTimestamp>=this.config.minSessionDurationMs}finishMinimumBufferingEvent(){this.minimumDurationReached()?this.flushAndReport():this.scheduleFlush()}refreshMinimumBuffer(){let e=this.buffer.length,t=this.pendingBytes;if(this.takeFullSnapshot!==void 0){this.refreshingMinimumSnapshot=!0;try{this.takeFullSnapshot()}catch(e){B(this.config.onError,e)}finally{this.refreshingMinimumSnapshot=!1}}return this.buffer.slice(e).some(e=>e.type===n.FullSnapshot)?(this.minimumBufferIncomplete=!1,!0):(this.buffer.length=e,this.pendingBytes=t,!1)}snapshotIdentity(){let e=this.snapshotUser(),t=this.config.distinctId;if(this.config.getDistinctId!==void 0)try{t=this.config.getDistinctId()??this.config.distinctId}catch(e){B(this.config.onError,e)}else e!==void 0&&(t=e.id);return{distinctId:t,user:e}}createEnvelope(e,t,n){return{version:1,meta:de(t,e,n.distinctId,this.sessionAttributes,n.user),events:e}}snapshotUser(){if(this.config.getUser!==void 0)try{return ue(this.config.getUser())}catch(e){B(this.config.onError,e);return}}allocateSeq(e){let t=this.seq;return this.seq+=e,this.saveSeq(this.sessionId,this.seq),t}enqueue(e,t,r,i){let a=Math.max(2e6,2*this.config.maxBufferBytes);if(this.queue.length>0&&this.retainedBytes+t>a){B(this.config.onError,new I({cause:/* @__PURE__ */ Error(`replay upload queue is full`),reason:`not-sent`,seq:void 0,sessionId:r})),this.beginResync();return}let o=()=>void 0,s={body:void 0,done:new Promise(e=>{o=e}),events:e,hasFullSnapshot:e.some(e=>e.type===n.FullSnapshot),identity:i,reachedFetch:!1,resolve:o,retainedBytes:t,seq:this.allocateSeq(1),sessionId:r,settled:!1};return this.queue.push(s),this.retainedBytes+=t,this.draining||(this.draining=!0,this.drainPromise=this.drain()),s}async drain(){try{for(;!this.shuttingDown;){let e=this.queue[0];if(e===void 0)break;this.activeUpload=e;let t=await this.deliverQueued(e);this.activeUpload=void 0,this.settle(e,t)}}finally{this.activeUpload=void 0,this.draining=!1}}async deliverQueued(e){let t=await this.compressQueued(e);if(t!==void 0||e.settled)return t;let n=Date.now(),r;for(let t=1;;t++){let i=z-(Date.now()-n);if(t>1&&i<=0)return G(r,e.reachedFetch);let a=await this.attemptQueued(e,Math.min(R,i));if(a===void 0)return;r=a;let o=Ee(a,t,this.config.random);if(o===void 0||this.shuttingDown||Date.now()-n+o>=z)return G(a,e.reachedFetch);await this.backoff(o)}}async compressQueued(e){if(e.body!==void 0||e.events===void 0)return;let n=e.events;try{let r=(0,t.strToU8)(JSON.stringify(this.createEnvelope(n,e.seq,e.identity))),i=this.shuttingDown?this.compression.gzipSync(r):await this.compressOrdinary(r);if(e.events!==n)return await this.compressQueued(e);e.settled||(this.retainedBytes+=i.byteLength-e.retainedBytes,e.retainedBytes=i.byteLength,e.body=i,e.events=void 0);return}catch(e){return{cause:e,reason:`not-sent`}}}async attemptQueued(e,t=R){let n=e.body;if(n!==void 0)try{await this.send({body:n,requestKeepalive:!1,reservedBytes:0,seq:e.seq,sessionId:e.sessionId},()=>{e.reachedFetch=!0},t);return}catch(e){return e}}async finalAttempt(e){let t=await this.compressQueued(e);if(t!==void 0){this.settle(e,t);return}let n=await this.attemptQueued(e);this.settle(e,n===void 0?void 0:G(n,e.reachedFetch))}async settleWithinDeadline(e){let t=Promise.all([...e,this.drainPromise,...this.lifecycleFlights]).then(()=>void 0,()=>void 0),n,r=new Promise(e=>{n=setTimeout(e,R)});if(await Promise.race([t,r]),clearTimeout(n),this.shuttingDown){this.deadlineAbort.abort(/* @__PURE__ */ Error(`replay upload did not finish before shutdown`));for(let e of[...this.queue])this.settle(e,{cause:/* @__PURE__ */ Error(`replay upload did not finish before shutdown`),reason:e.reachedFetch?`unconfirmed`:`not-sent`})}}settle(e,t){if(e.settled)return;e.settled=!0,this.retainedBytes-=e.retainedBytes;let n=this.queue.indexOf(e);n>=0&&this.queue.splice(n,1),e.body=void 0,e.events=void 0,e.resolve(),t!==void 0&&this.handleSequencedLoss(e.seq,e.sessionId,t)}handleSequencedLoss(e,t,n){let r=[];if(!this.shuttingDown){let t=!1;for(let n of[...this.queue])if(!(n.seq<e)){if(n.events===void 0){if(n.hasFullSnapshot){t=!0;break}continue}if(n.hasFullSnapshot){let e=U(n.events),r=W(e);this.retainedBytes+=r-n.retainedBytes,n.retainedBytes=r,n.events=e,t=!0;break}r.push(n.seq),this.settle(n,void 0)}!t&&!this.trimBufferToAnchor()&&this.beginResync()}B(this.config.onError,new I({cause:n.cause,droppedSeqs:r,reason:n.reason,seq:e,sessionId:t,status:n.status}))}trimBufferToAnchor(){return this.buffer.some(e=>e.type===n.FullSnapshot)?(this.buffer=U(this.buffer),this.pendingBytes=W(this.buffer),!0):!1}beginResync(){this.closed||(this.resyncPending=!0,this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,this.clearScheduledFlush(),this.scheduleResyncSnapshot())}scheduleResyncSnapshot(){if(this.resyncTimer!==void 0||this.closed)return;let e=this.lastResyncAt===void 0?0:Math.max(0,this.lastResyncAt+6e4-this.config.now());this.resyncTimer=setTimeout(()=>{this.resyncTimer=void 0,this.takeResyncSnapshot()},e)}takeResyncSnapshot(){if(this.resyncPending&&!this.closed&&this.takeFullSnapshot!==void 0){this.lastResyncAt=this.config.now();try{this.takeFullSnapshot()}catch(e){B(this.config.onError,e),this.scheduleResyncSnapshot();return}this.isResyncPending()&&(B(this.config.onError,/* @__PURE__ */ Error(`replay resync snapshot produced no full snapshot`)),this.scheduleResyncSnapshot())}}isResyncPending(){return this.resyncPending}clearResyncTimer(){this.resyncTimer!==void 0&&(clearTimeout(this.resyncTimer),this.resyncTimer=void 0)}async backoff(e){let t=this.retryAbort.signal;t.aborted||await new Promise(n=>{let r=()=>{clearTimeout(i),t.removeEventListener(`abort`,r),n()},i=setTimeout(r,e);t.addEventListener(`abort`,r)})}async deliverLifecycle(e,n,r,i){let a=[];for(let o=0;o<e.length;o++){let s=e[o];if(s===void 0){a.push(void 0);continue}let c=this.createEnvelope(s,n+o,i);try{a.push({body:this.compression.gzipSync((0,t.strToU8)(JSON.stringify(c))),requestKeepalive:!1,reservedBytes:0,seq:n+o,sessionId:r})}catch(e){this.handleSequencedLoss(n+o,r,{cause:e,reason:`not-sent`}),a.push(void 0)}}let o=!0,s=Math.max(0,48e3-this.reservedKeepaliveBytes);for(let e of a){if(e===void 0){o=!1;continue}o&&e.body.byteLength<=s?(e.requestKeepalive=!0,e.reservedBytes=e.body.byteLength,this.reservedKeepaliveBytes+=e.reservedBytes,s-=e.reservedBytes):o=!1}await Promise.all(a.map(async e=>{if(e===void 0)return;let t=!1;try{await this.send(e,()=>{t=!0})}catch(n){this.handleSequencedLoss(e.seq,e.sessionId,G(n,t))}}))}async compressOrdinary(e){if(!this.asyncCompressionAvailable)return this.compression.gzipSync(e);try{return await Ce(this.compression,e)}catch{return this.asyncCompressionAvailable=!1,this.compression.gzipSync(e)}}async send(e,t,n=R){let r,i,a,o=new AbortController,s=setTimeout(()=>{o.abort(/* @__PURE__ */ Error(`replay upload timed out after ${String(n)}ms`))},n),c=this.deadlineAbort.signal,l=()=>{o.abort(c.reason)};c.addEventListener(`abort`,l);try{let n=`${this.config.replayUrl.replace(/\/+$/u,``)}/${encodeURIComponent(e.sessionId)}?seq=${String(e.seq)}`,s=await xe(this.getUploadHeaders(),o.signal);t();let c=this.config.fetchImpl(n,{method:`POST`,headers:s,body:e.body.slice(),keepalive:e.requestKeepalive,signal:o.signal});r=!0;let l=await c;if(i=!0,a=await we(l),!l.ok){let e=l.status===429||l.status===503?De(l.headers.get(`retry-after`),Date.now()):void 0;throw new V(l.status,e)}}finally{clearTimeout(s),c.removeEventListener(`abort`,l),e.reservedBytes>0&&(r!==!0||i!==!0||a===!0)&&(this.reservedKeepaliveBytes=Math.max(0,this.reservedKeepaliveBytes-e.reservedBytes))}}async getUploadHeaders(){let e=this.config.headers===void 0?{}:await this.config.headers(),t=await be(this.config.token);return{...t===void 0||t.length===0?e:{...Object.fromEntries(Object.entries(e).filter(([e])=>e.toLowerCase()!==`authorization`)),Authorization:`Bearer ${t}`},"Content-Type":`application/json`,"Content-Encoding":`gzip`}}canResumeSequence(){return this.readPersistedSequence()===this.seq}readPersistedSequence(){if(this.storage!==null)try{let e=this.storage.getItem(L);if(e===null)return;let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let n=t;return n.id===this.sessionId&&typeof n.seq==`number`&&Number.isSafeInteger(n.seq)&&n.seq>=0?n.seq:void 0}catch{return}}saveSeq(e,t){if(this.storage!==null)try{this.storage.setItem(L,JSON.stringify({id:e,seq:t}))}catch{}}};function B(e,t){try{let n=e?.(t);ye(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function ye(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}var V=class extends Error{retryAfter;status;constructor(e,t){super(`replay ingest failed: ${String(e)}`),this.status=e,this.retryAfter=t,this.name=`ReplayIngestError`}};async function be(e){return typeof e==`function`?e():e}async function xe(e,t){if(t.aborted)throw t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e instanceof Error?e:Error(String(e)))})})}function H(e){try{return(0,t.strToU8)(JSON.stringify(e)).byteLength}catch{return 0}}function U(e){let t=e.findIndex(e=>e.type===n.FullSnapshot);if(t<0)return e;let r=t>0&&e[t-1]?.type===n.Meta?t-1:t;return e.slice(r)}function W(e){return e.reduce((e,t)=>e+H(t),0)}function Se(e){let t=[],n=[],r=0;for(let i of e){let e=H(i);n.length>0&&r+e>48e3&&(t.push(n),n=[],r=0),n.push(i),r+=e}return n.length>0&&t.push(n),t}async function Ce(e,t){return new Promise((n,r)=>{let i=[];typeof window<`u`&&i.push(window),typeof document<`u`&&i.push(document);let a=()=>{for(let e of i)e.removeEventListener(`securitypolicyviolation`,s)},o=(e,t)=>{if(a(),e!==null){r(e);return}n(t)},s=e=>{let t=e;(t.effectiveDirective.includes(`worker-src`)||t.violatedDirective.includes(`worker-src`))&&o(/* @__PURE__ */ Error(`replay compression worker blocked by Content Security Policy`))};for(let e of i)e.addEventListener(`securitypolicyviolation`,s);try{e.gzip(t,{level:6},(e,t)=>{o(e,t)})}catch(e){a(),r(e instanceof Error?e:Error(String(e)))}})}async function we(e){if(e.body===null)return!0;try{return await e.body.cancel(),!0}catch{return!1}}function Te(e){return e===408||e===425||e===429||e>=500}function Ee(e,t,n){if(e instanceof V&&!Te(e.status))return;let r=Math.min(8e3,500*2**(t-1)),i=Math.round(r*(1-.5*n())),a=e instanceof V?e.retryAfter:void 0;return a===void 0?i:Math.max(a,i)}function G(e,t){let n=e instanceof V?e.status:void 0;return n!==void 0&&!Te(n)?{cause:e,reason:`rejected`,status:n}:{cause:e,reason:t?`unconfirmed`:`not-sent`,status:n}}function De(e,t){if(e===null)return;let n=e.trim();if(/^\d+$/u.test(n)){let e=Number(n);return Number.isSafeInteger(e)?e*1e3:void 0}let r=je(n,t);return r===void 0?void 0:Math.max(0,r-t)}const Oe=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],ke=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],Ae=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function je(e,t){let n=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(n!==null)return K(n[1],n[2],n[3],n[4],n[5],n[6],n[7]);let r=/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(r!==null){let e=new Date(t).getUTCFullYear(),n=Number(r[4]),i=Math.floor(e/100)*100+n;return i>e+50&&(i-=100),K(r[1],r[2],r[3],String(i),r[5],r[6],r[7])}let i=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{2}| \d) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/u.exec(e);if(i!==null)return K(i[1],i[3]?.trim(),i[2],i[7],i[4],i[5],i[6])}function K(e,t,n,r,i,a,o){let s=Number(t),c=Oe.indexOf(n),l=Number(r),u=Number(i),d=Number(a),f=Number(o);if(c<0||s<1||s>31||u>23||d>59||f>59)return;let p=/* @__PURE__ */ new Date(0);if(p.setUTCFullYear(l,c,s),p.setUTCHours(u,d,f,0),p.getUTCFullYear()!==l||p.getUTCMonth()!==c||p.getUTCDate()!==s||p.getUTCHours()!==u||p.getUTCMinutes()!==d||p.getUTCSeconds()!==f)return;let m=ke.indexOf(e),h=Ae.indexOf(e);return(m>=0?m:h)===p.getUTCDay()?p.getTime():void 0}const Me=`lf_session_replay_recording`,q=`lf_session_replay_recording_owner`;var Ne=class{state;storage;owner;now;maxDurationMs;readOpenerState;constructor(e,t,n,r=()=>null){this.storage=e,this.now=t,this.owner=P(t),this.maxDurationMs=Math.min(n,72e5),this.readOpenerState=r;try{e?.getItem(`lf_session_replay_recording_owner`)===null&&(this.state=this.readResumableState()),e?.setItem(q,this.owner),e?.getItem(`lf_session_replay_recording_owner`)!==this.owner&&(this.storage=null,this.state=void 0)}catch{this.storage=null,this.state=void 0}}get(e){if(this.state!==void 0&&this.isCurrent(this.state.id,e))return this.state.id;this.state={id:P(this.now),rumSessionId:e,startedAt:this.now()};try{this.storage?.setItem(Me,JSON.stringify(this.state))}catch{}return this.state.id}isCurrent(e,t){let n=this.state;if(n===void 0)return!1;let r=this.now();return n.id===e&&n.rumSessionId===t&&r>=n.startedAt&&r-n.startedAt<this.maxDurationMs}release(){try{this.storage?.getItem(`lf_session_replay_recording_owner`)===this.owner&&this.storage.removeItem(q)}catch{}}resume(){try{this.state=this.storage?.getItem(`lf_session_replay_recording_owner`)===null?this.readResumableState():void 0,this.storage?.setItem(q,this.owner),this.storage?.getItem(`lf_session_replay_recording_owner`)!==this.owner&&(this.state=void 0,this.storage=null)}catch{this.state=void 0,this.storage=null}}readResumableState(){let e=this.storage?.getItem(Me),t=this.storage?.getItem(L);if(e==null||t==null)return;let n=null;try{n=this.readOpenerState()}catch{}if(n!==e)return Pe(e,t)}};function Pe(e,t){let n=JSON.parse(e),r=JSON.parse(t);if(typeof n!=`object`||!n||typeof r!=`object`||!r)return;let i=n,a=r;if(!(typeof i.id!=`string`||i.id.length===0||typeof i.rumSessionId!=`string`||typeof i.startedAt!=`number`||!Number.isFinite(i.startedAt)||a.id!==i.id||typeof a.seq!=`number`||!Number.isSafeInteger(a.seq)||a.seq<0))return{id:i.id,rumSessionId:i.rumSessionId,startedAt:i.startedAt}}function Fe(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Ie(e){let t=e.random??Math.random;return t()<Fe(e.sessionSampleRate)?`full`:t()<Fe(e.onErrorSampleRate)?`buffer`:`off`}const Le=/^[a-z][a-z0-9_]{0,63}$/u;function Re(e,t){let n=0;for(let r of e)if(n+=+(r.length>0),n>t)return!1;return!0}function ze(e,t){if(e===void 0)return Object.freeze({});let n;try{n=e()}catch(e){return t(e),Object.freeze({})}if(typeof n!=`object`||!n||Array.isArray(n))return Object.freeze({});let r;try{r=Object.getPrototypeOf(n)}catch(e){return t(e),Object.freeze({})}if(r!==Object.prototype&&r!==null)return Object.freeze({});let i;try{i=Object.keys(n)}catch(e){return t(e),Object.freeze({})}let a={},o=0;for(let e of i){if(!Le.test(e))continue;let r;try{r=Reflect.get(n,e)}catch(e){t(e);continue}if((typeof r==`boolean`||typeof r==`number`&&Number.isFinite(r)||typeof r==`string`&&Re(r,200))&&(Object.defineProperty(a,e,{configurable:!0,enumerable:!0,value:r,writable:!0}),o+=1,o===20))break}return Object.freeze(a)}const Be={mode:`off`,recording:!1,getSessionId:()=>``,captureError:()=>void 0,getRecordingId:()=>``,flush:async()=>Promise.resolve(),stop:async()=>Promise.resolve()},Ve=`lf_session_replay_mode`,J=Symbol.for(`@pydantic/logfire-session-replay/controller`);function He(e){if(typeof window>`u`||typeof document>`u`)return Be;let t=$e();try{let n=We(e),r=new me({idleTimeoutMs:n.sessionIdleTimeoutMs,maxDurationMs:n.maxSessionDurationMs,now:n.now}),i=r.getSession().id,a=e=>{let t;try{t=n.getSessionId?.()}catch(e){return Z(n.onError,e),i}if(t!==void 0&&t.length>0)return i=t,t;let a=e?r.touch().id:r.getSession().id;return i=a,a},o=F(),s=new Ne(o,n.now,n.maxSessionDurationMs,()=>window.opener?.sessionStorage.getItem(`lf_session_replay_recording`)??null),c=a(!1),l=s.get(c),u,d=!1,f=!1,p=0,m=!0,h=Promise.resolve(),g=Promise.resolve(),_,v=(e,t,r=!t)=>{let i=Ge(n,e,o);if(!(i===`off`||d||f||u!==void 0||e!==c))try{let t=l;u=Ue({config:n,getSessionId:a,mode:i,onSessionChanged:y,samplingModeStorage:o,sessionId:e,recordingId:t,isCurrentRecording:()=>s.isCurrent(t,a(!1)),holdUntilActivity:r})}catch(e){if(u=void 0,t)throw e;Z(n.onError,e)}},y=(e,t=!0)=>{if(d||f)return;let r=s.get(e);if(e===c&&r===l)return;c=e,l=r;let i=u;u=void 0;let a=i?.deactivate()??Promise.resolve(),o=p;h=h.then(async()=>{await X(a,n.onError),!d&&p===o&&c===e&&l===r&&v(e,!1,t)})},b;try{v(c,!0),b=setInterval(()=>{y(a(!1))},1e3)}catch(e){throw u?.discard(),u=void 0,s.release(),e}let x=()=>{f=!0,p+=1;let e=u;u=void 0;let t=e?.deactivate(!0)??Promise.resolve();g=Promise.all([g,h,X(t,n.onError)]).then(()=>void 0),h=Promise.resolve(),m=e?.transport.canResumeSequence()??m,m&&s.release()},S=e=>{if(!e.persisted||d)return;u?.discard(),u=void 0;let t=p;h=h.then(async()=>{await new Promise(e=>{setTimeout(e,0)}),!(d||p!==t)&&(f=!1,s.resume(),c=a(!1),l=s.get(c),m=!0,v(c,!1,!1))})};return window.addEventListener(`pagehide`,x),window.addEventListener(`pageshow`,S),{get mode(){try{return u?.transport.getMode()??`off`}catch(e){return Z(n.onError,e),`off`}},get recording(){try{return u!==void 0}catch(e){return Z(n.onError,e),!1}},getSessionId:()=>a(!1),captureError:(e,t)=>{try{u?.captureError(e,t)}catch(e){Z(n.onError,e)}},getRecordingId:()=>u!==void 0&&s.isCurrent(u.recordingId,a(!1))?u.recordingId:``,flush:async()=>{try{await h,await u?.transport.flush()}catch(e){Z(n.onError,e)}},stop:async()=>(_??=(async()=>{d=!0,p+=1,clearInterval(b),window.removeEventListener(`pagehide`,x),window.removeEventListener(`pageshow`,S);let e=u;u=void 0,await X(e?.deactivate()??Promise.resolve(),n.onError),await h,await g,r.flushPendingStorage(),m=e?.transport.canResumeSequence()??m,m&&s.release(),t()})(),_)}}catch(e){throw t(),e}}function Ue(e){let{config:t,getSessionId:n,holdUntilActivity:r,mode:i,onSessionChanged:o,samplingModeStorage:s,sessionId:l,recordingId:u,isCurrentRecording:d}=e,f=ze(t.getSessionAttributes,e=>{Z(t.onError,e)}),p,m=new ve(t,u,i,void 0,void 0,f,{holdUntilActivity:r,takeFullSnapshot:()=>{p.takeFullSnapshot()}}),v=[],y=!0,b=()=>y,x;try{p=se({beforeUserActivity:()=>{if(y&&m.isHeld())try{let e=n(!0);if(e!==l||!d()){o(e,!1);return}m.releaseHeld(()=>{p.takeFullSnapshot()})}catch(e){Z(t.onError,e)}},emit:e=>{if(y)try{let t=n(c(e));if(t!==l||!d()){o(t,!1);return}m.add(e)}catch(e){Z(t.onError,e)}},maskAllText:t.maskAllText,maskAllInputs:t.maskAllInputs,maskTextSelector:t.maskTextSelector,blockSelector:t.blockSelector,checkoutEveryNms:i===`buffer`?12e4:Math.max(3e5,t.minSessionDurationMs),redactUrlPatterns:t.redactUrlPatterns}),v.push(()=>{p.stop()});let e=(e,n)=>{if(y)try{p.addCustomEvent(e,n)}catch(e){Z(t.onError,e)}},r=n=>{b()&&(m.releaseHeld(()=>{p.takeFullSnapshot()}),e(a.Error,n),b()&&m.getMode()===`buffer`&&(qe(s,l,`full`),Y(m.triggerFlush(),t.onError)))},f=/* @__PURE__ */ new WeakSet,S=e=>typeof e!=`object`||!e||!f.has(e)&&(f.add(e),!0),C=(e,t)=>{if(S(e)){let n=$(Ye(e),void 0,Xe(e));r(typeof t?.timestamp==`number`?{...n,timestamp:t.timestamp}:n)}},w=e=>{e instanceof ErrorEvent&&S(e.error)&&r($(e.message,e.filename,Xe(e.error)))},T=e=>{C(e.reason)},E=()=>{document.visibilityState===`hidden`&&Y(m.flush({keepalive:!0}),t.onError)},D=()=>{Y(m.flush({keepalive:!0}),t.onError)};return t.captureGlobalErrors&&(window.addEventListener(`error`,w,!0),v.push(()=>{window.removeEventListener(`error`,w,!0)}),window.addEventListener(`unhandledrejection`,T,!0),v.push(()=>{window.removeEventListener(`unhandledrejection`,T,!0)})),document.addEventListener(`visibilitychange`,E),v.push(()=>{document.removeEventListener(`visibilitychange`,E)}),window.addEventListener(`pagehide`,D),v.push(()=>{window.removeEventListener(`pagehide`,D)}),t.captureConsole&&v.push(h(e,{onError:t.onError})),t.captureNetwork&&v.push(g(e,{ignoreUrlPatterns:t.ignoreUrlPatterns,now:t.now,onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),t.captureNavigation&&v.push(_(e,{onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),m.start(),{sessionId:l,recordingId:u,transport:m,captureError:C,deactivate:async(e=!1)=>(x??=(async()=>{let t=m.shutdown({keepalive:e});y=!1,Q(v),await t})(),x),discard:()=>{y=!1,Q(v),m.discard()}}}catch(e){throw y=!1,Q(v),m.discard(),e}}function We(e){if(e.replayUrl.length===0)throw Error("logfire session replay: `replayUrl` is required");let t=new URL(e.replayUrl,`https://logfire.invalid/`);if(t.search!==``||t.hash!==``)throw Error("logfire session replay: `replayUrl` must not contain a query or fragment");let n=e.fetchImpl??(typeof fetch==`function`?fetch.bind(globalThis):void 0);if(n===void 0)throw Error("logfire session replay: no `fetch` available; pass `fetchImpl`");return{replayUrl:e.replayUrl,headers:e.headers,token:e.token,getSessionId:e.getSessionId,getSessionAttributes:e.getSessionAttributes,sessionSampleRate:e.sessionSampleRate??o.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate??o.onErrorSampleRate,maskAllText:e.maskAllText??o.maskAllText,maskAllInputs:e.maskAllInputs??o.maskAllInputs,maskTextSelector:e.maskTextSelector??o.maskTextSelector,blockSelector:e.blockSelector??o.blockSelector,flushIntervalMs:e.flushIntervalMs??o.flushIntervalMs,maxBufferBytes:e.maxBufferBytes??o.maxBufferBytes,minSessionDurationMs:e.minSessionDurationMs??o.minSessionDurationMs,sessionIdleTimeoutMs:e.sessionIdleTimeoutMs??o.sessionIdleTimeoutMs,maxSessionDurationMs:e.maxSessionDurationMs??o.maxSessionDurationMs,distinctId:e.distinctId??o.distinctId,getDistinctId:e.getDistinctId,getUser:e.getUser,captureConsole:e.captureConsole??o.captureConsole,captureNetwork:e.captureNetwork??o.captureNetwork,captureNavigation:e.captureNavigation??o.captureNavigation,captureGlobalErrors:e.captureGlobalErrors??o.captureGlobalErrors,ignoreUrlPatterns:e.ignoreUrlPatterns??[],redactUrlPatterns:e.redactUrlPatterns??[...o.redactUrlPatterns],onError:e.onError,fetchImpl:n,now:e.now??Date.now,random:e.random??Math.random}}function Ge(e,t,n){let r=Ke(n,t);if(r!==void 0)return r;let i=Ie({sessionSampleRate:e.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate,random:e.random});return qe(n,t,i),i}function Ke(e,t){if(e!==null)try{let n=e.getItem(Ve);if(n===null)return;let r=JSON.parse(n);if(typeof r!=`object`||!r)return;let i=r;return i.id!==t||!Je(i.mode)?void 0:i.mode}catch{return}}function qe(e,t,n){if(e!==null)try{e.setItem(Ve,JSON.stringify({id:t,mode:n}))}catch{}}function Je(e){return e===`full`||e===`buffer`||e===`off`}function Ye(e){return et(Ze(e,`message`)??e)}function Xe(e){let t=Ze(e,`stack`);return typeof t==`string`?t:void 0}function Ze(e,t){try{return typeof e==`object`&&e&&t in e?e[t]:void 0}catch{return}}function Y(e,t){e.catch(e=>{Z(t,e)})}async function X(e,t){try{await e}catch(e){Z(t,e)}}function Z(e,t){try{let n=e?.(t);Qe(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function Qe(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function $e(){let e=globalThis;if(e[J]!==void 0)throw Error(`logfire session replay: a replay controller is already active in this page`);let t={};Object.defineProperty(e,J,{configurable:!0,enumerable:!1,value:t,writable:!0});let n=!1;return()=>{n||(n=!0,e[J]===t&&Reflect.deleteProperty(e,J))}}function Q(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}e.length=0}function $(e,t,n){return{message:e,...t===void 0||t.length===0?{}:{source:t},...n===void 0?{}:{stack:n}}}function et(e){if(e==null)return`unhandledrejection`;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return String(e);try{return Object.prototype.toString.call(e)}catch{return`[object Object]`}}exports.CHUNK_ENVELOPE_VERSION=1,exports.CustomTag=a,exports.EventType=n,exports.IncrementalSource=r,exports.MouseInteractions=i,exports.ReplayUploadError=I,exports.startSessionReplay=He;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@rrweb/record"),t=require("fflate");const n={DomContentLoaded:0,Load:1,FullSnapshot:2,IncrementalSnapshot:3,Meta:4,Custom:5,Plugin:6},r={Mutation:0,MouseMove:1,MouseInteraction:2,Scroll:3,ViewportResize:4,Input:5,TouchMove:6,MediaInteraction:7,Drag:12,Selection:14},i={MouseUp:0,MouseDown:1,Click:2,ContextMenu:3,DblClick:4},a={Error:`logfire.error`,Console:`logfire.console`,Network:`logfire.network`,Navigation:`logfire.navigation`},o={sessionSampleRate:1,onErrorSampleRate:1,maskAllText:!0,maskAllInputs:!0,maskTextSelector:``,blockSelector:``,flushIntervalMs:5e3,maxBufferBytes:1e6,minSessionDurationMs:1e4,sessionIdleTimeoutMs:18e5,maxSessionDurationMs:72e5,distinctId:``,captureConsole:!1,captureNetwork:!0,captureNavigation:!0,captureGlobalErrors:!0,redactUrlPatterns:[/.+/u]},s=/* @__PURE__ */ new Set([r.MouseMove,r.MouseInteraction,r.Scroll,r.ViewportResize,r.Input,r.TouchMove,r.MediaInteraction,r.Drag,r.Selection]);function c(e){return e.type!==n.IncrementalSnapshot||typeof e.data!=`object`||e.data===null||!(`source`in e.data)?!1:typeof e.data.source==`number`&&s.has(e.data.source)}function l(e,t){return t<3e4?e:t<3e5?Math.max(e,6e4):Math.max(e,3e5)}function u(e,t){return t.some(t=>new RegExp(t.source,t.flags).test(e))}function d(e,t,n){if(!u(e,t))return e;try{let t=new URL(e,n);return`${t.origin}${t.pathname}`}catch{let[t=e]=e.split(`?`),[n=t]=t.split(`#`);return n}}const f=[`log`,`info`,`warn`,`error`,`debug`],p=1024,m=()=>void 0;function h(e,t={}){let n=[],r=C(t.onError);try{for(let t of f)typeof console[t]==`function`&&n.push(T(console,t,(n,i)=>function(...o){return i()&&S(e,a.Console,{level:t,args:o.slice(0,10).map(O)},r),n.apply(this,o)}));return E(n)}catch(e){throw D(n),e}}function g(e,t){let n=b(t),r={...n,onError:C(n.onError)},i=v(e,r);try{return E([i,y(e,r)])}catch(e){throw i(),e}}function _(e,t={redactUrlPatterns:[]}){let n=C(t.onError),r=r=>{let i=d(window.location.href,t.redactUrlPatterns??[],window.location.href);S(e,a.Navigation,{url:i,kind:r},n)},i=[];try{i.push(T(history,`pushState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`push`),i})),i.push(T(history,`replaceState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`replace`),i}));let e=!0,t=()=>{e&&r(`pop`)};return window.addEventListener(`popstate`,t),i.push(()=>{e=!1,window.removeEventListener(`popstate`,t)}),E(i)}catch(e){throw D(i),e}}function v(e,t){return typeof window.fetch==`function`?T(window,`fetch`,(n,r)=>{let i=async function(i,o){let s=n;if(!r())return s.call(this,i,o);let c=t.now(),l=A(i,o),u=ee(i);if(ie(u,t.ignoreUrlPatterns))return s.call(this,i,o);let f=d(u,t.redactUrlPatterns,window.location.href),p=re(o?.body);try{let n=await s.call(this,i,o);return r()&&S(e,a.Network,j({method:l,url:f,status:n.status,durationMs:Math.max(0,t.now()-c),reqBytes:p,resBytes:te(n.headers)}),t.onError),n}catch(n){throw r()&&S(e,a.Network,j({method:l,url:f,status:0,durationMs:Math.max(0,t.now()-c),failed:!0,reqBytes:p}),t.onError),n}},o=Reflect.get(n,`__original`);return Object.defineProperty(i,"__original",{configurable:!0,value:typeof o==`function`?o:n,writable:!0}),i}):m}function y(e,t){let n=window.XMLHttpRequest.prototype,r=/* @__PURE__ */ new WeakMap,i=[];try{return i.push(T(n,`open`,(e,n)=>function(...i){let[a,o]=i;if(!n())return e.apply(this,i);let s=o.toString();return ie(s,t.ignoreUrlPatterns)?(r.delete(this),e.apply(this,i)):(r.set(this,{method:a.toUpperCase(),url:d(s,t.redactUrlPatterns,window.location.href),startedAt:0,reqBytes:0,failed:!1,emitted:!1}),e.apply(this,i))})),i.push(T(n,`send`,(n,i)=>function(...o){let[s]=o,c=i()?r.get(this):void 0;if(c===void 0)return n.apply(this,o);c.startedAt=t.now(),c.reqBytes=re(s);let l=()=>{c.failed=!0},u=()=>{c.emitted||(c.emitted=!0,this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),i()&&S(e,a.Network,j({method:c.method,url:c.url,status:this.status,durationMs:Math.max(0,t.now()-c.startedAt),failed:c.failed||this.status===0,reqBytes:c.reqBytes,resBytes:ne(this)}),t.onError))};this.addEventListener(`error`,l),this.addEventListener(`abort`,l),this.addEventListener(`timeout`,l),this.addEventListener(`loadend`,u,{once:!0});try{return n.apply(this,o)}catch(n){throw this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),this.removeEventListener(`loadend`,u),i()&&S(e,a.Network,j({method:c.method,url:c.url,status:0,durationMs:Math.max(0,t.now()-c.startedAt),failed:!0,reqBytes:c.reqBytes}),t.onError),n}})),E(i)}catch(e){throw D(i),e}}function b(e){return{...e,ignoreUrlPatterns:x(e.ignoreUrlPatterns),redactUrlPatterns:x(e.redactUrlPatterns)}}function x(e){return e.map(e=>{let t=e.flags.replace(/[gy]/gu,``);return t===e.flags?e:new RegExp(e.source,t)})}function S(e,t,n,r){try{e(t,n)}catch(e){r?.(e)}}function C(e){let t=!1;return n=>{if(!t){t=!0;try{let t=e?.(n);w(t)&&Promise.resolve(t).catch(()=>void 0)}catch{}finally{t=!1}}}}function w(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function T(e,t,n){let r=e,i=r[t];if(typeof i!=`function`)return m;let a=!0,o=n(i,()=>a);return r[t]=o,()=>{a&&(a=!1,r[t]===o&&(r[t]=i))}}function E(e){let t=!1;return()=>{t||(t=!0,D(e))}}function D(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}}function O(e){if(e==null)return String(e);if(typeof e==`string`)return k(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(e instanceof Error)return k(e.stack??`${e.name}: ${e.message}`);try{return k(JSON.stringify(e))}catch{return Object.prototype.toString.call(e)}}function k(e){if(e.length<=p)return e;let t=e.charCodeAt(1023),n=t>=55296&&t<=56319?1023:p;return`${e.slice(0,n)}...(+${String(e.length-n)} chars)`}function A(e,t){return(t?.method??(typeof e==`object`&&`method`in e?e.method:`GET`)).toUpperCase()}function ee(e){return typeof e==`string`||e instanceof URL?e.toString():e.url}function te(e){let t=e.get(`content-length`);if(t===null)return;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}function ne(e){try{let t=e.getResponseHeader(`content-length`);if(t===null)return;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}catch{return}}function j(e){return{method:e.method,url:e.url,status:e.status,durationMs:e.durationMs,...e.failed===void 0?{}:{failed:e.failed},...e.reqBytes===void 0?{}:{reqBytes:e.reqBytes},...e.resBytes===void 0?{}:{resBytes:e.resBytes}}}function re(e){if(e==null)return 0;if(typeof e==`string`)return new TextEncoder().encode(e).byteLength;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Blob)return e.size}function ie(e,t){return u(e,t)}const ae=/* @__PURE__ */ new Set([`action`,`formaction`,`href`,`src`]);function oe(t){let n=()=>{t.beforeUserActivity?.()},r={emit:e=>{t.emit(se(e,t.redactUrlPatterns))},maskAllInputs:t.maskAllInputs,recordCanvas:!1,collectFonts:!1,inlineImages:!1,recordCrossOriginIframes:!1,slimDOMOptions:`all`,hooks:{input:n,mediaInteaction:n,mouseInteraction:n,mousemove:n,scroll:n,selection:n,viewportResize:n},sampling:{mousemove:100,mouseInteraction:!0,scroll:250,media:800,input:`last`}};t.maskAllText?r.maskTextSelector=`*`:t.maskTextSelector!==void 0&&t.maskTextSelector.length>0&&(r.maskTextSelector=t.maskTextSelector),t.blockSelector!==void 0&&t.blockSelector.length>0&&(r.blockSelector=t.blockSelector),t.checkoutEveryNms!==void 0&&t.checkoutEveryNms>0&&(r.checkoutEveryNms=t.checkoutEveryNms);let i=(0,e.record)(r);if(i===void 0)throw Error(`logfire session replay: rrweb failed to start recording`);return{stop:()=>{i()},addCustomEvent:(t,n)=>{e.record.addCustomEvent(t,n)},takeFullSnapshot:()=>{e.record.takeFullSnapshot(!0)}}}function se(e,t){if(typeof e.data!=`object`||e.data===null)return e;let i=e.data;if(e.type===n.Meta){if(typeof i.href!=`string`)return e;let n=d(i.href,t,window.location.href);return n===i.href?e:{...e,data:{...i,href:n}}}if(e.type!==n.FullSnapshot&&(e.type!==n.IncrementalSnapshot||i.source!==r.Mutation))return e;let a=M(i,t);return a===i?e:{...e,data:a}}function M(e,t){if(Array.isArray(e)){let n=!1,r=[];for(let i of e){let e=M(i,t);e!==i&&(n=!0),r.push(e)}return n?r:e}if(typeof e!=`object`||!e)return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){let n=e===`attributes`&&!Array.isArray(a)?ce(a,t):M(a,t);n!==a&&(r=!0),i[e]=n}return r?i:e}function ce(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){if(!ae.has(e.toLowerCase())||typeof a!=`string`){i[e]=a;continue}let n=d(a,t,window.location.href);n!==a&&(r=!0),i[e]=n}return r?i:e}function N(e){return typeof e==`object`&&e?e:void 0}function P(e){return typeof e==`string`&&e.length>0?e:void 0}function le(e){let t=N(e),n=P(t?.id);if(t===void 0||n===void 0)return;let r=P(t.name),i=P(t.email);return{id:n,...r===void 0?{}:{name:r},...i===void 0?{}:{email:i}}}function ue(e,t,o,s={},c){let l=1/0,u=0,d=0,f=0,p=0,m=!1,h=/* @__PURE__ */ new Set;for(let e of t){e.timestamp<l&&(l=e.timestamp),e.timestamp>u&&(u=e.timestamp);let t=N(e.data);if(e.type===n.FullSnapshot)m=!0;else if(e.type===n.Meta){let e=P(t?.href);e!==void 0&&h.add(e)}else if(e.type===n.IncrementalSnapshot&&t!==void 0){let e=t.source;if(e===r.MouseInteraction){let e=t.type;(e===i.Click||e===i.DblClick)&&d++}else e===r.Input&&f++}else if(e.type===n.Custom&&t!==void 0){let e=P(t.tag),n=N(t.payload);if(e===a.Error)p++;else if(e===a.Console)n?.level===`error`&&p++;else if(e===a.Navigation){let e=P(n?.url);e!==void 0&&h.add(e)}}}return{seq:e,firstTimestamp:l===1/0?0:l,lastTimestamp:u,eventCount:t.length,clickCount:d,keypressCount:f,errorCount:p,hasFullSnapshot:m,urls:[...h],...o!==void 0&&o.length>0?{distinctId:o}:{},...c===void 0?{}:{user:{...c}},...Object.keys(s).length===0?{}:{sessionAttributes:{...s}}}}function F(e=Date.now){let t=e(),n=new Uint8Array(/* @__PURE__ */ new ArrayBuffer(16));de(n),n[0]=Math.floor(t/2**40)&255,n[1]=Math.floor(t/2**32)&255,n[2]=Math.floor(t/2**24)&255,n[3]=Math.floor(t/2**16)&255,n[4]=Math.floor(t/256)&255,n[5]=t&255,n[6]=(n[6]??0)&15|112,n[8]=(n[8]??0)&63|128;let r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function de(e){let t=globalThis.crypto;if(typeof t?.getRandomValues==`function`){t.getRandomValues(e);return}for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}const fe=`lf_session_replay`;var pe=class{idleTimeoutMs;maxDurationMs;now;storage;memorySession;pendingSession;persistenceTimer;constructor(e){this.idleTimeoutMs=e.idleTimeoutMs,this.maxDurationMs=e.maxDurationMs,this.now=e.now??Date.now,this.storage=e.storage===void 0?I():e.storage}getSession(){let e=this.now();if(this.memorySession!==void 0&&!this.isExpired(this.memorySession,e))return this.memorySession;let t=this.read();return t!==void 0&&!this.isExpired(t,e)?t:this.createSession(e)}touch(){let e=this.now(),t={...this.getSession(),lastActivityAt:e};return this.memorySession=t,this.scheduleWrite(t),t}reset(){return this.createSession(this.now())}flushPendingStorage(){this.persistenceTimer!==void 0&&(clearTimeout(this.persistenceTimer),this.persistenceTimer=void 0);let e=this.pendingSession;this.pendingSession=void 0,e!==void 0&&this.writeNow(e)}isExpired(e,t){return t-e.lastActivityAt>this.idleTimeoutMs||t-e.startedAt>this.maxDurationMs}createSession(e){let t={id:F(this.now),startedAt:e,lastActivityAt:e};return this.flushPendingStorage(),this.writeNow(t),t}read(){if(this.storage!==null)try{let e=this.storage.getItem(fe);if(e!==null){let t=JSON.parse(e);if(me(t))return this.memorySession=t,t}}catch{return this.memorySession}return this.memorySession}write(e){if(this.memorySession=e,this.storage!==null)try{this.storage.setItem(fe,JSON.stringify(e))}catch{}}scheduleWrite(e){this.pendingSession=e,this.persistenceTimer===void 0&&(this.persistenceTimer=setTimeout(()=>{this.persistenceTimer=void 0;let e=this.pendingSession;this.pendingSession=void 0,e!==void 0&&this.writeNow(e)},1e3))}writeNow(e){this.memorySession=e,this.write(e)}};function I(){try{return globalThis.sessionStorage??null}catch{return null}}function me(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.startedAt==`number`&&Number.isFinite(t.startedAt)&&typeof t.lastActivityAt==`number`&&Number.isFinite(t.lastActivityAt)}var L=class extends Error{droppedSeqs;reason;seq;sessionId;status;constructor(e){super(he(e),{cause:e.cause}),this.name=`ReplayUploadError`,this.droppedSeqs=Object.freeze([...e.droppedSeqs??[]]),this.reason=e.reason,this.seq=e.seq,this.sessionId=e.sessionId,this.status=e.status}};function he(e){let t=e.seq===void 0?`replay chunk`:`replay chunk seq=${String(e.seq)}`,n=e.cause instanceof Error?`: ${e.cause.message}`:``;return`${t} ${e.reason}${n}`}const R=`lf_session_replay_seq`,z=1e4,ge=3e4,B=48e3,_e=1e6,ve=.9,ye={gzip:t.gzip,gzipSync:t.gzipSync};var be=class{buffer=[];bufferHasFullSnapshot=!1;pendingBytes=0;seq=0;timer;nextFlushAt;lastUserActivityAt;startedAt;started=!1;held;heldBufferIncomplete=!1;minimumBufferIncomplete=!1;minimumDurationSatisfied=!1;firstObservedTimestamp;lastObservedTimestamp;refreshingMinimumSnapshot=!1;mode;queue=[];retainedBytes=0;activeUpload;drainPromise;draining=!1;pagehideUploads=/* @__PURE__ */ new Set;lifecycleFlights=/* @__PURE__ */ new Set;closed=!1;shuttingDown=!1;wakeRetry;retryAbort=new AbortController;deadlineAbort=new AbortController;resyncPending=!1;resyncTimer;lastResyncAt;reservedKeepaliveBytes=0;asyncCompressionAvailable=!0;config;compression;storage;sessionId;sessionAttributes;takeFullSnapshot;sequenceRecord;sequenceRecordFailed=!1;awaitingBinding;bindingBufferIncomplete=!1;constructor(e,t,n,r=I(),i=ye,a={},o={}){this.config=e,this.sessionId=t,this.sessionAttributes=Object.freeze({...a}),this.mode=n,this.storage=r,this.compression=i,this.held=o.holdUntilActivity===!0&&n===`full`,this.takeFullSnapshot=o.takeFullSnapshot,this.sequenceRecord=o.sequenceRecord,this.awaitingBinding=o.awaitBinding===!0,this.minimumDurationSatisfied=e.minSessionDurationMs===0,this.seq=o.sequenceRecord?.initialSeq??this.readPersistedSequence()??0,this.startedAt=this.config.now(),this.lastUserActivityAt=this.startedAt}start(){this.started||this.mode!==`full`||(this.started=!0,this.scheduleFlush())}add(e){this.minimumDurationSatisfied||(this.firstObservedTimestamp??=e.timestamp,this.lastObservedTimestamp=Math.max(this.lastObservedTimestamp??e.timestamp,e.timestamp)),c(e)&&(this.lastUserActivityAt=this.config.now());let t=U(e);if(this.resyncPending){this.addDuringResync(e,t);return}if(this.refreshingMinimumSnapshot){this.buffer.push(e),this.pendingBytes+=t;return}let r=!this.minimumDurationSatisfied;if(this.mode===`buffer`||this.held||r||this.awaitingBinding){if(e.type===n.Meta){this.buffer=[e],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=t,r&&(this.mode===`full`&&(this.firstObservedTimestamp=e.timestamp),this.finishMinimumBufferingEvent());return}if(e.type===n.FullSnapshot){let i=!this.bufferHasFullSnapshot&&this.buffer.length===1&&this.buffer[0]?.type===n.Meta?this.buffer[0]:void 0;this.buffer=i===void 0?[e]:[i,e],this.bufferHasFullSnapshot=!0,this.pendingBytes=t+(i===void 0?0:U(i)),this.heldBufferIncomplete=!1,this.minimumBufferIncomplete=!1,r&&(this.mode===`full`&&(this.firstObservedTimestamp=i?.timestamp??e.timestamp),this.finishMinimumBufferingEvent());return}if(!this.bufferHasFullSnapshot||t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held,this.bindingBufferIncomplete||=this.awaitingBinding,this.minimumBufferIncomplete||=r,r&&this.finishMinimumBufferingEvent();return}if(this.pendingBytes+t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held,this.bindingBufferIncomplete||=this.awaitingBinding,this.minimumBufferIncomplete||=r,r&&this.finishMinimumBufferingEvent();return}}if(e.type===n.Meta&&this.mode===`full`&&this.buffer.length>0&&this.flushAndReport(),this.buffer.push(e),this.pendingBytes+=t,r&&this.minimumDurationReached()){this.flushAndReport();return}this.mode===`full`&&this.pendingBytes>=this.config.maxBufferBytes&&e.type!==n.Meta?this.flushAndReport():this.scheduleFlush()}addDuringResync(e,t){if(e.type===n.Meta){this.buffer=[e],this.pendingBytes=t;return}if(e.type!==n.FullSnapshot)return;let r=this.buffer.length===1&&this.buffer[0]?.type===n.Meta?this.buffer[0]:void 0;this.buffer=r===void 0?[e]:[r,e],this.pendingBytes=t+(r===void 0?0:U(r)),this.resyncPending=!1,this.clearResyncTimer(),this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush()}async triggerFlush(){return this.mode===`buffer`&&(this.bufferHasFullSnapshot||(this.buffer=[],this.pendingBytes=0),this.mode=`full`,this.start()),this.flush()}async flush(e={}){if(this.closed)return;if(e.keepalive!==!0)return this.flushInternal(e);this.activeUpload!==void 0&&(this.activeUpload.background=!0,this.activeUpload.pagehide=!0);let t=this.queue.filter(e=>(e!==this.activeUpload||!e.attempting)&&!this.pagehideUploads.has(e));for(let e of t)this.pagehideUploads.add(e),e.background=!0;this.wakeRetry?.();let n=this.trackLifecycle(Promise.all(t.map(async e=>this.finalAttempt(e))).then(()=>void 0));await Promise.all([this.flushInternal(e),n])}async flushInternal(e={}){if(this.closed||this.mode===`buffer`||this.held||this.awaitingBinding||this.buffer.length===0||!this.minimumDurationReached()||(this.clearScheduledFlush(),this.minimumBufferIncomplete&&!this.refreshMinimumBuffer()))return;this.minimumDurationSatisfied=!0;let t=this.buffer,n=this.pendingBytes;this.buffer=[],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=0;let r=this.sessionId,i=this.snapshotIdentity();if(e.keepalive===!0){let e=this.splitKeepaliveEventChunks(t,i,Math.max(0,B-this.reservedKeepaliveBytes)),n=this.allocateSeq(e.length);if(n===void 0)return;await this.trackLifecycle(this.deliverLifecycle(e,n,r,i));return}if(e.background===!0){let e=[];for(let n of this.splitKeepaliveEventChunks(t,i)){let t=this.enqueue(n.events,n.eventBytes,r,i,!0,n);if(t===void 0)break;e.push(t)}await Promise.all(e.map(async e=>e.done));return}await this.enqueue(t,n,r,i)?.done}async shutdown(e={}){if(this.started=!1,this.clearScheduledFlush(),this.held||this.awaitingBinding||!this.minimumDurationReached()){this.discard(),await this.settleWithinDeadline([]);return}if(e.keepalive===!0){await this.flush(e),this.closed=!0,this.clearResyncTimer(),await this.settleWithinDeadline([]);return}let t=this.flushInternal();this.closed=!0,this.shuttingDown=!0,this.clearResyncTimer(),this.retryAbort.abort();let n=this.queue.filter(e=>e!==this.activeUpload&&!this.pagehideUploads.has(e)).map(async e=>this.finalAttempt(e));await this.settleWithinDeadline([t,...n])}discard(){this.started=!1,this.closed=!0,this.clearScheduledFlush(),this.clearResyncTimer(),this.buffer=[],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=0}getMode(){return this.mode}isHeld(){return this.held}releaseHeld(e){this.held&&((this.heldBufferIncomplete||!this.bufferHasFullSnapshot)&&(this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,e()),this.held=!1,this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush())}flushAndReport(){this.flushInternal().catch(e=>{V(this.config.onError,e)})}scheduleFlush(){let e=this.config.now(),t=Math.max(0,this.config.minSessionDurationMs-(e-this.startedAt)),n=Math.max(l(this.config.flushIntervalMs,e-this.lastUserActivityAt),t);this.scheduleFlushIn(e,n)}scheduleFlushIn(e,t){if(!this.started||this.mode!==`full`||this.held||this.buffer.length===0)return;let n=e+t;this.timer!==void 0&&this.nextFlushAt!==void 0&&this.nextFlushAt<=n||(this.clearScheduledFlush(),this.nextFlushAt=n,this.timer=setTimeout(()=>{this.timer=void 0,this.nextFlushAt=void 0,this.flushAndReport()},t))}clearScheduledFlush(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0),this.nextFlushAt=void 0}minimumDurationReached(){return this.minimumDurationSatisfied||this.config.minSessionDurationMs===0?!0:this.firstObservedTimestamp===void 0||this.lastObservedTimestamp===void 0?!1:this.lastObservedTimestamp-this.firstObservedTimestamp>=this.config.minSessionDurationMs}finishMinimumBufferingEvent(){this.minimumDurationReached()?this.flushAndReport():this.scheduleFlush()}refreshMinimumBuffer(){let e=this.buffer.length,t=this.pendingBytes;if(this.takeFullSnapshot!==void 0){this.refreshingMinimumSnapshot=!0;try{this.takeFullSnapshot()}catch(e){V(this.config.onError,e)}finally{this.refreshingMinimumSnapshot=!1}}return this.buffer.slice(e).some(e=>e.type===n.FullSnapshot)?(this.minimumBufferIncomplete=!1,!0):(this.buffer.length=e,this.pendingBytes=t,!1)}snapshotIdentity(){let e=this.snapshotUser(),t=this.config.distinctId;if(this.config.getDistinctId!==void 0)try{t=this.config.getDistinctId()??this.config.distinctId}catch(e){V(this.config.onError,e)}else e!==void 0&&(t=e.id);return{distinctId:t,user:e}}createEnvelope(e,t,n){return{version:1,meta:ue(t,e,n.distinctId,this.sessionAttributes,n.user),events:e}}snapshotUser(){if(this.config.getUser!==void 0)try{return le(this.config.getUser())}catch(e){V(this.config.onError,e);return}}allocateSeq(e){let t=this.seq,n=this.sequenceRecord;if(n!==void 0){if(this.sequenceRecordFailed)return;if(!n.write(t+e)){this.sequenceRecordFailed=!0,this.discard();try{n.onFailure()}catch(e){V(this.config.onError,e)}return}}return this.seq+=e,this.saveSeq(this.sessionId,this.seq),t}enqueue(e,t,r,i,a=!1,o){let s=Math.max(2e6,2*this.config.maxBufferBytes);if(this.queue.length>0&&this.retainedBytes+t>s){V(this.config.onError,new L({cause:/* @__PURE__ */ Error(`replay upload queue is full`),reason:`not-sent`,seq:void 0,sessionId:r})),this.beginResync();return}let c=this.allocateSeq(1);if(c===void 0)return;let l=()=>void 0,u={body:void 0,done:new Promise(e=>{l=e}),events:e,hasFullSnapshot:e.some(e=>e.type===n.FullSnapshot),identity:i,reachedFetch:!1,attempting:!1,background:a,pagehide:!1,prepared:o,resolve:l,retainedBytes:t,seq:c,sessionId:r,settled:!1};return this.queue.push(u),this.retainedBytes+=t,this.draining||(this.draining=!0,this.drainPromise=this.drain()),u}async drain(){try{for(;!this.shuttingDown;){let e=this.queue.find(e=>!this.pagehideUploads.has(e));if(e===void 0)break;this.activeUpload=e;let t=await this.deliverQueued(e);this.activeUpload=void 0,this.settle(e,t)}}finally{this.activeUpload=void 0,this.draining=!1}}async deliverQueued(e){let t=await this.compressQueued(e);if(t!==void 0||e.settled)return t;let n=Date.now(),r;for(let t=1;;t++){if(this.pagehideUploads.has(e))return e.done.then(()=>void 0);let i=ge-(Date.now()-n);if(t>1&&i<=0)return G(r,e.reachedFetch);let a=await this.attemptQueued(e,Math.min(z,i));if(a===void 0)return;r=a;let o=Ae(a,t,this.config.random);if(o===void 0||this.shuttingDown||e.pagehide||Date.now()-n+o>=ge)return G(a,e.reachedFetch);await this.backoff(o)}}retainCompressedBody(e,t){this.retainedBytes+=t.byteLength-e.retainedBytes,e.retainedBytes=t.byteLength,e.body=t,e.events=void 0}compressQueuedSync(e){let n=e.prepared;if(e.prepared=void 0,!(e.body!==void 0||e.events===void 0||e.settled)){if(n?.body!==void 0&&n.events===e.events){this.retainCompressedBody(e,n.body);return}try{let n=(0,t.strToU8)(JSON.stringify(this.createEnvelope(e.events,e.seq,e.identity)));this.retainCompressedBody(e,this.compression.gzipSync(n));return}catch(e){return{cause:e,reason:`not-sent`}}}}async compressQueued(e){if(this.shuttingDown||e.background)return this.compressQueuedSync(e);if(e.body!==void 0||e.events===void 0)return;let n=e.events;try{let r=(0,t.strToU8)(JSON.stringify(this.createEnvelope(n,e.seq,e.identity))),i=await this.compressOrdinary(r);if(e.events!==n)return await this.compressQueued(e);e.settled||this.retainCompressedBody(e,i);return}catch(e){return{cause:e,reason:`not-sent`}}}async attemptQueued(e,t=z){let n=e.body;if(n!==void 0){e.attempting=!0;try{await this.send(this.prepareUpload(n,e.seq,e.sessionId,e.background),()=>{e.reachedFetch=!0},t);return}catch(e){return e}finally{e.attempting=!1}}}async finalAttempt(e){let t=e.background?this.compressQueuedSync(e):await this.compressQueued(e);if(t!==void 0){this.settle(e,t);return}let n=await this.attemptQueued(e);this.settle(e,n===void 0?void 0:G(n,e.reachedFetch))}async trackLifecycle(e){this.lifecycleFlights.add(e);let t=()=>{this.lifecycleFlights.delete(e)};return e.then(t,t),e}async settleWithinDeadline(e){let t=Promise.all([...e,this.drainPromise,...this.lifecycleFlights]).then(()=>void 0,()=>void 0),n,r=new Promise(e=>{n=setTimeout(e,z)});if(await Promise.race([t,r]),clearTimeout(n),this.shuttingDown){this.deadlineAbort.abort(/* @__PURE__ */ Error(`replay upload did not finish before shutdown`));for(let e of[...this.queue])this.settle(e,{cause:/* @__PURE__ */ Error(`replay upload did not finish before shutdown`),reason:e.reachedFetch?`unconfirmed`:`not-sent`})}}settle(e,t){if(e.settled)return;e.settled=!0,this.pagehideUploads.delete(e),this.retainedBytes-=e.retainedBytes;let n=this.queue.indexOf(e);n>=0&&this.queue.splice(n,1),e.body=void 0,e.events=void 0,e.resolve(),t!==void 0&&this.handleSequencedLoss(e.seq,e.sessionId,t)}handleSequencedLoss(e,t,n){let r=[];if(!this.shuttingDown){let t=!1;for(let n of[...this.queue])if(!(n.seq<e)){if(n.events===void 0){if(n.hasFullSnapshot){t=!0;break}continue}if(n.hasFullSnapshot){let e=we(n.events),r=Te(e);this.retainedBytes+=r-n.retainedBytes,n.retainedBytes=r,n.events=e,t=!0;break}r.push(n.seq),this.settle(n,void 0)}!t&&!this.trimBufferToAnchor()&&this.beginResync()}V(this.config.onError,new L({cause:n.cause,droppedSeqs:r,reason:n.reason,seq:e,sessionId:t,status:n.status}))}trimBufferToAnchor(){return this.buffer.some(e=>e.type===n.FullSnapshot)?(this.buffer=we(this.buffer),this.pendingBytes=Te(this.buffer),!0):!1}beginResync(){this.closed||(this.resyncPending=!0,this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,this.clearScheduledFlush(),this.scheduleResyncSnapshot())}scheduleResyncSnapshot(){if(this.resyncTimer!==void 0||this.closed)return;let e=this.lastResyncAt===void 0?0:Math.max(0,this.lastResyncAt+6e4-this.config.now());this.resyncTimer=setTimeout(()=>{this.resyncTimer=void 0,this.takeResyncSnapshot()},e)}takeResyncSnapshot(){if(this.resyncPending&&!this.closed&&this.takeFullSnapshot!==void 0){this.lastResyncAt=this.config.now();try{this.takeFullSnapshot()}catch(e){V(this.config.onError,e),this.scheduleResyncSnapshot();return}this.isResyncPending()&&(V(this.config.onError,/* @__PURE__ */ Error(`replay resync snapshot produced no full snapshot`)),this.scheduleResyncSnapshot())}}isResyncPending(){return this.resyncPending}clearResyncTimer(){this.resyncTimer!==void 0&&(clearTimeout(this.resyncTimer),this.resyncTimer=void 0)}async backoff(e){let t=this.retryAbort.signal;t.aborted||await new Promise(n=>{let r=()=>{clearTimeout(i),t.removeEventListener(`abort`,r),this.wakeRetry===r&&(this.wakeRetry=void 0),n()},i=setTimeout(r,e);t.addEventListener(`abort`,r),this.wakeRetry=r})}prepareUpload(e,t,n,r){let i=r&&this.reservedKeepaliveBytes+e.byteLength<=B?e.byteLength:0;return this.reservedKeepaliveBytes+=i,{body:e,seq:t,sessionId:n,reservedBytes:i,requestKeepalive:i>0}}splitKeepaliveEventChunks(e,n,r=1/0){let i=e.map(U),a=[],o=r,s,c=0;for(;c<e.length;){let l=Math.min(B,o);if(l<4800){a.push({events:e.slice(c),eventBytes:W(i,c,e.length)});break}let u=this.seq+a.length,d=s===void 0?_e:Math.min(_e,l*s*ve),f=Ee(i,c,d);for(;;){let d=e.slice(c,f),p=W(i,c,f),m;try{m=this.compression.gzipSync((0,t.strToU8)(JSON.stringify(this.createEnvelope(d,u,n))))}catch{a.push({events:d,eventBytes:p}),o=Number.isFinite(r)?0:o;break}if(s=p/Math.max(1,m.byteLength),m.byteLength<=l){a.push({events:d,eventBytes:p,body:m}),o-=m.byteLength;break}if(f-c===1){Number.isFinite(r)?(a.push({events:e.slice(c),eventBytes:W(i,c,e.length)}),f=e.length):a.push({events:d,eventBytes:p,body:m});break}f=Math.max(c+1,Math.min(f-1,Ee(i,c,l*s*ve)))}c=f}return a}async deliverLifecycle(e,n,r,i){let a=[];for(let o=0;o<e.length;o++){let s=e[o];if(s===void 0){a.push(void 0);continue}try{a.push({body:s.body??this.compression.gzipSync((0,t.strToU8)(JSON.stringify(this.createEnvelope(s.events,n+o,i)))),requestKeepalive:!1,reservedBytes:0,seq:n+o,sessionId:r})}catch(e){this.handleSequencedLoss(n+o,r,{cause:e,reason:`not-sent`}),a.push(void 0)}}let o=!0,s=Math.max(0,B-this.reservedKeepaliveBytes);for(let e of a){if(e===void 0){o=!1;continue}o&&e.body.byteLength<=s?(e.requestKeepalive=!0,e.reservedBytes=e.body.byteLength,this.reservedKeepaliveBytes+=e.reservedBytes,s-=e.reservedBytes):o=!1}await Promise.all(a.map(async e=>{if(e===void 0)return;let t=!1;try{await this.send(e,()=>{t=!0})}catch(n){this.handleSequencedLoss(e.seq,e.sessionId,G(n,t))}}))}async compressOrdinary(e){if(!this.asyncCompressionAvailable)return this.compression.gzipSync(e);try{return await De(this.compression,e)}catch{return this.asyncCompressionAvailable=!1,this.compression.gzipSync(e)}}async send(e,t,n=z){let r,i,a,o=new AbortController,s=setTimeout(()=>{o.abort(/* @__PURE__ */ Error(`replay upload timed out after ${String(n)}ms`))},n),c=this.deadlineAbort.signal,l=()=>{o.abort(c.reason)};c.addEventListener(`abort`,l);try{let n=`${this.config.replayUrl.replace(/\/+$/u,``)}/${encodeURIComponent(e.sessionId)}?seq=${String(e.seq)}`,s=await Ce(this.getUploadHeaders(),o.signal);t();let c=this.config.fetchImpl(n,{method:`POST`,headers:s,body:e.body.slice(),keepalive:e.requestKeepalive,signal:o.signal});r=!0;let l=await c;if(i=!0,a=await Oe(l),!l.ok){let e=l.status===429||l.status===503?je(l.headers.get(`retry-after`),Date.now()):void 0;throw new H(l.status,e)}}finally{clearTimeout(s),c.removeEventListener(`abort`,l),e.reservedBytes>0&&(r!==!0||i!==!0||a===!0)&&(this.reservedKeepaliveBytes=Math.max(0,this.reservedKeepaliveBytes-e.reservedBytes))}}async getUploadHeaders(){let e=this.config.headers===void 0?{}:await this.config.headers(),t=await Se(this.config.token);return{...t===void 0||t.length===0?e:{...Object.fromEntries(Object.entries(e).filter(([e])=>e.toLowerCase()!==`authorization`)),Authorization:`Bearer ${t}`},"Content-Type":`application/json`,"Content-Encoding":`gzip`}}canResumeSequence(){return this.awaitingBinding?!0:this.readPersistedSequence()===this.seq}isAwaitingBinding(){return this.awaitingBinding}bind(e){this.awaitingBinding&&!this.closed&&(this.sequenceRecord=e,this.seq=e.initialSeq,this.awaitingBinding=!1,this.bindingBufferIncomplete&&(this.bindingBufferIncomplete=!1,this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,this.takeFullSnapshot?.()),!(this.mode!==`full`||this.held||this.buffer.length===0)&&(this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush()))}readPersistedSequence(){if(this.storage!==null)try{let e=this.storage.getItem(R);if(e===null)return;let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let n=t;return n.id===this.sessionId&&typeof n.seq==`number`&&Number.isSafeInteger(n.seq)&&n.seq>=0?n.seq:void 0}catch{return}}saveSeq(e,t){if(this.storage!==null)try{this.storage.setItem(R,JSON.stringify({id:e,seq:t}))}catch{}}};function V(e,t){try{let n=e?.(t);xe(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function xe(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}var H=class extends Error{retryAfter;status;constructor(e,t){super(`replay ingest failed: ${String(e)}`),this.status=e,this.retryAfter=t,this.name=`ReplayIngestError`}};async function Se(e){return typeof e==`function`?e():e}async function Ce(e,t){if(t.aborted)throw t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e instanceof Error?e:Error(String(e)))})})}function U(e){try{return(0,t.strToU8)(JSON.stringify(e)).byteLength}catch{return 0}}function we(e){let t=e.findIndex(e=>e.type===n.FullSnapshot);if(t<0)return e;let r=t>0&&e[t-1]?.type===n.Meta?t-1:t;return e.slice(r)}function Te(e){return e.reduce((e,t)=>e+U(t),0)}function W(e,t,n){let r=0;for(let i=t;i<n;i++)r+=e[i]??0;return r}function Ee(e,t,n){let r=t+1,i=e[t]??0;for(;r<e.length&&i+(e[r]??0)<=n;)i+=e[r]??0,r++;return r}async function De(e,t){return new Promise((n,r)=>{let i=[];typeof window<`u`&&i.push(window),typeof document<`u`&&i.push(document);let a=()=>{for(let e of i)e.removeEventListener(`securitypolicyviolation`,s)},o=(e,t)=>{if(a(),e!==null){r(e);return}n(t)},s=e=>{let t=e;(t.effectiveDirective.includes(`worker-src`)||t.violatedDirective.includes(`worker-src`))&&o(/* @__PURE__ */ Error(`replay compression worker blocked by Content Security Policy`))};for(let e of i)e.addEventListener(`securitypolicyviolation`,s);try{e.gzip(t,{level:6},(e,t)=>{o(e,t)})}catch(e){a(),r(e instanceof Error?e:Error(String(e)))}})}async function Oe(e){if(e.body===null)return!0;try{return await e.body.cancel(),!0}catch{return!1}}function ke(e){return e===408||e===425||e===429||e>=500}function Ae(e,t,n){if(e instanceof H&&!ke(e.status))return;let r=Math.min(8e3,500*2**(t-1)),i=Math.round(r*(1-.5*n())),a=e instanceof H?e.retryAfter:void 0;return a===void 0?i:Math.max(a,i)}function G(e,t){let n=e instanceof H?e.status:void 0;return n!==void 0&&!ke(n)?{cause:e,reason:`rejected`,status:n}:{cause:e,reason:t?`unconfirmed`:`not-sent`,status:n}}function je(e,t){if(e===null)return;let n=e.trim();if(/^\d+$/u.test(n)){let e=Number(n);return Number.isSafeInteger(e)?e*1e3:void 0}let r=Fe(n,t);return r===void 0?void 0:Math.max(0,r-t)}const Me=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Ne=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],Pe=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function Fe(e,t){let n=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(n!==null)return K(n[1],n[2],n[3],n[4],n[5],n[6],n[7]);let r=/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(r!==null){let e=new Date(t).getUTCFullYear(),n=Number(r[4]),i=Math.floor(e/100)*100+n;return i>e+50&&(i-=100),K(r[1],r[2],r[3],String(i),r[5],r[6],r[7])}let i=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{2}| \d) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/u.exec(e);if(i!==null)return K(i[1],i[3]?.trim(),i[2],i[7],i[4],i[5],i[6])}function K(e,t,n,r,i,a,o){let s=Number(t),c=Me.indexOf(n),l=Number(r),u=Number(i),d=Number(a),f=Number(o);if(c<0||s<1||s>31||u>23||d>59||f>59)return;let p=/* @__PURE__ */ new Date(0);if(p.setUTCFullYear(l,c,s),p.setUTCHours(u,d,f,0),p.getUTCFullYear()!==l||p.getUTCMonth()!==c||p.getUTCDate()!==s||p.getUTCHours()!==u||p.getUTCMinutes()!==d||p.getUTCSeconds()!==f)return;let m=Ne.indexOf(e),h=Pe.indexOf(e);return(m>=0?m:h)===p.getUTCDay()?p.getTime():void 0}const Ie=`lf_session_replay_recording`,q=`lf_session_replay_recording_owner`,Le=72e5;var Re=class{state;resumed=!1;storage;owner;now;maxDurationMs;readOpenerState;constructor(e,t,n,r=()=>null){this.storage=e,this.now=t,this.owner=F(t),this.maxDurationMs=Math.min(n,Le),this.readOpenerState=r;try{e?.getItem(`lf_session_replay_recording_owner`)===null&&(this.state=this.readResumableState()),e?.setItem(q,this.owner),e?.getItem(`lf_session_replay_recording_owner`)!==this.owner&&(this.storage=null,this.state=void 0)}catch{this.storage=null,this.state=void 0}this.resumed=this.state!==void 0}get(e){return this.state!==void 0&&this.isCurrent(this.state.id,e)?this.state.id:this.replace(e)}candidate(e){return{id:this.get(e),resumed:this.resumed}}replace(e){this.state={id:F(this.now),rumSessionId:e,startedAt:this.now()},this.resumed=!1;try{this.storage?.setItem(Ie,JSON.stringify(this.state))}catch{}return this.state.id}isCurrent(e,t){let n=this.state;if(n===void 0)return!1;let r=this.now();return n.id===e&&n.rumSessionId===t&&r>=n.startedAt&&r-n.startedAt<this.maxDurationMs}release(){try{this.storage?.getItem(`lf_session_replay_recording_owner`)===this.owner&&this.storage.removeItem(q)}catch{}}resume(){try{this.state=this.storage?.getItem(`lf_session_replay_recording_owner`)===null?this.readResumableState():void 0,this.storage?.setItem(q,this.owner),this.storage?.getItem(`lf_session_replay_recording_owner`)!==this.owner&&(this.state=void 0,this.storage=null)}catch{this.state=void 0,this.storage=null}this.resumed=this.state!==void 0}readResumableState(){let e=this.storage?.getItem(Ie),t=this.storage?.getItem(R);if(e==null||t==null)return;let n=null;try{n=this.readOpenerState()}catch{}if(n!==e)return ze(e,t)}};function ze(e,t){let n=JSON.parse(e),r=JSON.parse(t);if(typeof n!=`object`||!n||typeof r!=`object`||!r)return;let i=n,a=r;if(!(typeof i.id!=`string`||i.id.length===0||typeof i.rumSessionId!=`string`||typeof i.startedAt!=`number`||!Number.isFinite(i.startedAt)||a.id!==i.id||typeof a.seq!=`number`||!Number.isSafeInteger(a.seq)||a.seq<0))return{id:i.id,rumSessionId:i.rumSessionId,startedAt:i.startedAt}}function Be(){try{if(typeof window>`u`||!window.isSecureContext)return;let e=globalThis.navigator?.locks;return typeof e?.request==`function`?e:void 0}catch{return}}async function Ve(e,t,n,r=1e3){return n.aborted?{kind:`aborted`}:new Promise(i=>{let a=!1,o=e=>{a||(a=!0,clearTimeout(c),n.removeEventListener(`abort`,l),i(e))},s=new AbortController,c=setTimeout(()=>{s.abort(),o({kind:`timeout`})},r),l=()=>{s.abort(),o({kind:`aborted`})};n.addEventListener(`abort`,l);let u=!1;try{e.request(`logfire-session-replay:${t}`,{mode:`exclusive`,signal:s.signal},async()=>{if(u=!0,a||n.aborted){o({kind:`aborted`});return}await new Promise(e=>{o({kind:`held`,lock:{release:e}})})}).catch(()=>{u||o({kind:`aborted`})})}catch{o({kind:`aborted`})}})}function He(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Ue(e){let t=e.random??Math.random;return t()<He(e.sessionSampleRate)?`full`:t()<He(e.onErrorSampleRate)?`buffer`:`off`}const We=`lf_session_replay_seq:`,J=`lf_session_replay_probe`;var Ge=class{storage;now;constructor(e,t){this.storage=e,this.now=t}read(e){try{return Je(this.storage.getItem(qe(e)))?.seq}catch{return}}write(e,t){try{return this.storage.setItem(qe(e),JSON.stringify({seq:t,at:this.now()})),this.read(e)===t}catch{return!1}}prune(e){try{let t=this.now()-e,n=[];for(let e=0;e<this.storage.length;e+=1){let r=this.storage.key(e);if(r===null||!r.startsWith(We))continue;let i=Je(this.storage.getItem(r));(i===void 0||i.at<t)&&n.push(r)}for(let e of n)this.storage.removeItem(e)}catch{}}};function Ke(){try{let e=globalThis.localStorage;if(e===void 0)return null;e.setItem(J,`1`);let t=e.getItem(J)===`1`;return e.removeItem(J),t?e:null}catch{return null}}function qe(e){return`${We}${e}`}function Je(e){if(e!==null)try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let n=t;return typeof n.seq!=`number`||!Number.isSafeInteger(n.seq)||n.seq<0||typeof n.at!=`number`||!Number.isFinite(n.at)?void 0:{seq:n.seq,at:n.at}}catch{return}}const Ye=/^[a-z][a-z0-9_]{0,63}$/u;function Xe(e,t){let n=0;for(let r of e)if(n+=+(r.length>0),n>t)return!1;return!0}function Ze(e,t){if(e===void 0)return Object.freeze({});let n;try{n=e()}catch(e){return t(e),Object.freeze({})}if(typeof n!=`object`||!n||Array.isArray(n))return Object.freeze({});let r;try{r=Object.getPrototypeOf(n)}catch(e){return t(e),Object.freeze({})}if(r!==Object.prototype&&r!==null)return Object.freeze({});let i;try{i=Object.keys(n)}catch(e){return t(e),Object.freeze({})}let a={},o=0;for(let e of i){if(!Ye.test(e))continue;let r;try{r=Reflect.get(n,e)}catch(e){t(e);continue}if((typeof r==`boolean`||typeof r==`number`&&Number.isFinite(r)||typeof r==`string`&&Xe(r,200))&&(Object.defineProperty(a,e,{configurable:!0,enumerable:!0,value:r,writable:!0}),o+=1,o===20))break}return Object.freeze(a)}const Qe={mode:`off`,recording:!1,getSessionId:()=>``,captureError:()=>void 0,getRecordingId:()=>``,flush:async()=>Promise.resolve(),stop:async()=>Promise.resolve()},$e=`lf_session_replay_mode`,Y=Symbol.for(`@pydantic/logfire-session-replay/controller`);function et(e){if(typeof window>`u`||typeof document>`u`)return Qe;let t=ft();try{let n=nt(e),r=new pe({idleTimeoutMs:n.sessionIdleTimeoutMs,maxDurationMs:n.maxSessionDurationMs,now:n.now}),i=r.getSession().id,a=e=>{let t;try{t=n.getSessionId?.()}catch(e){return Q(n.onError,e),i}if(t!==void 0&&t.length>0)return i=t,t;let a=e?r.touch().id:r.getSession().id;return i=a,a},o=I(),s=new Re(o,n.now,n.maxSessionDurationMs,()=>window.opener?.sessionStorage.getItem(`lf_session_replay_recording`)??null),c=rt(n.now),l=a(!1),u=s.get(l),d,f=!1,p=!1,m=0,h=!0,g=Promise.resolve(),_=Promise.resolve(),v,y,b,x=!1,S=e=>{y!==void 0&&(e===void 0||y.recordingId===e)&&(y.lock.release(),y=void 0)},C=(e,t,r=!t,i=!1)=>{let c=it(n,e,o);if(!(c===`off`||f||p||d!==void 0||e!==l))try{x=i&&s.candidate(e).resumed;let t=u;d=tt({config:n,getSessionId:a,mode:c,onSessionChanged:O,samplingModeStorage:o,sessionId:e,recordingId:t,isCurrentRecording:()=>s.isCurrent(t,a(!1)),holdUntilActivity:r,awaitBinding:i})}catch(e){if(d=void 0,t)throw e;Q(n.onError,e)}},w=(e,t,n)=>({initialSeq:n,write:n=>e.records.write(t,n),onFailure:()=>{queueMicrotask(()=>{!f&&u===t&&(s.replace(l),O(l,!1))})}}),T=async(e,t,r)=>{b?.abort();let i=new AbortController;b=i;let a=()=>i.signal.aborted||f||p||m!==r||l!==t,o=s.candidate(t);u=o.id;let c=()=>{o={id:s.replace(t),resumed:!1},u=o.id};for(let t=0;t<2;t+=1){let t=await Ve(e.locks,o.id,i.signal);if(t.kind===`aborted`)return;if(t.kind===`timeout`){c();continue}if(a()||u!==o.id){t.lock.release();return}let n;if(o.resumed?n=e.records.read(o.id):e.records.write(o.id,0)&&(n=0),n===void 0){t.lock.release(),c();continue}return y={recordingId:o.id,lock:t.lock},{recordingId:o.id,sequenceRecord:w(e,o.id,n)}}Q(n.onError,/* @__PURE__ */ Error(`logfire session replay: could not claim a replay recording`))},E=async(e,t,r,i)=>{try{let n=await T(e,t,r),a=!f&&!p&&m===r&&l===t;if(n===void 0){a&&d?.transport.isAwaitingBinding()===!0&&(d.discard(),d=void 0);return}if(!a){S(n.recordingId);return}if(d!==void 0&&d.recordingId!==n.recordingId&&(d.discard(),d=void 0,C(t,!1,i,!0)),d===void 0||d.recordingId!==n.recordingId){S(n.recordingId);return}x=!1,d.transport.bind(n.sequenceRecord)}catch(e){Q(n.onError,e)}},D=async(e,t,n)=>{C(e,!1,n,c!==void 0),c!==void 0&&d!==void 0&&await E(c,e,t,n)},O=(e,t=!0)=>{if(f||p)return;let r=s.get(e);if(e===l&&r===u)return;let i=u;l=e,u=r,b?.abort();let a=d;d=void 0;let o=a?.deactivate()??Promise.resolve(),c=m;g=g.then(async()=>{await Z(o,n.onError),S(i),!f&&m===c&&l===e&&u===r&&await D(e,c,t)})},k;try{if(c===void 0)C(l,!0);else if(c.records.prune(Le),C(l,!0,!1,!0),d!==void 0){let e=l,t=m;g=g.then(async()=>E(c,e,t,!1))}k=setInterval(()=>{O(a(!1))},1e3)}catch(e){throw d?.discard(),d=void 0,b?.abort(),S(),s.release(),e}let A=()=>{p=!0,m+=1,b?.abort();let e=d;d=void 0;let t=e?.deactivate(!0)??Promise.resolve();S(),_=Promise.all([_,g,Z(t,n.onError)]).then(()=>void 0),g=Promise.resolve(),h=e?.transport.canResumeSequence()??h,h&&s.release()},ee=e=>{if(!e.persisted||f)return;d?.discard(),d=void 0;let t=m;g=g.then(async()=>{let e=()=>f||m!==t;if(e())return;let n=new AbortController;b=n;let r,i=!1;if(c!==void 0){let e=await Ve(c.locks,u,n.signal);if(e.kind===`aborted`)return;e.kind===`held`&&(r=e.lock),i=e.kind===`timeout`}else await new Promise(e=>{setTimeout(e,0)});try{if(e())return;p=!1,s.resume(),l=a(!1),u=i?s.replace(l):s.get(l),h=!0}finally{r?.release()}await D(l,t,!1)})};return window.addEventListener(`pagehide`,A),window.addEventListener(`pageshow`,ee),{get mode(){try{return d?.transport.getMode()??`off`}catch(e){return Q(n.onError,e),`off`}},get recording(){try{return d!==void 0}catch(e){return Q(n.onError,e),!1}},getSessionId:()=>a(!1),captureError:(e,t)=>{try{d?.captureError(e,t)}catch(e){Q(n.onError,e)}},getRecordingId:()=>d===void 0||x&&d.transport.isAwaitingBinding()?``:s.isCurrent(d.recordingId,a(!1))?d.recordingId:``,flush:async()=>{try{await g,await d?.transport.flush()}catch(e){Q(n.onError,e)}},stop:async()=>(v??=(async()=>{f=!0,m+=1,b?.abort(),clearInterval(k),window.removeEventListener(`pagehide`,A),window.removeEventListener(`pageshow`,ee);let e=d;d=void 0,await Z(e?.deactivate()??Promise.resolve(),n.onError),await g,await _,r.flushPendingStorage(),h=e?.transport.canResumeSequence()??h,h&&s.release(),S(),t()})(),v)}}catch(e){throw t(),e}}function tt(e){let{config:t,getSessionId:n,holdUntilActivity:r,mode:i,onSessionChanged:o,samplingModeStorage:s,sessionId:l,recordingId:u,isCurrentRecording:d,awaitBinding:f}=e,p=Ze(t.getSessionAttributes,e=>{Q(t.onError,e)}),m,v=new be(t,u,i,void 0,void 0,p,{holdUntilActivity:r,takeFullSnapshot:()=>{m.takeFullSnapshot()},awaitBinding:f}),y=[],b=!0,x=()=>b,S;try{m=oe({beforeUserActivity:()=>{if(b&&v.isHeld())try{let e=n(!0);if(e!==l||!d()){o(e,!1);return}v.releaseHeld(()=>{m.takeFullSnapshot()})}catch(e){Q(t.onError,e)}},emit:e=>{if(b)try{let t=n(c(e));if(t!==l||!d()){o(t,!1);return}v.add(e)}catch(e){Q(t.onError,e)}},maskAllText:t.maskAllText,maskAllInputs:t.maskAllInputs,maskTextSelector:t.maskTextSelector,blockSelector:t.blockSelector,checkoutEveryNms:i===`buffer`?12e4:Math.max(3e5,t.minSessionDurationMs),redactUrlPatterns:t.redactUrlPatterns}),y.push(()=>{m.stop()});let e=(e,n)=>{if(b)try{m.addCustomEvent(e,n)}catch(e){Q(t.onError,e)}},r=n=>{x()&&(v.releaseHeld(()=>{m.takeFullSnapshot()}),e(a.Error,n),x()&&v.getMode()===`buffer`&&(ot(s,l,`full`),X(v.triggerFlush(),t.onError)))},f=/* @__PURE__ */ new WeakSet,p=e=>typeof e!=`object`||!e||!f.has(e)&&(f.add(e),!0),C=(e,t)=>{if(p(e)){let n=pt(ct(e),void 0,lt(e));r(typeof t?.timestamp==`number`?{...n,timestamp:t.timestamp}:n)}},w=e=>{e instanceof ErrorEvent&&p(e.error)&&r(pt(e.message,e.filename,lt(e.error)))},T=e=>{C(e.reason)},E=()=>{document.visibilityState===`hidden`&&X(v.flush({background:!0}),t.onError)},D=()=>{X(v.flush({keepalive:!0}),t.onError)};return t.captureGlobalErrors&&(window.addEventListener(`error`,w,!0),y.push(()=>{window.removeEventListener(`error`,w,!0)}),window.addEventListener(`unhandledrejection`,T,!0),y.push(()=>{window.removeEventListener(`unhandledrejection`,T,!0)})),document.addEventListener(`visibilitychange`,E),y.push(()=>{document.removeEventListener(`visibilitychange`,E)}),window.addEventListener(`pagehide`,D),y.push(()=>{window.removeEventListener(`pagehide`,D)}),t.captureConsole&&y.push(h(e,{onError:t.onError})),t.captureNetwork&&y.push(g(e,{ignoreUrlPatterns:t.ignoreUrlPatterns,now:t.now,onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),t.captureNavigation&&y.push(_(e,{onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),v.start(),{sessionId:l,recordingId:u,transport:v,captureError:C,deactivate:async(e=!1)=>(S??=(async()=>{let t=v.shutdown({keepalive:e});b=!1,$(y),await t})(),S),discard:()=>{b=!1,$(y),v.discard()}}}catch(e){throw b=!1,$(y),v.discard(),e}}function nt(e){if(e.replayUrl.length===0)throw Error("logfire session replay: `replayUrl` is required");let t=new URL(e.replayUrl,`https://logfire.invalid/`);if(t.search!==``||t.hash!==``)throw Error("logfire session replay: `replayUrl` must not contain a query or fragment");let n=e.fetchImpl??(typeof fetch==`function`?fetch.bind(globalThis):void 0);if(n===void 0)throw Error("logfire session replay: no `fetch` available; pass `fetchImpl`");return{replayUrl:e.replayUrl,headers:e.headers,token:e.token,getSessionId:e.getSessionId,getSessionAttributes:e.getSessionAttributes,sessionSampleRate:e.sessionSampleRate??o.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate??o.onErrorSampleRate,maskAllText:e.maskAllText??o.maskAllText,maskAllInputs:e.maskAllInputs??o.maskAllInputs,maskTextSelector:e.maskTextSelector??o.maskTextSelector,blockSelector:e.blockSelector??o.blockSelector,flushIntervalMs:e.flushIntervalMs??o.flushIntervalMs,maxBufferBytes:e.maxBufferBytes??o.maxBufferBytes,minSessionDurationMs:e.minSessionDurationMs??o.minSessionDurationMs,sessionIdleTimeoutMs:e.sessionIdleTimeoutMs??o.sessionIdleTimeoutMs,maxSessionDurationMs:e.maxSessionDurationMs??o.maxSessionDurationMs,distinctId:e.distinctId??o.distinctId,getDistinctId:e.getDistinctId,getUser:e.getUser,captureConsole:e.captureConsole??o.captureConsole,captureNetwork:e.captureNetwork??o.captureNetwork,captureNavigation:e.captureNavigation??o.captureNavigation,captureGlobalErrors:e.captureGlobalErrors??o.captureGlobalErrors,ignoreUrlPatterns:e.ignoreUrlPatterns??[],redactUrlPatterns:e.redactUrlPatterns??[...o.redactUrlPatterns],onError:e.onError,fetchImpl:n,now:e.now??Date.now,random:e.random??Math.random}}function rt(e){let t=Be();if(t===void 0)return;let n=Ke();return n===null?void 0:{locks:t,records:new Ge(n,e)}}function it(e,t,n){let r=at(n,t);if(r!==void 0)return r;let i=Ue({sessionSampleRate:e.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate,random:e.random});return ot(n,t,i),i}function at(e,t){if(e!==null)try{let n=e.getItem($e);if(n===null)return;let r=JSON.parse(n);if(typeof r!=`object`||!r)return;let i=r;return i.id!==t||!st(i.mode)?void 0:i.mode}catch{return}}function ot(e,t,n){if(e!==null)try{e.setItem($e,JSON.stringify({id:t,mode:n}))}catch{}}function st(e){return e===`full`||e===`buffer`||e===`off`}function ct(e){return mt(ut(e,`message`)??e)}function lt(e){let t=ut(e,`stack`);return typeof t==`string`?t:void 0}function ut(e,t){try{return typeof e==`object`&&e&&t in e?e[t]:void 0}catch{return}}function X(e,t){e.catch(e=>{Q(t,e)})}async function Z(e,t){try{await e}catch(e){Q(t,e)}}function Q(e,t){try{let n=e?.(t);dt(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function dt(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function ft(){let e=globalThis;if(e[Y]!==void 0)throw Error(`logfire session replay: a replay controller is already active in this page`);let t={};Object.defineProperty(e,Y,{configurable:!0,enumerable:!1,value:t,writable:!0});let n=!1;return()=>{n||(n=!0,e[Y]===t&&Reflect.deleteProperty(e,Y))}}function $(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}e.length=0}function pt(e,t,n){return{message:e,...t===void 0||t.length===0?{}:{source:t},...n===void 0?{}:{stack:n}}}function mt(e){if(e==null)return`unhandledrejection`;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return String(e);try{return Object.prototype.toString.call(e)}catch{return`[object Object]`}}exports.CHUNK_ENVELOPE_VERSION=1,exports.CustomTag=a,exports.EventType=n,exports.IncrementalSource=r,exports.MouseInteractions=i,exports.ReplayUploadError=L,exports.startSessionReplay=et;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{record as e}from"@rrweb/record";import{gzip as t,gzipSync as n,strToU8 as r}from"fflate";const i={DomContentLoaded:0,Load:1,FullSnapshot:2,IncrementalSnapshot:3,Meta:4,Custom:5,Plugin:6},a={Mutation:0,MouseMove:1,MouseInteraction:2,Scroll:3,ViewportResize:4,Input:5,TouchMove:6,MediaInteraction:7,Drag:12,Selection:14},o={MouseUp:0,MouseDown:1,Click:2,ContextMenu:3,DblClick:4},s={Error:`logfire.error`,Console:`logfire.console`,Network:`logfire.network`,Navigation:`logfire.navigation`},c=1,l={sessionSampleRate:1,onErrorSampleRate:1,maskAllText:!0,maskAllInputs:!0,maskTextSelector:``,blockSelector:``,flushIntervalMs:5e3,maxBufferBytes:1e6,minSessionDurationMs:1e4,sessionIdleTimeoutMs:18e5,maxSessionDurationMs:72e5,distinctId:``,captureConsole:!1,captureNetwork:!0,captureNavigation:!0,captureGlobalErrors:!0,redactUrlPatterns:[/.+/u]},u=/* @__PURE__ */ new Set([a.MouseMove,a.MouseInteraction,a.Scroll,a.ViewportResize,a.Input,a.TouchMove,a.MediaInteraction,a.Drag,a.Selection]);function d(e){return e.type!==i.IncrementalSnapshot||typeof e.data!=`object`||e.data===null||!(`source`in e.data)?!1:typeof e.data.source==`number`&&u.has(e.data.source)}function f(e,t){return t<3e4?e:t<3e5?Math.max(e,6e4):Math.max(e,3e5)}function p(e,t){return t.some(t=>new RegExp(t.source,t.flags).test(e))}function m(e,t,n){if(!p(e,t))return e;try{let t=new URL(e,n);return`${t.origin}${t.pathname}`}catch{let[t=e]=e.split(`?`),[n=t]=t.split(`#`);return n}}const h=[`log`,`info`,`warn`,`error`,`debug`],g=1024,_=()=>void 0;function v(e,t={}){let n=[],r=E(t.onError);try{for(let t of h)typeof console[t]==`function`&&n.push(O(console,t,(n,i)=>function(...a){return i()&&T(e,s.Console,{level:t,args:a.slice(0,10).map(ee)},r),n.apply(this,a)}));return k(n)}catch(e){throw A(n),e}}function y(e,t){let n=C(t),r={...n,onError:E(n.onError)},i=x(e,r);try{return k([i,S(e,r)])}catch(e){throw i(),e}}function b(e,t={redactUrlPatterns:[]}){let n=E(t.onError),r=r=>{let i=m(window.location.href,t.redactUrlPatterns??[],window.location.href);T(e,s.Navigation,{url:i,kind:r},n)},i=[];try{i.push(O(history,`pushState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`push`),i})),i.push(O(history,`replaceState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`replace`),i}));let e=!0,t=()=>{e&&r(`pop`)};return window.addEventListener(`popstate`,t),i.push(()=>{e=!1,window.removeEventListener(`popstate`,t)}),k(i)}catch(e){throw A(i),e}}function x(e,t){return typeof window.fetch==`function`?O(window,`fetch`,(n,r)=>{let i=async function(i,a){let o=n;if(!r())return o.call(this,i,a);let c=t.now(),l=te(i,a),u=ne(i);if(oe(u,t.ignoreUrlPatterns))return o.call(this,i,a);let d=m(u,t.redactUrlPatterns,window.location.href),f=ae(a?.body);try{let n=await o.call(this,i,a);return r()&&T(e,s.Network,M({method:l,url:d,status:n.status,durationMs:Math.max(0,t.now()-c),reqBytes:f,resBytes:re(n.headers)}),t.onError),n}catch(n){throw r()&&T(e,s.Network,M({method:l,url:d,status:0,durationMs:Math.max(0,t.now()-c),failed:!0,reqBytes:f}),t.onError),n}},a=Reflect.get(n,`__original`);return Object.defineProperty(i,"__original",{configurable:!0,value:typeof a==`function`?a:n,writable:!0}),i}):_}function S(e,t){let n=window.XMLHttpRequest.prototype,r=/* @__PURE__ */ new WeakMap,i=[];try{return i.push(O(n,`open`,(e,n)=>function(...i){let[a,o]=i;if(!n())return e.apply(this,i);let s=o.toString();return oe(s,t.ignoreUrlPatterns)?(r.delete(this),e.apply(this,i)):(r.set(this,{method:a.toUpperCase(),url:m(s,t.redactUrlPatterns,window.location.href),startedAt:0,reqBytes:0,failed:!1,emitted:!1}),e.apply(this,i))})),i.push(O(n,`send`,(n,i)=>function(...a){let[o]=a,c=i()?r.get(this):void 0;if(c===void 0)return n.apply(this,a);c.startedAt=t.now(),c.reqBytes=ae(o);let l=()=>{c.failed=!0},u=()=>{c.emitted||(c.emitted=!0,this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),i()&&T(e,s.Network,M({method:c.method,url:c.url,status:this.status,durationMs:Math.max(0,t.now()-c.startedAt),failed:c.failed||this.status===0,reqBytes:c.reqBytes,resBytes:ie(this)}),t.onError))};this.addEventListener(`error`,l),this.addEventListener(`abort`,l),this.addEventListener(`timeout`,l),this.addEventListener(`loadend`,u,{once:!0});try{return n.apply(this,a)}catch(n){throw this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),this.removeEventListener(`loadend`,u),i()&&T(e,s.Network,M({method:c.method,url:c.url,status:0,durationMs:Math.max(0,t.now()-c.startedAt),failed:!0,reqBytes:c.reqBytes}),t.onError),n}})),k(i)}catch(e){throw A(i),e}}function C(e){return{...e,ignoreUrlPatterns:w(e.ignoreUrlPatterns),redactUrlPatterns:w(e.redactUrlPatterns)}}function w(e){return e.map(e=>{let t=e.flags.replace(/[gy]/gu,``);return t===e.flags?e:new RegExp(e.source,t)})}function T(e,t,n,r){try{e(t,n)}catch(e){r?.(e)}}function E(e){let t=!1;return n=>{if(!t){t=!0;try{let t=e?.(n);D(t)&&Promise.resolve(t).catch(()=>void 0)}catch{}finally{t=!1}}}}function D(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function O(e,t,n){let r=e,i=r[t];if(typeof i!=`function`)return _;let a=!0,o=n(i,()=>a);return r[t]=o,()=>{a&&(a=!1,r[t]===o&&(r[t]=i))}}function k(e){let t=!1;return()=>{t||(t=!0,A(e))}}function A(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}}function ee(e){if(e==null)return String(e);if(typeof e==`string`)return j(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(e instanceof Error)return j(e.stack??`${e.name}: ${e.message}`);try{return j(JSON.stringify(e))}catch{return Object.prototype.toString.call(e)}}function j(e){if(e.length<=g)return e;let t=e.charCodeAt(1023),n=t>=55296&&t<=56319?1023:g;return`${e.slice(0,n)}...(+${String(e.length-n)} chars)`}function te(e,t){return(t?.method??(typeof e==`object`&&`method`in e?e.method:`GET`)).toUpperCase()}function ne(e){return typeof e==`string`||e instanceof URL?e.toString():e.url}function re(e){let t=e.get(`content-length`);if(t===null)return;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}function ie(e){try{let t=e.getResponseHeader(`content-length`);if(t===null)return;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}catch{return}}function M(e){return{method:e.method,url:e.url,status:e.status,durationMs:e.durationMs,...e.failed===void 0?{}:{failed:e.failed},...e.reqBytes===void 0?{}:{reqBytes:e.reqBytes},...e.resBytes===void 0?{}:{resBytes:e.resBytes}}}function ae(e){if(e==null)return 0;if(typeof e==`string`)return new TextEncoder().encode(e).byteLength;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Blob)return e.size}function oe(e,t){return p(e,t)}const se=/* @__PURE__ */ new Set([`action`,`formaction`,`href`,`src`]);function ce(t){let n=()=>{t.beforeUserActivity?.()},r={emit:e=>{t.emit(le(e,t.redactUrlPatterns))},maskAllInputs:t.maskAllInputs,recordCanvas:!1,collectFonts:!1,inlineImages:!1,recordCrossOriginIframes:!1,slimDOMOptions:`all`,hooks:{input:n,mediaInteaction:n,mouseInteraction:n,mousemove:n,scroll:n,selection:n,viewportResize:n},sampling:{mousemove:100,mouseInteraction:!0,scroll:250,media:800,input:`last`}};t.maskAllText?r.maskTextSelector=`*`:t.maskTextSelector!==void 0&&t.maskTextSelector.length>0&&(r.maskTextSelector=t.maskTextSelector),t.blockSelector!==void 0&&t.blockSelector.length>0&&(r.blockSelector=t.blockSelector),t.checkoutEveryNms!==void 0&&t.checkoutEveryNms>0&&(r.checkoutEveryNms=t.checkoutEveryNms);let i=e(r);if(i===void 0)throw Error(`logfire session replay: rrweb failed to start recording`);return{stop:()=>{i()},addCustomEvent:(t,n)=>{e.addCustomEvent(t,n)},takeFullSnapshot:()=>{e.takeFullSnapshot(!0)}}}function le(e,t){if(typeof e.data!=`object`||e.data===null)return e;let n=e.data;if(e.type===i.Meta){if(typeof n.href!=`string`)return e;let r=m(n.href,t,window.location.href);return r===n.href?e:{...e,data:{...n,href:r}}}if(e.type!==i.FullSnapshot&&(e.type!==i.IncrementalSnapshot||n.source!==a.Mutation))return e;let r=N(n,t);return r===n?e:{...e,data:r}}function N(e,t){if(Array.isArray(e)){let n=!1,r=[];for(let i of e){let e=N(i,t);e!==i&&(n=!0),r.push(e)}return n?r:e}if(typeof e!=`object`||!e)return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){let n=e===`attributes`&&!Array.isArray(a)?ue(a,t):N(a,t);n!==a&&(r=!0),i[e]=n}return r?i:e}function ue(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){if(!se.has(e.toLowerCase())||typeof a!=`string`){i[e]=a;continue}let n=m(a,t,window.location.href);n!==a&&(r=!0),i[e]=n}return r?i:e}function P(e){return typeof e==`object`&&e?e:void 0}function F(e){return typeof e==`string`&&e.length>0?e:void 0}function de(e){let t=P(e),n=F(t?.id);if(t===void 0||n===void 0)return;let r=F(t.name),i=F(t.email);return{id:n,...r===void 0?{}:{name:r},...i===void 0?{}:{email:i}}}function fe(e,t,n,r={},c){let l=1/0,u=0,d=0,f=0,p=0,m=!1,h=/* @__PURE__ */ new Set;for(let e of t){e.timestamp<l&&(l=e.timestamp),e.timestamp>u&&(u=e.timestamp);let t=P(e.data);if(e.type===i.FullSnapshot)m=!0;else if(e.type===i.Meta){let e=F(t?.href);e!==void 0&&h.add(e)}else if(e.type===i.IncrementalSnapshot&&t!==void 0){let e=t.source;if(e===a.MouseInteraction){let e=t.type;(e===o.Click||e===o.DblClick)&&d++}else e===a.Input&&f++}else if(e.type===i.Custom&&t!==void 0){let e=F(t.tag),n=P(t.payload);if(e===s.Error)p++;else if(e===s.Console)n?.level===`error`&&p++;else if(e===s.Navigation){let e=F(n?.url);e!==void 0&&h.add(e)}}}return{seq:e,firstTimestamp:l===1/0?0:l,lastTimestamp:u,eventCount:t.length,clickCount:d,keypressCount:f,errorCount:p,hasFullSnapshot:m,urls:[...h],...n!==void 0&&n.length>0?{distinctId:n}:{},...c===void 0?{}:{user:{...c}},...Object.keys(r).length===0?{}:{sessionAttributes:{...r}}}}function I(e=Date.now){let t=e(),n=new Uint8Array(/* @__PURE__ */ new ArrayBuffer(16));pe(n),n[0]=Math.floor(t/2**40)&255,n[1]=Math.floor(t/2**32)&255,n[2]=Math.floor(t/2**24)&255,n[3]=Math.floor(t/2**16)&255,n[4]=Math.floor(t/256)&255,n[5]=t&255,n[6]=(n[6]??0)&15|112,n[8]=(n[8]??0)&63|128;let r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function pe(e){let t=globalThis.crypto;if(typeof t?.getRandomValues==`function`){t.getRandomValues(e);return}for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}const me=`lf_session_replay`;var he=class{idleTimeoutMs;maxDurationMs;now;storage;memorySession;pendingSession;persistenceTimer;constructor(e){this.idleTimeoutMs=e.idleTimeoutMs,this.maxDurationMs=e.maxDurationMs,this.now=e.now??Date.now,this.storage=e.storage===void 0?L():e.storage}getSession(){let e=this.now();if(this.memorySession!==void 0&&!this.isExpired(this.memorySession,e))return this.memorySession;let t=this.read();return t!==void 0&&!this.isExpired(t,e)?t:this.createSession(e)}touch(){let e=this.now(),t={...this.getSession(),lastActivityAt:e};return this.memorySession=t,this.scheduleWrite(t),t}reset(){return this.createSession(this.now())}flushPendingStorage(){this.persistenceTimer!==void 0&&(clearTimeout(this.persistenceTimer),this.persistenceTimer=void 0);let e=this.pendingSession;this.pendingSession=void 0,e!==void 0&&this.writeNow(e)}isExpired(e,t){return t-e.lastActivityAt>this.idleTimeoutMs||t-e.startedAt>this.maxDurationMs}createSession(e){let t={id:I(this.now),startedAt:e,lastActivityAt:e};return this.flushPendingStorage(),this.writeNow(t),t}read(){if(this.storage!==null)try{let e=this.storage.getItem(me);if(e!==null){let t=JSON.parse(e);if(ge(t))return this.memorySession=t,t}}catch{return this.memorySession}return this.memorySession}write(e){if(this.memorySession=e,this.storage!==null)try{this.storage.setItem(me,JSON.stringify(e))}catch{}}scheduleWrite(e){this.pendingSession=e,this.persistenceTimer===void 0&&(this.persistenceTimer=setTimeout(()=>{this.persistenceTimer=void 0;let e=this.pendingSession;this.pendingSession=void 0,e!==void 0&&this.writeNow(e)},1e3))}writeNow(e){this.memorySession=e,this.write(e)}};function L(){try{return globalThis.sessionStorage??null}catch{return null}}function ge(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.startedAt==`number`&&Number.isFinite(t.startedAt)&&typeof t.lastActivityAt==`number`&&Number.isFinite(t.lastActivityAt)}var R=class extends Error{droppedSeqs;reason;seq;sessionId;status;constructor(e){super(_e(e),{cause:e.cause}),this.name=`ReplayUploadError`,this.droppedSeqs=Object.freeze([...e.droppedSeqs??[]]),this.reason=e.reason,this.seq=e.seq,this.sessionId=e.sessionId,this.status=e.status}};function _e(e){let t=e.seq===void 0?`replay chunk`:`replay chunk seq=${String(e.seq)}`,n=e.cause instanceof Error?`: ${e.cause.message}`:``;return`${t} ${e.reason}${n}`}const z=`lf_session_replay_seq`,B=1e4,ve=3e4,ye={gzip:t,gzipSync:n};var be=class{buffer=[];bufferHasFullSnapshot=!1;pendingBytes=0;seq=0;timer;nextFlushAt;lastUserActivityAt;startedAt;started=!1;held;heldBufferIncomplete=!1;minimumBufferIncomplete=!1;minimumDurationSatisfied=!1;firstObservedTimestamp;lastObservedTimestamp;refreshingMinimumSnapshot=!1;mode;queue=[];retainedBytes=0;activeUpload;drainPromise;draining=!1;lifecycleFlights=/* @__PURE__ */ new Set;closed=!1;shuttingDown=!1;retryAbort=new AbortController;deadlineAbort=new AbortController;resyncPending=!1;resyncTimer;lastResyncAt;reservedKeepaliveBytes=0;asyncCompressionAvailable=!0;config;compression;storage;sessionId;sessionAttributes;takeFullSnapshot;constructor(e,t,n,r=L(),i=ye,a={},o={}){this.config=e,this.sessionId=t,this.sessionAttributes=Object.freeze({...a}),this.mode=n,this.storage=r,this.compression=i,this.held=o.holdUntilActivity===!0&&n===`full`,this.takeFullSnapshot=o.takeFullSnapshot,this.minimumDurationSatisfied=e.minSessionDurationMs===0,this.seq=this.readPersistedSequence()??0,this.startedAt=this.config.now(),this.lastUserActivityAt=this.startedAt}start(){this.started||this.mode!==`full`||(this.started=!0,this.scheduleFlush())}add(e){this.minimumDurationSatisfied||(this.firstObservedTimestamp??=e.timestamp,this.lastObservedTimestamp=Math.max(this.lastObservedTimestamp??e.timestamp,e.timestamp)),d(e)&&(this.lastUserActivityAt=this.config.now());let t=U(e);if(this.resyncPending){this.addDuringResync(e,t);return}if(this.refreshingMinimumSnapshot){this.buffer.push(e),this.pendingBytes+=t;return}let n=!this.minimumDurationSatisfied;if(this.mode===`buffer`||this.held||n){if(e.type===i.Meta){this.buffer=[e],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=t,n&&(this.mode===`full`&&(this.firstObservedTimestamp=e.timestamp),this.finishMinimumBufferingEvent());return}if(e.type===i.FullSnapshot){let r=!this.bufferHasFullSnapshot&&this.buffer.length===1&&this.buffer[0]?.type===i.Meta?this.buffer[0]:void 0;this.buffer=r===void 0?[e]:[r,e],this.bufferHasFullSnapshot=!0,this.pendingBytes=t+(r===void 0?0:U(r)),this.heldBufferIncomplete=!1,this.minimumBufferIncomplete=!1,n&&(this.mode===`full`&&(this.firstObservedTimestamp=r?.timestamp??e.timestamp),this.finishMinimumBufferingEvent());return}if(!this.bufferHasFullSnapshot||t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held,this.minimumBufferIncomplete||=n,n&&this.finishMinimumBufferingEvent();return}if(this.pendingBytes+t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held,this.minimumBufferIncomplete||=n,n&&this.finishMinimumBufferingEvent();return}}if(e.type===i.Meta&&this.mode===`full`&&this.buffer.length>0&&this.flushAndReport(),this.buffer.push(e),this.pendingBytes+=t,n&&this.minimumDurationReached()){this.flushAndReport();return}this.mode===`full`&&this.pendingBytes>=this.config.maxBufferBytes&&e.type!==i.Meta?this.flushAndReport():this.scheduleFlush()}addDuringResync(e,t){if(e.type===i.Meta){this.buffer=[e],this.pendingBytes=t;return}if(e.type!==i.FullSnapshot)return;let n=this.buffer.length===1&&this.buffer[0]?.type===i.Meta?this.buffer[0]:void 0;this.buffer=n===void 0?[e]:[n,e],this.pendingBytes=t+(n===void 0?0:U(n)),this.resyncPending=!1,this.clearResyncTimer(),this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush()}async triggerFlush(){return this.mode===`buffer`&&(this.bufferHasFullSnapshot||(this.buffer=[],this.pendingBytes=0),this.mode=`full`,this.start()),this.flush()}async flush(e={}){return this.flushInternal(e)}async flushInternal(e={}){if(this.closed||this.mode===`buffer`||this.held||this.buffer.length===0||!this.minimumDurationReached()||(this.clearScheduledFlush(),this.minimumBufferIncomplete&&!this.refreshMinimumBuffer()))return;this.minimumDurationSatisfied=!0;let t=this.buffer,n=this.pendingBytes;this.buffer=[],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=0;let r=this.sessionId,i=this.snapshotIdentity();if(e.keepalive===!0){let e=Ee(t),n=this.allocateSeq(e.length),a=this.deliverLifecycle(e,n,r,i);this.lifecycleFlights.add(a);let o=()=>{this.lifecycleFlights.delete(a)};a.then(o,o),await a;return}await this.enqueue(t,n,r,i)?.done}async shutdown(e={}){if(this.started=!1,this.clearScheduledFlush(),this.held||!this.minimumDurationReached()){this.discard(),await this.settleWithinDeadline([]);return}if(e.keepalive===!0){await this.flush(e),this.closed=!0,this.clearResyncTimer(),await this.settleWithinDeadline([]);return}let t=this.flushInternal();this.closed=!0,this.shuttingDown=!0,this.clearResyncTimer(),this.retryAbort.abort();let n=this.queue.filter(e=>e!==this.activeUpload).map(async e=>this.finalAttempt(e));await this.settleWithinDeadline([t,...n])}discard(){this.started=!1,this.closed=!0,this.clearScheduledFlush(),this.clearResyncTimer(),this.buffer=[],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=0}getMode(){return this.mode}isHeld(){return this.held}releaseHeld(e){this.held&&((this.heldBufferIncomplete||!this.bufferHasFullSnapshot)&&(this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,e()),this.held=!1,this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush())}flushAndReport(){this.flushInternal().catch(e=>{V(this.config.onError,e)})}scheduleFlush(){let e=this.config.now(),t=Math.max(0,this.config.minSessionDurationMs-(e-this.startedAt)),n=Math.max(f(this.config.flushIntervalMs,e-this.lastUserActivityAt),t);this.scheduleFlushIn(e,n)}scheduleFlushIn(e,t){if(!this.started||this.mode!==`full`||this.held||this.buffer.length===0)return;let n=e+t;this.timer!==void 0&&this.nextFlushAt!==void 0&&this.nextFlushAt<=n||(this.clearScheduledFlush(),this.nextFlushAt=n,this.timer=setTimeout(()=>{this.timer=void 0,this.nextFlushAt=void 0,this.flushAndReport()},t))}clearScheduledFlush(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0),this.nextFlushAt=void 0}minimumDurationReached(){return this.minimumDurationSatisfied||this.config.minSessionDurationMs===0?!0:this.firstObservedTimestamp===void 0||this.lastObservedTimestamp===void 0?!1:this.lastObservedTimestamp-this.firstObservedTimestamp>=this.config.minSessionDurationMs}finishMinimumBufferingEvent(){this.minimumDurationReached()?this.flushAndReport():this.scheduleFlush()}refreshMinimumBuffer(){let e=this.buffer.length,t=this.pendingBytes;if(this.takeFullSnapshot!==void 0){this.refreshingMinimumSnapshot=!0;try{this.takeFullSnapshot()}catch(e){V(this.config.onError,e)}finally{this.refreshingMinimumSnapshot=!1}}return this.buffer.slice(e).some(e=>e.type===i.FullSnapshot)?(this.minimumBufferIncomplete=!1,!0):(this.buffer.length=e,this.pendingBytes=t,!1)}snapshotIdentity(){let e=this.snapshotUser(),t=this.config.distinctId;if(this.config.getDistinctId!==void 0)try{t=this.config.getDistinctId()??this.config.distinctId}catch(e){V(this.config.onError,e)}else e!==void 0&&(t=e.id);return{distinctId:t,user:e}}createEnvelope(e,t,n){return{version:1,meta:fe(t,e,n.distinctId,this.sessionAttributes,n.user),events:e}}snapshotUser(){if(this.config.getUser!==void 0)try{return de(this.config.getUser())}catch(e){V(this.config.onError,e);return}}allocateSeq(e){let t=this.seq;return this.seq+=e,this.saveSeq(this.sessionId,this.seq),t}enqueue(e,t,n,r){let a=Math.max(2e6,2*this.config.maxBufferBytes);if(this.queue.length>0&&this.retainedBytes+t>a){V(this.config.onError,new R({cause:/* @__PURE__ */ Error(`replay upload queue is full`),reason:`not-sent`,seq:void 0,sessionId:n})),this.beginResync();return}let o=()=>void 0,s={body:void 0,done:new Promise(e=>{o=e}),events:e,hasFullSnapshot:e.some(e=>e.type===i.FullSnapshot),identity:r,reachedFetch:!1,resolve:o,retainedBytes:t,seq:this.allocateSeq(1),sessionId:n,settled:!1};return this.queue.push(s),this.retainedBytes+=t,this.draining||(this.draining=!0,this.drainPromise=this.drain()),s}async drain(){try{for(;!this.shuttingDown;){let e=this.queue[0];if(e===void 0)break;this.activeUpload=e;let t=await this.deliverQueued(e);this.activeUpload=void 0,this.settle(e,t)}}finally{this.activeUpload=void 0,this.draining=!1}}async deliverQueued(e){let t=await this.compressQueued(e);if(t!==void 0||e.settled)return t;let n=Date.now(),r;for(let t=1;;t++){let i=ve-(Date.now()-n);if(t>1&&i<=0)return W(r,e.reachedFetch);let a=await this.attemptQueued(e,Math.min(B,i));if(a===void 0)return;r=a;let o=Ae(a,t,this.config.random);if(o===void 0||this.shuttingDown||Date.now()-n+o>=ve)return W(a,e.reachedFetch);await this.backoff(o)}}async compressQueued(e){if(e.body!==void 0||e.events===void 0)return;let t=e.events;try{let n=r(JSON.stringify(this.createEnvelope(t,e.seq,e.identity))),i=this.shuttingDown?this.compression.gzipSync(n):await this.compressOrdinary(n);if(e.events!==t)return await this.compressQueued(e);e.settled||(this.retainedBytes+=i.byteLength-e.retainedBytes,e.retainedBytes=i.byteLength,e.body=i,e.events=void 0);return}catch(e){return{cause:e,reason:`not-sent`}}}async attemptQueued(e,t=B){let n=e.body;if(n!==void 0)try{await this.send({body:n,requestKeepalive:!1,reservedBytes:0,seq:e.seq,sessionId:e.sessionId},()=>{e.reachedFetch=!0},t);return}catch(e){return e}}async finalAttempt(e){let t=await this.compressQueued(e);if(t!==void 0){this.settle(e,t);return}let n=await this.attemptQueued(e);this.settle(e,n===void 0?void 0:W(n,e.reachedFetch))}async settleWithinDeadline(e){let t=Promise.all([...e,this.drainPromise,...this.lifecycleFlights]).then(()=>void 0,()=>void 0),n,r=new Promise(e=>{n=setTimeout(e,B)});if(await Promise.race([t,r]),clearTimeout(n),this.shuttingDown){this.deadlineAbort.abort(/* @__PURE__ */ Error(`replay upload did not finish before shutdown`));for(let e of[...this.queue])this.settle(e,{cause:/* @__PURE__ */ Error(`replay upload did not finish before shutdown`),reason:e.reachedFetch?`unconfirmed`:`not-sent`})}}settle(e,t){if(e.settled)return;e.settled=!0,this.retainedBytes-=e.retainedBytes;let n=this.queue.indexOf(e);n>=0&&this.queue.splice(n,1),e.body=void 0,e.events=void 0,e.resolve(),t!==void 0&&this.handleSequencedLoss(e.seq,e.sessionId,t)}handleSequencedLoss(e,t,n){let r=[];if(!this.shuttingDown){let t=!1;for(let n of[...this.queue])if(!(n.seq<e)){if(n.events===void 0){if(n.hasFullSnapshot){t=!0;break}continue}if(n.hasFullSnapshot){let e=we(n.events),r=Te(e);this.retainedBytes+=r-n.retainedBytes,n.retainedBytes=r,n.events=e,t=!0;break}r.push(n.seq),this.settle(n,void 0)}!t&&!this.trimBufferToAnchor()&&this.beginResync()}V(this.config.onError,new R({cause:n.cause,droppedSeqs:r,reason:n.reason,seq:e,sessionId:t,status:n.status}))}trimBufferToAnchor(){return this.buffer.some(e=>e.type===i.FullSnapshot)?(this.buffer=we(this.buffer),this.pendingBytes=Te(this.buffer),!0):!1}beginResync(){this.closed||(this.resyncPending=!0,this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,this.clearScheduledFlush(),this.scheduleResyncSnapshot())}scheduleResyncSnapshot(){if(this.resyncTimer!==void 0||this.closed)return;let e=this.lastResyncAt===void 0?0:Math.max(0,this.lastResyncAt+6e4-this.config.now());this.resyncTimer=setTimeout(()=>{this.resyncTimer=void 0,this.takeResyncSnapshot()},e)}takeResyncSnapshot(){if(this.resyncPending&&!this.closed&&this.takeFullSnapshot!==void 0){this.lastResyncAt=this.config.now();try{this.takeFullSnapshot()}catch(e){V(this.config.onError,e),this.scheduleResyncSnapshot();return}this.isResyncPending()&&(V(this.config.onError,/* @__PURE__ */ Error(`replay resync snapshot produced no full snapshot`)),this.scheduleResyncSnapshot())}}isResyncPending(){return this.resyncPending}clearResyncTimer(){this.resyncTimer!==void 0&&(clearTimeout(this.resyncTimer),this.resyncTimer=void 0)}async backoff(e){let t=this.retryAbort.signal;t.aborted||await new Promise(n=>{let r=()=>{clearTimeout(i),t.removeEventListener(`abort`,r),n()},i=setTimeout(r,e);t.addEventListener(`abort`,r)})}async deliverLifecycle(e,t,n,i){let a=[];for(let o=0;o<e.length;o++){let s=e[o];if(s===void 0){a.push(void 0);continue}let c=this.createEnvelope(s,t+o,i);try{a.push({body:this.compression.gzipSync(r(JSON.stringify(c))),requestKeepalive:!1,reservedBytes:0,seq:t+o,sessionId:n})}catch(e){this.handleSequencedLoss(t+o,n,{cause:e,reason:`not-sent`}),a.push(void 0)}}let o=!0,s=Math.max(0,48e3-this.reservedKeepaliveBytes);for(let e of a){if(e===void 0){o=!1;continue}o&&e.body.byteLength<=s?(e.requestKeepalive=!0,e.reservedBytes=e.body.byteLength,this.reservedKeepaliveBytes+=e.reservedBytes,s-=e.reservedBytes):o=!1}await Promise.all(a.map(async e=>{if(e===void 0)return;let t=!1;try{await this.send(e,()=>{t=!0})}catch(n){this.handleSequencedLoss(e.seq,e.sessionId,W(n,t))}}))}async compressOrdinary(e){if(!this.asyncCompressionAvailable)return this.compression.gzipSync(e);try{return await De(this.compression,e)}catch{return this.asyncCompressionAvailable=!1,this.compression.gzipSync(e)}}async send(e,t,n=B){let r,i,a,o=new AbortController,s=setTimeout(()=>{o.abort(/* @__PURE__ */ Error(`replay upload timed out after ${String(n)}ms`))},n),c=this.deadlineAbort.signal,l=()=>{o.abort(c.reason)};c.addEventListener(`abort`,l);try{let n=`${this.config.replayUrl.replace(/\/+$/u,``)}/${encodeURIComponent(e.sessionId)}?seq=${String(e.seq)}`,s=await Ce(this.getUploadHeaders(),o.signal);t();let c=this.config.fetchImpl(n,{method:`POST`,headers:s,body:e.body.slice(),keepalive:e.requestKeepalive,signal:o.signal});r=!0;let l=await c;if(i=!0,a=await Oe(l),!l.ok){let e=l.status===429||l.status===503?je(l.headers.get(`retry-after`),Date.now()):void 0;throw new H(l.status,e)}}finally{clearTimeout(s),c.removeEventListener(`abort`,l),e.reservedBytes>0&&(r!==!0||i!==!0||a===!0)&&(this.reservedKeepaliveBytes=Math.max(0,this.reservedKeepaliveBytes-e.reservedBytes))}}async getUploadHeaders(){let e=this.config.headers===void 0?{}:await this.config.headers(),t=await Se(this.config.token);return{...t===void 0||t.length===0?e:{...Object.fromEntries(Object.entries(e).filter(([e])=>e.toLowerCase()!==`authorization`)),Authorization:`Bearer ${t}`},"Content-Type":`application/json`,"Content-Encoding":`gzip`}}canResumeSequence(){return this.readPersistedSequence()===this.seq}readPersistedSequence(){if(this.storage!==null)try{let e=this.storage.getItem(z);if(e===null)return;let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let n=t;return n.id===this.sessionId&&typeof n.seq==`number`&&Number.isSafeInteger(n.seq)&&n.seq>=0?n.seq:void 0}catch{return}}saveSeq(e,t){if(this.storage!==null)try{this.storage.setItem(z,JSON.stringify({id:e,seq:t}))}catch{}}};function V(e,t){try{let n=e?.(t);xe(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function xe(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}var H=class extends Error{retryAfter;status;constructor(e,t){super(`replay ingest failed: ${String(e)}`),this.status=e,this.retryAfter=t,this.name=`ReplayIngestError`}};async function Se(e){return typeof e==`function`?e():e}async function Ce(e,t){if(t.aborted)throw t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e instanceof Error?e:Error(String(e)))})})}function U(e){try{return r(JSON.stringify(e)).byteLength}catch{return 0}}function we(e){let t=e.findIndex(e=>e.type===i.FullSnapshot);if(t<0)return e;let n=t>0&&e[t-1]?.type===i.Meta?t-1:t;return e.slice(n)}function Te(e){return e.reduce((e,t)=>e+U(t),0)}function Ee(e){let t=[],n=[],r=0;for(let i of e){let e=U(i);n.length>0&&r+e>48e3&&(t.push(n),n=[],r=0),n.push(i),r+=e}return n.length>0&&t.push(n),t}async function De(e,t){return new Promise((n,r)=>{let i=[];typeof window<`u`&&i.push(window),typeof document<`u`&&i.push(document);let a=()=>{for(let e of i)e.removeEventListener(`securitypolicyviolation`,s)},o=(e,t)=>{if(a(),e!==null){r(e);return}n(t)},s=e=>{let t=e;(t.effectiveDirective.includes(`worker-src`)||t.violatedDirective.includes(`worker-src`))&&o(/* @__PURE__ */ Error(`replay compression worker blocked by Content Security Policy`))};for(let e of i)e.addEventListener(`securitypolicyviolation`,s);try{e.gzip(t,{level:6},(e,t)=>{o(e,t)})}catch(e){a(),r(e instanceof Error?e:Error(String(e)))}})}async function Oe(e){if(e.body===null)return!0;try{return await e.body.cancel(),!0}catch{return!1}}function ke(e){return e===408||e===425||e===429||e>=500}function Ae(e,t,n){if(e instanceof H&&!ke(e.status))return;let r=Math.min(8e3,500*2**(t-1)),i=Math.round(r*(1-.5*n())),a=e instanceof H?e.retryAfter:void 0;return a===void 0?i:Math.max(a,i)}function W(e,t){let n=e instanceof H?e.status:void 0;return n!==void 0&&!ke(n)?{cause:e,reason:`rejected`,status:n}:{cause:e,reason:t?`unconfirmed`:`not-sent`,status:n}}function je(e,t){if(e===null)return;let n=e.trim();if(/^\d+$/u.test(n)){let e=Number(n);return Number.isSafeInteger(e)?e*1e3:void 0}let r=Fe(n,t);return r===void 0?void 0:Math.max(0,r-t)}const Me=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Ne=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],Pe=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function Fe(e,t){let n=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(n!==null)return G(n[1],n[2],n[3],n[4],n[5],n[6],n[7]);let r=/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(r!==null){let e=new Date(t).getUTCFullYear(),n=Number(r[4]),i=Math.floor(e/100)*100+n;return i>e+50&&(i-=100),G(r[1],r[2],r[3],String(i),r[5],r[6],r[7])}let i=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{2}| \d) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/u.exec(e);if(i!==null)return G(i[1],i[3]?.trim(),i[2],i[7],i[4],i[5],i[6])}function G(e,t,n,r,i,a,o){let s=Number(t),c=Me.indexOf(n),l=Number(r),u=Number(i),d=Number(a),f=Number(o);if(c<0||s<1||s>31||u>23||d>59||f>59)return;let p=/* @__PURE__ */ new Date(0);if(p.setUTCFullYear(l,c,s),p.setUTCHours(u,d,f,0),p.getUTCFullYear()!==l||p.getUTCMonth()!==c||p.getUTCDate()!==s||p.getUTCHours()!==u||p.getUTCMinutes()!==d||p.getUTCSeconds()!==f)return;let m=Ne.indexOf(e),h=Pe.indexOf(e);return(m>=0?m:h)===p.getUTCDay()?p.getTime():void 0}const Ie=`lf_session_replay_recording`,K=`lf_session_replay_recording_owner`;var Le=class{state;storage;owner;now;maxDurationMs;readOpenerState;constructor(e,t,n,r=()=>null){this.storage=e,this.now=t,this.owner=I(t),this.maxDurationMs=Math.min(n,72e5),this.readOpenerState=r;try{e?.getItem(`lf_session_replay_recording_owner`)===null&&(this.state=this.readResumableState()),e?.setItem(K,this.owner),e?.getItem(`lf_session_replay_recording_owner`)!==this.owner&&(this.storage=null,this.state=void 0)}catch{this.storage=null,this.state=void 0}}get(e){if(this.state!==void 0&&this.isCurrent(this.state.id,e))return this.state.id;this.state={id:I(this.now),rumSessionId:e,startedAt:this.now()};try{this.storage?.setItem(Ie,JSON.stringify(this.state))}catch{}return this.state.id}isCurrent(e,t){let n=this.state;if(n===void 0)return!1;let r=this.now();return n.id===e&&n.rumSessionId===t&&r>=n.startedAt&&r-n.startedAt<this.maxDurationMs}release(){try{this.storage?.getItem(`lf_session_replay_recording_owner`)===this.owner&&this.storage.removeItem(K)}catch{}}resume(){try{this.state=this.storage?.getItem(`lf_session_replay_recording_owner`)===null?this.readResumableState():void 0,this.storage?.setItem(K,this.owner),this.storage?.getItem(`lf_session_replay_recording_owner`)!==this.owner&&(this.state=void 0,this.storage=null)}catch{this.state=void 0,this.storage=null}}readResumableState(){let e=this.storage?.getItem(Ie),t=this.storage?.getItem(z);if(e==null||t==null)return;let n=null;try{n=this.readOpenerState()}catch{}if(n!==e)return Re(e,t)}};function Re(e,t){let n=JSON.parse(e),r=JSON.parse(t);if(typeof n!=`object`||!n||typeof r!=`object`||!r)return;let i=n,a=r;if(!(typeof i.id!=`string`||i.id.length===0||typeof i.rumSessionId!=`string`||typeof i.startedAt!=`number`||!Number.isFinite(i.startedAt)||a.id!==i.id||typeof a.seq!=`number`||!Number.isSafeInteger(a.seq)||a.seq<0))return{id:i.id,rumSessionId:i.rumSessionId,startedAt:i.startedAt}}function ze(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Be(e){let t=e.random??Math.random;return t()<ze(e.sessionSampleRate)?`full`:t()<ze(e.onErrorSampleRate)?`buffer`:`off`}const Ve=/^[a-z][a-z0-9_]{0,63}$/u;function He(e,t){let n=0;for(let r of e)if(n+=+(r.length>0),n>t)return!1;return!0}function Ue(e,t){if(e===void 0)return Object.freeze({});let n;try{n=e()}catch(e){return t(e),Object.freeze({})}if(typeof n!=`object`||!n||Array.isArray(n))return Object.freeze({});let r;try{r=Object.getPrototypeOf(n)}catch(e){return t(e),Object.freeze({})}if(r!==Object.prototype&&r!==null)return Object.freeze({});let i;try{i=Object.keys(n)}catch(e){return t(e),Object.freeze({})}let a={},o=0;for(let e of i){if(!Ve.test(e))continue;let r;try{r=Reflect.get(n,e)}catch(e){t(e);continue}if((typeof r==`boolean`||typeof r==`number`&&Number.isFinite(r)||typeof r==`string`&&He(r,200))&&(Object.defineProperty(a,e,{configurable:!0,enumerable:!0,value:r,writable:!0}),o+=1,o===20))break}return Object.freeze(a)}const We={mode:`off`,recording:!1,getSessionId:()=>``,captureError:()=>void 0,getRecordingId:()=>``,flush:async()=>Promise.resolve(),stop:async()=>Promise.resolve()},Ge=`lf_session_replay_mode`,q=Symbol.for(`@pydantic/logfire-session-replay/controller`);function Ke(e){if(typeof window>`u`||typeof document>`u`)return We;let t=nt();try{let n=Je(e),r=new he({idleTimeoutMs:n.sessionIdleTimeoutMs,maxDurationMs:n.maxSessionDurationMs,now:n.now}),i=r.getSession().id,a=e=>{let t;try{t=n.getSessionId?.()}catch(e){return Z(n.onError,e),i}if(t!==void 0&&t.length>0)return i=t,t;let a=e?r.touch().id:r.getSession().id;return i=a,a},o=L(),s=new Le(o,n.now,n.maxSessionDurationMs,()=>window.opener?.sessionStorage.getItem(`lf_session_replay_recording`)??null),c=a(!1),l=s.get(c),u,d=!1,f=!1,p=0,m=!0,h=Promise.resolve(),g=Promise.resolve(),_,v=(e,t,r=!t)=>{let i=Ye(n,e,o);if(!(i===`off`||d||f||u!==void 0||e!==c))try{let t=l;u=qe({config:n,getSessionId:a,mode:i,onSessionChanged:y,samplingModeStorage:o,sessionId:e,recordingId:t,isCurrentRecording:()=>s.isCurrent(t,a(!1)),holdUntilActivity:r})}catch(e){if(u=void 0,t)throw e;Z(n.onError,e)}},y=(e,t=!0)=>{if(d||f)return;let r=s.get(e);if(e===c&&r===l)return;c=e,l=r;let i=u;u=void 0;let a=i?.deactivate()??Promise.resolve(),o=p;h=h.then(async()=>{await X(a,n.onError),!d&&p===o&&c===e&&l===r&&v(e,!1,t)})},b;try{v(c,!0),b=setInterval(()=>{y(a(!1))},1e3)}catch(e){throw u?.discard(),u=void 0,s.release(),e}let x=()=>{f=!0,p+=1;let e=u;u=void 0;let t=e?.deactivate(!0)??Promise.resolve();g=Promise.all([g,h,X(t,n.onError)]).then(()=>void 0),h=Promise.resolve(),m=e?.transport.canResumeSequence()??m,m&&s.release()},S=e=>{if(!e.persisted||d)return;u?.discard(),u=void 0;let t=p;h=h.then(async()=>{await new Promise(e=>{setTimeout(e,0)}),!(d||p!==t)&&(f=!1,s.resume(),c=a(!1),l=s.get(c),m=!0,v(c,!1,!1))})};return window.addEventListener(`pagehide`,x),window.addEventListener(`pageshow`,S),{get mode(){try{return u?.transport.getMode()??`off`}catch(e){return Z(n.onError,e),`off`}},get recording(){try{return u!==void 0}catch(e){return Z(n.onError,e),!1}},getSessionId:()=>a(!1),captureError:(e,t)=>{try{u?.captureError(e,t)}catch(e){Z(n.onError,e)}},getRecordingId:()=>u!==void 0&&s.isCurrent(u.recordingId,a(!1))?u.recordingId:``,flush:async()=>{try{await h,await u?.transport.flush()}catch(e){Z(n.onError,e)}},stop:async()=>(_??=(async()=>{d=!0,p+=1,clearInterval(b),window.removeEventListener(`pagehide`,x),window.removeEventListener(`pageshow`,S);let e=u;u=void 0,await X(e?.deactivate()??Promise.resolve(),n.onError),await h,await g,r.flushPendingStorage(),m=e?.transport.canResumeSequence()??m,m&&s.release(),t()})(),_)}}catch(e){throw t(),e}}function qe(e){let{config:t,getSessionId:n,holdUntilActivity:r,mode:i,onSessionChanged:a,samplingModeStorage:o,sessionId:c,recordingId:l,isCurrentRecording:u}=e,f=Ue(t.getSessionAttributes,e=>{Z(t.onError,e)}),p,m=new be(t,l,i,void 0,void 0,f,{holdUntilActivity:r,takeFullSnapshot:()=>{p.takeFullSnapshot()}}),h=[],g=!0,_=()=>g,x;try{p=ce({beforeUserActivity:()=>{if(g&&m.isHeld())try{let e=n(!0);if(e!==c||!u()){a(e,!1);return}m.releaseHeld(()=>{p.takeFullSnapshot()})}catch(e){Z(t.onError,e)}},emit:e=>{if(g)try{let t=n(d(e));if(t!==c||!u()){a(t,!1);return}m.add(e)}catch(e){Z(t.onError,e)}},maskAllText:t.maskAllText,maskAllInputs:t.maskAllInputs,maskTextSelector:t.maskTextSelector,blockSelector:t.blockSelector,checkoutEveryNms:i===`buffer`?12e4:Math.max(3e5,t.minSessionDurationMs),redactUrlPatterns:t.redactUrlPatterns}),h.push(()=>{p.stop()});let e=(e,n)=>{if(g)try{p.addCustomEvent(e,n)}catch(e){Z(t.onError,e)}},r=n=>{_()&&(m.releaseHeld(()=>{p.takeFullSnapshot()}),e(s.Error,n),_()&&m.getMode()===`buffer`&&(Ze(o,c,`full`),Y(m.triggerFlush(),t.onError)))},f=/* @__PURE__ */ new WeakSet,S=e=>typeof e!=`object`||!e||!f.has(e)&&(f.add(e),!0),C=(e,t)=>{if(S(e)){let n=$($e(e),void 0,J(e));r(typeof t?.timestamp==`number`?{...n,timestamp:t.timestamp}:n)}},w=e=>{e instanceof ErrorEvent&&S(e.error)&&r($(e.message,e.filename,J(e.error)))},T=e=>{C(e.reason)},E=()=>{document.visibilityState===`hidden`&&Y(m.flush({keepalive:!0}),t.onError)},D=()=>{Y(m.flush({keepalive:!0}),t.onError)};return t.captureGlobalErrors&&(window.addEventListener(`error`,w,!0),h.push(()=>{window.removeEventListener(`error`,w,!0)}),window.addEventListener(`unhandledrejection`,T,!0),h.push(()=>{window.removeEventListener(`unhandledrejection`,T,!0)})),document.addEventListener(`visibilitychange`,E),h.push(()=>{document.removeEventListener(`visibilitychange`,E)}),window.addEventListener(`pagehide`,D),h.push(()=>{window.removeEventListener(`pagehide`,D)}),t.captureConsole&&h.push(v(e,{onError:t.onError})),t.captureNetwork&&h.push(y(e,{ignoreUrlPatterns:t.ignoreUrlPatterns,now:t.now,onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),t.captureNavigation&&h.push(b(e,{onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),m.start(),{sessionId:c,recordingId:l,transport:m,captureError:C,deactivate:async(e=!1)=>(x??=(async()=>{let t=m.shutdown({keepalive:e});g=!1,Q(h),await t})(),x),discard:()=>{g=!1,Q(h),m.discard()}}}catch(e){throw g=!1,Q(h),m.discard(),e}}function Je(e){if(e.replayUrl.length===0)throw Error("logfire session replay: `replayUrl` is required");let t=new URL(e.replayUrl,`https://logfire.invalid/`);if(t.search!==``||t.hash!==``)throw Error("logfire session replay: `replayUrl` must not contain a query or fragment");let n=e.fetchImpl??(typeof fetch==`function`?fetch.bind(globalThis):void 0);if(n===void 0)throw Error("logfire session replay: no `fetch` available; pass `fetchImpl`");return{replayUrl:e.replayUrl,headers:e.headers,token:e.token,getSessionId:e.getSessionId,getSessionAttributes:e.getSessionAttributes,sessionSampleRate:e.sessionSampleRate??l.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate??l.onErrorSampleRate,maskAllText:e.maskAllText??l.maskAllText,maskAllInputs:e.maskAllInputs??l.maskAllInputs,maskTextSelector:e.maskTextSelector??l.maskTextSelector,blockSelector:e.blockSelector??l.blockSelector,flushIntervalMs:e.flushIntervalMs??l.flushIntervalMs,maxBufferBytes:e.maxBufferBytes??l.maxBufferBytes,minSessionDurationMs:e.minSessionDurationMs??l.minSessionDurationMs,sessionIdleTimeoutMs:e.sessionIdleTimeoutMs??l.sessionIdleTimeoutMs,maxSessionDurationMs:e.maxSessionDurationMs??l.maxSessionDurationMs,distinctId:e.distinctId??l.distinctId,getDistinctId:e.getDistinctId,getUser:e.getUser,captureConsole:e.captureConsole??l.captureConsole,captureNetwork:e.captureNetwork??l.captureNetwork,captureNavigation:e.captureNavigation??l.captureNavigation,captureGlobalErrors:e.captureGlobalErrors??l.captureGlobalErrors,ignoreUrlPatterns:e.ignoreUrlPatterns??[],redactUrlPatterns:e.redactUrlPatterns??[...l.redactUrlPatterns],onError:e.onError,fetchImpl:n,now:e.now??Date.now,random:e.random??Math.random}}function Ye(e,t,n){let r=Xe(n,t);if(r!==void 0)return r;let i=Be({sessionSampleRate:e.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate,random:e.random});return Ze(n,t,i),i}function Xe(e,t){if(e!==null)try{let n=e.getItem(Ge);if(n===null)return;let r=JSON.parse(n);if(typeof r!=`object`||!r)return;let i=r;return i.id!==t||!Qe(i.mode)?void 0:i.mode}catch{return}}function Ze(e,t,n){if(e!==null)try{e.setItem(Ge,JSON.stringify({id:t,mode:n}))}catch{}}function Qe(e){return e===`full`||e===`buffer`||e===`off`}function $e(e){return rt(et(e,`message`)??e)}function J(e){let t=et(e,`stack`);return typeof t==`string`?t:void 0}function et(e,t){try{return typeof e==`object`&&e&&t in e?e[t]:void 0}catch{return}}function Y(e,t){e.catch(e=>{Z(t,e)})}async function X(e,t){try{await e}catch(e){Z(t,e)}}function Z(e,t){try{let n=e?.(t);tt(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function tt(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function nt(){let e=globalThis;if(e[q]!==void 0)throw Error(`logfire session replay: a replay controller is already active in this page`);let t={};Object.defineProperty(e,q,{configurable:!0,enumerable:!1,value:t,writable:!0});let n=!1;return()=>{n||(n=!0,e[q]===t&&Reflect.deleteProperty(e,q))}}function Q(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}e.length=0}function $(e,t,n){return{message:e,...t===void 0||t.length===0?{}:{source:t},...n===void 0?{}:{stack:n}}}function rt(e){if(e==null)return`unhandledrejection`;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return String(e);try{return Object.prototype.toString.call(e)}catch{return`[object Object]`}}export{c as CHUNK_ENVELOPE_VERSION,s as CustomTag,i as EventType,a as IncrementalSource,o as MouseInteractions,R as ReplayUploadError,Ke as startSessionReplay};
|
|
1
|
+
import{record as e}from"@rrweb/record";import{gzip as t,gzipSync as n,strToU8 as r}from"fflate";const i={DomContentLoaded:0,Load:1,FullSnapshot:2,IncrementalSnapshot:3,Meta:4,Custom:5,Plugin:6},a={Mutation:0,MouseMove:1,MouseInteraction:2,Scroll:3,ViewportResize:4,Input:5,TouchMove:6,MediaInteraction:7,Drag:12,Selection:14},o={MouseUp:0,MouseDown:1,Click:2,ContextMenu:3,DblClick:4},s={Error:`logfire.error`,Console:`logfire.console`,Network:`logfire.network`,Navigation:`logfire.navigation`},c=1,l={sessionSampleRate:1,onErrorSampleRate:1,maskAllText:!0,maskAllInputs:!0,maskTextSelector:``,blockSelector:``,flushIntervalMs:5e3,maxBufferBytes:1e6,minSessionDurationMs:1e4,sessionIdleTimeoutMs:18e5,maxSessionDurationMs:72e5,distinctId:``,captureConsole:!1,captureNetwork:!0,captureNavigation:!0,captureGlobalErrors:!0,redactUrlPatterns:[/.+/u]},u=/* @__PURE__ */ new Set([a.MouseMove,a.MouseInteraction,a.Scroll,a.ViewportResize,a.Input,a.TouchMove,a.MediaInteraction,a.Drag,a.Selection]);function d(e){return e.type!==i.IncrementalSnapshot||typeof e.data!=`object`||e.data===null||!(`source`in e.data)?!1:typeof e.data.source==`number`&&u.has(e.data.source)}function f(e,t){return t<3e4?e:t<3e5?Math.max(e,6e4):Math.max(e,3e5)}function p(e,t){return t.some(t=>new RegExp(t.source,t.flags).test(e))}function m(e,t,n){if(!p(e,t))return e;try{let t=new URL(e,n);return`${t.origin}${t.pathname}`}catch{let[t=e]=e.split(`?`),[n=t]=t.split(`#`);return n}}const h=[`log`,`info`,`warn`,`error`,`debug`],g=1024,_=()=>void 0;function v(e,t={}){let n=[],r=E(t.onError);try{for(let t of h)typeof console[t]==`function`&&n.push(O(console,t,(n,i)=>function(...a){return i()&&T(e,s.Console,{level:t,args:a.slice(0,10).map(j)},r),n.apply(this,a)}));return k(n)}catch(e){throw A(n),e}}function y(e,t){let n=C(t),r={...n,onError:E(n.onError)},i=x(e,r);try{return k([i,S(e,r)])}catch(e){throw i(),e}}function b(e,t={redactUrlPatterns:[]}){let n=E(t.onError),r=r=>{let i=m(window.location.href,t.redactUrlPatterns??[],window.location.href);T(e,s.Navigation,{url:i,kind:r},n)},i=[];try{i.push(O(history,`pushState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`push`),i})),i.push(O(history,`replaceState`,(e,t)=>function(...n){let i=e.apply(this,n);return t()&&r(`replace`),i}));let e=!0,t=()=>{e&&r(`pop`)};return window.addEventListener(`popstate`,t),i.push(()=>{e=!1,window.removeEventListener(`popstate`,t)}),k(i)}catch(e){throw A(i),e}}function x(e,t){return typeof window.fetch==`function`?O(window,`fetch`,(n,r)=>{let i=async function(i,a){let o=n;if(!r())return o.call(this,i,a);let c=t.now(),l=ee(i,a),u=te(i);if(ae(u,t.ignoreUrlPatterns))return o.call(this,i,a);let d=m(u,t.redactUrlPatterns,window.location.href),f=ie(a?.body);try{let n=await o.call(this,i,a);return r()&&T(e,s.Network,N({method:l,url:d,status:n.status,durationMs:Math.max(0,t.now()-c),reqBytes:f,resBytes:ne(n.headers)}),t.onError),n}catch(n){throw r()&&T(e,s.Network,N({method:l,url:d,status:0,durationMs:Math.max(0,t.now()-c),failed:!0,reqBytes:f}),t.onError),n}},a=Reflect.get(n,`__original`);return Object.defineProperty(i,"__original",{configurable:!0,value:typeof a==`function`?a:n,writable:!0}),i}):_}function S(e,t){let n=window.XMLHttpRequest.prototype,r=/* @__PURE__ */ new WeakMap,i=[];try{return i.push(O(n,`open`,(e,n)=>function(...i){let[a,o]=i;if(!n())return e.apply(this,i);let s=o.toString();return ae(s,t.ignoreUrlPatterns)?(r.delete(this),e.apply(this,i)):(r.set(this,{method:a.toUpperCase(),url:m(s,t.redactUrlPatterns,window.location.href),startedAt:0,reqBytes:0,failed:!1,emitted:!1}),e.apply(this,i))})),i.push(O(n,`send`,(n,i)=>function(...a){let[o]=a,c=i()?r.get(this):void 0;if(c===void 0)return n.apply(this,a);c.startedAt=t.now(),c.reqBytes=ie(o);let l=()=>{c.failed=!0},u=()=>{c.emitted||(c.emitted=!0,this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),i()&&T(e,s.Network,N({method:c.method,url:c.url,status:this.status,durationMs:Math.max(0,t.now()-c.startedAt),failed:c.failed||this.status===0,reqBytes:c.reqBytes,resBytes:re(this)}),t.onError))};this.addEventListener(`error`,l),this.addEventListener(`abort`,l),this.addEventListener(`timeout`,l),this.addEventListener(`loadend`,u,{once:!0});try{return n.apply(this,a)}catch(n){throw this.removeEventListener(`error`,l),this.removeEventListener(`abort`,l),this.removeEventListener(`timeout`,l),this.removeEventListener(`loadend`,u),i()&&T(e,s.Network,N({method:c.method,url:c.url,status:0,durationMs:Math.max(0,t.now()-c.startedAt),failed:!0,reqBytes:c.reqBytes}),t.onError),n}})),k(i)}catch(e){throw A(i),e}}function C(e){return{...e,ignoreUrlPatterns:w(e.ignoreUrlPatterns),redactUrlPatterns:w(e.redactUrlPatterns)}}function w(e){return e.map(e=>{let t=e.flags.replace(/[gy]/gu,``);return t===e.flags?e:new RegExp(e.source,t)})}function T(e,t,n,r){try{e(t,n)}catch(e){r?.(e)}}function E(e){let t=!1;return n=>{if(!t){t=!0;try{let t=e?.(n);D(t)&&Promise.resolve(t).catch(()=>void 0)}catch{}finally{t=!1}}}}function D(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function O(e,t,n){let r=e,i=r[t];if(typeof i!=`function`)return _;let a=!0,o=n(i,()=>a);return r[t]=o,()=>{a&&(a=!1,r[t]===o&&(r[t]=i))}}function k(e){let t=!1;return()=>{t||(t=!0,A(e))}}function A(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}}function j(e){if(e==null)return String(e);if(typeof e==`string`)return M(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(e instanceof Error)return M(e.stack??`${e.name}: ${e.message}`);try{return M(JSON.stringify(e))}catch{return Object.prototype.toString.call(e)}}function M(e){if(e.length<=g)return e;let t=e.charCodeAt(1023),n=t>=55296&&t<=56319?1023:g;return`${e.slice(0,n)}...(+${String(e.length-n)} chars)`}function ee(e,t){return(t?.method??(typeof e==`object`&&`method`in e?e.method:`GET`)).toUpperCase()}function te(e){return typeof e==`string`||e instanceof URL?e.toString():e.url}function ne(e){let t=e.get(`content-length`);if(t===null)return;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}function re(e){try{let t=e.getResponseHeader(`content-length`);if(t===null)return;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}catch{return}}function N(e){return{method:e.method,url:e.url,status:e.status,durationMs:e.durationMs,...e.failed===void 0?{}:{failed:e.failed},...e.reqBytes===void 0?{}:{reqBytes:e.reqBytes},...e.resBytes===void 0?{}:{resBytes:e.resBytes}}}function ie(e){if(e==null)return 0;if(typeof e==`string`)return new TextEncoder().encode(e).byteLength;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Blob)return e.size}function ae(e,t){return p(e,t)}const oe=/* @__PURE__ */ new Set([`action`,`formaction`,`href`,`src`]);function se(t){let n=()=>{t.beforeUserActivity?.()},r={emit:e=>{t.emit(ce(e,t.redactUrlPatterns))},maskAllInputs:t.maskAllInputs,recordCanvas:!1,collectFonts:!1,inlineImages:!1,recordCrossOriginIframes:!1,slimDOMOptions:`all`,hooks:{input:n,mediaInteaction:n,mouseInteraction:n,mousemove:n,scroll:n,selection:n,viewportResize:n},sampling:{mousemove:100,mouseInteraction:!0,scroll:250,media:800,input:`last`}};t.maskAllText?r.maskTextSelector=`*`:t.maskTextSelector!==void 0&&t.maskTextSelector.length>0&&(r.maskTextSelector=t.maskTextSelector),t.blockSelector!==void 0&&t.blockSelector.length>0&&(r.blockSelector=t.blockSelector),t.checkoutEveryNms!==void 0&&t.checkoutEveryNms>0&&(r.checkoutEveryNms=t.checkoutEveryNms);let i=e(r);if(i===void 0)throw Error(`logfire session replay: rrweb failed to start recording`);return{stop:()=>{i()},addCustomEvent:(t,n)=>{e.addCustomEvent(t,n)},takeFullSnapshot:()=>{e.takeFullSnapshot(!0)}}}function ce(e,t){if(typeof e.data!=`object`||e.data===null)return e;let n=e.data;if(e.type===i.Meta){if(typeof n.href!=`string`)return e;let r=m(n.href,t,window.location.href);return r===n.href?e:{...e,data:{...n,href:r}}}if(e.type!==i.FullSnapshot&&(e.type!==i.IncrementalSnapshot||n.source!==a.Mutation))return e;let r=P(n,t);return r===n?e:{...e,data:r}}function P(e,t){if(Array.isArray(e)){let n=!1,r=[];for(let i of e){let e=P(i,t);e!==i&&(n=!0),r.push(e)}return n?r:e}if(typeof e!=`object`||!e)return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){let n=e===`attributes`&&!Array.isArray(a)?le(a,t):P(a,t);n!==a&&(r=!0),i[e]=n}return r?i:e}function le(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){if(!oe.has(e.toLowerCase())||typeof a!=`string`){i[e]=a;continue}let n=m(a,t,window.location.href);n!==a&&(r=!0),i[e]=n}return r?i:e}function F(e){return typeof e==`object`&&e?e:void 0}function I(e){return typeof e==`string`&&e.length>0?e:void 0}function ue(e){let t=F(e),n=I(t?.id);if(t===void 0||n===void 0)return;let r=I(t.name),i=I(t.email);return{id:n,...r===void 0?{}:{name:r},...i===void 0?{}:{email:i}}}function de(e,t,n,r={},c){let l=1/0,u=0,d=0,f=0,p=0,m=!1,h=/* @__PURE__ */ new Set;for(let e of t){e.timestamp<l&&(l=e.timestamp),e.timestamp>u&&(u=e.timestamp);let t=F(e.data);if(e.type===i.FullSnapshot)m=!0;else if(e.type===i.Meta){let e=I(t?.href);e!==void 0&&h.add(e)}else if(e.type===i.IncrementalSnapshot&&t!==void 0){let e=t.source;if(e===a.MouseInteraction){let e=t.type;(e===o.Click||e===o.DblClick)&&d++}else e===a.Input&&f++}else if(e.type===i.Custom&&t!==void 0){let e=I(t.tag),n=F(t.payload);if(e===s.Error)p++;else if(e===s.Console)n?.level===`error`&&p++;else if(e===s.Navigation){let e=I(n?.url);e!==void 0&&h.add(e)}}}return{seq:e,firstTimestamp:l===1/0?0:l,lastTimestamp:u,eventCount:t.length,clickCount:d,keypressCount:f,errorCount:p,hasFullSnapshot:m,urls:[...h],...n!==void 0&&n.length>0?{distinctId:n}:{},...c===void 0?{}:{user:{...c}},...Object.keys(r).length===0?{}:{sessionAttributes:{...r}}}}function L(e=Date.now){let t=e(),n=new Uint8Array(/* @__PURE__ */ new ArrayBuffer(16));fe(n),n[0]=Math.floor(t/2**40)&255,n[1]=Math.floor(t/2**32)&255,n[2]=Math.floor(t/2**24)&255,n[3]=Math.floor(t/2**16)&255,n[4]=Math.floor(t/256)&255,n[5]=t&255,n[6]=(n[6]??0)&15|112,n[8]=(n[8]??0)&63|128;let r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function fe(e){let t=globalThis.crypto;if(typeof t?.getRandomValues==`function`){t.getRandomValues(e);return}for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}const pe=`lf_session_replay`;var me=class{idleTimeoutMs;maxDurationMs;now;storage;memorySession;pendingSession;persistenceTimer;constructor(e){this.idleTimeoutMs=e.idleTimeoutMs,this.maxDurationMs=e.maxDurationMs,this.now=e.now??Date.now,this.storage=e.storage===void 0?R():e.storage}getSession(){let e=this.now();if(this.memorySession!==void 0&&!this.isExpired(this.memorySession,e))return this.memorySession;let t=this.read();return t!==void 0&&!this.isExpired(t,e)?t:this.createSession(e)}touch(){let e=this.now(),t={...this.getSession(),lastActivityAt:e};return this.memorySession=t,this.scheduleWrite(t),t}reset(){return this.createSession(this.now())}flushPendingStorage(){this.persistenceTimer!==void 0&&(clearTimeout(this.persistenceTimer),this.persistenceTimer=void 0);let e=this.pendingSession;this.pendingSession=void 0,e!==void 0&&this.writeNow(e)}isExpired(e,t){return t-e.lastActivityAt>this.idleTimeoutMs||t-e.startedAt>this.maxDurationMs}createSession(e){let t={id:L(this.now),startedAt:e,lastActivityAt:e};return this.flushPendingStorage(),this.writeNow(t),t}read(){if(this.storage!==null)try{let e=this.storage.getItem(pe);if(e!==null){let t=JSON.parse(e);if(he(t))return this.memorySession=t,t}}catch{return this.memorySession}return this.memorySession}write(e){if(this.memorySession=e,this.storage!==null)try{this.storage.setItem(pe,JSON.stringify(e))}catch{}}scheduleWrite(e){this.pendingSession=e,this.persistenceTimer===void 0&&(this.persistenceTimer=setTimeout(()=>{this.persistenceTimer=void 0;let e=this.pendingSession;this.pendingSession=void 0,e!==void 0&&this.writeNow(e)},1e3))}writeNow(e){this.memorySession=e,this.write(e)}};function R(){try{return globalThis.sessionStorage??null}catch{return null}}function he(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.startedAt==`number`&&Number.isFinite(t.startedAt)&&typeof t.lastActivityAt==`number`&&Number.isFinite(t.lastActivityAt)}var z=class extends Error{droppedSeqs;reason;seq;sessionId;status;constructor(e){super(ge(e),{cause:e.cause}),this.name=`ReplayUploadError`,this.droppedSeqs=Object.freeze([...e.droppedSeqs??[]]),this.reason=e.reason,this.seq=e.seq,this.sessionId=e.sessionId,this.status=e.status}};function ge(e){let t=e.seq===void 0?`replay chunk`:`replay chunk seq=${String(e.seq)}`,n=e.cause instanceof Error?`: ${e.cause.message}`:``;return`${t} ${e.reason}${n}`}const B=`lf_session_replay_seq`,V=1e4,_e=3e4,H=48e3,ve=1e6,ye=.9,be={gzip:t,gzipSync:n};var xe=class{buffer=[];bufferHasFullSnapshot=!1;pendingBytes=0;seq=0;timer;nextFlushAt;lastUserActivityAt;startedAt;started=!1;held;heldBufferIncomplete=!1;minimumBufferIncomplete=!1;minimumDurationSatisfied=!1;firstObservedTimestamp;lastObservedTimestamp;refreshingMinimumSnapshot=!1;mode;queue=[];retainedBytes=0;activeUpload;drainPromise;draining=!1;pagehideUploads=/* @__PURE__ */ new Set;lifecycleFlights=/* @__PURE__ */ new Set;closed=!1;shuttingDown=!1;wakeRetry;retryAbort=new AbortController;deadlineAbort=new AbortController;resyncPending=!1;resyncTimer;lastResyncAt;reservedKeepaliveBytes=0;asyncCompressionAvailable=!0;config;compression;storage;sessionId;sessionAttributes;takeFullSnapshot;sequenceRecord;sequenceRecordFailed=!1;awaitingBinding;bindingBufferIncomplete=!1;constructor(e,t,n,r=R(),i=be,a={},o={}){this.config=e,this.sessionId=t,this.sessionAttributes=Object.freeze({...a}),this.mode=n,this.storage=r,this.compression=i,this.held=o.holdUntilActivity===!0&&n===`full`,this.takeFullSnapshot=o.takeFullSnapshot,this.sequenceRecord=o.sequenceRecord,this.awaitingBinding=o.awaitBinding===!0,this.minimumDurationSatisfied=e.minSessionDurationMs===0,this.seq=o.sequenceRecord?.initialSeq??this.readPersistedSequence()??0,this.startedAt=this.config.now(),this.lastUserActivityAt=this.startedAt}start(){this.started||this.mode!==`full`||(this.started=!0,this.scheduleFlush())}add(e){this.minimumDurationSatisfied||(this.firstObservedTimestamp??=e.timestamp,this.lastObservedTimestamp=Math.max(this.lastObservedTimestamp??e.timestamp,e.timestamp)),d(e)&&(this.lastUserActivityAt=this.config.now());let t=G(e);if(this.resyncPending){this.addDuringResync(e,t);return}if(this.refreshingMinimumSnapshot){this.buffer.push(e),this.pendingBytes+=t;return}let n=!this.minimumDurationSatisfied;if(this.mode===`buffer`||this.held||n||this.awaitingBinding){if(e.type===i.Meta){this.buffer=[e],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=t,n&&(this.mode===`full`&&(this.firstObservedTimestamp=e.timestamp),this.finishMinimumBufferingEvent());return}if(e.type===i.FullSnapshot){let r=!this.bufferHasFullSnapshot&&this.buffer.length===1&&this.buffer[0]?.type===i.Meta?this.buffer[0]:void 0;this.buffer=r===void 0?[e]:[r,e],this.bufferHasFullSnapshot=!0,this.pendingBytes=t+(r===void 0?0:G(r)),this.heldBufferIncomplete=!1,this.minimumBufferIncomplete=!1,n&&(this.mode===`full`&&(this.firstObservedTimestamp=r?.timestamp??e.timestamp),this.finishMinimumBufferingEvent());return}if(!this.bufferHasFullSnapshot||t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held,this.bindingBufferIncomplete||=this.awaitingBinding,this.minimumBufferIncomplete||=n,n&&this.finishMinimumBufferingEvent();return}if(this.pendingBytes+t>this.config.maxBufferBytes){this.heldBufferIncomplete||=this.held,this.bindingBufferIncomplete||=this.awaitingBinding,this.minimumBufferIncomplete||=n,n&&this.finishMinimumBufferingEvent();return}}if(e.type===i.Meta&&this.mode===`full`&&this.buffer.length>0&&this.flushAndReport(),this.buffer.push(e),this.pendingBytes+=t,n&&this.minimumDurationReached()){this.flushAndReport();return}this.mode===`full`&&this.pendingBytes>=this.config.maxBufferBytes&&e.type!==i.Meta?this.flushAndReport():this.scheduleFlush()}addDuringResync(e,t){if(e.type===i.Meta){this.buffer=[e],this.pendingBytes=t;return}if(e.type!==i.FullSnapshot)return;let n=this.buffer.length===1&&this.buffer[0]?.type===i.Meta?this.buffer[0]:void 0;this.buffer=n===void 0?[e]:[n,e],this.pendingBytes=t+(n===void 0?0:G(n)),this.resyncPending=!1,this.clearResyncTimer(),this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush()}async triggerFlush(){return this.mode===`buffer`&&(this.bufferHasFullSnapshot||(this.buffer=[],this.pendingBytes=0),this.mode=`full`,this.start()),this.flush()}async flush(e={}){if(this.closed)return;if(e.keepalive!==!0)return this.flushInternal(e);this.activeUpload!==void 0&&(this.activeUpload.background=!0,this.activeUpload.pagehide=!0);let t=this.queue.filter(e=>(e!==this.activeUpload||!e.attempting)&&!this.pagehideUploads.has(e));for(let e of t)this.pagehideUploads.add(e),e.background=!0;this.wakeRetry?.();let n=this.trackLifecycle(Promise.all(t.map(async e=>this.finalAttempt(e))).then(()=>void 0));await Promise.all([this.flushInternal(e),n])}async flushInternal(e={}){if(this.closed||this.mode===`buffer`||this.held||this.awaitingBinding||this.buffer.length===0||!this.minimumDurationReached()||(this.clearScheduledFlush(),this.minimumBufferIncomplete&&!this.refreshMinimumBuffer()))return;this.minimumDurationSatisfied=!0;let t=this.buffer,n=this.pendingBytes;this.buffer=[],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=0;let r=this.sessionId,i=this.snapshotIdentity();if(e.keepalive===!0){let e=this.splitKeepaliveEventChunks(t,i,Math.max(0,H-this.reservedKeepaliveBytes)),n=this.allocateSeq(e.length);if(n===void 0)return;await this.trackLifecycle(this.deliverLifecycle(e,n,r,i));return}if(e.background===!0){let e=[];for(let n of this.splitKeepaliveEventChunks(t,i)){let t=this.enqueue(n.events,n.eventBytes,r,i,!0,n);if(t===void 0)break;e.push(t)}await Promise.all(e.map(async e=>e.done));return}await this.enqueue(t,n,r,i)?.done}async shutdown(e={}){if(this.started=!1,this.clearScheduledFlush(),this.held||this.awaitingBinding||!this.minimumDurationReached()){this.discard(),await this.settleWithinDeadline([]);return}if(e.keepalive===!0){await this.flush(e),this.closed=!0,this.clearResyncTimer(),await this.settleWithinDeadline([]);return}let t=this.flushInternal();this.closed=!0,this.shuttingDown=!0,this.clearResyncTimer(),this.retryAbort.abort();let n=this.queue.filter(e=>e!==this.activeUpload&&!this.pagehideUploads.has(e)).map(async e=>this.finalAttempt(e));await this.settleWithinDeadline([t,...n])}discard(){this.started=!1,this.closed=!0,this.clearScheduledFlush(),this.clearResyncTimer(),this.buffer=[],this.bufferHasFullSnapshot=!1,this.minimumBufferIncomplete=!1,this.pendingBytes=0}getMode(){return this.mode}isHeld(){return this.held}releaseHeld(e){this.held&&((this.heldBufferIncomplete||!this.bufferHasFullSnapshot)&&(this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,e()),this.held=!1,this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush())}flushAndReport(){this.flushInternal().catch(e=>{U(this.config.onError,e)})}scheduleFlush(){let e=this.config.now(),t=Math.max(0,this.config.minSessionDurationMs-(e-this.startedAt)),n=Math.max(f(this.config.flushIntervalMs,e-this.lastUserActivityAt),t);this.scheduleFlushIn(e,n)}scheduleFlushIn(e,t){if(!this.started||this.mode!==`full`||this.held||this.buffer.length===0)return;let n=e+t;this.timer!==void 0&&this.nextFlushAt!==void 0&&this.nextFlushAt<=n||(this.clearScheduledFlush(),this.nextFlushAt=n,this.timer=setTimeout(()=>{this.timer=void 0,this.nextFlushAt=void 0,this.flushAndReport()},t))}clearScheduledFlush(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0),this.nextFlushAt=void 0}minimumDurationReached(){return this.minimumDurationSatisfied||this.config.minSessionDurationMs===0?!0:this.firstObservedTimestamp===void 0||this.lastObservedTimestamp===void 0?!1:this.lastObservedTimestamp-this.firstObservedTimestamp>=this.config.minSessionDurationMs}finishMinimumBufferingEvent(){this.minimumDurationReached()?this.flushAndReport():this.scheduleFlush()}refreshMinimumBuffer(){let e=this.buffer.length,t=this.pendingBytes;if(this.takeFullSnapshot!==void 0){this.refreshingMinimumSnapshot=!0;try{this.takeFullSnapshot()}catch(e){U(this.config.onError,e)}finally{this.refreshingMinimumSnapshot=!1}}return this.buffer.slice(e).some(e=>e.type===i.FullSnapshot)?(this.minimumBufferIncomplete=!1,!0):(this.buffer.length=e,this.pendingBytes=t,!1)}snapshotIdentity(){let e=this.snapshotUser(),t=this.config.distinctId;if(this.config.getDistinctId!==void 0)try{t=this.config.getDistinctId()??this.config.distinctId}catch(e){U(this.config.onError,e)}else e!==void 0&&(t=e.id);return{distinctId:t,user:e}}createEnvelope(e,t,n){return{version:1,meta:de(t,e,n.distinctId,this.sessionAttributes,n.user),events:e}}snapshotUser(){if(this.config.getUser!==void 0)try{return ue(this.config.getUser())}catch(e){U(this.config.onError,e);return}}allocateSeq(e){let t=this.seq,n=this.sequenceRecord;if(n!==void 0){if(this.sequenceRecordFailed)return;if(!n.write(t+e)){this.sequenceRecordFailed=!0,this.discard();try{n.onFailure()}catch(e){U(this.config.onError,e)}return}}return this.seq+=e,this.saveSeq(this.sessionId,this.seq),t}enqueue(e,t,n,r,a=!1,o){let s=Math.max(2e6,2*this.config.maxBufferBytes);if(this.queue.length>0&&this.retainedBytes+t>s){U(this.config.onError,new z({cause:/* @__PURE__ */ Error(`replay upload queue is full`),reason:`not-sent`,seq:void 0,sessionId:n})),this.beginResync();return}let c=this.allocateSeq(1);if(c===void 0)return;let l=()=>void 0,u={body:void 0,done:new Promise(e=>{l=e}),events:e,hasFullSnapshot:e.some(e=>e.type===i.FullSnapshot),identity:r,reachedFetch:!1,attempting:!1,background:a,pagehide:!1,prepared:o,resolve:l,retainedBytes:t,seq:c,sessionId:n,settled:!1};return this.queue.push(u),this.retainedBytes+=t,this.draining||(this.draining=!0,this.drainPromise=this.drain()),u}async drain(){try{for(;!this.shuttingDown;){let e=this.queue.find(e=>!this.pagehideUploads.has(e));if(e===void 0)break;this.activeUpload=e;let t=await this.deliverQueued(e);this.activeUpload=void 0,this.settle(e,t)}}finally{this.activeUpload=void 0,this.draining=!1}}async deliverQueued(e){let t=await this.compressQueued(e);if(t!==void 0||e.settled)return t;let n=Date.now(),r;for(let t=1;;t++){if(this.pagehideUploads.has(e))return e.done.then(()=>void 0);let i=_e-(Date.now()-n);if(t>1&&i<=0)return q(r,e.reachedFetch);let a=await this.attemptQueued(e,Math.min(V,i));if(a===void 0)return;r=a;let o=je(a,t,this.config.random);if(o===void 0||this.shuttingDown||e.pagehide||Date.now()-n+o>=_e)return q(a,e.reachedFetch);await this.backoff(o)}}retainCompressedBody(e,t){this.retainedBytes+=t.byteLength-e.retainedBytes,e.retainedBytes=t.byteLength,e.body=t,e.events=void 0}compressQueuedSync(e){let t=e.prepared;if(e.prepared=void 0,!(e.body!==void 0||e.events===void 0||e.settled)){if(t?.body!==void 0&&t.events===e.events){this.retainCompressedBody(e,t.body);return}try{let t=r(JSON.stringify(this.createEnvelope(e.events,e.seq,e.identity)));this.retainCompressedBody(e,this.compression.gzipSync(t));return}catch(e){return{cause:e,reason:`not-sent`}}}}async compressQueued(e){if(this.shuttingDown||e.background)return this.compressQueuedSync(e);if(e.body!==void 0||e.events===void 0)return;let t=e.events;try{let n=r(JSON.stringify(this.createEnvelope(t,e.seq,e.identity))),i=await this.compressOrdinary(n);if(e.events!==t)return await this.compressQueued(e);e.settled||this.retainCompressedBody(e,i);return}catch(e){return{cause:e,reason:`not-sent`}}}async attemptQueued(e,t=V){let n=e.body;if(n!==void 0){e.attempting=!0;try{await this.send(this.prepareUpload(n,e.seq,e.sessionId,e.background),()=>{e.reachedFetch=!0},t);return}catch(e){return e}finally{e.attempting=!1}}}async finalAttempt(e){let t=e.background?this.compressQueuedSync(e):await this.compressQueued(e);if(t!==void 0){this.settle(e,t);return}let n=await this.attemptQueued(e);this.settle(e,n===void 0?void 0:q(n,e.reachedFetch))}async trackLifecycle(e){this.lifecycleFlights.add(e);let t=()=>{this.lifecycleFlights.delete(e)};return e.then(t,t),e}async settleWithinDeadline(e){let t=Promise.all([...e,this.drainPromise,...this.lifecycleFlights]).then(()=>void 0,()=>void 0),n,r=new Promise(e=>{n=setTimeout(e,V)});if(await Promise.race([t,r]),clearTimeout(n),this.shuttingDown){this.deadlineAbort.abort(/* @__PURE__ */ Error(`replay upload did not finish before shutdown`));for(let e of[...this.queue])this.settle(e,{cause:/* @__PURE__ */ Error(`replay upload did not finish before shutdown`),reason:e.reachedFetch?`unconfirmed`:`not-sent`})}}settle(e,t){if(e.settled)return;e.settled=!0,this.pagehideUploads.delete(e),this.retainedBytes-=e.retainedBytes;let n=this.queue.indexOf(e);n>=0&&this.queue.splice(n,1),e.body=void 0,e.events=void 0,e.resolve(),t!==void 0&&this.handleSequencedLoss(e.seq,e.sessionId,t)}handleSequencedLoss(e,t,n){let r=[];if(!this.shuttingDown){let t=!1;for(let n of[...this.queue])if(!(n.seq<e)){if(n.events===void 0){if(n.hasFullSnapshot){t=!0;break}continue}if(n.hasFullSnapshot){let e=Te(n.events),r=Ee(e);this.retainedBytes+=r-n.retainedBytes,n.retainedBytes=r,n.events=e,t=!0;break}r.push(n.seq),this.settle(n,void 0)}!t&&!this.trimBufferToAnchor()&&this.beginResync()}U(this.config.onError,new z({cause:n.cause,droppedSeqs:r,reason:n.reason,seq:e,sessionId:t,status:n.status}))}trimBufferToAnchor(){return this.buffer.some(e=>e.type===i.FullSnapshot)?(this.buffer=Te(this.buffer),this.pendingBytes=Ee(this.buffer),!0):!1}beginResync(){this.closed||(this.resyncPending=!0,this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,this.clearScheduledFlush(),this.scheduleResyncSnapshot())}scheduleResyncSnapshot(){if(this.resyncTimer!==void 0||this.closed)return;let e=this.lastResyncAt===void 0?0:Math.max(0,this.lastResyncAt+6e4-this.config.now());this.resyncTimer=setTimeout(()=>{this.resyncTimer=void 0,this.takeResyncSnapshot()},e)}takeResyncSnapshot(){if(this.resyncPending&&!this.closed&&this.takeFullSnapshot!==void 0){this.lastResyncAt=this.config.now();try{this.takeFullSnapshot()}catch(e){U(this.config.onError,e),this.scheduleResyncSnapshot();return}this.isResyncPending()&&(U(this.config.onError,/* @__PURE__ */ Error(`replay resync snapshot produced no full snapshot`)),this.scheduleResyncSnapshot())}}isResyncPending(){return this.resyncPending}clearResyncTimer(){this.resyncTimer!==void 0&&(clearTimeout(this.resyncTimer),this.resyncTimer=void 0)}async backoff(e){let t=this.retryAbort.signal;t.aborted||await new Promise(n=>{let r=()=>{clearTimeout(i),t.removeEventListener(`abort`,r),this.wakeRetry===r&&(this.wakeRetry=void 0),n()},i=setTimeout(r,e);t.addEventListener(`abort`,r),this.wakeRetry=r})}prepareUpload(e,t,n,r){let i=r&&this.reservedKeepaliveBytes+e.byteLength<=H?e.byteLength:0;return this.reservedKeepaliveBytes+=i,{body:e,seq:t,sessionId:n,reservedBytes:i,requestKeepalive:i>0}}splitKeepaliveEventChunks(e,t,n=1/0){let i=e.map(G),a=[],o=n,s,c=0;for(;c<e.length;){let l=Math.min(H,o);if(l<4800){a.push({events:e.slice(c),eventBytes:K(i,c,e.length)});break}let u=this.seq+a.length,d=s===void 0?ve:Math.min(ve,l*s*ye),f=De(i,c,d);for(;;){let d=e.slice(c,f),p=K(i,c,f),m;try{m=this.compression.gzipSync(r(JSON.stringify(this.createEnvelope(d,u,t))))}catch{a.push({events:d,eventBytes:p}),o=Number.isFinite(n)?0:o;break}if(s=p/Math.max(1,m.byteLength),m.byteLength<=l){a.push({events:d,eventBytes:p,body:m}),o-=m.byteLength;break}if(f-c===1){Number.isFinite(n)?(a.push({events:e.slice(c),eventBytes:K(i,c,e.length)}),f=e.length):a.push({events:d,eventBytes:p,body:m});break}f=Math.max(c+1,Math.min(f-1,De(i,c,l*s*ye)))}c=f}return a}async deliverLifecycle(e,t,n,i){let a=[];for(let o=0;o<e.length;o++){let s=e[o];if(s===void 0){a.push(void 0);continue}try{a.push({body:s.body??this.compression.gzipSync(r(JSON.stringify(this.createEnvelope(s.events,t+o,i)))),requestKeepalive:!1,reservedBytes:0,seq:t+o,sessionId:n})}catch(e){this.handleSequencedLoss(t+o,n,{cause:e,reason:`not-sent`}),a.push(void 0)}}let o=!0,s=Math.max(0,H-this.reservedKeepaliveBytes);for(let e of a){if(e===void 0){o=!1;continue}o&&e.body.byteLength<=s?(e.requestKeepalive=!0,e.reservedBytes=e.body.byteLength,this.reservedKeepaliveBytes+=e.reservedBytes,s-=e.reservedBytes):o=!1}await Promise.all(a.map(async e=>{if(e===void 0)return;let t=!1;try{await this.send(e,()=>{t=!0})}catch(n){this.handleSequencedLoss(e.seq,e.sessionId,q(n,t))}}))}async compressOrdinary(e){if(!this.asyncCompressionAvailable)return this.compression.gzipSync(e);try{return await Oe(this.compression,e)}catch{return this.asyncCompressionAvailable=!1,this.compression.gzipSync(e)}}async send(e,t,n=V){let r,i,a,o=new AbortController,s=setTimeout(()=>{o.abort(/* @__PURE__ */ Error(`replay upload timed out after ${String(n)}ms`))},n),c=this.deadlineAbort.signal,l=()=>{o.abort(c.reason)};c.addEventListener(`abort`,l);try{let n=`${this.config.replayUrl.replace(/\/+$/u,``)}/${encodeURIComponent(e.sessionId)}?seq=${String(e.seq)}`,s=await we(this.getUploadHeaders(),o.signal);t();let c=this.config.fetchImpl(n,{method:`POST`,headers:s,body:e.body.slice(),keepalive:e.requestKeepalive,signal:o.signal});r=!0;let l=await c;if(i=!0,a=await ke(l),!l.ok){let e=l.status===429||l.status===503?Me(l.headers.get(`retry-after`),Date.now()):void 0;throw new W(l.status,e)}}finally{clearTimeout(s),c.removeEventListener(`abort`,l),e.reservedBytes>0&&(r!==!0||i!==!0||a===!0)&&(this.reservedKeepaliveBytes=Math.max(0,this.reservedKeepaliveBytes-e.reservedBytes))}}async getUploadHeaders(){let e=this.config.headers===void 0?{}:await this.config.headers(),t=await Ce(this.config.token);return{...t===void 0||t.length===0?e:{...Object.fromEntries(Object.entries(e).filter(([e])=>e.toLowerCase()!==`authorization`)),Authorization:`Bearer ${t}`},"Content-Type":`application/json`,"Content-Encoding":`gzip`}}canResumeSequence(){return this.awaitingBinding?!0:this.readPersistedSequence()===this.seq}isAwaitingBinding(){return this.awaitingBinding}bind(e){this.awaitingBinding&&!this.closed&&(this.sequenceRecord=e,this.seq=e.initialSeq,this.awaitingBinding=!1,this.bindingBufferIncomplete&&(this.bindingBufferIncomplete=!1,this.buffer=[],this.bufferHasFullSnapshot=!1,this.pendingBytes=0,this.takeFullSnapshot?.()),!(this.mode!==`full`||this.held||this.buffer.length===0)&&(this.pendingBytes>=this.config.maxBufferBytes?this.flushAndReport():this.scheduleFlush()))}readPersistedSequence(){if(this.storage!==null)try{let e=this.storage.getItem(B);if(e===null)return;let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let n=t;return n.id===this.sessionId&&typeof n.seq==`number`&&Number.isSafeInteger(n.seq)&&n.seq>=0?n.seq:void 0}catch{return}}saveSeq(e,t){if(this.storage!==null)try{this.storage.setItem(B,JSON.stringify({id:e,seq:t}))}catch{}}};function U(e,t){try{let n=e?.(t);Se(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function Se(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}var W=class extends Error{retryAfter;status;constructor(e,t){super(`replay ingest failed: ${String(e)}`),this.status=e,this.retryAfter=t,this.name=`ReplayIngestError`}};async function Ce(e){return typeof e==`function`?e():e}async function we(e,t){if(t.aborted)throw t.reason;return new Promise((n,r)=>{let i=()=>{r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e instanceof Error?e:Error(String(e)))})})}function G(e){try{return r(JSON.stringify(e)).byteLength}catch{return 0}}function Te(e){let t=e.findIndex(e=>e.type===i.FullSnapshot);if(t<0)return e;let n=t>0&&e[t-1]?.type===i.Meta?t-1:t;return e.slice(n)}function Ee(e){return e.reduce((e,t)=>e+G(t),0)}function K(e,t,n){let r=0;for(let i=t;i<n;i++)r+=e[i]??0;return r}function De(e,t,n){let r=t+1,i=e[t]??0;for(;r<e.length&&i+(e[r]??0)<=n;)i+=e[r]??0,r++;return r}async function Oe(e,t){return new Promise((n,r)=>{let i=[];typeof window<`u`&&i.push(window),typeof document<`u`&&i.push(document);let a=()=>{for(let e of i)e.removeEventListener(`securitypolicyviolation`,s)},o=(e,t)=>{if(a(),e!==null){r(e);return}n(t)},s=e=>{let t=e;(t.effectiveDirective.includes(`worker-src`)||t.violatedDirective.includes(`worker-src`))&&o(/* @__PURE__ */ Error(`replay compression worker blocked by Content Security Policy`))};for(let e of i)e.addEventListener(`securitypolicyviolation`,s);try{e.gzip(t,{level:6},(e,t)=>{o(e,t)})}catch(e){a(),r(e instanceof Error?e:Error(String(e)))}})}async function ke(e){if(e.body===null)return!0;try{return await e.body.cancel(),!0}catch{return!1}}function Ae(e){return e===408||e===425||e===429||e>=500}function je(e,t,n){if(e instanceof W&&!Ae(e.status))return;let r=Math.min(8e3,500*2**(t-1)),i=Math.round(r*(1-.5*n())),a=e instanceof W?e.retryAfter:void 0;return a===void 0?i:Math.max(a,i)}function q(e,t){let n=e instanceof W?e.status:void 0;return n!==void 0&&!Ae(n)?{cause:e,reason:`rejected`,status:n}:{cause:e,reason:t?`unconfirmed`:`not-sent`,status:n}}function Me(e,t){if(e===null)return;let n=e.trim();if(/^\d+$/u.test(n)){let e=Number(n);return Number.isSafeInteger(e)?e*1e3:void 0}let r=Ie(n,t);return r===void 0?void 0:Math.max(0,r-t)}const Ne=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Pe=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],Fe=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function Ie(e,t){let n=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(n!==null)return J(n[1],n[2],n[3],n[4],n[5],n[6],n[7]);let r=/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/u.exec(e);if(r!==null){let e=new Date(t).getUTCFullYear(),n=Number(r[4]),i=Math.floor(e/100)*100+n;return i>e+50&&(i-=100),J(r[1],r[2],r[3],String(i),r[5],r[6],r[7])}let i=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{2}| \d) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/u.exec(e);if(i!==null)return J(i[1],i[3]?.trim(),i[2],i[7],i[4],i[5],i[6])}function J(e,t,n,r,i,a,o){let s=Number(t),c=Ne.indexOf(n),l=Number(r),u=Number(i),d=Number(a),f=Number(o);if(c<0||s<1||s>31||u>23||d>59||f>59)return;let p=/* @__PURE__ */ new Date(0);if(p.setUTCFullYear(l,c,s),p.setUTCHours(u,d,f,0),p.getUTCFullYear()!==l||p.getUTCMonth()!==c||p.getUTCDate()!==s||p.getUTCHours()!==u||p.getUTCMinutes()!==d||p.getUTCSeconds()!==f)return;let m=Pe.indexOf(e),h=Fe.indexOf(e);return(m>=0?m:h)===p.getUTCDay()?p.getTime():void 0}const Le=`lf_session_replay_recording`,Y=`lf_session_replay_recording_owner`,Re=72e5;var ze=class{state;resumed=!1;storage;owner;now;maxDurationMs;readOpenerState;constructor(e,t,n,r=()=>null){this.storage=e,this.now=t,this.owner=L(t),this.maxDurationMs=Math.min(n,Re),this.readOpenerState=r;try{e?.getItem(`lf_session_replay_recording_owner`)===null&&(this.state=this.readResumableState()),e?.setItem(Y,this.owner),e?.getItem(`lf_session_replay_recording_owner`)!==this.owner&&(this.storage=null,this.state=void 0)}catch{this.storage=null,this.state=void 0}this.resumed=this.state!==void 0}get(e){return this.state!==void 0&&this.isCurrent(this.state.id,e)?this.state.id:this.replace(e)}candidate(e){return{id:this.get(e),resumed:this.resumed}}replace(e){this.state={id:L(this.now),rumSessionId:e,startedAt:this.now()},this.resumed=!1;try{this.storage?.setItem(Le,JSON.stringify(this.state))}catch{}return this.state.id}isCurrent(e,t){let n=this.state;if(n===void 0)return!1;let r=this.now();return n.id===e&&n.rumSessionId===t&&r>=n.startedAt&&r-n.startedAt<this.maxDurationMs}release(){try{this.storage?.getItem(`lf_session_replay_recording_owner`)===this.owner&&this.storage.removeItem(Y)}catch{}}resume(){try{this.state=this.storage?.getItem(`lf_session_replay_recording_owner`)===null?this.readResumableState():void 0,this.storage?.setItem(Y,this.owner),this.storage?.getItem(`lf_session_replay_recording_owner`)!==this.owner&&(this.state=void 0,this.storage=null)}catch{this.state=void 0,this.storage=null}this.resumed=this.state!==void 0}readResumableState(){let e=this.storage?.getItem(Le),t=this.storage?.getItem(B);if(e==null||t==null)return;let n=null;try{n=this.readOpenerState()}catch{}if(n!==e)return Be(e,t)}};function Be(e,t){let n=JSON.parse(e),r=JSON.parse(t);if(typeof n!=`object`||!n||typeof r!=`object`||!r)return;let i=n,a=r;if(!(typeof i.id!=`string`||i.id.length===0||typeof i.rumSessionId!=`string`||typeof i.startedAt!=`number`||!Number.isFinite(i.startedAt)||a.id!==i.id||typeof a.seq!=`number`||!Number.isSafeInteger(a.seq)||a.seq<0))return{id:i.id,rumSessionId:i.rumSessionId,startedAt:i.startedAt}}function Ve(){try{if(typeof window>`u`||!window.isSecureContext)return;let e=globalThis.navigator?.locks;return typeof e?.request==`function`?e:void 0}catch{return}}async function He(e,t,n,r=1e3){return n.aborted?{kind:`aborted`}:new Promise(i=>{let a=!1,o=e=>{a||(a=!0,clearTimeout(c),n.removeEventListener(`abort`,l),i(e))},s=new AbortController,c=setTimeout(()=>{s.abort(),o({kind:`timeout`})},r),l=()=>{s.abort(),o({kind:`aborted`})};n.addEventListener(`abort`,l);let u=!1;try{e.request(`logfire-session-replay:${t}`,{mode:`exclusive`,signal:s.signal},async()=>{if(u=!0,a||n.aborted){o({kind:`aborted`});return}await new Promise(e=>{o({kind:`held`,lock:{release:e}})})}).catch(()=>{u||o({kind:`aborted`})})}catch{o({kind:`aborted`})}})}function Ue(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function We(e){let t=e.random??Math.random;return t()<Ue(e.sessionSampleRate)?`full`:t()<Ue(e.onErrorSampleRate)?`buffer`:`off`}const Ge=`lf_session_replay_seq:`,X=`lf_session_replay_probe`;var Ke=class{storage;now;constructor(e,t){this.storage=e,this.now=t}read(e){try{return Ye(this.storage.getItem(Je(e)))?.seq}catch{return}}write(e,t){try{return this.storage.setItem(Je(e),JSON.stringify({seq:t,at:this.now()})),this.read(e)===t}catch{return!1}}prune(e){try{let t=this.now()-e,n=[];for(let e=0;e<this.storage.length;e+=1){let r=this.storage.key(e);if(r===null||!r.startsWith(Ge))continue;let i=Ye(this.storage.getItem(r));(i===void 0||i.at<t)&&n.push(r)}for(let e of n)this.storage.removeItem(e)}catch{}}};function qe(){try{let e=globalThis.localStorage;if(e===void 0)return null;e.setItem(X,`1`);let t=e.getItem(X)===`1`;return e.removeItem(X),t?e:null}catch{return null}}function Je(e){return`${Ge}${e}`}function Ye(e){if(e!==null)try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let n=t;return typeof n.seq!=`number`||!Number.isSafeInteger(n.seq)||n.seq<0||typeof n.at!=`number`||!Number.isFinite(n.at)?void 0:{seq:n.seq,at:n.at}}catch{return}}const Xe=/^[a-z][a-z0-9_]{0,63}$/u;function Ze(e,t){let n=0;for(let r of e)if(n+=+(r.length>0),n>t)return!1;return!0}function Qe(e,t){if(e===void 0)return Object.freeze({});let n;try{n=e()}catch(e){return t(e),Object.freeze({})}if(typeof n!=`object`||!n||Array.isArray(n))return Object.freeze({});let r;try{r=Object.getPrototypeOf(n)}catch(e){return t(e),Object.freeze({})}if(r!==Object.prototype&&r!==null)return Object.freeze({});let i;try{i=Object.keys(n)}catch(e){return t(e),Object.freeze({})}let a={},o=0;for(let e of i){if(!Xe.test(e))continue;let r;try{r=Reflect.get(n,e)}catch(e){t(e);continue}if((typeof r==`boolean`||typeof r==`number`&&Number.isFinite(r)||typeof r==`string`&&Ze(r,200))&&(Object.defineProperty(a,e,{configurable:!0,enumerable:!0,value:r,writable:!0}),o+=1,o===20))break}return Object.freeze(a)}const $e={mode:`off`,recording:!1,getSessionId:()=>``,captureError:()=>void 0,getRecordingId:()=>``,flush:async()=>Promise.resolve(),stop:async()=>Promise.resolve()},et=`lf_session_replay_mode`,Z=Symbol.for(`@pydantic/logfire-session-replay/controller`);function tt(e){if(typeof window>`u`||typeof document>`u`)return $e;let t=ht();try{let n=rt(e),r=new me({idleTimeoutMs:n.sessionIdleTimeoutMs,maxDurationMs:n.maxSessionDurationMs,now:n.now}),i=r.getSession().id,a=e=>{let t;try{t=n.getSessionId?.()}catch(e){return Q(n.onError,e),i}if(t!==void 0&&t.length>0)return i=t,t;let a=e?r.touch().id:r.getSession().id;return i=a,a},o=R(),s=new ze(o,n.now,n.maxSessionDurationMs,()=>window.opener?.sessionStorage.getItem(`lf_session_replay_recording`)??null),c=it(n.now),l=a(!1),u=s.get(l),d,f=!1,p=!1,m=0,h=!0,g=Promise.resolve(),_=Promise.resolve(),v,y,b,x=!1,S=e=>{y!==void 0&&(e===void 0||y.recordingId===e)&&(y.lock.release(),y=void 0)},C=(e,t,r=!t,i=!1)=>{let c=at(n,e,o);if(!(c===`off`||f||p||d!==void 0||e!==l))try{x=i&&s.candidate(e).resumed;let t=u;d=nt({config:n,getSessionId:a,mode:c,onSessionChanged:O,samplingModeStorage:o,sessionId:e,recordingId:t,isCurrentRecording:()=>s.isCurrent(t,a(!1)),holdUntilActivity:r,awaitBinding:i})}catch(e){if(d=void 0,t)throw e;Q(n.onError,e)}},w=(e,t,n)=>({initialSeq:n,write:n=>e.records.write(t,n),onFailure:()=>{queueMicrotask(()=>{!f&&u===t&&(s.replace(l),O(l,!1))})}}),T=async(e,t,r)=>{b?.abort();let i=new AbortController;b=i;let a=()=>i.signal.aborted||f||p||m!==r||l!==t,o=s.candidate(t);u=o.id;let c=()=>{o={id:s.replace(t),resumed:!1},u=o.id};for(let t=0;t<2;t+=1){let t=await He(e.locks,o.id,i.signal);if(t.kind===`aborted`)return;if(t.kind===`timeout`){c();continue}if(a()||u!==o.id){t.lock.release();return}let n;if(o.resumed?n=e.records.read(o.id):e.records.write(o.id,0)&&(n=0),n===void 0){t.lock.release(),c();continue}return y={recordingId:o.id,lock:t.lock},{recordingId:o.id,sequenceRecord:w(e,o.id,n)}}Q(n.onError,/* @__PURE__ */ Error(`logfire session replay: could not claim a replay recording`))},E=async(e,t,r,i)=>{try{let n=await T(e,t,r),a=!f&&!p&&m===r&&l===t;if(n===void 0){a&&d?.transport.isAwaitingBinding()===!0&&(d.discard(),d=void 0);return}if(!a){S(n.recordingId);return}if(d!==void 0&&d.recordingId!==n.recordingId&&(d.discard(),d=void 0,C(t,!1,i,!0)),d===void 0||d.recordingId!==n.recordingId){S(n.recordingId);return}x=!1,d.transport.bind(n.sequenceRecord)}catch(e){Q(n.onError,e)}},D=async(e,t,n)=>{C(e,!1,n,c!==void 0),c!==void 0&&d!==void 0&&await E(c,e,t,n)},O=(e,t=!0)=>{if(f||p)return;let r=s.get(e);if(e===l&&r===u)return;let i=u;l=e,u=r,b?.abort();let a=d;d=void 0;let o=a?.deactivate()??Promise.resolve(),c=m;g=g.then(async()=>{await pt(o,n.onError),S(i),!f&&m===c&&l===e&&u===r&&await D(e,c,t)})},k;try{if(c===void 0)C(l,!0);else if(c.records.prune(Re),C(l,!0,!1,!0),d!==void 0){let e=l,t=m;g=g.then(async()=>E(c,e,t,!1))}k=setInterval(()=>{O(a(!1))},1e3)}catch(e){throw d?.discard(),d=void 0,b?.abort(),S(),s.release(),e}let A=()=>{p=!0,m+=1,b?.abort();let e=d;d=void 0;let t=e?.deactivate(!0)??Promise.resolve();S(),_=Promise.all([_,g,pt(t,n.onError)]).then(()=>void 0),g=Promise.resolve(),h=e?.transport.canResumeSequence()??h,h&&s.release()},j=e=>{if(!e.persisted||f)return;d?.discard(),d=void 0;let t=m;g=g.then(async()=>{let e=()=>f||m!==t;if(e())return;let n=new AbortController;b=n;let r,i=!1;if(c!==void 0){let e=await He(c.locks,u,n.signal);if(e.kind===`aborted`)return;e.kind===`held`&&(r=e.lock),i=e.kind===`timeout`}else await new Promise(e=>{setTimeout(e,0)});try{if(e())return;p=!1,s.resume(),l=a(!1),u=i?s.replace(l):s.get(l),h=!0}finally{r?.release()}await D(l,t,!1)})};return window.addEventListener(`pagehide`,A),window.addEventListener(`pageshow`,j),{get mode(){try{return d?.transport.getMode()??`off`}catch(e){return Q(n.onError,e),`off`}},get recording(){try{return d!==void 0}catch(e){return Q(n.onError,e),!1}},getSessionId:()=>a(!1),captureError:(e,t)=>{try{d?.captureError(e,t)}catch(e){Q(n.onError,e)}},getRecordingId:()=>d===void 0||x&&d.transport.isAwaitingBinding()?``:s.isCurrent(d.recordingId,a(!1))?d.recordingId:``,flush:async()=>{try{await g,await d?.transport.flush()}catch(e){Q(n.onError,e)}},stop:async()=>(v??=(async()=>{f=!0,m+=1,b?.abort(),clearInterval(k),window.removeEventListener(`pagehide`,A),window.removeEventListener(`pageshow`,j);let e=d;d=void 0,await pt(e?.deactivate()??Promise.resolve(),n.onError),await g,await _,r.flushPendingStorage(),h=e?.transport.canResumeSequence()??h,h&&s.release(),S(),t()})(),v)}}catch(e){throw t(),e}}function nt(e){let{config:t,getSessionId:n,holdUntilActivity:r,mode:i,onSessionChanged:a,samplingModeStorage:o,sessionId:c,recordingId:l,isCurrentRecording:u,awaitBinding:f}=e,p=Qe(t.getSessionAttributes,e=>{Q(t.onError,e)}),m,h=new xe(t,l,i,void 0,void 0,p,{holdUntilActivity:r,takeFullSnapshot:()=>{m.takeFullSnapshot()},awaitBinding:f}),g=[],_=!0,x=()=>_,S;try{m=se({beforeUserActivity:()=>{if(_&&h.isHeld())try{let e=n(!0);if(e!==c||!u()){a(e,!1);return}h.releaseHeld(()=>{m.takeFullSnapshot()})}catch(e){Q(t.onError,e)}},emit:e=>{if(_)try{let t=n(d(e));if(t!==c||!u()){a(t,!1);return}h.add(e)}catch(e){Q(t.onError,e)}},maskAllText:t.maskAllText,maskAllInputs:t.maskAllInputs,maskTextSelector:t.maskTextSelector,blockSelector:t.blockSelector,checkoutEveryNms:i===`buffer`?12e4:Math.max(3e5,t.minSessionDurationMs),redactUrlPatterns:t.redactUrlPatterns}),g.push(()=>{m.stop()});let e=(e,n)=>{if(_)try{m.addCustomEvent(e,n)}catch(e){Q(t.onError,e)}},r=n=>{x()&&(h.releaseHeld(()=>{m.takeFullSnapshot()}),e(s.Error,n),x()&&h.getMode()===`buffer`&&(st(o,c,`full`),ft(h.triggerFlush(),t.onError)))},f=/* @__PURE__ */ new WeakSet,p=e=>typeof e!=`object`||!e||!f.has(e)&&(f.add(e),!0),C=(e,t)=>{if(p(e)){let n=gt(lt(e),void 0,ut(e));r(typeof t?.timestamp==`number`?{...n,timestamp:t.timestamp}:n)}},w=e=>{e instanceof ErrorEvent&&p(e.error)&&r(gt(e.message,e.filename,ut(e.error)))},T=e=>{C(e.reason)},E=()=>{document.visibilityState===`hidden`&&ft(h.flush({background:!0}),t.onError)},D=()=>{ft(h.flush({keepalive:!0}),t.onError)};return t.captureGlobalErrors&&(window.addEventListener(`error`,w,!0),g.push(()=>{window.removeEventListener(`error`,w,!0)}),window.addEventListener(`unhandledrejection`,T,!0),g.push(()=>{window.removeEventListener(`unhandledrejection`,T,!0)})),document.addEventListener(`visibilitychange`,E),g.push(()=>{document.removeEventListener(`visibilitychange`,E)}),window.addEventListener(`pagehide`,D),g.push(()=>{window.removeEventListener(`pagehide`,D)}),t.captureConsole&&g.push(v(e,{onError:t.onError})),t.captureNetwork&&g.push(y(e,{ignoreUrlPatterns:t.ignoreUrlPatterns,now:t.now,onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),t.captureNavigation&&g.push(b(e,{onError:t.onError,redactUrlPatterns:t.redactUrlPatterns})),h.start(),{sessionId:c,recordingId:l,transport:h,captureError:C,deactivate:async(e=!1)=>(S??=(async()=>{let t=h.shutdown({keepalive:e});_=!1,$(g),await t})(),S),discard:()=>{_=!1,$(g),h.discard()}}}catch(e){throw _=!1,$(g),h.discard(),e}}function rt(e){if(e.replayUrl.length===0)throw Error("logfire session replay: `replayUrl` is required");let t=new URL(e.replayUrl,`https://logfire.invalid/`);if(t.search!==``||t.hash!==``)throw Error("logfire session replay: `replayUrl` must not contain a query or fragment");let n=e.fetchImpl??(typeof fetch==`function`?fetch.bind(globalThis):void 0);if(n===void 0)throw Error("logfire session replay: no `fetch` available; pass `fetchImpl`");return{replayUrl:e.replayUrl,headers:e.headers,token:e.token,getSessionId:e.getSessionId,getSessionAttributes:e.getSessionAttributes,sessionSampleRate:e.sessionSampleRate??l.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate??l.onErrorSampleRate,maskAllText:e.maskAllText??l.maskAllText,maskAllInputs:e.maskAllInputs??l.maskAllInputs,maskTextSelector:e.maskTextSelector??l.maskTextSelector,blockSelector:e.blockSelector??l.blockSelector,flushIntervalMs:e.flushIntervalMs??l.flushIntervalMs,maxBufferBytes:e.maxBufferBytes??l.maxBufferBytes,minSessionDurationMs:e.minSessionDurationMs??l.minSessionDurationMs,sessionIdleTimeoutMs:e.sessionIdleTimeoutMs??l.sessionIdleTimeoutMs,maxSessionDurationMs:e.maxSessionDurationMs??l.maxSessionDurationMs,distinctId:e.distinctId??l.distinctId,getDistinctId:e.getDistinctId,getUser:e.getUser,captureConsole:e.captureConsole??l.captureConsole,captureNetwork:e.captureNetwork??l.captureNetwork,captureNavigation:e.captureNavigation??l.captureNavigation,captureGlobalErrors:e.captureGlobalErrors??l.captureGlobalErrors,ignoreUrlPatterns:e.ignoreUrlPatterns??[],redactUrlPatterns:e.redactUrlPatterns??[...l.redactUrlPatterns],onError:e.onError,fetchImpl:n,now:e.now??Date.now,random:e.random??Math.random}}function it(e){let t=Ve();if(t===void 0)return;let n=qe();return n===null?void 0:{locks:t,records:new Ke(n,e)}}function at(e,t,n){let r=ot(n,t);if(r!==void 0)return r;let i=We({sessionSampleRate:e.sessionSampleRate,onErrorSampleRate:e.onErrorSampleRate,random:e.random});return st(n,t,i),i}function ot(e,t){if(e!==null)try{let n=e.getItem(et);if(n===null)return;let r=JSON.parse(n);if(typeof r!=`object`||!r)return;let i=r;return i.id!==t||!ct(i.mode)?void 0:i.mode}catch{return}}function st(e,t,n){if(e!==null)try{e.setItem(et,JSON.stringify({id:t,mode:n}))}catch{}}function ct(e){return e===`full`||e===`buffer`||e===`off`}function lt(e){return _t(dt(e,`message`)??e)}function ut(e){let t=dt(e,`stack`);return typeof t==`string`?t:void 0}function dt(e,t){try{return typeof e==`object`&&e&&t in e?e[t]:void 0}catch{return}}function ft(e,t){e.catch(e=>{Q(t,e)})}async function pt(e,t){try{await e}catch(e){Q(t,e)}}function Q(e,t){try{let n=e?.(t);mt(n)&&Promise.resolve(n).catch(()=>void 0)}catch{}}function mt(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function ht(){let e=globalThis;if(e[Z]!==void 0)throw Error(`logfire session replay: a replay controller is already active in this page`);let t={};Object.defineProperty(e,Z,{configurable:!0,enumerable:!1,value:t,writable:!0});let n=!1;return()=>{n||(n=!0,e[Z]===t&&Reflect.deleteProperty(e,Z))}}function $(e){for(let t=e.length-1;t>=0;--t)try{e[t]?.()}catch{}e.length=0}function gt(e,t,n){return{message:e,...t===void 0||t.length===0?{}:{source:t},...n===void 0?{}:{stack:n}}}function _t(e){if(e==null)return`unhandledrejection`;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return String(e);try{return Object.prototype.toString.call(e)}catch{return`[object Object]`}}export{c as CHUNK_ENVELOPE_VERSION,s as CustomTag,i as EventType,a as IncrementalSource,o as MouseInteractions,z as ReplayUploadError,tt as startSessionReplay};
|