@depsmith/depsmith-sdk 0.9.3 → 0.9.5
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/CHANGELOG.md +16 -0
- package/README.md +49 -2
- package/dist/depsmith-sdk.global.js +1 -1
- package/dist/depsmith-sdk.global.js.map +1 -1
- package/dist/depsmith-sdk.pixel.global.js +1 -1
- package/dist/depsmith-sdk.replay.global.js +3 -0
- package/dist/depsmith-sdk.replay.global.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/replay.cjs +3 -0
- package/dist/replay.cjs.map +1 -0
- package/dist/replay.d.cts +56 -0
- package/dist/replay.d.ts +56 -0
- package/dist/replay.js +3 -0
- package/dist/replay.js.map +1 -0
- package/package.json +29 -6
package/dist/replay.cjs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"use strict";var te=Object.defineProperty;var it=Object.getOwnPropertyDescriptor;var st=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var ot=(r,e)=>{for(var t in e)te(r,t,{get:e[t],enumerable:!0})},at=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of st(e))!rt.call(r,i)&&i!==t&&te(r,i,{get:()=>e[i],enumerable:!(n=it(e,i))||n.enumerable});return r};var dt=r=>at(te({},"__esModule",{value:!0}),r);var nn={};ot(nn,{ALLOW_ATTR:()=>K,EXCLUDE_ATTR:()=>re,MASK_ATTR:()=>U,NO_CAPTURE_ATTR:()=>oe,default:()=>tn,replaySupported:()=>ee,sessionReplay:()=>we});module.exports=dt(nn);function Re(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e+r.charCodeAt(t)>>>0;return e.toString(36)}var _e="@depsmith/depsmith-sdk",xe="0.9.5";var ne=Symbol.for("depsmith.sdk.replay.registry"),Ae=()=>globalThis[ne]??(globalThis[ne]={});function Me(r){let e=Ae();if(e.integration!==r&&(e.integration=r,e.current))try{r.clientCreated(e.current)}catch{}}function R(r,e){let t=r?.hooks;if(t)try{e(t)}catch{}}var Ce=new WeakMap;function ie(r){let e=Ce.get(r);if(e)return e;let t=r,n=null,i={get config(){let p=t.config;return{debug:p.debug,childSafeMode:p.childSafeMode,apiKey:p.apiKey,endpoint:p.endpoint,sessionTimeoutMs:p.sessionTimeoutMs,libraryName:_e}},sdkVersion:xe,hooks:null,consentState:()=>t.consent.canUpload()?"granted":t.consent.current==="denied"?"denied":"pending",liveSessionId:()=>{let p=t.stopped?null:t.session.load();return p&&t.session.clock.now()-p.lastActivityAt<=t.session.timeoutMs?p.id:null},startSession:()=>t.stopped||!t.consent.canCapture()?null:t.touchSession().sessionId,userId:()=>t.identity.userId,anonymousId:()=>t.identity.anonymousId,currentScreen:()=>n,apiKeyFingerprint:p=>Re(p)};Ce.set(r,i);let s=t.consent,o=()=>s.current==="granted",{optIn:a,optOut:d,reload:c}=s;s.optIn=function(){a.call(s),R(i,p=>p.onConsentChanged(o()))},s.optOut=function(){d.call(s),R(i,p=>p.onConsentChanged(!1))},s.reload=function(){let p=c.call(s);return p&&R(i,f=>f.onConsentChanged(o())),p};let l=t.session,{rotate:u,adopt:h,touch:g}=l;l.rotate=function(){let p=u.call(l);return R(i,f=>f.onSessionRotated(p,"reset")),p},l.adopt=function(p,f){let w=h.call(l,p,f);return w&&R(i,k=>k.onSessionRotated(p,"set_session_id")),w},l.touch=function(){let p=g.call(l),f=p.startedSession;return f&&R(i,w=>w.onSessionRotated(f.id,"timeout")),p};let m=t.queue,y=m.enqueue;m.enqueue=function(p){if(y.call(m,p),p?.event_type==="page_view"){let f=p.properties?.$page_name;typeof f=="string"&&f&&(n=f,R(i,w=>w.onScreen(f)))}R(i,f=>f.onEventAccepted(p.event_id,p.session_id,p.event))};let v=t.shutdown;return t.shutdown=function(){v.call(r),se(i,!1)},i}function se(r,e){r?.hooks&&(R(r,t=>t.onShutdown(e)),r.hooks=null)}var U="data-depsmith-sdk-mask",K="data-depsmith-sdk-allow",re="data-depsmith-sdk-exclude",oe="data-depsmith-sdk-no-capture",lt=`[${re}],[${oe}]`;function ae(r){if(r.tagName!=="INPUT")return!1;let e=r;if((e.getAttribute("type")??"").toLowerCase()==="password")return!0;let n=(e.getAttribute("autocomplete")??"").toLowerCase();if(n.includes("one-time-code")||n.includes("current-password")||n.includes("new-password"))return!0;let i=e.style?.webkitTextSecurity;return!!i&&i!=="none"}function ut(r){if(!r)return!1;let e=r.tagName;if(e==="TEXTAREA"||e==="SELECT")return!0;if(e==="INPUT"){let t=(r.type||"text").toLowerCase();return!["button","submit","reset","checkbox","radio","image","range","color","file"].includes(t)}return r.isContentEditable===!0}function Ie(r){if(!r)return!1;if(ut(r))return!0;try{return r.closest(lt)!==null}catch{return!0}}function Ee(r){let e=r.activeElement;for(let t=0;t<8&&e?.shadowRoot?.activeElement;t++)e=e.shadowRoot.activeElement;return!!e&&ae(e)}var ct="#e5e7eb",ht="#cbd5e1",pt=new Set(["SCRIPT","STYLE","LINK","META","HEAD","TITLE","NOSCRIPT","TEMPLATE","BASE","SOURCE","TRACK","PARAM","AREA","MAP"]),Te=new Set(["IFRAME","EMBED","OBJECT","FRAME"]),z=class{constructor(e,t,n=256){this.onLoad=e;this.origin=t;this.max=n;this.entries=new Map}url(e){if(!e||e.startsWith("javascript:"))return null;let t=this.entries.get(e);return t==="loading"||t==="failed"?null:t||(this.load(e,e),null)}svg(e){let t=`svg:${e.length}:${ft(e)}`,n=this.entries.get(t);if(n==="loading"||n==="failed")return null;if(n)return n;let i=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(e)}`;return this.load(t,i),null}load(e,t){if(typeof Image>"u")return;if(this.entries.size>=this.max){let s=this.entries.keys().next().value;s!==void 0&&this.entries.delete(s)}this.entries.set(e,"loading");let n=new Image,i=!1;try{let s=new URL(t,this.origin);i=s.protocol.startsWith("http")&&s.origin!==this.origin}catch{}i&&(n.crossOrigin="anonymous"),n.decoding="async",n.onload=()=>{this.entries.set(e,n),this.onLoad()},n.onerror=()=>this.entries.set(e,"failed"),n.src=t}};function ft(r){let e=2166136261;for(let t=0;t<r.length;t++)e=Math.imul(e^r.charCodeAt(t),16777619);return(e>>>0).toString(36)}var Pe=(r,e)=>{let t="left"in r?r.left:r.x,n="top"in r?r.top:r.y,i="width"in r?r.width:r.w,s="height"in r?r.height:r.h;return t<e.x+e.w&&t+i>e.x&&n<e.y+e.h&&n+s>e.y&&i>0&&s>0},b=r=>{let e=parseFloat(r);return Number.isFinite(e)?e:0};function A(r){return!r||r==="transparent"||r==="rgba(0, 0, 0, 0)"||/^rgba\(.+,\s*0\)$/.test(r)?null:r}function De(r,e,t,n,i){let s={ctx:e,vw:t,vh:n,opts:i,now:i.now??(()=>performance.now()),visited:0,aborted:!1,canvases:[],origin:r.location?.origin??""};try{e.setTransform(1,0,0,1,0,0),e.globalAlpha=1,e.fillStyle=gt(r),e.fillRect(0,0,e.canvas.width,e.canvas.height),e.setTransform(i.scale,0,0,i.scale,0,0);let o=r.documentElement,a={x:0,y:0,w:t,h:n};o&&le(s,o,a,1,!1),r.body&&le(s,r.body,a,1,!1,!0)}catch{}finally{e.setTransform(1,0,0,1,0,0),e.globalAlpha=1}return s.aborted?{ok:!1,reason:"budget"}:{ok:!0,canvases:s.canvases}}function gt(r){let e=r.defaultView;if(!e)return"#ffffff";for(let t of[r.documentElement,r.body]){if(!t)continue;let n=A(e.getComputedStyle(t).backgroundColor);if(n)return n}return"#ffffff"}function mt(r){if(r.shadowRoot)return Array.from(r.shadowRoot.childNodes);if(r.tagName==="SLOT"){let e=r.assignedNodes?.({flatten:!0})??[];if(e.length)return e}return Array.from(r.childNodes)}function le(r,e,t,n,i,s=!1){let o=e.ownerDocument.defaultView,a=[],d=[],c=0;for(let l of mt(e)){if(r.aborted)return;if(l.nodeType===3){Mt(r,l,e,t,n,i);continue}if(l.nodeType!==1)continue;let u=l;if(pt.has(u.tagName)||!s&&e===e.ownerDocument.documentElement&&u.tagName==="BODY")continue;if(o.getComputedStyle(u).position!=="static"){let g=parseInt(o.getComputedStyle(u).zIndex,10),m={el:u,z:Number.isFinite(g)?g:0,order:c++};m.z<0?a.push(m):d.push(m);continue}de(r,u,t,n,i)}for(let l of a.sort((u,h)=>u.z-h.z||u.order-h.order))de(r,l.el,t,n,i);for(let l of d.sort((u,h)=>u.z-h.z||u.order-h.order))de(r,l.el,t,n,i)}function yt(r){return++r.visited%64===0&&r.now()>r.opts.deadline&&(r.aborted=!0),r.aborted}function de(r,e,t,n,i){if(yt(r))return;let s=e.ownerDocument.defaultView,o=e.getBoundingClientRect(),a=s.getComputedStyle(e);if(a.display==="none")return;let d=n*(parseFloat(a.opacity)||(a.opacity==="0"?0:1));if(d<=.01)return;let l=a.position==="fixed"?{x:0,y:0,w:r.vw,h:r.vh}:t,u=a.visibility!=="hidden"&&a.visibility!=="collapse",h=Pe(o,l),g=r.ctx;if(e.hasAttribute(U)){h&&ue(g,l,()=>qe(g,o,d,Le(a)));return}let m=i||e.hasAttribute(K);u&&h&&ue(g,l,()=>{g.globalAlpha=d,wt(r,e,o,a),kt(r,e,o,a,m)});let y=e.tagName;if(Te.has(y)||y==="VIDEO"||y==="CANVAS"||y==="IMG"||y==="svg"||y==="SVG"||y==="INPUT"||y==="TEXTAREA"||y==="SELECT"||e.namespaceURI==="http://www.w3.org/2000/svg")return;let v=l;if(a.overflowX!=="visible"||a.overflowY!=="visible"||a.contain.includes("paint")){let p={x:o.left+b(a.borderLeftWidth),y:o.top+b(a.borderTopWidth),w:o.width-b(a.borderLeftWidth)-b(a.borderRightWidth),h:o.height-b(a.borderTopWidth)-b(a.borderBottomWidth)};if(v=vt(l,p),v.w<=0||v.h<=0)return}!h&&e.childElementCount===0&&!e.shadowRoot||le(r,e,v,d,m)}function vt(r,e){let t=Math.max(r.x,e.x),n=Math.max(r.y,e.y);return{x:t,y:n,w:Math.min(r.x+r.w,e.x+e.w)-t,h:Math.min(r.y+r.h,e.y+e.h)-n}}function ue(r,e,t){r.save(),r.beginPath(),r.rect(e.x,e.y,e.w,e.h),r.clip();try{t()}finally{r.restore()}}function W(r,e,t){r.beginPath();let n=Math.max(0,Math.min(t,e.w/2,e.h/2));n>0&&typeof r.roundRect=="function"?r.roundRect(e.x,e.y,e.w,e.h,n):r.rect(e.x,e.y,e.w,e.h)}function Oe(r){return{x:r.left,y:r.top,w:r.width,h:r.height}}function qe(r,e,t,n){r.globalAlpha=t,r.fillStyle=n;let i="left"in e?Oe(e):e;r.fillRect(i.x,i.y,i.w,i.h)}var ce="#d1d5db",bt="#e5e7eb";function Le(r){return ce}function wt(r,e,t,n){let i=r.ctx,s=Oe(t),o=b(n.borderTopLeftRadius),a=A(n.backgroundColor);a&&(i.fillStyle=a,W(i,s,o),i.fill());let d=n.backgroundImage;if(d&&d!=="none"){let u=/url\(["']?([^"')]+)["']?\)/.exec(d)?.[1];if(u){let h=r.opts.images.url(new URL(u,e.ownerDocument.baseURI).href);h&&St(i,h,s,n,o)}else{let h=/(rgba?\([^)]+\)|#[0-9a-f]{3,8})/i.exec(d)?.[1];h&&(i.fillStyle=h,W(i,s,o),i.fill())}}let c=[[n.borderTopWidth,n.borderTopStyle,n.borderTopColor,[s.x,s.y,s.w,0]],[n.borderBottomWidth,n.borderBottomStyle,n.borderBottomColor,[s.x,s.y+s.h,s.w,0]],[n.borderLeftWidth,n.borderLeftStyle,n.borderLeftColor,[s.x,s.y,0,s.h]],[n.borderRightWidth,n.borderRightStyle,n.borderRightColor,[s.x+s.w,s.y,0,s.h]]];if(c.every(u=>u[0]===c[0][0]&&u[1]===c[0][1]&&u[2]===c[0][2])&&o>0){let u=b(c[0][0]),h=A(c[0][2]);u>0&&h&&c[0][1]!=="none"&&c[0][1]!=="hidden"&&(i.strokeStyle=h,i.lineWidth=u,W(i,{x:s.x+u/2,y:s.y+u/2,w:s.w-u,h:s.h-u},o-u/2),i.stroke());return}for(let[u,h,g,[m,y,v,p]]of c){let f=b(u),w=A(g);f<=0||!w||h==="none"||h==="hidden"||(i.fillStyle=w,v===0?i.fillRect(m===s.x?m:m-f,y,f,p):i.fillRect(m,y===s.y?y:y-f,v,f))}}function St(r,e,t,n,i){let s=e.naturalWidth||e.width||0,o=e.naturalHeight||e.height||0;if(!s||!o)return;r.save(),W(r,t,i),r.clip();let a=n.backgroundSize;if(a==="cover"||a==="contain"){let d=a==="cover"?Math.max(t.w/s,t.h/o):Math.min(t.w/s,t.h/o),c=s*d,l=o*d;r.drawImage(e,t.x+(t.w-c)/2,t.y+(t.h-l)/2,c,l)}else if(n.backgroundRepeat.startsWith("no-repeat")||a.includes("100%"))r.drawImage(e,t.x,t.y,a.includes("100%")?t.w:s,a.includes("100%")?t.h:o);else{let d=r.createPattern(e,"repeat");d&&(r.fillStyle=d,r.translate(t.x,t.y),r.fillRect(0,0,t.w,t.h))}r.restore()}function kt(r,e,t,n,i){let s=r.ctx,o=e.tagName,a=Rt(t,n);if(o==="IMG"||o==="INPUT"&&e.type==="image"){let d=e,c=_t(r,d);c?xt(s,c,a,n.objectFit,d.naturalWidth,d.naturalHeight):(d.complete===!1||d.naturalWidth>0)&&H(s,a);return}if(o==="CANVAS"){let d=e;if(r.opts.tainted.has(d)||d.width===0||d.height===0)H(s,a);else try{s.drawImage(d,a.x,a.y,a.w,a.h),r.canvases.push(d)}catch{H(s,a)}return}if(o==="VIDEO"){s.fillStyle="#111827",s.fillRect(a.x,a.y,a.w,a.h);return}if(Te.has(o)){H(s,a);return}if(e.namespaceURI==="http://www.w3.org/2000/svg"&&e.tagName.toLowerCase()==="svg"){At(r,e,t);return}(o==="INPUT"||o==="TEXTAREA"||o==="SELECT")&&Ct(r,e,a,n,i)}function Rt(r,e){let t=b(e.borderLeftWidth)+b(e.paddingLeft),n=b(e.borderTopWidth)+b(e.paddingTop),i=b(e.borderRightWidth)+b(e.paddingRight),s=b(e.borderBottomWidth)+b(e.paddingBottom);return{x:r.left+t,y:r.top+n,w:Math.max(0,r.width-t-i),h:Math.max(0,r.height-n-s)}}function H(r,e){e.w<=0||e.h<=0||(r.fillStyle=ct,r.fillRect(e.x,e.y,e.w,e.h),r.strokeStyle=ht,r.lineWidth=1,r.strokeRect(e.x+.5,e.y+.5,Math.max(0,e.w-1),Math.max(0,e.h-1)))}function _t(r,e){if(!e.complete||e.naturalWidth===0)return null;let t=e.currentSrc||e.src;if(!t)return null;let n=!1;try{let i=new URL(t,e.ownerDocument.baseURI);n=i.protocol==="data:"||i.protocol==="blob:"||i.origin===r.origin}catch{return null}return n||e.crossOrigin==="anonymous"||e.crossOrigin==="use-credentials"?e:r.opts.images.url(t)}function xt(r,e,t,n,i,s){if(t.w<=0||t.h<=0)return;let o=i||e.naturalWidth||t.w,a=s||e.naturalHeight||t.h;if(n==="cover"||n==="contain"||n==="scale-down"){let d=n==="cover"?Math.max(t.w/o,t.h/a):Math.min(t.w/o,t.h/a);n==="scale-down"&&(d=Math.min(1,d));let c=o*d,l=a*d;r.save(),r.beginPath(),r.rect(t.x,t.y,t.w,t.h),r.clip(),r.drawImage(e,t.x+(t.w-c)/2,t.y+(t.h-l)/2,c,l),r.restore();return}r.drawImage(e,t.x,t.y,t.w,t.h)}function At(r,e,t){let n=r.ctx,i=Array.from(e.querySelectorAll("text, foreignObject")),s=null;try{let a=e.cloneNode(!0);for(let c of Array.from(a.querySelectorAll('text, foreignObject, script, image, use[href^="http"]')))c.remove();a.setAttribute("width",String(t.width)),a.setAttribute("height",String(t.height)),a.getAttribute("xmlns")||a.setAttribute("xmlns","http://www.w3.org/2000/svg");let d=e.ownerDocument.defaultView.getComputedStyle(e).color;a.setAttribute("color",d),s=new XMLSerializer().serializeToString(a)}catch{s=null}let o=s&&s.length<2e5?r.opts.images.svg(s):null;o&&n.drawImage(o,t.left,t.top,t.width,t.height);for(let a of i){let d=a.getBoundingClientRect();d.width>0&&d.height>0&&qe(n,d,n.globalAlpha,Le(a.ownerDocument.defaultView.getComputedStyle(a)))}}function Ct(r,e,t,n,i){let s=r.ctx,o=e.tagName,a=o==="INPUT"?(e.type||"text").toLowerCase():o.toLowerCase();if(a==="checkbox"||a==="radio"){let h=Math.min(t.w,t.h);if(h<=0)return;s.strokeStyle="#6b7280",s.lineWidth=1.5,s.beginPath(),a==="radio"?s.arc(t.x+t.w/2,t.y+t.h/2,h/2-1,0,Math.PI*2):s.rect(t.x+1,t.y+1,h-2,h-2),s.stroke(),e.checked&&(s.fillStyle=A(n.accentColor)??"#2563eb",s.beginPath(),a==="radio"?s.arc(t.x+t.w/2,t.y+t.h/2,h/4,0,Math.PI*2):s.rect(t.x+3,t.y+3,h-6,h-6),s.fill());return}if(["range","color","file","hidden"].includes(a))return;let d=ae(e),c=b(n.fontSize)||14,l=Math.min(t.h,c*1.25);if(i&&!d){let h=o==="SELECT"?e.selectedOptions?.[0]?.text??"":e.value||e.placeholder||"";if(!h)return;s.save(),s.beginPath(),s.rect(t.x,t.y,t.w,t.h),s.clip(),s.fillStyle=(e.value||o==="SELECT"?A(n.color):null)??"#9ca3af",s.font=n.font||`${c}px sans-serif`,s.textBaseline="middle",s.fillText(h,t.x,o==="TEXTAREA"?t.y+l/2:t.y+t.h/2),s.restore();return}(o==="SELECT"||d||e.value!==""||e.placeholder)&&(s.fillStyle=o==="SELECT"||d||e.value!==""?ce:bt,s.fillRect(t.x,o==="TEXTAREA"?t.y:t.y+(t.h-l)/2,t.w,o==="TEXTAREA"?t.h:l))}function Mt(r,e,t,n,i,s){let o=e.data;if(!o||!/\S/.test(o))return;let d=t.ownerDocument.defaultView.getComputedStyle(t);if(d.visibility==="hidden"||d.display==="none")return;let c=t.ownerDocument.createRange();c.selectNodeContents(e);let l=Array.from(c.getClientRects()).filter(h=>h.width>0&&h.height>0&&Pe(h,n));if(l.length===0)return;let u=r.ctx;ue(u,n,()=>{if(s&&!It(t)){u.globalAlpha=i,u.fillStyle=A(d.color)??"#111827",u.font=d.font,u.textBaseline="alphabetic",Et(u,e,c);return}u.globalAlpha=i,u.fillStyle=ce;for(let h of l){let g=Math.max(0,(h.height-(b(d.fontSize)||h.height))/2);u.fillRect(h.left,h.top+g,h.width,h.height-g*2)}})}function It(r){return r.closest('input[type="password"]')!==null}function Et(r,e,t){let n=e.data,i=/\S+/g,s,o=0;for(;(s=i.exec(n))&&o++<2e3;){t.setStart(e,s.index),t.setEnd(e,s.index+s[0].length);let a=t.getClientRects()[0];!a||a.width===0||r.fillText(s[0],a.left,a.bottom-a.height*.22,a.width+1)}}var j=class{constructor(e,t,n){this.maxFps=e;this.burstFps=t;this.keyframeIntervalMs=n;this.dirty=!0;this.lastAcquiredAt=-Number.MAX_SAFE_INTEGER/2;this.burstUntil=-Number.MAX_SAFE_INTEGER/2}update(e,t,n){this.maxFps=e,this.burstFps=t,this.keyframeIntervalMs=n}get isDirty(){return this.dirty}onDirty(){this.dirty=!0}onBurst(e){this.dirty=!0,this.burstUntil=e+Tt}delayUntilDue(e){let t=e<this.burstUntil?Math.max(this.burstFps,this.maxFps):this.maxFps,n=t>0?Math.floor(1e3/t):Number.MAX_SAFE_INTEGER/4,i=e-this.lastAcquiredAt,s=this.dirty?n-i:this.keyframeIntervalMs-i;return Math.max(0,s)}onAcquired(e){this.lastAcquiredAt=e,this.dirty=!1}onDiscarded(){this.dirty=!0}},Tt=3e3;var q=class{constructor(e){this.tileSize=e;this.width=-1;this.height=-1;this.hashes=new Uint32Array(0)}reset(){this.width=-1,this.height=-1,this.hashes=new Uint32Array(0)}diff(e,t,n){if(e.length<t*n)throw new Error("pixels too short");let i=this.tileSize,s=Math.ceil(t/i),o=Math.ceil(n/i),a=new Uint32Array(s*o),d=[],c=t===this.width&&n===this.height&&this.hashes.length===a.length;for(let l=0;l<o;l++)for(let u=0;u<s;u++){let h=u*i,g=l*i,m=Math.min(i,t-h),y=Math.min(i,n-g),v=Pt(e,t,h,g,m,y),p=l*s+u;a[p]=v,c&&this.hashes[p]!==v&&d.push([h,g,m,y])}return this.hashes=a,this.width=t,this.height=n,c?d:null}tileCount(e,t){return Math.ceil(e/this.tileSize)*Math.ceil(t/this.tileSize)}};function Pt(r,e,t,n,i,s){let o=2166136261;for(let a=n;a<n+s;a++){let d=a*e+t,c=d+i;for(;d<c;)o=Math.imul(o^r[d],16777619),d++}return o>>>0}var Fe=4096,Dt=100,G=class{constructor(e,t=window){this.engine=e;this.win=t;this.policy=null;this.scheduler=new j(2,4,3e4);this.diff=new q(64);this.canvas=null;this.ctx=null;this.timer=null;this.timerDue=0;this.raf=null;this.busy=!1;this.codec=null;this.tainted=new WeakSet;this.observer=null;this.detachers=[];this.pointerDetachers=[];this.redactedPointers=new Map;this.lastMove=new Map;this.generation=0;this.images=new z(()=>this.dirty(),t.location.origin),e.onCaptureChanged=n=>this.setPolicy(n),e.onFrameDropped=()=>this.dirty(),this.attachPointers()}now(){return this.win.performance.now()}setPolicy(e){let t=this.policy;if(this.policy=e,!e){this.detach();return}this.scheduler.update(e.maxFps,e.burstFps,e.keyframeIntervalSeconds*1e3),(!t||t.tileSize!==e.tileSize||t.captureScale!==e.captureScale)&&(this.diff=new q(e.tileSize)),t||this.attach(),this.scheduler.onDirty(),this.schedule()}dispose(){this.detach();for(let e of this.pointerDetachers.splice(0))e();this.engine.onCaptureChanged=null,this.engine.onFrameDropped=null}attach(){let e=this.win.document,t=this.win.MutationObserver;t&&(this.observer=new t(()=>this.dirty()),this.observer.observe(e,{subtree:!0,childList:!0,attributes:!0,characterData:!0}));let n=(i,s,o)=>{i.addEventListener(s,o,{capture:!0,passive:!0}),this.detachers.push(()=>i.removeEventListener(s,o,{capture:!0}))};for(let i of["scroll","input","change","load","transitionend","animationend","focusin","focusout"])n(e,i,()=>this.dirty());n(this.win,"resize",()=>this.dirty()),this.canvas=e.createElement("canvas"),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0,alpha:!1})}detach(){this.generation++,this.observer?.disconnect(),this.observer=null;for(let e of this.detachers.splice(0))e();this.timer!==null&&clearTimeout(this.timer),this.timer=null,this.raf!==null&&this.win.cancelAnimationFrame?.(this.raf),this.raf=null,this.canvas=null,this.ctx=null,this.diff.reset()}dirty(){this.policy&&(this.scheduler.onDirty(),this.schedule())}burst(){this.policy&&(this.scheduler.onBurst(this.now()),this.schedule())}schedule(){if(!this.policy||this.raf!==null||this.busy)return;let e=this.now(),t=this.scheduler.delayUntilDue(e);if(this.timer!==null){if(e+t>=this.timerDue)return;clearTimeout(this.timer)}this.timerDue=e+t,this.timer=setTimeout(()=>{this.timer=null;let n=()=>{this.raf=null,this.acquire()};typeof this.win.requestAnimationFrame=="function"&&this.win.document.visibilityState!=="hidden"?this.raf=this.win.requestAnimationFrame(n):n()},Math.min(t,2147e6))}viewport(){let e=this.win.visualViewport,t=Math.max(1,Math.round(this.win.innerWidth||e?.width||1)),n=Math.max(1,Math.round(this.win.innerHeight||e?.height||1));return{w:t,h:n}}async acquire(){let e=this.policy,t=this.ctx;if(!e||!t||!this.canvas||this.busy)return;this.busy=!0;let n=this.generation,i=this.now();this.scheduler.onAcquired(i);try{let{w:s,h:o}=this.viewport(),a=Math.min(e.captureScale,Fe/s,Fe/o),d=Math.max(1,Math.round(s*a)),c=Math.max(1,Math.round(o*a));(this.canvas.width!==d||this.canvas.height!==c)&&(this.canvas.width=d,this.canvas.height=c,this.diff.reset());let l=De(this.win.document,t,s,o,{scale:a,deadline:i+e.uiBudgetMs,images:this.images,tainted:this.tainted});if(!l.ok){this.discard();return}let u;try{u=new Uint32Array(t.getImageData(0,0,d,c).data.buffer)}catch{for(let p of l.canvases)this.tainted.add(p);this.discard();return}if(this.now()-i>e.uiBudgetMs){this.discard();return}let h=this.diff.diff(u,d,c),g=e.imageQuality/100,m=this.engine.wantsKeyframe||h===null;if(!m&&h.length===0)return;if(m||h.length>this.diff.tileCount(d,c)/2){let p=await this.encode(this.canvas,g,d,c);if(n!==this.generation)return;if(!p){this.diff.reset(),this.discard();return}this.engine.submitFrame({keyframe:p});return}let v=[];for(let[p,f,w,k]of h){let N=this.win.document.createElement("canvas");N.width=w,N.height=k;let Se=N.getContext("2d",{alpha:!1});if(!Se){this.diff.reset(),this.discard();return}Se.drawImage(this.canvas,p,f,w,k,0,0,w,k);let ke=await this.encode(N,g,w,k);if(!ke){this.diff.reset(),this.discard();return}v.push([[p,f,w,k],ke])}if(n!==this.generation)return;this.engine.submitFrame({tiles:v})}catch{this.diff.reset(),this.discard()}finally{this.busy=!1,n===this.generation&&this.win.document.getAnimations?.().some(s=>s.playState==="running")&&this.scheduler.onDirty(),n===this.generation&&this.schedule()}}discard(){this.scheduler.onDiscarded(),this.engine.frameDiscarded()}async encode(e,t,n,i){if(this.codec===null)try{this.codec=e.toDataURL("image/webp",.1).startsWith("data:image/webp")?"webp":"jpeg"}catch{return null}let s=this.codec,o=await new Promise(d=>{try{e.toBlob(d,s==="webp"?"image/webp":"image/jpeg",t)}catch{d(null)}});if(!o)return null;let a=new Uint8Array(await o.arrayBuffer());return Ot(s,a)?{codec:s,w:n,h:i,bytes:a}:null}attachPointers(){let e=this.win,t=i=>s=>this.pointer(i,s),n=[["pointerdown",t("down")],["pointerup",t("up")],["pointermove",t("move")],["pointercancel",t("cancel")]];for(let[i,s]of n)e.addEventListener(i,s,{capture:!0,passive:!0}),this.pointerDetachers.push(()=>e.removeEventListener(i,s,{capture:!0}))}pointer(e,t){if(!this.engine.touchesWanted)return;let n=t.pointerId??1;if(e==="move"&&!this.redactedPointers.has(n))return;if(e==="move"){let c=this.now();if(c-(this.lastMove.get(n)??-1/0)<Dt)return;this.lastMove.set(n,c)}e==="down"&&this.burst();let i=t.composedPath?.()[0]instanceof Element?t.composedPath()[0]:t.target,s=Ie(i)||Ee(this.win.document),o;e==="down"?(o=s,this.redactedPointers.set(n,s)):o=s||(this.redactedPointers.get(n)??!1),(e==="up"||e==="cancel")&&(this.redactedPointers.delete(n),this.lastMove.delete(n));let{w:a,h:d}=this.viewport();this.engine.submitTouch(e,t.clientX/a,t.clientY/d,Math.max(1,this.redactedPointers.size||1),o?"exclude":"plain")}};function Ot(r,e){return r==="jpeg"?e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255:e.length>=12&&String.fromCharCode(e[0],e[1],e[2],e[3])==="RIFF"&&String.fromCharCode(e[8],e[9],e[10],e[11])==="WEBP"}var C="safe-default-v1";var he={policy_version:1,profile:C,max_stale_seconds:60,max_recording_seconds:1800,max_recording_bytes:20971520,max_chunk_bytes:1048576,chunk_max_seconds:10,max_fps:2,burst_fps:4,keyframe_interval_seconds:30,tile_size:64,ui_budget_ms:40,image_quality:60,capture_scale:.5,excluded_screens:[]},qt=r=>typeof r=="number"&&Number.isInteger(r),Lt=r=>typeof r=="number"&&Number.isFinite(r);function M(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=r;if(e.profile!==C)return null;let t=["policy_version","max_stale_seconds","max_recording_seconds","max_recording_bytes","max_chunk_bytes","chunk_max_seconds","keyframe_interval_seconds","tile_size","ui_budget_ms","image_quality"];for(let s of t)if(!qt(e[s]))return null;for(let s of["max_fps","burst_fps","capture_scale"])if(!Lt(e[s]))return null;let n=e.excluded_screens;if(!Array.isArray(n)||n.some(s=>typeof s!="string"))return null;let i={version:e.policy_version,maxStaleSeconds:e.max_stale_seconds,maxRecordingSeconds:e.max_recording_seconds,maxRecordingBytes:e.max_recording_bytes,maxChunkBytes:Math.min(e.max_chunk_bytes,1048576),chunkMaxSeconds:e.chunk_max_seconds,maxFps:e.max_fps,burstFps:e.burst_fps,keyframeIntervalSeconds:e.keyframe_interval_seconds,tileSize:e.tile_size,uiBudgetMs:e.ui_budget_ms,imageQuality:e.image_quality,captureScale:e.capture_scale,excludedScreens:new Set(n)};return i.version<1||i.maxFps<=0||i.maxStaleSeconds<=0||i.chunkMaxSeconds<=0||i.tileSize<8||i.captureScale<=0||i.captureScale>1?null:i}var _=r=>r.type==="keyframe"||r.type==="patch",V=r=>(r.images??[]).reduce((e,t)=>e+t.bytes.length,0)+200,Ft=[68,83,82,67],Bt=1,Nt=32,Be=new TextEncoder;function L(r,e,t,n,i,s){if(i.length===0)throw new Error("a chunk has at least one record");let o=[],a=[],d=[],c=[],l=n;for(let p of i){let f={seq:l,t:p.t,type:p.type};p.type==="keyframe"?(Object.assign(f,p.fields),o.push(p.images[0]),f.image=o.length,d.push(p.fields.frame_id)):p.type==="patch"?(f.base_frame_id=p.fields.base_frame_id,c.push(p.fields.base_frame_id),f.tiles=p.fields.tiles.map((w,k)=>(o.push(p.images[k]),{...w,image:o.length}))):Object.assign(f,p.fields),a.push(JSON.stringify(f)),l++}let u=Be.encode(a.join(`
|
|
2
|
+
`)),g=i.find(p=>p.type==="patch")?.fields.base_frame_id,m=g&&!d.includes(g)?g:null,y=Ne({recording_id:r,stream_id:e,chunk_seq:t,first_seq:n,last_seq:l-1,first_t:i[0].t,last_t:i[i.length-1].t,keyframe_ids:d,base_frame_id:m,profile:C,policy_version:s},u.length,u.length,o),v=o.reduce((p,f)=>p+f.bytes.length,0);return{recordingId:r,streamId:e,chunkSeq:t,firstSeq:n,lastSeq:l-1,ndjson:u,header:y,images:o,bound:10+y.length+Nt+u.length+v,keyframes:d,bases:c}}function Ne(r,e,t,n){let i=[{kind:"records",codec:"deflate-ndjson",offset:0,length:e,uncompressed_length:t}],s=e;for(let o of n)i.push({kind:"image",codec:o.codec,offset:s,length:o.bytes.length,w:o.w,h:o.h}),s+=o.bytes.length;return Be.encode(JSON.stringify({...r,sections:i}))}async function Ut(r){let e=new Blob([r]).stream().pipeThrough(new CompressionStream("deflate-raw"));return new Uint8Array(await new Response(e).arrayBuffer())}async function Kt(r){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",r)),t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}async function Ue(r){let e=await Ut(r.ndjson),t=JSON.parse(new TextDecoder().decode(r.header));delete t.sections;let n=Ne(t,e.length,r.ndjson.length,r.images),i=10+n.length+e.length+r.images.reduce((d,c)=>d+c.bytes.length,0),s=new Uint8Array(i);s.set(Ft,0);let o=new DataView(s.buffer);o.setUint16(4,Bt),o.setUint32(6,n.length),s.set(n,10);let a=10+n.length;s.set(e,a),a+=e.length;for(let d of r.images)s.set(d.bytes,a),a+=d.bytes.length;return{bytes:s,sha256:await Kt(s)}}function Ke(){try{return typeof CompressionStream>"u"||typeof Blob>"u"?!1:(new CompressionStream("deflate-raw"),typeof crypto<"u"&&typeof crypto.subtle?.digest=="function")}catch{return!1}}var me=class{constructor(){this.values=new Map}get(e){let t=this.values.get(e);return t===void 0?null:JSON.parse(t)}set(e,t){this.values.set(e,JSON.stringify(t))}},T="web-main",He="Web",$=5e5,We=1e4,Ht=1e4,ze=3e6,je=10*1024*1024,pe=4*1024*1024,Wt=24*3600*1e3,F=-Number.MAX_SAFE_INTEGER/2,Ge=6e4,zt=5*6e4,ye=200,fe=1024*1024,S=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:null,x=r=>typeof r=="string"?r:null,P=r=>typeof r=="number"&&Number.isInteger(r)?r:null,X=(r,e,t)=>Math.min(t,Math.max(e,r));function Ve(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let r=new Uint8Array(16);crypto.getRandomValues(r),r[6]=r[6]&15|64,r[8]=r[8]&63|128;let e=[...r].map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}var J=class{constructor(e,t){this.host=e;this.status={state:"off"};this.capturePolicy=null;this.wantsKeyframe=!0;this.onCaptureChanged=null;this.onFrameDropped=null;this.touchesWanted=!1;this.armed=!1;this.autoArmed=!1;this.hostStopped=!1;this.remoteChecking=!1;this.cfg=null;this.waiting=!1;this.triggered=!1;this.provisionals=new Set;this.options={allowedScreens:null,excludedScreens:new Set};this.admitting=!1;this.admissionAttempt=0;this.rotateAfterAdmission=!1;this.selfStarted=null;this.startingSession=!1;this.startWaiters=[];this.active=null;this.uploads=new Map;this.revokes=[];this.grants=new Map;this.checksumRetried=new Set;this.foreground=!0;this.backgroundSince=null;this.currentScreen=null;this.lastSuccessAt=0;this.backoffUntil=0;this.backoffMs=0;this.quotaUntil=0;this.lastRefreshAt=F;this.shutDown=!1;this.burstUntilMono=F;this.inflight=new Set;this.ticker=null;this.pumping=!1;this.pumpAgain=!1;this.writing=new Map;this.deps={startTimeoutMs:Ht,state:new me,...t}}log(e,t,n){try{this.deps.log?this.deps.log(e,t,n):(this.host.config.debug||e==="error")&&(e==="debug"?console.debug:e==="warn"?console.warn:console.error)(`[depsmith-sdk] ${t}`,n??"")}catch{}}bind(){this.host.hooks=this,this.post(async()=>{let e=this.host.currentScreen();e&&(this.currentScreen=e),this.deps.autoStart&&this.mayAuto()&&(this.cfg=this.cachedConfig(),this.eventRule()&&await this.applyConfig()),await this.recover(),await this.autoCheck()})}async idle(){for(let e=0;e<1e4&&this.inflight.size>0;e++)await Promise.allSettled([...this.inflight])}post(e){if(this.shutDown)return;let t=(async()=>{try{await e(),this.publishCapture()}catch(n){this.log("error","replay error",n)}})();this.track(t)}track(e){return this.inflight.add(e),e.finally(()=>this.inflight.delete(e)).catch(()=>{}),e}storeOp(e){return this.track(e())}mayAuto(){return!this.shutDown&&!this.hostStopped&&this.host.consentState()==="granted"&&!this.host.config.childSafeMode}async autoCheck(){if(!(!this.deps.autoStart||!this.mayAuto()||this.remoteChecking)&&!(this.armed&&!this.autoArmed&&!this.triggered||this.admitting||this.active&&!this.triggered)){this.remoteChecking=!0;try{await this.fetchConfig()}finally{this.remoteChecking=!1}this.mayAuto()&&await this.applyConfig()}}async refreshConfig(){if(!this.deps.autoStart||!this.mayAuto()||this.remoteChecking||this.deps.now()-(this.cfg?.at??F)<zt)return;let e=!!this.cfg?.rule;this.remoteChecking=!0;try{await this.fetchConfig()}finally{this.remoteChecking=!1}(e||this.cfg?.rule)&&this.mayAuto()&&await this.applyConfig()}eventRule(){let e=this.cfg?.rule;return e&&e.enabled&&e.startEvent?e:null}async applyConfig(){let e=this.cfg?.rule??null;if(e&&!e.enabled){this.waiting=!1,this.closeWindow();let n=this.active;n?.prov&&this.dropProvisional(n,this.admitting?void 0:"remote_disabled"),!this.active&&!this.admitting&&(this.armed=!1,this.autoArmed=!1,this.setStatus("off","remote_disabled"));return}let t=this.eventRule();if(t){if(this.waiting=!0,this.active||this.admitting||this.armed&&!this.autoArmed)return;this.armed=!1,this.autoArmed=!1;let n=this.window(),i=this.host.liveSessionId();i&&n?.open&&n.session_id===i&&n.start_event===t.startEvent&&n.event_id?this.beginProvisional(i,{start_event:t.startEvent,event_id:n.event_id},!0):(n?.open&&this.closeWindow(),this.setStatus("off",this.deniedReason()??"awaiting_start_event"));return}this.waiting=!1,!(this.armed&&!this.autoArmed||this.admitting||this.active)&&(e||this.cfg?.on?(this.armed=!0,this.autoArmed=!0,this.options={allowedScreens:null,excludedScreens:new Set},await this.admit()):(this.armed=!1,this.autoArmed=!1,this.setStatus("off","remote_disabled")))}fingerprint(){return this.host.apiKeyFingerprint(this.host.config.apiKey)}stateGet(e){try{return S(this.deps.state.get(e))}catch{return null}}stateSet(e,t){try{this.deps.state.set(e,t)}catch{}}cachedConfig(){let e;try{e=this.deps.state.get("remote")}catch{return null}if(e===1||e===0)return{fp:"",at:0,on:e===1,rule:null};let t=S(e);return!t||t.fp!==this.fingerprint()||typeof t.on!="boolean"?null:{fp:t.fp,at:P(t.at)??0,on:t.on,rule:Je(t.rule)}}async fetchConfig(){let e=this.host.config,t=`${e.endpoint.replace(/\/+$/,"")}/config?api_key=${encodeURIComponent(e.apiKey)}`,n=await this.deps.transport.get(t);if(n.status!==200)return;let i=I(n),s=S(i?.autocapture)?.session_replay;if(typeof s!="boolean")return;let o=i.session_replay??null,a={fp:this.fingerprint(),at:this.deps.now(),on:s,rule:Je(o)};this.cfg=a,this.stateSet("remote",{...a,rule:o})}window(){let e=this.stateGet("window");return e&&typeof e.session_id=="string"?e:null}closeWindow(){let e=this.window();e?.open&&this.stateSet("window",{...e,open:!1})}deniedReason(){let e=this.window(),t=e?.denied,n=this.host.liveSessionId();return t&&n&&e.session_id===n&&t.user_id===this.host.userId()?t.reason:null}hasTimedWork(){return!!this.active||this.armed||this.admitting||this.revokes.length>0||this.uploads.size>0||this.provisionals.size>0}updateTicker(){if(!(this.deps.manualTicks||this.shutDown)){if(!this.hasTimedWork()){this.ticker!==null&&clearInterval(this.ticker),this.ticker=null;return}this.ticker===null&&(this.ticker=setInterval(()=>this.post(()=>this.tickNow()),1e3),this.ticker.unref?.())}}start(e,t){let n={allowedScreens:e.allowedScreens?new Set(e.allowedScreens):null,excludedScreens:new Set(e.excludedScreens??[])};if(this.shutDown){t({...this.status});return}this.post(async()=>{let i=this.status.state;if(this.host.consentState()!=="granted")this.armed=!1,t(this.setStatus("off","consent_not_granted"));else if(this.host.config.childSafeMode)this.armed=!1,t(this.setStatus("off","child_safe_mode"));else if(this.deps.autoStart&&this.cfg?.rule&&!this.cfg.rule.enabled)t(this.setStatus("off","remote_disabled"));else if(this.admitting)this.autoArmed&&this.adoptHostOptions(n),this.startWaiters.push(t);else if((i==="recording"||i==="paused")&&this.triggered)this.adoptHostOptions(n),t({...this.status});else if(this.eventRule()&&!this.active){this.hostStopped=!1,this.waiting=!0,this.options=n;let s=this.sessionForAdmission(),o=s?this.beginProvisional(s,null,!1):null;o?(o.prov.waiters.push(t),(this.deps.setTimer??((d,c)=>setTimeout(d,c)))(()=>this.post(()=>this.resolveWaiters(o)),this.deps.startTimeoutMs)):t(this.setStatus("off","admission_unavailable"))}else(i==="recording"||i==="paused")&&this.autoArmed?(this.adoptHostOptions(n),t(this.status)):i==="recording"||i==="paused"?(jt(n,this.options)||this.log("debug","replay: start() options change applies from the next admission"),t(this.status)):(this.armed=!0,this.autoArmed=!1,this.hostStopped=!1,this.options=n,this.startWaiters.push(t),await this.admit())})}stop(e,t){if(this.shutDown){t();return}this.post(async()=>{if(this.hostStopped=!0,this.autoArmed=!1,this.triggered=!1,this.status.state==="off"&&!this.active&&!this.admitting){this.armed=!1,t();return}this.armed=!1;let n=this.active;if(!n)this.admitting&&(this.admitting=!1,this.admissionAttempt++,this.rotateAfterAdmission=!1),this.setStatus("off","stopped"),this.notifyStart();else if(e)this.purge(n.meta,"host_discard"),this.setStatus("off","stopped");else if(n.prov)this.finalize(n,"host_stop"),this.setStatus("off","stopped");else{this.finalize(n,"host_stop"),this.setStatus("finalizing","stopped",n.meta.recordingId),t(),await this.pump();return}t()})}frameDropped(e){e.needKeyframe=!0;try{this.onFrameDropped?.()}catch{}}submitFrame(e){this.post(()=>{let t=this.active;if(!t)return;if(!this.canCapture(t)){t.needKeyframe=!0;return}let n=this.deps.monoMicros(),i=n<this.burstUntilMono?Math.max(t.policy.burstFps,t.policy.maxFps):t.policy.maxFps,s=Math.floor(1e6/i);if(n-t.lastFrameMono<s){this.frameDropped(t);return}let o=n-t.lastKeyframeMono>=t.policy.keyframeIntervalSeconds*1e6,a=t.needKeyframe||o||t.lastKeyframeId===null||!e.tiles,d=e.keyframe;if(a&&!d){this.frameDropped(t),this.publishCapture();return}if(!a&&(!e.tiles||e.tiles.length===0))return;t.lastFrameMono=n,this.closeGap(t,"mask_uncertain");let c=a?d.bytes.length:e.tiles.reduce((l,[,u])=>l+u.bytes.length,0);if(t.buffer.length>0&&ge(t)+c>=t.policy.maxChunkBytes*8/10&&this.closeChunk(t,!1),a){let l=`f${t.frames++}`;t.buffer.push({type:"keyframe",t:this.t(t),fields:{frame_id:l,w:d.w,h:d.h,windows:e.windows??1},images:[d]}),t.lastKeyframeId=l,t.lastKeyframeMono=n,t.needKeyframe=!1}else{let l=e.tiles;t.buffer.push({type:"patch",t:this.t(t),fields:{base_frame_id:t.lastKeyframeId,tiles:l.map(([[u,h,g,m]])=>({x:u,y:h,w:g,h:m}))},images:l.map(([,u])=>u)})}this.publishCapture(),this.maybeCloseForSize(t)})}frameDiscarded(){this.post(()=>{let e=this.active;!e||!this.canCapture(e)||e.openGaps.has("mask_uncertain")||e.openGaps.set("mask_uncertain",this.t(e))})}submitTouch(e,t,n,i=1,s="plain",o=!1){this.post(()=>{let a=this.active;if(!a||!this.canCapture(a,!1))return;this.burstUntilMono=this.deps.monoMicros()+ze;let c=s!=="plain"||o||a.excluded?{kind:"redacted"}:{kind:e,nx:X(t,0,1),ny:X(n,0,1)};c.pointers=X(Math.round(i),1,10),a.buffer.push({type:"touch",t:this.t(a),fields:c})})}onConsentChanged(e){if(e){this.post(()=>this.autoCheck());return}this.post(()=>{this.armed=!1,this.triggered=!1,this.closeWindow(),this.active&&this.purge(this.active.meta,"opted_out");for(let t of[...this.uploads.values()])this.purge(t,"opted_out");for(let t of[...this.provisionals])this.dropProvisional(t);this.storeOp(()=>this.deps.store.purgeAll()),this.setStatus("off","opted_out"),this.track(this.pump())})}onSessionRotated(e,t){this.startingSession||e===this.selfStarted||this.post(async()=>{if(this.admitting){this.rotateAfterAdmission=!0;return}let n=this.active;if(n&&n.meta.sessionId!==e)this.finalize(n,"session_rotated"),this.setStatus("off");else if(n)return;this.window()?.session_id!==e&&this.closeWindow(),this.triggered&&(this.triggered=!1,this.armed=!1),this.autoArmed&&(this.armed=!1,this.autoArmed=!1),this.armed&&!this.active?await this.admit():await this.autoCheck()})}onEventAccepted(e,t,n){this.post(()=>{let i=this.eventRule();i&&n===i.startEvent&&this.waiting&&!this.active&&!this.admitting&&this.mayAuto()&&t===this.host.liveSessionId()&&!this.deniedReason()&&this.beginProvisional(t,{start_event:n,event_id:e},!1);let s=this.active;!s||t!==s.meta.sessionId||this.host.consentState()!=="granted"||(s.buffer.push({type:"event_ref",t:this.t(s),fields:{event_id:e}}),this.triggered&&i?.stopEvent&&n===i.stopEvent&&(s.meta.stopEvent=n,this.finalize(s,"stop_event"),this.triggered=!1,this.armed=!1,this.waiting=!0,this.closeWindow(),this.setStatus("off","awaiting_start_event"),this.track(this.pump())))})}onScreen(e){this.post(()=>{this.currentScreen=e,this.burstUntilMono=this.deps.monoMicros()+ze;let t=this.active;if(!t)return;let n=this.isExcluded(t,e);t.excluded&&!n&&this.leaveExclusion(t),t.buffer.push({type:"screen",t:this.t(t),fields:{name:e.slice(0,128)}}),!t.excluded&&n&&this.enterExclusion(t)})}onForeground(){this.post(()=>{this.foreground=!0,this.backgroundSince=null,this.track(this.refreshConfig());let e=this.active;e&&(e.backgrounded&&(e.backgrounded=!1,e.buffer.push({type:"lifecycle",t:this.t(e),fields:{kind:"foreground"}}),e.needKeyframe=!0),e.paused==="background"&&(e.paused=null,this.setStatus("recording",void 0,this.sid(e))))})}onBackground(){this.post(async()=>{this.foreground=!1,this.backgroundSince=this.deps.now();let e=this.active;e&&(e.backgrounded||(this.dropYoungVisuals(e,"dropped_frames"),e.buffer.push({type:"lifecycle",t:this.t(e),fields:{kind:"background"}}),this.closeChunk(e,!0),e.backgrounded=!0,e.paused===null&&(e.paused="background",this.setStatus("paused","background",this.sid(e))),await this.pump()))})}onShutdown(e){this.post(async()=>{if(this.armed=!1,e){this.active&&this.purge(this.active.meta,"api_key_changed");for(let n of[...this.uploads.values()])this.purge(n,"api_key_changed");for(let n of[...this.provisionals])this.dropProvisional(n);this.setStatus("off","stopped")}else this.active&&this.finalize(this.active,"shutdown"),this.setStatus("off","shutdown");this.admitting&&(this.admitting=!1,this.admissionAttempt++),this.notifyStart();for(let n of this.provisionals)this.resolveWaiters(n);this.provisionals.clear(),this.ticker!==null&&clearInterval(this.ticker),this.ticker=null;let t=e?this.pumpRevokes():Promise.resolve();this.shutDown=!0;for(let n of this.uploads.keys())this.deps.claims.release(n);await t})}async admit(){let e=this.sessionForAdmission();if(!e){this.setStatus("off","admission_unavailable"),this.armed=!1,this.notifyStart();return}this.admitting=!0;let t=++this.admissionAttempt;this.rotateAfterAdmission=!1,this.setStatus("admitting");let n=this.deps.setTimer??((c,l)=>setTimeout(c,l)),i=this.deps.clearTimer??(c=>clearTimeout(c)),s=n(()=>{this.post(()=>{this.admitting&&this.admissionAttempt===t&&this.timeOutAdmission()})},this.deps.startTimeoutMs),o;try{o=await this.call("/replay/recordings",null,this.admissionBody(e,null))}finally{i(s)}let a=I(o),d=()=>this.revokeLate(o,a);if(t!==this.admissionAttempt){d(),await this.pump();return}if(this.admitting=!1,!this.armed||this.host.consentState()!=="granted"){d(),this.notifyStart(),await this.pump();return}if(o.status===201&&a){let c=M(a.policy),l=x(a.recording_id),u=x(a.admission_token),h=P(a.upload_deadline_seconds);!c||!l||!u||h===null?(this.setStatus("off","admission_unavailable"),this.armed=!1):(this.stateSet("policy",{fp:this.fingerprint(),policy:a.policy}),this.begin(l,u,e,c,this.deps.now()+h*1e3))}else o.status===200&&a?.state==="not_sampled"?this.setStatus("off","not_sampled"):o.status===400||o.status===401||o.status===403?(this.setStatus("off","admission_denied"),this.armed=!1):o.status===429?(this.setStatus("off","quota_exhausted"),this.armed=!1):(this.setStatus("off","admission_unavailable"),this.armed=!1);if(this.notifyStart(),this.rotateAfterAdmission){this.rotateAfterAdmission=!1;let c=this.host.liveSessionId();c&&this.onSessionRotated(c,"reset")}}sessionForAdmission(){let e=this.host.liveSessionId();if(e)return e;this.startingSession=!0;try{this.selfStarted=this.host.startSession()}finally{this.startingSession=!1}return this.selfStarted}admissionBody(e,t){let n=this.deps.viewport(),i={session_id:e,platform:He,sdk_version:this.host.sdkVersion,library:this.host.config.libraryName.slice(0,64),viewport:{w:n.w,h:n.h,density:n.density},profile:C,client_nonce:(this.deps.uuid??Ve)(),stream_id:T};this.options.allowedScreens&&(i.allowed_screens=[...this.options.allowedScreens]),this.options.excludedScreens.size>0&&(i.excluded_screens=[...this.options.excludedScreens]),t&&(i.trigger=t);let s=this.host.userId(),o=this.host.anonymousId();return s&&s.length<=ye&&(i.user_id=s),o&&o.length<=ye&&(i.anonymous_id=o),JSON.stringify(i)}revokeLate(e,t){if(e.status!==201)return;let n=x(t?.recording_id),i=x(t?.admission_token),s=this.host.consentState()==="granted"?"host_discard":"opted_out";n&&i&&this.revokes.push([n,i,s])}begin(e,t,n,i,s){let o=this.newMeta(e,t,n,s);this.uploads.set(e,o),this.lastSuccessAt=this.deps.now(),this.open(o,i,null)}newMeta(e,t,n,i){return{recordingId:e,token:t,sessionId:n,apiKeyFingerprint:this.fingerprint(),uploadDeadlineMs:i,streamId:T,lastChunkSeq:-1,finishReason:null,chunks:[]}}shell(e,t,n){return{meta:e,policy:t,beginMono:this.deps.monoMicros(),startedAt:this.deps.now(),buffer:[],nextSeq:0,nextChunkSeq:0,lastFrameMono:F,lastKeyframeMono:F,lastKeyframeId:null,frames:0,needKeyframe:!0,chains:new Map,writtenBytes:0,excluded:!1,paused:null,backgrounded:!1,openGaps:new Map,lastT:0,drafted:0,draftN:0,draftDirty:!1,prov:n,startScreen:this.currentScreen}}open(e,t,n){this.deps.claims.claim(e.recordingId),this.storeOp(()=>this.deps.store.save(e));let i=this.host.currentScreen();i&&(this.currentScreen=i);let s=this.shell(e,t,n);this.active=s;let o=this.deps.viewport();return s.buffer.push({type:"recording_begin",t:0,fields:{session_id:e.sessionId,recording_id:e.recordingId,stream_id:T,wall_epoch_ms:s.startedAt,viewport:{w:o.w,h:o.h,density:o.density},orientation:o.w>o.h?"landscape":"portrait",platform:He,sdk_version:this.host.sdkVersion,library:this.host.config.libraryName.slice(0,64),profile:C,policy_version:t.version}}),this.setStatus("recording",void 0,this.sid(s)),this.isExcluded(s,this.currentScreen)&&this.enterExclusion(s),this.foreground||(s.backgrounded=!0,s.buffer.push({type:"lifecycle",t:this.t(s),fields:{kind:"background"}}),s.paused="background",this.setStatus("paused","background",this.sid(s))),s}sid(e){return e.prov?void 0:e.meta.recordingId}beginProvisional(e,t,n){let i=this.deps.now(),s=this.stateGet("policy"),o=s?.fp===this.fingerprint()&&M(s.policy)||M(he),a=this.newMeta((this.deps.uuid??Ve)(),"",e,i+Ge);a.provisional={openedAt:i,trigger:t},this.armed=!0,this.autoArmed=!1,this.triggered=!0,this.waiting=!1;let d=this.open(a,o,$e(i,t));return this.provisionals.add(d),t&&!n&&this.stateSet("window",{session_id:e,open:!0,opened_at:i,...t}),this.track(this.attemptAdmission(d)),d}async attemptAdmission(e){let t=e.prov;if(!t||t.inFlight||!this.provisionals.has(e))return;t.inFlight=!0;let n=await this.call("/replay/recordings",null,this.admissionBody(e.meta.sessionId,t.trigger));t.inFlight=!1;let i=I(n);this.provisionals.has(e)?n.status===201&&i&&this.accept(e,i)||(n.status===200&&i?.state==="not_sampled"?this.refuse(e,"not_sampled"):n.status===400||n.status===401||n.status===403?this.refuse(e,S(i?.error)?.code==="REPLAY_DISABLED"?"remote_disabled":"admission_denied"):(t.last=n.status,t.backoffMs=Math.min(t.backoffMs?t.backoffMs*2:1e3,6e4),t.nextAt=this.deps.now()+Math.max(t.backoffMs,n.status===429?Ye(n):0))):this.revokeLate(n,i),this.resolveWaiters(e),await this.pump()}resolveWaiters(e){for(let t of e.prov?.waiters.splice(0)??[])try{t({...this.status})}catch{}}accept(e,t){let n=M(t.policy),i=x(t.recording_id),s=x(t.admission_token),o=P(t.upload_deadline_seconds);if(!n||!i||!s||o===null)return!1;this.stateSet("policy",{fp:this.fingerprint(),policy:t.policy}),this.provisionals.delete(e);let a=e.meta,d=a.recordingId;this.storeOp(()=>this.deps.store.deleteRecording(d)),this.deps.claims.release(d),a.recordingId=i,a.token=s,a.uploadDeadlineMs=this.deps.now()+o*1e3,delete a.provisional,e.prov=null;for(let l of e.buffer)l.type==="recording_begin"&&(l.fields={...l.fields,recording_id:i,policy_version:n.version});let c=e.policy.excludedScreens;return e.policy=n,this.retro(e,c),this.deps.claims.claim(i),this.storeOp(()=>this.deps.store.save(a)),this.uploads.set(i,a),e.draftDirty=!0,e===this.active?this.setStatus(e.paused?"paused":"recording",e.paused??void 0,i):this.closeChunk(e,!0),!0}retro(e,t){let n=l=>l!==null&&t.has(l)||this.isExcluded(e,l),i=(l,u)=>({type:"gap",t:u,fields:{reason:"excluded_screen",from_t:l,to_t:u}}),s=[],o=n(e.startScreen)?0:null,a=!1,d=!0;for(let l of e.buffer)if(!(l.type==="gap"&&l.fields.reason==="excluded_screen")){if(l.type==="screen"){let u=n(l.fields.name);if(o!==null&&!u&&(s.push(i(o,l.t)),o=null),s.push(l),o===null&&u){o=l.t;for(let h=s.length-1;h>=0&&s[h].t>l.t-$;h--)_(s[h])&&(o=Math.min(o,s.splice(h,1)[0].t),d=!1,a=!0)}continue}if(_(l)&&(o!==null||!d&&l.type==="patch")){d=!1,a=!0;continue}l.type==="keyframe"&&(d=!0),o!==null&&l.type==="touch"&&l.fields.nx!==void 0&&(l={...l,fields:{kind:"redacted",pointers:l.fields.pointers}}),o!==null&&l.type==="recording_end"&&(s.push(i(o,l.t)),o=null),s.push(l)}e.buffer=s,e.openGaps.delete("excluded_screen"),(a||!d)&&(e.needKeyframe=!0,e.lastKeyframeId=null);let c=s.findIndex(l=>l.type==="recording_end");if(c>=0){s[c]={...s[c],fields:{...s[c].fields,last_seq:e.nextSeq+c}};return}e.excluded=this.isExcluded(e,this.currentScreen),o!==null&&e.excluded&&e===this.active?e.openGaps.set("excluded_screen",o):o!==null?(s.push(i(o,e===this.active?this.t(e):s[s.length-1].t)),e.needKeyframe=!0):e.excluded&&e.openGaps.set("excluded_screen",this.t(e))}refuse(e,t){this.dropProvisional(e,t);let n=e.meta.sessionId,i=this.window();this.stateSet("window",{...i?.session_id===n?i:{session_id:n,opened_at:this.deps.now()},open:!1,denied:{user_id:this.host.userId(),reason:t}})}dropProvisional(e,t){this.provisionals.delete(e),this.storeOp(()=>this.deps.store.deleteRecording(e.meta.recordingId)),this.deps.claims.release(e.meta.recordingId),this.active===e&&(this.active=null,this.armed=!1,this.triggered=!1,this.waiting=!!this.eventRule()&&!this.hostStopped,t&&this.setStatus("off",t)),this.resolveWaiters(e)}tickProvisional(){let e=this.deps.now();for(let t of[...this.provisionals]){let n=t.prov;e-n.openedAt>Ge||ge(t)>pe?this.dropProvisional(t,n.last===429?"quota_exhausted":"admission_unavailable"):!n.inFlight&&e>=n.nextAt&&this.deps.isOnline()&&this.track(this.attemptAdmission(t))}}timeOutAdmission(){this.admitting=!1,this.admissionAttempt++,this.rotateAfterAdmission=!1,this.armed&&(this.armed=!1,this.setStatus("off","admission_unavailable")),this.notifyStart()}notifyStart(){let e=this.startWaiters.splice(0);for(let t of e)try{t(this.status)}catch{}}t(e){let t=Math.max(e.lastT,Math.round(this.deps.monoMicros()-e.beginMono));return e.lastT=t,t}canCapture(e,t=!0){return this.armed&&this.status.state==="recording"&&e.paused===null&&this.foreground&&this.host.consentState()==="granted"&&!this.host.config.childSafeMode&&(!!e.prov||this.deps.now()-this.lastSuccessAt<e.policy.maxStaleSeconds*1e3)&&(!t||!e.excluded)}adoptHostOptions(e){this.autoArmed=!1,this.hostStopped=!1,this.options=e;let t=this.active;if(!t)return;let n=this.isExcluded(t,this.currentScreen);!t.excluded&&n?this.enterExclusion(t):t.excluded&&!n&&this.leaveExclusion(t)}isExcluded(e,t){if(t!==null&&(e.policy.excludedScreens.has(t)||this.options.excludedScreens.has(t)))return!0;let n=this.options.allowedScreens;return n?t===null||!n.has(t):!1}enterExclusion(e){let t=this.dropYoungVisuals(e,null);e.excluded=!0,e.openGaps.has("excluded_screen")||e.openGaps.set("excluded_screen",t??this.t(e))}leaveExclusion(e){this.closeGap(e,"excluded_screen"),e.excluded=!1,e.needKeyframe=!0}dropYoungVisuals(e,t){let n=this.t(e),i=n-$,s=e.buffer.filter(a=>_(a)&&a.t>i);if(s.length===0)return null;e.buffer=e.buffer.filter(a=>!s.includes(a)),e.needKeyframe=!0;let o=Math.min(...s.map(a=>a.t));return t&&e.buffer.push({type:"gap",t:n,fields:{reason:t,from_t:o,to_t:n}}),o}closeGap(e,t){let n=e.openGaps.get(t);if(n===void 0)return;e.openGaps.delete(t);let i=this.t(e);e.buffer.push({type:"gap",t:i,fields:{reason:t,from_t:n,to_t:i}})}pause(e,t){e.paused===null&&(e.paused=t,e.openGaps.has(t)||e.openGaps.set(t,this.t(e)),this.setStatus("paused",t,this.sid(e)))}resume(e,t){e.paused===t&&(this.closeGap(e,t),e.paused=null,e.needKeyframe=!0,this.setStatus("recording",void 0,this.sid(e)))}maybeCloseForSize(e){ge(e)>=e.policy.maxChunkBytes*8/10&&this.closeChunk(e,!1)}closeChunk(e,t){if(e.prov){this.writeDraft(e);return}let n=e.buffer.length;if(!t){let s=this.t(e)-$,o=e.buffer.findIndex(a=>_(a)&&a.t>s);o>=0&&(n=o)}let i=e.policy.maxChunkBytes*8/10;for(;n>0;){let s=0;for(let o=0;s<n&&(s===0||o+V(e.buffer[s])<i);s++)o+=V(e.buffer[s]);this.sealPiece(e,e.buffer.splice(0,s)),n=Math.min(n-s,e.buffer.length)}}sealPiece(e,t){let n=e.meta.recordingId,i=L(n,T,e.nextChunkSeq,e.nextSeq,t,e.policy.version);if(i.bound>e.policy.maxChunkBytes){this.log("warn",`replay: chunk of ~${i.bound} bytes over max_chunk_bytes; frames dropped`),e.needKeyframe=!0,e.lastKeyframeId=null;let d=new Set(t.filter(u=>u.type==="keyframe").map(u=>u.fields.frame_id));this.dropOrphanedPatches(e,d);let l=[{type:"gap",t:t[0].t,fields:{reason:"chunk_dropped",from_t:t[0].t,to_t:t[t.length-1].t}},...t.filter(u=>!_(u))].map((u,h)=>u.type==="recording_end"?{...u,fields:{...u.fields,last_seq:e.nextSeq+h}}:u);if(i=L(n,T,e.nextChunkSeq,e.nextSeq,l,e.policy.version),i.bound>e.policy.maxChunkBytes)return}e.chains.set(i.chunkSeq,{keyframes:new Set(i.keyframes),bases:new Set(i.bases)}),e.meta.lastChunkSeq=i.chunkSeq,e.nextSeq=i.lastSeq+1,e.meta.nextSeq=e.nextSeq,e.nextChunkSeq++,e.drafted=0,e.draftN=0,e.draftDirty=!1,e.writtenBytes+=i.bound;let s=e.meta,o={streamId:T,chunkSeq:i.chunkSeq,length:i.bound,sha256:"",createdWallMs:this.deps.now(),encoded:!1};this.writing.set(n,(this.writing.get(n)??0)+1);let a=()=>{let d=(this.writing.get(n)??1)-1;d>0?this.writing.set(n,d):this.writing.delete(n)};this.storeOp(()=>this.deps.store.writeChunk(s,o,i)).then(()=>{a(),this.uploads.get(n)===s&&(this.enforceStoreBounds(),this.track(this.pump()))},d=>{a(),this.log("warn","replay: chunk write failed",d),this.chunkDroppedGap(s)})}writeDraft(e){let t=this.t(e)-$,n=e.buffer.findIndex(c=>_(c)&&c.t>t),i=n<0?e.buffer.length:n,s=e.draftDirty?0:e.drafted;if(i<=s&&!e.draftDirty)return;let o=e.draftDirty?0:e.draftN,a={chunkSeq:e.nextChunkSeq,policyVersion:e.policy.version,records:e.buffer.slice(s,i)};e.drafted=i,e.draftN=o+1,e.draftDirty=!1;let d=e.meta.recordingId;this.storeOp(()=>this.deps.store.appendDraft(d,o,a))}finalize(e,t){this.dropYoungVisuals(e,t==="session_rotated"?null:"dropped_frames");for(let o of[...e.openGaps.keys()])this.closeGap(e,o);let n=e.nextSeq+e.buffer.length,i=t==="stop_event"?"host_stop":t;e.buffer.push({type:"recording_end",t:this.t(e),fields:{reason:i,last_seq:n}}),this.closeChunk(e,!0),e.meta.finishReason=t;let s=e.meta;this.storeOp(async()=>{(this.uploads.get(s.recordingId)===s||this.provisionals.has(e))&&await this.deps.store.save(s)}),this.active=null}purge(e,t){for(let n of this.provisionals)if(n.meta===e)return this.dropProvisional(n);this.revokes.push([e.recordingId,e.token,t]),this.uploads.delete(e.recordingId),this.storeOp(()=>this.deps.store.deleteRecording(e.recordingId));for(let n of[...this.grants.keys()])n.startsWith(`${e.recordingId}:`)&&this.grants.delete(n);this.active?.meta.recordingId===e.recordingId&&(this.active=null),this.deps.claims.release(e.recordingId)}storeBytes(){let e=0;for(let t of this.uploads.values())for(let n of t.chunks)e+=n.length;return e}enforceStoreBounds(){let e=this.deps.now();for(let i of[...this.uploads.values()])for(let s of i.chunks.filter(o=>e-o.createdWallMs>Wt))this.deleteChunk(i,s);let t=this.active;if(!t)return;let n=()=>t.meta.chunks.reduce((i,s)=>i+s.length,0);for(;n()>pe||this.storeBytes()>je;){let i=[...t.meta.chunks].sort((s,o)=>s.chunkSeq-o.chunkSeq)[0];if(!i)break;this.dropWithDependents(t,i),t.buffer.unshift({type:"gap",t:this.t(t),fields:{reason:"chunk_dropped",from_t:0,to_t:this.t(t)}}),t.draftDirty=!0,this.pause(t,"resource_limit")}}dropWithDependents(e,t){let n=new Set,i=[];for(let s of[...e.meta.chunks].sort((o,a)=>o.chunkSeq-a.chunkSeq)){let o=e.chains.get(s.chunkSeq);(s===t||o&&[...o.bases].some(a=>n.has(a)))&&(i.push(s),o?.keyframes.forEach(a=>n.add(a)))}for(let s of i)this.deleteChunk(e.meta,s),e.chains.delete(s.chunkSeq);this.dropOrphanedPatches(e,n)}dropOrphanedPatches(e,t){t.size!==0&&(e.buffer=e.buffer.filter(n=>!(n.type==="patch"&&t.has(n.fields.base_frame_id))),e.draftDirty=!0,e.lastKeyframeId!==null&&t.has(e.lastKeyframeId)&&(e.needKeyframe=!0,e.lastKeyframeId=null))}deleteChunk(e,t){e.chunks=e.chunks.filter(n=>n!==t),this.storeOp(()=>this.deps.store.deleteChunk({...e,chunks:[...e.chunks,t]},t))}tick(){this.post(()=>this.tickNow())}async tickNow(){this.tickProvisional();let e=this.active,t=this.deps.now();if(e){let n=e.buffer[0];n&&this.t(e)-n.t>=e.policy.chunkMaxSeconds*1e6?this.closeChunk(e,!1):this.writeDraft(e),!e.prov&&e.paused===null&&t-this.lastSuccessAt>=e.policy.maxStaleSeconds*1e3&&this.pause(e,"policy_stale"),(t-e.startedAt>=e.policy.maxRecordingSeconds*1e3||e.writtenBytes>=e.policy.maxRecordingBytes)&&(this.armed=!1,this.finalize(e,"limit"),this.setStatus("finalizing","limit",this.sid(e)));let i=this.backgroundSince;this.active&&!this.foreground&&i!==null&&t-i>this.host.config.sessionTimeoutMs&&(this.finalize(this.active,"background_timeout"),this.setStatus("off"))}await this.pump()}async hasDueWork(){if(await this.idle(),!this.deps.isOnline())return!1;let e=this.deps.now();if(this.revokes.length>0||this.provisionals.size>0)return!0;if(e<this.quotaUntil)return!1;for(let n of this.uploads.values())if(n.chunks.length>0||n.finishReason!==null)return!0;let t=this.active?.paused;return(t==="policy_stale"||t==="quota_exhausted")&&e-this.lastRefreshAt>=We}async pump(){if(!this.shutDown){if(this.pumping){this.pumpAgain=!0;return}this.pumping=!0;try{do this.pumpAgain=!1,await this.pumpOnce();while(this.pumpAgain&&!this.shutDown)}finally{this.pumping=!1}}}alive(e){return this.uploads.get(e.recordingId)===e}async pumpRevokes(){for(;this.revokes.length>0&&this.deps.isOnline();){let[e,t,n]=this.revokes.shift();await this.call(`/replay/recordings/${e}/revoke`,t,JSON.stringify({reason:n}),!1)}}async pumpOnce(){if(!this.deps.isOnline())return;await this.pumpRevokes();for(let n=0;n<64;n++){let i=this.deps.now();if(i<this.backoffUntil||i<this.quotaUntil)break;let s=this.active?.meta.recordingId,o=[...this.uploads.values()].find(c=>c.chunks.length>0||c.finishReason!==null&&c.recordingId!==s&&!this.writing.has(c.recordingId));if(!o)break;let a=[...o.chunks].sort((c,l)=>c.chunkSeq-l.chunkSeq)[0];if(!(a?await this.uploadOne(o,a):await this.finish(o)))break}let e=this.active;if(!e)return;e.paused==="resource_limit"&&e.meta.chunks.reduce((n,i)=>n+i.length,0)<=pe/2&&this.storeBytes()<=je/2&&this.resume(e,"resource_limit");let t=this.deps.now();if((e.paused==="policy_stale"||e.paused==="quota_exhausted"&&t>=this.quotaUntil)&&t-this.lastRefreshAt>=We&&t>=this.backoffUntil){this.lastRefreshAt=t;let n=await this.call("/replay/grants",e.meta.token,this.grantsBody(e.meta,[]));n.status===200?this.applyPolicy(I(n)):this.handleError(e.meta,null,n)}}grantsBody(e,t){return JSON.stringify({recording_id:e.recordingId,policy_version:this.policyVersionFor(e),chunks:t.map(n=>({stream_id:n.streamId,chunk_seq:n.chunkSeq,length:n.length,sha256:n.sha256}))})}policyVersionFor(e){return this.active?.meta.recordingId===e.recordingId?this.active.policy.version:1}async uploadOne(e,t){let n=`${e.recordingId}:${t.streamId}:${t.chunkSeq}`,i=await this.storeOp(()=>this.deps.store.readChunk(e.recordingId,t));if(!this.alive(e))return!0;if(!i)return this.deleteChunk(e,t),!0;let s;if(i instanceof Uint8Array)s=i;else{let l=await Ue(i);if(!this.alive(e))return!0;let u={...t,length:l.bytes.length,sha256:l.sha256,encoded:!0};try{await this.storeOp(()=>this.deps.store.replaceChunk(e,t,u,l.bytes))}catch{return this.backoff()}if(!this.alive(e))return!0;if(l.bytes.length>fe)return this.deleteChunk(e,u),this.chunkDroppedGap(e),!0;t=u,s=l.bytes}let o=this.grants.get(n);if(o&&this.deps.now()>=o.expiresAt&&(o=void 0),!o){let l=await this.call("/replay/grants",e.token,this.grantsBody(e,[t]));if(!this.alive(e))return!0;if(l.status!==200)return this.handleError(e,t,l);let u=I(l);if(!u)return this.backoff();if(this.applyPolicy(u),Array.isArray(u.committed)&&u.committed.some(f=>S(f)?.chunk_seq===t.chunkSeq))return this.deleteChunk(e,t),!0;let g=Array.isArray(u.grants)?S(u.grants[0]):null,m=S(g?.required_headers),y=x(g?.grant_id),v=x(g?.put_url),p=P(g?.expires_in_seconds);if(!g||!m||!y||!v||p===null||Object.values(m).some(f=>typeof f!="string"))return this.backoff();o={id:y,url:v,headers:m,expiresAt:this.deps.now()+(p-5)*1e3,uploaded:!1},this.grants.set(n,o)}if(!o.uploaded){let l=await this.deps.transport.put(o.url,o.headers,s);if(!this.alive(e))return!0;if(l<200||l>299)return this.backoff();o.uploaded=!0}let a=await this.call("/replay/commits",e.token,JSON.stringify({recording_id:e.recordingId,policy_version:this.policyVersionFor(e),grants:[{grant_id:o.id,stream_id:t.streamId,chunk_seq:t.chunkSeq}]}));if(!this.alive(e))return!0;if(a.status!==200)return this.handleError(e,t,a);let d=I(a);if(!d)return this.backoff();this.applyPolicy(d);let c=Array.isArray(d.results)?S(d.results[0]):null;if(!c)return this.backoff();switch(c.status){case"committed":case"duplicate":this.grants.delete(n),this.deleteChunk(e,t);break;case"pending":return this.backoff();case"expired":this.grants.delete(n);break;case"rejected":{this.grants.delete(n);let l=c.reason;if((l==="checksum_mismatch"||l==="size_mismatch")&&!this.checksumRetried.has(n))return this.checksumRetried.add(n),!0;this.deleteChunk(e,t),this.chunkDroppedGap(e);break}default:return this.backoff()}return!0}async finish(e){let t=await this.call(`/replay/recordings/${e.recordingId}/finish`,e.token,JSON.stringify({reason:e.finishReason,last_chunk_seq:{[e.streamId]:e.lastChunkSeq},...e.stopEvent?{stop_event:e.stopEvent}:{}}));return this.alive(e)?t.status===200||t.status===401||t.status===404||t.status===410?(this.done(e),!0):this.handleError(e,null,t):!0}done(e){this.uploads.delete(e.recordingId),this.storeOp(()=>this.deps.store.deleteRecording(e.recordingId)),this.deps.claims.release(e.recordingId),this.status.state==="finalizing"&&this.status.recordingId===e.recordingId&&!this.active&&this.setStatus("off",this.status.reason)}handleError(e,t,n){let i=this.active?.meta.recordingId===e.recordingId;switch(n.status){case 401:case 404:case 410:return this.purgeLocalOnly(e),i&&this.setStatus("off","recording_closed"),!0;case 403:return this.purgeLocalOnly(e),i&&(this.armed=!1,this.setStatus("off","policy_revoked")),!0;case 409:if(t&&this.deleteChunk(e,t),i){let s=this.active;this.armed=!1,this.active=null,s.meta.finishReason=s.meta.finishReason??"host_stop",this.setStatus("off","chunk_conflict")}return!0;case 400:case 413:return t&&(this.deleteChunk(e,t),this.chunkDroppedGap(e)),!0;case 429:return this.quotaUntil=this.deps.now()+Ye(n),i&&this.pause(this.active,"quota_exhausted"),!1;default:return this.backoff()}}purgeLocalOnly(e){this.uploads.delete(e.recordingId),this.storeOp(()=>this.deps.store.deleteRecording(e.recordingId)),this.deps.claims.release(e.recordingId),this.active?.meta.recordingId===e.recordingId&&(this.active=null)}chunkDroppedGap(e){let t=this.active;!t||t.meta.recordingId!==e.recordingId||t.buffer.push({type:"gap",t:this.t(t),fields:{reason:"chunk_dropped",from_t:0,to_t:this.t(t)}})}backoff(){this.backoffMs=this.backoffMs===0?1e3:Math.min(this.backoffMs*2,6e4);let e=this.deps.jitter===!1?this.backoffMs:Math.floor(this.backoffMs*(.5+Math.random()*.5));return this.backoffUntil=this.deps.now()+e,!1}applyPolicy(e){let t=this.active;if(!t)return;let n=P(e?.policy_version);if(n===null||n<=t.policy.version)return;let i=M(e?.policy);if(!i){this.pause(t,"policy_stale");return}t.policy=i;let s=this.isExcluded(t,this.currentScreen);!t.excluded&&s&&this.enterExclusion(t),t.excluded&&!s&&this.leaveExclusion(t)}markSuccess(){let e=this.deps.now();this.lastSuccessAt=e,this.backoffMs=0,this.backoffUntil=0;let t=this.active;t&&(t.paused==="policy_stale"&&this.resume(t,"policy_stale"),t.paused==="quota_exhausted"&&e>=this.quotaUntil&&this.resume(t,"quota_exhausted"))}async call(e,t,n,i=!0){let s=this.host.config,o=await this.deps.transport.post(s.endpoint.replace(/\/+$/,"")+e,s.apiKey,t,n);return i&&o.status>=200&&o.status<=299&&this.markSuccess(),o}async recover(){let e=this.host.consentState()==="granted",t=this.host.apiKeyFingerprint(this.host.config.apiKey),n=this.deps.now(),i=await this.storeOp(()=>this.deps.store.recordings());for(let s of i){let o=s.recordingId;if(!(this.uploads.has(o)||this.active?.meta.recordingId===o||[...this.provisionals].some(a=>a.meta.recordingId===o))&&await this.deps.claims.claim(o)){if(!e||this.host.config.childSafeMode||s.apiKeyFingerprint!==t||n>s.uploadDeadlineMs){await this.storeOp(()=>this.deps.store.deleteRecording(o)),this.deps.claims.release(o);continue}if(s.provisional){await this.recoverProvisional(s,s.provisional);continue}s.finishReason===null&&(s.finishReason="shutdown",await this.sealDrafts(s)),await this.storeOp(()=>this.deps.store.save(s)),this.uploads.set(s.recordingId,s)}}await this.pump()}async recoverProvisional(e,t){let{records:n}=await this.storeOp(()=>this.deps.store.readDrafts(e.recordingId,0));if(n[0]?.type!=="recording_begin"){await this.storeOp(()=>this.deps.store.deleteRecording(e.recordingId)),this.deps.claims.release(e.recordingId);return}e.finishReason??(e.finishReason="shutdown"),this.storeOp(()=>this.deps.store.save(e));let i=this.shell(e,M(he),$e(t.openedAt,t.trigger));i.buffer=n,i.startScreen=null,this.provisionals.add(i),this.track(this.attemptAdmission(i))}async sealDrafts(e){let t=e.lastChunkSeq+1,{records:n,policyVersion:i}=await this.storeOp(()=>this.deps.store.readDrafts(e.recordingId,t));if(n.length===0||t===0!=(n[0]?.type==="recording_begin"))return;let s=L(e.recordingId,e.streamId,t,e.nextSeq??0,n,i);if(s.bound>fe&&(s=L(e.recordingId,e.streamId,t,e.nextSeq??0,n.filter(a=>!_(a)),i),s.bound>fe))return;let o={streamId:e.streamId,chunkSeq:t,length:s.bound,sha256:"",createdWallMs:this.deps.now(),encoded:!1};e.lastChunkSeq=t,e.nextSeq=s.lastSeq+1;try{await this.storeOp(()=>this.deps.store.writeChunk(e,o,s))}catch{e.lastChunkSeq=t-1}}setStatus(e,t,n){let i={state:e};return t&&(i.reason=t),n&&(i.recordingId=n),this.status=i,this.publishCapture(),i}publishCapture(){let e=this.active,t=!!e&&this.canCapture(e,!1),n=e&&t&&!e.excluded?e.policy:null;if(this.touchesWanted=t,this.wantsKeyframe=!e||e.needKeyframe||e.lastKeyframeId===null||this.deps.monoMicros()-e.lastKeyframeMono>=e.policy.keyframeIntervalSeconds*1e6,n!==this.capturePolicy){this.capturePolicy=n;try{this.onCaptureChanged?.(n)}catch{}}this.updateTicker()}get recordingId(){return this.active?.meta.recordingId??null}};function ge(r){return r.buffer.reduce((e,t)=>e+V(t),0)}function jt(r,e){let t=(n,i)=>n===i||!!n&&!!i&&n.size===i.size&&[...n].every(s=>i.has(s));return t(r.allowedScreens,e.allowedScreens)&&t(r.excludedScreens,e.excludedScreens)}var $e=(r,e)=>({openedAt:r,trigger:e,inFlight:!1,nextAt:0,backoffMs:0,last:0,waiters:[]}),Xe=r=>typeof r=="string"&&r.length>=1&&r.length<=ye?r:null;function Je(r){if(r==null)return null;let e=S(r),t=e?.start_event===null?null:Xe(e?.start_event),n=e?.stop_event===null?null:Xe(e?.stop_event);return!e||typeof e.replay_enabled!="boolean"||t===null&&e.start_event!==null||n===null&&e.stop_event!==null?{enabled:!1,startEvent:null,stopEvent:null}:{enabled:e.replay_enabled,startEvent:t,stopEvent:t!==null&&n!==t?n:null}}function Ye(r){let e=P(S(I(r)?.error)?.retry_after_seconds),t=r.retryAfter&&/^\d+$/.test(r.retryAfter.trim())?Number(r.retryAfter.trim()):null;return X(e??t??60,1,3600)*1e3}function I(r){try{return S(JSON.parse(r.body))}catch{return null}}var B=(r,e)=>`${r}-${e.streamId}-${e.chunkSeq}`,Y=r=>({...r,chunks:r.chunks.map(e=>({...e}))}),Gt=(r,e)=>r.streamId===e.streamId&&r.chunkSeq===e.chunkSeq;var Vt="depsmith-replay",$t=1,ve=r=>`${r}~draft~`,Q=r=>IDBKeyRange.bound(ve(r),`${ve(r)}\uFFFF`);function D(r){return new Promise((e,t)=>{r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)})}function E(r){return new Promise((e,t)=>{r.oncomplete=()=>e(),r.onerror=()=>t(r.error),r.onabort=()=>t(r.error)})}var Z=class{constructor(e=indexedDB){this.db=new Promise((t,n)=>{let i=e.open(Vt,$t);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains("meta")||s.createObjectStore("meta",{keyPath:"recordingId"}),s.objectStoreNames.contains("chunks")||s.createObjectStore("chunks")},i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error),i.onblocked=()=>n(new Error("replay store blocked"))}),this.db.catch(()=>{})}async tx(e){return(await this.db).transaction(["meta","chunks"],e)}async recordings(){try{let e=await this.tx("readonly"),t=await D(e.objectStore("meta").getAll()),n=new Set(await D(e.objectStore("chunks").getAllKeys()));for(let i of t)i.chunks=i.chunks.filter(s=>n.has(B(i.recordingId,s)));return t.sort((i,s)=>i.recordingId<s.recordingId?-1:1)}catch{return[]}}async save(e){try{let t=await this.tx("readwrite");t.objectStore("meta").put(Y(e)),await E(t)}catch{}}async writeChunk(e,t,n){e.chunks.push(t);try{let i=await this.tx("readwrite");i.objectStore("chunks").put(n,B(e.recordingId,t)),i.objectStore("chunks").delete(Q(e.recordingId)),i.objectStore("meta").put(Y(e)),await E(i)}catch(i){throw e.chunks=e.chunks.filter(s=>s!==t),i}}async readChunk(e,t){try{let n=await this.tx("readonly"),i=await D(n.objectStore("chunks").get(B(e,t)));return i instanceof Uint8Array?i:i instanceof ArrayBuffer?new Uint8Array(i):i&&typeof i=="object"&&i.ndjson instanceof Uint8Array?i:null}catch{return null}}async replaceChunk(e,t,n,i){e.chunks=e.chunks.map(a=>Gt(a,t)?n:a);let s=await this.tx("readwrite");await D(s.objectStore("meta").get(e.recordingId))&&(s.objectStore("chunks").put(i,B(e.recordingId,n)),s.objectStore("meta").put(Y(e)),await E(s))}async appendDraft(e,t,n){try{let i=await this.tx("readwrite");t===0&&i.objectStore("chunks").delete(Q(e)),i.objectStore("chunks").put(n,`${ve(e)}${String(t).padStart(6,"0")}`),await E(i)}catch{}}async readDrafts(e,t){try{let n=await this.tx("readonly"),i=(await D(n.objectStore("chunks").getAll(Q(e)))).filter(s=>s&&s.chunkSeq===t&&Array.isArray(s.records));return{records:i.flatMap(s=>s.records),policyVersion:i[0]?.policyVersion??1}}catch{return{records:[],policyVersion:1}}}async deleteChunk(e,t){e.chunks=e.chunks.filter(n=>!(n.streamId===t.streamId&&n.chunkSeq===t.chunkSeq));try{let n=await this.tx("readwrite");n.objectStore("chunks").delete(B(e.recordingId,t)),await D(n.objectStore("meta").get(e.recordingId))&&n.objectStore("meta").put(Y(e)),await E(n)}catch{}}async deleteRecording(e){try{let t=await this.tx("readwrite");t.objectStore("meta").delete(e),t.objectStore("chunks").delete(IDBKeyRange.bound(`${e}-`,`${e}-\uFFFF`)),t.objectStore("chunks").delete(Q(e)),await E(t)}catch{}}async purgeAll(){try{let e=await this.tx("readwrite");e.objectStore("meta").clear(),e.objectStore("chunks").clear(),await E(e)}catch{}}};function Xt(r){if(typeof AbortController>"u")return{cancel:()=>{}};let e=new AbortController,t=setTimeout(()=>e.abort(),r);return{signal:e.signal,cancel:()=>clearTimeout(t)}}function Qe(r=(...e)=>fetch(...e)){let e=async(t,n)=>{let i=Xt(3e4);try{let s=await r(t,{...n,redirect:"manual",credentials:"omit",signal:i.signal});return s.type==="opaqueredirect"||s.status>=300&&s.status<400?{status:0,body:""}:{status:s.status,body:await s.text(),retryAfter:s.headers.get("Retry-After")}}catch{return{status:0,body:""}}finally{i.cancel()}};return{post:(t,n,i,s)=>{let o={"Content-Type":"application/json",Authorization:`Bearer ${n}`};return i&&(o["X-Replay-Token"]=i),e(t,{method:"POST",headers:o,body:s})},get:t=>e(t,{method:"GET"}),put:async(t,n,i)=>(await e(t,{method:"PUT",headers:{...n},body:i})).status}}var Jt={get(r){try{return JSON.parse(localStorage.getItem(`depsmith_replay_${r}`)??"null")}catch{return null}},set(r,e){try{localStorage.setItem(`depsmith_replay_${r}`,JSON.stringify(e))}catch{}}},be=class{constructor(){this.held=new Map}async claim(e){if(this.held.has(e))return!0;let t=typeof navigator<"u"?navigator.locks:void 0;return t?.request?new Promise(n=>{t.request(`depsmith-replay:${e}`,{ifAvailable:!0},i=>{if(!i){n(!1);return}return new Promise(s=>{this.held.set(e,s),n(!0)})}).catch(()=>n(!0))}):!0}release(e){this.held.get(e)?.(),this.held.delete(e)}};function ee(){try{if(typeof window>"u"||typeof document>"u"||typeof indexedDB>"u"||!Ke())return!1;let r=document.createElement("canvas");return typeof r.getContext=="function"&&!!r.getContext("2d")&&typeof r.toBlob=="function"}catch{return!1}}var O=null,Ze=null,et=!1,Yt=new be;function Qt(){let r=Math.max(1,Math.min(16384,Math.round(window.innerWidth||1))),e=Math.max(1,Math.min(16384,Math.round(window.innerHeight||1))),t=window.devicePixelRatio,n=Number.isFinite(t)&&t>0?Math.min(8,Math.round(t*1e3)/1e3):1;return{w:r,h:e,density:n}}function Zt(r){if(nt(),!ee())return;Ze??(Ze=new Z);let e=new J(r,{now:()=>Date.now(),monoMicros:()=>Math.round(performance.now()*1e3),transport:Qe(),store:Ze,isOnline:()=>navigator.onLine!==!1,viewport:Qt,claims:Yt,autoStart:!0,state:Jt});document.visibilityState==="hidden"&&e.onBackground();let t=()=>{document.visibilityState==="hidden"?e.onBackground():e.onForeground()},n=()=>e.onBackground(),i=o=>{o.persisted&&e.onForeground()};document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",n),window.addEventListener("pageshow",i);let s=new G(e,window);e.bind(),O={host:r,engine:e,capture:s,detach:()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",n),window.removeEventListener("pageshow",i),s.dispose()}}}function nt(){let r=O;O=null,r?.detach()}var en={clientCreated:r=>Zt(ie(r)),clientGone:(r,e)=>{e&&se(ie(r),!0),nt()}},tt=!1,we={install(){if(!et){et=!0;try{Me(en)}catch{}}},start(r={}){if(we.install(),!ee())return tt||(tt=!0,console.warn("[depsmith-sdk] Session Replay is not supported on this page (needs a secure context, IndexedDB and canvas)")),Promise.resolve({state:"off",reason:"unsupported_platform"});let e=O;if(!e)return Promise.resolve({state:"off",reason:"not_initialized"});let t={allowedScreens:Array.isArray(r.allowedScreens)?r.allowedScreens.filter(n=>typeof n=="string"):void 0,excludedScreens:Array.isArray(r.excludedScreens)?r.excludedScreens.filter(n=>typeof n=="string"):void 0};return new Promise(n=>{try{e.engine.start(t,n)}catch{n({state:"off",reason:"admission_unavailable"})}})},stop(r={}){let e=O;return e?new Promise(t=>{try{e.engine.stop(r.discardPending===!0,t)}catch{t()}}):Promise.resolve()},getStatus(){let r=O;return r?{...r.engine.status}:{state:"off",reason:ee()?"not_initialized":"unsupported_platform"}}},tn=we;0&&(module.exports={ALLOW_ATTR,EXCLUDE_ATTR,MASK_ATTR,NO_CAPTURE_ATTR,replaySupported,sessionReplay});
|
|
3
|
+
//# sourceMappingURL=replay.cjs.map
|