@sprig-technologies/sprig-browser 2.35.0 → 2.36.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/dist/{core-De2JxeSJ.js → core-BVtQnihE.js} +3 -3
- package/dist/{core-CGgKmpNf.cjs → core-Bzv2KQOu.cjs} +2 -2
- package/dist/core.cjs +1 -1
- package/dist/core.d.ts +4 -0
- package/dist/core.js +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -2
- package/dist/{metricsReporter-BvLxSPGb.cjs → metricsReporter-DbEyJSwA.cjs} +1 -1
- package/dist/{metricsReporter-BJVpNufn.js → metricsReporter-M_tu1Yrx.js} +1 -1
- package/dist/replay.cjs +1 -1
- package/dist/replay.js +54 -54
- package/dist/view-DJdeN4-t.js +3105 -0
- package/dist/view-qqhfcMHd.cjs +669 -0
- package/package.json +1 -1
- package/dist/view-CCKqaqND.cjs +0 -669
- package/dist/view-kh2hxG3p.js +0 -2979
package/dist/replay.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var et=Object.defineProperty;var tt=(e,t,r)=>t in e?et(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var N=(e,t,r)=>tt(e,typeof t!="symbol"?t+"":t,r);const o=require("./metricsReporter-BvLxSPGb.cjs");var L=(e=>(e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e))(L||{}),P=(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(P||{});const Z=(e,t)=>t.some(r=>e instanceof r);let ye,fe;const ee=new WeakMap,q=new WeakMap,$=new WeakMap;let te={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return ee.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return x(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&(t==="done"||t==="store")||t in e};function Ee(e){te=e(te)}function rt(e){return(fe||(fe=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(re(this),t),x(this.request)}:function(...t){return x(e.apply(re(this),t))}}function nt(e){return typeof e=="function"?rt(e):(e instanceof IDBTransaction&&function(t){if(ee.has(t))return;const r=new Promise((n,a)=>{const s=()=>{a(t.error||new DOMException("AbortError","AbortError"))};t.oncomplete=()=>{n()},t.onerror=s,t.onabort=s});ee.set(t,r)}(e),Z(e,ye||(ye=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,te):e)}function x(e){if(e instanceof IDBRequest)return function(r){const n=new Promise((a,s)=>{r.onsuccess=()=>{a(x(r.result))},r.onerror=()=>{s(r.error)}});return $.set(n,r),n}(e);if(q.has(e))return q.get(e);const t=nt(e);return t!==e&&(q.set(e,t),$.set(t,e)),t}const re=e=>$.get(e);function ne(e,{blocked:t}={}){const r=indexedDB.deleteDatabase(e);return t&&(r.onblocked=n=>t(n.oldVersion,n)),x(r).then(()=>{})}const at=["get","getKey","getAll","getAllKeys","count"],st=["put","add","delete","clear"],z=new Map;function he(e,t){if(!(e instanceof IDBDatabase)||t in e||typeof t!="string")return;if(z.get(t))return z.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,a=st.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!a&&!at.includes(r))return;const s=async function(i,...c){const d=this.transaction(i,a?"readwrite":"readonly");let u=d.store;return n&&(u=u.index(c.shift())),(await Promise.all([u[r](...c),a&&d.done]))[0]};return z.set(t,s),s}Ee(e=>({...e,get:(t,r,n)=>he(t,r)||e.get(t,r,n),has:(t,r)=>!!he(t,r)||e.has(t,r)}));const ot=["continue","continuePrimaryKey","advance"],Ie={},ae=new WeakMap,Re=new WeakMap,it={get(e,t){if(!ot.includes(t))return e[t];let r=Ie[t];return r||(r=Ie[t]=function(...n){ae.set(this,Re.get(this)[t](...n))}),r}};async function*dt(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const r=new Proxy(t,it);for(Re.set(r,t),$.set(r,re(t));t;)yield r,t=await(ae.get(r)||t.continue()),ae.delete(r)}function ve(e,t){return t===Symbol.asyncIterator&&Z(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&Z(e,[IDBIndex,IDBObjectStore])}Ee(e=>({...e,get:(t,r,n)=>ve(t,r)?dt:e.get(t,r,n),has:(t,r)=>ve(t,r)||e.has(t,r)}));const ct="sprigReplayIframeLoaded",ut="sprigReplayIframeSettings",lt="sprigReplayIframeTakeFullSnapshot",pt="sprigReplayTeardown",pe=[],Ce=new class{constructor(e){N(this,"awaitingResolvers",[]);N(this,"activeCount",0);this.capacity=e}async acquire(){if(!(this.activeCount<this.capacity))return new Promise(e=>{this.awaitingResolvers.push(e)});this.activeCount++}release(){const e=this.awaitingResolvers.shift();e&&this.activeCount<=this.capacity?e():this.activeCount--}async execute(e){try{return await this.acquire(),await e()}finally{this.release()}}setLimit(e){this.capacity=e}}(2),Te=async({apiUrl:e,surveyId:t,uploadId:r,etags:n,headers:a,responseGroupUuid:s,replayDuration:i,eventDigest:c},d=!1)=>{var w;if(!d&&!r&&!n)return void o.breadcrumbsLogger.error("UploadErr",{isMobile:d,uploadId:r,etags:n});o.breadcrumbsLogger.info("MarkUploadComplete",{surveyId:t});const u=await o.sprigFetch(`${e}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:n,uploadId:r,responseGroupUuid:s,surveyId:t,replayDuration:i,eventDigest:c,userAgent:(w=window==null?void 0:window.navigator)==null?void 0:w.userAgent}),headers:a,shouldRetryRequest:!0});return o.breadcrumbsLogger.info("MarkUploadDone",{surveyId:t}),u},gt=e=>{if(e instanceof Attr)return null;let t=1;for(let r=e.previousSibling;r;r=r.previousSibling)r.nodeName===e.nodeName&&++t;return t},Pe=e=>{if(e===null)return"";const t=[];if(e instanceof Document)return"/";for(let r=e;r&&!(r instanceof Document)&&r!==null;r=r instanceof Attr?r.ownerElement:r.parentElement){const n=t[t.length]={name:void 0,position:null};switch(r.nodeType){case Node.TEXT_NODE:n.name="text()";break;case Node.ATTRIBUTE_NODE:n.name="@"+r.nodeName;break;case Node.PROCESSING_INSTRUCTION_NODE:n.name="processing-instruction()";break;case Node.COMMENT_NODE:n.name="comment()";break;case Node.ELEMENT_NODE:n.name=r.nodeName}n.position=gt(r)}return"/"+t.reverse().map(r=>r.position!==null?`/${r.name}[${r.position}]`:`/${r.name}`).join("")},ge=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),R={capture:!0,passive:!0},mt=["a","button","input","option","li","link"],wt=["Escape","Enter","Backspace","F5","Tab"];let j=!1,S=null,V=null;const be=e=>{var r;if(((r=e.tagName)==null?void 0:r.toLowerCase())==="html")return{element:"html"};const t={};return t.element=(n=>{if(!n.tagName)return"No tagName";const a=n.getAttribute("type");return a?`${a} ${n.tagName.toLowerCase()}`:n.tagName.toLowerCase()})(e),t},yt=e=>{var n;if(!e)return{};const t={...be(e)},r=e.parentElement;if(r&&mt.includes((n=r.tagName)==null?void 0:n.toLowerCase())){const a=be(r);Object.assign(t,a)}return t},ke=(e,t)=>{var a,s;let r=t.target;var n;t.target===((a=window.document)==null?void 0:a.body)&&window.Sprig.pointerDownTarget&&(r=window.Sprig.pointerDownTarget),n={x:t.x,y:t.y,type:e,elementAttributes:yt(r),windowHeight:window.innerHeight,windowWidth:window.innerWidth,...r instanceof HTMLElement?{rect:r==null?void 0:r.getBoundingClientRect(),xPath:Pe(r)}:{}},(s=n==null?void 0:n.elementAttributes)!=null&&s.text&&(n.elementAttributes.text=ge(n.elementAttributes.text)),S==null||S("Sprig_Click",n)},Ue=e=>{var t;wt.includes(e.key)&&(t={key:e.key},S==null||S("Sprig_Keystroke",t))},ft=()=>{var e;window.performance.getEntriesByType("navigation").map(t=>t.type).includes("reload")&&(e={url:window.location.href,currentPageTitle:document.title},S==null||S("Sprig_Refresh",e))},ht=()=>{var e;window.performance.getEntriesByType("navigation").map(t=>t.type).includes("back_forward")&&((e={curUrl:window.location.href,fromUrl:document.referrer,currentPageTitle:document.title}).currentPageTitle&&(e.currentPageTitle=ge(e.currentPageTitle)),S==null||S("Sprig_BackForward",e))},Le=((e,t)=>{let r;return n=>{clearTimeout(r),r=window.setTimeout(()=>e(n),t)}})(e=>{if(!(e.target instanceof HTMLElement||e.target instanceof Document))return;let t=e.target;"scrollTop"in t||(t=t.documentElement),V==null||V({xPath:Pe(t),x:t.scrollLeft,y:t.scrollTop,elementAttributes:{targetScrollWidth:t.scrollWidth,targetClientWidth:t.clientWidth,targetScrollHeight:t.scrollHeight,targetClientHeight:t.clientHeight}})},750),xe=(Se="left_click",e=>ke(Se,e));var Se;const Be=e=>{e.button===2&&ke("right_click",e)},Me=e=>{window.Sprig&&(window.Sprig.pointerDownTarget=e.target)},g={isRecording:!1,scrollEventUuids:{},stopRecording:()=>{}},Ae=()=>window.indexedDB&&window.IDBKeyRange&&window.CompressionStream,h=(()=>{const e=o.sessionStorageHelper.getItem("sprig.sessionId");if(e)return o.breadcrumbsLogger.info("SessionIDFound",{savedSessionId:e}),o.sessionStorageHelper.removeItem("sprig.sessionId"),e;const t=o.v4();return o.breadcrumbsLogger.info("GeneratedSessionID",{uuid:t}),t})(),se=()=>{o.sessionStorageHelper.setItem("sprig.disableReplayRecording","disabled")},C=()=>!!o.sessionStorageHelper.getItem("sprig.disableReplayRecording"),K=()=>!!o.sessionStorageHelper.getItem("sprig.isReplayPaused");window.addEventListener("beforeunload",()=>{o.breadcrumbsLogger.info("BeforeUnload",{sessionId:h}),o.sessionStorageHelper.setItem("sprig.sessionId",h)});const k=(e,t)=>{var r,n;if(!C()&&g.isRecording&&!K())try{(n=(r=window.rrwebRecord)==null?void 0:r.addCustomEvent)==null||n.call(r,e,t)}catch(a){O("Error recording custom event",a)}},It=async e=>{const{x:t,xPath:r,y:n}=e,a=g.scrollEventUuids[r];if(a)return b(async()=>{var c,d,u,w;const s=await l.openDB(),i=await s.get("events",a);if(i!=null&&i.event){const p=JSON.parse(i.event),f=t>((d=(c=p.data)==null?void 0:c.payload)==null?void 0:d.x),m=n>((w=(u=p.data)==null?void 0:u.payload)==null?void 0:w.y);if(!f&&!m)return null;f&&(p.data.payload.x=t),m&&(p.data.payload.y=n),p.data.payload.elementAttributes=e.elementAttributes,i.event=JSON.stringify(p),await s.put("events",i)}else k("Sprig_Scroll",e)},"Error updating scroll event");k("Sprig_Scroll",e)},_e=()=>{g.stopRecording&&(g.stopRecording(),g.stopRecording=void 0),g.isRecording=!1,["cleanupInterval","inactivityInterval","pendingCheckInterval"].forEach(e=>{g[e]&&(clearInterval(g[e]),g[e]=void 0)}),j&&(window.removeEventListener("click",xe,R),window.removeEventListener("pointerdown",Me,R),window.removeEventListener("mousedown",Be,R),window.removeEventListener("keydown",Ue,R),window.removeEventListener("scroll",Le,R),j=!1),pe.forEach(e=>{var t;(t=e.source)==null||t.postMessage({type:pt},{targetOrigin:e.origin})})},vt=["did not allow mutations","called in an invalid security context"],bt=(e,t,{reportError:r=!0,extraInfo:n={}})=>{if(!C()&&t instanceof Error){if(se(),t.name==="VersionError")return o.breadcrumbsLogger.error("VersionErr",{message:e}),void l.deleteDB();(a=>{if(!a)return!0;for(const s of vt)if(a.toLowerCase().includes(s))return!1;return!0})(t==null?void 0:t.message)&&(r&&window.UserLeap.reportError(e,t,n),l.clearAll())}},O=(e,t,{reportError:r}={reportError:!0})=>{_e(),o.breadcrumbsLogger.error("ReplayErr",{code:t.code,name:t.name}),bt(e,t,{reportError:r})},b=async(e,t)=>{try{return await e()}catch(r){O(t,r)}},oe=()=>{g.isRecording&&(b(()=>{var e,t;return(t=(e=window.rrwebRecord)==null?void 0:e.takeFullSnapshot)==null?void 0:t.call(e,!0)},"Error recording full snapshot"),pe.forEach(e=>{var t;(t=e.source)==null||t.postMessage({type:lt},{targetOrigin:e.origin})}))};let Q=0;(async()=>Ae()&&Promise.allSettled([ne("replayStorage"),ne("sprig.replay")]))();const l=new class{constructor(){N(this,"wrapTransactionWithCounter",e=>{var n,a;const t=(a=(n=window.Sprig)==null?void 0:n._config)==null?void 0:a.outstandingTransactionLimit,r=t===void 0?100:t;if(r&&Q>r){const s="Too many outstanding transactions";O(s,new Error(s),{reportError:!1})}Q++,e.done.finally(()=>{Q--})});N(this,"getTransaction",async e=>{const t=(await this.openDB()).transaction(e,"readwrite");return this.wrapTransactionWithCounter(t),t})}openDB(){return function(e,t,{blocked:r,upgrade:n,blocking:a,terminated:s}={}){const i=indexedDB.open(e,t),c=x(i);return n&&(i.onupgradeneeded=d=>{n(x(i.result),d.oldVersion,d.newVersion,x(i.transaction),d)}),r&&(i.onblocked=d=>r(d.oldVersion,d.newVersion,d)),c.then(d=>{s&&(d.onclose=()=>s()),a&&(d.onversionchange=u=>a(u.oldVersion,u.newVersion,u))}).catch(()=>{}),c}("sprigReplay",1,{upgrade:(e,t,r)=>{if(r===0&&o.sessionStorageHelper.setItem("sprig.pendingCount","0"),!e.objectStoreNames.contains("events")){const n=e.createObjectStore("events",{keyPath:"uuid"});n.createIndex("sessionId","sessionId"),n.createIndex("timestamp","timestamp"),n.createIndex("[sessionId+timestamp]",["sessionId","timestamp"])}if(!e.objectStoreNames.contains("chunkUploads")){const n=e.createObjectStore("chunkUploads",{keyPath:"uuid"});n.createIndex("sessionId","sessionId"),n.createIndex("timestamp","timestamp"),n.createIndex("[sessionId+status]",["sessionId","status"]),n.createIndex("[uploadId+status]",["uploadId","status"]),n.createIndex("[sessionId+status+uploadId]",["sessionId","status","uploadId"])}if(!e.objectStoreNames.contains("pendingCaptures")){const n=e.createObjectStore("pendingCaptures",{keyPath:"uuid"});n.createIndex("sessionId","sessionId"),n.createIndex("timestamp","timestamp"),n.createIndex("[sessionId+targetTimestamp]",["sessionId","targetTimestamp"])}}})}async deleteDB(){try{await ne("sprigReplay")}catch{}}async bulkAdd(e,t){const r=await this.getTransaction(e);return Promise.all([...t.map(n=>r.store.add(n)),r.done])}async clearAll(){const e=(await this.openDB()).transaction(["events","chunkUploads","pendingCaptures"],"readwrite");return this.wrapTransactionWithCounter(e),Promise.all([e.objectStore("events").clear(),e.objectStore("chunkUploads").clear(),e.objectStore("pendingCaptures").clear()])}async deleteBySessionId(e,t){const r=IDBKeyRange.only(t),n=await this.getTransaction(e),a=n.store.index("sessionId");for await(const s of a.iterate(r))await s.delete();await n.done}async updatePartial(e,t,r){const n=await this.getTransaction(e),a=await n.store.get(t);a&&await n.store.put({...a,...r}),await n.done}async deleteRowsBefore(e,t,r=()=>!0){const n=IDBKeyRange.upperBound(t,!0),a=await this.getTransaction(e),s=a.store.index("timestamp");for await(const i of s.iterate(n))r(i.value)&&await i.delete();await a.done}async getEventsBetween(e,t=Date.now()){if(e>=t)return Promise.resolve([]);const r=IDBKeyRange.bound([h,e],[h,t],!1,!0);return(await this.openDB()).getAllFromIndex("events","[sessionId+timestamp]",r)}async updateEventsExpiredAt(e,t,r=30){const n=new Date,a=n.setMinutes(n.getMinutes()+(r??30)),s=await this.getTransaction("events"),i=s.store.index("[sessionId+timestamp]"),c=IDBKeyRange.bound([h,e],[h,t],!1,!0);for await(const d of i.iterate(c))await d.update({...d.value,expiredAt:a});await s.done}async deleteChunkUploads(e,t){const r=IDBKeyRange.only([t,e]),n=await this.getTransaction("chunkUploads");let s=await n.store.index("[uploadId+status]").openCursor(r);for(;s;)s.delete(),s=await s.continue();await n.done}async getChunkUploadsByStatus({sessionId:e,status:t,uploadId:r}){const n=(await this.openDB()).transaction("chunkUploads","readonly");this.wrapTransactionWithCounter(n);const a=r?n.store.index("[uploadId+status]"):n.store.index("[sessionId+status]"),s=r?IDBKeyRange.only([r,t]):IDBKeyRange.only([e,t]);return a.getAll(s)}async getPendingCaptures(e={}){return(await(await this.openDB()).getAllFromIndex("pendingCaptures","sessionId",h)).filter(r=>!e.beforePresent||r.targetTimestamp<Date.now()).filter(r=>!e.isBeforeType||r.captureParams.replayParams.replayDurationType==="before").filter(r=>!e.isHeatmap||(r.captureParams.isHeatmap??!1))}async markPendingCaptureToCanUpload(e){const t=await this.getTransaction("pendingCaptures"),r=t.store.index("sessionId");for await(const n of r.iterate(h)){const a=n.value;a.captureParams.responseGroupId===e&&await n.update({...a,canUpload:!0})}await t.done}async markPendingHeatmapsReady(e){if(parseInt(o.sessionStorageHelper.getItem("sprig.pendingCount")??"0")===0)return null;const t=Date.now(),r=await this.getTransaction("pendingCaptures"),n=r.store.index("sessionId");for await(const a of n.iterate(h)){const s=a.value;!s.captureParams.isHeatmap||e&&!e.includes(s.uuid)||await a.update({...s,targetTimestamp:t,captureParams:{...s.captureParams,triggerTimestamp:t,replayParams:{...s.captureParams.replayParams,replayDurationSeconds:Math.floor((t-s.timestamp)/1e3)}}})}await r.done}},U=[];let F,He,J,Ne,G,Oe,M=[],_=!1,A=0,W=!1,Fe=!1,me=[],X=!1;const H=()=>W&&!_&&Date.now()<=J,St=({apiUrl:e,config:t,triggerSnapshot:r,forceInit:n=!1})=>{W&&!n||(o.sessionStorageHelper.isStorageAvailable?(M=[],me.splice(0),U.splice(0),A=0,G=r,He=e,F={responseGroupUuid:t.responseGroupUuid,surveyId:t.surveyId,userAgent:t.userAgent,sdkVersion:t.sdkVersion},Ne=t.maxDurationSeconds,Ct(),W||(Oe=window.setInterval(Rt,500)),W=!0):_=!0)},Dt=[P.Drag,P.Input,P.MediaInteraction,P.MouseInteraction,P.MouseMove,P.Scroll,P.Selection,P.TouchMove],Et=e=>e.type===L.Custom||e.type===L.IncrementalSnapshot&&Dt.includes(e.data.source),we=e=>e.some(Et),Rt=async()=>{if(!H())return void window.clearInterval(Oe);if(Ve(),!we(U))return;const e=U[0].timestamp;Date.now()-e>35e3&&(G==null||G())},Ve=async()=>{if(M.length||X)return;X=!0;const e=await Pt();if(!e)return void(_=!0);me.splice(0,e.length).forEach(t=>t(e.shift())),e.forEach(t=>M.push(t)),X=!1},Ct=()=>{const e=o.sessionStorageHelper.getItem("sprig.alwayson.info");if(e){o.breadcrumbsLogger.info("Read stored session state",e);const t=JSON.parse(e);_=t.disabled,F=t.metadata,M=t.uploadUrls,A=t.currentIndex,J=t.expirationTimestamp,t.pendingEventTimestamp&&(o.breadcrumbsLogger.info(`Uploading with pending timestamp: ${t.pendingEventTimestamp}`),Tt(t.pendingEventTimestamp))}else J=1e3*Ne+Date.now()},Tt=async e=>{const t=Date.now(),r=(await l.getEventsBetween(e,t)).map(a=>JSON.parse(a.event));if(!we(r))return;je(r);const n=await $e();n&&await We(n,r)},Ge=async(e,t)=>{try{const r=await e();if(!r.ok)throw new Error(`Error ${t}`);return r}catch{_=!0}},We=async(e,t)=>{if(!H()||!e)return;const r=await(async n=>{const a=new TextEncoder,s=new CompressionStream("gzip"),i=s.writable.getWriter(),c=a.encode(JSON.stringify(n));return i.write(c),i.close(),new Uint8Array(await new Response(s.readable).arrayBuffer())})(t);o.breadcrumbsLogger.info("Uploading always-on events with presigned url"),await Ge(()=>o.sprigFetch(e,{body:r,method:"PUT"}),"uploading always-on with presigned url")},Pt=async()=>{if(!H())return;const{surveyId:e,responseGroupUuid:t}=F,r={responseGroupUuid:t,surveyId:e,index:A+1};o.breadcrumbsLogger.info("Fetching always-on upload urls",r);const n=await Ge(()=>o.sprigFetch(`${He}/sdk/1/replayUrls`,{method:"POST",body:JSON.stringify(r),headers:o.getHttpHeaders(window.UserLeap)}),"fetching always-on signed urls");if(!n)return;const a=n.json.signedUrls;return o.breadcrumbsLogger.info("Fetched more always-on upload urls",{body:r,urls:a}),a},$e=async()=>{if(M.length)return M.shift();const e=new Promise(t=>{me.push(t)});return Ve(),e},je=e=>{var a,s,i;const t=e.length?e[e.length-1].timestamp:Date.now(),r=A,n=((s=(a=window.UserLeap)==null?void 0:a.config)==null?void 0:s.customMetadata)??((i=window.__cfg)==null?void 0:i.customMetadata);A++,e.push({timestamp:t,type:L.Custom,data:{tag:"Sprig_Meta",payload:{...F,index:r,visitorId:window.UserLeap.visitorId??"",timestamp:t,customMetadata:n}}})},kt=(e,t)=>{H()&&!Fe&&(e||U.length)&&(e&&U.length&&(async()=>{const r=U.splice(0);if(!we(r))return;o.breadcrumbsLogger.info("Capturing always-on event array to upload"),je(r);const n=await $e();n&&await We(n,r)})(),U.push(t))};window.addEventListener("beforeunload",async()=>{Fe=!0,H()&&(o.breadcrumbsLogger.info("Always On handle page unload"),(()=>{let e;U.length&&(e=U[0].timestamp);const t={disabled:_,metadata:F,uploadUrls:M,currentIndex:A,pendingEventTimestamp:e,expirationTimestamp:J};o.breadcrumbsLogger.info("Storing session state on unload",t),o.sessionStorageHelper.setItem("sprig.alwayson.info",JSON.stringify(t))})())});const Ke=async(e,t)=>{const r=performance.now();let n;try{n=await e()}finally{const a=performance.now()-r;let s=o.PerformanceMetrics[t];s||(s=o.registerMetric(t)),s.report(a/1e3)}return n},Je=(e,t)=>{const r=performance.now();try{e()}finally{const n=performance.now()-r;let a=o.PerformanceMetrics[t];a||(a=o.registerMetric(t)),a.report(n/1e3)}};let qe=5e3,ie=6e4,de=0,B,ce=!1,ue=[];const Ut=e=>{var t,r,n,a;if((t=e.event)!=null&&t.includes("Sprig_Scroll")){const s=(a=(n=(r=JSON.parse(e.event))==null?void 0:r.data)==null?void 0:n.payload)==null?void 0:a.xPath;if(!s)return;g.scrollEventUuids[s]=e.uuid}ue.push(e),ce||Lt()},Lt=()=>{ce=!0,setTimeout(async()=>{if(C()||K())return;const e=ue;ue=[],ce=!1,Je(async()=>{await(async t=>{const r=t.map(n=>({...n,sessionId:n.sessionId??h}));if(r.length!==0)return b(()=>l.bulkAdd("events",r),"Error storing replay events")})(e)},"sdk_replay_add_event_batch_seconds")},500)},xt=(e,t,r)=>{g.cleanupInterval=window.setInterval(()=>{const n=Date.now();Ke(()=>b(async()=>{C()||await Promise.all([l.deleteRowsBefore("events",n-1e3*e,a=>a.expiredAt===void 0||a.expiredAt<n-1e3*e),l.deleteRowsBefore("chunkUploads",n-1e3*t),l.deleteRowsBefore("pendingCaptures",n-1e3*r,a=>!a.canUpload)])},"Error deleting table rows"),"sdk_replay_cleanup_seconds"),o.breadcrumbsLogger.debug("CleanupComplete")},3e4)},Bt=()=>{g.pendingCheckInterval=window.setInterval(async()=>{b(async()=>{await le()},"Error initiating pending captures")},5e3)};let Y=!1;const le=async(e=!1)=>{if(!Y)try{Y=!0;const t=parseInt(B??"0");if(t===0)return;const r=await l.getPendingCaptures({beforePresent:!0,isBeforeType:e}),n=await l.openDB();await Promise.all(r.map(async a=>(await n.delete("pendingCaptures",a.uuid),Xe(a.captureParams,a.canUpload)))),B=(t-r.length).toString(),o.sessionStorageHelper.setItem("sprig.pendingCount",B)}finally{Y=!1}},Mt=async(e,t,r,n,a)=>{const s=Math.min(e+a,r),i=await Ke(()=>l.getEventsBetween(e,s),"sdk_replay_get_events_between_seconds");if(!(i!=null&&i.length))return o.breadcrumbsLogger.debug("NoEventsFound"),{validStartFound:n,events:[]};if(!n){o.breadcrumbsLogger.debug("ValidStartSearch");let c=-1;return i==null||i.forEach((d,u)=>{if(!d.isValidStart)return;const w=d.timestamp<=t;(c<0||w)&&(c=u)}),c<0?(o.breadcrumbsLogger.debug("ValidStartNotFound"),{validStartFound:n,events:[]}):{validStartFound:!0,events:i==null?void 0:i.slice(c)}}return{validStartFound:n,events:i}},ze=e=>Promise.all(e.map(async t=>{const r=await(async n=>Ce.execute(async()=>{var i;o.breadcrumbsLogger.info("UploadChunkStart",{chunkIndex:n.chunkIndex,surveyId:n.surveyId});const a=await o.sprigFetch(n.uploadUrl,{body:n.data,method:"PUT"});o.breadcrumbsLogger.http("UploadChunkEnd",{url:n.uploadUrl,method:"PUT",status_code:a.status,reason:a.statusText??"OK",chunkIndex:n.chunkIndex,surveyId:n.surveyId});const s=(i=a.headers)==null?void 0:i.get("ETag");if(!s)throw new Error(`Upload response did not include etag for upload ${n.uploadId}, part ${n.chunkIndex}`);return s}))(t);return await l.updatePartial("chunkUploads",t.uuid,{data:null,etag:r,status:"UploadComplete"}),t.uploadId})),Qe=async e=>{const t=await l.getChunkUploadsByStatus({status:"UploadComplete",uploadId:e});if(!(t!=null&&t.length))return void o.breadcrumbsLogger.info("NoChunksForUpload",{uploadId:e});const r=t.reduce((s,i)=>(s.find(c=>c.chunkIndex===i.chunkIndex)||s.push(i),s),[]);r.sort((s,i)=>s.chunkIndex-i.chunkIndex);const n=r.map(s=>({ETag:s.etag,PartNumber:s.chunkIndex})).filter(s=>s.ETag!==null),a=r[0];await Te({apiUrl:a.apiUrl,surveyId:a.surveyId,uploadId:e,responseGroupUuid:a.responseGroupId,etags:n,headers:a.completeUploadHeaders,replayDuration:a.replayDuration}),await l.deleteChunkUploads("UploadComplete",e)},At=()=>{b(async()=>{const e=await l.getChunkUploadsByStatus({sessionId:h,status:"ReadyForUpload"});if(!(e!=null&&e.length))return;const t=await ze(e);t!=null&&t.length&&await Promise.all(t.map(r=>{if(r)return Qe(r)}))},"Error uploading unfinished chunks")},_t=async(e,t)=>{const r=t??Date.now();return(async(n,a)=>{const s=new TextEncoder;let i=null;const c=new CompressionStream("gzip"),d=c.writable.getWriter();let u=!1,w=!1,[p,f]=[0,0],m=[];for(let T=n-35e3;T<a;T+=ie){if({validStartFound:w,events:m}=await Mt(T,n,a,w,ie),!(m!=null&&m.length)){o.breadcrumbsLogger.debug("NoEventsFound");continue}p===0&&(p=m[0].timestamp),f=m[m.length-1].timestamp;const y=m.map(E=>E.event);y.push(`{"timestamp":${a}}`);const I=`${u?",":"["}${y}`,v=s.encode(I);Je(()=>{d.write(v)},"sdk_replay_compression_seconds"),u=!0}if(f-p<qe)return o.breadcrumbsLogger.debug("ReplayTooShort"),null;const D=s.encode("]");return d.write(D),d.close(),i=new Uint8Array(await new Response(c.readable).arrayBuffer()),i})(r-e,r)},De=async e=>{const{surveyId:t,responseGroupId:r,visitorId:n,apiUrl:a,completeUploadHeaders:s,replayParams:i,triggerTimestamp:c}=e,d=await _t(1e3*i.replayDurationSeconds,c);if(!(d!=null&&d.length))return void o.breadcrumbsLogger.info("FileDataEmpty",{surveyId:t});const u=((p,f,m)=>{const D=p.length,T=1024*f*1024,y=Math.ceil(D/m),I=Math.max(T,y),v=[];let E=0;for(;E<D;)v.push(p.slice(E,E+I)),E+=I;return v})(d,i.minimumChunkSizeMb,i.signedUrls.length),w=await Promise.all(u.map(async(p,f)=>{const m=o.v4(),D={apiUrl:a,chunkIndex:f+1,completeUploadHeaders:s,etag:null,responseGroupId:r,status:"ReadyForUpload",surveyId:t,timestamp:c,totalChunks:u.length,data:p,uploadId:i.uploadId,uploadUrl:i.signedUrls[f].url,uuid:m,visitorId:n};return await(await l.openDB()).add("chunkUploads",{...D,sessionId:D.sessionId??h}),D}));await(async(p,f)=>{await ze(f),await Promise.all(p.map(m=>Qe(m)))})([i.uploadId],w)},Xe=async(e,t)=>{if(C())return o.breadcrumbsLogger.debug("ReplayDisabled-ScheduleOrCapture");const{isHeatmap:r,isStandalone:n,replayParams:a,triggerTimestamp:s,responseGroupId:i}=e,c=async()=>{setTimeout(()=>o.eventEmitter.removeListener(o.SprigEvent.QuestionAnswered,c),0),b(async()=>{a.replayDurationType==="before"?await De(e):await l.markPendingCaptureToCanUpload(i)},"Error in schedule/capture callback")};b(async()=>{if(a.replayDurationType==="after"||a.replayDurationType==="beforeAndAfter")return!n&&!r&&o.eventEmitter.on(o.SprigEvent.QuestionAnswered,c),void await Ze(e);if(n||r||t)await De(e),r&&Ht();else{const d=35+a.replayDurationSeconds,u=s-1e3*d,w=s;await l.updateEventsExpiredAt(u,w,a.expirationTimeLimitMinutes),o.eventEmitter.on(o.SprigEvent.QuestionAnswered,c)}},"Error in scheduling/capturing replay")},Ht=async()=>{parseInt(B??"0")||o.sessionStorageHelper.removeItem("sprig.isCapturingHeatmap"),o.sessionStorageHelper.getItem("sprig.teardownAfterCapture")&&(_e(),Ye(),o.sessionStorageHelper.removeItem("sprig.teardownAfterCapture"))},Ye=async()=>C()?o.breadcrumbsLogger.debug("ReplayDisabled-ClearData"):Promise.all([l.deleteBySessionId("events",h),l.deleteBySessionId("pendingCaptures",h)]).catch(e=>{O("Error clearing user replay data",e)}),Ze=async e=>{if(C())return;const{isHeatmap:t,surveyId:r}=e,n=await l.getPendingCaptures(),a=n==null?void 0:n.filter(d=>d.captureParams.surveyId===r);if(a!=null&&a.length)return void o.breadcrumbsLogger.info("PendingCaptureExists",{surveyId:r});t&&(oe(),o.sessionStorageHelper.setItem("sprig.isCapturingHeatmap","true"),de=Date.now(),g.inactivityInterval||(g.inactivityInterval=window.setInterval(()=>{var d;d=de,Date.now()-d>=3e4&&b(()=>l.markPendingHeatmapsReady(),"Error in heatmap inactivity")},1e3)));const s={...e,replayParams:{...e.replayParams}};e.replayParams.replayDurationType==="beforeAndAfter"&&(s.replayParams.replayDurationSeconds*=2),s.replayParams.replayDurationType="before";const i=e.triggerTimestamp+1e3*e.replayParams.replayDurationSeconds;s.triggerTimestamp=i,B=(parseInt(B??"0")+1).toString(),o.sessionStorageHelper.setItem("sprig.pendingCount",B),await(await l.openDB()).add("pendingCaptures",{canUpload:!1,captureParams:s,sessionId:h,targetTimestamp:i,timestamp:Date.now(),uuid:o.v4()})},Nt=Object.freeze(Object.defineProperty({__proto__:null,RecordEvent:e=>{k("Sprig_TrackEvent",e)},RecordPageView:e=>{e.description&&(e.description=ge(e.description)),k("Sprig_PageView",e)},RecordSurveyShown:e=>{k("Sprig_ShowSurvey",e)},_completeSessionReplay:async({surveyId:e,responseGroupUuid:t,eventDigest:r,headers:n})=>{if(!e||!t)return!1;const a=window.UserLeap._API_URL,s=await Te({surveyId:e,responseGroupUuid:t,eventDigest:r,apiUrl:a,headers:n},!0);return!(s!=null&&s.error)},checkPendingHeatmapsUrl:()=>C()?o.breadcrumbsLogger.debug("ReplayDisabled-PendingHeatmaps"):b(async()=>{const e=(await l.getPendingCaptures({isHeatmap:!0})).map(t=>({eventId:t.captureParams.eventId,uuid:t.uuid})).filter(({eventId:t})=>!o.checkUrlStillMatching(t)).map(({uuid:t})=>t);return o.breadcrumbsLogger.info("PendingHeatmapsToComplete",{count:e.length}),e.length&&(await l.markPendingHeatmapsReady(e),o.breadcrumbsLogger.info("MarkedPendingHeatmapsReady")),e.length},"Error marking pending heatmaps ready"),clearUserReplayData:Ye,disableRecording:O,initializeReplay:async({maxReplayDurationSeconds:e,maxInflightRequests:t=2,replaySettings:r,teardownAfter:n=!1,apiUrl:a,alwaysOnConfig:s})=>{if(s&&St({apiUrl:a,config:s,triggerSnapshot:()=>{oe()}}),B=o.sessionStorageHelper.getItem("sprig.pendingCount"),g.isRecording)return;if(n&&o.sessionStorageHelper.setItem("sprig.teardownAfterCapture","true"),C())return o.breadcrumbsLogger.debug("ReplayDisabled");if(await(async()=>{var d;if(!Ae())return!0;if((d=window.navigator.storage)!=null&&d.estimate)try{const{quota:u=0,usage:w=0}=await window.navigator.storage.estimate(),p=(u-w)/1024**3;return o.breadcrumbsLogger.info("Storage",{availableGb:p}),p<.5}catch{return!0}return!1})())return o.breadcrumbsLogger.debug("IDBNotSupported"),se();try{const d=await l.openDB();o.breadcrumbsLogger.info("DBVersion",{version:d.version})}catch(d){return o.breadcrumbsLogger.error("ReplayOpenErr",{name:d.name}),d.name==="VersionError"&&l.deleteDB(),se()}b(async()=>{await le(!0)},"Error uploading ready pending captures");const i=H()?30:0,c=Math.max(e??0,i);if(!c)return o.breadcrumbsLogger.debug("MissingDuration");o.breadcrumbsLogger.debug("ReplayInit"),await b(async()=>{var d;r!=null&&r.minDuration&&(qe=r.minDuration),r!=null&&r.batchDuration&&(ie=r.batchDuration),d=t,Ce.setLimit(d),At(),xt(c+35,1800,c+35),Bt();const u=window.UserLeap.replayLibraryURL??"https://cdn.sprig.com/dependencies/record-2.0.0-alpha.17.min.js";if(!window.rrwebRecord){const{record:y}=await import(u);window.rrwebRecord=y}const w=window.rrwebRecord;if(!w)return o.breadcrumbsLogger.error("RecordScriptFailed");let p=!0,f=0;const m={checkoutEveryNms:3e4,sampling:{input:"last",scroll:250,media:800},...r};var D,T;g.stopRecording=w({emit:(y,I)=>{if(y.type===L.Custom&&(de=Date.now()),C()||K())return;if(I&&y.type===L.Meta)f=performance.now();else if(I&&f&&y.type===L.FullSnapshot){const E=performance.now()-f;o.reportAndRegister("sdk_replay_snapshot_seconds",E/1e3)}const v=p||!!I&&y.type===L.Meta;p=!1,kt(v,y),Ut({uuid:o.v4(),event:JSON.stringify(y),isValidStart:v,timestamp:Date.now()})},...m}),g.isRecording=!!g.stopRecording,g.isRecording&&(((y,I)=>{window.addEventListener("message",v=>{var E;v.data.type===ct&&(pe.push({source:v.source,origin:v.origin}),(E=v.source)==null||E.postMessage({type:ut,settings:y,replayLibraryUrl:I},{targetOrigin:v.origin}))})})(m,u),o.eventEmitter.on("survey.complete",y=>{var I;I={id:y,userAgent:window.navigator.userAgent},k("Sprig_SubmitSurvey",I)}),D=k,T=It,j||(S=D,V=T,window.addEventListener("click",xe,R),window.addEventListener("pointerdown",Me,R),window.addEventListener("mousedown",Be,R),window.addEventListener("keydown",Ue,R),window.addEventListener("scroll",Le,R),j=!0,ft(),ht()))},"Error initializing replay")},isReplayPaused:K,isReplayRecording:()=>g.isRecording,recordFullSnapshot:oe,recordReplayPaused:()=>{k("Sprig_ReplayPaused",{timestamp:Date.now()}),o.sessionStorageHelper.setItem("sprig.isReplayPaused","true")},recordReplayResumed:()=>{o.sessionStorageHelper.removeItem("sprig.isReplayPaused"),k("Sprig_ReplayResumed",{timestamp:Date.now()})},scheduleCapture:Ze,scheduleOrCaptureReplay:Xe,tryReplayAction:b,uploadReadyPendingCaptures:le},Symbol.toStringTag,{value:"Module"}));o.registerReplay(Nt);
|
|
1
|
+
"use strict";var et=Object.defineProperty;var tt=(e,t,n)=>t in e?et(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var N=(e,t,n)=>tt(e,typeof t!="symbol"?t+"":t,n);const o=require("./metricsReporter-DbEyJSwA.cjs");var L=(e=>(e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e))(L||{}),P=(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(P||{});const Z=(e,t)=>t.some(n=>e instanceof n);let ye,fe;const ee=new WeakMap,q=new WeakMap,$=new WeakMap;let te={get(e,t,n){if(e instanceof IDBTransaction){if(t==="done")return ee.get(e);if(t==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return x(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&(t==="done"||t==="store")||t in e};function Ee(e){te=e(te)}function nt(e){return(fe||(fe=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(ne(this),t),x(this.request)}:function(...t){return x(e.apply(ne(this),t))}}function rt(e){return typeof e=="function"?nt(e):(e instanceof IDBTransaction&&function(t){if(ee.has(t))return;const n=new Promise((r,a)=>{const s=()=>{a(t.error||new DOMException("AbortError","AbortError"))};t.oncomplete=()=>{r()},t.onerror=s,t.onabort=s});ee.set(t,n)}(e),Z(e,ye||(ye=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,te):e)}function x(e){if(e instanceof IDBRequest)return function(n){const r=new Promise((a,s)=>{n.onsuccess=()=>{a(x(n.result))},n.onerror=()=>{s(n.error)}});return $.set(r,n),r}(e);if(q.has(e))return q.get(e);const t=rt(e);return t!==e&&(q.set(e,t),$.set(t,e)),t}const ne=e=>$.get(e);function re(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&(n.onblocked=r=>t(r.oldVersion,r)),x(n).then(()=>{})}const at=["get","getKey","getAll","getAllKeys","count"],st=["put","add","delete","clear"],z=new Map;function he(e,t){if(!(e instanceof IDBDatabase)||t in e||typeof t!="string")return;if(z.get(t))return z.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,a=st.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!a&&!at.includes(n))return;const s=async function(i,...c){const d=this.transaction(i,a?"readwrite":"readonly");let u=d.store;return r&&(u=u.index(c.shift())),(await Promise.all([u[n](...c),a&&d.done]))[0]};return z.set(t,s),s}Ee(e=>({...e,get:(t,n,r)=>he(t,n)||e.get(t,n,r),has:(t,n)=>!!he(t,n)||e.has(t,n)}));const ot=["continue","continuePrimaryKey","advance"],Ie={},ae=new WeakMap,Re=new WeakMap,it={get(e,t){if(!ot.includes(t))return e[t];let n=Ie[t];return n||(n=Ie[t]=function(...r){ae.set(this,Re.get(this)[t](...r))}),n}};async function*dt(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,it);for(Re.set(n,t),$.set(n,ne(t));t;)yield n,t=await(ae.get(n)||t.continue()),ae.delete(n)}function ve(e,t){return t===Symbol.asyncIterator&&Z(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&Z(e,[IDBIndex,IDBObjectStore])}Ee(e=>({...e,get:(t,n,r)=>ve(t,n)?dt:e.get(t,n,r),has:(t,n)=>ve(t,n)||e.has(t,n)}));const ct="sprigReplayIframeLoaded",ut="sprigReplayIframeSettings",lt="sprigReplayIframeTakeFullSnapshot",pt="sprigReplayTeardown",pe=[],Ce=new class{constructor(e){N(this,"awaitingResolvers",[]);N(this,"activeCount",0);this.capacity=e}async acquire(){if(!(this.activeCount<this.capacity))return new Promise(e=>{this.awaitingResolvers.push(e)});this.activeCount++}release(){const e=this.awaitingResolvers.shift();e&&this.activeCount<=this.capacity?e():this.activeCount--}async execute(e){try{return await this.acquire(),await e()}finally{this.release()}}setLimit(e){this.capacity=e}}(2),Te=async({apiUrl:e,surveyId:t,uploadId:n,etags:r,headers:a,responseGroupUuid:s,replayDuration:i,eventDigest:c},d=!1)=>{var w;if(!d&&!n&&!r)return void o.breadcrumbsLogger.error("UploadErr",{isMobile:d,uploadId:n,etags:r});o.breadcrumbsLogger.info("MarkUploadComplete",{surveyId:t});const u=await o.sprigFetch(`${e}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:r,uploadId:n,responseGroupUuid:s,surveyId:t,replayDuration:i,eventDigest:c,userAgent:(w=window==null?void 0:window.navigator)==null?void 0:w.userAgent}),headers:a,shouldRetryRequest:!0});return o.breadcrumbsLogger.info("MarkUploadDone",{surveyId:t}),u},gt=e=>{if(e instanceof Attr)return null;let t=1;for(let n=e.previousSibling;n;n=n.previousSibling)n.nodeName===e.nodeName&&++t;return t},Pe=e=>{if(e===null)return"";const t=[];if(e instanceof Document)return"/";for(let n=e;n&&!(n instanceof Document)&&n!==null;n=n instanceof Attr?n.ownerElement:n.parentElement){const r=t[t.length]={name:void 0,position:null};switch(n.nodeType){case Node.TEXT_NODE:r.name="text()";break;case Node.ATTRIBUTE_NODE:r.name="@"+n.nodeName;break;case Node.PROCESSING_INSTRUCTION_NODE:r.name="processing-instruction()";break;case Node.COMMENT_NODE:r.name="comment()";break;case Node.ELEMENT_NODE:r.name=n.nodeName}r.position=gt(n)}return"/"+t.reverse().map(n=>n.position!==null?`/${n.name}[${n.position}]`:`/${n.name}`).join("")},ge=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),R={capture:!0,passive:!0},mt=["a","button","input","option","li","link"],wt=["Escape","Enter","Backspace","F5","Tab"];let j=!1,S=null,V=null;const be=e=>{var n;if(((n=e.tagName)==null?void 0:n.toLowerCase())==="html")return{element:"html"};const t={};return t.element=(r=>{if(!r.tagName)return"No tagName";const a=r.getAttribute("type");return a?`${a} ${r.tagName.toLowerCase()}`:r.tagName.toLowerCase()})(e),t},yt=e=>{var r;if(!e)return{};const t={...be(e)},n=e.parentElement;if(n&&mt.includes((r=n.tagName)==null?void 0:r.toLowerCase())){const a=be(n);Object.assign(t,a)}return t},ke=(e,t)=>{var a,s;let n=t.target;var r;t.target===((a=window.document)==null?void 0:a.body)&&window.Sprig.pointerDownTarget&&(n=window.Sprig.pointerDownTarget),r={x:t.x,y:t.y,type:e,elementAttributes:yt(n),windowHeight:window.innerHeight,windowWidth:window.innerWidth,...n instanceof HTMLElement||n instanceof SVGElement||n instanceof MathMLElement?{rect:n==null?void 0:n.getBoundingClientRect(),xPath:Pe(n)}:{}},(s=r==null?void 0:r.elementAttributes)!=null&&s.text&&(r.elementAttributes.text=ge(r.elementAttributes.text)),S==null||S("Sprig_Click",r)},Ue=e=>{var t;wt.includes(e.key)&&(t={key:e.key},S==null||S("Sprig_Keystroke",t))},ft=()=>{var e;window.performance.getEntriesByType("navigation").map(t=>t.type).includes("reload")&&(e={url:window.location.href,currentPageTitle:document.title},S==null||S("Sprig_Refresh",e))},ht=()=>{var e;window.performance.getEntriesByType("navigation").map(t=>t.type).includes("back_forward")&&((e={curUrl:window.location.href,fromUrl:document.referrer,currentPageTitle:document.title}).currentPageTitle&&(e.currentPageTitle=ge(e.currentPageTitle)),S==null||S("Sprig_BackForward",e))},Le=((e,t)=>{let n;return r=>{clearTimeout(n),n=window.setTimeout(()=>e(r),t)}})(e=>{if(!(e.target instanceof HTMLElement||e.target instanceof Document))return;let t=e.target;"scrollTop"in t||(t=t.documentElement),V==null||V({xPath:Pe(t),x:t.scrollLeft,y:t.scrollTop,elementAttributes:{targetScrollWidth:t.scrollWidth,targetClientWidth:t.clientWidth,targetScrollHeight:t.scrollHeight,targetClientHeight:t.clientHeight}})},750),xe=(Se="left_click",e=>ke(Se,e));var Se;const Be=e=>{e.button===2&&ke("right_click",e)},Me=e=>{window.Sprig&&(window.Sprig.pointerDownTarget=e.target)},g={isRecording:!1,scrollEventUuids:{},stopRecording:()=>{}},Ae=()=>window.indexedDB&&window.IDBKeyRange&&window.CompressionStream,h=(()=>{const e=o.sessionStorageHelper.getItem("sprig.sessionId");if(e)return o.breadcrumbsLogger.info("SessionIDFound",{savedSessionId:e}),o.sessionStorageHelper.removeItem("sprig.sessionId"),e;const t=o.v4();return o.breadcrumbsLogger.info("GeneratedSessionID",{uuid:t}),t})(),se=()=>{o.sessionStorageHelper.setItem("sprig.disableReplayRecording","disabled")},C=()=>!!o.sessionStorageHelper.getItem("sprig.disableReplayRecording"),K=()=>!!o.sessionStorageHelper.getItem("sprig.isReplayPaused");window.addEventListener("beforeunload",()=>{o.breadcrumbsLogger.info("BeforeUnload",{sessionId:h}),o.sessionStorageHelper.setItem("sprig.sessionId",h)});const k=(e,t)=>{var n,r;if(!C()&&g.isRecording&&!K())try{(r=(n=window.rrwebRecord)==null?void 0:n.addCustomEvent)==null||r.call(n,e,t)}catch(a){O("Error recording custom event",a)}},It=async e=>{const{x:t,xPath:n,y:r}=e,a=g.scrollEventUuids[n];if(a)return b(async()=>{var c,d,u,w;const s=await l.openDB(),i=await s.get("events",a);if(i!=null&&i.event){const p=JSON.parse(i.event),f=t>((d=(c=p.data)==null?void 0:c.payload)==null?void 0:d.x),m=r>((w=(u=p.data)==null?void 0:u.payload)==null?void 0:w.y);if(!f&&!m)return null;f&&(p.data.payload.x=t),m&&(p.data.payload.y=r),p.data.payload.elementAttributes=e.elementAttributes,i.event=JSON.stringify(p),await s.put("events",i)}else k("Sprig_Scroll",e)},"Error updating scroll event");k("Sprig_Scroll",e)},_e=()=>{g.stopRecording&&(g.stopRecording(),g.stopRecording=void 0),g.isRecording=!1,["cleanupInterval","inactivityInterval","pendingCheckInterval"].forEach(e=>{g[e]&&(clearInterval(g[e]),g[e]=void 0)}),j&&(window.removeEventListener("click",xe,R),window.removeEventListener("pointerdown",Me,R),window.removeEventListener("mousedown",Be,R),window.removeEventListener("keydown",Ue,R),window.removeEventListener("scroll",Le,R),j=!1),pe.forEach(e=>{var t;(t=e.source)==null||t.postMessage({type:pt},{targetOrigin:e.origin})})},vt=["did not allow mutations","called in an invalid security context"],bt=(e,t,{reportError:n=!0,extraInfo:r={}})=>{if(!C()&&t instanceof Error){if(se(),t.name==="VersionError")return o.breadcrumbsLogger.error("VersionErr",{message:e}),void l.deleteDB();(a=>{if(!a)return!0;for(const s of vt)if(a.toLowerCase().includes(s))return!1;return!0})(t==null?void 0:t.message)&&(n&&window.UserLeap.reportError(e,t,r),l.clearAll())}},O=(e,t,{reportError:n}={reportError:!0})=>{_e(),o.breadcrumbsLogger.error("ReplayErr",{code:t.code,name:t.name}),bt(e,t,{reportError:n})},b=async(e,t)=>{try{return await e()}catch(n){O(t,n)}},oe=()=>{g.isRecording&&(b(()=>{var e,t;return(t=(e=window.rrwebRecord)==null?void 0:e.takeFullSnapshot)==null?void 0:t.call(e,!0)},"Error recording full snapshot"),pe.forEach(e=>{var t;(t=e.source)==null||t.postMessage({type:lt},{targetOrigin:e.origin})}))};let Q=0;(async()=>Ae()&&Promise.allSettled([re("replayStorage"),re("sprig.replay")]))();const l=new class{constructor(){N(this,"wrapTransactionWithCounter",e=>{var r,a;const t=(a=(r=window.Sprig)==null?void 0:r._config)==null?void 0:a.outstandingTransactionLimit,n=t===void 0?100:t;if(n&&Q>n){const s="Too many outstanding transactions";O(s,new Error(s),{reportError:!1})}Q++,e.done.finally(()=>{Q--})});N(this,"getTransaction",async e=>{const t=(await this.openDB()).transaction(e,"readwrite");return this.wrapTransactionWithCounter(t),t})}openDB(){return function(e,t,{blocked:n,upgrade:r,blocking:a,terminated:s}={}){const i=indexedDB.open(e,t),c=x(i);return r&&(i.onupgradeneeded=d=>{r(x(i.result),d.oldVersion,d.newVersion,x(i.transaction),d)}),n&&(i.onblocked=d=>n(d.oldVersion,d.newVersion,d)),c.then(d=>{s&&(d.onclose=()=>s()),a&&(d.onversionchange=u=>a(u.oldVersion,u.newVersion,u))}).catch(()=>{}),c}("sprigReplay",1,{upgrade:(e,t,n)=>{if(n===0&&o.sessionStorageHelper.setItem("sprig.pendingCount","0"),!e.objectStoreNames.contains("events")){const r=e.createObjectStore("events",{keyPath:"uuid"});r.createIndex("sessionId","sessionId"),r.createIndex("timestamp","timestamp"),r.createIndex("[sessionId+timestamp]",["sessionId","timestamp"])}if(!e.objectStoreNames.contains("chunkUploads")){const r=e.createObjectStore("chunkUploads",{keyPath:"uuid"});r.createIndex("sessionId","sessionId"),r.createIndex("timestamp","timestamp"),r.createIndex("[sessionId+status]",["sessionId","status"]),r.createIndex("[uploadId+status]",["uploadId","status"]),r.createIndex("[sessionId+status+uploadId]",["sessionId","status","uploadId"])}if(!e.objectStoreNames.contains("pendingCaptures")){const r=e.createObjectStore("pendingCaptures",{keyPath:"uuid"});r.createIndex("sessionId","sessionId"),r.createIndex("timestamp","timestamp"),r.createIndex("[sessionId+targetTimestamp]",["sessionId","targetTimestamp"])}}})}async deleteDB(){try{await re("sprigReplay")}catch{}}async bulkAdd(e,t){const n=await this.getTransaction(e);return Promise.all([...t.map(r=>n.store.add(r)),n.done])}async clearAll(){const e=(await this.openDB()).transaction(["events","chunkUploads","pendingCaptures"],"readwrite");return this.wrapTransactionWithCounter(e),Promise.all([e.objectStore("events").clear(),e.objectStore("chunkUploads").clear(),e.objectStore("pendingCaptures").clear()])}async deleteBySessionId(e,t){const n=IDBKeyRange.only(t),r=await this.getTransaction(e),a=r.store.index("sessionId");for await(const s of a.iterate(n))await s.delete();await r.done}async updatePartial(e,t,n){const r=await this.getTransaction(e),a=await r.store.get(t);a&&await r.store.put({...a,...n}),await r.done}async deleteRowsBefore(e,t,n=()=>!0){const r=IDBKeyRange.upperBound(t,!0),a=await this.getTransaction(e),s=a.store.index("timestamp");for await(const i of s.iterate(r))n(i.value)&&await i.delete();await a.done}async getEventsBetween(e,t=Date.now()){if(e>=t)return Promise.resolve([]);const n=IDBKeyRange.bound([h,e],[h,t],!1,!0);return(await this.openDB()).getAllFromIndex("events","[sessionId+timestamp]",n)}async updateEventsExpiredAt(e,t,n=30){const r=new Date,a=r.setMinutes(r.getMinutes()+(n??30)),s=await this.getTransaction("events"),i=s.store.index("[sessionId+timestamp]"),c=IDBKeyRange.bound([h,e],[h,t],!1,!0);for await(const d of i.iterate(c))await d.update({...d.value,expiredAt:a});await s.done}async deleteChunkUploads(e,t){const n=IDBKeyRange.only([t,e]),r=await this.getTransaction("chunkUploads");let s=await r.store.index("[uploadId+status]").openCursor(n);for(;s;)s.delete(),s=await s.continue();await r.done}async getChunkUploadsByStatus({sessionId:e,status:t,uploadId:n}){const r=(await this.openDB()).transaction("chunkUploads","readonly");this.wrapTransactionWithCounter(r);const a=n?r.store.index("[uploadId+status]"):r.store.index("[sessionId+status]"),s=n?IDBKeyRange.only([n,t]):IDBKeyRange.only([e,t]);return a.getAll(s)}async getPendingCaptures(e={}){return(await(await this.openDB()).getAllFromIndex("pendingCaptures","sessionId",h)).filter(n=>!e.beforePresent||n.targetTimestamp<Date.now()).filter(n=>!e.isBeforeType||n.captureParams.replayParams.replayDurationType==="before").filter(n=>!e.isHeatmap||(n.captureParams.isHeatmap??!1))}async markPendingCaptureToCanUpload(e){const t=await this.getTransaction("pendingCaptures"),n=t.store.index("sessionId");for await(const r of n.iterate(h)){const a=r.value;a.captureParams.responseGroupId===e&&await r.update({...a,canUpload:!0})}await t.done}async markPendingHeatmapsReady(e){if(parseInt(o.sessionStorageHelper.getItem("sprig.pendingCount")??"0")===0)return null;const t=Date.now(),n=await this.getTransaction("pendingCaptures"),r=n.store.index("sessionId");for await(const a of r.iterate(h)){const s=a.value;!s.captureParams.isHeatmap||e&&!e.includes(s.uuid)||await a.update({...s,targetTimestamp:t,captureParams:{...s.captureParams,triggerTimestamp:t,replayParams:{...s.captureParams.replayParams,replayDurationSeconds:Math.floor((t-s.timestamp)/1e3)}}})}await n.done}},U=[];let F,He,J,Ne,G,Oe,M=[],_=!1,A=0,W=!1,Fe=!1,me=[],X=!1;const H=()=>W&&!_&&Date.now()<=J,St=({apiUrl:e,config:t,triggerSnapshot:n,forceInit:r=!1})=>{W&&!r||(o.sessionStorageHelper.isStorageAvailable?(M=[],me.splice(0),U.splice(0),A=0,G=n,He=e,F={responseGroupUuid:t.responseGroupUuid,surveyId:t.surveyId,userAgent:t.userAgent,sdkVersion:t.sdkVersion},Ne=t.maxDurationSeconds,Ct(),W||(Oe=window.setInterval(Rt,500)),W=!0):_=!0)},Dt=[P.Drag,P.Input,P.MediaInteraction,P.MouseInteraction,P.MouseMove,P.Scroll,P.Selection,P.TouchMove],Et=e=>e.type===L.Custom||e.type===L.IncrementalSnapshot&&Dt.includes(e.data.source),we=e=>e.some(Et),Rt=async()=>{if(!H())return void window.clearInterval(Oe);if(Ve(),!we(U))return;const e=U[0].timestamp;Date.now()-e>35e3&&(G==null||G())},Ve=async()=>{if(M.length||X)return;X=!0;const e=await Pt();if(!e)return void(_=!0);me.splice(0,e.length).forEach(t=>t(e.shift())),e.forEach(t=>M.push(t)),X=!1},Ct=()=>{const e=o.sessionStorageHelper.getItem("sprig.alwayson.info");if(e){o.breadcrumbsLogger.info("Read stored session state",e);const t=JSON.parse(e);_=t.disabled,F=t.metadata,M=t.uploadUrls,A=t.currentIndex,J=t.expirationTimestamp,t.pendingEventTimestamp&&(o.breadcrumbsLogger.info(`Uploading with pending timestamp: ${t.pendingEventTimestamp}`),Tt(t.pendingEventTimestamp))}else J=1e3*Ne+Date.now()},Tt=async e=>{const t=Date.now(),n=(await l.getEventsBetween(e,t)).map(a=>JSON.parse(a.event));if(!we(n))return;je(n);const r=await $e();r&&await We(r,n)},Ge=async(e,t)=>{try{const n=await e();if(!n.ok)throw new Error(`Error ${t}`);return n}catch{_=!0}},We=async(e,t)=>{if(!H()||!e)return;const n=await(async r=>{const a=new TextEncoder,s=new CompressionStream("gzip"),i=s.writable.getWriter(),c=a.encode(JSON.stringify(r));return i.write(c),i.close(),new Uint8Array(await new Response(s.readable).arrayBuffer())})(t);o.breadcrumbsLogger.info("Uploading always-on events with presigned url"),await Ge(()=>o.sprigFetch(e,{body:n,method:"PUT"}),"uploading always-on with presigned url")},Pt=async()=>{if(!H())return;const{surveyId:e,responseGroupUuid:t}=F,n={responseGroupUuid:t,surveyId:e,index:A+1};o.breadcrumbsLogger.info("Fetching always-on upload urls",n);const r=await Ge(()=>o.sprigFetch(`${He}/sdk/1/replayUrls`,{method:"POST",body:JSON.stringify(n),headers:o.getHttpHeaders(window.UserLeap)}),"fetching always-on signed urls");if(!r)return;const a=r.json.signedUrls;return o.breadcrumbsLogger.info("Fetched more always-on upload urls",{body:n,urls:a}),a},$e=async()=>{if(M.length)return M.shift();const e=new Promise(t=>{me.push(t)});return Ve(),e},je=e=>{var a,s,i;const t=e.length?e[e.length-1].timestamp:Date.now(),n=A,r=((s=(a=window.UserLeap)==null?void 0:a.config)==null?void 0:s.customMetadata)??((i=window.__cfg)==null?void 0:i.customMetadata);A++,e.push({timestamp:t,type:L.Custom,data:{tag:"Sprig_Meta",payload:{...F,index:n,visitorId:window.UserLeap.visitorId??"",timestamp:t,customMetadata:r}}})},kt=(e,t)=>{H()&&!Fe&&(e||U.length)&&(e&&U.length&&(async()=>{const n=U.splice(0);if(!we(n))return;o.breadcrumbsLogger.info("Capturing always-on event array to upload"),je(n);const r=await $e();r&&await We(r,n)})(),U.push(t))};window.addEventListener("beforeunload",async()=>{Fe=!0,H()&&(o.breadcrumbsLogger.info("Always On handle page unload"),(()=>{let e;U.length&&(e=U[0].timestamp);const t={disabled:_,metadata:F,uploadUrls:M,currentIndex:A,pendingEventTimestamp:e,expirationTimestamp:J};o.breadcrumbsLogger.info("Storing session state on unload",t),o.sessionStorageHelper.setItem("sprig.alwayson.info",JSON.stringify(t))})())});const Ke=async(e,t)=>{const n=performance.now();let r;try{r=await e()}finally{const a=performance.now()-n;let s=o.PerformanceMetrics[t];s||(s=o.registerMetric(t)),s.report(a/1e3)}return r},Je=(e,t)=>{const n=performance.now();try{e()}finally{const r=performance.now()-n;let a=o.PerformanceMetrics[t];a||(a=o.registerMetric(t)),a.report(r/1e3)}};let qe=5e3,ie=6e4,de=0,B,ce=!1,ue=[];const Ut=e=>{var t,n,r,a;if((t=e.event)!=null&&t.includes("Sprig_Scroll")){const s=(a=(r=(n=JSON.parse(e.event))==null?void 0:n.data)==null?void 0:r.payload)==null?void 0:a.xPath;if(!s)return;g.scrollEventUuids[s]=e.uuid}ue.push(e),ce||Lt()},Lt=()=>{ce=!0,setTimeout(async()=>{if(C()||K())return;const e=ue;ue=[],ce=!1,Je(async()=>{await(async t=>{const n=t.map(r=>({...r,sessionId:r.sessionId??h}));if(n.length!==0)return b(()=>l.bulkAdd("events",n),"Error storing replay events")})(e)},"sdk_replay_add_event_batch_seconds")},500)},xt=(e,t,n)=>{g.cleanupInterval=window.setInterval(()=>{const r=Date.now();Ke(()=>b(async()=>{C()||await Promise.all([l.deleteRowsBefore("events",r-1e3*e,a=>a.expiredAt===void 0||a.expiredAt<r-1e3*e),l.deleteRowsBefore("chunkUploads",r-1e3*t),l.deleteRowsBefore("pendingCaptures",r-1e3*n,a=>!a.canUpload)])},"Error deleting table rows"),"sdk_replay_cleanup_seconds"),o.breadcrumbsLogger.debug("CleanupComplete")},3e4)},Bt=()=>{g.pendingCheckInterval=window.setInterval(async()=>{b(async()=>{await le()},"Error initiating pending captures")},5e3)};let Y=!1;const le=async(e=!1)=>{if(!Y)try{Y=!0;const t=parseInt(B??"0");if(t===0)return;const n=await l.getPendingCaptures({beforePresent:!0,isBeforeType:e}),r=await l.openDB();await Promise.all(n.map(async a=>(await r.delete("pendingCaptures",a.uuid),Xe(a.captureParams,a.canUpload)))),B=(t-n.length).toString(),o.sessionStorageHelper.setItem("sprig.pendingCount",B)}finally{Y=!1}},Mt=async(e,t,n,r,a)=>{const s=Math.min(e+a,n),i=await Ke(()=>l.getEventsBetween(e,s),"sdk_replay_get_events_between_seconds");if(!(i!=null&&i.length))return o.breadcrumbsLogger.debug("NoEventsFound"),{validStartFound:r,events:[]};if(!r){o.breadcrumbsLogger.debug("ValidStartSearch");let c=-1;return i==null||i.forEach((d,u)=>{if(!d.isValidStart)return;const w=d.timestamp<=t;(c<0||w)&&(c=u)}),c<0?(o.breadcrumbsLogger.debug("ValidStartNotFound"),{validStartFound:r,events:[]}):{validStartFound:!0,events:i==null?void 0:i.slice(c)}}return{validStartFound:r,events:i}},ze=e=>Promise.all(e.map(async t=>{const n=await(async r=>Ce.execute(async()=>{var i;o.breadcrumbsLogger.info("UploadChunkStart",{chunkIndex:r.chunkIndex,surveyId:r.surveyId});const a=await o.sprigFetch(r.uploadUrl,{body:r.data,method:"PUT"});o.breadcrumbsLogger.http("UploadChunkEnd",{url:r.uploadUrl,method:"PUT",status_code:a.status,reason:a.statusText??"OK",chunkIndex:r.chunkIndex,surveyId:r.surveyId});const s=(i=a.headers)==null?void 0:i.get("ETag");if(!s)throw new Error(`Upload response did not include etag for upload ${r.uploadId}, part ${r.chunkIndex}`);return s}))(t);return await l.updatePartial("chunkUploads",t.uuid,{data:null,etag:n,status:"UploadComplete"}),t.uploadId})),Qe=async e=>{const t=await l.getChunkUploadsByStatus({status:"UploadComplete",uploadId:e});if(!(t!=null&&t.length))return void o.breadcrumbsLogger.info("NoChunksForUpload",{uploadId:e});const n=t.reduce((s,i)=>(s.find(c=>c.chunkIndex===i.chunkIndex)||s.push(i),s),[]);n.sort((s,i)=>s.chunkIndex-i.chunkIndex);const r=n.map(s=>({ETag:s.etag,PartNumber:s.chunkIndex})).filter(s=>s.ETag!==null),a=n[0];await Te({apiUrl:a.apiUrl,surveyId:a.surveyId,uploadId:e,responseGroupUuid:a.responseGroupId,etags:r,headers:a.completeUploadHeaders,replayDuration:a.replayDuration}),await l.deleteChunkUploads("UploadComplete",e)},At=()=>{b(async()=>{const e=await l.getChunkUploadsByStatus({sessionId:h,status:"ReadyForUpload"});if(!(e!=null&&e.length))return;const t=await ze(e);t!=null&&t.length&&await Promise.all(t.map(n=>{if(n)return Qe(n)}))},"Error uploading unfinished chunks")},_t=async(e,t)=>{const n=t??Date.now();return(async(r,a)=>{const s=new TextEncoder;let i=null;const c=new CompressionStream("gzip"),d=c.writable.getWriter();let u=!1,w=!1,[p,f]=[0,0],m=[];for(let T=r-35e3;T<a;T+=ie){if({validStartFound:w,events:m}=await Mt(T,r,a,w,ie),!(m!=null&&m.length)){o.breadcrumbsLogger.debug("NoEventsFound");continue}p===0&&(p=m[0].timestamp),f=m[m.length-1].timestamp;const y=m.map(E=>E.event);y.push(`{"timestamp":${a}}`);const I=`${u?",":"["}${y}`,v=s.encode(I);Je(()=>{d.write(v)},"sdk_replay_compression_seconds"),u=!0}if(f-p<qe)return o.breadcrumbsLogger.debug("ReplayTooShort"),null;const D=s.encode("]");return d.write(D),d.close(),i=new Uint8Array(await new Response(c.readable).arrayBuffer()),i})(n-e,n)},De=async e=>{const{surveyId:t,responseGroupId:n,visitorId:r,apiUrl:a,completeUploadHeaders:s,replayParams:i,triggerTimestamp:c}=e,d=await _t(1e3*i.replayDurationSeconds,c);if(!(d!=null&&d.length))return void o.breadcrumbsLogger.info("FileDataEmpty",{surveyId:t});const u=((p,f,m)=>{const D=p.length,T=1024*f*1024,y=Math.ceil(D/m),I=Math.max(T,y),v=[];let E=0;for(;E<D;)v.push(p.slice(E,E+I)),E+=I;return v})(d,i.minimumChunkSizeMb,i.signedUrls.length),w=await Promise.all(u.map(async(p,f)=>{const m=o.v4(),D={apiUrl:a,chunkIndex:f+1,completeUploadHeaders:s,etag:null,responseGroupId:n,status:"ReadyForUpload",surveyId:t,timestamp:c,totalChunks:u.length,data:p,uploadId:i.uploadId,uploadUrl:i.signedUrls[f].url,uuid:m,visitorId:r};return await(await l.openDB()).add("chunkUploads",{...D,sessionId:D.sessionId??h}),D}));await(async(p,f)=>{await ze(f),await Promise.all(p.map(m=>Qe(m)))})([i.uploadId],w)},Xe=async(e,t)=>{if(C())return o.breadcrumbsLogger.debug("ReplayDisabled-ScheduleOrCapture");const{isHeatmap:n,isStandalone:r,replayParams:a,triggerTimestamp:s,responseGroupId:i}=e,c=async()=>{setTimeout(()=>o.eventEmitter.removeListener(o.SprigEvent.QuestionAnswered,c),0),b(async()=>{a.replayDurationType==="before"?await De(e):await l.markPendingCaptureToCanUpload(i)},"Error in schedule/capture callback")};b(async()=>{if(a.replayDurationType==="after"||a.replayDurationType==="beforeAndAfter")return!r&&!n&&o.eventEmitter.on(o.SprigEvent.QuestionAnswered,c),void await Ze(e);if(r||n||t)await De(e),n&&Ht();else{const d=35+a.replayDurationSeconds,u=s-1e3*d,w=s;await l.updateEventsExpiredAt(u,w,a.expirationTimeLimitMinutes),o.eventEmitter.on(o.SprigEvent.QuestionAnswered,c)}},"Error in scheduling/capturing replay")},Ht=async()=>{parseInt(B??"0")||o.sessionStorageHelper.removeItem("sprig.isCapturingHeatmap"),o.sessionStorageHelper.getItem("sprig.teardownAfterCapture")&&(_e(),Ye(),o.sessionStorageHelper.removeItem("sprig.teardownAfterCapture"))},Ye=async()=>C()?o.breadcrumbsLogger.debug("ReplayDisabled-ClearData"):Promise.all([l.deleteBySessionId("events",h),l.deleteBySessionId("pendingCaptures",h)]).catch(e=>{O("Error clearing user replay data",e)}),Ze=async e=>{if(C())return;const{isHeatmap:t,surveyId:n}=e,r=await l.getPendingCaptures(),a=r==null?void 0:r.filter(d=>d.captureParams.surveyId===n);if(a!=null&&a.length)return void o.breadcrumbsLogger.info("PendingCaptureExists",{surveyId:n});t&&(oe(),o.sessionStorageHelper.setItem("sprig.isCapturingHeatmap","true"),de=Date.now(),g.inactivityInterval||(g.inactivityInterval=window.setInterval(()=>{var d;d=de,Date.now()-d>=3e4&&b(()=>l.markPendingHeatmapsReady(),"Error in heatmap inactivity")},1e3)));const s={...e,replayParams:{...e.replayParams}};e.replayParams.replayDurationType==="beforeAndAfter"&&(s.replayParams.replayDurationSeconds*=2),s.replayParams.replayDurationType="before";const i=e.triggerTimestamp+1e3*e.replayParams.replayDurationSeconds;s.triggerTimestamp=i,B=(parseInt(B??"0")+1).toString(),o.sessionStorageHelper.setItem("sprig.pendingCount",B),await(await l.openDB()).add("pendingCaptures",{canUpload:!1,captureParams:s,sessionId:h,targetTimestamp:i,timestamp:Date.now(),uuid:o.v4()})},Nt=Object.freeze(Object.defineProperty({__proto__:null,RecordEvent:e=>{k("Sprig_TrackEvent",e)},RecordPageView:e=>{e.description&&(e.description=ge(e.description)),k("Sprig_PageView",e)},RecordSurveyShown:e=>{k("Sprig_ShowSurvey",e)},_completeSessionReplay:async({surveyId:e,responseGroupUuid:t,eventDigest:n,headers:r})=>{if(!e||!t)return!1;const a=window.UserLeap._API_URL,s=await Te({surveyId:e,responseGroupUuid:t,eventDigest:n,apiUrl:a,headers:r},!0);return!(s!=null&&s.error)},checkPendingHeatmapsUrl:()=>C()?o.breadcrumbsLogger.debug("ReplayDisabled-PendingHeatmaps"):b(async()=>{const e=(await l.getPendingCaptures({isHeatmap:!0})).map(t=>({eventId:t.captureParams.eventId,uuid:t.uuid})).filter(({eventId:t})=>!o.checkUrlStillMatching(t)).map(({uuid:t})=>t);return o.breadcrumbsLogger.info("PendingHeatmapsToComplete",{count:e.length}),e.length&&(await l.markPendingHeatmapsReady(e),o.breadcrumbsLogger.info("MarkedPendingHeatmapsReady")),e.length},"Error marking pending heatmaps ready"),clearUserReplayData:Ye,disableRecording:O,initializeReplay:async({maxReplayDurationSeconds:e,maxInflightRequests:t=2,replaySettings:n,teardownAfter:r=!1,apiUrl:a,alwaysOnConfig:s})=>{if(s&&St({apiUrl:a,config:s,triggerSnapshot:()=>{oe()}}),B=o.sessionStorageHelper.getItem("sprig.pendingCount"),g.isRecording)return;if(r&&o.sessionStorageHelper.setItem("sprig.teardownAfterCapture","true"),C())return o.breadcrumbsLogger.debug("ReplayDisabled");if(await(async()=>{var d;if(!Ae())return!0;if((d=window.navigator.storage)!=null&&d.estimate)try{const{quota:u=0,usage:w=0}=await window.navigator.storage.estimate(),p=(u-w)/1024**3;return o.breadcrumbsLogger.info("Storage",{availableGb:p}),p<.5}catch{return!0}return!1})())return o.breadcrumbsLogger.debug("IDBNotSupported"),se();try{const d=await l.openDB();o.breadcrumbsLogger.info("DBVersion",{version:d.version})}catch(d){return o.breadcrumbsLogger.error("ReplayOpenErr",{name:d.name}),d.name==="VersionError"&&l.deleteDB(),se()}b(async()=>{await le(!0)},"Error uploading ready pending captures");const i=H()?30:0,c=Math.max(e??0,i);if(!c)return o.breadcrumbsLogger.debug("MissingDuration");o.breadcrumbsLogger.debug("ReplayInit"),await b(async()=>{var d;n!=null&&n.minDuration&&(qe=n.minDuration),n!=null&&n.batchDuration&&(ie=n.batchDuration),d=t,Ce.setLimit(d),At(),xt(c+35,1800,c+35),Bt();const u=window.UserLeap.replayLibraryURL??"https://cdn.sprig.com/dependencies/record-2.0.0-alpha.17.min.js";if(!window.rrwebRecord){const{record:y}=await import(u);window.rrwebRecord=y}const w=window.rrwebRecord;if(!w)return o.breadcrumbsLogger.error("RecordScriptFailed");let p=!0,f=0;const m={checkoutEveryNms:3e4,sampling:{input:"last",scroll:250,media:800},...n};var D,T;g.stopRecording=w({emit:(y,I)=>{if(y.type===L.Custom&&(de=Date.now()),C()||K())return;if(I&&y.type===L.Meta)f=performance.now();else if(I&&f&&y.type===L.FullSnapshot){const E=performance.now()-f;o.reportAndRegister("sdk_replay_snapshot_seconds",E/1e3)}const v=p||!!I&&y.type===L.Meta;p=!1,kt(v,y),Ut({uuid:o.v4(),event:JSON.stringify(y),isValidStart:v,timestamp:Date.now()})},...m}),g.isRecording=!!g.stopRecording,g.isRecording&&(((y,I)=>{window.addEventListener("message",v=>{var E;v.data.type===ct&&(pe.push({source:v.source,origin:v.origin}),(E=v.source)==null||E.postMessage({type:ut,settings:y,replayLibraryUrl:I},{targetOrigin:v.origin}))})})(m,u),o.eventEmitter.on("survey.complete",y=>{var I;I={id:y,userAgent:window.navigator.userAgent},k("Sprig_SubmitSurvey",I)}),D=k,T=It,j||(S=D,V=T,window.addEventListener("click",xe,R),window.addEventListener("pointerdown",Me,R),window.addEventListener("mousedown",Be,R),window.addEventListener("keydown",Ue,R),window.addEventListener("scroll",Le,R),j=!0,ft(),ht()))},"Error initializing replay")},isReplayPaused:K,isReplayRecording:()=>g.isRecording,recordFullSnapshot:oe,recordReplayPaused:()=>{k("Sprig_ReplayPaused",{timestamp:Date.now()}),o.sessionStorageHelper.setItem("sprig.isReplayPaused","true")},recordReplayResumed:()=>{o.sessionStorageHelper.removeItem("sprig.isReplayPaused"),k("Sprig_ReplayResumed",{timestamp:Date.now()})},scheduleCapture:Ze,scheduleOrCaptureReplay:Xe,tryReplayAction:b,uploadReadyPendingCaptures:le},Symbol.toStringTag,{value:"Module"}));o.registerReplay(Nt);
|
package/dist/replay.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var it = Object.defineProperty;
|
|
2
2
|
var dt = (e, t, n) => t in e ? it(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
|
|
3
3
|
var F = (e, t, n) => dt(e, typeof t != "symbol" ? t + "" : t, n);
|
|
4
|
-
import { b as d, s as Q, a as m, v as X, c as ct, g as
|
|
4
|
+
import { b as d, s as Q, a as m, v as X, c as ct, g as lt, P as ke, r as Ue, d as ut, e as V, S as Z, f as pt } from "./metricsReporter-M_tu1Yrx.js";
|
|
5
5
|
var B = ((e) => (e[e.DomContentLoaded = 0] = "DomContentLoaded", e[e.Load = 1] = "Load", e[e.FullSnapshot = 2] = "FullSnapshot", e[e.IncrementalSnapshot = 3] = "IncrementalSnapshot", e[e.Meta = 4] = "Meta", e[e.Custom = 5] = "Custom", e[e.Plugin = 6] = "Plugin", e))(B || {}), k = ((e) => (e[e.Mutation = 0] = "Mutation", e[e.MouseMove = 1] = "MouseMove", e[e.MouseInteraction = 2] = "MouseInteraction", e[e.Scroll = 3] = "Scroll", e[e.ViewportResize = 4] = "ViewportResize", e[e.Input = 5] = "Input", e[e.TouchMove = 6] = "TouchMove", e[e.MediaInteraction = 7] = "MediaInteraction", e[e.StyleSheetRule = 8] = "StyleSheetRule", e[e.CanvasMutation = 9] = "CanvasMutation", e[e.Font = 10] = "Font", e[e.Log = 11] = "Log", e[e.Drag = 12] = "Drag", e[e.StyleDeclaration = 13] = "StyleDeclaration", e[e.Selection = 14] = "Selection", e[e.AdoptedStyleSheet = 15] = "AdoptedStyleSheet", e[e.CustomElement = 16] = "CustomElement", e))(k || {});
|
|
6
6
|
const re = (e, t) => t.some((n) => e instanceof n);
|
|
7
7
|
let Se, De;
|
|
@@ -66,8 +66,8 @@ function be(e, t) {
|
|
|
66
66
|
if (!(n in (a ? IDBIndex : IDBObjectStore).prototype) || !r && !wt.includes(n)) return;
|
|
67
67
|
const o = async function(s, ...c) {
|
|
68
68
|
const i = this.transaction(s, r ? "readwrite" : "readonly");
|
|
69
|
-
let
|
|
70
|
-
return a && (
|
|
69
|
+
let l = i.store;
|
|
70
|
+
return a && (l = l.index(c.shift())), (await Promise.all([l[n](...c), r && i.done]))[0];
|
|
71
71
|
};
|
|
72
72
|
return ee.set(t, o), o;
|
|
73
73
|
}
|
|
@@ -119,8 +119,8 @@ const vt = "sprigReplayIframeLoaded", St = "sprigReplayIframeSettings", Dt = "sp
|
|
|
119
119
|
var y;
|
|
120
120
|
if (!i && !n && !a) return void d.error("UploadErr", { isMobile: i, uploadId: n, etags: a });
|
|
121
121
|
d.info("MarkUploadComplete", { surveyId: t });
|
|
122
|
-
const
|
|
123
|
-
return d.info("MarkUploadDone", { surveyId: t }),
|
|
122
|
+
const l = await Q(`${e}/sdk/1/completeSessionReplay`, { method: "POST", body: JSON.stringify({ etags: a, uploadId: n, responseGroupUuid: o, surveyId: t, replayDuration: s, eventDigest: c, userAgent: (y = window == null ? void 0 : window.navigator) == null ? void 0 : y.userAgent }), headers: r, shouldRetryRequest: !0 });
|
|
123
|
+
return d.info("MarkUploadDone", { surveyId: t }), l;
|
|
124
124
|
}, Et = (e) => {
|
|
125
125
|
if (e instanceof Attr) return null;
|
|
126
126
|
let t = 1;
|
|
@@ -175,7 +175,7 @@ const Ce = (e) => {
|
|
|
175
175
|
var r, o;
|
|
176
176
|
let n = t.target;
|
|
177
177
|
var a;
|
|
178
|
-
t.target === ((r = window.document) == null ? void 0 : r.body) && window.Sprig.pointerDownTarget && (n = window.Sprig.pointerDownTarget), a = { x: t.x, y: t.y, type: e, elementAttributes: Tt(n), windowHeight: window.innerHeight, windowWidth: window.innerWidth, ...n instanceof HTMLElement ? { rect: n == null ? void 0 : n.getBoundingClientRect(), xPath: Ae(n) } : {} }, (o = a == null ? void 0 : a.elementAttributes) != null && o.text && (a.elementAttributes.text = he(a.elementAttributes.text)), b == null || b("Sprig_Click", a);
|
|
178
|
+
t.target === ((r = window.document) == null ? void 0 : r.body) && window.Sprig.pointerDownTarget && (n = window.Sprig.pointerDownTarget), a = { x: t.x, y: t.y, type: e, elementAttributes: Tt(n), windowHeight: window.innerHeight, windowWidth: window.innerWidth, ...n instanceof HTMLElement || n instanceof SVGElement || n instanceof MathMLElement ? { rect: n == null ? void 0 : n.getBoundingClientRect(), xPath: Ae(n) } : {} }, (o = a == null ? void 0 : a.elementAttributes) != null && o.text && (a.elementAttributes.text = he(a.elementAttributes.text)), b == null || b("Sprig_Click", a);
|
|
179
179
|
}, Le = (e) => {
|
|
180
180
|
var t;
|
|
181
181
|
Ct.includes(e.key) && (t = { key: e.key }, b == null || b("Sprig_Keystroke", t));
|
|
@@ -206,7 +206,7 @@ const He = (e) => {
|
|
|
206
206
|
if (e) return d.info("SessionIDFound", { savedSessionId: e }), m.removeItem("sprig.sessionId"), e;
|
|
207
207
|
const t = X();
|
|
208
208
|
return d.info("GeneratedSessionID", { uuid: t }), t;
|
|
209
|
-
})(),
|
|
209
|
+
})(), le = () => {
|
|
210
210
|
m.setItem("sprig.disableReplayRecording", "disabled");
|
|
211
211
|
}, T = () => !!m.getItem("sprig.disableReplayRecording"), z = () => !!m.getItem("sprig.isReplayPaused");
|
|
212
212
|
window.addEventListener("beforeunload", () => {
|
|
@@ -222,10 +222,10 @@ const U = (e, t) => {
|
|
|
222
222
|
}, Ut = async (e) => {
|
|
223
223
|
const { x: t, xPath: n, y: a } = e, r = g.scrollEventUuids[n];
|
|
224
224
|
if (r) return D(async () => {
|
|
225
|
-
var c, i,
|
|
226
|
-
const o = await
|
|
225
|
+
var c, i, l, y;
|
|
226
|
+
const o = await u.openDB(), s = await o.get("events", r);
|
|
227
227
|
if (s != null && s.event) {
|
|
228
|
-
const p = JSON.parse(s.event), h = t > ((i = (c = p.data) == null ? void 0 : c.payload) == null ? void 0 : i.x), w = a > ((y = (
|
|
228
|
+
const p = JSON.parse(s.event), h = t > ((i = (c = p.data) == null ? void 0 : c.payload) == null ? void 0 : i.x), w = a > ((y = (l = p.data) == null ? void 0 : l.payload) == null ? void 0 : y.y);
|
|
229
229
|
if (!h && !w) return null;
|
|
230
230
|
h && (p.data.payload.x = t), w && (p.data.payload.y = a), p.data.payload.elementAttributes = e.elementAttributes, s.event = JSON.stringify(p), await o.put("events", s);
|
|
231
231
|
} else U("Sprig_Scroll", e);
|
|
@@ -240,12 +240,12 @@ const U = (e, t) => {
|
|
|
240
240
|
});
|
|
241
241
|
}, xt = ["did not allow mutations", "called in an invalid security context"], Bt = (e, t, { reportError: n = !0, extraInfo: a = {} }) => {
|
|
242
242
|
if (!T() && t instanceof Error) {
|
|
243
|
-
if (
|
|
243
|
+
if (le(), t.name === "VersionError") return d.error("VersionErr", { message: e }), void u.deleteDB();
|
|
244
244
|
((r) => {
|
|
245
245
|
if (!r) return !0;
|
|
246
246
|
for (const o of xt) if (r.toLowerCase().includes(o)) return !1;
|
|
247
247
|
return !0;
|
|
248
|
-
})(t == null ? void 0 : t.message) && (n && window.UserLeap.reportError(e, t, a),
|
|
248
|
+
})(t == null ? void 0 : t.message) && (n && window.UserLeap.reportError(e, t, a), u.clearAll());
|
|
249
249
|
}
|
|
250
250
|
}, H = (e, t, { reportError: n } = { reportError: !0 }) => {
|
|
251
251
|
Ge(), d.error("ReplayErr", { code: t.code, name: t.name }), Bt(e, t, { reportError: n });
|
|
@@ -255,7 +255,7 @@ const U = (e, t) => {
|
|
|
255
255
|
} catch (n) {
|
|
256
256
|
H(t, n);
|
|
257
257
|
}
|
|
258
|
-
},
|
|
258
|
+
}, ue = () => {
|
|
259
259
|
g.isRecording && (D(() => {
|
|
260
260
|
var e, t;
|
|
261
261
|
return (t = (e = window.rrwebRecord) == null ? void 0 : e.takeFullSnapshot) == null ? void 0 : t.call(e, !0);
|
|
@@ -266,7 +266,7 @@ const U = (e, t) => {
|
|
|
266
266
|
};
|
|
267
267
|
let te = 0;
|
|
268
268
|
(async () => Ve() && Promise.allSettled([de("replayStorage"), de("sprig.replay")]))();
|
|
269
|
-
const
|
|
269
|
+
const u = new class {
|
|
270
270
|
constructor() {
|
|
271
271
|
F(this, "wrapTransactionWithCounter", (e) => {
|
|
272
272
|
var a, r;
|
|
@@ -290,7 +290,7 @@ const l = new class {
|
|
|
290
290
|
return a && (s.onupgradeneeded = (i) => {
|
|
291
291
|
a(M(s.result), i.oldVersion, i.newVersion, M(s.transaction), i);
|
|
292
292
|
}), n && (s.onblocked = (i) => n(i.oldVersion, i.newVersion, i)), c.then((i) => {
|
|
293
|
-
o && (i.onclose = () => o()), r && (i.onversionchange = (
|
|
293
|
+
o && (i.onclose = () => o()), r && (i.onversionchange = (l) => r(l.oldVersion, l.newVersion, l));
|
|
294
294
|
}).catch(() => {
|
|
295
295
|
}), c;
|
|
296
296
|
}("sprigReplay", 1, { upgrade: (e, t, n) => {
|
|
@@ -401,7 +401,7 @@ const O = () => $ && !L && Date.now() <= q, Mt = ({ apiUrl: e, config: t, trigge
|
|
|
401
401
|
L = t.disabled, j = t.metadata, A = t.uploadUrls, N = t.currentIndex, q = t.expirationTimestamp, t.pendingEventTimestamp && (d.info(`Uploading with pending timestamp: ${t.pendingEventTimestamp}`), Ot(t.pendingEventTimestamp));
|
|
402
402
|
} else q = 1e3 * $e + Date.now();
|
|
403
403
|
}, Ot = async (e) => {
|
|
404
|
-
const t = Date.now(), n = (await
|
|
404
|
+
const t = Date.now(), n = (await u.getEventsBetween(e, t)).map((r) => JSON.parse(r.event));
|
|
405
405
|
if (!ve(n)) return;
|
|
406
406
|
Ze(n);
|
|
407
407
|
const a = await Xe();
|
|
@@ -425,7 +425,7 @@ const O = () => $ && !L && Date.now() <= q, Mt = ({ apiUrl: e, config: t, trigge
|
|
|
425
425
|
if (!O()) return;
|
|
426
426
|
const { surveyId: e, responseGroupUuid: t } = j, n = { responseGroupUuid: t, surveyId: e, index: N + 1 };
|
|
427
427
|
d.info("Fetching always-on upload urls", n);
|
|
428
|
-
const a = await qe(() => Q(`${We}/sdk/1/replayUrls`, { method: "POST", body: JSON.stringify(n), headers:
|
|
428
|
+
const a = await qe(() => Q(`${We}/sdk/1/replayUrls`, { method: "POST", body: JSON.stringify(n), headers: lt(window.UserLeap) }), "fetching always-on signed urls");
|
|
429
429
|
if (!a) return;
|
|
430
430
|
const r = a.json.signedUrls;
|
|
431
431
|
return d.info("Fetched more always-on upload urls", { body: n, urls: r }), r;
|
|
@@ -493,7 +493,7 @@ const jt = (e) => {
|
|
|
493
493
|
we = [], me = !1, et(async () => {
|
|
494
494
|
await (async (t) => {
|
|
495
495
|
const n = t.map((a) => ({ ...a, sessionId: a.sessionId ?? I }));
|
|
496
|
-
if (n.length !== 0) return D(() =>
|
|
496
|
+
if (n.length !== 0) return D(() => u.bulkAdd("events", n), "Error storing replay events");
|
|
497
497
|
})(e);
|
|
498
498
|
}, "sdk_replay_add_event_batch_seconds");
|
|
499
499
|
}, 500);
|
|
@@ -501,7 +501,7 @@ const jt = (e) => {
|
|
|
501
501
|
g.cleanupInterval = window.setInterval(() => {
|
|
502
502
|
const a = Date.now();
|
|
503
503
|
Ye(() => D(async () => {
|
|
504
|
-
T() || await Promise.all([
|
|
504
|
+
T() || await Promise.all([u.deleteRowsBefore("events", a - 1e3 * e, (r) => r.expiredAt === void 0 || r.expiredAt < a - 1e3 * e), u.deleteRowsBefore("chunkUploads", a - 1e3 * t), u.deleteRowsBefore("pendingCaptures", a - 1e3 * n, (r) => !r.canUpload)]);
|
|
505
505
|
}, "Error deleting table rows"), "sdk_replay_cleanup_seconds"), d.debug("CleanupComplete");
|
|
506
506
|
}, 3e4);
|
|
507
507
|
}, Wt = () => {
|
|
@@ -517,21 +517,21 @@ const ye = async (e = !1) => {
|
|
|
517
517
|
ae = !0;
|
|
518
518
|
const t = parseInt(_ ?? "0");
|
|
519
519
|
if (t === 0) return;
|
|
520
|
-
const n = await
|
|
520
|
+
const n = await u.getPendingCaptures({ beforePresent: !0, isBeforeType: e }), a = await u.openDB();
|
|
521
521
|
await Promise.all(n.map(async (r) => (await a.delete("pendingCaptures", r.uuid), rt(r.captureParams, r.canUpload)))), _ = (t - n.length).toString(), m.setItem("sprig.pendingCount", _);
|
|
522
522
|
} finally {
|
|
523
523
|
ae = !1;
|
|
524
524
|
}
|
|
525
525
|
}, $t = async (e, t, n, a, r) => {
|
|
526
|
-
const o = Math.min(e + r, n), s = await Ye(() =>
|
|
526
|
+
const o = Math.min(e + r, n), s = await Ye(() => u.getEventsBetween(e, o), "sdk_replay_get_events_between_seconds");
|
|
527
527
|
if (!(s != null && s.length)) return d.debug("NoEventsFound"), { validStartFound: a, events: [] };
|
|
528
528
|
if (!a) {
|
|
529
529
|
d.debug("ValidStartSearch");
|
|
530
530
|
let c = -1;
|
|
531
|
-
return s == null || s.forEach((i,
|
|
531
|
+
return s == null || s.forEach((i, l) => {
|
|
532
532
|
if (!i.isValidStart) return;
|
|
533
533
|
const y = i.timestamp <= t;
|
|
534
|
-
(c < 0 || y) && (c =
|
|
534
|
+
(c < 0 || y) && (c = l);
|
|
535
535
|
}), c < 0 ? (d.debug("ValidStartNotFound"), { validStartFound: a, events: [] }) : { validStartFound: !0, events: s == null ? void 0 : s.slice(c) };
|
|
536
536
|
}
|
|
537
537
|
return { validStartFound: a, events: s };
|
|
@@ -545,17 +545,17 @@ const ye = async (e = !1) => {
|
|
|
545
545
|
if (!o) throw new Error(`Upload response did not include etag for upload ${a.uploadId}, part ${a.chunkIndex}`);
|
|
546
546
|
return o;
|
|
547
547
|
}))(t);
|
|
548
|
-
return await
|
|
548
|
+
return await u.updatePartial("chunkUploads", t.uuid, { data: null, etag: n, status: "UploadComplete" }), t.uploadId;
|
|
549
549
|
})), at = async (e) => {
|
|
550
|
-
const t = await
|
|
550
|
+
const t = await u.getChunkUploadsByStatus({ status: "UploadComplete", uploadId: e });
|
|
551
551
|
if (!(t != null && t.length)) return void d.info("NoChunksForUpload", { uploadId: e });
|
|
552
552
|
const n = t.reduce((o, s) => (o.find((c) => c.chunkIndex === s.chunkIndex) || o.push(s), o), []);
|
|
553
553
|
n.sort((o, s) => o.chunkIndex - s.chunkIndex);
|
|
554
554
|
const a = n.map((o) => ({ ETag: o.etag, PartNumber: o.chunkIndex })).filter((o) => o.ETag !== null), r = n[0];
|
|
555
|
-
await _e({ apiUrl: r.apiUrl, surveyId: r.surveyId, uploadId: e, responseGroupUuid: r.responseGroupId, etags: a, headers: r.completeUploadHeaders, replayDuration: r.replayDuration }), await
|
|
555
|
+
await _e({ apiUrl: r.apiUrl, surveyId: r.surveyId, uploadId: e, responseGroupUuid: r.responseGroupId, etags: a, headers: r.completeUploadHeaders, replayDuration: r.replayDuration }), await u.deleteChunkUploads("UploadComplete", e);
|
|
556
556
|
}, Kt = () => {
|
|
557
557
|
D(async () => {
|
|
558
|
-
const e = await
|
|
558
|
+
const e = await u.getChunkUploadsByStatus({ sessionId: I, status: "ReadyForUpload" });
|
|
559
559
|
if (!(e != null && e.length)) return;
|
|
560
560
|
const t = await nt(e);
|
|
561
561
|
t != null && t.length && await Promise.all(t.map((n) => {
|
|
@@ -568,7 +568,7 @@ const ye = async (e = !1) => {
|
|
|
568
568
|
const o = new TextEncoder();
|
|
569
569
|
let s = null;
|
|
570
570
|
const c = new CompressionStream("gzip"), i = c.writable.getWriter();
|
|
571
|
-
let
|
|
571
|
+
let l = !1, y = !1, [p, h] = [0, 0], w = [];
|
|
572
572
|
for (let P = a - 35e3; P < r; P += pe) {
|
|
573
573
|
if ({ validStartFound: y, events: w } = await $t(P, a, r, y, pe), !(w != null && w.length)) {
|
|
574
574
|
d.debug("NoEventsFound");
|
|
@@ -577,10 +577,10 @@ const ye = async (e = !1) => {
|
|
|
577
577
|
p === 0 && (p = w[0].timestamp), h = w[w.length - 1].timestamp;
|
|
578
578
|
const f = w.map((R) => R.event);
|
|
579
579
|
f.push(`{"timestamp":${r}}`);
|
|
580
|
-
const v = `${
|
|
580
|
+
const v = `${l ? "," : "["}${f}`, S = o.encode(v);
|
|
581
581
|
et(() => {
|
|
582
582
|
i.write(S);
|
|
583
|
-
}, "sdk_replay_compression_seconds"),
|
|
583
|
+
}, "sdk_replay_compression_seconds"), l = !0;
|
|
584
584
|
}
|
|
585
585
|
if (h - p < tt) return d.debug("ReplayTooShort"), null;
|
|
586
586
|
const E = o.encode("]");
|
|
@@ -589,14 +589,14 @@ const ye = async (e = !1) => {
|
|
|
589
589
|
}, Pe = async (e) => {
|
|
590
590
|
const { surveyId: t, responseGroupId: n, visitorId: a, apiUrl: r, completeUploadHeaders: o, replayParams: s, triggerTimestamp: c } = e, i = await Jt(1e3 * s.replayDurationSeconds, c);
|
|
591
591
|
if (!(i != null && i.length)) return void d.info("FileDataEmpty", { surveyId: t });
|
|
592
|
-
const
|
|
592
|
+
const l = ((p, h, w) => {
|
|
593
593
|
const E = p.length, P = 1024 * h * 1024, f = Math.ceil(E / w), v = Math.max(P, f), S = [];
|
|
594
594
|
let R = 0;
|
|
595
595
|
for (; R < E; ) S.push(p.slice(R, R + v)), R += v;
|
|
596
596
|
return S;
|
|
597
|
-
})(i, s.minimumChunkSizeMb, s.signedUrls.length), y = await Promise.all(
|
|
598
|
-
const w = X(), E = { apiUrl: r, chunkIndex: h + 1, completeUploadHeaders: o, etag: null, responseGroupId: n, status: "ReadyForUpload", surveyId: t, timestamp: c, totalChunks:
|
|
599
|
-
return await (await
|
|
597
|
+
})(i, s.minimumChunkSizeMb, s.signedUrls.length), y = await Promise.all(l.map(async (p, h) => {
|
|
598
|
+
const w = X(), E = { apiUrl: r, chunkIndex: h + 1, completeUploadHeaders: o, etag: null, responseGroupId: n, status: "ReadyForUpload", surveyId: t, timestamp: c, totalChunks: l.length, data: p, uploadId: s.uploadId, uploadUrl: s.signedUrls[h].url, uuid: w, visitorId: a };
|
|
599
|
+
return await (await u.openDB()).add("chunkUploads", { ...E, sessionId: E.sessionId ?? I }), E;
|
|
600
600
|
}));
|
|
601
601
|
await (async (p, h) => {
|
|
602
602
|
await nt(h), await Promise.all(p.map((w) => at(w)));
|
|
@@ -605,7 +605,7 @@ const ye = async (e = !1) => {
|
|
|
605
605
|
if (T()) return d.debug("ReplayDisabled-ScheduleOrCapture");
|
|
606
606
|
const { isHeatmap: n, isStandalone: a, replayParams: r, triggerTimestamp: o, responseGroupId: s } = e, c = async () => {
|
|
607
607
|
setTimeout(() => V.removeListener(Z.QuestionAnswered, c), 0), D(async () => {
|
|
608
|
-
r.replayDurationType === "before" ? await Pe(e) : await
|
|
608
|
+
r.replayDurationType === "before" ? await Pe(e) : await u.markPendingCaptureToCanUpload(s);
|
|
609
609
|
}, "Error in schedule/capture callback");
|
|
610
610
|
};
|
|
611
611
|
D(async () => {
|
|
@@ -613,26 +613,26 @@ const ye = async (e = !1) => {
|
|
|
613
613
|
return !a && !n && V.on(Z.QuestionAnswered, c), void await st(e);
|
|
614
614
|
if (a || n || t) await Pe(e), n && zt();
|
|
615
615
|
else {
|
|
616
|
-
const i = 35 + r.replayDurationSeconds,
|
|
617
|
-
await
|
|
616
|
+
const i = 35 + r.replayDurationSeconds, l = o - 1e3 * i, y = o;
|
|
617
|
+
await u.updateEventsExpiredAt(l, y, r.expirationTimeLimitMinutes), V.on(Z.QuestionAnswered, c);
|
|
618
618
|
}
|
|
619
619
|
}, "Error in scheduling/capturing replay");
|
|
620
620
|
}, zt = async () => {
|
|
621
621
|
parseInt(_ ?? "0") || m.removeItem("sprig.isCapturingHeatmap"), m.getItem("sprig.teardownAfterCapture") && (Ge(), ot(), m.removeItem("sprig.teardownAfterCapture"));
|
|
622
|
-
}, ot = async () => T() ? d.debug("ReplayDisabled-ClearData") : Promise.all([
|
|
622
|
+
}, ot = async () => T() ? d.debug("ReplayDisabled-ClearData") : Promise.all([u.deleteBySessionId("events", I), u.deleteBySessionId("pendingCaptures", I)]).catch((e) => {
|
|
623
623
|
H("Error clearing user replay data", e);
|
|
624
624
|
}), st = async (e) => {
|
|
625
625
|
if (T()) return;
|
|
626
|
-
const { isHeatmap: t, surveyId: n } = e, a = await
|
|
626
|
+
const { isHeatmap: t, surveyId: n } = e, a = await u.getPendingCaptures(), r = a == null ? void 0 : a.filter((i) => i.captureParams.surveyId === n);
|
|
627
627
|
if (r != null && r.length) return void d.info("PendingCaptureExists", { surveyId: n });
|
|
628
|
-
t && (
|
|
628
|
+
t && (ue(), m.setItem("sprig.isCapturingHeatmap", "true"), ge = Date.now(), g.inactivityInterval || (g.inactivityInterval = window.setInterval(() => {
|
|
629
629
|
var i;
|
|
630
|
-
i = ge, Date.now() - i >= 3e4 && D(() =>
|
|
630
|
+
i = ge, Date.now() - i >= 3e4 && D(() => u.markPendingHeatmapsReady(), "Error in heatmap inactivity");
|
|
631
631
|
}, 1e3)));
|
|
632
632
|
const o = { ...e, replayParams: { ...e.replayParams } };
|
|
633
633
|
e.replayParams.replayDurationType === "beforeAndAfter" && (o.replayParams.replayDurationSeconds *= 2), o.replayParams.replayDurationType = "before";
|
|
634
634
|
const s = e.triggerTimestamp + 1e3 * e.replayParams.replayDurationSeconds;
|
|
635
|
-
o.triggerTimestamp = s, _ = (parseInt(_ ?? "0") + 1).toString(), m.setItem("sprig.pendingCount", _), await (await
|
|
635
|
+
o.triggerTimestamp = s, _ = (parseInt(_ ?? "0") + 1).toString(), m.setItem("sprig.pendingCount", _), await (await u.openDB()).add("pendingCaptures", { canUpload: !1, captureParams: o, sessionId: I, targetTimestamp: s, timestamp: Date.now(), uuid: X() });
|
|
636
636
|
}, qt = Object.freeze(Object.defineProperty({ __proto__: null, RecordEvent: (e) => {
|
|
637
637
|
U("Sprig_TrackEvent", e);
|
|
638
638
|
}, RecordPageView: (e) => {
|
|
@@ -644,29 +644,29 @@ const ye = async (e = !1) => {
|
|
|
644
644
|
const r = window.UserLeap._API_URL, o = await _e({ surveyId: e, responseGroupUuid: t, eventDigest: n, apiUrl: r, headers: a }, !0);
|
|
645
645
|
return !(o != null && o.error);
|
|
646
646
|
}, checkPendingHeatmapsUrl: () => T() ? d.debug("ReplayDisabled-PendingHeatmaps") : D(async () => {
|
|
647
|
-
const e = (await
|
|
648
|
-
return d.info("PendingHeatmapsToComplete", { count: e.length }), e.length && (await
|
|
647
|
+
const e = (await u.getPendingCaptures({ isHeatmap: !0 })).map((t) => ({ eventId: t.captureParams.eventId, uuid: t.uuid })).filter(({ eventId: t }) => !ct(t)).map(({ uuid: t }) => t);
|
|
648
|
+
return d.info("PendingHeatmapsToComplete", { count: e.length }), e.length && (await u.markPendingHeatmapsReady(e), d.info("MarkedPendingHeatmapsReady")), e.length;
|
|
649
649
|
}, "Error marking pending heatmaps ready"), clearUserReplayData: ot, disableRecording: H, initializeReplay: async ({ maxReplayDurationSeconds: e, maxInflightRequests: t = 2, replaySettings: n, teardownAfter: a = !1, apiUrl: r, alwaysOnConfig: o }) => {
|
|
650
650
|
if (o && Mt({ apiUrl: r, config: o, triggerSnapshot: () => {
|
|
651
|
-
|
|
651
|
+
ue();
|
|
652
652
|
} }), _ = m.getItem("sprig.pendingCount"), g.isRecording) return;
|
|
653
653
|
if (a && m.setItem("sprig.teardownAfterCapture", "true"), T()) return d.debug("ReplayDisabled");
|
|
654
654
|
if (await (async () => {
|
|
655
655
|
var i;
|
|
656
656
|
if (!Ve()) return !0;
|
|
657
657
|
if ((i = window.navigator.storage) != null && i.estimate) try {
|
|
658
|
-
const { quota:
|
|
658
|
+
const { quota: l = 0, usage: y = 0 } = await window.navigator.storage.estimate(), p = (l - y) / 1024 ** 3;
|
|
659
659
|
return d.info("Storage", { availableGb: p }), p < 0.5;
|
|
660
660
|
} catch {
|
|
661
661
|
return !0;
|
|
662
662
|
}
|
|
663
663
|
return !1;
|
|
664
|
-
})()) return d.debug("IDBNotSupported"),
|
|
664
|
+
})()) return d.debug("IDBNotSupported"), le();
|
|
665
665
|
try {
|
|
666
|
-
const i = await
|
|
666
|
+
const i = await u.openDB();
|
|
667
667
|
d.info("DBVersion", { version: i.version });
|
|
668
668
|
} catch (i) {
|
|
669
|
-
return d.error("ReplayOpenErr", { name: i.name }), i.name === "VersionError" &&
|
|
669
|
+
return d.error("ReplayOpenErr", { name: i.name }), i.name === "VersionError" && u.deleteDB(), le();
|
|
670
670
|
}
|
|
671
671
|
D(async () => {
|
|
672
672
|
await ye(!0);
|
|
@@ -676,12 +676,12 @@ const ye = async (e = !1) => {
|
|
|
676
676
|
d.debug("ReplayInit"), await D(async () => {
|
|
677
677
|
var i;
|
|
678
678
|
n != null && n.minDuration && (tt = n.minDuration), n != null && n.batchDuration && (pe = n.batchDuration), i = t, Me.setLimit(i), Kt(), Gt(c + 35, 1800, c + 35), Wt();
|
|
679
|
-
const
|
|
679
|
+
const l = window.UserLeap.replayLibraryURL ?? "https://cdn.sprig.com/dependencies/record-2.0.0-alpha.17.min.js";
|
|
680
680
|
if (!window.rrwebRecord) {
|
|
681
681
|
const { record: f } = await import(
|
|
682
682
|
/* webpackIgnore: true */
|
|
683
683
|
/* @vite-ignore */
|
|
684
|
-
|
|
684
|
+
l
|
|
685
685
|
);
|
|
686
686
|
window.rrwebRecord = f;
|
|
687
687
|
}
|
|
@@ -695,7 +695,7 @@ const ye = async (e = !1) => {
|
|
|
695
695
|
if (v && f.type === B.Meta) h = performance.now();
|
|
696
696
|
else if (v && h && f.type === B.FullSnapshot) {
|
|
697
697
|
const R = performance.now() - h;
|
|
698
|
-
|
|
698
|
+
ut("sdk_replay_snapshot_seconds", R / 1e3);
|
|
699
699
|
}
|
|
700
700
|
const S = p || !!v && f.type === B.Meta;
|
|
701
701
|
p = !1, Ht(S, f), jt({ uuid: X(), event: JSON.stringify(f), isValidStart: S, timestamp: Date.now() });
|
|
@@ -704,12 +704,12 @@ const ye = async (e = !1) => {
|
|
|
704
704
|
var R;
|
|
705
705
|
S.data.type === vt && (fe.push({ source: S.source, origin: S.origin }), (R = S.source) == null || R.postMessage({ type: St, settings: f, replayLibraryUrl: v }, { targetOrigin: S.origin }));
|
|
706
706
|
});
|
|
707
|
-
})(w,
|
|
707
|
+
})(w, l), V.on("survey.complete", (f) => {
|
|
708
708
|
var v;
|
|
709
709
|
v = { id: f, userAgent: window.navigator.userAgent }, U("Sprig_SubmitSurvey", v);
|
|
710
710
|
}), E = U, P = Ut, J || (b = E, G = P, window.addEventListener("click", Fe, C), window.addEventListener("pointerdown", je, C), window.addEventListener("mousedown", He, C), window.addEventListener("keydown", Le, C), window.addEventListener("scroll", Oe, C), J = !0, Pt(), kt()));
|
|
711
711
|
}, "Error initializing replay");
|
|
712
|
-
}, isReplayPaused: z, isReplayRecording: () => g.isRecording, recordFullSnapshot:
|
|
712
|
+
}, isReplayPaused: z, isReplayRecording: () => g.isRecording, recordFullSnapshot: ue, recordReplayPaused: () => {
|
|
713
713
|
U("Sprig_ReplayPaused", { timestamp: Date.now() }), m.setItem("sprig.isReplayPaused", "true");
|
|
714
714
|
}, recordReplayResumed: () => {
|
|
715
715
|
m.removeItem("sprig.isReplayPaused"), U("Sprig_ReplayResumed", { timestamp: Date.now() });
|