@sprig-technologies/sprig-browser 2.32.2 → 2.32.3
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-DsBuStDe.js +1000 -0
- package/dist/core-gTCnh_sk.cjs +12 -0
- 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-D4pafvTR.cjs +1 -0
- package/dist/{metricsReporter-D0VZ2ZgI.js → metricsReporter-Gimz6xcf.js} +46 -29
- package/dist/replay.cjs +1 -1
- package/dist/replay.js +149 -144
- package/dist/view-BRI_mHiJ.cjs +669 -0
- package/dist/view-Csp070UH.js +2841 -0
- package/package.json +1 -1
- package/dist/core-D-LZZjJw.cjs +0 -12
- package/dist/core-DJ-C8ZCy.js +0 -983
- package/dist/metricsReporter-CiE5uf1B.cjs +0 -1
- package/dist/view-CDdG2lXT.js +0 -2830
- package/dist/view-CW-37QDp.cjs +0 -669
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";var ct=Object.defineProperty;var pt=(t,e,o)=>e in t?ct(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o;var q=(t,e,o)=>(pt(t,typeof e!="symbol"?e+"":e,o),o);const i=require("./metricsReporter-D4pafvTR.cjs"),Ve="360px",Ae=()=>{try{return window.parent.Intercom}catch{return null}},Oe=[Object.freeze(Object.defineProperty({__proto__:null,disable:()=>{const t=Ae();t&&(t.ul_wasVisible=!!document.querySelector("iframe.intercom-launcher-frame"),t.ul_wasVisible&&t("update",{hide_default_launcher:!0}))},enable:()=>{const t=Ae();t&&(t.ul_wasVisible&&t("update",{hide_default_launcher:!1}),delete t.ul_wasVisible)}},Symbol.toStringTag,{value:"Module"}))];class We{static disable(){Oe.forEach(e=>e.disable())}static enable(){Oe.forEach(e=>e.enable())}}const Ce="ul-view-sdk-script",ut=["ios","android"],P="visitors",T="environments";async function O(t,e){var n,s,d;const{shouldDropOnRateLimit:o,...a}=e;a.headers=Object.assign(i.getHttpHeaders(window.UserLeap),a.headers);const r=await i.sprigFetch(t,{...a,shouldDropOnRateLimit:o});if(r.ok){const c=(n=r.headers)==null?void 0:n.get("Authorization"),p=c?c.split(" "):void 0,l=p&&p.length===2?p[1]:void 0,u=(s=r.headers)==null?void 0:s.get("x-ul-visitor-id");if(window.UserLeap.userId&&u===window.UserLeap.visitorId){const m=i.localStorageHelper.getItemObject("sprig.anon.env.vid.map");m&&m[window.UserLeap.envId]===u&&(delete m[window.UserLeap.envId],i.localStorageHelper.setItemObject("sprig.anon.env.vid.map",m))}l&&u&&(u!==window.UserLeap.visitorId||window.UserLeap.token!==l)&&(k("token",l),k("vid",u),i.eventEmitter.emit(i.SprigEvent.VisitorIDUpdated,{visitorId:u}),window.UserLeap.token=l,window.UserLeap.visitorId=u)}return(d=r.json)!=null&&d.logMessage&&console.warn(`[Sprig] ${r.json.logMessage}`),r}function k(t,e){const o=i.localStorageHelper.getItemObject("userleap.ids");let a=o[window.UserLeap.envId];a?a[t]=e:a={[t]:e},o[window.UserLeap.envId]=a,i.localStorageHelper.setItemObject("userleap.ids",o)}function be(){return window.previewMode?"0":window.UserLeap.visitorId??""}function R(t,e,o){const a=[window.UserLeap._API_URL,"sdk",t];return e&&e.forEach(r=>{a.push(r),r===T?a.push(window.UserLeap.envId):r===P&&a.push(be())}),o&&a.push(o),a.join("/")}const B=async(t,e)=>{var _e,De,Re;const{context:o,delay:a,forceBrandedLogo:r,endCard:n,isFeedback:s=!1,heatmap:d,locale:c,previewMode:p,productConfig:l,questions:u,responseGroupUid:m,surveyId:w,uuid:g,vid:I,sessionReplay:h,studyType:S}=t,f=i.getHttpHeaders(window.UserLeap),b=se(f),U=Se(f);if(h)if(b)i.eventEmitter.emit(i.SprigEvent.ReplayCapture,{responseGroupUid:m,hasQuestions:!!(u!=null&&u.length),surveyId:w,uploadId:h.uploadId,replayType:h.replayDurationType??"before",seconds:h.replayDurationSeconds,generateVideoUploadUrlPayload:{mediaRecordingUid:i.v4(),mediaType:"screen",questionId:1,responseGroupUid:m,surveyId:w,updatedAt:new Date().toISOString(),visitorId:window.UserLeap.visitorId,isReplay:!0}});else{if(!i.modules.replay)return window.UserLeap.reportError("displayQuestions",new Error("Replay module not registered")),{success:!1,message:"Replay module not registered",surveyState:"no survey"};i.modules.replay.scheduleOrCaptureReplay({responseGroupId:m,surveyId:w,visitorId:I,replayParams:h,completeUploadHeaders:f,apiUrl:window.UserLeap._API_URL,triggerTimestamp:Date.now(),isStandalone:u.length===0})}if(d){if(!i.modules.replay)return window.UserLeap.reportError("displayQuestions",new Error("Replay module not registered")),{success:!1,message:"Replay module not registered",surveyState:"no survey"};const{eventId:L,replayParams:de,responseGroupUid:dt,surveyId:lt}=d;await i.modules.replay.initializeReplay({maxReplayDurationSeconds:300,maxInflightRequests:window.UserLeap.maxInflightReplayRequests,teardownAfter:!0}),i.modules.replay.tryReplayAction(()=>{var xe;return(xe=i.modules.replay)==null?void 0:xe.scheduleCapture({apiUrl:window.UserLeap._API_URL,completeUploadHeaders:f,eventId:L,isHeatmap:!0,replayParams:de,responseGroupId:dt,surveyId:lt,triggerTimestamp:Date.now(),visitorId:I})},"Error in scheduling/capturing replay")}if(I==null||!(u!=null&&u.length))return i.breadcrumbsLogger.info("CannotDisplaySurvey",{vid:I}),{success:!1,message:"[Sprig] no survey found",surveyState:"no survey"};if(window.UserLeap.container){i.breadcrumbsLogger.info("AlreadyDisplayingSurvey");const L="[Sprig] (ERR-409) Found an existing Survey container, aborting rendering of this survey";return console.warn(L),{success:!1,message:L,surveyState:"no survey"}}if(I!==window.UserLeap.visitorId&&g!==window.UserLeap.visitorId&&!window.previewMode){const L="Attempted to display survey to a different visitor";return window.UserLeap.reportError("DisplaySurvey",new Error(L)),{success:!1,message:L,surveyState:"no survey"}}i.breadcrumbsLogger.info("ShowingSurvey",{surveyId:w}),(_e=i.modules.replay)==null||_e.RecordSurveyShown({id:w,userAgent:window.navigator.userAgent}),We.disable(),i.eventEmitter.emit(i.SprigEvent.SurveyWillPresent,{name:i.SprigEvent.SurveyWillPresent,"survey.id":w});let x,v,E,_,D=document.createElement("div");const H=L=>{const{"view.version":de}=L;de!==f["x-ul-sdk-version"]&&ze(),i.eventEmitter.removeListener("verify.view.version",H)};i.eventEmitter.on("verify.view.version",H),window.UserLeap.useMobileStyling=U,i.shouldDirectEmbed(f)?(x="ul-direct-embeded-frame",v=document.head,E=window,_=!1,b&&(Ne(w,s),D.id=x,window.UserLeap.container.appendChild(D),Be(),i.eventEmitter.emit(i.SprigEvent.SurveyLifeCycle,{state:"presented"}),i.eventEmitter.emit(i.SprigEvent.SurveyPresented,{name:i.SprigEvent.SurveyPresented,"survey.id":w}))):{frameId:x,contentWinDocHead:v,contentWindow:E,hasOverlay:_,iframe:D}=gt({productConfig:l,useMobileStyling:U,surveyId:w,isFeedback:s}),window.UserLeap.frameId=x;const A={apiURL:window.UserLeap._API_URL,cards:u,configureExitOnOverlayClick:L=>{i.eventEmitter.once(i.SprigEvent.CloseSurveyOnOverlayClick,L)},context:o,endCard:n,envId:window.UserLeap.envId,eventEmitFn:i.eventEmitter.emit.bind(i.eventEmitter),fontFamily:window.UserLeap.fontFamily,fontFamilyURL:window.UserLeap.fontFamilyURL,forceBrandedLogo:r,frame:D,headers:f,locale:c,mobileSDKVersion:window.UserLeap.mobileSDKVersion,previewKey:i.localStorageHelper.getItem("sprig.previewKey"),previewMode:p,productConfig:{framePosition:l==null?void 0:l.framePosition,desktopDisplay:l==null?void 0:l.desktopDisplay,placement:l==null?void 0:l.placement},responseGroupUid:m,startingQuestionIdx:(De=window.UserLeap.config)==null?void 0:De.startingQuestionIdx,studyType:S,styleNonce:window.UserLeap.styleNonce,surveyId:w,tabTitle:document.title,trackPageViewUrl:e,ulEvents:i.EVENTS,upchunkLibraryURL:window.UserLeap.upchunkLibraryURL,useMobileStyling:U,userId:g,viewDocument:E==null?void 0:E.document,viewWindow:E,visitorAttributes:{externalUserId:window.UserLeap.userId,email:window.UserLeap.email},...window.UserLeap._config};(Re=window.UserLeap._config)!=null&&Re.startingQuestionIdx&&(window.UserLeap._config={...window.UserLeap._config,startingQuestionIdx:null});const J=(s?window.UserLeap.feedbackCustomStyles:window.UserLeap.customStyles)??l.customStyles;A.customStyles=J,E&&(E.__cfg=A);const W=window.UserLeap.viewSDKURL?window.UserLeap.viewSDKURL:A.path,Ee=document.getElementById(Ce);Ee&&Ee.remove();const ae=function(){const L=document.createElement("script");return window.UserLeap.nonce&&L.setAttribute("nonce",window.UserLeap.nonce),L.id=Ce,L}(),Ie=()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{display:"flex"})};if(A.installationMethod==="web-npm"||A.installationMethod==="web-npm-bundled"){const{default:L}=await Promise.resolve().then(()=>require("./view-BRI_mHiJ.cjs"));L.configure(A),_&&window.UserLeap.container&&Ie()}else W&&(ae.src=W,_&&ae.addEventListener("load",()=>{window.UserLeap.container&&Ie()}),E==null||E.addEventListener("error",L=>{L.target instanceof HTMLScriptElement&&L.target.src===W&&window.UserLeap.reportError("loadFrameScript",new Error("Frame script failed to load"))},{capture:!0,once:!0}));v==null||v.appendChild(ae);const ke={success:!0,surveyState:"ready",surveyId:w,responseGroupUid:m};return window.UserLeap.isMobileSDK&&a&&(ke.delay=a),ke};function Se(t){var o;if(window.UserLeap.useMobileStyling!==void 0)return window.UserLeap.useMobileStyling;const e=((o=window.UserLeap.windowDimensions)==null?void 0:o.width)??document.body.clientWidth;return se(t)||e>10&&e<500}function se(t){return ut.includes(t["userleap-platform"])}const Le="ul-frame";window.UserLeap&&window.Sprig&&(window.Sprig._gtm?window.Sprig=window.UserLeap:window.UserLeap=window.Sprig),window.UserLeap||(window.UserLeap=window.Sprig),window.Sprig||(window.Sprig=window.UserLeap);const le="0px",Ne=(t,e,o)=>{window.UserLeap.container=document.createElement("div"),window.UserLeap.container.className="ul-container"+(e?" ul-container-feedback":""),t&&(window.UserLeap.container.dataset.studyId=t.toString());const a=Ke();o&&a&&!window.UserLeap.useMobileStyling?a.appendChild(window.UserLeap.container):document.body.appendChild(window.UserLeap.container)},ze=(t,e)=>{var a;yt();const o=window.UserLeap.container;if(o)try{(a=o.parentNode)==null||a.removeChild(o),window.UserLeap.container=null,k("trackStartUrl",null),i.eventEmitter.emit(i.SprigEvent.SurveyLifeCycle,{state:"dismissed"}),i.eventEmitter.emit(i.SprigEvent.SurveyClosed,{name:i.SprigEvent.SurveyClosed,initiator:t,"survey.id":parseInt(o.dataset.studyId),...e&&{studyType:e}})}catch(r){console.warn(`[Sprig] (ERR-412) Error removing UserLeap container by ${t} `+o),r instanceof Error&&window.UserLeap.reportError("dismissActiveSurvey",r)}},Be=()=>{i.eventEmitter.once(i.SprigEvent.SurveyWillClose,({initiator:t,studyType:e})=>{i.eventEmitter.removeAllListeners(i.SprigEvent.CloseSurveyOnOverlayClick),ze(t,e)})},wt=(t,e,o,a)=>{var l,u;const r={position:"fixed",bottom:"0px",right:le,border:0,backgroundColor:"rgba(0,0,0,0)",zIndex:2147483646,transition:"width 0.2s ease-in-out, height 0.2s ease-in-out",maxWidth:"100%"},n=Object.assign({},e,window.UserLeap),{desktopDisplay:s}=e||{},d=s==="center-modal";let c;d&&(n.framePosition="center");let p=!1;if(o)(l=window.UserLeap.windowDimensions)!=null&&l.width?r.width=`${window.UserLeap.windowDimensions.width}px`:r.width="100%",(u=window.UserLeap.windowDimensions)!=null&&u.height?r.maxHeight=window.UserLeap.windowDimensions.height-20+"px":window.UserLeap.maxHeight?r.maxHeight=window.UserLeap.maxHeight:r.maxHeight=document.body.clientHeight-20+"px",["light","dark"].includes(n.overlayStyleMobile)&&(p=!0);else{r.width=Ve,r.maxHeight=window.UserLeap.maxHeight||"66vh";const m=()=>{p=!0,c={margin:"auto",position:"static"}};if(a)d?m():c={position:"relative",height:"300px"};else switch(n.framePosition){case"bottomLeft":c={left:le};break;case"topLeft":c={left:le,top:0};break;case"topRight":c={top:0};break;case"center":m()}}return p&&((m,w)=>{const g={position:"fixed",overflow:"auto",top:"0px",left:"0px",display:"none",height:"100%",width:"100%",transition:"background-color 0.3s ease-out",zIndex:2147483646},I=w?m.overlayStyleMobile:m.overlayStyle;g["background-color"]=I==="light"?"rgba(255,255,255, 0.95)":"rgba(0,0,0,0.9)",w||(g.margin="auto"),window.UserLeap.container&&Object.assign(window.UserLeap.container.style,g)})(n,o),Object.assign(t.style,r,c),p},gt=({productConfig:t,useMobileStyling:e,surveyId:o,isFeedback:a})=>{var m,w;const r=Le,n=a&&t.desktopDisplay==="slider";Ne(o,a,n),mt();const s=document.createElement("iframe");s.id=r,s.setAttribute("title","Sprig User Feedback Dialog");const d=wt(s,t,e,a);Be();let c=!1;s.setHeight=g=>{parseInt(s.style.height)==g&&c||(c=!0,s.style.height=`${g}px`,i.eventEmitter.emit(i.SprigEvent.SurveyHeight,{name:i.SprigEvent.SurveyHeight,contentFrameHeight:g,"survey.id":o}))};let p=!1;s.setWidth=g=>{parseInt(s.style.width)==g&&p||(p=!0,s.style.width=`${g}px`,i.eventEmitter.emit(i.SprigEvent.SurveyWidth,{name:i.SprigEvent.SurveyWidth,contentFrameWidth:g,"survey.id":o}))},(m=window.UserLeap.container)==null||m.appendChild(s),t&&(e?t.exitOnOverlayClickMobile:t.exitOnOverlayClick)&&window.UserLeap.container&&(window.UserLeap.container.onclick=()=>{i.eventEmitter.emit(i.SprigEvent.CloseSurveyOnOverlayClick)}),i.eventEmitter.emit(i.SprigEvent.SurveyLifeCycle,{state:"presented"}),i.eventEmitter.emit(i.SprigEvent.SurveyPresented,{name:i.SprigEvent.SurveyPresented,"survey.id":o});const l=(w=s.contentWindow)==null?void 0:w.document;if(l&&(l.open("text/html","replace"),l.write("<!doctype html><head></head><body></body></html>"),l.close(),!e)){const g=l.body;g.style.display="flex",g.style.alignItems="center"}const u=l==null?void 0:l.head;return{frameId:r,contentWinDocHead:u,contentWindow:s.contentWindow,hasOverlay:d,iframe:s}},$e={[i.SprigEvent.SurveyFadingOut]:()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{"background-color":"rgba(0,0,0,0)"})}},mt=()=>{Object.entries($e).forEach(([t,e])=>{i.eventEmitter.on(t,e)})},yt=()=>{Object.entries($e).forEach(([t,e])=>{i.eventEmitter.off(t,e)})},F=t=>!!t&&t.nodeType===Node.ELEMENT_NODE,Pe=t=>t instanceof HTMLElement||t instanceof SVGElement,K=({document:t,elementId:e,styleString:o,nonce:a})=>{const r=t.getElementById(e);if(r)return void(r.textContent=o);const n=t.createElement("style");a&&(n.nonce=a),n.textContent=o,n.id=e,t.head.appendChild(n)},vt=(t,e)=>{const o=e.querySelector(".sprig-question-body");if(!F(o))return t;const a=o.scrollHeight;return a<100?t:t-(a-100)},Te=(t,e)=>{const o=e.querySelector(t);if(!F(o))return 0;const a=getComputedStyle(o);return parseFloat(a.paddingLeft)+parseFloat(a.paddingRight)+(parseFloat(a.marginLeft)+parseFloat(a.marginRight))+(parseFloat(a.borderLeftWidth)+parseFloat(a.borderRightWidth))},Ge=t=>{const e=t.querySelector(".ul-card__container");let o=600,a=360,r=0;if(F(e)){o=e.clientHeight,o+=(d=>{const c=d.querySelector(".sprig-question-body"),p=d.querySelector(".ul-card"),l=d.querySelector(".ul-card-main-content");let u=0;return F(p)&&(u+=p.scrollHeight-p.clientHeight),F(l)&&(u+=l.scrollHeight-l.clientHeight),F(c)&&(u+=c.scrollHeight-c.clientHeight),u})(t);const n=getComputedStyle(e);r=o,o+=parseFloat(n.marginTop)+parseFloat(n.marginBottom)+(parseFloat(n.borderTopWidth)+parseFloat(n.borderBottomWidth));const s=e.querySelector(".ul-card--matrix_grid");a=s?s.scrollWidth:e.scrollWidth,a+=Te(".ul-card__container",t),a+=Te(".sprig-question-body",t)}return[o+1,a,vt(r,t)]},Ke=()=>y,V=()=>document.getElementById("sprig-feedback-container"),we=()=>document.getElementById("sprig-feedback-loading-animation"),Je=()=>!!document.getElementById(Le);let He=!1,y=null,C=null,Ue=!1,$=null,M=null;const ft=["bottom-left","bottom-right","center-left","center-right"],X=()=>{var e;const t=window.UserLeap.container;return((e=t==null?void 0:t.parentElement)==null?void 0:e.id)==="sprig-feedback-loading-container"},Qe=()=>document.getElementById("sprig-feedback-error-container"),Ye=()=>{if(!y)return 0;const t=y==null?void 0:y.clientWidth,e=window.getComputedStyle(y);return t+parseInt(e.borderRightWidth||"0")+parseInt(e.borderLeftWidth||"0")},Z=t=>{const e=V();e&&(M!=null&&M.endsWith("right")?e.style.right=`${t}px`:M!=null&&M.endsWith("left")&&(e.style.left=`${t}px`))},ce=()=>{if(y&&(X()||Qe())){i.eventEmitter.off(i.SprigEvent.SurveyAppeared,z),ge();const t=Ye();return Z(-t),!0}return!1},z=()=>{if(!y||!C)return;const t=we();t&&t.remove(),y.style.height="auto",y.style.width="auto",C.disabled=!1,Ue=!1},ge=()=>{if(y&&!we()){const t=(()=>{if(we())return;const e=document.createElement("div");return e.className="ul-loading-spinner-container",e.id="sprig-feedback-loading-animation",e.role="progressbar",e.setAttribute("aria-live","polite"),e.setAttribute("aria-busy","true"),e.setAttribute("aria-label","Processing..."),e.innerHTML=`
|
|
2
|
+
<div class="ul-loading-spinner">
|
|
3
|
+
<div class="first"></div>
|
|
4
|
+
<div class="second"></div>
|
|
5
|
+
<div class="third"></div>
|
|
6
|
+
<div class="fourth"></div>
|
|
7
|
+
</div>
|
|
8
|
+
`,e})();t&&(y.style.height="300px",y.style.width="360px",y.appendChild(t))}},Me=()=>{y&&C&&(Z(0),C.disabled=!0,Ue=!0)},Xe=async(t,e,o)=>{const{buttonTheme:a,customStyles:r,eventId:n,placement:s,desktopDisplay:d,feedbackLabel:c,surveyUuid:p,surveyId:l}=t;window.UserLeap.feedbackCustomStyles=void 0;let u=V();if(u){if(!e&&n===$)return;u.remove(),i.eventEmitter.off(i.EVENTS.SURVEY_FADING_OUT,ce)}$=n,K({document,elementId:"sprig-feedback-style",styleString:'.ul-loading-spinner-container{font-size:1.8rem;flex-grow:1;width:100%;height:100%;display:flex;align-items:center;justify-content:center}.ul-loading-spinner{display:inline-block;position:relative;width:6rem;height:6rem}.ul-loading-spinner div{box-sizing:border-box;display:block;position:absolute;width:80%;height:80%;margin:5px;border:5px solid #152e3e;border-radius:50%;animation:lds-ring 1.2s cubic-bezier(.5,0,.5,1) infinite;border-color:#152e3e transparent transparent transparent}.ul-loading-spinner .first{animation-delay:-.45s}.ul-loading-spinner .second{animation-delay:-.3s}.ul-loading-spinner .third{animation-delay:-.15s}@keyframes lds-ring{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.fade-in-transition{animation:fadeIn .4s ease-in}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}#sprig-feedback-button{border-left:0;border-radius:0 8px 8px 0;display:grid;padding:8px;text-align:center;transition:all ease-in-out 1s;z-index:inherit}#sprig-feedback-button:hover{cursor:pointer}.sprig-feedback-button-label{writing-mode:vertical-lr;text-orientation:sideways}.sprig-feedback-button-right{transform:rotate(180deg)}.sprig-feedback-button-bottom{align-self:flex-end;margin-bottom:20px}.sprig-feedback-button-light{background:#efefee;color:#000;border:1px solid #e2e3e1}.sprig-feedback-button-dark{background:#000;color:#fff;border:1px solid #000000}#sprig-feedback-container{display:flex;align-items:center;position:fixed;transition:right .2s linear,left .2s linear;z-index:2147483646}.sprig-feedback-container-left{flex-flow:row-reverse}.sprig-feedback-container-center{top:50%;transform:translateY(-50%)}.sprig-feedback-container-bottom{bottom:0%;margin-bottom:15px}.sprig-feedback-loading-container{align-items:center;background-color:#fff;border:2px solid var(--feedback-border);display:flex;max-height:90vh;max-width:90vw;min-width:0px}.sprig-feedback-loading-container-left{border-left:none;border-radius:0 8px 8px 0}.sprig-feedback-loading-container-right{border-right:none;border-radius:8px 0 0 8px}#sprig-feedback-error-container{margin:auto;text-align:center;width:360px}.sprig-feedback-error-text{font-weight:400;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol}#sprig-feedback-loading-container .ul-container{position:relative;max-height:inherit}#sprig-feedback-loading-animation{position:absolute}.sprig-feedback-loading-container-previews iframe{max-height:inherit!important}',nonce:window.UserLeap.styleNonce}),K({document,elementId:"ul-custom-style",styleString:r??"",nonce:window.UserLeap.styleNonce}),He=d==="center-modal",M=s;const[m,w]=s.split("-");(S=>{if(V()||!ft.includes(S))return;const[f,b]=S.split("-"),U=document.createElement("div");U.id="sprig-feedback-container",U.classList.add(`sprig-feedback-container-${b}`,`sprig-feedback-container-${f}`),document.body.appendChild(U)})(s),u=V(),C=document.createElement("button");const g=document.createElement("div");g.className="sprig-feedback-button-label",g.innerText=c,C.appendChild(g),C.id="sprig-feedback-button",C.classList.add(`sprig-feedback-button-${w}`,`sprig-feedback-button-${m}`,`sprig-feedback-button-${a}`,"fade-in-transition"),i.eventEmitter.on(i.EVENTS.SURVEY_FADING_OUT,ce),C.addEventListener("click",async()=>{const S=document.getElementById("sprig-feedback-error-container");if(Je()||Qe()){if(ce()){i.eventEmitter.emit(i.SprigEvent.SurveyWillClose,{name:i.SprigEvent.SurveyWillClose,initiator:i.DismissReason.FeedbackClosed,studyType:"feedbackButton","survey.id":l});const b=V();S&&b&&(b.remove(),$=null,y=null)}return}if(Se(i.getHttpHeaders(window.UserLeap))||Ue||Me(),e)return y&&y.classList.add("sprig-feedback-loading-container-previews"),await B(e),void z();const f=await(async b=>{const U=await O(R("1",[P],"startFeedbackStudy"),{body:JSON.stringify({surveyUuid:b}),method:"POST"});return U.ok?U.json:null})(p);if(f)i.eventEmitter.once(i.SprigEvent.SurveyAppeared,z),B({...f,studyType:"feedbackButton"},o);else if(y){const b=ht();y.appendChild(b),z(),y.style.height="300px",y.style.width="360px"}}),u==null||u.appendChild(C),i.eventEmitter.emit(i.SprigEvent.FeedbackButtonLoaded,{name:i.SprigEvent.FeedbackButtonLoaded,"survey.id":l});const{useMobileStyling:I,_config:{border:h}}=window.UserLeap;if(He||I)Z(0);else{const S=document.createElement("div");S.id="sprig-feedback-loading-container",S.className=`sprig-feedback-loading-container sprig-feedback-loading-container-${w}`,S.style.setProperty("--feedback-border",h),y=S,ge(),u==null||u.appendChild(S);const f=Ye();Z(-f)}window.UserLeap._config.isOnQuestionsTab&&e&&!X()&&y&&(Me(),ge(),y&&y.classList.add("sprig-feedback-loading-container-previews"),B(e),z())},ht=()=>{const t=document.createElement("div");t.id="sprig-feedback-error-container",t.innerHTML=`<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40" fill="none">
|
|
9
|
+
<circle cx="20" cy="20" r="14.5" stroke="#B0B5B7" stroke-width="3"/>
|
|
10
|
+
<path d="M20 12L20 21.6" stroke="#B0B5B7" stroke-width="3" stroke-linecap="round"/>
|
|
11
|
+
<circle cx="19.9984" cy="27.6" r="1.6" fill="#B0B5B7"/>
|
|
12
|
+
</svg>`;const e=document.createElement("h3");return e.className="sprig-feedback-error-text",e.innerText="There was an error while loading the survey",t.appendChild(e),t},me=new class{constructor(){q(this,"_ldData",{})}getAllLaunchDarklyVariations(){return this._ldData}setLDFlagsVariations(t){try{return!(!t||typeof t!="object"||Array.isArray(t))&&(Object.keys(this._ldData).forEach(e=>{delete this._ldData[e]}),Object.keys(t).forEach(e=>this._ldData[`!launch_darkly_${e}`]=(t[e]??0)+1),!0)}catch(e){return e instanceof Error&&window.UserLeap.reportError("setAllLDFlagsVariations",e),console.warn("[Sprig] An issue had occured when setting LaunchDarkly flags and variations."),!1}}};Object.freeze(me);const Y=new class{constructor(){q(this,"_optimizelyData",{})}setOptimizelyExperiment(t,e=!0){if(!t||typeof t!="object")return!1;const{experiments:o}=t;try{return e&&Object.keys(this._optimizelyData).map(a=>{delete this._optimizelyData[a]}),o&&o.map(a=>{const{id:r,variation:n}=a,s=this.transformExperimentId(r);n&&typeof n=="string"&&(this._optimizelyData[s]=n)}),!0}catch(a){return a instanceof Error&&window.UserLeap.reportError("setOptimizelyExperiment",a),!1}}getAllOptimizelyExperiments(){return this._optimizelyData}getOptimizelyVariationName(t){return this._optimizelyData[this.transformExperimentId(t)]}transformExperimentId(t){return"!optimizely_experiments_"+t}getAndSetWebOptimizelyExperiments(){var t;try{if(window&&window.optimizely&&typeof window.optimizely.get=="function"){const e=(t=window.optimizely.get("state"))==null?void 0:t.getExperimentStates({isActive:!0});if(e){const o=Object.keys(e).map(a=>{var r,n;return(r=e[a].variation)!=null&&r.name?{id:a,variation:(n=e[a].variation)==null?void 0:n.name}:{id:a,variation:"Original"}});return this.setOptimizelyExperiment({experiments:o},!1),!0}return!1}return!1}catch(e){return e instanceof Error&&window.UserLeap.reportError("getAndSetWebOptimizely",e),!1}}};Object.freeze(Y);class bt{constructor(e,o){q(this,"paused");q(this,"queue");q(this,"ul");this.ul=e,this.paused=!1,this.queue=[],this.flush(o)}flush(e){const o=e.length;if(o)for(let a=0;a<o;a++)this.push(e[a])}isPaused(){return this.paused}pause(){this.paused=!0}unpause(){this.paused=!1;const e=this.queue.slice();this.empty(),this.flush(e)}push(e){if(this.paused)this.queue.push(e);else if(e instanceof Function)e();else{const o=Array.prototype.slice.call(e,1),a=e[0],r=this.ul[a];r instanceof Function?r.apply(this.ul,o):a&&console.warn("[Sprig] (ERR-100) No valid UserLeap action called",a)}}perform(e){if(this.paused){let o=()=>{};const a=new Promise(function(r){o=function(){r(e())}});return this.queue.push(o),a}return e()}empty(){this.queue.length=0}}let Ze,et;const ye=t=>{let e=0,o=t.firstElementChild;for(;o;)e+=ye(o),o.shadowRoot&&(e+=ye(o.shadowRoot)),o=o.nextElementSibling,e++;return e},je=()=>{Ze.report(ye(document.body)),et.report(document.documentElement.innerHTML.length)},ve=(t,e)=>{const o=performance.now();document.hidden?setTimeout(()=>ve(t,e),t):setTimeout(()=>{const a=performance.now()-o;e.report(a/1e3),setTimeout(()=>ve(t,e),t)},0)};let ee,te,re,ie,Fe,j={};const Q=(t,e=1)=>{const{name:o}=t;j[o]=(j[o]||0)+e},tt=t=>{let e=1;return t.childNodes.forEach(o=>{e+=tt(o)}),e},qe=t=>{let e=0;return t.forEach(o=>{e+=tt(o)}),e},St=t=>{switch(t.type){case"childList":return Q(ee,qe(t.addedNodes)),void Q(te,qe(t.removedNodes));case"attributes":return void Q(re);case"characterData":return void Q(ie)}},Lt=t=>t.forEach(St),Ut=()=>{ee.report(j[ee.name]||0),te.report(j[te.name]||0),re.report(j[re.name]||0),ie.report(j[ie.name]||0),j={}},Et=(t=1e3)=>{ee=i.registerMetric("sdk_mutations_nodes_added"),te=i.registerMetric("sdk_mutations_nodes_removed"),re=i.registerMetric("sdk_mutations_attributes_changed"),ie=i.registerMetric("sdk_mutations_character_data"),Fe=new MutationObserver(Lt),Fe.observe(document,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),setInterval(Ut,t)},It=({isWeb:t,reportingIntervalSeconds:e,thresholds:o,postMetrics:a})=>{i.registerThresholds(o,(r,n)=>{var s,d;if((s=i.modules.replay)!=null&&s.isReplayRecording()){const c=`Value: ${r} on ${n.metric} violated threshold of ${n.type} ${n.value}`;(d=i.modules.replay)==null||d.disableRecording("Threshold violated",new Error(c),{reportError:!1}),window.UserLeap.reportError("Sdk Performance Metric threshold violated",new Error("Sdk Performance Metric threshold violated"),{metricName:n.metric,type:n.type,value:n.value},{metricName:n.metric}),i.disableThresholdChecking()}}),i.initPerformanceReporting({reportingIntervalSeconds:e,postMetrics:a}),t&&(((r=1e3)=>{const n=i.registerMetric("sdk_event_queue_latency_seconds");ve(r,n)})(),((r=1e4)=>{Ze=i.registerMetric("sdk_dom_nodes_count"),et=i.registerMetric("sdk_page_html_characters"),je(),setInterval(je,r)})(),Et())},kt="test",_t=["popState","pushState","replaceState"];let fe;const ne={},N="!email",rt="pageUrl";let pe=window.location.href;function G(t){var d;const{pageUrlEvents:e,interactiveEvents:o,dismissOnPageChange:a,platform:r}=window.UserLeap._config;if(r&&r!=="web")return;pe!==window.location.href&&i.breadcrumbsLogger.navigation("LocationChange",{from:pe,to:window.location.href}),pe=window.location.href;const n=ot().trackStartUrl,s=n?String(n):null;e&&at(window.location.href),o&&(nt(),Dt()),Ke()&&(()=>{if(X())return;const c=V();c&&(i.checkUrlStillMatching($)||(c.remove(),$=null,y=null))})(),i.sessionStorageHelper.getItem("sprig.isCapturingHeatmap")&&((d=i.modules.replay)==null||d.checkPendingHeatmapsUrl()),!X()&&a&&s&&s!==window.location.href&&t&&_t.includes(t.type)&&window.UserLeap("dismissActiveSurvey",i.DismissReason.PageChange)}const it={capture:!0},Dt=()=>{const t=window.UserLeap._config.interactiveEvents.filter(o=>i.checkUrlMatch(o,window.location.href)).map(o=>{const{name:a,properties:r}=o,{selector:n,innerText:s}=r;return n?d=>{if(Pe(d.target))try{d.target.closest(n)&&window.UserLeap("track",a)}catch{}return!1}:d=>(Pe(d.target)&&d.target.innerText===s&&window.UserLeap("track",a),!1)}),e=o=>t.forEach(a=>a(o));window.UserLeap._config.interactiveEventsHandler=e,window.addEventListener("click",e,it)},nt=()=>{window.UserLeap._config.interactiveEventsHandler&&window.removeEventListener("click",window.UserLeap._config.interactiveEventsHandler,it),delete window.UserLeap._config.interactiveEventsHandler};function ot(){const t=i.localStorageHelper.getItemObject("userleap.ids");return t&&t[window.UserLeap.envId]||{}}function st(){if(window.previewMode)return;const t=i.localStorageHelper.getItemObject("sprig.anon.env.vid.map")||{},e=t[window.UserLeap.envId];window.UserLeap.visitorId=e||i.v4(),i.breadcrumbsLogger.info("NewVid",{vid:window.UserLeap.visitorId}),k("vid",window.UserLeap.visitorId),e||(t[window.UserLeap.envId]=window.UserLeap.visitorId,i.localStorageHelper.setItemObject("sprig.anon.env.vid.map",t)),i.eventEmitter.emit(i.SprigEvent.VisitorIDUpdated,{visitorId:window.UserLeap.visitorId})}function at(t,e,o,a){var r,n;try{if(t.endsWith("mock_snippet.html"))return;i.breadcrumbsLogger.info("PageView",{url:t});const s=window.UserLeap._config.pageUrlEvents;let d=!1;if(s&&s.length)for(let l=0;l<s.length&&(d=i.checkUrlMatch(s[l],t),!d);l++);if(!d)return;window.UserLeap.debugMode&&console.info("[DEBUG] Sprig trackPageView",t);const c={url:t};a&&(c.trackPageView=!0),window.UserLeap._queue.push(["track",rt,e,c,o]);const p=(r=document==null?void 0:document.querySelector('meta[name="description"]'))==null?void 0:r.getAttribute("content");(n=i.modules.replay)==null||n.RecordPageView({...p&&{description:p},url:t,referrer:document.referrer,pageTitle:document.title})}catch(s){s instanceof Error&&(s.stack=t,window.UserLeap.reportError("trackPageView",s)),console.warn("[Sprig] (ERR-428) Failed to track page view",s)}}function Rt(){const t="Backbone"in window&&window.Backbone&&window.Backbone.history?window.Backbone.history:window.history;"pushState"in t&&(t.pushState=(e=>function(...o){const a=e.apply(this,o),r=new Event("pushState");return window.dispatchEvent(r),G(r),a})(t.pushState)),"replaceState"in t&&(t.replaceState=(e=>function(...o){const a=e.apply(this,o),r=new Event("replaceState");return window.dispatchEvent(r),G(r),a})(t.replaceState)),["hashchange","popstate"].forEach(e=>window.addEventListener(e,G,!0))}async function ue(t,e){const o=be();t&&!e&&(window.UserLeap._config.mode=kt);const a=Se(i.getHttpHeaders(window.UserLeap)),r=await O(function(n){const s=new URL(R("1",[T],"questions"));return Object.entries(n||{}).forEach(([d,c])=>{c&&s.searchParams.append(d,String(c))}),s.toString()}({desktopDisplay:window.UserLeap._config.desktopDisplay,isMobile:a,previewLanguage:window.UserLeap._config.previewLanguage,surveyid:t==null?void 0:t.surveyId,surveytemplateid:t==null?void 0:t.surveyTemplateId,vid:o}),{shouldDropOnRateLimit:!0});if(!r.ok)return r.reportError&&r.error&&(console.warn("[Sprig] (ERR-414) Failed to request questions from the server",r.error),window.UserLeap.reportError("getQuestions",r.error)),{success:!1,surveyState:"no survey"};if(r.json.delay&&await i.delay(r.json.delay),!r.json.isFeedback)return B(r.json,fe);{const{feedbackLabel:n,productConfig:s,surveyUuid:d,feedbackCustomStyles:c}=r.json,{buttonTheme:p,placement:l,desktopDisplay:u}=s;Xe({customStyles:c,buttonTheme:p,desktopDisplay:u,eventId:0,feedbackLabel:n,placement:l,surveyUuid:d,surveyId:t==null?void 0:t.surveyId},r.json)}}function xt(t){if(!t)return;window.UserLeap._config=t,t.mute&&window.UserLeap._queue.pause();const{interactiveEvents:e,pageUrlEvents:o,dismissOnPageChange:a}=t;e&&function(r){let n=r.length;for(;n;){const s=Math.floor(Math.random()*n);n-=1;const d=r[n];r[n]=r[s],r[s]=d}}(e),(e||o||a)&&(Rt(),G())}const At=function(t){if(!window.UserLeap)return;const e=async(r={})=>{var S,f,b,U,x;const{userId:n,anonymousId:s,metadata:d={},properties:c,showSurveyCallback:p}=r;let{eventName:l}=r;if(window.UserLeap.debugMode&&l!==rt&&console.info("[DEBUG] Sprig track",r),t.mode==="test")return;const u=i.localStorageHelper.getItem("sprig.previewKey")??void 0;if(t.requireUserIdForTracking&&!window.UserLeap.userId&&!n){const v="[Sprig] - Skipping tracking without userId";return console.warn(v),{success:!1,message:v,surveyState:"no survey"}}if(!l||l.trim().length===0){l=l?String(l):"";const v="[Sprig] - Invalid event name "+l;return console.warn(v),{success:!1,message:v,surveyState:"no survey"}}const m=fe??window.location.href;d.url||(d.url=m),k("trackStartUrl",m),(f=(S=window.UserLeap)==null?void 0:S._config)!=null&&f.optimizelyEnabled&&(se(i.getHttpHeaders(window.UserLeap))||Y.getAndSetWebOptimizelyExperiments(),d.optimizelyExperiments=Object.assign({},Y.getAllOptimizelyExperiments())),(U=(b=window.UserLeap)==null?void 0:b._config)!=null&&U.launchDarklyEnabled&&(d.launchDarklyFlags=me.getAllLaunchDarklyVariations()),n&&(window.UserLeap.userId=n),s&&(window.UserLeap.partnerAnonymousId=s),c&&(d.eventProperties=c),(x=i.modules.replay)==null||x.RecordEvent({name:l,url:d.url}),i.breadcrumbsLogger.info("TrackEvent",{eventName:l});const w=window.UserLeap.delayingSurvey||Je()?await O(R("1",[P],"events/batch"),{body:JSON.stringify({events:[{event:l,metadata:d}],previewKey:u}),method:"POST",shouldDropOnRateLimit:!0}):await O(R("1",[P],"events"),{body:JSON.stringify({event:l,metadata:d,previewKey:u}),method:"POST",shouldDropOnRateLimit:!0});if(!w.ok){const v="[Sprig] (ERR-421) Failed to track event";return w.reportError&&(console.warn(v,w.error),w.error&&window.UserLeap.reportError("track",w.error)),{success:!1,message:v,error:w.error,surveyState:"no survey"}}n&&k("uid",n),s&&k("aid",s);const g=w.json;g.invalidPreviewKey&&i.localStorageHelper.removeItem("sprig.previewKey");const I=d.trackPageView?d.url:void 0;return g!=null&&g.feedbackButton&&Xe(g.feedbackButton,void 0,I),await async function(v,E){var D,H;let _=!0;return!(E&&((D=v==null?void 0:v.json)!=null&&D.surveyId)&&(window.UserLeap.delayingSurvey=!0,_=await E(v.json.surveyId),window.UserLeap.delayingSurvey=!1,!_))&&((H=v==null?void 0:v.json)!=null&&H.delay&&!window.UserLeap.isMobileSDK&&(window.UserLeap.delayingSurvey=!0,await i.delay(v.json.delay),window.UserLeap.delayingSurvey=!1),_)}(w,p)?function(v,E){const{pageUrlEvents:_,interactiveEvents:D,dismissOnPageChange:H}=window.UserLeap._config;if(!H)return!0;const A=[];_&&_.length&&A.push(..._),D&&D.length&&A.push(...D);const J=v&&A.find(W=>W.id===v);return J?i.checkUrlMatch(J,window.location.href):E===window.location.href}(g.eventId,m)?B(g,I):{success:!1,message:"Study should not be displayed after page navigation",surveyState:"no survey"}:{success:!1,message:"[Sprig] Callback returned false, aborting rendering of survey",surveyState:"no survey"}},o=(r,n)=>{var d;const s=(d=r==null?void 0:r.querySelector(`[id="${Le}"]`))==null?void 0:d.contentDocument;s&&K({document:s,elementId:"ul-custom-style",styleString:n})},a={displaySurvey:async r=>(console.warn("[Sprig] displaySurvey should only be used to debug your studies; not intended for production usage."),window.UserLeap("dismissActiveSurvey",i.DismissReason.Override),ue({surveyId:r},!0)),_previewSurvey(r){window.UserLeap("dismissActiveSurvey",i.DismissReason.Override),ue({surveyTemplateId:r},!1)},_reviewSurvey(r){window.UserLeap("dismissActiveSurvey",i.DismissReason.Override),ue({surveyId:r},!1)},previewSurvey(r){a._previewSurvey(r)},reviewSurvey(r){a._reviewSurvey(r)},mute(){window.UserLeap._queue.pause()},unmute(){window.UserLeap._queue.unpause()},setVisitorToken(){console.warn("[Sprig] setVisitorToken is deprecated.")},dismissActiveSurvey(r=i.DismissReason.API){window.UserLeap.container&&i.eventEmitter.emit(i.SprigEvent.SurveyWillClose,{name:i.SprigEvent.SurveyWillClose,initiator:r,"survey.id":parseInt(window.UserLeap.container.dataset.studyId)})},async setAttribute(r,n){if(!r||!n&&n!==0&&n!==!1){const s="[Sprig] - Disregarding empty attribute / value provided";return console.warn(s),{success:!1,message:s}}return this.setAttributes({[r]:n})},async setAttributes(r){if(r==null||Object.keys(r).length===0){const n="[Sprig] - Disregarding empty attributes provided";return console.warn(n),{success:!1,message:n}}return this.identifyAndSetAttributes({attributes:r})},async identifyAndSetAttributes(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig identifyAndSetAttributes",r),t.mode==="test")return;if(r===null||typeof r!="object"||!(r.userId||r.anonymousId||r.attributes)){const l="[Sprig] - Disregarding empty payload provided";return console.warn(l),{success:!1,message:l}}const{userId:n,anonymousId:s,attributes:d}=r;if(t.requireUserIdForTracking&&!window.UserLeap.userId&&!n){const l="[Sprig] - Skipping tracking without userId";return console.warn(l),{success:!1,message:l}}if(d){d.email&&!d[N]&&(d[N]=d.email,delete d.email);const l=Object.keys(d);for(const u of l)d[u]===ne[u]&&delete d[u]}if(!(d&&Object.keys(d).length!==0||n&&window.UserLeap.userId!==n||s&&window.UserLeap.partnerAnonymousId!==s))return{success:!0};const c={};let p;return n&&(c.userId=window.UserLeap.userId=n),s&&(c.partnerAnonymousId=window.UserLeap.partnerAnonymousId=s),d&&Object.keys(d).length>0?(p=await O(R("1",[T,P],"attributes"),{body:JSON.stringify(d),method:"PUT"}),p.ok?Object.assign(ne,d):p.reportError&&(console.warn("[Sprig] (ERR-432) identifyAndSetAttributes failed",p.error),p.error&&window.UserLeap.reportError("identifyAndSetAttributes",p.error))):p=await O(R("1",[T,P]),{body:JSON.stringify(c),method:"PUT"}),d&&d[N]&&(window.UserLeap.email=d[N]),p.ok&&(n&&k("uid",n),s&&k("aid",s)),{success:!!p.ok}},async removeAttributes(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig removeAttributes",r),t.mode==="test")return;if(r==null||r.length===0){const s="[Sprig] - Disregarding empty attributes provided";return console.warn(s),{success:!1,message:s}}if(t.requireUserIdForTracking&&!window.UserLeap.userId){const s="[Sprig] - Skipping tracking without userId";return console.warn(s),{success:!1,message:s}}const n=await O(R("1",[T,P],"attributes"),{body:JSON.stringify({delete:r}),method:"DELETE"});return!n.ok&&n.reportError&&(console.warn("[Sprig] (ERR-433) Remove attributes failed",n.error),n.error&&window.UserLeap.reportError("removeAttributes",n.error)),{success:!!n.ok}},async addSurveyListener(r){i.eventEmitter.on(i.SprigEvent.SurveyLifeCycle,r)},async removeSurveyListener(r){i.eventEmitter.removeListener(i.SprigEvent.SurveyLifeCycle,r)},async addListener(r,n){i.eventEmitter.on(r,n)},async removeListener(r,n){i.eventEmitter.removeListener(r,n)},async removeAllListeners(){i.eventEmitter.removeAllListeners()},setPreviewKey(r){r&&typeof r=="string"&&i.localStorageHelper.isStorageAvailable&&r&&i.localStorageHelper.setItem("sprig.previewKey",r)},async setUserId(r){var d;if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig setUserId",r),r==null){const c=`[Sprig] - Invalid userId ${r}`;return console.warn(c),{success:!1,message:c}}if(t.mode==="test"||r===window.UserLeap.userId)return;window.UserLeap.userId=r;const n=window.UserLeap.visitorId,s=await O(R("1",[T,P]),{body:JSON.stringify({userId:r}),method:"PUT"});s.ok?(n!==window.UserLeap.visitorId&&((d=i.modules.replay)==null||d.clearUserReplayData()),k("uid",r)):s.reportError&&(console.warn("[Sprig] (ERR-420) Failed to set user id",s.error),s.error&&window.UserLeap.reportError("setUserId",s.error))},async setPartnerAnonymousId(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig setPartnerAnonymousId",r),r==null){const n=`[Sprig] - Invalid partnerAnonymousId ${r}`;return console.warn(n),{success:!1,message:n}}return window.UserLeap.partnerAnonymousId=r,k("aid",r),{success:!0}},track:async(r,n,s={},d=void 0)=>e({eventName:r,properties:n,metadata:s,showSurveyCallback:d}),identifyAndTrack:async r=>await e(r),trackPageView(r,n=void 0,s=void 0,d=!0){fe=r,at(r,n,s,d)},applyFeedbackStyles({button:r="",view:n=""}){window.UserLeap.feedbackCustomStyles=n,document.getElementById("sprig-feedback-style")&&K({document,elementId:"ul-custom-style",styleString:r,nonce:window.UserLeap.styleNonce}),o(document.querySelector(".ul-container-feedback"),n)},applyStyles(r){window.UserLeap.customStyles=r,o(window.UserLeap.container,r)},setWindowDimensions(r,n){var p,l;const s=typeof r=="string"?parseInt(r,10):r,d=typeof n=="string"?parseInt(n,10):n;if(isNaN(s)||isNaN(d)||(window.UserLeap.windowDimensions={width:s,height:d}),!window.UserLeap.frameId)return;const c=document.getElementById(window.UserLeap.frameId);c&&(window.UserLeap.useMobileStyling&&((p=window.UserLeap.windowDimensions)!=null&&p.width&&(c.style.width=`${window.UserLeap.windowDimensions.width}px`),(l=window.UserLeap.windowDimensions)!=null&&l.height&&(c.style.maxHeight=window.UserLeap.windowDimensions.height-20+"px"),c.contentDocument&&(c.style.height=String(Ge(c.contentDocument)[0])+"px")),i.eventEmitter.emit(i.SprigEvent.SurveyDimensions,{name:i.SprigEvent.SurveyDimensions,contentFrameWidth:c.clientWidth,contentFrameHeight:c.clientHeight,"survey.id":parseInt(window.UserLeap.container.dataset.studyId)}))},logoutUser(){var r;window.UserLeap.debugMode&&console.info("[DEBUG] Sprig logout"),i.breadcrumbsLogger.info("LogOut",{vid:window.UserLeap.visitorId,userId:window.UserLeap.userId}),window.UserLeap.visitorId=null,window.UserLeap.userId=null,window.UserLeap.partnerAnonymousId=null,window.UserLeap.token=null,window.UserLeap.email=null,i.localStorageHelper.removeItem("userleap.ids"),window.UserLeap._queue.isPaused()&&window.UserLeap._queue.empty(),st(),(r=i.modules.replay)==null||r.clearUserReplayData(),window.UserLeap._queue.unpause()},teardown(){["hashchange","popstate"].forEach(r=>window.removeEventListener(r,G,!0)),window.UserLeap._config.interactiveEvents&&nt(),window.UserLeap("dismissActiveSurvey",i.DismissReason.API),delete window.UserLeap,delete window.Sprig,delete window._Sprig},integrateOptimizely(r,n=!0){var s,d;if((d=(s=window.UserLeap)==null?void 0:s._config)!=null&&d.optimizelyEnabled)try{const c=typeof r=="string"?JSON.parse(r):r;Y.setOptimizelyExperiment(c,n)}catch(c){console.warn("[Sprig] Error with integrating Optimizely data"),c instanceof Error&&window.UserLeap.reportError("integrateOptimizely",c)}else console.warn("[SPRIG] Optimizely integration is currently not enabled for your product.")},integrateOptimizelyClient(r){var n,s;if(!((s=(n=window.UserLeap)==null?void 0:n._config)!=null&&s.optimizelyEnabled))return void console.warn("[SPRIG] Optimizely integration is currently not enabled for your product.");r.notificationCenter.addNotificationListener("ACTIVATE:experiment, user_id,attributes, variation, event",({experiment:d,variation:c})=>{const p={experiments:[{id:d.id,variation:c.key}]};window.UserLeap("integrateOptimizely",p,!1)})},importLaunchDarklyData(r){var n,s;(s=(n=window.UserLeap)==null?void 0:n._config)!=null&&s.launchDarklyEnabled?me.setLDFlagsVariations(r):console.warn("[SPRIG] LaunchDarkly integration is currently not enabled for your product.")},setVisitorAttribute:(r,n)=>(console.warn("[Sprig] setVisitorAttribute is deprecated. Please use setAttribute"),a.setAttribute(r,n)),setEmail:async r=>a.setAttribute(N,r),setVisitorEmail:async r=>(console.warn("[Sprig] setVisitorEmail is deprecated. Please use setEmail"),a.setEmail(r)),_generateVideoUploadUrl:async r=>async function(n){var d;if(!n)return;const s=`${window.UserLeap._API_URL}/2/environments/integrations/upload`;try{const c=await fetch(s,{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(c.ok){const p=await c.json();return(d=p==null?void 0:p.upload)==null?void 0:d.url}return null}catch(c){console.warn("[Sprig] Error with generating video upload url"),c instanceof Error&&window.UserLeap.reportError("generateVideoUploadUrl",c)}}(r),_reportMetric(r,n){i.reportAndRegister(r,n)},_completeSessionReplay:async({surveyId:r,responseGroupUuid:n,eventDigest:s})=>{var d;return i.modules.replay?(d=i.modules.replay)==null?void 0:d._completeSessionReplay({surveyId:r,responseGroupUuid:n,eventDigest:s,headers:i.getHttpHeaders(window.UserLeap)}):(window.UserLeap.reportError("_completeSessionReplay",new Error("Replay module not registered")),!1)}};Object.assign(window.UserLeap,a)};async function Ot(t,e,o={},a={}){const r=window.__cfg&&window.__cfg.mode,n=be(),s=window.UserLeap.envId,d=window.document.documentElement,c={mode:r,screenWidth:window.screen.width,screenHeight:window.screen.height,clientWidth:d.clientWidth,clientHeight:d.clientHeight,location:window.location.href,language:window.navigator.language,...o},p={action:t,breadcrumbs:i.breadcrumbsLogger.breadcrumbs,err:{message:`${e==null?void 0:e.name} - ${e==null?void 0:e.message}`,stack:e==null?void 0:e.stack},meta:c,vid:n,envId:s,...a};(await O(R("1",null,"errors"),{method:"POST",headers:{"x-ul-error":window.btoa(`userleap-${Date.now()}-error`)},body:JSON.stringify(p),shouldDropOnRateLimit:!0})).ok||console.warn("[Sprig] (ERR-444) Failed to report error to API",e)}function Ct(t={}){var a;(a=window.SprigLoggerCallback)==null||a.call(window,"Initializing Sprig");const e=new URLSearchParams(window.location.search).get("sprigPreviewKey")??"";async function o(){var u,m,w,g,I;if(window.UserLeap.loaded)return;if((u=window.SprigLoggerCallback)==null||u.call(window,"Loading Sprig"),window.UserLeap.reportError=Ot,window.UserLeap.loaded=!0,window.UserLeap._config=Object.assign({},t,window.UserLeap.config),window.UserLeap.delayingSurvey=!1,window.UserLeap._config&&typeof window.UserLeap._config=="object")for(const h in window.UserLeap._config)window.UserLeap[h]=window.UserLeap._config[h];if(!window.UserLeap.envId){if(!window.UserLeap.appId)throw new Error("Missing Environment id");window.UserLeap.envId=window.UserLeap.appId}window.UserLeap.debugMode&&console.info("[DEBUG] Sprig debug mode enabled");const r=ot(),n=window.UserLeap.sampleRate;let s=r.sampled;if(n){if(s===null&&(s=Math.random()<n,k("sampled",s)),!s)return}else s!==null&&k("sampled",null);window.UserLeap._API_URL||(window.UserLeap._API_URL="https://api.sprig.com");const d=[...window.UserLeap._queue];window.UserLeap._queue=new bt(window.UserLeap,[]),window.UserLeap._queue.pause();for(let h=0;h<d.length;h++)window.UserLeap._queue.push(d[h]);const c=r.token;c?(window.UserLeap.token=c,window.UserLeap.visitorId=r.vid??null,window.UserLeap.userId=r.uid??null,window.UserLeap.partnerAnonymousId=r.aid??null):st();const p=se(i.getHttpHeaders(window.UserLeap));(m=window.SprigLoggerCallback)==null||m.call(window,"Sprig fetching config");const l=await async function(h){var U,x;const S=i.getHttpHeaders(window.UserLeap);document.addEventListener("securitypolicyviolation",i.cspViolationHandler);const f=await i.sprigFetch(R("1",[T],"config"),{headers:S});if(document.removeEventListener("securitypolicyviolation",i.cspViolationHandler),!f.ok)return(U=window.SprigLoggerCallback)==null||U.call(window,"Sprig config fetch failed"),f.reportError&&(console.warn("[Sprig] (ERR-422) Failed to load configuration",f.error),f.error&&window.UserLeap.reportError("applyRemoteConfig",f.error)),i.killNetworkRequests("Disabled: failed to fetch configuration"),h;const b=f.json;return b!=null&&b.disabled?((x=window.SprigLoggerCallback)==null||x.call(window,"Sprig config fetch disabled"),i.killNetworkRequests(`Disabled: ${b.disabled}`),{disabled:b.disabled}):Object.assign({},b,h)}(t);(w=window.SprigLoggerCallback)==null||w.call(window,"Sprig fetched config"),It({isWeb:!p,reportingIntervalSeconds:l.metricsReportingEnabled||l.mobileMetricsReportingEnabled?l.metricsReportingIntervalSeconds:0,thresholds:l.metricThresholds,postMetrics:async h=>{var S;await O(R("1",[T],"metrics"),{body:h,method:"POST",headers:{"x-ul-replay-enabled":`${!!((S=i.modules.replay)!=null&&S.isReplayRecording())}`},shouldDropOnRateLimit:!0})}}),await((g=i.modules.replay)==null?void 0:g.initializeReplay({maxReplayDurationSeconds:l.maxReplayDurationSeconds,maxInflightRequests:window.UserLeap.maxInflightReplayRequests??2,replaySettings:l.replaySettings})),At(l),await xt(l),window.UserLeap._queue.unpause(),(I=window.SprigLoggerCallback)==null||I.call(window,"SdkReady"),i.eventEmitter.emit(i.SprigEvent.SDKReady,{mobileMetricsReportingEnabled:!!l.mobileMetricsReportingEnabled,metricsReportingInterval:l.metricsReportingIntervalSeconds||0,metricsThresholds:l.metricThresholds||[],maxMobileReplayDurationSeconds:l.maxMobileReplayDurationSeconds,mobileReplaySettings:l.mobileReplaySettings}),i.eventEmitter.emit(i.SprigEvent.VisitorIDUpdated,{visitorId:window.UserLeap.visitorId}),i.eventEmitter.on(i.SprigEvent.VisitorIDUpdated,()=>{for(const h in ne)delete ne[h]})}window.UserLeap.UPDATES=i.EVENTS,window.UserLeap("setPreviewKey",e),document.readyState==="complete"?o():window.attachEvent?window.attachEvent("onload",o):window.addEventListener("load",()=>{o()},!1)}class oe{constructor(){this.UPDATES=i.EVENTS}displaySurvey(e){window.Sprig("displaySurvey",e)}mute(){window.Sprig("mute")}unmute(){window.Sprig("unmute")}dismissActiveSurvey(){window.Sprig("dismissActiveSurvey")}setAttribute(e,o){window.Sprig("setAttribute",e,o)}setAttributes(e){window.Sprig("setAttributes",e)}identifyAndSetAttributes(e){window.Sprig("identifyAndSetAttributes",e)}removeAttributes(e){window.Sprig("removeAttributes",e)}addListener(e,o){window.Sprig("addListener",e,o)}removeListener(e,o){window.Sprig("removeListener",e,o)}removeAllListeners(){window.Sprig("removeAllListeners")}setEmail(e){window.Sprig("setAttribute","!email",e)}setUserId(e){window.Sprig("setUserId",e)}setPartnerAnonymousId(e){window.Sprig("setPartnerAnonymousId",e)}track(e,o={},a={}){window.Sprig("track",e,o,a)}identifyAndTrack(e){window.Sprig("identifyAndTrack",e)}trackPageView(e,o,a){window.Sprig("trackPageView",e,o,a)}applyStyles(e){window.Sprig("applyStyles",e)}setWindowDimensions(e,o){window.Sprig("setWindowDimensions",e,o)}logoutUser(){window.Sprig("logoutUser")}teardown(){window.Sprig("teardown")}}const he={configure:t=>{if(!t.envId&&!t.environmentId)throw new Error("Initialization Error: Sprig configure requires an environmentId");if(t.envId||(t.envId=t.environmentId??""),t.installationMethod="web-npm",window.Sprig)return window.Sprig;window.Sprig=function(){window.Sprig._queue.push(arguments)},Object.getOwnPropertyNames(oe.prototype).map(o=>{o!=="constructor"&&(window.Sprig[o]=oe.prototype[o])});const e=window.Sprig;return e.appId=t.envId,e._queue=[],window.UserLeap=e,Ct(t),window.Sprig}},Pt={sprig:he,SprigAPI:oe,configure:he.configure};exports.APP_ID="ul-app",exports.ConflictingWidgets=We,exports.DEFAULT_BORDER_COLOR="#e6e6e6",exports.DEFAULT_WIDTH=Ve,exports.EMBED_MOBILE_MAX_WIDTH=1030,exports.ERROR_BORDER_COLOR="#bd282a",exports.SprigAPI=oe,exports.calculateFrameDimensions=Ge,exports.core=Pt,exports.isHTMLElement=F,exports.resetScrollPosition=t=>{const e=t.querySelector(".ul-card__container");e&&(e.scrollTop=0)},exports.setSurveyStyles=K,exports.sprig=he;
|
package/dist/core.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("./metricsReporter-
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("./metricsReporter-D4pafvTR.cjs"),e=require("./core-gTCnh_sk.cjs");exports.DismissReason=i.DismissReason,exports.SprigEvent=i.SprigEvent,exports.SprigAPI=e.SprigAPI,exports.default=e.core,exports.sprig=e.sprig;
|
package/dist/core.d.ts
CHANGED
|
@@ -1066,6 +1066,7 @@ interface TextUrlPromptCard extends BaseCard {
|
|
|
1066
1066
|
promptActionType: PromptActionType;
|
|
1067
1067
|
required: boolean;
|
|
1068
1068
|
richTextBody: RichTextBody;
|
|
1069
|
+
questionHtml?: string;
|
|
1069
1070
|
};
|
|
1070
1071
|
routingOptions: RoutingOptions;
|
|
1071
1072
|
};
|
|
@@ -1091,6 +1092,7 @@ interface ConsentLegalCard extends BaseCard {
|
|
|
1091
1092
|
richTextBody: RichTextBody;
|
|
1092
1093
|
skipButtonText: string;
|
|
1093
1094
|
submitButtonText: string;
|
|
1095
|
+
questionHtml?: string;
|
|
1094
1096
|
};
|
|
1095
1097
|
routingOptions: RoutingOptions;
|
|
1096
1098
|
};
|
|
@@ -1923,6 +1925,7 @@ declare namespace sprigConfig {
|
|
|
1923
1925
|
mobileHeadersJSON?: string;
|
|
1924
1926
|
nonce?: string;
|
|
1925
1927
|
partnerAnonymousId: string | null;
|
|
1928
|
+
pointerDownTarget?: EventTarget | null;
|
|
1926
1929
|
replayLibraryURL?: string;
|
|
1927
1930
|
reportError: (
|
|
1928
1931
|
name: string,
|
|
@@ -1964,6 +1967,7 @@ declare global {
|
|
|
1964
1967
|
UserLeap: sprigConfig.WindowSprig;
|
|
1965
1968
|
rrwebRecord?: (typeof _rrweb_record)["record"];
|
|
1966
1969
|
sprigAPI?: object;
|
|
1970
|
+
SprigLoggerCallback?: (message: string) => void;
|
|
1967
1971
|
}
|
|
1968
1972
|
|
|
1969
1973
|
type WindowSprig = sprigConfig.WindowSprig;
|
package/dist/core.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { D as r, S as e } from "./metricsReporter-
|
|
2
|
-
import { S as o, c as p, s as t } from "./core-
|
|
1
|
+
import { D as r, S as e } from "./metricsReporter-Gimz6xcf.js";
|
|
2
|
+
import { S as o, c as p, s as t } from "./core-DsBuStDe.js";
|
|
3
3
|
export {
|
|
4
4
|
r as DismissReason,
|
|
5
5
|
o as SprigAPI,
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./core-
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./core-gTCnh_sk.cjs");require("./replay.cjs");const r=require("./metricsReporter-D4pafvTR.cjs");exports.SprigAPI=e.SprigAPI,exports.default=e.core,exports.sprig=e.sprig,exports.DismissReason=r.DismissReason,exports.SprigEvent=r.SprigEvent;
|
package/dist/index.d.ts
CHANGED
|
@@ -1066,6 +1066,7 @@ interface TextUrlPromptCard extends BaseCard {
|
|
|
1066
1066
|
promptActionType: PromptActionType;
|
|
1067
1067
|
required: boolean;
|
|
1068
1068
|
richTextBody: RichTextBody;
|
|
1069
|
+
questionHtml?: string;
|
|
1069
1070
|
};
|
|
1070
1071
|
routingOptions: RoutingOptions;
|
|
1071
1072
|
};
|
|
@@ -1091,6 +1092,7 @@ interface ConsentLegalCard extends BaseCard {
|
|
|
1091
1092
|
richTextBody: RichTextBody;
|
|
1092
1093
|
skipButtonText: string;
|
|
1093
1094
|
submitButtonText: string;
|
|
1095
|
+
questionHtml?: string;
|
|
1094
1096
|
};
|
|
1095
1097
|
routingOptions: RoutingOptions;
|
|
1096
1098
|
};
|
|
@@ -1923,6 +1925,7 @@ declare namespace sprigConfig {
|
|
|
1923
1925
|
mobileHeadersJSON?: string;
|
|
1924
1926
|
nonce?: string;
|
|
1925
1927
|
partnerAnonymousId: string | null;
|
|
1928
|
+
pointerDownTarget?: EventTarget | null;
|
|
1926
1929
|
replayLibraryURL?: string;
|
|
1927
1930
|
reportError: (
|
|
1928
1931
|
name: string,
|
|
@@ -1964,6 +1967,7 @@ declare global {
|
|
|
1964
1967
|
UserLeap: sprigConfig.WindowSprig;
|
|
1965
1968
|
rrwebRecord?: (typeof _rrweb_record)["record"];
|
|
1966
1969
|
sprigAPI?: object;
|
|
1970
|
+
SprigLoggerCallback?: (message: string) => void;
|
|
1967
1971
|
}
|
|
1968
1972
|
|
|
1969
1973
|
type WindowSprig = sprigConfig.WindowSprig;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { S as i, c as o, s as p } from "./core-
|
|
1
|
+
import { S as i, c as o, s as p } from "./core-DsBuStDe.js";
|
|
2
2
|
import "./replay.js";
|
|
3
|
-
import { D as t, S as m } from "./metricsReporter-
|
|
3
|
+
import { D as t, S as m } from "./metricsReporter-Gimz6xcf.js";
|
|
4
4
|
export {
|
|
5
5
|
t as DismissReason,
|
|
6
6
|
i as SprigAPI,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var Y=Object.defineProperty;var j=(e,t,r)=>t in e?Y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var l=(e,t,r)=>(j(e,typeof t!="symbol"?t+"":t,r),r);var U=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.FeedbackClosed="feedback.closed",e.PageChange="page.change",e.API="api",e.Override="override",e))(U||{}),A=(e=>(e.ReplayCapture="replay.capture",e.FeedbackButtonLoaded="feedback.button.loaded",e.SDKReady="sdk.ready",e.SurveyAppeared="survey.appeared",e.SurveyClosed="survey.closed",e.SurveyDimensions="survey.dimensions",e.SurveyFadingOut="survey.fadingOut",e.SurveyHeight="survey.height",e.SurveyPresented="survey.presented",e.SurveyLifeCycle="survey.lifeCycle",e.SurveyWidth="survey.width",e.SurveyWillClose="survey.willClose",e.SurveyWillPresent="survey.will.present",e.CloseSurveyOnOverlayClick="close.survey.overlayClick",e.VisitorIDUpdated="visitor.id.updated",e.QuestionAnswered="question.answered",e))(A||{});let m;const H=new Uint8Array(16);function B(){if(!m&&(m=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!m))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return m(H)}const a=[];for(let e=0;e<256;++e)a.push((e+256).toString(16).slice(1));const w={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)},b=new class{constructor(){l(this,"breadcrumbs",[])}getTimeStamp(){return new Date().toISOString()}addBreadcrumb(e){this.breadcrumbs.push(e),this.breadcrumbs.length>300&&this.breadcrumbs.shift()}debug(e,t="debug"){this.addBreadcrumb({category:t,level:"info",message:e,timestamp:this.getTimeStamp(),type:"debug"})}error(e,t={}){this.addBreadcrumb({category:"error",data:t,level:"error",message:e,timestamp:this.getTimeStamp(),type:"error"})}http(e,t){this.addBreadcrumb({category:"xhr",data:t,message:e,timestamp:this.getTimeStamp(),type:"http"})}info(e,t={}){this.addBreadcrumb({category:"info",data:t,level:"info",message:e,timestamp:this.getTimeStamp(),type:"info"})}navigation(e,t){this.addBreadcrumb({category:"navigation",data:t,message:e,timestamp:this.getTimeStamp(),type:"navigation"})}};var F=class extends Error{constructor(e,t,r){super(`Possible EventEmitter memory leak detected. ${r} ${t.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`),this.emitter=e,this.type=t,this.count=r,this.name="MaxListenersExceededWarning"}},D=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=D.defaultMaxListeners,this.hasWarnedAboutPotentialMemoryLeak=!1}_emitInternalEvent(e,t,r){this.emit(e,t,r)}_getListeners(e){return Array.prototype.concat.apply([],this.events.get(e))||[]}_removeListener(e,t){const r=e.indexOf(t);return r>-1&&e.splice(r,1),[]}_wrapOnceListener(e,t){const r=(...s)=>(this.removeListener(e,r),t.apply(this,s));return Object.defineProperty(r,"name",{value:t.name}),r}setMaxListeners(e){return this.maxListeners=e,this}getMaxListeners(){return this.maxListeners}eventNames(){return Array.from(this.events.keys())}emit(e,...t){const r=this._getListeners(e);return r.forEach(s=>{s.apply(this,t)}),r.length>0}addListener(e,t){this._emitInternalEvent("newListener",e,t);const r=this._getListeners(e).concat(t);if(this.events.set(e,r),this.maxListeners>0&&this.listenerCount(e)>this.maxListeners&&!this.hasWarnedAboutPotentialMemoryLeak){this.hasWarnedAboutPotentialMemoryLeak=!0;const s=new F(this,e,this.listenerCount(e));console.warn(s)}return this}on(e,t){return this.addListener(e,t)}once(e,t){return this.addListener(e,this._wrapOnceListener(e,t))}prependListener(e,t){const r=this._getListeners(e);if(r.length>0){const s=[t].concat(r);this.events.set(e,s)}else this.events.set(e,r.concat(t));return this}prependOnceListener(e,t){return this.prependListener(e,this._wrapOnceListener(e,t))}removeListener(e,t){const r=this._getListeners(e);return r.length>0&&(this._removeListener(r,t),this.events.set(e,r),this._emitInternalEvent("removeListener",e,t)),this}off(e,t){return this.removeListener(e,t)}removeAllListeners(e){return e?this.events.delete(e):this.events.clear(),this}listeners(e){return Array.from(this._getListeners(e))}listenerCount(e){return this._getListeners(e).length}rawListeners(e){return this.listeners(e)}},C=D;C.defaultMaxListeners=10;const q=new C,S=async e=>{await new Promise(t=>{setTimeout(t,e)})};class x{constructor(t){l(this,"storage");l(this,"tempStorage",{});l(this,"isStorageAvailable");this.storage=window[t],this.isStorageAvailable=this.checkIfStorageAvailable()}checkIfStorageAvailable(){try{const t="__storage_test__";return this.storage.setItem(t,t),this.storage.removeItem(t),!0}catch{return!1}}setItem(t,r){this.isStorageAvailable?this.storage.setItem(t,r):this.tempStorage[t]=r}setItemObject(t,r){try{this.setItem(t,JSON.stringify(r))}catch(s){s instanceof Error&&(s.stack=t+": "+r,window.UserLeap.reportError("Failed to save to local storage",s))}}getItem(t){return this.isStorageAvailable?this.storage.getItem(t):this.tempStorage[t]}getItemObject(t){const r=this.getItem(t);if(r)try{return JSON.parse(r)}catch(s){s instanceof Error&&(s.stack=t+": "+r,window.UserLeap.reportError("Failed to parse local storage",s))}return{}}removeItem(t){this.isStorageAvailable?this.storage.removeItem(t):delete this.tempStorage[t]}clear(){this.isStorageAvailable?this.storage.clear():this.tempStorage={}}}const J=new x("sessionStorage"),$=new x("localStorage");class K{constructor(t){l(this,"payload");l(this,"promise");l(this,"reject",()=>{});l(this,"resolve",()=>{});this.payload=t,this.promise=new Promise((r,s)=>{this.reject=s,this.resolve=r})}resolveRequest(t){this.resolve(t)}}const E={replay:null},G=()=>{const e=[];return E.replay&&e.push("replay"),e.join(",")},z=10;let T=!1,M="",g=!1,P=!1,y=[];const Q=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?"web-gtm":e._segment?"web-segment":"web-snippet",N=(e="")=>{T=!0,M=e},I=async({shouldDropOnRateLimit:e,...t})=>{if(e)return{status:429};{const r=new K(t);return y.push(r),r.promise}},v=async(e,t)=>{const{retries:r=0,shouldDropOnRateLimit:s=!1,shouldRetryRequest:n=!1,...i}=t,d={url:e,options:i,retries:r,shouldDropOnRateLimit:s};if(g&&!n)return I(d);const u={ok:!1,reportError:!1};if(T)return console.info(`UserLeap - ${M}`),u;try{const c=await fetch(e,i);if(c.status===429){if(!g&&!s||n){g=!0;const o=c.headers.has("ratelimit-reset")?Number(c.headers.get("ratelimit-reset")):z;return await S(1e3*o),v(e,{...i,shouldDropOnRateLimit:s,shouldRetryRequest:!0})}return I(d)}if(g=!1,y.length&&(y.map(o=>{const h=o.payload;v(h.url,{...h.options,retries:h.retries,shouldDropOnRateLimit:h.shouldDropOnRateLimit}).then(W=>{o.resolveRequest(W)})}),y=[]),c.ok){if(c.status===249)return N(),u;const o=await c.text();try{return o&&o!=="OK"&&(c.json=JSON.parse(o)),c}catch{return{ok:!1,reportError:!1,error:new Error(`failed parsing response json for ${e} - ${o}`)}}}return c}catch(c){const o=r+1;return o>5||P?{ok:!1,reportError:!1,error:c}:(await S(1e3*Math.pow(2,r)),v(e,{...i,retries:o}))}},R=Object.freeze({contains:(e,t)=>t.includes(e),notContains:(e,t)=>!t.includes(e),exactly:(e,t)=>t===e,notExactly:(e,t)=>t!==e,startsWith:(e,t)=>t.startsWith(e),endsWith:(e,t)=>t.endsWith(e),regex:(e,t)=>new RegExp(e).test(t),legacy:(e,t)=>new RegExp(e,"i").test(t)});function k(e,t){const{matchType:r,pattern:s}=e,n=r?R[r]:R.legacy;let i=!1;try{i=n(s,t)}catch(d){const u=`[Sprig] (ERR-445) Failed to check url match with pattern ${s}`;d instanceof Error&&(console.warn(u,d),d.stack=JSON.stringify(e),window.UserLeap.reportError(u,d))}return i}let V=!0,f=!1;const X=["sdk_event_queue_latency_seconds","sdk_replay_add_event_batch_seconds","sdk_replay_cleanup_seconds","sdk_replay_compression_seconds","sdk_replay_get_events_between_seconds","sdk_replay_snapshot_seconds","sdk_mutations_nodes_added","sdk_mutations_nodes_removed","sdk_mutations_attributes_changed","sdk_mutations_character_data","sdk_dom_nodes_count","sdk_page_html_characters"];let L,p={};class Z{constructor(t){l(this,"_values",[]);l(this,"_isWebMetric");this.name=t,this._isWebMetric=X.includes(this.name)}report(t){if(V&&this._values.push({time:Date.now(),value:t}),f||!this._isWebMetric)return;const r=this.findExceededThreshold(t);r&&L&&L(t,r)}collect(){const t=this._values;return this._values=[],t}findExceededThreshold(t){const r=p[this.name];if(r)return r.find(s=>this.valueExceedsThreshold(t,s))}valueExceedsThreshold(t,r){return r.type==="max"?t>r.value:r.type==="min"&&t<r.value}}const _={},O=e=>{const t=new Z(e);return _[e]=t,t};exports.DismissReason=U,exports.EVENTS={FEEDBACK_BUTTON_LOADED:"feedback.button.loaded",SDK_READY:"sdk.ready",SURVEY_APPEARED:"survey.appeared",SURVEY_CLOSED:"survey.closed",SURVEY_DIMENSIONS:"survey.dimensions",SURVEY_FADING_OUT:"survey.fadingOut",SURVEY_HEIGHT:"survey.height",SURVEY_WIDTH:"survey.width",SURVEY_PRESENTED:"survey.presented",SURVEY_LIFE_CYCLE:"survey.lifeCycle",SURVEY_WILL_CLOSE:"survey.willClose",SURVEY_WILL_PRESENT:"survey.will.present",QUESTION_ANSWERED:"question.answered",REPLAY_CAPTURE:"replay.capture",CLOSE_SURVEY_ON_OVERLAY_CLICK:"close.survey.overlayClick",VISITOR_ID_UPDATED:"visitor.id.updated",DATA:{DISMISS_REASONS:{API:"api",CLOSED:"close.click",COMPLETE:"survey.completed",PAGE_CHANGE:"page.change",OVERRIDE:"override"},SURVEY_ID:"survey.id"}},exports.PerformanceMetrics=_,exports.SprigEvent=A,exports.breadcrumbsLogger=b,exports.checkUrlMatch=k,exports.checkUrlStillMatching=e=>{const{pageUrlEvents:t}=window.UserLeap._config,r=t==null?void 0:t.find(s=>s.id===e);return!!r&&k(r,window.location.href)},exports.cspViolationHandler=e=>{var t;(t=e==null?void 0:e.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(P=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`))},exports.delay=S,exports.disableThresholdChecking=()=>f=!0,exports.eventEmitter=q,exports.getHttpHeaders=function(e={}){const t={"Content-Type":"application/json","userleap-platform":"web","x-ul-sdk-version":"2.32.3","x-ul-installation-method":Q(e),"sprig-modules":G()};if(e.envId&&(t["x-ul-environment-id"]=e.envId),e.token&&(t.Authorization="Bearer "+e.token),e.userId&&(t["x-ul-user-id"]=e.userId),e.visitorId&&(t["x-ul-visitor-id"]=e.visitorId),e.partnerAnonymousId&&(t["x-ul-anonymous-id"]=e.partnerAnonymousId),e.mobileHeadersJSON){const r=JSON.parse(e.mobileHeadersJSON);Object.assign(t,r)}return e.locale&&(t["accept-language"]=e.locale),window.previewMode&&(t["x-ul-preview-mode"]="1"),t},exports.initPerformanceReporting=({reportingIntervalSeconds:e,postMetrics:t})=>{e?setInterval(()=>{(async r=>{const s=Object.values(_).map(n=>({name:n.name,values:n.collect()}));if(s.some(n=>n.values.length))try{await r(JSON.stringify(s))}catch(n){n instanceof Error&&b.error("MetricsErr",{error:{message:n.message,name:n.name}})}})(t)},1e3*e):V=!1},exports.killNetworkRequests=N,exports.localStorageHelper=$,exports.modules=E,exports.registerMetric=O,exports.registerReplay=e=>{E.replay=e},exports.registerThresholds=(e,t)=>{p={},f=!1,e==null||e.forEach(r=>{var s;r.metric in p||(p[r.metric]=[]),(s=p[r.metric])==null||s.push(r)}),L=t},exports.reportAndRegister=(e,t)=>{let r=_[e];return r||(r=O(e)),r.report(t)},exports.sessionStorageHelper=J,exports.shouldDirectEmbed=({"userleap-platform":e})=>e!=="web",exports.sprigFetch=v,exports.v4=function(e,t,r){if(w.randomUUID&&!t&&!e)return w.randomUUID();const s=(e=e||{}).random||(e.rng||B)();return s[6]=15&s[6]|64,s[8]=63&s[8]|128,function(n,i=0){return a[n[i+0]]+a[n[i+1]]+a[n[i+2]]+a[n[i+3]]+"-"+a[n[i+4]]+a[n[i+5]]+"-"+a[n[i+6]]+a[n[i+7]]+"-"+a[n[i+8]]+a[n[i+9]]+"-"+a[n[i+10]]+a[n[i+11]]+a[n[i+12]]+a[n[i+13]]+a[n[i+14]]+a[n[i+15]]}(s)};
|
|
@@ -135,14 +135,14 @@ var j = class extends Error {
|
|
|
135
135
|
rawListeners(e) {
|
|
136
136
|
return this.listeners(e);
|
|
137
137
|
}
|
|
138
|
-
},
|
|
139
|
-
|
|
140
|
-
const ee = new
|
|
138
|
+
}, O = I;
|
|
139
|
+
O.defaultMaxListeners = 10;
|
|
140
|
+
const ee = new O(), L = async (e) => {
|
|
141
141
|
await new Promise((t) => {
|
|
142
142
|
setTimeout(t, e);
|
|
143
143
|
});
|
|
144
144
|
}, te = ({ "userleap-platform": e }) => e !== "web";
|
|
145
|
-
class
|
|
145
|
+
class R {
|
|
146
146
|
constructor(t) {
|
|
147
147
|
l(this, "storage");
|
|
148
148
|
l(this, "tempStorage", {});
|
|
@@ -160,9 +160,26 @@ class k {
|
|
|
160
160
|
setItem(t, s) {
|
|
161
161
|
this.isStorageAvailable ? this.storage.setItem(t, s) : this.tempStorage[t] = s;
|
|
162
162
|
}
|
|
163
|
+
setItemObject(t, s) {
|
|
164
|
+
try {
|
|
165
|
+
this.setItem(t, JSON.stringify(s));
|
|
166
|
+
} catch (r) {
|
|
167
|
+
r instanceof Error && (r.stack = t + ": " + s, window.UserLeap.reportError("Failed to save to local storage", r));
|
|
168
|
+
}
|
|
169
|
+
}
|
|
163
170
|
getItem(t) {
|
|
164
171
|
return this.isStorageAvailable ? this.storage.getItem(t) : this.tempStorage[t];
|
|
165
172
|
}
|
|
173
|
+
getItemObject(t) {
|
|
174
|
+
const s = this.getItem(t);
|
|
175
|
+
if (s)
|
|
176
|
+
try {
|
|
177
|
+
return JSON.parse(s);
|
|
178
|
+
} catch (r) {
|
|
179
|
+
r instanceof Error && (r.stack = t + ": " + s, window.UserLeap.reportError("Failed to parse local storage", r));
|
|
180
|
+
}
|
|
181
|
+
return {};
|
|
182
|
+
}
|
|
166
183
|
removeItem(t) {
|
|
167
184
|
this.isStorageAvailable ? this.storage.removeItem(t) : delete this.tempStorage[t];
|
|
168
185
|
}
|
|
@@ -170,7 +187,7 @@ class k {
|
|
|
170
187
|
this.isStorageAvailable ? this.storage.clear() : this.tempStorage = {};
|
|
171
188
|
}
|
|
172
189
|
}
|
|
173
|
-
const se = new
|
|
190
|
+
const se = new R("sessionStorage"), re = new R("localStorage");
|
|
174
191
|
class B {
|
|
175
192
|
constructor(t) {
|
|
176
193
|
l(this, "payload");
|
|
@@ -187,21 +204,21 @@ class B {
|
|
|
187
204
|
this.resolve(t);
|
|
188
205
|
}
|
|
189
206
|
}
|
|
190
|
-
const
|
|
191
|
-
|
|
192
|
-
},
|
|
207
|
+
const k = { replay: null }, ne = (e) => {
|
|
208
|
+
k.replay = e;
|
|
209
|
+
}, F = () => {
|
|
193
210
|
const e = [];
|
|
194
|
-
return
|
|
195
|
-
},
|
|
196
|
-
let A = !1, U = "", y = !1, D = !1,
|
|
197
|
-
const
|
|
211
|
+
return k.replay && e.push("replay"), e.join(",");
|
|
212
|
+
}, q = 10;
|
|
213
|
+
let A = !1, U = "", y = !1, D = !1, g = [];
|
|
214
|
+
const J = (e) => e._config && e._config.installationMethod ? e._config.installationMethod : e._gtm ? "web-gtm" : e._segment ? "web-segment" : "web-snippet", ie = (e) => {
|
|
198
215
|
var t;
|
|
199
216
|
(t = e == null ? void 0 : e.blockedURI) != null && t.includes(window.UserLeap._API_URL) && (D = !0, console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`));
|
|
200
|
-
},
|
|
217
|
+
}, H = (e = "") => {
|
|
201
218
|
A = !0, U = e;
|
|
202
219
|
};
|
|
203
220
|
function ae(e = {}) {
|
|
204
|
-
const t = { "Content-Type": "application/json", "userleap-platform": "web", "x-ul-sdk-version": "2.32.
|
|
221
|
+
const t = { "Content-Type": "application/json", "userleap-platform": "web", "x-ul-sdk-version": "2.32.3", "x-ul-installation-method": J(e), "sprig-modules": F() };
|
|
205
222
|
if (e.envId && (t["x-ul-environment-id"] = e.envId), e.token && (t.Authorization = "Bearer " + e.token), e.userId && (t["x-ul-user-id"] = e.userId), e.visitorId && (t["x-ul-visitor-id"] = e.visitorId), e.partnerAnonymousId && (t["x-ul-anonymous-id"] = e.partnerAnonymousId), e.mobileHeadersJSON) {
|
|
206
223
|
const s = JSON.parse(e.mobileHeadersJSON);
|
|
207
224
|
Object.assign(t, s);
|
|
@@ -213,9 +230,9 @@ const w = async ({ shouldDropOnRateLimit: e, ...t }) => {
|
|
|
213
230
|
return { status: 429 };
|
|
214
231
|
{
|
|
215
232
|
const s = new B(t);
|
|
216
|
-
return
|
|
233
|
+
return g.push(s), s.promise;
|
|
217
234
|
}
|
|
218
|
-
},
|
|
235
|
+
}, v = async (e, t) => {
|
|
219
236
|
const { retries: s = 0, shouldDropOnRateLimit: r = !1, shouldRetryRequest: n = !1, ...i } = t, d = { url: e, options: i, retries: s, shouldDropOnRateLimit: r };
|
|
220
237
|
if (y && !n)
|
|
221
238
|
return w(d);
|
|
@@ -227,19 +244,19 @@ const w = async ({ shouldDropOnRateLimit: e, ...t }) => {
|
|
|
227
244
|
if (c.status === 429) {
|
|
228
245
|
if (!y && !r || n) {
|
|
229
246
|
y = !0;
|
|
230
|
-
const o = c.headers.has("ratelimit-reset") ? Number(c.headers.get("ratelimit-reset")) :
|
|
231
|
-
return await L(1e3 * o),
|
|
247
|
+
const o = c.headers.has("ratelimit-reset") ? Number(c.headers.get("ratelimit-reset")) : q;
|
|
248
|
+
return await L(1e3 * o), v(e, { ...i, shouldDropOnRateLimit: r, shouldRetryRequest: !0 });
|
|
232
249
|
}
|
|
233
250
|
return w(d);
|
|
234
251
|
}
|
|
235
|
-
if (y = !1,
|
|
252
|
+
if (y = !1, g.length && (g.map((o) => {
|
|
236
253
|
const h = o.payload;
|
|
237
|
-
|
|
254
|
+
v(h.url, { ...h.options, retries: h.retries, shouldDropOnRateLimit: h.shouldDropOnRateLimit }).then((x) => {
|
|
238
255
|
o.resolveRequest(x);
|
|
239
256
|
});
|
|
240
|
-
}),
|
|
257
|
+
}), g = []), c.ok) {
|
|
241
258
|
if (c.status === 249)
|
|
242
|
-
return
|
|
259
|
+
return H(), u;
|
|
243
260
|
const o = await c.text();
|
|
244
261
|
try {
|
|
245
262
|
return o && o !== "OK" && (c.json = JSON.parse(o)), c;
|
|
@@ -250,10 +267,10 @@ const w = async ({ shouldDropOnRateLimit: e, ...t }) => {
|
|
|
250
267
|
return c;
|
|
251
268
|
} catch (c) {
|
|
252
269
|
const o = s + 1;
|
|
253
|
-
return o > 5 || D ? { ok: !1, reportError: !1, error: c } : (await L(1e3 * Math.pow(2, s)),
|
|
270
|
+
return o > 5 || D ? { ok: !1, reportError: !1, error: c } : (await L(1e3 * Math.pow(2, s)), v(e, { ...i, retries: o }));
|
|
254
271
|
}
|
|
255
272
|
}, b = Object.freeze({ contains: (e, t) => t.includes(e), notContains: (e, t) => !t.includes(e), exactly: (e, t) => t === e, notExactly: (e, t) => t !== e, startsWith: (e, t) => t.startsWith(e), endsWith: (e, t) => t.endsWith(e), regex: (e, t) => new RegExp(e).test(t), legacy: (e, t) => new RegExp(e, "i").test(t) });
|
|
256
|
-
function
|
|
273
|
+
function $(e, t) {
|
|
257
274
|
const { matchType: s, pattern: r } = e, n = s ? b[s] : b.legacy;
|
|
258
275
|
let i = !1;
|
|
259
276
|
try {
|
|
@@ -266,7 +283,7 @@ function J(e, t) {
|
|
|
266
283
|
}
|
|
267
284
|
const oe = (e) => {
|
|
268
285
|
const { pageUrlEvents: t } = window.UserLeap._config, s = t == null ? void 0 : t.find((r) => r.id === e);
|
|
269
|
-
return !!s &&
|
|
286
|
+
return !!s && $(s, window.location.href);
|
|
270
287
|
};
|
|
271
288
|
let C = !0, S = !1;
|
|
272
289
|
const ce = () => S = !0, K = ["sdk_event_queue_latency_seconds", "sdk_replay_add_event_batch_seconds", "sdk_replay_cleanup_seconds", "sdk_replay_compression_seconds", "sdk_replay_get_events_between_seconds", "sdk_replay_snapshot_seconds", "sdk_mutations_nodes_added", "sdk_mutations_nodes_removed", "sdk_mutations_attributes_changed", "sdk_mutations_character_data", "sdk_dom_nodes_count", "sdk_page_html_characters"];
|
|
@@ -337,12 +354,12 @@ export {
|
|
|
337
354
|
ue as j,
|
|
338
355
|
ce as k,
|
|
339
356
|
re as l,
|
|
340
|
-
|
|
357
|
+
k as m,
|
|
341
358
|
ie as n,
|
|
342
|
-
|
|
343
|
-
|
|
359
|
+
H as o,
|
|
360
|
+
$ as p,
|
|
344
361
|
L as q,
|
|
345
362
|
z as r,
|
|
346
|
-
|
|
363
|
+
v as s,
|
|
347
364
|
Z as v
|
|
348
365
|
};
|
package/dist/replay.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Se=Object.defineProperty;var De=(e,t,r)=>t in e?Se(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var _=(e,t,r)=>(De(e,typeof t!="symbol"?t+"":t,r),r);const o=require("./metricsReporter-CiE5uf1B.cjs");var R=(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))(R||{});const ne=new class{constructor(e){_(this,"awaitingResolvers",[]);_(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),ae=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},H=(e,t)=>t.some(r=>e instanceof r);let J,Q;const M=new WeakMap,A=new WeakMap,U=new WeakMap;let O={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return M.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return D(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&(t==="done"||t==="store")||t in e};function se(e){O=e(O)}function Ee(e){return(Q||(Q=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(F(this),t),D(this.request)}:function(...t){return D(e.apply(F(this),t))}}function ke(e){return typeof e=="function"?Ee(e):(e instanceof IDBTransaction&&function(t){if(M.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});M.set(t,r)}(e),H(e,J||(J=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,O):e)}function D(e){if(e instanceof IDBRequest)return function(r){const n=new Promise((a,s)=>{r.onsuccess=()=>{a(D(r.result))},r.onerror=()=>{s(r.error)}});return U.set(n,r),n}(e);if(A.has(e))return A.get(e);const t=ke(e);return t!==e&&(A.set(e,t),U.set(t,e)),t}const F=e=>U.get(e);function j(e,{blocked:t}={}){const r=indexedDB.deleteDatabase(e);return t&&(r.onblocked=n=>t(n.oldVersion,n)),D(r).then(()=>{})}const Ce=["get","getKey","getAll","getAllKeys","count"],Re=["put","add","delete","clear"],N=new Map;function X(e,t){if(!(e instanceof IDBDatabase)||t in e||typeof t!="string")return;if(N.get(t))return N.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,a=Re.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!a&&!Ce.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 N.set(t,s),s}se(e=>({...e,get:(t,r,n)=>X(t,r)||e.get(t,r,n),has:(t,r)=>!!X(t,r)||e.has(t,r)}));const Pe=["continue","continuePrimaryKey","advance"],Y={},V=new WeakMap,oe=new WeakMap,xe={get(e,t){if(!Pe.includes(t))return e[t];let r=Y[t];return r||(r=Y[t]=function(...n){V.set(this,oe.get(this)[t](...n))}),r}};async function*Be(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const r=new Proxy(t,xe);for(oe.set(r,t),U.set(r,F(t));t;)yield r,t=await(V.get(r)||t.continue()),V.delete(r)}function Z(e,t){return t===Symbol.asyncIterator&&H(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&H(e,[IDBIndex,IDBObjectStore])}se(e=>({...e,get:(t,r,n)=>Z(t,r)?Be:e.get(t,r,n),has:(t,r)=>Z(t,r)||e.has(t,r)}));const Ue=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},ie=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=Ue(r)}return"/"+t.reverse().map(r=>r.position!==null?`/${r.name}[${r.position}]`:`/${r.name}`).join("")},S={capture:!0,passive:!0},Le=["a","button","input","option","li","link"],Te=["Escape","Enter","Backspace","F5","Tab"];let L=!1;const _e=["label","type","role","title","placeholder","errormessage","valuetext","href"],Ae="aria-",ee=e=>{var n;if(((n=e.tagName)==null?void 0:n.toLowerCase())==="html")return{element:"html"};const t=e.textContent,r=t?{text:t}:{};r.element=(a=>{if(!a.tagName)return"No tagName";const s=a.getAttribute("type");return s?`${s} ${a.tagName.toLowerCase()}`:a.tagName.toLowerCase()})(e);for(const a of e.attributes){let s=a.name;const i=a.value;s.startsWith(Ae)&&(s=s.substring(5)),_e.includes(s)&&(r[s]=i)}return r},Ne=e=>{var n;if(!e)return{};const t={...ee(e)},r=e.parentElement;if(r&&Le.includes((n=r.tagName)==null?void 0:n.toLowerCase())){const a=ee(r);Object.assign(t,a)}return t},de=(e,t)=>{var r;Me({x:t.x,y:t.y,type:e,elementAttributes:Ne(t.target),windowHeight:window.innerHeight,windowWidth:window.innerWidth,...t.target instanceof HTMLElement?{rect:(r=t.target)==null?void 0:r.getBoundingClientRect(),xPath:ie(t.target)}:{}})},ce=e=>{Te.includes(e.key)&&je({key:e.key})},ue=((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),Ve({xPath:ie(t),x:t.scrollLeft,y:t.scrollTop,elementAttributes:{targetScrollWidth:t.scrollWidth,targetClientWidth:t.clientWidth,targetScrollHeight:t.scrollHeight,targetClientHeight:t.clientHeight}})},750),le=(te="left_click",e=>de(te,e));var te;const pe=e=>{e.button===2&&de("right_click",e)},He=()=>{L||(window.addEventListener("click",le,S),window.addEventListener("mousedown",pe,S),window.addEventListener("keydown",ce,S),window.addEventListener("scroll",ue,S),L=!0,window.performance.getEntriesByType("navigation").map(e=>e.type).includes("reload")&&Oe({url:window.location.href,currentPageTitle:document.title}),window.performance.getEntriesByType("navigation").map(e=>e.type).includes("back_forward")&&Fe({curUrl:window.location.href,fromUrl:document.referrer,currentPageTitle:document.title}))},p={isRecording:!1,scrollEventUuids:{},stopRecording:()=>{}},y=(()=>{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})(),K=()=>{o.sessionStorageHelper.setItem("sprig.disableReplayRecording","disabled")},b=()=>!!o.sessionStorageHelper.getItem("sprig.disableReplayRecording");window.addEventListener("beforeunload",()=>{o.breadcrumbsLogger.info("BeforeUnload",{sessionId:y}),o.sessionStorageHelper.setItem("sprig.sessionId",y)});const z=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),I=(e,t)=>{var r,n;if(!b()&&p.isRecording)try{(n=(r=window.rrwebRecord)==null?void 0:r.addCustomEvent)==null||n.call(r,e,t)}catch(a){T("Error recording custom event",a)}},Me=e=>{var t;(t=e==null?void 0:e.elementAttributes)!=null&&t.text&&(e.elementAttributes.text=z(e.elementAttributes.text)),I("Sprig_Click",e)},Oe=e=>{I("Sprig_Refresh",e)},Fe=e=>{e.currentPageTitle&&(e.currentPageTitle=z(e.currentPageTitle)),I("Sprig_BackForward",e)},je=e=>{I("Sprig_Keystroke",e)},Ve=async e=>{const{x:t,xPath:r,y:n}=e,a=p.scrollEventUuids[r];if(a)return h(async()=>{var c,d,u,w;const s=await l.openDB(),i=await s.get("events",a);if(i!=null&&i.event){const g=JSON.parse(i.event),f=t>((d=(c=g.data)==null?void 0:c.payload)==null?void 0:d.x),m=n>((w=(u=g.data)==null?void 0:u.payload)==null?void 0:w.y);if(!f&&!m)return null;f&&(g.data.payload.x=t),m&&(g.data.payload.y=n),g.data.payload.elementAttributes=e.elementAttributes,i.event=JSON.stringify(g),await s.put("events",i)}else I("Sprig_Scroll",e)},"Error updating scroll event");I("Sprig_Scroll",e)},ge=()=>{p.stopRecording&&(p.stopRecording(),p.stopRecording=void 0),p.isRecording=!1,["cleanupInterval","inactivityInterval","pendingCheckInterval"].forEach(e=>{p[e]&&(clearInterval(p[e]),p[e]=void 0)}),L&&(window.removeEventListener("click",le,S),window.removeEventListener("mousedown",pe,S),window.removeEventListener("keydown",ce,S),window.removeEventListener("scroll",ue,S),L=!1)},Ke=["did not allow mutations","called in an invalid security context"],Ge=(e,t,{reportError:r=!0,extraInfo:n={}})=>{if(!b()&&t instanceof Error){if(K(),t.name==="VersionError")return o.breadcrumbsLogger.error("VersionErr",{message:e}),l.deleteDB();(a=>{if(!a)return!0;for(const s of Ke)if(a.toLowerCase().includes(s))return!1;return!0})(t==null?void 0:t.message)&&(r&&window.UserLeap.reportError(e,t,n),l.clearAll())}},T=(e,t,{reportError:r}={reportError:!0})=>{ge(),o.breadcrumbsLogger.error("ReplayErr",{code:t.code,name:t.name}),Ge(e,t,{reportError:r})},h=async(e,t)=>{try{await e()}catch(r){T(t,r)}};j("replayStorage").catch(console.error),j("sprig.replay").catch(console.error);const l=new class{openDB(){return function(e,t,{blocked:r,upgrade:n,blocking:a,terminated:s}={}){const i=indexedDB.open(e,t),c=D(i);return n&&(i.onupgradeneeded=d=>{n(D(i.result),d.oldVersion,d.newVersion,D(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"])}}})}deleteDB(){return j("sprigReplay").catch(console.error)}async bulkAdd(e,t){const r=(await this.openDB()).transaction(e,"readwrite");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 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.openDB()).transaction(e,"readwrite"),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.openDB()).transaction(e,"readwrite"),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.openDB()).transaction(e,"readwrite"),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([y,e],[y,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.openDB()).transaction("events","readwrite"),i=s.store.index("[sessionId+timestamp]"),c=IDBKeyRange.bound([y,e],[y,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.openDB()).transaction("chunkUploads","readwrite");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"),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",y)).filter(r=>!e.beforePresent||r.targetTimestamp<Date.now()).filter(r=>!e.isHeatmap||(r.captureParams.isHeatmap??!1))}async markPendingCaptureToCanUpload(e){const t=(await this.openDB()).transaction("pendingCaptures","readwrite"),r=t.store.index("sessionId");for await(const n of r.iterate(y)){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.openDB()).transaction("pendingCaptures","readwrite"),n=r.store.index("sessionId");for await(const a of n.iterate(y)){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}},me=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},we=(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 ye=5e3,G=6e4,W=0,E,$=!1,q=[];const We=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;p.scrollEventUuids[s]=e.uuid}q.push(e),$||$e()},$e=()=>{$=!0,setTimeout(async()=>{if(b())return;const e=q;q=[],$=!1,we(async()=>{await(async t=>{const r=t.map(n=>({...n,sessionId:n.sessionId??y}));if(r.length!==0)return h(()=>l.bulkAdd("events",r),"Error storing replay events")})(e)},"sdk_replay_add_event_batch_seconds")},500)},qe=(e,t,r)=>{p.cleanupInterval=window.setInterval(()=>{const n=Date.now();me(()=>h(async()=>{b()||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)},ze=()=>{p.pendingCheckInterval=window.setInterval(async()=>{h(async()=>{const e=parseInt(E??"0");if(e===0)return;const t=await l.getPendingCaptures({beforePresent:!0}),r=await l.openDB();await Promise.all(t.map(async n=>(await r.delete("pendingCaptures",n.uuid),Ie(n.captureParams,n.canUpload)))),E=(e-t.length).toString(),o.sessionStorageHelper.setItem("sprig.pendingCount",E)},"Error initiating pending captures")},5e3)},Je=async(e,t,r,n,a)=>{const s=Math.min(e+a,r),i=await me(()=>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}},fe=e=>Promise.all(e.map(async t=>{const r=await(async n=>ne.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})),he=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 ae({apiUrl:a.apiUrl,surveyId:a.surveyId,uploadId:e,responseGroupUuid:a.responseGroupId,etags:n,headers:a.completeUploadHeaders,replayDuration:a.replayDuration}),await l.deleteChunkUploads("UploadComplete",e)},Qe=()=>{h(async()=>{const e=await l.getChunkUploadsByStatus({sessionId:y,status:"ReadyForUpload"});if(!(e!=null&&e.length))return;const t=await fe(e);t!=null&&t.length&&await Promise.all(t.map(r=>{if(r)return he(r)}))},"Error uploading unfinished chunks")},Xe=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,[g,f]=[0,0],m=[];for(let k=n-35e3;k<a;k+=G){if({validStartFound:w,events:m}=await Je(k,n,a,w,G),!(m!=null&&m.length)){o.breadcrumbsLogger.debug("NoEventsFound");continue}g===0&&(g=m[0].timestamp),f=m[m.length-1].timestamp;const P=m.map(C=>C.event);P.push(`{"timestamp":${a}}`);const x=`${u?",":"["}${P}`,B=s.encode(x);we(()=>{d.write(B)},"sdk_replay_compression_seconds"),u=!0}if(f-g<ye)return o.breadcrumbsLogger.debug("ReplayTooShort"),null;const v=s.encode("]");return d.write(v),d.close(),i=new Uint8Array(await new Response(c.readable).arrayBuffer()),i})(r-e,r)},re=async e=>{const{surveyId:t,responseGroupId:r,visitorId:n,apiUrl:a,completeUploadHeaders:s,replayParams:i,triggerTimestamp:c}=e,d=await Xe(1e3*i.replayDurationSeconds,c);if(!(d!=null&&d.length))return void o.breadcrumbsLogger.info("FileDataEmpty",{surveyId:t});const u=((g,f,m)=>{const v=g.length,k=1024*f*1024,P=Math.ceil(v/m),x=Math.max(k,P),B=[];let C=0;for(;C<v;)B.push(g.slice(C,C+x)),C+=x;return B})(d,i.minimumChunkSizeMb,i.signedUrls.length),w=await Promise.all(u.map(async(g,f)=>{const m=o.v4(),v={apiUrl:a,chunkIndex:f+1,completeUploadHeaders:s,etag:null,responseGroupId:r,status:"ReadyForUpload",surveyId:t,timestamp:c,totalChunks:u.length,data:g,uploadId:i.uploadId,uploadUrl:i.signedUrls[f].url,uuid:m,visitorId:n};return await(await l.openDB()).add("chunkUploads",{...v,sessionId:v.sessionId??y}),v}));await(async(g,f)=>{await fe(f),await Promise.all(g.map(m=>he(m)))})([i.uploadId],w)},Ie=async(e,t)=>{if(b())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),h(async()=>{a.replayDurationType==="before"?await re(e):await l.markPendingCaptureToCanUpload(i)},"Error in schedule/capture callback")};h(async()=>{if(a.replayDurationType==="after"||a.replayDurationType==="beforeAndAfter")return!n&&!r&&o.eventEmitter.on(o.SprigEvent.QuestionAnswered,c),void await ve(e);if(n||r||t)await re(e),r&&Ye();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")},Ye=async()=>{parseInt(E??"0")||o.sessionStorageHelper.removeItem("sprig.isCapturingHeatmap"),o.sessionStorageHelper.getItem("sprig.teardownAfterCapture")&&(ge(),be(),o.sessionStorageHelper.removeItem("sprig.teardownAfterCapture"))},be=async()=>b()?o.breadcrumbsLogger.debug("ReplayDisabled-ClearData"):Promise.all([l.deleteBySessionId("events",y),l.deleteBySessionId("pendingCaptures",y)]).catch(e=>{T("Error clearing user replay data",e)}),ve=async e=>{if(b())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&&(p.isRecording&&h(()=>{var d,u;return(u=(d=window.rrwebRecord)==null?void 0:d.takeFullSnapshot)==null?void 0:u.call(d,!0)},"Error recording full snapshot"),o.sessionStorageHelper.setItem("sprig.isCapturingHeatmap","true"),W=Date.now(),p.inactivityInterval||(p.inactivityInterval=window.setInterval(()=>{var d;d=W,Date.now()-d>=3e4&&h(()=>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,E=(parseInt(E??"0")+1).toString(),o.sessionStorageHelper.setItem("sprig.pendingCount",E),await(await l.openDB()).add("pendingCaptures",{canUpload:!1,captureParams:s,sessionId:y,targetTimestamp:i,timestamp:Date.now(),uuid:o.v4()})},Ze=Object.freeze(Object.defineProperty({__proto__:null,RecordEvent:e=>{I("Sprig_TrackEvent",e)},RecordPageView:e=>{e.description&&(e.description=z(e.description)),I("Sprig_PageView",e)},RecordSurveyShown:e=>{I("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 ae({surveyId:e,responseGroupUuid:t,eventDigest:r,apiUrl:a,headers:n},!0);return!(s!=null&&s.error)},checkPendingHeatmapsUrl:()=>b()?o.breadcrumbsLogger.debug("ReplayDisabled-PendingHeatmaps"):h(async()=>{const e=(await l.getPendingCaptures({isHeatmap:!0})).map(r=>({eventId:r.captureParams.eventId,uuid:r.uuid})),t=[];e.forEach(({eventId:r,uuid:n})=>{o.checkUrlStillMatching(r)||t.push(n)}),t.length&&await l.markPendingHeatmapsReady(t)},"Error marking pending heatmaps ready"),clearUserReplayData:be,disableRecording:T,initializeReplay:async({maxReplayDurationSeconds:e,maxInflightRequests:t=2,replaySettings:r,teardownAfter:n=!1})=>{if(E=o.sessionStorageHelper.getItem("sprig.pendingCount"),!p.isRecording){if(n&&o.sessionStorageHelper.setItem("sprig.teardownAfterCapture","true"),b())return o.breadcrumbsLogger.debug("ReplayDisabled");if(await(async()=>{var a;if(!window.indexedDB||!window.IDBKeyRange||!window.CompressionStream)return!0;if((a=window.navigator.storage)!=null&&a.estimate)try{const{quota:s=0,usage:i=0}=await window.navigator.storage.estimate(),c=(s-i)/1024**3;return o.breadcrumbsLogger.info("Storage",{availableGb:c}),c<.5}catch{return!0}return!1})())return o.breadcrumbsLogger.debug("IDBNotSupported"),K();try{const a=await l.openDB();o.breadcrumbsLogger.info("DBVersion",{version:a.version})}catch(a){return o.breadcrumbsLogger.error("ReplayOpenErr",{name:a.name}),a.name==="VersionError"&&l.deleteDB(),K()}if(!e)return o.breadcrumbsLogger.debug("MissingDuration");o.breadcrumbsLogger.debug("ReplayInit"),await h(async()=>{var a;if(r!=null&&r.minDuration&&(ye=r.minDuration),r!=null&&r.batchDuration&&(G=r.batchDuration),a=t,ne.setLimit(a),Qe(),qe(e+35,1800,e+35),ze(),!window.rrwebRecord){const{record:d}=await import(window.UserLeap.replayLibraryURL??"https://cdn.sprig.com/dependencies/record-2.0.0-alpha.17.min.js");window.rrwebRecord=d}const s=window.rrwebRecord;if(!s)return o.breadcrumbsLogger.error("RecordScriptFailed");let i=!0,c=0;p.stopRecording=s({checkoutEveryNms:3e4,sampling:{input:"last",scroll:250,media:800},emit:(d,u)=>{if(d.type===R.Custom&&(W=Date.now()),b())return;if(u&&d.type===R.Meta)c=performance.now();else if(u&&c&&d.type===R.FullSnapshot){const g=performance.now()-c;o.reportAndRegister("sdk_replay_snapshot_seconds",g/1e3)}const w=i||!!u&&d.type===R.Meta;i=!1,We({uuid:o.v4(),event:JSON.stringify(d),isValidStart:w,timestamp:Date.now()})},...r}),p.isRecording=!!p.stopRecording,p.isRecording&&(o.eventEmitter.on("survey.complete",d=>{var u;u={id:d,userAgent:window.navigator.userAgent},I("Sprig_SubmitSurvey",u)}),He())},"Error initializing replay")}},isReplayRecording:()=>p.isRecording,scheduleCapture:ve,scheduleOrCaptureReplay:Ie,tryReplayAction:h},Symbol.toStringTag,{value:"Module"}));o.registerReplay(Ze);
|
|
1
|
+
"use strict";var Ee=Object.defineProperty;var ke=(e,t,r)=>t in e?Ee(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var _=(e,t,r)=>(ke(e,typeof t!="symbol"?t+"":t,r),r);const s=require("./metricsReporter-D4pafvTR.cjs");var P=(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))(P||{});const ne=new class{constructor(e){_(this,"awaitingResolvers",[]);_(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),ae=async({apiUrl:e,surveyId:t,uploadId:r,etags:n,headers:a,responseGroupUuid:o,replayDuration:i,eventDigest:c},d=!1)=>{var w;if(!d&&!r&&!n)return void s.breadcrumbsLogger.error("UploadErr",{isMobile:d,uploadId:r,etags:n});s.breadcrumbsLogger.info("MarkUploadComplete",{surveyId:t});const u=await s.sprigFetch(`${e}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:n,uploadId:r,responseGroupUuid:o,surveyId:t,replayDuration:i,eventDigest:c,userAgent:(w=window==null?void 0:window.navigator)==null?void 0:w.userAgent}),headers:a,shouldRetryRequest:!0});return s.breadcrumbsLogger.info("MarkUploadDone",{surveyId:t}),u},H=(e,t)=>t.some(r=>e instanceof r);let J,Q;const M=new WeakMap,A=new WeakMap,U=new WeakMap;let O={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return M.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return D(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&(t==="done"||t==="store")||t in e};function oe(e){O=e(O)}function Ce(e){return(Q||(Q=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(F(this),t),D(this.request)}:function(...t){return D(e.apply(F(this),t))}}function Pe(e){return typeof e=="function"?Ce(e):(e instanceof IDBTransaction&&function(t){if(M.has(t))return;const r=new Promise((n,a)=>{const o=()=>{a(t.error||new DOMException("AbortError","AbortError"))};t.oncomplete=()=>{n()},t.onerror=o,t.onabort=o});M.set(t,r)}(e),H(e,J||(J=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,O):e)}function D(e){if(e instanceof IDBRequest)return function(r){const n=new Promise((a,o)=>{r.onsuccess=()=>{a(D(r.result))},r.onerror=()=>{o(r.error)}});return U.set(n,r),n}(e);if(A.has(e))return A.get(e);const t=Pe(e);return t!==e&&(A.set(e,t),U.set(t,e)),t}const F=e=>U.get(e);function j(e,{blocked:t}={}){const r=indexedDB.deleteDatabase(e);return t&&(r.onblocked=n=>t(n.oldVersion,n)),D(r).then(()=>{})}const Re=["get","getKey","getAll","getAllKeys","count"],Be=["put","add","delete","clear"],N=new Map;function X(e,t){if(!(e instanceof IDBDatabase)||t in e||typeof t!="string")return;if(N.get(t))return N.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,a=Be.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!a&&!Re.includes(r))return;const o=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 N.set(t,o),o}oe(e=>({...e,get:(t,r,n)=>X(t,r)||e.get(t,r,n),has:(t,r)=>!!X(t,r)||e.has(t,r)}));const xe=["continue","continuePrimaryKey","advance"],Y={},V=new WeakMap,se=new WeakMap,Ue={get(e,t){if(!xe.includes(t))return e[t];let r=Y[t];return r||(r=Y[t]=function(...n){V.set(this,se.get(this)[t](...n))}),r}};async function*Le(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const r=new Proxy(t,Ue);for(se.set(r,t),U.set(r,F(t));t;)yield r,t=await(V.get(r)||t.continue()),V.delete(r)}function Z(e,t){return t===Symbol.asyncIterator&&H(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&H(e,[IDBIndex,IDBObjectStore])}oe(e=>({...e,get:(t,r,n)=>Z(t,r)?Le:e.get(t,r,n),has:(t,r)=>Z(t,r)||e.has(t,r)}));const Te=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},ie=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=Te(r)}return"/"+t.reverse().map(r=>r.position!==null?`/${r.name}[${r.position}]`:`/${r.name}`).join("")},I={capture:!0,passive:!0},_e=["a","button","input","option","li","link"],Ae=["Escape","Enter","Backspace","F5","Tab"];let L=!1;const Ne=["label","type","role","title","placeholder","errormessage","valuetext","href"],He="aria-",ee=e=>{var n;if(((n=e.tagName)==null?void 0:n.toLowerCase())==="html")return{element:"html"};const t=e.textContent,r=t?{text:t}:{};r.element=(a=>{if(!a.tagName)return"No tagName";const o=a.getAttribute("type");return o?`${o} ${a.tagName.toLowerCase()}`:a.tagName.toLowerCase()})(e);for(const a of e.attributes){let o=a.name;const i=a.value;o.startsWith(He)&&(o=o.substring(5)),Ne.includes(o)&&(r[o]=i)}return r},Me=e=>{var n;if(!e)return{};const t={...ee(e)},r=e.parentElement;if(r&&_e.includes((n=r.tagName)==null?void 0:n.toLowerCase())){const a=ee(r);Object.assign(t,a)}return t},de=(e,t)=>{var n;let r=t.target;t.target===((n=window.document)==null?void 0:n.body)&&window.Sprig.pointerDownTarget&&(r=window.Sprig.pointerDownTarget),Fe({x:t.x,y:t.y,type:e,elementAttributes:Me(r),windowHeight:window.innerHeight,windowWidth:window.innerWidth,...r instanceof HTMLElement?{rect:r==null?void 0:r.getBoundingClientRect(),xPath:ie(r)}:{}})},ce=e=>{Ae.includes(e.key)&&Ke({key:e.key})},ue=((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),Ge({xPath:ie(t),x:t.scrollLeft,y:t.scrollTop,elementAttributes:{targetScrollWidth:t.scrollWidth,targetClientWidth:t.clientWidth,targetScrollHeight:t.scrollHeight,targetClientHeight:t.clientHeight}})},750),le=(te="left_click",e=>de(te,e));var te;const pe=e=>{e.button===2&&de("right_click",e)},ge=e=>{window.Sprig&&(window.Sprig.pointerDownTarget=e.target)},Oe=()=>{L||(window.addEventListener("click",le,I),window.addEventListener("pointerdown",ge,I),window.addEventListener("mousedown",pe,I),window.addEventListener("keydown",ce,I),window.addEventListener("scroll",ue,I),L=!0,window.performance.getEntriesByType("navigation").map(e=>e.type).includes("reload")&&je({url:window.location.href,currentPageTitle:document.title}),window.performance.getEntriesByType("navigation").map(e=>e.type).includes("back_forward")&&Ve({curUrl:window.location.href,fromUrl:document.referrer,currentPageTitle:document.title}))},p={isRecording:!1,scrollEventUuids:{},stopRecording:()=>{}},y=(()=>{const e=s.sessionStorageHelper.getItem("sprig.sessionId");if(e)return s.breadcrumbsLogger.info("SessionIDFound",{savedSessionId:e}),s.sessionStorageHelper.removeItem("sprig.sessionId"),e;const t=s.v4();return s.breadcrumbsLogger.info("GeneratedSessionID",{uuid:t}),t})(),K=()=>{s.sessionStorageHelper.setItem("sprig.disableReplayRecording","disabled")},v=()=>!!s.sessionStorageHelper.getItem("sprig.disableReplayRecording");window.addEventListener("beforeunload",()=>{s.breadcrumbsLogger.info("BeforeUnload",{sessionId:y}),s.sessionStorageHelper.setItem("sprig.sessionId",y)});const z=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),b=(e,t)=>{var r,n;if(!v()&&p.isRecording)try{(n=(r=window.rrwebRecord)==null?void 0:r.addCustomEvent)==null||n.call(r,e,t)}catch(a){T("Error recording custom event",a)}},Fe=e=>{var t;(t=e==null?void 0:e.elementAttributes)!=null&&t.text&&(e.elementAttributes.text=z(e.elementAttributes.text)),b("Sprig_Click",e)},je=e=>{b("Sprig_Refresh",e)},Ve=e=>{e.currentPageTitle&&(e.currentPageTitle=z(e.currentPageTitle)),b("Sprig_BackForward",e)},Ke=e=>{b("Sprig_Keystroke",e)},Ge=async e=>{const{x:t,xPath:r,y:n}=e,a=p.scrollEventUuids[r];if(a)return f(async()=>{var c,d,u,w;const o=await l.openDB(),i=await o.get("events",a);if(i!=null&&i.event){const g=JSON.parse(i.event),h=t>((d=(c=g.data)==null?void 0:c.payload)==null?void 0:d.x),m=n>((w=(u=g.data)==null?void 0:u.payload)==null?void 0:w.y);if(!h&&!m)return null;h&&(g.data.payload.x=t),m&&(g.data.payload.y=n),g.data.payload.elementAttributes=e.elementAttributes,i.event=JSON.stringify(g),await o.put("events",i)}else b("Sprig_Scroll",e)},"Error updating scroll event");b("Sprig_Scroll",e)},me=()=>{p.stopRecording&&(p.stopRecording(),p.stopRecording=void 0),p.isRecording=!1,["cleanupInterval","inactivityInterval","pendingCheckInterval"].forEach(e=>{p[e]&&(clearInterval(p[e]),p[e]=void 0)}),L&&(window.removeEventListener("click",le,I),window.removeEventListener("pointerdown",ge,I),window.removeEventListener("mousedown",pe,I),window.removeEventListener("keydown",ce,I),window.removeEventListener("scroll",ue,I),L=!1)},We=["did not allow mutations","called in an invalid security context"],$e=(e,t,{reportError:r=!0,extraInfo:n={}})=>{if(!v()&&t instanceof Error){if(K(),t.name==="VersionError")return s.breadcrumbsLogger.error("VersionErr",{message:e}),l.deleteDB();(a=>{if(!a)return!0;for(const o of We)if(a.toLowerCase().includes(o))return!1;return!0})(t==null?void 0:t.message)&&(r&&window.UserLeap.reportError(e,t,n),l.clearAll())}},T=(e,t,{reportError:r}={reportError:!0})=>{me(),s.breadcrumbsLogger.error("ReplayErr",{code:t.code,name:t.name}),$e(e,t,{reportError:r})},f=async(e,t)=>{try{await e()}catch(r){T(t,r)}};j("replayStorage").catch(console.error),j("sprig.replay").catch(console.error);const l=new class{openDB(){return function(e,t,{blocked:r,upgrade:n,blocking:a,terminated:o}={}){const i=indexedDB.open(e,t),c=D(i);return n&&(i.onupgradeneeded=d=>{n(D(i.result),d.oldVersion,d.newVersion,D(i.transaction),d)}),r&&(i.onblocked=d=>r(d.oldVersion,d.newVersion,d)),c.then(d=>{o&&(d.onclose=()=>o()),a&&(d.onversionchange=u=>a(u.oldVersion,u.newVersion,u))}).catch(()=>{}),c}("sprigReplay",1,{upgrade:(e,t,r)=>{if(r===0&&s.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"])}}})}deleteDB(){return j("sprigReplay").catch(console.error)}async bulkAdd(e,t){const r=(await this.openDB()).transaction(e,"readwrite");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 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.openDB()).transaction(e,"readwrite"),a=n.store.index("sessionId");for await(const o of a.iterate(r))await o.delete();await n.done}async updatePartial(e,t,r){const n=(await this.openDB()).transaction(e,"readwrite"),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.openDB()).transaction(e,"readwrite"),o=a.store.index("timestamp");for await(const i of o.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([y,e],[y,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)),o=(await this.openDB()).transaction("events","readwrite"),i=o.store.index("[sessionId+timestamp]"),c=IDBKeyRange.bound([y,e],[y,t],!1,!0);for await(const d of i.iterate(c))await d.update({...d.value,expiredAt:a});await o.done}async deleteChunkUploads(e,t){const r=IDBKeyRange.only([t,e]),n=(await this.openDB()).transaction("chunkUploads","readwrite");let o=await n.store.index("[uploadId+status]").openCursor(r);for(;o;)o.delete(),o=await o.continue();await n.done}async getChunkUploadsByStatus({sessionId:e,status:t,uploadId:r}){const n=(await this.openDB()).transaction("chunkUploads","readonly"),a=r?n.store.index("[uploadId+status]"):n.store.index("[sessionId+status]"),o=r?IDBKeyRange.only([r,t]):IDBKeyRange.only([e,t]);return a.getAll(o)}async getPendingCaptures(e={}){return(await(await this.openDB()).getAllFromIndex("pendingCaptures","sessionId",y)).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.openDB()).transaction("pendingCaptures","readwrite"),r=t.store.index("sessionId");for await(const n of r.iterate(y)){const a=n.value;a.captureParams.responseGroupId===e&&await n.update({...a,canUpload:!0})}await t.done}async markPendingHeatmapsReady(e){if(parseInt(s.sessionStorageHelper.getItem("sprig.pendingCount")??"0")===0)return null;const t=Date.now(),r=(await this.openDB()).transaction("pendingCaptures","readwrite"),n=r.store.index("sessionId");for await(const a of n.iterate(y)){const o=a.value;!o.captureParams.isHeatmap||e&&!e.includes(o.uuid)||await a.update({...o,targetTimestamp:t,captureParams:{...o.captureParams,triggerTimestamp:t,replayParams:{...o.captureParams.replayParams,replayDurationSeconds:Math.floor((t-o.timestamp)/1e3)}}})}await r.done}},we=async(e,t)=>{const r=performance.now();let n;try{n=await e()}finally{const a=performance.now()-r;let o=s.PerformanceMetrics[t];o||(o=s.registerMetric(t)),o.report(a/1e3)}return n},ye=(e,t)=>{const r=performance.now();try{e()}finally{const n=performance.now()-r;let a=s.PerformanceMetrics[t];a||(a=s.registerMetric(t)),a.report(n/1e3)}};let fe=5e3,G=6e4,W=0,E,$=!1,q=[];const qe=e=>{var t,r,n,a;if((t=e.event)!=null&&t.includes("Sprig_Scroll")){const o=(a=(n=(r=JSON.parse(e.event))==null?void 0:r.data)==null?void 0:n.payload)==null?void 0:a.xPath;if(!o)return;p.scrollEventUuids[o]=e.uuid}q.push(e),$||ze()},ze=()=>{$=!0,setTimeout(async()=>{if(v())return;const e=q;q=[],$=!1,ye(async()=>{await(async t=>{const r=t.map(n=>({...n,sessionId:n.sessionId??y}));if(r.length!==0)return f(()=>l.bulkAdd("events",r),"Error storing replay events")})(e)},"sdk_replay_add_event_batch_seconds")},500)},Je=(e,t,r)=>{p.cleanupInterval=window.setInterval(()=>{const n=Date.now();we(()=>f(async()=>{v()||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"),s.breadcrumbsLogger.debug("CleanupComplete")},3e4)},Qe=()=>{p.pendingCheckInterval=window.setInterval(async()=>{f(async()=>{await he()},"Error initiating pending captures")},5e3)},he=async(e=!1)=>{const t=parseInt(E??"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),ve(a.captureParams,a.canUpload)))),E=(t-r.length).toString(),s.sessionStorageHelper.setItem("sprig.pendingCount",E)},Xe=async(e,t,r,n,a)=>{const o=Math.min(e+a,r),i=await we(()=>l.getEventsBetween(e,o),"sdk_replay_get_events_between_seconds");if(!(i!=null&&i.length))return s.breadcrumbsLogger.debug("NoEventsFound"),{validStartFound:n,events:[]};if(!n){s.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?(s.breadcrumbsLogger.debug("ValidStartNotFound"),{validStartFound:n,events:[]}):{validStartFound:!0,events:i==null?void 0:i.slice(c)}}return{validStartFound:n,events:i}},Ie=e=>Promise.all(e.map(async t=>{const r=await(async n=>ne.execute(async()=>{var i;s.breadcrumbsLogger.info("UploadChunkStart",{chunkIndex:n.chunkIndex,surveyId:n.surveyId});const a=await s.sprigFetch(n.uploadUrl,{body:n.data,method:"PUT"});s.breadcrumbsLogger.http("UploadChunkEnd",{url:n.uploadUrl,method:"PUT",status_code:a.status,reason:a.statusText??"OK",chunkIndex:n.chunkIndex,surveyId:n.surveyId});const o=(i=a.headers)==null?void 0:i.get("ETag");if(!o)throw new Error(`Upload response did not include etag for upload ${n.uploadId}, part ${n.chunkIndex}`);return o}))(t);return await l.updatePartial("chunkUploads",t.uuid,{data:null,etag:r,status:"UploadComplete"}),t.uploadId})),be=async e=>{const t=await l.getChunkUploadsByStatus({status:"UploadComplete",uploadId:e});if(!(t!=null&&t.length))return void s.breadcrumbsLogger.info("NoChunksForUpload",{uploadId:e});const r=t.reduce((o,i)=>(o.find(c=>c.chunkIndex===i.chunkIndex)||o.push(i),o),[]);r.sort((o,i)=>o.chunkIndex-i.chunkIndex);const n=r.map(o=>({ETag:o.etag,PartNumber:o.chunkIndex})).filter(o=>o.ETag!==null),a=r[0];await ae({apiUrl:a.apiUrl,surveyId:a.surveyId,uploadId:e,responseGroupUuid:a.responseGroupId,etags:n,headers:a.completeUploadHeaders,replayDuration:a.replayDuration}),await l.deleteChunkUploads("UploadComplete",e)},Ye=()=>{f(async()=>{const e=await l.getChunkUploadsByStatus({sessionId:y,status:"ReadyForUpload"});if(!(e!=null&&e.length))return;const t=await Ie(e);t!=null&&t.length&&await Promise.all(t.map(r=>{if(r)return be(r)}))},"Error uploading unfinished chunks")},Ze=async(e,t)=>{const r=t??Date.now();return(async(n,a)=>{const o=new TextEncoder;let i=null;const c=new CompressionStream("gzip"),d=c.writable.getWriter();let u=!1,w=!1,[g,h]=[0,0],m=[];for(let k=n-35e3;k<a;k+=G){if({validStartFound:w,events:m}=await Xe(k,n,a,w,G),!(m!=null&&m.length)){s.breadcrumbsLogger.debug("NoEventsFound");continue}g===0&&(g=m[0].timestamp),h=m[m.length-1].timestamp;const R=m.map(C=>C.event);R.push(`{"timestamp":${a}}`);const B=`${u?",":"["}${R}`,x=o.encode(B);ye(()=>{d.write(x)},"sdk_replay_compression_seconds"),u=!0}if(h-g<fe)return s.breadcrumbsLogger.debug("ReplayTooShort"),null;const S=o.encode("]");return d.write(S),d.close(),i=new Uint8Array(await new Response(c.readable).arrayBuffer()),i})(r-e,r)},re=async e=>{const{surveyId:t,responseGroupId:r,visitorId:n,apiUrl:a,completeUploadHeaders:o,replayParams:i,triggerTimestamp:c}=e,d=await Ze(1e3*i.replayDurationSeconds,c);if(!(d!=null&&d.length))return void s.breadcrumbsLogger.info("FileDataEmpty",{surveyId:t});const u=((g,h,m)=>{const S=g.length,k=1024*h*1024,R=Math.ceil(S/m),B=Math.max(k,R),x=[];let C=0;for(;C<S;)x.push(g.slice(C,C+B)),C+=B;return x})(d,i.minimumChunkSizeMb,i.signedUrls.length),w=await Promise.all(u.map(async(g,h)=>{const m=s.v4(),S={apiUrl:a,chunkIndex:h+1,completeUploadHeaders:o,etag:null,responseGroupId:r,status:"ReadyForUpload",surveyId:t,timestamp:c,totalChunks:u.length,data:g,uploadId:i.uploadId,uploadUrl:i.signedUrls[h].url,uuid:m,visitorId:n};return await(await l.openDB()).add("chunkUploads",{...S,sessionId:S.sessionId??y}),S}));await(async(g,h)=>{await Ie(h),await Promise.all(g.map(m=>be(m)))})([i.uploadId],w)},ve=async(e,t)=>{if(v())return s.breadcrumbsLogger.debug("ReplayDisabled-ScheduleOrCapture");const{isHeatmap:r,isStandalone:n,replayParams:a,triggerTimestamp:o,responseGroupId:i}=e,c=async()=>{setTimeout(()=>s.eventEmitter.removeListener(s.SprigEvent.QuestionAnswered,c),0),f(async()=>{a.replayDurationType==="before"?await re(e):await l.markPendingCaptureToCanUpload(i)},"Error in schedule/capture callback")};f(async()=>{if(a.replayDurationType==="after"||a.replayDurationType==="beforeAndAfter")return!n&&!r&&s.eventEmitter.on(s.SprigEvent.QuestionAnswered,c),void await De(e);if(n||r||t)await re(e),r&&et();else{const d=35+a.replayDurationSeconds,u=o-1e3*d,w=o;await l.updateEventsExpiredAt(u,w,a.expirationTimeLimitMinutes),s.eventEmitter.on(s.SprigEvent.QuestionAnswered,c)}},"Error in scheduling/capturing replay")},et=async()=>{parseInt(E??"0")||s.sessionStorageHelper.removeItem("sprig.isCapturingHeatmap"),s.sessionStorageHelper.getItem("sprig.teardownAfterCapture")&&(me(),Se(),s.sessionStorageHelper.removeItem("sprig.teardownAfterCapture"))},Se=async()=>v()?s.breadcrumbsLogger.debug("ReplayDisabled-ClearData"):Promise.all([l.deleteBySessionId("events",y),l.deleteBySessionId("pendingCaptures",y)]).catch(e=>{T("Error clearing user replay data",e)}),De=async e=>{if(v())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 s.breadcrumbsLogger.info("PendingCaptureExists",{surveyId:r});t&&(p.isRecording&&f(()=>{var d,u;return(u=(d=window.rrwebRecord)==null?void 0:d.takeFullSnapshot)==null?void 0:u.call(d,!0)},"Error recording full snapshot"),s.sessionStorageHelper.setItem("sprig.isCapturingHeatmap","true"),W=Date.now(),p.inactivityInterval||(p.inactivityInterval=window.setInterval(()=>{var d;d=W,Date.now()-d>=3e4&&f(()=>l.markPendingHeatmapsReady(),"Error in heatmap inactivity")},1e3)));const o={...e,replayParams:{...e.replayParams}};e.replayParams.replayDurationType==="beforeAndAfter"&&(o.replayParams.replayDurationSeconds*=2),o.replayParams.replayDurationType="before";const i=e.triggerTimestamp+1e3*e.replayParams.replayDurationSeconds;o.triggerTimestamp=i,E=(parseInt(E??"0")+1).toString(),s.sessionStorageHelper.setItem("sprig.pendingCount",E),await(await l.openDB()).add("pendingCaptures",{canUpload:!1,captureParams:o,sessionId:y,targetTimestamp:i,timestamp:Date.now(),uuid:s.v4()})},tt=Object.freeze(Object.defineProperty({__proto__:null,RecordEvent:e=>{b("Sprig_TrackEvent",e)},RecordPageView:e=>{e.description&&(e.description=z(e.description)),b("Sprig_PageView",e)},RecordSurveyShown:e=>{b("Sprig_ShowSurvey",e)},_completeSessionReplay:async({surveyId:e,responseGroupUuid:t,eventDigest:r,headers:n})=>{if(!e||!t)return!1;const a=window.UserLeap._API_URL,o=await ae({surveyId:e,responseGroupUuid:t,eventDigest:r,apiUrl:a,headers:n},!0);return!(o!=null&&o.error)},checkPendingHeatmapsUrl:()=>v()?s.breadcrumbsLogger.debug("ReplayDisabled-PendingHeatmaps"):f(async()=>{const e=(await l.getPendingCaptures({isHeatmap:!0})).map(t=>({eventId:t.captureParams.eventId,uuid:t.uuid})).filter(({eventId:t})=>!s.checkUrlStillMatching(t)).map(({uuid:t})=>t);s.breadcrumbsLogger.info("PendingHeatmapsToComplete",{count:e.length}),e.length&&(await l.markPendingHeatmapsReady(e),s.breadcrumbsLogger.info("MarkedPendingHeatmapsReady"))},"Error marking pending heatmaps ready"),clearUserReplayData:Se,disableRecording:T,initializeReplay:async({maxReplayDurationSeconds:e,maxInflightRequests:t=2,replaySettings:r,teardownAfter:n=!1})=>{if(E=s.sessionStorageHelper.getItem("sprig.pendingCount"),!p.isRecording){if(n&&s.sessionStorageHelper.setItem("sprig.teardownAfterCapture","true"),v())return s.breadcrumbsLogger.debug("ReplayDisabled");if(await(async()=>{var a;if(!window.indexedDB||!window.IDBKeyRange||!window.CompressionStream)return!0;if((a=window.navigator.storage)!=null&&a.estimate)try{const{quota:o=0,usage:i=0}=await window.navigator.storage.estimate(),c=(o-i)/1024**3;return s.breadcrumbsLogger.info("Storage",{availableGb:c}),c<.5}catch{return!0}return!1})())return s.breadcrumbsLogger.debug("IDBNotSupported"),K();try{const a=await l.openDB();s.breadcrumbsLogger.info("DBVersion",{version:a.version})}catch(a){return s.breadcrumbsLogger.error("ReplayOpenErr",{name:a.name}),a.name==="VersionError"&&l.deleteDB(),K()}if(f(async()=>{await he(!0)},"Error uploading ready pending captures"),!e)return s.breadcrumbsLogger.debug("MissingDuration");s.breadcrumbsLogger.debug("ReplayInit"),await f(async()=>{var a;if(r!=null&&r.minDuration&&(fe=r.minDuration),r!=null&&r.batchDuration&&(G=r.batchDuration),a=t,ne.setLimit(a),Ye(),Je(e+35,1800,e+35),Qe(),!window.rrwebRecord){const{record:d}=await import(window.UserLeap.replayLibraryURL??"https://cdn.sprig.com/dependencies/record-2.0.0-alpha.17.min.js");window.rrwebRecord=d}const o=window.rrwebRecord;if(!o)return s.breadcrumbsLogger.error("RecordScriptFailed");let i=!0,c=0;p.stopRecording=o({checkoutEveryNms:3e4,sampling:{input:"last",scroll:250,media:800},emit:(d,u)=>{if(d.type===P.Custom&&(W=Date.now()),v())return;if(u&&d.type===P.Meta)c=performance.now();else if(u&&c&&d.type===P.FullSnapshot){const g=performance.now()-c;s.reportAndRegister("sdk_replay_snapshot_seconds",g/1e3)}const w=i||!!u&&d.type===P.Meta;i=!1,qe({uuid:s.v4(),event:JSON.stringify(d),isValidStart:w,timestamp:Date.now()})},...r}),p.isRecording=!!p.stopRecording,p.isRecording&&(s.eventEmitter.on("survey.complete",d=>{var u;u={id:d,userAgent:window.navigator.userAgent},b("Sprig_SubmitSurvey",u)}),Oe())},"Error initializing replay")}},isReplayRecording:()=>p.isRecording,scheduleCapture:De,scheduleOrCaptureReplay:ve,tryReplayAction:f},Symbol.toStringTag,{value:"Module"}));s.registerReplay(tt);
|