!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8a199fe2-6214-5d50-ac0a-2590159f6e9d")}catch(e){}}(); (function(){"use strict";var Fa=Object.defineProperty;var Na=(V,G,ue)=>G in V?Fa(V,G,{enumerable:!0,configurable:!0,writable:!0,value:ue}):V[G]=ue;var E=(V,G,ue)=>Na(V,typeof G!="symbol"?G+"":G,ue);var Ss,Ts,Us;let V;const G=new Uint8Array(16);function ue(){if(!V&&(V=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!V))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return V(G)}const R=[];for(let e=0;e<256;++e)R.push((e+256).toString(16).slice(1));function Os(e,t=0){return R[e[t+0]]+R[e[t+1]]+R[e[t+2]]+R[e[t+3]]+"-"+R[e[t+4]]+R[e[t+5]]+"-"+R[e[t+6]]+R[e[t+7]]+"-"+R[e[t+8]]+R[e[t+9]]+"-"+R[e[t+10]]+R[e[t+11]]+R[e[t+12]]+R[e[t+13]]+R[e[t+14]]+R[e[t+15]]}const Gt={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function pe(e,t,r){if(Gt.randomUUID&&!e)return Gt.randomUUID();e=e||{};const n=e.random||(e.rng||ue)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Os(n)}const Ms='.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}',Bs="360px",Fs=500;var W=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.FeedbackClosed="feedback.closed",e.PageChange="page.change",e.API="api",e.Override="override",e))(W||{}),g=(e=>(e.ReplayCapture="replay.capture",e.ReplayPaused="replay.paused",e.ReplayResumed="replay.resumed",e.FeedbackButtonLoaded="feedback.button.loaded",e.SDKReady="sdk.ready",e.SurveyAppeared="survey.appeared",e.SurveyCloseRequested="survey.closeRequested",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))(g||{});const De={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"}},Ns=300;class Hs{constructor(){E(this,"breadcrumbs",[])}getTimeStamp(){return new Date().toISOString()}addBreadcrumb(t){this.breadcrumbs.push(t),this.breadcrumbs.length>Ns&&this.breadcrumbs.shift()}debug(t,r="debug"){this.addBreadcrumb({category:r,level:"info",message:t,timestamp:this.getTimeStamp(),type:"debug"})}error(t,r={}){this.addBreadcrumb({category:"error",data:r,level:"error",message:t,timestamp:this.getTimeStamp(),type:"error"})}http(t,r){this.addBreadcrumb({category:"xhr",data:r,message:t,timestamp:this.getTimeStamp(),type:"http"})}info(t,r={}){this.addBreadcrumb({category:"info",data:r,level:"info",message:t,timestamp:this.getTimeStamp(),type:"info"})}navigation(t,r){this.addBreadcrumb({category:"navigation",data:r,message:t,timestamp:this.getTimeStamp(),type:"navigation"})}}const p=new Hs,Yt=()=>{try{return window.parent.Intercom}catch{return null}},Jt=[Object.freeze(Object.defineProperty({__proto__:null,disable:()=>{const e=Yt();e&&(e.ul_wasVisible=!!document.querySelector("iframe.intercom-launcher-frame"),e.ul_wasVisible&&e("update",{hide_default_launcher:!0}))},enable:()=>{const e=Yt();e&&(e.ul_wasVisible&&e("update",{hide_default_launcher:!1}),delete e.ul_wasVisible)}},Symbol.toStringTag,{value:"Module"}))];class Vs{static disable(){Jt.forEach(t=>t.disable())}static enable(){Jt.forEach(t=>t.enable())}}var Ws=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"}},Qt=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=Qt.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=(...n)=>(this.removeListener(e,r),t.apply(this,n));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(n=>{n.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 n=new Ws(this,e,this.listenerCount(e));console.warn(n)}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 n=[t].concat(r);this.events.set(e,n)}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)}},Xt=Qt;Xt.defaultMaxListeners=10;const h=new Xt,Ce=async e=>{await new Promise(t=>{setTimeout(t,e)})},Zt=({"userleap-platform":e})=>{var t;return((t=window.UserLeap)==null?void 0:t.forceDirectEmbed)||e!=="web"};class er{constructor(t){E(this,"storage");E(this,"tempStorage",{});E(this,"isStorageAvailable");try{this.storage=window[t];const r="__storage_test__";this.storage.setItem(r,r),this.storage.removeItem(r),this.isStorageAvailable=!0}catch{this.isStorageAvailable=!1}}setItem(t,r){this.isStorageAvailable&&this.storage?this.storage.setItem(t,r):this.tempStorage[t]=r}setItemObject(t,r){try{this.setItem(t,JSON.stringify(r))}catch(n){n instanceof Error&&(n.stack=t+": "+r,window.UserLeap.reportError("Failed to save to local storage",n))}}getItem(t){return this.isStorageAvailable&&this.storage?this.storage.getItem(t):this.tempStorage[t]}getItemObject(t){const r=this.getItem(t);if(r)try{return JSON.parse(r)}catch(n){n instanceof Error&&(n.stack=t+": "+r,window.UserLeap.reportError("Failed to parse local storage",n))}return{}}removeItem(t){this.isStorageAvailable&&this.storage?this.storage.removeItem(t):delete this.tempStorage[t]}clear(){this.isStorageAvailable&&this.storage?this.storage.clear():this.tempStorage={}}}const w=new er("sessionStorage"),Z=new er("localStorage");class js{constructor(t){E(this,"payload");E(this,"promise");E(this,"reject",()=>{});E(this,"resolve",()=>{});this.payload=t,this.promise=new Promise((r,n)=>{this.reject=n,this.resolve=r})}resolveRequest(t){this.resolve(t)}}const L={replay:null},qs=e=>{L.replay=e},$s=()=>{const e=[];return L.replay&&e.push("replay"),e.join(",")},zs={RATELIMIT_RESET_DEFAULT:10};let tr=!1,rr="",Ae=!1,sr=!1,xe=[];const Ks=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?"web-gtm":e._segment?"web-segment":"web-snippet",nr=e=>{var t;(t=e==null?void 0:e.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(sr=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`))},st=(e="")=>{tr=!0,rr=e};function B(e={}){const t={"Content-Type":"application/json","userleap-platform":"web","x-ul-sdk-version":"2.48.0","x-ul-installation-method":Ks(e),"sprig-modules":$s()};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 ir=async({shouldDropOnRateLimit:e,...t})=>{if(e)return{status:429};{const r=new js(t);return xe.push(r),r.promise}},Y=async(e,t)=>{const{retries:r=0,shouldDropOnRateLimit:n=!1,shouldRetryRequest:s=!1,...i}=t,a={url:e,options:i,retries:r,shouldDropOnRateLimit:n};if(Ae&&!s)return ir(a);const o={ok:!1,reportError:!1};if(tr)return console.info(`UserLeap - ${rr}`),o;try{const l=await fetch(e,i);if(l.status===429)if(!Ae&&!n||s){Ae=!0;const u=l.headers.has("ratelimit-reset")?Number(l.headers.get("ratelimit-reset")):zs.RATELIMIT_RESET_DEFAULT;return await Ce(u*1e3),Y(e,{...i,shouldDropOnRateLimit:n,shouldRetryRequest:!0})}else return ir(a);if(Ae=!1,xe.length&&(xe.map(d=>{const u=d.payload;Y(u.url,{...u.options,retries:u.retries,shouldDropOnRateLimit:u.shouldDropOnRateLimit}).then(c=>{d.resolveRequest(c)})}),xe=[]),l.ok){if(l.status===249)return st(),o;const d=await l.text();try{return d&&d!=="OK"&&(l.json=JSON.parse(d)),l}catch{return{ok:!1,reportError:!1,error:new Error(`failed parsing response json for ${e} - ${d}`)}}}return l}catch(l){const d=r+1;return d>5||sr?{ok:!1,reportError:!1,error:l}:(await Ce(Math.pow(2,r)*1e3),Y(e,{...i,retries:d}))}},ar="ul-view-sdk-script",Gs="ios",Ys="android",Js=new Set([Gs,Ys]),ee="visitors",te="environments";async function j(e,t){var i,a,o;const{shouldDropOnRateLimit:r,...n}=t;n.headers=Object.assign(B(window.UserLeap),n.headers);const s=await Y(e,{...n,shouldDropOnRateLimit:r});if(s.ok){const l=(i=s.headers)==null?void 0:i.get("Authorization"),d=l?l.split(" "):void 0,u=d&&d.length===2?d[1]:void 0,c=(a=s.headers)==null?void 0:a.get("x-ul-visitor-id");if(window.UserLeap.userId&&c===window.UserLeap.visitorId){const m=Z.getItemObject("sprig.anon.env.vid.map");m&&m[window.UserLeap.envId]===c&&(delete m[window.UserLeap.envId],Z.setItemObject("sprig.anon.env.vid.map",m))}u&&c&&(c!==window.UserLeap.visitorId||window.UserLeap.token!==u)&&(A("token",u),A("vid",c),h.emit(g.VisitorIDUpdated,{visitorId:c}),window.UserLeap.token=u,window.UserLeap.visitorId=c)}return(o=s.json)!=null&&o.logMessage&&console.warn(`[Sprig] ${s.json.logMessage}`),s}function A(e,t){const r=Z.getItemObject("userleap.ids");let n=r[window.UserLeap.envId];n?n[e]=t:n={[e]:t},r[window.UserLeap.envId]=n,Z.setItemObject("userleap.ids",r)}function nt(){return window.previewMode?"0":window.UserLeap.visitorId??""}function F(e,t,r){const n=[window.UserLeap._API_URL,"sdk",e];return t&&t.forEach(s=>{n.push(s),s===te?n.push(window.UserLeap.envId):s===ee&&n.push(nt())}),r&&n.push(r),n.join("/")}const Qs=()=>{const e=B(window.UserLeap),t=we(e),r=window.UserLeap.forceDirectEmbed,n=e["userleap-platform"]==="web";return t||r&&n},be=async(e,t,r)=>{var Ds,Cs,As,xs;const{context:n,delay:s,avatars:i,experimentFlags:a,forceBrandedLogo:o,endCard:l,isFeedback:d=!1,heatmap:u,locale:c,layout:m,previewMode:f,productConfig:y,quotaMessages:b,providerPersona:N,quotas:k,questions:T,responseGroupUid:M,surveyId:C,uuid:ae,vid:O,sessionReplay:_,showProviderPersona:Is,useBranding:_a,studyType:Da,surveyVisitorAttributes:Ca}=e,de=B(window.UserLeap),Aa=we(de),qt=Pe(de);if(_)if(Aa)h.emit(g.ReplayCapture,{responseGroupUid:M,hasQuestions:!!(T!=null&&T.length),surveyId:C,uploadId:_.uploadId,replayType:_.replayDurationType??"before",seconds:_.replayDurationSeconds,generateVideoUploadUrlPayload:{mediaRecordingUid:pe(),mediaType:"screen",questionId:1,responseGroupUid:M,surveyId:C,updatedAt:new Date().toISOString(),visitorId:window.UserLeap.visitorId,isReplay:!0}});else{if(!L.replay)return window.UserLeap.reportError("displayQuestions",new Error("Replay module not registered")),{success:!1,message:"Replay module not registered",surveyState:"no survey"};L.replay.scheduleOrCaptureReplay({responseGroupId:M,surveyId:C,visitorId:O,replayParams:_,completeUploadHeaders:de,apiUrl:window.UserLeap._API_URL,triggerTimestamp:Date.now(),isStandalone:T.length===0})}if(u){if(!L.replay)return window.UserLeap.reportError("displayQuestions",new Error("Replay module not registered")),{success:!1,message:"Replay module not registered",surveyState:"no survey"};const{eventId:I,replayParams:Kt,responseGroupUid:Ma,surveyId:Ba}=u;await L.replay.initializeReplay({maxReplayDurationSeconds:300,maxInflightRequests:window.UserLeap.maxInflightReplayRequests,teardownAfter:!0,apiUrl:window.UserLeap._API_URL,replaySettings:r}),L.replay.tryReplayAction(()=>{var Ps;return(Ps=L.replay)==null?void 0:Ps.scheduleCapture({apiUrl:window.UserLeap._API_URL,completeUploadHeaders:de,eventId:I,isHeatmap:!0,replayParams:Kt,responseGroupId:Ma,surveyId:Ba,triggerTimestamp:Date.now(),visitorId:O})},"Error in scheduling/capturing replay")}if(O==null||!(T!=null&&T.length))return p.info("CannotDisplaySurvey",{vid:O}),{success:!1,message:"[Sprig] no survey found",surveyState:window.UserLeap.container?"previous survey ready":"no survey"};if(window.UserLeap.container){p.info("AlreadyDisplayingSurvey");const I="[Sprig] (ERR-409) Found an existing Survey container, aborting rendering of this survey";return console.warn(I),{success:!1,message:I,surveyState:"previous survey ready"}}if(O!==window.UserLeap.visitorId&&ae!==window.UserLeap.visitorId&&!window.previewMode){const I="Attempted to display survey to a different visitor";return window.UserLeap.reportError("DisplaySurvey",new Error(I)),{success:!1,message:I,surveyState:"no survey"}}p.info("ShowingSurvey",{surveyId:C}),(Ds=L.replay)==null||Ds.RecordSurveyShown({id:C,userAgent:window.navigator.userAgent}),Vs.disable(),h.emit(g.SurveyWillPresent,{name:g.SurveyWillPresent,"survey.id":C,layout:m});let et,tt=document.createElement("div"),_e,H,rt;const Es=I=>{const{"view.version":Kt}=I;Kt!==de["x-ul-sdk-version"]&&cr(),h.removeListener("verify.view.version",Es)};h.on("verify.view.version",Es),window.UserLeap.useMobileStyling=qt,Zt(de)?(et="ul-direct-embeded-frame",_e=document.head,H=window,rt=!1,Qs()&&(lr(C,d),tt.id=et,window.UserLeap.container.appendChild(tt),dr(),h.emit(g.SurveyLifeCycle,{state:"presented"}),h.emit(g.SurveyPresented,{name:g.SurveyPresented,"survey.id":C}))):{frameId:et,contentWinDocHead:_e,contentWindow:H,hasOverlay:rt,iframe:tt}=an({productConfig:y,useMobileStyling:qt,surveyId:C,isFeedback:d,enableCspTrustedTypes:(Cs=window.UserLeap._config)==null?void 0:Cs.enableCspTrustedTypes}),window.UserLeap.frameId=et;const xa=I=>{h.once(g.CloseSurveyOnOverlayClick,I)},ye={apiURL:window.UserLeap._API_URL,avatars:i,cards:T,configureExitOnOverlayClick:xa,context:n,endCard:l,envId:window.UserLeap.envId,eventEmitFn:h.emit.bind(h),experimentFlags:a,fontFamily:window.UserLeap.fontFamily,fontFamilyURL:window.UserLeap.fontFamilyURL,forceBrandedLogo:o,frame:tt,headers:de,layout:m,locale:c,mobileSDKVersion:window.UserLeap.mobileSDKVersion,previewKey:w.getItem("sprig.previewKey"),previewMode:f||!!window.previewMode,productConfig:{framePosition:y==null?void 0:y.framePosition,desktopDisplay:y==null?void 0:y.desktopDisplay,placement:y==null?void 0:y.placement},quotaMessages:b,providerPersona:N,quotas:k,responseGroupUid:M,showProviderPersona:Is,useBranding:_a??!0,startingQuestionIdx:(As=window.UserLeap.config)==null?void 0:As.startingQuestionIdx,studyType:Da,styleNonce:window.UserLeap.styleNonce,surveyId:C,tabTitle:document.title,trackPageViewUrl:t,ulEvents:De,upchunkLibraryURL:window.UserLeap.upchunkLibraryURL,useMobileStyling:qt,userId:ae,viewDocument:H==null?void 0:H.document,viewWindow:H,visitorAttributes:{externalUserId:window.UserLeap.userId,email:window.UserLeap.email},surveyVisitorAttributes:Ca||{},...window.UserLeap._config};(xs=window.UserLeap._config)!=null&&xs.startingQuestionIdx&&(window.UserLeap._config={...window.UserLeap._config,startingQuestionIdx:null});const Pa=(d?window.UserLeap.feedbackCustomStyles:window.UserLeap.customStyles)??y.customStyles;ye.customStyles=Pa,H&&(H.__cfg=ye);function Oa(){const I=document.createElement("script");return window.UserLeap.isMobileSDK||I.setAttribute("type","module"),window.UserLeap.nonce&&I.setAttribute("nonce",window.UserLeap.nonce),I.id=ar,I}const $t=window.UserLeap.viewSDKURL?window.UserLeap.viewSDKURL:ye.path,ks=document.getElementById(ar);ks&&ks.remove();const zt=Oa(),Rs=()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{display:"flex"})};if(ye.installationMethod==="web-npm"||ye.installationMethod==="web-npm-bundled"){const{default:I}=await import("../view/view.tsx");I.configure(ye),rt&&window.UserLeap.container&&Rs()}else $t&&(zt.src=`${$t}${window.UserLeap.isMobileSDK?"":`?t=${Date.now()}`}`,rt&&zt.addEventListener("load",()=>{window.UserLeap.container&&Rs()}),H==null||H.addEventListener("error",I=>{I.target instanceof HTMLScriptElement&&I.target.src===$t&&window.UserLeap.reportError("loadFrameScript",new Error("Frame script failed to load"))},{capture:!0,once:!0}));_e==null||_e.appendChild(zt);const _s={success:!0,surveyState:"ready",surveyId:C,responseGroupUid:M};return window.UserLeap.isMobileSDK&&s&&(_s.delay=s),_s};function Pe(e){var r;if(window.UserLeap.useMobileStyling!==void 0)return window.UserLeap.useMobileStyling;const t=((r=window.UserLeap.windowDimensions)==null?void 0:r.width)??document.body.clientWidth;return we(e)||t>10&&t{var n,s;const t=or.get(e);if(t)return t;if(!((n=e.trustedTypes)!=null&&n.createPolicy))throw new Error("Trusted types not supported");const r=(s=e.trustedTypes)==null?void 0:s.createPolicy(Xs,{createHTML(i){return i},createScript(i){return i},createScriptURL(i){return i}});return or.set(e,r),r},en=(e,t)=>{try{return Zs(t).createHTML(e)}catch(r){return console.warn("Could not create TrustedHTML object",r),e}},it=(e,t,r=window)=>{var n;return t&&((n=r.trustedTypes)!=null&&n.createPolicy)?en(e,r):e},at="ul-frame";globalThis.UserLeap&&globalThis.Sprig&&(globalThis.Sprig._gtm?globalThis.Sprig=globalThis.UserLeap:globalThis.UserLeap=globalThis.Sprig),globalThis.UserLeap||(globalThis.UserLeap=globalThis.Sprig),globalThis.Sprig||(globalThis.Sprig=globalThis.UserLeap);const tn="rgba(255,255,255, 0.95)",rn="rgba(0,0,0,0.9)",ot="0px",lr=(e,t,r)=>{globalThis.UserLeap.container=document.createElement("div"),globalThis.UserLeap.container.className=`ul-container${t?" ul-container-feedback":""}`,e&&(globalThis.UserLeap.container.dataset.studyId=e.toString());const n=mr();r&&n&&!globalThis.UserLeap.useMobileStyling?n.appendChild(globalThis.UserLeap.container):document.body.appendChild(globalThis.UserLeap.container)},cr=(e,t)=>{var n;ln();const r=globalThis.UserLeap.container;if(r)try{(n=r.parentNode)==null||n.removeChild(r),globalThis.UserLeap.container=null,A("trackStartUrl",null),h.emit(g.SurveyLifeCycle,{state:"dismissed"}),h.emit(g.SurveyClosed,{name:g.SurveyClosed,initiator:e,"survey.id":parseInt(r.dataset.studyId),...t&&{studyType:t}})}catch(s){console.warn(`[Sprig] (ERR-412) Error removing UserLeap container by ${e} `+r),s instanceof Error&&globalThis.UserLeap.reportError("dismissActiveSurvey",s)}},dr=()=>{h.once(g.SurveyWillClose,({initiator:e,studyType:t})=>{h.removeAllListeners(g.CloseSurveyOnOverlayClick),cr(e,t)})},sn=(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}},s=t?e.overlayStyleMobile:e.overlayStyle;n["background-color"]=s==="light"?tn:rn,t||(n.margin="auto"),globalThis.UserLeap.container&&Object.assign(globalThis.UserLeap.container.style,n)},nn=(e,t,r,n)=>{var u,c;const s={position:"fixed",bottom:"0px",right:ot,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%"},i=Object.assign({},t,globalThis.UserLeap),{desktopDisplay:a}=t||{},o=a==="center-modal";o&&(i.framePosition="center");let l,d=!1;if(r)(u=globalThis.UserLeap.windowDimensions)!=null&&u.width?s.width=`${globalThis.UserLeap.windowDimensions.width}px`:s.width="100%",(c=globalThis.UserLeap.windowDimensions)!=null&&c.height?s.maxHeight=`${globalThis.UserLeap.windowDimensions.height-20}px`:globalThis.UserLeap.maxHeight?s.maxHeight=globalThis.UserLeap.maxHeight:s.maxHeight=`${document.body.clientHeight-20}px`,["light","dark"].includes(i.overlayStyleMobile)&&(d=!0);else{s.width=Bs,s.maxHeight=globalThis.UserLeap.maxHeight||"66vh";const m=()=>{d=!0,l={margin:"auto",position:"static"}};if(n)o?m():l={position:"relative",height:"300px"};else switch(i.framePosition){case"bottomLeft":l={left:ot};break;case"topLeft":l={left:ot,top:0};break;case"topRight":l={top:0};break;case"center":m();break}}return d&&sn(i,r),Object.assign(e.style,s,l),d},an=({productConfig:e,useMobileStyling:t,surveyId:r,isFeedback:n,enableCspTrustedTypes:s})=>{var f,y;const i=at,a=n&&e.desktopDisplay==="slider";lr(r,n,a),on();const o=document.createElement("iframe");o.id=i,o.setAttribute("title","Sprig User Feedback Dialog");const l=nn(o,e,t,n);dr();let d=!1;o.setHeight=b=>{(parseInt(o.style.height)!=b||!d)&&(d=!0,o.style.height=`${b}px`,h.emit(g.SurveyHeight,{name:g.SurveyHeight,contentFrameHeight:b,"survey.id":r}))};let u=!1;o.setWidth=b=>{(parseInt(o.style.width)!=b||!u)&&(u=!0,o.style.width=`${b}px`,h.emit(g.SurveyWidth,{name:g.SurveyWidth,contentFrameWidth:b,"survey.id":r}))},(f=globalThis.UserLeap.container)==null||f.appendChild(o),e&&(t?e.exitOnOverlayClickMobile:e.exitOnOverlayClick)&&globalThis.UserLeap.container&&(globalThis.UserLeap.container.onclick=()=>{h.emit(g.CloseSurveyOnOverlayClick)}),h.emit(g.SurveyLifeCycle,{state:"presented"}),h.emit(g.SurveyPresented,{name:g.SurveyPresented,"survey.id":r});const c=(y=o.contentWindow)==null?void 0:y.document;if(c&&(c.open("text/html","replace"),c.write(it("",s,o.contentWindow)),c.close(),!t)){const b=c.body;b.style.display="flex",b.style.alignItems="center"}const m=c==null?void 0:c.head;return{frameId:i,contentWinDocHead:m,contentWindow:o.contentWindow,hasOverlay:l,iframe:o}},ur={[g.SurveyFadingOut]:()=>{globalThis.UserLeap.container&&Object.assign(globalThis.UserLeap.container.style,{"background-color":"rgba(0,0,0,0)"})}},on=()=>{Object.entries(ur).forEach(([e,t])=>{h.on(e,t)})},ln=()=>{Object.entries(ur).forEach(([e,t])=>{h.off(e,t)})},pr=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 lt(e,t){const{matchType:r,pattern:n}=e,s=r?pr[r]:pr.legacy;let i=!1;try{i=s(n,t)}catch(a){const o=`[Sprig] (ERR-445) Failed to check url match with pattern ${n}`;a instanceof Error&&(console.warn(o,a),a.stack=JSON.stringify(e),window.UserLeap.reportError(o,a))}return i}const gr=e=>{const{pageUrlEvents:t}=window.UserLeap._config,r=t==null?void 0:t.find(n=>n.id===e);return r?lt(r,window.location.href):!1},re=e=>e?e.nodeType===Node.ELEMENT_NODE:!1,cn=2,hr=e=>e instanceof HTMLElement||e instanceof SVGElement,Oe=({document:e,elementId:t,styleString:r,nonce:n})=>{const s=e.getElementById(t);if(s){s.textContent=r;return}const i=e.createElement("style");n&&(i.nonce=n),i.textContent=r,i.id=t,e.head.appendChild(i)},dn=e=>{const t=e.querySelector(".sprig-question-body"),r=e.querySelector(".ul-card"),n=e.querySelector(".ul-card-main-content"),s=e.querySelector(".ul-footer"),i=e.querySelector(".sprig-container");let a=0;return re(r)&&(a+=r.scrollHeight-r.clientHeight),re(n)&&(a+=n.scrollHeight-n.clientHeight),re(t)&&(a+=t.scrollHeight-t.clientHeight),re(s)&&re(i)&&i.clientHeight===0&&(a+=s.clientHeight),a},fr=(e,t)=>{const r=t.querySelector(e);if(!re(r))return 0;const n=getComputedStyle(r),s=parseFloat(n.paddingLeft)+parseFloat(n.paddingRight),i=parseFloat(n.marginLeft)+parseFloat(n.marginRight),a=parseFloat(n.borderLeftWidth)+parseFloat(n.borderRightWidth);return s+i+a},un=(e,t,r)=>{const n=e.querySelector(".ul-card__container"),s=e.querySelector(".ul-app");let i=600,a=360;if(re(n)&&re(s)){const l=n.querySelector(".ul-card--matrix_grid"),d=!l&&t&&r;try{d&&(s.style.width="360px"),i=n.scrollHeight,i+=dn(e);const u=getComputedStyle(n),c=parseFloat(u.marginTop)+parseFloat(u.marginBottom),m=parseFloat(u.borderTopWidth)+parseFloat(u.borderBottomWidth);i+=c+m,l&&(a=l.scrollWidth,a+=fr(".ul-card__container",e),a+=fr(".sprig-question-body",e))}finally{d&&s.style.removeProperty("width")}}return[i+cn,a]},mr=()=>v,ge=()=>document.getElementById("sprig-feedback-container"),ct=()=>document.getElementById("sprig-feedback-loading-animation"),pn=()=>{var t;if(ct())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=it(`
`,(t=window.UserLeap._config)==null?void 0:t.enableCspTrustedTypes),e},yr=()=>!!document.getElementById(at);let br=!1,v=null,q=null,dt=!1,ve=null,oe=null;const gn=["bottom-left","bottom-right","center-left","center-right"],hn=e=>{if(ge()||!gn.includes(e))return;const[t,r]=e.split("-"),n=document.createElement("div");n.id="sprig-feedback-container",n.classList.add(`sprig-feedback-container-${r}`,`sprig-feedback-container-${t}`),document.body.appendChild(n)},Me=()=>{var t;const e=window.UserLeap.container;return((t=e==null?void 0:e.parentElement)==null?void 0:t.id)==="sprig-feedback-loading-container"},wr=()=>document.getElementById("sprig-feedback-error-container"),vr=()=>{if(!v)return 0;const e=v==null?void 0:v.clientWidth,t=window.getComputedStyle(v),r=parseInt(t.borderRightWidth||"0"),n=parseInt(t.borderLeftWidth||"0");return e+r+n},Be=e=>{const t=ge();t&&(oe!=null&&oe.endsWith("right")?t.style.right=`${e}px`:oe!=null&&oe.endsWith("left")&&(t.style.left=`${e}px`))},ut=()=>{if(v&&(Me()||wr())){h.off(g.SurveyAppeared,Le),pt();const e=vr();return Be(-e),!0}return!1},Le=()=>{if(!v||!q)return;const e=ct();e&&e.remove(),v.style.height="auto",v.style.width="auto",q.disabled=!1,dt=!1},pt=()=>{if(!v)return;if(!ct()){const t=pn();t&&(v.style.height="300px",v.style.width="360px",v.appendChild(t))}},Lr=()=>{!v||!q||(Be(0),q.disabled=!0,dt=!0)},fn=async e=>{const t=await j(F("1",[ee],"startFeedbackStudy"),{body:JSON.stringify({surveyUuid:e}),method:"POST"});return t.ok?t.json:null},Sr=async(e,t,r)=>{const{buttonTheme:n,customStyles:s,eventId:i,placement:a,desktopDisplay:o,feedbackLabel:l,surveyUuid:d,surveyId:u}=e;window.UserLeap.feedbackCustomStyles=void 0;let c=ge();if(c){if(!t&&i===ve)return;c.remove(),h.off(De.SURVEY_FADING_OUT,ut)}ve=i,Oe({document,elementId:"sprig-feedback-style",styleString:Ms,nonce:window.UserLeap.styleNonce}),Oe({document,elementId:"ul-custom-style",styleString:s??"",nonce:window.UserLeap.styleNonce}),br=o==="center-modal",oe=a;const[f,y]=a.split("-");hn(a),c=ge(),q=document.createElement("button");const b=document.createElement("div");b.className="sprig-feedback-button-label",b.innerText=l,q.appendChild(b),q.id="sprig-feedback-button",q.classList.add(`sprig-feedback-button-${y}`,`sprig-feedback-button-${f}`,`sprig-feedback-button-${n}`,"fade-in-transition"),h.on(De.SURVEY_FADING_OUT,ut),q.addEventListener("click",async()=>{const T=document.getElementById("sprig-feedback-error-container");if(yr()||wr()){if(ut()){h.emit(g.SurveyCloseRequested,{name:g.SurveyCloseRequested,initiator:W.FeedbackClosed,studyType:"feedbackButton","survey.id":u}),h.emit(g.SurveyWillClose,{name:g.SurveyWillClose,initiator:W.FeedbackClosed,studyType:"feedbackButton","survey.id":u});const O=ge();T&&O&&(O.remove(),ve=null,v=null)}return}const M=B(window.UserLeap);if(!Pe(M)&&!dt&&Lr(),t){v&&v.classList.add("sprig-feedback-loading-container-previews"),await be(t),Le();return}const ae=await fn(d);if(ae)h.once(g.SurveyAppeared,Le),be({...ae,studyType:"feedbackButton"},r);else if(v){const O=yn();v.appendChild(O),Le(),v.style.height="300px",v.style.width="360px"}}),c==null||c.appendChild(q),h.emit(g.FeedbackButtonLoaded,{name:g.FeedbackButtonLoaded,"survey.id":u});const{useMobileStyling:N,_config:{border:k}}=window.UserLeap;if(!br&&!N){const T=document.createElement("div");T.id="sprig-feedback-loading-container",T.className=`sprig-feedback-loading-container sprig-feedback-loading-container-${y}`,T.style.setProperty("--feedback-border",k),v=T,pt(),c==null||c.appendChild(T);const M=vr();Be(-M)}else Be(0);window.UserLeap._config.isOnQuestionsTab&&t&&!Me()&&v&&(Lr(),pt(),v&&v.classList.add("sprig-feedback-loading-container-previews"),be(t),Le())},mn=()=>{if(Me())return;const e=ge();if(!e)return;gr(ve)||(e.remove(),ve=null,v=null)},yn=()=>{var r;const e=document.createElement("div");e.id="sprig-feedback-error-container",e.innerHTML=it(` `,(r=window.UserLeap._config)==null?void 0:r.enableCspTrustedTypes);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},bn="!launch_darkly_";class wn{constructor(){E(this,"_ldData",{})}getAllLaunchDarklyVariations(){return this._ldData}setLDFlagsVariations(t){try{return!t||typeof t!="object"||Array.isArray(t)?!1:(Object.keys(this._ldData).forEach(r=>{delete this._ldData[r]}),Object.keys(t).forEach(r=>this._ldData[`${bn}${r}`]=(t[r]??0)+1),!0)}catch(r){return r instanceof Error&&window.UserLeap.reportError("setAllLDFlagsVariations",r),console.warn("[Sprig] An issue had occured when setting LaunchDarkly flags and variations."),!1}}}const gt=new wn;Object.freeze(gt);const vn="!optimizely_experiments_";class Ln{constructor(){E(this,"_optimizelyData",{})}setOptimizelyExperiment(t,r=!0){if(!t||typeof t!="object")return!1;const{experiments:n}=t;try{return r&&Object.keys(this._optimizelyData).map(s=>{delete this._optimizelyData[s]}),n&&n.map(s=>{const{id:i,variation:a}=s,o=this.transformExperimentId(i);a&&typeof a=="string"&&(this._optimizelyData[o]=a)}),!0}catch(s){return s instanceof Error&&window.UserLeap.reportError("setOptimizelyExperiment",s),!1}}getAllOptimizelyExperiments(){return this._optimizelyData}getOptimizelyVariationName(t){return this._optimizelyData[this.transformExperimentId(t)]}transformExperimentId(t){return vn+t}getAndSetWebOptimizelyExperiments(){var t;try{if(window&&window.optimizely&&typeof window.optimizely.get=="function"){const r=(t=window.optimizely.get("state"))==null?void 0:t.getExperimentStates({isActive:!0});if(r){const n=Object.keys(r).map(s=>{var i,a;return(i=r[s].variation)!=null&&i.name?{id:s,variation:(a=r[s].variation)==null?void 0:a.name}:{id:s,variation:"Original"}});return this.setOptimizelyExperiment({experiments:n},!1),!0}return!1}return!1}catch(r){return r instanceof Error&&window.UserLeap.reportError("getAndSetWebOptimizely",r),!1}}}const Fe=new Ln;Object.freeze(Fe);class Sn{constructor(t,r){E(this,"paused");E(this,"queue");E(this,"ul");this.ul=t,this.paused=!1,this.queue=[],this.flush(r)}flush(t){const r=t.length;if(r)for(let n=0;n{};const n=new Promise(function(s){r=function(){s(t())}});return this.queue.push(r),n}else return t()}empty(){this.queue.length=0}}let Tr=!0,ht=!1;const Tn=()=>Tr=!1,Un=()=>ht=!0,In=["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 Se={},ft;class En{constructor(t){E(this,"_values",[]);E(this,"_isWebMetric");this.name=t,this._isWebMetric=In.includes(this.name)}report(t){if(Tr&&this._values.push({time:Date.now(),value:t}),ht||!this._isWebMetric)return;const r=this.findExceededThreshold(t);r&&ft&&ft(t,r)}collect(){const t=this._values;return this._values=[],t}findExceededThreshold(t){const r=Se[this.name];if(r)return r.find(n=>this.valueExceedsThreshold(t,n))}valueExceedsThreshold(t,r){return r.type==="max"?t>r.value:r.type==="min"?t{Se={},ht=!1,e==null||e.forEach(r=>{var n;r.metric in Se||(Se[r.metric]=[]),(n=Se[r.metric])==null||n.push(r)}),ft=t},Te={},$=e=>{const t=new En(e);return Te[e]=t,t},Ur=(e,t)=>{let r=Te[e];return r||(r=$(e)),r.report(t)},Rn=async e=>{const t=Object.values(Te).map(r=>({name:r.name,values:r.collect()}));if(t.some(r=>r.values.length))try{await e(JSON.stringify(t))}catch(r){r instanceof Error&&p.error("MetricsErr",{error:{message:r.message,name:r.name}})}},_n=({reportingIntervalSeconds:e,postMetrics:t})=>{e?setInterval(()=>{Rn(t)},e*1e3):Tn()};let Ir,Er;const mt=e=>{let t=0,r=e.firstElementChild;for(;r;)t+=mt(r),r.shadowRoot&&(t+=mt(r.shadowRoot)),r=r.nextElementSibling,t++;return t},Dn=()=>document.documentElement.innerHTML.toString().length,kr=()=>{Ir.report(mt(document.body)),Er.report(Dn())},Cn=(e=10*1e3)=>{Ir=$("sdk_dom_nodes_count"),Er=$("sdk_page_html_characters"),kr(),setInterval(kr,e)},yt=(e,t)=>{const r=performance.now();document.hidden?setTimeout(()=>yt(e,t),e):setTimeout(()=>{const n=performance.now()-r;t.report(n/1e3),setTimeout(()=>yt(e,t),e)},0)},An=(e=1e3)=>{const t=$("sdk_event_queue_latency_seconds");yt(e,t)};let Ne,He,Ve,We,le={},Rr;const je=(e,t=1)=>{const{name:r}=e;le[r]=(le[r]||0)+t},_r=e=>{let t=1;return e.childNodes.forEach(r=>{t+=_r(r)}),t},Dr=e=>{let t=0;return e.forEach(r=>{t+=_r(r)}),t},xn=e=>{switch(e.type){case"childList":je(Ne,Dr(e.addedNodes)),je(He,Dr(e.removedNodes));return;case"attributes":je(Ve);return;case"characterData":je(We);return}},Pn=e=>e.forEach(xn),On=()=>{Rr=new MutationObserver(Pn),Rr.observe(document,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0})},Mn=()=>{Ne.report(le[Ne.name]||0),He.report(le[He.name]||0),Ve.report(le[Ve.name]||0),We.report(le[We.name]||0),le={}},Bn=(e=1*1e3)=>{Ne=$("sdk_mutations_nodes_added"),He=$("sdk_mutations_nodes_removed"),Ve=$("sdk_mutations_attributes_changed"),We=$("sdk_mutations_character_data"),On(),setInterval(Mn,e)},Fn=({isWeb:e,reportingIntervalSeconds:t,thresholds:r,postMetrics:n})=>{kn(r,(s,i)=>{var a,o;if((a=L.replay)!=null&&a.isReplayRecording()){const l=`Value: ${s} on ${i.metric} violated threshold of ${i.type} ${i.value}`;(o=L.replay)==null||o.disableRecording("Threshold violated",new Error(l),{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}),Un()}}),_n({reportingIntervalSeconds:t,postMetrics:n}),e&&(An(),Cn(),Bn())},Nn={test:"test"},Hn=["popState","pushState","replaceState"];let bt,Ue;const qe={},Ie="!email",Cr="pageUrl";function Vn(e){if(!globalThis.UserLeap._config.dismissOnPageChange)return!0;const t=new URL(e),r=new URL(Ue??globalThis.location.href);return t.hostname===r.hostname&&t.pathname===r.pathname}let wt=((Ss=globalThis.location)==null?void 0:Ss.href)||"";function Ee(e){var l,d;const{pageUrlEvents:t,interactiveEvents:r,dismissOnPageChange:n,platform:s}=globalThis.UserLeap._config;if(s&&s!=="web")return;wt!==globalThis.location.href&&p.navigation("LocationChange",{from:wt,to:globalThis.location.href}),wt=globalThis.location.href;const a=Pr().trackStartUrl,o=a?String(a):null;t&&Mr(globalThis.location.href),r&&(xr(),Wn()),mr()&&mn(),w.getItem("sprig.isCapturingHeatmap")&&((d=(l=L.replay)==null?void 0:l.checkPendingHeatmapsUrl())==null||d.then(u=>{var c;u&&((c=L.replay)==null||c.uploadReadyPendingCaptures(!0))})),!Me()&&n&&o&&o!==globalThis.location.href&&e&&Hn.includes(e.type)&&globalThis.UserLeap("dismissActiveSurvey",W.PageChange)}const Ar={capture:!0},Wn=()=>{const t=globalThis.UserLeap._config.interactiveEvents.filter(n=>lt(n,globalThis.location.href)).map(n=>{const{name:s,properties:i}=n,{selector:a,innerText:o}=i;return a?l=>{if(hr(l.target))try{l.target.closest(a)&&globalThis.UserLeap("track",s)}catch{}return!1}:l=>(hr(l.target)&&l.target.innerText===o&&globalThis.UserLeap("track",s),!1)}),r=n=>t.forEach(s=>s(n));globalThis.UserLeap._config.interactiveEventsHandler=r,globalThis.addEventListener("click",r,Ar)},xr=()=>{globalThis.UserLeap._config.interactiveEventsHandler&&globalThis.removeEventListener("click",globalThis.UserLeap._config.interactiveEventsHandler,Ar),delete globalThis.UserLeap._config.interactiveEventsHandler};function jn(){["hashchange","popstate"].forEach(e=>globalThis.addEventListener(e,Ee,!0))}function qn(){["hashchange","popstate"].forEach(e=>globalThis.removeEventListener(e,Ee,!0)),globalThis.UserLeap._config.interactiveEvents&&xr()}function $n(e){const t=new URL(F("1",[te],"questions"));return Object.entries(e||{}).forEach(([r,n])=>{n&&t.searchParams.append(r,String(n))}),t.toString()}function Pr(){const e=Z.getItemObject("userleap.ids");return(e==null?void 0:e[globalThis.UserLeap.envId])||{}}function Or(){if(globalThis.previewMode)return;const e=Z.getItemObject("sprig.anon.env.vid.map")||{},t=e[globalThis.UserLeap.envId];globalThis.UserLeap.visitorId=t||pe(),p.info("NewVid",{vid:globalThis.UserLeap.visitorId}),A("vid",globalThis.UserLeap.visitorId),t||(e[globalThis.UserLeap.envId]=globalThis.UserLeap.visitorId,Z.setItemObject("sprig.anon.env.vid.map",e)),h.emit(g.VisitorIDUpdated,{visitorId:globalThis.UserLeap.visitorId})}function Mr(e,t,r,n){var s,i;try{if(e.endsWith("mock_snippet.html"))return;p.info("PageView",{url:e});const a=(s=document==null?void 0:document.querySelector('meta[name="description"]'))==null?void 0:s.getAttribute("content");(i=L.replay)==null||i.RecordPageView({...a&&{description:a},url:e,referrer:document.referrer,pageTitle:document.title});const o=globalThis.UserLeap._config.pageUrlEvents;let l=!1;if(o&&o.length)for(let u=0;ufunction(...s){const i=r.apply(this,s),a=new Event("pushState");return globalThis.dispatchEvent(a),Ee(a),i})(e.pushState)),"replaceState"in e&&(e.replaceState=(r=>function(...s){const i=r.apply(this,s),a=new Event("replaceState");return globalThis.dispatchEvent(a),Ee(a),i})(e.replaceState)),jn()}async function vt(e,t){const r=nt();e&&!t&&(globalThis.UserLeap._config.mode=Nn.test);const n=B(globalThis.UserLeap),s=Pe(n),i=await j($n({desktopDisplay:globalThis.UserLeap._config.desktopDisplay,isMobile:s,previewLanguage:globalThis.UserLeap._config.previewLanguage,surveyid:e==null?void 0:e.surveyId,surveytemplateid:e==null?void 0:e.surveyTemplateId,vid:r}),{shouldDropOnRateLimit:!0});if(!i.ok)return i.reportError&&i.error&&(console.warn("[Sprig] (ERR-414) Failed to request questions from the server",i.error),globalThis.UserLeap.reportError("getQuestions",i.error)),{success:!1,surveyState:"no survey"};if(i.json.delay&&await Ce(i.json.delay),i.json.isFeedback){const{feedbackLabel:a,productConfig:o,surveyUuid:l,feedbackCustomStyles:d}=i.json,{buttonTheme:u,placement:c,desktopDisplay:m}=o,f={customStyles:d,buttonTheme:u,desktopDisplay:m,eventId:0,feedbackLabel:a,placement:c,surveyUuid:l,surveyId:e==null?void 0:e.surveyId};Sr(f,i.json)}else return be(i.json,Ue,bt)}function Kn(e){let t=e.length;for(;t;){const r=Math.floor(Math.random()*t);t-=1;const n=e[t];e[t]=e[r],e[r]=n}}function Gn(e){if(!e)return;globalThis.UserLeap._config=e,e.mute&&globalThis.UserLeap._queue.pause();const{interactiveEvents:t,pageUrlEvents:r,dismissOnPageChange:n}=e;t&&Kn(t),(t||r||n)&&(zn(),Ee())}async function Yn(e,t){var n,s;let r=!0;return t&&((n=e==null?void 0:e.json)!=null&&n.surveyId)&&(globalThis.UserLeap.delayingSurvey=!0,r=await t(e.json.surveyId),globalThis.UserLeap.delayingSurvey=!1,!r)?!1:((s=e==null?void 0:e.json)!=null&&s.delay&&!globalThis.UserLeap.isMobileSDK&&(globalThis.UserLeap.delayingSurvey=!0,await Ce(e.json.delay),globalThis.UserLeap.delayingSurvey=!1),r)}const Jn=function(e){if(!globalThis.UserLeap)return;const t=async(s={})=>{var T,M,C,ae,O;const{userId:i,anonymousId:a,metadata:o={},properties:l,showSurveyCallback:d}=s;let{eventName:u}=s;if(globalThis.UserLeap.debugMode&&u!==Cr&&console.info("[DEBUG] Sprig track",s),e.mode==="test")return;const c=w.getItem("sprig.previewKey")??void 0;if(e.requireUserIdForTracking&&!globalThis.UserLeap.userId&&!i){const _="[Sprig] - Skipping tracking without userId";return console.warn(_),{success:!1,message:_,surveyState:"no survey"}}if(!u||u.trim().length===0){u=u?String(u):"";const _="[Sprig] - Invalid event name "+u;return console.warn(_),{success:!1,message:_,surveyState:"no survey"}}const m=Ue??globalThis.location.href;if(o.url||(o.url=m),A("trackStartUrl",m),(M=(T=globalThis.UserLeap)==null?void 0:T._config)!=null&&M.optimizelyEnabled){const _=B(globalThis.UserLeap);we(_)||Fe.getAndSetWebOptimizelyExperiments(),o.optimizelyExperiments=Object.assign({},Fe.getAllOptimizelyExperiments())}(ae=(C=globalThis.UserLeap)==null?void 0:C._config)!=null&&ae.launchDarklyEnabled&&(o.launchDarklyFlags=gt.getAllLaunchDarklyVariations()),i&&(globalThis.UserLeap.userId=i),a&&(globalThis.UserLeap.partnerAnonymousId=a),l&&(o.eventProperties=l),(O=L.replay)==null||O.RecordEvent({name:u,url:o.url}),p.info("TrackEvent",{eventName:u});const f=globalThis.UserLeap.delayingSurvey||yr()?await j(F("1",[ee],"events/batch"),{body:JSON.stringify({events:[{event:u,metadata:o}],previewKey:c}),method:"POST",shouldDropOnRateLimit:!0}):await j(F("1",[ee],"events"),{body:JSON.stringify({event:u,metadata:o,previewKey:c}),method:"POST",shouldDropOnRateLimit:!0});if(!f.ok){const _="[Sprig] (ERR-421) Failed to track event";return f.reportError&&(console.warn(_,f.error),f.error&&globalThis.UserLeap.reportError("track",f.error)),{success:!1,message:_,error:f.error,surveyState:"no survey"}}i&&A("uid",i),a&&A("aid",a);const y=f.json;y.invalidPreviewKey&&w.removeItem("sprig.previewKey");const b=o.trackPageView?o.url:void 0;return!!(y!=null&&y.feedbackButton)&&Sr(y.feedbackButton,void 0,b),await Yn(f,d)?Vn(m)?be(y,b,bt):{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"}},r=(s,i)=>{var o;const a=(o=s==null?void 0:s.querySelector(`[id="${at}"]`))==null?void 0:o.contentDocument;a&&Oe({document:a,elementId:"ul-custom-style",styleString:i})},n={async displaySurvey(s){return console.warn("[Sprig] displaySurvey should only be used to debug your studies; not intended for production usage."),globalThis.UserLeap("dismissActiveSurvey",W.Override),vt({surveyId:s},!0)},_previewSurvey(s){globalThis.UserLeap("dismissActiveSurvey",W.Override),vt({surveyTemplateId:s},!1)},_reviewSurvey(s){globalThis.UserLeap("dismissActiveSurvey",W.Override),vt({surveyId:s},!1)},previewSurvey(s){n._previewSurvey(s)},reviewSurvey(s){n._reviewSurvey(s)},mute(){globalThis.UserLeap._queue.pause()},unmute(){globalThis.UserLeap._queue.unpause()},setVisitorToken(){console.warn("[Sprig] setVisitorToken is deprecated.")},dismissActiveSurvey(s=W.API){globalThis.UserLeap.container&&(s===W.Closed&&globalThis.Sprig.trackHistory&&globalThis.Sprig.trackHistory({event:"closed"}),h.emit(g.SurveyCloseRequested,{name:g.SurveyCloseRequested,initiator:s,"survey.id":parseInt(globalThis.UserLeap.container.dataset.studyId)}),h.emit(g.SurveyWillClose,{name:g.SurveyWillClose,initiator:s,"survey.id":parseInt(globalThis.UserLeap.container.dataset.studyId)}))},async setAttribute(s,i){if(!s||!i&&i!==0&&i!==!1){const a="[Sprig] - Disregarding empty attribute / value provided";return console.warn(a),{success:!1,message:a}}return this.setAttributes({[s]:i})},async setAttributes(s){if(s==null||Object.keys(s).length===0){const i="[Sprig] - Disregarding empty attributes provided";return console.warn(i),{success:!1,message:i}}return this.identifyAndSetAttributes({attributes:s})},async identifyAndSetAttributes(s){if(globalThis.UserLeap.debugMode&&console.info("[DEBUG] Sprig identifyAndSetAttributes",s),e.mode==="test")return;if(s===null||typeof s!="object"||!(s.userId||s.anonymousId||s.attributes)){const u="[Sprig] - Disregarding empty payload provided";return console.warn(u),{success:!1,message:u}}const{userId:i,anonymousId:a,attributes:o}=s;if(e.requireUserIdForTracking&&!globalThis.UserLeap.userId&&!i){const u="[Sprig] - Skipping tracking without userId";return console.warn(u),{success:!1,message:u}}if(o){o.email&&!o[Ie]&&(o[Ie]=o.email,delete o.email);const u=Object.keys(o);for(const c of u)o[c]===qe[c]&&delete o[c]}if((!o||Object.keys(o).length===0)&&(!i||globalThis.UserLeap.userId===i)&&(!a||globalThis.UserLeap.partnerAnonymousId===a))return{success:!0};const l={};i&&(l.userId=globalThis.UserLeap.userId=i),a&&(l.partnerAnonymousId=globalThis.UserLeap.partnerAnonymousId=a);let d;return o&&Object.keys(o).length>0?(d=await j(F("1",[te,ee],"attributes"),{body:JSON.stringify(o),method:"PUT"}),d.ok?Object.assign(qe,o):d.reportError&&(console.warn("[Sprig] (ERR-432) identifyAndSetAttributes failed",d.error),d.error&&globalThis.UserLeap.reportError("identifyAndSetAttributes",d.error))):d=await j(F("1",[te,ee]),{body:JSON.stringify(l),method:"PUT"}),o&&o[Ie]&&(globalThis.UserLeap.email=o[Ie]),d.ok&&(i&&A("uid",i),a&&A("aid",a)),{success:!!d.ok}},async removeAttributes(s){if(globalThis.UserLeap.debugMode&&console.info("[DEBUG] Sprig removeAttributes",s),e.mode==="test")return;if(s==null||s.length===0){const a="[Sprig] - Disregarding empty attributes provided";return console.warn(a),{success:!1,message:a}}if(e.requireUserIdForTracking&&!globalThis.UserLeap.userId){const a="[Sprig] - Skipping tracking without userId";return console.warn(a),{success:!1,message:a}}const i=await j(F("1",[te,ee],"attributes"),{body:JSON.stringify({delete:s}),method:"DELETE"});return!i.ok&&i.reportError&&(console.warn("[Sprig] (ERR-433) Remove attributes failed",i.error),i.error&&globalThis.UserLeap.reportError("removeAttributes",i.error)),{success:!!i.ok}},async addSurveyListener(s){h.on(g.SurveyLifeCycle,s)},async removeSurveyListener(s){h.removeListener(g.SurveyLifeCycle,s)},async addListener(s,i){h.on(s,i)},async removeListener(s,i){h.removeListener(s,i)},async removeAllListeners(){h.removeAllListeners()},setPreviewKey(s){!s||typeof s!="string"||w.isStorageAvailable&&s&&w.setItem("sprig.previewKey",s)},async setUserId(s){var o;if(globalThis.UserLeap.debugMode&&console.info("[DEBUG] Sprig setUserId",s),s==null){const l=`[Sprig] - Invalid userId ${s}`;return console.warn(l),{success:!1,message:l}}if(e.mode==="test"||s===globalThis.UserLeap.userId)return;globalThis.UserLeap.userId=s;const i=globalThis.UserLeap.visitorId,a=await j(F("1",[te,ee]),{body:JSON.stringify({userId:s}),method:"PUT"});if(!a.ok){a.reportError&&(console.warn("[Sprig] (ERR-420) Failed to set user id",a.error),a.error&&globalThis.UserLeap.reportError("setUserId",a.error));return}i!==globalThis.UserLeap.visitorId&&((o=L.replay)==null||o.clearUserReplayData()),A("uid",s)},async setPartnerAnonymousId(s){if(globalThis.UserLeap.debugMode&&console.info("[DEBUG] Sprig setPartnerAnonymousId",s),s==null){const i=`[Sprig] - Invalid partnerAnonymousId ${s}`;return console.warn(i),{success:!1,message:i}}return globalThis.UserLeap.partnerAnonymousId=s,A("aid",s),{success:!0}},async track(s,i,a={},o=void 0){return t({eventName:s,properties:i,metadata:a,showSurveyCallback:o})},async identifyAndTrack(s){return await t(s)},trackPageView(s,i=void 0,a=void 0,o=!0){Ue=s,Mr(s,i,a,o)},applyFeedbackStyles({button:s="",view:i=""}){globalThis.UserLeap.feedbackCustomStyles=i,document.getElementById("sprig-feedback-style")&&Oe({document,elementId:"ul-custom-style",styleString:s,nonce:globalThis.UserLeap.styleNonce}),r(document.querySelector(".ul-container-feedback"),i)},applyStyles(s){globalThis.UserLeap.customStyles=s,r(globalThis.UserLeap.container,s)},setWindowDimensions(s,i){var m,f;const a=typeof s=="string"?parseInt(s,10):s,o=typeof i=="string"?parseInt(i,10):i;!isNaN(a)&&!isNaN(o)&&(globalThis.UserLeap.windowDimensions={width:a,height:o});const l=B(globalThis.UserLeap),d=Pe(l),u=l["userleap-platform"]==="web";if(!globalThis.UserLeap.frameId)return;const c=document.getElementById(globalThis.UserLeap.frameId);c&&(globalThis.UserLeap.useMobileStyling&&((m=globalThis.UserLeap.windowDimensions)!=null&&m.width&&(c.style.width=`${globalThis.UserLeap.windowDimensions.width}px`),(f=globalThis.UserLeap.windowDimensions)!=null&&f.height&&(c.style.maxHeight=`${globalThis.UserLeap.windowDimensions.height-20}px`),c.contentDocument&&(c.style.height=String(un(c.contentDocument,u&&!d,Zt(l))[0])+"px")),h.emit(g.SurveyDimensions,{name:g.SurveyDimensions,contentFrameWidth:c.clientWidth,contentFrameHeight:c.clientHeight,"survey.id":parseInt(globalThis.UserLeap.container.dataset.studyId)}))},logoutUser(){var s;globalThis.UserLeap.debugMode&&console.info("[DEBUG] Sprig logout"),p.info("LogOut",{vid:globalThis.UserLeap.visitorId,userId:globalThis.UserLeap.userId}),globalThis.UserLeap.visitorId=null,globalThis.UserLeap.userId=null,globalThis.UserLeap.partnerAnonymousId=null,globalThis.UserLeap.token=null,globalThis.UserLeap.email=null,Z.removeItem("userleap.ids"),globalThis.UserLeap._queue.isPaused()&&globalThis.UserLeap._queue.empty(),Or(),(s=L.replay)==null||s.clearUserReplayData(),globalThis.UserLeap._queue.unpause()},teardown(){qn(),globalThis.UserLeap("dismissActiveSurvey",W.API),delete globalThis.UserLeap,delete globalThis.Sprig,delete globalThis._Sprig},integrateOptimizely(s,i=!0){var a,o;if(!((o=(a=globalThis.UserLeap)==null?void 0:a._config)!=null&&o.optimizelyEnabled)){console.warn("[SPRIG] Optimizely integration is currently not enabled for your product.");return}try{const l=typeof s=="string"?JSON.parse(s):s;Fe.setOptimizelyExperiment(l,i)}catch(l){console.warn("[Sprig] Error with integrating Optimizely data"),l instanceof Error&&globalThis.UserLeap.reportError("integrateOptimizely",l)}},integrateOptimizelyClient(s){var a,o;if(!((o=(a=globalThis.UserLeap)==null?void 0:a._config)!=null&&o.optimizelyEnabled)){console.warn("[SPRIG] Optimizely integration is currently not enabled for your product.");return}const i=({experiment:l,variation:d})=>{const u={experiments:[{id:l.id,variation:d.key}]};globalThis.UserLeap("integrateOptimizely",u,!1)};s.notificationCenter.addNotificationListener("ACTIVATE:experiment, user_id,attributes, variation, event",i)},importLaunchDarklyData(s){var i,a;if(!((a=(i=globalThis.UserLeap)==null?void 0:i._config)!=null&&a.launchDarklyEnabled)){console.warn("[SPRIG] LaunchDarkly integration is currently not enabled for your product.");return}gt.setLDFlagsVariations(s)},setVisitorAttribute(s,i){return console.warn("[Sprig] setVisitorAttribute is deprecated. Please use setAttribute"),n.setAttribute(s,i)},async setEmail(s){return n.setAttribute(Ie,s)},async setVisitorEmail(s){return console.warn("[Sprig] setVisitorEmail is deprecated. Please use setEmail"),n.setEmail(s)},async _generateVideoUploadUrl(s){return Zn(s)},_reportMetric(s,i){Ur(s,i)},async _completeSessionReplay({surveyId:s,responseGroupUuid:i,eventDigest:a}){var o;return L.replay?(o=L.replay)==null?void 0:o._completeSessionReplay({surveyId:s,responseGroupUuid:i,eventDigest:a,headers:B(globalThis.UserLeap)}):(globalThis.UserLeap.reportError("_completeSessionReplay",new Error("Replay module not registered")),!1)},pauseReplayRecording(){var s,i,a,o;(i=(s=L.replay)==null?void 0:s.isReplayPaused)!=null&&i.call(s)||(o=(a=L.replay)==null?void 0:a.recordReplayPaused)==null||o.call(a)},resumeReplayRecording(){var s,i,a,o,l,d;(i=(s=L.replay)==null?void 0:s.isReplayPaused)!=null&&i.call(s)&&((o=(a=L.replay)==null?void 0:a.recordReplayResumed)==null||o.call(a),(d=(l=L.replay)==null?void 0:l.recordFullSnapshot)==null||d.call(l))}};Object.assign(globalThis.UserLeap,n)};async function Qn(e){var i,a;const t=B(globalThis.UserLeap);document.addEventListener("securitypolicyviolation",nr);const r=await Y(F("1",[te],"config"),{headers:t});if(document.removeEventListener("securitypolicyviolation",nr),!r.ok)return(i=globalThis.SprigLoggerCallback)==null||i.call(globalThis,"Sprig config fetch failed"),r.reportError&&(console.warn("[Sprig] (ERR-422) Failed to load configuration",r.error),r.error&&globalThis.UserLeap.reportError("applyRemoteConfig",r.error)),st("Disabled: failed to fetch configuration"),e;const n=r.json;return n!=null&&n.disabled?((a=globalThis.SprigLoggerCallback)==null||a.call(globalThis,"Sprig config fetch disabled"),st(`Disabled: ${n.disabled}`),{disabled:n.disabled}):Object.assign({},n,e)}async function Xn(e,t,r={},n={}){var c;const s=(c=globalThis.__cfg)==null?void 0:c.mode,i=nt(),a=globalThis.UserLeap.envId,o=globalThis.document.documentElement,l={mode:s,screenWidth:globalThis.screen.width,screenHeight:globalThis.screen.height,clientWidth:o.clientWidth,clientHeight:o.clientHeight,location:Ue??globalThis.location.href,language:globalThis.navigator.language,...r},d={action:e,breadcrumbs:p.breadcrumbs,err:{message:`${t==null?void 0:t.name} - ${t==null?void 0:t.message}`,stack:t==null?void 0:t.stack},meta:l,vid:i,envId:a,...n};(await j(F("1",null,"errors"),{method:"POST",headers:{"x-ul-error":globalThis.btoa(`userleap-${Date.now()}-error`)},body:JSON.stringify(d),shouldDropOnRateLimit:!0})).ok||console.warn("[Sprig] (ERR-444) Failed to report error to API",t)}async function Zn(e){var r;if(!e)return;const t=`${globalThis.UserLeap._API_URL}/2/environments/integrations/upload`;try{const n=await fetch(t,{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(n.ok){const s=await n.json();return(r=s==null?void 0:s.upload)==null?void 0:r.url}else return null}catch(n){console.warn("[Sprig] Error with generating video upload url"),n instanceof Error&&globalThis.UserLeap.reportError("generateVideoUploadUrl",n)}}function ei(e={}){var n;(n=globalThis.SprigLoggerCallback)==null||n.call(globalThis,"Initializing Sprig");const t=new URLSearchParams(globalThis.location.search).get("sprigPreviewKey")??"";globalThis.UserLeap.UPDATES=De,globalThis.UserLeap("setPreviewKey",t);async function r(){var m,f,y,b,N;if(globalThis.UserLeap.loaded)return;if((m=globalThis.SprigLoggerCallback)==null||m.call(globalThis,"Loading Sprig"),globalThis.UserLeap.reportError=Xn,globalThis.UserLeap.loaded=!0,globalThis.UserLeap._config=Object.assign({},e,globalThis.UserLeap.config),globalThis.UserLeap.delayingSurvey=!1,globalThis.UserLeap._config&&typeof globalThis.UserLeap._config=="object")for(const k in globalThis.UserLeap._config)globalThis.UserLeap[k]=globalThis.UserLeap._config[k];if(globalThis.Sprig.outstandingTransactionLimit!==void 0&&(e.outstandingTransactionLimit=globalThis.Sprig.outstandingTransactionLimit),!globalThis.UserLeap.envId)if(globalThis.UserLeap.appId)globalThis.UserLeap.envId=globalThis.UserLeap.appId;else throw new Error("Missing Environment id");globalThis.UserLeap.debugMode&&console.info("[DEBUG] Sprig debug mode enabled");const s=Pr(),i=globalThis.UserLeap.sampleRate;let a=s.sampled;if(i){if(a===null&&(a=Math.random(){var T;await j(F("1",[te],"metrics"),{body:k,method:"POST",headers:{"x-ul-replay-enabled":`${!!((T=L.replay)!=null&&T.isReplayRecording())}`},shouldDropOnRateLimit:!0})}}),!u){const k=c.alwaysOnReplay?{userAgent:globalThis.navigator.userAgent,surveyId:c.alwaysOnReplay.surveyId,responseGroupUuid:c.alwaysOnReplay.responseGroupUuid,sdkVersion:"2.48.0",maxDurationSeconds:c.alwaysOnReplay.maxDurationSeconds}:void 0;await((b=L.replay)==null?void 0:b.initializeReplay({maxReplayDurationSeconds:c.maxReplayDurationSeconds,maxInflightRequests:globalThis.UserLeap.maxInflightReplayRequests??2,replaySettings:c.replaySettings,apiUrl:globalThis.UserLeap._API_URL,alwaysOnConfig:k})),bt=c.replaySettings}Jn(c),await Gn(c),globalThis.UserLeap._queue.unpause(),(N=globalThis.SprigLoggerCallback)==null||N.call(globalThis,"SdkReady"),h.emit(g.SDKReady,{mobileMetricsReportingEnabled:!!c.mobileMetricsReportingEnabled,metricsReportingInterval:c.metricsReportingIntervalSeconds||0,metricsThresholds:c.metricThresholds||[],maxMobileReplayDurationSeconds:c.maxMobileReplayDurationSeconds,mobileReplaySettings:c.mobileReplaySettings}),h.emit(g.VisitorIDUpdated,{visitorId:globalThis.UserLeap.visitorId}),h.on(g.VisitorIDUpdated,()=>{for(const k in qe)delete qe[k]})}document.readyState==="complete"?r():globalThis.attachEvent?globalThis.attachEvent("onload",r):globalThis.addEventListener("load",()=>{r()},!1)}var se=(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))(se||{}),J=(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(J||{});const Lt=(e,t)=>t.some(r=>e instanceof r);let Br,Fr;function ti(){return Br||(Br=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function ri(){return Fr||(Fr=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const St=new WeakMap,Tt=new WeakMap,$e=new WeakMap;function si(e){const t=new Promise((r,n)=>{const s=()=>{r(ne(e.result))},i=()=>{n(e.error)};e.onsuccess=s,e.onerror=i});return $e.set(t,e),t}function ni(e){if(St.has(e))return;const t=new Promise((r,n)=>{const s=()=>{r()},i=()=>{n(e.error||new DOMException("AbortError","AbortError"))};e.oncomplete=s,e.onerror=i,e.onabort=i});St.set(e,t)}let Ut={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return St.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return ne(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function Nr(e){Ut=e(Ut)}function ii(e){return ri().includes(e)?function(...t){return e.apply(It(this),t),ne(this.request)}:function(...t){return ne(e.apply(It(this),t))}}function ai(e){return typeof e=="function"?ii(e):(e instanceof IDBTransaction&&ni(e),Lt(e,ti())?new Proxy(e,Ut):e)}function ne(e){if(e instanceof IDBRequest)return si(e);if(Tt.has(e))return Tt.get(e);const t=ai(e);return t!==e&&(Tt.set(e,t),$e.set(t,e)),t}const It=e=>$e.get(e);function oi(e,t,{blocked:r,upgrade:n,blocking:s,terminated:i}={}){const a=indexedDB.open(e,t),o=ne(a);return n&&(a.onupgradeneeded=l=>{n(ne(a.result),l.oldVersion,l.newVersion,ne(a.transaction),l)}),r&&(a.onblocked=l=>r(l.oldVersion,l.newVersion,l)),o.then(l=>{i&&(l.onclose=()=>i()),s&&(l.onversionchange=d=>s(d.oldVersion,d.newVersion,d))}).catch(()=>{}),o}function Et(e,{blocked:t}={}){const r=indexedDB.deleteDatabase(e);return t&&(r.onblocked=n=>t(n.oldVersion,n)),ne(r).then(()=>{})}const li=["get","getKey","getAll","getAllKeys","count"],ci=["put","add","delete","clear"],kt=new Map;function Hr(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(kt.get(t))return kt.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,s=ci.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(s||li.includes(r)))return;const i=async function(a,...o){const l=this.transaction(a,s?"readwrite":"readonly");let d=l.store;return n&&(d=d.index(o.shift())),(await Promise.all([d[r](...o),s&&l.done]))[0]};return kt.set(t,i),i}Nr(e=>({...e,get:(t,r,n)=>Hr(t,r)||e.get(t,r,n),has:(t,r)=>!!Hr(t,r)||e.has(t,r)}));const di=["continue","continuePrimaryKey","advance"],Vr={},Rt=new WeakMap,Wr=new WeakMap,ui={get(e,t){if(!di.includes(t))return e[t];let r=Vr[t];return r||(r=Vr[t]=function(...n){Rt.set(this,Wr.get(this)[t](...n))}),r}};async function*pi(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;const r=new Proxy(t,ui);for(Wr.set(r,t),$e.set(r,It(t));t;)yield r,t=await(Rt.get(r)||t.continue()),Rt.delete(r)}function jr(e,t){return t===Symbol.asyncIterator&&Lt(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&Lt(e,[IDBIndex,IDBObjectStore])}Nr(e=>({...e,get(t,r,n){return jr(t,r)?pi:e.get(t,r,n)},has(t,r){return jr(t,r)||e.has(t,r)}}));const ze={Loaded:"sprigReplayIframeLoaded",Settings:"sprigReplayIframeSettings",Snapshot:"sprigReplayIframeTakeFullSnapshot",Teardown:"sprigReplayTeardown"},_t=[],gi=(e,t)=>{window.addEventListener("message",r=>{var n;r.data.type===ze.Loaded&&(_t.push({source:r.source,origin:r.origin}),(n=r.source)==null||n.postMessage({type:ze.Settings,settings:e,replayLibraryUrl:t},{targetOrigin:r.origin}))})},hi=()=>{_t.forEach(e=>{var t;(t=e.source)==null||t.postMessage({type:ze.Snapshot},{targetOrigin:e.origin})})},fi=()=>{_t.forEach(e=>{var t;(t=e.source)==null||t.postMessage({type:ze.Teardown},{targetOrigin:e.origin})})};class mi{constructor(t){E(this,"awaitingResolvers",[]);E(this,"activeCount",0);this.capacity=t}async acquire(){if(this.activeCount{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 qr=new mi(2),yi=e=>qr.setLimit(e),bi=async e=>qr.execute(async()=>{var n;p.info("UploadChunkStart",{chunkIndex:e.chunkIndex,surveyId:e.surveyId});const t=await Y(e.uploadUrl,{body:e.data,method:"PUT"});p.http("UploadChunkEnd",{url:e.uploadUrl,method:"PUT",status_code:t.status,reason:t.statusText??"OK",chunkIndex:e.chunkIndex,surveyId:e.surveyId});const r=(n=t.headers)==null?void 0:n.get("ETag");if(!r)throw new Error(`Upload response did not include etag for upload ${e.uploadId}, part ${e.chunkIndex}`);return r}),$r=async({apiUrl:e,surveyId:t,uploadId:r,etags:n,headers:s,responseGroupUuid:i,replayDuration:a,eventDigest:o},l=!1)=>{var u;if(!l&&!r&&!n){p.error("UploadErr",{isMobile:l,uploadId:r,etags:n});return}p.info("MarkUploadComplete",{surveyId:t});const d=await Y(`${e}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:n,uploadId:r,responseGroupUuid:i,surveyId:t,replayDuration:a,eventDigest:o,userAgent:(u=window==null?void 0:window.navigator)==null?void 0:u.userAgent}),headers:s,shouldRetryRequest:!0});return p.info("MarkUploadDone",{surveyId:t}),d},wi=e=>{if(e instanceof Attr)return null;let t=1;for(let r=e.previousSibling;r;r=r.previousSibling)r.nodeName===e.nodeName&&++t;return t},zr=e=>{if(e===null)return"";const t=[];if(e instanceof Document)return"/";for(let r=e;r&&!(r instanceof Document)&&r!==null;r=r instanceof Attr?r.ownerElement:r.parentElement){const n=t[t.length]={name:void 0,position:null};switch(r.nodeType){case Node.TEXT_NODE:n.name="text()";break;case Node.ATTRIBUTE_NODE:n.name="@"+r.nodeName;break;case Node.PROCESSING_INSTRUCTION_NODE:n.name="processing-instruction()";break;case Node.COMMENT_NODE:n.name="comment()";break;case Node.ELEMENT_NODE:n.name=r.nodeName;break}n.position=wi(r)}return"/"+t.reverse().map(r=>r.position!==null?`/${r.name}[${r.position}]`:`/${r.name}`).join("")},Dt=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),vi=(e,t)=>{let r;return n=>{clearTimeout(r),r=window.setTimeout(()=>e(n),t)}},z={capture:!0,passive:!0},Li=["a","button","input","option","li","link"],Si=["Escape","Enter","Backspace","F5","Tab"];let Ke=!1,x=null,Ge=null;const Ti=e=>{e.currentPageTitle&&(e.currentPageTitle=Dt(e.currentPageTitle)),x==null||x("Sprig_BackForward",e)},Ui=e=>{var t;(t=e==null?void 0:e.elementAttributes)!=null&&t.text&&(e.elementAttributes.text=Dt(e.elementAttributes.text)),x==null||x("Sprig_Click",e)},Ii=e=>{x==null||x("Sprig_Refresh",e)},Ei=e=>{x==null||x("Sprig_Keystroke",e)},ki=e=>{if(!e.tagName)return"No tagName";const t=e.getAttribute("type");return t?`${t} ${e.tagName.toLowerCase()}`:e.tagName.toLowerCase()},Kr=e=>{var r;if(((r=e.tagName)==null?void 0:r.toLowerCase())==="html")return{element:"html"};const t={};return t.element=ki(e),t},Ri=e=>{var s;if(!e)return{};const r={...Kr(e)},n=e.parentElement;if(n&&Li.includes((s=n.tagName)==null?void 0:s.toLowerCase())){const i=Kr(n);Object.assign(r,i)}return r},Gr=(e,t)=>{var n;let r=t.target;t.target===((n=window.document)==null?void 0:n.body)&&window.Sprig.pointerDownTarget&&(r=window.Sprig.pointerDownTarget),Ui({x:t.x,y:t.y,type:e,elementAttributes:Ri(r),windowHeight:window.innerHeight,windowWidth:window.innerWidth,...r instanceof HTMLElement||r instanceof SVGElement||r instanceof MathMLElement?{rect:r==null?void 0:r.getBoundingClientRect(),xPath:zr(r)}:{}})},_i=e=>t=>Gr(e,t),Yr=e=>{Si.includes(e.key)&&Ei({key:e.key})},Di=()=>{window.performance.getEntriesByType("navigation").map(t=>t.type).includes("reload")&&Ii({url:window.location.href,currentPageTitle:document.title})},Ci=()=>{window.performance.getEntriesByType("navigation").map(t=>t.type).includes("back_forward")&&Ti({curUrl:window.location.href,fromUrl:document.referrer,currentPageTitle:document.title})},Jr=vi(e=>{if(!(e.target instanceof HTMLElement||e.target instanceof Document))return;let t=e.target;"scrollTop"in t||(t=t.documentElement),Ge==null||Ge({xPath:zr(t),x:t.scrollLeft,y:t.scrollTop,elementAttributes:{targetScrollWidth:t.scrollWidth,targetClientWidth:t.clientWidth,targetScrollHeight:t.scrollHeight,targetClientHeight:t.clientHeight}})},750),Qr=_i("left_click"),Xr=e=>{e.button===2&&Gr("right_click",e)},Zr=e=>{window.Sprig&&(window.Sprig.pointerDownTarget=e.target)},Ai=(e,t)=>{Ke||(x=e,Ge=t,window.addEventListener("click",Qr,z),window.addEventListener("pointerdown",Zr,z),window.addEventListener("mousedown",Xr,z),window.addEventListener("keydown",Yr,z),window.addEventListener("scroll",Jr,z),Ke=!0,Di(),Ci())},xi=()=>{Ke&&(window.removeEventListener("click",Qr,z),window.removeEventListener("pointerdown",Zr,z),window.removeEventListener("mousedown",Xr,z),window.removeEventListener("keydown",Yr,z),window.removeEventListener("scroll",Jr,z),Ke=!1)},Pi=3e4,U={isRecording:!1,scrollEventUuids:{},stopRecording:()=>{}},es=()=>globalThis.indexedDB&&globalThis.IDBKeyRange&&globalThis.CompressionStream,Oi=.5,Mi=async()=>{var e;if(!es())return!0;if((e=globalThis.navigator.storage)!=null&&e.estimate)try{const{quota:t=0,usage:r=0}=await globalThis.navigator.storage.estimate(),n=(t-r)/1024**3;return p.info("Storage",{availableGb:n}),n{const e=w.getItem("sprig.sessionId");if(e)return p.info("SessionIDFound",{savedSessionId:e}),w.removeItem("sprig.sessionId"),e;const t=pe();return p.info("GeneratedSessionID",{uuid:t}),t})(),Ct=()=>{w.setItem("sprig.disableReplayRecording","disabled")},K=()=>!!w.getItem("sprig.disableReplayRecording"),Bi=()=>{w.setItem("sprig.isReplayPaused","true")},Fi=()=>{w.removeItem("sprig.isReplayPaused")},Ye=()=>!!w.getItem("sprig.isReplayPaused");(Ts=globalThis.addEventListener)==null||Ts.call(globalThis,"beforeunload",()=>{p.info("BeforeUnload",{sessionId:D}),w.setItem("sprig.sessionId",D)});const Ni=()=>K()?p.debug("ReplayDisabled-PendingHeatmaps"):P(async()=>{const t=(await S.getPendingCaptures({isHeatmap:!0})).map(r=>({eventId:r.captureParams.eventId,uuid:r.uuid})).filter(({eventId:r})=>!gr(r)).map(({uuid:r})=>r);return p.info("PendingHeatmapsToComplete",{count:t.length}),t.length&&(await S.markPendingHeatmapsReady(t),p.info("MarkedPendingHeatmapsReady")),t.length},"Error marking pending heatmaps ready"),Hi=e=>{Date.now()-e>=Pi&&P(()=>S.markPendingHeatmapsReady(),"Error in heatmap inactivity")},Q=(e,t)=>{var r,n;if(!(K()||!U.isRecording||Ye()))try{(n=(r=globalThis.rrwebRecord)==null?void 0:r.addCustomEvent)==null||n.call(r,e,t)}catch(s){ke("Error recording custom event",s)}},Vi=e=>{e.description&&(e.description=Dt(e.description)),Q("Sprig_PageView",e)},Wi=e=>{Q("Sprig_TrackEvent",e)},ji=e=>{Q("Sprig_ShowSurvey",e)},qi=e=>{Q("Sprig_SubmitSurvey",e)},$i=async e=>{const{x:t,xPath:r,y:n}=e,s=U.scrollEventUuids[r];if(s)return P(async()=>{var o,l,d,u;const i=await S.openDB(),a=await i.get("events",s);if(a!=null&&a.event){const c=JSON.parse(a.event),m=t>((l=(o=c.data)==null?void 0:o.payload)==null?void 0:l.x),f=n>((u=(d=c.data)==null?void 0:d.payload)==null?void 0:u.y);if(!(m||f))return null;m&&(c.data.payload.x=t),f&&(c.data.payload.y=n),c.data.payload.elementAttributes=e.elementAttributes,a.event=JSON.stringify(c),await i.put("events",a)}else Q("Sprig_Scroll",e)},"Error updating scroll event");Q("Sprig_Scroll",e)},zi=()=>{Q("Sprig_ReplayPaused",{timestamp:Date.now()}),Bi()},Ki=()=>{Fi(),Q("Sprig_ReplayResumed",{timestamp:Date.now()})},Gi=()=>U.isRecording,ts=()=>{U.stopRecording&&(U.stopRecording(),U.stopRecording=void 0),U.isRecording=!1,["cleanupInterval","inactivityInterval","pendingCheckInterval"].forEach(e=>{U[e]&&(clearInterval(U[e]),U[e]=void 0)}),xi(),fi()},Yi=["did not allow mutations","called in an invalid security context"],Ji=e=>{if(!e)return!0;for(const t of Yi)if(e.toLowerCase().includes(t))return!1;return!0},Qi=(e,t,{reportError:r=!0,extraInfo:n={}})=>{if(!(K()||!(t instanceof Error))){if(Ct(),t.name==="VersionError"){p.error("VersionErr",{message:e}),S.deleteDB();return}Ji(t==null?void 0:t.message)&&(r&&globalThis.UserLeap.reportError(e,t,n),S.clearAll())}},ke=(e,t,{reportError:r}={reportError:!0})=>{ts(),p.error("ReplayErr",{code:t.code,name:t.name}),Qi(e,t,{reportError:r})},P=async(e,t)=>{try{return await e()}catch(r){ke(t,r)}},At=()=>{U.isRecording&&(P(()=>{var e,t;return(t=(e=globalThis.rrwebRecord)==null?void 0:e.takeFullSnapshot)==null?void 0:t.call(e,!0)},"Error recording full snapshot"),hi())},Xi=async({surveyId:e,responseGroupUuid:t,eventDigest:r,headers:n})=>{if(!e||!t)return!1;const s=globalThis.UserLeap._API_URL,i=await $r({surveyId:e,responseGroupUuid:t,eventDigest:r,apiUrl:s,headers:n},!0);return!(i!=null&&i.error)},rs=30,Zi=1;let xt=0;(async()=>{es()&&Promise.allSettled([Et("replayStorage"),Et("sprig.replay")])})();class ea{constructor(){E(this,"wrapTransactionWithCounter",t=>{var s,i;const r=(i=(s=window.Sprig)==null?void 0:s._config)==null?void 0:i.outstandingTransactionLimit,n=r===void 0?100:r;if(n&&xt>n){const a="Too many outstanding transactions";ke(a,new Error(a),{reportError:!1})}xt++,t.done.finally(()=>{xt--})});E(this,"getTransaction",async t=>{const n=(await this.openDB()).transaction(t,"readwrite");return this.wrapTransactionWithCounter(n),n})}openDB(){return oi("sprigReplay",Zi,{upgrade:(t,r,n)=>{if(n===0&&w.setItem("sprig.pendingCount","0"),!t.objectStoreNames.contains("events")){const s=t.createObjectStore("events",{keyPath:"uuid"});s.createIndex("sessionId","sessionId"),s.createIndex("timestamp","timestamp"),s.createIndex("[sessionId+timestamp]",["sessionId","timestamp"])}if(!t.objectStoreNames.contains("chunkUploads")){const s=t.createObjectStore("chunkUploads",{keyPath:"uuid"});s.createIndex("sessionId","sessionId"),s.createIndex("timestamp","timestamp"),s.createIndex("[sessionId+status]",["sessionId","status"]),s.createIndex("[uploadId+status]",["uploadId","status"]),s.createIndex("[sessionId+status+uploadId]",["sessionId","status","uploadId"])}if(!t.objectStoreNames.contains("pendingCaptures")){const s=t.createObjectStore("pendingCaptures",{keyPath:"uuid"});s.createIndex("sessionId","sessionId"),s.createIndex("timestamp","timestamp"),s.createIndex("[sessionId+targetTimestamp]",["sessionId","targetTimestamp"])}}})}async deleteDB(){try{await Et("sprigReplay")}catch{}}async bulkAdd(t,r){const n=await this.getTransaction(t);return Promise.all([...r.map(s=>n.store.add(s)),n.done])}async clearAll(){const t=(await this.openDB()).transaction(["events","chunkUploads","pendingCaptures"],"readwrite");return this.wrapTransactionWithCounter(t),Promise.all([t.objectStore("events").clear(),t.objectStore("chunkUploads").clear(),t.objectStore("pendingCaptures").clear()])}async deleteBySessionId(t,r){const n=IDBKeyRange.only(r),s=await this.getTransaction(t),i=s.store.index("sessionId");for await(const a of i.iterate(n))await a.delete();await s.done}async updatePartial(t,r,n){const s=await this.getTransaction(t),i=await s.store.get(r);i&&await s.store.put({...i,...n}),await s.done}async deleteRowsBefore(t,r,n=()=>!0){const s=IDBKeyRange.upperBound(r,!0),i=await this.getTransaction(t),a=i.store.index("timestamp");for await(const o of a.iterate(s))n(o.value)&&await o.delete();await i.done}async getEventsBetween(t,r=Date.now()){if(t>=r)return Promise.resolve([]);const n=IDBKeyRange.bound([D,t],[D,r],!1,!0);return(await this.openDB()).getAllFromIndex("events","[sessionId+timestamp]",n)}async updateEventsExpiredAt(t,r,n=rs){const s=new Date,i=s.setMinutes(s.getMinutes()+(n??rs)),a=await this.getTransaction("events"),o=a.store.index("[sessionId+timestamp]"),l=IDBKeyRange.bound([D,t],[D,r],!1,!0);for await(const d of o.iterate(l))await d.update({...d.value,expiredAt:i});await a.done}async deleteChunkUploads(t,r){const n=IDBKeyRange.only([r,t]),s=await this.getTransaction("chunkUploads");let a=await s.store.index("[uploadId+status]").openCursor(n);for(;a;)a.delete(),a=await a.continue();await s.done}async getChunkUploadsByStatus({sessionId:t,status:r,uploadId:n}){const i=(await this.openDB()).transaction("chunkUploads","readonly");this.wrapTransactionWithCounter(i);const a=n?i.store.index("[uploadId+status]"):i.store.index("[sessionId+status]"),o=n?IDBKeyRange.only([n,r]):IDBKeyRange.only([t,r]);return a.getAll(o)}async getPendingCaptures(t={}){return(await(await this.openDB()).getAllFromIndex("pendingCaptures","sessionId",D)).filter(s=>!t.beforePresent||s.targetTimestamp!t.isBeforeType||s.captureParams.replayParams.replayDurationType==="before").filter(s=>!t.isHeatmap||(s.captureParams.isHeatmap??!1))}async tryAddPendingCaptureForSurvey(t){const{surveyId:r,record:n}=t,i=(await this.openDB()).transaction("pendingCaptures","readwrite");this.wrapTransactionWithCounter(i);const o=await i.store.index("sessionId").getAll(D),l=!!n.captureParams.isHeatmap;return o.some(u=>u.captureParams.surveyId===r&&!!u.captureParams.isHeatmap===l)?(await i.done,{added:!1}):(await i.store.add(n),await i.done,{added:!0})}async markPendingCaptureToCanUpload(t){const r=await this.getTransaction("pendingCaptures"),n=r.store.index("sessionId");for await(const s of n.iterate(D)){const i=s.value;i.captureParams.responseGroupId===t&&await s.update({...i,canUpload:!0})}await r.done}async markPendingHeatmapsReady(t){if(parseInt(w.getItem("sprig.pendingCount")??"0")===0)return null;const n=Date.now(),s=await this.getTransaction("pendingCaptures"),i=s.store.index("sessionId");for await(const a of i.iterate(D)){const o=a.value;o.captureParams.isHeatmap&&(!t||t.includes(o.uuid))&&await a.update({...o,targetTimestamp:n,captureParams:{...o.captureParams,triggerTimestamp:n,replayParams:{...o.captureParams.replayParams,replayDurationSeconds:Math.floor((n-o.timestamp)/1e3)}}})}await s.done}}const S=new ea,ta=35*1e3,X=[];let ce=[],he=!1,Re,ss,fe=0,Je=!1,ns=!1;const Pt=[];let Ot=!1,Qe,is,Xe,as;const me=()=>Je&&!he&&Date.now()<=Qe,ra=({apiUrl:e,config:t,triggerSnapshot:r,forceInit:n=!1})=>{if(!(Je&&!n)){if(!w.isStorageAvailable){he=!0;return}ce=[],Pt.splice(0),X.splice(0),fe=0,Xe=r,ss=e,Re={responseGroupUuid:t.responseGroupUuid,surveyId:t.surveyId,userAgent:t.userAgent,sdkVersion:t.sdkVersion},is=t.maxDurationSeconds,aa(),Je||(as=globalThis.setInterval(ia,500)),Je=!0}},sa=[J.Drag,J.Input,J.MediaInteraction,J.MouseInteraction,J.MouseMove,J.Scroll,J.Selection,J.TouchMove],na=e=>e.type===se.Custom||e.type===se.IncrementalSnapshot&&sa.includes(e.data.source),Mt=e=>e.some(na),ia=async()=>{if(!me()){globalThis.clearInterval(as);return}if(os(),!Mt(X))return;const e=X[0].timestamp;Date.now()-e>ta&&(Xe==null||Xe())},os=async()=>{if(ce.length||Ot)return;Ot=!0;const e=await da();if(!e){he=!0;return}Pt.splice(0,e.length).forEach(r=>r(e.shift())),e.forEach(r=>ce.push(r)),Ot=!1},aa=()=>{const e=w.getItem("sprig.alwayson.info");if(e){p.info("Read stored session state",e);const t=JSON.parse(e);he=t.disabled,Re=t.metadata,ce=t.uploadUrls,fe=t.currentIndex,Qe=t.expirationTimestamp,t.pendingEventTimestamp&&(p.info(`Uploading with pending timestamp: ${t.pendingEventTimestamp}`),oa(t.pendingEventTimestamp))}else Qe=is*1e3+Date.now()},oa=async e=>{const t=Date.now(),n=(await S.getEventsBetween(e,t)).map(i=>JSON.parse(i.event));if(!Mt(n))return;us(n);const s=await ds();s&&await cs(s,n)},la=()=>{let e;X.length&&(e=X[0].timestamp);const t={disabled:he,metadata:Re,uploadUrls:ce,currentIndex:fe,pendingEventTimestamp:e,expirationTimestamp:Qe};p.info("Storing session state on unload",t),w.setItem("sprig.alwayson.info",JSON.stringify(t))},ca=async e=>{const t=new TextEncoder,r=new CompressionStream("gzip"),n=r.writable.getWriter(),s=t.encode(JSON.stringify(e));return n.write(s),n.close(),new Uint8Array(await new Response(r.readable).arrayBuffer())},ls=async(e,t)=>{try{const r=await e();if(!r.ok)throw new Error(`Error ${t}`);return r}catch{he=!0}},cs=async(e,t)=>{if(!me()||!e)return;const r=await ca(t);p.info("Uploading always-on events with presigned url"),await ls(()=>Y(e,{body:r,method:"PUT"}),"uploading always-on with presigned url")},da=async()=>{if(!me())return;const{surveyId:e,responseGroupUuid:t}=Re,r={responseGroupUuid:t,surveyId:e,index:fe+1};p.info("Fetching always-on upload urls",r);const n=await ls(()=>Y(`${ss}/sdk/1/replayUrls`,{method:"POST",body:JSON.stringify(r),headers:B(globalThis.UserLeap)}),"fetching always-on signed urls");if(!n)return;const s=n.json.signedUrls;return p.info("Fetched more always-on upload urls",{body:r,urls:s}),s},ds=async()=>{if(ce.length)return ce.shift();const e=new Promise(t=>{Pt.push(t)});return os(),e},ua=async()=>{const e=X.splice(0);if(!Mt(e))return;p.info("Capturing always-on event array to upload"),us(e);const t=await ds();t&&await cs(t,e)},us=e=>{var s,i,a;const t=e.length?e[e.length-1].timestamp:Date.now(),r=fe,n=((i=(s=globalThis.UserLeap)==null?void 0:s.config)==null?void 0:i.customMetadata)??((a=globalThis.__cfg)==null?void 0:a.customMetadata);fe++,e.push({timestamp:t,type:se.Custom,data:{tag:"Sprig_Meta",payload:{...Re,index:r,visitorId:globalThis.UserLeap.visitorId??"",timestamp:t,customMetadata:n}}})},pa=async()=>{ns=!0,me()&&(p.info("Always On handle page unload"),la())},ga=(e,t)=>{!me()||ns||!e&&!X.length||(e&&X.length&&ua(),X.push(t))};(Us=globalThis.addEventListener)==null||Us.call(globalThis,"beforeunload",pa);const ps=async(e,t)=>{const r=performance.now();let n;try{n=await e()}finally{const s=performance.now()-r;let i=Te[t];i||(i=$(t)),i.report(s/1e3)}return n},gs=(e,t)=>{const r=performance.now();try{e()}finally{const n=performance.now()-r;let s=Te[t];s||(s=$(t)),s.report(n/1e3)}};let hs=5e3,Bt=6e4,Ft=0;const ha=5,Nt=30,Ze=Nt+ha;let ie,Ht=!1,Vt=[];const fa=async({maxReplayDurationSeconds:e,maxInflightRequests:t=2,replaySettings:r,teardownAfter:n=!1,apiUrl:s,alwaysOnConfig:i})=>{if(i&&ra({apiUrl:s,config:i,triggerSnapshot:()=>{At()}}),ie=w.getItem("sprig.pendingCount"),U.isRecording)return;if(n&&w.setItem("sprig.teardownAfterCapture","true"),K())return p.debug("ReplayDisabled");if(await Mi())return p.debug("IDBNotSupported"),Ct();try{const l=await S.openDB();p.info("DBVersion",{version:l.version})}catch(l){return p.error("ReplayOpenErr",{name:l.name}),l.name==="VersionError"&&S.deleteDB(),Ct()}P(async()=>{await jt(!0)},"Error uploading ready pending captures");const a=me()?Nt:0,o=Math.max(e??0,a);if(!o)return p.debug("MissingDuration");p.debug("ReplayInit"),await P(async()=>{r!=null&&r.minDuration&&(hs=r.minDuration),r!=null&&r.batchDuration&&(Bt=r.batchDuration),yi(t),Ta(),wa(o+Ze,30*60,o+Ze),va();const l=window.UserLeap.replayLibraryURL??"https://cdn.sprig.com/dependencies/record.min.js";if(!window.rrwebRecord){const{record:f}=await import(l);window.rrwebRecord=f}const d=window.rrwebRecord;if(!d)return p.error("RecordScriptFailed");let u=!0,c=0;const m={checkoutEveryNms:Nt*1e3,sampling:{input:"last",scroll:250,media:800},...r,mutationQueueEnabled:r==null?void 0:r.enableMutationQueue};U.stopRecording=d({emit:(f,y)=>{if(f.type===se.Custom&&(Ft=Date.now()),K()||Ye())return;if(y&&f.type===se.Meta)c=performance.now();else if(y&&c&&f.type===se.FullSnapshot){const N=performance.now()-c;Ur("sdk_replay_snapshot_seconds",N/1e3)}const b=u||!!y&&f.type===se.Meta;u=!1,ga(b,f),ma({uuid:pe(),event:JSON.stringify(f),isValidStart:b,timestamp:Date.now()})},...m}),U.isRecording=!!U.stopRecording,U.isRecording&&(gi(m,l),h.on("survey.complete",f=>{qi({id:f,userAgent:window.navigator.userAgent})}),Ai(Q,$i))},"Error initializing replay")},ma=e=>{var t,r,n,s;if((t=e.event)!=null&&t.includes("Sprig_Scroll")){const i=(s=(n=(r=JSON.parse(e.event))==null?void 0:r.data)==null?void 0:n.payload)==null?void 0:s.xPath;if(!i)return;U.scrollEventUuids[i]=e.uuid}Vt.push(e),Ht||ba()},ya=async e=>{const t=e.map(r=>({...r,sessionId:r.sessionId??D}));if(t.length!==0)return P(()=>S.bulkAdd("events",t),"Error storing replay events")},ba=()=>{Ht=!0,setTimeout(async()=>{if(K()||Ye())return;const e=Vt;Vt=[],Ht=!1,gs(async()=>{await ya(e)},"sdk_replay_add_event_batch_seconds")},500)},wa=(e,t,r)=>{U.cleanupInterval=window.setInterval(()=>{const n=Date.now();ps(()=>P(async()=>{K()||await Promise.all([S.deleteRowsBefore("events",n-e*1e3,s=>s.expiredAt===void 0||s.expiredAt!s.canUpload)])},"Error deleting table rows"),"sdk_replay_cleanup_seconds"),p.debug("CleanupComplete")},3e4)},va=()=>{U.pendingCheckInterval=window.setInterval(async()=>{P(async()=>{await jt()},"Error initiating pending captures")},5e3)};let Wt=!1;const jt=async(e=!1)=>{if(!Wt)try{Wt=!0;const t=parseInt(ie??"0");if(t===0)return;const r=await S.getPendingCaptures({beforePresent:!0,isBeforeType:e}),n=await S.openDB();await Promise.all(r.map(async s=>(await n.delete("pendingCaptures",s.uuid),bs(s.captureParams,s.canUpload)))),ie=(t-r.length).toString(),w.setItem("sprig.pendingCount",ie)}finally{Wt=!1}},La=async(e,t,r,n,s)=>{const i=Math.min(e+s,r),a=await ps(()=>S.getEventsBetween(e,i),"sdk_replay_get_events_between_seconds");if(!(a!=null&&a.length))return p.debug("NoEventsFound"),{validStartFound:n,events:[]};if(!n){p.debug("ValidStartSearch");let o=-1;return a==null||a.forEach((l,d)=>{if(!l.isValidStart)return;const u=l.timestamp<=t;(o<0||u)&&(o=d)}),o<0?(p.debug("ValidStartNotFound"),{validStartFound:n,events:[]}):{validStartFound:!0,events:a==null?void 0:a.slice(o)}}return{validStartFound:n,events:a}},Sa=(e,t,r)=>{const n=e.length,s=t*1024*1024,i=Math.ceil(n/r),a=Math.max(s,i),o=[];let l=0;for(;lPromise.all(e.map(async t=>{const r=await bi(t);return await S.updatePartial("chunkUploads",t.uuid,{data:null,etag:r,status:"UploadComplete"}),t.uploadId})),ms=async e=>{const t=await S.getChunkUploadsByStatus({status:"UploadComplete",uploadId:e});if(!(t!=null&&t.length)){p.info("NoChunksForUpload",{uploadId:e});return}const r=t.reduce((i,a)=>(i.find(o=>o.chunkIndex===a.chunkIndex)||i.push(a),i),[]);r.sort((i,a)=>i.chunkIndex-a.chunkIndex);const n=r.map(i=>({ETag:i.etag,PartNumber:i.chunkIndex})).filter(i=>i.ETag!==null),s=r[0];await $r({apiUrl:s.apiUrl,surveyId:s.surveyId,uploadId:e,responseGroupUuid:s.responseGroupId,etags:n,headers:s.completeUploadHeaders,replayDuration:s.replayDuration}),await S.deleteChunkUploads("UploadComplete",e)},Ta=()=>{P(async()=>{const e=await S.getChunkUploadsByStatus({sessionId:D,status:"ReadyForUpload"});if(!(e!=null&&e.length))return;const t=await fs(e);t!=null&&t.length&&await Promise.all(t.map(r=>{if(r)return ms(r)}))},"Error uploading unfinished chunks")},Ua=async(e,t)=>{await fs(t),await Promise.all(e.map(r=>ms(r)))},Ia=async(e,t)=>{const r=new TextEncoder;let n=null;const s=new CompressionStream("gzip"),i=s.writable.getWriter();let a=!1,o=!1,[l,d]=[0,0];const u=e-Ze*1e3;let c=[];for(let f=u;fk.event);y.push(`{"timestamp":${t}}`);const b=`${a?",":"["}${y}`,N=r.encode(b);gs(()=>{i.write(N)},"sdk_replay_compression_seconds"),a=!0}if(d-l{const r=t??Date.now(),n=r-e;return Ia(n,r)},ys=async e=>{const{surveyId:t,responseGroupId:r,visitorId:n,apiUrl:s,completeUploadHeaders:i,replayParams:a,triggerTimestamp:o}=e,l=await Ea(a.replayDurationSeconds*1e3,o);if(!(l!=null&&l.length)){p.info("FileDataEmpty",{surveyId:t});return}const d=Sa(l,a.minimumChunkSizeMb,a.signedUrls.length),u=await Promise.all(d.map(async(c,m)=>{const f=pe(),y={apiUrl:s,chunkIndex:m+1,completeUploadHeaders:i,etag:null,responseGroupId:r,status:"ReadyForUpload",surveyId:t,timestamp:o,totalChunks:d.length,data:c,uploadId:a.uploadId,uploadUrl:a.signedUrls[m].url,uuid:f,visitorId:n};return await(await S.openDB()).add("chunkUploads",{...y,sessionId:y.sessionId??D}),y}));await Ua([a.uploadId],u)},bs=async(e,t)=>{if(K())return p.debug("ReplayDisabled-ScheduleOrCapture");const{isHeatmap:r,isStandalone:n,replayParams:s,triggerTimestamp:i,responseGroupId:a}=e,o=async()=>{setTimeout(()=>h.removeListener(g.QuestionAnswered,o),0),P(async()=>{s.replayDurationType==="before"?await ys(e):await S.markPendingCaptureToCanUpload(a)},"Error in schedule/capture callback")};P(async()=>{if(s.replayDurationType==="after"||s.replayDurationType==="beforeAndAfter"){!n&&!r&&h.on(g.QuestionAnswered,o),await vs(e);return}if(n||r||t)await ys(e),r&&ka();else{const d=Ze+s.replayDurationSeconds,u=i-d*1e3,c=i;await S.updateEventsExpiredAt(u,c,s.expirationTimeLimitMinutes),h.on(g.QuestionAnswered,o)}},"Error in scheduling/capturing replay")},ka=async()=>{parseInt(ie??"0")||w.removeItem("sprig.isCapturingHeatmap"),w.getItem("sprig.teardownAfterCapture")&&(ts(),ws(),w.removeItem("sprig.teardownAfterCapture"))},ws=async()=>K()?p.debug("ReplayDisabled-ClearData"):Promise.all([S.deleteBySessionId("events",D),S.deleteBySessionId("pendingCaptures",D)]).catch(e=>{ke("Error clearing user replay data",e)}),vs=async e=>{if(K())return;const{isHeatmap:t,surveyId:r}=e,n={...e,replayParams:{...e.replayParams}};e.replayParams.replayDurationType==="beforeAndAfter"&&(n.replayParams.replayDurationSeconds*=2),n.replayParams.replayDurationType="before";const s=e.triggerTimestamp+e.replayParams.replayDurationSeconds*1e3;n.triggerTimestamp=s;const i={canUpload:!1,captureParams:n,sessionId:D,targetTimestamp:s,timestamp:Date.now(),uuid:pe()},{added:a}=await S.tryAddPendingCaptureForSurvey({surveyId:r,record:i});if(!a){p.info("PendingCaptureExists",{surveyId:r});return}ie=(parseInt(ie??"0")+1).toString(),w.setItem("sprig.pendingCount",ie),t&&(At(),w.setItem("sprig.isCapturingHeatmap","true"),Ft=Date.now(),U.inactivityInterval||(U.inactivityInterval=window.setInterval(()=>{Hi(Ft)},1e3)))};qs(Object.freeze(Object.defineProperty({__proto__:null,RecordEvent:Wi,RecordPageView:Vi,RecordSurveyShown:ji,_completeSessionReplay:Xi,checkPendingHeatmapsUrl:Ni,clearUserReplayData:ws,disableRecording:ke,initializeReplay:fa,isReplayPaused:Ye,isReplayRecording:Gi,recordFullSnapshot:At,recordReplayPaused:zi,recordReplayResumed:Ki,scheduleCapture:vs,scheduleOrCaptureReplay:bs,tryReplayAction:P,uploadReadyPendingCaptures:jt},Symbol.toStringTag,{value:"Module"})));const Ra="sprig-web-view-sdk";let Ls;Ls={path:`https://cdn.sprig.com/${Ra}-v2.48.0.js`},ei(Ls)})(); //# debugId=8a199fe2-6214-5d50-ac0a-2590159f6e9d