@sprig-technologies/sprig-browser 2.31.0 → 2.31.2
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-CZcCXjci.js +12 -0
- package/dist/core-D0ATZnzx.cjs +12 -0
- package/dist/core.cjs +1 -1
- package/dist/core.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/{metricsReporter-DLAgtaq2.js → metricsReporter-D-m62w_D.js} +1 -1
- package/dist/{metricsReporter-D8MMZt8T.cjs → metricsReporter-DaSVYNOK.cjs} +1 -1
- package/dist/replay.cjs +1 -1
- package/dist/replay.js +1 -1
- package/dist/{view-Y4Pp5FJ1.js → view-B4bFr3nV.js} +6 -6
- package/dist/{view-hsiavHCt.cjs → view-D4GRlCAk.cjs} +4 -4
- package/package.json +1 -1
- package/dist/core-C0coGRtP.js +0 -12
- package/dist/core-rfFWMlyt.cjs +0 -12
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
var Lt=Object.defineProperty,Ut=(e,t,n)=>t in e?Lt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,q=(e,t,n)=>(Ut(e,typeof t!="symbol"?t+"":t,n),n);import{h as C,s as Fe,d as u,S as w,l as R,i as _,v as Me,m as U,j as St,E as $,D as M,c as kt,r as j,k as It,n as Et,o as _t,p as xt,q as je,t as Ne,u as Rt,a as At,x as ye,b as Dt,y as ze}from"./metricsReporter-D-m62w_D.js";const Ot='.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}',We="360px",Pt="ul-app",Ct="#e6e6e6",Tt="#bd282a",Ft=500,Mt=1030,Be=()=>{try{return window.parent.Intercom}catch{return null}},jt=()=>{const e=Be();e&&(e.ul_wasVisible&&e("update",{hide_default_launcher:!1}),delete e.ul_wasVisible)},Nt=()=>{const e=Be();e&&(e.ul_wasVisible=!!document.querySelector("iframe.intercom-launcher-frame"),e.ul_wasVisible&&e("update",{hide_default_launcher:!0}))},zt=Object.freeze(Object.defineProperty({__proto__:null,disable:Nt,enable:jt},Symbol.toStringTag,{value:"Module"})),qe=[zt];class $e{static disable(){qe.forEach(t=>t.disable())}static enable(){qe.forEach(t=>t.enable())}}const Ve="ul-view-sdk-script",Wt=["ios","android"],T="visitors",F="environments";async function A(e,t){var n,o,r;const{shouldDropOnRateLimit:i,...s}=t;s.headers=Object.assign(C(window.UserLeap),s.headers);const a=await Fe(e,{...s,shouldDropOnRateLimit:i});if(a.ok){const c=(n=a.headers)==null?void 0:n.get("Authorization"),l=c?c.split(" "):void 0,d=l&&l.length===2?l[1]:void 0,p=(o=a.headers)==null?void 0:o.get("x-ul-visitor-id");d&&p&&(p!==window.UserLeap.visitorId||window.UserLeap.token!==d)&&(E("token",d),E("vid",p),u.emit(w.VisitorIDUpdated,{visitorId:p}),window.UserLeap.token=d,window.UserLeap.visitorId=p)}return(r=a.json)!=null&&r.logMessage&&console.warn(`[Sprig] ${a.json.logMessage}`),a}function E(e,t){const n=R.getItem("userleap.ids");let o={};if(n)try{o=JSON.parse(n)}catch(i){i instanceof Error&&(i.stack=n,window.UserLeap.reportError("Failed to parse local storage credentials",i)),console.warn("[Sprig] (ERR-427) Failed to lookup saved ids",i)}let r=o[window.UserLeap.envId];r?r[e]=t:r={[e]:t},o[window.UserLeap.envId]=r;try{R.setItem("userleap.ids",JSON.stringify(o))}catch(i){i instanceof Error&&console.warn(`[Sprig] (ERR-426) Unable to write to Local Storage:: ${i.message}`)}}function ve(){return window.previewMode?"0":window.UserLeap.visitorId??""}function x(e,t,n){const o=[window.UserLeap._API_URL,"sdk",e];return t&&t.forEach(r=>{o.push(r),r===F?o.push(window.UserLeap.envId):r===T&&o.push(ve())}),n&&o.push(n),o.join("/")}const V=async(e,t)=>{var n,o,r;const{context:i,delay:s,forceBrandedLogo:a,endCard:c,isFeedback:l=!1,heatmap:d,locale:p,previewMode:g,productConfig:v,questions:m,responseGroupUid:h,surveyId:S,uuid:I,vid:b,sessionReplay:k,studyType:O}=e,L=C(window.UserLeap),Ae=re(L),ue=fe(L);if(_(`Attempting to display survey: ${S}`),k)if(_("Survey has replay attached"),Ae)u.emit(w.ReplayCapture,{responseGroupUid:h,hasQuestions:!!(m!=null&&m.length),surveyId:S,uploadId:k.uploadId,replayType:k.replayDurationType??"before",seconds:k.replayDurationSeconds,generateVideoUploadUrlPayload:{mediaRecordingUid:Me(),mediaType:"screen",questionId:1,responseGroupUid:h,surveyId:S,updatedAt:new Date().toISOString(),visitorId:window.UserLeap.visitorId,isReplay:!0}});else{if(!U.replay)return window.UserLeap.reportError("displayQuestions",new Error("Replay module not registered")),{success:!1,message:"Replay module not registered",surveyState:"no survey"};U.replay.scheduleOrCaptureReplay({responseGroupId:h,surveyId:S,visitorId:b,replayParams:k,completeUploadHeaders:L,apiUrl:window.UserLeap._API_URL,triggerTimestamp:Date.now(),isStandalone:m.length===0})}if(d){if(!U.replay)return window.UserLeap.reportError("displayQuestions",new Error("Replay module not registered")),{success:!1,message:"Replay module not registered",surveyState:"no survey"};const{eventId:f,replayParams:me,responseGroupUid:ht,surveyId:bt}=d;await U.replay.initializeReplay({viewDocument:window.document,maxReplayDurationSeconds:300,replayNonce:window.UserLeap.replayNonce,maxInflightRequests:window.UserLeap.maxInflightReplayRequests,teardownAfter:!0}),U.replay.tryReplayAction(()=>{var Te;return(Te=U.replay)==null?void 0:Te.scheduleCapture({apiUrl:window.UserLeap._API_URL,completeUploadHeaders:L,eventId:f,isHeatmap:!0,replayParams:me,responseGroupId:ht,surveyId:bt,triggerTimestamp:Date.now(),visitorId:b})},"Error in scheduling/capturing replay")}if(b==null||!(m!=null&&m.length))return _(`Not displaying survey: vid: ${b} / questions: ${m}`),{success:!1,message:"[Sprig] no survey found",surveyState:"no survey"};if(window.UserLeap.container){_("Already displaying a survey");const f="[Sprig] (ERR-409) Found an existing Survey container, aborting rendering of this survey";return console.warn(f),{success:!1,message:f,surveyState:"no survey"}}if(b!==window.UserLeap.visitorId&&I!==window.UserLeap.visitorId&&!window.previewMode){const f="Attempted to display survey to a different visitor";return _(f),window.UserLeap.reportError("DisplaySurvey",new Error(f)),{success:!1,message:f,surveyState:"no survey"}}_(`Showing survey: ${S}`),(n=U.replay)==null||n.RecordSurveyShown({id:S,userAgent:window.navigator.userAgent}),$e.disable(),u.emit(w.SurveyWillPresent,{name:w.SurveyWillPresent,"survey.id":S});let X,Z=document.createElement("div"),ee,P,te;const De=f=>{const{"view.version":me}=f;me!==L["x-ul-sdk-version"]&&Ge(),u.removeListener("verify.view.version",De)};u.on("verify.view.version",De),window.UserLeap.useMobileStyling=ue,St(L)?(X="ul-direct-embeded-frame",ee=document.head,P=window,te=!1,Ae&&(He(l),Z.id=X,window.UserLeap.container.appendChild(Z),Ke(),u.emit(w.SurveyLifeCycle,{state:"presented"}),u.emit(w.SurveyPresented,{name:w.SurveyPresented,"survey.id":S}))):{frameId:X,contentWinDocHead:ee,contentWindow:P,hasOverlay:te,iframe:Z}=Ht({productConfig:v,useMobileStyling:ue,surveyId:S,isFeedback:l}),window.UserLeap.frameId=X;const yt=f=>{u.once(w.CloseSurveyOnOverlayClick,f)},W={apiURL:window.UserLeap._API_URL,cards:m,configureExitOnOverlayClick:yt,context:i,endCard:c,envId:window.UserLeap.envId,eventEmitFn:u.emit.bind(u),fontFamily:window.UserLeap.fontFamily,fontFamilyURL:window.UserLeap.fontFamilyURL,forceBrandedLogo:a,frame:Z,headers:L,locale:p,mobileSDKVersion:window.UserLeap.mobileSDKVersion,previewKey:R.getItem("sprig.previewKey"),previewMode:g,productConfig:{framePosition:v?.framePosition,desktopDisplay:v?.desktopDisplay,placement:v?.placement},responseGroupUid:h,startingQuestionIdx:(o=window.UserLeap.config)==null?void 0:o.startingQuestionIdx,studyType:O,styleNonce:window.UserLeap.styleNonce,surveyId:S,tabTitle:document.title,trackPageViewUrl:t,ulEvents:$,upchunkLibraryURL:window.UserLeap.upchunkLibraryURL,useMobileStyling:ue,userId:I,viewDocument:P?.document,viewWindow:P,visitorAttributes:{externalUserId:window.UserLeap.userId,email:window.UserLeap.email},...window.UserLeap._config};(r=window.UserLeap._config)!=null&&r.startingQuestionIdx&&(window.UserLeap._config={...window.UserLeap._config,startingQuestionIdx:null});const vt=(l?window.UserLeap.feedbackCustomStyles:window.UserLeap.customStyles)??v.customStyles;W.customStyles=vt,P&&(P.__cfg=W);function ft(){const f=document.createElement("script");return window.UserLeap.nonce&&f.setAttribute("nonce",window.UserLeap.nonce),f.id=Ve,f}const we=window.UserLeap.viewSDKURL?window.UserLeap.viewSDKURL:W.path,Oe=document.getElementById(Ve);Oe&&Oe.remove();const ge=ft(),Pe=()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{display:"flex"})};if(W.installationMethod==="web-npm"||W.installationMethod==="web-npm-bundled"){const{default:f}=await import("./view-B4bFr3nV.js");f.configure(W),te&&window.UserLeap.container&&Pe()}else we&&(ge.src=we,te&&ge.addEventListener("load",()=>{window.UserLeap.container&&Pe()}),P?.addEventListener("error",f=>{f.target instanceof HTMLScriptElement&&f.target.src===we&&window.UserLeap.reportError("loadFrameScript",new Error("Frame script failed to load"))},{capture:!0,once:!0}));ee?.appendChild(ge);const Ce={success:!0,surveyState:"ready",surveyId:S,responseGroupUid:h};return window.UserLeap.isMobileSDK&&s&&(Ce.delay=s),Ce};function fe(e){var t;if(window.UserLeap.useMobileStyling!==void 0)return window.UserLeap.useMobileStyling;const n=((t=window.UserLeap.windowDimensions)==null?void 0:t.width)??document.body.clientWidth;return re(e)||n>10&&n<Ft}function re(e){return Wt.includes(e["userleap-platform"])}const he="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 Bt="rgba(255,255,255, 0.95)",qt="rgba(0,0,0,0.9)",be="0px",He=(e,t)=>{window.UserLeap.container=document.createElement("div"),window.UserLeap.container.className=`ul-container${e?" ul-container-feedback":""}`;const n=Xe();t&&n&&!window.UserLeap.useMobileStyling?n.appendChild(window.UserLeap.container):document.body.appendChild(window.UserLeap.container)},Ge=(e,t)=>{var n;Kt();const o=window.UserLeap.container;if(o)try{(n=o.parentNode)==null||n.removeChild(o),window.UserLeap.container=null,E("trackStartUrl",null),u.emit(w.SurveyLifeCycle,{state:"dismissed"}),u.emit(w.SurveyClosed,{name:w.SurveyClosed,initiator:e,studyType:t})}catch(r){console.warn(`[Sprig] (ERR-412) Error removing UserLeap container by ${e} `+o),r instanceof Error&&window.UserLeap.reportError("dismissActiveSurvey",r)}},Ke=()=>{u.once(w.SurveyWillClose,({initiator:e,studyType:t})=>{u.removeAllListeners(w.CloseSurveyOnOverlayClick),Ge(e,t)})},$t=(e,t)=>{const n={position:"fixed",overflow:"auto",top:"0px",left:"0px",display:"none",height:"100%",width:"100%",transition:"background-color 0.3s ease-out",zIndex:2147483646},o=t?e.overlayStyleMobile:e.overlayStyle;n["background-color"]=o==="light"?Bt:qt,t||(n.margin="auto"),window.UserLeap.container&&Object.assign(window.UserLeap.container.style,n)},Vt=(e,t,n,o)=>{var r,i;const s={position:"fixed",bottom:"0px",right:be,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%"},a=Object.assign({},t,window.UserLeap),{desktopDisplay:c}=t||{},l=c==="center-modal";l&&(a.framePosition="center");let d,p=!1;if(n)(r=window.UserLeap.windowDimensions)!=null&&r.width?s.width=`${window.UserLeap.windowDimensions.width}px`:s.width="100%",(i=window.UserLeap.windowDimensions)!=null&&i.height?s.maxHeight=`${window.UserLeap.windowDimensions.height-20}px`:window.UserLeap.maxHeight?s.maxHeight=window.UserLeap.maxHeight:s.maxHeight=`${document.body.clientHeight-20}px`,["light","dark"].includes(a.overlayStyleMobile)&&(p=!0);else{s.width=We,s.maxHeight=window.UserLeap.maxHeight||"66vh";const g=()=>{p=!0,d={margin:"auto",position:"static"}};if(o)l?g():d={position:"relative",height:"300px"};else switch(a.framePosition){case"bottomLeft":d={left:be};break;case"topLeft":d={left:be,top:0};break;case"topRight":d={top:0};break;case"center":g();break}}return p&&$t(a,n),Object.assign(e.style,s,d),p},Ht=({productConfig:e,useMobileStyling:t,surveyId:n,isFeedback:o})=>{var r,i;const s=he,a=o&&e.desktopDisplay==="slider";He(o,a),Gt();const c=document.createElement("iframe");c.id=s,c.setAttribute("title","Sprig User Feedback Dialog");const l=Vt(c,e,t,o);Ke();let d=!1;c.setHeight=m=>{(parseInt(c.style.height)!=m||!d)&&(d=!0,c.style.height=`${m}px`,u.emit(w.SurveyHeight,{name:w.SurveyHeight,contentFrameHeight:m}))};let p=!1;c.setWidth=m=>{(parseInt(c.style.width)!=m||!p)&&(p=!0,c.style.width=`${m}px`,u.emit(w.SurveyWidth,{name:w.SurveyWidth,contentFrameWidth:m}))},(r=window.UserLeap.container)==null||r.appendChild(c),e&&(t?e.exitOnOverlayClickMobile:e.exitOnOverlayClick)&&window.UserLeap.container&&(window.UserLeap.container.onclick=()=>{u.emit(w.CloseSurveyOnOverlayClick)}),u.emit(w.SurveyLifeCycle,{state:"presented"}),u.emit(w.SurveyPresented,{name:w.SurveyPresented,"survey.id":n});const g=(i=c.contentWindow)==null?void 0:i.document;if(g&&(g.open("text/html","replace"),g.write("<!doctype html><head></head><body></body></html>"),g.close(),!t)){const m=g.body;m.style.display="flex",m.style.alignItems="center"}const v=g?.head;return{frameId:s,contentWinDocHead:v,contentWindow:c.contentWindow,hasOverlay:l,iframe:c}},Je={[w.SurveyFadingOut]:()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{"background-color":"rgba(0,0,0,0)"})}},Gt=()=>{Object.entries(Je).forEach(([e,t])=>{u.on(e,t)})},Kt=()=>{Object.entries(Je).forEach(([e,t])=>{u.off(e,t)})},Jt=1,Qe=e=>e instanceof HTMLElement||e instanceof SVGElement,H=({document:e,elementId:t,styleString:n,nonce:o})=>{const r=e.getElementById(t);if(r){r.textContent=n;return}const i=e.createElement("style");o&&(i.nonce=o),i.textContent=n,i.id=t,e.head.appendChild(i)},Ye=e=>{const t=e.querySelector(".ul-card__container");let n=600,o=360;if(t){n=t.scrollHeight;const r=getComputedStyle(t),i=parseFloat(r.marginTop)+parseFloat(r.marginBottom),s=parseFloat(r.borderTopWidth)+parseFloat(r.borderBottomWidth),a=parseFloat(r.paddingTop)+parseFloat(r.paddingBottom);n+=i+s+a;const c=t.querySelector(".ul-card--matrix_grid");o=c?c.scrollWidth:t.scrollWidth;const l=parseFloat(r.paddingLeft)+parseFloat(r.paddingRight),d=parseFloat(r.marginLeft)+parseFloat(r.marginRight),p=parseFloat(r.borderLeftWidth)+parseFloat(r.borderRightWidth);o+=d+p+l}return[n+Jt,o]},Qt=e=>{const t=e.querySelector(".ul-card__container");t&&(t.scrollTop=0)},Xe=()=>y,B=()=>document.getElementById("sprig-feedback-container"),Le=()=>document.getElementById("sprig-feedback-loading-animation"),Yt=()=>{if(Le())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},Ze=()=>!!document.getElementById(he);let et=!1,y=null,D=null,Ue=!1,G=null,K=null;const Xt=["bottom-left","bottom-right","center-left","center-right"],Zt=e=>{if(B()||!Xt.includes(e))return;const[t,n]=e.split("-"),o=document.createElement("div");o.id="sprig-feedback-container",o.classList.add(`sprig-feedback-container-${n}`,`sprig-feedback-container-${t}`),document.body.appendChild(o)},ne=()=>{var e;const t=window.UserLeap.container;return((e=t?.parentElement)==null?void 0:e.id)==="sprig-feedback-loading-container"},tt=()=>document.getElementById("sprig-feedback-error-container"),rt=()=>{if(!y)return 0;const e=y?.clientWidth,t=window.getComputedStyle(y),n=parseInt(t.borderRightWidth||"0"),o=parseInt(t.borderLeftWidth||"0");return e+n+o},ie=e=>{const t=B();t&&(K!=null&&K.endsWith("right")?t.style.right=`${e}px`:K!=null&&K.endsWith("left")&&(t.style.left=`${e}px`))},Se=()=>{if(y&&(ne()||tt())){u.off(w.SurveyAppeared,J),ke();const e=rt();return ie(-e),!0}return!1},J=()=>{if(!y||!D)return;const e=Le();e&&e.remove(),y.style.height="auto",y.style.width="auto",D.disabled=!1,Ue=!1},ke=()=>{if(y&&!Le()){const e=Yt();e&&(y.style.height="300px",y.style.width="360px",y.appendChild(e))}},nt=()=>{!y||!D||(ie(0),D.disabled=!0,Ue=!0)},er=async e=>{const t=await A(x("1",[T],"startFeedbackStudy"),{body:JSON.stringify({surveyUuid:e}),method:"POST"});return t.ok?t.json:null},it=async(e,t,n)=>{const{buttonTheme:o,customStyles:r,eventId:i,placement:s,desktopDisplay:a,feedbackLabel:c,surveyUuid:l,surveyId:d}=e;window.UserLeap.feedbackCustomStyles=void 0;let p=B();if(p){if(!t&&i===G)return;p.remove(),u.off($.SURVEY_FADING_OUT,Se)}G=i,H({document,elementId:"sprig-feedback-style",styleString:Ot,nonce:window.UserLeap.styleNonce}),H({document,elementId:"ul-custom-style",styleString:r??"",nonce:window.UserLeap.styleNonce}),et=a==="center-modal",K=s;const[g,v]=s.split("-");Zt(s),p=B(),D=document.createElement("button");const m=document.createElement("div");m.className="sprig-feedback-button-label",m.innerText=c,D.appendChild(m),D.id="sprig-feedback-button",D.classList.add(`sprig-feedback-button-${v}`,`sprig-feedback-button-${g}`,`sprig-feedback-button-${o}`,"fade-in-transition"),u.on($.SURVEY_FADING_OUT,Se),D.addEventListener("click",async()=>{const I=document.getElementById("sprig-feedback-error-container");if(Ze()||tt()){if(Se()){u.emit(w.SurveyWillClose,{name:w.SurveyWillClose,initiator:M.FeedbackClosed,studyType:"feedbackButton"});const O=B();I&&O&&(O.remove(),G=null,y=null)}return}const b=C(window.UserLeap);if(!fe(b)&&!Ue&&nt(),t){y&&y.classList.add("sprig-feedback-loading-container-previews"),await V(t),J();return}const k=await er(l);if(k)u.once(w.SurveyAppeared,J),V({...k,studyType:"feedbackButton"},n);else if(y){const O=rr();y.appendChild(O),J(),y.style.height="300px",y.style.width="360px"}}),p?.appendChild(D),u.emit(w.FeedbackButtonLoaded,{name:w.FeedbackButtonLoaded,"survey.id":d});const{useMobileStyling:h,_config:{border:S}}=window.UserLeap;if(!et&&!h){const I=document.createElement("div");I.id="sprig-feedback-loading-container",I.className=`sprig-feedback-loading-container sprig-feedback-loading-container-${v}`,I.style.setProperty("--feedback-border",S),y=I,ke(),p?.appendChild(I);const b=rt();ie(-b)}else ie(0);window.UserLeap._config.isOnQuestionsTab&&t&&!ne()&&y&&(nt(),ke(),y&&y.classList.add("sprig-feedback-loading-container-previews"),V(t),J())},tr=()=>{if(ne())return;const e=B();e&&(kt(G)||(e.remove(),G=null,y=null))},rr=()=>{const e=document.createElement("div");e.id="sprig-feedback-error-container",e.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 t=document.createElement("h3");return t.className="sprig-feedback-error-text",t.innerText="There was an error while loading the survey",e.appendChild(t),e},nr="!launch_darkly_";class ir{constructor(){q(this,"_ldData",{})}getAllLaunchDarklyVariations(){return this._ldData}setLDFlagsVariations(t){try{return!t||typeof t!="object"||Array.isArray(t)?!1:(Object.keys(this._ldData).forEach(n=>{delete this._ldData[n]}),Object.keys(t).forEach(n=>this._ldData[`${nr}${n}`]=(t[n]??0)+1),!0)}catch(n){return n instanceof Error&&window.UserLeap.reportError("setAllLDFlagsVariations",n),console.warn("[Sprig] An issue had occured when setting LaunchDarkly flags and variations."),!1}}}const Ie=new ir;Object.freeze(Ie);const or="!optimizely_experiments_";class sr{constructor(){q(this,"_optimizelyData",{})}setOptimizelyExperiment(t,n=!0){if(!t||typeof t!="object")return!1;const{experiments:o}=t;try{return n&&Object.keys(this._optimizelyData).map(r=>{delete this._optimizelyData[r]}),o&&o.map(r=>{const{id:i,variation:s}=r,a=this.transformExperimentId(i);s&&typeof s=="string"&&(this._optimizelyData[a]=s)}),!0}catch(r){return r instanceof Error&&window.UserLeap.reportError("setOptimizelyExperiment",r),!1}}getAllOptimizelyExperiments(){return this._optimizelyData}getOptimizelyVariationName(t){return this._optimizelyData[this.transformExperimentId(t)]}transformExperimentId(t){return or+t}getAndSetWebOptimizelyExperiments(){var t;try{if(window&&window.optimizely&&typeof window.optimizely.get=="function"){const n=(t=window.optimizely.get("state"))==null?void 0:t.getExperimentStates({isActive:!0});if(n){const o=Object.keys(n).map(r=>{var i,s;return(i=n[r].variation)!=null&&i.name?{id:r,variation:(s=n[r].variation)==null?void 0:s.name}:{id:r,variation:"Original"}});return this.setOptimizelyExperiment({experiments:o},!1),!0}return!1}return!1}catch(n){return n instanceof Error&&window.UserLeap.reportError("getAndSetWebOptimizely",n),!1}}}const oe=new sr;Object.freeze(oe);class ar{constructor(t,n){q(this,"paused"),q(this,"queue"),q(this,"ul"),this.ul=t,this.paused=!1,this.queue=[],this.flush(n)}flush(t){const n=t.length;if(n)for(let o=0;o<n;o++)this.push(t[o])}isPaused(){return this.paused}pause(){this.paused=!0}unpause(){this.paused=!1;const t=this.queue.slice();this.empty(),this.flush(t)}push(t){if(this.paused)this.queue.push(t);else if(t instanceof Function)t();else{const n=Array.prototype.slice.call(t,1),o=t[0],r=this.ul[o];r instanceof Function?r.apply(this.ul,n):o&&console.warn("[Sprig] (ERR-100) No valid UserLeap action called",o)}}perform(t){if(this.paused){let n=()=>{};const o=new Promise(function(r){n=function(){r(t())}});return this.queue.push(n),o}else return t()}empty(){this.queue.length=0}}let ot,st;const Ee=e=>{let t=0,n=e.firstElementChild;for(;n;)t+=Ee(n),n.shadowRoot&&(t+=Ee(n.shadowRoot)),n=n.nextElementSibling,t++;return t},dr=()=>document.documentElement.innerHTML.length,at=()=>{ot.report(Ee(document.body)),st.report(dr())},lr=(e=10*1e3)=>{ot=j("sdk_dom_nodes_count"),st=j("sdk_page_html_characters"),at(),setInterval(at,e)},_e=(e,t)=>{const n=performance.now();document.hidden?setTimeout(()=>_e(e,t),e):setTimeout(()=>{const o=performance.now()-n;t.report(o/1e3),setTimeout(()=>_e(e,t),e)},0)},cr=(e=1e3)=>{const t=j("sdk_event_queue_latency_seconds");_e(e,t)};let se,ae,de,le,N={},dt;const ce=(e,t=1)=>{const{name:n}=e;N[n]=(N[n]||0)+t},lt=e=>{let t=1;return e.childNodes.forEach(n=>{t+=lt(n)}),t},ct=e=>{let t=0;return e.forEach(n=>{t+=lt(n)}),t},pr=e=>{switch(e.type){case"childList":ce(se,ct(e.addedNodes)),ce(ae,ct(e.removedNodes));return;case"attributes":ce(de);return;case"characterData":ce(le);return}},ur=e=>e.forEach(pr),wr=()=>{dt=new MutationObserver(ur),dt.observe(document,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0})},gr=()=>{se.report(N[se.name]||0),ae.report(N[ae.name]||0),de.report(N[de.name]||0),le.report(N[le.name]||0),N={}},mr=(e=1*1e3)=>{se=j("sdk_mutations_nodes_added"),ae=j("sdk_mutations_nodes_removed"),de=j("sdk_mutations_attributes_changed"),le=j("sdk_mutations_character_data"),wr(),setInterval(gr,e)},yr=({isWeb:e,reportingIntervalSeconds:t,thresholds:n,postMetrics:o})=>{It(n,(r,i)=>{var s,a;if((s=U.replay)!=null&&s.isReplayRecording()){const c=`Value: ${r} on ${i.metric} violated threshold of ${i.type} ${i.value}`;(a=U.replay)==null||a.disableRecording("Threshold violated",new Error(c),{reportError:!1}),window.UserLeap.reportError("Sdk Performance Metric threshold violated",new Error("Sdk Performance Metric threshold violated"),{metricName:i.metric,type:i.type,value:i.value},{metricName:i.metric}),_t()}}),Et({reportingIntervalSeconds:t,postMetrics:o}),e&&(cr(),lr(),mr())},vr={test:"test"},fr=["popState","pushState","replaceState"],Q="!email",pt="pageUrl";function hr(e,t){const{pageUrlEvents:n,interactiveEvents:o,dismissOnPageChange:r}=window.UserLeap._config;if(!r)return!0;const i=[];n&&n.length&&i.push(...n),o&&o.length&&i.push(...o);const s=e&&i.find(a=>a.id===e);return s?ye(s,window.location.href):t===window.location.href}function Y(e){var t;const{pageUrlEvents:n,interactiveEvents:o,dismissOnPageChange:r,platform:i}=window.UserLeap._config;if(i&&i!=="web")return;const s=z("trackStartUrl"),a=s?String(s):null;n&&mt(window.location.href),o&&(wt(),br()),Xe()&&tr(),At.getItem("sprig.isCapturingHeatmap")&&((t=U.replay)==null||t.checkPendingHeatmapsUrl()),!ne()&&r&&a&&a!==window.location.href&&e&&fr.includes(e.type)&&window.UserLeap("dismissActiveSurvey",M.PageChange)}const ut={capture:!0},br=()=>{const e=window.UserLeap._config.interactiveEvents.filter(n=>ye(n,window.location.href)).map(n=>{const{name:o,properties:r}=n,{selector:i,innerText:s}=r;return i?a=>{if(Qe(a.target))try{a.target.closest(i)&&window.UserLeap("track",o)}catch{}return!1}:a=>(Qe(a.target)&&a.target.innerText===s&&window.UserLeap("track",o),!1)}),t=n=>e.forEach(o=>o(n));window.UserLeap._config.interactiveEventsHandler=t,window.addEventListener("click",t,ut)},wt=()=>{window.UserLeap._config.interactiveEventsHandler&&window.removeEventListener("click",window.UserLeap._config.interactiveEventsHandler,ut),delete window.UserLeap._config.interactiveEventsHandler};function Lr(){["hashchange","popstate"].forEach(e=>window.addEventListener(e,Y,!0))}function Ur(){["hashchange","popstate"].forEach(e=>window.removeEventListener(e,Y,!0)),window.UserLeap._config.interactiveEvents&&wt()}function Sr(e){const t=new URL(x("1",[F],"questions"));return Object.entries(e||{}).forEach(([n,o])=>{o&&t.searchParams.append(n,String(o))}),t.toString()}function z(e){const t=R.getItem("userleap.ids");if(t)try{const n=JSON.parse(t)[window.UserLeap.envId];return n&&n[e]||null}catch(n){n instanceof Error&&(n.stack=t,window.UserLeap.reportError("Failed to parse local storage credentials",n)),console.warn("[Sprig] (ERR-427) Failed to lookup saved ids",n)}return null}function gt(){window.previewMode||(window.UserLeap.visitorId=Me(),_(`Generating new vid: ${window.UserLeap.visitorId}`),E("vid",window.UserLeap.visitorId),u.emit(w.VisitorIDUpdated,{visitorId:window.UserLeap.visitorId}))}function mt(e,t,n,o){var r,i;try{if(e.endsWith("mock_snippet.html"))return;_(`Tracking page view: ${e}`);const s=window.UserLeap._config.pageUrlEvents;let a=!1;if(s&&s.length)for(let d=0;d<s.length&&(a=ye(s[d],e),!a);d++);if(!a)return;window.UserLeap.debugMode&&console.info("[DEBUG] Sprig trackPageView",e);const c={url:e};o&&(c.trackPageView=!0),window.UserLeap._queue.push(["track",pt,t,c,n]);const l=(r=document?.querySelector('meta[name="description"]'))==null?void 0:r.getAttribute("content");(i=U.replay)==null||i.RecordPageView({...l&&{description:l},url:e,referrer:document.referrer,pageTitle:document.title})}catch(s){s instanceof Error&&(s.stack=e,window.UserLeap.reportError("trackPageView",s)),console.warn("[Sprig] (ERR-428) Failed to track page view",s)}}function kr(){const e="Backbone"in window&&window.Backbone&&window.Backbone.history?window.Backbone.history:window.history;"pushState"in e&&(e.pushState=(t=>function(...n){const o=t.apply(this,n),r=new Event("pushState");return window.dispatchEvent(r),Y(r),o})(e.pushState)),"replaceState"in e&&(e.replaceState=(t=>function(...n){const o=t.apply(this,n),r=new Event("replaceState");return window.dispatchEvent(r),Y(r),o})(e.replaceState)),Lr()}async function xe(e,t){const n=ve();e&&!t&&(window.UserLeap._config.mode=vr.test);const o=C(window.UserLeap),r=fe(o),i=await A(Sr({desktopDisplay:window.UserLeap._config.desktopDisplay,isMobile:r,previewLanguage:window.UserLeap._config.previewLanguage,surveyid:e?.surveyId,surveytemplateid:e?.surveyTemplateId,vid:n}),{shouldDropOnRateLimit:!0});if(!i.ok)return i.reportError&&i.error&&(console.warn("[Sprig] (ERR-414) Failed to request questions from the server",i.error),window.UserLeap.reportError("getQuestions",i.error)),{success:!1,surveyState:"no survey"};if(i.json.delay&&await ze(i.json.delay),i.json.isFeedback){const{feedbackLabel:s,productConfig:a,surveyUuid:c,feedbackCustomStyles:l}=i.json,{buttonTheme:d,placement:p,desktopDisplay:g}=a,v={customStyles:l,buttonTheme:d,desktopDisplay:g,eventId:0,feedbackLabel:s,placement:p,surveyUuid:c,surveyId:e?.surveyId};it(v,i.json)}else return V(i.json)}function Ir(e){let t=e.length;for(;t;){const n=Math.floor(Math.random()*t);t-=1;const o=e[t];e[t]=e[n],e[n]=o}}function Er(e){if(!e)return;window.UserLeap._config=e,e.mute&&window.UserLeap._queue.pause();const{interactiveEvents:t,pageUrlEvents:n,dismissOnPageChange:o}=e;t&&Ir(t),(t||n||o)&&(kr(),Y())}async function _r(e,t){var n,o;let r=!0;return t&&(n=e?.json)!=null&&n.surveyId&&(window.UserLeap.delayingSurvey=!0,r=await t(e.json.surveyId),window.UserLeap.delayingSurvey=!1,!r)?!1:((o=e?.json)!=null&&o.delay&&!window.UserLeap.isMobileSDK&&(window.UserLeap.delayingSurvey=!0,await ze(e.json.delay),window.UserLeap.delayingSurvey=!1),r)}const xr=function(e){if(!window.UserLeap)return;const t=async(r={})=>{var i,s,a,c,l;const{userId:d,anonymousId:p,metadata:g={},properties:v,showSurveyCallback:m}=r;let{eventName:h}=r;if(window.UserLeap.debugMode&&h!==pt&&console.info("[DEBUG] Sprig track",r),e.mode==="test")return;const S=R.getItem("sprig.previewKey")??void 0;if(e.requireUserIdForTracking&&!window.UserLeap.userId&&!d){const L="[Sprig] - Skipping tracking without userId";return console.warn(L),{success:!1,message:L,surveyState:"no survey"}}if(!h||h.trim().length===0){h=h?String(h):"";const L="[Sprig] - Invalid event name "+h;return console.warn(L),{success:!1,message:L,surveyState:"no survey"}}const I=window.location.href;if(g.url||(g.url=I),E("trackStartUrl",I),(s=(i=window.UserLeap)==null?void 0:i._config)!=null&&s.optimizelyEnabled){const L=C(window.UserLeap);re(L)||oe.getAndSetWebOptimizelyExperiments(),g.optimizelyExperiments=Object.assign({},oe.getAllOptimizelyExperiments())}(c=(a=window.UserLeap)==null?void 0:a._config)!=null&&c.launchDarklyEnabled&&(g.launchDarklyFlags=Ie.getAllLaunchDarklyVariations()),d&&(window.UserLeap.userId=d),p&&(window.UserLeap.partnerAnonymousId=p),v&&(g.eventProperties=v),(l=U.replay)==null||l.RecordEvent({name:h,url:g.url}),_(`Tracking event: ${h}`);const b=window.UserLeap.delayingSurvey||Ze()?await A(x("1",[T],"events/batch"),{body:JSON.stringify({events:[{event:h,metadata:g}],previewKey:S}),method:"POST",shouldDropOnRateLimit:!0}):await A(x("1",[T],"events"),{body:JSON.stringify({event:h,metadata:g,previewKey:S}),method:"POST",shouldDropOnRateLimit:!0});if(!b.ok){const L="[Sprig] (ERR-421) Failed to track event";return b.reportError&&(console.warn(L,b.error),b.error&&window.UserLeap.reportError("track",b.error)),{success:!1,message:L,error:b.error,surveyState:"no survey"}}d&&E("uid",d),p&&E("aid",p);const k=b.json;k.invalidPreviewKey&&R.removeItem("sprig.previewKey");const O=g.trackPageView?g.url:void 0;return k!=null&&k.feedbackButton&&it(k.feedbackButton,void 0,O),await _r(b,m)?hr(k.eventId,I)?V(k,O):{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"}},n=(r,i)=>{var s;const a=(s=r?.querySelector(`[id="${he}"]`))==null?void 0:s.contentDocument;a&&H({document:a,elementId:"ul-custom-style",styleString:i})},o={async displaySurvey(r){return console.warn("[Sprig] displaySurvey should only be used to debug your studies; not intended for production usage."),window.UserLeap("dismissActiveSurvey",M.Override),xe({surveyId:r},!0)},_previewSurvey(r){window.UserLeap("dismissActiveSurvey",M.Override),xe({surveyTemplateId:r},!1)},_reviewSurvey(r){window.UserLeap("dismissActiveSurvey",M.Override),xe({surveyId:r},!1)},previewSurvey(r){o._previewSurvey(r)},reviewSurvey(r){o._reviewSurvey(r)},mute(){window.UserLeap._queue.pause()},unmute(){window.UserLeap._queue.unpause()},setVisitorToken(){console.warn("[Sprig] setVisitorToken is deprecated.")},dismissActiveSurvey(r=M.API){u.emit(w.SurveyWillClose,{name:w.SurveyWillClose,initiator:r})},async setAttribute(r,i){if(!r||!i&&i!==0&&i!==!1){const s="[Sprig] - Disregarding empty attribute / value provided";return console.warn(s),{success:!1,message:s}}return this.setAttributes({[r]:i})},async setAttributes(r){if(r==null||Object.keys(r).length===0){const i="[Sprig] - Disregarding empty attributes provided";return console.warn(i),{success:!1,message:i}}return this.identifyAndSetAttributes({attributes:r})},async identifyAndSetAttributes(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig identifyAndSetAttributes",r),e.mode==="test")return;if(r===null||typeof r!="object"||!(r.userId||r.anonymousId||r.attributes)){const d="[Sprig] - Disregarding empty payload provided";return console.warn(d),{success:!1,message:d}}const{userId:i,anonymousId:s,attributes:a}=r;if(e.requireUserIdForTracking&&!window.UserLeap.userId&&!i){const d="[Sprig] - Skipping tracking without userId";return console.warn(d),{success:!1,message:d}}if(!a&&(!i||window.UserLeap.userId===i)&&(!s||window.UserLeap.partnerAnonymousId===s))return{success:!0};const c={};i&&(c.userId=window.UserLeap.userId=i),s&&(c.partnerAnonymousId=window.UserLeap.partnerAnonymousId=s);let l;return a?(a.email&&!Object.prototype.hasOwnProperty.call(a,Q)&&(a[Q]=a.email,delete a.email),_(`Setting attributes: ${JSON.stringify(a)}`),l=await A(x("1",[F,T],"attributes"),{body:JSON.stringify(a),method:"PUT"}),!l.ok&&l.reportError&&(console.warn("[Sprig] (ERR-432) identifyAndSetAttributes failed",l.error),l.error&&window.UserLeap.reportError("identifyAndSetAttributes",l.error))):l=await A(x("1",[F,T]),{body:JSON.stringify(c),method:"PUT"}),a&&a[Q]&&(window.UserLeap.email=a[Q]),l.ok&&(i&&E("uid",i),s&&E("aid",s)),{success:!!l.ok}},async removeAttributes(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig removeAttributes",r),e.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(e.requireUserIdForTracking&&!window.UserLeap.userId){const s="[Sprig] - Skipping tracking without userId";return console.warn(s),{success:!1,message:s}}const i=await A(x("1",[F,T],"attributes"),{body:JSON.stringify({delete:r}),method:"DELETE"});return!i.ok&&i.reportError&&(console.warn("[Sprig] (ERR-433) Remove attributes failed",i.error),i.error&&window.UserLeap.reportError("removeAttributes",i.error)),{success:!!i.ok}},async addSurveyListener(r){u.on(w.SurveyLifeCycle,r)},async removeSurveyListener(r){u.removeListener(w.SurveyLifeCycle,r)},async addListener(r,i){u.on(r,i)},async removeListener(r,i){u.removeListener(r,i)},async removeAllListeners(){u.removeAllListeners()},setPreviewKey(r){!r||typeof r!="string"||R.isStorageAvailable&&r&&R.setItem("sprig.previewKey",r)},async setUserId(r){var i;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(e.mode==="test"||r===window.UserLeap.userId)return;window.UserLeap.userId=r;const s=window.UserLeap.visitorId,a=await A(x("1",[F,T]),{body:JSON.stringify({userId:r}),method:"PUT"});if(!a.ok){a.reportError&&(console.warn("[Sprig] (ERR-420) Failed to set user id",a.error),a.error&&window.UserLeap.reportError("setUserId",a.error));return}s!==window.UserLeap.visitorId&&((i=U.replay)==null||i.clearUserReplayData()),E("uid",r)},async setPartnerAnonymousId(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig setPartnerAnonymousId",r),r==null){const i=`[Sprig] - Invalid partnerAnonymousId ${r}`;return console.warn(i),{success:!1,message:i}}return window.UserLeap.partnerAnonymousId=r,E("aid",r),{success:!0}},async track(r,i,s={},a=void 0){return t({eventName:r,properties:i,metadata:s,showSurveyCallback:a})},async identifyAndTrack(r){return await t(r)},trackPageView(r,i=void 0,s=void 0,a=!0){mt(r,i,s,a)},applyFeedbackStyles({button:r="",view:i=""}){window.UserLeap.feedbackCustomStyles=i,document.getElementById("sprig-feedback-style")&&H({document,elementId:"ul-custom-style",styleString:r,nonce:window.UserLeap.styleNonce}),n(document.querySelector(".ul-container-feedback"),i)},applyStyles(r){window.UserLeap.customStyles=r,n(window.UserLeap.container,r)},setWindowDimensions(r,i){var s,a;const c=typeof r=="string"?parseInt(r,10):r,l=typeof i=="string"?parseInt(i,10):i;if(!isNaN(c)&&!isNaN(l)&&(window.UserLeap.windowDimensions={width:c,height:l}),!window.UserLeap.frameId)return;const d=document.getElementById(window.UserLeap.frameId);d&&(window.UserLeap.useMobileStyling&&((s=window.UserLeap.windowDimensions)!=null&&s.width&&(d.style.width=`${window.UserLeap.windowDimensions.width}px`),(a=window.UserLeap.windowDimensions)!=null&&a.height&&(d.style.maxHeight=`${window.UserLeap.windowDimensions.height-20}px`),d.contentDocument&&(d.style.height=String(Ye(d.contentDocument)[0])+"px")),u.emit(w.SurveyDimensions,{name:w.SurveyDimensions,contentFrameWidth:d.clientWidth,contentFrameHeight:d.clientHeight}))},logoutUser(){var r;window.UserLeap.debugMode&&console.info("[DEBUG] Sprig logout"),_(`Logging out user: ${window.UserLeap.userId} / vid: ${window.UserLeap.visitorId}`),window.UserLeap.visitorId=null,window.UserLeap.userId=null,window.UserLeap.partnerAnonymousId=null,window.UserLeap.token=null,window.UserLeap.email=null,R.removeItem("userleap.ids"),window.UserLeap._queue.isPaused()&&window.UserLeap._queue.empty(),gt(),(r=U.replay)==null||r.clearUserReplayData(),window.UserLeap._queue.unpause()},teardown(){Ur(),window.UserLeap("dismissActiveSurvey",M.API),delete window.UserLeap,delete window.Sprig,delete window._Sprig},integrateOptimizely(r,i=!0){var s,a;if(!((a=(s=window.UserLeap)==null?void 0:s._config)!=null&&a.optimizelyEnabled)){console.warn("[SPRIG] Optimizely integration is currently not enabled for your product.");return}try{const c=typeof r=="string"?JSON.parse(r):r;oe.setOptimizelyExperiment(c,i)}catch(c){console.warn("[Sprig] Error with integrating Optimizely data"),c instanceof Error&&window.UserLeap.reportError("integrateOptimizely",c)}},integrateOptimizelyClient(r){var i,s;if(!((s=(i=window.UserLeap)==null?void 0:i._config)!=null&&s.optimizelyEnabled)){console.warn("[SPRIG] Optimizely integration is currently not enabled for your product.");return}const a=({experiment:c,variation:l})=>{const d={experiments:[{id:c.id,variation:l.key}]};window.UserLeap("integrateOptimizely",d,!1)};r.notificationCenter.addNotificationListener("ACTIVATE:experiment, user_id,attributes, variation, event",a)},importLaunchDarklyData(r){var i,s;if(!((s=(i=window.UserLeap)==null?void 0:i._config)!=null&&s.launchDarklyEnabled)){console.warn("[SPRIG] LaunchDarkly integration is currently not enabled for your product.");return}Ie.setLDFlagsVariations(r)},setVisitorAttribute(r,i){return console.warn("[Sprig] setVisitorAttribute is deprecated. Please use setAttribute"),o.setAttribute(r,i)},async setEmail(r){return o.setAttribute(Q,r)},async setVisitorEmail(r){return console.warn("[Sprig] setVisitorEmail is deprecated. Please use setEmail"),o.setEmail(r)},async _generateVideoUploadUrl(r){return Or(r)},_reportMetric(r,i){Dt(r,i)},async _completeSessionReplay({surveyId:r,responseGroupUuid:i,eventDigest:s}){var a;return U.replay?(a=U.replay)==null?void 0:a._completeSessionReplay({surveyId:r,responseGroupUuid:i,eventDigest:s,headers:C(window.UserLeap)}):(window.UserLeap.reportError("_completeSessionReplay",new Error("Replay module not registered")),!1)}};Object.assign(window.UserLeap,o)};async function Rr(e){const t=C(window.UserLeap);document.addEventListener("securitypolicyviolation",je);const n=await Fe(x("1",[F],"config"),{headers:t});if(document.removeEventListener("securitypolicyviolation",je),!n.ok)return n.reportError&&(console.warn("[Sprig] (ERR-422) Failed to load configuration",n.error),n.error&&window.UserLeap.reportError("applyRemoteConfig",n.error)),Ne("Disabled: failed to fetch configuration"),e;const o=n.json;return o!=null&&o.disabled?(Ne(`Disabled: ${o.disabled}`),{disabled:o.disabled}):Object.assign({},o,e)}const Ar=e=>typeof e=="object"&&e&&"inner"in e&&!!e.inner&&typeof e.inner=="object";async function Dr(e,t,n={},o={}){var r,i;const s=window.__cfg&&window.__cfg.mode,a=ve(),c=window.UserLeap.envId,l=window.document.documentElement,d=Ar(t)?{inner:{message:(r=t.inner)==null?void 0:r.message,stack:(i=t.inner)==null?void 0:i.stack}}:{},p={mode:s,screenWidth:window.screen.width,screenHeight:window.screen.height,clientWidth:l.clientWidth,clientHeight:l.clientHeight,location:window.location.href,language:window.navigator.language,...n,...d},g={action:e,err:{message:t.message,stack:t.stack},meta:p,vid:a,envId:c,...o},v=await A(x("1",null,"errors"),{method:"POST",headers:{"x-ul-error":window.btoa(`userleap-${Date.now()}-error`)},body:JSON.stringify(g),shouldDropOnRateLimit:!0});if(!v.ok)console.warn("[Sprig] (ERR-444) Failed to report error to API",t);else{const{presignedUrl:m}=v.json;Rt(m)}}async function Or(e){var t;if(!e)return;const n=`${window.UserLeap._API_URL}/2/environments/integrations/upload`;try{const o=await fetch(n,{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(o.ok){const r=await o.json();return(t=r?.upload)==null?void 0:t.url}else return null}catch(o){console.warn("[Sprig] Error with generating video upload url"),o instanceof Error&&window.UserLeap.reportError("generateVideoUploadUrl",o)}}function Pr(e={}){const t=new URLSearchParams(window.location.search).get("sprigPreviewKey")??"";window.UserLeap.UPDATES=$,window.UserLeap("setPreviewKey",t);async function n(){var o;if(window.UserLeap.loaded)return;if(_("Loading sprig on page load"),window.UserLeap.reportError=Dr,window.UserLeap.loaded=!0,window.UserLeap._config=Object.assign({},e,window.UserLeap.config),window.UserLeap.delayingSurvey=!1,window.UserLeap._config&&typeof window.UserLeap._config=="object")for(const d in window.UserLeap._config)window.UserLeap[d]=window.UserLeap._config[d];if(!window.UserLeap.envId)if(window.UserLeap.appId)window.UserLeap.envId=window.UserLeap.appId;else throw new Error("Missing Environment id");window.UserLeap.debugMode&&console.info("[DEBUG] Sprig debug mode enabled");const r=window.UserLeap.sampleRate;if(r){let d=z("sampled");if(d===null&&(d=Math.random()<r,E("sampled",d)),!d)return}else z("sampled")!==null&&E("sampled",null);window.UserLeap._API_URL||(window.UserLeap._API_URL="https://api.sprig.com");const i=[...window.UserLeap._queue];window.UserLeap._queue=new ar(window.UserLeap,[]),window.UserLeap._queue.pause();for(let d=0;d<i.length;d++)window.UserLeap._queue.push(i[d]);const s=z("token");s?(window.UserLeap.token=s,window.UserLeap.visitorId=z("vid"),window.UserLeap.userId=z("uid"),window.UserLeap.partnerAnonymousId=z("aid")):(R.removeItem("userleap.ids"),gt());const a=C(window.UserLeap),c=re(a),l=await Rr(e);yr({isWeb:!c,reportingIntervalSeconds:l.metricsReportingEnabled||l.mobileMetricsReportingEnabled?l.metricsReportingIntervalSeconds:0,thresholds:l.metricThresholds,postMetrics:async d=>{var p;await A(x("1",[F],"metrics"),{body:d,method:"POST",headers:{"x-ul-replay-enabled":`${!!((p=U.replay)!=null&&p.isReplayRecording())}`},shouldDropOnRateLimit:!0})}}),(o=U.replay)==null||o.initializeReplay({viewDocument:window.document,maxReplayDurationSeconds:l.maxReplayDurationSeconds,replayNonce:window.UserLeap.replayNonce,maxInflightRequests:window.UserLeap.maxInflightReplayRequests??2,replaySettings:l.replaySettings}),xt(l.logBufferLimit,l.logLevel),xr(l),await Er(l),window.UserLeap._queue.unpause(),u.emit(w.SDKReady,{mobileMetricsReportingEnabled:!!l.mobileMetricsReportingEnabled,metricsReportingInterval:l.metricsReportingIntervalSeconds||0,metricsThresholds:l.metricThresholds||[],maxMobileReplayDurationSeconds:l.maxMobileReplayDurationSeconds,mobileReplaySettings:l.mobileReplaySettings}),u.emit(w.VisitorIDUpdated,{visitorId:window.UserLeap.visitorId})}document.readyState==="complete"?n():window.attachEvent?window.attachEvent("onload",n):window.addEventListener("load",()=>{n()},!1)}class pe{constructor(){this.UPDATES=$}displaySurvey(t){window.Sprig("displaySurvey",t)}mute(){window.Sprig("mute")}unmute(){window.Sprig("unmute")}dismissActiveSurvey(){window.Sprig("dismissActiveSurvey")}setAttribute(t,n){window.Sprig("setAttribute",t,n)}setAttributes(t){window.Sprig("setAttributes",t)}identifyAndSetAttributes(t){window.Sprig("identifyAndSetAttributes",t)}removeAttributes(t){window.Sprig("removeAttributes",t)}addListener(t,n){window.Sprig("addListener",t,n)}removeListener(t,n){window.Sprig("removeListener",t,n)}removeAllListeners(){window.Sprig("removeAllListeners")}setEmail(t){window.Sprig("setAttribute","!email",t)}setUserId(t){window.Sprig("setUserId",t)}setPartnerAnonymousId(t){window.Sprig("setPartnerAnonymousId",t)}track(t,n={},o={}){window.Sprig("track",t,n,o)}identifyAndTrack(t){window.Sprig("identifyAndTrack",t)}trackPageView(t,n,o){window.Sprig("trackPageView",t,n,o)}applyStyles(t){window.Sprig("applyStyles",t)}setWindowDimensions(t,n){window.Sprig("setWindowDimensions",t,n)}logoutUser(){window.Sprig("logoutUser")}teardown(){window.Sprig("teardown")}}const Re={configure:e=>{if(!e.envId&&!e.environmentId)throw new Error("Initialization Error: Sprig configure requires an environmentId");if(e.envId||(e.envId=e.environmentId??""),e.installationMethod="web-npm",window.Sprig)return window.Sprig;window.Sprig=function(){window.Sprig._queue.push(arguments)},Object.getOwnPropertyNames(pe.prototype).map(n=>{n!=="constructor"&&(window.Sprig[n]=pe.prototype[n])});const t=window.Sprig;return t.appId=e.envId,t._queue=[],window.UserLeap=t,Pr(e),window.Sprig}},Cr={sprig:Re,SprigAPI:pe,configure:Re.configure};export{Pt as A,$e as C,We as D,Mt as E,pe as S,Ye as a,Tt as b,Cr as c,Ct as d,H as e,Qt as r,Re as s};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";var at=Object.defineProperty;var dt=(e,t,n)=>t in e?at(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var F=(e,t,n)=>(dt(e,typeof t!="symbol"?t+"":t,n),n);const i=require("./metricsReporter-DaSVYNOK.cjs"),lt='.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}',Ce="360px",ct="ul-app",pt="#e6e6e6",ut="#bd282a",wt=500,gt=1030,Me=()=>{try{return window.parent.Intercom}catch{return null}},ft=()=>{const e=Me();e&&(e.ul_wasVisible&&e("update",{hide_default_launcher:!1}),delete e.ul_wasVisible)},mt=()=>{const e=Me();e&&(e.ul_wasVisible=!!document.querySelector("iframe.intercom-launcher-frame"),e.ul_wasVisible&&e("update",{hide_default_launcher:!0}))},yt=Object.freeze(Object.defineProperty({__proto__:null,disable:mt,enable:ft},Symbol.toStringTag,{value:"Module"})),_e=[yt];class Fe{static disable(){_e.forEach(t=>t.disable())}static enable(){_e.forEach(t=>t.enable())}}const Re="ul-view-sdk-script",vt=["ios","android"],D="visitors",O="environments";async function I(e,t){var o,a,d;const{shouldDropOnRateLimit:n,...s}=t;s.headers=Object.assign(i.getHttpHeaders(window.UserLeap),s.headers);const r=await i.sprigFetch(e,{...s,shouldDropOnRateLimit:n});if(r.ok){const c=(o=r.headers)==null?void 0:o.get("Authorization"),p=c?c.split(" "):void 0,l=p&&p.length===2?p[1]:void 0,u=(a=r.headers)==null?void 0:a.get("x-ul-visitor-id");l&&u&&(u!==window.UserLeap.visitorId||window.UserLeap.token!==l)&&(S("token",l),S("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 S(e,t){const n=i.localStorageHelper.getItem("userleap.ids");let s={};if(n)try{s=JSON.parse(n)}catch(o){o instanceof Error&&(o.stack=n,window.UserLeap.reportError("Failed to parse local storage credentials",o)),console.warn("[Sprig] (ERR-427) Failed to lookup saved ids",o)}let r=s[window.UserLeap.envId];r?r[e]=t:r={[e]:t},s[window.UserLeap.envId]=r;try{i.localStorageHelper.setItem("userleap.ids",JSON.stringify(s))}catch(o){o instanceof Error&&console.warn(`[Sprig] (ERR-426) Unable to write to Local Storage:: ${o.message}`)}}function ge(){return window.previewMode?"0":window.UserLeap.visitorId??""}function U(e,t,n){const s=[window.UserLeap._API_URL,"sdk",e];return t&&t.forEach(r=>{s.push(r),r===O?s.push(window.UserLeap.envId):r===D&&s.push(ge())}),n&&s.push(n),s.join("/")}const V=async(e,t)=>{var Ee,Ue,ke;const{context:n,delay:s,forceBrandedLogo:r,endCard:o,isFeedback:a=!1,heatmap:d,locale:c,previewMode:p,productConfig:l,questions:u,responseGroupUid:m,surveyId:w,uuid:f,vid:L,sessionReplay:A,studyType:$}=e,v=i.getHttpHeaders(window.UserLeap),R=te(v),x=fe(v);if(i.info(`Attempting to display survey: ${w}`),A)if(i.info("Survey has replay attached"),R)i.eventEmitter.emit(i.SprigEvent.ReplayCapture,{responseGroupUid:m,hasQuestions:!!(u!=null&&u.length),surveyId:w,uploadId:A.uploadId,replayType:A.replayDurationType??"before",seconds:A.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:L,replayParams:A,completeUploadHeaders:v,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:y,replayParams:oe,responseGroupUid:ot,surveyId:st}=d;await i.modules.replay.initializeReplay({viewDocument:window.document,maxReplayDurationSeconds:300,replayNonce:window.UserLeap.replayNonce,maxInflightRequests:window.UserLeap.maxInflightReplayRequests,teardownAfter:!0}),i.modules.replay.tryReplayAction(()=>{var Ie;return(Ie=i.modules.replay)==null?void 0:Ie.scheduleCapture({apiUrl:window.UserLeap._API_URL,completeUploadHeaders:v,eventId:y,isHeatmap:!0,replayParams:oe,responseGroupId:ot,surveyId:st,triggerTimestamp:Date.now(),visitorId:L})},"Error in scheduling/capturing replay")}if(L==null||!(u!=null&&u.length))return i.info(`Not displaying survey: vid: ${L} / questions: ${u}`),{success:!1,message:"[Sprig] no survey found",surveyState:"no survey"};if(window.UserLeap.container){i.info("Already displaying a survey");const y="[Sprig] (ERR-409) Found an existing Survey container, aborting rendering of this survey";return console.warn(y),{success:!1,message:y,surveyState:"no survey"}}if(L!==window.UserLeap.visitorId&&f!==window.UserLeap.visitorId&&!window.previewMode){const y="Attempted to display survey to a different visitor";return i.info(y),window.UserLeap.reportError("DisplaySurvey",new Error(y)),{success:!1,message:y,surveyState:"no survey"}}i.info(`Showing survey: ${w}`),(Ee=i.modules.replay)==null||Ee.RecordSurveyShown({id:w,userAgent:window.navigator.userAgent}),Fe.disable(),i.eventEmitter.emit(i.SprigEvent.SurveyWillPresent,{name:i.SprigEvent.SurveyWillPresent,"survey.id":w});let k,b=document.createElement("div"),h,E,q;const he=y=>{const{"view.version":oe}=y;oe!==v["x-ul-sdk-version"]&&Ne(),i.eventEmitter.removeListener("verify.view.version",he)};i.eventEmitter.on("verify.view.version",he),window.UserLeap.useMobileStyling=x,i.shouldDirectEmbed(v)?(k="ul-direct-embeded-frame",h=document.head,E=window,q=!1,R&&(He(a),b.id=k,window.UserLeap.container.appendChild(b),Be(),i.eventEmitter.emit(i.SprigEvent.SurveyLifeCycle,{state:"presented"}),i.eventEmitter.emit(i.SprigEvent.SurveyPresented,{name:i.SprigEvent.SurveyPresented,"survey.id":w}))):{frameId:k,contentWinDocHead:h,contentWindow:E,hasOverlay:q,iframe:b}=Et({productConfig:l,useMobileStyling:x,surveyId:w,isFeedback:a}),window.UserLeap.frameId=k;const rt=y=>{i.eventEmitter.once(i.SprigEvent.CloseSurveyOnOverlayClick,y)},M={apiURL:window.UserLeap._API_URL,cards:u,configureExitOnOverlayClick:rt,context:n,endCard:o,envId:window.UserLeap.envId,eventEmitFn:i.eventEmitter.emit.bind(i.eventEmitter),fontFamily:window.UserLeap.fontFamily,fontFamilyURL:window.UserLeap.fontFamilyURL,forceBrandedLogo:r,frame:b,headers:v,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:(Ue=window.UserLeap.config)==null?void 0:Ue.startingQuestionIdx,studyType:$,styleNonce:window.UserLeap.styleNonce,surveyId:w,tabTitle:document.title,trackPageViewUrl:t,ulEvents:i.EVENTS,upchunkLibraryURL:window.UserLeap.upchunkLibraryURL,useMobileStyling:x,userId:f,viewDocument:E==null?void 0:E.document,viewWindow:E,visitorAttributes:{externalUserId:window.UserLeap.userId,email:window.UserLeap.email},...window.UserLeap._config};(ke=window.UserLeap._config)!=null&&ke.startingQuestionIdx&&(window.UserLeap._config={...window.UserLeap._config,startingQuestionIdx:null});const it=(a?window.UserLeap.feedbackCustomStyles:window.UserLeap.customStyles)??l.customStyles;M.customStyles=it,E&&(E.__cfg=M);function nt(){const y=document.createElement("script");return window.UserLeap.nonce&&y.setAttribute("nonce",window.UserLeap.nonce),y.id=Re,y}const ie=window.UserLeap.viewSDKURL?window.UserLeap.viewSDKURL:M.path,Se=document.getElementById(Re);Se&&Se.remove();const ne=nt(),Le=()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{display:"flex"})};if(M.installationMethod==="web-npm"||M.installationMethod==="web-npm-bundled"){const{default:y}=await Promise.resolve().then(()=>require("./view-D4GRlCAk.cjs"));y.configure(M),q&&window.UserLeap.container&&Le()}else ie&&(ne.src=ie,q&&ne.addEventListener("load",()=>{window.UserLeap.container&&Le()}),E==null||E.addEventListener("error",y=>{y.target instanceof HTMLScriptElement&&y.target.src===ie&&window.UserLeap.reportError("loadFrameScript",new Error("Frame script failed to load"))},{capture:!0,once:!0}));h==null||h.appendChild(ne);const be={success:!0,surveyState:"ready",surveyId:w,responseGroupUid:m};return window.UserLeap.isMobileSDK&&s&&(be.delay=s),be};function fe(e){var n;if(window.UserLeap.useMobileStyling!==void 0)return window.UserLeap.useMobileStyling;const t=((n=window.UserLeap.windowDimensions)==null?void 0:n.width)??document.body.clientWidth;return te(e)||t>10&&t<wt}function te(e){return vt.includes(e["userleap-platform"])}const me="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 ht="rgba(255,255,255, 0.95)",St="rgba(0,0,0,0.9)",se="0px",He=(e,t)=>{window.UserLeap.container=document.createElement("div"),window.UserLeap.container.className=`ul-container${e?" ul-container-feedback":""}`;const n=je();t&&n&&!window.UserLeap.useMobileStyling?n.appendChild(window.UserLeap.container):document.body.appendChild(window.UserLeap.container)},Ne=(e,t)=>{var s;kt();const n=window.UserLeap.container;if(n)try{(s=n.parentNode)==null||s.removeChild(n),window.UserLeap.container=null,S("trackStartUrl",null),i.eventEmitter.emit(i.SprigEvent.SurveyLifeCycle,{state:"dismissed"}),i.eventEmitter.emit(i.SprigEvent.SurveyClosed,{name:i.SprigEvent.SurveyClosed,initiator:e,studyType:t})}catch(r){console.warn(`[Sprig] (ERR-412) Error removing UserLeap container by ${e} `+n),r instanceof Error&&window.UserLeap.reportError("dismissActiveSurvey",r)}},Be=()=>{i.eventEmitter.once(i.SprigEvent.SurveyWillClose,({initiator:e,studyType:t})=>{i.eventEmitter.removeAllListeners(i.SprigEvent.CloseSurveyOnOverlayClick),Ne(e,t)})},Lt=(e,t)=>{const s={...{position:"fixed",overflow:"auto",top:"0px",left:"0px",display:"none",height:"100%",width:"100%",transition:"background-color 0.3s ease-out",zIndex:2147483646}},r=t?e.overlayStyleMobile:e.overlayStyle;s["background-color"]=r==="light"?ht:St,t||(s.margin="auto"),window.UserLeap.container&&Object.assign(window.UserLeap.container.style,s)},bt=(e,t,n,s)=>{var l,u;const r={position:"fixed",bottom:"0px",right:se,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%"},o=Object.assign({},t,window.UserLeap),{desktopDisplay:a}=t||{},d=a==="center-modal";d&&(o.framePosition="center");let c,p=!1;if(n)(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(o.overlayStyleMobile)&&(p=!0);else{r.width=Ce,r.maxHeight=window.UserLeap.maxHeight||"66vh";const m=()=>{p=!0,c={margin:"auto",position:"static"}};if(s)d?m():c={position:"relative",height:"300px"};else switch(o.framePosition){case"bottomLeft":c={left:se};break;case"topLeft":c={left:se,top:0};break;case"topRight":c={top:0};break;case"center":m();break}}return p&&Lt(o,n),Object.assign(e.style,r,c),p},Et=({productConfig:e,useMobileStyling:t,surveyId:n,isFeedback:s})=>{var m,w;const r=me,o=s&&e.desktopDisplay==="slider";He(s,o),Ut();const a=document.createElement("iframe");a.id=r,a.setAttribute("title","Sprig User Feedback Dialog");const d=bt(a,e,t,s);Be();let c=!1;a.setHeight=f=>{(parseInt(a.style.height)!=f||!c)&&(c=!0,a.style.height=`${f}px`,i.eventEmitter.emit(i.SprigEvent.SurveyHeight,{name:i.SprigEvent.SurveyHeight,contentFrameHeight:f}))};let p=!1;a.setWidth=f=>{(parseInt(a.style.width)!=f||!p)&&(p=!0,a.style.width=`${f}px`,i.eventEmitter.emit(i.SprigEvent.SurveyWidth,{name:i.SprigEvent.SurveyWidth,contentFrameWidth:f}))},(m=window.UserLeap.container)==null||m.appendChild(a),e&&(t?e.exitOnOverlayClickMobile:e.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":n});const l=(w=a.contentWindow)==null?void 0:w.document;if(l&&(l.open("text/html","replace"),l.write("<!doctype html><head></head><body></body></html>"),l.close(),!t)){const f=l.body;f.style.display="flex",f.style.alignItems="center"}const u=l==null?void 0:l.head;return{frameId:r,contentWinDocHead:u,contentWindow:a.contentWindow,hasOverlay:d,iframe:a}},Ve={[i.SprigEvent.SurveyFadingOut]:()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{"background-color":"rgba(0,0,0,0)"})}},Ut=()=>{Object.entries(Ve).forEach(([e,t])=>{i.eventEmitter.on(e,t)})},kt=()=>{Object.entries(Ve).forEach(([e,t])=>{i.eventEmitter.off(e,t)})},It=1,Ae=e=>e instanceof HTMLElement||e instanceof SVGElement,j=({document:e,elementId:t,styleString:n,nonce:s})=>{const r=e.getElementById(t);if(r){r.textContent=n;return}const o=e.createElement("style");s&&(o.nonce=s),o.textContent=n,o.id=t,e.head.appendChild(o)},We=e=>{const t=e.querySelector(".ul-card__container");let n=600,s=360;if(t){n=t.scrollHeight;const r=getComputedStyle(t),o=parseFloat(r.marginTop)+parseFloat(r.marginBottom),a=parseFloat(r.borderTopWidth)+parseFloat(r.borderBottomWidth),d=parseFloat(r.paddingTop)+parseFloat(r.paddingBottom);n+=o+a+d;const c=t.querySelector(".ul-card--matrix_grid");s=c?c.scrollWidth:t.scrollWidth;const p=parseFloat(r.paddingLeft)+parseFloat(r.paddingRight),l=parseFloat(r.marginLeft)+parseFloat(r.marginRight),u=parseFloat(r.borderLeftWidth)+parseFloat(r.borderRightWidth);s+=l+u+p}return[n+It,s]},_t=e=>{const t=e.querySelector(".ul-card__container");t&&(t.scrollTop=0)},je=()=>g,H=()=>document.getElementById("sprig-feedback-container"),ye=()=>document.getElementById("sprig-feedback-loading-animation"),Rt=()=>{if(ye())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},ze=()=>!!document.getElementById(me);let De=!1,g=null,_=null,ve=!1,W=null,T=null;const At=["bottom-left","bottom-right","center-left","center-right"],Dt=e=>{if(H()||!At.includes(e))return;const[t,n]=e.split("-"),s=document.createElement("div");s.id="sprig-feedback-container",s.classList.add(`sprig-feedback-container-${n}`,`sprig-feedback-container-${t}`),document.body.appendChild(s)},re=()=>{var t;const e=window.UserLeap.container;return((t=e==null?void 0:e.parentElement)==null?void 0:t.id)==="sprig-feedback-loading-container"},$e=()=>document.getElementById("sprig-feedback-error-container"),qe=()=>{if(!g)return 0;const e=g==null?void 0:g.clientWidth,t=window.getComputedStyle(g),n=parseInt(t.borderRightWidth||"0"),s=parseInt(t.borderLeftWidth||"0");return e+n+s},J=e=>{const t=H();t&&(T!=null&&T.endsWith("right")?t.style.right=`${e}px`:T!=null&&T.endsWith("left")&&(t.style.left=`${e}px`))},ae=()=>{if(g&&(re()||$e())){i.eventEmitter.off(i.SprigEvent.SurveyAppeared,B),le();const e=qe();return J(-e),!0}return!1},B=()=>{if(!g||!_)return;const e=ye();e&&e.remove(),g.style.height="auto",g.style.width="auto",_.disabled=!1,ve=!1},le=()=>{if(!g)return;if(!ye()){const t=Rt();t&&(g.style.height="300px",g.style.width="360px",g.appendChild(t))}},Oe=()=>{!g||!_||(J(0),_.disabled=!0,ve=!0)},Ot=async e=>{const t=await I(U("1",[D],"startFeedbackStudy"),{body:JSON.stringify({surveyUuid:e}),method:"POST"});return t.ok?t.json:null},Ge=async(e,t,n)=>{const{buttonTheme:s,customStyles:r,eventId:o,placement:a,desktopDisplay:d,feedbackLabel:c,surveyUuid:p,surveyId:l}=e;window.UserLeap.feedbackCustomStyles=void 0;let u=H();if(u){if(!t&&o===W)return;u.remove(),i.eventEmitter.off(i.EVENTS.SURVEY_FADING_OUT,ae)}W=o,j({document,elementId:"sprig-feedback-style",styleString:lt,nonce:window.UserLeap.styleNonce}),j({document,elementId:"ul-custom-style",styleString:r??"",nonce:window.UserLeap.styleNonce}),De=d==="center-modal",T=a;const[w,f]=a.split("-");Dt(a),u=H(),_=document.createElement("button");const L=document.createElement("div");L.className="sprig-feedback-button-label",L.innerText=c,_.appendChild(L),_.id="sprig-feedback-button",_.classList.add(`sprig-feedback-button-${f}`,`sprig-feedback-button-${w}`,`sprig-feedback-button-${s}`,"fade-in-transition"),i.eventEmitter.on(i.EVENTS.SURVEY_FADING_OUT,ae),_.addEventListener("click",async()=>{const v=document.getElementById("sprig-feedback-error-container");if(ze()||$e()){if(ae()){i.eventEmitter.emit(i.SprigEvent.SurveyWillClose,{name:i.SprigEvent.SurveyWillClose,initiator:i.DismissReason.FeedbackClosed,studyType:"feedbackButton"});const b=H();v&&b&&(b.remove(),W=null,g=null)}return}const R=i.getHttpHeaders(window.UserLeap);if(!fe(R)&&!ve&&Oe(),t){g&&g.classList.add("sprig-feedback-loading-container-previews"),await V(t),B();return}const k=await Ot(p);if(k)i.eventEmitter.once(i.SprigEvent.SurveyAppeared,B),V({...k,studyType:"feedbackButton"},n);else if(g){const b=Tt();g.appendChild(b),B(),g.style.height="300px",g.style.width="360px"}}),u==null||u.appendChild(_),i.eventEmitter.emit(i.SprigEvent.FeedbackButtonLoaded,{name:i.SprigEvent.FeedbackButtonLoaded,"survey.id":l});const{useMobileStyling:A,_config:{border:$}}=window.UserLeap;if(!De&&!A){const v=document.createElement("div");v.id="sprig-feedback-loading-container",v.className=`sprig-feedback-loading-container sprig-feedback-loading-container-${f}`,v.style.setProperty("--feedback-border",$),g=v,le(),u==null||u.appendChild(v);const R=qe();J(-R)}else J(0);window.UserLeap._config.isOnQuestionsTab&&t&&!re()&&g&&(Oe(),le(),g&&g.classList.add("sprig-feedback-loading-container-previews"),V(t),B())},xt=()=>{if(re())return;const e=H();if(!e)return;i.checkUrlStillMatching(W)||(e.remove(),W=null,g=null)},Tt=()=>{const e=document.createElement("div");e.id="sprig-feedback-error-container",e.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 t=document.createElement("h3");return t.className="sprig-feedback-error-text",t.innerText="There was an error while loading the survey",e.appendChild(t),e},Pt="!launch_darkly_";class Ct{constructor(){F(this,"_ldData",{})}getAllLaunchDarklyVariations(){return this._ldData}setLDFlagsVariations(t){try{return!t||typeof t!="object"||Array.isArray(t)?!1:(Object.keys(this._ldData).forEach(n=>{delete this._ldData[n]}),Object.keys(t).forEach(n=>this._ldData[`${Pt}${n}`]=(t[n]??0)+1),!0)}catch(n){return n instanceof Error&&window.UserLeap.reportError("setAllLDFlagsVariations",n),console.warn("[Sprig] An issue had occured when setting LaunchDarkly flags and variations."),!1}}}const ce=new Ct;Object.freeze(ce);const Mt="!optimizely_experiments_";class Ft{constructor(){F(this,"_optimizelyData",{})}setOptimizelyExperiment(t,n=!0){if(!t||typeof t!="object")return!1;const{experiments:s}=t;try{return n&&Object.keys(this._optimizelyData).map(r=>{delete this._optimizelyData[r]}),s&&s.map(r=>{const{id:o,variation:a}=r,d=this.transformExperimentId(o);a&&typeof a=="string"&&(this._optimizelyData[d]=a)}),!0}catch(r){return r instanceof Error&&window.UserLeap.reportError("setOptimizelyExperiment",r),!1}}getAllOptimizelyExperiments(){return this._optimizelyData}getOptimizelyVariationName(t){return this._optimizelyData[this.transformExperimentId(t)]}transformExperimentId(t){return Mt+t}getAndSetWebOptimizelyExperiments(){var t;try{if(window&&window.optimizely&&typeof window.optimizely.get=="function"){const n=(t=window.optimizely.get("state"))==null?void 0:t.getExperimentStates({isActive:!0});if(n){const s=Object.keys(n).map(r=>{var o,a;return(o=n[r].variation)!=null&&o.name?{id:r,variation:(a=n[r].variation)==null?void 0:a.name}:{id:r,variation:"Original"}});return this.setOptimizelyExperiment({experiments:s},!1),!0}return!1}return!1}catch(n){return n instanceof Error&&window.UserLeap.reportError("getAndSetWebOptimizely",n),!1}}}const K=new Ft;Object.freeze(K);class Ht{constructor(t,n){F(this,"paused");F(this,"queue");F(this,"ul");this.ul=t,this.paused=!1,this.queue=[],this.flush(n)}flush(t){const n=t.length;if(n)for(let s=0;s<n;s++)this.push(t[s])}isPaused(){return this.paused}pause(){this.paused=!0}unpause(){this.paused=!1;const t=this.queue.slice();this.empty(),this.flush(t)}push(t){if(this.paused)this.queue.push(t);else if(t instanceof Function)t();else{const n=Array.prototype.slice.call(t,1),s=t[0],r=this.ul[s];r instanceof Function?r.apply(this.ul,n):s&&console.warn("[Sprig] (ERR-100) No valid UserLeap action called",s)}}perform(t){if(this.paused){let n=()=>{};const s=new Promise(function(r){n=function(){r(t())}});return this.queue.push(n),s}else return t()}empty(){this.queue.length=0}}let Ke,Je;const pe=e=>{let t=0,n=e.firstElementChild;for(;n;)t+=pe(n),n.shadowRoot&&(t+=pe(n.shadowRoot)),n=n.nextElementSibling,t++;return t},Nt=()=>document.documentElement.innerHTML.length,xe=()=>{Ke.report(pe(document.body)),Je.report(Nt())},Bt=(e=10*1e3)=>{Ke=i.registerMetric("sdk_dom_nodes_count"),Je=i.registerMetric("sdk_page_html_characters"),xe(),setInterval(xe,e)},ue=(e,t)=>{const n=performance.now();document.hidden?setTimeout(()=>ue(e,t),e):setTimeout(()=>{const s=performance.now()-n;t.report(s/1e3),setTimeout(()=>ue(e,t),e)},0)},Vt=(e=1e3)=>{const t=i.registerMetric("sdk_event_queue_latency_seconds");ue(e,t)};let Q,Y,X,Z,C={},Te;const G=(e,t=1)=>{const{name:n}=e;C[n]=(C[n]||0)+t},Qe=e=>{let t=1;return e.childNodes.forEach(n=>{t+=Qe(n)}),t},Pe=e=>{let t=0;return e.forEach(n=>{t+=Qe(n)}),t},Wt=e=>{switch(e.type){case"childList":G(Q,Pe(e.addedNodes)),G(Y,Pe(e.removedNodes));return;case"attributes":G(X);return;case"characterData":G(Z);return}},jt=e=>e.forEach(Wt),zt=()=>{Te=new MutationObserver(jt),Te.observe(document,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0})},$t=()=>{Q.report(C[Q.name]||0),Y.report(C[Y.name]||0),X.report(C[X.name]||0),Z.report(C[Z.name]||0),C={}},qt=(e=1*1e3)=>{Q=i.registerMetric("sdk_mutations_nodes_added"),Y=i.registerMetric("sdk_mutations_nodes_removed"),X=i.registerMetric("sdk_mutations_attributes_changed"),Z=i.registerMetric("sdk_mutations_character_data"),zt(),setInterval($t,e)},Gt=({isWeb:e,reportingIntervalSeconds:t,thresholds:n,postMetrics:s})=>{i.registerThresholds(n,(r,o)=>{var a,d;if((a=i.modules.replay)!=null&&a.isReplayRecording()){const c=`Value: ${r} on ${o.metric} violated threshold of ${o.type} ${o.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:o.metric,type:o.type,value:o.value},{metricName:o.metric}),i.disableThresholdChecking()}}),i.initPerformanceReporting({reportingIntervalSeconds:t,postMetrics:s}),e&&(Vt(),Bt(),qt())},Kt={test:"test"},Jt=["popState","pushState","replaceState"],N="!email",Ye="pageUrl";function Qt(e,t){const{pageUrlEvents:n,interactiveEvents:s,dismissOnPageChange:r}=window.UserLeap._config;if(!r)return!0;const o=[];n&&n.length&&o.push(...n),s&&s.length&&o.push(...s);const a=e&&o.find(d=>d.id===e);return a?i.checkUrlMatch(a,window.location.href):t===window.location.href}function z(e){var d;const{pageUrlEvents:t,interactiveEvents:n,dismissOnPageChange:s,platform:r}=window.UserLeap._config;if(r&&r!=="web")return;const o=P("trackStartUrl"),a=o?String(o):null;t&&tt(window.location.href),n&&(Ze(),Yt()),je()&&xt(),i.sessionStorageHelper.getItem("sprig.isCapturingHeatmap")&&((d=i.modules.replay)==null||d.checkPendingHeatmapsUrl()),!re()&&s&&a&&a!==window.location.href&&e&&Jt.includes(e.type)&&window.UserLeap("dismissActiveSurvey",i.DismissReason.PageChange)}const Xe={capture:!0},Yt=()=>{const t=window.UserLeap._config.interactiveEvents.filter(s=>i.checkUrlMatch(s,window.location.href)).map(s=>{const{name:r,properties:o}=s,{selector:a,innerText:d}=o;return a?c=>{if(Ae(c.target))try{c.target.closest(a)&&window.UserLeap("track",r)}catch{}return!1}:c=>(Ae(c.target)&&c.target.innerText===d&&window.UserLeap("track",r),!1)}),n=s=>t.forEach(r=>r(s));window.UserLeap._config.interactiveEventsHandler=n,window.addEventListener("click",n,Xe)},Ze=()=>{window.UserLeap._config.interactiveEventsHandler&&window.removeEventListener("click",window.UserLeap._config.interactiveEventsHandler,Xe),delete window.UserLeap._config.interactiveEventsHandler};function Xt(){["hashchange","popstate"].forEach(e=>window.addEventListener(e,z,!0))}function Zt(){["hashchange","popstate"].forEach(e=>window.removeEventListener(e,z,!0)),window.UserLeap._config.interactiveEvents&&Ze()}function er(e){const t=new URL(U("1",[O],"questions"));return Object.entries(e||{}).forEach(([n,s])=>{s&&t.searchParams.append(n,String(s))}),t.toString()}function P(e){const t=i.localStorageHelper.getItem("userleap.ids");if(t)try{const s=JSON.parse(t)[window.UserLeap.envId];return s&&s[e]||null}catch(n){n instanceof Error&&(n.stack=t,window.UserLeap.reportError("Failed to parse local storage credentials",n)),console.warn("[Sprig] (ERR-427) Failed to lookup saved ids",n)}return null}function et(){window.previewMode||(window.UserLeap.visitorId=i.v4(),i.info(`Generating new vid: ${window.UserLeap.visitorId}`),S("vid",window.UserLeap.visitorId),i.eventEmitter.emit(i.SprigEvent.VisitorIDUpdated,{visitorId:window.UserLeap.visitorId}))}function tt(e,t,n,s){var r,o;try{if(e.endsWith("mock_snippet.html"))return;i.info(`Tracking page view: ${e}`);const a=window.UserLeap._config.pageUrlEvents;let d=!1;if(a&&a.length)for(let l=0;l<a.length&&(d=i.checkUrlMatch(a[l],e),!d);l++);if(!d)return;window.UserLeap.debugMode&&console.info("[DEBUG] Sprig trackPageView",e);const c={url:e};s&&(c.trackPageView=!0),window.UserLeap._queue.push(["track",Ye,t,c,n]);const p=(r=document==null?void 0:document.querySelector('meta[name="description"]'))==null?void 0:r.getAttribute("content");(o=i.modules.replay)==null||o.RecordPageView({...p&&{description:p},url:e,referrer:document.referrer,pageTitle:document.title})}catch(a){a instanceof Error&&(a.stack=e,window.UserLeap.reportError("trackPageView",a)),console.warn("[Sprig] (ERR-428) Failed to track page view",a)}}function tr(){const e="Backbone"in window&&window.Backbone&&window.Backbone.history?window.Backbone.history:window.history;"pushState"in e&&(e.pushState=(t=>function(...s){const r=t.apply(this,s),o=new Event("pushState");return window.dispatchEvent(o),z(o),r})(e.pushState)),"replaceState"in e&&(e.replaceState=(t=>function(...s){const r=t.apply(this,s),o=new Event("replaceState");return window.dispatchEvent(o),z(o),r})(e.replaceState)),Xt()}async function de(e,t){const n=ge();e&&!t&&(window.UserLeap._config.mode=Kt.test);const s=i.getHttpHeaders(window.UserLeap),r=fe(s),o=await I(er({desktopDisplay:window.UserLeap._config.desktopDisplay,isMobile:r,previewLanguage:window.UserLeap._config.previewLanguage,surveyid:e==null?void 0:e.surveyId,surveytemplateid:e==null?void 0:e.surveyTemplateId,vid:n}),{shouldDropOnRateLimit:!0});if(!o.ok)return o.reportError&&o.error&&(console.warn("[Sprig] (ERR-414) Failed to request questions from the server",o.error),window.UserLeap.reportError("getQuestions",o.error)),{success:!1,surveyState:"no survey"};if(o.json.delay&&await i.delay(o.json.delay),o.json.isFeedback){const{feedbackLabel:a,productConfig:d,surveyUuid:c,feedbackCustomStyles:p}=o.json,{buttonTheme:l,placement:u,desktopDisplay:m}=d,w={customStyles:p,buttonTheme:l,desktopDisplay:m,eventId:0,feedbackLabel:a,placement:u,surveyUuid:c,surveyId:e==null?void 0:e.surveyId};Ge(w,o.json)}else return V(o.json)}function rr(e){let t=e.length;for(;t;){const n=Math.floor(Math.random()*t);t-=1;const s=e[t];e[t]=e[n],e[n]=s}}function ir(e){if(!e)return;window.UserLeap._config=e,e.mute&&window.UserLeap._queue.pause();const{interactiveEvents:t,pageUrlEvents:n,dismissOnPageChange:s}=e;t&&rr(t),(t||n||s)&&(tr(),z())}async function nr(e,t){var s,r;let n=!0;return t&&((s=e==null?void 0:e.json)!=null&&s.surveyId)&&(window.UserLeap.delayingSurvey=!0,n=await t(e.json.surveyId),window.UserLeap.delayingSurvey=!1,!n)?!1:((r=e==null?void 0:e.json)!=null&&r.delay&&!window.UserLeap.isMobileSDK&&(window.UserLeap.delayingSurvey=!0,await i.delay(e.json.delay),window.UserLeap.delayingSurvey=!1),n)}const or=function(e){if(!window.UserLeap)return;const t=async(r={})=>{var v,R,x,k,b;const{userId:o,anonymousId:a,metadata:d={},properties:c,showSurveyCallback:p}=r;let{eventName:l}=r;if(window.UserLeap.debugMode&&l!==Ye&&console.info("[DEBUG] Sprig track",r),e.mode==="test")return;const u=i.localStorageHelper.getItem("sprig.previewKey")??void 0;if(e.requireUserIdForTracking&&!window.UserLeap.userId&&!o){const h="[Sprig] - Skipping tracking without userId";return console.warn(h),{success:!1,message:h,surveyState:"no survey"}}if(!l||l.trim().length===0){l=l?String(l):"";const h="[Sprig] - Invalid event name "+l;return console.warn(h),{success:!1,message:h,surveyState:"no survey"}}const m=window.location.href;if(d.url||(d.url=m),S("trackStartUrl",m),(R=(v=window.UserLeap)==null?void 0:v._config)!=null&&R.optimizelyEnabled){const h=i.getHttpHeaders(window.UserLeap);te(h)||K.getAndSetWebOptimizelyExperiments(),d.optimizelyExperiments=Object.assign({},K.getAllOptimizelyExperiments())}(k=(x=window.UserLeap)==null?void 0:x._config)!=null&&k.launchDarklyEnabled&&(d.launchDarklyFlags=ce.getAllLaunchDarklyVariations()),o&&(window.UserLeap.userId=o),a&&(window.UserLeap.partnerAnonymousId=a),c&&(d.eventProperties=c),(b=i.modules.replay)==null||b.RecordEvent({name:l,url:d.url}),i.info(`Tracking event: ${l}`);const w=window.UserLeap.delayingSurvey||ze()?await I(U("1",[D],"events/batch"),{body:JSON.stringify({events:[{event:l,metadata:d}],previewKey:u}),method:"POST",shouldDropOnRateLimit:!0}):await I(U("1",[D],"events"),{body:JSON.stringify({event:l,metadata:d,previewKey:u}),method:"POST",shouldDropOnRateLimit:!0});if(!w.ok){const h="[Sprig] (ERR-421) Failed to track event";return w.reportError&&(console.warn(h,w.error),w.error&&window.UserLeap.reportError("track",w.error)),{success:!1,message:h,error:w.error,surveyState:"no survey"}}o&&S("uid",o),a&&S("aid",a);const f=w.json;f.invalidPreviewKey&&i.localStorageHelper.removeItem("sprig.previewKey");const L=d.trackPageView?d.url:void 0;return!!(f!=null&&f.feedbackButton)&&Ge(f.feedbackButton,void 0,L),await nr(w,p)?Qt(f.eventId,m)?V(f,L):{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"}},n=(r,o)=>{var d;const a=(d=r==null?void 0:r.querySelector(`[id="${me}"]`))==null?void 0:d.contentDocument;a&&j({document:a,elementId:"ul-custom-style",styleString:o})},s={async displaySurvey(r){return console.warn("[Sprig] displaySurvey should only be used to debug your studies; not intended for production usage."),window.UserLeap("dismissActiveSurvey",i.DismissReason.Override),de({surveyId:r},!0)},_previewSurvey(r){window.UserLeap("dismissActiveSurvey",i.DismissReason.Override),de({surveyTemplateId:r},!1)},_reviewSurvey(r){window.UserLeap("dismissActiveSurvey",i.DismissReason.Override),de({surveyId:r},!1)},previewSurvey(r){s._previewSurvey(r)},reviewSurvey(r){s._reviewSurvey(r)},mute(){window.UserLeap._queue.pause()},unmute(){window.UserLeap._queue.unpause()},setVisitorToken(){console.warn("[Sprig] setVisitorToken is deprecated.")},dismissActiveSurvey(r=i.DismissReason.API){i.eventEmitter.emit(i.SprigEvent.SurveyWillClose,{name:i.SprigEvent.SurveyWillClose,initiator:r})},async setAttribute(r,o){if(!r||!o&&o!==0&&o!==!1){const a="[Sprig] - Disregarding empty attribute / value provided";return console.warn(a),{success:!1,message:a}}return this.setAttributes({[r]:o})},async setAttributes(r){if(r==null||Object.keys(r).length===0){const o="[Sprig] - Disregarding empty attributes provided";return console.warn(o),{success:!1,message:o}}return this.identifyAndSetAttributes({attributes:r})},async identifyAndSetAttributes(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig identifyAndSetAttributes",r),e.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:o,anonymousId:a,attributes:d}=r;if(e.requireUserIdForTracking&&!window.UserLeap.userId&&!o){const l="[Sprig] - Skipping tracking without userId";return console.warn(l),{success:!1,message:l}}if(!d&&(!o||window.UserLeap.userId===o)&&(!a||window.UserLeap.partnerAnonymousId===a))return{success:!0};const c={};o&&(c.userId=window.UserLeap.userId=o),a&&(c.partnerAnonymousId=window.UserLeap.partnerAnonymousId=a);let p;return d?(d.email&&!Object.prototype.hasOwnProperty.call(d,N)&&(d[N]=d.email,delete d.email),i.info(`Setting attributes: ${JSON.stringify(d)}`),p=await I(U("1",[O,D],"attributes"),{body:JSON.stringify(d),method:"PUT"}),!p.ok&&p.reportError&&(console.warn("[Sprig] (ERR-432) identifyAndSetAttributes failed",p.error),p.error&&window.UserLeap.reportError("identifyAndSetAttributes",p.error))):p=await I(U("1",[O,D]),{body:JSON.stringify(c),method:"PUT"}),d&&d[N]&&(window.UserLeap.email=d[N]),p.ok&&(o&&S("uid",o),a&&S("aid",a)),{success:!!p.ok}},async removeAttributes(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig removeAttributes",r),e.mode==="test")return;if(r==null||r.length===0){const a="[Sprig] - Disregarding empty attributes provided";return console.warn(a),{success:!1,message:a}}if(e.requireUserIdForTracking&&!window.UserLeap.userId){const a="[Sprig] - Skipping tracking without userId";return console.warn(a),{success:!1,message:a}}const o=await I(U("1",[O,D],"attributes"),{body:JSON.stringify({delete:r}),method:"DELETE"});return!o.ok&&o.reportError&&(console.warn("[Sprig] (ERR-433) Remove attributes failed",o.error),o.error&&window.UserLeap.reportError("removeAttributes",o.error)),{success:!!o.ok}},async addSurveyListener(r){i.eventEmitter.on(i.SprigEvent.SurveyLifeCycle,r)},async removeSurveyListener(r){i.eventEmitter.removeListener(i.SprigEvent.SurveyLifeCycle,r)},async addListener(r,o){i.eventEmitter.on(r,o)},async removeListener(r,o){i.eventEmitter.removeListener(r,o)},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(e.mode==="test"||r===window.UserLeap.userId)return;window.UserLeap.userId=r;const o=window.UserLeap.visitorId,a=await I(U("1",[O,D]),{body:JSON.stringify({userId:r}),method:"PUT"});if(!a.ok){a.reportError&&(console.warn("[Sprig] (ERR-420) Failed to set user id",a.error),a.error&&window.UserLeap.reportError("setUserId",a.error));return}o!==window.UserLeap.visitorId&&((d=i.modules.replay)==null||d.clearUserReplayData()),S("uid",r)},async setPartnerAnonymousId(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig setPartnerAnonymousId",r),r==null){const o=`[Sprig] - Invalid partnerAnonymousId ${r}`;return console.warn(o),{success:!1,message:o}}return window.UserLeap.partnerAnonymousId=r,S("aid",r),{success:!0}},async track(r,o,a={},d=void 0){return t({eventName:r,properties:o,metadata:a,showSurveyCallback:d})},async identifyAndTrack(r){return await t(r)},trackPageView(r,o=void 0,a=void 0,d=!0){tt(r,o,a,d)},applyFeedbackStyles({button:r="",view:o=""}){window.UserLeap.feedbackCustomStyles=o,document.getElementById("sprig-feedback-style")&&j({document,elementId:"ul-custom-style",styleString:r,nonce:window.UserLeap.styleNonce}),n(document.querySelector(".ul-container-feedback"),o)},applyStyles(r){window.UserLeap.customStyles=r,n(window.UserLeap.container,r)},setWindowDimensions(r,o){var p,l;const a=typeof r=="string"?parseInt(r,10):r,d=typeof o=="string"?parseInt(o,10):o;if(!isNaN(a)&&!isNaN(d)&&(window.UserLeap.windowDimensions={width:a,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(We(c.contentDocument)[0])+"px")),i.eventEmitter.emit(i.SprigEvent.SurveyDimensions,{name:i.SprigEvent.SurveyDimensions,contentFrameWidth:c.clientWidth,contentFrameHeight:c.clientHeight}))},logoutUser(){var r;window.UserLeap.debugMode&&console.info("[DEBUG] Sprig logout"),i.info(`Logging out user: ${window.UserLeap.userId} / vid: ${window.UserLeap.visitorId}`),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(),et(),(r=i.modules.replay)==null||r.clearUserReplayData(),window.UserLeap._queue.unpause()},teardown(){Zt(),window.UserLeap("dismissActiveSurvey",i.DismissReason.API),delete window.UserLeap,delete window.Sprig,delete window._Sprig},integrateOptimizely(r,o=!0){var a,d;if(!((d=(a=window.UserLeap)==null?void 0:a._config)!=null&&d.optimizelyEnabled)){console.warn("[SPRIG] Optimizely integration is currently not enabled for your product.");return}try{const c=typeof r=="string"?JSON.parse(r):r;K.setOptimizelyExperiment(c,o)}catch(c){console.warn("[Sprig] Error with integrating Optimizely data"),c instanceof Error&&window.UserLeap.reportError("integrateOptimizely",c)}},integrateOptimizelyClient(r){var a,d;if(!((d=(a=window.UserLeap)==null?void 0:a._config)!=null&&d.optimizelyEnabled)){console.warn("[SPRIG] Optimizely integration is currently not enabled for your product.");return}const o=({experiment:c,variation:p})=>{const l={experiments:[{id:c.id,variation:p.key}]};window.UserLeap("integrateOptimizely",l,!1)};r.notificationCenter.addNotificationListener("ACTIVATE:experiment, user_id,attributes, variation, event",o)},importLaunchDarklyData(r){var o,a;if(!((a=(o=window.UserLeap)==null?void 0:o._config)!=null&&a.launchDarklyEnabled)){console.warn("[SPRIG] LaunchDarkly integration is currently not enabled for your product.");return}ce.setLDFlagsVariations(r)},setVisitorAttribute(r,o){return console.warn("[Sprig] setVisitorAttribute is deprecated. Please use setAttribute"),s.setAttribute(r,o)},async setEmail(r){return s.setAttribute(N,r)},async setVisitorEmail(r){return console.warn("[Sprig] setVisitorEmail is deprecated. Please use setEmail"),s.setEmail(r)},async _generateVideoUploadUrl(r){return lr(r)},_reportMetric(r,o){i.reportAndRegister(r,o)},async _completeSessionReplay({surveyId:r,responseGroupUuid:o,eventDigest:a}){var d;return i.modules.replay?(d=i.modules.replay)==null?void 0:d._completeSessionReplay({surveyId:r,responseGroupUuid:o,eventDigest:a,headers:i.getHttpHeaders(window.UserLeap)}):(window.UserLeap.reportError("_completeSessionReplay",new Error("Replay module not registered")),!1)}};Object.assign(window.UserLeap,s)};async function sr(e){const t=i.getHttpHeaders(window.UserLeap);document.addEventListener("securitypolicyviolation",i.cspViolationHandler);const n=await i.sprigFetch(U("1",[O],"config"),{headers:t});if(document.removeEventListener("securitypolicyviolation",i.cspViolationHandler),!n.ok)return n.reportError&&(console.warn("[Sprig] (ERR-422) Failed to load configuration",n.error),n.error&&window.UserLeap.reportError("applyRemoteConfig",n.error)),i.killNetworkRequests("Disabled: failed to fetch configuration"),e;const s=n.json;return s!=null&&s.disabled?(i.killNetworkRequests(`Disabled: ${s.disabled}`),{disabled:s.disabled}):Object.assign({},s,e)}const ar=e=>typeof e=="object"&&e&&"inner"in e&&!!e.inner&&typeof e.inner=="object";async function dr(e,t,n={},s={}){var m,w;const r=window.__cfg&&window.__cfg.mode,o=ge(),a=window.UserLeap.envId,d=window.document.documentElement,c=ar(t)?{inner:{message:(m=t.inner)==null?void 0:m.message,stack:(w=t.inner)==null?void 0:w.stack}}:{},p={mode:r,screenWidth:window.screen.width,screenHeight:window.screen.height,clientWidth:d.clientWidth,clientHeight:d.clientHeight,location:window.location.href,language:window.navigator.language,...n,...c},l={action:e,err:{message:t.message,stack:t.stack},meta:p,vid:o,envId:a,...s},u=await I(U("1",null,"errors"),{method:"POST",headers:{"x-ul-error":window.btoa(`userleap-${Date.now()}-error`)},body:JSON.stringify(l),shouldDropOnRateLimit:!0});if(!u.ok)console.warn("[Sprig] (ERR-444) Failed to report error to API",t);else{const{presignedUrl:f}=u.json;i.uploadLogfile(f)}}async function lr(e){var n;if(!e)return;const t=`${window.UserLeap._API_URL}/2/environments/integrations/upload`;try{const s=await fetch(t,{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(s.ok){const r=await s.json();return(n=r==null?void 0:r.upload)==null?void 0:n.url}else return null}catch(s){console.warn("[Sprig] Error with generating video upload url"),s instanceof Error&&window.UserLeap.reportError("generateVideoUploadUrl",s)}}function cr(e={}){const t=new URLSearchParams(window.location.search).get("sprigPreviewKey")??"";window.UserLeap.UPDATES=i.EVENTS,window.UserLeap("setPreviewKey",t);async function n(){var p;if(window.UserLeap.loaded)return;if(i.info("Loading sprig on page load"),window.UserLeap.reportError=dr,window.UserLeap.loaded=!0,window.UserLeap._config=Object.assign({},e,window.UserLeap.config),window.UserLeap.delayingSurvey=!1,window.UserLeap._config&&typeof window.UserLeap._config=="object")for(const l in window.UserLeap._config)window.UserLeap[l]=window.UserLeap._config[l];if(!window.UserLeap.envId)if(window.UserLeap.appId)window.UserLeap.envId=window.UserLeap.appId;else throw new Error("Missing Environment id");window.UserLeap.debugMode&&console.info("[DEBUG] Sprig debug mode enabled");const s=window.UserLeap.sampleRate;if(s){let l=P("sampled");if(l===null&&(l=Math.random()<s,S("sampled",l)),!l)return}else P("sampled")!==null&&S("sampled",null);window.UserLeap._API_URL||(window.UserLeap._API_URL="https://api.sprig.com");const r=[...window.UserLeap._queue];window.UserLeap._queue=new Ht(window.UserLeap,[]),window.UserLeap._queue.pause();for(let l=0;l<r.length;l++)window.UserLeap._queue.push(r[l]);const o=P("token");o?(window.UserLeap.token=o,window.UserLeap.visitorId=P("vid"),window.UserLeap.userId=P("uid"),window.UserLeap.partnerAnonymousId=P("aid")):(i.localStorageHelper.removeItem("userleap.ids"),et());const a=i.getHttpHeaders(window.UserLeap),d=te(a),c=await sr(e);Gt({isWeb:!d,reportingIntervalSeconds:c.metricsReportingEnabled||c.mobileMetricsReportingEnabled?c.metricsReportingIntervalSeconds:0,thresholds:c.metricThresholds,postMetrics:async l=>{var u;await I(U("1",[O],"metrics"),{body:l,method:"POST",headers:{"x-ul-replay-enabled":`${!!((u=i.modules.replay)!=null&&u.isReplayRecording())}`},shouldDropOnRateLimit:!0})}}),(p=i.modules.replay)==null||p.initializeReplay({viewDocument:window.document,maxReplayDurationSeconds:c.maxReplayDurationSeconds,replayNonce:window.UserLeap.replayNonce,maxInflightRequests:window.UserLeap.maxInflightReplayRequests??2,replaySettings:c.replaySettings}),i.configureLogger(c.logBufferLimit,c.logLevel),or(c),await ir(c),window.UserLeap._queue.unpause(),i.eventEmitter.emit(i.SprigEvent.SDKReady,{mobileMetricsReportingEnabled:!!c.mobileMetricsReportingEnabled,metricsReportingInterval:c.metricsReportingIntervalSeconds||0,metricsThresholds:c.metricThresholds||[],maxMobileReplayDurationSeconds:c.maxMobileReplayDurationSeconds,mobileReplaySettings:c.mobileReplaySettings}),i.eventEmitter.emit(i.SprigEvent.VisitorIDUpdated,{visitorId:window.UserLeap.visitorId})}document.readyState==="complete"?n():window.attachEvent?window.attachEvent("onload",n):window.addEventListener("load",()=>{n()},!1)}class ee{constructor(){this.UPDATES=i.EVENTS}displaySurvey(t){window.Sprig("displaySurvey",t)}mute(){window.Sprig("mute")}unmute(){window.Sprig("unmute")}dismissActiveSurvey(){window.Sprig("dismissActiveSurvey")}setAttribute(t,n){window.Sprig("setAttribute",t,n)}setAttributes(t){window.Sprig("setAttributes",t)}identifyAndSetAttributes(t){window.Sprig("identifyAndSetAttributes",t)}removeAttributes(t){window.Sprig("removeAttributes",t)}addListener(t,n){window.Sprig("addListener",t,n)}removeListener(t,n){window.Sprig("removeListener",t,n)}removeAllListeners(){window.Sprig("removeAllListeners")}setEmail(t){window.Sprig("setAttribute","!email",t)}setUserId(t){window.Sprig("setUserId",t)}setPartnerAnonymousId(t){window.Sprig("setPartnerAnonymousId",t)}track(t,n={},s={}){window.Sprig("track",t,n,s)}identifyAndTrack(t){window.Sprig("identifyAndTrack",t)}trackPageView(t,n,s){window.Sprig("trackPageView",t,n,s)}applyStyles(t){window.Sprig("applyStyles",t)}setWindowDimensions(t,n){window.Sprig("setWindowDimensions",t,n)}logoutUser(){window.Sprig("logoutUser")}teardown(){window.Sprig("teardown")}}const we={configure:e=>{if(!e.envId&&!e.environmentId)throw new Error("Initialization Error: Sprig configure requires an environmentId");if(e.envId||(e.envId=e.environmentId??""),e.installationMethod="web-npm",window.Sprig)return window.Sprig;window.Sprig=function(){window.Sprig._queue.push(arguments)},Object.getOwnPropertyNames(ee.prototype).map(n=>{n!=="constructor"&&(window.Sprig[n]=ee.prototype[n])});const t=window.Sprig;return t.appId=e.envId,t._queue=[],window.UserLeap=t,cr(e),window.Sprig}},pr={sprig:we,SprigAPI:ee,configure:we.configure};exports.APP_ID=ct;exports.ConflictingWidgets=Fe;exports.DEFAULT_BORDER_COLOR=pt;exports.DEFAULT_WIDTH=Ce;exports.EMBED_MOBILE_MAX_WIDTH=gt;exports.ERROR_BORDER_COLOR=ut;exports.SprigAPI=ee;exports.calculateFrameDimensions=We;exports.core=pr;exports.resetScrollPosition=_t;exports.setSurveyStyles=j;exports.sprig=we;
|
package/dist/core.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const r=require("./metricsReporter-
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const r=require("./metricsReporter-DaSVYNOK.cjs"),e=require("./core-D0ATZnzx.cjs");exports.DismissReason=r.DismissReason;exports.SprigEvent=r.SprigEvent;exports.SprigAPI=e.SprigAPI;exports.default=e.core;exports.sprig=e.sprig;
|
package/dist/core.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{D as s,S as a}from"./metricsReporter-
|
|
1
|
+
import{D as s,S as a}from"./metricsReporter-D-m62w_D.js";import{S as r,c as i,s as o}from"./core-CZcCXjci.js";export{s as DismissReason,r as SprigAPI,a as SprigEvent,i as default,o as sprig};
|
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-D0ATZnzx.cjs");require("./replay.cjs");const r=require("./metricsReporter-DaSVYNOK.cjs");exports.SprigAPI=e.SprigAPI;exports.default=e.core;exports.sprig=e.sprig;exports.DismissReason=r.DismissReason;exports.SprigEvent=r.SprigEvent;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{S as s,c as a,s as i}from"./core-
|
|
1
|
+
import{S as s,c as a,s as i}from"./core-CZcCXjci.js";import"./replay.js";import{D as r,S as o}from"./metricsReporter-D-m62w_D.js";export{r as DismissReason,s as SprigAPI,o as SprigEvent,a as default,i as sprig};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var J=Object.defineProperty,K=(e,t,s)=>t in e?J(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,a=(e,t,s)=>(K(e,typeof t!="symbol"?t+"":t,s),s),k=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.FeedbackClosed="feedback.closed",e.PageChange="page.change",e.API="api",e.Override="override",e))(k||{}),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||{});const B={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"}};let _;const G=new Uint8Array(16);function z(){if(!_&&(_=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!_))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return _(G)}const n=[];for(let e=0;e<256;++e)n.push((e+256).toString(16).slice(1));function Q(e,t=0){return n[e[t+0]]+n[e[t+1]]+n[e[t+2]]+n[e[t+3]]+"-"+n[e[t+4]]+n[e[t+5]]+"-"+n[e[t+6]]+n[e[t+7]]+"-"+n[e[t+8]]+n[e[t+9]]+"-"+n[e[t+10]]+n[e[t+11]]+n[e[t+12]]+n[e[t+13]]+n[e[t+14]]+n[e[t+15]]}const X=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),D={randomUUID:X};function Z(e,t,s){if(D.randomUUID&&!t&&!e)return D.randomUUID();e=e||{};const r=e.random||(e.rng||z)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Q(r)}var ee=class extends Error{constructor(e,t,s){super(`Possible EventEmitter memory leak detected. ${s} ${t.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`),this.emitter=e,this.type=t,this.count=s,this.name="MaxListenersExceededWarning"}},U=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=U.defaultMaxListeners,this.hasWarnedAboutPotentialMemoryLeak=!1}_emitInternalEvent(e,t,s){this.emit(e,t,s)}_getListeners(e){return Array.prototype.concat.apply([],this.events.get(e))||[]}_removeListener(e,t){const s=e.indexOf(t);return s>-1&&e.splice(s,1),[]}_wrapOnceListener(e,t){const s=(...r)=>(this.removeListener(e,s),t.apply(this,r));return Object.defineProperty(s,"name",{value:t.name}),s}setMaxListeners(e){return this.maxListeners=e,this}getMaxListeners(){return this.maxListeners}eventNames(){return Array.from(this.events.keys())}emit(e,...t){const s=this._getListeners(e);return s.forEach(r=>{r.apply(this,t)}),s.length>0}addListener(e,t){this._emitInternalEvent("newListener",e,t);const s=this._getListeners(e).concat(t);if(this.events.set(e,s),this.maxListeners>0&&this.listenerCount(e)>this.maxListeners&&!this.hasWarnedAboutPotentialMemoryLeak){this.hasWarnedAboutPotentialMemoryLeak=!0;const r=new ee(this,e,this.listenerCount(e));console.warn(r)}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 s=this._getListeners(e);if(s.length>0){const r=[t].concat(s);this.events.set(e,r)}else this.events.set(e,s.concat(t));return this}prependOnceListener(e,t){return this.prependListener(e,this._wrapOnceListener(e,t))}removeListener(e,t){const s=this._getListeners(e);return s.length>0&&(this._removeListener(s,t),this.events.set(e,s),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=U;C.defaultMaxListeners=10;const te=new C,w=async e=>{await new Promise(t=>{setTimeout(t,e)})},se=({"userleap-platform":e})=>e!=="web";class x{constructor(t){a(this,"storage"),a(this,"tempStorage",{}),a(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,s){this.isStorageAvailable?this.storage.setItem(t,s):this.tempStorage[t]=s}getItem(t){return this.isStorageAvailable?this.storage.getItem(t):this.tempStorage[t]}removeItem(t){this.isStorageAvailable?this.storage.removeItem(t):delete this.tempStorage[t]}clear(){this.isStorageAvailable?this.storage.clear():this.tempStorage={}}}const re=new x("sessionStorage"),ne=new x("localStorage");class ie{constructor(t){a(this,"payload"),a(this,"promise"),a(this,"reject",()=>{}),a(this,"resolve",()=>{}),this.payload=t,this.promise=new Promise((s,r)=>{this.reject=r,this.resolve=s})}resolveRequest(t){this.resolve(t)}}const I={replay:null},oe=e=>{I.replay=e},ae=()=>{const e=[];return I.replay&&e.push("replay"),e.join(",")},le={RATELIMIT_RESET_DEFAULT:10};let T=!1,P="",g=!1,M=!1,E=[];const ce=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?"web-gtm":e._segment?"web-segment":"web-snippet",ue=e=>{var t;(t=e?.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(M=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`))},N=(e="")=>{T=!0,P=e};function de(e={}){const t={"Content-Type":"application/json","userleap-platform":"web","x-ul-sdk-version":"2.31.
|
|
1
|
+
var J=Object.defineProperty,K=(e,t,s)=>t in e?J(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,a=(e,t,s)=>(K(e,typeof t!="symbol"?t+"":t,s),s),k=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.FeedbackClosed="feedback.closed",e.PageChange="page.change",e.API="api",e.Override="override",e))(k||{}),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||{});const B={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"}};let _;const G=new Uint8Array(16);function z(){if(!_&&(_=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!_))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return _(G)}const n=[];for(let e=0;e<256;++e)n.push((e+256).toString(16).slice(1));function Q(e,t=0){return n[e[t+0]]+n[e[t+1]]+n[e[t+2]]+n[e[t+3]]+"-"+n[e[t+4]]+n[e[t+5]]+"-"+n[e[t+6]]+n[e[t+7]]+"-"+n[e[t+8]]+n[e[t+9]]+"-"+n[e[t+10]]+n[e[t+11]]+n[e[t+12]]+n[e[t+13]]+n[e[t+14]]+n[e[t+15]]}const X=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),D={randomUUID:X};function Z(e,t,s){if(D.randomUUID&&!t&&!e)return D.randomUUID();e=e||{};const r=e.random||(e.rng||z)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Q(r)}var ee=class extends Error{constructor(e,t,s){super(`Possible EventEmitter memory leak detected. ${s} ${t.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`),this.emitter=e,this.type=t,this.count=s,this.name="MaxListenersExceededWarning"}},U=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=U.defaultMaxListeners,this.hasWarnedAboutPotentialMemoryLeak=!1}_emitInternalEvent(e,t,s){this.emit(e,t,s)}_getListeners(e){return Array.prototype.concat.apply([],this.events.get(e))||[]}_removeListener(e,t){const s=e.indexOf(t);return s>-1&&e.splice(s,1),[]}_wrapOnceListener(e,t){const s=(...r)=>(this.removeListener(e,s),t.apply(this,r));return Object.defineProperty(s,"name",{value:t.name}),s}setMaxListeners(e){return this.maxListeners=e,this}getMaxListeners(){return this.maxListeners}eventNames(){return Array.from(this.events.keys())}emit(e,...t){const s=this._getListeners(e);return s.forEach(r=>{r.apply(this,t)}),s.length>0}addListener(e,t){this._emitInternalEvent("newListener",e,t);const s=this._getListeners(e).concat(t);if(this.events.set(e,s),this.maxListeners>0&&this.listenerCount(e)>this.maxListeners&&!this.hasWarnedAboutPotentialMemoryLeak){this.hasWarnedAboutPotentialMemoryLeak=!0;const r=new ee(this,e,this.listenerCount(e));console.warn(r)}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 s=this._getListeners(e);if(s.length>0){const r=[t].concat(s);this.events.set(e,r)}else this.events.set(e,s.concat(t));return this}prependOnceListener(e,t){return this.prependListener(e,this._wrapOnceListener(e,t))}removeListener(e,t){const s=this._getListeners(e);return s.length>0&&(this._removeListener(s,t),this.events.set(e,s),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=U;C.defaultMaxListeners=10;const te=new C,w=async e=>{await new Promise(t=>{setTimeout(t,e)})},se=({"userleap-platform":e})=>e!=="web";class x{constructor(t){a(this,"storage"),a(this,"tempStorage",{}),a(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,s){this.isStorageAvailable?this.storage.setItem(t,s):this.tempStorage[t]=s}getItem(t){return this.isStorageAvailable?this.storage.getItem(t):this.tempStorage[t]}removeItem(t){this.isStorageAvailable?this.storage.removeItem(t):delete this.tempStorage[t]}clear(){this.isStorageAvailable?this.storage.clear():this.tempStorage={}}}const re=new x("sessionStorage"),ne=new x("localStorage");class ie{constructor(t){a(this,"payload"),a(this,"promise"),a(this,"reject",()=>{}),a(this,"resolve",()=>{}),this.payload=t,this.promise=new Promise((s,r)=>{this.reject=r,this.resolve=s})}resolveRequest(t){this.resolve(t)}}const I={replay:null},oe=e=>{I.replay=e},ae=()=>{const e=[];return I.replay&&e.push("replay"),e.join(",")},le={RATELIMIT_RESET_DEFAULT:10};let T=!1,P="",g=!1,M=!1,E=[];const ce=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?"web-gtm":e._segment?"web-segment":"web-snippet",ue=e=>{var t;(t=e?.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(M=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`))},N=(e="")=>{T=!0,P=e};function de(e={}){const t={"Content-Type":"application/json","userleap-platform":"web","x-ul-sdk-version":"2.31.2","x-ul-installation-method":ce(e),"sprig-modules":ae()};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 s=JSON.parse(e.mobileHeadersJSON);Object.assign(t,s)}return e.locale&&(t["accept-language"]=e.locale),window.previewMode&&(t["x-ul-preview-mode"]="1"),t}const V=async({shouldDropOnRateLimit:e,...t})=>{if(e)return{status:429};{const s=new ie(t);return E.push(s),s.promise}},p=async(e,t)=>{const{retries:s=0,shouldDropOnRateLimit:r=!1,shouldRetryRequest:v=!1,...l}=t,c={url:e,options:l,retries:s,shouldDropOnRateLimit:r};if(g&&!v)return V(c);const h={ok:!1,reportError:!1};if(T)return console.info(`UserLeap - ${P}`),h;try{const o=await fetch(e,l);if(o.status===429)if(!g&&!r||v){g=!0;const i=o.headers.has("ratelimit-reset")?Number(o.headers.get("ratelimit-reset")):le.RATELIMIT_RESET_DEFAULT;return await w(i*1e3),p(e,{...l,shouldDropOnRateLimit:r,shouldRetryRequest:!0})}else return V(c);if(g=!1,E.length&&(E.map(i=>{const y=i.payload;p(y.url,{...y.options,retries:y.retries,shouldDropOnRateLimit:y.shouldDropOnRateLimit}).then(H=>{i.resolveRequest(H)})}),E=[]),o.ok){if(o.status===249)return N(),h;const i=await o.text();try{return i&&i!=="OK"&&(o.json=JSON.parse(i)),o}catch{return{ok:!1,reportError:!1,error:new Error(`failed parsing response json for ${e} - ${i}`)}}}return o}catch(o){const i=s+1;return i>5||M?{ok:!1,reportError:!1,error:o}:(await w(Math.pow(2,s)*1e3),p(e,{...l,retries:i}))}},u={Error:1,Warn:2,Info:3,Debug:4};let b=1e3,f=u.Debug,d=[];const he=e=>{const t=Object.entries(u).find(s=>s[1]===e);return t?.[0]??""},pe=e=>e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3}),me=(e,t)=>`${pe(t)}:${e}`,ve=()=>{d=d.filter(e=>e.level<=f)},ye=()=>{d.length>b&&d.shift()},S=(e,t)=>{e>f||(d.push({level:e,line:me(t,new Date)}),ye())},W=e=>{S(u.Debug,e)},_e=e=>{S(u.Info,e)},Y=e=>{S(u.Warn,e)},ge=e=>{S(u.Error,e)},Ee=()=>d.map(e=>e.line),fe=()=>new TextEncoder().encode(Ee().join(`
|
|
2
2
|
`)),Se=async e=>{if(!e)return;const t=fe();return p(e,{body:t,method:"PUT"})},Le=(e,t)=>{e!==void 0&&(b=e),t!==void 0&&(f=t),W(`Initializing logger with limit of ${b} lines and ${he(f)} level`),ve()},j=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 $(e,t){const{matchType:s,pattern:r}=e,v=s?j[s]:j.legacy;let l=!1;try{l=v(r,t)}catch(c){const h=`[Sprig] (ERR-445) Failed to check url match with pattern ${r}`;c instanceof Error&&(console.warn(h,c),c.stack=JSON.stringify(e),window.UserLeap.reportError(h,c))}return l}const we=e=>{const{pageUrlEvents:t}=window.UserLeap._config,s=t?.find(r=>r.id===e);return s?$(s,window.location.href):!1};let F=!0,R=!1;const Ie=()=>F=!1,be=()=>R=!0,Re=["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 m={},O;class Oe{constructor(t){a(this,"_values",[]),a(this,"_isWebMetric"),this.name=t,this._isWebMetric=Re.includes(this.name)}report(t){if(F&&this._values.push({time:Date.now(),value:t}),R||!this._isWebMetric)return;const s=this.findExceededThreshold(t);s&&O&&O(t,s)}collect(){const t=this._values;return this._values=[],t}findExceededThreshold(t){const s=m[this.name];if(s)return s.find(r=>this.valueExceedsThreshold(t,r))}valueExceedsThreshold(t,s){return s.type==="max"?t>s.value:s.type==="min"?t<s.value:!1}}const ke=(e,t)=>{m={},R=!1,e?.forEach(s=>{var r;s.metric in m||(m[s.metric]=[]),(r=m[s.metric])==null||r.push(s)}),O=t},L={},q=e=>{const t=new Oe(e);return L[e]=t,t},Ae=(e,t)=>{let s=L[e];return s||(s=q(e)),s.report(t)},De=async e=>{const t=Object.values(L).map(s=>({name:s.name,values:s.collect()}));if(t.some(s=>s.values.length))try{await e(JSON.stringify(t))}catch(s){Y(`Error posting metrics: ${s}`)}},Ue=({reportingIntervalSeconds:e,postMetrics:t})=>{e?setInterval(()=>{De(t)},e*1e3):Ie()};export{k as D,B as E,L as P,A as S,re as a,Ae as b,we as c,te as d,ge as e,W as f,oe as g,de as h,_e as i,se as j,ke as k,ne as l,I as m,Ue as n,be as o,Le as p,ue as q,q as r,p as s,N as t,Se as u,Z as v,Y as w,$ as x,w as y};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var B=Object.defineProperty;var J=(e,t,r)=>t in e?B(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var a=(e,t,r)=>(J(e,typeof t!="symbol"?t+"":t,r),r);var O=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.FeedbackClosed="feedback.closed",e.PageChange="page.change",e.API="api",e.Override="override",e))(O||{}),U=(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))(U||{});const K={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"}};let g;const G=new Uint8Array(16);function Q(){if(!g&&(g=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!g))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return g(G)}const n=[];for(let e=0;e<256;++e)n.push((e+256).toString(16).slice(1));function z(e,t=0){return n[e[t+0]]+n[e[t+1]]+n[e[t+2]]+n[e[t+3]]+"-"+n[e[t+4]]+n[e[t+5]]+"-"+n[e[t+6]]+n[e[t+7]]+"-"+n[e[t+8]]+n[e[t+9]]+"-"+n[e[t+10]]+n[e[t+11]]+n[e[t+12]]+n[e[t+13]]+n[e[t+14]]+n[e[t+15]]}const X=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),A={randomUUID:X};function Z(e,t,r){if(A.randomUUID&&!t&&!e)return A.randomUUID();e=e||{};const s=e.random||(e.rng||Q)();return s[6]=s[6]&15|64,s[8]=s[8]&63|128,z(s)}var ee=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"}},x=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=x.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 ee(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)}},D=x;D.defaultMaxListeners=10;const te=new D,R=async e=>{await new Promise(t=>{setTimeout(t,e)})},re=({"userleap-platform":e})=>e!=="web";class M{constructor(t){a(this,"storage");a(this,"tempStorage",{});a(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}getItem(t){return this.isStorageAvailable?this.storage.getItem(t):this.tempStorage[t]}removeItem(t){this.isStorageAvailable?this.storage.removeItem(t):delete this.tempStorage[t]}clear(){this.isStorageAvailable?this.storage.clear():this.tempStorage={}}}const se=new M("sessionStorage"),ne=new M("localStorage");class ie{constructor(t){a(this,"payload");a(this,"promise");a(this,"reject",()=>{});a(this,"resolve",()=>{});this.payload=t,this.promise=new Promise((r,s)=>{this.reject=s,this.resolve=r})}resolveRequest(t){this.resolve(t)}}const k={replay:null},oe=e=>{k.replay=e},ae=()=>{const e=[];return k.replay&&e.push("replay"),e.join(",")},le={RATELIMIT_RESET_DEFAULT:10};let P=!1,V="",_=!1,H=!1,L=[];const ce=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?"web-gtm":e._segment?"web-segment":"web-snippet",ue=e=>{var t;(t=e==null?void 0:e.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(H=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`))},W=(e="")=>{P=!0,V=e};function de(e={}){const t={"Content-Type":"application/json","userleap-platform":"web","x-ul-sdk-version":"2.31.
|
|
1
|
+
"use strict";var B=Object.defineProperty;var J=(e,t,r)=>t in e?B(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var a=(e,t,r)=>(J(e,typeof t!="symbol"?t+"":t,r),r);var O=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.FeedbackClosed="feedback.closed",e.PageChange="page.change",e.API="api",e.Override="override",e))(O||{}),U=(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))(U||{});const K={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"}};let g;const G=new Uint8Array(16);function Q(){if(!g&&(g=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!g))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return g(G)}const n=[];for(let e=0;e<256;++e)n.push((e+256).toString(16).slice(1));function z(e,t=0){return n[e[t+0]]+n[e[t+1]]+n[e[t+2]]+n[e[t+3]]+"-"+n[e[t+4]]+n[e[t+5]]+"-"+n[e[t+6]]+n[e[t+7]]+"-"+n[e[t+8]]+n[e[t+9]]+"-"+n[e[t+10]]+n[e[t+11]]+n[e[t+12]]+n[e[t+13]]+n[e[t+14]]+n[e[t+15]]}const X=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),A={randomUUID:X};function Z(e,t,r){if(A.randomUUID&&!t&&!e)return A.randomUUID();e=e||{};const s=e.random||(e.rng||Q)();return s[6]=s[6]&15|64,s[8]=s[8]&63|128,z(s)}var ee=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"}},x=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=x.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 ee(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)}},D=x;D.defaultMaxListeners=10;const te=new D,R=async e=>{await new Promise(t=>{setTimeout(t,e)})},re=({"userleap-platform":e})=>e!=="web";class M{constructor(t){a(this,"storage");a(this,"tempStorage",{});a(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}getItem(t){return this.isStorageAvailable?this.storage.getItem(t):this.tempStorage[t]}removeItem(t){this.isStorageAvailable?this.storage.removeItem(t):delete this.tempStorage[t]}clear(){this.isStorageAvailable?this.storage.clear():this.tempStorage={}}}const se=new M("sessionStorage"),ne=new M("localStorage");class ie{constructor(t){a(this,"payload");a(this,"promise");a(this,"reject",()=>{});a(this,"resolve",()=>{});this.payload=t,this.promise=new Promise((r,s)=>{this.reject=s,this.resolve=r})}resolveRequest(t){this.resolve(t)}}const k={replay:null},oe=e=>{k.replay=e},ae=()=>{const e=[];return k.replay&&e.push("replay"),e.join(",")},le={RATELIMIT_RESET_DEFAULT:10};let P=!1,V="",_=!1,H=!1,L=[];const ce=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?"web-gtm":e._segment?"web-segment":"web-snippet",ue=e=>{var t;(t=e==null?void 0:e.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(H=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`))},W=(e="")=>{P=!0,V=e};function de(e={}){const t={"Content-Type":"application/json","userleap-platform":"web","x-ul-sdk-version":"2.31.2","x-ul-installation-method":ce(e),"sprig-modules":ae()};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}const T=async({shouldDropOnRateLimit:e,...t})=>{if(e)return{status:429};{const r=new ie(t);return L.push(r),r.promise}},f=async(e,t)=>{const{retries:r=0,shouldDropOnRateLimit:s=!1,shouldRetryRequest:y=!1,...l}=t,c={url:e,options:l,retries:r,shouldDropOnRateLimit:s};if(_&&!y)return T(c);const p={ok:!1,reportError:!1};if(P)return console.info(`UserLeap - ${V}`),p;try{const i=await fetch(e,l);if(i.status===429)if(!_&&!s||y){_=!0;const u=i.headers.has("ratelimit-reset")?Number(i.headers.get("ratelimit-reset")):le.RATELIMIT_RESET_DEFAULT;return await R(u*1e3),f(e,{...l,shouldDropOnRateLimit:s,shouldRetryRequest:!0})}else return T(c);if(_=!1,L.length&&(L.map(o=>{const u=o.payload;f(u.url,{...u.options,retries:u.retries,shouldDropOnRateLimit:u.shouldDropOnRateLimit}).then($=>{o.resolveRequest($)})}),L=[]),i.ok){if(i.status===249)return W(),p;const o=await i.text();try{return o&&o!=="OK"&&(i.json=JSON.parse(o)),i}catch{return{ok:!1,reportError:!1,error:new Error(`failed parsing response json for ${e} - ${o}`)}}}return i}catch(i){const o=r+1;return o>5||H?{ok:!1,reportError:!1,error:i}:(await R(Math.pow(2,r)*1e3),f(e,{...l,retries:o}))}},h={Error:1,Warn:2,Info:3,Debug:4};let b=1e3,v=h.Debug,d=[];const he=e=>{const t=Object.entries(h).find(r=>r[1]===e);return(t==null?void 0:t[0])??""},pe=e=>e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3}),me=(e,t)=>`${pe(t)}:${e}`,fe=()=>{d=d.filter(e=>e.level<=v)},ye=()=>{d.length>b&&d.shift()},E=(e,t)=>{e>v||(d.push({level:e,line:me(t,new Date)}),ye())},Y=e=>{E(h.Debug,e)},ge=e=>{E(h.Info,e)},q=e=>{E(h.Warn,e)},_e=e=>{E(h.Error,e)},Le=()=>d.map(e=>e.line),ve=()=>new TextEncoder().encode(Le().join(`
|
|
2
2
|
`)),Ee=async e=>{if(!e)return;const t=ve();return f(e,{body:t,method:"PUT"})},we=(e,t)=>{e!==void 0&&(b=e),t!==void 0&&(v=t),Y(`Initializing logger with limit of ${b} lines and ${he(v)} level`),fe()},C=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 N(e,t){const{matchType:r,pattern:s}=e,y=r?C[r]:C.legacy;let l=!1;try{l=y(s,t)}catch(c){const p=`[Sprig] (ERR-445) Failed to check url match with pattern ${s}`;c instanceof Error&&(console.warn(p,c),c.stack=JSON.stringify(e),window.UserLeap.reportError(p,c))}return l}const Re=e=>{const{pageUrlEvents:t}=window.UserLeap._config,r=t==null?void 0:t.find(s=>s.id===e);return r?N(r,window.location.href):!1};let j=!0,S=!1;const be=()=>j=!1,Ie=()=>S=!0,ke=["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 m={},I;class Se{constructor(t){a(this,"_values",[]);a(this,"_isWebMetric");this.name=t,this._isWebMetric=ke.includes(this.name)}report(t){if(j&&this._values.push({time:Date.now(),value:t}),S||!this._isWebMetric)return;const r=this.findExceededThreshold(t);r&&I&&I(t,r)}collect(){const t=this._values;return this._values=[],t}findExceededThreshold(t){const r=m[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:!1}}const Ae=(e,t)=>{m={},S=!1,e==null||e.forEach(r=>{var s;r.metric in m||(m[r.metric]=[]),(s=m[r.metric])==null||s.push(r)}),I=t},w={},F=e=>{const t=new Se(e);return w[e]=t,t},Te=(e,t)=>{let r=w[e];return r||(r=F(e)),r.report(t)},Ce=async e=>{const t=Object.values(w).map(r=>({name:r.name,values:r.collect()}));if(t.some(r=>r.values.length))try{await e(JSON.stringify(t))}catch(r){q(`Error posting metrics: ${r}`)}},Oe=({reportingIntervalSeconds:e,postMetrics:t})=>{e?setInterval(()=>{Ce(t)},e*1e3):be()};exports.DismissReason=O;exports.EVENTS=K;exports.PerformanceMetrics=w;exports.SprigEvent=U;exports.checkUrlMatch=N;exports.checkUrlStillMatching=Re;exports.configureLogger=we;exports.cspViolationHandler=ue;exports.debug=Y;exports.delay=R;exports.disableThresholdChecking=Ie;exports.error=_e;exports.eventEmitter=te;exports.getHttpHeaders=de;exports.info=ge;exports.initPerformanceReporting=Oe;exports.killNetworkRequests=W;exports.localStorageHelper=ne;exports.modules=k;exports.registerMetric=F;exports.registerReplay=oe;exports.registerThresholds=Ae;exports.reportAndRegister=Te;exports.sessionStorageHelper=se;exports.shouldDirectEmbed=re;exports.sprigFetch=f;exports.uploadLogfile=Ee;exports.v4=Z;exports.warn=q;
|
package/dist/replay.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var xe=Object.defineProperty;var Te=(e,t,n)=>t in e?xe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var U=(e,t,n)=>(Te(e,typeof t!="symbol"?t+"":t,n),n);const o=require("./metricsReporter-D8MMZt8T.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||{});class Ae{constructor(t){U(this,"awaitingResolvers",[]);U(this,"activeCount",0);this.capacity=t}async acquire(){if(this.activeCount<this.capacity){this.activeCount++;return}return new Promise(t=>{this.awaitingResolvers.push(t)})}release(){const t=this.awaitingResolvers.shift();t&&this.activeCount<=this.capacity?t():this.activeCount--}async execute(t){try{return await this.acquire(),await t()}finally{this.release()}}setLimit(t){this.capacity=t}}const oe=new Ae(2),Be=e=>oe.setLimit(e),Ue=async e=>oe.execute(async()=>{var r;o.info(`Beginning upload of chunk ${e.chunkIndex} for survey: ${e.surveyId}`);const t=await o.sprigFetch(e.uploadUrl,{body:e.data,method:"PUT"});o.info(`Completed upload of chunk ${e.chunkIndex} for survey: ${e.surveyId}`);const n=(r=t.headers)==null?void 0:r.get("ETag");if(!n)throw new Error(`Upload response did not include etag for upload ${e.uploadId}, part ${e.chunkIndex}`);return n}),ie=async({apiUrl:e,surveyId:t,uploadId:n,etags:r,headers:a,responseGroupUuid:s,replayDuration:i,eventDigest:c},l=!1)=>{var p;if(!l&&!n&&!r){o.info(`Cannot mark upload complete: isMobile: ${l} / uploadId: ${n} / etags: ${r}`);return}o.info(`Marking upload complete for survey: ${t}`);const d=await o.sprigFetch(`${e}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:r,uploadId:n,responseGroupUuid:s,surveyId:t,replayDuration:i,eventDigest:c,userAgent:(p=window==null?void 0:window.navigator)==null?void 0:p.userAgent}),headers:a,shouldRetryRequest:!0});return o.info(`Done marking upload complete for survey: ${t}`),d},_=(e,t)=>t.some(n=>e instanceof n);let z,J;function $e(){return z||(z=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Ne(){return J||(J=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const L=new WeakMap,$=new WeakMap,A=new WeakMap;function _e(e){const t=new Promise((n,r)=>{const a=()=>{n(S(e.result))},s=()=>{r(e.error)};e.onsuccess=a,e.onerror=s});return A.set(t,e),t}function Le(e){if(L.has(e))return;const t=new Promise((n,r)=>{const a=()=>{n()},s=()=>{r(e.error||new DOMException("AbortError","AbortError"))};e.oncomplete=a,e.onerror=s,e.onabort=s});L.set(e,t)}let M={get(e,t,n){if(e instanceof IDBTransaction){if(t==="done")return L.get(e);if(t==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return S(e[t])},set(e,t,n){return e[t]=n,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function ce(e){M=e(M)}function Me(e){return Ne().includes(e)?function(...t){return e.apply(H(this),t),S(this.request)}:function(...t){return S(e.apply(H(this),t))}}function He(e){return typeof e=="function"?Me(e):(e instanceof IDBTransaction&&Le(e),_(e,$e())?new Proxy(e,M):e)}function S(e){if(e instanceof IDBRequest)return _e(e);if($.has(e))return $.get(e);const t=He(e);return t!==e&&($.set(e,t),A.set(t,e)),t}const H=e=>A.get(e);function Oe(e,t,{blocked:n,upgrade:r,blocking:a,terminated:s}={}){const i=indexedDB.open(e,t),c=S(i);return r&&(i.onupgradeneeded=l=>{r(S(i.result),l.oldVersion,l.newVersion,S(i.transaction),l)}),n&&(i.onblocked=l=>n(l.oldVersion,l.newVersion,l)),c.then(l=>{s&&(l.onclose=()=>s()),a&&(l.onversionchange=d=>a(d.oldVersion,d.newVersion,d))}).catch(()=>{}),c}function le(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&(n.onblocked=r=>t(r.oldVersion,r)),S(n).then(()=>{})}const Fe=["get","getKey","getAll","getAllKeys","count"],je=["put","add","delete","clear"],N=new Map;function q(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(N.get(t))return N.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,a=je.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(a||Fe.includes(n)))return;const s=async function(i,...c){const l=this.transaction(i,a?"readwrite":"readonly");let d=l.store;return r&&(d=d.index(c.shift())),(await Promise.all([d[n](...c),a&&l.done]))[0]};return N.set(t,s),s}ce(e=>({...e,get:(t,n,r)=>q(t,n)||e.get(t,n,r),has:(t,n)=>!!q(t,n)||e.has(t,n)}));const Ve=["continue","continuePrimaryKey","advance"],Q={},O=new WeakMap,de=new WeakMap,Ke={get(e,t){if(!Ve.includes(t))return e[t];let n=Q[t];return n||(n=Q[t]=function(...r){O.set(this,de.get(this)[t](...r))}),n}};async function*Ge(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;const n=new Proxy(t,Ke);for(de.set(n,t),A.set(n,H(t));t;)yield n,t=await(O.get(n)||t.continue()),O.delete(n)}function X(e,t){return t===Symbol.asyncIterator&&_(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&_(e,[IDBIndex,IDBObjectStore])}ce(e=>({...e,get(t,n,r){return X(t,n)?Ge:e.get(t,n,r)},has(t,n){return X(t,n)||e.has(t,n)}}));const We=e=>{if(e instanceof Attr)return null;let t=1;for(let n=e.previousSibling;n;n=n.previousSibling)n.nodeName===e.nodeName&&++t;return t},ue=e=>{if(e===null)return"";const t=[];if(e instanceof Document)return"/";for(let n=e;n&&!(n instanceof Document)&&n!==null;n=n instanceof Attr?n.ownerElement:n.parentElement){const r=t[t.length]={name:void 0,position:null};switch(n.nodeType){case Node.TEXT_NODE:r.name="text()";break;case Node.ATTRIBUTE_NODE:r.name="@"+n.nodeName;break;case Node.PROCESSING_INSTRUCTION_NODE:r.name="processing-instruction()";break;case Node.COMMENT_NODE:r.name="comment()";break;case Node.ELEMENT_NODE:r.name=n.nodeName;break}r.position=We(n)}return"/"+t.reverse().map(n=>n.position!==null?`/${n.name}[${n.position}]`:`/${n.name}`).join("")},v={capture:!0,passive:!0},ze=["a","button","input","option","li","link"],Je=["Escape","Enter","Backspace","F5","Tab"];let x=!1;const qe=["label","type","role","title","placeholder","errormessage","valuetext","href"],Y="aria-",Qe=e=>{if(!e.tagName)return"No tagName";const t=e.getAttribute("type");return t?`${t} ${e.tagName.toLowerCase()}`:e.tagName.toLowerCase()},Z=e=>{var r;if(((r=e.tagName)==null?void 0:r.toLowerCase())==="html")return{element:"html"};const t=e.textContent,n=t?{text:t}:{};n.element=Qe(e);for(const a of e.attributes){let s=a.name;const i=a.value;s.startsWith(Y)&&(s=s.substring(Y.length)),qe.includes(s)&&(n[s]=i)}return n},Xe=e=>{var a;if(!e)return{};const n={...Z(e)},r=e.parentElement;if(r&&ze.includes((a=r.tagName)==null?void 0:a.toLowerCase())){const s=Z(r);Object.assign(n,s)}return n},pe=(e,t)=>{var n;ut({x:t.x,y:t.y,type:e,elementAttributes:Xe(t.target),windowHeight:window.innerHeight,windowWidth:window.innerWidth,...t.target instanceof HTMLElement?{rect:(n=t.target)==null?void 0:n.getBoundingClientRect(),xPath:ue(t.target)}:{}})},Ye=e=>t=>pe(e,t),me=e=>{Je.includes(e.key)&&yt({key:e.key})},Ze=()=>{window.performance.getEntriesByType("navigation").map(t=>t.type).includes("reload")&>({url:window.location.href,currentPageTitle:document.title})},et=()=>{window.performance.getEntriesByType("navigation").map(t=>t.type).includes("back_forward")&&wt({curUrl:window.location.href,fromUrl:document.referrer,currentPageTitle:document.title})},tt=(e,t)=>{let n;return r=>{clearTimeout(n),n=window.setTimeout(()=>e(r),t)}},nt=e=>{if(!(e.target instanceof HTMLElement||e.target instanceof Document))return;let t=e.target;"scrollTop"in t||(t=t.documentElement),ht({xPath:ue(t),x:t.scrollLeft,y:t.scrollTop,elementAttributes:{targetScrollWidth:t.scrollWidth,targetClientWidth:t.clientWidth,targetScrollHeight:t.scrollHeight,targetClientHeight:t.clientHeight}})},fe=tt(nt,750),ge=Ye("left_click"),we=e=>{e.button===2&&pe("right_click",e)},rt=()=>{x||(window.addEventListener("click",ge,v),window.addEventListener("mousedown",we,v),window.addEventListener("keydown",me,v),window.addEventListener("scroll",fe,v),x=!0,Ze(),et())},at=()=>{x&&(window.removeEventListener("click",ge,v),window.removeEventListener("mousedown",we,v),window.removeEventListener("keydown",me,v),window.removeEventListener("scroll",fe,v),x=!1)},st=3e4;let E=0;const m={isRecording:!1,scrollEventUuids:{},stopRecording:()=>{}},ot=()=>{const e=o.sessionStorageHelper.getItem("sprig.sessionId");if(e)return o.info(`Found saved session id: ${e}`),o.sessionStorageHelper.removeItem("sprig.sessionId"),e;const t=o.v4();return o.info(`Generating new uuid: ${t}`),t},w=ot(),it=async e=>{var t;if((t=window.navigator.storage)!=null&&t.estimate){const{quota:n=0,usage:r=0}=await window.navigator.storage.estimate();return(n-r)/1024**3>=e}return!0},ye=()=>{o.sessionStorageHelper.setItem("sprig.disableReplayRecording","disabled")},D=()=>!!o.sessionStorageHelper.getItem("sprig.disableReplayRecording");window.addEventListener("beforeunload",()=>{o.info(`Before page unload saving session id: ${w}`),o.sessionStorageHelper.setItem("sprig.sessionId",w)});const ct=async()=>{const t=(await u.getPendingCaptures({isHeatmap:!0})).map(r=>({eventId:r.captureParams.eventId,uuid:r.uuid})),n=[];t.forEach(({eventId:r,uuid:a})=>{o.checkUrlStillMatching(r)||n.push(a)}),n.length&&h(()=>u.markPendingHeatmapsReady(n),"Error marking pending heatmaps ready")},lt=e=>{if(e>1){E=0;return}const t=Date.now();if(!E){E=t;return}t-E>=st&&(E=0,h(()=>u.markPendingHeatmapsReady(),"Error marking pending heatmaps ready"))},K=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),I=(e,t)=>{var n,r;if(m.isRecording)try{(r=(n=window.rrwebRecord)==null?void 0:n.addCustomEvent)==null||r.call(n,e,t)}catch(a){B("Error recording custom event",a)}},dt=e=>{e.description&&(e.description=K(e.description)),I("Sprig_PageView",e)},ut=e=>{var t;(t=e==null?void 0:e.elementAttributes)!=null&&t.text&&(e.elementAttributes.text=K(e.elementAttributes.text)),I("Sprig_Click",e)},pt=e=>{I("Sprig_TrackEvent",e)},mt=e=>{I("Sprig_ShowSurvey",e)},ft=e=>{I("Sprig_SubmitSurvey",e)},gt=e=>{I("Sprig_Refresh",e)},wt=e=>{e.currentPageTitle&&(e.currentPageTitle=K(e.currentPageTitle)),I("Sprig_BackForward",e)},yt=e=>{I("Sprig_Keystroke",e)},ht=async e=>{const{x:t,xPath:n,y:r}=e,a=m.scrollEventUuids[n];if(a)return h(async()=>{var c,l,d,p;const s=await u.openDB(),i=await s.get("events",a);if(i!=null&&i.event){const f=JSON.parse(i.event),y=t>((l=(c=f.data)==null?void 0:c.payload)==null?void 0:l.x),g=r>((p=(d=f.data)==null?void 0:d.payload)==null?void 0:p.y);if(!(y||g))return null;y&&(f.data.payload.x=t),g&&(f.data.payload.y=r),f.data.payload.elementAttributes=e.elementAttributes,i.event=JSON.stringify(f),await s.put("events",i)}else I("Sprig_Scroll",e)},"Error updating scroll event");I("Sprig_Scroll",e)},It=()=>m.isRecording,he=()=>{m.stopRecording&&(m.stopRecording(),m.stopRecording=void 0),m.isRecording=!1,["cleanupInterval","noopInterval","pendingCheckInterval"].forEach(e=>{m[e]&&(clearInterval(m[e]),m[e]=void 0)}),at()},bt=["did not allow mutations","called in an invalid security context"],vt=e=>{if(!e)return!0;for(const t of bt)if(e.toLowerCase().includes(t))return!1;return!0},St=(e,t,{reportError:n=!0,extraInfo:r})=>{D()||t instanceof Error&&(ye(),vt(t==null?void 0:t.message)&&(n&&window.UserLeap.reportError(e,t,r),u.clearAll()))},Ct=async(e,t,{reportError:n}={reportError:!0})=>{var a;let r;try{if(n&&((a=window.navigator.storage)!=null&&a.estimate)){const{quota:s=0,usage:i=0}=await window.navigator.storage.estimate();r={availableSpaceInMB:(s-i)/2**20,quota:s,usage:i}}}catch(s){window.UserLeap.reportError("Error getting storage estimate",s,{originalMessage:e,originalError:t})}St(e,t,{reportError:n,extraInfo:r})},B=(e,t,{reportError:n}={reportError:!0})=>(he(),o.error(`${e} - ${JSON.stringify(t)}`),Ct(e,t,{reportError:n})),h=async(e,t)=>{try{await e()}catch(n){B(t,n)}},Dt=()=>{m.isRecording&&h(()=>{var e,t;return(t=(e=window.rrwebRecord)==null?void 0:e.takeFullSnapshot)==null?void 0:t.call(e,!0)},"Error recording full snapshot")},Et=async({surveyId:e,responseGroupUuid:t,eventDigest:n,headers:r})=>{if(!e||!t)return!1;const a=window.UserLeap._API_URL,s=await ie({surveyId:e,responseGroupUuid:t,eventDigest:n,apiUrl:a,headers:r},!0);return!(s!=null&&s.error)},ee=30,kt=1;le("replayStorage").catch(console.error);le("sprig.replay").catch(console.error);class Pt{openDB(){return Oe("sprigReplay",kt,{upgrade:(t,n,r)=>{if(r===0&&o.sessionStorageHelper.setItem("sprig.pendingCount","0"),!t.objectStoreNames.contains("events")){const a=t.createObjectStore("events",{keyPath:"uuid"});a.createIndex("sessionId","sessionId"),a.createIndex("timestamp","timestamp"),a.createIndex("[sessionId+timestamp]",["sessionId","timestamp"])}if(!t.objectStoreNames.contains("chunkUploads")){const a=t.createObjectStore("chunkUploads",{keyPath:"uuid"});a.createIndex("sessionId","sessionId"),a.createIndex("timestamp","timestamp"),a.createIndex("[sessionId+status]",["sessionId","status"]),a.createIndex("[uploadId+status]",["uploadId","status"]),a.createIndex("[sessionId+status+uploadId]",["sessionId","status","uploadId"])}if(!t.objectStoreNames.contains("pendingCaptures")){const a=t.createObjectStore("pendingCaptures",{keyPath:"uuid"});a.createIndex("sessionId","sessionId"),a.createIndex("timestamp","timestamp"),a.createIndex("[sessionId+targetTimestamp]",["sessionId","targetTimestamp"])}}}).catch(t=>(o.error(`Error opening replay storage: ${t.message}`),ye(),Promise.reject(t)))}constructor(){this.openDB()}async bulkAdd(t,n){const r=(await this.openDB()).transaction(t,"readwrite");return Promise.all([...n.map(a=>r.store.add(a)),r.done])}async clearAll(){const t=(await this.openDB()).transaction(["events","chunkUploads","pendingCaptures"],"readwrite");return Promise.allSettled([t.objectStore("events").clear(),t.objectStore("chunkUploads").clear(),t.objectStore("pendingCaptures").clear()])}async deleteBySessionId(t,n){const r=IDBKeyRange.only(n),a=(await this.openDB()).transaction(t,"readwrite");let i=await a.store.index("sessionId").openCursor(r);for(;i;)i.delete(),i=await i.continue();await a.done}async updatePartial(t,n,r){const s=(await this.openDB()).transaction(t,"readwrite"),i=await s.store.get(n);i&&await s.store.put({...i,...r}),await s.done}async deleteRowsBefore(t,n,r=()=>!0){const a=IDBKeyRange.upperBound(n,!0),s=(await this.openDB()).transaction(t,"readwrite");let c=await s.store.index("timestamp").openCursor(a);for(;c;)r(c.value)&&c.delete(),c=await c.continue();await s.done}async getEventsBetween(t,n=Date.now()){if(t>=n)return Promise.resolve([]);const r=IDBKeyRange.bound([w,t],[w,n],!1,!0);return(await this.openDB()).getAllFromIndex("events","[sessionId+timestamp]",r)}async updateEventsExpiredAt(t,n,r=ee){const a=new Date,s=a.setMinutes(a.getMinutes()+(r??ee)),i=(await this.openDB()).transaction("events","readwrite"),c=i.store.index("[sessionId+timestamp]"),l=IDBKeyRange.bound([w,t],[w,n],!1,!0);let d=await c.openCursor(l);for(;d;)d.update({...d.value,expiredAt:s}),d=await d.continue();await i.done}async deleteChunkUploads(t,n){const r=IDBKeyRange.only([n,t]),a=(await this.openDB()).transaction("chunkUploads","readwrite");let i=await a.store.index("[uploadId+status]").openCursor(r);for(;i;)i.delete(),i=await i.continue();await a.done}async getChunkUploadsByStatus({sessionId:t,status:n,uploadId:r}){const s=(await this.openDB()).transaction("chunkUploads","readonly"),i=r?s.store.index("[uploadId+status]"):s.store.index("[sessionId+status]"),c=r?IDBKeyRange.only([r,n]):IDBKeyRange.only([t,n]);return i.getAll(c)}async getPendingCaptures(t={}){return(await(await this.openDB()).getAllFromIndex("pendingCaptures","sessionId",w)).filter(a=>!t.beforePresent||a.targetTimestamp<Date.now()).filter(a=>!t.isHeatmap||(a.captureParams.isHeatmap??!1))}async markPendingCaptureToCanUpload(t){const n=(await this.openDB()).transaction("pendingCaptures","readwrite");let a=await n.store.index("sessionId").openCursor(w);for(;a;){const s=a.value;s.captureParams.responseGroupId===t&&a.update({...s,canUpload:!0}),a=await a.continue()}await n.done}async markPendingHeatmapsReady(t){if(parseInt(o.sessionStorageHelper.getItem("sprig.pendingCount")??"0")===0)return null;const r=Date.now(),a=(await this.openDB()).transaction("pendingCaptures","readwrite");let i=await a.store.index("sessionId").openCursor(w);for(;i;){const c=i.value;c.captureParams.isHeatmap&&(!t||t.includes(c.uuid))&&i.update({...c,targetTimestamp:r,captureParams:{...c.captureParams,triggerTimestamp:r,replayParams:{...c.captureParams.replayParams,replayDurationSeconds:Math.floor((r-c.timestamp)/1e3)}}}),i=await i.continue()}await a.done}}const u=new Pt,Rt=async(e,t,n)=>new Promise((r,a)=>{const s=e.createElement("script");s.src=t,s.onload=r,s.onerror=a,n&&(s.nonce=n),e.head.appendChild(s)}),Ie=async(e,t)=>{const n=performance.now();let r;try{r=await e()}finally{const a=performance.now()-n;let s=o.PerformanceMetrics[t];s||(s=o.registerMetric(t)),s.report(a/1e3)}return r},be=(e,t)=>{const n=performance.now();try{e()}finally{const r=performance.now()-n;let a=o.PerformanceMetrics[t];a||(a=o.registerMetric(t)),a.report(r/1e3)}};let te=1,F=5e3,R=6e4;const ne=1e3,xt=5,ve=30,T=ve+xt;let re=Date.now(),C,G=!!o.sessionStorageHelper.getItem("sprig.isCapturingHeatmap"),j=!1,V=[];const Tt=async({viewDocument:e,maxReplayDurationSeconds:t,replayNonce:n,maxInflightRequests:r=2,replaySettings:a,teardownAfter:s=!1})=>{C=o.sessionStorageHelper.getItem("sprig.pendingCount"),!m.isRecording&&(s&&o.sessionStorageHelper.setItem("sprig.teardownAfterCapture","true"),await h(async()=>{if(D()){o.info("Not initializing replay because recording is disabled");return}if(!t){o.info("Not initializing replay because config didn't specify maxReplayDurationSeconds");return}if(a!=null&&a.minAvailableGb&&(te=a.minAvailableGb),!await it(te)){o.warn("Minimum storage not available");return}if(o.info("Initializing replay"),a!=null&&a.minDuration&&(F=a.minDuration),a!=null&&a.batchDuration&&(R=a.batchDuration),Be(r),Mt(),$t(t+T,30*60,t+T),Nt(),!window.rrwebRecord){o.info("Loading recording script");const d=window.UserLeap.replayLibraryURL??"https://cdn.sprig.com/dependencies/record-2.0.0-alpha.6.min.js";await Rt(e,d,n),o.info("Recording script finished loading")}const i=window.rrwebRecord;if(!i){o.warn("Record script failed to set global function");return}let c=!0,l=0;m.stopRecording=i({checkoutEveryNms:ve*1e3,sampling:{input:"last",scroll:250,media:800},emit:(d,p)=>{if(D())return;if(re=Date.now(),p&&d.type===P.Meta)l=performance.now();else if(p&&l&&d.type===P.FullSnapshot){const y=performance.now()-l;o.reportAndRegister("sdk_replay_snapshot_seconds",y/1e3)}const f=c||!!p&&d.type===P.Meta;c=!1,At({uuid:o.v4(),event:JSON.stringify(d),isValidStart:f,timestamp:Date.now()})},...a}),m.isRecording=!!m.stopRecording,m.isRecording&&(m.noopInterval||(m.noopInterval=window.setInterval(()=>{Date.now()-re>ne&&I("Sprig_Noop",{})},ne)),o.eventEmitter.on("survey.complete",d=>{ft({id:d,userAgent:window.navigator.userAgent})}),rt())},"Error initializing replay"))},At=e=>{var t,n,r,a;if((t=e.event)!=null&&t.includes("Sprig_Scroll")){const s=(a=(r=(n=JSON.parse(e.event))==null?void 0:n.data)==null?void 0:r.payload)==null?void 0:a.xPath;if(!s)return;m.scrollEventUuids[s]=e.uuid}V.push(e),j||Ut()},Bt=async e=>{const t=e.map(n=>({...n,sessionId:n.sessionId??w}));if(G&<(t.length),t.length!==0)return h(()=>u.bulkAdd("events",t),"Error storing replay events")},Ut=()=>{j=!0,setTimeout(async()=>{if(D())return;const e=V;V=[],j=!1,be(async()=>{await Bt(e)},"sdk_replay_add_event_batch_seconds")},500)},$t=(e,t,n)=>{m.cleanupInterval=window.setInterval(()=>{const r=Date.now();D()||(o.debug(`Performing periodic replay data cleanup / Event Seconds ${e} / Chunk Seconds ${t} / Pending Capture Seconds ${n}`),Ie(()=>h(async()=>{const s=(await Promise.allSettled([u.deleteRowsBefore("events",r-e*1e3,i=>i.expiredAt===void 0||i.expiredAt<r-e*1e3),u.deleteRowsBefore("chunkUploads",r-t*1e3),u.deleteRowsBefore("pendingCaptures",r-n*1e3,i=>!i.canUpload)])).find(i=>i.status==="rejected");if(s)throw new Error(s.reason)},"Error deleting table rows"),"sdk_replay_cleanup_seconds"),o.info("Cleanup complete"))},3e4)},Nt=()=>{m.pendingCheckInterval=window.setInterval(async()=>{h(async()=>{const e=parseInt(C??"0");if(e===0)return;const t=await u.getPendingCaptures({beforePresent:!0}),n=await u.openDB();await Promise.all(t.map(async r=>(await n.delete("pendingCaptures",r.uuid),De(r.captureParams,r.canUpload)))),C=(e-t.length).toString(),o.sessionStorageHelper.setItem("sprig.pendingCount",C)},"Error initiating pending captures")},5e3)},_t=async(e,t,n,r,a)=>{const s=Math.min(e+a,n),i=`from: ${new Date(e).toLocaleTimeString()} to ${new Date(s).toLocaleTimeString()}`;o.info(`Getting event batch ${i}`);const c=await Ie(()=>u.getEventsBetween(e,s),"sdk_replay_get_events_between_seconds");if(!(c!=null&&c.length))return o.info(`No events found ${i}`),{validStartFound:r,events:[]};if(!r){o.info(`Searching for valid start in ${c.length} events ${i}`);let l=-1;if(c==null||c.forEach((p,f)=>{if(!p.isValidStart)return;const y=p.timestamp<=t;(l<0||y)&&(l=f)}),l<0)return o.info(`No valid start found in ${c.length} events ${i}`),{validStartFound:r,events:[]};const d=c[l].timestamp;return o.info(`Found valid start at: ${new Date(d).toLocaleTimeString()} in events ${i}`),{validStartFound:!0,events:c==null?void 0:c.slice(l)}}return{validStartFound:r,events:c}},Lt=(e,t,n)=>{const r=e.length,a=t*1024*1024,s=Math.ceil(r/n),i=Math.max(a,s);o.info(`Total file bytes: ${r} / target chunk size: ${i}`);const c=[];let l=0;for(;l<r;)c.push(e.slice(l,l+i)),l+=i;return c},Se=e=>Promise.all(e.map(async t=>{const n=await Ue(t);return await u.updatePartial("chunkUploads",t.uuid,{data:null,etag:n,status:"UploadComplete"}),t.uploadId})),Ce=async e=>{o.info(`Marking upload complete if finished: ${e}`);const t=await u.getChunkUploadsByStatus({status:"UploadComplete",uploadId:e});if(!(t!=null&&t.length)){o.info(`No finished chunks found for upload: ${e}`);return}const n=t.reduce((s,i)=>(s.find(c=>c.chunkIndex===i.chunkIndex)||s.push(i),s),[]);n.sort((s,i)=>s.chunkIndex-i.chunkIndex);const r=n.map(s=>({ETag:s.etag,PartNumber:s.chunkIndex})).filter(s=>s.ETag!==null),a=n[0];await ie({apiUrl:a.apiUrl,surveyId:a.surveyId,uploadId:e,responseGroupUuid:a.responseGroupId,etags:r,headers:a.completeUploadHeaders,replayDuration:a.replayDuration}),o.info(`Cleaning up chunks for ${e}`),await u.deleteChunkUploads("UploadComplete",e),o.info(`Done cleaning up chunks for ${e}`)},Mt=async()=>{h(async()=>{const e=await u.getChunkUploadsByStatus({sessionId:w,status:"ReadyForUpload"});if(!(e!=null&&e.length))return;const t=await Se(e);o.info(`Finished uploading unfinished chunks for ${t}`),t!=null&&t.length&&await Promise.all(t.map(n=>{if(n)return Ce(n)}))},"Error uploading unfinished chunks")},Ht=async(e,t)=>{await Se(t),o.info(`Done uploading chunks for uploads: ${e.join(",")}`),await Promise.all(e.map(n=>Ce(n)))},Ot=e=>{let t=0;e.forEach(a=>{t+=a.length});const n=new Uint8Array(t);let r=0;return e.forEach(a=>{n.set(a,r),r+=a.length}),n},ae=async(e,t,n)=>{const r=new TextEncoder;let a=null,s=null,i=null,c=!1,l=!1,[d,p]=[0,0];const f=e-T*1e3,y=[];let g=[];o.info(`Getting events between ${new Date(e).toLocaleTimeString()} and ${new Date(t).toLocaleTimeString()}`),o.info(`Using batch duration: ${R}ms`);for(let k=f;k<t;k+=R){if({validStartFound:l,events:g}=await _t(k,e,t,l,R),!(g!=null&&g.length)){o.info("No events found");continue}d===0&&(d=g[0].timestamp),p=g[g.length-1].timestamp,o.info(`Last event time in batch: ${new Date(p).toLocaleTimeString()}`);const Pe=`${c?",":"["}${g.map(Re=>Re.event).join(",")}`,W=r.encode(Pe);n&&s===null&&(o.debug("Attempting compression"),i=new window.CompressionStream("gzip"),s=i.writable.getWriter()),be(()=>{n&&s?s.write(W):y.push(W)},"sdk_replay_compression_seconds"),c=!0}if(p-d<F)return o.info(`Replay duration is shorter than minimum of ${F}ms / Start:${d} / End:${p}`),null;const b=r.encode("]");return o.debug("Writing final close brace"),s&&i?(s.write(b),s.close(),a=new Uint8Array(await new Response(i.readable).arrayBuffer())):(y.push(b),a=Ot(y)),o.info("Finished generating file data"),a},Ft=async(e,t)=>{const n=window.CompressionStream!==void 0;let r=null;const a=t??Date.now(),s=a-e;try{r=await ae(s,a,n)}catch(i){i instanceof Error&&window.UserLeap.reportError("Error compressing replay",i),n&&h(async()=>{await ae(s,a,!1)},"fileData fallback failed")}return r},se=async e=>{const{surveyId:t,responseGroupId:n,visitorId:r,apiUrl:a,completeUploadHeaders:s,replayParams:i,triggerTimestamp:c}=e,l=await Ft(i.replayDurationSeconds*1e3,c);if(l!=null&&l.length)o.info(`Found file data for survey: ${t}`);else{o.info(`File data is empty for survey: ${t}`);return}const d=Lt(l,i.minimumChunkSizeMb,i.signedUrls.length);o.info(`Got ${d.length} chunks for survey: ${t}`);const p=await Promise.all(d.map(async(f,y)=>{const g=o.v4(),b={apiUrl:a,chunkIndex:y+1,completeUploadHeaders:s,etag:null,responseGroupId:n,status:"ReadyForUpload",surveyId:t,timestamp:c,totalChunks:d.length,data:f,uploadId:i.uploadId,uploadUrl:i.signedUrls[y].url,uuid:g,visitorId:r};return o.info(`Recording chunk upload: ${JSON.stringify({index:b.chunkIndex,surveyId:b.surveyId,uploadId:b.uploadId,size:f.length,id:g},null,2)}`),await(await u.openDB()).add("chunkUploads",{...b,sessionId:b.sessionId??w}),o.info(`Done creating chunk upload: ${g}`),b}));o.info(`All chunk records created. Beginning upload for survey: ${t}`),await Ht([i.uploadId],p)},De=async(e,t)=>{if(o.info(`Attempting replay capture: ${JSON.stringify({isStandalone:e.isStandalone,duration:e.replayParams.replayDurationSeconds,type:e.replayParams.replayDurationType,responseGroupId:e.responseGroupId,surveyId:e.surveyId,triggerTimestamp:e.triggerTimestamp,visitorId:e.visitorId},null,2)}`),D())return o.info(`Replay recording is disabled: ${e.surveyId}`);o.info(`Replay recording enabled: ${e.surveyId}`);const{isHeatmap:n,isStandalone:r,replayParams:a,triggerTimestamp:s,responseGroupId:i}=e,c=async()=>{setTimeout(()=>o.eventEmitter.removeListener(o.SprigEvent.QuestionAnswered,c),0),h(async()=>{a.replayDurationType==="before"?await se(e):await u.markPendingCaptureToCanUpload(i)},"Error in schedule/capture callback")};h(async()=>{if(a.replayDurationType==="after"||a.replayDurationType==="beforeAndAfter"){!r&&!n&&(o.info("Attaching QuestionAnswered listener for non-standalone replay"),o.eventEmitter.on(o.SprigEvent.QuestionAnswered,c)),o.info(`Scheduling capture for replay of type: ${a.replayDurationType}`),await ke(e);return}if(r||n||t)o.info(`Proceeding to capture replay for survey: ${e.surveyId} / standalone? ${r} / canUpload? ${t}`),await se(e),n&&jt();else{const d=T+a.replayDurationSeconds,p=s-d*1e3,f=s;o.info(`Setting expiry minutes to ${a.expirationTimeLimitMinutes} for events from ${new Date(p).toLocaleTimeString()} to ${new Date(f).toLocaleTimeString()}`),await u.updateEventsExpiredAt(p,f,a.expirationTimeLimitMinutes),o.info("Attaching QuestionAnswered listener"),o.eventEmitter.on(o.SprigEvent.QuestionAnswered,c)}},"Error in scheduling/capturing replay")},jt=async()=>{parseInt(C??"0")||(o.sessionStorageHelper.removeItem("sprig.isCapturingHeatmap"),G=!1),o.sessionStorageHelper.getItem("sprig.teardownAfterCapture")&&(he(),Ee(),o.sessionStorageHelper.removeItem("sprig.teardownAfterCapture"))},Ee=()=>{if(D()){o.debug("Not clearing user data, replay is disabled");return}return Promise.allSettled([u.deleteBySessionId("events",w),u.deleteBySessionId("pendingCaptures",w)]).then(e=>{var n;const t=(n=e.find(r=>r.status==="rejected"))==null?void 0:n.reason;t&&B("Error clearing session event data",t)})},ke=async e=>{o.info(`Scheduling replay capture: ${JSON.stringify(e)}`);const{isHeatmap:t,surveyId:n}=e,r=await u.getPendingCaptures(),a=r==null?void 0:r.filter(l=>l.captureParams.surveyId===n);if(a!=null&&a.length){o.info(`Pending capture exists for survey: ${n}`);return}t&&(Dt(),G=!0,o.sessionStorageHelper.setItem("sprig.isCapturingHeatmap","true"));const s={...e,replayParams:{...e.replayParams}};e.replayParams.replayDurationType==="beforeAndAfter"&&(s.replayParams.replayDurationSeconds*=2),s.replayParams.replayDurationType="before";const i=e.triggerTimestamp+e.replayParams.replayDurationSeconds*1e3;s.triggerTimestamp=i,C=(parseInt(C??"0")+1).toString(),o.sessionStorageHelper.setItem("sprig.pendingCount",C),await(await u.openDB()).add("pendingCaptures",{canUpload:!1,captureParams:s,sessionId:w,targetTimestamp:i,timestamp:Date.now(),uuid:o.v4()})},Vt=Object.freeze(Object.defineProperty({__proto__:null,RecordEvent:pt,RecordPageView:dt,RecordSurveyShown:mt,_completeSessionReplay:Et,checkPendingHeatmapsUrl:ct,clearUserReplayData:Ee,disableRecording:B,initializeReplay:Tt,isReplayRecording:It,scheduleCapture:ke,scheduleOrCaptureReplay:De},Symbol.toStringTag,{value:"Module"}));o.registerReplay(Vt);
|
|
1
|
+
"use strict";var xe=Object.defineProperty;var Te=(e,t,n)=>t in e?xe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var U=(e,t,n)=>(Te(e,typeof t!="symbol"?t+"":t,n),n);const o=require("./metricsReporter-DaSVYNOK.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||{});class Ae{constructor(t){U(this,"awaitingResolvers",[]);U(this,"activeCount",0);this.capacity=t}async acquire(){if(this.activeCount<this.capacity){this.activeCount++;return}return new Promise(t=>{this.awaitingResolvers.push(t)})}release(){const t=this.awaitingResolvers.shift();t&&this.activeCount<=this.capacity?t():this.activeCount--}async execute(t){try{return await this.acquire(),await t()}finally{this.release()}}setLimit(t){this.capacity=t}}const ie=new Ae(2),Be=e=>ie.setLimit(e),Ue=async e=>ie.execute(async()=>{var a;o.info(`Beginning upload of chunk ${e.chunkIndex} for survey: ${e.surveyId}`);const t=await o.sprigFetch(e.uploadUrl,{body:e.data,method:"PUT"});o.info(`Completed upload of chunk ${e.chunkIndex} for survey: ${e.surveyId}`);const n=(a=t.headers)==null?void 0:a.get("ETag");if(!n)throw new Error(`Upload response did not include etag for upload ${e.uploadId}, part ${e.chunkIndex}`);return n}),ce=async({apiUrl:e,surveyId:t,uploadId:n,etags:a,headers:r,responseGroupUuid:s,replayDuration:i,eventDigest:c},l=!1)=>{var p;if(!l&&!n&&!a){o.info(`Cannot mark upload complete: isMobile: ${l} / uploadId: ${n} / etags: ${a}`);return}o.info(`Marking upload complete for survey: ${t}`);const d=await o.sprigFetch(`${e}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:a,uploadId:n,responseGroupUuid:s,surveyId:t,replayDuration:i,eventDigest:c,userAgent:(p=window==null?void 0:window.navigator)==null?void 0:p.userAgent}),headers:r,shouldRetryRequest:!0});return o.info(`Done marking upload complete for survey: ${t}`),d},_=(e,t)=>t.some(n=>e instanceof n);let J,q;function $e(){return J||(J=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Ne(){return q||(q=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const L=new WeakMap,$=new WeakMap,A=new WeakMap;function _e(e){const t=new Promise((n,a)=>{const r=()=>{n(S(e.result))},s=()=>{a(e.error)};e.onsuccess=r,e.onerror=s});return A.set(t,e),t}function Le(e){if(L.has(e))return;const t=new Promise((n,a)=>{const r=()=>{n()},s=()=>{a(e.error||new DOMException("AbortError","AbortError"))};e.oncomplete=r,e.onerror=s,e.onabort=s});L.set(e,t)}let M={get(e,t,n){if(e instanceof IDBTransaction){if(t==="done")return L.get(e);if(t==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return S(e[t])},set(e,t,n){return e[t]=n,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function le(e){M=e(M)}function Me(e){return Ne().includes(e)?function(...t){return e.apply(H(this),t),S(this.request)}:function(...t){return S(e.apply(H(this),t))}}function He(e){return typeof e=="function"?Me(e):(e instanceof IDBTransaction&&Le(e),_(e,$e())?new Proxy(e,M):e)}function S(e){if(e instanceof IDBRequest)return _e(e);if($.has(e))return $.get(e);const t=He(e);return t!==e&&($.set(e,t),A.set(t,e)),t}const H=e=>A.get(e);function Oe(e,t,{blocked:n,upgrade:a,blocking:r,terminated:s}={}){const i=indexedDB.open(e,t),c=S(i);return a&&(i.onupgradeneeded=l=>{a(S(i.result),l.oldVersion,l.newVersion,S(i.transaction),l)}),n&&(i.onblocked=l=>n(l.oldVersion,l.newVersion,l)),c.then(l=>{s&&(l.onclose=()=>s()),r&&(l.onversionchange=d=>r(d.oldVersion,d.newVersion,d))}).catch(()=>{}),c}function K(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&(n.onblocked=a=>t(a.oldVersion,a)),S(n).then(()=>{})}const Fe=["get","getKey","getAll","getAllKeys","count"],je=["put","add","delete","clear"],N=new Map;function Q(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(N.get(t))return N.get(t);const n=t.replace(/FromIndex$/,""),a=t!==n,r=je.includes(n);if(!(n in(a?IDBIndex:IDBObjectStore).prototype)||!(r||Fe.includes(n)))return;const s=async function(i,...c){const l=this.transaction(i,r?"readwrite":"readonly");let d=l.store;return a&&(d=d.index(c.shift())),(await Promise.all([d[n](...c),r&&l.done]))[0]};return N.set(t,s),s}le(e=>({...e,get:(t,n,a)=>Q(t,n)||e.get(t,n,a),has:(t,n)=>!!Q(t,n)||e.has(t,n)}));const Ve=["continue","continuePrimaryKey","advance"],X={},O=new WeakMap,de=new WeakMap,Ke={get(e,t){if(!Ve.includes(t))return e[t];let n=X[t];return n||(n=X[t]=function(...a){O.set(this,de.get(this)[t](...a))}),n}};async function*Ge(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;const n=new Proxy(t,Ke);for(de.set(n,t),A.set(n,H(t));t;)yield n,t=await(O.get(n)||t.continue()),O.delete(n)}function Y(e,t){return t===Symbol.asyncIterator&&_(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&_(e,[IDBIndex,IDBObjectStore])}le(e=>({...e,get(t,n,a){return Y(t,n)?Ge:e.get(t,n,a)},has(t,n){return Y(t,n)||e.has(t,n)}}));const We=e=>{if(e instanceof Attr)return null;let t=1;for(let n=e.previousSibling;n;n=n.previousSibling)n.nodeName===e.nodeName&&++t;return t},ue=e=>{if(e===null)return"";const t=[];if(e instanceof Document)return"/";for(let n=e;n&&!(n instanceof Document)&&n!==null;n=n instanceof Attr?n.ownerElement:n.parentElement){const a=t[t.length]={name:void 0,position:null};switch(n.nodeType){case Node.TEXT_NODE:a.name="text()";break;case Node.ATTRIBUTE_NODE:a.name="@"+n.nodeName;break;case Node.PROCESSING_INSTRUCTION_NODE:a.name="processing-instruction()";break;case Node.COMMENT_NODE:a.name="comment()";break;case Node.ELEMENT_NODE:a.name=n.nodeName;break}a.position=We(n)}return"/"+t.reverse().map(n=>n.position!==null?`/${n.name}[${n.position}]`:`/${n.name}`).join("")},v={capture:!0,passive:!0},ze=["a","button","input","option","li","link"],Je=["Escape","Enter","Backspace","F5","Tab"];let x=!1;const qe=["label","type","role","title","placeholder","errormessage","valuetext","href"],Z="aria-",Qe=e=>{if(!e.tagName)return"No tagName";const t=e.getAttribute("type");return t?`${t} ${e.tagName.toLowerCase()}`:e.tagName.toLowerCase()},ee=e=>{var a;if(((a=e.tagName)==null?void 0:a.toLowerCase())==="html")return{element:"html"};const t=e.textContent,n=t?{text:t}:{};n.element=Qe(e);for(const r of e.attributes){let s=r.name;const i=r.value;s.startsWith(Z)&&(s=s.substring(Z.length)),qe.includes(s)&&(n[s]=i)}return n},Xe=e=>{var r;if(!e)return{};const n={...ee(e)},a=e.parentElement;if(a&&ze.includes((r=a.tagName)==null?void 0:r.toLowerCase())){const s=ee(a);Object.assign(n,s)}return n},pe=(e,t)=>{var n;ut({x:t.x,y:t.y,type:e,elementAttributes:Xe(t.target),windowHeight:window.innerHeight,windowWidth:window.innerWidth,...t.target instanceof HTMLElement?{rect:(n=t.target)==null?void 0:n.getBoundingClientRect(),xPath:ue(t.target)}:{}})},Ye=e=>t=>pe(e,t),me=e=>{Je.includes(e.key)&&yt({key:e.key})},Ze=()=>{window.performance.getEntriesByType("navigation").map(t=>t.type).includes("reload")&&ft({url:window.location.href,currentPageTitle:document.title})},et=()=>{window.performance.getEntriesByType("navigation").map(t=>t.type).includes("back_forward")&&wt({curUrl:window.location.href,fromUrl:document.referrer,currentPageTitle:document.title})},tt=(e,t)=>{let n;return a=>{clearTimeout(n),n=window.setTimeout(()=>e(a),t)}},nt=e=>{if(!(e.target instanceof HTMLElement||e.target instanceof Document))return;let t=e.target;"scrollTop"in t||(t=t.documentElement),ht({xPath:ue(t),x:t.scrollLeft,y:t.scrollTop,elementAttributes:{targetScrollWidth:t.scrollWidth,targetClientWidth:t.clientWidth,targetScrollHeight:t.scrollHeight,targetClientHeight:t.clientHeight}})},ge=tt(nt,750),fe=Ye("left_click"),we=e=>{e.button===2&&pe("right_click",e)},rt=()=>{x||(window.addEventListener("click",fe,v),window.addEventListener("mousedown",we,v),window.addEventListener("keydown",me,v),window.addEventListener("scroll",ge,v),x=!0,Ze(),et())},at=()=>{x&&(window.removeEventListener("click",fe,v),window.removeEventListener("mousedown",we,v),window.removeEventListener("keydown",me,v),window.removeEventListener("scroll",ge,v),x=!1)},st=3e4;let E=0;const m={isRecording:!1,scrollEventUuids:{},stopRecording:()=>{}},ot=()=>{const e=o.sessionStorageHelper.getItem("sprig.sessionId");if(e)return o.info(`Found saved session id: ${e}`),o.sessionStorageHelper.removeItem("sprig.sessionId"),e;const t=o.v4();return o.info(`Generating new uuid: ${t}`),t},w=ot(),it=async e=>{var t;if((t=window.navigator.storage)!=null&&t.estimate){const{quota:n=0,usage:a=0}=await window.navigator.storage.estimate();return(n-a)/1024**3>=e}return!0},ye=()=>{o.sessionStorageHelper.setItem("sprig.disableReplayRecording","disabled")},D=()=>!!o.sessionStorageHelper.getItem("sprig.disableReplayRecording");window.addEventListener("beforeunload",()=>{o.info(`Before page unload saving session id: ${w}`),o.sessionStorageHelper.setItem("sprig.sessionId",w)});const ct=async()=>{const t=(await u.getPendingCaptures({isHeatmap:!0})).map(a=>({eventId:a.captureParams.eventId,uuid:a.uuid})),n=[];t.forEach(({eventId:a,uuid:r})=>{o.checkUrlStillMatching(a)||n.push(r)}),n.length&&h(()=>u.markPendingHeatmapsReady(n),"Error marking pending heatmaps ready")},lt=e=>{if(e>1){E=0;return}const t=Date.now();if(!E){E=t;return}t-E>=st&&(E=0,h(()=>u.markPendingHeatmapsReady(),"Error marking pending heatmaps ready"))},G=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),I=(e,t)=>{var n,a;if(m.isRecording)try{(a=(n=window.rrwebRecord)==null?void 0:n.addCustomEvent)==null||a.call(n,e,t)}catch(r){B("Error recording custom event",r)}},dt=e=>{e.description&&(e.description=G(e.description)),I("Sprig_PageView",e)},ut=e=>{var t;(t=e==null?void 0:e.elementAttributes)!=null&&t.text&&(e.elementAttributes.text=G(e.elementAttributes.text)),I("Sprig_Click",e)},pt=e=>{I("Sprig_TrackEvent",e)},mt=e=>{I("Sprig_ShowSurvey",e)},gt=e=>{I("Sprig_SubmitSurvey",e)},ft=e=>{I("Sprig_Refresh",e)},wt=e=>{e.currentPageTitle&&(e.currentPageTitle=G(e.currentPageTitle)),I("Sprig_BackForward",e)},yt=e=>{I("Sprig_Keystroke",e)},ht=async e=>{const{x:t,xPath:n,y:a}=e,r=m.scrollEventUuids[n];if(r)return h(async()=>{var c,l,d,p;const s=await u.openDB(),i=await s.get("events",r);if(i!=null&&i.event){const g=JSON.parse(i.event),y=t>((l=(c=g.data)==null?void 0:c.payload)==null?void 0:l.x),f=a>((p=(d=g.data)==null?void 0:d.payload)==null?void 0:p.y);if(!(y||f))return null;y&&(g.data.payload.x=t),f&&(g.data.payload.y=a),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)},It=()=>m.isRecording,he=()=>{m.stopRecording&&(m.stopRecording(),m.stopRecording=void 0),m.isRecording=!1,["cleanupInterval","noopInterval","pendingCheckInterval"].forEach(e=>{m[e]&&(clearInterval(m[e]),m[e]=void 0)}),at()},bt=["did not allow mutations","called in an invalid security context"],vt=e=>{if(!e)return!0;for(const t of bt)if(e.toLowerCase().includes(t))return!1;return!0},St=(e,t,{reportError:n=!0,extraInfo:a})=>{D()||t instanceof Error&&(ye(),vt(t==null?void 0:t.message)&&(n&&window.UserLeap.reportError(e,t,a),u.clearAll()))},Ct=async(e,t,{reportError:n}={reportError:!0})=>{var r;let a;try{if(n&&((r=window.navigator.storage)!=null&&r.estimate)){const{quota:s=0,usage:i=0}=await window.navigator.storage.estimate();a={availableSpaceInMB:(s-i)/2**20,quota:s,usage:i}}}catch(s){window.UserLeap.reportError("Error getting storage estimate",s,{originalMessage:e,originalError:t})}St(e,t,{reportError:n,extraInfo:a})},B=(e,t,{reportError:n}={reportError:!0})=>(he(),o.error(`${e} - ${JSON.stringify(t)}`),Ct(e,t,{reportError:n})),h=async(e,t)=>{try{await e()}catch(n){B(t,n)}},Dt=()=>{m.isRecording&&h(()=>{var e,t;return(t=(e=window.rrwebRecord)==null?void 0:e.takeFullSnapshot)==null?void 0:t.call(e,!0)},"Error recording full snapshot")},Et=async({surveyId:e,responseGroupUuid:t,eventDigest:n,headers:a})=>{if(!e||!t)return!1;const r=window.UserLeap._API_URL,s=await ce({surveyId:e,responseGroupUuid:t,eventDigest:n,apiUrl:r,headers:a},!0);return!(s!=null&&s.error)},te=30,kt=1;K("replayStorage").catch(console.error);K("sprig.replay").catch(console.error);class Pt{openDB(){return Oe("sprigReplay",kt,{upgrade:(t,n,a)=>{if(a===0&&o.sessionStorageHelper.setItem("sprig.pendingCount","0"),!t.objectStoreNames.contains("events")){const r=t.createObjectStore("events",{keyPath:"uuid"});r.createIndex("sessionId","sessionId"),r.createIndex("timestamp","timestamp"),r.createIndex("[sessionId+timestamp]",["sessionId","timestamp"])}if(!t.objectStoreNames.contains("chunkUploads")){const r=t.createObjectStore("chunkUploads",{keyPath:"uuid"});r.createIndex("sessionId","sessionId"),r.createIndex("timestamp","timestamp"),r.createIndex("[sessionId+status]",["sessionId","status"]),r.createIndex("[uploadId+status]",["uploadId","status"]),r.createIndex("[sessionId+status+uploadId]",["sessionId","status","uploadId"])}if(!t.objectStoreNames.contains("pendingCaptures")){const r=t.createObjectStore("pendingCaptures",{keyPath:"uuid"});r.createIndex("sessionId","sessionId"),r.createIndex("timestamp","timestamp"),r.createIndex("[sessionId+targetTimestamp]",["sessionId","targetTimestamp"])}}})}constructor(){this.openDB().catch(t=>{o.error(`Error opening replay storage: ${t.message}`),ye(),t.name==="VersionError"&&K("sprigReplay").catch(console.error)})}async bulkAdd(t,n){const a=(await this.openDB()).transaction(t,"readwrite");return Promise.all([...n.map(r=>a.store.add(r)),a.done])}async clearAll(){const t=(await this.openDB()).transaction(["events","chunkUploads","pendingCaptures"],"readwrite");return Promise.all([t.objectStore("events").clear(),t.objectStore("chunkUploads").clear(),t.objectStore("pendingCaptures").clear()])}async deleteBySessionId(t,n){const a=IDBKeyRange.only(n),r=(await this.openDB()).transaction(t,"readwrite");let i=await r.store.index("sessionId").openCursor(a);for(;i;)i.delete(),i=await i.continue();await r.done}async updatePartial(t,n,a){const s=(await this.openDB()).transaction(t,"readwrite"),i=await s.store.get(n);i&&await s.store.put({...i,...a}),await s.done}async deleteRowsBefore(t,n,a=()=>!0){const r=IDBKeyRange.upperBound(n,!0),s=(await this.openDB()).transaction(t,"readwrite");let c=await s.store.index("timestamp").openCursor(r);for(;c;)a(c.value)&&c.delete(),c=await c.continue();await s.done}async getEventsBetween(t,n=Date.now()){if(t>=n)return Promise.resolve([]);const a=IDBKeyRange.bound([w,t],[w,n],!1,!0);return(await this.openDB()).getAllFromIndex("events","[sessionId+timestamp]",a)}async updateEventsExpiredAt(t,n,a=te){const r=new Date,s=r.setMinutes(r.getMinutes()+(a??te)),i=(await this.openDB()).transaction("events","readwrite"),c=i.store.index("[sessionId+timestamp]"),l=IDBKeyRange.bound([w,t],[w,n],!1,!0);let d=await c.openCursor(l);for(;d;)d.update({...d.value,expiredAt:s}),d=await d.continue();await i.done}async deleteChunkUploads(t,n){const a=IDBKeyRange.only([n,t]),r=(await this.openDB()).transaction("chunkUploads","readwrite");let i=await r.store.index("[uploadId+status]").openCursor(a);for(;i;)i.delete(),i=await i.continue();await r.done}async getChunkUploadsByStatus({sessionId:t,status:n,uploadId:a}){const s=(await this.openDB()).transaction("chunkUploads","readonly"),i=a?s.store.index("[uploadId+status]"):s.store.index("[sessionId+status]"),c=a?IDBKeyRange.only([a,n]):IDBKeyRange.only([t,n]);return i.getAll(c)}async getPendingCaptures(t={}){return(await(await this.openDB()).getAllFromIndex("pendingCaptures","sessionId",w)).filter(r=>!t.beforePresent||r.targetTimestamp<Date.now()).filter(r=>!t.isHeatmap||(r.captureParams.isHeatmap??!1))}async markPendingCaptureToCanUpload(t){const n=(await this.openDB()).transaction("pendingCaptures","readwrite");let r=await n.store.index("sessionId").openCursor(w);for(;r;){const s=r.value;s.captureParams.responseGroupId===t&&r.update({...s,canUpload:!0}),r=await r.continue()}await n.done}async markPendingHeatmapsReady(t){if(parseInt(o.sessionStorageHelper.getItem("sprig.pendingCount")??"0")===0)return null;const a=Date.now(),r=(await this.openDB()).transaction("pendingCaptures","readwrite");let i=await r.store.index("sessionId").openCursor(w);for(;i;){const c=i.value;c.captureParams.isHeatmap&&(!t||t.includes(c.uuid))&&i.update({...c,targetTimestamp:a,captureParams:{...c.captureParams,triggerTimestamp:a,replayParams:{...c.captureParams.replayParams,replayDurationSeconds:Math.floor((a-c.timestamp)/1e3)}}}),i=await i.continue()}await r.done}}const u=new Pt,Rt=async(e,t,n)=>new Promise((a,r)=>{const s=e.createElement("script");s.src=t,s.onload=a,s.onerror=r,n&&(s.nonce=n),e.head.appendChild(s)}),Ie=async(e,t)=>{const n=performance.now();let a;try{a=await e()}finally{const r=performance.now()-n;let s=o.PerformanceMetrics[t];s||(s=o.registerMetric(t)),s.report(r/1e3)}return a},be=(e,t)=>{const n=performance.now();try{e()}finally{const a=performance.now()-n;let r=o.PerformanceMetrics[t];r||(r=o.registerMetric(t)),r.report(a/1e3)}};let ne=1,F=5e3,R=6e4;const re=1e3,xt=5,ve=30,T=ve+xt;let ae=Date.now(),C,W=!!o.sessionStorageHelper.getItem("sprig.isCapturingHeatmap"),j=!1,V=[];const Tt=async({viewDocument:e,maxReplayDurationSeconds:t,replayNonce:n,maxInflightRequests:a=2,replaySettings:r,teardownAfter:s=!1})=>{C=o.sessionStorageHelper.getItem("sprig.pendingCount"),!m.isRecording&&(s&&o.sessionStorageHelper.setItem("sprig.teardownAfterCapture","true"),await h(async()=>{if(D()){o.info("Not initializing replay because recording is disabled");return}if(!t){o.info("Not initializing replay because config didn't specify maxReplayDurationSeconds");return}if(r!=null&&r.minAvailableGb&&(ne=r.minAvailableGb),!await it(ne)){o.warn("Minimum storage not available");return}if(o.info("Initializing replay"),r!=null&&r.minDuration&&(F=r.minDuration),r!=null&&r.batchDuration&&(R=r.batchDuration),Be(a),Mt(),$t(t+T,30*60,t+T),Nt(),!window.rrwebRecord){o.info("Loading recording script");const d=window.UserLeap.replayLibraryURL??"https://cdn.sprig.com/dependencies/record-2.0.0-alpha.6.min.js";await Rt(e,d,n),o.info("Recording script finished loading")}const i=window.rrwebRecord;if(!i){o.warn("Record script failed to set global function");return}let c=!0,l=0;m.stopRecording=i({checkoutEveryNms:ve*1e3,sampling:{input:"last",scroll:250,media:800},emit:(d,p)=>{if(D())return;if(ae=Date.now(),p&&d.type===P.Meta)l=performance.now();else if(p&&l&&d.type===P.FullSnapshot){const y=performance.now()-l;o.reportAndRegister("sdk_replay_snapshot_seconds",y/1e3)}const g=c||!!p&&d.type===P.Meta;c=!1,At({uuid:o.v4(),event:JSON.stringify(d),isValidStart:g,timestamp:Date.now()})},...r}),m.isRecording=!!m.stopRecording,m.isRecording&&(m.noopInterval||(m.noopInterval=window.setInterval(()=>{Date.now()-ae>re&&I("Sprig_Noop",{})},re)),o.eventEmitter.on("survey.complete",d=>{gt({id:d,userAgent:window.navigator.userAgent})}),rt())},"Error initializing replay"))},At=e=>{var t,n,a,r;if((t=e.event)!=null&&t.includes("Sprig_Scroll")){const s=(r=(a=(n=JSON.parse(e.event))==null?void 0:n.data)==null?void 0:a.payload)==null?void 0:r.xPath;if(!s)return;m.scrollEventUuids[s]=e.uuid}V.push(e),j||Ut()},Bt=async e=>{const t=e.map(n=>({...n,sessionId:n.sessionId??w}));if(W&<(t.length),t.length!==0)return h(()=>u.bulkAdd("events",t),"Error storing replay events")},Ut=()=>{j=!0,setTimeout(async()=>{if(D())return;const e=V;V=[],j=!1,be(async()=>{await Bt(e)},"sdk_replay_add_event_batch_seconds")},500)},$t=(e,t,n)=>{m.cleanupInterval=window.setInterval(()=>{const a=Date.now();D()||(o.debug(`Performing periodic replay data cleanup / Event Seconds ${e} / Chunk Seconds ${t} / Pending Capture Seconds ${n}`),Ie(()=>h(async()=>{await Promise.all([u.deleteRowsBefore("events",a-e*1e3,r=>r.expiredAt===void 0||r.expiredAt<a-e*1e3),u.deleteRowsBefore("chunkUploads",a-t*1e3),u.deleteRowsBefore("pendingCaptures",a-n*1e3,r=>!r.canUpload)])},"Error deleting table rows"),"sdk_replay_cleanup_seconds"),o.info("Cleanup complete"))},3e4)},Nt=()=>{m.pendingCheckInterval=window.setInterval(async()=>{h(async()=>{const e=parseInt(C??"0");if(e===0)return;const t=await u.getPendingCaptures({beforePresent:!0}),n=await u.openDB();await Promise.all(t.map(async a=>(await n.delete("pendingCaptures",a.uuid),De(a.captureParams,a.canUpload)))),C=(e-t.length).toString(),o.sessionStorageHelper.setItem("sprig.pendingCount",C)},"Error initiating pending captures")},5e3)},_t=async(e,t,n,a,r)=>{const s=Math.min(e+r,n),i=`from: ${new Date(e).toLocaleTimeString()} to ${new Date(s).toLocaleTimeString()}`;o.info(`Getting event batch ${i}`);const c=await Ie(()=>u.getEventsBetween(e,s),"sdk_replay_get_events_between_seconds");if(!(c!=null&&c.length))return o.info(`No events found ${i}`),{validStartFound:a,events:[]};if(!a){o.info(`Searching for valid start in ${c.length} events ${i}`);let l=-1;if(c==null||c.forEach((p,g)=>{if(!p.isValidStart)return;const y=p.timestamp<=t;(l<0||y)&&(l=g)}),l<0)return o.info(`No valid start found in ${c.length} events ${i}`),{validStartFound:a,events:[]};const d=c[l].timestamp;return o.info(`Found valid start at: ${new Date(d).toLocaleTimeString()} in events ${i}`),{validStartFound:!0,events:c==null?void 0:c.slice(l)}}return{validStartFound:a,events:c}},Lt=(e,t,n)=>{const a=e.length,r=t*1024*1024,s=Math.ceil(a/n),i=Math.max(r,s);o.info(`Total file bytes: ${a} / target chunk size: ${i}`);const c=[];let l=0;for(;l<a;)c.push(e.slice(l,l+i)),l+=i;return c},Se=e=>Promise.all(e.map(async t=>{const n=await Ue(t);return await u.updatePartial("chunkUploads",t.uuid,{data:null,etag:n,status:"UploadComplete"}),t.uploadId})),Ce=async e=>{o.info(`Marking upload complete if finished: ${e}`);const t=await u.getChunkUploadsByStatus({status:"UploadComplete",uploadId:e});if(!(t!=null&&t.length)){o.info(`No finished chunks found for upload: ${e}`);return}const n=t.reduce((s,i)=>(s.find(c=>c.chunkIndex===i.chunkIndex)||s.push(i),s),[]);n.sort((s,i)=>s.chunkIndex-i.chunkIndex);const a=n.map(s=>({ETag:s.etag,PartNumber:s.chunkIndex})).filter(s=>s.ETag!==null),r=n[0];await ce({apiUrl:r.apiUrl,surveyId:r.surveyId,uploadId:e,responseGroupUuid:r.responseGroupId,etags:a,headers:r.completeUploadHeaders,replayDuration:r.replayDuration}),o.info(`Cleaning up chunks for ${e}`),await u.deleteChunkUploads("UploadComplete",e),o.info(`Done cleaning up chunks for ${e}`)},Mt=async()=>{h(async()=>{const e=await u.getChunkUploadsByStatus({sessionId:w,status:"ReadyForUpload"});if(!(e!=null&&e.length))return;const t=await Se(e);o.info(`Finished uploading unfinished chunks for ${t}`),t!=null&&t.length&&await Promise.all(t.map(n=>{if(n)return Ce(n)}))},"Error uploading unfinished chunks")},Ht=async(e,t)=>{await Se(t),o.info(`Done uploading chunks for uploads: ${e.join(",")}`),await Promise.all(e.map(n=>Ce(n)))},Ot=e=>{let t=0;e.forEach(r=>{t+=r.length});const n=new Uint8Array(t);let a=0;return e.forEach(r=>{n.set(r,a),a+=r.length}),n},se=async(e,t,n)=>{const a=new TextEncoder;let r=null,s=null,i=null,c=!1,l=!1,[d,p]=[0,0];const g=e-T*1e3,y=[];let f=[];o.info(`Getting events between ${new Date(e).toLocaleTimeString()} and ${new Date(t).toLocaleTimeString()}`),o.info(`Using batch duration: ${R}ms`);for(let k=g;k<t;k+=R){if({validStartFound:l,events:f}=await _t(k,e,t,l,R),!(f!=null&&f.length)){o.info("No events found");continue}d===0&&(d=f[0].timestamp),p=f[f.length-1].timestamp,o.info(`Last event time in batch: ${new Date(p).toLocaleTimeString()}`);const Pe=`${c?",":"["}${f.map(Re=>Re.event).join(",")}`,z=a.encode(Pe);n&&s===null&&(o.debug("Attempting compression"),i=new window.CompressionStream("gzip"),s=i.writable.getWriter()),be(()=>{n&&s?s.write(z):y.push(z)},"sdk_replay_compression_seconds"),c=!0}if(p-d<F)return o.info(`Replay duration is shorter than minimum of ${F}ms / Start:${d} / End:${p}`),null;const b=a.encode("]");return o.debug("Writing final close brace"),s&&i?(s.write(b),s.close(),r=new Uint8Array(await new Response(i.readable).arrayBuffer())):(y.push(b),r=Ot(y)),o.info("Finished generating file data"),r},Ft=async(e,t)=>{const n=window.CompressionStream!==void 0;let a=null;const r=t??Date.now(),s=r-e;try{a=await se(s,r,n)}catch(i){i instanceof Error&&window.UserLeap.reportError("Error compressing replay",i),n&&h(async()=>{await se(s,r,!1)},"fileData fallback failed")}return a},oe=async e=>{const{surveyId:t,responseGroupId:n,visitorId:a,apiUrl:r,completeUploadHeaders:s,replayParams:i,triggerTimestamp:c}=e,l=await Ft(i.replayDurationSeconds*1e3,c);if(l!=null&&l.length)o.info(`Found file data for survey: ${t}`);else{o.info(`File data is empty for survey: ${t}`);return}const d=Lt(l,i.minimumChunkSizeMb,i.signedUrls.length);o.info(`Got ${d.length} chunks for survey: ${t}`);const p=await Promise.all(d.map(async(g,y)=>{const f=o.v4(),b={apiUrl:r,chunkIndex:y+1,completeUploadHeaders:s,etag:null,responseGroupId:n,status:"ReadyForUpload",surveyId:t,timestamp:c,totalChunks:d.length,data:g,uploadId:i.uploadId,uploadUrl:i.signedUrls[y].url,uuid:f,visitorId:a};return o.info(`Recording chunk upload: ${JSON.stringify({index:b.chunkIndex,surveyId:b.surveyId,uploadId:b.uploadId,size:g.length,id:f},null,2)}`),await(await u.openDB()).add("chunkUploads",{...b,sessionId:b.sessionId??w}),o.info(`Done creating chunk upload: ${f}`),b}));o.info(`All chunk records created. Beginning upload for survey: ${t}`),await Ht([i.uploadId],p)},De=async(e,t)=>{if(o.info(`Attempting replay capture: ${JSON.stringify({isStandalone:e.isStandalone,duration:e.replayParams.replayDurationSeconds,type:e.replayParams.replayDurationType,responseGroupId:e.responseGroupId,surveyId:e.surveyId,triggerTimestamp:e.triggerTimestamp,visitorId:e.visitorId},null,2)}`),D())return o.info(`Replay recording is disabled: ${e.surveyId}`);o.info(`Replay recording enabled: ${e.surveyId}`);const{isHeatmap:n,isStandalone:a,replayParams:r,triggerTimestamp:s,responseGroupId:i}=e,c=async()=>{setTimeout(()=>o.eventEmitter.removeListener(o.SprigEvent.QuestionAnswered,c),0),h(async()=>{r.replayDurationType==="before"?await oe(e):await u.markPendingCaptureToCanUpload(i)},"Error in schedule/capture callback")};h(async()=>{if(r.replayDurationType==="after"||r.replayDurationType==="beforeAndAfter"){!a&&!n&&(o.info("Attaching QuestionAnswered listener for non-standalone replay"),o.eventEmitter.on(o.SprigEvent.QuestionAnswered,c)),o.info(`Scheduling capture for replay of type: ${r.replayDurationType}`),await ke(e);return}if(a||n||t)o.info(`Proceeding to capture replay for survey: ${e.surveyId} / standalone? ${a} / canUpload? ${t}`),await oe(e),n&&jt();else{const d=T+r.replayDurationSeconds,p=s-d*1e3,g=s;o.info(`Setting expiry minutes to ${r.expirationTimeLimitMinutes} for events from ${new Date(p).toLocaleTimeString()} to ${new Date(g).toLocaleTimeString()}`),await u.updateEventsExpiredAt(p,g,r.expirationTimeLimitMinutes),o.info("Attaching QuestionAnswered listener"),o.eventEmitter.on(o.SprigEvent.QuestionAnswered,c)}},"Error in scheduling/capturing replay")},jt=async()=>{parseInt(C??"0")||(o.sessionStorageHelper.removeItem("sprig.isCapturingHeatmap"),W=!1),o.sessionStorageHelper.getItem("sprig.teardownAfterCapture")&&(he(),Ee(),o.sessionStorageHelper.removeItem("sprig.teardownAfterCapture"))},Ee=()=>{if(D()){o.debug("Not clearing user data, replay is disabled");return}return Promise.all([u.deleteBySessionId("events",w),u.deleteBySessionId("pendingCaptures",w)]).catch(e=>{B("Error clearing user replay data",e)})},ke=async e=>{o.info(`Scheduling replay capture: ${JSON.stringify(e)}`);const{isHeatmap:t,surveyId:n}=e,a=await u.getPendingCaptures(),r=a==null?void 0:a.filter(l=>l.captureParams.surveyId===n);if(r!=null&&r.length){o.info(`Pending capture exists for survey: ${n}`);return}t&&(Dt(),W=!0,o.sessionStorageHelper.setItem("sprig.isCapturingHeatmap","true"));const s={...e,replayParams:{...e.replayParams}};e.replayParams.replayDurationType==="beforeAndAfter"&&(s.replayParams.replayDurationSeconds*=2),s.replayParams.replayDurationType="before";const i=e.triggerTimestamp+e.replayParams.replayDurationSeconds*1e3;s.triggerTimestamp=i,C=(parseInt(C??"0")+1).toString(),o.sessionStorageHelper.setItem("sprig.pendingCount",C),await(await u.openDB()).add("pendingCaptures",{canUpload:!1,captureParams:s,sessionId:w,targetTimestamp:i,timestamp:Date.now(),uuid:o.v4()})},Vt=Object.freeze(Object.defineProperty({__proto__:null,RecordEvent:pt,RecordPageView:dt,RecordSurveyShown:mt,_completeSessionReplay:Et,checkPendingHeatmapsUrl:ct,clearUserReplayData:Ee,disableRecording:B,initializeReplay:Tt,isReplayRecording:It,scheduleCapture:ke,scheduleOrCaptureReplay:De,tryReplayAction:h},Symbol.toStringTag,{value:"Module"}));o.registerReplay(Vt);
|